BotSharp/src/Infrastructure/BotSharp.Core.MCP/Hooks/MCPToolAgentHook.cs

60 lines
1.8 KiB
C#
Raw Normal View History

using ModelContextProtocol.Client;
2025-03-31 21:43:42 +00:00
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)
2025-03-31 21:43:42 +00:00
{
return;
2025-03-31 21:43:42 +00:00
}
var conv = _services.GetRequiredService<IConversationService>();
var isConvMode = conv.IsConversationMode();
if (!isConvMode) return;
agent.SecondaryFunctions ??= [];
2025-03-02 12:49:07 +00:00
var functions = GetMCPContent(agent).Result;
foreach (var fn in functions)
{
if (!agent.SecondaryFunctions.Any(x => x.Name.Equals(fn.Name, StringComparison.OrdinalIgnoreCase)))
{
agent.SecondaryFunctions.Add(fn);
}
}
}
2025-03-02 12:49:07 +00:00
private async Task<IEnumerable<FunctionDef>> GetMCPContent(Agent agent)
{
2025-03-31 21:43:42 +00:00
var functionDefs = new List<FunctionDef>();
var mcpClientManager = _services.GetRequiredService<MCPClientManager>();
var mcps = agent.McpTools;
foreach (var item in mcps)
{
var mcpClient = await mcpClientManager.GetMcpClientAsync(item.ServerId);
2025-03-02 12:49:07 +00:00
if (mcpClient != null)
{
2025-03-29 02:05:52 +00:00
var tools = await mcpClient.ListToolsAsync();
2025-03-24 01:20:17 +00:00
var toolnames = item.Functions.Select(x => x.Name).ToList();
2025-03-31 21:43:42 +00:00
foreach (var tool in tools.Where(x => toolnames.Contains(x.Name, StringComparer.OrdinalIgnoreCase)))
{
var funDef = AIFunctionUtilities.MapToFunctionDef(tool);
functionDefs.Add(funDef);
2025-03-29 02:23:54 +00:00
}
}
}
return functionDefs;
}
}