Overhaul McpClientFactory/McpServerFactory (#87)

Handlers are now specified before connecting the client/server. Otherwise, race conditions exist. Handlers move into being a part of the McpClientOptions/McpServerOptions, so that they're provided to the factories. Where relevant, the handlers are specified as part of the capability descriptors, so that they go hand in hand.

The factories are no longer stateful. Instead of allocating a factory and then calling a create method on it, you just call a static factory method.
This commit is contained in:
Stephen Toub 2025-03-16 12:08:52 -04:00 • committed by GitHub
commit 08b0a04dab
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,24 +1,21 @@
using Anthropic.SDK;
using Anthropic.SDK.Constants;
using Anthropic.SDK.Messaging;
using System.Linq;
using McpDotNet;
using McpDotNet.Client;
using McpDotNet.Configuration;
using McpDotNet.Protocol.Transport;
using Microsoft.Extensions.Logging.Abstractions;
internal class Program
{
private static async Task<IMcpClient> GetMcpClientAsync()
{
McpClientOptions options = new()
McpClientOptions clientOptions = new()
{
ClientInfo = new() { Name = "SimpleToolsConsole", Version = "1.0.0" }
};
var config = new McpServerConfig
McpServerConfig serverConfig = new()
{
Id = "everything",
Name = "Everything",
@ -30,13 +27,7 @@ internal class Program
}
};
var factory = new McpClientFactory(
[config],
options,
NullLoggerFactory.Instance
);
return await factory.GetClientAsync("everything");
return await McpClientFactory.CreateAsync(serverConfig, clientOptions);
}
private static async Task Main(string[] args)
@ -44,7 +35,7 @@ internal class Program
try
{
Console.WriteLine("Initializing MCP 'everything' server");
var client = await GetMcpClientAsync();
await using var client = await GetMcpClientAsync();
Console.WriteLine("MCP 'everything' server initialized");
Console.WriteLine("Listing tools...");
var tools = await client.ListToolsAsync().ToListAsync();
@ -60,10 +51,10 @@ internal class Program
Console.WriteLine("Asking Claude to call the Echo Tool...");
var messages = new List<Message>
{
List<Message> messages =
[
new Message(RoleType.User, "Please call the echo tool with the string 'Hello MCP!' and show me the echoed response.")
};
];
var parameters = new MessageParameters()
{