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
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
28 changes: 26 additions & 2 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 Down Expand Up @@ -76,6 +78,28 @@ private protected ContentBlock()
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class Converter : JsonConverter<ContentBlock>
{
private static readonly ConditionalWeakTable<JsonSerializerOptions, JsonSerializerOptions> s_nestedReadOptions = 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_nestedReadOptions.GetValue(options, CreateNestedReadOptions)
: CreateNestedReadOptions(options);
return nestedOptions.GetTypeInfo<T>();
}

private static JsonSerializerOptions CreateNestedReadOptions(JsonSerializerOptions callerOptions)
{
// A caller context may register ContentBlock without discovering the types read 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 +196,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 +207,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
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
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ internal sealed class Converter : JsonConverter<GetTaskResult>
}
string requestKey = reader.GetString()!;
reader.Read();
var inputRequest = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.DefaultOptions.GetTypeInfo<InputRequest>())
var inputRequest = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.ProtocolOptions.GetTypeInfo<InputRequest>())
?? throw new JsonException($"Failed to deserialize InputRequest for key '{requestKey}'.");
inputRequests[requestKey] = inputRequest;
}
Expand Down Expand Up @@ -315,7 +315,7 @@ public override void Write(Utf8JsonWriter writer, GetTaskResult value, JsonSeria
foreach (var kvp in reqs)
{
writer.WritePropertyName(kvp.Key);
JsonSerializer.Serialize(writer, kvp.Value, McpJsonUtilities.DefaultOptions.GetTypeInfo<InputRequest>());
JsonSerializer.Serialize(writer, kvp.Value, McpJsonUtilities.ProtocolOptions.GetTypeInfo<InputRequest>());
}
}
writer.WriteEndObject();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ internal sealed class Converter : JsonConverter<TaskStatusNotificationParams>
}
string requestKey = reader.GetString()!;
reader.Read();
var inputRequest = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.DefaultOptions.GetTypeInfo<InputRequest>())
var inputRequest = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.ProtocolOptions.GetTypeInfo<InputRequest>())
?? throw new JsonException($"Failed to deserialize InputRequest for key '{requestKey}'.");
inputRequests[requestKey] = inputRequest;
}
Expand Down Expand Up @@ -311,7 +311,7 @@ public override void Write(Utf8JsonWriter writer, TaskStatusNotificationParams v
foreach (var kvp in reqs)
{
writer.WritePropertyName(kvp.Key);
JsonSerializer.Serialize(writer, kvp.Value, McpJsonUtilities.DefaultOptions.GetTypeInfo<InputRequest>());
JsonSerializer.Serialize(writer, kvp.Value, McpJsonUtilities.ProtocolOptions.GetTypeInfo<InputRequest>());
}
}
writer.WriteEndObject();
Expand Down
Loading