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: fail closed on invalid dynamic schemas

jkomyno3fef432dc0bd
diff --git a/.changeset/claude-agent-sdk-complete-schema-registration.md b/.changeset/claude-agent-sdk-complete-schema-registration.md
index e63f07eb7..02225446f 100644
--- a/.changeset/claude-agent-sdk-complete-schema-registration.md
+++ b/.changeset/claude-agent-sdk-complete-schema-registration.md
@@ -19,7 +19,7 @@ An undeclared argument no longer passes silently.
{ to: '[email protected]', hallucinated: 'value' }
// before: `hallucinated` was stripped, and the tool ran with { to: '...' }
-// now: the call is rejected with an MCP invalid-params error (-32602)
+// now: the caller receives an error result, and the tool does not run
```
Tools with no input parameters behave the same way. They stay closed and reject every argument.
diff --git a/python/composio/utils/schema_converter.py b/python/composio/utils/schema_converter.py
index b01e7c05d..3e954054f 100644
--- a/python/composio/utils/schema_converter.py
+++ b/python/composio/utils/schema_converter.py
@@ -477,6 +477,66 @@ def _compile_object_policy(
)
+def _validate_dynamic_object_policies(
+ schema: t.Any,
+ root_schema: t.Dict[str, t.Any],
+ visited: t.Optional[t.Set[int]] = None,
+) -> None:
+ """Compile every reachable dynamic object policy before conversion fallback."""
+ if visited is None:
+ visited = set()
+ if isinstance(schema, list):
+ for item in schema:
+ _validate_dynamic_object_policies(item, root_schema, visited)
+ return
+ if not isinstance(schema, dict) or id(schema) in visited:
+ return
+ visited.add(id(schema))
+
+ if schema.get("patternProperties") or isinstance(
+ schema.get("additionalProperties"), dict
+ ):
+ _compile_object_policy(schema, root_schema)
+
+ reference = schema.get("$ref")
+ if isinstance(reference, str) and (reference == "#" or reference.startswith("#/")):
+ try:
+ resolved = _resolve_local_json_pointer(reference, root_schema)
+ except ValueError:
+ # Ordinary references retain the converter's legacy fallback.
+ # References used by dynamic-key constraints are rejected by
+ # `_compile_object_policy` above.
+ resolved = None
+ if isinstance(resolved, (dict, list)):
+ _validate_dynamic_object_policies(resolved, root_schema, visited)
+
+ for keyword in ("properties", "patternProperties"):
+ values = schema.get(keyword)
+ if isinstance(values, dict):
+ for child in values.values():
+ _validate_dynamic_object_policies(child, root_schema, visited)
+
+ for keyword in _SCHEMA_VALUED_KEYWORDS:
+ child = schema.get(keyword)
+ if isinstance(child, (dict, list)):
+ _validate_dynamic_object_policies(child, root_schema, visited)
+
+ for keyword in _SCHEMA_LIST_KEYWORDS:
+ children = schema.get(keyword)
+ if isinstance(children, list):
+ _validate_dynamic_object_policies(children, root_schema, visited)
+
+ items = schema.get("items")
+ if isinstance(items, (dict, list)):
+ _validate_dynamic_object_policies(items, root_schema, visited)
+
+ dependencies = schema.get("dependencies")
+ if isinstance(dependencies, dict):
+ for child in dependencies.values():
+ if isinstance(child, (dict, bool)):
+ _validate_dynamic_object_policies(child, root_schema, visited)
+
+
class _DynamicObjectModel(BaseModel):
"""Base for object models that must police and preserve dynamic keys.
@@ -611,6 +671,7 @@ def json_schema_to_pydantic_type(
filtered_schema = _filter_boolean_schemas(json_schema)
filtered_schema = _resolve_unsatisfiable_references(filtered_schema)
document_root = root_schema if root_schema is not None else json_schema
+ _validate_dynamic_object_policies(json_schema, document_root)
return _filtered_schema_to_pydantic_type(
filtered_schema,
root_schema=document_root,
@@ -724,6 +785,57 @@ def _convert_with_library(
root_schema: t.Optional[t.Dict[str, t.Any]] = None,
) -> t.Union[t.Type, t.Any]:
"""Use json-schema-to-pydantic for complex schema conversion."""
+ # Dynamic-key policy compilation is an acceptance boundary, so it must run
+ # outside the legacy library-conversion fallback below. Invalid patterns or
+ # references must fail closed instead of silently changing the field to str.
+ if schema.get("type") == "object":
+ if _contains_unsatisfiable_schema(schema.get("properties", {})):
+ try:
+ return _convert_object_with_unsatisfiable_properties(
+ schema,
+ root_schema=root_schema,
+ )
+ except (SchemaError, CombinerError) as e:
+ logger.debug(
+ f"Library schema conversion failed: {e}, falling back to string"
+ )
+ return str
+ except Exception as e:
+ logger.debug(
+ f"Unexpected error in schema conversion: {e}, falling back to string"
+ )
+ return str
+ # A property-less object with no dynamic-key constraints accepts and
+ # preserves arbitrary content. Modelling it as an empty Pydantic
+ # model instead silently discarded every key (issue #4064).
+ if object_is_open(schema) and not schema.get("patternProperties"):
+ return t.cast(t.Type, t.Dict[str, t.Any])
+ if "title" not in schema:
+ schema = {**schema, "title": "GeneratedModel"}
+
+ try:
+ base_model = create_model_from_schema(
+ schema,
+ allow_undefined_array_items=True,
+ allow_undefined_type=True,
+ )
+ except (SchemaError, CombinerError) as e:
+ logger.debug(
+ f"Library schema conversion failed: {e}, falling back to string"
+ )
+ return str
+ except Exception as e:
+ logger.debug(
+ f"Unexpected error in schema conversion: {e}, falling back to string"
+ )
+ return str
+
+ return apply_object_policy(
+ schema,
+ base_model,
+ root_schema=root_schema,
+ )
+
try:
# Handle top-level combiner without type (e.g., {"anyOf": [...]})
if (
@@ -732,30 +844,6 @@ def _convert_with_library(
):
return _handle_toplevel_combiner(schema, root_schema=root_schema)
- # For object schemas, create model directly
- if schema.get("type") == "object":
- if _contains_unsatisfiable_schema(schema.get("properties", {})):
- return _convert_object_with_unsatisfiable_properties(
- schema,
- root_schema=root_schema,
- )
- # A property-less object with no dynamic-key constraints accepts and
- # preserves arbitrary content. Modelling it as an empty Pydantic
- # model instead silently discarded every key (issue #4064).
- if object_is_open(schema) and not schema.get("patternProperties"):
- return t.cast(t.Type, t.Dict[str, t.Any])
- if "title" not in schema:
- schema = {**schema, "title": "GeneratedModel"}
- return apply_object_policy(
- schema,
- create_model_from_schema(
- schema,
- allow_undefined_array_items=True,
- allow_undefined_type=True,
- ),
- root_schema=root_schema,
- )
-
# For array schemas
if schema.get("type") == "array":
items = schema.get("items")
diff --git a/python/tests/fixtures/json-schema-conversion/object-cases.json b/python/tests/fixtures/json-schema-conversion/object-cases.json
index c3a6b8ac1..aba143e21 100644
--- a/python/tests/fixtures/json-schema-conversion/object-cases.json
+++ b/python/tests/fixtures/json-schema-conversion/object-cases.json
@@ -176,6 +176,7 @@
{
"id": "named-properties-with-pattern-properties",
"description": "With named `properties` plus `patternProperties` and omitted `additionalProperties`, pattern-matching keys are admitted and validated while other unknown keys stay rejected.",
+ "divergesFromJsonSchema": "JSON Schema treats omitted `additionalProperties` as permissive; Composio tool inputs keep it strict.",
"schema": {
"type": "object",
"properties": { "name": { "type": "string" } },
diff --git a/python/tests/test_schema_converter.py b/python/tests/test_schema_converter.py
index cba165526..817a4434f 100644
--- a/python/tests/test_schema_converter.py
+++ b/python/tests/test_schema_converter.py
@@ -197,6 +197,59 @@ def test_schema_converter_required_unsatisfiable_property_has_no_valid_value():
model(impossible=impossible_value)
+ "invalid_object_schema,error_match",
+ [
+ (
+ {
+ "type": "object",
+ "patternProperties": {
+ "^value_": {"$ref": "https://example.com/schema.json"}
+ },
+ },
+ "must be a local JSON Pointer",
+ ),
+ (
+ {
+ "type": "object",
+ "patternProperties": {"^value_": {"$ref": "#/$defs/missing"}},
+ },
+ "Unresolvable dynamic-key schema reference",
+ ),
+ (
+ {
+ "type": "object",
+ "patternProperties": {"[": {"type": "string"}},
+ },
+ "Invalid patternProperties regular expression",
+ ),
+ ],
+ ids=["external-ref", "missing-local-ref", "invalid-pattern"],
+)
+ "converter",
+ [json_schema_to_model, json_schema_to_pydantic_type],
+ ids=["model", "pydantic-type"],
+)
[email protected]("nested", [False, True], ids=["root", "nested"])
+def test_invalid_dynamic_object_schema_fails_closed_across_public_entry_points(
+ invalid_object_schema,
+ error_match,
+ converter,
+ nested,
+):
+ schema = invalid_object_schema
+ if nested:
+ schema = {
+ "type": "object",
+ "properties": {"payload": invalid_object_schema},
+ "required": ["payload"],
+ }
+
+ with pytest.raises(ValueError, match=error_match):
+ converter(schema)
+
+
@pytest.mark.parametrize(
"case,index",
[
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 c3a6b8ac1..aba143e21 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
@@ -176,6 +176,7 @@
{
"id": "named-properties-with-pattern-properties",
"description": "With named `properties` plus `patternProperties` and omitted `additionalProperties`, pattern-matching keys are admitted and validated while other unknown keys stay rejected.",
+ "divergesFromJsonSchema": "JSON Schema treats omitted `additionalProperties` as permissive; Composio tool inputs keep it strict.",
"schema": {
"type": "object",
"properties": { "name": { "type": "string" } },
diff --git a/ts/packages/core/test/utils/jsonSchema.test.ts b/ts/packages/core/test/utils/jsonSchema.test.ts
index 438e864ef..029bc2dd2 100644
--- a/ts/packages/core/test/utils/jsonSchema.test.ts
+++ b/ts/packages/core/test/utils/jsonSchema.test.ts
@@ -643,6 +643,14 @@ describe('shared corpus invariants', () => {
expect(() => assertCorpusInvariants(loadObjectCases())).not.toThrow();
});
+ it('documents the patternProperties strictness divergence from JSON Schema', () => {
+ const testCase = loadObjectCases().find(
+ ({ id }) => id === 'named-properties-with-pattern-properties'
+ );
+
+ expect(testCase?.divergesFromJsonSchema).toContain('omitted `additionalProperties`');
+ });
+
it('rejects duplicate case ids', () => {
expect(() => assertCorpusInvariants([baseCase('dup'), baseCase('dup')])).toThrow(
'Duplicate corpus case id: dup'