Spaces:
Sleeping
Sleeping
Update start_mcp.py
Browse files- start_mcp.py +75 -62
start_mcp.py
CHANGED
|
@@ -64,9 +64,11 @@ def run_sse_server(host: str, port: int):
|
|
| 64 |
|
| 65 |
while True:
|
| 66 |
try:
|
| 67 |
-
|
|
|
|
| 68 |
yield f"event: message\ndata: {json.dumps(msg)}\n\n"
|
| 69 |
except asyncio.TimeoutError:
|
|
|
|
| 70 |
yield ": keepalive\n\n"
|
| 71 |
except asyncio.CancelledError:
|
| 72 |
pass
|
|
@@ -98,71 +100,82 @@ def run_sse_server(host: str, port: int):
|
|
| 98 |
if not mcp_available:
|
| 99 |
return JSONResponse({"error": "MCP service not available"}, status_code=500)
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
}
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
else:
|
| 145 |
-
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
"
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
-
# Send via SSE
|
| 165 |
-
await connections[session_id].put(response)
|
| 166 |
return JSONResponse({"ok": True})
|
| 167 |
|
| 168 |
async def health(request: Request):
|
|
|
|
| 64 |
|
| 65 |
while True:
|
| 66 |
try:
|
| 67 |
+
# Shorter timeout for more frequent keepalives
|
| 68 |
+
msg = await asyncio.wait_for(queue.get(), timeout=15)
|
| 69 |
yield f"event: message\ndata: {json.dumps(msg)}\n\n"
|
| 70 |
except asyncio.TimeoutError:
|
| 71 |
+
# Send keepalive more frequently
|
| 72 |
yield ": keepalive\n\n"
|
| 73 |
except asyncio.CancelledError:
|
| 74 |
pass
|
|
|
|
| 100 |
if not mcp_available:
|
| 101 |
return JSONResponse({"error": "MCP service not available"}, status_code=500)
|
| 102 |
|
| 103 |
+
body = await request.json()
|
| 104 |
+
method = body.get("method", "")
|
| 105 |
+
params = body.get("params", {})
|
| 106 |
+
msg_id = body.get("id")
|
| 107 |
+
|
| 108 |
+
logger.info(f"Method: {method}, ID: {msg_id}")
|
| 109 |
+
|
| 110 |
+
async def process_request():
|
| 111 |
+
"""Process the request in background."""
|
| 112 |
+
try:
|
| 113 |
+
# Process MCP methods
|
| 114 |
+
if method == "initialize":
|
| 115 |
+
result = {
|
| 116 |
+
"protocolVersion": "2024-11-05",
|
| 117 |
+
"serverInfo": {"name": "MaTableGPT-MCP", "version": "1.0.0"},
|
| 118 |
+
"capabilities": {"tools": {}}
|
| 119 |
+
}
|
| 120 |
+
elif method == "tools/list":
|
| 121 |
+
tools = []
|
| 122 |
+
for name, tool in mcp._tool_manager._tools.items():
|
| 123 |
+
tools.append({
|
| 124 |
+
"name": tool.name,
|
| 125 |
+
"description": tool.description or name,
|
| 126 |
+
"inputSchema": tool.parameters if hasattr(tool, 'parameters') else {"type": "object", "properties": {}}
|
| 127 |
+
})
|
| 128 |
+
result = {"tools": tools}
|
| 129 |
+
logger.info(f"Listed {len(tools)} tools")
|
| 130 |
+
elif method == "tools/call":
|
| 131 |
+
tool_name = params.get("name")
|
| 132 |
+
tool_args = params.get("arguments", {})
|
| 133 |
+
|
| 134 |
+
if tool_name not in mcp._tool_manager._tools:
|
| 135 |
+
raise Exception(f"Unknown tool: {tool_name}")
|
| 136 |
+
|
| 137 |
+
logger.info(f"Calling tool: {tool_name}")
|
| 138 |
+
|
| 139 |
+
tool = mcp._tool_manager._tools[tool_name]
|
| 140 |
+
|
| 141 |
+
# Run in executor if sync to avoid blocking
|
| 142 |
+
if tool.is_async:
|
| 143 |
+
tool_result = await tool.fn(**tool_args)
|
| 144 |
+
else:
|
| 145 |
+
loop = asyncio.get_event_loop()
|
| 146 |
+
tool_result = await loop.run_in_executor(None, lambda: tool.fn(**tool_args))
|
| 147 |
+
|
| 148 |
+
result = {"content": [{"type": "text", "text": json.dumps(tool_result)}]}
|
| 149 |
+
logger.info(f"Tool {tool_name} completed")
|
| 150 |
else:
|
| 151 |
+
raise Exception(f"Unknown method: {method}")
|
| 152 |
|
| 153 |
+
response = {"jsonrpc": "2.0", "id": msg_id, "result": result}
|
| 154 |
+
|
| 155 |
+
except Exception as e:
|
| 156 |
+
logger.error(f"Error: {e}")
|
| 157 |
+
import traceback
|
| 158 |
+
traceback.print_exc()
|
| 159 |
+
response = {
|
| 160 |
+
"jsonrpc": "2.0",
|
| 161 |
+
"id": msg_id,
|
| 162 |
+
"error": {"code": -32000, "message": str(e)}
|
| 163 |
+
}
|
| 164 |
|
| 165 |
+
# Send response via SSE
|
| 166 |
+
if session_id in connections:
|
| 167 |
+
await connections[session_id].put(response)
|
| 168 |
+
logger.info(f"Response sent for {method}")
|
| 169 |
+
else:
|
| 170 |
+
logger.error(f"Session {session_id} disconnected before response")
|
| 171 |
+
|
| 172 |
+
# Handle notifications immediately
|
| 173 |
+
if method == "notifications/initialized":
|
| 174 |
+
return JSONResponse({"ok": True})
|
| 175 |
+
|
| 176 |
+
# Start background task for other requests
|
| 177 |
+
asyncio.create_task(process_request())
|
| 178 |
|
|
|
|
|
|
|
| 179 |
return JSONResponse({"ok": True})
|
| 180 |
|
| 181 |
async def health(request: Request):
|