mcp-init
Okay, here's a basic outline and code snippets for creating a new MCP (Minecraft Protocol) server in TypeScript, with some "batteries included" features like basic logging, player management, and simple command handling. This is a starting point; a full MCP server is a complex project. **Conceptual Outline** 1. **Project Setup:** Initialize a TypeScript project with necessary dependencies. 2. **Networking:** Set up a TCP server to listen for incoming Minecraft client connections. 3. **Protocol Handling:** Implement the Minecraft protocol (handshaking, status, login, play). This is the most complex part. We'll use a library to help. 4. **Player Management:** Track connected players, their usernames, UUIDs, and game state. 5. **Command Handling:** Parse and execute simple commands entered by players. 6. **World Simulation (Optional):** A very basic world representation (e.g., a flat plane) to allow players to move around. 7. **Logging:** Implement a basic logging system for debugging and monitoring. **Code Snippets (TypeScript)** **1. Project Setup** ```bash mkdir mcp-server cd mcp-server npm init -y npm install typescript ts-node ws uuid node-nbt --save # Core dependencies npm install @types/node @types/ws @types/uuid --save-dev # Type definitions tsc --init # Initialize TypeScript config ``` **`tsconfig.json` (Example)** ```json { "compilerOptions": { "target": "es2020", "module": "commonjs", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true }, "include": ["src/**/*"], "exclude": ["node_modules"] } ``` **2. `src/index.ts` (Main Server File)** ```typescript import { WebSocketServer, WebSocket } from 'ws'; import { v4 as uuidv4 } from 'uuid'; import * as nbt from 'node-nbt'; // Basic Logging const log = (message: string) => { console.log(`[${new Date().toISOString()}] ${message}`); }; // Player Interface interface Player { id: string; username: string; socket: WebSocket; x: number; y: number; z: number; } // Server Configuration const SERVER_PORT = 25565; const SERVER_MOTD = "My Awesome MCP Server"; const MAX_PLAYERS = 10; // Global Server State const players: { [id: string]: Player } = {}; // Function to handle incoming messages from clients const handleClientMessage = (ws: WebSocket, message: string) => { try { const data = JSON.parse(message); // Assuming JSON format for simplicity if (data.type === 'chat') { const playerId = Object.keys(players).find(key => players[key].socket === ws); if (playerId) { const player = players[playerId]; const chatMessage = `<${player.username}> ${data.message}`; log(chatMessage); broadcast(chatMessage); // Broadcast to all players } } else if (data.type === 'position') { const playerId = Object.keys(players).find(key => players[key].socket === ws); if (playerId) { const player = players[playerId]; player.x = data.x; player.y = data.y; player.z = data.z; // Broadcast position update (optional) // broadcastPosition(player); } } else { log(`Unknown message type: ${data.type}`); } } catch (error) { log(`Error parsing message: ${error}`); } }; // Function to broadcast a message to all connected clients const broadcast = (message: string) => { for (const playerId in players) { if (players.hasOwnProperty(playerId)) { const player = players[playerId]; player.socket.send(JSON.stringify({ type: 'chat', message: message })); } } }; // Function to handle new client connections const handleNewConnection = (ws: WebSocket) => { const playerId = uuidv4(); let username = `Player${Object.keys(players).length + 1}`; // Default username log(`New connection from ${ws._socket.remoteAddress}, assigning ID: ${playerId}`); // Add the player to the players object players[playerId] = { id: playerId, username: username, socket: ws, x: 0, y: 0, z: 0, }; // Send a welcome message to the new player ws.send(JSON.stringify({ type: 'welcome', message: `Welcome to the server, ${username}!` })); // Notify other players about the new player (optional) broadcast(`${username} has joined the server.`); // Set up event listeners for the new connection ws.on('message', (message) => { handleClientMessage(ws, message.toString()); }); ws.on('close', () => { log(`Connection closed for player ${playerId}`); delete players[playerId]; broadcast(`${username} has left the server.`); }); ws.on('error', (error) => { log(`Error on connection ${playerId}: ${error}`); delete players[playerId]; }); }; // Create a WebSocket server const wss = new WebSocketServer({ port: SERVER_PORT }); wss.on('connection', handleNewConnection); wss.on('listening', () => { log(`Server listening on port ${SERVER_PORT}`); }); wss.on('error', (error) => { log(`Server error: ${error}`); }); // Start the server log(`Starting MCP server...`); ``` **3. Building and Running** ```bash npm run build # Transpile TypeScript to JavaScript (check your package.json for the build script) node dist/index.js # Run the server ``` **Explanation and "Batteries Included" Features:** * **`ws` Library:** Uses the `ws` library for WebSocket communication, which is a common choice for real-time applications. This handles the low-level socket management. * **`uuid` Library:** Generates unique player IDs using the `uuid` library. * **`node-nbt` Library:** This is included for handling NBT (Named Binary Tag) data, which is used for storing world data, player data, and other Minecraft-related information. You'll need this for more advanced features. * **Logging:** A simple `log` function provides basic timestamped logging to the console. * **Player Management:** The `players` object stores information about connected players (ID, username, socket, position). * **Chat:** Basic chat functionality is implemented. Players can send messages, and the server broadcasts them to all other players. * **Position Updates:** The server can receive position updates from clients, although the example doesn't do anything with them beyond storing them. * **Error Handling:** Basic error handling is included for connection errors and message parsing errors. **Important Considerations and Next Steps:** * **Minecraft Protocol:** This example *does not* implement the full Minecraft protocol. You'll need to handle the handshake, status, login, and play states correctly. Libraries like `prismarine-protocol` (Node.js) can help with this, but they are complex. The example uses a simplified JSON-based communication for demonstration. * **Security:** This is a very basic example and has no security measures. You'll need to implement proper authentication, authorization, and input validation to prevent malicious clients from exploiting the server. * **World Generation:** The example doesn't have any world generation. You'll need to implement a world generator to create a playable environment. Consider using libraries for procedural generation. * **Game Logic:** You'll need to implement the game logic for your server, such as handling player movement, interactions with the world, and other game events. * **Performance:** For a large number of players, you'll need to optimize the server's performance. Consider using techniques like multithreading or clustering. * **Data Storage:** You'll need to store world data, player data, and other server data in a persistent storage system, such as a database or file system. * **Command System:** Expand the command handling to support more complex commands and permissions. **Example Client (Simple WebSocket Client)** You'll need a client to connect to your server. Here's a very basic HTML/JavaScript example: ```html <!DOCTYPE html> <html> <head> <title>MCP Client</title> </head> <body> <h1>MCP Client</h1> <input type="text" id="messageInput" placeholder="Enter message"> <button onclick="sendMessage()">Send</button> <div id="chatLog"></div> <script> const ws = new WebSocket('ws://localhost:25565'); // Replace with your server address ws.onopen = () => { console.log('Connected to server'); }; ws.onmessage = (event) => { const data = JSON.parse(event.data); const chatLog = document.getElementById('chatLog'); if (data.type === 'chat') { chatLog.innerHTML += `<p>${data.message}</p>`; } else if (data.type === 'welcome') { chatLog.innerHTML += `<p>${data.message}</p>`; } else { console.log('Received:', data); } }; ws.onclose = () => { console.log('Disconnected from server'); }; ws.onerror = (error) => { console.error('WebSocket error:', error); }; function sendMessage() { const messageInput = document.getElementById('messageInput'); const message = messageInput.value; ws.send(JSON.stringify({ type: 'chat', message: message })); messageInput.value = ''; } </script> </body> </html> ``` Save this as `index.html` and open it in your browser. You should be able to connect to the server and send chat messages. **In summary, this is a very basic starting point. Building a full MCP server is a significant undertaking that requires a deep understanding of the Minecraft protocol and server-side development concepts.** Use this as a foundation and build upon it, researching the Minecraft protocol and using appropriate libraries to handle the complexities. Good luck!
stephencme
README
mcp-init
使用 TypeScript 创建一个新的 MCP 服务器,功能齐全。
为 mcp-init 项目提供支持的构建工具。
packages/mcpi-template-default
mcp-init 的默认项目模板。
推荐服务器
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
MCP Package Docs Server
促进大型语言模型高效访问和获取 Go、Python 和 NPM 包的结构化文档,通过多语言支持和性能优化来增强软件开发。
Claude Code MCP
一个实现了 Claude Code 作为模型上下文协议(Model Context Protocol, MCP)服务器的方案,它可以通过标准化的 MCP 接口来使用 Claude 的软件工程能力(代码生成、编辑、审查和文件操作)。
@kazuph/mcp-taskmanager
用于任务管理的模型上下文协议服务器。它允许 Claude Desktop(或任何 MCP 客户端)在基于队列的系统中管理和执行任务。
mermaid-mcp-server
一个模型上下文协议 (MCP) 服务器,用于将 Mermaid 图表转换为 PNG 图像。
Jira-Context-MCP
MCP 服务器向 AI 编码助手(如 Cursor)提供 Jira 工单信息。
Linear MCP Server
一个模型上下文协议(Model Context Protocol)服务器,它与 Linear 的问题跟踪系统集成,允许大型语言模型(LLM)通过自然语言交互来创建、更新、搜索和评论 Linear 问题。
Sequential Thinking MCP Server
这个服务器通过将复杂问题分解为顺序步骤来促进结构化的问题解决,支持修订,并通过完整的 MCP 集成来实现多条解决方案路径。
Curri MCP Server
通过管理文本笔记、提供笔记创建工具以及使用结构化提示生成摘要,从而实现与 Curri API 的交互。