Discover Awesome MCP Servers

Extend your agent with 84,517 capabilities via MCP servers.

All84,517
myscheme

myscheme

Enables searching live myScheme.gov.in schemes by eligibility, keyword, and detail lookup through MCP tools.

SEFAZ PB: IPVA

SEFAZ PB: IPVA

MCP server for querying IPVA (vehicle tax) information from the official SEFAZ PB (Paraíba state) source, read-only, with prepaid per-query pricing.

Mediora MCP Server

Mediora MCP Server

Exposes a doctor-reviewed medical catalog of blood-test markers, clinical conditions, and patient symptoms as MCP tools in English, Russian, and Hebrew, supporting both anonymous queries and authenticated patient data analysis.

mcp-brasil

mcp-brasil

Connects AI agents to 28 Brazilian public APIs, providing over 200 tools to access data on economy, legislation, transparency, and the judiciary. It enables complex queries and cross-referencing of government datasets like IBGE, the Central Bank, and the National Congress through natural language.

kube-MCP

kube-MCP

A Model Context Protocol server for Kubernetes that provides full resource coverage and advanced troubleshooting tools via HTTP chunked streaming. It enables users to manage clusters and diagnose complex issues like pod crashloops through specialized prompts and standard kubectl-like operations.

Windows MCP Server

Windows MCP Server

An enterprise-grade automation server that enables AI assistants to control Windows PCs through intelligent UI element detection, window management, and system-level commands. It leverages the Windows UI Automation tree for reliable interaction, providing tools for mouse/keyboard control, application management, and high-performance screen state analysis.

orizn-visa-mcp

orizn-visa-mcp

Check visa requirements for 39,585 passport-destination pairs in 15 languages. Returns visa type, required documents, application process, and travel tips from 136 official government sources. Free quick checks without API key.

mcp-init

mcp-init

