2025-04-01 01:59:19 +00:00
|
|
|
using BotSharp.Core.MCP.Settings;
|
|
|
|
|
using ModelContextProtocol.Client;
|
2025-04-15 05:25:03 +00:00
|
|
|
using ModelContextProtocol.Protocol.Transport;
|
2025-04-01 01:59:19 +00:00
|
|
|
|
|
|
|
|
namespace BotSharp.Core.MCP.Managers;
|
|
|
|
|
|
|
|
|
|
public class McpClientManager : IDisposable
|
|
|
|
|
{
|
2025-04-01 03:11:18 +00:00
|
|
|
private readonly McpSettings _mcpSettings;
|
2025-04-01 01:59:19 +00:00
|
|
|
|
2025-04-01 03:11:18 +00:00
|
|
|
public McpClientManager(McpSettings mcpSettings)
|
2025-04-01 01:59:19 +00:00
|
|
|
{
|
2025-04-01 03:11:18 +00:00
|
|
|
_mcpSettings = mcpSettings;
|
2025-04-01 01:59:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<IMcpClient> GetMcpClientAsync(string serverId)
|
|
|
|
|
{
|
2025-04-15 05:25:03 +00:00
|
|
|
var config = _mcpSettings.McpServerConfigs.Where(x => x.Id == serverId).FirstOrDefault();
|
|
|
|
|
|
|
|
|
|
IClientTransport transport;
|
|
|
|
|
if (config.SseConfig != null)
|
|
|
|
|
{
|
|
|
|
|
transport = new SseClientTransport(new SseClientTransportOptions
|
|
|
|
|
{
|
|
|
|
|
Name = config.Name,
|
|
|
|
|
Endpoint = new Uri(config.SseConfig.EndPoint)
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
else if (config.StdioConfig != null)
|
|
|
|
|
{
|
|
|
|
|
transport = new StdioClientTransport(new StdioClientTransportOptions
|
|
|
|
|
{
|
|
|
|
|
Name = config.Name,
|
|
|
|
|
Command = config.StdioConfig.Command,
|
|
|
|
|
Arguments = config.StdioConfig.Arguments,
|
|
|
|
|
EnvironmentVariables = config.StdioConfig.EnvironmentVariables
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
throw new ArgumentNullException("Invalid MCP server configuration!");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return await McpClientFactory.CreateAsync(transport, _mcpSettings.McpClientOptions);
|
2025-04-01 01:59:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Dispose()
|
|
|
|
|
{
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|