RobotFrameworkLibrary-to-MCP
Okay, here's a breakdown of how to turn a Robot Framework library into an MCP (Message Center Protocol) server, along with explanations and considerations: **Understanding the Goal** The core idea is to expose the functionality of your Robot Framework library as a service that can be accessed remotely via MCP. This allows other systems (potentially written in different languages or running on different machines) to trigger actions within your Robot Framework library. **Key Concepts** * **Robot Framework Library:** A collection of keywords (functions) that can be used in Robot Framework test cases. * **MCP (Message Center Protocol):** A lightweight protocol for inter-process communication. It's often used for sending commands and receiving responses between different applications or services. * **MCP Server:** A process that listens for MCP requests, processes them, and sends back responses. * **MCP Client:** A process that sends MCP requests to an MCP server. * **Serialization/Deserialization:** Converting data structures (like Python objects) into a format suitable for transmission over a network (e.g., JSON) and then converting them back on the receiving end. **General Approach** 1. **Choose an MCP Library/Framework:** You'll need a Python library that handles the MCP protocol. Some options include: * **`mcp` (Python Package):** A dedicated MCP library for Python. This is likely the most direct and appropriate choice. You can install it with `pip install mcp`. * **ZeroMQ (with MCP Implementation):** ZeroMQ is a powerful messaging library that can be used to implement MCP. This is a more general-purpose solution, but it might be overkill if you only need MCP. * **Other Messaging Libraries:** You *could* potentially use other messaging libraries (like RabbitMQ or Redis Pub/Sub), but you'd need to implement the MCP protocol on top of them, which is more complex. 2. **Create an MCP Server:** Write a Python script that: * Imports your Robot Framework library. * Uses the chosen MCP library to create a server that listens on a specific port. * Registers handlers for different MCP commands. Each handler will correspond to a keyword in your Robot Framework library. * When a command is received, the handler will: * Extract the arguments from the MCP message. * Call the corresponding Robot Framework keyword with those arguments. * Capture the return value (if any) from the keyword. * Serialize the return value (e.g., to JSON). * Send the serialized result back to the MCP client as an MCP response. 3. **Create an MCP Client (if needed for testing):** Write a Python script (or use a tool like `netcat`) that: * Uses the chosen MCP library to connect to the MCP server. * Sends MCP requests with the appropriate command name and arguments. * Receives and deserializes the MCP response. * Prints or processes the result. **Example using the `mcp` Python Package** ```python # server.py (MCP Server) import mcp import json from robot.libraries.BuiltIn import BuiltIn # Or import your custom library # Instantiate your Robot Framework library (or use BuiltIn for demonstration) # my_library = MyRobotLibrary() builtin = BuiltIn() def execute_keyword(keyword_name, *args): """Executes a Robot Framework keyword and returns the result.""" try: result = builtin.run_keyword(keyword_name, *args) return result except Exception as e: return {"error": str(e)} # Handle errors gracefully class MyMCPHandler(mcp.Handler): def handle_message(self, message): """Handles incoming MCP messages.""" try: command = message.command arguments = message.arguments if command == "log_message": # Example: Expose the 'Log' keyword result = execute_keyword("Log", arguments.get("message", "")) # Pass arguments as needed return mcp.Response(result=result) elif command == "get_variable_value": #Example: Expose the 'Get Variable Value' keyword variable_name = arguments.get("name") default_value = arguments.get("default", None) result = execute_keyword("Get Variable Value", variable_name, default_value) return mcp.Response(result=result) else: return mcp.Response(error="Unknown command: {}".format(command)) except Exception as e: return mcp.Response(error=str(e)) if __name__ == "__main__": server = mcp.Server(handler=MyMCPHandler()) server.start() # Defaults to port 7000 print("MCP server started on port 7000...") try: server.join() # Keep the server running except KeyboardInterrupt: print("Shutting down server...") server.stop() ``` ```python # client.py (MCP Client - for testing) import mcp import json def send_mcp_request(command, arguments): """Sends an MCP request and returns the response.""" try: client = mcp.Client() response = client.send_message(mcp.Message(command=command, arguments=arguments)) client.close() return response.result, response.error except Exception as e: return None, str(e) if __name__ == "__main__": # Example 1: Call the 'Log' keyword result, error = send_mcp_request("log_message", {"message": "Hello from MCP!"}) if error: print("Error:", error) else: print("Log Result:", result) # Example 2: Call the 'Get Variable Value' keyword result, error = send_mcp_request("get_variable_value", {"name": "${TEMPDIR}"}) if error: print("Error:", error) else: print("Variable Value:", result) ``` **Explanation of the Example** * **`server.py`:** * Imports the `mcp` library and `robot.libraries.BuiltIn`. Replace `robot.libraries.BuiltIn` with your actual Robot Framework library. * `execute_keyword` function: This is the crucial part. It takes a keyword name and arguments, and then uses `BuiltIn().run_keyword()` (or the equivalent for your library) to execute the keyword. Error handling is included. * `MyMCPHandler`: This class inherits from `mcp.Handler` and overrides the `handle_message` method. This method is called whenever the server receives an MCP message. * It extracts the command name and arguments from the message. * It uses a series of `if/elif/else` statements to determine which Robot Framework keyword to call based on the command name. * It calls `execute_keyword` to execute the keyword. * It creates an `mcp.Response` object with the result (or an error message) and returns it. * The `if __name__ == "__main__":` block creates an `mcp.Server` instance, starts it, and keeps it running until a `KeyboardInterrupt` (Ctrl+C) is received. * **`client.py`:** * Imports the `mcp` library. * `send_mcp_request` function: This function takes a command name and arguments, creates an `mcp.Message` object, sends it to the server, and returns the response. * The `if __name__ == "__main__":` block shows how to use the `send_mcp_request` function to call the `log_message` and `get_variable_value` commands. **How to Run the Example** 1. **Install `mcp`:** `pip install mcp` 2. **Save the code:** Save the server code as `server.py` and the client code as `client.py`. 3. **Run the server:** `python server.py` 4. **Run the client:** `python client.py` (in a separate terminal) You should see the "Hello from MCP!" message logged by the Robot Framework `Log` keyword, and the value of the `${TEMPDIR}` variable printed by the client. **Important Considerations and Enhancements** * **Error Handling:** The example includes basic error handling, but you should add more robust error handling to catch exceptions and return meaningful error messages to the client. * **Security:** MCP itself doesn't provide any security features. If you need to secure your MCP server, you'll need to implement your own security mechanisms (e.g., authentication, encryption). Consider using TLS/SSL for encryption. * **Argument Handling:** The example assumes that the arguments are passed as a dictionary. You might need to adjust the argument handling to match the specific requirements of your Robot Framework keywords. Consider using a more structured data format like JSON Schema to define the expected arguments for each command. * **Data Serialization:** The example uses JSON for serialization. You can use other serialization formats (e.g., Pickle, MessagePack) if needed. JSON is generally a good choice for interoperability. * **Asynchronous Operations:** If your Robot Framework keywords perform long-running operations, consider using asynchronous programming (e.g., `asyncio`) to prevent the MCP server from blocking. * **Configuration:** Use a configuration file (e.g., YAML, JSON) to store the server's port number, logging settings, and other configuration parameters. * **Logging:** Add logging to the server to track requests, responses, and errors. Use a logging library like `logging`. * **Command Discovery:** Implement a mechanism for the client to discover the available commands and their arguments. This could be done by adding a special "describe" command to the server. * **Robot Framework Listener:** You could potentially use a Robot Framework listener to automatically register keywords as MCP commands. This would reduce the amount of manual configuration required. * **Testing:** Write unit tests and integration tests to ensure that your MCP server is working correctly. **In summary, turning a Robot Framework library into an MCP server involves creating a Python script that listens for MCP requests, calls the appropriate Robot Framework keywords, and sends back the results as MCP responses. The `mcp` Python package provides a convenient way to implement the MCP protocol.** Remember to consider error handling, security, argument handling, and other important factors to create a robust and reliable service.
noubar
README
将 Robot Framework 库转换为 MCP 服务器
如何将任何 Robot Framework 库转换为 MCP 服务器
方法如下
- 克隆你的 Robot 库
- 打开文件夹并进入 init.py,其中初始化了具有混合核心或动态核心的 Library 类。
(示例)
from robotlibcore import DynamicCore class LibraryName(DynamicCore): def __init__(self): ... - 将以下函数添加到类中
def to_mcp(self):
from mcp.server.fastmcp import FastMCP
mcp = FastMCP(self.__class__.__name__)
for kw in self.keywords.values():
mcp.add_tool(kw)
return mcp
在库的根文件夹中的 py 文件中运行以下代码:
from src.LibraryName import LibraryName
a = LibraryName().to_mcp()
a.run(transport='stdio')
你可以在任何 MCP 客户端中使用它 这是一个使用 vscode insiders 的示例
- 按 ctrl shift p 并输入 MCP:Add Server
- 添加以下行
{
"mcp": {
"servers": {
"LibName": {
"type": "stdio",
"command": "uv",
"args": [
"--directory",
"C:\\somefolder\\ABS Path to The library Root",
"run",
"test.py"] # 运行服务器的新 py 文件名
}
}
}
}
就这样
演示
我将记录一个使用 MailClientLibrary 的演示
from src.MailClientLibrary import MailClientLibrary
a = MailClientLibrary(Username="user", Password="pass", MailServerAddress="127.0.0.1", ImapPorts=[993,143], Pop3Ports=[995,110], SmtpPorts=[465,25]).to_mcp()
a.run(transport='stdio')
print(a)
推荐服务器
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
MCP Package Docs Server
促进大型语言模型高效访问和获取 Go、Python 和 NPM 包的结构化文档,通过多语言支持和性能优化来增强软件开发。
Claude Code MCP
一个实现了 Claude Code 作为模型上下文协议(Model Context Protocol, MCP)服务器的方案,它可以通过标准化的 MCP 接口来使用 Claude 的软件工程能力(代码生成、编辑、审查和文件操作)。
@kazuph/mcp-taskmanager
用于任务管理的模型上下文协议服务器。它允许 Claude Desktop(或任何 MCP 客户端)在基于队列的系统中管理和执行任务。
mermaid-mcp-server
一个模型上下文协议 (MCP) 服务器,用于将 Mermaid 图表转换为 PNG 图像。
Jira-Context-MCP
MCP 服务器向 AI 编码助手(如 Cursor)提供 Jira 工单信息。
Linear MCP Server
一个模型上下文协议(Model Context Protocol)服务器,它与 Linear 的问题跟踪系统集成,允许大型语言模型(LLM)通过自然语言交互来创建、更新、搜索和评论 Linear 问题。
Sequential Thinking MCP Server
这个服务器通过将复杂问题分解为顺序步骤来促进结构化的问题解决,支持修订,并通过完整的 MCP 集成来实现多条解决方案路径。
Curri MCP Server
通过管理文本笔记、提供笔记创建工具以及使用结构化提示生成摘要,从而实现与 Curri API 的交互。