Okay, here's a basic outline and code snippets to get you started with creating a new MCP (Minecraft Protocol) server in TypeScript, with some common "batteries included" features. This will be a simplified example, focusing on the core concepts. Keep in mind that a full-fledged MCP server is a complex undertaking. **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 (MCP) parsing and serialization. This is the most complex part. 4. **Authentication (Optional):** Implement authentication to verify the client's identity. 5. **World Management (Simplified):** Create a basic world representation (e.g., a simple array of blocks). 6. **Player Management:** Track connected players and their data. 7. **Game Logic (Basic):** Implement some basic game logic (e.g., handling player movement, chat messages). 8. **Event Handling:** Use an event system to decouple components. 9. **Logging:** Implement logging for debugging and monitoring. **1. Project Setup** ```bash mkdir mcp-server cd mcp-server npm init -y npm install typescript ts-node ws --save # ws for WebSocket support (modern clients) npm install @types/node @types/ws --save-dev # Typescript definitions tsc --init # Create tsconfig.json ``` Modify `tsconfig.json` (example): ```json { "compilerOptions": { "target": "es2020", "module": "commonjs", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "sourceMap": true }, "include": ["src/**/*"], "exclude": ["node_modules"] } ``` **2. Networking (Basic TCP Server with WebSocket)** Create `src/index.ts`: ```typescript import * as net from 'net'; import * as WebSocket from 'ws'; const PORT = 25565; // TCP Server const tcpServer = net.createServer((socket) => { console.log('TCP Client connected:', socket.remoteAddress, socket.remotePort); socket.on('data', (data) => { console.log('TCP Received data:', data); // TODO: Handle Minecraft protocol data here socket.write('TCP: Hello from the server!\n'); // Echo back for testing }); socket.on('close', () => { console.log('TCP Client disconnected:', socket.remoteAddress, socket.remotePort); }); socket.on('error', (err) => { console.error('TCP Socket error:', err); }); }); tcpServer.listen(PORT, () => { console.log(`TCP Server listening on port ${PORT}`); }); // WebSocket Server (for modern clients) const wss = new WebSocket.Server({ port: 8080 }); // Different port wss.on('connection', ws => { console.log('WebSocket Client connected'); ws.on('message', message => { console.log('WebSocket Received: %s', message); ws.send(`WebSocket: Server received -> ${message}`); }); ws.on('close', () => { console.log('WebSocket Client disconnected'); }); ws.on('error', (err) => { console.error('WebSocket error:', err); }); }); console.log('WebSocket Server listening on port 8080'); ``` **3. Protocol Handling (MCP - This is the Hard Part)** This is where the real complexity lies. You'll need to understand the Minecraft protocol. Here's a very simplified example of reading a single packet (not complete or correct for all packets): ```typescript // In src/protocol.ts (create this file) import { Buffer } from 'node:buffer'; export function readVarInt(buffer: Buffer, offset: number): { value: number; bytesRead: number } { let result = 0; let shift = 0; let bytesRead = 0; while (true) { const byte = buffer.readUInt8(offset + bytesRead); result |= (byte & 0x7f) << shift; bytesRead++; if ((byte & 0x80) === 0) { break; } shift += 7; if (shift > 35) { throw new Error("VarInt is too big"); } } return { value: result, bytesRead: bytesRead }; } export function writeVarInt(value: number): Buffer { const buffer = []; while (true) { let byte = value & 0x7f; value >>>= 7; if (value !== 0) { byte |= 0x80; } buffer.push(byte); if (value === 0) { break; } } return Buffer.from(buffer); } // Example usage (back in src/index.ts, inside the TCP socket 'data' handler): // import { readVarInt } from './protocol'; // socket.on('data', (data) => { // try { // const { value, bytesRead } = readVarInt(data, 0); // console.log('Packet Length:', value); // // Now you know the packet length, you can read the rest of the packet. // } catch (error) { // console.error('Error reading VarInt:', error); // } // }); ``` **Important Protocol Notes:** * **VarInt/VarLong:** Minecraft uses variable-length integers. The `readVarInt` and `writeVarInt` functions above are crucial for handling these. * **Packet Structure:** Packets generally have a length (VarInt), an ID (VarInt), and then the packet data. * **Packet IDs:** Each packet type has a unique ID. You'll need to map these IDs to specific handlers. * **Data Types:** Minecraft uses various data types (strings, integers, booleans, etc.). You'll need to read and write these correctly. * **State Management:** The protocol has different states (handshaking, status, login, play). You need to track the client's state and handle packets accordingly. * **Compression:** The protocol can use compression. You'll need to handle compression/decompression if enabled. * **Encryption:** The protocol can use encryption. You'll need to handle encryption/decryption if enabled. **4. Authentication (Optional - Simplified)** ```typescript // In src/auth.ts (create this file) export function authenticate(username: string, accessToken: string): boolean { // In a real server, you would verify the access token with Mojang's authentication servers. // This is a simplified example. if (username && accessToken) { // Basic check: Just make sure they're not empty strings. return true; } return false; } // Example usage (in src/index.ts, after receiving a Login Start packet): // import { authenticate } from './auth'; // if (authenticate(username, accessToken)) { // // Login successful // } else { // // Login failed // } ``` **5. World Management (Simplified)** ```typescript // In src/world.ts (create this file) const CHUNK_SIZE = 16; // Minecraft chunks are 16x16x256 export class World { private blocks: number[][][]; // 3D array: x, y, z constructor(width: number, height: number, depth: number) { this.blocks = []; for (let x = 0; x < width; x++) { this.blocks[x] = []; for (let y = 0; y < height; y++) { this.blocks[x][y] = []; for (let z = 0; z < depth; z++) { this.blocks[x][y][z] = 0; // 0 = Air } } } } getBlock(x: number, y: number, z: number): number { if (x < 0 || x >= this.blocks.length || y < 0 || y >= this.blocks[0].length || z < 0 || z >= this.blocks[0][0].length) { return -1; // Out of bounds } return this.blocks[x][y][z]; } setBlock(x: number, y: number, z: number, blockId: number): void { if (x < 0 || x >= this.blocks.length || y < 0 || y >= this.blocks[0].length || z < 0 || z >= this.blocks[0][0].length) { return; // Out of bounds } this.blocks[x][y][z] = blockId; } // Example: Get a chunk of data (simplified) getChunkData(chunkX: number, chunkZ: number): Buffer { // This is a very basic example. Real chunk data is much more complex. const chunkData = Buffer.alloc(CHUNK_SIZE * CHUNK_SIZE * 256 * 2); // Assuming 2 bytes per block let offset = 0; for (let x = 0; x < CHUNK_SIZE; x++) { for (let y = 0; y < 256; y++) { for (let z = 0; z < CHUNK_SIZE; z++) { const blockId = this.getBlock(chunkX * CHUNK_SIZE + x, y, chunkZ * CHUNK_SIZE + z); chunkData.writeUInt16BE(blockId, offset); // Write block ID (example) offset += 2; } } } return chunkData; } } // Example usage (in src/index.ts): // import { World } from './world'; // const world = new World(256, 256, 256); // Example world size // world.setBlock(10, 64, 10, 2); // Set a block at (10, 64, 10) to block ID 2 (Grass) ``` **6. Player Management** ```typescript // In src/player.ts (create this file) export class Player { public username: string; public x: number; public y: number; public z: number; public entityId: number; // Unique ID for the player constructor(username: string, entityId: number) { this.username = username; this.x = 0; this.y = 0; this.z = 0; this.entityId = entityId; } } // In src/index.ts: // const players: { [entityId: number]: Player } = {}; // let nextEntityId = 1; // // When a player connects: // const newPlayer = new Player(username, nextEntityId++); // players[newPlayer.entityId] = newPlayer; ``` **7. Game Logic (Basic)** This is highly dependent on what you want your server to do. Here's a very basic example of handling player movement: ```typescript // In src/index.ts (inside the TCP socket 'data' handler, after parsing the packet): // if (packetId === 0x15) { // Example: Clientbound Player Position and Look packet // const x = data.readDoubleBE(1); // const y = data.readDoubleBE(9); // const z = data.readDoubleBE(17); // const yaw = data.readFloatBE(25); // const pitch = data.readFloatBE(29); // const player = players[entityId]; // Get the player object // if (player) { // player.x = x; // player.y = y; // player.z = z; // console.log(`${player.username} moved to ${x}, ${y}, ${z}`); // // TODO: Send this position update to other players. // } // } ``` **8. Event Handling** ```typescript // In src/events.ts (create this file) import { Player } from './player'; type EventHandler<T> = (data: T) => void; interface Events { 'playerJoin': Player; 'playerLeave': Player; 'playerMove': { player: Player; x: number; y: number; z: number }; 'chatMessage': { player: Player; message: string }; // Add more events as needed } class EventEmitter<T extends Events> { private listeners: { [K in keyof T]?: EventHandler<T[K]>[] } = {}; on<K extends keyof T>(event: K, listener: EventHandler<T[K]>): void { if (!this.listeners[event]) { this.listeners[event] = []; } this.listeners[event]!.push(listener); } emit<K extends keyof T>(event: K, data: T[K]): void { const handlers = this.listeners[event]; if (handlers) { handlers.forEach(handler => handler(data)); } } } export const eventEmitter = new EventEmitter<Events>(); // Example usage (in src/index.ts): // import { eventEmitter } from './events'; // // When a player joins: // eventEmitter.emit('playerJoin', newPlayer); // // To listen for the event: // eventEmitter.on('playerJoin', (player) => { // console.log(`${player.username} joined the game!`); // }); ``` **9. Logging** ```typescript // In src/logger.ts (create this file) export class Logger { private static log(level: string, message: string, ...args: any[]): void { const timestamp = new Date().toISOString(); console.log(`[${timestamp}] [${level}] ${message}`, ...args); } static info(message: string, ...args: any[]): void { Logger.log('INFO', message, ...args); } static warn(message: string, ...args: any[]): void { Logger.log('WARN', message, ...args); } static error(message: string, ...args: any[]): void { Logger.log('ERROR', message, ...args); } static debug(message: string, ...args: any[]): void { Logger.log('DEBUG', message, ...args); } } // Example usage (in src/index.ts): // import { Logger } from './logger'; // Logger.info('Server started successfully!'); // Logger.error('An error occurred!'); ``` **Building and Running** 1. **Compile:** `tsc` 2. **Run:** `node dist/index.js` **Key Improvements and Considerations:** * **Error Handling:** Add more robust error handling throughout the code. * **Configuration:** Use a configuration file (e.g., JSON or YAML) to store server settings (port, world size, etc.). * **Asynchronous Operations:** Use `async/await` for asynchronous operations (e.g., database access, network requests). * **Data Structures:** Use appropriate data structures for efficient storage and retrieval of data (e.g., maps, sets). * **Code Organization:** Break down the code into smaller, more manageable modules. * **Testing:** Write unit tests to ensure the code is working correctly. * **Minecraft Protocol Library:** Consider using an existing Minecraft protocol library (if one exists for TypeScript) to simplify protocol handling. This is *highly* recommended. Searching for "minecraft protocol typescript" might yield useful results. * **Performance:** Profile the code and optimize for performance. Minecraft servers can be resource-intensive. * **Security:** Implement security measures to protect against attacks (e.g., rate limiting, input validation). * **Plugins/Mods:** Design the server architecture to support plugins or mods. * **Database Integration:** Use a database to store player data, world data, and other persistent information. * **Concurrency:** Use threads or worker processes to handle multiple client connections concurrently. **Important Disclaimer:** This is a *very* basic starting point. Building a fully functional Minecraft server is a significant undertaking. You'll need to invest a lot of time and effort to learn the Minecraft protocol and implement all the necessary features. Using an existing library is *strongly* recommended. **Tradução para Português:** Aqui está um esboço básico e trechos de código para você começar a criar um novo servidor MCP (Minecraft Protocol) em TypeScript, com alguns recursos comuns "baterias incluídas". Este será um exemplo simplificado, com foco nos conceitos principais. Lembre-se de que um servidor MCP completo é uma tarefa complexa. **Esboço Conceitual** 1. **Configuração do Projeto:** Inicialize um projeto TypeScript com as dependências necessárias. 2. **Rede:** Configure um servidor TCP para ouvir as conexões de clientes Minecraft recebidas. 3. **Manipulação do Protocolo:** Implemente a análise e serialização do protocolo Minecraft (MCP). Esta é a parte mais complexa. 4. **Autenticação (Opcional):** Implemente a autenticação para verificar a identidade do cliente. 5. **Gerenciamento do Mundo (Simplificado):** Crie uma representação básica do mundo (por exemplo, um array simples de blocos). 6. **Gerenciamento de Jogadores:** Rastreie os jogadores conectados e seus dados. 7. **Lógica do Jogo (Básica):** Implemente alguma lógica básica do jogo (por exemplo, lidar com o movimento do jogador, mensagens de bate-papo). 8. **Manipulação de Eventos:** Use um sistema de eventos para desacoplar os componentes. 9. **Registro (Logging):** Implemente o registro para depuração e monitoramento. **1. Configuração do Projeto** ```bash mkdir mcp-server cd mcp-server npm init -y npm install typescript ts-node ws --save # ws para suporte a WebSocket (clientes modernos) npm install @types/node @types/ws --save-dev # Definições do Typescript tsc --init # Cria tsconfig.json ``` Modifique `tsconfig.json` (exemplo): ```json { "compilerOptions": { "target": "es2020", "module": "commonjs", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "sourceMap": true }, "include": ["src/**/*"], "exclude": ["node_modules"] } ``` **2. Rede (Servidor TCP Básico com WebSocket)** Crie `src/index.ts`: ```typescript import * as net from 'net'; import * as WebSocket from 'ws'; const PORT = 25565; // Servidor TCP const tcpServer = net.createServer((socket) => { console.log('Cliente TCP conectado:', socket.remoteAddress, socket.remotePort); socket.on('data', (data) => { console.log('TCP Dados recebidos:', data); // TODO: Lidar com os dados do protocolo Minecraft aqui socket.write('TCP: Olá do servidor!\n'); // Ecoa de volta para teste }); socket.on('close', () => { console.log('Cliente TCP desconectado:', socket.remoteAddress, socket.remotePort); }); socket.on('error', (err) => { console.error('Erro de Socket TCP:', err); }); }); tcpServer.listen(PORT, () => { console.log(`Servidor TCP ouvindo na porta ${PORT}`); }); // Servidor WebSocket (para clientes modernos) const wss = new WebSocket.Server({ port: 8080 }); // Porta diferente wss.on('connection', ws => { console.log('Cliente WebSocket conectado'); ws.on('message', message => { console.log('WebSocket Recebido: %s', message); ws.send(`WebSocket: Servidor recebeu -> ${message}`); }); ws.on('close', () => { console.log('Cliente WebSocket desconectado'); }); ws.on('error', (err) => { console.error('Erro de WebSocket:', err); }); }); console.log('Servidor WebSocket ouvindo na porta 8080'); ``` **3. Manipulação do Protocolo (MCP - Esta é a Parte Difícil)** É aqui que reside a verdadeira complexidade. Você precisará entender o protocolo Minecraft. Aqui está um exemplo muito simplificado de leitura de um único pacote (não completo ou correto para todos os pacotes): ```typescript // Em src/protocol.ts (crie este arquivo) import { Buffer } from 'node:buffer'; export function readVarInt(buffer: Buffer, offset: number): { value: number; bytesRead: number } { let result = 0; let shift = 0; let bytesRead = 0; while (true) { const byte = buffer.readUInt8(offset + bytesRead); result |= (byte & 0x7f) << shift; bytesRead++; if ((byte & 0x80) === 0) { break; } shift += 7; if (shift > 35) { throw new Error("VarInt é muito grande"); } } return { value: result, bytesRead: bytesRead }; } export function writeVarInt(value: number): Buffer { const buffer = []; while (true) { let byte = value & 0x7f; value >>>= 7; if (value !== 0) { byte |= 0x80; } buffer.push(byte); if (value === 0) { break; } } return Buffer.from(buffer); } // Exemplo de uso (de volta em src/index.ts, dentro do manipulador 'data' do socket TCP): // import { readVarInt } from './protocol'; // socket.on('data', (data) => { // try { // const { value, bytesRead } = readVarInt(data, 0); // console.log('Comprimento do Pacote:', value); // // Agora você sabe o comprimento do pacote, você pode ler o resto do pacote. // } catch (error) { // console.error('Erro ao ler VarInt:', error); // } // }); ``` **Notas Importantes sobre o Protocolo:** * **VarInt/VarLong:** Minecraft usa inteiros de comprimento variável. As funções `readVarInt` e `writeVarInt` acima são cruciais para lidar com eles. * **Estrutura do Pacote:** Os pacotes geralmente têm um comprimento (VarInt), um ID (VarInt) e, em seguida, os dados do pacote. * **IDs de Pacotes:** Cada tipo de pacote tem um ID exclusivo. Você precisará mapear esses IDs para manipuladores específicos. * **Tipos de Dados:** Minecraft usa vários tipos de dados (strings, inteiros, booleanos, etc.). Você precisará ler e gravar esses corretamente. * **Gerenciamento de Estado:** O protocolo tem diferentes estados (handshaking, status, login, play). Você precisa rastrear o estado do cliente e lidar com os pacotes de acordo. * **Compressão:** O protocolo pode usar compressão. Você precisará lidar com a compressão/descompressão se estiver habilitada. * **Criptografia:** O protocolo pode usar criptografia. Você precisará lidar com a criptografia/descriptografia se estiver habilitada. **4. Autenticação (Opcional - Simplificado)** ```typescript // Em src/auth.ts (crie este arquivo) export function authenticate(username: string, accessToken: string): boolean { // Em um servidor real, você verificaria o token de acesso com os servidores de autenticação da Mojang. // Este é um exemplo simplificado. if (username && accessToken) { // Verificação básica: Apenas certifique-se de que não sejam strings vazias. return true; } return false; } // Exemplo de uso (em src/index.ts, após receber um pacote de Login Start): // import { authenticate } from './auth'; // if (authenticate(username, accessToken)) { // // Login bem-sucedido // } else { // // Login falhou // } ``` **5. Gerenciamento do Mundo (Simplificado)** ```typescript // Em src/world.ts (crie este arquivo) const CHUNK_SIZE = 16; // Os chunks do Minecraft são 16x16x256 export class World { private blocks: number[][][]; // Array 3D: x, y, z constructor(width: number, height: number, depth: number) { this.blocks = []; for (let x = 0; x < width; x++) { this.blocks[x] = []; for (let y = 0; y < height; y++) { this.blocks[x][y] = []; for (let z = 0; z < depth; z++) { this.blocks[x][y][z] = 0; // 0 = Ar } } } } getBlock(x: number, y: number, z: number): number { if (x < 0 || x >= this.blocks.length || y < 0 || y >= this.blocks[0].length || z < 0 || z >= this.blocks[0][0].length) { return -1; // Fora dos limites } return this.blocks[x][y][z]; } setBlock(x: number, y: number, z: number, blockId: number): void { if (x < 0 || x >= this.blocks.length || y < 0 || y >= this.blocks[0].length || z < 0 || z >= this.blocks[0][0].length) { return; // Fora dos limites } this.blocks[x][y][z] = blockId; } // Exemplo: Obter um chunk de dados (simplificado) getChunkData(chunkX: number, chunkZ: number): Buffer { // Este é um exemplo muito básico. Os dados reais do chunk são muito mais complexos. const chunkData = Buffer.alloc(CHUNK_SIZE * CHUNK_SIZE * 256 * 2); // Assumindo 2 bytes por bloco let offset = 0; for (let x = 0; x < CHUNK_SIZE; x++) { for (let y = 0; y < 256; y++) { for (let z = 0; z < CHUNK_SIZE; z++) { const blockId = this.getBlock(chunkX * CHUNK_SIZE + x, y, chunkZ * CHUNK_SIZE + z); chunkData.writeUInt16BE(blockId, offset); // Escreve o ID do bloco (exemplo) offset += 2; } } } return chunkData; } } // Exemplo de uso (em src/index.ts): // import { World } from './world'; // const world = new World(256, 256, 256); // Tamanho do mundo de exemplo // world.setBlock(10, 64, 10, 2); // Define um bloco em (10, 64, 10) para o ID do bloco 2 (Grama) ``` **6. Gerenciamento de Jogadores** ```typescript // Em src/player.ts (crie este arquivo) export class Player { public username: string; public x: number; public y: number; public z: number; public entityId: number; // ID exclusivo para o jogador constructor(username: string, entityId: number) { this.username = username; this.x = 0; this.y = 0; this.z = 0; this.entityId = entityId; } } // Em src/index.ts: // const players: { [entityId: number]: Player } = {}; // let nextEntityId = 1; // // Quando um jogador se conecta: // const newPlayer = new Player(username, nextEntityId++); // players[newPlayer.entityId] = newPlayer; ``` **7. Lógica do Jogo (Básica)** Isso depende muito do que você quer que seu servidor faça. Aqui está um exemplo muito básico de como lidar com o movimento do jogador: ```typescript // Em src/index.ts (dentro do manipulador 'data' do socket TCP, após analisar o pacote): // if (packetId === 0x15) { // Exemplo: Pacote Clientbound Player Position and Look // const x = data.readDoubleBE(1); // const y = data.readDoubleBE(9); // const z = data.readDoubleBE(17); // const yaw = data.readFloatBE(25); // const pitch = data.readFloatBE(29); // const player = players[entityId]; // Obtém o objeto do jogador // if (player) { // player.x = x; // player.y = y; // player.z = z; // console.log(`${player.username} moveu-se para ${x}, ${y}, ${z}`); // // TODO: Enviar esta atualização de posição para outros jogadores. // } // } ``` **8. Manipulação de Eventos** ```typescript // Em src/events.ts (crie este arquivo) import { Player } from './player'; type EventHandler<T> = (data: T) => void; interface Events { 'playerJoin': Player; 'playerLeave': Player; 'playerMove': { player: Player; x: number; y: number; z: number }; 'chatMessage': { player: Player; message: string }; // Adicione mais eventos conforme necessário } class EventEmitter<T extends Events> { private listeners: { [K in keyof T]?: EventHandler<T[K]>[] } = {}; on<K extends keyof T>(event: K, listener: EventHandler<T[K]>): void { if (!this.listeners[event]) { this.listeners[event] = []; } this.listeners[event]!.push(listener); } emit<K extends keyof T>(event: K, data: T[K]): void { const handlers = this.listeners[event]; if (handlers) { handlers.forEach(handler => handler(data)); } } } export const eventEmitter = new EventEmitter<Events>(); // Exemplo de uso (em src/index.ts): // import { eventEmitter } from './events'; // // Quando um jogador se junta: // eventEmitter.emit('playerJoin', newPlayer); // // Para ouvir o evento: // eventEmitter.on('playerJoin', (player) => { // console.log(`${player.username} juntou-se ao jogo!`); // }); ``` **9. Registro (Logging)** ```typescript // Em src/logger.ts (crie este arquivo) export class Logger { private static log(level: string, message: string, ...args: any[]): void { const timestamp = new Date().toISOString(); console.log(`[${timestamp}] [${level}] ${message}`, ...args); } static info(message: string, ...args: any[]): void { Logger.log('INFO', message, ...args); } static warn(message: string, ...args: any[]): void { Logger.log('WARN', message, ...args); } static error(message: string, ...args: any[]): void { Logger.log('ERROR', message, ...args); } static debug(message: string, ...args: any[]): void { Logger.log('DEBUG', message, ...args); } } // Exemplo de uso (em src/index.ts): // import { Logger } from './logger'; // Logger.info('Servidor iniciado com sucesso!'); // Logger.error('Ocorreu um erro!'); ``` **Construindo e Executando** 1. **Compilar:** `tsc` 2. **Executar:** `node dist/index.js` **Melhorias e Considerações Chave:** * **Tratamento de Erros:** Adicione um tratamento de erros mais robusto em todo o código. * **Configuração:** Use um arquivo de configuração (por exemplo, JSON ou YAML) para armazenar as configurações do servidor (porta, tamanho do mundo, etc.). * **Operações Assíncronas:** Use `async/await` para operações assíncronas (por exemplo, acesso ao banco de dados, solicitações de rede). * **Estruturas de Dados:** Use estruturas de dados apropriadas para armazenamento e recuperação eficientes de dados (por exemplo, mapas, conjuntos). * **Organização do Código:** Divida o código em módulos menores e mais gerenciáveis. * **Testes:** Escreva testes de unidade para garantir que o código esteja funcionando corretamente. * **Biblioteca do Protocolo Minecraft:** Considere usar uma biblioteca de protocolo Minecraft existente (se houver uma para TypeScript) para simplificar o tratamento do protocolo. Isso é *altamente* recomendado. Pesquisar por "minecraft protocol typescript" pode render resultados úteis. * **Desempenho:** Faça o perfil do código e otimize para o desempenho. Os servidores Minecraft podem consumir muitos recursos. * **Segurança:** Implement

