Echo MCP Server

Echo MCP Server

Okay, here's a basic outline and code example for a Model Context Protocol (MCP) server implementing an echo service using .NET Core. Since MCP isn't a widely standardized protocol, I'll make some assumptions about its structure. I'll assume it's a text-based protocol where messages are delimited by a newline character (`\n`). You'll likely need to adapt this to your specific MCP definition. **Conceptual Overview** 1. **Server Setup:** Create a TCP listener to accept incoming connections. 2. **Connection Handling:** For each connection, create a new thread or task to handle it concurrently. 3. **Receive Data:** Read data from the client socket. 4. **Parse MCP Message:** Parse the received data according to your MCP specification. In this simple echo example, we'll just treat the entire line as the message. 5. **Echo Response:** Send the received message back to the client. 6. **Close Connection:** Close the socket when the client disconnects or an error occurs. **Code Example (.NET Core)** ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace McpEchoServer { class Program { private static int _port = 12345; // Change this to your desired port private static IPAddress _ipAddress = IPAddress.Any; // Listen on all interfaces static async Task Main(string[] args) { TcpListener listener = null; try { listener = new TcpListener(_ipAddress, _port); listener.Start(); Console.WriteLine($"MCP Echo Server started on {_ipAddress}:{_port}"); while (true) { TcpClient client = await listener.AcceptTcpClientAsync(); Console.WriteLine($"Accepted new client: {client.Client.RemoteEndPoint}"); _ = HandleClientAsync(client); // Fire and forget - handle client in a separate task } } catch (Exception e) { Console.WriteLine($"An error occurred: {e}"); } finally { listener?.Stop(); } Console.WriteLine("Server stopped."); } static async Task HandleClientAsync(TcpClient client) { try { using (NetworkStream stream = client.GetStream()) using (var reader = new System.IO.StreamReader(stream, Encoding.UTF8)) using (var writer = new System.IO.StreamWriter(stream, Encoding.UTF8) { AutoFlush = true }) // AutoFlush ensures data is sent immediately { string message; while ((message = await reader.ReadLineAsync()) != null) { Console.WriteLine($"Received: {message} from {client.Client.RemoteEndPoint}"); // Echo the message back await writer.WriteLineAsync(message); Console.WriteLine($"Sent: {message} to {client.Client.RemoteEndPoint}"); } Console.WriteLine($"Client disconnected: {client.Client.RemoteEndPoint}"); } } catch (Exception e) { Console.WriteLine($"Error handling client {client.Client.RemoteEndPoint}: {e}"); } finally { client.Close(); } } } } ``` **How to Use:** 1. **Create a new .NET Core Console Application:** In Visual Studio or using the .NET CLI (`dotnet new console`). 2. **Replace the `Program.cs` content:** Paste the code above into your `Program.cs` file. 3. **Adjust the Port:** Change the `_port` variable to the port you want the server to listen on. 4. **Run the Server:** Build and run the application. You should see the "MCP Echo Server started" message. **Client Example (Simple Telnet or Netcat)** You can test this server using a simple Telnet client or Netcat. * **Telnet:** Open a command prompt or terminal and type: `telnet localhost 12345` (replace `12345` with your port). Then type some text and press Enter. You should see the same text echoed back. * **Netcat (nc):** `nc localhost 12345`. Type some text and press Enter. **Explanation:** * **`TcpListener`:** Listens for incoming TCP connections on the specified IP address and port. * **`AcceptTcpClientAsync()`:** Asynchronously accepts a pending connection request. This returns a `TcpClient` object representing the connected client. * **`HandleClientAsync()`:** This `async` method handles the communication with a single client. It's launched as a separate task using `_ = HandleClientAsync(client);` so that the server can handle multiple clients concurrently. * **`NetworkStream`:** Provides access to the underlying network stream of the `TcpClient`. * **`StreamReader` and `StreamWriter`:** Used for reading and writing text data to the stream. `StreamReader.ReadLineAsync()` reads a line of text from the stream asynchronously. `StreamWriter.WriteLineAsync()` writes a line of text to the stream asynchronously. `AutoFlush = true` ensures that data is sent immediately. * **`Encoding.UTF8`:** Specifies the character encoding to use for reading and writing text. * **`client.Close()`:** Closes the connection to the client. * **Error Handling:** The `try...catch...finally` blocks provide basic error handling. **Important Considerations and Improvements:** * **MCP Specification:** This example assumes a very simple MCP protocol. You'll need to adapt the parsing and message handling logic to match your actual MCP specification. This might involve parsing headers, message types, data lengths, etc. * **Error Handling:** The error handling is basic. You should add more robust error handling to catch exceptions and handle them gracefully. Consider logging errors. * **Threading/Task Management:** The `_ = HandleClientAsync(client);` approach is a simple way to launch a task, but for a production server, you might want to use a more sophisticated task management strategy (e.g., using a `TaskScheduler` or a thread pool) to control the number of concurrent tasks. * **Security:** This example is not secure. If you're transmitting sensitive data, you should use TLS/SSL to encrypt the connection. * **Message Framing:** If your MCP protocol doesn't use newline characters as delimiters, you'll need to implement a different message framing mechanism (e.g., using a fixed-length header that specifies the message length). * **Asynchronous Operations:** The use of `async` and `await` makes the server more scalable by allowing it to handle multiple clients concurrently without blocking threads. * **Logging:** Implement a logging mechanism to record server events, errors, and client interactions. This is crucial for debugging and monitoring. * **Configuration:** Externalize configuration settings (e.g., port number, IP address) into a configuration file. **Chinese Translation of Key Concepts:** * **Model Context Protocol (MCP):** 模型上下文协议 (Móxíng shàngxiàwén xiéyì) * **Echo Service:** 回显服务 (Huíxiǎn fúwù) * **.NET Core:** .NET Core * **TCP Listener:** TCP 监听器 (TCP jiāntīng qì) * **Socket:** 套接字 (Tàojiēzì) * **Network Stream:** 网络流 (Wǎngluò liú) * **Asynchronous:** 异步 (Yìbù) * **Thread:** 线程 (Xiànchéng) * **Task:** 任务 (Rènwù) * **Client:** 客户端 (Kèhùduān) * **Server:** 服务器 (Fúwùqì) * **Port:** 端口 (Duānkǒu) * **IP Address:** IP 地址 (IP dìzhǐ) * **Encoding:** 编码 (Biānmǎ) * **Message:** 消息 (Xiāoxī) * **Delimiter:** 分隔符 (Fēngéfú) This comprehensive example should give you a good starting point for building your MCP echo server in .NET Core. Remember to adapt the code to your specific MCP protocol requirements. Good luck!

