发现优秀的 MCP 服务器

通过 MCP 服务器扩展您的代理能力,拥有 12,350 个能力。

开发者工具3,065
Template for Bun MCP Server

Template for Bun MCP Server

Okay, here's a template structure and some example code for a Bun + Minecraft Protocol (MCP) server project, along with explanations to get you started. This focuses on the core structure and handling basic connections. You'll need to adapt it based on the specific features you want to implement. **Project Structure:** ``` bun-mcp-server/ ├── src/ │ ├── index.ts # Main entry point │ ├── server.ts # Server logic (listening, connection handling) │ ├── protocol.ts # MCP packet handling (encoding/decoding) │ ├── player.ts # Player object/class │ ├── config.ts # Configuration loading │ └── utils.ts # Utility functions ├── package.json ├── bun.lockb ├── .gitignore └── README.md ``` **1. `package.json`:** ```json { "name": "bun-mcp-server", "version": "0.0.1", "description": "A Minecraft Protocol server written in Bun", "main": "src/index.ts", "scripts": { "start": "bun run src/index.ts", "dev": "bun run --watch src/index.ts" }, "dependencies": { // Add any dependencies here, e.g., for logging, configuration, etc. }, "devDependencies": { "@types/node": "^20.0.0" // Important for Node.js compatibility }, "type": "module" } ``` **Explanation:** * `name`, `version`, `description`: Standard package metadata. * `main`: Specifies the entry point of your application. * `scripts`: Defines commands for running and developing your server. `bun run src/index.ts` starts the server. `bun run --watch src/index.ts` starts the server in watch mode, automatically restarting when files change. * `dependencies`: List any external libraries your project uses. You'll likely need libraries for more advanced features (e.g., logging, configuration parsing). * `devDependencies`: Development-time dependencies, like TypeScript type definitions. `@types/node` is crucial for compatibility with Node.js APIs that Bun supports. * `type": "module"`: This is *essential* for using ES modules (import/export syntax) in Bun. **2. `src/index.ts` (Main Entry Point):** ```typescript import { startServer } from './server'; import { loadConfig } from './config'; async function main() { try { const config = await loadConfig(); // Load configuration console.log("Configuration loaded:", config); startServer(config); // Start the server } catch (error) { console.error("Error starting server:", error); } } main(); ``` **Explanation:** * This is the starting point of your application. * It imports the `startServer` function from `server.ts` and `loadConfig` from `config.ts`. * It calls `loadConfig` to load the server configuration. * It calls `startServer` to start the server, passing the configuration. * It includes error handling to catch any errors that occur during startup. **3. `src/server.ts` (Server Logic):** ```typescript import { listen } from 'bun'; import { handleConnection } from './protocol'; import { ServerConfig } from './config'; export function startServer(config: ServerConfig) { console.log(`Starting server on ${config.host}:${config.port}`); Bun.serve({ fetch(req, server) { if (server.upgrade(req)) { // handle WebSocket request return undefined; } return new Response("Upgrade failed :(", { status: 500 }); }, websocket: { open(ws) { console.log("Client connected"); handleConnection(ws); // Handle the new connection }, message(ws, message) { // Handle WebSocket message console.log(`Received message: ${message}`); }, close(ws, code, message) { console.log(`Client disconnected with code ${code} and message ${message}`); }, error(ws, error) { console.error("WebSocket error:", error); }, }, port: config.port, hostname: config.host, }); console.log("Server started"); } ``` **Explanation:** * This file contains the core server logic. * `startServer` function takes a `config` object (defined in `config.ts`). * It uses `Bun.serve` to create an HTTP server that listens for incoming connections. * The `fetch` function handles HTTP requests and upgrades them to WebSockets. * The `websocket` object defines the WebSocket event handlers: * `open`: Called when a new WebSocket connection is established. It calls `handleConnection` to process the connection. * `message`: Called when a WebSocket message is received. This is where you'll handle incoming MCP packets. * `close`: Called when a WebSocket connection is closed. * `error`: Called when a WebSocket error occurs. * The server listens on the port and hostname specified in the configuration. **4. `src/protocol.ts` (MCP Packet Handling):** ```typescript import { WebSocket } from 'bun'; import { Player } from './player'; export function handleConnection(ws: WebSocket) { console.log("Handling new connection..."); const player = new Player(ws); // Create a new player object ws.addEventListener("message", (event) => { const message = event.data; if (typeof message === "string") { console.log(`Received text message: ${message}`); } else if (message instanceof ArrayBuffer) { // Handle binary data (MCP packets) const buffer = new Uint8Array(message); console.log(`Received binary message: ${buffer}`); // TODO: Decode the MCP packet and process it // Example: // const packetId = buffer[0]; // switch (packetId) { // case 0x00: // Handshake // handleHandshake(buffer, player); // break; // // ... other packet types // default: // console.warn(`Unknown packet ID: ${packetId}`); // } } else { console.log(`Received unknown message type: ${typeof message}`); } }); ws.addEventListener("close", () => { console.log("Connection closed"); // Clean up player data }); ws.addEventListener("error", (error) => { console.error("WebSocket error:", error); }); } // Example Handshake handler (replace with actual MCP logic) function handleHandshake(buffer: Uint8Array, player: Player) { // TODO: Implement handshake logic based on the MCP protocol console.log("Handling handshake packet"); // Example: Read protocol version, server address, and next state from the buffer // const protocolVersion = buffer.readInt32BE(1); // Example: Read from offset 1 // ... } ``` **Explanation:** * This file handles the Minecraft Protocol (MCP) logic. * `handleConnection` is called when a new WebSocket connection is established. * It creates a `Player` object to represent the connected player. * It sets up event listeners for the WebSocket: * `message`: This is the most important part. It receives incoming messages from the client. You'll need to: * Check if the message is a string or an `ArrayBuffer`. MCP packets are binary data (ArrayBuffer). * Decode the MCP packet. This involves reading the packet ID and any data associated with the packet. * Process the packet based on its ID. This might involve updating the player's state, sending data to other players, etc. * `close`: Called when the connection is closed. You'll need to clean up any player data. * `error`: Called when an error occurs. * The `handleHandshake` function is a placeholder. You'll need to implement the actual handshake logic based on the MCP protocol. The handshake is the first packet sent by the client and is used to establish the connection. **5. `src/player.ts` (Player Class):** ```typescript import { WebSocket } from 'bun'; export class Player { socket: WebSocket; username: string | null = null; // Add other player properties here (e.g., position, health, inventory) constructor(socket: WebSocket) { this.socket = socket; } send(data: Uint8Array) { if (this.socket.readyState === WebSocket.OPEN) { this.socket.send(data); } else { console.warn("Socket is not open, cannot send data"); } } // Add methods for updating player state, sending packets, etc. } ``` **Explanation:** * This file defines the `Player` class, which represents a connected player. * It stores the player's WebSocket connection, username, and other properties. * The `send` method sends data to the player's client. * You'll need to add methods for updating the player's state, sending packets, and handling other player-related logic. **6. `src/config.ts` (Configuration):** ```typescript import { readFile } from 'node:fs/promises'; // Use Node.js fs/promises for file reading export interface ServerConfig { host: string; port: number; motd: string; // Message of the Day maxPlayers: number; } const defaultConfig: ServerConfig = { host: '0.0.0.0', port: 25565, motd: 'A Bun Minecraft Server', maxPlayers: 20, }; export async function loadConfig(): Promise<ServerConfig> { try { // Attempt to load from config.json const configFile = await readFile('config.json', 'utf-8'); const parsedConfig = JSON.parse(configFile) as Partial<ServerConfig>; // Merge with defaults, overriding with values from config.json return { ...defaultConfig, ...parsedConfig }; } catch (error) { console.warn("Failed to load config.json, using default configuration:", error); return defaultConfig; } } ``` **Explanation:** * This file handles loading the server configuration. * The `ServerConfig` interface defines the structure of the configuration object. * `defaultConfig` provides default values for the configuration. * `loadConfig` attempts to load the configuration from a `config.json` file. If the file doesn't exist or is invalid, it uses the default configuration. * It uses `node:fs/promises` to read the file asynchronously. This is important for performance. **7. `config.json` (Example Configuration File):** ```json { "port": 25566, "motd": "My Awesome Bun Server!" } ``` **8. `src/utils.ts` (Utility Functions):** ```typescript // Example utility function (add more as needed) export function hexEncode(data: Uint8Array): string { return Array.from(data) .map(byte => byte.toString(16).padStart(2, '0')) .join(''); } ``` **9. `.gitignore`:** ``` node_modules bun.lockb ``` **Key Concepts and Next Steps:** 1. **Minecraft Protocol (MCP):** This is the most important part. You *must* understand the MCP to build a functional server. Refer to the official Minecraft Protocol documentation (search for "Minecraft Protocol" or "wiki.vg/Protocol"). Pay close attention to: * **Packet IDs:** Each packet has a unique ID that identifies its type. * **Data Types:** The MCP uses specific data types (e.g., VarInt, VarLong, strings, integers, booleans). You'll need to read and write these data types correctly. * **Packet Structure:** Each packet has a specific structure, with fields in a defined order. * **State Machine:** The protocol operates in different states (Handshaking, Status, Login, Play). You need to handle packets differently depending on the current state. 2. **Binary Data Handling:** MCP packets are binary data. You'll need to use `Uint8Array` and `DataView` to read and write data to the buffers. 3. **VarInt and VarLong:** These are variable-length integers used in the MCP. You'll need to implement functions to read and write them. 4. **Asynchronous Operations:** Bun is designed for asynchronous operations. Use `async/await` and Promises to handle network I/O efficiently. 5. **Error Handling:** Implement robust error handling to catch and log errors. 6. **Logging:** Use a logging library to log important events and errors. 7. **Configuration:** Use a configuration file to store server settings (e.g., port, MOTD, max players). 8. **Player Management:** Keep track of connected players and their state. 9. **World Management:** Implement world loading, saving, and generation. 10. **Game Logic:** Implement the game logic (e.g., player movement, block placement, entity spawning). **Example: Reading a VarInt (Important for MCP):** ```typescript function readVarInt(buffer: Uint8Array, offset: number): { value: number, bytesRead: number } { let result = 0; let shift = 0; let bytesRead = 0; while (true) { const byte = buffer[offset + bytesRead]; bytesRead++; if (byte === undefined) { throw new Error("Incomplete VarInt"); } result |= (byte & 0x7F) << shift; shift += 7; if (!(byte & 0x80)) { return { value: result, bytesRead: bytesRead }; } if (shift > 35) { throw new Error("VarInt is too big"); } } } ``` **Example: Writing a VarInt:** ```typescript function writeVarInt(value: number): Uint8Array { const buffer: number[] = []; while (true) { const byte = value & 0x7F; value >>>= 7; if (value !== 0) { buffer.push(byte | 0x80); } else { buffer.push(byte); break; } } return new Uint8Array(buffer); } ``` **How to Run:** 1. **Install Bun:** Follow the instructions on the official Bun website ([https://bun.sh/](https://bun.sh/)). 2. **Create the Project:** Create the directory structure and files as described above. 3. **Install Dependencies:** Run `bun install` in the project directory. 4. **Start the Server:** Run `bun run start` or `bun run dev` in the project directory. **Important Considerations for Bun:** * **Node.js Compatibility:** Bun aims to be compatible with Node.js APIs, but there may be differences. Test your code thoroughly. * **WebSockets:** Bun has excellent WebSocket support. * **Performance:** Bun is designed for performance. Take advantage of its features to optimize your server. This template provides a solid foundation for building a Bun + MCP server. Remember to consult the Minecraft Protocol documentation and adapt the code to your specific needs. Good luck! **Chinese Translation of Key Terms:** * **Minecraft Protocol (MCP):** Minecraft 协议 (Minecraft Xiéyì) * **Packet:** 数据包 (Shùjùbāo) * **Server:** 服务器 (Fúwùqì) * **Client:** 客户端 (Kèhùduān) * **WebSocket:** WebSocket (pronounced the same in Chinese) * **Handshake:** 握手 (Wòshǒu) * **VarInt:** 变长整数 (Biàncháng Zhěngshù) * **Configuration:** 配置 (Pèizhì) * **Player:** 玩家 (Wánjiā) * **World:** 世界 (Shìjiè) * **MOTD (Message of the Day):** 每日消息 (Měirì Xiāoxī) or 服务器标语 (Fúwùqì Biāoyǔ) * **ArrayBuffer:** 数组缓冲区 (Shùzǔ Huǎnchōngqū) * **Uint8Array:** 8位无符号整数数组 (8 Wèi Wúfúhào Zhěngshù Shùzǔ) This should give you a good start. Let me know if you have any more questions!

mcp_rs_testWhat is MCP RS Test?How to use MCP RS Test?Key features of MCP RS Test?Use cases of MCP RS Test?FAQ from MCP RS Test?

mcp_rs_testWhat is MCP RS Test?How to use MCP RS Test?Key features of MCP RS Test?Use cases of MCP RS Test?FAQ from MCP RS Test?

用 Rust 实现 MCP 服务器

mcp-server-notifier

mcp-server-notifier

轻量级 Node.js 服务器,用于发送 Webhook 通知。非常适合在多项目中使用 AI 代理(例如 Cursor)的开发者,可在任务完成时发出警报,以便高效切换。功能包括 Webhook 警报、多项目开发、AI 集成,以及为开发工具和自动化提供的简易设置。

Prometheus MCP

Prometheus MCP

MCP 服务器,用于将 LLM 连接到 Prometheus HTTP API

WordPress MCP Server

WordPress MCP Server

镜子 (jìng zi)

MCP Server - Build Tools

MCP Server - Build Tools

一个基于模型上下文协议的服务器,用于 JVM 构建工具。

aivengers-mcp MCP server

aivengers-mcp MCP server

使用 AIvengers 智能工具的 MCP 服务器,具有动态工具搜索/调用功能。

google-adk-mcp

google-adk-mcp

使用 Google ADK 和为 repair_world_application 编写的 MCP 服务器

LinkedIn MCP Server Documentation

LinkedIn MCP Server Documentation

用于 LinkedIn 集成的 n8n 的模型上下文协议 (MCP) 服务器

mcp-all

mcp-all

使用 Spring AI 构建 MCP 服务器和客户端

MCP Server Neurolorap

MCP Server Neurolorap

镜子 (jìng zi)

mcp-taskwarrior

mcp-taskwarrior

Taskwarrior 的一个简单的 MCP 服务器

Kafka MCP Server

Kafka MCP Server

镜子 (jìng zi)

mcp-server-template

mcp-server-template

TypeScript 模型上下文协议 (MCP) 服务器模板

MySQL MCP Server

MySQL MCP Server

Remote MCP Server on Cloudflare

Remote MCP Server on Cloudflare

Linear MCP Server Extension for Zed

Linear MCP Server Extension for Zed

Zed 的线性 MCP 服务器扩展

easyMcp

easyMcp

That's a good translation! It's accurate and concise. Here are a couple of minor variations that might be slightly more natural, depending on the specific context: * **使开发者能够快速构建一个支持stdio和sse的MCP服务器服务框架。** (This emphasizes the *ability* of the developers.) * **帮助开发者快速构建一个支持stdio和sse的MCP服务器服务框架。** (This emphasizes the *assistance* provided in building the framework.) The original translation is perfectly understandable, but these alternatives might flow a bit better in some situations. The key difference is the choice of verb: * **使 (shǐ):** To cause, to enable, to make * **使能够 (shǐ nénggòu):** To enable (more explicitly) * **帮助 (bāngzhù):** To help, to assist Ultimately, the best choice depends on the nuance you want to convey.

Central MCP Host

Central MCP Host

将 MCP 服务器集中化,使其在家庭实验室中运行,而不是在每台机器上单独运行。

mcp-server-with-bun

mcp-server-with-bun

mcp-jira-server

mcp-jira-server

MCP Jira 服务器 (MCP Jira fúwùqì)

Admin Transactions MCP

Admin Transactions MCP

通过 MCP 服务器暴露 ZoomRx AP API

Workers MCP Server

Workers MCP Server

镜子 (jìng zi)

Zig MCP Server

Zig MCP Server

镜子 (jìng zi)

JADX-AI-MCP

JADX-AI-MCP

将 MCP 服务器集成到 JADX 的插件

Hologres MCP Server

Hologres MCP Server

镜子 (jìng zi)

MCP Server Office

MCP Server Office

镜子 (jìng zi)

MCP-ChatBot

MCP-ChatBot

Okay, here's a simple example of an MCP (Minecraft Coder Pack) client-server setup, focusing on the core concepts and using simplified code for clarity. This example demonstrates a basic message exchange. Keep in mind that a real-world Minecraft mod would be significantly more complex. **Important Considerations:** * **MCP Setup:** This assumes you have a working MCP development environment set up. This is *essential* before you can run any of this code. Follow the official MCP documentation for your Minecraft version. * **Minecraft Forge:** You'll need Minecraft Forge to create mods. Make sure you have the correct Forge version for your MCP version. * **Simplified:** This is a *very* simplified example. It doesn't handle error conditions, complex data, or proper Minecraft threading. It's meant to illustrate the basic structure. * **Networking:** Minecraft Forge provides its own networking system, which is what you should use for real mods. This example uses standard Java sockets for simplicity, but it's not recommended for production mods. **1. Common Code (Shared between Client and Server)** Create a class to hold constants and shared data. This helps keep things organized. ```java // CommonConstants.java public class CommonConstants { public static final String MOD_ID = "simplemcp"; public static final String MOD_NAME = "Simple MCP Mod"; public static final String MOD_VERSION = "1.0"; public static final int SERVER_PORT = 12345; // Choose a port public static final String MESSAGE_TO_SERVER = "Hello from the client!"; public static final String MESSAGE_FROM_SERVER = "Hello from the server!"; } ``` **2. Server-Side (Minecraft Server Mod)** Create a class that will run on the Minecraft server. ```java // ServerProxy.java (or ServerSide.java, etc.) import java.io.*; import java.net.*; public class ServerProxy { public void init() { // Server-side initialization code here (e.g., registering commands, event handlers) System.out.println("ServerProxy init"); startServer(); } private void startServer() { new Thread(() -> { // Run the server in a separate thread try (ServerSocket serverSocket = new ServerSocket(CommonConstants.SERVER_PORT)) { System.out.println("Server started on port " + CommonConstants.SERVER_PORT); while (true) { // Keep listening for connections try (Socket clientSocket = serverSocket.accept(); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) { System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress()); String inputLine = in.readLine(); System.out.println("Received from client: " + inputLine); out.println(CommonConstants.MESSAGE_FROM_SERVER); // Send a response System.out.println("Sent to client: " + CommonConstants.MESSAGE_FROM_SERVER); } catch (IOException e) { System.err.println("Exception handling client: " + e.getMessage()); } } } catch (IOException e) { System.err.println("Could not listen on port " + CommonConstants.SERVER_PORT + ": " + e.getMessage()); } }).start(); } } ``` **3. Client-Side (Minecraft Client Mod)** Create a class that will run on the Minecraft client. ```java // ClientProxy.java (or ClientSide.java, etc.) import java.io.*; import java.net.*; public class ClientProxy { public void init() { // Client-side initialization code here (e.g., registering keybindings, event handlers) System.out.println("ClientProxy init"); startClient(); } private void startClient() { new Thread(() -> { // Run the client in a separate thread try (Socket socket = new Socket("localhost", CommonConstants.SERVER_PORT); // Connect to the server PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { out.println(CommonConstants.MESSAGE_TO_SERVER); // Send a message System.out.println("Sent to server: " + CommonConstants.MESSAGE_TO_SERVER); String response = in.readLine(); System.out.println("Received from server: " + response); } catch (UnknownHostException e) { System.err.println("Don't know about host localhost"); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to localhost: " + e.getMessage()); } }).start(); } } ``` **4. Main Mod Class** This is the core class that Forge uses to load your mod. ```java // SimpleMCPMod.java import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.SidedProxy; @Mod(modid = CommonConstants.MOD_ID, name = CommonConstants.MOD_NAME, version = CommonConstants.MOD_VERSION) public class SimpleMCPMod { @SidedProxy(clientSide = "ClientProxy", serverSide = "ServerProxy") public static ServerProxy proxy; // Changed to ServerProxy @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { // Pre-initialization code (e.g., configuration loading) } @Mod.EventHandler public void init(FMLInitializationEvent event) { // Initialization code (e.g., registering blocks, items, recipes) proxy.init(); // Call the init method of the appropriate proxy } } ``` **5. `mcmod.info` (Required)** Create a `mcmod.info` file in the root of your mod's source directory (usually `src/main/resources`). This file tells Minecraft about your mod. ```json [ { "modid": "simplemcp", "name": "Simple MCP Mod", "description": "A simple example mod demonstrating client-server communication.", "version": "1.0", "mcversion": "1.12.2", // Or your Minecraft version "authorList": ["Your Name"], "credits": "MCP, Forge, and you!", "url": "" } ] ``` **How to Run:** 1. **MCP Setup:** Ensure your MCP environment is correctly set up for your Minecraft version. 2. **Forge Installation:** Make sure Forge is installed in your development environment. 3. **Code Placement:** Place the Java files in the correct package structure within your `src/main/java` directory. Place the `mcmod.info` file in `src/main/resources`. 4. **Recompile:** Recompile your mod using the MCP commands (e.g., `gradlew build`). 5. **Run Minecraft:** Run Minecraft from your development environment (using the MCP run configurations). Make sure you run both the client and the server. 6. **Check Logs:** Look at the Minecraft client and server logs (usually in the `logs` directory) to see the output from the `System.out.println` statements. You should see the messages being exchanged. **Explanation:** * **`CommonConstants`:** Holds shared information like the mod ID, name, version, and the port number for the server. * **`ServerProxy`:** This class runs on the *server* side. It creates a `ServerSocket` to listen for incoming connections on the specified port. When a client connects, it reads a message from the client and sends a response. The server runs in a separate thread to avoid blocking the main Minecraft server thread. * **`ClientProxy`:** This class runs on the *client* side. It creates a `Socket` to connect to the server. It sends a message to the server and then waits for a response. The client also runs in a separate thread. * **`SimpleMCPMod`:** This is the main mod class. The `@Mod` annotation tells Forge that this is a mod. The `@SidedProxy` annotation tells Forge to load either the `ClientProxy` or the `ServerProxy` depending on whether the code is running on the client or the server. The `init` method is called during the Minecraft initialization process. * **`mcmod.info`:** Provides metadata about your mod. **Important Notes:** * **Threading:** Using `new Thread(() -> ...).start()` is a basic way to handle networking in a separate thread. In a real Minecraft mod, you should use Forge's built-in threading mechanisms for better integration with the game. * **Error Handling:** The error handling in this example is very basic. You should add more robust error handling to catch exceptions and prevent crashes. * **Forge Networking:** For a real mod, *use Forge's networking system*. It provides a more reliable and efficient way to communicate between the client and the server. Look into `SimpleNetworkWrapper` and message handlers. * **Security:** Be very careful about what data you send between the client and the server. Never trust data from the client. Validate all data on the server side to prevent exploits. * **Synchronization:** If you are modifying Minecraft data (e.g., player inventories, world data) from the networking threads, you will need to use proper synchronization to avoid race conditions and data corruption. Use `Minecraft.getMinecraft().addScheduledTask()` on the client and `MinecraftServer.addScheduledTask()` on the server to execute code on the main thread. **Chinese Translation (Simplified Chinese):** 好的,这是一个简单的 MCP (Minecraft Coder Pack) 客户端-服务器设置的例子,重点在于核心概念,并使用简化的代码以求清晰。 这个例子演示了一个基本的消息交换。 请记住,一个真实的 Minecraft Mod 会复杂得多。 **重要注意事项:** * **MCP 设置:** 这假设你已经设置了一个可用的 MCP 开发环境。 这是运行任何这些代码的*必要条件*。 请按照你的 Minecraft 版本的官方 MCP 文档进行操作。 * **Minecraft Forge:** 你需要 Minecraft Forge 来创建 Mod。 确保你拥有适用于你的 MCP 版本的正确 Forge 版本。 * **简化:** 这是一个*非常*简化的例子。 它不处理错误情况、复杂数据或正确的 Minecraft 线程处理。 它的目的是说明基本结构。 * **网络:** Minecraft Forge 提供了自己的网络系统,这才是你应该用于真实 Mod 的。 这个例子为了简单起见使用了标准的 Java 套接字,但不建议用于生产 Mod。 **1. 通用代码(客户端和服务器之间共享)** 创建一个类来保存常量和共享数据。 这有助于保持组织性。 ```java // CommonConstants.java public class CommonConstants { public static final String MOD_ID = "simplemcp"; public static final String MOD_NAME = "Simple MCP Mod"; public static final String MOD_VERSION = "1.0"; public static final int SERVER_PORT = 12345; // 选择一个端口 public static final String MESSAGE_TO_SERVER = "来自客户端的问候!"; public static final String MESSAGE_FROM_SERVER = "来自服务器的问候!"; } ``` **2. 服务器端(Minecraft 服务器 Mod)** 创建一个将在 Minecraft 服务器上运行的类。 ```java // ServerProxy.java (或 ServerSide.java 等) import java.io.*; import java.net.*; public class ServerProxy { public void init() { // 服务器端初始化代码(例如,注册命令、事件处理程序) System.out.println("ServerProxy init"); startServer(); } private void startServer() { new Thread(() -> { // 在单独的线程中运行服务器 try (ServerSocket serverSocket = new ServerSocket(CommonConstants.SERVER_PORT)) { System.out.println("服务器在端口 " + CommonConstants.SERVER_PORT + " 上启动"); while (true) { // 持续监听连接 try (Socket clientSocket = serverSocket.accept(); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) { System.out.println("客户端已连接: " + clientSocket.getInetAddress().getHostAddress()); String inputLine = in.readLine(); System.out.println("从客户端收到: " + inputLine); out.println(CommonConstants.MESSAGE_FROM_SERVER); // 发送响应 System.out.println("发送到客户端: " + CommonConstants.MESSAGE_FROM_SERVER); } catch (IOException e) { System.err.println("处理客户端时发生异常: " + e.getMessage()); } } } catch (IOException e) { System.err.println("无法监听端口 " + CommonConstants.SERVER_PORT + ": " + e.getMessage()); } }).start(); } } ``` **3. 客户端(Minecraft 客户端 Mod)** 创建一个将在 Minecraft 客户端上运行的类。 ```java // ClientProxy.java (或 ClientSide.java 等) import java.io.*; import java.net.*; public class ClientProxy { public void init() { // 客户端初始化代码(例如,注册按键绑定、事件处理程序) System.out.println("ClientProxy init"); startClient(); } private void startClient() { new Thread(() -> { // 在单独的线程中运行客户端 try (Socket socket = new Socket("localhost", CommonConstants.SERVER_PORT); // 连接到服务器 PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { out.println(CommonConstants.MESSAGE_TO_SERVER); // 发送消息 System.out.println("发送到服务器: " + CommonConstants.MESSAGE_TO_SERVER); String response = in.readLine(); System.out.println("从服务器收到: " + response); } catch (UnknownHostException e) { System.err.println("不知道主机 localhost"); } catch (IOException e) { System.err.println("无法获取到 localhost 的连接的 I/O: " + e.getMessage()); } }).start(); } } ``` **4. 主 Mod 类** 这是 Forge 用于加载你的 Mod 的核心类。 ```java // SimpleMCPMod.java import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.SidedProxy; @Mod(modid = CommonConstants.MOD_ID, name = CommonConstants.MOD_NAME, version = CommonConstants.MOD_VERSION) public class SimpleMCPMod { @SidedProxy(clientSide = "ClientProxy", serverSide = "ServerProxy") public static ServerProxy proxy; // 更改为 ServerProxy @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { // 预初始化代码(例如,配置加载) } @Mod.EventHandler public void init(FMLInitializationEvent event) { // 初始化代码(例如,注册方块、物品、配方) proxy.init(); // 调用相应代理的 init 方法 } } ``` **5. `mcmod.info` (必需)** 在你的 Mod 的源目录的根目录(通常是 `src/main/resources`)中创建一个 `mcmod.info` 文件。 此文件告诉 Minecraft 关于你的 Mod 的信息。 ```json [ { "modid": "simplemcp", "name": "Simple MCP Mod", "description": "一个简单的示例 Mod,演示客户端-服务器通信。", "version": "1.0", "mcversion": "1.12.2", // 或你的 Minecraft 版本 "authorList": ["你的名字"], "credits": "MCP, Forge, 和你!", "url": "" } ] ``` **如何运行:** 1. **MCP 设置:** 确保你的 MCP 环境已为你的 Minecraft 版本正确设置。 2. **Forge 安装:** 确保 Forge 已安装在你的开发环境中。 3. **代码放置:** 将 Java 文件放置在 `src/main/java` 目录中的正确包结构中。 将 `mcmod.info` 文件放置在 `src/main/resources` 中。 4. **重新编译:** 使用 MCP 命令重新编译你的 Mod(例如,`gradlew build`)。 5. **运行 Minecraft:** 从你的开发环境运行 Minecraft(使用 MCP 运行配置)。 确保你同时运行客户端和服务器。 6. **检查日志:** 查看 Minecraft 客户端和服务器日志(通常在 `logs` 目录中)以查看 `System.out.println` 语句的输出。 你应该看到消息正在交换。 **解释:** * **`CommonConstants`:** 保存共享信息,例如 Mod ID、名称、版本和服务器的端口号。 * **`ServerProxy`:** 此类在*服务器*端运行。 它创建一个 `ServerSocket` 以侦听指定端口上的传入连接。 当客户端连接时,它从客户端读取消息并发送响应。 服务器在单独的线程中运行,以避免阻塞主 Minecraft 服务器线程。 * **`ClientProxy`:** 此类在*客户端*端运行。 它创建一个 `Socket` 以连接到服务器。 它向服务器发送消息,然后等待响应。 客户端也在单独的线程中运行。 * **`SimpleMCPMod`:** 这是主 Mod 类。 `@Mod` 注释告诉 Forge 这是一个 Mod。 `@SidedProxy` 注释告诉 Forge 根据代码是在客户端还是服务器上运行来加载 `ClientProxy` 或 `ServerProxy`。 `init` 方法在 Minecraft 初始化过程中被调用。 * **`mcmod.info`:** 提供关于你的 Mod 的元数据。 **重要提示:** * **线程处理:** 使用 `new Thread(() -> ...).start()` 是一种在单独的线程中处理网络的基本方法。 在真实的 Minecraft Mod 中,你应该使用 Forge 的内置线程机制,以便更好地与游戏集成。 * **错误处理:** 此示例中的错误处理非常基本。 你应该添加更强大的错误处理来捕获异常并防止崩溃。 * **Forge 网络:** 对于真实的 Mod,*使用 Forge 的网络系统*。 它提供了一种更可靠和高效的方式来在客户端和服务器之间进行通信。 查找 `SimpleNetworkWrapper` 和消息处理程序。 * **安全性:** 非常小心你在客户端和服务器之间发送的数据。 永远不要信任来自客户端的数据。 在服务器端验证所有数据以防止漏洞利用。 * **同步:** 如果你要从网络线程修改 Minecraft 数据(例如,玩家库存、世界数据),你将需要使用适当的同步来避免竞争条件和数据损坏。 在客户端上使用 `Minecraft.getMinecraft().addScheduledTask()`,在服务器上使用 `MinecraftServer.addScheduledTask()` 以在主线程上执行代码。 This translation should be helpful. Remember to adapt the code and comments to your specific needs and Minecraft version. Good luck!

MCP Server Logger

MCP Server Logger

好的,这是将 "console.log for your stdio MCP server" 翻译成中文的几种方式,根据不同的语境,表达的侧重点会有所不同: **1. 最直接的翻译 (偏技术):** * **为你的标准输入输出 MCP 服务器使用 console.log** 这个翻译比较直白,适合技术文档或者代码注释。 **2. 更自然的翻译 (强调调试):** * **使用 console.log 来调试你的标准输入输出 MCP 服务器** 这个翻译强调了 `console.log` 的用途是调试。 **3. 更加口语化的翻译:** * **在你的标准输入输出 MCP 服务器里用 console.log 来输出信息** 这个翻译更加口语化,更容易理解。 **4. 如果 "stdio" 指的是标准输入/输出流,可以这样翻译:** * **为你的基于标准输入/输出流的 MCP 服务器使用 console.log** **选择哪个翻译取决于你想要表达的具体含义和目标读者。** 总的来说,`console.log` 在编程中通常用于输出信息进行调试,所以强调调试的含义通常是合适的。 希望这些翻译对您有帮助!

python-base-mcp-server

python-base-mcp-server

一个用于快速引导基于 Python 的 MCP 服务器的 Cookiecutter 模板。