MCP Codebase Analyzer

MCP Codebase Analyzer

Enables LLMs to explore codebases structurally via MCP tools for outlines, function sources, imports, complexity, git changes, and dead code detection, reducing token usage by avoiding raw file ingestion.

Recipes MCP

Recipes MCP

Wraps the TheMealDB API to search for recipes, get full meal details, random meal suggestions, and find recipes by ingredient.

Korean Stock MCP

Korean Stock MCP

Provides access to Korean stock market data, including stock listings, daily historical records, and 10-minute intraday candles via FinanceDataReader and Naver APIs. It enables users to search for stocks, retrieve detailed profiles, and calculate technical indicators locally.

Thoth MCP Server

Thoth MCP Server

Model Context Protocol (MCP) server for Thoth content creation platform. Enables AI assistants and tools to create and retrieve content through Thoth's API.

⚡️ mcpo

⚡️ mcpo

Um servidor proxy MCP para OpenAPI simples e seguro.

cv-builder

cv-builder

Provides MCP tools for managing a CV as structured content, including a SQLite-backed snippet library with tools to list, create, update, and match job postings, compose role-tailored CV variants, and manage drafts.

rfcxml-mcp

rfcxml-mcp

A Model Context Protocol (MCP) server for structured understanding of RFC documents.

