MCP是一个典型的C/S架构模式,即客户端 和 服务端,它们之间采用一种标准的消息格式(JSON-RPC)进行通信.
The MCP C# SDK has great samples of creating MCP server, MCP client
MCP Server in C# .NET
Table of Contents
Simple MCP Server in C#
Step 1: Create a Console Application
dotnet new console -n McpServer
Step 2: Add Required Packages MCP SDK
dotnet add package ModelContextProtocol --prerelease
安装MCP SDK
<ItemGroup>
<PackageReference Include="ModelContextProtocol" Version="0.2.0-preview.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.5" />
</ItemGroup>
https://github.com/iaspnetcore/MCPServer/commit/fd50c9b5fd9c8d9e46b6dde9e4f99f7bac57d24f
The official C# SDK for Model Context Protocol servers and clients
ModelContextProtocol sdk
https://github.com/modelcontextprotocol/csharp-sdk
Step 3: Define Tools
创建一个Tools目录,然后添加一个TimeTool.cs
src/McpServerConsole.Server/Tools/TimeTool.cs
using ModelContextProtocol.Server;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace McpServerConsole.Server.Tools
{
[McpServerToolType]
public static class TimeTool
{
[McpServerTool, Description("Get the current time for a city")]
public static string GetCurrentTime(string city) =>
$"It is {DateTime.Now.Hour}:{DateTime.Now.Minute} in {city}.";
}
}
https://github.com/iaspnetcore/MCPServer/commit/1f94a3f1c78c2aac376cff24d9317df696806eb0
step 4. Update Program.cs - Update your Program.cs to set up the MCP server
Update your Program.cs to set up the MCP server
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using System.ComponentModel;
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(consoleLogOptions =>
{
// Configure all logs to go to stderr
consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
});
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();
WithToolsFromAssembly扩展方法,会自动扫描程序集中添加了McpServerTool标签的类进行注册
https://github.com/iaspnetcore/MCPServer/commit/33e996ee7c6707871ba7441d3f78cabbe2d117b4
2.MCP includes two standard transport(Built-in Transport Types) implementations
Standard Input/Output (stdio)标准IO传输方式-> .WithStdioServerTransport
Server-Sent Events (SSE) SSE传输方式 ->
step 5. run your MCP server
cd F:\developer_mcp\src\McpServerConsole.Server
McpServerConsole.Client
Step 1: Create a Console Application
Step 2: Add Required Packages
dotnet add package ModelContextProtocol" Version="0.2.0-preview.1
F:\developer_mcp
https://github.com/iaspnetcore/MCPServer.git/
blog:https://www.iaspnetcore.com/blogpost-683332645fb02c0677df0289-mcp-server-in-c-net
https://modelcontextprotocol.io/docs/concepts/transports
https://www.cnblogs.com/edisonchou/p/-/introduction-to-mcp-csharp-sdk
https://devblogs.microsoft.com/dotnet/build-a-model-context-protocol-mcp-server-in-csharp/