{"record":{"id":"3b85f504ba2816f9","repo":"agentscope-ai/agentscope","slug":"mcp-self-name-session-is-not-initialized-call","errorCode":null,"errorMessage":"MCP '{self.name}' session is not initialized. Call connect() first.","messagePattern":"MCP '(.+?)' session is not initialized\\. Call connect\\(\\) first\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/agentscope/mcp/_mcp_client.py","lineNumber":441,"sourceCode":"                mcp_name=self.name,\n                tool=target_tool,\n                session=self._session,\n                timeout=self.execution_timeout,\n            )\n\n    def _validate_connection(self) -> None:\n        \"\"\"Validate connection state for stateful connections.\n\n        Raises:\n            RuntimeError: If not connected or session not initialized.\n        \"\"\"\n        if not self._is_connected:\n            raise RuntimeError(\n                f\"MCP '{self.name}' is not connected. \"\n                \"Call connect() first.\",\n            )\n        if not self._session:\n            raise RuntimeError(\n                f\"MCP '{self.name}' session is not initialized. \"\n                \"Call connect() first.\",\n            )\n","sourceCodeStart":423,"sourceCodeEnd":445,"githubUrl":"https://github.com/agentscope-ai/agentscope/blob/e90f1c7592896cc95f6e5ee506194f533378247d/src/agentscope/mcp/_mcp_client.py#L423-L445","documentation":"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.","triggerScenarios":"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().","commonSituations":"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.","solutions":["Call close() then connect() again to re-establish a clean session","Ensure only one coroutine connects a given client at a time (use an asyncio.Lock if needed)","Report as a bug if it reproduces with a stock transport on the current version"],"exampleFix":"// before\ntools = await client.list_tools()  # RuntimeError 230: session missing\n\n// after\nif not getattr(client, \"_session\", None):\n    await client.close()\n    await client.connect()\ntools = await client.list_tools()","handlingStrategy":"retry","validationCode":"if client.is_stateful and (not client._is_connected or not getattr(client, \"_session\", None)):\n    await client.close()\n    await client.connect()","typeGuard":null,"tryCatchPattern":"try:\n    tools = await client.list_tools()\nexcept RuntimeError as e:\n    if \"session is not initialized\" in str(e):\n        await client.close()\n        await client.connect()\n        tools = await client.list_tools()\n    else:\n        raise","preventionTips":["Serialize connect() calls with an asyncio.Lock per client","Treat a missing session after connect as a stale state: full close+reconnect","Avoid swallowing exceptions inside connect() setup code"],"tags":["mcp","session-initialization","not-connected"],"backgroundTag":"session-not-initialized","analyzedSha":"e90f1c7592896cc95f6e5ee506194f533378247d","analyzedAt":"2026-08-28T18:24:12.087Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}