发现优秀的 MCP 服务器
通过 MCP 服务器扩展您的代理能力,拥有 86,267 个能力。
Server
Okay, here's a basic outline and code snippets for a simple "Weather MCP" (presumably meaning "Minecraft Protocol") server in Python. I'll break it down into sections and explain the key concepts. Keep in mind that this is a *very* simplified example and doesn't implement the full Minecraft protocol. It's designed to illustrate the core idea of a server that responds to Minecraft client requests with weather data. **Important Considerations:** * **Minecraft Protocol Complexity:** The actual Minecraft protocol is complex and constantly evolving. This example *does not* implement it fully. It's a simplified demonstration. For real Minecraft server development, you'd need a robust library like `mcstatus` or a more complete server implementation. * **MCP (Minecraft Coder Pack):** MCP is primarily for *modding* the Minecraft client and server, not for creating entirely new servers. I'm assuming you're using "MCP" loosely to mean "something that interacts with Minecraft." * **Weather Data Source:** This example uses a placeholder for weather data. You'll need to integrate a real weather API (e.g., OpenWeatherMap, AccuWeather) to get actual weather information. * **Security:** This is a basic example and doesn't include any security measures. Real Minecraft servers need proper security to prevent exploits. **Conceptual Outline:** 1. **Socket Setup:** Create a TCP socket to listen for incoming connections from Minecraft clients (or a proxy/mod that simulates a client). 2. **Client Connection Handling:** When a client connects, accept the connection and create a new thread or process to handle it. 3. **Simplified Protocol:** Define a very simple protocol for the client to request weather data. For example, the client might send a specific string like "WEATHER_REQUEST". 4. **Weather Data Retrieval:** When a request is received, fetch weather data from your chosen source (API or placeholder). 5. **Response Formatting:** Format the weather data into a string or a simple data structure that the client can understand. 6. **Sending the Response:** Send the formatted weather data back to the client through the socket. 7. **Closing the Connection:** Close the connection with the client. **Python Code (Illustrative Example):** ```python import socket import threading import time # For simulating weather updates import random # For simulating weather updates # Configuration HOST = '127.0.0.1' # Listen on localhost PORT = 25566 # Choose a port (not the default Minecraft port) WEATHER_REQUEST_COMMAND = "WEATHER_REQUEST" SIMULATE_WEATHER = True # Set to False if using a real API # Placeholder for weather data (replace with API integration) weather_data = { "temperature": 25, "condition": "Clear", "humidity": 60 } def update_weather(): """Simulates weather updates (replace with API calls).""" global weather_data while SIMULATE_WEATHER: weather_data["temperature"] = random.randint(15, 35) conditions = ["Clear", "Rain", "Cloudy", "Thunderstorm"] weather_data["condition"] = random.choice(conditions) weather_data["humidity"] = random.randint(40, 80) print(f"Weather updated: {weather_data}") time.sleep(60) # Update every 60 seconds def handle_client(conn, addr): """Handles a single client connection.""" print(f"Connected by {addr}") try: while True: data = conn.recv(1024) # Receive up to 1024 bytes if not data: break # Client disconnected message = data.decode('utf-8').strip() print(f"Received: {message}") if message == WEATHER_REQUEST_COMMAND: # Format the weather data into a string weather_string = f"Temperature: {weather_data['temperature']}°C, Condition: {weather_data['condition']}, Humidity: {weather_data['humidity']}%" conn.sendall(weather_string.encode('utf-8')) else: conn.sendall("Unknown command".encode('utf-8')) except Exception as e: print(f"Error handling client: {e}") finally: conn.close() print(f"Connection closed with {addr}") def start_server(): """Starts the weather server.""" server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Avoid address already in use error try: server_socket.bind((HOST, PORT)) server_socket.listen() print(f"Weather server listening on {HOST}:{PORT}") # Start the weather update thread if SIMULATE_WEATHER: weather_thread = threading.Thread(target=update_weather) weather_thread.daemon = True # Exit when the main thread exits weather_thread.start() while True: conn, addr = server_socket.accept() client_thread = threading.Thread(target=handle_client, args=(conn, addr)) client_thread.start() except Exception as e: print(f"Server error: {e}") finally: server_socket.close() if __name__ == "__main__": start_server() ``` **Explanation:** 1. **Imports:** Imports necessary modules: `socket` for network communication, `threading` for handling multiple clients concurrently, `time` for simulating weather updates, and `random` for generating random weather data. 2. **Configuration:** * `HOST`: The IP address to listen on (localhost in this case). * `PORT`: The port number to listen on. Choose a port that's not already in use. *Do not use the default Minecraft port (25565) unless you know what you're doing.* * `WEATHER_REQUEST_COMMAND`: The string that the client sends to request weather data. * `SIMULATE_WEATHER`: A flag to control whether to simulate weather updates or use a real API. 3. **`weather_data`:** A dictionary to store the current weather information. This is a placeholder; you'll replace this with data from a real weather API. 4. **`update_weather()`:** This function simulates weather updates. It randomly changes the temperature, condition, and humidity every 60 seconds. *Replace this with code that calls a weather API.* The `time.sleep(60)` call pauses the thread for 60 seconds. The `weather_thread.daemon = True` line ensures that the thread exits when the main program exits. 5. **`handle_client(conn, addr)`:** This function handles the communication with a single client. * It receives data from the client using `conn.recv(1024)`. * It decodes the data from bytes to a string using `data.decode('utf-8')`. * It checks if the received message is the `WEATHER_REQUEST_COMMAND`. * If it is, it formats the weather data into a string and sends it back to the client using `conn.sendall(weather_string.encode('utf-8'))`. The `encode('utf-8')` converts the string to bytes before sending. * If the message is not recognized, it sends an "Unknown command" message. * It closes the connection using `conn.close()`. 6. **`start_server()`:** This function sets up the server socket and listens for incoming connections. * It creates a TCP socket using `socket.socket(socket.AF_INET, socket.SOCK_STREAM)`. * It binds the socket to the specified host and port using `server_socket.bind((HOST, PORT))`. * It starts listening for connections using `server_socket.listen()`. * It enters a loop that accepts incoming connections using `server_socket.accept()`. * For each connection, it creates a new thread to handle the client using `threading.Thread(target=handle_client, args=(conn, addr))`. * It starts the thread using `client_thread.start()`. * The `server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)` line is important. It allows you to quickly restart the server after it crashes or is stopped without getting an "Address already in use" error. 7. **`if __name__ == "__main__":`:** This ensures that the `start_server()` function is only called when the script is run directly (not when it's imported as a module). **How to Run:** 1. Save the code as a Python file (e.g., `weather_server.py`). 2. Run the script from your terminal: `python weather_server.py` **Client-Side (Simplified Example - Requires Modification for Minecraft):** This is a *very* basic Python client to test the server. **This will NOT work directly with Minecraft.** You'll need to adapt it to send the request from within a Minecraft mod or through a proxy. ```python import socket HOST = '127.0.0.1' PORT = 25566 WEATHER_REQUEST_COMMAND = "WEATHER_REQUEST" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) s.sendall(WEATHER_REQUEST_COMMAND.encode('utf-8')) data = s.recv(1024) print('Received:', repr(data.decode('utf-8'))) ``` **Important Notes and Next Steps:** * **Minecraft Integration:** The biggest challenge is integrating this with Minecraft. You'll need to: * **Create a Minecraft Mod:** This is the most common approach. Your mod would need to: * Establish a connection to your Python server. * Send the `WEATHER_REQUEST_COMMAND`. * Receive the weather data. * Display the weather data in the game (e.g., in the chat, on a custom GUI). * **Use a Proxy:** You could create a proxy server that sits between the Minecraft client and the real Minecraft server. The proxy would intercept weather-related packets and replace them with data from your Python server. This is more complex. * **Weather API Integration:** Replace the placeholder weather data with calls to a real weather API. You'll need to: * Sign up for an API key from a weather service (e.g., OpenWeatherMap). * Install the `requests` library: `pip install requests` * Modify the `update_weather()` function to make API calls. * **Error Handling:** Add more robust error handling to the server and client code. * **Data Formatting:** Consider using a more structured data format like JSON for sending weather data between the server and client. This will make it easier to parse the data on the client side. * **Security:** Implement security measures to protect your server from unauthorized access. **Example of Weather API Integration (OpenWeatherMap):** ```python import requests # Replace with your OpenWeatherMap API key API_KEY = "YOUR_OPENWEATHERMAP_API_KEY" CITY = "London" # Or any city you want def get_weather_from_api(): """Gets weather data from OpenWeatherMap.""" url = f"http://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={API_KEY}&units=metric" try: response = requests.get(url) response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx) data = response.json() weather_data = { "temperature": data["main"]["temp"], "condition": data["weather"][0]["description"], "humidity": data["main"]["humidity"] } return weather_data except requests.exceptions.RequestException as e: print(f"Error fetching weather data: {e}") return None # In your update_weather() function: def update_weather(): global weather_data while SIMULATE_WEATHER: new_weather = get_weather_from_api() if new_weather: weather_data = new_weather print(f"Weather updated from API: {weather_data}") else: print("Failed to update weather from API.") time.sleep(60) ``` Remember to replace `"YOUR_OPENWEATHERMAP_API_KEY"` with your actual API key. You'll also need to adjust the `CITY` variable to the city you want weather data for. This comprehensive explanation and code should give you a solid starting point for building your weather MCP server in Python. Good luck!
Hungarian Financial Regulation MCP
Enables querying Hungarian financial regulation data, including regulations, decisions, and requirements from MNB, directly from MCP-compatible clients like Claude or Cursor.
lockbox-mcp
Enables AI coding agents to securely store and retrieve encrypted API keys via MCP tools.
MessagesBridge
MCP server that lets ChatGPT search and read iMessage/SMS history, send one-at-a-time messages, and manage Contacts on your own Mac, with confirmations for any writes.
Ambiance MCP Server
Provides intelligent code context and analysis through semantic compression, AST parsing, and multi-language support. Offers 60-80% token reduction while enabling AI assistants to understand codebases through local analysis, OpenAI-enhanced insights, and GitHub repository integration.
Android Debug Bridge MCP
Enables control of Android devices via ADB for automation and testing. Supports app management, screen capture, UI analysis, and input simulation through natural language commands.
MCP_servers
mcp-arcgis-leecounty
Enables AI agents to search and query Lee County GIS open geospatial datasets (parcels, addresses, zoning, public works) via ArcGIS Feature Services.
secure-comms
Enables secure communications with built-in EU AI Act compliance through the MCP protocol.
figma-mcp-flutter-test
使用 Figma MCP 服务器,在 Flutter 中重现 Figma 设计的实验性项目。
AuthMCP Gateway
Secure MCP protocol proxy with OAuth2 + Dynamic Client Registration (DCR), JWT auth, RBAC, rate limiting, multi-server aggregation, and a monitoring/admin dashboard.
GitLab MCP Server
Connects AI assistants to GitLab, enabling natural language queries to view merge requests, review discussions, test reports, pipeline status, and respond to comments directly from chat.
geocode-mcp
MCP server for geocoding, reverse geocoding, place/POI search, and distance calculation using OpenStreetMap Nominatim, with no API key required.
Frigolog HACCP MCP
Provides AI agents with accurate French HACCP regulatory data, live RappelConso recalls, and Alim'confiance scores to ensure food safety compliance and avoid hallucinations.
MCP Dungeon Game
An idle dungeon crawler game playable through conversation, featuring equipment collection, time-based dungeon exploration, auto-battles, random events, and encrypted local save data.
Google Ads MCP Server (Fork with Write Tools)
Enables AI assistants to manage Google Ads accounts by providing tools for querying account data and performing write operations such as updating campaign budgets, statuses, and bidding strategies.
YNAB MCP Server
Enables interaction with You Need A Budget (YNAB) through their API, allowing users to manage budgets, accounts, categories, transactions, payees, and scheduled transactions through natural language.
Weather MCP App
An MCP server that provides current weather, hourly and 7-day forecasts, and air quality data for any city or zip code, with an interactive React UI and support for both stdio and HTTP transports.
phonecall-mcp
Enables Claude to make and manage real phone calls through Twilio, allowing it to think, search, and respond in real-time conversations.
PanDA Gateway
A thin, stateless MCP routing layer that exposes a single Streamable HTTP endpoint and routes tool calls to upstream servers (e.g., Bamboo MCP, PanDA MCP) based on namespace prefixes, enabling unified access and tool catalog management.
browser-use-native-windows
A Windows-only MCP server for controlling a real browser using native screenshots, Windows accessibility, and node-interception mouse/keyboard input, without CDP or Playwright.
Saya
Enables agents to query team brain for memory, channels, decisions, skills, and readiness through a central remote MCP endpoint.
mcp-server-testWhat is MCP Server Test?How to use MCP Server Test?Key features of MCP Server Test?Use cases of MCP Server Test?FAQ from MCP Server Test?
测试 MCP 服务器 (Cèshì MCP fúwùqì)
SAP RFC MCP Server
An enterprise-grade MCP server that enables AI agents to execute SAP RFC functions and read business data securely through the Model Context Protocol.
kimi-computer-use
Bridges Kimi Code CLI to OpenAI Computer Use, enabling Kimi to control local macOS applications via MCP.
MCP YouTube-DLP
Provides tools for downloading YouTube videos and audio using yt-dlp, enabling integration with AI assistants via MCP.
mcp-arcgis-indianriver
Enables searching and querying Indian River County, Florida open geospatial datasets (parcels, addresses, zoning, public works) through natural language or direct tool calls.
MCP Scheduler
A robust task scheduler server built with Model Context Protocol for scheduling and managing various types of automated tasks including shell commands, API calls, AI tasks, and reminders.
Connexia MCP Server
Converts existing Express, Fastify, NestJS, Hono, or Koa backends into an MCP-compatible server accessible to AI clients like Claude Desktop and Cursor.
Mailbuttons MCP Server
Enables AI agents to send and receive email with enforced security policies, scoped mailboxes, and human approval for external sending.