Skip to content
Back to search

MCPSharp

MCPSharp is a .NET library that helps you build Model Context Protocol (MCP) servers and clients - the standardized API protocol used by AI assistants and models.

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/afrise--mcpsharp/badge.svg)](/listings/afrise--mcpsharp)

HTML

<a href="/listings/afrise--mcpsharp"><img src="/api/listings/afrise--mcpsharp/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.

dotnet add package MCPSharp

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 · 209 lines

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

  1. [![Build](https://github.com/afrise/MCPSharp/actions/workflows/build.yml/badge.svg)](https://github.com/afrise/MCPSharp/actions/workflows/build.yml)
  2. [![NuGet](https://img.shields.io/nuget/v/MCPSharp)](https://www.nuget.org/packages/MCPSharp)
  3. [![NuGet Downloads](https://img.shields.io/nuget/dt/MCPSharp)](https://www.nuget.org/packages/MCPSharp)
  4. # MCPSharp
  5. MCPSharp is a .NET library that helps you build Model Context Protocol (MCP) servers and clients - the standardized API protocol used by AI assistants and models. With MCPSharp, you can:
  6. - Create MCP-compliant tools and functions that AI models can discover and use
  7. - Connect directly to existing MCP servers from C# code with an easy to use client
  8. - Expose your .NET methods as MCP endpoints with simple attributes
  9. - Handle MCP protocol details and JSON-RPC communication seamlessly
  10. ## 🚀 What's New in MCPSharp
  11. - **Microsoft.Extensions.AI Integration**: MCPSharp now integrates with Microsoft.Extensions.AI, allowing tools to be exposed as AIFunctions
  12. - **Semantic Kernel Support**: Add tools using Semantic Kernel's KernelFunctionAttribute
  13. - **Dynamic Tool Registration**: Register tools on-the-fly with custom implementation logic
  14. - **Tool Change Notifications**: Server now notifies clients when tools are added, updated, or removed
  15. - **Complex Object Parameter Support**: Better handling of complex objects in tool parameters
  16. - **Better Error Handling**: Improved error handling with detailed stack traces
  17. ## When to Use MCPSharp
  18. Use MCPSharp when you want to:
  19. - Create tools that AI assistants like Anthropic's Claude Desktop can use
  20. - Build MCP-compliant APIs without dealing with the protocol details
  21. - Expose existing .NET code as MCP endpoints
  22. - Add AI capabilities to your applications through standardized interfaces
  23. - Integrate with Microsoft.Extensions.AI and/or Semantic Kernel without locking into a single vendor
  24. ## Features
  25. - Easy-to-use attribute-based API (`[McpTool]`, `[McpResource]`)
  26. - Built-in JSON-RPC support with automatic request/response handling
  27. - Automatic parameter validation and type conversion
  28. - Rich documentation support through XML comments
  29. - Near zero configuration required for basic usage
  30. ## Prerequisites
  31. - Any version of .NET that supports [standard 2.0](https://learn.microsoft.com/en-us/dotnet/standard/net-standard?tabs=net-standard-2-0#tabpanel_1_net-standard-2-0)
  32. ## Installation
  33. ```bash
  34. dotnet add package MCPSharp
  35. ```
  36. ## Quick Start
  37. ### 1. Define a Tool
  38. Create a class and mark your method(s) with the `[McpTool]` attribute:
  39. ```csharp
  40. using MCPSharp;
  41. public class Calculator
  42. {
  43. [McpTool("add", "Adds two numbers")] // Note: [McpFunction] is deprecated, use [McpTool] instead
  44. public static int Add([McpParameter(true)] int a, [McpParameter(true)] int b)
  45. {
  46. return a + b;
  47. }
  48. }
  49. ```
  50. ### 2. Start the Server
  51. ```csharp
  52. await MCPServer.StartAsync("CalculatorServer", "1.0.0");
  53. ```
  54. The StartAsync() method will automatically find any methods in the base assembly that are marked with the McpTool attribute. In order to add any methods that are in a referenced library, you can manually register them by calling `MCPServer.Register<T>();` with `T` being the class containing the desired methods. If your methods are marked with Semantic Kernel attributes, this will work as well. If the client supports list changed notifications, it will be notified when additional tools are registered.
  55. ## Advanced Usage
  56. ### Dynamic Tool Registration
  57. Register tools dynamically with custom implementation:
  58. ```csharp
  59. MCPServer.AddToolHandler(new Tool()
  60. {
  61. Name = "dynamicTool",
  62. Description = "A dynamic tool",
  63. InputSchema = new InputSchema {
  64. Type = "object",
  65. Required = ["input"],
  66. Properties = new Dictionary<string, ParameterSchema>{
  67. {"input", new ParameterSchema{Type="string", Description="Input value"}}
  68. }
  69. }
  70. }, (string input) => { return $"You provided: {input}"; });
  71. ```
  72. ### Use with Microsoft.Extensions.AI
  73. ```csharp
  74. // Client-side integration
  75. MCPClient client = new("AIClient", "1.0", "path/to/mcp/server");
  76. IList<AIFunction> functions = await client.GetFunctionsAsync();
  77. ```
  78. This list can be plugged into the [ChatOptions.Tools](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.ai.chatoptions?view=net-9.0-pp) property for an [IChatClient](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.ai.ichatclient?view=net-9.0-pp), Allowing MCP servers to be used seamlessly with Any IChatClient Implementation.
  79. ### Semantic Kernel Integration
  80. ```csharp
  81. using Microsoft.SemanticKernel;
  82. public class MySkillClass
  83. {
  84. [KernelFunction("MyFunction")]
  85. [Description("Description of my function")]
  86. public string MyFunction(string input) => $"Processed: {input}";
  87. }
  88. // Register with MCPServer
  89. MCPServer.Register<MySkillClass>();
  90. ```
  91. Currently, This is the only way to make a Semantic kernel method registerable with the MCP server. If you have a use case that is not covered here, please reach out!
  92. ## API Reference
  93. ### Attributes
  94. - `[McpTool]` - Marks a class or method as an MCP tool
  95. - Optional parameters:
  96. - `Name` - The tool name (default: class/method name)
  97. - `Description` - Description of the tool
  98. - `[McpParameter]` - Provides metadata for function parameters
  99. - Optional parameters:
  100. - `Description` - Parameter description
  101. - `Required` - Whether the parameter is required (default: false)
  102. - `[McpResource]` - Marks a property or method as an MCP resource
  103. - Parameters:
  104. - `Name` - Resource name
  105. - `Uri` - Resource URI (can include templates)
  106. - `MimeType` - MIME type of the resource
  107. - `Description` - Resource description
  108. ### Server Methods
  109. - `MCPServer.StartAsync(string serverName, string version)` - Starts the MCP server
  110. - `MCPServer.Register<T>()` - Registers a class containing tools or resources
  111. - `MCPServer.AddToolHandler(Tool tool, Delegate func)` - Registers a dynamic tool
  112. ### Client Methods
  113. - `new MCPClient(string name, string version, string server, string args = null, IDictionary<string, string> env = null)` - Create a client instance
  114. - `client.GetToolsAsync()` - Get available tools
  115. - `client.CallToolAsync(string name, Dictionary<string, object> parameters)` - Call a tool
  116. - `client.GetResourcesAsync()` - Get available resources
  117. - `client.GetFunctionsAsync()` - Get tools as AIFunctions
  118. ## XML Documentation Support
  119. MCPSharp automatically extracts documentation from XML comments:
  120. ```csharp
  121. /// <summary>
  122. /// Provides mathematical operations
  123. /// </summary>
  124. public class Calculator
  125. {
  126. /// <summary>
  127. /// Adds two numbers together
  128. /// </summary>
  129. /// <param name="a">The first number to add</param>
  130. /// <param name="b">The second number to add</param>
  131. /// <returns>The sum of the two numbers</returns>
  132. [McpTool]
  133. public static int Add(
  134. [McpParameter(true)] int a,
  135. [McpParameter(true)] int b)
  136. {
  137. return a + b;
  138. }
  139. }
  140. ```
  141. Enable XML documentation in your project file:
  142. ```xml
  143. <PropertyGroup>
  144. <GenerateDocumentationFile>true</GenerateDocumentationFile>
  145. <NoWarn>$(NoWarn);1591</NoWarn>
  146. </PropertyGroup>
  147. ```
  148. This allows you to be able to quickly change the names and descriptions of your MCP tools without having to recompile. For example, if you find the model is having trouble understanding how to use it correctly.
  149. ## Migration Notes
  150. - `[McpFunction]` is deprecated and replaced with `[McpTool]` for better alignment with MCP standards
  151. - Use `MCPServer.Register<T>()` instead of `MCPServer.RegisterTool<T>()` for consistency (old method still works but is deprecated)
  152. ## Contributing
  153. We welcome contributions! Please feel free to submit a Pull Request.
  154. ## License
  155. This project is licensed under the MIT License.

Ratings and comments

Sign in to rate this skill.

Sign in

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