Skip to content

fix(mcp): keep oneOf exclusivity when converting schemas - #399

Open
SajjadPSavoji wants to merge 6 commits into
Eigenwise:mainfrom
SajjadPSavoji:fix-368-mcp-oneof-branches-lose
Open

SajjadPSavoji wants to merge 6 commits into
Eigenwise:mainfrom
SajjadPSavoji:fix-368-mcp-oneof-branches-lose

Conversation

@SajjadPSavoji

Copy link
Copy Markdown

oneOf was converted to a plain Pydantic Union, so a value matching more than one branch (like 1 against integer and number) was accepted by the model and by the schema sent to the model. Now json_to_pydantic_field sends a multi-branch oneOf through a new SchemaTransformer._one_of_type helper. It keeps the Union and adds a BeforeValidator that counts how many original branches the JSON form of the value matches and rejects anything but exactly one. It uses the same $ref-tolerant validator as the enum/const path. A small annotation also emits oneOf instead of anyOf in the model JSON schema. anyOf is untouched, and since this is the shared converter it covers array items, $ref targets, optional fields and both MCPFactory input and output schemas.

I added tests/connectors/mcp/test_oneof_exclusivity.py, which compares the generated model and its emitted schema against Draft202012Validator for the cases in the issue plus optional, anyOf and $ref cases. I also updated two assertions in test_schema_transformer.py for the new Annotated type. The new file fails before the change and passes after, and the whole atomic-agents/tests/connectors/mcp folder passes. I didn't run the full suite.

Fixes #368

@Eigenwise Eigenwise left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for picking up #368. The exclusivity check does what the issue asks for the cases in the tests: 1 against integer | number is rejected and 1.5 passes. Three things before it can merge.

1. Branch patterns run through Python re. The branch check validates each original branch with jsonschema, which evaluates pattern with re.search. MCP schemas come from the server, and #363 (merged now) moved pattern handling off that path for this reason.

  • {"oneOf": [{"type": "string", "pattern": "^(a+)+$"}, {"type": "integer"}]} with the value "a" * 27 + "!" takes 2.7 s here, and the time doubles with every extra character. On main the same value returns instantly.
  • With "pattern": "^\\p{L}+$" in a branch, validating "abc" raises re.PatternError: bad escape \p, which is not a ValidationError, so it escapes the model.

Please don't evaluate pattern with re in the branch check. After rebasing on #363 you can reuse its pattern handling, including the fallback for patterns the engine doesn't support.

2. Duplicate branches disagree with the advertised schema. {"oneOf": [{"type": "integer"}, {"type": "integer"}]} advertises plain {"type": "integer"}, because the Union collapses and there is no anyOf left to rename. Validation then rejects every integer with "matches 2 oneOf branches". The schema sent to the model and the validator should agree, whichever way you decide it.

3. Rebase. #335 and #363 both changed schema_transformer.py and are on main now.

@SajjadPSavoji

Copy link
Copy Markdown
Author

branch patterns now go through the same Pydantic regex adapter as #363, and unsupported ones are skipped like there. For duplicates I kept JSON Schema semantics, so repeated branches stay separate in the Union and in the advertised oneOf. Both sides now reject 1 for integer | integer. The branch was already merged with main so #335 and #363 are in

@Solaris-star

Copy link
Copy Markdown
Contributor

Two follow-ups on 03fba5c from an AI-assisted offline check:

Nullable oneOf breaks schema generation. This succeeds on base 6a5e19e but raises KeyError: 'schema' here:

from atomic_agents.connectors.mcp import SchemaTransformer

schema = {
    "type": "object",
    "properties": {
        "value": {"oneOf": [{"type": "null"}, {"type": "string"}]}
    },
    "required": ["value"],
}
model = SchemaTransformer.create_model_from_schema(schema, "NullableInput", "nullable")
model.model_json_schema()

