Skip to content

Add ValidationOptions for lenient output schema validation - #1260

Closed
lorenss-m wants to merge 3 commits into
modelcontextprotocol:mainfrom
hud-evals:pr/validation-options
Closed

Add ValidationOptions for lenient output schema validation#1260
lorenss-m wants to merge 3 commits into
modelcontextprotocol:mainfrom
hud-evals:pr/validation-options

Conversation

@lorenss-m

Copy link
Copy Markdown
Contributor

Motivation and Context

Currently, MCP clients raise RuntimeError when tools don't return structured content matching their outputSchema. This breaks integrations with servers that have schema/implementation mismatches.

This PR adds optional lenient validation that converts these errors to warnings, allowing clients to continue operating with imperfect servers.

How Has This Been Tested?

  • Added test suite in tests/client/test_validation_options.py
  • All existing tests pass
  • Tested with real MCP servers exhibiting validation issues

Breaking Changes

None. Default behavior unchanged. Lenient validation is opt-in:

frommcp.client.sessionimportValidationOptions# Opt-in to lenient validationoptions=ValidationOptions(strict_output_validation=False)
session=ClientSession(read, write, validation_options=options)

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

  • Added ValidationOptions class following existing patterns (e.g., TransportSecuritySettings)
  • Modified ClientSession.call_tool() to check options before raising validation errors
  • Fixed workspace config issue with structured_output_lowlevel.py by creating proper package structure

@lorenss-m
lorenss-m requested review from a team and dsp-antAugust 10, 2025 21:22
@lorenss-m
lorenss-mforce-pushed the pr/validation-options branch 5 times, most recently from 26c6806 to 7722e38CompareAugust 10, 2025 22:05

@ochafikochafik left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hi @lorenss-m, thanks for sending this!

Seems reasonable to add this option given the spec only says clients "should" validate structured results against the output schema.

I'm curious tho, which examples of non-conforming outputs did you find / how bad were they?

cc/ @bhosmer-ant since authored initial support in #993

Comment threadsrc/mcp/client/session.py Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What error would None produce here, do we need the two branches?

Comment threadsrc/mcp/client/session.py Outdated
Comment threadsrc/mcp/client/session.py Outdated
Comment threadsrc/mcp/client/session.py Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Let's not introduce parameters that are BaseModel's please. The best experience is usually to have flat parameters.

@lorenss-m
lorenss-mforce-pushed the pr/validation-options branch from 82db20c to 9a8592eCompareAugust 26, 2025 08:50
@lorenss-mlorenss-m reopened this Aug 26, 2025
@lorenss-m
lorenss-m requested review from a team and pcarletonAugust 26, 2025 08:57
@lorenss-m

Copy link
Copy Markdown
ContributorAuthor

Added the validate_structured_outputs suggestion!

@dsp-ant

Copy link
Copy Markdown
Member

We should make sure that this matches how other SDKs behave before we merge this. @modelcontextprotocol/sdk-maintainers .

@jba

jba commented Sep 1, 2025

Copy link
Copy Markdown

In the Go SDK, currently all schema validation is done on the server side.

@mikekistler

Copy link
Copy Markdown

The C# SDK delegates the validation of the structured content to the MCP Host. This is mainly because there is no standard, built-in JSON Schema validator in .NET, so doing this in the client would require pulling in an external package, one of potentially several, which adds bulk to the SDK and usurps the MCP Host's choce of validation package.

@lorenss-m

Copy link
Copy Markdown
ContributorAuthor

Anything else we should change here? Would love to get this rolled out, our library is forced to depend on our fork otherwise!

@felixweinbergerfelixweinberger left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks like there isn't necessarily a single approach across SDKs. Go does server-side validation, C# delegates it to the host, with neither currently doing any validation within the client.

This PR allows optionally disabling client side validation specifically in Python, which thus seems like it would enable behaviors like in Go & C# at least (no client side validation).

Also matches the spec as pointed out by @ochafik above, so this seems OK to me to merge.

However, left some comments - especially the change to auth seems unintentional.

def construct_redirect_uri(redirect_uri_base: str, **params: str | None) -> str:
parsed_uri = urlparse(redirect_uri_base)
query_params = [(k, v) for k, vs in parse_qs(parsed_uri.query) for v in vs]
query_params = [(k, v) for k, vs in parse_qs(parsed_uri.query).items() for v in vs]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

intentional? seems unrelated

f"Invalid structured content returned by tool {name}: {e}. Continuing without validation."
)
except SchemaError as e:
# Schema errors are always raised - they indicate a problem with the schema itself

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: remove redundant comment

Comment on lines 327 to +329
if output_schema is not None:
if result.structuredContent is None:
raise RuntimeError(f"Tool {name} has an output schema but did not return structured content")
try:
validate(result.structuredContent, output_schema)
except ValidationError as e:
raise RuntimeError(f"Invalid structured content returned by tool {name}: {e}")
except SchemaError as e:
raise RuntimeError(f"Invalid schema for tool {name}: {e}")
if self._validate_structured_outputs:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: getting quite heavily nested here, could at least partially simplify with

if output_schema is None:
return
if result.structuredContent is None:
# raise / log depending
# handle the base case of try / except with raise / log depending

@felixweinbergerfelixweinberger added needs more work Not ready to be merged yet, needs additional follow-up from the author(s). improves spec compliance When a change improves ability of SDK users to comply with spec definition needs more eyes labels Sep 23, 2025
@felixweinberger

Copy link
Copy Markdown
Contributor

Hi @lorenss-m are you planning to come back to this one?

@felixweinberger

Copy link
Copy Markdown
Contributor

Closing this for now due to inactivity.

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

Labels

improves spec complianceWhen a change improves ability of SDK users to comply with spec definitionneeds more workNot ready to be merged yet, needs additional follow-up from the author(s).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants

@lorenss-m@dsp-ant@jba@mikekistler@felixweinberger@ochafik@Kludex