You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
2.0 KiB
C#

namespace McpStudy.McpClient;
3 days ago
internal class Program
{
3 days ago
static async Task Main(string[] args)
{
Console.WriteLine("调用MCP服务示例");
await CallStdioAsync();
3 days ago
await Task.CompletedTask;
}
/// <summary>
/// 使用Mcp客户端直接调用Stdio类型的MCP服务
///
/// </summary>
/// <returns></returns>
static async Task CallStdioAsync()
{
Console.WriteLine($"开始调用 Studio 类型的MCP服务......{System.Environment.NewLine}");
var clientTransport = new StdioClientTransport(new StdioClientTransportOptions
{
Name = "Everything",
Command = "dotnet",
Arguments = ["run", "--project", "E:\\软件项目\\学习项目\\AI学习\\McpStudy\\McpStudy.McpServerStdio\\McpStudy.McpServerStdio.csproj"],
});
Console.WriteLine("创建客户端......");
IMcpClient client = await McpClientFactory.CreateAsync(clientTransport);
Console.WriteLine($"创建客户端完成{System.Environment.NewLine}");
Console.WriteLine("列举MCP服务中可用的工具......");
foreach (McpClientTool tool in await client.ListToolsAsync())
{
Console.WriteLine($"工具名称:{tool.Name} 工具描述:({tool.Description})");
}
Console.WriteLine($"列举完成{System.Environment.NewLine}");
Console.WriteLine("调用Echo工具......");
CallToolResult result = await client.CallToolAsync
(
toolName: "Echo",
arguments: new Dictionary<string, object?>() { ["message"] = "Hello MCP!" },
cancellationToken: CancellationToken.None
);
Console.Write("Echo工具结果");
var content = result.Content.First(c => c.Type == "text") as TextContentBlock;
Console.WriteLine(content?.Text);
Console.WriteLine($"调用完成{System.Environment.NewLine}");
Console.WriteLine("调用 Studio 类型的MCP服务结束");
}
}