Skip to content

Preserve nulls required by structured output schemas - #1929

Open
mikemikimike wants to merge 65 commits into
modelcontextprotocol:mainfrom
mikemikimike:fix/structured-content-null-schema
Open

mikemikimike wants to merge 65 commits into
modelcontextprotocol:mainfrom
mikemikimike:fix/structured-content-null-schema

Conversation

@mikemikimike

Copy link
Copy Markdown

Fixes #1915

Issue: #1915

When structured tool output has an output schema and serializer options ignore null values, required nullable properties are omitted from structuredContent. Preserve explicit nulls for this serialization path so the result matches its schema while leaving ordinary text serialization unchanged.

Add regression coverage for record and class outputs with null and non-null values across the current protocol and 2025-11-25.

Validation passed: dotnet test in Debug and Release across the repository test suites; dotnet format whitespace --verify-no-changes; Windows x64 NativeAOT publish and execution; Release NuGet pack; and DocFX with warnings treated as errors. The Core suites passed 2,398 tests per net8.0/net9.0/net10.0 target (4 skipped) and 2,081 tests on net472 (294 skipped); ASP.NET Core passed 635 tests per modern target (30 skipped); Analyzer passed 57 tests.

@PederHP

PederHP commented Oct 14, 2026

Copy link
Copy Markdown
Member

Adding a data point on why this matters beyond the TypeScript 1.x client in #1915: it breaks interop with the other official SDKs' current clients, too. I hit it in a companion sample for my book. A C# server returns a positional record with nullable members (OperationStatus(string OperationId, string Kind, string Status, string? Result, string? Guidance), source), and both other SDKs' clients reject every call where one of those members is null. The repro calls the tool over stdio with an unknown ID, so Result is null:

Client Server on ModelContextProtocol 2.2.0 Same server built against this PR (519e96c)
Python mcp 2.0.0 (negotiates 2026-07-28) Invalid structured content returned by tool check_operation_status: 'result' is a required property OK, "result": null
TypeScript @modelcontextprotocol/client 2.2.0 (versionNegotiation: { mode: 'auto' }) Structured content does not match the tool's output schema: data must have required property 'result' OK, "result": null

