agentscope-ai/agentscope · error · HTTPException

connect failed: {e}

Error message

connect failed: {e}

What it means

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.

Source

Thrown at src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py:139

    ) -> dict[str, Any]:
        body = await request.json()
        name = body.get("name", "")
        if not name:
            raise HTTPException(400, "name required")
        async with state.lock:
            by_name = state.clients.setdefault((agent_id, session_id), {})
            if name in by_name:
                raise HTTPException(
                    409,
                    f"{name!r} already exists for agent={agent_id!r} "
                    f"session={session_id!r}",
                )
            try:
                by_name[name] = await _build_client(body)
            except HTTPException:
                raise
            except Exception as e:  # noqa: BLE001
                raise HTTPException(500, f"connect failed: {e}") from e
        return {"ok": True}

    @app.delete("/mcps/{name}")
    async def _remove_mcp(
        name: str,
        agent_id: str = "",
        session_id: str = "",
    ) -> dict[str, Any]:
        async with state.lock:
            client = _lookup(agent_id, session_id, name)
            del state.clients[(agent_id, session_id)][name]
            if not state.clients[(agent_id, session_id)]:
                del state.clients[(agent_id, session_id)]
            if client.is_stateful and client.is_connected:
                await client.close()
        return {"ok": True}

    @app.get("/mcps/{name}/tools")

View on GitHub (pinned to e90f1c7592)

Solutions

  1. Verify the MCP server is running and reachable: curl the URL or run the stdio command manually.
  2. Fix the transport/config fields in the POST body to match the server (url, command/args, transport type).
  3. Check the embedded exception text for the specific cause (connection refused vs timeout vs handshake error).
  4. Upgrade/align agentscope and the MCP server versions if the error mentions protocol or capability mismatches.

Example fix

# before
await client.post("/mcps", json={"name": "srv", "url": "http://localhost:9999/mcp"})  # connect failed: [Errno 111]

# after
# start the server first: mcp-server --port 9999
await client.post("/mcps", json={"name": "srv", "url": "http://localhost:9999/mcp"})
Defensive patterns

Strategy: retry

Validate before calling

import httpx

async def mcp_server_reachable(url: str) -> bool:
    try:
        async with httpx.AsyncClient() as c:
            await c.post(url, json={"jsonrpc": "2.0", "method": "initialize", "id": 1, "params": {}}, timeout=3)
        return True
    except Exception:
        return False

Try / catch

for attempt in range(3):
    r = await client.post("/mcps", json=config)
    if r.status_code != 500 or "connect failed" not in r.text:
        break
    await asyncio.sleep(2 ** attempt)

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of agentscope-ai/agentscope@e90f1c7592 (2026-08-28). Data as JSON: /api/errors/42eb398d5198ee30. Report an issue: GitHub.