BotSharp/src/Infrastructure/BotSharp.Core.MCP/BotSharpMCPExtensions.cs

58 lines
1.9 KiB
C#
Raw Normal View History

2025-03-31 21:43:42 +00:00
using BotSharp.Core.MCP.Functions;
using BotSharp.Core.MCP.Settings;
using BotSharp.Core.MCP.Hooks;
2025-03-31 15:23:03 +00:00
using Microsoft.Extensions.Configuration;
using ModelContextProtocol.Configuration;
using ModelContextProtocol.Client;
2025-04-01 01:59:19 +00:00
using BotSharp.Core.MCP.Managers;
2025-03-31 15:23:03 +00:00
2025-03-31 21:43:42 +00:00
namespace BotSharp.Core.MCP;
2025-03-31 15:23:03 +00:00
2025-04-01 01:59:19 +00:00
public static class BotSharpMcpExtensions
2025-03-31 15:23:03 +00:00
{
/// <summary>
/// Add mcp
/// </summary>
/// <param name="services"></param>
/// <param name="config"></param>
/// <returns></returns>
2025-03-31 21:43:42 +00:00
public static IServiceCollection AddBotSharpMCP(this IServiceCollection services, IConfiguration config)
2025-03-31 15:23:03 +00:00
{
2025-04-01 01:59:19 +00:00
var settings = config.GetSection("MCPSettings").Get<McpSettings>();
services.AddScoped<McpSettings>(provider => { return settings; });
if (settings != null && !settings.McpServerConfigs.IsNullOrEmpty())
2025-03-31 15:23:03 +00:00
{
2025-04-01 01:59:19 +00:00
var clientManager = new McpClientManager(settings);
2025-03-31 15:23:03 +00:00
services.AddSingleton(clientManager);
foreach (var server in settings.McpServerConfigs)
{
RegisterFunctionCall(services, server, clientManager)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
}
2025-04-01 01:59:19 +00:00
2025-03-31 15:23:03 +00:00
// Register hooks
2025-04-01 01:59:19 +00:00
services.AddScoped<IAgentHook, McpToolAgentHook>();
2025-03-31 15:23:03 +00:00
}
return services;
}
2025-04-01 01:59:19 +00:00
private static async Task RegisterFunctionCall(IServiceCollection services, McpServerConfig server, McpClientManager clientManager)
2025-03-31 15:23:03 +00:00
{
var client = await clientManager.GetMcpClientAsync(server.Id);
var tools = await client.ListToolsAsync();
foreach (var tool in tools)
{
services.AddScoped(provider => { return tool; });
services.AddScoped<IFunctionCallback>(provider =>
{
var funcTool = new McpToolAdapter(provider, tool, clientManager);
return funcTool;
});
}
}
}