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: fail closed on invalid dynamic schemas
jkomyno committed
Aug 7, 2026 at 21:03 UTC
3fef432dc0bd751448e267391935e5ce95873a6b
6 files changed
+176
-25
.changeset/claude-agent-sdk-complete-schema-registration.md
+1
-1
@@ -19,7 +19,7 @@ An undeclared argument no longer passes silently.
19
{ to: 'someone@example.com', hallucinated: 'value' }
20
21
// before: `hallucinated` was stripped, and the tool ran with { to: '...' }
22
-// now: the call is rejected with an MCP invalid-params error (-32602)
22
+// now: the caller receives an error result, and the tool does not run
23
```
24
25
Tools with no input parameters behave the same way. They stay closed and reject every argument.
python/composio/utils/schema_converter.py
+112
-24
@@ -477,6 +477,66 @@ def _compile_object_policy(
477
)
478
479
480
+def _validate_dynamic_object_policies(
481
+ schema: t.Any,
482
+ root_schema: t.Dict[str, t.Any],
483
+ visited: t.Optional[t.Set[int]] = None,
484
+) -> None:
485
+ """Compile every reachable dynamic object policy before conversion fallback."""
486
+ if visited is None:
487
+ visited = set()
488
+ if isinstance(schema, list):
489
+ for item in schema:
490
+ _validate_dynamic_object_policies(item, root_schema, visited)
491
+ return
492
+ if not isinstance(schema, dict) or id(schema) in visited:
493
+ return
494
+ visited.add(id(schema))
495
+
496
+ if schema.get("patternProperties") or isinstance(
497
+ schema.get("additionalProperties"), dict
498
+ ):
499
+ _compile_object_policy(schema, root_schema)
500
+
501
+ reference = schema.get("$ref")
502
+ if isinstance(reference, str) and (reference == "#" or reference.startswith("#/")):
503
+ try:
504
+ resolved = _resolve_local_json_pointer(reference, root_schema)
505
+ except ValueError:
506
+ # Ordinary references retain the converter's legacy fallback.
507
+ # References used by dynamic-key constraints are rejected by
508
+ # `_compile_object_policy` above.
509
+ resolved = None
510
+ if isinstance(resolved, (dict, list)):
511
+ _validate_dynamic_object_policies(resolved, root_schema, visited)
512
+
513
+ for keyword in ("properties", "patternProperties"):
514
+ values = schema.get(keyword)
515
+ if isinstance(values, dict):
516
+ for child in values.values():
517
+ _validate_dynamic_object_policies(child, root_schema, visited)
518
+
519
+ for keyword in _SCHEMA_VALUED_KEYWORDS:
520
+ child = schema.get(keyword)
521
+ if isinstance(child, (dict, list)):
522
+ _validate_dynamic_object_policies(child, root_schema, visited)
523
+
524
+ for keyword in _SCHEMA_LIST_KEYWORDS:
525
+ children = schema.get(keyword)
526
+ if isinstance(children, list):
527
+ _validate_dynamic_object_policies(children, root_schema, visited)
528
+
529
+ items = schema.get("items")
530
+ if isinstance(items, (dict, list)):
531
+ _validate_dynamic_object_policies(items, root_schema, visited)
532
+
533
+ dependencies = schema.get("dependencies")
534
+ if isinstance(dependencies, dict):
535
+ for child in dependencies.values():
536
+ if isinstance(child, (dict, bool)):
537
+ _validate_dynamic_object_policies(child, root_schema, visited)
538
+
539
+
540
class _DynamicObjectModel(BaseModel):
541
"""Base for object models that must police and preserve dynamic keys.
542
@@ -611,6 +671,7 @@ def json_schema_to_pydantic_type(
671
filtered_schema = _filter_boolean_schemas(json_schema)
672
filtered_schema = _resolve_unsatisfiable_references(filtered_schema)
673
document_root = root_schema if root_schema is not None else json_schema
674
+ _validate_dynamic_object_policies(json_schema, document_root)
675
return _filtered_schema_to_pydantic_type(
676
filtered_schema,
677
root_schema=document_root,
@@ -724,6 +785,57 @@ def _convert_with_library(
785
root_schema: t.Optional[t.Dict[str, t.Any]] = None,
786
) -> t.Union[t.Type, t.Any]:
787
"""Use json-schema-to-pydantic for complex schema conversion."""
788
+ # Dynamic-key policy compilation is an acceptance boundary, so it must run
789
+ # outside the legacy library-conversion fallback below. Invalid patterns or
790
+ # references must fail closed instead of silently changing the field to str.
791
+ if schema.get("type") == "object":
792
+ if _contains_unsatisfiable_schema(schema.get("properties", {})):
793
+ try:
794
+ return _convert_object_with_unsatisfiable_properties(
795
+ schema,
796
+ root_schema=root_schema,
797
+ )
798
+ except (SchemaError, CombinerError) as e:
799
+ logger.debug(
800
+ f"Library schema conversion failed: {e}, falling back to string"
801
+ )
802
+ return str
803
+ except Exception as e:
804
+ logger.debug(
805
+ f"Unexpected error in schema conversion: {e}, falling back to string"
806
+ )
807
+ return str
808
+ # A property-less object with no dynamic-key constraints accepts and
809
+ # preserves arbitrary content. Modelling it as an empty Pydantic
810
+ # model instead silently discarded every key (issue #4064).
811
+ if object_is_open(schema) and not schema.get("patternProperties"):
812
+ return t.cast(t.Type, t.Dict[str, t.Any])
813
+ if "title" not in schema:
814
+ schema = {**schema, "title": "GeneratedModel"}
815
+
816
+ try:
817
+ base_model = create_model_from_schema(
818
+ schema,
819
+ allow_undefined_array_items=True,
820
+ allow_undefined_type=True,
821
+ )
822
+ except (SchemaError, CombinerError) as e:
823
+ logger.debug(
824
+ f"Library schema conversion failed: {e}, falling back to string"
825
+ )
826
+ return str
827
+ except Exception as e:
828
+ logger.debug(
829
+ f"Unexpected error in schema conversion: {e}, falling back to string"
830
+ )
831
+ return str
832
+
833
+ return apply_object_policy(
834
+ schema,
835
+ base_model,
836
+ root_schema=root_schema,
837
+ )
838
+
839
try:
840
# Handle top-level combiner without type (e.g., {"anyOf": [...]})
841
if (
@@ -732,30 +844,6 @@ def _convert_with_library(
844
):
845
return _handle_toplevel_combiner(schema, root_schema=root_schema)
846
735
- # For object schemas, create model directly
736
- if schema.get("type") == "object":
737
- if _contains_unsatisfiable_schema(schema.get("properties", {})):
738
- return _convert_object_with_unsatisfiable_properties(
739
- schema,
740
- root_schema=root_schema,
741
- )
742
- # A property-less object with no dynamic-key constraints accepts and
743
- # preserves arbitrary content. Modelling it as an empty Pydantic
744
- # model instead silently discarded every key (issue #4064).
745
- if object_is_open(schema) and not schema.get("patternProperties"):
746
- return t.cast(t.Type, t.Dict[str, t.Any])
747
- if "title" not in schema:
748
- schema = {**schema, "title": "GeneratedModel"}
749
- return apply_object_policy(
750
- schema,
751
- create_model_from_schema(
752
- schema,
753
- allow_undefined_array_items=True,
754
- allow_undefined_type=True,
755
- ),
756
- root_schema=root_schema,
757
- )
758
-
847
# For array schemas
848
if schema.get("type") == "array":
849
items = schema.get("items")
python/tests/fixtures/json-schema-conversion/object-cases.json
+1
@@ -176,6 +176,7 @@
176
{
177
"id": "named-properties-with-pattern-properties",
178
"description": "With named `properties` plus `patternProperties` and omitted `additionalProperties`, pattern-matching keys are admitted and validated while other unknown keys stay rejected.",
179
+ "divergesFromJsonSchema": "JSON Schema treats omitted `additionalProperties` as permissive; Composio tool inputs keep it strict.",
180
"schema": {
181
"type": "object",
182
"properties": { "name": { "type": "string" } },
python/tests/test_schema_converter.py
+53
@@ -197,6 +197,59 @@ def test_schema_converter_required_unsatisfiable_property_has_no_valid_value():
197
model(impossible=impossible_value)
198
199
200
+@pytest.mark.parametrize(
201
+ "invalid_object_schema,error_match",
202
+ [
203
+ (
204
+ {
205
+ "type": "object",
206
+ "patternProperties": {
207
+ "^value_": {"$ref": "https://example.com/schema.json"}
208
+ },
209
+ },
210
+ "must be a local JSON Pointer",
211
+ ),
212
+ (
213
+ {
214
+ "type": "object",
215
+ "patternProperties": {"^value_": {"$ref": "#/$defs/missing"}},
216
+ },
217
+ "Unresolvable dynamic-key schema reference",
218
+ ),
219
+ (
220
+ {
221
+ "type": "object",
222
+ "patternProperties": {"[": {"type": "string"}},
223
+ },
224
+ "Invalid patternProperties regular expression",
225
+ ),
226
+ ],
227
+ ids=["external-ref", "missing-local-ref", "invalid-pattern"],
228
+)
229
+@pytest.mark.parametrize(
230
+ "converter",
231
+ [json_schema_to_model, json_schema_to_pydantic_type],
232
+ ids=["model", "pydantic-type"],
233
+)
234
+@pytest.mark.parametrize("nested", [False, True], ids=["root", "nested"])
235
+def test_invalid_dynamic_object_schema_fails_closed_across_public_entry_points(
236
+ invalid_object_schema,
237
+ error_match,
238
+ converter,
239
+ nested,
240
+):
241
+ schema = invalid_object_schema
242
+ if nested:
243
+ schema = {
244
+ "type": "object",
245
+ "properties": {"payload": invalid_object_schema},
246
+ "required": ["payload"],
247
+ }
248
+
249
+ with pytest.raises(ValueError, match=error_match):
250
+ converter(schema)
251
+
252
+
253
@pytest.mark.parametrize(
254
"case,index",
255
[
ts/packages/core/test/fixtures/json-schema-conversion/object-cases.json
+1
@@ -176,6 +176,7 @@
176
{
177
"id": "named-properties-with-pattern-properties",
178
"description": "With named `properties` plus `patternProperties` and omitted `additionalProperties`, pattern-matching keys are admitted and validated while other unknown keys stay rejected.",
179
+ "divergesFromJsonSchema": "JSON Schema treats omitted `additionalProperties` as permissive; Composio tool inputs keep it strict.",
180
"schema": {
181
"type": "object",
182
"properties": { "name": { "type": "string" } },
ts/packages/core/test/utils/jsonSchema.test.ts
+8
@@ -643,6 +643,14 @@ describe('shared corpus invariants', () => {
643
expect(() => assertCorpusInvariants(loadObjectCases())).not.toThrow();
644
});
645
646
+ it('documents the patternProperties strictness divergence from JSON Schema', () => {
647
+ const testCase = loadObjectCases().find(
648
+ ({ id }) => id === 'named-properties-with-pattern-properties'
649
+ );
650
+
651
+ expect(testCase?.divergesFromJsonSchema).toContain('omitted `additionalProperties`');
652
+ });
653
+
654
it('rejects duplicate case ids', () => {
655
expect(() => assertCorpusInvariants([baseCase('dup'), baseCase('dup')])).toThrow(
656
'Duplicate corpus case id: dup'