Skip to content

Avoid rooting IServiceProvider in AIFunctionFactoryOptions parameter binding - #2062

Open
sharafutdinovdi wants to merge 1 commit into
modelcontextprotocol:mainfrom
sharafutdinovdi:fix/service-provider-leak-1898
Open

sharafutdinovdi wants to merge 1 commit into
modelcontextprotocol:mainfrom
sharafutdinovdi:fix/service-provider-leak-1898

Conversation

@sharafutdinovdi

Copy link
Copy Markdown

Fixes #1898

Problem

Creating an McpServerTool, McpServerPrompt, or McpServerResource with Services passed in options kept the ServiceProvider alive even after it was disposed.

Root cause

CreateAIFunctionFactoryOptions in AIFunctionMcpServerTool, AIFunctionMcpServerPrompt, and AIFunctionMcpServerResource captured options (and therefore options.Services, which implements IServiceProviderIsService) inside the ConfigureParameterBinding lambda. Because AIFunctionFactory caches descriptors keyed by SerializerOptions (McpJsonUtilities.DefaultOptions), the closure rooted the disposed ServiceProvider for the lifetime of the process.

Fix

  • Added internal static HashSet<Type>? GetServiceParameterTypes(MethodInfo, IServiceProvider?) in AIFunctionMcpServerTool to precompute which parameter types of the target method are registered services (allocating only when at least one parameter resolves as a service).
  • Updated ConfigureParameterBinding in AIFunctionMcpServerTool, AIFunctionMcpServerPrompt, and AIFunctionMcpServerResource to check serviceParameterTypes?.Contains(pi.ParameterType) is true instead of capturing options.
  • Added WeakReference regression tests (Create_DoesNotRootServiceProvider) for tools, prompts, and resources.

Verification

  • Confirmed the three new Create_DoesNotRootServiceProvider tests fail without the fix and pass with it.
  • dotnet build src/ModelContextProtocol.Core/ModelContextProtocol.Core.csproj -c Release (all TFMs: netstandard2.0, net8.0, net9.0, net10.0): 0 warnings, 0 errors.
  • dotnet test tests/ModelContextProtocol.Tests/ModelContextProtocol.Tests.csproj -c Release -f net10.0 --filter "FullyQualifiedName~McpServerToolTests|FullyQualifiedName~McpServerPromptTests|FullyQualifiedName~McpServerResourceTests|FullyQualifiedName~InjectedParameterSchemaTests": 164/164 passed.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tools registered with WithTools keep a disposed service provider in memory

1 participant