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
Original file line number Diff line number Diff line change
Expand Up @@ -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<Type>? serviceParameterTypes = AIFunctionMcpServerTool.GetServiceParameterTypes(method, options?.Services);

return new()
{
Name = options?.Name ?? method.GetCustomAttribute<McpServerPromptAttribute>()?.Name ?? AIFunctionMcpServerTool.DeriveName(method),
Description = options?.Description,
Expand All @@ -78,8 +82,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(
ConfigureParameterBinding = pi =>
{
if (RequestServiceProvider<GetPromptRequestParams>.IsAugmentedWith(pi.ParameterType) ||
(options?.Services?.GetService<IServiceProviderIsService>() is { } ispis &&
ispis.IsService(pi.ParameterType)))
serviceParameterTypes?.Contains(pi.ParameterType) is true)
{
return new()
{
Expand All @@ -106,6 +109,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(
return default;
},
};
}

/// <summary>Creates an <see cref="McpServerPrompt"/> that wraps the specified <see cref="AIFunction"/>.</summary>
public static new AIFunctionMcpServerPrompt Create(AIFunction function, McpServerPromptCreateOptions? options)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Type>? serviceParameterTypes = AIFunctionMcpServerTool.GetServiceParameterTypes(method, options?.Services);

return new()
{
Name = options?.Name ?? method.GetCustomAttribute<McpServerResourceAttribute>()?.Name ?? AIFunctionMcpServerTool.DeriveName(method),
Description = options?.Description,
Expand All @@ -87,8 +91,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(
ConfigureParameterBinding = pi =>
{
if (RequestServiceProvider<ReadResourceRequestParams>.IsAugmentedWith(pi.ParameterType) ||
(options?.Services?.GetService<IServiceProviderIsService>() is { } ispis &&
ispis.IsService(pi.ParameterType)))
serviceParameterTypes?.Contains(pi.ParameterType) is true)
{
return new()
{
Expand Down Expand Up @@ -140,6 +143,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(
return default;
},
};
}

private static readonly ConcurrentDictionary<Type, Func<string, object?>> s_convertersCache = [];

Expand Down
29 changes: 25 additions & 4 deletions src/ModelContextProtocol.Core/Server/AIFunctionMcpServerTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,30 @@ internal sealed partial class AIFunctionMcpServerTool : McpServerTool
returnType.IsAssignableFrom(typeof(CallToolResult)) ? null : false;
}

internal static HashSet<Type>? GetServiceParameterTypes(MethodInfo method, IServiceProvider? services)
{
HashSet<Type>? types = null;
if (services?.GetService<IServiceProviderIsService>() 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<Type>? serviceParameterTypes = GetServiceParameterTypes(method, options?.Services);

return new()
{
Name = options?.Name ?? method.GetCustomAttribute<McpServerToolAttribute>()?.Name ?? DeriveName(method),
Description = options?.Description,
Expand All @@ -96,8 +117,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(
ConfigureParameterBinding = pi =>
{
if (RequestServiceProvider<CallToolRequestParams>.IsAugmentedWith(pi.ParameterType) ||
(options?.Services?.GetService<IServiceProviderIsService>() is { } ispis &&
ispis.IsService(pi.ParameterType)))
serviceParameterTypes?.Contains(pi.ParameterType) is true)
{
return new()
{
Expand All @@ -124,6 +144,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(
return default;
},
};
}

/// <summary>Creates an <see cref="McpServerTool"/> that wraps the specified <see cref="AIFunction"/>.</summary>
public static new AIFunctionMcpServerTool Create(AIFunction function, McpServerToolCreateOptions? options) =>
Expand Down
34 changes: 34 additions & 0 deletions tests/ModelContextProtocol.Tests/Server/McpServerPromptTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<LeakTestService>();
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;
}
34 changes: 34 additions & 0 deletions tests/ModelContextProtocol.Tests/Server/McpServerResourceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<LeakTestService>();
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<AIContent>))]
Expand Down
34 changes: 34 additions & 0 deletions tests/ModelContextProtocol.Tests/Server/McpServerToolTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<LeakTestService>();
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;
}