
将 MCP 工具接入 Semantic KernelModelContextProtocolPlugin 示例源码级实战指南【免费下载链接】semantic-kernelIntegrate cutting-edge LLM technology quickly and easily into your apps项目地址: https://gitcode.com/GitHub_Trending/se/semantic-kernel导读本篇文章以 Semantic Kernel 仓库中的 ModelContextProtocolPlugin 示例 为主体完整讲解如何通过 Model Context ProtocolMCP将第三方 MCP Server 暴露的工具接入 Semantic Kernel从创建 MCP 客户端、检索工具列表到将工具转换为 Kernel Function 并借助函数调用Function Calling自动执行。读完本文你将掌握一条可直接复用的 MCP 工具接入链路并能理解AsKernelFunction等桥接 API 的底层实现原理。MCP 是什么为什么 Semantic Kernel 需要它MCPModel Context Protocol是一个开放协议它标准化了应用程序如何向 LLM 提供上下文这一环节。在 MCP 之前接入外部工具通常需要为每个工具服务编写专用的客户端代码和适配层有了 MCP任意实现了该协议的 Server 都能以统一的工具Tool、资源Resource与提示词Prompt形态对外提供服务客户端侧则可以通过同一套抽象消费它们。Semantic Kernel 定位为将前沿 LLM 技术快速、轻松集成到应用中的编排框架。MCP 与它的结合点在于Semantic Kernel 的函数KernelFunction天然适合作为 LLM 可调用的工具而 MCP 恰恰提供了一种标准化的工具供给方式。两者结合后一个 MCP Server 上暴露的工具可以被批量转换为 Semantic Kernel 函数进而参与 Kernel 的函数调用流程甚至被 Agent 使用。示例概览一条完整的 MCP 接入链路ModelContextProtocolPlugin 示例演示了四个环环相扣的步骤使用ModelContextProtocolNuGet 包连接一个 MCP Server检索该 MCP Server 暴露的工具列表将 MCP 工具转换为 Semantic Kernel 函数并注册到 Kernel 实例通过函数调用Function Calling从 Semantic Kernel 中调用这些工具。示例默认连接的是 GitHub MCP Servermodelcontextprotocol/server-github并向模型提出如下问题Summarize the last four commits to the microsoft/semantic-kernel repository?模型会根据问题内容自动决策并调用已注册的 GitHub 工具最后返回摘要结果。环境准备安装前提与项目结构安装 Node.js 与 npm示例通过npx启动 MCP Server因此运行前必须安装 Node.js 与 npm官方下载地址见 nodejs.org。npx会在首次运行时自动拉取modelcontextprotocol/server-github包无需手动全局安装。项目文件构成该示例目录只包含三个文件ModelContextProtocolPlugin.csproj项目配置声明了包引用与项目引用Program.cs全部演示逻辑README.md官方说明文档。从csproj可以看到示例依赖的关键包ItemGroup PackageReference IncludeModelContextProtocol / PackageReference IncludeMicrosoft.Extensions.Configuration.EnvironmentVariables / PackageReference IncludeMicrosoft.Extensions.Configuration.UserSecrets / PackageReference IncludeMicrosoft.Extensions.Logging.Debug / /ItemGroup其中ModelContextProtocol提供了 MCP 客户端与服务端所需的完整 API另外四个包分别用于读取用户机密、环境变量配置与调试日志。除 NuGet 包外示例还通过ProjectReference引用了仓库内的SemanticKernel.Abstractions、SemanticKernel.Core、Agents.Abstractions、Agents.Core以及Connectors.AzureOpenAI等源码项目——这解释了为何它既能运行kernel.InvokePromptAsync也能构建ChatCompletionAgent。配置 OpenAI 凭据Secret Manager 与环境变量示例需要 OpenAI 凭据才能调用对话补全服务。如果你已经在同一解决方案的其它示例中用 Secret Manager 或环境变量配置过凭据此处会自动复用。方式一Secret Manager推荐本地开发在示例目录下初始化并设置用户机密cd dotnet/samples/Demos/ModelContextProtocolPlugin dotnet user-secrets init dotnet user-secrets set OpenAI:ChatModelId ... dotnet user-secrets set OpenAI:ApiKey ...dotnet user-secrets init会在csproj中写入UserSecretsId本例为5ee045b0-aea3-4f08-8d31-32d1a6f8fed0后续set命令即可将键值安全保存在用户主目录的机密存储中避免密钥进入版本控制。方式二环境变量直接以__双下划线作为层级分隔符设置同名配置# OpenAI OpenAI__ChatModelId OpenAI__ApiKey这两种方式均与 Program.cs 中的配置加载逻辑对应var config new ConfigurationBuilder() .AddUserSecretsProgram() .AddEnvironmentVariables() .Build(); if (config[OpenAI:ApiKey] is not { } apiKey) { Console.Error.WriteLine(Please provide a valid OpenAI:ApiKey to run this sample. See the associated README.md for more details.); return; }注意AddUserSecrets先于AddEnvironmentVariables注册因此环境变量的优先级更高可覆盖机密中的同名配置。若OpenAI:ChatModelId未配置代码会回退到默认值gpt-4o-mini。核心实现拆解四步接入链路逐行分析第一步创建 MCP 客户端连接 GitHub Servervar mcpClient await McpClient.CreateAsync(new StdioClientTransport(new() { Name MCPServer, Command npx, Arguments [-y, modelcontextprotocol/server-github], }));McpClient.CreateAsync负责与 MCP Server 建立会话StdioClientTransport表示通过标准输入输出stdio与子进程通信这里以npx -y modelcontextprotocol/server-github启动 GitHub MCP Server。-y参数让 npx 免确认直接安装并运行包。第二步检索 MCP Server 的工具列表var tools await mcpClient.ListToolsAsync().ConfigureAwait(false); foreach (var tool in tools) { Console.WriteLine(${tool.Name}: {tool.Description}); }ListToolsAsync返回McpClientTool列表每个工具包含名称、描述等信息。示例先将其打印到控制台方便观察 GitHub Server 暴露了哪些能力例如搜索代码、读取文件、查询 issue 等。第三步将 MCP 工具转换为 Kernel Function 并注册为插件var builder Kernel.CreateBuilder(); builder.Services .AddLogging(c c.AddDebug().SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace)) .AddOpenAIChatCompletion( modelId: config[OpenAI:ChatModelId] ?? gpt-4o-mini, apiKey: apiKey); Kernel kernel builder.Build(); kernel.Plugins.AddFromFunctions(GitHub, tools.Select(aiFunction aiFunction.AsKernelFunction()));这是整个示例的桥接核心AsKernelFunction()将McpClientTool其本质是Microsoft.Extensions.AI中的AIFunction转换为KernelFunction随后kernel.Plugins.AddFromFunctions(GitHub, ...)以GitHub为插件名批量注册所有工具。插件名会成为函数全名的一部分如GitHub-search_repositories供模型在函数调用时引用。第四步启用自动函数调用并执行OpenAIPromptExecutionSettings executionSettings new() { Temperature 0, FunctionChoiceBehavior FunctionChoiceBehavior.Auto(options: new() { RetainArgumentTypes true }) }; var prompt Summarize the last four commits to the microsoft/semantic-kernel repository?; var result await kernel.InvokePromptAsync(prompt, new(executionSettings)).ConfigureAwait(false); Console.WriteLine($\n\n{prompt}\n{result});FunctionChoiceBehavior.Auto()让 Kernel 在模型需要时自动选择并调用已注册的函数Temperature 0降低输出随机性使工具调用更确定RetainArgumentTypes true则保留参数类型避免 JSON 序列化造成类型丢失。运行时模型会先规划需要哪些 GitHub 工具再由 Kernel 实际执行这些函数最后将结果交还模型生成最终回答。原理纵深AsKernelFunction 的底层实现AsKernelFunction并非 MCP 专属方法而是Microsoft.SemanticKernel命名空间下针对AIFunction的通用扩展其实现位于 AIFunctionExtensions.cspublic static KernelFunction AsKernelFunction(this AIFunction aiFunction) { Verify.NotNull(aiFunction); return aiFunction is KernelFunction kf ? kf : new AIFunctionKernelFunction(aiFunction); }从源码结构看该方法优先复用已是KernelFunction的实例否则包装为AIFunctionKernelFunction位于SemanticKernel.Core的 Contents 目录。这正是 MCP 工具能无缝进入 Kernel 插件体系的根基McpClientTool继承自AIFunction经包装后获得KernelFunction的全部行为——包括被FunctionChoiceBehavior识别、参与KernelArguments传参、支持流式调用与过滤器等。相关行为在 AIFunctionKernelFunctionTests.cs 中有配套单元测试验证。进阶把 MCP 工具交给 Agent 使用示例末尾还演示了同一套工具如何服务于 Agent 场景ChatCompletionAgent agent new() { Instructions Answer questions about GitHub repositories., Name GitHubAgent, Kernel kernel, Arguments new KernelArguments(executionSettings), }; ChatMessageContent response await agent.InvokeAsync(Summarize the last four commits to the microsoft/semantic-kernel repository?).FirstAsync(); Console.WriteLine($\n\nResponse from GitHubAgent:\n{response.Content});ChatCompletionAgent复用同一个注入了 GitHub MCP 工具的 Kernel配合FunctionChoiceBehavior.Auto()即可让 Agent 在对话中按需调用 MCP 工具回答问题。这一模式说明MCP 工具一经转换为 Kernel 函数就能与 Semantic Kernel 的函数调用、Agent、过滤与遥测等全部能力无缝协同。扩展视角仓库中的 MCP 双向集成MCP 与 Semantic Kernel 的集成并非单向。仓库内还有完整的 ModelContextProtocolClientServer 示例其 MCPServer/Program.cs 展示了反向流程——将 Semantic Kernel 插件暴露为 MCP Server 的工具builder.Services .AddMcpServer() .WithStdioServerTransport() .WithTools() // 将 Kernel 插件中的全部函数作为 MCP 工具暴露 .WithPrompt(...) // 注册 MCP 提示词 .WithResourceTemplate(...) // 注册资源模板如向量检索 .WithResource(...); // 注册资源如图片同时MCPToolsSample.cs 展示了与本文相同的客户端消费链路获取工具 →AsKernelFunction→ 自动函数调用。若需处理 MCP 调用中的认证授权可参考同目录下的 ModelContextProtocolPluginAuth 示例。小结通过本示例可以提炼出一条通用的 MCP 工具接入方法论建立连接用McpClient.CreateAsync 合适的传输层stdio 等连接 MCP Server枚举工具用ListToolsAsync获取 Server 的能力清单桥接转换用AsKernelFunction将 MCP 工具批量变为KernelFunction注册使用以插件形式注册进 Kernel配合FunctionChoiceBehavior.Auto实现自动函数调用或直接交付给 Agent。整个链路只有寥寥数行代码却打通了任意 MCP Server → Semantic Kernel 插件 → LLM 函数调用/Agent的完整通道。对希望在应用中以标准协议快速接入外部工具的开发者而言这正是 Semantic Kernel 提供的一条高效集成路径。【免费下载链接】semantic-kernelIntegrate cutting-edge LLM technology quickly and easily into your apps项目地址: https://gitcode.com/GitHub_Trending/se/semantic-kernel创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考