Pydantic optimizes this to a nullable core schema, so _OneOfJsonSchema never reaches a union and eventually indexes schema on the inner scalar. Reversing the branches and substituting integer gives the same failure. All four input schemas pass Draft202012Validator.check_schema; the equivalent anyOf control works. Value validation itself succeeds. Your 21 oneOf tests still pass (Python 3.12.14 / Pydantic 2.12.4).

The regex review has another path: overriding pattern does not intercept patternProperties or additionalProperties's find_additional_properties helper. Both still reach Python re.search; I confirmed this with short ASCII inputs, not a stress test. No hosted model or MCP server was contacted, and this is not a full-suite or human-approval claim.

@SajjadPSavoji

Copy link
Copy Markdown
Author

the nullable oneOf crash and the patternProperties/additionalProperties regex path are both fixed in 908c01d, with tests for each

Copy link
Copy Markdown
Contributor

Thanks, I independently rechecked current head 373d6a9 (which includes 908c01d). My four original nullable cases (null/string and null/integer, both branch orders) now generate schemas successfully, and null/non-null values agree with the emitted schemas. Short-ASCII patternProperties and additionalProperties acceptance/rejection probes also pass with Python re.search patched to raise, so those paths did not reach it.

The MCP test directory passed locally: 721 tests, Python 3.13.5 / Pydantic 2.14.3. This closes the two findings from my earlier comment, within these checks. AI-assisted verification, not a full-suite result or human approval; no hosted model or MCP server was contacted.

@Eigenwise Eigenwise left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for sticking with this through several rounds. I owe you a straight answer on where it stands, and part of the problem is my own earlier guidance.

The goal is right. A tool's schema is its contract, and on main a oneOf of two object shapes accepts an object that matches neither. That should be rejected locally, before the tool is called.

What I'm not happy with is how the check is built, and that's on me: when I asked for regex safety on the jsonschema path in an earlier round, I pushed this further into running a second validator next to Pydantic. Concretely, with this branch and a property like

{"oneOf": [
  {"type": "object", "properties": {"kind": {"const": "file"}, "path": {"type": "string"}}, "required": ["kind", "path"]},
  {"type": "object", "properties": {"kind": {"const": "url"}, "url": {"type": "string"}}, "required": ["kind", "url"]}
]}
  • the schema the model is shown is {"oneOf": [{"additionalProperties": true, "type": "object"}, {"additionalProperties": true, "type": "object"}]}, so it can't see either variant's fields;
  • a wrong value is rejected with "Value matches 0 oneOf branches", from a jsonschema validator inside a closure, which doesn't tell the model (or someone with a debugger) what was missing;
  • _OneOfJsonSchema walks Pydantic's core schema ("choices", generate_inner) to print oneOf, which ties us to internals.

On #340's branch, without this change, the same schema becomes a union of two real nested models. The model is shown both variants with their fields, and the wrong value is rejected by Pydantic itself with an ordinary missing-field error. That is how this project wants contracts expressed: in the models, with nothing hidden.

So here's what I'd like, and I'm happy to do the integration work with you:

  1. #340 goes in first (I'm finishing it; its author has gone quiet). After that, object variants are covered without any of this.
  2. This PR then only needs what a union of models can't express: a value that matches more than one branch, like 1 against [integer, number]. Please count matches with the branch types that are already converted, instead of a second jsonschema pass. If that turns out not to work for some case, say which one and we'll look at it together.
  3. Drop _OneOfJsonSchema, and with the jsonschema pass gone, the custom pattern, patternProperties and additionalProperties keywords go too.
  4. _pattern_adapter is worth keeping on its own: the existing enum check at model construction still sends server patterns to Python's re, and it should use your helper. That can be a separate small PR if you prefer.

This branch also conflicts with main now (#389 landed in the same file). No need to rebase until #340 is in; I'll ping you here.

@SajjadPSavoji

Copy link
Copy Markdown
Author

makes sense. I'll leave the branch as it is until #340 is in, then count matches with the converted branch types and drop the jsonschema pass and _OneOfJsonSchema

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP oneOf branches lose exclusivity during schema conversion

3 participants