From 0d251770c7b88d386bc3d45bd3d8766118a96f50 Mon Sep 17 00:00:00 2001 From: Dinar Sharafutdinov <89812052+sharafutdinovdi@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:00:19 +0100 Subject: [PATCH] Avoid rooting IServiceProvider in AIFunctionFactoryOptions parameter binding --- .../Server/AIFunctionMcpServerPrompt.cs | 12 ++++--- .../Server/AIFunctionMcpServerResource.cs | 12 ++++--- .../Server/AIFunctionMcpServerTool.cs | 29 +++++++++++++--- .../Server/McpServerPromptTests.cs | 34 +++++++++++++++++++ .../Server/McpServerResourceTests.cs | 34 +++++++++++++++++++ .../Server/McpServerToolTests.cs | 34 +++++++++++++++++++ 6 files changed, 143 insertions(+), 12 deletions(-) diff --git a/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerPrompt.cs b/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerPrompt.cs index c755cd9e5..100b6cb02 100644 --- a/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerPrompt.cs +++ b/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerPrompt.cs @@ -67,8 +67,12 @@ internal sealed class AIFunctionMcpServerPrompt : McpServerPrompt } private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions( - MethodInfo method, McpServerPromptCreateOptions? options) => - new() + MethodInfo method, McpServerPromptCreateOptions? options) + { + // Precompute the service-bound parameter types so the long-lived factory options don't capture options.Services. + HashSet? serviceParameterTypes = AIFunctionMcpServerTool.GetServiceParameterTypes(method, options?.Services); + + return new() { Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? AIFunctionMcpServerTool.DeriveName(method), Description = options?.Description, @@ -78,8 +82,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions( ConfigureParameterBinding = pi => { if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) || - (options?.Services?.GetService() is { } ispis && - ispis.IsService(pi.ParameterType))) + serviceParameterTypes?.Contains(pi.ParameterType) is true) { return new() { @@ -106,6 +109,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions( return default; }, }; + } /// Creates an that wraps the specified . public static new AIFunctionMcpServerPrompt Create(AIFunction function, McpServerPromptCreateOptions? options) diff --git a/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerResource.cs b/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerResource.cs index 7f0f29140..5d55229e4 100644 --- a/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerResource.cs +++ b/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerResource.cs @@ -76,8 +76,12 @@ internal sealed class AIFunctionMcpServerResource : McpServerResource } private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions( - MethodInfo method, McpServerResourceCreateOptions? options) => - new() + MethodInfo method, McpServerResourceCreateOptions? options) + { + // Precompute the service-bound parameter types so the long-lived factory options don't capture options.Services. + HashSet? serviceParameterTypes = AIFunctionMcpServerTool.GetServiceParameterTypes(method, options?.Services); + + return new() { Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? AIFunctionMcpServerTool.DeriveName(method), Description = options?.Description, @@ -87,8 +91,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions( ConfigureParameterBinding = pi => { if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) || - (options?.Services?.GetService() is { } ispis && - ispis.IsService(pi.ParameterType))) + serviceParameterTypes?.Contains(pi.ParameterType) is true) { return new() { @@ -140,6 +143,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions( return default; }, }; + } private static readonly ConcurrentDictionary> s_convertersCache = []; diff --git a/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerTool.cs b/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerTool.cs index 6d4579f66..e2506dfa2 100644 --- a/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerTool.cs +++ b/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerTool.cs @@ -84,9 +84,30 @@ internal sealed partial class AIFunctionMcpServerTool : McpServerTool returnType.IsAssignableFrom(typeof(CallToolResult)) ? null : false; } + internal static HashSet? GetServiceParameterTypes(MethodInfo method, IServiceProvider? services) + { + HashSet? types = null; + if (services?.GetService() is { } isService) + { + foreach (ParameterInfo p in method.GetParameters()) + { + if (isService.IsService(p.ParameterType)) + { + (types ??= []).Add(p.ParameterType); + } + } + } + + return types; + } + private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions( - MethodInfo method, McpServerToolCreateOptions? options) => - new() + MethodInfo method, McpServerToolCreateOptions? options) + { + // Precompute the service-bound parameter types so the long-lived factory options don't capture options.Services. + HashSet? serviceParameterTypes = GetServiceParameterTypes(method, options?.Services); + + return new() { Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? DeriveName(method), Description = options?.Description, @@ -96,8 +117,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions( ConfigureParameterBinding = pi => { if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) || - (options?.Services?.GetService() is { } ispis && - ispis.IsService(pi.ParameterType))) + serviceParameterTypes?.Contains(pi.ParameterType) is true) { return new() { @@ -124,6 +144,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions( return default; }, }; + } /// Creates an that wraps the specified . public static new AIFunctionMcpServerTool Create(AIFunction function, McpServerToolCreateOptions? options) => diff --git a/tests/ModelContextProtocol.Tests/Server/McpServerPromptTests.cs b/tests/ModelContextProtocol.Tests/Server/McpServerPromptTests.cs index dec16d6b2..2db71fcb2 100644 --- a/tests/ModelContextProtocol.Tests/Server/McpServerPromptTests.cs +++ b/tests/ModelContextProtocol.Tests/Server/McpServerPromptTests.cs @@ -547,4 +547,38 @@ public void SupportsPromptWithoutIcons() Assert.Null(prompt.ProtocolPrompt.Icons); } + + [Fact] + public void Create_DoesNotRootServiceProvider() + { + var (weakRef, item) = CreateWithServiceProvider(); + + for (int i = 0; i < 5 && weakRef.IsAlive; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + } + + Assert.False(weakRef.IsAlive); + GC.KeepAlive(item); + } + + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + private static (WeakReference, McpServerPrompt) CreateWithServiceProvider() + { + ServiceCollection sc = new(); + sc.AddSingleton(); + ServiceProvider services = sc.BuildServiceProvider(); + + McpServerPrompt item = McpServerPrompt.Create( + (LeakTestService svc) => "result", + new() { Services = services }); + + var weakRef = new WeakReference(services); + services.Dispose(); + return (weakRef, item); + } + + private sealed class LeakTestService; } diff --git a/tests/ModelContextProtocol.Tests/Server/McpServerResourceTests.cs b/tests/ModelContextProtocol.Tests/Server/McpServerResourceTests.cs index 6a67bac9a..8df71c977 100644 --- a/tests/ModelContextProtocol.Tests/Server/McpServerResourceTests.cs +++ b/tests/ModelContextProtocol.Tests/Server/McpServerResourceTests.cs @@ -734,6 +734,40 @@ public void SupportsResourceWithoutIcons() Assert.Null(resource.ProtocolResourceTemplate.Icons); } + [Fact] + public void Create_DoesNotRootServiceProvider() + { + var (weakRef, item) = CreateWithServiceProvider(); + + for (int i = 0; i < 5 && weakRef.IsAlive; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + } + + Assert.False(weakRef.IsAlive); + GC.KeepAlive(item); + } + + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + private static (WeakReference, McpServerResource) CreateWithServiceProvider() + { + ServiceCollection sc = new(); + sc.AddSingleton(); + ServiceProvider services = sc.BuildServiceProvider(); + + McpServerResource item = McpServerResource.Create( + (LeakTestService svc) => "result", + new() { Services = services, UriTemplate = "test://resource" }); + + var weakRef = new WeakReference(services); + services.Dispose(); + return (weakRef, item); + } + + private sealed class LeakTestService; + [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] [JsonSerializable(typeof(DisposableResourceType))] [JsonSerializable(typeof(List))] diff --git a/tests/ModelContextProtocol.Tests/Server/McpServerToolTests.cs b/tests/ModelContextProtocol.Tests/Server/McpServerToolTests.cs index c77151884..4af1ca46c 100644 --- a/tests/ModelContextProtocol.Tests/Server/McpServerToolTests.cs +++ b/tests/ModelContextProtocol.Tests/Server/McpServerToolTests.cs @@ -1455,4 +1455,38 @@ public static string ToolWithUInt64Header( [McpHeader("Count")] ulong count) => "result"; } + + [Fact] + public void Create_DoesNotRootServiceProvider() + { + var (weakRef, item) = CreateWithServiceProvider(); + + for (int i = 0; i < 5 && weakRef.IsAlive; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + } + + Assert.False(weakRef.IsAlive); + GC.KeepAlive(item); + } + + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + private static (WeakReference, McpServerTool) CreateWithServiceProvider() + { + ServiceCollection sc = new(); + sc.AddSingleton(); + ServiceProvider services = sc.BuildServiceProvider(); + + McpServerTool item = McpServerTool.Create( + (LeakTestService svc) => "result", + new() { Services = services }); + + var weakRef = new WeakReference(services); + services.Dispose(); + return (weakRef, item); + } + + private sealed class LeakTestService; }