创建 MCP client
# 如果调用本地开发项目,使用如下调用参数
Command = "dotnet", Arguments = ["run", "--project", GetMcpServerProjectDirectory(),],
# 使用标准输入/输出(Stdio)传输作为示例 transport, 该方式为父子进程间调用
# 使用 dnx 调用,程序会从 nuget 上
var stdioClientTransportOptions = new StdioClientTransportOptions
{
Name = "Minimal MCP Server",
Command = "dnx",
Arguments = ["iox.SampleMcpServer@0.2.3-beta", "--yes",],
EnvironmentVariables = new Dictionary<string, string?>
{
["SENIVERSE_KEY"] = "xxxx",
},
StandardErrorLines = this.LogInfo,
};
var mcpClient = await McpClient.CreateAsync(new StdioClientTransport(stdioClientTransportOptions));
return mcpClient;
通过 TOOLS 供 AI 调用
# 创建 mcp client 连接天气 mcp
var mcpClient = await this.CreateMcpClient();
# 返回 AI 调用的工作列表
var tools = await mcpClient.ListToolsAsync();
# 进行聊天,传入天气工具, 设置 IChatClient.UseFunctionInvocation()
using var chateClient = serviceProvider.GetRequiredService<IChatClient>().ConfigChatClient(it => it.UseFunctionInvocation());
var chatResponse = await chateClient.GetResponseAsync(new ChatMessage(ChatRole.User, "现在南京的天气"), new ChatOptions { Tools = [.. tools,], });
# 输出结果
this.LogInfo(chatResponse.Text);
代码直接调用 Mcp 函数
# 创建 mcp client 连接天气 mcp
var mcpClient = await this.CreateMcpClient();
# 第一次调用, 列出可用工具, 看一下真实的函数名
await mcpClient.ListToolsAsync()
# 下面是查询城市的天气,第一步是根据城市名称查出城市 ID, 第二步使用城市 ID 去查询天气
# 查询城市 id
var arguments = new Dictionary<string, object?> { { "cityName", "南京" }, };
var result = await mcpClient.CallToolAsync("get_city_id_from_city_name", arguments);
# 从返回结果中解析出需要的内容, 一般都是 TextContentBlock 格式返回
if (result.Content.FirstOrDefault() is not TextContentBlock idContent) { return; }
var cityId = idContent.Text;
# 根据城市 id 查询天气
arguments = new Dictionary<string, object?> { { "cityId", cityId }, };
result = await mcpClient.CallToolAsync("get_city_weather", arguments);
# 解析出返回内容
if (result.Content.FirstOrDefault() is not TextContentBlock weatherContent){ return;}
# 输出天气
this.LogObjectInfo(weatherContent.Text);
列出 MCP Server 工具列表
var mcpClient = await this.CreateMcpClient();
# 列出可用工具的函数名及描述
var list = await mcpClient.ListToolsAsync();
foreach (var tool in list)
{
this.LogInfo($"发现工具 {tool.Name} ({tool.Description})");
}
相关链接
快速入门 - 使用 .NET 创建最小 MCP 客户端 - .NET | Microsoft Learn