### Full HTTP SSE Server Example (Python) Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt A complete Python implementation of an MCP HTTP SSE server. It handles session management, SSE connections for real-time updates, and POST requests for JSON-RPC communication. This example uses Python's built-in http.server and socketserver modules. ```python import json import uuid import queue import socketserver from http.server import BaseHTTPRequestHandler from urllib.parse import urlparse, parse_qs # 会话存储 sessions = {} class Session: def __init__(self, session_id): self.session_id = session_id self.message_queue = queue.Queue() class MCPHandler(BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' def do_GET(self): """处理 SSE 连接""" if self.path == '/sse': session_id = str(uuid.uuid4()) session = Session(session_id) sessions[session_id] = session self.send_response(200) self.send_header('Content-Type', 'text/event-stream; charset=utf-8') self.send_header('Cache-Control', 'no-cache') self.send_header('Connection', 'keep-alive') self.end_headers() # 发送 endpoint 事件 self.wfile.write(f"event: endpoint\ndata: /messages/?session_id={session_id}\n\n".encode()) self.wfile.flush() # 持续推送消息 while True: try: message = session.message_queue.get(timeout=30) self.wfile.write(f"event: message\ndata: {json.dumps(message)}\n\n".encode()) self.wfile.flush() except queue.Empty: self.wfile.write(b": keepalive\n\n") self.wfile.flush() def do_POST(self): """处理 JSON-RPC 请求""" parsed = urlparse(self.path) params = parse_qs(parsed.query) session_id = params.get('session_id', [None])[0] session = sessions.get(session_id) if not session: self.send_error(400, "Invalid session") return content_length = int(self.headers['Content-Length']) request = json.loads(self.rfile.read(content_length)) # 处理请求 response = self.handle_request(request) # 返回 202 Accepted self.send_response(202) self.send_header('Content-Type', 'application/json; charset=utf-8') self.end_headers() self.wfile.write(b"{}") # 通过 SSE 推送响应 if response: session.message_queue.put(response) def handle_request(self, request): method = request.get('method') request_id = request.get('id') if method == 'initialize': return { "jsonrpc": "2.0", "id": request_id, "result": { "protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, "serverInfo": {"name": "mcp-server", "version": "1.0.0"} } } elif method == 'tools/list': return { "jsonrpc": "2.0", "id": request_id, "result": { "tools": [{ "name": "example_tool", "description": "示例工具", "inputSchema": {"type": "object", "properties": {}} }] } } elif method == 'tools/call': return { "jsonrpc": "2.0", "id": request_id, "result": {"content": [{"type": "text", "text": "工具执行成功"}]} } return None # 启动多线程服务器 class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): allow_reuse_address = True daemon_threads = True if __name__ == '__main__': server = ThreadedTCPServer(("", 8080), MCPHandler) print("MCP Server running on http://localhost:8080") server.serve_forever() ``` -------------------------------- ### GET / (SSE Connection) Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt Establishes an SSE connection to receive asynchronous responses and notifications from the MCP server. ```APIDOC ## GET / ### Description Establishes a Server-Sent Events (SSE) stream to receive JSON-RPC responses and server notifications. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **event: endpoint** - Initial connection event containing the session URI. - **event: message** - JSON-RPC response data. #### Response Example event: endpoint data: /messages/?session_id=abc123 event: message data: {"jsonrpc": "2.0", "result": { ... }, "id": 1} ``` -------------------------------- ### GET /sse Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt Establishes a Server-Sent Events (SSE) connection to receive asynchronous updates and tool execution results from the MCP server. ```APIDOC ## GET /sse ### Description Initializes a persistent SSE connection. The server returns an 'endpoint' event containing the URI for subsequent POST requests, followed by a stream of 'message' events. ### Method GET ### Endpoint /sse ### Response #### Success Response (200) - **Content-Type** - text/event-stream #### Response Example event: endpoint data: /messages/?session_id=uuid-string event: message data: {"jsonrpc": "2.0", ...} ``` -------------------------------- ### Method: tools/list Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt Retrieves the list of tools available on the MCP server. ```APIDOC ## POST / (tools/list) ### Description Retrieves a list of all tools supported by the server, including their schemas. ### Request Body - **method** (string) - Required - "tools/list" ### Response #### Success Response (200 via SSE) - **result.tools** (array) - List of available tools with name, description, and inputSchema ### Response Example { "jsonrpc": "2.0", "id": 2, "result": { "tools": [ { "name": "get_weather", "description": "Get weather info", "inputSchema": { "type": "object", "properties": { "city": { "type": "string" } } } } ] } } ``` -------------------------------- ### Method: initialize Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt The handshake method to initialize the MCP connection and exchange capabilities. ```APIDOC ## POST / (initialize) ### Description Performs the initial handshake to define protocol version and server capabilities. ### Request Body - **method** (string) - Required - "initialize" - **params** (object) - Required - Includes protocolVersion and clientInfo ### Response #### Success Response (200 via SSE) - **result** (object) - Contains protocolVersion, capabilities, and serverInfo ### Response Example { "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2025-06-18", "capabilities": { "tools": {} }, "serverInfo": { "name": "example-mcp-server", "version": "1.0.0" } } } ``` -------------------------------- ### MCP tools/call Method Implementation (JSON) Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt Demonstrates the client request and server response structure for the 'tools/call' method in MCP. The server response must include a 'content' array with 'type' and corresponding data, supporting both successful results and error reporting. ```json // 客户端请求 { "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "get_weather", "arguments": { "city": "北京" } } } // 服务器响应 (通过 SSE 推送) { "jsonrpc": "2.0", "id": 3, "result": { "content": [ { "type": "text", "text": "北京当前天气: 晴, 温度: 25°C, 湿度: 45%" } ] } } // 工具调用错误响应 { "jsonrpc": "2.0", "id": 3, "result": { "content": [ { "type": "text", "text": "错误: 无法获取城市天气信息" } ], "isError": true } } ``` -------------------------------- ### MCP 核心方法实现示例 Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt 展示了 initialize 握手流程及 tools/list 工具列表获取的 JSON-RPC 交互示例。 ```json // initialize 请求 {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18"}} // tools/list 请求 {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}} ``` -------------------------------- ### 多线程服务器实现 (Python) Source: https://github.com/baggiogan2000/mcp-development-specification/blob/main/MCP_DEVELOPMENT_SPECIFICATION.md 在处理 HTTP SSE 时,必须使用多线程服务器以防止阻塞。此示例展示了如何通过 ThreadingMixIn 实现并发处理。 ```python import socketserver class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): allow_reuse_address = True daemon_threads = True ``` -------------------------------- ### 多线程 HTTP 服务器配置 Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt 为了支持 SSE 连接,MCP 服务器必须使用多线程架构,避免单线程阻塞导致的通信故障。 ```python import socketserver from http.server import HTTPServer, BaseHTTPRequestHandler class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): allow_reuse_address = True daemon_threads = True PORT = 8080 server = ThreadedTCPServer(("", PORT), MCPHandler) server.serve_forever() ``` -------------------------------- ### POST /tools/call Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt Executes a specific tool provided by the MCP server. The request is sent via POST and the result is pushed asynchronously via the SSE channel. ```APIDOC ## POST /tools/call ### Description Invokes a server-side tool by name with provided arguments. The server acknowledges the request with a 202 status and pushes the result through the established SSE stream. ### Method POST ### Endpoint /messages/?session_id={session_id} ### Parameters #### Query Parameters - **session_id** (string) - Required - The unique identifier for the active SSE session. #### Request Body - **jsonrpc** (string) - Required - Must be "2.0". - **id** (integer) - Required - Unique request identifier. - **method** (string) - Required - Must be "tools/call". - **params** (object) - Required - Contains the tool name and arguments. ### Request Example { "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "get_weather", "arguments": { "city": "北京" } } } ### Response #### Success Response (202) - **(empty)** - The server returns an empty body with a 202 Accepted status, indicating the request is being processed. #### SSE Async Response Example { "jsonrpc": "2.0", "id": 3, "result": { "content": [ { "type": "text", "text": "北京当前天气: 晴, 温度: 25°C, 湿度: 45%" } ] } } ``` -------------------------------- ### HTTP SSE 服务器处理实现 Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt 使用 Python 实现 MCP 服务器的 POST 请求处理逻辑。必须返回 202 Accepted 以防止客户端阻塞,并通过 SSE 通道异步推送响应。 ```python import json from http.server import BaseHTTPRequestHandler class MCPHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) request_data = self.rfile.read(content_length) request = json.loads(request_data) response = self.process_request(request) self.send_response(202) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(b"{}") session = self.get_session() session.message_queue.put(response) ``` -------------------------------- ### HTTP SSE 异步响应处理 (Python) Source: https://github.com/baggiogan2000/mcp-development-specification/blob/main/MCP_DEVELOPMENT_SPECIFICATION.md 演示了在 HTTP POST 请求中正确返回 202 Accepted 状态码,并通过消息队列异步推送响应的逻辑。 ```python # 正确的响应处理逻辑 self.send_response(202) self.wfile.write(b"{}") session.message_queue.put(response) # 通过 SSE 推送 ``` -------------------------------- ### POST / (JSON-RPC Request) Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt Sends a JSON-RPC 2.0 request to the MCP server. The server must respond with 202 Accepted, and the actual result is delivered via an SSE message event. ```APIDOC ## POST / ### Description Sends a JSON-RPC 2.0 request to the server. The server processes the request asynchronously and returns a 202 Accepted status code. ### Method POST ### Endpoint / ### Request Body - **jsonrpc** (string) - Required - Must be "2.0" - **id** (number/string) - Required - Unique request identifier - **method** (string) - Required - The RPC method to invoke - **params** (object) - Optional - Method parameters ### Request Example { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-06-18", "clientInfo": { "name": "client", "version": "1.0.0" } } } ### Response #### Success Response (202) - **(empty)** - The server acknowledges receipt and will push the result via SSE. #### Response Example { "status": "202 Accepted" } ``` -------------------------------- ### HTTP SSE 传输事件格式规范 Source: https://github.com/baggiogan2000/mcp-development-specification/blob/main/MCP_DEVELOPMENT_SPECIFICATION.md 定义了 HTTP SSE 传输中 endpoint 和 message 事件的正确格式,确保客户端能够正确解析会话 URI 和 JSON-RPC 消息。 ```text event: endpoint data: /messages/?session_id=abc123 event: message data: {"jsonrpc": "2.0", "result": {...}, "id": 1} ``` -------------------------------- ### JSON-RPC 2.0 消息格式示例 Source: https://github.com/baggiogan2000/mcp-development-specification/blob/main/MCP_DEVELOPMENT_SPECIFICATION.md 展示了 MCP 协议中请求、响应、错误及通知的标准 JSON-RPC 2.0 消息结构。 ```json {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}} {"jsonrpc": "2.0", "id": 1, "result": {}} {"jsonrpc": "2.0", "id": 1, "error": {"code": -32601, "message": "Method not found"}} {"jsonrpc": "2.0", "method": "notifications/initialized"} ``` -------------------------------- ### HTTP SSE 传输事件格式 Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt 规定了 SSE 连接中的 endpoint 和 message 事件格式。endpoint 事件传输 URI,message 事件传输 JSON-RPC 响应数据。 ```text event: endpoint data: /messages/?session_id=abc123 event: message data: {"jsonrpc": "2.0", "result": {"capabilities": {}, "serverInfo": {"name": "example"}}, "id": 1} ``` -------------------------------- ### JSON-RPC 2.0 标准错误代码 Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt 定义了 MCP 服务器在处理请求时可能返回的标准错误代码,包括解析错误、无效请求、方法未找到等场景。 ```json // 解析错误 (-32700) {"jsonrpc": "2.0", "id": null, "error": {"code": -32700, "message": "Parse error"}} // 无效请求 (-32600) {"jsonrpc": "2.0", "id": 1, "error": {"code": -32600, "message": "Invalid Request"}} // 方法未找到 (-32601) {"jsonrpc": "2.0", "id": 1, "error": {"code": -32601, "message": "Method not found"}} // 无效参数 (-32602) {"jsonrpc": "2.0", "id": 1, "error": {"code": -32602, "message": "Invalid params"}} // 内部错误 (-32603) {"jsonrpc": "2.0", "id": 1, "error": {"code": -32603, "message": "Internal error"}} ``` -------------------------------- ### JSON-RPC 2.0 消息格式定义 Source: https://context7.com/baggiogan2000/mcp-development-specification/llms.txt 展示了 MCP 协议中标准的请求、响应、错误及通知消息的 JSON 结构,确保通信双方遵循统一的数据交换格式。 ```json // 标准请求格式 {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}} // 标准响应格式 {"jsonrpc": "2.0", "id": 1, "result": {}} // 错误响应格式 {"jsonrpc": "2.0", "id": 1, "error": {"code": -32601, "message": "Method not found"}} // 通知格式 (无需响应,没有 id 字段) {"jsonrpc": "2.0", "method": "notifications/initialized"} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.