mcp-codestats

mcp-codestats

Enables fetching public Code::Stats user XP and activity data, including total XP, per-language breakdowns, and recent coding activity.

FastMCP Google Docs Manager

FastMCP Google Docs Manager

Enables interaction with Google Docs through a FastMCP server, allowing users to list, read, and create documents. It leverages the Google Docs and Drive APIs to provide seamless document management via Gemini-CLI.

mcp-patent

mcp-patent

MCP server for USPTO patent prior-art search, enabling keyword search, ranking, and date filtering via Claude, Cursor, or Windsurf.

bsc-dex-spread

bsc-dex-spread

Provides a tool to get real-time cross-DEX price and spread data for PancakeSwap v2 and v3 on BSC, with a pay-per-call model settled via x402.

overleaf-mcp

overleaf-mcp

Enables AI agents to read, edit, and compile LaTeX documents in Overleaf projects with tracked changes via the Model Context Protocol.

Web Search MCP Server

Web Search MCP Server

Enables AI agents to search the web and extract content using multiple search providers, with caching, retry logic, and options for JavaScript-heavy page rendering.

mcp-quotable

mcp-quotable

Wraps the Quotable API to search for quotes by keyword or phrase, returning matching quotes with author names and topic tags.

mcp-buzzword-density

mcp-buzzword-density

