Spaces:
Sleeping
Sleeping
Raghav Samavedam commited on
Commit ·
269fe23
1
Parent(s): ed16817
Fix: Implement proper JSON-RPC 2.0 protocol for ChatGPT compatibility
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465664 unmodified lines7172737475767778798081828384855 unmodified lines9192939495969798991001011021031041051061071081091108 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214310 unmodified lines154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208#!/usr/bin/env python3"""Web-based MCP Server for ChatGPT Custom ConnectorsProvides HTTP endpoints that mimic MCP protocol"""from fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Any, Dict, List, Optionalimport httpximport jsonimport osapp = FastAPI(title="CRO MCP Server")# Add CORS for ChatGPTapp.add_middleware(CORSMiddleware,allow_origins=["https://chat.openai.com", "*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# Your deployed APIAPI_BASE_URL = "https://raghavsam-mcp-cro-mock.hf.space"class MCPRequest(BaseModel):method: strparams: Optional[Dict[str, Any]] = {}class ToolCallParams(BaseModel):name: strarguments: Dict[str, Any]@app.get("/")async def root():"""MCP server info"""return {"mcp_version": "0.9.1","server_name": "cro-mock-mcp","capabilities": ["tools", "resources"]}@app.post("/")async def handle_mcp_request(request: MCPRequest):"""Main MCP endpoint - handles all MCP requests"""if request.method == "initialize":return {"protocolVersion": "0.9.1","serverInfo": {"name": "cro-mock-mcp","version": "1.0.0"},"capabilities": {"tools": {},"resources": {}}}elif request.method == "tools/list":return {"tools": [{4 unmodified lines"properties": {"capability_filter": {"type": "array","items": {"type": "string"}},"region": {"type": "string", "enum": ["US", "EU", "ANY"]}}}},{"name": "draft_protocol","description": "Convert objectives to protocols","inputSchema": {"type": "object","required": ["objective", "inputs"],5 unmodified lines},{"name": "request_quote","description": "Get quotes from CROs","inputSchema": {"type": "object","required": ["protocol_id", "targets"],"properties": {"protocol_id": {"type": "string"},"targets": {"type": "array", "items": {"type": "string"}},"speed_vs_cost": {"type": "string"}}}},{"name": "submit_order","description": "Submit order to CRO","inputSchema": {"type": "object","required": ["rfq_id", "selected_cro", "po_ref", "billing", "ship_to"],8 unmodified lines},{"name": "check_status","description": "Check order status","inputSchema": {"type": "object","required": ["order_id"],"properties": {"order_id": {"type": "string"}}}}]}elif request.method == "tools/call":# Extract parametersparams = request.paramstool_name = params.get("name")arguments = params.get("arguments", {})# Call the actual APIasync with httpx.AsyncClient() as client:try:response = await client.post(f"{API_BASE_URL}/{tool_name}",json=arguments,10 unmodified lines]}except Exception as e:return {"error": {"type": "api_error","message": f"Failed to call {tool_name}: {str(e)}"}}elif request.method == "resources/list":return {"resources": [{"uri": "cro://status","name": "API Status","description": "Check CRO API status","mimeType": "application/json"}]}elif request.method == "resources/read":uri = request.params.get("uri")if uri == "cro://status":async with httpx.AsyncClient() as client:try:response = await client.get(API_BASE_URL)return {"contents": [{"uri": uri,"text": json.dumps({"status": "operational","api": API_BASE_URL,"data": response.json()}, indent=2)}]}except:return {"contents": [{"uri": uri, "text": '{"status": "error"}'}]}else:raise HTTPException(status_code=404, detail=f"Unknown method: {request.method}")# Health check for deployment@app.get("/health")async def health():return {"status": "healthy"}if __name__ == "__main__":import uvicornport = int(os.environ.get("PORT", 8000))uvicorn.run(app, host="0.0.0.0", port=port)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051064 unmodified lines1111121131141151161171181191201211221231241251261271281291305 unmodified lines1361371381391401411421431441451461471481491501511521531541558 unmodified lines16416516616716816917017117217317417517617717817918018118218318418518618718818910 unmodified lines200201202203204205206207208209210211212213214215216217218219220221222223224225226#!/usr/bin/env python3"""JSON-RPC MCP Server for ChatGPT Custom ConnectorsProperly implements JSON-RPC 2.0 protocol"""from fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponsefrom typing import Any, Dict, List, Optional, Unionimport httpximport jsonimport osimport logging# Setup logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)app = FastAPI(title="CRO MCP Server - JSON-RPC")# Add CORS for ChatGPTapp.add_middleware(CORSMiddleware,allow_origins=["https://chat.openai.com", "https://chatgpt.com", "*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],expose_headers=["*"])# Your deployed APIAPI_BASE_URL = "https://raghavsam-mcp-cro-mock.hf.space"@app.get("/")async def root():"""Health check endpoint"""return {"status": "ok","server": "CRO MCP Server","protocol": "JSON-RPC 2.0"}@app.post("/")async def handle_jsonrpc(request: Request):"""Main JSON-RPC endpoint"""try:# Get raw bodybody = await request.json()logger.info(f"Received request: {json.dumps(body, indent=2)}")# Extract JSON-RPC fieldsjsonrpc = body.get("jsonrpc", "2.0")method = body.get("method")params = body.get("params", {})req_id = body.get("id")if not method:return JSONResponse(content={"jsonrpc": "2.0","error": {"code": -32600,"message": "Invalid Request: missing method"},"id": req_id})# Route to appropriate handlerresult = await handle_method(method, params)# Return JSON-RPC responseresponse = {"jsonrpc": "2.0","result": result,"id": req_id}logger.info(f"Sending response: {json.dumps(response, indent=2)}")return JSONResponse(content=response)except Exception as e:logger.error(f"Error handling request: {str(e)}")return JSONResponse(content={"jsonrpc": "2.0","error": {"code": -32603,"message": f"Internal error: {str(e)}"},"id": body.get("id") if "body" in locals() else None})async def handle_method(method: str, params: Dict[str, Any]) -> Any:"""Route methods to handlers"""if method == "initialize":return {"protocolVersion": "2024-11-05","capabilities": {"tools": {}}}elif method == "tools/list":return {"tools": [{4 unmodified lines"properties": {"capability_filter": {"type": "array","items": {"type": "string"},"description": "Filter by capabilities like dissolution, HPLC"},"region": {"type": "string","enum": ["US", "EU", "ANY"],"default": "ANY"}}}},{"name": "draft_protocol","description": "Convert high-level objectives into structured protocols","inputSchema": {"type": "object","required": ["objective", "inputs"],5 unmodified lines},{"name": "request_quote","description": "Request quotes from multiple CROs","inputSchema": {"type": "object","required": ["protocol_id", "targets"],"properties": {"protocol_id": {"type": "string"},"targets": {"type": "array", "items": {"type": "string"}},"speed_vs_cost": {"type": "string", "enum": ["speed", "balanced", "cost"]}}}},{"name": "submit_order","description": "Submit order to selected CRO","inputSchema": {"type": "object","required": ["rfq_id", "selected_cro", "po_ref", "billing", "ship_to"],8 unmodified lines},{"name": "check_status","description": "Check order status and progress","inputSchema": {"type": "object","required": ["order_id"],"properties": {"order_id": {"type": "string"}}}}]}elif method == "tools/call":tool_name = params.get("name")arguments = params.get("arguments", {})# Call the actual APIasync with httpx.AsyncClient() as client:try:logger.info(f"Calling API: {API_BASE_URL}/{tool_name} with {arguments}")response = await client.post(f"{API_BASE_URL}/{tool_name}",json=arguments,10 unmodified lines]}except Exception as e:logger.error(f"API call failed: {str(e)}")raise Exception(f"Failed to call {tool_name}: {str(e)}")else:raise Exception(f"Unknown method: {method}")# Additional endpoints for debugging@app.get("/health")async def health():return {"status": "healthy", "api_backend": API_BASE_URL}@app.post("/test")async def test_endpoint(request: Request):"""Test endpoint to see raw requests"""body = await request.body()return {"headers": dict(request.headers),"body": body.decode() if body else None}if __name__ == "__main__":import uvicornport = int(os.environ.get("PORT", 7860))uvicorn.run(app, host="0.0.0.0", port=port)
app.py+102-84