Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/concepts/apps/apps.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ The key concepts are:
- **UI resources** — HTML content served with the MIME type `text/html;profile=mcp-app`
- **Tool UI metadata** — Tools declare their associated UI resource in `_meta.ui`

### JSON property matching

`McpApps.SerializerOptions` matches extension-defined property names case-sensitively, using `McpJsonUtilities.ProtocolOptions` together with the Apps source-generated metadata. For example, `resourceUri` and `mimeTypes` bind their respective properties, while `ResourceUri` and `MimeTypes` are ignored. When both spellings occur, the canonical spelling is used regardless of their order. This agrees with `McpApps.GetUiCapability`.

This changes the behavior of applications that previously deserialized alternate-cased JSON through the Apps preset. Correctly cased JSON, serialization output, and strongly typed C# usage are unchanged. `McpJsonUtilities.DefaultOptions` continues to match user-defined data case-insensitively, and callers can still supply their own serializer options.

## Associating tools with UI resources

### Using the builder extension (recommended)
Expand Down
2 changes: 1 addition & 1 deletion docs/concepts/transports/transports.md
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ Like [stdio](#stdio-transport), the in-memory transport is inherently single-ses

## Cross-application access

The SDK provides built-in support for the [Identity Assertion Authorization Grant (ID-JAG) flow](https://github.com/modelcontextprotocol/ext-auth/blob/main/specification/stable/enterprise-managed-authorization.mdx) via `IdentityAssertionGrantProvider`. This enables non-interactive enterprise SSO scenarios where users authenticate once via their enterprise Identity Provider (IdP) and access MCP servers without per-server authorization prompts.
The SDK provides built-in support for the [Identity Assertion Authorization Grant (ID-JAG) flow](https://github.com/modelcontextprotocol/ext-auth/blob/main/specification/stable/enterprise-managed-authorization/2026-07-28/enterprise-managed-authorization.mdx) via `IdentityAssertionGrantProvider`. This enables non-interactive enterprise SSO scenarios where users authenticate once via their enterprise Identity Provider (IdP) and access MCP servers without per-server authorization prompts.

The flow consists of two steps:

Expand Down
23 changes: 23 additions & 0 deletions docs/experimental.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,29 @@ JsonSerializerOptions options = new()

By placing the SDK's resolver first, MCP types are serialized using the SDK's contract (which includes experimental properties), while your custom context handles your own types. This is recommended even if you aren't currently using experimental APIs, since it ensures your serialization configuration remains correct as new experimental properties are introduced or as you adopt experimental features in the future.

### Customizing nested content contracts

If you intentionally override the SDK's contracts for nested `Icon` or `Annotations` values, place your custom resolver before the SDK's resolver. Unlike the SDK-first configuration above, this selects your contracts, so you are responsible for preserving any experimental properties you need.

When combining these customizations with an application-defined source-generated context, use `JsonSourceGenerationMode.Metadata` for every context that supplies an enclosing type, such as `CallToolResult`, not just the context that supplies `Icon` or `Annotations`:

```csharp
using ModelContextProtocol.Protocol;
using System.Text.Json.Serialization;

[JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(CallToolResult))]
[JsonSerializable(typeof(Icon))]
[JsonSerializable(typeof(Annotations))]
internal partial class CustomContentContext : JsonSerializerContext;
```

Apply your contract modifiers through the resolver used by the `JsonSerializerOptions` passed to both serialization and deserialization. The SDK's content converter uses caller-supplied icon and annotation contracts first and supplies SDK metadata for missing nested types.

The default source-generation mode can generate optimized serialization handlers for enclosing types. These handlers can pass their context's own options to the content converter, bypassing the caller's modified nested contracts. This can cause serialization to emit the original property names while deserialization expects the customized names, losing annotation values or rejecting icons with missing required properties. Changing only the nested context to metadata mode does not prevent the enclosing handler from doing this.

Metadata-mode source generation avoids this mismatch and remains compatible with Native AOT and reflection-disabled applications. This requirement applies to intentional nested-contract customizations with caller-owned contexts; ordinary use of the SDK's serializer presets does not require a custom context. Keep the specification-defined property names when exchanging MCP protocol messages.

## See also

- [Versioning](versioning.md)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -714,7 +714,7 @@ internal static Task RunSessionAsync(HttpContext httpContext, McpServer session,
return null;
}

internal static JsonTypeInfo<T> GetRequiredJsonTypeInfo<T>() => (JsonTypeInfo<T>)McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(T));
internal static JsonTypeInfo<T> GetRequiredJsonTypeInfo<T>() => (JsonTypeInfo<T>)McpJsonUtilities.ProtocolOptions.GetTypeInfo(typeof(T));

/// <summary>
/// Validates that a request riding a per-request-metadata protocol revision carries the required
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ private async Task ProcessMessageAsync(string line, CancellationToken cancellati
{
try
{
var message = (JsonRpcMessage?)JsonSerializer.Deserialize(line.AsSpan().Trim(), McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonRpcMessage)));
var message = (JsonRpcMessage?)JsonSerializer.Deserialize(line.AsSpan().Trim(), McpJsonUtilities.ProtocolOptions.GetTypeInfo(typeof(JsonRpcMessage)));
if (message != null)
{
await WriteMessageAsync(message, cancellationToken).ConfigureAwait(false);
Expand Down
44 changes: 38 additions & 6 deletions src/ModelContextProtocol.Core/McpJsonUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,48 @@ public static partial class McpJsonUtilities
/// <item>Enables <see cref="JsonNumberHandling.AllowReadingFromString"/> as the default number handling for number types.</item>
/// </list>
/// </para>
/// <para>
/// Property names are matched case-insensitively, as with <see cref="JsonSerializerDefaults.Web"/>, because these
/// options are also used for user-defined data such as tool arguments and results. The SDK deserializes protocol
/// messages with <see cref="ProtocolOptions"/> instead, so a protocol property such as <c>params.name</c> is only
/// recognized with the casing defined by the MCP specification. Protocol types deserialized through these options
/// keep case-insensitive matching.
/// </para>
/// </remarks>
public static JsonSerializerOptions DefaultOptions { get; } = CreateDefaultOptions(propertyNameCaseInsensitive: true);

/// <summary>
/// Gets the <see cref="JsonSerializerOptions"/> singleton used to deserialize MCP and JSON-RPC protocol messages.
/// </summary>
/// <remarks>
/// <para>
/// These options are configured like <see cref="DefaultOptions"/>, except that property names are matched
/// case-sensitively. Protocol property names are defined by the MCP and JSON-RPC specifications, so a property such
/// as <c>params.Name</c> or <c>error.Code</c> is not bound to <c>name</c> or <c>code</c>.
/// </para>
/// <para>
/// Use these options when deserializing protocol messages yourself. User-defined data, such as tool arguments,
/// should continue to use <see cref="DefaultOptions"/> or caller-supplied options.
/// </para>
/// </remarks>
public static JsonSerializerOptions DefaultOptions { get; } = CreateDefaultOptions();
public static JsonSerializerOptions ProtocolOptions { get; } = CreateDefaultOptions(propertyNameCaseInsensitive: false);

/// <summary>
/// Creates default options to use for MCP-related serialization.
/// </summary>
/// <param name="propertyNameCaseInsensitive">Whether property names are matched case-insensitively.</param>
/// <returns>The configured options.</returns>
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL3050:RequiresDynamicCode", Justification = "Converter is guarded by IsReflectionEnabledByDefault check.")]
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access", Justification = "Converter is guarded by IsReflectionEnabledByDefault check.")]
private static JsonSerializerOptions CreateDefaultOptions()
private static JsonSerializerOptions CreateDefaultOptions(bool propertyNameCaseInsensitive)
{
// Copy the configuration from the source generated context.
JsonSerializerOptions options = new(JsonContext.Default.Options);
// Copy the configuration from the source generated context. The context matches protocol property names
// case-sensitively; DefaultOptions is also used for user-defined types (for example tool parameters),
// so it keeps the web default.
JsonSerializerOptions options = new(JsonContext.Default.Options)
{
PropertyNameCaseInsensitive = propertyNameCaseInsensitive,
};

// Chain with all supported types from MEAI.
options.TypeInfoResolverChain.Add(AIJsonUtilities.DefaultOptions.TypeInfoResolver!);
Expand Down Expand Up @@ -101,10 +130,13 @@ internal static bool IsValidMcpToolSchema(JsonElement element)
internal static bool IsValidToolOutputSchema(JsonElement element) =>
element.ValueKind is JsonValueKind.Object or JsonValueKind.True or JsonValueKind.False;

// Keep in sync with CreateDefaultOptions above.
// Keep in sync with CreateDefaultOptions above. Like ProtocolOptions, property names are matched
// case-sensitively: these contracts deserialize protocol messages, whose property names are defined
// by the MCP and JSON-RPC specifications, and must agree with the JSON-RPC envelope converter.
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
NumberHandling = JsonNumberHandling.AllowReadingFromString)]
NumberHandling = JsonNumberHandling.AllowReadingFromString,
PropertyNameCaseInsensitive = false)]
Comment thread
tarekgh marked this conversation as resolved.

// JSON-RPC
[JsonSerializable(typeof(JsonRpcMessage))]
Expand Down
39 changes: 35 additions & 4 deletions src/ModelContextProtocol.Core/Protocol/ContentBlock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;

namespace ModelContextProtocol.Protocol;

Expand All @@ -24,6 +26,13 @@ namespace ModelContextProtocol.Protocol;
/// and other communication between clients and servers.
/// </para>
/// <para>
/// When customizing nested <see cref="Icon"/> or <see cref="Protocol.Annotations"/> contracts through a
/// caller-supplied source-generated resolver, configure the context for any enclosing type, such as
/// <see cref="CallToolResult"/>, with <see cref="JsonSourceGenerationMode.Metadata"/>.
/// Optimized serialization handlers can use their context's own options instead of the caller's modified
/// nested contracts. Metadata-mode source generation preserves those customizations without requiring reflection.
/// </para>
/// <para>
/// See the <see href="https://github.com/modelcontextprotocol/specification/blob/main/schema/">schema</see> for more details.
/// </para>
/// </remarks>
Expand Down Expand Up @@ -76,6 +85,28 @@ private protected ContentBlock()
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class Converter : JsonConverter<ContentBlock>
{
private static readonly ConditionalWeakTable<JsonSerializerOptions, JsonSerializerOptions> s_nestedOptions = new();

private static JsonTypeInfo<T> GetNestedTypeInfo<T>(JsonSerializerOptions options)
{
// JsonSerializer freezes options, but direct converter callers may still change them.
JsonSerializerOptions nestedOptions = options.IsReadOnly
? s_nestedOptions.GetValue(options, CreateNestedOptions)
: CreateNestedOptions(options);
return nestedOptions.GetTypeInfo<T>();
}

private static JsonSerializerOptions CreateNestedOptions(JsonSerializerOptions callerOptions)
{
// A caller context may register ContentBlock without discovering the types used by
// this custom converter. Keep caller contracts first, then supply the SDK metadata
// (including nested collection types) using the same settings and converters.
JsonSerializerOptions nestedOptions = new(callerOptions);
nestedOptions.TypeInfoResolverChain.Add(McpJsonUtilities.JsonContext.Default);
nestedOptions.MakeReadOnly();
return nestedOptions;
}

/// <inheritdoc/>
public override ContentBlock? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Expand Down Expand Up @@ -172,7 +203,7 @@ public sealed class Converter : JsonConverter<ContentBlock>
icons = [];
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
{
icons.Add(JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.Icon) ??
icons.Add(JsonSerializer.Deserialize(ref reader, GetNestedTypeInfo<Icon>(options)) ??
throw new JsonException("Unexpected null item in icons array."));
}
}
Expand All @@ -183,7 +214,7 @@ public sealed class Converter : JsonConverter<ContentBlock>
break;

case "annotations":
annotations = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.Annotations);
annotations = JsonSerializer.Deserialize(ref reader, GetNestedTypeInfo<Annotations>(options));
break;

