Skip to content

MCP TypedDict schemas misclassify Required/NotRequired under postponed annotations #1344

Open

Description

@wevt

We found and reproduced this during our local correctness review of the SDK. No matching public report was found in our issue/PR searches; this is not a claim that nobody has discovered it privately.

Reproduced against commit db750b2 (SDK 0.2.163), Python 3.13.14, MCP 2.2.0, on asyncio and Trio. All inputs and transports were synthetic/local; no live Claude services or credentials were used.

1. Postponed annotations corrupt TypedDict tool requiredness

Source: src/claude_agent_sdk/__init__.py, _typeddict_to_json_schema, lines 392–407, specifically line 400. Runtime rejection occurs in run_tool, lines 600–603.

Exact reviewed source

Minimal reproduction of schema generation:

from __future__ import annotations
from typing import TypedDict, NotRequired
from claude_agent_sdk import _typeddict_to_json_schema

class Params(TypedDict):
    query: str
    limit: NotRequired[int]

print(_typeddict_to_json_schema(Params)["required"])
# Expected: ['query']
# Actual:   ['limit', 'query']

The helper above is private to keep the minimal demonstration short. The in-memory reproduction below also confirms the externally observable behavior using the public @tool, create_sdk_mcp_server, and MCP ClientSession APIs over in-memory streams. Calling the tool with {"query": "test"} returns isError=true and Input validation error: 'limit' is a required property; the Python handler never runs. The valid call should execute the handler.

The reverse is confirmed too: with class RequiredParams(TypedDict, total=False): query: Required[str], the generated schema has no required array. A call with {} is accepted and invokes the handler. It should fail validation for missing query.

Cause: The converter evaluates annotations with get_type_hints(..., include_extras=True) but obtains requiredness separately from __required_keys__. With postponed annotations, that metadata can be wrong even though the evaluated hints correctly contain Required/NotRequired. Python explicitly documents this limitation: TypedDict runtime introspection. The converter needs to apply evaluated requiredness qualifiers to its metadata-derived defaults, including qualifiers wrapped in Annotated.

Practical impact: A normal module-level future import causes optional tool arguments to become mandatory, rejects valid calls before handlers run, and can allow missing required arguments through to handlers. It also publishes misleading MCP tool schemas. Removing postponed annotations is a verified control: the schema correctly requires only query.

Public-report check: No matching public issue or PR was found as of 2026-10-01. Searched 1,329 accessible issue/PR titles and bodies, plus GitHub issue search (including indexed comments) for postponed, future TypedDict, __required_keys__, and NotRequired optional. Inspected related schema PR discussion/review comments on #726, #733–736, #761, #762, #1176, and #1341, and issue #1337. PR #761 concerns unsupported stdlib/backport mixing on Python 3.10; this reproduces with stdlib typing on Python 3.13. PR #1176 covers nullable/types conversion, not postponed-annotation requiredness. This is a search result, not proof that nobody has discovered it privately.

Full offline public-API reproduction

Run with Python (default asyncio), or pass "trio" as the first argument. The script also checks the separately reported session-summary bug.

from __future__ import annotations

import asyncio
import json
import sys
from typing import TypedDict, NotRequired, Required
from uuid import uuid4

import anyio
from mcp import ClientSession
from claude_agent_sdk import (
    tool, create_sdk_mcp_server, InMemorySessionStore,
    project_key_for_directory, get_session_info_from_store,
    list_sessions_from_store,
)

class Params(TypedDict):
    query: str
    limit: NotRequired[int]

class RequiredParams(TypedDict, total=False):
    query: Required[str]
    limit: int

calls = []

@tool("search", "Search", Params)
async def search(args):
    calls.append(args)
    return {"content": [{"type": "text", "text": "ok"}]}

@tool("required_search", "Search", RequiredParams)
async def required_search(args):
    return {"content": [{"type": "text", "text": "ok"}]}

async def main():
    server = create_sdk_mcp_server("repro", tools=[search, required_search])["instance"]
    client_send, server_receive = anyio.create_memory_object_stream(20)
    server_send, client_receive = anyio.create_memory_object_stream(20)
    async with anyio.create_task_group() as tg:
        tg.start_soon(server.run, server_receive, server_send, server.create_initialization_options())
        async with ClientSession(client_receive, client_send) as client:
            await client.initialize()
            listed = await client.list_tools()
            print("SCHEMAS", json.dumps({t.name: t.model_dump(by_alias=True)["inputSchema"] for t in listed.tools}))
            omitted_optional = await client.call_tool("search", {"query": "test"})
            print("OMITTED OPTIONAL", omitted_optional.model_dump_json())
            assert omitted_optional.model_dump(by_alias=True)["isError"] and not calls
            omitted_required = await client.call_tool("required_search", {})
            print("OMITTED REQUIRED", omitted_required.model_dump_json())
            assert not omitted_required.model_dump(by_alias=True)["isError"]
        tg.cancel_scope.cancel()

    store = InMemorySessionStore()
    sid = str(uuid4())
    directory = "."
    key = {"project_key": project_key_for_directory(directory), "session_id": sid}
    await store.append(key, [{"type": "user", "uuid": str(uuid4()), "sessionId": sid,
                             "timestamp": "2026-10-01T00:00:00Z",
                             "message": {"role": "user", "content": [{"type": "text", "text": "tool_result"}]}}])
    info = await get_session_info_from_store(store, sid, directory)
    sessions = await list_sessions_from_store(store, directory)
    print("SINGLE SESSION INFO", info)
    print("LIST SESSION PROMPTS", [s.first_prompt for s in sessions])
    assert info is None
    assert [s.first_prompt for s in sessions] == ["tool_result"]

anyio.run(main, backend=sys.argv[1] if len(sys.argv) > 1 else "asyncio")

Activity

  1. added
    bug
    on Oct 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions