refine mcp

This commit is contained in:
Jicheng Lu 2025-03-31 16:43:42 -05:00
parent 5eca6b484f
commit 74476030e1
18 changed files with 64 additions and 94 deletions

View file

@ -127,12 +127,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BotSharp.Core.Rules", "src\
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BotSharp.Plugin.DeepSeekAI", "src\Plugins\BotSharp.Plugin.DeepSeekAI\BotSharp.Plugin.DeepSeekAI.csproj", "{AF329442-B48E-4B48-A18A-1C869D1BA6F5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BotSharp.MCP", "src\Infrastructure\BotSharp.MCP\BotSharp.MCP.csproj", "{684781D5-3DD4-6A0B-B53F-0A362CD6BB0C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BotSharp.Core.Realtime", "src\Infrastructure\BotSharp.Core.Realtime\BotSharp.Core.Realtime.csproj", "{781F1465-365C-0F22-1775-25025DAFA4C7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BotSharp.PizzaBot.MCPServer", "tests\BotSharp.PizzaBot.MCPServer\BotSharp.PizzaBot.MCPServer.csproj", "{8D2AD45F-836A-516F-DE6A-71443CEBB18A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BotSharp.Core.MCP", "src\Infrastructure\BotSharp.Core.MCP\BotSharp.Core.MCP.csproj", "{534D1DD5-9D62-115C-F230-47080D76CE52}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -525,14 +525,6 @@ Global
{AF329442-B48E-4B48-A18A-1C869D1BA6F5}.Release|Any CPU.Build.0 = Release|Any CPU
{AF329442-B48E-4B48-A18A-1C869D1BA6F5}.Release|x64.ActiveCfg = Release|Any CPU
{AF329442-B48E-4B48-A18A-1C869D1BA6F5}.Release|x64.Build.0 = Release|Any CPU
{684781D5-3DD4-6A0B-B53F-0A362CD6BB0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{684781D5-3DD4-6A0B-B53F-0A362CD6BB0C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{684781D5-3DD4-6A0B-B53F-0A362CD6BB0C}.Debug|x64.ActiveCfg = Debug|Any CPU
{684781D5-3DD4-6A0B-B53F-0A362CD6BB0C}.Debug|x64.Build.0 = Debug|Any CPU
{684781D5-3DD4-6A0B-B53F-0A362CD6BB0C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{684781D5-3DD4-6A0B-B53F-0A362CD6BB0C}.Release|Any CPU.Build.0 = Release|Any CPU
{684781D5-3DD4-6A0B-B53F-0A362CD6BB0C}.Release|x64.ActiveCfg = Release|Any CPU
{684781D5-3DD4-6A0B-B53F-0A362CD6BB0C}.Release|x64.Build.0 = Release|Any CPU
{781F1465-365C-0F22-1775-25025DAFA4C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{781F1465-365C-0F22-1775-25025DAFA4C7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{781F1465-365C-0F22-1775-25025DAFA4C7}.Debug|x64.ActiveCfg = Debug|Any CPU
@ -549,6 +541,14 @@ Global
{8D2AD45F-836A-516F-DE6A-71443CEBB18A}.Release|Any CPU.Build.0 = Release|Any CPU
{8D2AD45F-836A-516F-DE6A-71443CEBB18A}.Release|x64.ActiveCfg = Release|Any CPU
{8D2AD45F-836A-516F-DE6A-71443CEBB18A}.Release|x64.Build.0 = Release|Any CPU
{534D1DD5-9D62-115C-F230-47080D76CE52}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{534D1DD5-9D62-115C-F230-47080D76CE52}.Debug|Any CPU.Build.0 = Debug|Any CPU
{534D1DD5-9D62-115C-F230-47080D76CE52}.Debug|x64.ActiveCfg = Debug|Any CPU
{534D1DD5-9D62-115C-F230-47080D76CE52}.Debug|x64.Build.0 = Debug|Any CPU
{534D1DD5-9D62-115C-F230-47080D76CE52}.Release|Any CPU.ActiveCfg = Release|Any CPU
{534D1DD5-9D62-115C-F230-47080D76CE52}.Release|Any CPU.Build.0 = Release|Any CPU
{534D1DD5-9D62-115C-F230-47080D76CE52}.Release|x64.ActiveCfg = Release|Any CPU
{534D1DD5-9D62-115C-F230-47080D76CE52}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -610,9 +610,9 @@ Global
{F812BAAE-5A7D-4DF7-8E71-70696B51C61F} = {E29DC6C4-5E57-48C5-BCB0-6B8F84782749}
{AFD64412-4D6A-452E-82A2-79E5D8842E29} = {E29DC6C4-5E57-48C5-BCB0-6B8F84782749}
{AF329442-B48E-4B48-A18A-1C869D1BA6F5} = {D5293208-2BEF-42FC-A64C-5954F61720BA}
{684781D5-3DD4-6A0B-B53F-0A362CD6BB0C} = {E29DC6C4-5E57-48C5-BCB0-6B8F84782749}
{781F1465-365C-0F22-1775-25025DAFA4C7} = {E29DC6C4-5E57-48C5-BCB0-6B8F84782749}
{8D2AD45F-836A-516F-DE6A-71443CEBB18A} = {32FAFFFE-A4CB-4FEE-BF7C-84518BBC6DCC}
{534D1DD5-9D62-115C-F230-47080D76CE52} = {E29DC6C4-5E57-48C5-BCB0-6B8F84782749}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A9969D89-C98B-40A5-A12B-FC87E55B3A19}

View file

@ -1,10 +1,7 @@
using BotSharp.Abstraction.Functions.Models;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Types;
using System;
using System.Collections.Generic;
using System.Text.Json;
using ModelContextProtocol.Client;
namespace BotSharp.Core.MCP;
internal static class AIFunctionUtilities
@ -19,7 +16,7 @@ internal static class AIFunctionUtilities
var properties = tool.JsonSchema.GetProperty("properties");
var required = tool.JsonSchema.GetProperty("required");
FunctionDef funDef = new FunctionDef
var funDef = new FunctionDef
{
Name = tool.Name,
Description = tool.Description ?? string.Empty,

View file

@ -1,21 +1,11 @@
using BotSharp.Abstraction.Agents;
using BotSharp.Abstraction.Functions;
using BotSharp.Core.Mcp.Functions;
using BotSharp.Core.Mcp.Settings;
using BotSharp.Core.Mcp;
using BotSharp.MCP.Hooks;
using BotSharp.Core.MCP.Functions;
using BotSharp.Core.MCP.Settings;
using BotSharp.Core.MCP.Hooks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ModelContextProtocol.Client;
namespace BotSharp.MCP;
namespace BotSharp.Core.MCP;
public static class BotSharpMCPExtensions
{
@ -25,14 +15,12 @@ public static class BotSharpMCPExtensions
/// <param name="services"></param>
/// <param name="config"></param>
/// <returns></returns>
public static IServiceCollection AddBotSharpMCP(this IServiceCollection services,
IConfiguration config)
public static IServiceCollection AddBotSharpMCP(this IServiceCollection services, IConfiguration config)
{
var settings = config.GetSection("MCPSettings").Get<MCPSettings>();
services.AddScoped<MCPSettings>(provider => { return settings; });
if (settings != null)
{
var clientManager = new MCPClientManager(settings);
services.AddSingleton(clientManager);

View file

@ -1,27 +1,17 @@
using BotSharp.Abstraction.Agents;
using BotSharp.Abstraction.Conversations.Models;
using BotSharp.Abstraction.Functions;
using BotSharp.Abstraction.Utilities;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using ModelContextProtocol.Client;
namespace BotSharp.Core.Mcp.Functions;
namespace BotSharp.Core.MCP.Functions;
public class McpToolAdapter : IFunctionCallback
{
private readonly McpClientTool _tool;
private readonly MCPClientManager _clientManager;
private readonly IServiceProvider _serviceProvider;
private readonly IServiceProvider _services;
public McpToolAdapter(IServiceProvider provider, McpClientTool tool, MCPClientManager client)
public McpToolAdapter(IServiceProvider services, McpClientTool tool, MCPClientManager client)
{
_serviceProvider = provider ?? throw new ArgumentNullException(nameof(provider));
_services = services ?? throw new ArgumentNullException(nameof(services));
_tool = tool ?? throw new ArgumentNullException(nameof(tool));
_clientManager = client ?? throw new ArgumentNullException(nameof(client));
}
@ -33,21 +23,18 @@ public class McpToolAdapter : IFunctionCallback
// Convert arguments to dictionary format expected by mcpdotnet
Dictionary<string, object> argDict = JsonToDictionary(message.FunctionArgs);
var currentAgentId = message.CurrentAgentId;
var agentService = _serviceProvider.GetRequiredService<IAgentService>();
var agentService = _services.GetRequiredService<IAgentService>();
var agent = await agentService.LoadAgent(currentAgentId);
var serverId = agent.McpTools.Where(t => t.Functions.Any(f => f.Name == Name)).FirstOrDefault().ServerId;
var client = await _clientManager.GetMcpClientAsync(serverId);
// Call the tool through mcpdotnet
var result = await client.CallToolAsync(
_tool.Name,
argDict.Count == 0 ? new() : argDict
);
var result = await client.CallToolAsync(_tool.Name, argDict.IsNullOrEmpty() ? new() : argDict);
// Extract the text content from the result
var json = string.Join("\n", result.Content
.Where(c => c.Type == "text")
.Select(c => c.Text));
var json = string.Join("\n", result.Content.Where(c => c.Type == "text").Select(c => c.Text));
message.Content = json;
message.Data = json.JsonContent();
return true;

View file

@ -1,19 +1,6 @@
using BotSharp.Abstraction.Agents;
using BotSharp.Abstraction.Agents.Enums;
using BotSharp.Abstraction.Agents.Models;
using BotSharp.Abstraction.Agents.Settings;
using BotSharp.Abstraction.Conversations;
using BotSharp.Abstraction.Functions.Models;
using BotSharp.Core.Mcp;
using BotSharp.Core.MCP;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BotSharp.MCP.Hooks;
namespace BotSharp.Core.MCP.Hooks;
public class MCPToolAgentHook : AgentHookBase
{
@ -27,7 +14,10 @@ public class MCPToolAgentHook : AgentHookBase
public override void OnAgentMCPToolLoaded(Agent agent)
{
if (agent.Type == AgentType.Routing)
{
return;
}
var conv = _services.GetRequiredService<IConversationService>();
var isConvMode = conv.IsConversationMode();
if (!isConvMode) return;
@ -35,7 +25,6 @@ public class MCPToolAgentHook : AgentHookBase
agent.SecondaryFunctions ??= [];
var functions = GetMCPContent(agent).Result;
foreach (var fn in functions)
{
if (!agent.SecondaryFunctions.Any(x => x.Name.Equals(fn.Name, StringComparison.OrdinalIgnoreCase)))
@ -47,7 +36,7 @@ public class MCPToolAgentHook : AgentHookBase
private async Task<IEnumerable<FunctionDef>> GetMCPContent(Agent agent)
{
List<FunctionDef> functionDefs = new List<FunctionDef>();
var functionDefs = new List<FunctionDef>();
var mcpClientManager = _services.GetRequiredService<MCPClientManager>();
var mcps = agent.McpTools;
foreach (var item in mcps)
@ -57,7 +46,7 @@ public class MCPToolAgentHook : AgentHookBase
{
var tools = await mcpClient.ListToolsAsync();
var toolnames = item.Functions.Select(x => x.Name).ToList();
foreach (var tool in tools.ToList().Where(x => toolnames.Contains(x.Name, StringComparer.OrdinalIgnoreCase)))
foreach (var tool in tools.Where(x => toolnames.Contains(x.Name, StringComparer.OrdinalIgnoreCase)))
{
var funDef = AIFunctionUtilities.MapToFunctionDef(tool);
functionDefs.Add(funDef);

View file

@ -1,11 +1,7 @@
using BotSharp.Core.Mcp.Settings;
using Microsoft.Extensions.Logging;
using BotSharp.Core.MCP.Settings;
using ModelContextProtocol.Client;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace BotSharp.Core.Mcp;
namespace BotSharp.Core.MCP;
public class MCPClientManager : IDisposable
{

View file

@ -1,13 +1,11 @@
using ModelContextProtocol.Client;
using ModelContextProtocol.Configuration;
using System.Collections.Generic;
namespace BotSharp.Core.Mcp.Settings;
namespace BotSharp.Core.MCP.Settings;
public class MCPSettings
{
public McpClientOptions McpClientOptions { get; set; }
public List<McpServerConfig> McpServerConfigs { get; set; } = new();
}

View file

@ -0,0 +1,16 @@
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading.Tasks;
global using Microsoft.Extensions.DependencyInjection;
global using BotSharp.Abstraction.Agents;
global using BotSharp.Abstraction.Agents.Enums;
global using BotSharp.Abstraction.Agents.Models;
global using BotSharp.Abstraction.Agents.Settings;
global using BotSharp.Abstraction.Conversations;
global using BotSharp.Abstraction.Conversations.Models;
global using BotSharp.Abstraction.Functions;
global using BotSharp.Abstraction.Functions.Models;
global using BotSharp.Abstraction.Utilities;

View file

@ -72,7 +72,7 @@ public partial class AgentService
hook.OnAgentUtilityLoaded(agent);
}
if(agent.McpTools != null && agent.McpTools.Count >0)
if(!agent.McpTools.IsNullOrEmpty())
{
hook.OnAgentMCPToolLoaded(agent);
}

View file

@ -47,8 +47,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BotSharp.Core\BotSharp.Core.csproj" />
<ProjectReference Include="..\BotSharp.MCP\BotSharp.MCP.csproj" />
<ProjectReference Include="..\BotSharp.Core\BotSharp.Core.csproj" />
</ItemGroup>
<ItemGroup>

View file

@ -24,7 +24,7 @@ public class AgentViewModel
[JsonPropertyName("merge_utility")]
public bool MergeUtility { get; set; }
public List<AgentUtility> Utilities { get; set; }
public List<MCPTool> Acps { get; set; }
public List<MCPTool> McpTools { get; set; }
[JsonPropertyName("knowledge_bases")]
public List<AgentKnowledgeBase> KnowledgeBases { get; set; }
@ -87,7 +87,7 @@ public class AgentViewModel
Responses = agent.Responses ?? [],
Samples = agent.Samples ?? [],
Utilities = agent.Utilities ?? [],
Acps = agent.McpTools ?? [],
McpTools = agent.McpTools ?? [],
KnowledgeBases = agent.KnowledgeBases ?? [],
IsPublic= agent.IsPublic,
Disabled = agent.Disabled,

View file

@ -6,9 +6,7 @@ namespace BotSharp.Plugin.MongoStorage.Models;
public class AgentMCPToolMongoElement
{
public string Name { get; set; }
public string ServerId { get; set; }
public bool Disabled { get; set; }
public List<McpFunctionMongoElement> Functions { get; set; } = [];
@ -31,6 +29,7 @@ public class AgentMCPToolMongoElement
}
}
[BsonIgnoreExtraElements(Inherited = true)]
public class McpFunctionMongoElement
{
public string Name { get; set; }

View file

@ -7,5 +7,5 @@ namespace BotSharp.Plugin.OpenAI.Providers.Realtime;
public interface IOpenAiRealtimeApi
{
[Post("/v1/realtime/sessions")]
Task<RealtimeSession> GetSessionAsync(RealtimeSessionCreationRequest model, [Authorize("Bearer")] string token);
Task<RealtimeSession> CreateSessionAsync(RealtimeSessionCreationRequest model, [Authorize("Bearer")] string token);
}

View file

@ -297,7 +297,7 @@ public class RealTimeCompletionProvider : IRealTimeCompletion
var settings = settingsService.GetSetting(Provider, args.Model ?? _model);
var api = _services.GetRequiredService<IOpenAiRealtimeApi>();
var session = await api.GetSessionAsync(args, settings.ApiKey);
var session = await api.CreateSessionAsync(args, settings.ApiKey);
return session;
}

View file

@ -1,11 +1,11 @@
using BotSharp.Core;
using BotSharp.Core.MCP;
using BotSharp.OpenAPI;
using BotSharp.Logger;
using BotSharp.Plugin.ChatHub;
using Serilog;
using BotSharp.Abstraction.Messaging.JsonConverters;
using StackExchange.Redis;
using BotSharp.MCP;
var builder = WebApplication.CreateBuilder(args);

View file

@ -30,6 +30,7 @@
<ItemGroup>
<ProjectReference Include="..\..\tests\BotSharp.Plugin.PizzaBot\BotSharp.Plugin.PizzaBot.csproj" />
<ProjectReference Include="..\BotSharp.ServiceDefaults\BotSharp.ServiceDefaults.csproj" />
<ProjectReference Include="..\Infrastructure\BotSharp.Core.MCP\BotSharp.Core.MCP.csproj" />
</ItemGroup>
<ItemGroup Condition="$(SolutionName)==BotSharp">
@ -72,7 +73,6 @@
<ProjectReference Include="..\Plugins\BotSharp.Plugin.MetaGLM\BotSharp.Plugin.MetaGLM.csproj" />
<ProjectReference Include="..\Plugins\BotSharp.Plugin.Planner\BotSharp.Plugin.Planner.csproj" />
<ProjectReference Include="..\Plugins\BotSharp.Plugin.TencentCos\BotSharp.Plugin.TencentCos.csproj" />
<ProjectReference Include="..\Infrastructure\BotSharp.MCP\BotSharp.MCP.csproj" />
</ItemGroup>
<ItemGroup>

View file

@ -412,6 +412,7 @@
"BotSharp.Core.SideCar",
"BotSharp.Core.Crontab",
"BotSharp.Core.Realtime",
"BotSharp.Core.MCP",
"BotSharp.Logger",
"BotSharp.Plugin.MongoStorage",
"BotSharp.Plugin.Dashboard",