MCP服务器实现

一个基于JSON-RPC 2.0标准通过stdin/stdout通信的MCP服务器实现,主要用于学习目的。

  • by jonsb
  • C#
  • 本地部署
  • 更新于
在 GitHub 查看 jonsb/minimal-mcp-server

使用说明

最小MCP服务器(C#,stdio)

从头开始实现 主控程序 用于学习目的的服务器。
没有SDK。没有HTTP。只需在stdin/stdout上使用原始JSON-RPC 2.0。


MCP stdio传输是如何工作的

MCP使用 换行符分隔的JSON --每条消息都是一行上的单个JSON对象:

stdin  → messages arriving from the client (e.g. Copilot CLI)
stdout → responses sent back to the client
stderr → safe for logging; the client ignores it

握手(按顺序)

Client                          Server
  |                               |
  |-- initialize ---------------→ |   "Hi, here's my info and capabilities"
  |← initialize response -------- |   "Hi, here's what I can do"
  |                               |
  |-- notifications/initialized → |   "Got it, handshake done" (no reply expected)
  |                               |
  |-- tools/list ---------------→ |   "What tools do you have?"
  |← tools/list response -------- |   "Here's my list of tools"
  |                               |
  |-- tools/call ---------------→ |   "Please run tool X with these arguments"
  |← tools/call response -------- |   "Here's the result"

JSON-RPC 2.0基础

每条消息都有这样的形状:

{ "jsonrpc": "2.0", "id": 1, "method": "...", "params": { ... } }
  • 请求: 有一个 id → 您必须发送相同的回复 id
  • 通知 没有 id → 你不能回答
  • 回复 有一个 id +要么 "result" 或 "error"

手动尝试

构建并运行服务器,然后在stdin中键入消息:

dotnet run

一次粘贴一行(每行都是一条JSON消息):

{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}
{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}
{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"message":"Hello, MCP!"}}}
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"add","arguments":{"number1":1.0, "number2":2.1}}}

使用Copilot CLI注册

将此添加到您的MCP配置中(/mcp → 添加服务器):

{
  "command": "dotnet",
  "args": ["run", "--project", "C:\\mobitech\\minimal-mcp-server"]
}

或出版后:

{
  "command": "C:\\mobitech\\minimal-mcp-server\\bin\\Release\\net10.0\\MinimalMcpServer.exe"
}