Discover Awesome MCP Servers
Extend your agent with 12,708 capabilities via MCP servers.
- All12,708
- 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
Modular Outlook MCP Server
MCP server for Claude to access Outlook data via Microsoft Graph API
mcp-server-datahub
O servidor MCP oficial para o DataHub (
Browser JavaScript Evaluator
This is a reference design for a MCP server that hosts a web page that connects back to the server via sse and allows Claude to execute javascript on the page.
Model Context Protocol (MCP) Implementation
Learn MCP by building from Scarch
MCPClient Python Application
Okay, I understand. You want an implementation that allows an MCP (presumably Minecraft Protocol) server to interact with an Ollama model. This is a complex task that involves several steps. Here's a breakdown of the concepts, potential implementation strategies, and code snippets to get you started. Keep in mind that this is a high-level overview and will require significant development effort to create a fully functional system. **Core Concepts** * **MCP (Minecraft Protocol):** This is the communication protocol used between Minecraft clients and servers. You'll need to understand how to send and receive packets to interact with the server. Libraries like `mcstatus` (Python) or similar libraries in other languages can help with this. * **Ollama:** This is a tool that allows you to run large language models (LLMs) locally. You'll need to have Ollama installed and a model downloaded. You'll interact with Ollama via its API (usually a REST API). * **Bridge/Middleware:** You'll need a piece of software (the "bridge") that sits between the Minecraft server and the Ollama model. This bridge will: * Receive messages from the Minecraft server (e.g., player chat). * Format the messages and send them to the Ollama model. * Receive the response from the Ollama model. * Format the response and send it back to the Minecraft server (e.g., as a chat message, a command execution, etc.). **Implementation Strategy** Here's a possible implementation strategy, using Python as the example language (but you could use other languages like Java, Go, etc.): 1. **Minecraft Server Interaction:** * **Choose a Library:** Select a library that allows you to interact with the Minecraft protocol. `mcstatus` is good for basic server status, but for more advanced interaction (like reading chat), you'll likely need a more robust library or write your own packet handling. Consider libraries that allow you to create a Minecraft bot. * **Authentication:** If you need to authenticate with the server, implement the necessary login sequence. * **Chat Monitoring:** Listen for chat messages from players. Parse the messages to extract the player's name and the message content. * **Command Handling (Optional):** You might want to allow players to use specific commands (e.g., `/ask <question>`) to interact with the Ollama model. 2. **Ollama Interaction:** * **Ollama API:** Use the Ollama API to send prompts to the model and receive responses. The API is typically a REST API. * **Prompt Engineering:** Design your prompts carefully. You'll need to provide context to the model so it can generate relevant responses. For example, you might include the player's name, the current game state (if you can access it), and the question they asked. * **Response Parsing:** Parse the response from the Ollama model to extract the relevant information. 3. **The Bridge (Middleware):** * **Event Loop:** Create an event loop that continuously listens for messages from the Minecraft server and sends prompts to the Ollama model. * **Message Formatting:** Format the messages from the Minecraft server into a suitable prompt for the Ollama model. * **Response Formatting:** Format the response from the Ollama model into a message that can be sent back to the Minecraft server. * **Error Handling:** Implement error handling to gracefully handle errors such as network issues, API errors, and invalid prompts. * **Rate Limiting:** Implement rate limiting to prevent the Ollama model from being overloaded. **Code Snippets (Python - Illustrative)** ```python import asyncio import aiohttp import json # Replace with your actual Minecraft server details MINECRAFT_SERVER_ADDRESS = "your_server_ip" MINECRAFT_SERVER_PORT = 25565 # Replace with your Ollama model name OLLAMA_MODEL_NAME = "llama2" # Or any other model you have # --- Minecraft Interaction (Illustrative - Requires a proper Minecraft library) --- async def read_minecraft_chat(): """ This is a placeholder. You'll need to use a Minecraft library to actually connect to the server and read chat messages. """ # Example: Assume you have a function that returns a list of chat messages # chat_messages = await get_chat_messages_from_minecraft_server() # For now, let's simulate a chat message await asyncio.sleep(1) # Simulate waiting for a message return [{"player": "Player123", "message": "Hello, Ollama! What is the capital of France?"}] # --- Ollama Interaction --- async def send_to_ollama(prompt: str) -> str: """Sends a prompt to the Ollama API and returns the response.""" url = "http://localhost:11434/api/generate" # Default Ollama API endpoint headers = {"Content-Type": "application/json"} data = { "model": OLLAMA_MODEL_NAME, "prompt": prompt, "stream": False # Set to True for streaming responses } async with aiohttp.ClientSession() as session: try: async with session.post(url, headers=headers, data=json.dumps(data)) as response: if response.status == 200: response_data = await response.json() return response_data["response"] else: print(f"Ollama API Error: {response.status} - {await response.text()}") return "Error communicating with Ollama." except aiohttp.ClientError as e: print(f"AIOHTTP Error: {e}") return "Error communicating with Ollama." # --- Bridge Logic --- async def process_chat_message(player: str, message: str): """Processes a chat message and sends it to Ollama.""" prompt = f"Minecraft Player {player} says: {message}. Respond as a helpful assistant in the Minecraft world." print(f"Sending prompt to Ollama: {prompt}") ollama_response = await send_to_ollama(prompt) print(f"Ollama Response: {ollama_response}") # --- Send the response back to the Minecraft server --- await send_message_to_minecraft(f"Ollama: {ollama_response}") # Replace with actual sending logic async def send_message_to_minecraft(message: str): """ Placeholder for sending a message back to the Minecraft server. You'll need to use your Minecraft library to implement this. """ print(f"Sending to Minecraft: {message}") # Example: await minecraft_bot.send_chat_message(message) pass async def main(): """Main event loop.""" print("Starting MCP-Ollama bridge...") while True: chat_messages = await read_minecraft_chat() if chat_messages: for chat_message in chat_messages: await process_chat_message(chat_message["player"], chat_message["message"]) await asyncio.sleep(0.1) # Check for new messages every 100ms if __name__ == "__main__": asyncio.run(main()) ``` **Explanation of the Code:** * **`read_minecraft_chat()`:** This is a placeholder. You'll need to replace this with code that actually connects to your Minecraft server and reads chat messages. This is the most complex part, as it requires understanding the Minecraft protocol. * **`send_to_ollama()`:** This function sends a prompt to the Ollama API. It uses the `aiohttp` library for asynchronous HTTP requests. It constructs a JSON payload with the model name and the prompt. * **`process_chat_message()`:** This function takes a chat message from a player, formats it into a prompt for Ollama, sends the prompt to Ollama, and then sends the response back to the Minecraft server. * **`send_message_to_minecraft()`:** This is another placeholder. You'll need to replace this with code that sends a message back to the Minecraft server. * **`main()`:** This is the main event loop. It continuously checks for new chat messages from the Minecraft server and processes them. **Key Considerations and Challenges:** * **Minecraft Protocol Complexity:** The Minecraft protocol is complex and constantly evolving. You'll need to stay up-to-date with the latest changes. * **Ollama API Stability:** The Ollama API is relatively new, so it may be subject to change. * **Prompt Engineering:** The quality of the responses from the Ollama model will depend heavily on the quality of your prompts. Experiment with different prompts to find what works best. * **Latency:** There will be some latency involved in sending prompts to the Ollama model and receiving responses. This latency can be noticeable to players. Consider using streaming responses from Ollama to improve perceived responsiveness. * **Resource Usage:** Running an LLM locally can be resource-intensive. Make sure your server has enough CPU and memory to handle the load. * **Security:** Be careful about the prompts you send to the Ollama model. Avoid sending sensitive information. Also, be aware that the Ollama model could potentially generate harmful or offensive content. Implement appropriate filtering and moderation. * **Context Management:** LLMs have limited context windows. You'll need to manage the context effectively to ensure that the model can generate relevant responses. Consider using techniques like summarization or conversation history to provide context. * **Rate Limiting:** Implement rate limiting to prevent players from overloading the Ollama model. * **Error Handling:** Implement robust error handling to gracefully handle errors such as network issues, API errors, and invalid prompts. **Steps to Get Started:** 1. **Install Ollama:** Follow the instructions on the Ollama website to install Ollama on your server. 2. **Download a Model:** Download a suitable LLM from Ollama (e.g., `ollama pull llama2`). 3. **Choose a Minecraft Library:** Select a library that allows you to interact with the Minecraft protocol. 4. **Implement Minecraft Chat Reading:** Implement the `read_minecraft_chat()` function to read chat messages from your Minecraft server. 5. **Implement Minecraft Message Sending:** Implement the `send_message_to_minecraft()` function to send messages back to your Minecraft server. 6. **Test and Iterate:** Test your implementation thoroughly and iterate on your prompts and code to improve the quality of the responses. **Translation to Portuguese (Summary):** Aqui está uma visão geral de como implementar uma interação entre um servidor MCP (Minecraft Protocol) e um modelo Ollama: 1. **Conceitos:** * **MCP:** Protocolo de comunicação do Minecraft. * **Ollama:** Ferramenta para executar modelos de linguagem grandes (LLMs) localmente. * **Ponte/Middleware:** Software que conecta o servidor Minecraft e o Ollama. 2. **Estratégia:** * Usar uma biblioteca para interagir com o protocolo Minecraft (ex: `mcstatus` em Python, ou similar). * Autenticar com o servidor Minecraft (se necessário). * Monitorar o chat do Minecraft. * Usar a API do Ollama para enviar prompts e receber respostas. * Criar prompts bem definidos para o Ollama. * Formatar as mensagens do Minecraft para o Ollama e as respostas do Ollama para o Minecraft. * Implementar tratamento de erros e limitação de taxa. 3. **Código (Python - Exemplo):** O código fornecido demonstra como enviar prompts para o Ollama e receber respostas, mas requer implementação da interação com o servidor Minecraft. 4. **Considerações:** * Complexidade do protocolo Minecraft. * Estabilidade da API do Ollama. * Engenharia de prompts (qualidade dos prompts afeta a qualidade das respostas). * Latência (tempo de resposta). * Uso de recursos (Ollama pode consumir muitos recursos). * Segurança (evitar enviar informações sensíveis e moderar o conteúdo gerado). * Gerenciamento de contexto (LLMs têm janelas de contexto limitadas). * Limitação de taxa (para evitar sobrecarga do Ollama). * Tratamento de erros. 5. **Próximos Passos:** * Instalar o Ollama. * Baixar um modelo Ollama. * Escolher uma biblioteca Minecraft. * Implementar a leitura do chat do Minecraft. * Implementar o envio de mensagens para o Minecraft. * Testar e iterar. This is a complex project, but hopefully, this detailed explanation and the code snippets will give you a good starting point. Good luck! Remember to break down the problem into smaller, manageable tasks.
MCP2HTTP
MCP2HTTP is a minimal transport adapter that bridges MCP clients using stdio with stateless HTTP servers.
Remote MCP Server on Cloudflare
Dockerized Salesforce MCP Server
Dockerized Salesforce MCP Server for REST API integration
Rails MCP Server
A Ruby gem implementation of a Model Context Protocol (MCP) server for Rails projects. This server allows LLMs (Large Language Models) to interact with Rails projects through the Model Context Protocol.
mcp_server_local_files
Local File System MCP Server
MCP Expert Server
Mirror of
iOS Simulator MCP Server
Mirror of
NSAF MCP Server
Espelho de
MCP Server Playwright
MCP Server Playwright - Um serviço de automação de navegador para o Claude Desktop
Supergateway
Run MCP stdio servers over SSE and SSE over stdio. AI gateway.
generator-mcp
Yeoman Generator to quickly create a new MCP Server
Initial thoughts
Okay, here's a breakdown of how to convert OpenAPI specifications to MCP (presumably, you mean Media Control Protocol) server-ready tools, along with considerations and potential approaches: **Understanding the Problem** * **OpenAPI (Swagger):** A standard format for describing RESTful APIs. It defines endpoints, request/response structures, data types, authentication, etc. * **MCP (Media Control Protocol):** A protocol used for controlling media devices (e.g., video servers, routers, switchers, audio consoles). It's often a binary or text-based protocol with specific commands and responses. There isn't a single, universally defined MCP; it's often vendor-specific. * **The Gap:** OpenAPI describes a REST API, while MCP is a different protocol altogether. You need to bridge this gap. You're essentially creating a translation layer. **General Approach** The core idea is to create a service (or set of services) that: 1. **Receives REST requests** (as defined by your OpenAPI specification). 2. **Translates those requests into MCP commands.** 3. **Sends the MCP commands to the target media device(s).** 4. **Receives MCP responses from the device(s).** 5. **Translates the MCP responses into REST responses** (as defined by your OpenAPI specification). 6. **Sends the REST responses back to the client.** **Key Steps and Considerations** 1. **Analyze the OpenAPI Specification:** * **Identify Endpoints:** List all the API endpoints you need to support. * **Understand Data Structures:** Examine the request and response schemas for each endpoint. This is crucial for mapping to MCP commands and data. * **Authentication/Authorization:** How is the REST API secured? You'll need to handle this and potentially translate it into MCP-compatible authentication (if any). 2. **Understand the MCP Protocol:** * **Command Set:** Get the documentation for the specific MCP implementation you're targeting. What commands are available? What are the exact formats (binary or text)? * **Response Formats:** How does the device respond to commands? What data is included in the responses? * **State Management:** Does the MCP device maintain state? If so, you'll need to manage this in your translation layer. * **Connection Management:** How do you connect to the MCP device? TCP/IP? Serial? 3. **Mapping OpenAPI to MCP:** * **Define the Translation Rules:** This is the most critical step. For each OpenAPI endpoint, you need to define *exactly* how it maps to one or more MCP commands. Consider: * **Endpoint -> Command(s):** Which MCP command(s) are triggered by a specific REST endpoint? * **Request Data -> Command Parameters:** How do the data fields in the REST request map to the parameters of the MCP command? This might involve data type conversions, unit conversions, or other transformations. * **Response Data <- Command Responses:** How do the data fields in the MCP response map to the fields in the REST response? * **Error Handling:** How are MCP errors translated into REST error codes and messages? * **Example:** * **OpenAPI Endpoint:** `PUT /channels/1/volume` (sets the volume of channel 1) with a request body like `{ "volume": 0.75 }` * **MCP Command (Hypothetical):** `SET_VOLUME 1 75` (sets volume of channel 1 to 75%, assuming MCP uses integer percentages) * **Mapping:** The `volume` field in the REST request (0.75) is multiplied by 100 and converted to an integer (75) to become the second parameter of the `SET_VOLUME` command. 4. **Implementation:** * **Choose a Programming Language/Framework:** Python, Node.js, Go, Java, etc. Consider factors like: * Your familiarity with the language. * Availability of libraries for REST API handling (e.g., Flask/FastAPI for Python, Express for Node.js). * Availability of libraries for communicating with the MCP device (you might need to write your own if it's a custom protocol). * Performance requirements. * **Create the REST API Server:** Use your chosen framework to create a REST API that conforms to your OpenAPI specification. This will handle incoming requests, route them to the appropriate handlers, and send back responses. * **Implement the MCP Communication:** Write code to: * Establish a connection to the MCP device. * Send MCP commands. * Receive MCP responses. * Handle connection errors and timeouts. * **Implement the Translation Logic:** This is where you implement the mapping rules you defined in step 3. This will involve: * Parsing the REST request data. * Constructing the MCP command string or binary data. * Parsing the MCP response data. * Constructing the REST response data. * **Error Handling:** Implement robust error handling to catch exceptions, log errors, and return appropriate error responses to the client. 5. **Testing:** * **Unit Tests:** Test individual components of your translation layer (e.g., the functions that convert data types). * **Integration Tests:** Test the entire flow from REST request to MCP command to MCP response to REST response. * **End-to-End Tests:** Test the API with real clients and the actual MCP device. * **Load Testing:** Test the API under load to ensure it can handle the expected number of requests. **Example (Conceptual - Python with Flask)** ```python from flask import Flask, request, jsonify import socket # For MCP communication app = Flask(__name__) # MCP Configuration MCP_HOST = "192.168.1.100" MCP_PORT = 5000 def send_mcp_command(command): """Sends an MCP command and returns the response.""" try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((MCP_HOST, MCP_PORT)) s.sendall(command.encode('utf-8')) # Assuming text-based MCP response = s.recv(1024).decode('utf-8') return response except Exception as e: print(f"MCP Error: {e}") return None @app.route('/channels/<int:channel_id>/volume', methods=['PUT']) def set_channel_volume(channel_id): """Sets the volume of a channel.""" try: data = request.get_json() volume = data['volume'] # Volume as a float (0.0 - 1.0) # MCP Command: SET_VOLUME <channel> <volume_percentage> volume_percentage = int(volume * 100) mcp_command = f"SET_VOLUME {channel_id} {volume_percentage}" mcp_response = send_mcp_command(mcp_command) if mcp_response: # Assuming MCP response is just "OK" or "ERROR" if "OK" in mcp_response: return jsonify({"message": "Volume set successfully"}), 200 else: return jsonify({"error": "MCP error", "details": mcp_response}), 500 else: return jsonify({"error": "Failed to communicate with MCP device"}), 500 except Exception as e: print(f"Error: {e}") return jsonify({"error": "Invalid request", "details": str(e)}), 400 if __name__ == '__main__': app.run(debug=True) ``` **Important Considerations:** * **Vendor-Specific MCP:** The biggest challenge is the lack of a standardized MCP. You'll need to work closely with the documentation and potentially the vendor of the media devices you're controlling. * **Asynchronous Operations:** If MCP commands take a long time to execute, consider using asynchronous programming (e.g., `asyncio` in Python) to avoid blocking the REST API server. * **Security:** Secure the REST API with appropriate authentication and authorization mechanisms. Consider how to translate these mechanisms to the MCP protocol (if necessary). * **Scalability:** If you need to handle a large number of requests, consider using a load balancer and scaling your REST API server horizontally. * **Monitoring:** Implement monitoring to track the health and performance of your translation layer. **Tools that Might Help:** * **OpenAPI Generator:** Can generate server stubs (code skeletons) from your OpenAPI specification in various languages. This can save you time in setting up the REST API. * **Swagger UI:** Provides a user interface for exploring and testing your OpenAPI specification. * **Postman/Insomnia:** Tools for sending REST requests and inspecting responses. Useful for testing your API. * **Wireshark:** A network protocol analyzer that can be used to capture and analyze MCP traffic. This can be helpful for debugging MCP communication. **In summary, converting OpenAPI to MCP requires a custom translation layer that understands both protocols and can map between them. The complexity of this task depends heavily on the specific MCP implementation you're targeting.** Good luck!
Financial Analysis MCP Server
Espelho de
Ghost MCP Server
Mirror of
Weather MCP Server
Here's a sample MCP (Minecraft Protocol) server implementation concept for fetching weather forecasts. This is a high-level outline and would require significant coding to implement fully. It focuses on the *communication* aspect using MCP, not the actual weather data retrieval. **Conceptual Overview** The idea is to create a custom Minecraft server mod (or plugin) that: 1. **Registers a Custom Channel:** Uses the Minecraft Protocol to define a new channel (e.g., "weather:forecast"). This channel will be used for communication between the client (player's Minecraft client) and the server. 2. **Listens for Requests:** The server listens for incoming packets on the "weather:forecast" channel. These packets will contain requests for weather information. 3. **Fetches Weather Data:** Upon receiving a request, the server uses an external weather API (e.g., OpenWeatherMap, AccuWeather API) to retrieve the weather forecast for a specified location (e.g., based on player coordinates or a named location). 4. **Sends Response:** The server formats the weather data into a packet and sends it back to the client on the "weather:forecast" channel. 5. **Client-Side Mod:** A client-side mod is required to: * Register the same "weather:forecast" channel. * Send requests to the server on this channel. * Receive and parse the weather data from the server. * Display the weather information to the player (e.g., in the chat, on a custom GUI). **Simplified Code Example (Conceptual - Java/Spigot/Paper)** This is a very simplified example to illustrate the core concepts. It omits error handling, proper data serialization, and other important considerations. **Server-Side (Spigot/Paper Plugin)** ```java import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.messaging.PluginMessageListener; import org.bukkit.entity.Player; import org.bukkit.Bukkit; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import org.json.JSONObject; public class WeatherPlugin extends JavaPlugin implements PluginMessageListener { private static final String CHANNEL = "weather:forecast"; private static final String WEATHER_API_KEY = "YOUR_OPENWEATHERMAP_API_KEY"; // Replace with your API key @Override public void onEnable() { getLogger().info("WeatherPlugin has been enabled!"); getServer().getMessenger().registerIncomingPluginChannel(this, CHANNEL, this); getServer().getMessenger().registerOutgoingPluginChannel(this, CHANNEL); } @Override public void onDisable() { getLogger().info("WeatherPlugin has been disabled!"); getServer().getMessenger().unregisterIncomingPluginChannel(this, CHANNEL, this); getServer().getMessenger().unregisterOutgoingPluginChannel(this, CHANNEL); } @Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { if (!channel.equals(CHANNEL)) { return; } try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(message))) { String subchannel = in.readUTF(); // e.g., "request_weather" if (subchannel.equals("request_weather")) { double latitude = in.readDouble(); double longitude = in.readDouble(); // Asynchronously fetch weather data Bukkit.getScheduler().runTaskAsynchronously(this, () -> { String weatherData = fetchWeatherData(latitude, longitude); sendWeatherResponse(player, weatherData); }); } } catch (IOException e) { e.printStackTrace(); } } private String fetchWeatherData(double latitude, double longitude) { // Replace with your actual weather API call String apiUrl = String.format("https://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=%s&units=metric", latitude, longitude, WEATHER_API_KEY); HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(apiUrl)) .build(); try { HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() == 200) { // Parse the JSON response (using org.json) JSONObject json = new JSONObject(response.body()); String description = json.getJSONArray("weather").getJSONObject(0).getString("description"); double temperature = json.getJSONObject("main").getDouble("temp"); return "Weather: " + description + ", Temperature: " + temperature + "°C"; } else { return "Error fetching weather data: " + response.statusCode(); } } catch (Exception e) { e.printStackTrace(); return "Error fetching weather data: " + e.getMessage(); } } private void sendWeatherResponse(Player player, String weatherData) { Bukkit.getScheduler().runTask(this, () -> { // Back to main thread for Bukkit operations try { java.io.ByteArrayOutputStream bOut = new java.io.ByteArrayOutputStream(); java.io.DataOutputStream out = new java.io.DataOutputStream(bOut); out.writeUTF("weather_response"); // Subchannel out.writeUTF(weatherData); player.sendPluginMessage(this, CHANNEL, bOut.toByteArray()); out.close(); } catch (IOException e) { e.printStackTrace(); } }); } } ``` **Client-Side (Forge/Fabric Mod - Example using Forge)** ```java import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.network.FMLNetworkEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.relauncher.Side; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.text.TextComponentString; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; @Mod(modid = "weatherclient", name = "Weather Client", version = "1.0") public class WeatherClient { public static final String MODID = "weatherclient"; public static final String CHANNEL = "weather:forecast"; public static SimpleNetworkWrapper network; @Mod.EventHandler public void init(FMLInitializationEvent event) { network = NetworkRegistry.INSTANCE.newSimpleChannel(MODID); NetworkRegistry.INSTANCE.registerGuiHandler(MODID, new GuiProxy()); // If you want a GUI // Register the client-side packet handler (if using custom packets) // network.registerMessage(WeatherMessageHandler.class, WeatherMessage.class, 0, Side.CLIENT); } @SubscribeEvent public void onClientConnectedToServer(FMLNetworkEvent.ClientConnectedToServerEvent event) { // Register the channel when the client connects Minecraft.getMinecraft().getConnection().getNetworkManager().channel().attr(io.netty.channel.ChannelHandler.class).set(new io.netty.channel.ChannelHandler() { @Override public void handlerAdded(io.netty.channel.ChannelHandlerContext ctx) throws Exception { ctx.pipeline().addLast(new io.netty.channel.ChannelInboundHandlerAdapter() { @Override public void channelRead(io.netty.channel.ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof net.minecraft.network.PacketBuffer) { net.minecraft.network.PacketBuffer buffer = (net.minecraft.network.PacketBuffer) msg; String channelName = buffer.readString(32767); // Max string length if (CHANNEL.equals(channelName)) { byte[] data = new byte[buffer.readableBytes()]; buffer.readBytes(data); handleWeatherResponse(data); } } super.channelRead(ctx, msg); } }); } @Override public void handlerRemoved(io.netty.channel.ChannelHandlerContext ctx) throws Exception { } @Override public void exceptionCaught(io.netty.channel.ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); } @Override public boolean isSharable() { return false; } }); } public static void requestWeather() { EntityPlayer player = Minecraft.getMinecraft().player; if (player != null && Minecraft.getMinecraft().getConnection() != null) { try { java.io.ByteArrayOutputStream bOut = new java.io.ByteArrayOutputStream(); java.io.DataOutputStream out = new java.io.DataOutputStream(bOut); out.writeUTF("request_weather"); // Subchannel out.writeDouble(player.posX); out.writeDouble(player.posZ); out.close(); net.minecraft.network.PacketBuffer buffer = new net.minecraft.network.PacketBuffer(io.netty.buffer.Unpooled.buffer()); buffer.writeString(CHANNEL); buffer.writeBytes(bOut.toByteArray()); Minecraft.getMinecraft().getConnection().getNetworkManager().sendPacket(new net.minecraft.network.play.client.CPacketCustomPayload(CHANNEL, buffer)); } catch (IOException e) { e.printStackTrace(); } } } private void handleWeatherResponse(byte[] data) { try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(data))) { String subchannel = in.readUTF(); if (subchannel.equals("weather_response")) { String weatherData = in.readUTF(); Minecraft.getMinecraft().player.sendMessage(new TextComponentString(weatherData)); } } catch (IOException e) { e.printStackTrace(); } } // Example: Add a keybinding to trigger the weather request // (Requires more setup - see Forge documentation) // @SubscribeEvent // public void onKeyInput(InputEvent.KeyInputEvent event) { // if (KeyBindings.WEATHER_KEY.isPressed()) { // requestWeather(); // } // } } ``` **Key Improvements and Explanations** * **Asynchronous Weather Fetching:** The server now fetches weather data *asynchronously* using `Bukkit.getScheduler().runTaskAsynchronously()`. This prevents the main server thread from being blocked while waiting for the API response, improving server performance. The response is then sent back to the client on the main thread. * **JSON Parsing:** The server now parses the JSON response from the OpenWeatherMap API using the `org.json` library (you'll need to include this in your plugin's dependencies). It extracts the weather description and temperature. * **Error Handling:** Basic error handling is included in the `fetchWeatherData` method to catch exceptions and return an error message to the client. * **Subchannels:** The code uses "subchannels" within the main `weather:forecast` channel. This allows you to send different types of requests and responses on the same channel (e.g., "request_weather", "weather_response"). This is a good practice for organizing your communication. * **Client-Side Channel Registration:** The client-side code now registers the custom channel using a `ChannelHandler` when the client connects to the server. This is crucial for receiving custom payload packets. * **Packet Sending:** The client-side code now correctly sends the custom payload packet using `CPacketCustomPayload`. * **Data Streams:** Uses `DataInputStream` and `DataOutputStream` for more robust data serialization and deserialization. This is important for handling different data types (strings, numbers, etc.). * **Thread Safety:** The `sendWeatherResponse` method uses `Bukkit.getScheduler().runTask()` to ensure that the `player.sendPluginMessage()` call is executed on the main server thread, which is required for Bukkit API calls. * **OpenWeatherMap API:** The example uses the OpenWeatherMap API. You'll need to sign up for an API key and replace `"YOUR_OPENWEATHERMAP_API_KEY"` with your actual key. The API URL includes latitude, longitude, your API key, and specifies metric units. * **Forge Networking:** The client-side example uses Forge's `SimpleNetworkWrapper` for handling network communication. This is a common and recommended approach for Forge mods. (Note: The example shows the basic setup but doesn't fully implement custom packets. You might want to explore using custom packets for more complex data structures.) * **Client-Side Packet Handling:** The client-side code now includes a basic packet handler (`WeatherMessageHandler`) that receives and processes the weather data from the server. This handler is registered with the `SimpleNetworkWrapper`. * **Displaying Weather:** The client-side code now displays the received weather data in the player's chat using `Minecraft.getMinecraft().player.sendMessage()`. * **Keybinding (Commented Out):** The example includes a commented-out section for adding a keybinding to trigger the weather request. This requires additional setup (registering the keybinding, handling input events), which is beyond the scope of this basic example. Refer to Forge documentation for details. **Important Considerations** * **Minecraft Version:** The code needs to be adapted to the specific Minecraft version you are targeting (e.g., 1.12.2, 1.16.5, 1.18.2, 1.19.x). The MCP mappings and API calls will vary. * **MCP Mappings:** You'll need to use MCP mappings (or equivalent) to deobfuscate the Minecraft code and access the necessary classes and methods. * **Dependencies:** You'll need to include the necessary dependencies in your project (e.g., Spigot/Paper API, Forge API, JSON library). * **Error Handling:** Implement robust error handling to handle API errors, network errors, and other potential issues. * **Data Serialization:** Use a reliable data serialization method (e.g., JSON, Protocol Buffers) to ensure that data is transmitted correctly between the client and server. * **Security:** Be mindful of security considerations, especially when handling user input or external API calls. Sanitize data and prevent injection vulnerabilities. * **Performance:** Optimize your code for performance, especially if you are handling a large number of requests. Use asynchronous operations and caching to reduce the load on the server. * **Permissions:** Consider adding permissions to control who can access the weather information. * **Configuration:** Allow users to configure the plugin/mod (e.g., API key, location, display settings). * **Alternative APIs:** Explore other weather APIs that might better suit your needs. * **Fabric:** If you're using Fabric instead of Forge, the networking and mod loading mechanisms will be different. Refer to the Fabric documentation for details. **How to Use** 1. **Set up a Development Environment:** Set up a Minecraft mod development environment using either Forge or Fabric. 2. **Create a Plugin/Mod:** Create a new plugin (for Spigot/Paper) or mod (for Forge/Fabric). 3. **Add Dependencies:** Add the necessary dependencies to your project (e.g., Spigot/Paper API, Forge API, JSON library). 4. **Copy the Code:** Copy the server-side code into your plugin's main class and the client-side code into your mod's main class. 5. **Replace API Key:** Replace `"YOUR_OPENWEATHERMAP_API_KEY"` with your actual OpenWeatherMap API key. 6. **Build and Install:** Build the plugin/mod and install it on your Minecraft server and client. 7. **Test:** Run the Minecraft client and server and test the weather functionality. You might need to add a command or keybinding to trigger the weather request. This is a complex project, but this detailed outline and example code should give you a good starting point. Remember to consult the documentation for your chosen Minecraft modding platform (Forge or Fabric) and the weather API you are using. Good luck!
glif-mcp
Espelho de
ConnectWise Manage MCP Server
A Model Context Protocol (MCP) server for ConnectWise Manage API integration
Gmail MCP Server
Mirror of
Spring AI MCP Server 示例项目
Fiberflow MCP Gateway
Run Fiberflow MCP SSE Server over stdio.
simple_mcp_server
Test Simple MCP server

ChatSum
Okay, I understand. Please provide me with the chat messages you'd like me to query and summarize. I'm ready to translate them into Portuguese and then provide a summary in Portuguese as well. Just paste the text here.
Google Drive & Sheets MCP Server
A Model Context Protocol (MCP) server built in Rust for interacting with Google Drive and Google Sheets.
gameanalytics-server MCP Server
GameAnalytics MCP server for Model Context Protocol integration
Airbnb MCP Server (Enhanced)
Enhanced MCP server for Airbnb search and listing details