{"record":{"id":"fc75dff449bbbfd1","repo":"microsoft/semantic-kernel","slug":"subscriptioninstantiationcontext-runtime-must-be","errorCode":null,"errorMessage":"SubscriptionInstantiationContext.runtime() must be called within an instantiation context such as when the AgentRuntime is instantiating an agent. Mostly likely this was caused by directly instantiating an agent instead of using the AgentRuntime to do so.","messagePattern":"SubscriptionInstantiationContext\\.runtime\\(\\) must be called within an instantiation context such as when the AgentRuntime is instantiating an agent\\. Mostly likely this was caused by directly instantiating an agent instead of using the AgentRuntime to do so\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/agents/runtime/in_process/subscription_context.py","lineNumber":41,"sourceCode":"    _SUBSCRIPTION_CONTEXT_VAR: ClassVar[ContextVar[AgentType]] = ContextVar(\"_SUBSCRIPTION_CONTEXT_VAR\")\n\n    @classmethod\n    @contextmanager\n    def populate_context(cls, ctx: AgentType) -> Generator[None, Any, None]:\n        \"\"\"Populate the context with the agent type.\"\"\"\n        token = SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.set(ctx)\n        try:\n            yield\n        finally:\n            SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.reset(token)\n\n    @classmethod\n    def agent_type(cls) -> AgentType:\n        \"\"\"Get the agent type from the context.\"\"\"\n        try:\n            return cls._SUBSCRIPTION_CONTEXT_VAR.get()\n        except LookupError as e:\n            raise RuntimeError(\n                \"SubscriptionInstantiationContext.runtime() must be called within an instantiation context such as \"\n                \"when the AgentRuntime is instantiating an agent. Mostly likely this was caused by directly \"\n                \"instantiating an agent instead of using the AgentRuntime to do so.\"\n            ) from e\n","sourceCodeStart":23,"sourceCodeEnd":46,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/agents/runtime/in_process/subscription_context.py#L23-L46","documentation":"agent_type() reads a ContextVar that is set only while the runtime is instantiating an agent (inside populate_context). When the ContextVar is unset, ContextVar.get() raises LookupError, which is caught and re-raised as RuntimeError. This almost always means an agent was constructed directly instead of through the runtime.","triggerScenarios":"Calling SubscriptionInstantiationContext.agent_type() from application code outside the runtime's instantiation flow, or constructing an agent directly (e.g. `MyAgent(...)`) whose constructor reads agent_type() instead of obtaining the agent via the runtime (`await runtime.get_agent` / register-and-get APIs).","commonSituations":"Direct agent instantiation bypassing the runtime; calling agent_type in a separate asyncio Task or thread to which the ContextVar was not propagated; testing an agent in isolation without establishing the context.","solutions":["Instantiate agents through the runtime API (get/register helpers) so populate_context is active during construction.","If you must call agent_type manually, wrap the call in `with SubscriptionInstantiationContext.populate_context(agent_type):`","When spawning tasks, ensure they run within the same context or re-establish it, since ContextVar values do not cross certain boundaries automatically."],"exampleFix":"// before\nagent = MyAgent(name=\"a\", runtime=runtime)  # constructor reads agent_type() -> no context set\n\n// after\nagent = await runtime.get_agent(...)  # runtime sets the instantiation context first","handlingStrategy":"try-catch","validationCode":"# Prefer not to call agent_type() yourself. If you must, ensure a context is active:\nfrom semantic_kernel.agents.runtime.in_process.subscription_context import SubscriptionInstantiationContext\n\ntry:\n    SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.get()\n    has_context = True\nexcept LookupError:\n    has_context = False\nif not has_context:\n    raise RuntimeError('no instantiation context; obtain the agent via the runtime instead')","typeGuard":null,"tryCatchPattern":"try:\n    agent_type = SubscriptionInstantiationContext.agent_type()\nexcept RuntimeError:\n    # no context: fall back to runtime-managed instantiation\n    agent = await runtime.get_agent(...)","preventionTips":["Never construct agents directly; always go through the runtime","Do not call agent_type() from arbitrary application code","Propagate context when spawning tasks that need it"],"tags":["runtime","agent-runtime","context","contextvar"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}