Skip to content
Back to search

mcpdotnet

.NET implementation of the Model Context Protocol (MCP)

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/pederhp--mcpdotnet/badge.svg)](/listings/pederhp--mcpdotnet)

HTML

<a href="/listings/pederhp--mcpdotnet"><img src="/api/listings/pederhp--mcpdotnet/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

To use mcpdotnet, first install it via NuGet:

dotnet add package mcpdotnet

Then create a client and start using tools, or other capabilities, from the servers you configure:

McpClientOptions options = new()
{
    ClientInfo = new() { Name = "TestClient", Version = "1.0.0" }
};

McpServerConfig config = new()
{
    Id = "everything",
    Name = "Everything",
    TransportType = TransportTypes.StdIo,
    TransportOptions = new()
    {
        ["command"] = "npx",
        ["arguments"] = "-y @modelcontextprotocol/server-everything",
    }
};

var client = await McpClientFactory.CreateAsync(config, options);

// Print the list of tools available from the server.
await foreach (var tool in client.ListToolsAsync())
{
    Console.WriteLine($"{tool.Name} ({tool.Description})");
}

// Execute a tool (this would normally be driven by LLM tool invocations).
var result = await client.CallToolAsync(
    "echo",
    new() { ["message"] = "Hello MCP!" },
    CancellationToken.None);

// echo always returns one and only one text content object
Console.WriteLine(result.Content.First(c => c.Type == "text").Text);

Note that you should pass CancellationToken objects suitable for your use case, to enable proper error handling, timeouts, etc. This example also does not paginate the tools list, which may be necessary for large tool sets. See the IntegrationTests project for an example of pagination, as well as examples of how to handle Prompts and Resources.

It is also highly recommended that you pass a proper LoggerFactory instance to the factory constructor, to enable logging of MCP client operations.

You can find samples demonstrating how to use mcpdotnet with an LLM SDK in the [samples](samples) directory, and also refer to the [IntegrationTests](test/McpDotNet.IntegrationTests) project for more examples.

Additional examples and documentation will be added as in the near future.

Remember you can connect to any MCP server, not just ones created using mcpdotnet. The protocol is designed to be server-agnostic, so you can use this library to connect to any compliant server.

Tools can be exposed easily as `AIFunction` instances so that they are immediately usable with `IChatClient`s.

// Get available functions.
IList<AIFunction> tools = await client.GetAIFunctionsAsync();