Both clients validate structuredContent against outputSchema by default (the spec's SHOULD), while the C# client doesn't, so a C# server passes its own end-to-end tests and only fails when a Python or TypeScript client calls it. The equivalent Python (Pydantic str | None) and TypeScript (zod .nullable()) servers already put an explicit null on the wire, so with this change the three SDKs agree.

Until this ships, the per-member workaround that worked for me is [property: JsonIgnore(Condition = JsonIgnoreCondition.Never)] on the nullable record parameters.

@tarekgh tarekgh 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.

This fixes a real interoperability issue: required nullable properties must be present in structured output, and Python and TypeScript clients reject results when those properties are omitted.

I found one narrow compatibility regression with explicit output schemas, noted inline. Two related ignore-policy gaps also remain, but those predate this PR.

Copilot AI 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.

🟡 Changes recommended

Globally including nulls can invalidate previously valid explicit-schema responses whose optional properties prohibit null.

1 open finding
What changed in this PR

Addresses #1915 by preserving nulls in structured tool results to match required nullable output properties.

Changes:

  • Adds separate serializer options for schema-backed structured content, leaving text serialization unchanged.
  • Adds record and class regression tests across two protocol versions.
File Description
tests/​ModelContextProtocol.Tests/​Server/​McpServerToolTests.cs Tests nullable output properties against their schemas.
src/​ModelContextProtocol.Core/​Server/​AIFunctionMcpServerTool.cs Preserves nulls during schema-backed structured serialization.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot AI 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.

🟡 Changes recommended

The previously reported regression remains unresolved for explicit schemas whose optional properties prohibit null values.

1 open finding

🧠 Review effort: Balanced

Signed-off-by: mikemikimike <13286568797@163.com>

Copilot AI 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.

🟡 Changes recommended

Schema traversal remains incomplete, and restoration can replace actual values with null or invalidate previously valid output.

5 open issues
1 resolved since last review

Review effort: Balanced

@tarekgh

tarekgh commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

@mikemikimike thanks for last updates. Could you please look at the copilot comments and address them?

Signed-off-by: mikemikimike <13286568797@163.com>

Copilot AI 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.

Copilot AI 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.

@tarekgh tarekgh 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.

Two additional gaps reproduced against f1a39f8: source recovery can fabricate values, and dependentSchemas requirements are not collected.

@tarekgh tarekgh 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.

Three remaining issues reproduced against 0170ae6: caller-filter bypass for default-ignored values, incompatible intermediate union repairs, and missing dependentRequired handling.

Copilot AI 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.

🟡 Changes recommended

Validation converts incomplete tool results to errors and discards their content before response filters can repair them, leaving recovered results incorrectly marked as errors.

1 open issue

Review effort: Balanced

@tarekgh
tarekgh requested a balanced review from Copilot November 25, 2026 02:02

Copilot AI 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.

🟡 Changes recommended

Active issues can reject valid tool results by matching unrelated schemas and can trigger premature validation when replacement request facades reset nesting depth.

2 open issues
1 resolved since last review

Review effort: Balanced

Copilot AI 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.

🔵 Needs a closer look

Human assessment is needed to weigh unpublished concerns about the no-fetch guarantee for CLR tool outputs and the framing test’s potentially flaky two-second timeout.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

Copilot-Session: b91be0f5-23d2-433f-a110-5001e3f607b8

Copilot AI 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.

🔵 Needs a closer look

Human assessment is needed to evaluate omitted findings about schema-validation inconsistencies involving delegating tools and repeated schema-less dispatches.

No open issues 🎉

Review effort: Balanced

Copilot-Session: b91be0f5-23d2-433f-a110-5001e3f607b8

Copilot AI 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.

🔵 Needs a closer look

Cross-cutting schema-validation and platform-specific shutdown changes warrant human architectural review, especially because the central recovery implementation’s diff is absent and builds and tests were not run.

No open issues 🎉

Review effort: Balanced

@tarekgh

tarekgh commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Proposal: scope this PR back to #1915 and track the broader work separately

Where the PR is today

The original problem in #1915 is narrow. With UseStructuredContent = true and the default WhenWritingNull serializer option, a required nullable property (for example record Order(string Id, string? Note)) is listed in the generated outputSchema.required, but is omitted from structuredContent when its value is null. Validating clients then reject the result.

Through several review rounds, the PR grew well beyond that fix. It now changes 26 files (about +14.8K / -0.5K lines, roughly 4.7K of production code) and includes:

  1. Schema-aware recovery of omitted members, respecting serializer contracts (custom converters, ShouldSerialize, JsonIgnore conditions, enums, default values, custom equality, non-indexable collections).
  2. A general output validator based on a new Core dependency (JsonSchema.Net), with local $ref resolution and no external schema fetching.
  3. Fail-closed behavior: if a successful result cannot be repaired or verified against the advertised schema, the call returns a generic tool error without structured content.
  4. Validation through the request pipeline: explicit OutputSchema, delegating tools, call-tool filters, and task-backed execution, with dispatch-time schema snapshots and result correlation.
  5. Resource bounds for recovery and validation (identity, byte, evaluation, and deferred-record limits).
  6. Stdio client shutdown and framing changes (draining stdout during exit, bounded waits, concurrent cleanup, and a read-buffer boundary fix), which are unrelated to structured output.

Decisions taken along the way

Decision Rationale
Do not globally switch to keeping nulls An explicit schema may allow a property to be absent but not null; adding null would break previously valid output.
Conservative recovery Only restore a value when it is provably the omitted default; skip ambiguous custom equality, converters, and predicates.
Fail closed Do not present an unverified result as schema-conforming.
No external schema fetching Keep validation deterministic and network-independent; same-document and embedded references still resolve.
Bounded recovery work 128 identities and 4 MiB per dispatch, plus evaluation and shutdown bounds, to avoid amplification or unbounded retention.
Validate delegated and filtered results against the outer schema Without this, wrappers could still return nonconforming output.
No per-client schema tracking for ListToolsFilters Out of scope; documented instead.

Why we should not merge this scope as is

Each of these decisions is reasonable on its own, but together they are a significant design change that has not had a dedicated discussion:

  • Behavior change: fail-closed validation can turn calls that succeed today into tool errors, including for tools with explicit schemas or unresolvable external references. The MCP spec says servers MUST return conforming results, but it does not require the SDK to enforce that with a general validator.
  • New dependency in ModelContextProtocol.Core, which has a minimal-dependency goal and must remain Native AOT friendly.
  • Pipeline coupling: schema snapshots and result correlation now flow through McpServerImpl, RequestContext, delegating tools, filters, and tasks. That is a lot of new internal state on a hot path.
  • Unrelated transport changes: the stdio shutdown and framing work deserves its own review and test history.
  • Reviewability: the size makes it hard to be confident there are no remaining gaps, and each review round has found new edge cases.

At the same time, #1915 is a real interoperability bug that users hit with the TypeScript and Python clients today. We do not want the broader design questions to keep that fix blocked.

Proposed scope for this PR

Fix only the case reported in #1915:

  • Applies only when the output schema is generated by the SDK from the return type (no explicit OutputSchema), and only when structured content is produced from a CLR value (not JsonElement, JsonNode, or CallToolResult).
  • For members that the generated schema lists as required and whose value is null, emit "name": null instead of omitting the member, when the omission comes only from the serializer's default WhenWritingNull policy.
  • Members with an explicit [JsonIgnore] condition, a custom ShouldSerialize, or a custom converter keep their current behavior.
  • Ordinary text content serialization, explicit schemas, delegating tools, filters, tasks, and the pre-SEP-2106 legacy envelope are unchanged.
  • No new dependency, no general validator, and no fail-closed behavior change.
  • Tests: the UseStructuredContent: with the default serializer options, structuredContent omits a null property that outputSchema requires #1915 repro shapes (positional record, required member, nullable optional property, defaulted record parameter), non-null values, nested objects, an explicit schema that is left untouched, the legacy protocol version, and Native AOT.

Why this scope is a good middle ground

  • It fixes the reported bug where it actually occurs. With a generated schema, the SDK owns both sides (the schema and the serialization), so it can make them agree without guessing.
  • The advertised schema does not change, so clients keep the stronger "always present, may be null" contract described in the issue.
  • Existing successful calls do not become errors.
  • It keeps ModelContextProtocol.Core free of a new dependency and keeps the change small enough to review with confidence.
  • Explicit schemas and wrappers behave exactly as they do today, so the only behavioral difference is that null is now present where the generated schema already requires it.

Follow-up issues to open

  1. Structured output validation and repair for explicit schemas, delegating tools, filters, and tasks. Should the SDK validate structured content at all? If so, should it fail closed, which validator should it use, and how should it handle unresolvable references and resource limits? The current PR branch is a useful reference implementation for that discussion.
  2. Stdio client shutdown and read framing. Drain stdout while waiting for process exit, bound shutdown waits, handle concurrent cleanup, and keep the read-buffer boundary fix if the chunked read loop is kept.
  3. Per-client schema consistency with ListToolsFilters: track whether a filtered schema should drive structured-output handling.

We will preserve the current branch head so none of the existing work is lost, and link it from the follow-up issues.

We will scope this PR to the focused fix above, then track the remaining work in follow-up issues so those design questions can be discussed separately.

Copilot AI 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.

🟡 Changes recommended

The serializer discards child recovery plans for recursive "$ref":"#" schemas, causing required nullable members to be omitted from nested results.

1 open issue

Review effort: Balanced

Copilot AI 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.

🔵 Needs a closer look

Human assessment is needed because serialization repair can insert null for intentionally omitted, non-null source-generated readonly fields when field and property ignore settings differ.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Copilot AI 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.

🔵 Needs a closer look

Human assessment is needed because URI-encoded local schema references can cause required null values to be omitted from structured output.

No open issues 🎉

Review effort: Balanced

Copilot AI 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.

🟢 Approval recommended

No active review issues are reported for the changes restoring required nullable members in supported structured tool outputs.

No open issues 🎉

Review effort: Balanced

Copilot AI 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.

🔵 Needs a closer look

Human assessment is needed because schema differences between a delegating wrapper and its inner tool can cause null-repair behavior to invalidate previously valid output.

No open issues 🎉

Review effort: Balanced

Copilot AI 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.

🟡 Changes recommended

Transparent tool wrappers disable null recovery because of a tool-identity check, allowing required nullable properties to remain missing from structured content and violate the advertised schema.

1 open issue

Review effort: Balanced

}

