Discover Awesome MCP Servers
Extend your agent with 17,417 capabilities via MCP servers.
- All17,417
- Developer Tools3,867
- Search1,714
- Research & Data1,557
- AI Integration Systems229
- Cloud Platforms219
- Data & App Analysis181
- Database Interaction177
- Remote Shell Execution165
- Browser Automation147
- Databases145
- Communication137
- AI Content Generation127
- OS Automation120
- Programming Docs Access109
- Content Fetching108
- Note Taking97
- File Systems96
- Version Control93
- Finance91
- Knowledge & Memory90
- Monitoring79
- Security71
- Image & Video Processing69
- Digital Note Management66
- AI Memory Systems62
- Advanced AI Reasoning59
- Git Management Tools58
- Cloud Storage51
- Entertainment & Media43
- Virtualization42
- Location Services35
- Web Automation & Stealth32
- Media Content Processing32
- Calendar Management26
- Ecommerce & Retail18
- Speech Processing18
- Customer Data Platforms16
- Travel & Transportation14
- Education & Learning Tools13
- Home Automation & IoT13
- Web Search Integration12
- Health & Wellness10
- Customer Support10
- Marketing9
- Games & Gamification8
- Google Cloud Integrations7
- Art & Culture4
- Language Translation3
- Legal & Compliance2
ChuckNorris MCP Server
Um gateway MCP experimental que fornece prompts de aprimoramento de LLM especializados com base no repositório L1B3RT4S, destinado principalmente a aprimorar as capacidades de modelos mais fracos.
Meeting Automation MCP Server
Orchestrates Fireflies, Asana, and Notion MCP servers to automate end-to-end meeting workflows. Enables users to search meetings, extract action items, create tasks, and generate meeting documentation through natural language commands.
Deepseek Reasoner
Spreadsheet Remote MCP Server
Enables interaction with Google Spreadsheets through OAuth 2.0 authentication, supporting reading, writing, and creating spreadsheets via a remote MCP server using SSE.
Curl MCP Server
An MCP server that enables AI assistants to make HTTP requests and download files using curl, allowing them to interact with web APIs and content.
Snowflake Server
Integração com o Snowflake implementando operações de leitura e (opcionalmente) gravação, bem como rastreamento de insights.
MCP Weather Server
A lightweight server that exposes weather-related tools (get_coordinates and get_forecast) using the Modular Command Protocol, designed for integration with AI agents and LLMs.
Knowledge Graph MCP Server
Enables fast code analysis and navigation through hybrid semantic search, graph-based relationship tracking, and structure exploration across multiple programming languages with optimized indexing for large codebases.
Image Extractor
Um servidor de Protocolo de Contexto de Modelo que extrai imagens de URLs ou dados base64 e as converte em um formato adequado para análise de LLMs, permitindo que modelos de IA processem e compreendam conteúdo visual.
AgentMCP: Multi-Agent Collaboration Platform
MCPAgent para colaboração multiagente com capacidades de Protocolo de Contexto de Modelo (MCP) integradas.
Obsidian MCP Server
Enables AI assistants like Claude to read, search, create, and manage notes in Obsidian vaults, with features for link analysis, tag management, daily notes, templates, and optional Google Calendar integration. Provides comprehensive vault operations including batch updates, backlinks discovery, and secure file management with path traversal protection.
HuggingMCP
A Model Context Protocol server that allows Claude and other MCP-compatible AI assistants to interact with the Hugging Face ecosystem, enabling repository management, file operations, search, and collections management through natural language.
MCP Tools
An MCP (Model Context Protocol) server implementation using HTTP SSE (Server-Sent Events) connections with built-in utility tools including echo, time, calculator, and weather query functionality.
Cloudflare Playwright MCP
Enables AI assistants to control a browser through Playwright and Cloudflare Workers, allowing web automation tasks like navigation, typing, clicking, and taking screenshots through natural language commands.
MCP Tool
Um servidor construído no mcp-framework que permite a integração com o Claude Desktop através do Protocolo de Contexto de Modelo.
Athena Health MCP Server
Enables interaction with Athena Health's API for comprehensive healthcare practice management. Supports appointment scheduling, provider and department management, patient search, and available slot discovery through natural language.
Ectlocal Connect MCP Server
Enables connection to PostgreSQL databases for EC solution platforms to query and manage e-commerce data including orders, members, and other business information. Provides tools for direct SQL execution, table structure analysis, and specialized e-commerce data retrieval functions.
Cloudflare Playwright MCP
Enables AI assistants to control a browser through a set of tools, allowing them to perform web automation tasks like navigation, typing, clicking, and taking screenshots.
mcp-server-requests
Espelho de
MCP Debugger Tools
A VSCode extension that enables AI agents to programmatically control VSCode's debugging features through the Model Context Protocol (MCP).
MAVLinkMCP
Servidor MCP para comunicação LLM-drone via MAVLink
Azure Java SDK MCP Server
A Model Context Protocol server that provides Azure Java SDK documentation to AI assistants, allowing them to access readme files with introductions, key concepts, and code samples.
Node.js MCP Weather Server
An MCP server that provides weather information like forecasts and alerts for US locations using the National Weather Service API.
MCP Servers Hub
Descubra a coleção mais abrangente e atualizada de servidores MCP do mercado. Este repositório serve como um hub centralizado, oferecendo um catálogo extenso de servidores MCP de código aberto e proprietários, completo com recursos, links de documentação e colaboradores.
Eureka Labo MCP Server
Enables task management and automated development tracking for Eureka Labo projects with git integration. Supports creating, updating, and tracking tasks while automatically capturing code changes and generating detailed development logs with syntax highlighting.
UML MCP
Enables AI assistants to generate UML diagrams through natural language by rendering PlantUML code into PNG or SVG images. Supports sequence diagrams, class diagrams, use case diagrams, and other UML chart types with Base64-encoded output.
Prisma
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
homelab-mcp
MCP servers for managing homelab infrastructure. Monitor Docker/Podman containers, Ollama AI models, Pi-hole DNS, Unifi networks, and Ansible inventory.
Bluetooth MCP Server
Um servidor ModelContextProtocol que permite à IA Claude detectar e escanear dispositivos Bluetooth próximos, fornecendo capacidades de detecção Bluetooth a Claude através de uma interface MCP compatível.