{"record":{"id":"a6bebebf6ab18b37","repo":"microsoft/semantic-kernel","slug":"messagehandlercontext-agent-id-must-be-called-wi","errorCode":null,"errorMessage":"MessageHandlerContext.agent_id() must be called within a message handler.","messagePattern":"MessageHandlerContext\\.agent_id\\(\\) must be called within a message handler\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/agents/runtime/in_process/message_handler_context.py","lineNumber":41,"sourceCode":"    _MESSAGE_HANDLER_CONTEXT: ClassVar[ContextVar[AgentId]] = ContextVar(\"_MESSAGE_HANDLER_CONTEXT\")\n\n    @classmethod\n    @contextmanager\n    def populate_context(cls, ctx: AgentId) -> Generator[None, Any, None]:\n        \"\"\"Populate the context with the current agent ID.\"\"\"\n        token = MessageHandlerContext._MESSAGE_HANDLER_CONTEXT.set(ctx)\n        try:\n            yield\n        finally:\n            MessageHandlerContext._MESSAGE_HANDLER_CONTEXT.reset(token)\n\n    @classmethod\n    def agent_id(cls) -> AgentId:\n        \"\"\"Get the current agent ID.\"\"\"\n        try:\n            return cls._MESSAGE_HANDLER_CONTEXT.get()\n        except LookupError as e:\n            raise RuntimeError(\"MessageHandlerContext.agent_id() must be called within a message handler.\") from e\n","sourceCodeStart":23,"sourceCodeEnd":42,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/agents/runtime/in_process/message_handler_context.py#L23-L42","documentation":"MessageHandlerContext.agent_id() reads the _MESSAGE_HANDLER_CONTEXT ContextVar, which is only set when the runtime dispatches a message to a handler (via populate_context). If called outside a message handler invocation, the ContextVar lookup raises LookupError, re-raised as RuntimeError.","triggerScenarios":"Calling MessageHandlerContext.agent_id() in agent code that runs outside of a message handler callback — e.g. in __init__, in a background task, or in code invoked directly by the user rather than through the runtime's message dispatch.","commonSituations":"An agent method that is called both as a message handler and directly by user code. A message handler spawns a background task that later calls agent_id() after the populate_context scope has exited.","solutions":["Only call MessageHandlerContext.agent_id() from within a message handler invoked by the runtime.","If you need the agent ID outside a handler, capture it from within the handler and pass it through.","Store the agent ID as an instance attribute set during the first message handler invocation."],"exampleFix":"# before\nclass MyAgent:\n    def do_something(self):\n        aid = MessageHandlerContext.agent_id()  # raises if called outside handler\n\n# after\nclass MyAgent:\n    async def handle_message(self, message, ctx):\n        self._cached_id = MessageHandlerContext.agent_id()  # ok: inside handler\n        # pass self._cached_id to deferred work","handlingStrategy":"try-catch","validationCode":"null","typeGuard":"null","tryCatchPattern":"from semantic_kernel.agents.runtime.in_process.message_handler_context import MessageHandlerContext\ntry:\n    agent_id = MessageHandlerContext.agent_id()\nexcept RuntimeError:\n    # Not inside a message handler — use explicit agent_id\n    agent_id = self._stored_agent_id","preventionTips":["Only call MessageHandlerContext.agent_id() from within a message handler.","Capture the agent_id inside the handler and pass it to deferred/background work.","Store agent_id as an instance attribute for later use outside handler scope."],"tags":["agent-runtime","message-handler","contextvar","agent-id","semantic-kernel"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}