aadversteeg

开发者工具
访问服务器

README

Echo MCP 服务器

一个实现了模型上下文协议 (MCP) 的简单回显服务器。此服务器通过 MCP 接口提供基本的回显功能。

概述

Echo MCP 服务器使用 .NET Core 构建,并使用了 Model Context Protocol C# SDK (github.com/modelcontextprotocol/csharp-sdk)。 它提供了一个将消息回显给客户端的工具。 该服务器设计轻量级,并演示了如何创建一个具有简单功能的自定义 MCP 服务器。 它可以直接部署在机器上,也可以作为 Docker 容器部署。

特性

  • 将任何消息回显给客户端
  • 可通过配置自定义消息格式
  • 基于模型上下文协议标准

快速开始

前提条件

  • .NET 9.0 (用于本地开发/部署)
  • Docker (用于容器部署)

构建说明 (用于开发)

如果您想从源代码构建项目:

  1. 克隆此仓库:

    git clone https://github.com/yourusername/echo-mcp-server.git
    
  2. 导航到项目根目录:

    cd echo-mcp-server
    
  3. 使用以下命令构建项目:

    dotnet build src/echo.sln
    
  4. 运行测试:

    dotnet test src/echo.sln
    

Docker 支持

手动 Docker 构建

要自己构建 Docker 镜像:

# 导航到仓库根目录
cd echo-mcp-server

# 构建 Docker 镜像
docker build -f src/Core.Infrastructure.McpServer/Dockerfile -t echo-mcp-server:latest src/

# 运行本地构建的镜像
docker run -d --name echo-mcp echo-mcp-server:latest

MCP 协议使用

客户端集成

要从您的应用程序连接到 Echo MCP 服务器:

  1. 使用 Model Context Protocol C# SDK 或任何 MCP 兼容的客户端
  2. 配置您的客户端以连接到服务器的端点
  3. 调用下面描述的可用工具

可用工具

echo

将消息回显给客户端。

参数:

  • message (必需): 要回显的消息。

示例请求:

{
  "name": "echo",
  "parameters": {
    "message": "Hello, world!"
  }
}

示例响应:

Echo: Hello, world!

配置

MessageFormat

MessageFormat 设置决定了回显消息的格式。 它使用一个模板字符串,其中 {message} 占位符会被替换为输入消息。

