-
-
Notifications
You must be signed in to change notification settings - Fork 634
Expand file tree
/
Copy pathBotSharpMCPExtensions.cs
More file actions
67 lines (59 loc) · 2.19 KB
/
BotSharpMCPExtensions.cs
File metadata and controls
67 lines (59 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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;
using Microsoft.Extensions.Configuration;
using ModelContextProtocol.Client;
namespace BotSharp.Core.MCP;
public static class BotSharpMcpExtensions
{
/// <summary>
/// Add mcp
/// </summary>
/// <param name="services"></param>
/// <param name="config"></param>
/// <returns></returns>
public static IServiceCollection AddBotSharpMCP(this IServiceCollection services, IConfiguration config)
{
services.AddScoped<IMcpService, McpService>();
var settings = config.GetSection("MCP").Get<McpSettings>();
services.AddScoped(provider => settings);
if (settings != null && settings.Enabled && !settings.McpServerConfigs.IsNullOrEmpty())
{
var clientManager = new McpClientManager(settings);
services.AddSingleton(clientManager);
foreach (var server in settings.McpServerConfigs)
{
RegisterFunctionCall(services, server, clientManager)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
}
// Register hooks
services.AddScoped<IAgentHook, McpToolAgentHook>();
}
return services;
}
private static async Task RegisterFunctionCall(IServiceCollection services, McpServerConfigModel server, McpClientManager clientManager)
{
try
{
var client = await clientManager.GetMcpClientAsync(server.Id);
var tools = await client.ListToolsAsync();
foreach (var tool in tools)
{
services.AddScoped(provider => tool);
services.AddScoped<IFunctionCallback>(provider =>
{
var funcTool = new McpToolAdapter(provider, server.Name, tool, clientManager);
return funcTool;
});
}
}
catch (Exception ex)
{
Console.WriteLine($"Error when registering {server?.Name} MCP tools. {ex.Message}\r\n{ex.InnerException}");
}
}
}