simple-mcp-server

simple-mcp-server

Okay, here's a basic outline and code snippets for a simple MCP (Minecraft Protocol) server implementation using Java Spring Boot. This will be a *very* simplified version, focusing on the core concepts of receiving and responding to a handshake packet. It won't handle full game logic, world data, or player interactions. This is a starting point. **Important Considerations:** * **Complexity:** The Minecraft Protocol is complex. This example only covers the initial handshake. Implementing a full server requires significant effort. * **Security:** This example is *not* secure. Real-world servers need proper authentication, encryption, and anti-cheat measures. * **Libraries:** While Spring Boot simplifies things, you'll likely need a library to handle the low-level details of the Minecraft Protocol (packet encoding/decoding). I'll show a basic example without a dedicated library, but for a real server, consider libraries like `minecraft-server-util` or similar. * **Asynchronous Handling:** Use asynchronous processing (e.g., `CompletableFuture`, `ExecutorService`) to avoid blocking the main thread when handling network operations. **1. Project Setup (Spring Boot)** * Create a new Spring Boot project using Spring Initializr ([https://start.spring.io/](https://start.spring.io/)). * Dependencies: You'll need at least `spring-boot-starter-web`. Consider adding `spring-boot-starter-logging` for better logging. **2. Core Components** * **MinecraftServer Class:** This class will manage the server socket and handle incoming connections. * **Packet Handling:** Functions to read and write Minecraft Protocol packets. * **Data Structures:** Classes to represent the data in the packets (e.g., Handshake). **3. Code Example (Simplified)** ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Component; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SpringBootApplication public class MinecraftServerApplication { public static void main(String[] args) { SpringApplication.run(MinecraftServerApplication.class, args); } } @Component class MinecraftServer { private static final Logger logger = LoggerFactory.getLogger(MinecraftServer.class); private final int port = 25565; // Default Minecraft port private final ExecutorService executor = Executors.newFixedThreadPool(10); // Thread pool private ServerSocket serverSocket; public MinecraftServer() { startServer(); } private void startServer() { try { serverSocket = new ServerSocket(port); logger.info("Minecraft server started on port " + port); while (true) { Socket clientSocket = serverSocket.accept(); executor.submit(() -> handleClient(clientSocket)); // Handle in a separate thread } } catch (IOException e) { logger.error("Error starting server: " + e.getMessage(), e); } finally { if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { logger.error("Error closing server socket: " + e.getMessage(), e); } } } } private void handleClient(Socket clientSocket) { try (DataInputStream in = new DataInputStream(clientSocket.getInputStream()); DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream())) { logger.info("Client connected from " + clientSocket.getInetAddress()); // 1. Read the Handshake packet Handshake handshake = readHandshake(in); logger.info("Received handshake: " + handshake); // 2. Respond to the handshake (Status Response) sendStatusResponse(out); //3. Handle Ping handlePing(in, out); } catch (IOException e) { logger.error("Error handling client: " + e.getMessage(), e); } finally { try { clientSocket.close(); logger.info("Client disconnected from " + clientSocket.getInetAddress()); } catch (IOException e) { logger.error("Error closing client socket: " + e.getMessage(), e); } } } private Handshake readHandshake(DataInputStream in) throws IOException { // Read packet length (VarInt) int packetLength = readVarInt(in); // Read packet ID (VarInt) int packetId = readVarInt(in); if (packetId != 0x00) { throw new IOException("Expected handshake packet (ID 0x00), got " + packetId); } // Read protocol version (VarInt) int protocolVersion = readVarInt(in); // Read server address (String) String serverAddress = readString(in); // Read server port (Unsigned Short) int serverPort = in.readUnsignedShort(); // Read next state (VarInt) int nextState = readVarInt(in); return new Handshake(protocolVersion, serverAddress, serverPort, nextState); } private void sendStatusResponse(DataOutputStream out) throws IOException { // Create a simple JSON response String jsonResponse = "{\n" + " \"version\": {\n" + " \"name\": \"My Simple Server\",\n" + " \"protocol\": 757\n" + // Example protocol version " },\n" + " \"players\": {\n" + " \"max\": 100,\n" + " \"online\": 0\n" + " },\n" + " \"description\": {\n" + " \"text\": \"A simple Minecraft server\"\n" + " }\n" + "}"; byte[] jsonBytes = jsonResponse.getBytes(StandardCharsets.UTF_8); int dataLength = jsonBytes.length; // Packet ID for Status Response is 0x00 byte[] packetData = new byte[dataLength + varIntSize(dataLength) + varIntSize(0x00)]; int offset = 0; offset = writeVarInt(packetData, offset, dataLength + varIntSize(0x00)); // Packet Length offset = writeVarInt(packetData, offset, 0x00); // Packet ID System.arraycopy(jsonBytes, 0, packetData, offset, dataLength); // JSON Data out.write(packetData); out.flush(); } private void handlePing(DataInputStream in, DataOutputStream out) throws IOException { // Read packet length (VarInt) int packetLength = readVarInt(in); // Read packet ID (VarInt) int packetId = readVarInt(in); if (packetId != 0x01) { throw new IOException("Expected Ping packet (ID 0x01), got " + packetId); } // Read payload (long) long payload = in.readLong(); // Send Pong response sendPongResponse(out, payload); } private void sendPongResponse(DataOutputStream out, long payload) throws IOException { // Packet ID for Pong Response is 0x01 byte[] packetData = new byte[8 + varIntSize(8) + varIntSize(0x01)]; // 8 bytes for long payload int offset = 0; offset = writeVarInt(packetData, offset, 8 + varIntSize(0x01)); // Packet Length offset = writeVarInt(packetData, offset, 0x01); // Packet ID writeLong(packetData, offset, payload); // Payload out.write(packetData); out.flush(); } // Helper methods for reading and writing VarInts and Strings (Minecraft Protocol) private int readVarInt(DataInputStream in) throws IOException { int numRead = 0; int result = 0; byte read; do { read = in.readByte(); int value = (read & 0x7f); result |= (value << (7 * numRead)); numRead++; if (numRead > 5) { throw new RuntimeException("VarInt is too big"); } } while ((read & 0x80) != 0); return result; } private String readString(DataInputStream in) throws IOException { int length = readVarInt(in); byte[] bytes = new byte[length]; in.readFully(bytes); return new String(bytes, StandardCharsets.UTF_8); } private int writeVarInt(byte[] buffer, int offset, int value) { while (true) { if ((value & ~0x7F) == 0) { buffer[offset++] = (byte) value; return offset; } else { buffer[offset++] = (byte) ((value & 0x7F) | 0x80); value >>>= 7; } } } private int varIntSize(int value) { int size = 0; do { value >>>= 7; size++; } while (value != 0); return size; } private void writeLong(byte[] buffer, int offset, long value) { buffer[offset++] = (byte) (value >>> 0); buffer[offset++] = (byte) (value >>> 8); buffer[offset++] = (byte) (value >>> 16); buffer[offset++] = (byte) (value >>> 24); buffer[offset++] = (byte) (value >>> 32); buffer[offset++] = (byte) (value >>> 40); buffer[offset++] = (byte) (value >>> 48); buffer[offset++] = (byte) (value >>> 56); } } // Data class for the Handshake packet class Handshake { public int protocolVersion; public String serverAddress; public int serverPort; public int nextState; public Handshake(int protocolVersion, String serverAddress, int serverPort, int nextState) { this.protocolVersion = protocolVersion; this.serverAddress = serverAddress; this.serverPort = serverPort; this.nextState = nextState; } @Override public String toString() { return "Handshake{" + "protocolVersion=" + protocolVersion + ", serverAddress='" + serverAddress + '\'' + ", serverPort=" + serverPort + ", nextState=" + nextState + '}'; } } ``` **Explanation:** 1. **`MinecraftServerApplication`:** Standard Spring Boot application entry point. 2. **`MinecraftServer`:** * `@Component`: Makes this a Spring-managed bean. * `startServer()`: Creates a `ServerSocket` and listens for incoming connections. Uses a thread pool (`ExecutorService`) to handle each client connection asynchronously. * `handleClient()`: This is where the magic happens. It reads the handshake packet, sends a status response, and handles the ping. * `readHandshake()`: Reads the handshake packet data from the input stream. It reads VarInts and Strings according to the Minecraft Protocol. * `sendStatusResponse()`: Creates a simple JSON response (the server status) and sends it back to the client. This is what you see when you add a server to your Minecraft client. * `handlePing()`: Reads the ping packet and sends a pong response. * `readVarInt()`, `readString()`, `writeVarInt()`: Helper methods to read and write VarInts and Strings, which are used extensively in the Minecraft Protocol. VarInts are variable-length integers. 3. **`Handshake`:** A simple data class to hold the handshake information. **How to Run:** 1. Build the Spring Boot project (e.g., using Maven or Gradle). 2. Run the resulting JAR file. 3. In your Minecraft client, add a new server with the address `localhost` (or the IP address of your server). 4. You should see the server in the server list with the status information you provided in the `sendStatusResponse()` method. **Key Improvements and Next Steps:** * **Error Handling:** Add more robust error handling and logging. * **Configuration:** Externalize the server port and other settings using Spring Boot's configuration mechanisms. * **Minecraft Protocol Library:** Use a dedicated Minecraft Protocol library to simplify packet handling and ensure correctness. This will handle the complexities of VarInts, strings, and other data types. * **State Management:** Implement proper state management to track the client's connection state (handshake, status, login, play). * **Login:** Implement the login sequence to authenticate players. * **World Generation:** Generate or load a Minecraft world. * **Game Logic:** Implement the core game logic (player movement, block updates, etc.). * **Security:** Implement encryption (e.g., using the `net.minecraft.network.Encryption` class from a Minecraft server library) and authentication. * **Asynchronous I/O:** Use non-blocking I/O (NIO) for better performance. **Chinese Translation of Key Concepts:** * **Minecraft Protocol (MCP):** 我的世界协议 (Wǒ de Shìjiè Xiéyì) * **Handshake:** 握手 (Wòshǒu) * **Packet:** 数据包 (Shùjùbāo) * **Server:** 服务器 (Fúwùqì) * **Client:** 客户端 (Kèhùduān) * **VarInt:** 变长整数 (Biàn cháng zhěngshù) * **Status Response:** 状态响应 (Zhuàngtài xiǎngyìng) * **Ping:** 延迟测试 (Yánchí cèshì) / 心跳 (Xīntiào) * **Pong:** 延迟测试回应 (Yánchí cèshì huíyìng) / 心跳回应 (Xīntiào huíyìng) * **Thread Pool:** 线程池 (Xiànchéng chí) * **Asynchronous:** 异步 (Yìbù) * **Socket:** 套接字 (Tàojiēzì) This example provides a basic foundation. Building a full Minecraft server is a complex undertaking, but this should give you a good starting point. Remember to prioritize security and use appropriate libraries to handle the Minecraft Protocol correctly. Good luck!

marcelloraffaele

开发者工具
访问服务器

README

simple-mcp-server

Java Spring Boot 简易 MCP 服务器实现

描述

simple-mcp-server 项目包含两个核心服务:

  1. GreetingsService: 此服务负责生成个性化的问候消息。 它提供基于输入参数创建动态和用户特定问候语的功能。

  2. NumberService: 此服务处理与数字相关的操作,例如执行算术计算或生成随机数。 它旨在有效地支持各种数值运算。

使用 Docker 镜像运行

修改 mcp.server 配置

{
    "servers": {
        "simple-mcp-server": {
            "command": "docker",
            "args": [
                "run",
                "-i",
                "--rm",
                "ghcr.io/marcelloraffaele/simple-mcp-server:main"
            ]
        }
        
    }
}

在本地运行

  1. 构建项目
mvn clean install

  1. 运行服务器 更改 mcp.server 配置,添加以下内容:

        "simple-mcp-server": {
            "type": "stdio",
            "command": "java",
            "args": [
                "-Dspring.ai.mcp.server.stdio=true",
                "-jar",
                "C:\\Workspaces\\......\\simple-mcp-server\target\\simple-mcp-server-0.0.1-SNAPSHOT.jar"
            ]
        }

使用 Docker 运行服务器

  1. 构建项目
mvn clean install
docker build -t simplemcpserver:1.0 .
  1. 运行服务器 更改 mcp.server 配置,添加以下内容:
        "simple-mcp-server": {
            "command": "docker",
            "args": [
                "run",
                "-i",
                "--rm",
                "simplemcpserver:1.0"
            ]
        }

推荐服务器

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