From 7bc0ccc337360e50e232192ce65c6d1042056554 Mon Sep 17 00:00:00 2001 From: CS Date: Wed, 11 Nov 2026 17:45:05 -0800 Subject: [PATCH 1/4] fix(sdk): @mcp_tool emits JSON Schema types, not Python type names (#362) Schema extraction wrote getattr(hint, "__name__") into "type", so an annotated parameter became {"type": "str"} or {"type": "int"}, which is not valid JSON Schema. Map annotations through _json_schema_for_hint(): str, int, float, bool and None map to string, integer, number, boolean and null; list, tuple, set and dict map to array and object with items; Optional and unions map to anyOf; Enum and Literal map to enum; pydantic models keep their own schema. Anything else maps to {} (any value) so the schema stays valid. *args and **kwargs are no longer listed as properties. Fixes #362 Co-Authored-By: Claude Opus 5.5 Signed-off-by: CS --- sdk/python/src/b2a_sdk/decorators.py | 80 +++++++++++++++-- sdk/python/tests/test_mcp_tool_schema.py | 110 +++++++++++++++++++++++ 2 files changed, 182 insertions(+), 8 deletions(-) create mode 100644 sdk/python/tests/test_mcp_tool_schema.py diff --git a/sdk/python/src/b2a_sdk/decorators.py b/sdk/python/src/b2a_sdk/decorators.py index 338468f0b..1123966d7 100644 --- a/sdk/python/src/b2a_sdk/decorators.py +++ b/sdk/python/src/b2a_sdk/decorators.py @@ -13,12 +13,24 @@ import asyncio import contextvars +import enum import functools import inspect import time import traceback -from collections.abc import Awaitable, Callable, Coroutine -from typing import Any, ParamSpec, TypeVar, cast, get_type_hints +import types +from collections.abc import Awaitable, Callable, Coroutine, Mapping, Sequence +from typing import ( + Any, + Literal, + ParamSpec, + TypeVar, + Union, + cast, + get_args, + get_origin, + get_type_hints, +) from .client import B2AClient, DryRunSimulation @@ -89,6 +101,60 @@ def _notify_registration( pass +_JSON_SCHEMA_SCALARS: dict[Any, str] = { + str: "string", + int: "integer", + float: "number", + bool: "boolean", + bytes: "string", + type(None): "null", +} + + +def _json_schema_for_hint(hint: Any) -> dict[str, Any]: + """Map a Python type annotation to a JSON Schema fragment. + + Unknown annotations map to ``{}`` (any value) so the emitted schema stays + valid JSON Schema instead of carrying a Python type name. + """ + if hint is Any or hint is object: + return {} + if hint in _JSON_SCHEMA_SCALARS: + return {"type": _JSON_SCHEMA_SCALARS[hint]} + if hasattr(hint, "model_json_schema"): + return cast(dict[str, Any], hint.model_json_schema()) + if isinstance(hint, type) and issubclass(hint, enum.Enum): + return {"enum": [member.value for member in hint]} + + origin = get_origin(hint) + args = get_args(hint) + if origin is Literal: + return {"enum": list(args)} + if origin is Union or origin is types.UnionType: + options = [_json_schema_for_hint(arg) for arg in args] + if any(option == {} for option in options): + return {} + return {"anyOf": options} + if hint in (list, tuple, set, frozenset) or ( + isinstance(origin, type) and issubclass(origin, (list, tuple, set, frozenset, Sequence)) + ): + schema: dict[str, Any] = {"type": "array"} + if origin is tuple and args and args[-1] is not Ellipsis: + schema["prefixItems"] = [_json_schema_for_hint(arg) for arg in args] + schema["minItems"] = schema["maxItems"] = len(args) + elif args: + schema["items"] = _json_schema_for_hint(args[0]) + return schema + if hint is dict or (isinstance(origin, type) and issubclass(origin, Mapping)): + schema = {"type": "object"} + if len(args) == 2: + schema["additionalProperties"] = _json_schema_for_hint(args[1]) + return schema + if hasattr(hint, "schema") and callable(hint.schema): + return cast(dict[str, Any], hint.schema()) + return {} + + def _extract_schema_from_func(func: Callable) -> tuple[dict | None, dict | None]: """Extract input/output schemas from a function signature.""" try: @@ -102,16 +168,14 @@ def _extract_schema_from_func(func: Callable) -> tuple[dict | None, dict | None] if param_name in ("self", "cls"): continue + if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD): + continue + hint = hints.get(param_name) if hint is None: properties[param_name] = {"type": "string"} - elif hasattr(hint, "model_json_schema"): - properties[param_name] = hint.model_json_schema() - elif hasattr(hint, "schema"): - properties[param_name] = hint.schema() else: - type_str = getattr(hint, "__name__", str(hint)) - properties[param_name] = {"type": type_str} + properties[param_name] = _json_schema_for_hint(hint) if param.default is inspect.Parameter.empty: required.append(param_name) diff --git a/sdk/python/tests/test_mcp_tool_schema.py b/sdk/python/tests/test_mcp_tool_schema.py new file mode 100644 index 000000000..2b1c0d1ef --- /dev/null +++ b/sdk/python/tests/test_mcp_tool_schema.py @@ -0,0 +1,110 @@ +"""@mcp_tool registers JSON Schema types, not Python type names (issue #362).""" + +from __future__ import annotations + +import enum +from typing import Any, Literal, Optional + +import pytest + +from b2a_sdk import decorators +from b2a_sdk.decorators import mcp_tool + +JSON_SCHEMA_TYPES = {"string", "integer", "number", "boolean", "object", "array", "null"} + + +def _all_type_values(schema: Any) -> list[Any]: + found: list[Any] = [] + if isinstance(schema, dict): + if "type" in schema: + found.append(schema["type"]) + for value in schema.values(): + found.extend(_all_type_values(value)) + elif isinstance(schema, list): + for item in schema: + found.extend(_all_type_values(item)) + return found + + +@pytest.fixture +def registrations(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]: + captured: list[dict[str, Any]] = [] + monkeypatch.setattr(decorators, "_registration_callbacks", []) + + def record(service_id: str, func: Any, input_schema: Any, output_schema: Any) -> None: + captured.append({"service_id": service_id, "input_schema": input_schema}) + + decorators.register_mcp_tool_callback(record) + return captured + + +def test_example_tool_schema_uses_json_schema_types( + registrations: list[dict[str, Any]], +) -> None: + @mcp_tool(service_id="text-analyzer") + async def analyze_text(text: str, operation: str = "summarize", max_length: int = 100) -> dict: + return {} + + schema = registrations[0]["input_schema"] + assert schema == { + "type": "object", + "properties": { + "text": {"type": "string"}, + "operation": {"type": "string"}, + "max_length": {"type": "integer"}, + }, + "required": ["text"], + } + + +class Mode(enum.Enum): + FAST = "fast" + SLOW = "slow" + + +def test_common_annotations_map_to_valid_json_schema( + registrations: list[dict[str, Any]], +) -> None: + @mcp_tool(service_id="many-types") + async def tool( + ratio: float, + enabled: bool, + tags: list[str], + pair: tuple[int, str], + counts: dict[str, int], + note: Optional[str] = None, # noqa: UP045 - the typing form is what users write + limit: int | None = None, + mode: Mode = Mode.FAST, + level: Literal["low", "high"] = "low", + extra: Any = None, + *args: Any, + **kwargs: Any, + ) -> dict: + return {} + + props = registrations[0]["input_schema"]["properties"] + assert props["ratio"] == {"type": "number"} + assert props["enabled"] == {"type": "boolean"} + assert props["tags"] == {"type": "array", "items": {"type": "string"}} + assert props["pair"] == { + "type": "array", + "prefixItems": [{"type": "integer"}, {"type": "string"}], + "minItems": 2, + "maxItems": 2, + } + assert props["counts"] == {"type": "object", "additionalProperties": {"type": "integer"}} + assert props["note"] == {"anyOf": [{"type": "string"}, {"type": "null"}]} + assert props["limit"] == {"anyOf": [{"type": "integer"}, {"type": "null"}]} + assert props["mode"] == {"enum": ["fast", "slow"]} + assert props["level"] == {"enum": ["low", "high"]} + assert props["extra"] == {} + assert "args" not in props and "kwargs" not in props + assert set(_all_type_values(props)) <= JSON_SCHEMA_TYPES + + +def test_unannotated_parameter_stays_string(registrations: list[dict[str, Any]]) -> None: + @mcp_tool(service_id="untyped") + async def tool(value): # type: ignore[no-untyped-def] + return value + + assert registrations[0]["input_schema"]["properties"] == {"value": {"type": "string"}} From 6669956c810abcdf2a9c5412be4bdab86bea0874 Mon Sep 17 00:00:00 2001 From: CS Date: Wed, 11 Nov 2026 21:29:06 -0800 Subject: [PATCH 2/4] fix(sdk): @mcp_tool writes Literal enum members as their values (#362) Literal[Mode.FAST] put the enum member itself into the schema's enum list, so the registered inputSchema could not be serialized to JSON. Literal and Enum annotations now share one helper that uses each member's value and falls back to {} (any value) when a value still cannot be written as JSON, such as bytes. Co-Authored-By: Claude Fable 5.2 Signed-off-by: CS --- sdk/python/src/b2a_sdk/decorators.py | 20 ++++++++++++-- sdk/python/tests/test_mcp_tool_schema.py | 33 ++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/sdk/python/src/b2a_sdk/decorators.py b/sdk/python/src/b2a_sdk/decorators.py index 1123966d7..767c8adbb 100644 --- a/sdk/python/src/b2a_sdk/decorators.py +++ b/sdk/python/src/b2a_sdk/decorators.py @@ -16,6 +16,7 @@ import enum import functools import inspect +import json import time import traceback import types @@ -111,6 +112,21 @@ def _notify_registration( } +def _json_schema_enum(values: Any) -> dict[str, Any]: + """Build an ``enum`` fragment from literal values or enum members. + + Enum members contribute their ``.value``. If any value still cannot be + written as JSON, the fragment is ``{}`` (any value) so the schema stays + serializable. + """ + choices = [value.value if isinstance(value, enum.Enum) else value for value in values] + try: + json.dumps(choices) + except (TypeError, ValueError): + return {} + return {"enum": choices} + + def _json_schema_for_hint(hint: Any) -> dict[str, Any]: """Map a Python type annotation to a JSON Schema fragment. @@ -124,12 +140,12 @@ def _json_schema_for_hint(hint: Any) -> dict[str, Any]: if hasattr(hint, "model_json_schema"): return cast(dict[str, Any], hint.model_json_schema()) if isinstance(hint, type) and issubclass(hint, enum.Enum): - return {"enum": [member.value for member in hint]} + return _json_schema_enum(hint) origin = get_origin(hint) args = get_args(hint) if origin is Literal: - return {"enum": list(args)} + return _json_schema_enum(args) if origin is Union or origin is types.UnionType: options = [_json_schema_for_hint(arg) for arg in args] if any(option == {} for option in options): diff --git a/sdk/python/tests/test_mcp_tool_schema.py b/sdk/python/tests/test_mcp_tool_schema.py index 2b1c0d1ef..bf5dd2214 100644 --- a/sdk/python/tests/test_mcp_tool_schema.py +++ b/sdk/python/tests/test_mcp_tool_schema.py @@ -3,6 +3,7 @@ from __future__ import annotations import enum +import json from typing import Any, Literal, Optional import pytest @@ -108,3 +109,35 @@ async def tool(value): # type: ignore[no-untyped-def] return value assert registrations[0]["input_schema"]["properties"] == {"value": {"type": "string"}} + + +class Blob(enum.Enum): + RAW = b"raw" + + +def test_literal_enum_members_become_their_values( + registrations: list[dict[str, Any]], +) -> None: + @mcp_tool(service_id="literal-enum") + async def tool( + mode: Literal[Mode.FAST], + mixed: Literal[Mode.SLOW, "auto", 3, None] = "auto", + ) -> dict: + return {} + + schema = registrations[0]["input_schema"] + assert schema["properties"]["mode"] == {"enum": ["fast"]} + assert schema["properties"]["mixed"] == {"enum": ["slow", "auto", 3, None]} + assert json.loads(json.dumps(schema)) == schema + + +def test_values_json_cannot_hold_fall_back_to_any( + registrations: list[dict[str, Any]], +) -> None: + @mcp_tool(service_id="non-json-values") + async def tool(blob: Blob, raw: Literal[b"raw"], member: Literal[Blob.RAW]) -> dict: + return {} + + schema = registrations[0]["input_schema"] + assert schema["properties"] == {"blob": {}, "raw": {}, "member": {}} + assert json.loads(json.dumps(schema)) == schema From 3e8467a90a54d14b67c2e3b6ea221bad5fd6dae3 Mon Sep 17 00:00:00 2001 From: PetrefiedThunder <131207452+PetrefiedThunder@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:09:51 -0800 Subject: [PATCH 3/4] fix(sdk): @mcp_tool keeps nested model refs resolvable (#362) A model schema was inlined with its own $defs wherever the model sat in the tool's input schema, so refs such as #/$defs/Model, which resolve from the document root, pointed at nothing. Model definitions are now hoisted to the root of the input schema. Two different models that share a definition name get distinct names and their refs are rewritten. Co-Authored-By: Claude Fable 5.2 Signed-off-by: PetrefiedThunder <131207452+PetrefiedThunder@users.noreply.github.com> --- sdk/python/src/b2a_sdk/decorators.py | 83 +++++++++++++-- sdk/python/tests/test_mcp_tool_schema.py | 129 +++++++++++++++++++++++ 2 files changed, 204 insertions(+), 8 deletions(-) diff --git a/sdk/python/src/b2a_sdk/decorators.py b/sdk/python/src/b2a_sdk/decorators.py index 767c8adbb..065b30b1a 100644 --- a/sdk/python/src/b2a_sdk/decorators.py +++ b/sdk/python/src/b2a_sdk/decorators.py @@ -127,18 +127,82 @@ def _json_schema_enum(values: Any) -> dict[str, Any]: return {"enum": choices} -def _json_schema_for_hint(hint: Any) -> dict[str, Any]: +_DEFINITION_KEYWORDS = ("$defs", "definitions") + + +def _rewrite_refs(node: Any, renames: dict[str, str]) -> Any: + """Return ``node`` with every ``$ref`` in ``renames`` pointed at its new name.""" + if isinstance(node, dict): + return { + key: renames.get(value, value) + if key == "$ref" and isinstance(value, str) + else _rewrite_refs(value, renames) + for key, value in node.items() + } + if isinstance(node, list): + return [_rewrite_refs(item, renames) for item in node] + return node + + +def _hoist_definitions(schema: dict[str, Any], defs: dict[str, dict[str, Any]]) -> dict[str, Any]: + """Move a model schema's definitions into ``defs`` and return the rest. + + Pydantic writes ``$ref`` values such as ``#/$defs/Model`` that resolve from + the document root. The caller places ``defs`` at the root of the tool's + schema so those references still resolve when the model schema is nested. + Two different models that share a name get distinct names. + """ + found = { + keyword: schema[keyword] + for keyword in _DEFINITION_KEYWORDS + if isinstance(schema.get(keyword), dict) + } + if not found: + return schema + body = {key: value for key, value in schema.items() if key not in found} + + renames: dict[str, str] = {} + targets: dict[tuple[str, str], str] = {} + for keyword, definitions in found.items(): + taken = set(defs.get(keyword, {})) | set(definitions) + for name, definition in definitions.items(): + target = name + if defs.get(keyword, {}).get(name, definition) != definition: + suffix = 2 + while f"{name}_{suffix}" in taken: + suffix += 1 + target = f"{name}_{suffix}" + taken.add(target) + renames[f"#/{keyword}/{name}"] = f"#/{keyword}/{target}" + targets[keyword, name] = target + + for keyword, definitions in found.items(): + for name, definition in definitions.items(): + defs.setdefault(keyword, {})[targets[keyword, name]] = _rewrite_refs( + definition, renames + ) + return cast(dict[str, Any], _rewrite_refs(body, renames)) + + +def _json_schema_for_hint( + hint: Any, defs: dict[str, dict[str, Any]] | None = None +) -> dict[str, Any]: """Map a Python type annotation to a JSON Schema fragment. Unknown annotations map to ``{}`` (any value) so the emitted schema stays valid JSON Schema instead of carrying a Python type name. + + Model definitions are collected into ``defs`` (keyed by ``$defs`` or + ``definitions``) for the caller to place at the root of the schema. """ + if defs is None: + defs = {} if hint is Any or hint is object: return {} if hint in _JSON_SCHEMA_SCALARS: return {"type": _JSON_SCHEMA_SCALARS[hint]} if hasattr(hint, "model_json_schema"): - return cast(dict[str, Any], hint.model_json_schema()) + return _hoist_definitions(cast(dict[str, Any], hint.model_json_schema()), defs) if isinstance(hint, type) and issubclass(hint, enum.Enum): return _json_schema_enum(hint) @@ -147,7 +211,7 @@ def _json_schema_for_hint(hint: Any) -> dict[str, Any]: if origin is Literal: return _json_schema_enum(args) if origin is Union or origin is types.UnionType: - options = [_json_schema_for_hint(arg) for arg in args] + options = [_json_schema_for_hint(arg, defs) for arg in args] if any(option == {} for option in options): return {} return {"anyOf": options} @@ -156,18 +220,18 @@ def _json_schema_for_hint(hint: Any) -> dict[str, Any]: ): schema: dict[str, Any] = {"type": "array"} if origin is tuple and args and args[-1] is not Ellipsis: - schema["prefixItems"] = [_json_schema_for_hint(arg) for arg in args] + schema["prefixItems"] = [_json_schema_for_hint(arg, defs) for arg in args] schema["minItems"] = schema["maxItems"] = len(args) elif args: - schema["items"] = _json_schema_for_hint(args[0]) + schema["items"] = _json_schema_for_hint(args[0], defs) return schema if hint is dict or (isinstance(origin, type) and issubclass(origin, Mapping)): schema = {"type": "object"} if len(args) == 2: - schema["additionalProperties"] = _json_schema_for_hint(args[1]) + schema["additionalProperties"] = _json_schema_for_hint(args[1], defs) return schema if hasattr(hint, "schema") and callable(hint.schema): - return cast(dict[str, Any], hint.schema()) + return _hoist_definitions(cast(dict[str, Any], hint.schema()), defs) return {} @@ -179,6 +243,7 @@ def _extract_schema_from_func(func: Callable) -> tuple[dict | None, dict | None] properties = {} required = [] + defs: dict[str, dict[str, Any]] = {} for param_name, param in sig.parameters.items(): if param_name in ("self", "cls"): @@ -191,7 +256,7 @@ def _extract_schema_from_func(func: Callable) -> tuple[dict | None, dict | None] if hint is None: properties[param_name] = {"type": "string"} else: - properties[param_name] = _json_schema_for_hint(hint) + properties[param_name] = _json_schema_for_hint(hint, defs) if param.default is inspect.Parameter.empty: required.append(param_name) @@ -205,6 +270,8 @@ def _extract_schema_from_func(func: Callable) -> tuple[dict | None, dict | None] if properties else None ) + if input_schema is not None: + input_schema.update(defs) return_type = hints.get("return") output_schema = None diff --git a/sdk/python/tests/test_mcp_tool_schema.py b/sdk/python/tests/test_mcp_tool_schema.py index bf5dd2214..01227016e 100644 --- a/sdk/python/tests/test_mcp_tool_schema.py +++ b/sdk/python/tests/test_mcp_tool_schema.py @@ -8,6 +8,11 @@ import pytest +try: + import pydantic +except ImportError: # the SDK does not depend on pydantic + pydantic = None # type: ignore[assignment] + from b2a_sdk import decorators from b2a_sdk.decorators import mcp_tool @@ -141,3 +146,127 @@ async def tool(blob: Blob, raw: Literal[b"raw"], member: Literal[Blob.RAW]) -> d schema = registrations[0]["input_schema"] assert schema["properties"] == {"blob": {}, "raw": {}, "member": {}} assert json.loads(json.dumps(schema)) == schema + + +def _resolve(schema: dict[str, Any], ref: str) -> Any: + assert ref.startswith("#/") + node: Any = schema + for part in ref[2:].split("/"): + node = node[part] + return node + + +def _all_refs(node: Any) -> list[str]: + found: list[str] = [] + if isinstance(node, dict): + for key, value in node.items(): + if key == "$ref" and isinstance(value, str): + found.append(value) + else: + found.extend(_all_refs(value)) + elif isinstance(node, list): + for item in node: + found.extend(_all_refs(item)) + return found + + +class _ItemHolder: + """Stands in for a model class: exposes the schema hook @mcp_tool reads.""" + + value_type = "integer" + + @classmethod + def model_json_schema(cls) -> dict[str, Any]: + return { + "$defs": { + "Item": { + "type": "object", + "properties": {"value": {"type": cls.value_type}}, + "required": ["value"], + } + }, + "type": "object", + "properties": {"item": {"$ref": "#/$defs/Item"}}, + "required": ["item"], + } + + +class _TextItemHolder(_ItemHolder): + value_type = "string" + + +def test_nested_model_refs_resolve_from_the_schema_root( + registrations: list[dict[str, Any]], +) -> None: + @mcp_tool(service_id="nested-models") + async def tool( + owner: _ItemHolder, + backup: _ItemHolder | None = None, + team: list[_ItemHolder] = [], # noqa: B006 - the default is never mutated + pair: tuple[_ItemHolder, int] | None = None, + by_name: dict[str, _ItemHolder] = {}, # noqa: B006 - the default is never mutated + ) -> dict: + return {} + + schema = registrations[0]["input_schema"] + item = _ItemHolder.model_json_schema()["$defs"]["Item"] + assert schema["$defs"] == {"Item": item} + refs = _all_refs(schema) + assert refs == ["#/$defs/Item"] * 5 + assert all(_resolve(schema, ref) == item for ref in refs) + + props = schema["properties"] + assert '"$defs":' not in json.dumps(props) + holder = { + key: value for key, value in _ItemHolder.model_json_schema().items() if key != "$defs" + } + assert props["owner"] == holder + assert props["backup"] == {"anyOf": [holder, {"type": "null"}]} + assert props["team"] == {"type": "array", "items": holder} + assert props["pair"]["anyOf"][0]["prefixItems"] == [holder, {"type": "integer"}] + assert props["by_name"] == {"type": "object", "additionalProperties": holder} + assert json.loads(json.dumps(schema)) == schema + + +def test_same_named_definitions_from_different_models_stay_distinct( + registrations: list[dict[str, Any]], +) -> None: + @mcp_tool(service_id="name-clash") + async def tool(a: _ItemHolder, b: list[_TextItemHolder], c: _ItemHolder | None = None) -> dict: + return {} + + schema = registrations[0]["input_schema"] + assert set(schema["$defs"]) == {"Item", "Item_2"} + props = schema["properties"] + a_ref = props["a"]["properties"]["item"]["$ref"] + b_ref = props["b"]["items"]["properties"]["item"]["$ref"] + c_ref = props["c"]["anyOf"][0]["properties"]["item"]["$ref"] + assert _resolve(schema, a_ref)["properties"]["value"] == {"type": "integer"} + assert _resolve(schema, b_ref)["properties"]["value"] == {"type": "string"} + assert c_ref == a_ref + + +if pydantic is not None: + + class Address(pydantic.BaseModel): + city: str + + class Person(pydantic.BaseModel): + name: str + address: Address + + +@pytest.mark.skipif(pydantic is None, reason="pydantic is not installed") +def test_pydantic_nested_model_refs_resolve(registrations: list[dict[str, Any]]) -> None: + @mcp_tool(service_id="pydantic-nested") + async def tool(owner: Person, team: list[Person], backup: Person | None = None) -> dict: + return {} + + schema = registrations[0]["input_schema"] + assert set(schema["$defs"]) == {"Address"} + refs = _all_refs(schema) + assert refs == ["#/$defs/Address"] * 3 + for ref in refs: + assert _resolve(schema, ref)["properties"]["city"]["type"] == "string" + assert '"$defs":' not in json.dumps(schema["properties"]) + assert schema["required"] == ["owner", "team"] From 488a911e928927022fb289300d4e9c517d300f19 Mon Sep 17 00:00:00 2001 From: PetrefiedThunder <131207452+PetrefiedThunder@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:18:43 -0800 Subject: [PATCH 4/4] fix(sdk): @mcp_tool keeps each model's definition graph intact (#362) Merging model definitions compared each definition on its own, so a definition that only pointed at a conflicting one was shared and then overwritten, and an earlier parameter resolved to the later model's types. Names are now settled across the whole incoming graph before anything is stored, and stored definitions are never rewritten. Enum and Literal values that strict JSON rejects, such as infinity, now fall back to {} like bytes do. The nested Pydantic test skips on Pydantic 1. Co-Authored-By: Claude Fable 5.2 Signed-off-by: PetrefiedThunder <131207452+PetrefiedThunder@users.noreply.github.com> --- sdk/python/src/b2a_sdk/decorators.py | 65 ++++++++++++-------- sdk/python/tests/test_mcp_tool_schema.py | 75 +++++++++++++++++++++++- 2 files changed, 114 insertions(+), 26 deletions(-) diff --git a/sdk/python/src/b2a_sdk/decorators.py b/sdk/python/src/b2a_sdk/decorators.py index 065b30b1a..6261e3053 100644 --- a/sdk/python/src/b2a_sdk/decorators.py +++ b/sdk/python/src/b2a_sdk/decorators.py @@ -116,12 +116,12 @@ def _json_schema_enum(values: Any) -> dict[str, Any]: """Build an ``enum`` fragment from literal values or enum members. Enum members contribute their ``.value``. If any value still cannot be - written as JSON, the fragment is ``{}`` (any value) so the schema stays - serializable. + written as strict JSON (bytes, or a non-finite number), the fragment is + ``{}`` (any value) so the schema stays serializable. """ choices = [value.value if isinstance(value, enum.Enum) else value for value in values] try: - json.dumps(choices) + json.dumps(choices, allow_nan=False) except (TypeError, ValueError): return {} return {"enum": choices} @@ -161,26 +161,45 @@ def _hoist_definitions(schema: dict[str, Any], defs: dict[str, dict[str, Any]]) return schema body = {key: value for key, value in schema.items() if key not in found} - renames: dict[str, str] = {} - targets: dict[tuple[str, str], str] = {} - for keyword, definitions in found.items(): - taken = set(defs.get(keyword, {})) | set(definitions) - for name, definition in definitions.items(): - target = name - if defs.get(keyword, {}).get(name, definition) != definition: - suffix = 2 - while f"{name}_{suffix}" in taken: - suffix += 1 - target = f"{name}_{suffix}" - taken.add(target) - renames[f"#/{keyword}/{name}"] = f"#/{keyword}/{target}" - targets[keyword, name] = target - - for keyword, definitions in found.items(): - for name, definition in definitions.items(): - defs.setdefault(keyword, {})[targets[keyword, name]] = _rewrite_refs( - definition, renames - ) + # Pick a root name for every incoming definition. A name is shared with a + # stored definition only when the two are equal after the incoming refs + # are rewritten, so a definition that merely points at a conflicting one + # is renamed too and the stored graph is never changed. + incoming = [(keyword, name) for keyword, names in found.items() for name in names] + targets = {(keyword, name): name for keyword, name in incoming} + suffixes = dict.fromkeys(incoming, 1) + while True: + renames = { + f"#/{keyword}/{name}": f"#/{keyword}/{target}" + for (keyword, name), target in targets.items() + if target != name + } + rewritten = { + (keyword, name): _rewrite_refs(found[keyword][name], renames) + for keyword, name in incoming + } + settled = True + for keyword, name in incoming: + stored = defs.get(keyword, {}).get(targets[keyword, name]) + if stored is None or stored == rewritten[keyword, name]: + continue + settled = False + others = { + target + for (other_keyword, other), target in targets.items() + if other_keyword == keyword and other != name + } | (set(found[keyword]) - {name}) + while True: + suffixes[keyword, name] += 1 + candidate = f"{name}_{suffixes[keyword, name]}" + if candidate not in others: + break + targets[keyword, name] = candidate + if settled: + break + + for keyword, name in incoming: + defs.setdefault(keyword, {})[targets[keyword, name]] = rewritten[keyword, name] return cast(dict[str, Any], _rewrite_refs(body, renames)) diff --git a/sdk/python/tests/test_mcp_tool_schema.py b/sdk/python/tests/test_mcp_tool_schema.py index 01227016e..84732fbbe 100644 --- a/sdk/python/tests/test_mcp_tool_schema.py +++ b/sdk/python/tests/test_mcp_tool_schema.py @@ -4,7 +4,7 @@ import enum import json -from typing import Any, Literal, Optional +from typing import Any, Literal, Optional, cast import pytest @@ -246,7 +246,7 @@ async def tool(a: _ItemHolder, b: list[_TextItemHolder], c: _ItemHolder | None = assert c_ref == a_ref -if pydantic is not None: +if pydantic is not None and int(pydantic.VERSION.split(".")[0]) >= 2: class Address(pydantic.BaseModel): city: str @@ -256,7 +256,10 @@ class Person(pydantic.BaseModel): address: Address -@pytest.mark.skipif(pydantic is None, reason="pydantic is not installed") +@pytest.mark.skipif( + pydantic is None or int(pydantic.VERSION.split(".")[0]) < 2, + reason="needs pydantic 2 or newer", +) def test_pydantic_nested_model_refs_resolve(registrations: list[dict[str, Any]]) -> None: @mcp_tool(service_id="pydantic-nested") async def tool(owner: Person, team: list[Person], backup: Person | None = None) -> dict: @@ -270,3 +273,69 @@ async def tool(owner: Person, team: list[Person], backup: Person | None = None) assert _resolve(schema, ref)["properties"]["city"]["type"] == "string" assert '"$defs":' not in json.dumps(schema["properties"]) assert schema["required"] == ["owner", "team"] + + +class _BoxHolder: + """Two levels of definitions: the tool refs Box, and Box refs Item.""" + + value_type = "integer" + + @classmethod + def model_json_schema(cls) -> dict[str, Any]: + return { + "$defs": { + "Box": {"type": "object", "properties": {"item": {"$ref": "#/$defs/Item"}}}, + "Item": {"type": "object", "properties": {"value": {"type": cls.value_type}}}, + }, + "type": "object", + "properties": {"box": {"$ref": "#/$defs/Box"}}, + } + + +class _TextBoxHolder(_BoxHolder): + value_type = "string" + + +def _item_value_type(schema: dict[str, Any], holder: dict[str, Any]) -> str: + box = _resolve(schema, holder["properties"]["box"]["$ref"]) + item = _resolve(schema, box["properties"]["item"]["$ref"]) + return cast(str, item["properties"]["value"]["type"]) + + +def test_equal_definitions_that_ref_conflicting_ones_are_not_merged( + registrations: list[dict[str, Any]], +) -> None: + @mcp_tool(service_id="graph-clash") + async def tool( + a: _BoxHolder, + b: _TextBoxHolder, + c: list[_BoxHolder], + d: _TextBoxHolder | None = None, + ) -> dict: + return {} + + schema = registrations[0]["input_schema"] + props = schema["properties"] + assert _item_value_type(schema, props["a"]) == "integer" + assert _item_value_type(schema, props["b"]) == "string" + assert _item_value_type(schema, props["c"]["items"]) == "integer" + assert _item_value_type(schema, props["d"]["anyOf"][0]) == "string" + assert set(schema["$defs"]) == {"Box", "Item", "Box_2", "Item_2"} + assert props["c"]["items"] == props["a"] + assert props["d"]["anyOf"][0] == props["b"] + + +class Ratio(enum.Enum): + UNBOUNDED = float("inf") + + +def test_non_finite_enum_values_fall_back_to_any( + registrations: list[dict[str, Any]], +) -> None: + @mcp_tool(service_id="non-finite") + async def tool(ratio: Ratio, limit: Literal[Ratio.UNBOUNDED]) -> dict: + return {} + + schema = registrations[0]["input_schema"] + assert schema["properties"] == {"ratio": {}, "limit": {}} + assert json.loads(json.dumps(schema, allow_nan=False)) == schema