JsonElement? structuredContent = CreateStructuredResponse(result, request.Server.NegotiatedProtocolVersion);
bool restoreRequiredNulls = request.MatchedPrimitive is null || ReferenceEquals(request.MatchedPrimitive, this);
@tarekgh

tarekgh commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

I lean toward the #2067 approach, assuming we accept the broader default change. Writing nulls through normal System.Text.Json serialization is simpler than adding a post-serialization repair layer, and aligns C# with the common default in the Python, TypeScript, Java, Go, and Rust SDKs.

One design point would make this stronger: keep the generated output schema aligned with the actual serialization contract. In particular, if [JsonIgnore(Condition = WhenWritingNull)] or SerializerOptions.DefaultIgnoreCondition = WhenWritingNull omits a nullable property, the generated schema should not require that property. Go and Rust already account for their omission annotations when generating output schemas. Otherwise, even with #2067, opting back into null omission can recreate the schema mismatch.

The tradeoff is that #2067 affects all user data serialized with DefaultOptions, including tool arguments, explicit-schema results, and other outputs. I would favor it if we can keep protocol DTO behavior unchanged and address schema alignment in #2067 or a clearly linked follow-up. If that wider behavior change is not acceptable, #1929 is the narrower fix for the reported generated-schema case.

References: Go output schema inference, Rust output schema inference, Python structured serialization, TypeScript output validation.

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.

UseStructuredContent: with the default serializer options, structuredContent omits a null property that outputSchema requires

4 participants