microsoft/semantic-kernel · error · CantHandleException

Message type {type(message)} not in target types {target_typ

Error message

Message type {type(message)} not in target types {target_types}

What it means

Raised at runtime by the @message_handler wrapper (strict mode) when an incoming message's concrete type is not in the handler's declared target_types. This is a routing/contract mismatch: the runtime dispatched a message to a handler whose signature does not cover that type.

Source

Thrown at python/semantic_kernel/agents/runtime/core/routed_agent.py:153

            raise AssertionError("return not found in function signature")

        # Get the type of the message parameter
        target_types = get_types(type_hints["message"])
        if target_types is None:
            raise AssertionError("Message type not found")

        return_types = get_types(type_hints["return"])

        if return_types is None:
            raise AssertionError("Return type not found")

        # Convert target_types to list and stash

        @wraps(func)
        async def wrapper(self: AgentT, message: ReceivesT, ctx: MessageContext) -> ProducesT:
            if type(message) not in target_types:
                if strict:
                    raise CantHandleException(f"Message type {type(message)} not in target types {target_types}")
                logger.warning(f"Message type {type(message)} not in target types {target_types}")

            return_value = await func(self, message, ctx)

            if AnyType not in return_types and type(return_value) not in return_types:
                if strict:
                    raise ValueError(f"Return type {type(return_value)} not in return types {return_types}")
                logger.warning(f"Return type {type(return_value)} not in return types {return_types}")

            return return_value

        wrapper_handler = cast(MessageHandler[AgentT, ReceivesT, ProducesT], wrapper)
        wrapper_handler.target_types = list(target_types)
        wrapper_handler.produces_types = list(return_types)
        wrapper_handler.is_message_handler = True
        wrapper_handler.router = match or (lambda _message, _ctx: True)

        return wrapper_handler

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Add the delivered message type to the handler's message annotation (Union[Existing, NewType]).
  2. Set strict=False to demote this to a logged warning (only if skipping is acceptable).
  3. Fix the subscription/routing so the message is delivered to a handler that declares it.
  4. Ensure the published message is an instance of a declared type, not a subclass whose exact type() differs.

Example fix

// before
@message_handler
async def handle(self, message: Foo, ctx: MessageContext) -> None: ...
# runtime delivers Bar -> CantHandleException
// after
@message_handler
async def handle(self, message: Union[Foo, Bar], ctx: MessageContext) -> None: ...
Defensive patterns

Strategy: try-catch

Validate before calling

from semantic_kernel.agents.runtime.core.type_helpers import get_types

def message_in_target_types(message, target_types) -> bool:
    return type(message) in target_types

Type guard

from typing import Any

def message_matches_handler(message: Any, target_types) -> bool:
    return type(message) in target_types

Try / catch

from semantic_kernel.agents.runtime.core.exceptions import CantHandleException

try:
    await handler.run(message, ctx)
except CantHandleException as e:
    if "not in target types" in str(e):
        # route to the correct handler or set strict=False
        pass
    else:
        raise

Prevention

When it happens

Trigger: The runtime delivers a message of type X to a handler declared for type Y (or a Union not including X), and strict=True (default for the wrapper). Happens with shared topics, mismatched subscriptions, or when a subclass changes the message type but not the subscription.

Common situations: Two handlers on the same topic with overlapping but not identical message types; publishing a message type the handler was not declared to receive; inheritance where a base handler is reused for a new message type without updating the annotation.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/9d952cdb6a7c9b4f. Report an issue: GitHub.