您可以通过两种方式设置 MessageFormat:

  1. appsettings.json 文件 (用于本地部署):
{
  "MessageFormat": "Server says: {message}"
}
  1. 环境变量 (用于容器化部署):

当将 MCP 服务器与 Claude 一起使用时,环境变量会通过 Claude Desktop 配置传递,如下面的“配置 Claude Desktop”部分所示。

如果未指定,服务器默认为 "Echo: {message}"。

配置 Claude Desktop

使用本地安装

要配置 Claude Desktop 以使用本地安装的 Echo 服务器:

  1. 将服务器配置添加到 Claude Desktop 配置中的 mcpServers 部分:
"echo": {
  "command": "dotnet",
  "args": [
    "YOUR_PATH_TO_DLL\\Core.Infrastructure.McpServer.dll"
  ],
  "env": {
    "MessageFormat": "Claude says: {message}"
  }
}
  1. 保存文件并重启 Claude Desktop

使用 Docker 容器

要从 Docker 容器中使用 Echo 服务器与 Claude Desktop:

  1. 将服务器配置添加到 Claude Desktop 配置中的 mcpServers 部分:
"echo": {
  "command": "docker",
  "args": [
    "run",
    "--rm",
    "-i",
    "-e", "MessageFormat=Claude says: {message}",
    "echo-mcp-server:latest"
  ]
}

使用带有自定义配置文件的 Docker

要使用来自主机系统的自定义配置文件:

  1. 在您的主机上创建一个自定义配置文件(例如,echo-appsettings.json):
{
  "MessageFormat": "My Custom Format: {message}",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    }
  }
}
  1. 更新 Claude Desktop 配置以挂载此文件:
"echo": {
  "command": "docker",
  "args": [
    "run",
    "--rm",
    "-i",
    "-v", "C:/path/to/echo-appsettings.json:/app/appsettings.json",
    "echo-mcp-server:latest"
  ]
}

重要提示:

  • 配置文件必须在启动容器之前存在于您的主机系统上
  • 您可以使用主机上的任何文件名(例如,echo-appsettings.json),但它必须挂载到容器内的 /app/appsettings.json
  • 确保路径对于您的操作系统是正确的(Windows 使用反斜杠或正斜杠,Linux/macOS 使用正斜杠)
  • 更改配置文件后,重启 Claude Desktop 以应用更改
  1. 保存文件并重启 Claude Desktop

许可证

此项目根据 MIT 许可证授权 - 有关详细信息,请参阅 LICENSE 文件。

推荐服务器

Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
MCP Package Docs Server

MCP Package Docs Server

促进大型语言模型高效访问和获取 Go、Python 和 NPM 包的结构化文档,通过多语言支持和性能优化来增强软件开发。

精选
本地
TypeScript
Claude Code MCP

Claude Code MCP

一个实现了 Claude Code 作为模型上下文协议(Model Context Protocol, MCP)服务器的方案,它可以通过标准化的 MCP 接口来使用 Claude 的软件工程能力(代码生成、编辑、审查和文件操作)。

精选
本地
JavaScript
@kazuph/mcp-taskmanager

@kazuph/mcp-taskmanager

用于任务管理的模型上下文协议服务器。它允许 Claude Desktop(或任何 MCP 客户端)在基于队列的系统中管理和执行任务。

精选
本地
JavaScript
mermaid-mcp-server

mermaid-mcp-server

一个模型上下文协议 (MCP) 服务器,用于将 Mermaid 图表转换为 PNG 图像。

精选
JavaScript
Jira-Context-MCP

Jira-Context-MCP

MCP 服务器向 AI 编码助手(如 Cursor)提供 Jira 工单信息。

精选
TypeScript
Linear MCP Server

Linear MCP Server

一个模型上下文协议(Model Context Protocol)服务器,它与 Linear 的问题跟踪系统集成,允许大型语言模型(LLM)通过自然语言交互来创建、更新、搜索和评论 Linear 问题。

精选
JavaScript
Sequential Thinking MCP Server

Sequential Thinking MCP Server

这个服务器通过将复杂问题分解为顺序步骤来促进结构化的问题解决,支持修订,并通过完整的 MCP 集成来实现多条解决方案路径。

精选
Python
Curri MCP Server

Curri MCP Server

通过管理文本笔记、提供笔记创建工具以及使用结构化提示生成摘要,从而实现与 Curri API 的交互。

官方
本地
JavaScript