case "_meta":
Expand Down Expand Up @@ -357,7 +388,7 @@ public override void Write(Utf8JsonWriter writer, ContentBlock value, JsonSerial
writer.WriteStartArray();
foreach (var icon in resourceLink.Icons)
{
JsonSerializer.Serialize(writer, icon, McpJsonUtilities.JsonContext.Default.Icon);
JsonSerializer.Serialize(writer, icon, GetNestedTypeInfo<Icon>(options));
}
writer.WriteEndArray();
}
Expand Down Expand Up @@ -394,7 +425,7 @@ public override void Write(Utf8JsonWriter writer, ContentBlock value, JsonSerial
if (value.Annotations is { } annotations)
{
writer.WritePropertyName("annotations");
JsonSerializer.Serialize(writer, annotations, McpJsonUtilities.JsonContext.Default.Annotations);
JsonSerializer.Serialize(writer, annotations, GetNestedTypeInfo<Annotations>(options));
}

if (value.Meta is not null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ private async Task ReadMessagesAsync()

try
{
if (JsonSerializer.Deserialize(line, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonRpcMessage))) is JsonRpcMessage message)
if (JsonSerializer.Deserialize(line, McpJsonUtilities.ProtocolOptions.GetTypeInfo(typeof(JsonRpcMessage))) is JsonRpcMessage message)
{
await WriteMessageAsync(message, shutdownToken).ConfigureAwait(false);
}
Expand Down
4 changes: 3 additions & 1 deletion src/ModelContextProtocol.Extensions.Apps/Server/McpApps.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,14 @@ public static class McpApps
/// <remarks>
/// Use these options when serializing or deserializing MCP Apps types such as
/// <see cref="McpUiToolMeta"/>, <see cref="McpUiClientCapabilities"/>, and <see cref="McpUiResourceMeta"/>.
/// Property names are matched case-sensitively, as with <see cref="McpJsonUtilities.ProtocolOptions"/>.
/// Alternate spellings such as <c>ResourceUri</c> do not bind the protocol's <c>resourceUri</c> property.
/// </remarks>
public static JsonSerializerOptions SerializerOptions { get; } = CreateSerializerOptions();

private static JsonSerializerOptions CreateSerializerOptions()
{
var options = new JsonSerializerOptions(McpJsonUtilities.DefaultOptions);
var options = new JsonSerializerOptions(McpJsonUtilities.ProtocolOptions);
options.TypeInfoResolverChain.Insert(0, McpAppsJsonContext.Default);
options.MakeReadOnly();
return options;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public static async ValueTask<ResultOrCreatedTask<CallToolResult>> CallToolAsTas
JsonRpcRequest jsonRpcRequest = new()
{
Method = RequestMethods.ToolsCall,
Params = JsonSerializer.SerializeToNode(paramsWithMeta, McpJsonUtilities.DefaultOptions.GetTypeInfo<CallToolRequestParams>()),
Params = JsonSerializer.SerializeToNode(paramsWithMeta, McpJsonUtilities.ProtocolOptions.GetTypeInfo<CallToolRequestParams>()),
};

JsonRpcResponse response = await client.SendRequestAsync(jsonRpcRequest, cancellationToken).ConfigureAwait(false);
Expand All @@ -51,7 +51,7 @@ public static async ValueTask<ResultOrCreatedTask<CallToolResult>> CallToolAsTas
return new ResultOrCreatedTask<CallToolResult>(taskCreated);
}

var callToolResult = JsonSerializer.Deserialize(response.Result, McpJsonUtilities.DefaultOptions.GetTypeInfo<CallToolResult>())
var callToolResult = JsonSerializer.Deserialize(response.Result, McpJsonUtilities.ProtocolOptions.GetTypeInfo<CallToolResult>())
?? throw new JsonException("Failed to deserialize CallToolResult from response.");
return new ResultOrCreatedTask<CallToolResult>(callToolResult);
}
Expand Down Expand Up @@ -163,7 +163,7 @@ public static async ValueTask<UpdateTaskResult> UpdateTaskAsync(
{
paramsObj["inputResponses"] = JsonSerializer.SerializeToNode(
inputResponses,
McpJsonUtilities.DefaultOptions.GetTypeInfo<IDictionary<string, InputResponse>>());
McpJsonUtilities.ProtocolOptions.GetTypeInfo<IDictionary<string, InputResponse>>());
}

JsonRpcRequest jsonRpcRequest = CreateTaskRequest(
Expand Down Expand Up @@ -268,7 +268,7 @@ private static async ValueTask<CallToolResult> PollTaskToCompletionAsync(
switch (taskResult)
{
case CompletedTaskResult completed:
return JsonSerializer.Deserialize(completed.Result, McpJsonUtilities.DefaultOptions.GetTypeInfo<CallToolResult>())
return JsonSerializer.Deserialize(completed.Result, McpJsonUtilities.ProtocolOptions.GetTypeInfo<CallToolResult>())
?? throw new JsonException("Failed to deserialize CallToolResult from completed task.");

case FailedTaskResult failed:
Expand Down
Loading
Loading