{"record":{"id":"5151b85f73c27877","repo":"microsoft/autogen","slug":"mcp-actor-not-running-call-initialize-first","errorCode":null,"errorMessage":"MCP Actor not running, call initialize() first","messagePattern":"MCP Actor not running, call initialize\\(\\) first","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-ext/src/autogen_ext/tools/mcp/_actor.py","lineNumber":100,"sourceCode":"        self._command_queue: asyncio.Queue[Dict[str, Any]] = asyncio.Queue()\n        self._actor_task: asyncio.Task[Any] | None = None\n        self._shutdown_future: asyncio.Future[Any] | None = None\n        self._active = False\n        self._initialize_result: mcp_types.InitializeResult | None = None\n        atexit.register(self._sync_shutdown)\n\n    @property\n    def initialize_result(self) -> mcp_types.InitializeResult | None:\n        return self._initialize_result\n\n    async def initialize(self) -> None:\n        if not self._active:\n            self._active = True\n            self._actor_task = asyncio.create_task(self._run_actor())\n\n    async def call(self, type: str, args: McpActorArgs | None = None) -> McpFuture:\n        if not self._active:\n            raise RuntimeError(\"MCP Actor not running, call initialize() first\")\n        if self._actor_task and self._actor_task.done():\n            raise RuntimeError(\"MCP actor task crashed\", self._actor_task.exception())\n        fut: asyncio.Future[McpFuture] = asyncio.Future()\n        if type in {\"list_tools\", \"list_prompts\", \"list_resources\", \"list_resource_templates\", \"shutdown\"}:\n            await self._command_queue.put({\"type\": type, \"future\": fut})\n            res = await fut\n        elif type in {\"call_tool\", \"read_resource\", \"get_prompt\"}:\n            if args is None:\n                raise ValueError(f\"args is required for {type}\")\n            name = args.get(\"name\", None)\n            kwargs = args.get(\"kargs\", {})\n            if type == \"call_tool\" and name is None:\n                raise ValueError(\"name is required for call_tool\")\n            elif type == \"read_resource\":\n                uri = kwargs.get(\"uri\", None)\n                if uri is None:\n                    raise ValueError(\"uri is required for read_resource\")\n                await self._command_queue.put({\"type\": type, \"uri\": uri, \"future\": fut})","sourceCodeStart":82,"sourceCodeEnd":118,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_actor.py#L82-L118","documentation":"The MCP actor is a long-running asyncio task that owns the MCP session. call() checks the self._active flag set only by initialize(); calling any command before initialize() (or after close() reset it) raises RuntimeError('MCP Actor not running, call initialize() first'). It is a lifecycle-order error, not an MCP protocol error.","triggerScenarios":"Calling actor.call('list_tools') (or call_tool/read_resource/get_prompt) without awaiting actor.initialize() first, or after close() has run and cleared _active. Also when initialize() was scheduled but not awaited, so the flag is not yet set.","commonSituations":"Forgetting the initialize step in a script; awaiting initialize() on a different actor instance than the one used for call(); reusing an actor after close() in a retry loop; calling from a different event loop/task where initialization raced ahead.","solutions":["Await actor.initialize() before the first call(): await actor.initialize(); result = await actor.call('list_tools').","Make sure you call methods on the same actor instance you initialized.","After close(), create a new actor or re-call initialize() before issuing more commands.","In frameworks that manage the actor (e.g. McpWorkbench), use the framework's lifecycle entry points instead of touching the actor directly."],"exampleFix":"# before\nactor = McpActor(session_factory)\ntools = await actor.call(\"list_tools\")  # RuntimeError\n\n# after\nactor = McpActor(session_factory)\nawait actor.initialize()\ntools = await actor.call(\"list_tools\")","handlingStrategy":"validation","validationCode":"if not actor._active:  # or track initialized state in your wrapper\n    await actor.initialize()","typeGuard":null,"tryCatchPattern":"try:\n    res = await actor.call(\"list_tools\")\nexcept RuntimeError as e:\n    if \"not running\" in str(e):\n        await actor.initialize()\n        res = await actor.call(\"list_tools\")\n    else:\n        raise","preventionTips":["Encapsulate the actor in a context manager that initializes on __aenter__ and closes on __aexit__.","Never share actor construction and call sites across different code paths.","Add an integration test that exercises the full lifecycle (init -> call -> close)."],"tags":["mcp","lifecycle","asyncio","initialization"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}