API Wrapper MCP Server
Okay, I understand you want to create an MCP (presumably meaning "Minimal Communication Protocol") server that can handle requests for *any* API. This is a very broad request, as the implementation details will heavily depend on the specific API you want to support. However, I can provide a conceptual outline and a basic Python example to illustrate the core principles. **Conceptual Outline** 1. **API Definition:** The most crucial step. You *must* have a clear definition of the API you want to support. This includes: * **Endpoints:** The URLs or routes that the API exposes (e.g., `/users`, `/products/{id}`). * **HTTP Methods:** The HTTP methods used for each endpoint (e.g., GET, POST, PUT, DELETE). * **Request Parameters:** The data that needs to be sent in the request (e.g., query parameters, request body). Specify data types and validation rules. * **Request Body Format:** If the API uses request bodies (e.g., for POST or PUT requests), define the format (e.g., JSON, XML, form data). * **Response Format:** The format of the data returned by the API (e.g., JSON, XML). Define the structure and data types. * **Error Handling:** How errors are reported (e.g., HTTP status codes, error messages in the response body). 2. **MCP Protocol Definition:** Define your "Minimal Communication Protocol." This is how your clients will communicate with your server. Consider these aspects: * **Message Format:** How will the client send the API request information to the server? A simple text-based format might be suitable for a minimal protocol. For example: ``` METHOD:GET ENDPOINT:/users HEADER:Authorization: Bearer <token> ``` Or, you could use a more structured format like JSON: ```json { "method": "GET", "endpoint": "/users", "headers": {"Authorization": "Bearer <token>"}, "body": null } ``` * **Response Format:** How will the server send the API response back to the client? Again, a simple text-based format or JSON could be used. * **Error Handling:** How will the server indicate errors to the client? 3. **Server Implementation:** * **Socket Listener:** The server needs to listen on a specific port for incoming client connections. * **Message Parsing:** The server needs to parse the incoming MCP message to extract the API request details (method, endpoint, headers, body). * **API Request Handling:** Based on the parsed request, the server needs to: * Construct the appropriate API request. * Send the request to the actual API endpoint. * Receive the API response. * **Response Formatting:** The server needs to format the API response into the MCP response format and send it back to the client. * **Error Handling:** The server needs to handle errors that occur during any of these steps and send appropriate error responses to the client. **Python Example (Illustrative)** This is a very basic example using Python's `socket` library. It assumes a simple text-based MCP protocol. **This is not production-ready code.** It lacks proper error handling, security, and scalability. ```python import socket import requests import json # Configuration HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023) API_BASE_URL = "https://jsonplaceholder.typicode.com" # Example API def handle_client(conn, addr): print(f"Connected by {addr}") while True: data = conn.recv(1024) # Receive up to 1024 bytes if not data: break try: # Decode the received data (assuming UTF-8 encoding) request_str = data.decode('utf-8') # Parse the request (very basic parsing) lines = request_str.strip().split('\n') method = lines[0].split(':')[1].strip() endpoint = lines[1].split(':')[1].strip() headers = {} for line in lines[2:]: if line.startswith("HEADER:"): header_parts = line[7:].split(':') if len(header_parts) == 2: headers[header_parts[0].strip()] = header_parts[1].strip() # Construct the API URL api_url = API_BASE_URL + endpoint # Make the API request try: response = requests.request(method, api_url, headers=headers) response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx) api_response_data = response.json() # Assuming JSON response # Format the API response into MCP response (JSON) mcp_response = json.dumps(api_response_data) conn.sendall(mcp_response.encode('utf-8')) except requests.exceptions.RequestException as e: error_message = f"API Request Error: {str(e)}" conn.sendall(error_message.encode('utf-8')) print(error_message) except Exception as e: error_message = f"Error processing request: {str(e)}" conn.sendall(error_message.encode('utf-8')) print(error_message) conn.close() print(f"Connection closed with {addr}") def main(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() print(f"Listening on {HOST}:{PORT}") while True: conn, addr = s.accept() handle_client(conn, addr) if __name__ == "__main__": main() ``` **Explanation:** * **`handle_client(conn, addr)`:** This function handles the communication with a single client. * **`conn.recv(1024)`:** Receives data from the client. * **Request Parsing:** The code parses the incoming data, assuming a simple text-based format. It extracts the method, endpoint, and headers. **This is very basic and needs to be improved for real-world use.** * **`requests.request(method, api_url, headers=headers)`:** Uses the `requests` library to make the actual API request. * **Response Formatting:** The API response (assumed to be JSON) is formatted into a JSON string and sent back to the client. * **Error Handling:** Basic error handling is included, but it's not comprehensive. * **`main()`:** Sets up the socket listener and accepts incoming connections. **To run this example:** 1. **Save:** Save the code as a Python file (e.g., `mcp_server.py`). 2. **Install `requests`:** `pip install requests` 3. **Run:** `python mcp_server.py` **Example Client (Python):** ```python import socket HOST = '127.0.0.1' PORT = 65432 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) request = f"METHOD:GET\nENDPOINT:/todos/1\nHEADER:Content-Type: application/json" s.sendall(request.encode('utf-8')) data = s.recv(1024) print('Received:', data.decode('utf-8')) ``` **Important Considerations:** * **Security:** This example is *not* secure. You need to implement proper authentication, authorization, and input validation to protect your server. Consider using HTTPS for secure communication. * **Error Handling:** The error handling is very basic. You need to handle different types of errors gracefully and provide informative error messages to the client. * **Scalability:** This example is not scalable. For production use, you'll need to use a more robust server architecture (e.g., using a framework like Flask or Django, and a multi-threaded or asynchronous approach). * **Data Validation:** Validate all incoming data to prevent injection attacks and other security vulnerabilities. * **API Rate Limiting:** Implement rate limiting to prevent abuse of your server. * **Logging:** Implement logging to track requests and errors. * **Configuration:** Use a configuration file to store settings like the API base URL, port number, and other parameters. * **Protocol Design:** Carefully design your MCP protocol to be efficient and easy to parse. Consider using a binary protocol for better performance. * **Asynchronous I/O:** For handling many concurrent connections, consider using asynchronous I/O (e.g., with `asyncio` in Python). **In summary, creating a generic MCP server for any API is a complex task. You need to carefully define your MCP protocol, handle API requests and responses, and implement proper error handling, security, and scalability. The example above provides a basic starting point, but it needs to be significantly improved for real-world use.** **中文翻译:** 好的,我理解您想要创建一个 MCP(大概意思是“最小通信协议”)服务器,它可以处理任何 API 的请求。 这是一个非常广泛的要求,因为实现细节将很大程度上取决于您想要支持的特定 API。 但是,我可以提供一个概念性的概述和一个基本的 Python 示例来说明核心原则。 **概念性概述** 1. **API 定义:** 最关键的一步。 您*必须*清楚地定义您想要支持的 API。 这包括: * **端点:** API 公开的 URL 或路由(例如,`/users`,`/products/{id}`)。 * **HTTP 方法:** 每个端点使用的 HTTP 方法(例如,GET,POST,PUT,DELETE)。 * **请求参数:** 需要在请求中发送的数据(例如,查询参数,请求体)。 指定数据类型和验证规则。 * **请求体格式:** 如果 API 使用请求体(例如,对于 POST 或 PUT 请求),请定义格式(例如,JSON,XML,表单数据)。 * **响应格式:** API 返回的数据的格式(例如,JSON,XML)。 定义结构和数据类型。 * **错误处理:** 如何报告错误(例如,HTTP 状态代码,响应体中的错误消息)。 2. **MCP 协议定义:** 定义您的“最小通信协议”。 这是您的客户端将如何与您的服务器通信。 考虑以下几个方面: * **消息格式:** 客户端将如何将 API 请求信息发送到服务器? 简单的基于文本的格式可能适合于最小协议。 例如: ``` METHOD:GET ENDPOINT:/users HEADER:Authorization: Bearer <token> ``` 或者,您可以使用更结构化的格式,例如 JSON: ```json { "method": "GET", "endpoint": "/users", "headers": {"Authorization": "Bearer <token>"}, "body": null } ``` * **响应格式:** 服务器将如何将 API 响应发送回客户端? 同样,可以使用简单的基于文本的格式或 JSON。 * **错误处理:** 服务器将如何向客户端指示错误? 3. **服务器实现:** * **套接字监听器:** 服务器需要监听特定端口上的传入客户端连接。 * **消息解析:** 服务器需要解析传入的 MCP 消息以提取 API 请求详细信息(方法,端点,标头,正文)。 * **API 请求处理:** 根据解析的请求,服务器需要: * 构造适当的 API 请求。 * 将请求发送到实际的 API 端点。 * 接收 API 响应。 * **响应格式化:** 服务器需要将 API 响应格式化为 MCP 响应格式,然后将其发送回客户端。 * **错误处理:** 服务器需要处理在任何这些步骤中发生的错误,并将适当的错误响应发送给客户端。 **Python 示例(说明性)** 这是一个使用 Python 的 `socket` 库的非常基本的示例。 它假定一个简单的基于文本的 MCP 协议。 **这不是生产就绪的代码。** 它缺乏适当的错误处理,安全性和可伸缩性。 ```python import socket import requests import json # 配置 HOST = '127.0.0.1' # 标准环回接口地址(localhost) PORT = 65432 # 监听端口(非特权端口 > 1023) API_BASE_URL = "https://jsonplaceholder.typicode.com" # 示例 API def handle_client(conn, addr): print(f"Connected by {addr}") while True: data = conn.recv(1024) # 接收最多 1024 字节 if not data: break try: # 解码接收到的数据(假设 UTF-8 编码) request_str = data.decode('utf-8') # 解析请求(非常基本的解析) lines = request_str.strip().split('\n') method = lines[0].split(':')[1].strip() endpoint = lines[1].split(':')[1].strip() headers = {} for line in lines[2:]: if line.startswith("HEADER:"): header_parts = line[7:].split(':') if len(header_parts) == 2: headers[header_parts[0].strip()] = header_parts[1].strip() # 构造 API URL api_url = API_BASE_URL + endpoint # 发出 API 请求 try: response = requests.request(method, api_url, headers=headers) response.raise_for_status() # 为错误的响应(4xx 或 5xx)引发 HTTPError api_response_data = response.json() # 假设 JSON 响应 # 将 API 响应格式化为 MCP 响应(JSON) mcp_response = json.dumps(api_response_data) conn.sendall(mcp_response.encode('utf-8')) except requests.exceptions.RequestException as e: error_message = f"API 请求错误:{str(e)}" conn.sendall(error_message.encode('utf-8')) print(error_message) except Exception as e: error_message = f"处理请求时出错:{str(e)}" conn.sendall(error_message.encode('utf-8')) print(error_message) conn.close() print(f"与 {addr} 的连接已关闭") def main(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() print(f"监听 {HOST}:{PORT}") while True: conn, addr = s.accept() handle_client(conn, addr) if __name__ == "__main__": main() ``` **说明:** * **`handle_client(conn, addr)`:** 此函数处理与单个客户端的通信。 * **`conn.recv(1024)`:** 接收来自客户端的数据。 * **请求解析:** 代码解析传入的数据,假设为简单的基于文本的格式。 它提取方法,端点和标头。 **这非常基本,需要改进以用于实际应用。** * **`requests.request(method, api_url, headers=headers)`:** 使用 `requests` 库发出实际的 API 请求。 * **响应格式化:** API 响应(假定为 JSON)被格式化为 JSON 字符串并发送回客户端。 * **错误处理:** 包含基本的错误处理,但并不全面。 * **`main()`:** 设置套接字监听器并接受传入的连接。 **要运行此示例:** 1. **保存:** 将代码另存为 Python 文件(例如,`mcp_server.py`)。 2. **安装 `requests`:** `pip install requests` 3. **运行:** `python mcp_server.py` **示例客户端 (Python):** ```python import socket HOST = '127.0.0.1' PORT = 65432 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) request = f"METHOD:GET\nENDPOINT:/todos/1\nHEADER:Content-Type: application/json" s.sendall(request.encode('utf-8')) data = s.recv(1024) print('Received:', data.decode('utf-8')) ``` **重要注意事项:** * **安全性:** 此示例*不*安全。 您需要实施适当的身份验证,授权和输入验证来保护您的服务器。 考虑使用 HTTPS 进行安全通信。 * **错误处理:** 错误处理非常基本。 您需要优雅地处理不同类型的错误,并向客户端提供有用的错误消息。 * **可伸缩性:** 此示例不可伸缩。 对于生产用途,您需要使用更强大的服务器架构(例如,使用 Flask 或 Django 之类的框架,以及多线程或异步方法)。 * **数据验证:** 验证所有传入数据,以防止注入攻击和其他安全漏洞。 * **API 速率限制:** 实施速率限制以防止滥用您的服务器。 * **日志记录:** 实施日志记录以跟踪请求和错误。 * **配置:** 使用配置文件来存储诸如 API 基本 URL,端口号和其他参数之类的设置。 * **协议设计:** 仔细设计您的 MCP 协议,使其高效且易于解析。 考虑使用二进制协议以获得更好的性能。 * **异步 I/O:** 为了处理许多并发连接,请考虑使用异步 I/O(例如,在 Python 中使用 `asyncio`)。 **总而言之,为任何 API 创建通用 MCP 服务器是一项复杂的任务。 您需要仔细定义您的 MCP 协议,处理 API 请求和响应,并实施适当的错误处理,安全性和可伸缩性。 上面的示例提供了一个基本的起点,但是需要对其进行重大改进才能用于实际应用。**
gomcpgo
README
API Wrapper MCP 服务器
这是一个用于模型上下文协议 (MCP) 的通用 API 包装服务器。它允许您轻松地将 REST API 包装为 MCP 工具,这些工具可以被 Claude 和其他 MCP 客户端访问。
特性
- 简单的 YAML 配置,支持多个 API 端点
- 支持 GET 和 POST 请求
- 参数验证和默认值
- 通过环境变量进行身份验证
- API 调用的自定义超时
用法
- 创建一个 YAML 配置文件,定义您的 API 端点(请参阅
example-config.yaml
) - 将任何必需的 API 令牌设置为环境变量
- 使用您的配置文件运行服务器:
# 构建服务器
go build -o api_wrapper
# 使用您的配置运行
./api_wrapper my-apis.yaml
配置格式
配置文件使用 YAML 格式,结构如下:
# 服务器信息
server:
name: "API Gateway MCP"
description: "将 REST API 包装为 MCP 工具的通用 API 网关"
version: "1.0.0"
# 身份验证
auth:
token_env_var: "API_GATEWAY_TOKEN" # API 令牌的环境变量
# 工具定义
tools:
- name: "tool-name"
description: "工具描述"
endpoint: "https://api.example.com/endpoint"
method: "POST" # 或 "GET"
timeout: 30 # 单位为秒
template: |
{
"param1": "{{variable1}}",
"param2": {{variable2}}
}
# 对于 GET 请求,使用 query_params
query_params:
param1: "{{variable1}}"
param2: "{{variable2}}"
parameters:
variable1:
type: "string"
description: "variable1 的描述"
required: true
variable2:
type: "number"
description: "variable2 的描述"
default: 10
Claude Desktop 集成
要与 Claude Desktop 一起使用,请将以下内容添加到您的 claude_desktop_config.json
:
{
"mcpServers": {
"api-wrapper": {
"command": "path/to/api_wrapper",
"args": ["path/to/your-config.yaml"],
"env": {
"API_GATEWAY_TOKEN": "your-api-token"
}
}
}
}
示例
查看 example-config.yaml
获取示例 API 配置。
环境变量
- 使用
auth.token_env_var
字段中指定的环境变量设置主身份验证令牌。 - 您还可以在模板中使用
{{env:VARIABLE_NAME}}
语法引用其他环境变量。
推荐服务器
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 的交互。