Skip to content

Make McpJsonUtilities public and remove IVT to sample #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 20, 2025
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public static IEndpointConventionBuilder MapMcpSse(this IEndpointRouteBuilder en
return;
}

var message = await context.Request.ReadFromJsonAsync<IJsonRpcMessage>(JsonSerializerOptionsExtensions.DefaultOptions, context.RequestAborted);
var message = await context.Request.ReadFromJsonAsync<IJsonRpcMessage>(McpJsonUtilities.DefaultOptions, context.RequestAborted);
if (message is null)
{
await Results.BadRequest("No message in request body.").ExecuteAsync(context);
Expand Down
2 changes: 1 addition & 1 deletion samples/AspNetCoreSseServer/SseServerStreamTransport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ void WriteJsonRpcMessageToBuffer(SseItem<IJsonRpcMessage?> item, IBufferWriter<b
return;
}

JsonSerializer.Serialize(GetUtf8JsonWriter(writer), item.Data, JsonSerializerOptionsExtensions.DefaultOptions);
JsonSerializer.Serialize(GetUtf8JsonWriter(writer), item.Data, McpJsonUtilities.DefaultOptions);
}

// The very first SSE event isn't really an IJsonRpcMessage, but there's no API to write a single item of a different type,
Expand Down
4 changes: 2 additions & 2 deletions src/ModelContextProtocol/Client/McpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,8 @@ private async Task InitializeAsync(CancellationToken cancellationToken)

// Store server information
_logger.ServerCapabilitiesReceived(EndpointName,
capabilities: JsonSerializer.Serialize(initializeResponse.Capabilities, JsonSerializerOptionsExtensions.JsonContext.Default.ServerCapabilities),
serverInfo: JsonSerializer.Serialize(initializeResponse.ServerInfo, JsonSerializerOptionsExtensions.JsonContext.Default.Implementation));
capabilities: JsonSerializer.Serialize(initializeResponse.Capabilities, McpJsonUtilities.JsonContext.Default.ServerCapabilities),
serverInfo: JsonSerializer.Serialize(initializeResponse.ServerInfo, McpJsonUtilities.JsonContext.Default.Implementation));

ServerCapabilities = initializeResponse.Capabilities;
ServerInfo = initializeResponse.ServerInfo;
Expand Down
4 changes: 2 additions & 2 deletions src/ModelContextProtocol/Client/McpClientExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ private sealed class McpAIFunction(IMcpClient client, Tool tool) : AIFunction
["description"] = tool.Description ?? string.Empty,
["properties"] = tool.InputSchema?.Properties ?? [],
["required"] = tool.InputSchema?.Required ?? []
}, JsonSerializerOptionsExtensions.JsonContext.Default.DictionaryStringObject);
}, McpJsonUtilities.JsonContext.Default.DictionaryStringObject);

/// <inheritdoc/>
protected async override Task<object?> InvokeCoreAsync(
Expand All @@ -501,7 +501,7 @@ private sealed class McpAIFunction(IMcpClient client, Tool tool) : AIFunction
}

CallToolResponse result = await client.CallToolAsync(tool.Name, argDict, cancellationToken).ConfigureAwait(false);
return JsonSerializer.SerializeToElement(result, JsonSerializerOptionsExtensions.JsonContext.Default.CallToolResponse);
return JsonSerializer.SerializeToElement(result, McpJsonUtilities.JsonContext.Default.CallToolResponse);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, params
{
Name = function.Name,
Description = function.Description,
InputSchema = JsonSerializer.Deserialize(function.JsonSchema, JsonSerializerOptionsExtensions.JsonContext.Default.JsonSchema),
InputSchema = JsonSerializer.Deserialize(function.JsonSchema, McpJsonUtilities.JsonContext.Default.JsonSchema),
});

