Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(json-schema): enforce dynamic object contracts

jkomyno4a89ff112c10
diff --git a/.changeset/preserve-root-dynamic-key-constraints.md b/.changeset/preserve-root-dynamic-key-constraints.md
index 234369af4..083cd81c9 100644
--- a/.changeset/preserve-root-dynamic-key-constraints.md
+++ b/.changeset/preserve-root-dynamic-key-constraints.md
@@ -2,9 +2,9 @@
'@composio/core': minor
---
-Keep root `patternProperties` and `additionalProperties` when parsing a tool schema.
+Keep free-form object roots, `patternProperties`, and `additionalProperties` when parsing a tool schema.
-`ToolSchema.parse` used to drop root `patternProperties` as an unknown key, and it rejected a root `additionalProperties` written as a schema instead of a boolean. Both constraints were lost before any converter or provider could read them. They now survive parsing exactly as written.
+`ToolSchema.parse` used to reject a bare `{ "type": "object" }` root, drop root `patternProperties` as an unknown key, and reject a root `additionalProperties` written as a schema instead of a boolean. Free-form roots now parse successfully, and both constraints survive parsing exactly as written. The public `ToolSchema` type now makes `properties` optional to reflect those valid property-less object schemas.
This matters downstream. Every provider reads `inputParameters` after parsing, so a tool that declares dynamic keys had those rules stripped before the model ever saw them.
diff --git a/python/composio/utils/schema_converter.py b/python/composio/utils/schema_converter.py
index 2f249f855..8e343007a 100644
--- a/python/composio/utils/schema_converter.py
+++ b/python/composio/utils/schema_converter.py
@@ -12,20 +12,27 @@ We handle those by pre-filtering them before passing to the library.
import re
import typing as t
from functools import reduce
+from urllib.parse import unquote
from json_schema_to_pydantic import (
CombinerError,
SchemaError,
+)
+from json_schema_to_pydantic import (
create_model as create_model_from_schema,
)
+from jsonschema import validators as jsonschema_validators
+from jsonschema.protocols import Validator
from pydantic import (
BaseModel,
ConfigDict,
Field,
TypeAdapter,
- create_model as create_pydantic_model,
model_validator,
)
+from pydantic import (
+ create_model as create_pydantic_model,
+)
from pydantic_core import core_schema
from composio.utils.logging import get as get_logger
@@ -231,41 +238,30 @@ def _contains_unsatisfiable_schema(schema: t.Any) -> bool:
return False
-_PRIMITIVE_TYPES = frozenset({"string", "number", "integer", "boolean", "null"})
-
-# JSON Schema keyword -> Pydantic `Field` constraint, by instance type. Simple
-# primitives lose their constraints in `PYDANTIC_TYPE_TO_PYTHON_TYPE`, which is
-# fine for declared fields the library models but not for dynamic keys, where
-# this module is the only validator.
-_CONSTRAINTS: t.Dict[str, t.Dict[str, str]] = {
- "string": {
- "minLength": "min_length",
- "maxLength": "max_length",
- "pattern": "pattern",
- },
- "array": {"minItems": "min_length", "maxItems": "max_length"},
-}
-_NUMERIC_CONSTRAINTS = {
- "minimum": "ge",
- "maximum": "le",
- "exclusiveMinimum": "gt",
- "exclusiveMaximum": "lt",
- "multipleOf": "multiple_of",
-}
-_CONSTRAINTS["number"] = _NUMERIC_CONSTRAINTS
-_CONSTRAINTS["integer"] = _NUMERIC_CONSTRAINTS
-
-
class _DynamicKeyValidator(t.NamedTuple):
- """Validator for one dynamic-key schema, plus how strictly to apply it."""
+ """Exact JSON Schema validation with optional default materialization."""
- adapter: TypeAdapter
- strict: bool
+ validator: Validator
+ materializer: t.Optional[TypeAdapter]
- def coerce(self, value: t.Any) -> t.Any:
- return self.adapter.dump_python(
- self.adapter.validate_python(value, strict=self.strict)
- )
+ def validate(self, value: t.Any) -> None:
+ error = next(self.validator.iter_errors(value), None)
+ if error is not None:
+ raise ValueError(error.message)
+
+ def materialize(self, value: t.Any) -> t.Any:
+ if self.materializer is None:
+ return value
+ try:
+ return self.materializer.dump_python(
+ self.materializer.validate_python(value)
+ )
+ except (TypeError, ValueError):
+ # JSON Schema alone decides acceptance. Pydantic is only retained
+ # for the existing default-materialization behavior, and an
+ # incomplete Pydantic representation must not reject valid input.
+ logger.debug("Could not materialize dynamic-key defaults; preserving input")
+ return value
class _ObjectPolicy(t.NamedTuple):
@@ -277,7 +273,7 @@ class _ObjectPolicy(t.NamedTuple):
"""
declared: t.FrozenSet[str]
- patterns: t.Tuple[t.Tuple[t.Pattern[str], t.Optional[_DynamicKeyValidator]], ...]
+ patterns: t.Tuple[t.Tuple[t.Pattern[str], _DynamicKeyValidator], ...]
additional: t.Optional[_DynamicKeyValidator]
rejects_unmatched: bool
@@ -300,50 +296,128 @@ def object_is_open(schema: t.Dict[str, t.Any]) -> bool:
return not (schema.get("properties") or {}) and additional in (_MISSING, True)
-def _dynamic_key_validator(schema: t.Any) -> t.Optional[_DynamicKeyValidator]:
- """Build the validator for one dynamic-key schema, or ``None`` if unmodellable."""
- try:
- annotation: t.Any = json_schema_to_pydantic_type(schema)
- strict = False
-
- if isinstance(schema, dict):
- schema_type = schema.get("type") or ""
- constraints = {
- field: schema[keyword]
- for keyword, field in _CONSTRAINTS.get(schema_type, {}).items()
- if keyword in schema
- }
- if constraints:
- annotation = t.Annotated[annotation, Field(**constraints)]
- # Primitives validate strictly so Pydantic's lax coercion cannot
- # admit a value the TypeScript converters reject (`true` as a
- # number, `1` as a boolean).
- strict = schema_type in _PRIMITIVE_TYPES
-
- return _DynamicKeyValidator(TypeAdapter(annotation), strict)
- except Exception as exc: # pragma: no cover - defensive
- logger.debug(f"Could not build a dynamic-key validator for {schema!r}: {exc}")
- return None
+def _contains_default(schema: t.Any) -> bool:
+ """Whether Pydantic must run after validation to materialize a default."""
+ if isinstance(schema, list):
+ return any(_contains_default(item) for item in schema)
+ if not isinstance(schema, dict):
+ return False
+ return "default" in schema or any(
+ _contains_default(value) for value in schema.values()
+ )
+
+
+def _resolve_local_json_pointer(
+ reference: str,
+ root_schema: t.Dict[str, t.Any],
+) -> t.Any:
+ """Resolve a local JSON Pointer or fail while the model is constructed."""
+ if reference == "#":
+ return root_schema
+ if not reference.startswith("#/"):
+ raise ValueError(
+ f"Dynamic-key schema reference {reference!r} must be a local JSON Pointer"
+ )
+
+ current: t.Any = root_schema
+ for raw_token in unquote(reference[2:]).split("/"):
+ token = raw_token.replace("~1", "/").replace("~0", "~")
+ if isinstance(current, dict) and token in current:
+ current = current[token]
+ continue
+ if isinstance(current, list):
+ try:
+ current = current[int(token)]
+ continue
+ except (ValueError, IndexError):
+ pass
+ raise ValueError(f"Unresolvable dynamic-key schema reference: {reference!r}")
+ return current
+
+
+def _check_dynamic_references(
+ schema: t.Any,
+ root_schema: t.Dict[str, t.Any],
+ checked_references: t.Optional[t.Set[str]] = None,
+) -> None:
+ """Reject external, anchored, and unresolved references before validation."""
+ if checked_references is None:
+ checked_references = set()
+ if isinstance(schema, list):
+ for item in schema:
+ _check_dynamic_references(item, root_schema, checked_references)
+ return
+ if not isinstance(schema, dict):
+ return
+
+ reference = schema.get("$ref")
+ if reference is not None:
+ if not isinstance(reference, str):
+ raise ValueError("Dynamic-key schema `$ref` must be a string")
+ resolved = _resolve_local_json_pointer(reference, root_schema)
+ if not isinstance(resolved, (dict, bool)):
+ raise ValueError(
+ f"Dynamic-key schema reference {reference!r} does not target a schema"
+ )
+ if reference not in checked_references:
+ checked_references.add(reference)
+ _check_dynamic_references(resolved, root_schema, checked_references)
+
+ for value in schema.values():
+ _check_dynamic_references(value, root_schema, checked_references)
+
+
+def _dynamic_key_validator(
+ schema: t.Any,
+ root_schema: t.Dict[str, t.Any],
+ root_validator: Validator,
+) -> _DynamicKeyValidator:
+ """Compile a complete inline JSON subschema without coercive acceptance."""
+ validator_type = type(root_validator)
+ validator_type.check_schema(schema)
+ _check_dynamic_references(schema, root_schema)
+
+ materializer = None
+ if _contains_default(schema):
+ annotation = json_schema_to_pydantic_type(schema)
+ materializer = TypeAdapter(annotation)
+
+ return _DynamicKeyValidator(
+ validator=root_validator.evolve(schema=schema),
+ materializer=materializer,
+ )
def _compile_object_policy(schema: t.Dict[str, t.Any]) -> _ObjectPolicy:
declared = frozenset(schema.get("properties") or {})
additional = schema.get("additionalProperties", _MISSING)
+ validator_type = jsonschema_validators.validator_for(
+ schema,
+ default=jsonschema_validators.Draft7Validator,
+ )
+ root_validator = validator_type(schema)
patterns = []
for pattern, pattern_schema in (schema.get("patternProperties") or {}).items():
try:
patterns.append(
- (re.compile(pattern), _dynamic_key_validator(pattern_schema))
+ (
+ re.compile(pattern),
+ _dynamic_key_validator(pattern_schema, schema, root_validator),
+ )
)
- except re.error:
- logger.debug(f"Skipping uncompilable patternProperties regex: {pattern!r}")
+ except re.error as exc:
+ raise ValueError(
+ f"Invalid patternProperties regular expression: {pattern!r}"
+ ) from exc
return _ObjectPolicy(
declared=declared,
patterns=tuple(patterns),
additional=(
- _dynamic_key_validator(additional) if isinstance(additional, dict) else None
+ _dynamic_key_validator(additional, schema, root_validator)
+ if isinstance(additional, dict)
+ else None
),
rejects_unmatched=additional is False
or (additional is _MISSING and bool(declared)),
@@ -356,42 +430,28 @@ class _DynamicObjectModel(BaseModel):
``extra="allow"`` is what makes preservation possible at all: Pydantic's
default silently discards accepted arguments, so a provider that re-reads
them (``LangchainProvider`` uses ``getattr``) would lose valid payloads.
- Coerced values are written back into ``__pydantic_extra__`` so they show up
- in ``model_dump()`` and remain readable as attributes.
+ Materialized defaults are written back into ``__pydantic_extra__`` so they
+ show up in ``model_dump()`` and remain readable as attributes.
"""
model_config = ConfigDict(extra="allow")
- @model_validator(mode="after")
- def _apply_object_policy(self):
+ @model_validator(mode="before")
+ @classmethod
+ def _validate_object_policy(cls, value: t.Any) -> t.Any:
policy: t.Optional[_ObjectPolicy] = getattr(
- type(self), "__composio_object_policy__", None
+ cls, "__composio_object_policy__", None
)
- if policy is None or policy.is_trivial:
- return self
-
- # A key declared in `properties` is still checked against every matching
- # pattern; its declared value is authoritative and is not overwritten.
- for name, field in type(self).model_fields.items():
- if name not in self.model_fields_set:
- continue
- key = field.alias or name
- for regex, validator in policy.patterns:
- if validator is not None and regex.search(key):
- validator.coerce(getattr(self, name))
-
- extra = self.__pydantic_extra__
- if not extra:
- return self
+ if policy is None or policy.is_trivial or not isinstance(value, dict):
+ return value
unrecognized = []
- for key, value in list(extra.items()):
+ for key, item in value.items():
matched = False
for regex, validator in policy.patterns:
if regex.search(key):
matched = True
- if validator is not None:
- extra[key] = validator.coerce(value)
+ validator.validate(item)
if matched or key in policy.declared:
continue
@@ -399,13 +459,40 @@ class _DynamicObjectModel(BaseModel):
if policy.rejects_unmatched:
unrecognized.append(key)
elif policy.additional is not None:
- extra[key] = policy.additional.coerce(value)
+ policy.additional.validate(item)
if unrecognized:
raise ValueError(
f"Unrecognized key(s) in object: {', '.join(repr(key) for key in unrecognized)}"
)
+ return value
+
+ @model_validator(mode="after")
+ def _materialize_dynamic_defaults(self):
+ policy: t.Optional[_ObjectPolicy] = getattr(
+ type(self), "__composio_object_policy__", None
+ )
+ if policy is None or policy.is_trivial:
+ return self
+
+ extra = self.__pydantic_extra__
+ if not extra:
+ return self
+
+ for key, value in list(extra.items()):
+ matched = False
+ for regex, validator in policy.patterns:
+ if regex.search(key):
+ matched = True
+ extra[key] = validator.materialize(extra[key])
+
+ if matched or key in policy.declared:
+ continue
+
+ if policy.additional is not None:
+ extra[key] = policy.additional.materialize(value)
+
return self
@@ -417,6 +504,13 @@ def apply_object_policy(
"""Wrap ``base_model`` with the covered dynamic-key policy for ``schema``."""
policy = _compile_object_policy(schema)
name = model_name or base_model.__name__
+ json_schema_extra: t.Dict[str, t.Any] = {}
+ if "patternProperties" in schema:
+ json_schema_extra["patternProperties"] = schema["patternProperties"]
+ if "additionalProperties" in schema:
+ json_schema_extra["additionalProperties"] = schema["additionalProperties"]
+ elif policy.rejects_unmatched:
+ json_schema_extra["additionalProperties"] = False
return t.cast(
t.Type[BaseModel],
@@ -426,7 +520,10 @@ def apply_object_policy(
{
"__module__": __name__,
"__qualname__": name,
- "model_config": ConfigDict(extra="allow"),
+ "model_config": ConfigDict(
+ extra="allow",
+ json_schema_extra=json_schema_extra,
+ ),
"__composio_object_policy__": policy,
},
),
diff --git a/python/noxfile.py b/python/noxfile.py
index 72c7e4d6e..eb71ccd1b 100644
--- a/python/noxfile.py
+++ b/python/noxfile.py
@@ -31,6 +31,7 @@ modules_for_ruff = [
type_stubs = [
"types-requests==2.33.0.20260712",
"types-protobuf==7.34.1.20260518",
+ "types-jsonschema==4.26.0.20260518",
"anthropic==0.120.0",
# Keep this aligned with the CrewAI provider dependency metadata.
"crewai==1.15.7",
diff --git a/python/pyproject.toml b/python/pyproject.toml
index 03594efe1..d491ad0a3 100644
--- a/python/pyproject.toml
+++ b/python/pyproject.toml
@@ -11,6 +11,7 @@ dependencies = [
"typing-extensions>=4.16.0",
"openai>=2.48.0",
"json-schema-to-pydantic>=0.4.11",
+ "jsonschema>=4.23.0",
]
classifiers = [
"Programming Language :: Python :: 3",
diff --git a/python/setup.py b/python/setup.py
index d2dd55781..72b88857a 100644
--- a/python/setup.py
+++ b/python/setup.py
@@ -29,6 +29,7 @@ setup(
"typing-extensions>=4.16.0",
"openai>=2.48.0",
"json-schema-to-pydantic>=0.4.11",
+ "jsonschema>=4.23.0",
],
include_package_data=True,
)
diff --git a/python/tests/fixtures/json-schema-conversion/object-cases.json b/python/tests/fixtures/json-schema-conversion/object-cases.json
index 82f06ecd7..c3a6b8ac1 100644
--- a/python/tests/fixtures/json-schema-conversion/object-cases.json
+++ b/python/tests/fixtures/json-schema-conversion/object-cases.json
@@ -34,6 +34,10 @@
"id": "root-free-form-absent-properties",
"description": "A root object with no `properties` member and omitted `additionalProperties` is open.",
"schema": { "type": "object" },
+ "ingress": {
+ "accepted": true,
+ "preserved": { "type": "object" }
+ },
"instances": [
{
"input": { "anything": { "a": 1 }, "other": "x" },
@@ -348,6 +352,169 @@
}
]
},
+ {
+ "id": "empty-schema-additional-properties",
+ "description": "An empty schema accepts every unmatched value without coercing or discarding it.",
+ "schema": {
+ "type": "object",
+ "properties": { "name": { "type": "string" } },
+ "additionalProperties": {}
+ },
+ "instances": [
+ {
+ "input": { "name": "a", "count": 1, "metadata": { "active": true } },
+ "accepted": true,
+ "zod": {
+ "output": { "name": "a", "count": 1, "metadata": { "active": true } }
+ },
+ "effect": {
+ "output": { "name": "a", "count": 1, "metadata": { "active": true } }
+ },
+ "python": {
+ "output": { "name": "a", "count": 1, "metadata": { "active": true } }
+ }
+ }
+ ]
+ },
+ {
+ "id": "pattern-property-enum",
+ "description": "A matching dynamic key must satisfy an enum-only schema with no explicit type.",
+ "schema": {
+ "type": "object",
+ "patternProperties": { "^status_": { "enum": ["ready", "done"] } }
+ },
+ "instances": [
+ {
+ "input": { "status_job": "ready" },
+ "accepted": true,
+ "zod": { "output": { "status_job": "ready" } },
+ "effect": { "output": { "status_job": "ready" } },
+ "python": { "output": { "status_job": "ready" } }
+ },
+ {
+ "input": { "status_job": "blocked" },
+ "accepted": false
+ }
+ ]
+ },
+ {
+ "id": "pattern-property-strict-nested-array",
+ "description": "Nested container values are validated without coercing strings into integers.",
+ "schema": {
+ "type": "object",
+ "patternProperties": {
+ "^batch_": {
+ "type": "object",
+ "properties": {
+ "values": { "type": "array", "items": { "type": "integer" } }
+ },
+ "required": ["values"],
+ "additionalProperties": false
+ }
+ }
+ },
+ "instances": [
+ {
+ "input": { "batch_a": { "values": [1, 2] } },
+ "accepted": true,
+ "zod": { "output": { "batch_a": { "values": [1, 2] } } },
+ "effect": { "output": { "batch_a": { "values": [1, 2] } } },
+ "python": { "output": { "batch_a": { "values": [1, 2] } } }
+ },
+ {
+ "input": { "batch_a": { "values": ["1"] } },
+ "accepted": false
+ }
+ ]
+ },
+ {
+ "id": "false-pattern-property-schema",
+ "description": "A boolean-false pattern schema rejects every value for matching keys.",
+ "schema": {
+ "type": "object",
+ "patternProperties": { "^forbidden$": false }
+ },
+ "instances": [
+ {
+ "input": { "other": 1 },
+ "accepted": true,
+ "zod": { "output": { "other": 1 } },
+ "effect": { "output": { "other": 1 } },
+ "python": { "output": { "other": 1 } }
+ },
+ {
+ "input": { "forbidden": null },
+ "accepted": false
+ }
+ ]
+ },
+ {
+ "id": "pattern-property-type-union",
+ "description": "A list-valued type accepts only the listed JSON instance types.",
+ "schema": {
+ "type": "object",
+ "patternProperties": { "^value_": { "type": ["string", "null"] } }
+ },
+ "instances": [
+ {
+ "input": { "value_a": "text", "value_b": null },
+ "accepted": true,
+ "zod": { "output": { "value_a": "text", "value_b": null } },
+ "effect": { "output": { "value_a": "text", "value_b": null } },
+ "python": { "output": { "value_a": "text", "value_b": null } }
+ },
+ {
+ "input": { "value_a": 1 },
+ "accepted": false
+ }
+ ]
+ },
+ {
+ "id": "pattern-property-json-integer",
+ "description": "A mathematically integral JSON number satisfies the integer type even when decoded as a float.",
+ "schema": {
+ "type": "object",
+ "patternProperties": { "^count_": { "type": "integer" } }
+ },
+ "instances": [
+ {
+ "input": { "count_a": 1.0 },
+ "accepted": true,
+ "zod": { "output": { "count_a": 1.0 } },
+ "effect": { "output": { "count_a": 1.0 } },
+ "python": { "output": { "count_a": 1.0 } }
+ },
+ {
+ "input": { "count_a": 1.5 },
+ "accepted": false
+ }
+ ]
+ },
+ {
+ "id": "pattern-property-composed-const-exclusion",
+ "description": "Composed dynamic-key schemas retain const and not semantics.",
+ "schema": {
+ "type": "object",
+ "patternProperties": {
+ "^label_": {
+ "allOf": [{ "type": "string" }, { "not": { "const": "blocked" } }]
+ }
+ }
+ },
+ "instances": [
+ {
+ "input": { "label_job": "ready" },
+ "accepted": true,
+ "zod": { "output": { "label_job": "ready" } },
+ "effect": { "output": { "label_job": "ready" } },
+ "python": { "output": { "label_job": "ready" } }
+ },
+ {
+ "input": { "label_job": "blocked" },
+ "accepted": false
+ }
+ ]
+ },
{
"id": "pattern-property-default-materialization",
"description": "Composio divergence: Zod and Pydantic materialize `default` inside a matching pattern schema, while Effect decoding is validation-only and returns the input unchanged.",
diff --git a/python/tests/test_gemini_provider.py b/python/tests/test_gemini_provider.py
index ba9761889..7badbd17d 100644
--- a/python/tests/test_gemini_provider.py
+++ b/python/tests/test_gemini_provider.py
@@ -10,6 +10,7 @@ Verifies:
"""
import inspect
+import typing as t
from unittest.mock import MagicMock, Mock
import pytest
@@ -176,6 +177,26 @@ class TestWrapTool:
assert sig.parameters["title"].annotation is str
assert sig.parameters["body"].annotation is str
+ def test_callable_has_typed_free_form_object_argument(self):
+ from composio_gemini import GeminiProvider
+
+ provider = GeminiProvider()
+ tool = create_mock_tool(
+ "PROCESS_PAYLOAD",
+ "test",
+ input_parameters={
+ "type": "object",
+ "properties": {"payload": {"type": "object"}},
+ "required": ["payload"],
+ },
+ )
+
+ result = provider.wrap_tool(tool, create_mock_execute_tool())
+ parameter = inspect.signature(result).parameters["payload"]
+
+ assert parameter.annotation == t.Dict[str, t.Any] # noqa: UP006
+ assert result.__annotations__["payload"] == t.Dict[str, t.Any] # noqa: UP006
+
def test_callable_has_annotations(self):
from composio_gemini import GeminiProvider
diff --git a/python/tests/test_schema_parser.py b/python/tests/test_schema_parser.py
index d786088f9..ccab7ff43 100644
--- a/python/tests/test_schema_parser.py
+++ b/python/tests/test_schema_parser.py
@@ -1764,3 +1764,84 @@ class TestSharedObjectCorpusThroughJsonSchemaToModel:
assert getattr(result, "anything") == {"a": 1}
assert getattr(result, "other") == "x"
+
+ @pytest.mark.parametrize(
+ ("case_id", "expected"),
+ [
+ ("named-properties-strict-by-default", {"additionalProperties": False}),
+ (
+ "root-additional-properties-schema-valued",
+ {"additionalProperties": {"type": "number"}},
+ ),
+ (
+ "pattern-only-object",
+ {"patternProperties": {"^s_": {"type": "string"}}},
+ ),
+ ],
+ )
+ def test_model_json_schema_preserves_root_object_policy(
+ self,
+ case_id: str,
+ expected: t.Dict[str, t.Any],
+ ) -> None:
+ model = json_schema_to_model(find_case(case_id).schema_)
+ advertised = model.model_json_schema()
+
+ for key, value in expected.items():
+ assert advertised[key] == value
+
+ def test_dynamic_schema_resolves_local_json_pointer(self) -> None:
+ schema = {
+ "$defs": {"positive": {"type": "integer", "minimum": 1}},
+ "type": "object",
+ "patternProperties": {"^count_": {"$ref": "#/$defs/positive"}},
+ }
+ model = json_schema_to_model(schema)
+
+ assert model.model_validate({"count_a": 1}).model_dump() == {"count_a": 1}
+ with pytest.raises(ValidationError):
+ model.model_validate({"count_a": 0})
+
+ def test_dynamic_schema_materialization_cannot_reject_valid_input(self) -> None:
+ schema = {
+ "type": "object",
+ "patternProperties": {"^value_": {"enum": [1], "default": 1}},
+ }
+ model = json_schema_to_model(schema)
+
+ assert model.model_validate({"value_a": 1}).model_dump() == {"value_a": 1}
+
+ @pytest.mark.parametrize(
+ "reference",
+ ["#/$defs/missing", "https://example.com/schema.json"],
+ )
+ def test_dynamic_schema_rejects_unresolvable_reference(
+ self,
+ reference: str,
+ ) -> None:
+ schema = {
+ "type": "object",
+ "patternProperties": {"^value_": {"$ref": reference}},
+ }
+
+ with pytest.raises(ValueError, match="schema reference"):
+ json_schema_to_model(schema)
+
+ def test_dynamic_schema_rejects_invalid_pattern(self) -> None:
+ schema = {
+ "type": "object",
+ "patternProperties": {"[": {"type": "string"}},
+ }
+
+ with pytest.raises(ValueError, match="Invalid patternProperties"):
+ json_schema_to_model(schema)
+
+ def test_dynamic_schema_checks_references_inside_local_target(self) -> None:
+ schema = {
+ "$defs": {"nested": {"$ref": "https://example.com/external-schema.json"}},
+ "type": "object",
+ "patternProperties": {"^value_": {"$ref": "#/$defs/nested"}},
+ }
+
+ with pytest.raises(ValueError, match="must be a local JSON Pointer"):
+ json_schema_to_model(schema)
diff --git a/ts/packages/core/src/types/tool.types.ts b/ts/packages/core/src/types/tool.types.ts
index c418c94c3..3d191d628 100644
--- a/ts/packages/core/src/types/tool.types.ts
+++ b/ts/packages/core/src/types/tool.types.ts
@@ -139,7 +139,7 @@ const ParametersSchema = z.preprocess(
oneOf: z.array(JSONSchemaPropertySchema).optional(),
allOf: z.array(JSONSchemaPropertySchema).optional(),
not: JSONSchemaPropertySchema.optional(),
- properties: z.record(z.string(), JSONSchemaPropertySchema),
+ properties: z.record(z.string(), JSONSchemaPropertySchema).optional(),
required: z.array(z.string()).optional(),
title: z.string().optional(),
default: z.unknown().optional(),
diff --git a/ts/packages/core/test/fixtures/json-schema-conversion/object-cases.json b/ts/packages/core/test/fixtures/json-schema-conversion/object-cases.json
index 82f06ecd7..c3a6b8ac1 100644
--- a/ts/packages/core/test/fixtures/json-schema-conversion/object-cases.json
+++ b/ts/packages/core/test/fixtures/json-schema-conversion/object-cases.json
@@ -34,6 +34,10 @@
"id": "root-free-form-absent-properties",
"description": "A root object with no `properties` member and omitted `additionalProperties` is open.",
"schema": { "type": "object" },
+ "ingress": {
+ "accepted": true,
+ "preserved": { "type": "object" }
+ },
"instances": [
{
"input": { "anything": { "a": 1 }, "other": "x" },
@@ -348,6 +352,169 @@
}
]
},
+ {
+ "id": "empty-schema-additional-properties",
+ "description": "An empty schema accepts every unmatched value without coercing or discarding it.",
+ "schema": {
+ "type": "object",
+ "properties": { "name": { "type": "string" } },
+ "additionalProperties": {}
+ },
+ "instances": [
+ {
+ "input": { "name": "a", "count": 1, "metadata": { "active": true } },
+ "accepted": true,
+ "zod": {
+ "output": { "name": "a", "count": 1, "metadata": { "active": true } }
+ },
+ "effect": {
+ "output": { "name": "a", "count": 1, "metadata": { "active": true } }
+ },
+ "python": {
+ "output": { "name": "a", "count": 1, "metadata": { "active": true } }
+ }
+ }
+ ]
+ },
+ {
+ "id": "pattern-property-enum",
+ "description": "A matching dynamic key must satisfy an enum-only schema with no explicit type.",
+ "schema": {
+ "type": "object",
+ "patternProperties": { "^status_": { "enum": ["ready", "done"] } }
+ },
+ "instances": [
+ {
+ "input": { "status_job": "ready" },
+ "accepted": true,
+ "zod": { "output": { "status_job": "ready" } },
+ "effect": { "output": { "status_job": "ready" } },
+ "python": { "output": { "status_job": "ready" } }
+ },
+ {
+ "input": { "status_job": "blocked" },
+ "accepted": false
+ }
+ ]
+ },
+ {
+ "id": "pattern-property-strict-nested-array",
+ "description": "Nested container values are validated without coercing strings into integers.",
+ "schema": {
+ "type": "object",
+ "patternProperties": {
+ "^batch_": {
+ "type": "object",
+ "properties": {
+ "values": { "type": "array", "items": { "type": "integer" } }
+ },
+ "required": ["values"],
+ "additionalProperties": false
+ }
+ }
+ },
+ "instances": [
+ {
+ "input": { "batch_a": { "values": [1, 2] } },
+ "accepted": true,
+ "zod": { "output": { "batch_a": { "values": [1, 2] } } },
+ "effect": { "output": { "batch_a": { "values": [1, 2] } } },
+ "python": { "output": { "batch_a": { "values": [1, 2] } } }
+ },
+ {
+ "input": { "batch_a": { "values": ["1"] } },
+ "accepted": false
+ }
+ ]
+ },
+ {
+ "id": "false-pattern-property-schema",
+ "description": "A boolean-false pattern schema rejects every value for matching keys.",
+ "schema": {
+ "type": "object",
+ "patternProperties": { "^forbidden$": false }
+ },
+ "instances": [
+ {
+ "input": { "other": 1 },
+ "accepted": true,
+ "zod": { "output": { "other": 1 } },
+ "effect": { "output": { "other": 1 } },
+ "python": { "output": { "other": 1 } }
+ },
+ {
+ "input": { "forbidden": null },
+ "accepted": false
+ }
+ ]
+ },
+ {
+ "id": "pattern-property-type-union",
+ "description": "A list-valued type accepts only the listed JSON instance types.",
+ "schema": {
+ "type": "object",
+ "patternProperties": { "^value_": { "type": ["string", "null"] } }
+ },
+ "instances": [
+ {
+ "input": { "value_a": "text", "value_b": null },
+ "accepted": true,
+ "zod": { "output": { "value_a": "text", "value_b": null } },
+ "effect": { "output": { "value_a": "text", "value_b": null } },
+ "python": { "output": { "value_a": "text", "value_b": null } }
+ },
+ {
+ "input": { "value_a": 1 },
+ "accepted": false
+ }
+ ]
+ },
+ {
+ "id": "pattern-property-json-integer",
+ "description": "A mathematically integral JSON number satisfies the integer type even when decoded as a float.",
+ "schema": {
+ "type": "object",
+ "patternProperties": { "^count_": { "type": "integer" } }
+ },
+ "instances": [
+ {
+ "input": { "count_a": 1.0 },
+ "accepted": true,
+ "zod": { "output": { "count_a": 1.0 } },
+ "effect": { "output": { "count_a": 1.0 } },
+ "python": { "output": { "count_a": 1.0 } }
+ },
+ {
+ "input": { "count_a": 1.5 },
+ "accepted": false
+ }
+ ]
+ },
+ {
+ "id": "pattern-property-composed-const-exclusion",
+ "description": "Composed dynamic-key schemas retain const and not semantics.",
+ "schema": {
+ "type": "object",
+ "patternProperties": {
+ "^label_": {
+ "allOf": [{ "type": "string" }, { "not": { "const": "blocked" } }]
+ }
+ }
+ },
+ "instances": [
+ {
+ "input": { "label_job": "ready" },
+ "accepted": true,
+ "zod": { "output": { "label_job": "ready" } },
+ "effect": { "output": { "label_job": "ready" } },
+ "python": { "output": { "label_job": "ready" } }
+ },
+ {
+ "input": { "label_job": "blocked" },
+ "accepted": false
+ }
+ ]
+ },
{
"id": "pattern-property-default-materialization",
"description": "Composio divergence: Zod and Pydantic materialize `default` inside a matching pattern schema, while Effect decoding is validation-only and returns the input unchanged.",
diff --git a/ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.registration.test.ts b/ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.registration.test.ts
index 7f00e2441..fc76ef472 100644
--- a/ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.registration.test.ts
+++ b/ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.registration.test.ts
@@ -133,6 +133,31 @@ describe('ClaudeAgentSDKProvider registration boundary', () => {
expect(executeToolFn).not.toHaveBeenCalled();
});
+ it('preserves schema-valued additionalProperties through MCP registration', async () => {
+ const { inputSchema, executeToolFn, call } = await registerTool(
+ buildTool({
+ type: 'object',
+ properties: { name: { type: 'string' } },
+ additionalProperties: { type: 'number' },
+ })
+ );
+
+ expect(inputSchema.additionalProperties).toEqual({ type: 'number' });
+
+ const accepted = await call({ name: 'report', count: 2 });
+ expect(accepted.isError ?? false).toBe(false);
+ expect(executeToolFn).toHaveBeenCalledWith(
+ 'TEST_TOOL',
+ expect.objectContaining({ name: 'report', count: 2 })
+ );
+
+ executeToolFn.mockClear();
+
+ const rejected = await call({ name: 'report', count: 'two' });
+ expect(rejected.isError).toBe(true);
+ expect(executeToolFn).not.toHaveBeenCalled();
+ });
+
it('keeps a tool with no input parameters closed', async () => {
const { inputSchema, executeToolFn, call } = await registerTool(buildTool(undefined));
diff --git a/uv.lock b/uv.lock
index 314ef6944..ba13980a2 100644
--- a/uv.lock
+++ b/uv.lock
@@ -719,6 +719,7 @@ source = { editable = "python" }
dependencies = [
{ name = "composio-client" },
{ name = "json-schema-to-pydantic" },
+ { name = "jsonschema" },
{ name = "openai" },
{ name = "pydantic" },
{ name = "pysher" },
@@ -746,6 +747,7 @@ dev = [
requires-dist = [
{ name = "composio-client", specifier = "==1.43.0" },
{ name = "json-schema-to-pydantic", specifier = ">=0.4.11" },
+ { name = "jsonschema", specifier = ">=4.23.0" },
{ name = "openai", specifier = ">=2.48.0" },
{ name = "pydantic", specifier = ">=2.11.9" },
{ name = "pysher", specifier = ">=1.0.8" },
@@ -1139,7 +1141,7 @@ name = "exceptiongroup"
version = "1.3.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "typing-extensions" },
+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }
wheels = [
@@ -1905,7 +1907,7 @@ name = "importlib-metadata"
version = "9.0.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "zipp" },
+ { name = "zipp", marker = "python_full_version < '3.12'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a9/01/15bb152d77b21318514a96f43af312635eb2500c96b55398d020c93d86ea/importlib_metadata-9.0.0.tar.gz", hash = "sha256:a4f57ab599e6a2e3016d7595cfd72eb4661a5106e787a95bcc90c7105b831efc", size = 56405, upload-time = "2026-03-20T06:42:56.999Z" }
wheels = [
@@ -3170,11 +3172,11 @@ resolution-markers = [
"python_full_version < '3.11'",
]
dependencies = [
- { name = "flatbuffers" },
- { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } },
- { name = "packaging" },
- { name = "protobuf" },
- { name = "sympy" },
+ { name = "flatbuffers", marker = "python_full_version < '3.11'" },
+ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
+ { name = "packaging", marker = "python_full_version < '3.11'" },
+ { name = "protobuf", marker = "python_full_version < '3.11'" },
+ { name = "sympy", marker = "python_full_version < '3.11'" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/15/41/3253db975a90c3ce1d475e2a230773a21cd7998537f0657947df6fb79861/onnxruntime-1.24.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3e6456801c66b095c5cd68e690ca25db970ea5202bd0c5b84a2c3ef7731c5a3c", size = 17332766, upload-time = "2026-03-05T17:18:59.714Z" },
@@ -3216,11 +3218,11 @@ resolution-markers = [
"python_full_version == '3.11.*'",
]
dependencies = [
- { name = "flatbuffers" },
- { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
+ { name = "flatbuffers", marker = "python_full_version >= '3.11'" },
+ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
- { name = "packaging" },
- { name = "protobuf" },
+ { name = "packaging", marker = "python_full_version >= '3.11'" },
+ { name = "protobuf", marker = "python_full_version >= '3.11'" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/17/4d/5014667e2a3a77d6e1b74cc3d88948d06163b8e0a33a84c85073322b5dec/onnxruntime-1.28.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:f5c5daabd28aad610f83fdcf32acec8fb57e6adc6c6a39fe2a3c755db957b410", size = 19130506, upload-time = "2026-07-25T01:22:34.489Z" },
@@ -5110,8 +5112,8 @@ name = "secretstorage"
version = "3.5.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "cryptography" },
- { name = "jeepney" },
+ { name = "cryptography", marker = "python_full_version < '3.13' or sys_platform != 'win32'" },
+ { name = "jeepney", marker = "python_full_version < '3.13' or sys_platform != 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz", hash = "sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size = 19884, upload-time = "2025-11-23T19:02:53.191Z" }
wheels = [
@@ -5185,7 +5187,7 @@ name = "sympy"
version = "1.14.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "mpmath" },
+ { name = "mpmath", marker = "python_full_version < '3.11'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" }
wheels = [