Discover Awesome MCP Servers
Extend your agent with 24,070 capabilities via MCP servers.
- All24,070
- 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
RulesetMCP
Provides AI agents with queryable, version-controlled project rules and coding standards. Enables validation, rule-based guidance, and task summaries to keep AI work aligned with your project's conventions without repeating context.
API Suggestion Server
BuildBetter
AI for product teams. Connect all your company and customer knowledge to all of your other tools via BuildBetter's 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.
Aareguru MCP Server
Provides Swiss Aare river swimming data including water temperature, flow rates, safety assessments, and forecasts. Enables AI assistants to answer questions about current conditions, compare cities, and provide safety recommendations based on official BAFU thresholds.
mcp-server-hcp-terraform
Servidor MCP para trabalhar com HCP Terraform
QuantPlay MCP Server
Provides access to the QuantPlay trading API for managing broker accounts, tracking positions, and analyzing holdings. It enables users to interact with their trading data through MCP-compatible clients like Claude Desktop.
Jina Free MCP
A Managed Component Provider that enables fetching webpage content using Jina AI's reader service.
Monitor MCP Server
Basic MCP Server
A minimal template server demonstrating MCP tools, resources, and prompts built with Smithery SDK. Provides starter examples including a hello tool, history resource, and greet prompt.
Medical MCP Server
Provides comprehensive medical information by querying authoritative sources including FDA drug database, WHO health statistics, PubMed literature, RxNorm nomenclature, Google Scholar, and Australia's PBS API through 22+ specialized tools.
mcp-server-bash
Servidor MCP minimalista escrito em script bash.
mcpmonorepo
Ambiente de teste para servidores MCP em um Mono Repo.
Self-hosted AI starter kit (by the n8n team)
Here's a translation of "pydantic agent workflow using mcp servers to test out advanced retrieval of linked data" into Portuguese, along with some considerations for different nuances: **Option 1 (More Literal):** "Fluxo de trabalho de agente Pydantic usando servidores MCP para testar a recuperação avançada de dados vinculados." **Option 2 (Slightly More Natural):** "Um fluxo de trabalho de agente Pydantic que utiliza servidores MCP para testar a recuperação avançada de dados vinculados." **Option 3 (Emphasizing the Purpose):** "Fluxo de trabalho de um agente Pydantic para testar a recuperação avançada de dados vinculados, utilizando servidores MCP." **Explanation of Choices and Nuances:** * **"Pydantic agent workflow"**: "Fluxo de trabalho de agente Pydantic" is a direct and generally accepted translation. "Agente Pydantic" implies an agent built using the Pydantic library. * **"using mcp servers"**: "usando servidores MCP" is a direct translation. If the context is very technical, you might consider adding "servidores MCP" in parentheses after the first mention of MCP, like this: "servidores MCP (Message Channel Protocol)". * **"to test out"**: This phrase implies experimentation. "Para testar" is the most direct translation. You could also use "para experimentar" if you want to emphasize the experimental nature. * **"advanced retrieval of linked data"**: "recuperação avançada de dados vinculados" is a good translation. "Dados vinculados" is the standard translation for "linked data." **Which option to choose depends on the context:** * If you need a very precise and technical translation, **Option 1** is best. * If you want a slightly more natural-sounding sentence, **Option 2** is a good choice. * If you want to emphasize the purpose of the workflow, **Option 3** is suitable. Therefore, I recommend **Option 2** as a good balance between accuracy and naturalness: **"Um fluxo de trabalho de agente Pydantic que utiliza servidores MCP para testar a recuperação avançada de dados vinculados."**
Multi MCP Server
Multi MCP Server
Test MCP
Servidor MCP simples para fins de teste.
Oracle DB Context
Provides contextual Oracle database schema information to AI assistants, enabling them to understand and work with large databases containing thousands of tables. Supports multi-database connections, smart schema caching, table lookups, and relationship mapping.
Get My Notion MCP Server
Provides access to a specific GitHub repository (my-notion) allowing AI assistants to browse files, read content, and track commit information. Enables real-time interaction with repository data through the GitHub API without authentication requirements.
Feifei Proxy MCP
A service that converts existing MCP protocols (stdio/sse) to streamable\_http transmission type, allowing compatibility between different MCP implementations.
Schwab MCP Server
A read-only MCP server that provides access to Charles Schwab account data and market information, including portfolio positions, real-time quotes, options chains, price history, and account balances through AI assistants.
Productboard Integration
Integra a API do Productboard em fluxos de trabalho agentic, permitindo a interação com empresas, componentes, funcionalidades, notas e produtos da plataforma Productboard.
Pearch
Best people search engine that reduces the time spent on talent discovery
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
Harmonic MCP Server
Provides tools to interact with the Harmonic AI API for company and person enrichment, specifically focusing on venture capital deal flow. It enables users to search for companies using natural language, find similar businesses, and retrieve detailed information on organizations and individuals.
Get Gather
A containerized service that enables MCP clients to interact with data and perform actions through a remote browser environment. It supports live streaming of the container desktop and offers proxy configuration for location-based browser sessions.
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.
Graphiti-Memory MCP Server
Enables storing and querying memories in a Neo4j knowledge graph with automatic entity extraction. Supports adding episodes, searching entities and relationships, and managing graph data through natural language.
GitHub GraphQL API MCP
Enables querying and exploring the GitHub GraphQL API schema and executing optimized GraphQL queries to retrieve precise GitHub data (repositories, issues, PRs, users) with reduced token consumption.