Fix binding to wrong overload in WithTools (#152)

This commit is contained in:
Stephen Toub 2025-03-31 06:28:46 -04:00 • committed by GitHub
commit 0294c574a6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 50 additions and 2 deletions

View file

@ -38,7 +38,7 @@ public static partial class McpServerBuilderExtensions
if (toolMethod.GetCustomAttribute<McpServerToolAttribute>() is not null)
{
builder.Services.AddSingleton((Func<IServiceProvider, McpServerTool>)(toolMethod.IsStatic ?
services => McpServerTool.Create(toolMethod, new McpServerToolCreateOptions() { Services = services }) :
services => McpServerTool.Create(toolMethod, options: new() { Services = services }) :
services => McpServerTool.Create(toolMethod, typeof(TTool), new() { Services = services })));
}
}
@ -71,7 +71,7 @@ public static partial class McpServerBuilderExtensions
if (toolMethod.GetCustomAttribute<McpServerToolAttribute>() is not null)
{
builder.Services.AddSingleton((Func<IServiceProvider, McpServerTool>)(toolMethod.IsStatic ?
services => McpServerTool.Create(toolMethod, new McpServerToolCreateOptions() { Services = services }) :
services => McpServerTool.Create(toolMethod, options: new() { Services = services }) :
services => McpServerTool.Create(toolMethod, toolType, new() { Services = services })));
}
}

View file

@ -395,6 +395,54 @@ public class McpServerBuilderExtensionsToolsTests : LoggedTest, IAsyncDisposable
Assert.Contains(services.GetServices<McpServerTool>(), t => t.ProtocolTool.Name == "Echo");
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void WithTools_Parameters_Satisfiable_From_DI(bool parameterInServices)
{
ServiceCollection sc = new();
if (parameterInServices)
{
sc.AddSingleton(new ComplexObject());
}
sc.AddMcpServer().WithTools(typeof(EchoTool));
IServiceProvider services = sc.BuildServiceProvider();
McpServerTool tool = services.GetServices<McpServerTool>().First(t => t.ProtocolTool.Name == "EchoComplex");
if (parameterInServices)
{
Assert.DoesNotContain("\"complex\"", JsonSerializer.Serialize(tool.ProtocolTool.InputSchema));
}
else
{
Assert.Contains("\"complex\"", JsonSerializer.Serialize(tool.ProtocolTool.InputSchema));
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void WithToolsFromAssembly_Parameters_Satisfiable_From_DI(bool parameterInServices)
{
ServiceCollection sc = new();
if (parameterInServices)
{
sc.AddSingleton(new ComplexObject());
}
sc.AddMcpServer().WithToolsFromAssembly();
IServiceProvider services = sc.BuildServiceProvider();
McpServerTool tool = services.GetServices<McpServerTool>().First(t => t.ProtocolTool.Name == "EchoComplex");
if (parameterInServices)
{
Assert.DoesNotContain("\"complex\"", JsonSerializer.Serialize(tool.ProtocolTool.InputSchema));
}
else
{
Assert.Contains("\"complex\"", JsonSerializer.Serialize(tool.ProtocolTool.InputSchema));
}
}
[Fact]
public async Task Recognizes_Parameter_Types()
{