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

60 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.Hooks;
using BotSharp.Core.MCP.Managers;
using BotSharp.Core.MCP.Services;
using BotSharp.Core.MCP.Settings;
2025-03-31 15:23:03 +00:00
using Microsoft.Extensions.Configuration;
using ModelContextProtocol.Client;
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
{
services.AddScoped<IMcpService, McpService>();
2025-04-01 03:11:18 +00:00
var settings = config.GetSection("MCP").Get<McpSettings>();
2025-04-15 05:25:03 +00:00
services.AddScoped(provider => settings);
2025-04-01 20:02:19 +00:00
2025-04-01 15:24:48 +00:00
if (settings != null && settings.Enabled && !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-15 05:25:03 +00:00
private static async Task RegisterFunctionCall(IServiceCollection services, McpServerConfigModel 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)
{
2025-04-15 05:25:03 +00:00
services.AddScoped(provider => tool);
2025-03-31 15:23:03 +00:00
services.AddScoped<IFunctionCallback>(provider =>
{
var funcTool = new McpToolAdapter(provider, tool, clientManager);
return funcTool;
});
}
}
}