diff --git a/McpStudy.McpClient/Program.cs b/McpStudy.McpClient/Program.cs index 0596563..73652c2 100644 --- a/McpStudy.McpClient/Program.cs +++ b/McpStudy.McpClient/Program.cs @@ -1,47 +1,59 @@ -using System.Diagnostics; -using System.Threading.Tasks; - -using ModelContextProtocol; -using ModelContextProtocol.Client; - -using ModelContextProtocol.AspNetCore; - - - -namespace McpStudy.McpClient; +namespace McpStudy.McpClient; internal class Program { static async Task Main(string[] args) { - Console.WriteLine("调用MCP服务器示例"); + Console.WriteLine("调用MCP服务示例"); + + await CallStdioAsync(); await Task.CompletedTask; } - static async Task CallStdio() + /// + /// 使用Mcp客户端,直接调用Stdio类型的MCP服务 + /// + /// + /// + static async Task CallStdioAsync() { + Console.WriteLine($"开始调用 Studio 类型的MCP服务......{System.Environment.NewLine}"); + var clientTransport = new StdioClientTransport(new StdioClientTransportOptions { Name = "Everything", - Command = "npx", - Arguments = ["-y", "@modelcontextprotocol/server-everything"], + Command = "dotnet", + Arguments = ["run", "--project", "E:\\软件项目\\学习项目\\AI学习\\McpStudy\\McpStudy.McpServerStdio\\McpStudy.McpServerStdio.csproj"], }); - var client = await McpClientFactory.CreateAsync(clientTransport); - // Print the list of tools available from the server. - foreach (var tool in await client.ListToolsAsync()) + 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($"工具名称:{tool.Name}, 工具描述:({tool.Description})"); } + Console.WriteLine($"列举完成{System.Environment.NewLine}"); + + + Console.WriteLine("调用Echo工具......"); + CallToolResult result = await client.CallToolAsync + ( + toolName: "Echo", + arguments: new Dictionary() { ["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}"); - // Execute a tool (this would normally be driven by LLM tool invocations). - var result = await client.CallToolAsync( - "echo", - new Dictionary() { ["message"] = "Hello MCP!" }, - cancellationToken: CancellationToken.None); - // echo always returns one and only one text content object - Console.WriteLine(result.Content.First(c => c.Type == "text").ToString()); + Console.WriteLine("调用 Studio 类型的MCP服务结束!"); } }