{"record":{"id":"4d8219597fd0461b","repo":"microsoft/autogen","slug":"closureagent-must-be-instantiated-within-the-conte","errorCode":null,"errorMessage":"ClosureAgent must be instantiated within the context of an AgentRuntime. It cannot be directly instantiated.","messagePattern":"ClosureAgent must be instantiated within the context of an AgentRuntime\\. It cannot be directly instantiated\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-core/src/autogen_core/_closure_agent.py","lineNumber":88,"sourceCode":"        topic_id: TopicId,\n        *,\n        cancellation_token: CancellationToken | None = None,\n    ) -> None: ...\n\n\nclass ClosureAgent(BaseAgent, ClosureContext):\n    def __init__(\n        self,\n        description: str,\n        closure: Callable[[ClosureContext, T, MessageContext], Awaitable[Any]],\n        *,\n        unknown_type_policy: Literal[\"error\", \"warn\", \"ignore\"] = \"warn\",\n    ) -> None:\n        try:\n            runtime = AgentInstantiationContext.current_runtime()\n            id = AgentInstantiationContext.current_agent_id()\n        except Exception as e:\n            raise RuntimeError(\n                \"ClosureAgent must be instantiated within the context of an AgentRuntime. It cannot be directly instantiated.\"\n            ) from e\n\n        self._runtime: AgentRuntime = runtime\n        self._id: AgentId = id\n        self._description = description\n        handled_types = get_handled_types_from_closure(closure)\n        self._expected_types = handled_types\n        self._closure = closure\n        self._unknown_type_policy = unknown_type_policy\n        super().__init__(description)\n\n    @property\n    def metadata(self) -> AgentMetadata:\n        assert self._id is not None\n        return AgentMetadata(\n            key=self._id.key,\n            type=self._id.type,","sourceCodeStart":70,"sourceCodeEnd":106,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-core/src/autogen_core/_closure_agent.py#L70-L106","documentation":"ClosureAgent.__init__ immediately calls AgentInstantiationContext.current_runtime() and current_agent_id(); outside a runtime factory call both raise, and the except re-raises as RuntimeError. Unlike plain BaseAgent subclasses, ClosureAgent cannot be constructed standalone or via bind_id_and_runtime — it must be created by a registered runtime factory.","triggerScenarios":"ClosureAgent(\"d\", closure) in ordinary code or tests; registering it with a factory that is never invoked through the runtime; constructing inside a thread/task where the ContextVar is not set.","commonSituations":"Prototyping closures without setting up a runtime; calling the constructor in unit tests instead of registering with SingleThreadedAgentRuntime and using runtime.get()/send_message.","solutions":["Register via ClosureAgent.register(runtime, \"closure_agent\", lambda: ClosureAgent(\"desc\", my_closure)) and instantiate through the runtime.","Trigger instantiation by sending a message to the agent or calling await runtime.get(\"closure_agent\").","In tests, instantiate inside populate_context((runtime, AgentId(...))) if you truly need a direct handle."],"exampleFix":"# before\nagent = ClosureAgent(\"d\", my_closure)  # RuntimeError\n\n# after\nawait ClosureAgent.register(\n    runtime, \"closure_agent\", lambda: ClosureAgent(\"d\", my_closure)\n)\nagent = await runtime.get(\"closure_agent\")","handlingStrategy":"try-catch","validationCode":"from autogen_core import AgentInstantiationContext\n\nif not AgentInstantiationContext.is_in_factory_call():\n    raise RuntimeError(\"construct ClosureAgent via runtime-registered factory\")","typeGuard":null,"tryCatchPattern":"try:\n    agent = ClosureAgent(\"d\", closure)\nexcept RuntimeError as e:\n    if \"must be instantiated within the context of an AgentRuntime\" in str(e):\n        # fix call site: register factory with a runtime instead\n        raise\n    raise","preventionTips":["Always create ClosureAgents through ClosureAgent.register(runtime, type, factory).","Instantiate with await runtime.get(type) or by sending a message.","Never call the ClosureAgent constructor directly in application or test code."],"tags":["autogen-core","closure-agent","instantiation","runtime"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}