FoundationAgents/OpenManus · error · RuntimeError

Session not initialized for server {server_id}

Error message

Session not initialized for server {server_id}

What it means

Raised by MCPClient._initialize_and_list_tools (app/tool/mcp.py:101) when the given server_id has no entry in self.sessions. It is a RuntimeError indicating an internal ordering bug: the helper is supposed to be called immediately after a session is registered by connect_sse/connect_stdio, so reaching it without a session means the key never matched (e.g. server_id normalization mismatch) or the session was concurrently removed.

Source

Thrown at app/tool/mcp.py:101

        exit_stack = AsyncExitStack()
        self.exit_stacks[server_id] = exit_stack

        server_params = StdioServerParameters(command=command, args=args)
        stdio_transport = await exit_stack.enter_async_context(
            stdio_client(server_params)
        )
        read, write = stdio_transport
        session = await exit_stack.enter_async_context(ClientSession(read, write))
        self.sessions[server_id] = session

        await self._initialize_and_list_tools(server_id)

    async def _initialize_and_list_tools(self, server_id: str) -> None:
        """Initialize session and populate tool map."""
        session = self.sessions.get(server_id)
        if not session:
            raise RuntimeError(f"Session not initialized for server {server_id}")

        await session.initialize()
        response = await session.list_tools()

        # Create proper tool objects for each server tool
        for tool in response.tools:
            original_name = tool.name
            tool_name = f"mcp_{server_id}_{original_name}"
            tool_name = self._sanitize_tool_name(tool_name)

            server_tool = MCPClientTool(
                name=tool_name,
                description=tool.description,
                parameters=tool.inputSchema,
                session=session,
                server_id=server_id,
                original_name=original_name,
            )

View on GitHub (pinned to 52a13f2a57)

Solutions

  1. Do not call _initialize_and_list_tools directly; use connect_sse/connect_stdio, which register the session first.
  2. Use the exact same server_id for connect/disconnect/initialize — derive it once and pass it everywhere.
  3. Guard concurrent access: serialize connect/disconnect per server_id (e.g. an asyncio.Lock keyed by server_id) so a disconnect cannot interleave with initialization.
  4. If invoking manually, check membership first: `if server_id not in mcp.sessions: await mcp.connect_*(...)`.

Example fix

// before
await mcp._initialize_and_list_tools('fs')  # RuntimeError if never connected

// after
if 'fs' not in mcp.sessions:
    await mcp.connect_stdio('npx', ['-y', '@modelcontextprotocol/server-filesystem'], server_id='fs')
# session is initialized and tools listed by connect itself
Defensive patterns

Strategy: validation

Validate before calling

if server_id not in mcp.sessions:
    await mcp.connect_stdio(cmd, args, server_id=server_id)  # connect initializes+lists
# session is now guaranteed initialized

Type guard

def session_ready(mcp, server_id: str) -> bool:
    return server_id in mcp.sessions and mcp.sessions[server_id] is not None

Try / catch

try:
    await call_tool(f'mcp_{server_id}_{tool_name}', args)
except RuntimeError as e:
    if 'Session not initialized' in str(e):
        await mcp.connect_stdio(cmd, args, server_id=server_id)  # reconnect once
        await call_tool(f'mcp_{server_id}_{tool_name}', args)
    else:
        raise

Prevention

When it happens

Trigger: Calling _initialize_and_list_tools directly without a prior successful connect; a race where disconnect(server_id) ran between registration and initialization; server_id differing between the connect call and the lookup (e.g. one used a URL-derived id, the other a custom id, or a sanitization step changed the key).

Common situations: Custom integrations that reuse the private helper instead of the public connect methods; concurrent reconnect logic that disconnects while another task initializes; server_id values containing characters that get sanitized in tool names but not consistently in session keys.

Related errors


AI-assisted analysis of FoundationAgents/OpenManus@52a13f2a57 (2026-08-15). Data as JSON: /api/errors/a015bdd2c0f32a0d. Report an issue: GitHub.