callbacks.Add(function.Name, async (request, cancellationToken) =>
Expand Down
5 changes: 2 additions & 3 deletions src/ModelContextProtocol/ModelContextProtocol.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,11 @@
<PropertyGroup Condition="'$(TargetFramework)' != 'netstandard2.0'">
<IsAotCompatible>true</IsAotCompatible>
</PropertyGroup>

<ItemGroup>
<InternalsVisibleTo Include="ModelContextProtocol.Tests" />
<InternalsVisibleTo Include="AspNetCoreSseServer" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.AI.Abstractions"/>
<PackageReference Include="Microsoft.Extensions.AI" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public HttpListenerSseServerTransport(string serverName, int port, ILoggerFactor
{
_serverName = serverName;
_logger = loggerFactory.CreateLogger<HttpListenerSseServerTransport>();
_jsonOptions = JsonSerializerOptionsExtensions.DefaultOptions;
_jsonOptions = McpJsonUtilities.DefaultOptions;
_httpServerProvider = new HttpListenerServerProvider(port);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public SseClientTransport(SseClientTransportOptions transportOptions, McpServerC
_httpClient = httpClient;
_connectionCts = new CancellationTokenSource();
_logger = (ILogger?)loggerFactory?.CreateLogger<SseClientTransport>() ?? NullLogger.Instance;
_jsonOptions = JsonSerializerOptionsExtensions.DefaultOptions;
_jsonOptions = McpJsonUtilities.DefaultOptions;
_connectionEstablished = new TaskCompletionSource<bool>();
_ownsHttpClient = ownsHttpClient;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public StdioClientTransport(StdioClientTransportOptions options, McpServerConfig
_options = options;
_serverConfig = serverConfig;
_logger = (ILogger?)loggerFactory?.CreateLogger<StdioClientTransport>() ?? NullLogger.Instance;
_jsonOptions = JsonSerializerOptionsExtensions.DefaultOptions;
_jsonOptions = McpJsonUtilities.DefaultOptions;
}

/// <inheritdoc/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public sealed class StdioServerTransport : TransportBase, IServerTransport
private readonly string _serverName;
private readonly ILogger _logger;

private readonly JsonSerializerOptions _jsonOptions = JsonSerializerOptionsExtensions.DefaultOptions;
private readonly JsonSerializerOptions _jsonOptions = McpJsonUtilities.DefaultOptions;
private readonly TextReader _stdin = Console.In;
private readonly TextWriter _stdout = Console.Out;

Expand Down
2 changes: 1 addition & 1 deletion src/ModelContextProtocol/Shared/McpJsonRpcEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ protected McpJsonRpcEndpoint(ITransport transport, ILoggerFactory? loggerFactory
_pendingRequests = new();
_notificationHandlers = new();
_nextRequestId = 1;
_jsonOptions = JsonSerializerOptionsExtensions.DefaultOptions;
_jsonOptions = McpJsonUtilities.DefaultOptions;
_logger = (ILogger?)loggerFactory?.CreateLogger<McpClient>() ?? NullLogger.Instance;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,39 @@
using ModelContextProtocol.Protocol.Messages;
using ModelContextProtocol.Protocol.Types;
using System.Diagnostics.CodeAnalysis;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;

namespace ModelContextProtocol.Utils.Json;

/// <summary>
/// Extensions for configuring System.Text.Json serialization options for MCP.
/// </summary>
internal static partial class JsonSerializerOptionsExtensions
/// <summary>Provides a collection of utility methods for working with JSON data in the context of MCP.</summary>
public static partial class McpJsonUtilities
{
/// <summary>
/// Gets the <see cref="JsonSerializerOptions"/> singleton used as the default in JSON serialization operations.
/// </summary>
/// <remarks>
/// <para>
/// For Native AOT or applications disabling <see cref="JsonSerializer.IsReflectionEnabledByDefault"/>, this instance
/// includes source generated contracts for all common exchange types contained in the ModelContextProtocol library.
/// </para>
/// <para>
/// It additionally turns on the following settings:
/// <list type="number">
/// <item>Enables string-based enum serialization as implemented by <see cref="JsonStringEnumConverter"/>.</item>
/// <item>Enables <see cref="JsonIgnoreCondition.WhenWritingNull"/> as the default ignore condition for properties.</item>
/// <item>Enables <see cref="JsonNumberHandling.AllowReadingFromString"/> as the default number handling for number types.</item>
/// <item>
/// Enables <see cref="JavaScriptEncoder.UnsafeRelaxedJsonEscaping"/> when escaping JSON strings.
/// Consuming applications must ensure that JSON outputs are adequately escaped before embedding in other document formats,
/// such as HTML and XML.
/// </item>
/// </list>
/// </para>
/// </remarks>
public static JsonSerializerOptions DefaultOptions { get; } = CreateDefaultOptions();

/// <summary>
Expand All @@ -26,23 +47,31 @@ private static JsonSerializerOptions CreateDefaultOptions()
// If reflection-based serialization is enabled by default, use it, as it's the most permissive in terms of what it can serialize,
// and we want to be flexible in terms of what can be put into the various collections in the object model.
// Otherwise, use the source-generated options to enable trimming and Native AOT.
JsonSerializerOptions options;

if (JsonSerializer.IsReflectionEnabledByDefault)
Copy link
Member

Choose a reason for hiding this comment

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

I think this is a good stopgap, but longer term we should look at using the source generator everywhere. Whether we can do this or not is a function of allowing user-defined types to be inserted in the DTOs. I don't believe that would be necessary -- the protocol should only deal with closed types.

{
// Keep in sync with the JsonSourceGenerationOptions attribute on JsonContext below.
JsonSerializerOptions options = new(JsonSerializerDefaults.Web)
options = new(JsonSerializerDefaults.Web)
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver(),
Converters = { new JsonStringEnumConverter() },
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
NumberHandling = JsonNumberHandling.AllowReadingFromString
NumberHandling = JsonNumberHandling.AllowReadingFromString,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
}
else
{
options = new(JsonContext.Default.Options)
{
// Compile-time encoder setting not yet available
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};

options.MakeReadOnly();
return options;
}

return JsonContext.Default.Options;
options.MakeReadOnly();
return options;
}

internal static JsonTypeInfo<T> GetTypeInfo<T>(this JsonSerializerOptions options) =>
Expand All @@ -62,6 +91,7 @@ internal static JsonTypeInfo<T> GetTypeInfo<T>(this JsonSerializerOptions option
[JsonSerializable(typeof(JsonRpcResponse))]
[JsonSerializable(typeof(JsonRpcError))]
[JsonSerializable(typeof(ServerCapabilities))]
[JsonSerializable(typeof(ClientCapabilities))]
[JsonSerializable(typeof(Implementation))]
[JsonSerializable(typeof(CreateMessageResult))]
[JsonSerializable(typeof(ListRootsResult))]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public async Task SendMessageAsync_Should_Send_Message()
await transport.SendMessageAsync(message);

var result = output.ToString()?.Trim();
var expected = JsonSerializer.Serialize(message, JsonSerializerOptionsExtensions.DefaultOptions);
var expected = JsonSerializer.Serialize(message, McpJsonUtilities.DefaultOptions);

Assert.Equal(expected, result);
}
Expand Down Expand Up @@ -113,7 +113,7 @@ public async Task DisposeAsync_Should_Dispose_Resources()
public async Task ReadMessagesAsync_Should_Read_Messages()
{
var message = new JsonRpcRequest { Method = "test", Id = RequestId.FromNumber(44) };
var json = JsonSerializer.Serialize(message, JsonSerializerOptionsExtensions.DefaultOptions);
var json = JsonSerializer.Serialize(message, McpJsonUtilities.DefaultOptions);

TextReader oldIn = Console.In;
TextWriter oldOut = Console.Out;
Expand Down