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
jkomyno committed
Aug 7, 2026 at 00:06 UTC
4a89ff112c101bdc56c307870b21ed820ba72839
12 files changed
+668
-105
.changeset/preserve-root-dynamic-key-constraints.md
+2
-2
@@ -2,9 +2,9 @@
2
'@composio/core': minor
3
---
4
5
-Keep root `patternProperties` and `additionalProperties` when parsing a tool schema.
5
+Keep free-form object roots, `patternProperties`, and `additionalProperties` when parsing a tool schema.
6
7
-`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.
7
+`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.
8
9
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.
10
python/composio/utils/schema_converter.py
+185
-88
@@ -12,20 +12,27 @@ We handle those by pre-filtering them before passing to the library.
12
import re
13
import typing as t
14
from functools import reduce
15
+from urllib.parse import unquote
16
17
from json_schema_to_pydantic import (
18
CombinerError,
19
SchemaError,
20
+)
21
+from json_schema_to_pydantic import (
22
create_model as create_model_from_schema,
23
)
24
+from jsonschema import validators as jsonschema_validators
25
+from jsonschema.protocols import Validator
26
from pydantic import (
27
BaseModel,
28
ConfigDict,
29
Field,
30
TypeAdapter,
26
- create_model as create_pydantic_model,
31
model_validator,
32
)
33
+from pydantic import (
34
+ create_model as create_pydantic_model,
35
+)
36
from pydantic_core import core_schema
37
38
from composio.utils.logging import get as get_logger
@@ -231,41 +238,30 @@ def _contains_unsatisfiable_schema(schema: t.Any) -> bool:
238
return False
239
240
234
-_PRIMITIVE_TYPES = frozenset({"string", "number", "integer", "boolean", "null"})
235
-
236
-# JSON Schema keyword -> Pydantic `Field` constraint, by instance type. Simple
237
-# primitives lose their constraints in `PYDANTIC_TYPE_TO_PYTHON_TYPE`, which is
238
-# fine for declared fields the library models but not for dynamic keys, where
239
-# this module is the only validator.
240
-_CONSTRAINTS: t.Dict[str, t.Dict[str, str]] = {
241
- "string": {
242
- "minLength": "min_length",
243
- "maxLength": "max_length",
244
- "pattern": "pattern",
245
- },
246
- "array": {"minItems": "min_length", "maxItems": "max_length"},
247
-}
248
-_NUMERIC_CONSTRAINTS = {
249
- "minimum": "ge",
250
- "maximum": "le",
251
- "exclusiveMinimum": "gt",
252
- "exclusiveMaximum": "lt",
253
- "multipleOf": "multiple_of",
254
-}
255
-_CONSTRAINTS["number"] = _NUMERIC_CONSTRAINTS
256
-_CONSTRAINTS["integer"] = _NUMERIC_CONSTRAINTS
257
-
258
-
241
class _DynamicKeyValidator(t.NamedTuple):
260
- """Validator for one dynamic-key schema, plus how strictly to apply it."""
242
+ """Exact JSON Schema validation with optional default materialization."""
243
262
- adapter: TypeAdapter
263
- strict: bool
244
+ validator: Validator
245
+ materializer: t.Optional[TypeAdapter]
246
265
- def coerce(self, value: t.Any) -> t.Any:
266
- return self.adapter.dump_python(
267
- self.adapter.validate_python(value, strict=self.strict)
268
- )
247
+ def validate(self, value: t.Any) -> None:
248
+ error = next(self.validator.iter_errors(value), None)
249
+ if error is not None:
250
+ raise ValueError(error.message)
251
+
252
+ def materialize(self, value: t.Any) -> t.Any:
253
+ if self.materializer is None:
254
+ return value
255
+ try:
256
+ return self.materializer.dump_python(
257
+ self.materializer.validate_python(value)
258
+ )
259
+ except (TypeError, ValueError):
260
+ # JSON Schema alone decides acceptance. Pydantic is only retained
261
+ # for the existing default-materialization behavior, and an
262
+ # incomplete Pydantic representation must not reject valid input.
263
+ logger.debug("Could not materialize dynamic-key defaults; preserving input")
264
+ return value
265
266
267
class _ObjectPolicy(t.NamedTuple):
@@ -277,7 +273,7 @@ class _ObjectPolicy(t.NamedTuple):
273
"""
274
275
declared: t.FrozenSet[str]
280
- patterns: t.Tuple[t.Tuple[t.Pattern[str], t.Optional[_DynamicKeyValidator]], ...]
276
+ patterns: t.Tuple[t.Tuple[t.Pattern[str], _DynamicKeyValidator], ...]
277
additional: t.Optional[_DynamicKeyValidator]
278
rejects_unmatched: bool
279
@@ -300,50 +296,128 @@ def object_is_open(schema: t.Dict[str, t.Any]) -> bool:
296
return not (schema.get("properties") or {}) and additional in (_MISSING, True)
297
298
303
-def _dynamic_key_validator(schema: t.Any) -> t.Optional[_DynamicKeyValidator]:
304
- """Build the validator for one dynamic-key schema, or ``None`` if unmodellable."""
305
- try:
306
- annotation: t.Any = json_schema_to_pydantic_type(schema)
307
- strict = False
308
-
309
- if isinstance(schema, dict):
310
- schema_type = schema.get("type") or ""
311
- constraints = {
312
- field: schema[keyword]
313
- for keyword, field in _CONSTRAINTS.get(schema_type, {}).items()
314
- if keyword in schema
315
- }
316
- if constraints:
317
- annotation = t.Annotated[annotation, Field(**constraints)]
318
- # Primitives validate strictly so Pydantic's lax coercion cannot
319
- # admit a value the TypeScript converters reject (`true` as a
320
- # number, `1` as a boolean).
321
- strict = schema_type in _PRIMITIVE_TYPES
322
-
323
- return _DynamicKeyValidator(TypeAdapter(annotation), strict)
324
- except Exception as exc: # pragma: no cover - defensive
325
- logger.debug(f"Could not build a dynamic-key validator for {schema!r}: {exc}")
326
- return None
299
+def _contains_default(schema: t.Any) -> bool:
300
+ """Whether Pydantic must run after validation to materialize a default."""
301
+ if isinstance(schema, list):
302
+ return any(_contains_default(item) for item in schema)
303
+ if not isinstance(schema, dict):
304
+ return False
305
+ return "default" in schema or any(
306
+ _contains_default(value) for value in schema.values()
307
+ )
308
+
309
+
310
+def _resolve_local_json_pointer(
311
+ reference: str,
312
+ root_schema: t.Dict[str, t.Any],
313
+) -> t.Any:
314
+ """Resolve a local JSON Pointer or fail while the model is constructed."""
315
+ if reference == "#":
316
+ return root_schema
317
+ if not reference.startswith("#/"):
318
+ raise ValueError(
319
+ f"Dynamic-key schema reference {reference!r} must be a local JSON Pointer"
320
+ )
321
+
322
+ current: t.Any = root_schema
323
+ for raw_token in unquote(reference[2:]).split("/"):
324
+ token = raw_token.replace("~1", "/").replace("~0", "~")
325
+ if isinstance(current, dict) and token in current:
326
+ current = current[token]
327
+ continue
328
+ if isinstance(current, list):
329
+ try:
330
+ current = current[int(token)]
331
+ continue
332
+ except (ValueError, IndexError):
333
+ pass
334
+ raise ValueError(f"Unresolvable dynamic-key schema reference: {reference!r}")
335
+ return current
336
+
337
+
338
+def _check_dynamic_references(
339
+ schema: t.Any,
340
+ root_schema: t.Dict[str, t.Any],
341
+ checked_references: t.Optional[t.Set[str]] = None,
342
+) -> None:
343
+ """Reject external, anchored, and unresolved references before validation."""
344
+ if checked_references is None:
345
+ checked_references = set()
346
+ if isinstance(schema, list):
347
+ for item in schema:
348
+ _check_dynamic_references(item, root_schema, checked_references)
349
+ return
350
+ if not isinstance(schema, dict):
351
+ return
352
+
353
+ reference = schema.get("$ref")
354
+ if reference is not None:
355
+ if not isinstance(reference, str):
356
+ raise ValueError("Dynamic-key schema `$ref` must be a string")
357
+ resolved = _resolve_local_json_pointer(reference, root_schema)
358
+ if not isinstance(resolved, (dict, bool)):
359
+ raise ValueError(
360
+ f"Dynamic-key schema reference {reference!r} does not target a schema"
361
+ )
362
+ if reference not in checked_references:
363
+ checked_references.add(reference)
364
+ _check_dynamic_references(resolved, root_schema, checked_references)
365
+
366
+ for value in schema.values():
367
+ _check_dynamic_references(value, root_schema, checked_references)
368
+
369
+
370
+def _dynamic_key_validator(
371
+ schema: t.Any,
372
+ root_schema: t.Dict[str, t.Any],
373
+ root_validator: Validator,
374
+) -> _DynamicKeyValidator:
375
+ """Compile a complete inline JSON subschema without coercive acceptance."""
376
+ validator_type = type(root_validator)
377
+ validator_type.check_schema(schema)
378
+ _check_dynamic_references(schema, root_schema)
379
+
380
+ materializer = None
381
+ if _contains_default(schema):
382
+ annotation = json_schema_to_pydantic_type(schema)
383
+ materializer = TypeAdapter(annotation)
384
+
385
+ return _DynamicKeyValidator(
386
+ validator=root_validator.evolve(schema=schema),
387
+ materializer=materializer,
388
+ )
389
390
391
def _compile_object_policy(schema: t.Dict[str, t.Any]) -> _ObjectPolicy:
392
declared = frozenset(schema.get("properties") or {})
393
additional = schema.get("additionalProperties", _MISSING)
394
+ validator_type = jsonschema_validators.validator_for(
395
+ schema,
396
+ default=jsonschema_validators.Draft7Validator,
397
+ )
398
+ root_validator = validator_type(schema)
399
400
patterns = []
401
for pattern, pattern_schema in (schema.get("patternProperties") or {}).items():
402
try:
403
patterns.append(
337
- (re.compile(pattern), _dynamic_key_validator(pattern_schema))
404
+ (
405
+ re.compile(pattern),
406
+ _dynamic_key_validator(pattern_schema, schema, root_validator),
407
+ )
408
)
339
- except re.error:
340
- logger.debug(f"Skipping uncompilable patternProperties regex: {pattern!r}")
409
+ except re.error as exc:
410
+ raise ValueError(
411
+ f"Invalid patternProperties regular expression: {pattern!r}"
412
+ ) from exc
413
414
return _ObjectPolicy(
415
declared=declared,
416
patterns=tuple(patterns),
417
additional=(
346
- _dynamic_key_validator(additional) if isinstance(additional, dict) else None
418
+ _dynamic_key_validator(additional, schema, root_validator)
419
+ if isinstance(additional, dict)
420
+ else None
421
),
422
rejects_unmatched=additional is False
423
or (additional is _MISSING and bool(declared)),
@@ -356,42 +430,28 @@ class _DynamicObjectModel(BaseModel):
430
``extra="allow"`` is what makes preservation possible at all: Pydantic's
431
default silently discards accepted arguments, so a provider that re-reads
432
them (``LangchainProvider`` uses ``getattr``) would lose valid payloads.
359
- Coerced values are written back into ``__pydantic_extra__`` so they show up
360
- in ``model_dump()`` and remain readable as attributes.
433
+ Materialized defaults are written back into ``__pydantic_extra__`` so they
434
+ show up in ``model_dump()`` and remain readable as attributes.
435
"""
436
437
model_config = ConfigDict(extra="allow")
438
365
- @model_validator(mode="after")
366
- def _apply_object_policy(self):
439
+ @model_validator(mode="before")
440
+ @classmethod
441
+ def _validate_object_policy(cls, value: t.Any) -> t.Any:
442
policy: t.Optional[_ObjectPolicy] = getattr(
368
- type(self), "__composio_object_policy__", None
443
+ cls, "__composio_object_policy__", None
444
)
370
- if policy is None or policy.is_trivial:
371
- return self
372
-
373
- # A key declared in `properties` is still checked against every matching
374
- # pattern; its declared value is authoritative and is not overwritten.
375
- for name, field in type(self).model_fields.items():
376
- if name not in self.model_fields_set:
377
- continue
378
- key = field.alias or name
379
- for regex, validator in policy.patterns:
380
- if validator is not None and regex.search(key):
381
- validator.coerce(getattr(self, name))
382
-
383
- extra = self.__pydantic_extra__
384
- if not extra:
385
- return self
445
+ if policy is None or policy.is_trivial or not isinstance(value, dict):
446
+ return value
447
448
unrecognized = []
388
- for key, value in list(extra.items()):
449
+ for key, item in value.items():
450
matched = False
451
for regex, validator in policy.patterns:
452
if regex.search(key):
453
matched = True
393
- if validator is not None:
394
- extra[key] = validator.coerce(value)
454
+ validator.validate(item)
455
456
if matched or key in policy.declared:
457
continue
@@ -399,13 +459,40 @@ class _DynamicObjectModel(BaseModel):
459
if policy.rejects_unmatched:
460
unrecognized.append(key)
461
elif policy.additional is not None:
402
- extra[key] = policy.additional.coerce(value)
462
+ policy.additional.validate(item)
463
464
if unrecognized:
465
raise ValueError(
466
f"Unrecognized key(s) in object: {', '.join(repr(key) for key in unrecognized)}"
467
)
468
469
+ return value
470
+
471
+ @model_validator(mode="after")
472
+ def _materialize_dynamic_defaults(self):
473
+ policy: t.Optional[_ObjectPolicy] = getattr(
474
+ type(self), "__composio_object_policy__", None
475
+ )
476
+ if policy is None or policy.is_trivial:
477
+ return self
478
+
479
+ extra = self.__pydantic_extra__
480
+ if not extra:
481
+ return self
482
+
483
+ for key, value in list(extra.items()):
484
+ matched = False
485
+ for regex, validator in policy.patterns:
486
+ if regex.search(key):
487
+ matched = True
488
+ extra[key] = validator.materialize(extra[key])
489
+
490
+ if matched or key in policy.declared:
491
+ continue
492
+
493
+ if policy.additional is not None:
494
+ extra[key] = policy.additional.materialize(value)
495
+
496
return self
497
498
@@ -417,6 +504,13 @@ def apply_object_policy(
504
"""Wrap ``base_model`` with the covered dynamic-key policy for ``schema``."""
505
policy = _compile_object_policy(schema)
506
name = model_name or base_model.__name__
507
+ json_schema_extra: t.Dict[str, t.Any] = {}
508
+ if "patternProperties" in schema:
509
+ json_schema_extra["patternProperties"] = schema["patternProperties"]
510
+ if "additionalProperties" in schema:
511
+ json_schema_extra["additionalProperties"] = schema["additionalProperties"]
512
+ elif policy.rejects_unmatched:
513
+ json_schema_extra["additionalProperties"] = False
514
515
return t.cast(
516
t.Type[BaseModel],
@@ -426,7 +520,10 @@ def apply_object_policy(
520
{
521
"__module__": __name__,
522
"__qualname__": name,
429
- "model_config": ConfigDict(extra="allow"),
523
+ "model_config": ConfigDict(
524
+ extra="allow",
525
+ json_schema_extra=json_schema_extra,
526
+ ),
527
"__composio_object_policy__": policy,
528
},
529
),
python/noxfile.py
+1
@@ -31,6 +31,7 @@ modules_for_ruff = [
31
type_stubs = [
32
"types-requests==2.33.0.20260712",
33
"types-protobuf==7.34.1.20260518",
34
+ "types-jsonschema==4.26.0.20260518",
35
"anthropic==0.120.0",
36
# Keep this aligned with the CrewAI provider dependency metadata.
37
"crewai==1.15.7",
python/pyproject.toml
+1
@@ -11,6 +11,7 @@ dependencies = [
11
"typing-extensions>=4.16.0",
12
"openai>=2.48.0",
13
"json-schema-to-pydantic>=0.4.11",
14
+ "jsonschema>=4.23.0",
15
]
16
classifiers = [
17
"Programming Language :: Python :: 3",
python/setup.py
+1
@@ -29,6 +29,7 @@ setup(
29
"typing-extensions>=4.16.0",
30
"openai>=2.48.0",
31
"json-schema-to-pydantic>=0.4.11",
32
+ "jsonschema>=4.23.0",
33
],
34
include_package_data=True,
35
)
python/tests/fixtures/json-schema-conversion/object-cases.json
+167
@@ -34,6 +34,10 @@
34
"id": "root-free-form-absent-properties",
35
"description": "A root object with no `properties` member and omitted `additionalProperties` is open.",
36
"schema": { "type": "object" },
37
+ "ingress": {
38
+ "accepted": true,
39
+ "preserved": { "type": "object" }
40
+ },
41
"instances": [
42
{
43
"input": { "anything": { "a": 1 }, "other": "x" },
@@ -348,6 +352,169 @@
352
}
353
]
354
},
355
+ {
356
+ "id": "empty-schema-additional-properties",
357
+ "description": "An empty schema accepts every unmatched value without coercing or discarding it.",
358
+ "schema": {
359
+ "type": "object",
360
+ "properties": { "name": { "type": "string" } },
361
+ "additionalProperties": {}
362
+ },
363
+ "instances": [
364
+ {
365
+ "input": { "name": "a", "count": 1, "metadata": { "active": true } },
366
+ "accepted": true,
367
+ "zod": {
368
+ "output": { "name": "a", "count": 1, "metadata": { "active": true } }
369
+ },
370
+ "effect": {
371
+ "output": { "name": "a", "count": 1, "metadata": { "active": true } }
372
+ },
373
+ "python": {
374
+ "output": { "name": "a", "count": 1, "metadata": { "active": true } }
375
+ }
376
+ }
377
+ ]
378
+ },
379
+ {
380
+ "id": "pattern-property-enum",
381
+ "description": "A matching dynamic key must satisfy an enum-only schema with no explicit type.",
382
+ "schema": {
383
+ "type": "object",
384
+ "patternProperties": { "^status_": { "enum": ["ready", "done"] } }
385
+ },
386
+ "instances": [
387
+ {
388
+ "input": { "status_job": "ready" },
389
+ "accepted": true,
390
+ "zod": { "output": { "status_job": "ready" } },
391
+ "effect": { "output": { "status_job": "ready" } },
392
+ "python": { "output": { "status_job": "ready" } }
393
+ },
394
+ {
395
+ "input": { "status_job": "blocked" },
396
+ "accepted": false
397
+ }
398
+ ]
399
+ },
400
+ {
401
+ "id": "pattern-property-strict-nested-array",
402
+ "description": "Nested container values are validated without coercing strings into integers.",
403
+ "schema": {
404
+ "type": "object",
405
+ "patternProperties": {
406
+ "^batch_": {
407
+ "type": "object",
408
+ "properties": {
409
+ "values": { "type": "array", "items": { "type": "integer" } }
410
+ },
411
+ "required": ["values"],
412
+ "additionalProperties": false
413
+ }
414
+ }
415
+ },
416
+ "instances": [
417
+ {
418
+ "input": { "batch_a": { "values": [1, 2] } },
419
+ "accepted": true,
420
+ "zod": { "output": { "batch_a": { "values": [1, 2] } } },
421
+ "effect": { "output": { "batch_a": { "values": [1, 2] } } },
422
+ "python": { "output": { "batch_a": { "values": [1, 2] } } }
423
+ },
424
+ {
425
+ "input": { "batch_a": { "values": ["1"] } },
426
+ "accepted": false
427
+ }
428
+ ]
429
+ },
430
+ {
431
+ "id": "false-pattern-property-schema",
432
+ "description": "A boolean-false pattern schema rejects every value for matching keys.",
433
+ "schema": {
434
+ "type": "object",
435
+ "patternProperties": { "^forbidden$": false }
436
+ },
437
+ "instances": [
438
+ {
439
+ "input": { "other": 1 },
440
+ "accepted": true,
441
+ "zod": { "output": { "other": 1 } },
442
+ "effect": { "output": { "other": 1 } },
443
+ "python": { "output": { "other": 1 } }
444
+ },
445
+ {
446
+ "input": { "forbidden": null },
447
+ "accepted": false
448
+ }
449
+ ]
450
+ },
451
+ {
452
+ "id": "pattern-property-type-union",
453
+ "description": "A list-valued type accepts only the listed JSON instance types.",
454
+ "schema": {
455
+ "type": "object",
456
+ "patternProperties": { "^value_": { "type": ["string", "null"] } }
457
+ },
458
+ "instances": [
459
+ {
460
+ "input": { "value_a": "text", "value_b": null },
461
+ "accepted": true,
462
+ "zod": { "output": { "value_a": "text", "value_b": null } },
463
+ "effect": { "output": { "value_a": "text", "value_b": null } },
464
+ "python": { "output": { "value_a": "text", "value_b": null } }
465
+ },
466
+ {
467
+ "input": { "value_a": 1 },
468
+ "accepted": false
469
+ }
470
+ ]
471
+ },
472
+ {
473
+ "id": "pattern-property-json-integer",
474
+ "description": "A mathematically integral JSON number satisfies the integer type even when decoded as a float.",
475
+ "schema": {
476
+ "type": "object",
477
+ "patternProperties": { "^count_": { "type": "integer" } }
478
+ },
479
+ "instances": [
480
+ {
481
+ "input": { "count_a": 1.0 },
482
+ "accepted": true,
483
+ "zod": { "output": { "count_a": 1.0 } },
484
+ "effect": { "output": { "count_a": 1.0 } },
485
+ "python": { "output": { "count_a": 1.0 } }
486
+ },
487
+ {
488
+ "input": { "count_a": 1.5 },
489
+ "accepted": false
490
+ }
491
+ ]
492
+ },
493
+ {
494
+ "id": "pattern-property-composed-const-exclusion",
495
+ "description": "Composed dynamic-key schemas retain const and not semantics.",
496
+ "schema": {
497
+ "type": "object",
498
+ "patternProperties": {
499
+ "^label_": {
500
+ "allOf": [{ "type": "string" }, { "not": { "const": "blocked" } }]
501
+ }
502
+ }
503
+ },
504
+ "instances": [
505
+ {
506
+ "input": { "label_job": "ready" },
507
+ "accepted": true,
508
+ "zod": { "output": { "label_job": "ready" } },
509
+ "effect": { "output": { "label_job": "ready" } },
510
+ "python": { "output": { "label_job": "ready" } }
511
+ },
512
+ {
513
+ "input": { "label_job": "blocked" },
514
+ "accepted": false
515
+ }
516
+ ]
517
+ },
518
{
519
"id": "pattern-property-default-materialization",
520
"description": "Composio divergence: Zod and Pydantic materialize `default` inside a matching pattern schema, while Effect decoding is validation-only and returns the input unchanged.",
python/tests/test_gemini_provider.py
+21
@@ -10,6 +10,7 @@ Verifies:
10
"""
11
12
import inspect
13
+import typing as t
14
from unittest.mock import MagicMock, Mock
15
16
import pytest
@@ -176,6 +177,26 @@ class TestWrapTool:
177
assert sig.parameters["title"].annotation is str
178
assert sig.parameters["body"].annotation is str
179
180
+ def test_callable_has_typed_free_form_object_argument(self):
181
+ from composio_gemini import GeminiProvider
182
+
183
+ provider = GeminiProvider()
184
+ tool = create_mock_tool(
185
+ "PROCESS_PAYLOAD",
186
+ "test",
187
+ input_parameters={
188
+ "type": "object",
189
+ "properties": {"payload": {"type": "object"}},
190
+ "required": ["payload"],
191
+ },
192
+ )
193
+
194
+ result = provider.wrap_tool(tool, create_mock_execute_tool())
195
+ parameter = inspect.signature(result).parameters["payload"]
196
+
197
+ assert parameter.annotation == t.Dict[str, t.Any] # noqa: UP006
198
+ assert result.__annotations__["payload"] == t.Dict[str, t.Any] # noqa: UP006
199
+
200
def test_callable_has_annotations(self):
201
from composio_gemini import GeminiProvider
202
python/tests/test_schema_parser.py
+81
@@ -1764,3 +1764,84 @@ class TestSharedObjectCorpusThroughJsonSchemaToModel:
1764
1765
assert getattr(result, "anything") == {"a": 1}
1766
assert getattr(result, "other") == "x"
1767
+
1768
+ @pytest.mark.parametrize(
1769
+ ("case_id", "expected"),
1770
+ [
1771
+ ("named-properties-strict-by-default", {"additionalProperties": False}),
1772
+ (
1773
+ "root-additional-properties-schema-valued",
1774
+ {"additionalProperties": {"type": "number"}},
1775
+ ),
1776
+ (
1777
+ "pattern-only-object",
1778
+ {"patternProperties": {"^s_": {"type": "string"}}},
1779
+ ),
1780
+ ],
1781
+ )
1782
+ def test_model_json_schema_preserves_root_object_policy(
1783
+ self,
1784
+ case_id: str,
1785
+ expected: t.Dict[str, t.Any],
1786
+ ) -> None:
1787
+ model = json_schema_to_model(find_case(case_id).schema_)
1788
+ advertised = model.model_json_schema()
1789
+
1790
+ for key, value in expected.items():
1791
+ assert advertised[key] == value
1792
+
1793
+ def test_dynamic_schema_resolves_local_json_pointer(self) -> None:
1794
+ schema = {
1795
+ "$defs": {"positive": {"type": "integer", "minimum": 1}},
1796
+ "type": "object",
1797
+ "patternProperties": {"^count_": {"$ref": "#/$defs/positive"}},
1798
+ }
1799
+ model = json_schema_to_model(schema)
1800
+
1801
+ assert model.model_validate({"count_a": 1}).model_dump() == {"count_a": 1}
1802
+ with pytest.raises(ValidationError):
1803
+ model.model_validate({"count_a": 0})
1804
+
1805
+ def test_dynamic_schema_materialization_cannot_reject_valid_input(self) -> None:
1806
+ schema = {
1807
+ "type": "object",
1808
+ "patternProperties": {"^value_": {"enum": [1], "default": 1}},
1809
+ }
1810
+ model = json_schema_to_model(schema)
1811
+
1812
+ assert model.model_validate({"value_a": 1}).model_dump() == {"value_a": 1}
1813
+
1814
+ @pytest.mark.parametrize(
1815
+ "reference",
1816
+ ["#/$defs/missing", "https://example.com/schema.json"],
1817
+ )
1818
+ def test_dynamic_schema_rejects_unresolvable_reference(
1819
+ self,
1820
+ reference: str,
1821
+ ) -> None:
1822
+ schema = {
1823
+ "type": "object",
1824
+ "patternProperties": {"^value_": {"$ref": reference}},
1825
+ }
1826
+
1827
+ with pytest.raises(ValueError, match="schema reference"):
1828
+ json_schema_to_model(schema)
1829
+
1830
+ def test_dynamic_schema_rejects_invalid_pattern(self) -> None:
1831
+ schema = {
1832
+ "type": "object",
1833
+ "patternProperties": {"[": {"type": "string"}},
1834
+ }
1835
+
1836
+ with pytest.raises(ValueError, match="Invalid patternProperties"):
1837
+ json_schema_to_model(schema)
1838
+
1839
+ def test_dynamic_schema_checks_references_inside_local_target(self) -> None:
1840
+ schema = {
1841
+ "$defs": {"nested": {"$ref": "https://example.com/external-schema.json"}},
1842
+ "type": "object",
1843
+ "patternProperties": {"^value_": {"$ref": "#/$defs/nested"}},
1844
+ }
1845
+
1846
+ with pytest.raises(ValueError, match="must be a local JSON Pointer"):
1847
+ json_schema_to_model(schema)
ts/packages/core/src/types/tool.types.ts
+1
-1
@@ -139,7 +139,7 @@ const ParametersSchema = z.preprocess(
139
oneOf: z.array(JSONSchemaPropertySchema).optional(),
140
allOf: z.array(JSONSchemaPropertySchema).optional(),
141
not: JSONSchemaPropertySchema.optional(),
142
- properties: z.record(z.string(), JSONSchemaPropertySchema),
142
+ properties: z.record(z.string(), JSONSchemaPropertySchema).optional(),
143
required: z.array(z.string()).optional(),
144
title: z.string().optional(),
145
default: z.unknown().optional(),
ts/packages/core/test/fixtures/json-schema-conversion/object-cases.json
+167
@@ -34,6 +34,10 @@
34
"id": "root-free-form-absent-properties",
35
"description": "A root object with no `properties` member and omitted `additionalProperties` is open.",
36
"schema": { "type": "object" },
37
+ "ingress": {
38
+ "accepted": true,
39
+ "preserved": { "type": "object" }
40
+ },
41
"instances": [
42
{
43
"input": { "anything": { "a": 1 }, "other": "x" },
@@ -348,6 +352,169 @@
352
}
353
]
354
},
355
+ {
356
+ "id": "empty-schema-additional-properties",
357
+ "description": "An empty schema accepts every unmatched value without coercing or discarding it.",
358
+ "schema": {
359
+ "type": "object",
360
+ "properties": { "name": { "type": "string" } },
361
+ "additionalProperties": {}
362
+ },
363
+ "instances": [
364
+ {
365
+ "input": { "name": "a", "count": 1, "metadata": { "active": true } },
366
+ "accepted": true,
367
+ "zod": {
368
+ "output": { "name": "a", "count": 1, "metadata": { "active": true } }
369
+ },
370
+ "effect": {
371
+ "output": { "name": "a", "count": 1, "metadata": { "active": true } }
372
+ },
373
+ "python": {
374
+ "output": { "name": "a", "count": 1, "metadata": { "active": true } }
375
+ }
376
+ }
377
+ ]
378
+ },
379
+ {
380
+ "id": "pattern-property-enum",
381
+ "description": "A matching dynamic key must satisfy an enum-only schema with no explicit type.",
382
+ "schema": {
383
+ "type": "object",
384
+ "patternProperties": { "^status_": { "enum": ["ready", "done"] } }
385
+ },
386
+ "instances": [
387
+ {
388
+ "input": { "status_job": "ready" },
389
+ "accepted": true,
390
+ "zod": { "output": { "status_job": "ready" } },
391
+ "effect": { "output": { "status_job": "ready" } },
392
+ "python": { "output": { "status_job": "ready" } }
393
+ },
394
+ {
395
+ "input": { "status_job": "blocked" },
396
+ "accepted": false
397
+ }
398
+ ]
399
+ },
400
+ {
401
+ "id": "pattern-property-strict-nested-array",
402
+ "description": "Nested container values are validated without coercing strings into integers.",
403
+ "schema": {
404
+ "type": "object",
405
+ "patternProperties": {
406
+ "^batch_": {
407
+ "type": "object",
408
+ "properties": {
409
+ "values": { "type": "array", "items": { "type": "integer" } }
410
+ },
411
+ "required": ["values"],
412
+ "additionalProperties": false
413
+ }
414
+ }
415
+ },
416
+ "instances": [
417
+ {
418
+ "input": { "batch_a": { "values": [1, 2] } },
419
+ "accepted": true,
420
+ "zod": { "output": { "batch_a": { "values": [1, 2] } } },
421
+ "effect": { "output": { "batch_a": { "values": [1, 2] } } },
422
+ "python": { "output": { "batch_a": { "values": [1, 2] } } }
423
+ },
424
+ {
425
+ "input": { "batch_a": { "values": ["1"] } },
426
+ "accepted": false
427
+ }
428
+ ]
429
+ },
430
+ {
431
+ "id": "false-pattern-property-schema",
432
+ "description": "A boolean-false pattern schema rejects every value for matching keys.",
433
+ "schema": {
434
+ "type": "object",
435
+ "patternProperties": { "^forbidden$": false }
436
+ },
437
+ "instances": [
438
+ {
439
+ "input": { "other": 1 },
440
+ "accepted": true,
441
+ "zod": { "output": { "other": 1 } },
442
+ "effect": { "output": { "other": 1 } },
443
+ "python": { "output": { "other": 1 } }
444
+ },
445
+ {
446
+ "input": { "forbidden": null },
447
+ "accepted": false
448
+ }
449
+ ]
450
+ },
451
+ {
452
+ "id": "pattern-property-type-union",
453
+ "description": "A list-valued type accepts only the listed JSON instance types.",
454
+ "schema": {
455
+ "type": "object",
456
+ "patternProperties": { "^value_": { "type": ["string", "null"] } }
457
+ },
458
+ "instances": [
459
+ {
460
+ "input": { "value_a": "text", "value_b": null },
461
+ "accepted": true,
462
+ "zod": { "output": { "value_a": "text", "value_b": null } },
463
+ "effect": { "output": { "value_a": "text", "value_b": null } },
464
+ "python": { "output": { "value_a": "text", "value_b": null } }
465
+ },
466
+ {
467
+ "input": { "value_a": 1 },
468
+ "accepted": false
469
+ }
470
+ ]
471
+ },
472
+ {
473
+ "id": "pattern-property-json-integer",
474
+ "description": "A mathematically integral JSON number satisfies the integer type even when decoded as a float.",
475
+ "schema": {
476
+ "type": "object",
477
+ "patternProperties": { "^count_": { "type": "integer" } }
478
+ },
479
+ "instances": [
480
+ {
481
+ "input": { "count_a": 1.0 },
482
+ "accepted": true,
483
+ "zod": { "output": { "count_a": 1.0 } },
484
+ "effect": { "output": { "count_a": 1.0 } },
485
+ "python": { "output": { "count_a": 1.0 } }
486
+ },
487
+ {
488
+ "input": { "count_a": 1.5 },
489
+ "accepted": false
490
+ }
491
+ ]
492
+ },
493
+ {
494
+ "id": "pattern-property-composed-const-exclusion",
495
+ "description": "Composed dynamic-key schemas retain const and not semantics.",
496
+ "schema": {
497
+ "type": "object",
498
+ "patternProperties": {
499
+ "^label_": {
500
+ "allOf": [{ "type": "string" }, { "not": { "const": "blocked" } }]
501
+ }
502
+ }
503
+ },
504
+ "instances": [
505
+ {
506
+ "input": { "label_job": "ready" },
507
+ "accepted": true,
508
+ "zod": { "output": { "label_job": "ready" } },
509
+ "effect": { "output": { "label_job": "ready" } },
510
+ "python": { "output": { "label_job": "ready" } }
511
+ },
512
+ {
513
+ "input": { "label_job": "blocked" },
514
+ "accepted": false
515
+ }
516
+ ]
517
+ },
518
{
519
"id": "pattern-property-default-materialization",
520
"description": "Composio divergence: Zod and Pydantic materialize `default` inside a matching pattern schema, while Effect decoding is validation-only and returns the input unchanged.",
ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.registration.test.ts
+25
@@ -133,6 +133,31 @@ describe('ClaudeAgentSDKProvider registration boundary', () => {
133
expect(executeToolFn).not.toHaveBeenCalled();
134
});
135
136
+ it('preserves schema-valued additionalProperties through MCP registration', async () => {
137
+ const { inputSchema, executeToolFn, call } = await registerTool(
138
+ buildTool({
139
+ type: 'object',
140
+ properties: { name: { type: 'string' } },
141
+ additionalProperties: { type: 'number' },
142
+ })
143
+ );
144
+
145
+ expect(inputSchema.additionalProperties).toEqual({ type: 'number' });
146
+
147
+ const accepted = await call({ name: 'report', count: 2 });
148
+ expect(accepted.isError ?? false).toBe(false);
149
+ expect(executeToolFn).toHaveBeenCalledWith(
150
+ 'TEST_TOOL',
151
+ expect.objectContaining({ name: 'report', count: 2 })
152
+ );
153
+
154
+ executeToolFn.mockClear();
155
+
156
+ const rejected = await call({ name: 'report', count: 'two' });
157
+ expect(rejected.isError).toBe(true);
158
+ expect(executeToolFn).not.toHaveBeenCalled();
159
+ });
160
+
161
it('keeps a tool with no input parameters closed', async () => {
162
const { inputSchema, executeToolFn, call } = await registerTool(buildTool(undefined));
163
uv.lock
+16
-14
@@ -719,6 +719,7 @@ source = { editable = "python" }
719
dependencies = [
720
{ name = "composio-client" },
721
{ name = "json-schema-to-pydantic" },
722
+ { name = "jsonschema" },
723
{ name = "openai" },
724
{ name = "pydantic" },
725
{ name = "pysher" },
@@ -746,6 +747,7 @@ dev = [
747
requires-dist = [
748
{ name = "composio-client", specifier = "==1.43.0" },
749
{ name = "json-schema-to-pydantic", specifier = ">=0.4.11" },
750
+ { name = "jsonschema", specifier = ">=4.23.0" },
751
{ name = "openai", specifier = ">=2.48.0" },
752
{ name = "pydantic", specifier = ">=2.11.9" },
753
{ name = "pysher", specifier = ">=1.0.8" },
@@ -1139,7 +1141,7 @@ name = "exceptiongroup"
1141
version = "1.3.1"
1142
source = { registry = "https://pypi.org/simple" }
1143
dependencies = [
1142
- { name = "typing-extensions" },
1144
+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },
1145
]
1146
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" }
1147
wheels = [
@@ -1905,7 +1907,7 @@ name = "importlib-metadata"
1907
version = "9.0.0"
1908
source = { registry = "https://pypi.org/simple" }
1909
dependencies = [
1908
- { name = "zipp" },
1910
+ { name = "zipp", marker = "python_full_version < '3.12'" },
1911
]
1912
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" }
1913
wheels = [
@@ -3170,11 +3172,11 @@ resolution-markers = [
3172
"python_full_version < '3.11'",
3173
]
3174
dependencies = [
3173
- { name = "flatbuffers" },
3174
- { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } },
3175
- { name = "packaging" },
3176
- { name = "protobuf" },
3177
- { name = "sympy" },
3175
+ { name = "flatbuffers", marker = "python_full_version < '3.11'" },
3176
+ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
3177
+ { name = "packaging", marker = "python_full_version < '3.11'" },
3178
+ { name = "protobuf", marker = "python_full_version < '3.11'" },
3179
+ { name = "sympy", marker = "python_full_version < '3.11'" },
3180
]
3181
wheels = [
3182
{ 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 = [
3218
"python_full_version == '3.11.*'",
3219
]
3220
dependencies = [
3219
- { name = "flatbuffers" },
3220
- { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
3221
+ { name = "flatbuffers", marker = "python_full_version >= '3.11'" },
3222
+ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },
3223
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
3222
- { name = "packaging" },
3223
- { name = "protobuf" },
3224
+ { name = "packaging", marker = "python_full_version >= '3.11'" },
3225
+ { name = "protobuf", marker = "python_full_version >= '3.11'" },
3226
]
3227
wheels = [
3228
{ 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"
5112
version = "3.5.0"
5113
source = { registry = "https://pypi.org/simple" }
5114
dependencies = [
5113
- { name = "cryptography" },
5114
- { name = "jeepney" },
5115
+ { name = "cryptography", marker = "python_full_version < '3.13' or sys_platform != 'win32'" },
5116
+ { name = "jeepney", marker = "python_full_version < '3.13' or sys_platform != 'win32'" },
5117
]
5118
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" }
5119
wheels = [
@@ -5185,7 +5187,7 @@ name = "sympy"
5187
version = "1.14.0"
5188
source = { registry = "https://pypi.org/simple" }
5189
dependencies = [
5188
- { name = "mpmath" },
5190
+ { name = "mpmath", marker = "python_full_version < '3.11'" },
5191
]
5192
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" }
5193
wheels = [