{"record":{"id":"42eb398d5198ee30","repo":"agentscope-ai/agentscope","slug":"connect-failed-e","errorCode":null,"errorMessage":"connect failed: {e}","messagePattern":"connect failed: (.+?)","errorType":"http","errorClass":"HTTPException","httpStatus":500,"severity":"error","filePath":"src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py","lineNumber":139,"sourceCode":"    ) -> dict[str, Any]:\n        body = await request.json()\n        name = body.get(\"name\", \"\")\n        if not name:\n            raise HTTPException(400, \"name required\")\n        async with state.lock:\n            by_name = state.clients.setdefault((agent_id, session_id), {})\n            if name in by_name:\n                raise HTTPException(\n                    409,\n                    f\"{name!r} already exists for agent={agent_id!r} \"\n                    f\"session={session_id!r}\",\n                )\n            try:\n                by_name[name] = await _build_client(body)\n            except HTTPException:\n                raise\n            except Exception as e:  # noqa: BLE001\n                raise HTTPException(500, f\"connect failed: {e}\") from e\n        return {\"ok\": True}\n\n    @app.delete(\"/mcps/{name}\")\n    async def _remove_mcp(\n        name: str,\n        agent_id: str = \"\",\n        session_id: str = \"\",\n    ) -> dict[str, Any]:\n        async with state.lock:\n            client = _lookup(agent_id, session_id, name)\n            del state.clients[(agent_id, session_id)][name]\n            if not state.clients[(agent_id, session_id)]:\n                del state.clients[(agent_id, session_id)]\n            if client.is_stateful and client.is_connected:\n                await client.close()\n        return {\"ok\": True}\n\n    @app.get(\"/mcps/{name}/tools\")","sourceCodeStart":121,"sourceCodeEnd":157,"githubUrl":"https://github.com/agentscope-ai/agentscope/blob/e90f1c7592896cc95f6e5ee506194f533378247d/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py#L121-L157","documentation":"Raised as HTTP 500 by _add_mcp when _build_client (which constructs and presumably connects the MCPClient) raises any non-HTTP exception. The original exception text is embedded as 'connect failed: {e}'. It indicates the server config was accepted syntactically but the client failed to reach or initialize the MCP server.","triggerScenarios":"POST /mcps with a url that is unreachable, wrong transport (streamable-http vs sse vs stdio), invalid command path for stdio servers, TLS failures, or the server not speaking the MCP handshake — any of these surfaces as 500 connect failed.","commonSituations":"MCP server not started yet, wrong port, http:// vs https:// mismatch, stdio command not on PATH, or version skew between client and server MCP protocol versions.","solutions":["Verify the MCP server is running and reachable: curl the URL or run the stdio command manually.","Fix the transport/config fields in the POST body to match the server (url, command/args, transport type).","Check the embedded exception text for the specific cause (connection refused vs timeout vs handshake error).","Upgrade/align agentscope and the MCP server versions if the error mentions protocol or capability mismatches."],"exampleFix":"# before\nawait client.post(\"/mcps\", json={\"name\": \"srv\", \"url\": \"http://localhost:9999/mcp\"})  # connect failed: [Errno 111]\n\n# after\n# start the server first: mcp-server --port 9999\nawait client.post(\"/mcps\", json={\"name\": \"srv\", \"url\": \"http://localhost:9999/mcp\"})","handlingStrategy":"retry","validationCode":"import httpx\n\nasync def mcp_server_reachable(url: str) -> bool:\n    try:\n        async with httpx.AsyncClient() as c:\n            await c.post(url, json={\"jsonrpc\": \"2.0\", \"method\": \"initialize\", \"id\": 1, \"params\": {}}, timeout=3)\n        return True\n    except Exception:\n        return False","typeGuard":null,"tryCatchPattern":"for attempt in range(3):\n    r = await client.post(\"/mcps\", json=config)\n    if r.status_code != 500 or \"connect failed\" not in r.text:\n        break\n    await asyncio.sleep(2 ** attempt)","preventionTips":["Start MCP servers before registering them with the gateway.","Add readiness checks (port open / initialize handshake) prior to POST /mcps.","Pin compatible versions of agentscope and your MCP servers."],"tags":["agentscope","mcp","gateway","connection","http-500","connect"],"backgroundTag":"mcp-server-connection-failed","analyzedSha":"e90f1c7592896cc95f6e5ee506194f533378247d","analyzedAt":"2026-08-28T18:24:12.087Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}