使用 SemanticKernel 框架对接 LLM将 MCP Tool 转换为 Function 添加到对话上下文中。var aiModel configuration.GetSection(AIModel); var builder Kernel.CreateBuilder() .AddAzureOpenAIChatCompletion( deploymentName: aiModel[ModelId], endpoint: aiModel[Endpoint], apiKey: aiModel[Key]); builder.Services.AddLogging(s { s.AddConsole(); }); Kernel kernel builder.Build(); // 这里将 mcp 转换为 functaion call kernel.Plugins.AddFromFunctions(amap, tools.Select(aiFunction aiFunction.AsKernelFunction())); var chatCompletionService kernel.GetRequiredServiceIChatCompletionService(); OpenAIPromptExecutionSettings openAIPromptExecutionSettings new() { Temperature 0, FunctionChoiceBehavior FunctionChoiceBehavior.Auto(options: new() { RetainArgumentTypes true }) };第三步对话交互编写控制台与用户对话交互。var history new ChatHistory(); string? userInput; do { Console.Write(用户提问 ); userInput Console.ReadLine(); history.AddUserMessage(userInput!); var result await chatCompletionService.GetChatMessageContentAsync( history, executionSettings: openAIPromptExecutionSettings, kernel: kernel); Console.WriteLine(AI 回答 result); history.AddMessage(result.Role, result.Content ?? string.Empty); } while (userInput is not null);演示地图规划注意由于高德地图免费额度限流而 AI 对话时可能有多次对 MCP Server 请求因此有时候效果并不是那么好。1. 智能旅游路线规划最多支持16个途经点的旅游路线规划自动计算最优顺序并提供可视化地图链接。使用示例请帮我规划一条上海三日游路线包括外滩、东方明珠、迪士尼、豫园、南京路并提供可视化地图2. 景点搜索与详情查询查询景点的详细信息包括评分、开放时间、门票价格等。使用示例请查询黄山风景区的开放时间、门票价格和旅游季节推荐AI 是怎么识别调用 MCP在编写高德地图规划时有一段代码是将 MCP 服务器的接口转换为 Function 的代码如下kernel.Plugins .AddFromFunctions(amap, tools.Select(aiFunction aiFunction.AsKernelFunction()))其实在这里就可以下结论并不是 AI 模型直接调用 MCP Server 的依然 Client 进行是 Function call 。通过拦截 http 请求可以发现当用户输入请帮我规划一条上海三日游路线包括外滩、东方明珠、迪士尼、豫园、南京路并提供可视化地图时客户端首先将用户提问和 mcp 服务所提供的 function call 一起发送到 AI 模型服务器。对话时Client 提供给 LLM 的 Function MCP Tool列表。然后 AI 回答要调用的 Function call 步骤和参数接着由客户端实现将 Function 定位 MCP Server并顺序调用每个 Tool。LLM 返回要顺序调用的 Function 列表以及参数客户端将每个 Function 的执行结果和用户的提问等信息一起再次提交给 AI 模型服务器。由于高德接口并发限制有部分接口调用失败那么客户端可能会来回请求多次最后输出 AI 的回答。到这里读者应该明白 MCP Tool、Plugin、Function Call 的关系了吧实现 Mcp Server前面笔者介绍了 MCP Tool但是 MCP Server 还可以提供很多很有用的功能MCP 协议定义了以下核心模块Core architectureResourcesPromptsToolsSamplingRootsTransports作为当前社区中最关注的 Tools本文已经单独介绍接下来将会以继续讲解其它功能模块。实现 Resources示例项目参考ResourceServer、ResourceClient。Resources 定义Resources 是 Model Context Protocol (MCP) 中的一个核心原语它允许服务器暴露可以被 clients 读取并用作 LLM 交互上下文的数据和内容。Resources 代表 MCP server 想要提供给 clients 的任何类型的数据在使用上MCP Server 可以给每种资源定义一个 Uri这个 Uri 的协议格式可以是虚拟的这不重要只要是能够定位资源的一段 Uri 字符串即可。只看定义读者可能不理解什么意思没关系等后面动手做的时候就知道了。