agentscope-ai/agentscope · error · RuntimeError

MCP '{self.name}' session is not initialized. Call connect()

Error message

MCP '{self.name}' session is not initialized. Call connect() first.

What it means

Companion check to 229: the client is marked connected but the MCP _session object is missing, meaning connect() did not fully initialize the session (partial failure) or internal state was corrupted. _validate_connection raises so tool operations fail fast instead of dereferencing None.

Source

Thrown at src/agentscope/mcp/_mcp_client.py:441

                mcp_name=self.name,
                tool=target_tool,
                session=self._session,
                timeout=self.execution_timeout,
            )

    def _validate_connection(self) -> None:
        """Validate connection state for stateful connections.

        Raises:
            RuntimeError: If not connected or session not initialized.
        """
        if not self._is_connected:
            raise RuntimeError(
                f"MCP '{self.name}' is not connected. "
                "Call connect() first.",
            )
        if not self._session:
            raise RuntimeError(
                f"MCP '{self.name}' session is not initialized. "
                "Call connect() first.",
            )

View on GitHub (pinned to e90f1c7592)

Solutions

  1. Call close() then connect() again to re-establish a clean session
  2. Ensure only one coroutine connects a given client at a time (use an asyncio.Lock if needed)
  3. Report as a bug if it reproduces with a stock transport on the current version

Example fix

// before
tools = await client.list_tools()  # RuntimeError 230: session missing

// after
if not getattr(client, "_session", None):
    await client.close()
    await client.connect()
tools = await client.list_tools()
Defensive patterns

Strategy: retry

Validate before calling

if client.is_stateful and (not client._is_connected or not getattr(client, "_session", None)):
    await client.close()
    await client.connect()

Try / catch

try:
    tools = await client.list_tools()
except RuntimeError as e:
    if "session is not initialized" in str(e):
        await client.close()
        await client.connect()
        tools = await client.list_tools()
    else:
        raise

Prevention

When it happens

Trigger: connect() completed enough to set _is_connected but the session handshake/initialization step failed or was interrupted; or internal state manipulated directly. Triggered by list_raw_tools()/get_tool().

Common situations: Exceptions during session initialization swallowed by broad try/except; race between concurrent connect() calls on the same client; bugs in custom transports that exit the AsyncExitStack early.

Related errors


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