Avoid new JsonSerializerOptions instances (#34)

We try hard to avoid creating unnecessary JsonSerializerOptions, as each can have a non-trivial overhead due to how reflection is used by JsonSerializer and the JSO instance serving as a cache.  Rather than creating a new JSO for each transport / endpoint, this can just use a singleton. The only thing it loses is logging when the converter fails, but all of those paths are also throwing an exception, which can be logged higher in the call stack.
This commit is contained in:
Stephen Toub 2025-03-07 13:50:27 -05:00 • committed by GitHub
commit 9f0beec63a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -3,21 +3,24 @@ using System.Text.Json;
using System.Text.Json.Serialization;
namespace McpDotNet.Utils.Json;
/// <summary>
/// Extensions for configuring System.Text.Json serialization options for MCP.
/// </summary>
internal static class JsonSerializerOptionsExtensions
{
public static JsonSerializerOptions DefaultOptions { get; } = CreateDefaultOptions();
/// <summary>
/// Configures JsonSerializerOptions with MCP-specific settings and converters.
/// Creates default options to use for MCP-related serialization.
/// </summary>
/// <param name="options">The options to configure.</param>
/// <param name="loggerFactory">The logger factory to use for logging.</param>
/// <returns>The configured options.</returns>
public static JsonSerializerOptions ConfigureForMcp(this JsonSerializerOptions options, ILoggerFactory loggerFactory)
private static JsonSerializerOptions CreateDefaultOptions()
{
JsonSerializerOptions options = new();
// Add custom converters
options.Converters.Add(new JsonRpcMessageConverter(loggerFactory.CreateLogger<JsonRpcMessageConverter>()));
options.Converters.Add(new JsonRpcMessageConverter());
options.Converters.Add(new JsonStringEnumConverter());
// Configure general options