// Call the chat client using the tools.
IChatClient chatClient = ...;
var response = await chatClient.GetResponseAsync(
    "your prompt here",
    new() 
    {
        Tools = [.. tools],
    });

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.MD · README · 233 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # ⚠️ REPOSITORY MOVED ⚠️
  2. **This repository has been adopted as the foundations of the official C# SDK for the Model Context Protocol and moved to [https://github.com/modelcontextprotocol/csharp-sdk](https://github.com/modelcontextprotocol/csharp-sdk).**
  3. **Please use the official repository for all new issues, pull requests, and development. This repository is kept for historical purposes but is no longer actively maintained.**
  4. ---
  5. # mcpdotnet
  6. [![NuGet version](https://img.shields.io/nuget/v/mcpdotnet.svg)](https://www.nuget.org/packages/mcpdotnet/)
  7. ![Build](https://github.com/PederHP/mcpdotnet/actions/workflows/ci.yml/badge.svg?branch=main)
  8. [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
  9. [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=PederHP_mcpdotnet&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=PederHP_mcpdotnet)
  10. [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=PederHP_mcpdotnet&metric=reliability_rating)](https://sonarcloud.io/summary/new_code?id=PederHP_mcpdotnet)
  11. [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=PederHP_mcpdotnet&metric=security_rating)](https://sonarcloud.io/summary/new_code?id=PederHP_mcpdotnet)
  12. [![Bugs](https://sonarcloud.io/api/project_badges/measure?project=PederHP_mcpdotnet&metric=bugs)](https://sonarcloud.io/summary/new_code?id=PederHP_mcpdotnet)
  13. [![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=PederHP_mcpdotnet&metric=vulnerabilities)](https://sonarcloud.io/summary/new_code?id=PederHP_mcpdotnet)
  14. [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=PederHP_mcpdotnet&metric=coverage)](https://sonarcloud.io/summary/new_code?id=PederHP_mcpdotnet)
  15. A .NET implementation of the Model Context Protocol (MCP), enabling .NET applications to connect to and interact with MCP clients and servers.
  16. ## About MCP
  17. The Model Context Protocol (MCP) is an open protocol that standardizes how applications provide context to Large Language Models (LLMs). It enables secure integration between LLMs and various data sources and tools.
  18. For more information about MCP:
  19. - [Official Documentation](https://modelcontextprotocol.io/)
  20. - [Protocol Specification](https://spec.modelcontextprotocol.io/)
  21. - [GitHub Organization](https://github.com/modelcontextprotocol)
  22. ## Available Packages
  23. | Package | Description | Documentation |
  24. |---------|-------------|---------------|
  25. | [mcpdotnet](src/mcpdotnet) | Core MCP implementation for .NET | [README](README.md) |
  26. | [McpDotNet.Extensions.AI](src/McpDotNet.Extensions.AI) | Integration with Microsoft.Extensions.AI | [README](src/McpDotNet.Extensions.AI/README.md) |
  27. ## Design Goals
  28. This library aims to provide a clean, specification-compliant implementation of the MCP protocol, with minimal additional abstraction. While transport implementations necessarily include additional code, they follow patterns established by the official SDKs where possible.
  29. ## Features
  30. - MCP implementation for .NET applications
  31. - Support for stdio and SSE transports (Clients)
  32. - Support for stdio transport (Servers)
  33. - Support for all MCP capabilities: Tool, Resource, Prompt, Sampling, Roots
  34. - Support for the Completion utility capability
  35. - Support for server instructions, pagination and notifications
  36. - Async/await pattern throughout
  37. - Comprehensive logging support
  38. - Compatible with .NET 8.0 and later
  39. ## Getting Started (Client)
  40. To use mcpdotnet, first install it via NuGet:
  41. ```powershell
  42. dotnet add package mcpdotnet
  43. ```
  44. Then create a client and start using tools, or other capabilities, from the servers you configure:
  45. ```csharp
  46. McpClientOptions options = new()
  47. {
  48. ClientInfo = new() { Name = "TestClient", Version = "1.0.0" }
  49. };
  50. McpServerConfig config = new()
  51. {
  52. Id = "everything",
  53. Name = "Everything",
  54. TransportType = TransportTypes.StdIo,
  55. TransportOptions = new()
  56. {
  57. ["command"] = "npx",
  58. ["arguments"] = "-y @modelcontextprotocol/server-everything",
  59. }
  60. };
  61. var client = await McpClientFactory.CreateAsync(config, options);
  62. // Print the list of tools available from the server.
  63. await foreach (var tool in client.ListToolsAsync())
  64. {
  65. Console.WriteLine($"{tool.Name} ({tool.Description})");
  66. }
  67. // Execute a tool (this would normally be driven by LLM tool invocations).
  68. var result = await client.CallToolAsync(
  69. "echo",
  70. new() { ["message"] = "Hello MCP!" },
  71. CancellationToken.None);
  72. // echo always returns one and only one text content object
  73. Console.WriteLine(result.Content.First(c => c.Type == "text").Text);
  74. ```
  75. Note that you should pass CancellationToken objects suitable for your use case, to enable proper error handling, timeouts, etc. This example also does not paginate the tools list, which may be necessary for large tool sets. See the IntegrationTests project for an example of pagination, as well as examples of how to handle Prompts and Resources.
  76. It is also highly recommended that you pass a proper LoggerFactory instance to the factory constructor, to enable logging of MCP client operations.
  77. You can find samples demonstrating how to use mcpdotnet with an LLM SDK in the [samples](samples) directory, and also refer to the [IntegrationTests](test/McpDotNet.IntegrationTests) project for more examples.
  78. Additional examples and documentation will be added as in the near future.
  79. Remember you can connect to any MCP server, not just ones created using mcpdotnet. The protocol is designed to be server-agnostic, so you can use this library to connect to any compliant server.
  80. Tools can be exposed easily as `AIFunction` instances so that they are immediately usable with `IChatClient`s.
  81. ```csharp
  82. // Get available functions.
  83. IList<AIFunction> tools = await client.GetAIFunctionsAsync();
  84. // Call the chat client using the tools.
  85. IChatClient chatClient = ...;
  86. var response = await chatClient.GetResponseAsync(
  87. "your prompt here",
  88. new()
  89. {
  90. Tools = [.. tools],
  91. });
  92. ```
  93. ## Getting Started (Server)
  94. Here is an example of how to create an MCP server and register all tools from the current application.
  95. It includes a simple echo tool as an example (this is included in the same file here for easy of copy and paste, but it needn't be in the same file...
  96. the employed overload of `WithTools` examines the current assembly for classes with the `McpToolType` attribute, and registers all methods with the
  97. `McpTool` attribute as tools.)
  98. ```csharp
  99. using McpDotNet;
  100. using McpDotNet.Server;
  101. using Microsoft.Extensions.Hosting;
  102. using System.ComponentModel;
  103. var builder = Host.CreateEmptyApplicationBuilder(settings: null);
  104. builder.Services
  105. .AddMcpServer()
  106. .WithStdioServerTransport()
  107. .WithTools();
  108. await builder.Build().RunAsync();
  109. [McpToolType]
  110. public static class EchoTool
  111. {
  112. [McpTool, Description("Echoes the message back to the client.")]
  113. public static string Echo(string message) => $"hello {message}";
  114. }
  115. ```
  116. More control is also available, with fine-grained control over configuring the server and how it should handle client requests. For example:
  117. ```csharp
  118. using McpDotNet.Protocol.Transport;
  119. using McpDotNet.Protocol.Types;
  120. using McpDotNet.Server;
  121. using Microsoft.Extensions.Logging.Abstractions;
  122. McpServerOptions options = new()
  123. {
  124. ServerInfo = new() { Name = "MyServer", Version = "1.0.0" },
  125. Capabilities = new()
  126. {
  127. Tools = new()
  128. {
  129. ListToolsHandler = async (request, cancellationToken) =>
  130. {
  131. return new ListToolsResult()
  132. {
  133. Tools =
  134. [
  135. new Tool()
  136. {
  137. Name = "echo",
  138. Description = "Echoes the input back to the client.",
  139. InputSchema = new JsonSchema()
  140. {
  141. Type = "object",
  142. Properties = new Dictionary<string, JsonSchemaProperty>()
  143. {
  144. ["message"] = new JsonSchemaProperty() { Type = "string", Description = "The input to echo back." }
  145. }
  146. },
  147. }
  148. ]
  149. };
  150. },
  151. CallToolHandler = async (request, cancellationToken) =>
  152. {
  153. if (request.Params?.Name == "echo")
  154. {
  155. if (request.Params.Arguments?.TryGetValue("message", out var message) is not true)
  156. {
  157. throw new McpServerException("Missing required argument 'message'");
  158. }
  159. return new CallToolResponse()
  160. {
  161. Content = [new Content() { Text = $"Echo: {message}", Type = "text" }]
  162. };
  163. }
  164. throw new McpServerException($"Unknown tool: '{request.Params?.Name}'");
  165. },
  166. }
  167. },
  168. };
  169. await using IMcpServer server = McpServerFactory.Create(new StdioServerTransport("MyServer"), options);
  170. await server.StartAsync();
  171. // Run until process is stopped by the client (parent process)
  172. await Task.Delay(Timeout.Infinite);
  173. ```
  174. ## Roadmap
  175. - Expand documentation with detailed guides for:
  176. - Advanced scenarios (Sampling, Resources, Prompts)
  177. - Transport configuration
  178. - Error handling and recovery
  179. - Increase test coverage
  180. - Add additional samples and examples
  181. - Performance optimization
  182. - SSE server support
  183. - Authentication
  184. ## License
  185. This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.