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

64 lines
2 KiB
C#
Raw Normal View History

2025-04-01 01:59:19 +00:00
using BotSharp.Core.MCP.Helpers;
using BotSharp.Core.MCP.Managers;
2025-04-01 15:24:48 +00:00
using BotSharp.Core.MCP.Settings;
using ModelContextProtocol.Client;
2025-03-31 21:43:42 +00:00
namespace BotSharp.Core.MCP.Hooks;
2025-04-01 01:59:19 +00:00
public class McpToolAgentHook : AgentHookBase
{
public override string SelfId => string.Empty;
2025-04-01 01:59:19 +00:00
public McpToolAgentHook(IServiceProvider services, AgentSettings settings)
: base(services, settings)
{
}
2025-04-01 01:59:19 +00:00
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-04-01 01:59:19 +00:00
var functions = GetMcpContent(agent).Result;
2025-05-07 21:34:39 +00:00
agent.SecondaryFunctions = agent.SecondaryFunctions.Concat(functions).DistinctBy(x => x.Name).ToList();
}
2025-04-01 01:59:19 +00:00
private async Task<IEnumerable<FunctionDef>> GetMcpContent(Agent agent)
{
2025-03-31 21:43:42 +00:00
var functionDefs = new List<FunctionDef>();
2025-04-01 15:24:48 +00:00
var settings = _services.GetRequiredService<McpSettings>();
if (settings?.Enabled != true)
{
return functionDefs;
}
2025-04-01 01:59:19 +00:00
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);
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)))
{
2025-04-01 01:59:19 +00:00
var funDef = AiFunctionHelper.MapToFunctionDef(tool);
functionDefs.Add(funDef);
2025-03-29 02:23:54 +00:00
}
}
}
return functionDefs;
}
}