74 lines
2.4 KiB
C#
74 lines
2.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Threading.Tasks;
|
|
using System.Windows.Documents;
|
|
using ModelContextProtocol.Protocol.Types;
|
|
using Newtonsoft.Json;
|
|
|
|
namespace LinkToolAddin.client;
|
|
|
|
using ModelContextProtocol.Client;
|
|
using ModelContextProtocol.Protocol.Transport;
|
|
|
|
public class StdioMcpClient : McpClient
|
|
{
|
|
private List<string> arguments;
|
|
private StdioClientTransportOptions transportOptions;
|
|
|
|
public StdioMcpClient(string command,List<string> arguments)
|
|
{
|
|
this.arguments = arguments;
|
|
transportOptions = new StdioClientTransportOptions()
|
|
{
|
|
Command = command,
|
|
Arguments = this.arguments
|
|
};
|
|
}
|
|
|
|
public static async Task<string> StdioMcpTest()
|
|
{
|
|
List<string> arguments = new List<string>();
|
|
arguments.Add("mcp-server-time");
|
|
arguments.Add("--local-timezone=America/New_York");
|
|
StdioClientTransportOptions transportOptions = new StdioClientTransportOptions()
|
|
{
|
|
Command = "uvx", // 运行服务器的命令
|
|
Arguments = arguments
|
|
};
|
|
var client = await McpClientFactory.CreateAsync(new StdioClientTransport(transportOptions));
|
|
var tools = await client.ListToolsAsync();
|
|
Console.WriteLine("Available Tools:");
|
|
foreach (var tool in tools)
|
|
{
|
|
Console.WriteLine($"- {tool.Name}");
|
|
}
|
|
|
|
var result = await client.CallToolAsync("get_current_time",
|
|
new Dictionary<string, object> { { "timezone", "America/New_York" } });
|
|
Console.WriteLine(JsonConvert.SerializeObject(result));
|
|
return tools[0].Name;
|
|
}
|
|
|
|
public async Task<IList<McpClientTool>> GetToolListAsync()
|
|
{
|
|
try
|
|
{
|
|
IMcpClient client = await McpClientFactory.CreateAsync(new StdioClientTransport(transportOptions));
|
|
IList<McpClientTool> tools = await client.ListToolsAsync();
|
|
return tools;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine(ex.Message);
|
|
return null;
|
|
}
|
|
|
|
}
|
|
|
|
public async Task<CallToolResponse> CallToolAsync(string toolName, Dictionary<string, object> parameters = null)
|
|
{
|
|
IMcpClient client = await McpClientFactory.CreateAsync(new StdioClientTransport(transportOptions));
|
|
CallToolResponse result = await client.CallToolAsync(toolName,parameters);
|
|
return result;
|
|
}
|
|
} |