Skip to content

Conversation

lorenss-m
Copy link
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:

from mcp.client.session import ValidationOptions

# Opt-in to lenient validation
options = 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-ant August 10, 2025 21:22
@lorenss-m lorenss-m force-pushed the pr/validation-options branch 5 times, most recently from 26c6806 to 7722e38 Compare August 10, 2025 22:05
Copy link

@ochafik ochafik left a comment

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

)
else:
try:
validate(result.structuredContent, output_schema)
Copy link

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?

logger = logging.getLogger("client")


class ValidationOptions(BaseModel):
Copy link
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-m closed this Aug 26, 2025
@lorenss-m lorenss-m force-pushed the pr/validation-options branch from 82db20c to 9a8592e Compare August 26, 2025 08:50
@lorenss-m lorenss-m reopened this Aug 26, 2025
@lorenss-m lorenss-m requested review from a team and pcarleton August 26, 2025 08:57
@lorenss-m
Copy link
Contributor Author

Added the validate_structured_outputs suggestion!

@dsp-ant dsp-ant requested review from Kludex and ochafik September 1, 2025 12:34
@dsp-ant
Copy link
Member

dsp-ant commented Sep 1, 2025

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

@jba
Copy link

jba commented Sep 1, 2025

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

@mikekistler
Copy link

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
Contributor Author

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

Copy link
Contributor

@felixweinberger felixweinberger left a comment

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
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
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
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

@felixweinberger felixweinberger added needs more work Not ready to be merged yet, needs additional changes. improves spec compliance When a change improves ability of SDK users to comply with spec definition needs more eyes Needs alignment among maintainers whether this is something we want to add labels Sep 23, 2025
@felixweinberger
Copy link
Contributor

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

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

Labels

improves spec compliance When a change improves ability of SDK users to comply with spec definition needs more eyes Needs alignment among maintainers whether this is something we want to add needs more work Not ready to be merged yet, needs additional changes.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants