forked from SciSharp/BotSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMCPToolAgentHook.cs
More file actions
71 lines (58 loc) · 2.17 KB
/
MCPToolAgentHook.cs
File metadata and controls
71 lines (58 loc) · 2.17 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
68
69
70
71
using BotSharp.Core.MCP.Helpers;
using BotSharp.Core.MCP.Managers;
using BotSharp.Core.MCP.Settings;
using ModelContextProtocol.Client;
namespace BotSharp.Core.MCP.Hooks;
public class McpToolAgentHook : AgentHookBase
{
public override string SelfId => string.Empty;
public McpToolAgentHook(IServiceProvider services, AgentSettings settings)
: base(services, settings)
{
}
public override void OnAgentMcpToolLoaded(Agent agent)
{
if (agent.Type == AgentType.Routing)
{
return;
}
var conv = _services.GetRequiredService<IConversationService>();
var isConvMode = conv.IsConversationMode();
if (!isConvMode) return;
agent.SecondaryFunctions ??= [];
var functions = GetMcpContent(agent).Result;
agent.SecondaryFunctions = agent.SecondaryFunctions.Concat(functions).DistinctBy(x => x.Name, StringComparer.OrdinalIgnoreCase).ToList();
}
private async Task<IEnumerable<FunctionDef>> GetMcpContent(Agent agent)
{
var functionDefs = new List<FunctionDef>();
var settings = _services.GetRequiredService<McpSettings>();
if (settings?.Enabled != true)
{
return functionDefs;
}
var mcpClientManager = _services.GetService<McpClientManager>();
if (mcpClientManager == null)
{
return functionDefs;
}
var mcps = agent.McpTools?.Where(x => !x.Disabled) ?? [];
foreach (var item in mcps)
{
var mcpClient = await mcpClientManager.GetMcpClientAsync(item.ServerId);
if (mcpClient == null) continue;
var tools = await mcpClient.ListToolsAsync();
var toolNames = item.Functions.Select(x => x.Name).ToList();
var targetTools = tools.Where(x => toolNames.Contains(x.Name, StringComparer.OrdinalIgnoreCase));
foreach (var tool in targetTools)
{
var funDef = AiFunctionHelper.MapToFunctionDef(tool);
if (funDef != null)
{
functionDefs.Add(funDef);
}
}
}
return functionDefs;
}
}