Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/claude_agent_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,12 +392,27 @@ def _python_type_to_json_schema(py_type: Any) -> dict[str, Any]:
def _typeddict_to_json_schema(td_class: type) -> dict[str, Any]:
"""Convert a TypedDict class to a JSON Schema dict."""
hints = _get_type_hints(td_class, include_extras=True)
required_keys = set(getattr(td_class, "__required_keys__", hints.keys()))

properties: dict[str, Any] = {}
for field_name, field_type in hints.items():
properties[field_name] = _python_type_to_json_schema(field_type)
# Postponed annotations can leave __required_keys__ incorrect. Prefer
# evaluated qualifiers, including those nested inside Annotated/ReadOnly.
while True:
origin: Any = get_origin(field_type)
qualifier = getattr(origin, "_name", None)
if qualifier == "Required":
required_keys.add(field_name)
break
if qualifier == "NotRequired":
required_keys.discard(field_name)
break
if origin is Annotated or qualifier == "ReadOnly":
field_type = get_args(field_type)[0]
else:
break

required_keys = getattr(td_class, "__required_keys__", set(properties.keys()))
schema: dict[str, Any] = {
"type": "object",
"properties": properties,
Expand Down
61 changes: 61 additions & 0 deletions tests/test_sdk_mcp_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -2107,6 +2107,67 @@ class Empty(TypedDict):
class TestTypedDictMcpIntegration:
"""Tests for TypedDict schemas flowing through create_sdk_mcp_server."""

@pytest.mark.anyio
@pytest.mark.parametrize("total", [True, False])
@pytest.mark.parametrize(
"wrapper",
["{q}[{t}]", 'Annotated[{q}[{t}], "desc"]', '{q}[Annotated[{t}, "desc"]]'],
)
async def test_postponed_requiredness(
self, monkeypatch: pytest.MonkeyPatch, total: bool, wrapper: str
) -> None:
import sys
from types import ModuleType

typing_module = "typing" if sys.version_info >= (3, 11) else "typing_extensions"

module = ModuleType("_postponed_tool_params")
monkeypatch.setitem(sys.modules, module.__name__, module)
query_type = wrapper.format(q="Required", t="str")
limit_type = wrapper.format(q="NotRequired", t="int")
exec(
f"""from __future__ import annotations
from {typing_module} import Annotated, NotRequired, Required, TypedDict

class Base(TypedDict, total={not total}):
inherited: int

class Params(Base, total={total}):
query: {query_type}
limit: {limit_type}
default: int
""",
module.__dict__,
)
calls: list[dict[str, Any]] = []

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

default_key = "default" if total else "inherited"
valid = {"query": "test", default_key: 1}
config = create_sdk_mcp_server(name="srv", tools=[search])
async with connected(config) as client:
[listed] = await client.list_tools("srv")
schema = listed["inputSchema"]
assert schema["required"] == sorted(["query", default_key])
for name, kind in [("query", "string"), ("limit", "integer")]:
expected = {"type": kind}
if "Annotated" in wrapper:
expected["description"] = "desc"
assert schema["properties"][name] == expected

result = await client.call_tool("srv", "search", valid)
assert texts(result) == ["ok"]
missing = await client.call_tool("srv", "search", {default_key: 1})
assert missing["isError"] is True
assert texts(missing) == [
"Input validation error: 'query' is a required property"
]
assert calls == [valid]

@pytest.mark.anyio
async def test_typeddict_tool_schema_in_list_tools(self) -> None:
from typing import TypedDict
Expand Down