Analyzes text for overused industry jargon, returning buzzword count, density score, severity level, and flagged terms. Optionally provides humorous critique in roast mode.

crypto-portfolio

crypto-portfolio

Enables real-time cryptocurrency prices, search, and market data via the CoinGecko API without requiring an API key.

kwjm-mcp

kwjm-mcp

MCP server that provides unified access to text, image, and video generation models via the kwjm.com API, with model discovery, capability validation, and clear error explanations.

MarkLogic MCP Server

MarkLogic MCP Server

Um servidor de Protocolo de Contexto de Modelo para MarkLogic que permite operações CRUD e capacidades de consulta de documentos através de uma interface de cliente.

wordpress-mcp

wordpress-mcp

An MCP server for day-to-day WordPress maintenance across multiple client sites.

StatFlow

StatFlow

Enables AI assistants to perform statistical analysis on MySQL databases, generating formatted Excel reports with t-tests and effect sizes, and creating thesis-quality Word documents with AI-powered insights.

MCPishCode

MCPishCode

A self-hosted MCP server that brings a Codex-style coding workflow to ChatGPT, allowing it to read, edit, search, and run code in your local projects.

Aionis MCP Server

Aionis MCP Server

Bridges Aionis execution memory to MCP clients, enabling governed memory context for AI agents.