-
-
Notifications
You must be signed in to change notification settings - Fork 638
Expand file tree
/
Copy pathMCPToolAgentHook.cs
More file actions
63 lines (52 loc) · 2.01 KB
/
Copy pathMCPToolAgentHook.cs
File metadata and controls
63 lines (52 loc) · 2.01 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
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.GetRequiredService<McpClientManager>();
var mcps = agent.McpTools.Where(x => !x.Disabled);
foreach (var item in mcps)
{
var mcpClient = await mcpClientManager.GetMcpClientAsync(item.ServerId);
if (mcpClient != null)
{
var tools = await mcpClient.ListToolsAsync();
var toolnames = item.Functions.Select(x => x.Name).ToList();
foreach (var tool in tools.Where(x => toolnames.Contains(x.Name, StringComparer.OrdinalIgnoreCase)))
{
var funDef = AiFunctionHelper.MapToFunctionDef(tool);
functionDefs.Add(funDef);
}
}
}
return functionDefs;
}
}