microsoft/semantic-kernel · error · RuntimeError
MessageHandlerContext.agent_id() must be called within a mes
Error message
MessageHandlerContext.agent_id() must be called within a message handler.
What it means
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.
Source
Thrown at python/semantic_kernel/agents/runtime/in_process/message_handler_context.py:41
_MESSAGE_HANDLER_CONTEXT: ClassVar[ContextVar[AgentId]] = ContextVar("_MESSAGE_HANDLER_CONTEXT")
@classmethod
@contextmanager
def populate_context(cls, ctx: AgentId) -> Generator[None, Any, None]:
"""Populate the context with the current agent ID."""
token = MessageHandlerContext._MESSAGE_HANDLER_CONTEXT.set(ctx)
try:
yield
finally:
MessageHandlerContext._MESSAGE_HANDLER_CONTEXT.reset(token)
@classmethod
def agent_id(cls) -> AgentId:
"""Get the current agent ID."""
try:
return cls._MESSAGE_HANDLER_CONTEXT.get()
except LookupError as e:
raise RuntimeError("MessageHandlerContext.agent_id() must be called within a message handler.") from e
View on GitHub (pinned to c028a0c7dc)
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.
Example fix
# before
class MyAgent:
def do_something(self):
aid = MessageHandlerContext.agent_id() # raises if called outside handler
# after
class MyAgent:
async def handle_message(self, message, ctx):
self._cached_id = MessageHandlerContext.agent_id() # ok: inside handler
# pass self._cached_id to deferred work Defensive patterns
Strategy: try-catch
Validate before calling
null
Type guard
null
Try / catch
from semantic_kernel.agents.runtime.in_process.message_handler_context import MessageHandlerContext
try:
agent_id = MessageHandlerContext.agent_id()
except RuntimeError:
# Not inside a message handler — use explicit agent_id
agent_id = self._stored_agent_id Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- AgentInstantiationContext.agent_id() must be called within a
- MessageHandlerContext cannot be instantiated. It is a static
- AgentInstantiationContext cannot be instantiated. It is a st
- AgentInstantiationContext.runtime() must be called within an
- If agent_type is not specified DefaultSubscription must be c
AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13).
Data as JSON: /api/errors/a6bebebf6ab18b37.
Report an issue: GitHub.