MCPSharp
by: afrise
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.
📌Overview
Purpose: MCPSharp is designed to facilitate the development of Model Context Protocol (MCP) servers and clients, providing a standardized API for AI assistants and models.
Overview: MCPSharp is a robust .NET library that allows developers to create and expose MCP-compliant tools and APIs seamlessly. It abstracts the complexities of the MCP protocol, enabling easy integration with AI functionality in applications while supporting a flexible and attribute-based programming model.
Key Features:
-
Easy-to-use Attribute-based API: Developers can easily define tools and resources using attributes like
[McpTool]
, simplifying the process of creating MCP endpoints. -
Built-in JSON-RPC Support: Automatic handling of request and response communication streamlines interactions with the server, eliminating the need for extensive boilerplate code.
-
Dynamic Tool Registration: Allows for on-the-fly registration of tools, accommodating custom implementations and enhancing flexibility in tool management.
-
Error Handling & Complex Object Support: Improved error handling features provide detailed insights during development, while enhanced support for complex object parameters simplifies interactions.
-
Integration with Microsoft.Extensions.AI and Semantic Kernel: MCPSharp allows broad compatibility with existing AI frameworks, making it easier to enhance applications with advanced AI capabilities.
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. With MCPSharp, you can:
- Create MCP-compliant tools and functions that AI models can discover and use
- Connect directly to existing MCP servers from C# code with an easy to use client
- Expose your .NET methods as MCP endpoints with simple attributes
- Handle MCP protocol details and JSON-RPC communication seamlessly
What's New in MCPSharp
- Microsoft.Extensions.AI Integration: Expose tools as AIFunctions
- Semantic Kernel Support: Add tools using Semantic Kernel's KernelFunctionAttribute
- Dynamic Tool Registration: Register tools on-the-fly with custom implementation logic
- Tool Change Notifications: Server notifies clients when tools are added, updated, or removed
- Complex Object Parameter Support: Improved handling of complex objects in tool parameters
- Better Error Handling: Improved error handling with detailed stack traces
When to Use MCPSharp
Use MCPSharp when you want to:
- Create tools that AI assistants like Anthropic's Claude Desktop can use
- Build MCP-compliant APIs without dealing with protocol details
- Expose existing .NET code as MCP endpoints
- Add AI capabilities through standardized interfaces
- Integrate with Microsoft.Extensions.AI and/or Semantic Kernel without vendor lock-in
Features
- Attribute-based API (
[McpTool]
,[McpResource]
) - Built-in JSON-RPC support with automatic request/response handling
- Automatic parameter validation and type conversion
- Rich documentation support through XML comments
- Near zero configuration required for basic usage
Prerequisites
- Any .NET version supporting standard 2.0
Installation
dotnet add package MCPSharp
Quick Start
1. Define a Tool
Create a class and mark your method(s) with the [McpTool]
attribute:
using MCPSharp;
public class Calculator
{
[McpTool("add", "Adds two numbers")] // [McpFunction] is deprecated; use [McpTool]
public static int Add([McpParameter(true)] int a, [McpParameter(true)] int b)
{
return a + b;
}
}
2. Start the Server
await MCPServer.StartAsync("CalculatorServer", "1.0.0");
StartAsync() automatically finds methods in the base assembly marked with [McpTool]
. To add methods from referenced libraries, register them manually:
MCPServer.Register<T>(); // T is the class containing desired methods
This also works for methods marked with Semantic Kernel attributes. Clients that support list change notifications will be notified when tools are added.
Advanced Usage
Dynamic Tool Registration
Register tools dynamically with custom implementation:
MCPServer.AddToolHandler(new Tool()
{
Name = "dynamicTool",
Description = "A dynamic tool",
InputSchema = new InputSchema {
Type = "object",
Required = ["input"],
Properties = new Dictionary<string, ParameterSchema>{
{"input", new ParameterSchema{Type="string", Description="Input value"}}
}
}
}, (string input) => { return $"You provided: {input}"; });
Use with Microsoft.Extensions.AI
Client-side integration example:
MCPClient client = new("AIClient", "1.0", "path/to/mcp/server");
IList<AIFunction> functions = await client.GetFunctionsAsync();
These functions can be plugged into the ChatOptions.Tools property for an IChatClient, allowing MCP servers to be used seamlessly with any IChatClient implementation.
Semantic Kernel Integration
using Microsoft.SemanticKernel;
public class MySkillClass
{
[KernelFunction("MyFunction")]
[Description("Description of my function")]
public string MyFunction(string input) => $"Processed: {input}";
}
// Register with MCPServer
MCPServer.Register<MySkillClass>();
This is currently the only way to make Semantic Kernel methods registerable with MCP server.
API Reference
Attributes
-
[McpTool]
- Marks a class or method as an MCP tool- Optional parameters:
- Name - Tool name (default: class/method name)
- Description - Description of the tool
- Optional parameters:
-
[McpParameter]
- Provides metadata for function parameters- Optional parameters:
- Description - Parameter description
- Required - Whether the parameter is required (default: false)
- Optional parameters:
-
[McpResource]
- Marks a property or method as an MCP resource- Parameters:
- Name - Resource name
- Uri - Resource URI (can include templates)
- MimeType - MIME type of the resource
- Description - Resource description
- Parameters:
Server Methods
MCPServer.StartAsync(string serverName, string version)
- Starts the MCP serverMCPServer.Register<T>()
- Registers a class containing tools or resourcesMCPServer.AddToolHandler(Tool tool, Delegate func)
- Registers a dynamic tool
Client Methods
new MCPClient(string name, string version, string server, string args = null, IDictionary<string, string> env = null)
- Creates a client instanceclient.GetToolsAsync()
- Get available toolsclient.CallToolAsync(string name, Dictionary<string, object> parameters)
- Call a toolclient.GetResourcesAsync()
- Get available resourcesclient.GetFunctionsAsync()
- Get tools as AIFunctions
XML Documentation Support
MCPSharp automatically extracts documentation from XML comments:
/// <summary>
/// Provides mathematical operations
/// </summary>
public class Calculator
{
/// <summary>
/// Adds two numbers together
/// </summary>
/// <param name="a">The first number to add</param>
/// <param name="b">The second number to add</param>
/// <returns>The sum of the two numbers</returns>
[McpTool]
public static int Add(
[McpParameter(true)] int a,
[McpParameter(true)] int b)
{
return a + b;
}
}
Enable XML documentation in your project file:
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
This allows you to quickly update tool names and descriptions without recompiling, improving model comprehension.
Migration Notes
[McpFunction]
is deprecated and replaced by[McpTool]
to better align with MCP standards- Use
MCPServer.Register<T>()
instead ofMCPServer.RegisterTool<T>()
(the old method still works but is deprecated)
Contributing
Contributions are welcome! Feel free to submit a Pull Request.
License
This project is licensed under the MIT License.