{"id":4347,"date":"2025-03-05T07:29:56","date_gmt":"2025-03-05T15:29:56","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/semantic-kernel\/?p=4347"},"modified":"2025-07-08T23:11:08","modified_gmt":"2025-07-09T06:11:08","slug":"integrating-model-context-protocol-tools-with-semantic-kernel-a-step-by-step-guide","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/agent-framework\/integrating-model-context-protocol-tools-with-semantic-kernel-a-step-by-step-guide\/","title":{"rendered":"Integrating Model Context Protocol Tools with Semantic Kernel: A Step-by-Step Guide"},"content":{"rendered":"<p>This post describes how to use Model Context Protocol tools with Semantic Kernel. Model Context Protocol (MCP) is an open protocol that standardizes how applications provide context to LLMs. MCP standardizes the connection between AI models and various data sources and tools.<\/p>\n<p>The Model Context Protocol is significant because it enhances the way AI models interface with data and tools, promoting interoperability, flexibility, and improved contextual understanding. Its potential applications span various domains including, data integration and knowledge management, making it a valuable component in the development of advanced AI solutions.<\/p>\n<p>The sample described in this post focusses on connecting an AI model to an MCP tool via function calling.<\/p>\n<p>For more information on Model Context Protocol (MCP) please refer to the <a href=\"https:\/\/modelcontextprotocol.io\/introduction\">documentation<\/a>.<\/p>\n<p>This sample described below uses the official <a href=\"https:\/\/www.nuget.org\/packages\/mcpdotnet\">ModelContextProtocol<\/a> package is influenced by these <a href=\"https:\/\/github.com\/PederHP\/mcpdotnet\/tree\/main\/samples\">samples<\/a>.<\/p>\n<p>The sample shows:<\/p>\n<ol>\n<li>How to connect to an MCP Server using <a href=\"https:\/\/www.nuget.org\/packages\/mcpdotnet\">ModelContextProtocol<\/a><\/li>\n<li>Retrieve the list of tools the MCP Server makes available<\/li>\n<li>Convert the MCP tools to Semantic Kernel functions so they can be added to a Kernel instance<\/li>\n<li>Invoke the MCP tools from Semantic Kernel in response to LLM function calling requests<\/li>\n<\/ol>\n<p>Full source code for the sample is available in the <a href=\"https:\/\/github.com\/microsoft\/semantic-kernel\/tree\/main\/dotnet\/samples\/Demos\/ModelContextProtocolPlugin\">Semantic Kernel repository<\/a>.<\/p>\n<h4>Build a Kernel with OpenAI Chat Completion<\/h4>\n<p>The sample use OpenAI so you must provide a valid API Key. You can do this via <a href=\"https:\/\/github.com\/microsoft\/semantic-kernel\/tree\/main\/dotnet\/samples\/Demos\/ModelContextProtocol#to-set-your-secrets-with-secret-manager\">user secrets<\/a> or an <a href=\"https:\/\/github.com\/microsoft\/semantic-kernel\/tree\/main\/dotnet\/samples\/Demos\/ModelContextProtocol#to-set-your-secrets-with-environment-variables\">environment variable<\/a>.<\/p>\n<pre class=\"prettyprint language-cs language-csharp\"><code class=\"language-cs language-csharp\">\/\/ Prepare and build kernel\r\nvar builder = Kernel.CreateBuilder();\r\nbuilder.Services.AddLogging(c =&gt; c.AddDebug().SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace));\r\nbuilder.Services.AddOpenAIChatCompletion(\r\n    modelId: config[\"OpenAI:ChatModelId\"] ?? \"gpt-4o\",\r\n    apiKey: config[\"OpenAI:ApiKey\"]!);\r\nKernel kernel = builder.Build();<\/code><\/pre>\n<p>&nbsp;<\/p>\n<h4>Create an MCP Client<\/h4>\n<p>MCP follows a client-server architecture where a host application can connect to an MCP server using an MCP client.<\/p>\n<p>For this sample the architecture can be represented as follows:<\/p>\n<p><a href=\"https:\/\/devblogs.microsoft.com\/semantic-kernel\/wp-content\/uploads\/sites\/78\/2025\/03\/SKMCP.png\"><img decoding=\"async\" class=\"alignnone wp-image-4361\" src=\"https:\/\/devblogs.microsoft.com\/semantic-kernel\/wp-content\/uploads\/sites\/78\/2025\/03\/SKMCP.png\" alt=\"Image SK MCP\" width=\"1003\" height=\"121\" srcset=\"https:\/\/devblogs.microsoft.com\/agent-framework\/wp-content\/uploads\/sites\/78\/2025\/03\/SKMCP.png 1739w, https:\/\/devblogs.microsoft.com\/agent-framework\/wp-content\/uploads\/sites\/78\/2025\/03\/SKMCP-300x36.png 300w, https:\/\/devblogs.microsoft.com\/agent-framework\/wp-content\/uploads\/sites\/78\/2025\/03\/SKMCP-1024x124.png 1024w, https:\/\/devblogs.microsoft.com\/agent-framework\/wp-content\/uploads\/sites\/78\/2025\/03\/SKMCP-768x93.png 768w, https:\/\/devblogs.microsoft.com\/agent-framework\/wp-content\/uploads\/sites\/78\/2025\/03\/SKMCP-1536x185.png 1536w\" sizes=\"(max-width: 1003px) 100vw, 1003px\" \/><\/a><\/p>\n<ul>\n<li><strong>MCP Hosts<\/strong>: Programs like IDEs, or AI tools that want to access data through MCP<\/li>\n<li><strong>MCP Clients<\/strong>: Protocol clients that maintain 1:1 connections with servers<\/li>\n<li><strong>MCP Servers<\/strong>: Lightweight programs that each expose specific capabilities through the standardized Model Context Protocol<\/li>\n<\/ul>\n<p>The following code will create an MCP Client which is configured to connect to a local GitHub server using the stdio transport. The code will start the GitHub server using the <span style=\"font-family: 'courier new', courier, monospace;\">npx<\/span> command.<\/p>\n<p><div class=\"alert alert-primary\"><p class=\"alert-divider\"><i class=\"fabric-icon fabric-icon--Info\"><\/i><strong>What is npx?<\/strong><\/p>npx is a command-line tool that comes with Node.js (starting from version 5.2.0) and is a part of the npm (Node Package Manager) ecosystem. It is used to execute Node.js packages directly from the command line without needing to install them globally on your system.<\/div><\/p>\n<pre class=\"prettyprint language-cs language-csharp\"><code class=\"language-cs language-csharp\">\/\/ Create an MCPClient for the GitHub server\r\nawait using IMcpClient mcpClient = await McpClientFactory.CreateAsync(new StdioClientTransport(new()\r\n{\r\n    Name = \"GitHub\",\r\n    Command = \"npx\",\r\n    Arguments = [\"-y\", \"@modelcontextprotocol\/server-github\"],\r\n}));\r\n<\/code><\/pre>\n<h4>Retrieve the MCP Tools<\/h4>\n<p>A Model Context Protocol (MCP) server can expose executable functionality to clients as tools. Tools can be invoked by LLMs enabling them to interact with external systems, perform computations, and take actions in the real world.<\/p>\n<p>The following code lists the tools exposed by the server and prints out each tool name and description.<\/p>\n<pre class=\"prettyprint language-cs language-csharp\"><code class=\"language-cs language-csharp\">\/\/ Retrieve the list of tools available on the GitHub server\r\nvar tools = await mcpClient.ListToolsAsync().ConfigureAwait(false);\r\nforeach (var tool in tools.Tools)\r\n{\r\n    Console.WriteLine($\"{tool.Name}: {tool.Description}\");\r\n}<\/code><\/pre>\n<p>The GitHub MCP server exposes the following tools:<\/p>\n<pre class=\"prettyprint language-default\"><code class=\"language-default\">create_or_update_file: Create or update a single file in a GitHub repository\r\nsearch_repositories: Search for GitHub repositories\r\ncreate_repository: Create a new GitHub repository in your account\r\nget_file_contents: Get the contents of a file or directory from a GitHub repository\r\npush_files: Push multiple files to a GitHub repository in a single commit\r\ncreate_issue: Create a new issue in a GitHub repository\r\ncreate_pull_request: Create a new pull request in a GitHub repository\r\nfork_repository: Fork a GitHub repository to your account or specified organization\r\ncreate_branch: Create a new branch in a GitHub repository\r\nlist_commits: Get list of commits of a branch in a GitHub repository\r\nlist_issues: List issues in a GitHub repository with filtering options\r\nupdate_issue: Update an existing issue in a GitHub repository\r\nadd_issue_comment: Add a comment to an existing issue\r\nsearch_code: Search for code across GitHub repositories\r\nsearch_issues: Search for issues and pull requests across GitHub repositories\r\nsearch_users: Search for users on GitHub\r\nget_issue: Get details of a specific issue in a GitHub repository<\/code><\/pre>\n<p>For more information about the GitHub MCP server see the <a href=\"https:\/\/github.com\/modelcontextprotocol\/servers\/tree\/main\/src\/github\">documentation<\/a>.<\/p>\n<p>&nbsp;<\/p>\n<h4>Convert MCP Tools to Kernel Functions<\/h4>\n<p>Semantic Kernel provides a <span style=\"font-family: 'courier new', courier, monospace;\">KernelFunction<\/span> abstraction which is used to represent a tool which an LLM can invoke. To use MCP server tools with Semantic Kernel is necessary to first adapt each tool to be a <span style=\"font-family: 'courier new', courier, monospace;\">KernelFunction<\/span>.<\/p>\n<p>The code below shows how an MCP tool can be converted to a Semantic Kernel function and added to the <span style=\"font-family: 'courier new', courier, monospace;\">Kernel<\/span>. This functionality has been added to\u00a0 <a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.SemanticKernel.Core\">NuGet Gallery | Microsoft.SemanticKernel.Core 1.44.0<\/a><\/p>\n<pre class=\"prettyprint language-cs language-csharp\"><code class=\"language-cs language-csharp\">kernel.Plugins.AddFromFunctions(\"GitHub\", tools.Select(aiFunction =&gt; aiFunction.AsKernelFunction()));\r\n<\/code><\/pre>\n<p>&nbsp;<\/p>\n<h4>Invoke the MCP Tools via Function Calling<\/h4>\n<p>Once the MCP tools have been converted to Semantic Kernel functions they can be added to the <span style=\"font-family: 'courier new', courier, monospace;\">Kernel.Plugins<\/span> and are now available for use with function calling.<\/p>\n<pre class=\"prettyprint language-cs language-csharp\"><code class=\"language-cs language-csharp\">\/\/ Enable automatic function calling\r\nOpenAIPromptExecutionSettings executionSettings = new()\r\n{\r\n    Temperature = 0,\r\n    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(options: new() { RetainArgumentTypes = true })\r\n};\r\n\r\n\/\/ Test using GitHub tools\r\nvar prompt = \"Summarize the last four commits to the microsoft\/semantic-kernel repository?\";\r\nvar result = await kernel.InvokePromptAsync(prompt, new(executionSettings)).ConfigureAwait(false);\r\nConsole.WriteLine($\"\\n\\n{prompt}\\n{result}\");<\/code><\/pre>\n<p class=\"prettyprint language-cs language-csharp\">Here are some samples results:<\/p>\n<pre class=\"prettyprint language-default\"><code class=\"language-default\">Summarize the last four commits to the microsoft\/semantic-kernel repository?\r\nHere are the summaries of the last four commits to the `microsoft\/semantic-kernel` repository:\r\n\r\n1. **Commit f8ee3ac** by Mark Wallace on 2025-03-04:\r\n   - **Title:** .Net: Demo showing how to integrate MCP tools with Semantic Kernel\r\n   - **Description:** This commit introduces a demo for integrating MCP tools with the Semantic Kernel. It includes necessary changes to ensure the code builds cleanly without errors or warnings and follows the contribution guidelines. [View Commit](https:\/\/github.com\/microsoft\/semantic-kernel\/commit\/f8ee3ac408532a805ae3e9d7cc912c1df5e2796a)\r\n\r\n2. **Commit 7c8dccc** by Roger Barreto on 2025-03-04:\r\n   - **Title:** .Net: Add missing Ollama Connector Aspire Friendly Extensions\r\n   - **Description:** This commit addresses issue #10532 by adding missing extensions for the Ollama Connector to ensure compatibility and functionality. [View Commit](https:\/\/github.com\/microsoft\/semantic-kernel\/commit\/7c8dccc2c62d6641aa2cc1c976d6a681c8b2200b)\r\n\r\n3. **Commit 7787725** by dependabot[bot] on 2025-03-04:\r\n   - **Title:** Python: Bump google-cloud-aiplatform from 1.80.0 to 1.82.0 in \/python\r\n   - **Description:** This automated commit updates the `google-cloud-aiplatform` dependency from version 1.80.0 to 1.82.0, incorporating new features and bug fixes as detailed in the release notes. [View Commit](https:\/\/github.com\/microsoft\/semantic-kernel\/commit\/7787725a1ae0b91325bd7602358ed6173b610076)\r\n\r\n4. **Commit 022f05e** by Ross Smith on 2025-03-04:\r\n   - **Title:** .Net: dotnet format issues with SDK 9.0\r\n   - **Description:** This commit resolves formatting issues related to BOM encoding in the .NET codebase, ensuring compatibility with SDK version 9.0. It addresses problems in the `ActivityExtensions.cs` file and removes access modifiers on interface members. [View Commit](https:\/\/github.com\/microsoft\/semantic-kernel\/commit\/022f05e795ba80c7c5d52af2b1c3271dcc7e80bd)<\/code><\/pre>\n<p>&nbsp;<\/p>\n<h4>Invoke the MCP Tools via an Agent<\/h4>\n<p>The MCP tools can also be invoked by an Agent. In the code below the same Kernel instance which has the MCP tools already added is being reused. The code also enabled automatic function calling for the Agent. The same GitHub related query can be sent as a message to the agent and the MCP tools will be used to provide content for the response.<\/p>\n<pre class=\"prettyprint language-cs language-csharp\"><code class=\"language-cs language-csharp\">\/\/ Define the agent\r\nChatCompletionAgent agent =\r\n    new()\r\n    {\r\n        Instructions = \"Answer questions about GitHub repositories.\",\r\n        Name = \"GitHubAgent\",\r\n        Kernel = kernel,\r\n        Arguments = new KernelArguments(new PromptExecutionSettings() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(options: new() { RetainArgumentTypes = true }) }),\r\n    };\r\n\r\n\/\/ Respond to user input, invoking functions where appropriate.\r\nChatMessageContent response = await agent.InvokeAsync(\"Summarize the last four commits to the microsoft\/semantic-kernel repository?\").FirstAsync();\r\nConsole.WriteLine($\"\\n\\nResponse from GitHubAgent:\\n{response.Content}\");<\/code><\/pre>\n<p>&nbsp;<\/p>\n<h4>What&#8217;s Next?<\/h4>\n<p>We encourage you to try out this integration possibility and let us know how it goes. Please create <a href=\"https:\/\/github.com\/microsoft\/semantic-kernel\/issues\">issues<\/a> to request enhancements to the sample and provide your feedback. Full source code for the sample is available in the <a href=\"https:\/\/github.com\/microsoft\/semantic-kernel\/tree\/main\/dotnet\/samples\/Demos\/ModelContextProtocolPlugin\">Semantic Kernel repository<\/a>.<\/p>\n<p>Next up, the team is looking at building samples showing:<\/p>\n<ol>\n<li>How to consume MCP <a href=\"https:\/\/modelcontextprotocol.io\/docs\/concepts\/prompts\">prompts<\/a> and <a href=\"https:\/\/modelcontextprotocol.io\/docs\/concepts\/resources\">resources<\/a> from a Semantic Kernel based application.<\/li>\n<li>How to build an MCP Server using Semantic Kernel and expose Kernel functions, prompts and memory via MCP.<\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>This post describes how to use Model Context Protocol tools with Semantic Kernel. Model Context Protocol (MCP) is an open protocol that standardizes how applications provide context to LLMs. MCP standardizes the connection between AI models and various data sources and tools. The Model Context Protocol is significant because it enhances the way AI models [&hellip;]<\/p>\n","protected":false},"author":131388,"featured_media":4373,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[],"class_list":["post-4347","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-semantic-kernel"],"acf":[],"blog_post_summary":"<p>This post describes how to use Model Context Protocol tools with Semantic Kernel. Model Context Protocol (MCP) is an open protocol that standardizes how applications provide context to LLMs. MCP standardizes the connection between AI models and various data sources and tools. The Model Context Protocol is significant because it enhances the way AI models [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/agent-framework\/wp-json\/wp\/v2\/posts\/4347","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/agent-framework\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/agent-framework\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/agent-framework\/wp-json\/wp\/v2\/users\/131388"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/agent-framework\/wp-json\/wp\/v2\/comments?post=4347"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/agent-framework\/wp-json\/wp\/v2\/posts\/4347\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/agent-framework\/wp-json\/wp\/v2\/media\/4373"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/agent-framework\/wp-json\/wp\/v2\/media?parent=4347"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/agent-framework\/wp-json\/wp\/v2\/categories?post=4347"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/agent-framework\/wp-json\/wp\/v2\/tags?post=4347"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}