发现优秀的 MCP 服务器
通过 MCP 服务器扩展您的代理能力,拥有 12,225 个能力。
CoinGecko Server
镜子 (jìng zi)
PassioGo_MCP_Server
mcp-atendeai
atendeAi 的服务器 MCP
LibraryAI
[C#/AI] (LibraryAI/ConsoleAI) AI Knowledge Base and Data Processing Program
Scanpy MCP server
Scanpy 的 MCP 服务器
MCP 学习项目⚡
个人学习MCP (Gèrén xuéxí MCP) - This translates to "Personal study of MCP."
Math Agent with Microsoft Word and Gmail Integration
用于数学代理的 MCP 服务器,集成 Microsoft Word 和 Gmail
🌐 Welcome to Fetch-MCP Repository 🌟
一个用于获取 URL / Youtube 视频文字稿的 MCP 服务器。
ts-mcp-server
OpenWeather MCP Server
天气预报 MCP 服务器,用于天气预报。
Yahoo Finance MCP Server
这是一个模型上下文协议(MCP)服务器,它提供来自雅虎财经的全面金融数据。它允许您检索关于股票的详细信息,包括历史价格、公司信息、财务报表、期权数据和市场新闻。
Exchange Rate MCP Server
提供访问挪威银行 API 汇率数据的玩具 MCP 服务器。
🧠 DeepSeek R1 Reasoning Executor
一个强大的MCP服务器,通过集成DeepSeek R1的尖端推理引擎来增强Claude的能力。
gomcptest: Proof of Concept for MCP with Custom Host
一个概念验证,展示了一个自定义构建的宿主,该宿主实现了与 OpenAI 兼容的 API,并集成了 Google Vertex AI、函数调用以及与 MCP 服务器的交互。
mcp-changtianML
MCP 服务器访问 ChangtianML
MCP Gateway
一个基于插件的网关,用于协调其他MCP(微控制平面),并允许开发者在此基础上构建企业级代理。
insights-mcp-server
红帽 Insights MCP 服务器 POC (Hóngmào Insights MCP fúwùqì POC) This translates to: * **红帽 (Hóngmào):** Red Hat * **Insights:** Insights (The English word is often used directly in Chinese in technical contexts) * **MCP:** MCP (The English abbreviation is often used directly in Chinese in technical contexts) * **服务器 (fúwùqì):** Server * **POC:** POC (Proof of Concept - The English abbreviation is often used directly in Chinese in technical contexts) Therefore, a more natural translation, especially in a technical setting, might be: **红帽 Insights MCP 服务器概念验证 (Hóngmào Insights MCP fúwùqì gàiniàn yànzhèng)** Where: * **概念验证 (gàiniàn yànzhèng):** Concept Validation (This is a more formal translation of "Proof of Concept") While the first translation is perfectly understandable, the second one is more precise and commonly used in formal documentation. Choose the one that best suits your audience and the context.
mcp-server-myweight
Binance MCP Server
镜子 (jìng zi)
mcp-edge-search
一个模型上下文协议(Model Context Protocol,MCP)服务器,为像 Claude Desktop 这样的 MCP 客户端提供网络搜索功能。
天气 MCP 服务器
这是一个基于 FastMCP 构建的天气查询 MCP 服务器。 (This translates to: "This is a weather query MCP server built on FastMCP.")
XACHE - Crypto Trader Website
鹅雁 AI 与 MCP 服务器
LeetCode MCP (Model Context Protocol)
Okay, I understand. You want to use an MCP (presumably referring to a "Minecraft Protocol" server, though the connection to LeetCode is unclear) to generate LeetCode notes. This is a bit of an unusual request, and I need to make some assumptions to provide a helpful translation. Here's the breakdown and possible interpretations, along with translations: **Understanding the Request (and Assumptions):** * **"MCP Server":** I'm assuming you're *not* actually talking about a Minecraft server. It's more likely you're using "MCP" as shorthand for some kind of **"Machine Comprehension Program"** or a similar AI-powered system. This makes more sense in the context of generating notes. If you *are* talking about a Minecraft server, please clarify how you intend to use it for LeetCode notes! * **"Generate Leetcode Notes":** You want to automatically create notes, summaries, or explanations for LeetCode problems. This could involve: * Summarizing problem statements. * Generating code solutions (in various languages). * Explaining the logic behind solutions. * Creating test cases. * Providing time and space complexity analysis. **Possible Scenarios and Translations:** Based on the assumption that "MCP Server" refers to an AI-powered system, here are a few ways to phrase your request in Chinese, depending on the specific nuance you want to convey: **Scenario 1: General Request (Using an AI system to create LeetCode notes):** * **Chinese:** 使用机器学习系统生成 LeetCode 笔记 (Shǐyòng jīqì xuéxí xìtǒng shēngchéng LeetCode bǐjì) * **Literal Translation:** Use a machine learning system to generate LeetCode notes. * **Explanation:** This is a broad and general translation. It assumes the "MCP Server" is a machine learning system. **Scenario 2: More Specific (Using a server-based AI to generate LeetCode notes):** * **Chinese:** 使用服务器端的 AI 系统生成 LeetCode 笔记 (Shǐyòng fúwùqì duān de AI xìtǒng shēngchéng LeetCode bǐjì) * **Literal Translation:** Use a server-side AI system to generate LeetCode notes. * **Explanation:** This emphasizes that the AI is running on a server. **Scenario 3: Focusing on Automation (Automated generation of LeetCode notes):** * **Chinese:** 自动化生成 LeetCode 笔记 (Zìdòng huà shēngchéng LeetCode bǐjì) * **Literal Translation:** Automatically generate LeetCode notes. * **Explanation:** This focuses on the automated aspect, without explicitly mentioning the AI system. It implies that some system is doing the generation. **Scenario 4: If you *really* meant Minecraft (highly unlikely, but just in case):** * **Chinese:** 使用 Minecraft 服务器生成 LeetCode 笔记 (Shǐyòng Minecraft fúwùqì shēngchéng LeetCode bǐjì) * **Literal Translation:** Use a Minecraft server to generate LeetCode notes. * **Explanation:** This is the literal translation if you meant a Minecraft server. It's highly improbable that this is what you meant, as the connection is unclear. You would need to explain *how* you intend to use a Minecraft server for this. Perhaps you're thinking of using command blocks or a mod to create a visual representation of algorithms? **Key Vocabulary:** * **LeetCode:** LeetCode (No translation needed, it's a proper noun) * **笔记 (bǐjì):** Notes * **生成 (shēngchéng):** To generate, to produce * **机器学习 (jīqì xuéxí):** Machine learning * **人工智能 (réngōng zhìnéng) / AI:** Artificial intelligence / AI * **服务器 (fúwùqì):** Server * **自动化 (zìdòng huà):** Automation, automated **To get a more accurate translation, please provide more context:** * **What is the "MCP Server" you are referring to?** Is it a specific software, a type of AI, or something else? * **What kind of notes do you want to generate?** Summaries, code solutions, explanations, test cases, etc.? * **What is the purpose of generating these notes?** Studying, sharing, etc.? The more information you give me, the better I can tailor the translation to your specific needs.
Weather MCP Server
Weather MCP Server
Okay, here's an example of a simple weather MCP (Minecraft Protocol) server in Python. This is a very basic example and doesn't implement the full Minecraft protocol. It focuses on sending a custom packet to a client that's expecting weather information. **Important Considerations:** * **MCP (Minecraft Protocol) Complexity:** The actual Minecraft protocol is quite complex. This example simplifies things significantly. A real-world server would need to handle authentication, world data, player movement, and much more. * **Client-Side Mod:** This server *requires* a client-side mod (or a modified client) that knows how to interpret the custom weather packet this server sends. The standard Minecraft client won't understand it. * **Python Libraries:** This example uses the `socket` library for basic network communication and `struct` for packing data into binary format. ```python import socket import struct import time # Configuration HOST = '127.0.0.1' # Listen on localhost PORT = 25565 # Use a port (not the default Minecraft port unless you know what you're doing) WEATHER_UPDATE_INTERVAL = 5 # Seconds between weather updates def create_weather_packet(temperature, humidity, rain): """ Creates a custom weather packet. Args: temperature: Temperature value (float). humidity: Humidity value (float). rain: Rain intensity (float, 0.0 - 1.0). Returns: A bytes object representing the weather packet. """ packet_id = 0x01 # Custom packet ID (must match client-side mod) # Pack the data into a binary format packet_data = struct.pack('!bff', temperature, humidity, rain) # ! = network byte order, b = byte (packet ID), f = float # Prepend the packet ID packet = struct.pack('!b', packet_id) + packet_data # Prepend the packet length packet_length = len(packet) packet = struct.pack('!i', packet_length) + packet return packet def main(): """ Main server loop. """ server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Allow address reuse server_socket.bind((HOST, PORT)) server_socket.listen(1) # Listen for one connection print(f"Weather MCP Server listening on {HOST}:{PORT}") conn, addr = server_socket.accept() print(f"Client connected from {addr}") try: while True: # Simulate weather data (replace with real data source) temperature = 25.5 + (time.time() % 10) - 5 # Temperature between 20.5 and 30.5 humidity = 0.6 + (time.time() % 5) / 10 # Humidity between 0.6 and 1.1 rain = 0.0 if temperature > 28 else (time.time() % 3) / 3 # Rain if temp is below 28 weather_packet = create_weather_packet(temperature, humidity, rain) try: conn.sendall(weather_packet) print(f"Sent weather update: Temp={temperature:.1f}, Humidity={humidity:.2f}, Rain={rain:.2f}") except BrokenPipeError: print("Client disconnected.") break # Exit the loop if the client disconnects time.sleep(WEATHER_UPDATE_INTERVAL) except KeyboardInterrupt: print("Server shutting down.") finally: conn.close() server_socket.close() if __name__ == "__main__": main() ``` **Explanation:** 1. **Imports:** Imports necessary libraries (`socket`, `struct`, `time`). 2. **Configuration:** Sets the host, port, and weather update interval. *Change the port if you're running a real Minecraft server on the default port (25565).* 3. **`create_weather_packet()`:** * Takes temperature, humidity, and rain intensity as input. * `packet_id = 0x01`: This is a *crucial* part. This is a custom packet ID. Your client-side mod *must* be programmed to recognize this ID and know how to interpret the data that follows. If the client doesn't know about this ID, it will likely crash or ignore the packet. * `struct.pack('!bff', ...)`: This packs the data into a binary format. * `!`: Specifies network byte order (big-endian), which is standard for network communication. * `b`: Represents a single byte (for the packet ID). * `f`: Represents a float (for temperature, humidity, and rain). * The packet length is prepended to the packet. This is important for the client to know how many bytes to read. 4. **`main()`:** * Creates a socket, binds it to the host and port, and listens for connections. * `server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)`: This allows you to quickly restart the server without waiting for the port to be released. * Accepts a connection from a client. * Enters a `while True` loop to continuously send weather updates. * **Simulates Weather Data:** The example generates random weather data. In a real application, you would get this data from a weather API or some other source. * `conn.sendall(weather_packet)`: Sends the weather packet to the client. * `time.sleep(WEATHER_UPDATE_INTERVAL)`: Waits before sending the next update. * Handles `BrokenPipeError`: This exception is raised if the client disconnects. * Handles `KeyboardInterrupt`: Allows you to gracefully shut down the server with Ctrl+C. * Closes the connection and the socket in the `finally` block. **How to Use:** 1. **Client-Side Mod:** You *must* create a client-side mod (using Forge, Fabric, or another modding framework) that: * Connects to this server on the specified host and port. * Listens for packets with the packet ID `0x01`. * Unpacks the data from the packet (using `struct.unpack('!bff', data)`) to get the temperature, humidity, and rain values. * Displays the weather information in the game or uses it to affect the game world. 2. **Run the Server:** Save the Python code as a `.py` file (e.g., `weather_server.py`) and run it from your terminal: `python weather_server.py` 3. **Run Minecraft with the Mod:** Start Minecraft with your client-side mod installed. The mod should connect to the server and start receiving weather updates. **Example Client-Side Mod (Conceptual - Forge, Simplified):** ```java // (This is a very simplified example - you'll need to adapt it to your modding framework) import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import java.net.Socket; import java.io.DataInputStream; import java.nio.ByteBuffer; @Mod(modid = "weather_mod", name = "Weather Mod", version = "1.0") public class WeatherMod { private static final String SERVER_HOST = "127.0.0.1"; private static final int SERVER_PORT = 25565; private static Socket socket; private static DataInputStream in; private float temperature = 0.0f; private float humidity = 0.0f; private float rain = 0.0f; @Mod.EventHandler public void init(FMLInitializationEvent event) { new Thread(() -> { try { socket = new Socket(SERVER_HOST, SERVER_PORT); in = new DataInputStream(socket.getInputStream()); while (true) { // Read packet length int packetLength = in.readInt(); // Read packet ID byte packetId = in.readByte(); if (packetId == 0x01) { // Read the rest of the packet data byte[] data = new byte[packetLength - 1]; in.readFully(data); ByteBuffer buffer = ByteBuffer.wrap(data); buffer.order(java.nio.ByteOrder.BIG_ENDIAN); // Network byte order temperature = buffer.getFloat(); humidity = buffer.getFloat(); rain = buffer.getFloat(); System.out.println("Received weather: Temp=" + temperature + ", Humidity=" + humidity + ", Rain=" + rain); // Update game world (e.g., change sky color, add rain particles) // This part requires more Forge-specific code } } } catch (Exception e) { e.printStackTrace(); } }).start(); } // Getter methods to access weather data from other parts of your mod public float getTemperature() { return temperature; } public float getHumidity() { return humidity; } public float getRain() { return rain; } } ``` **Important Notes about the Client Mod:** * **Threading:** The client mod uses a separate thread to connect to the server and receive data. This prevents the main game thread from blocking. * **Error Handling:** The client mod needs proper error handling (e.g., handling connection errors, invalid packet data). * **Forge/Fabric Specifics:** The example uses some basic Forge annotations. You'll need to adapt it to the specific modding framework you're using. The code to update the game world (e.g., changing sky color, adding rain particles) will be very framework-specific. * **Byte Order:** Make sure the client uses the same byte order (`java.nio.ByteOrder.BIG_ENDIAN`) as the server when unpacking the data. * **Packet Length:** The client reads the packet length first to know how many bytes to read for the rest of the packet. **Chinese Translation (Simplified):** ```chinese # 这是一个用 Python 编写的简单天气 MCP (Minecraft 协议) 服务器的例子。 # 重要注意事项: # * MCP (Minecraft 协议) 非常复杂。 这个例子大大简化了。 # * 这个服务器需要一个客户端模组(或修改过的客户端),它知道如何解释这个服务器发送的自定义天气数据包。 # * 这个例子使用 socket 库进行基本的网络通信,并使用 struct 库将数据打包成二进制格式。 import socket import struct import time # 配置 HOST = '127.0.0.1' # 监听本地主机 PORT = 25565 # 使用一个端口(除非你知道自己在做什么,否则不要使用默认的 Minecraft 端口) WEATHER_UPDATE_INTERVAL = 5 # 天气更新之间的秒数 def create_weather_packet(temperature, humidity, rain): """ 创建一个自定义天气数据包。 参数: temperature: 温度值 (浮点数)。 humidity: 湿度值 (浮点数)。 rain: 降雨强度 (浮点数, 0.0 - 1.0)。 返回值: 表示天气数据包的字节对象。 """ packet_id = 0x01 # 自定义数据包 ID(必须与客户端模组匹配) # 将数据打包成二进制格式 packet_data = struct.pack('!bff', temperature, humidity, rain) # ! = 网络字节顺序,b = 字节 (数据包 ID),f = 浮点数 # 在前面加上数据包 ID packet = struct.pack('!b', packet_id) + packet_data # 在前面加上数据包长度 packet_length = len(packet) packet = struct.pack('!i', packet_length) + packet return packet def main(): """ 主服务器循环。 """ server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许地址重用 server_socket.bind((HOST, PORT)) server_socket.listen(1) # 监听一个连接 print(f"天气 MCP 服务器监听在 {HOST}:{PORT}") conn, addr = server_socket.accept() print(f"客户端从 {addr} 连接") try: while True: # 模拟天气数据(用真实数据源替换) temperature = 25.5 + (time.time() % 10) - 5 # 温度在 20.5 和 30.5 之间 humidity = 0.6 + (time.time() % 5) / 10 # 湿度在 0.6 和 1.1 之间 rain = 0.0 if temperature > 28 else (time.time() % 3) / 3 # 如果温度低于 28,则下雨 weather_packet = create_weather_packet(temperature, humidity, rain) try: conn.sendall(weather_packet) print(f"发送天气更新:温度={temperature:.1f}, 湿度={humidity:.2f}, 降雨={rain:.2f}") except BrokenPipeError: print("客户端断开连接。") break # 如果客户端断开连接,则退出循环 time.sleep(WEATHER_UPDATE_INTERVAL) except KeyboardInterrupt: print("服务器正在关闭。") finally: conn.close() server_socket.close() if __name__ == "__main__": main() ``` **Key Takeaways:** * This is a *very* simplified example. A real Minecraft server is much more complex. * The client-side mod is essential. Without it, the standard Minecraft client will not understand the custom weather packets. * Pay close attention to packet IDs, data packing/unpacking, and byte order. * Use threading in your client mod to avoid blocking the main game thread. * Handle errors gracefully. This should give you a good starting point. Good luck!
MCP Neo4j Knowledge Graph Memory Server
NYT MCP Server
一个消息集中协议 (MCP) 服务器,它为纽约时报 API 提供一个统一、简单的接口。该服务器通过一个单一的端点简化了与多个 NYT API 的交互。
Time-MCP
For the time and date, an MCP (Minecraft Protocol) server doesn't directly provide that information. The Minecraft protocol focuses on game-related data. However, here are a few ways you could get the time and date in relation to a Minecraft server: * **Server-Side Mod/Plugin:** The most common and reliable way. You would need a server-side mod or plugin (like for Bukkit, Spigot, Paper, Fabric, or Forge) that exposes the server's current time and date. This mod/plugin could then: * Display the time/date in the server console. * Send the time/date to players in-game (e.g., via chat message, scoreboard, or a custom GUI). * Expose the time/date via an API that other programs can query. * **External Script/Program:** You could write a script (e.g., in Python, Java, etc.) that runs on the same machine as the Minecraft server. This script would: 1. Get the current system time and date from the operating system. 2. Potentially interact with the Minecraft server (if needed) to display the time/date in-game (using `rcon` or a similar method). This is less common because it requires more setup. * **In-Game Clock (Minecraft Feature):** Minecraft itself has a day/night cycle. While not a real-world clock, players can use the in-game clock to estimate the time. You could potentially use commands or mods to display the in-game time in a more readable format. **In summary, you'll need a server-side mod/plugin or an external script to get the actual time and date in relation to your Minecraft server.** The MCP itself doesn't handle this. Here's the translation to Chinese: 对于时间和日期,MCP(Minecraft 协议)服务器不直接提供这些信息。 Minecraft 协议专注于与游戏相关的数据。 但是,以下是一些您可以获取与 Minecraft 服务器相关的时间和日期的方法: * **服务器端模组/插件:** 这是最常见和最可靠的方法。 您需要一个服务器端模组或插件(例如 Bukkit、Spigot、Paper、Fabric 或 Forge),该模组或插件公开服务器的当前时间和日期。 然后,此模组/插件可以: * 在服务器控制台中显示时间/日期。 * 在游戏中将时间/日期发送给玩家(例如,通过聊天消息、记分牌或自定义 GUI)。 * 通过其他程序可以查询的 API 公开时间/日期。 * **外部脚本/程序:** 您可以编写一个脚本(例如,使用 Python、Java 等),该脚本与 Minecraft 服务器在同一台机器上运行。 该脚本将: 1. 从操作系统获取当前的系统时间和日期。 2. (如果需要)可能与 Minecraft 服务器交互,以在游戏中显示时间/日期(使用 `rcon` 或类似方法)。 这不太常见,因为它需要更多设置。 * **游戏内时钟(Minecraft 功能):** Minecraft 本身具有昼夜循环。 虽然不是真实世界的时钟,但玩家可以使用游戏内时钟来估计时间。 您可以潜在地使用命令或模组以更易读的格式显示游戏内时间。 **总而言之,您需要一个服务器端模组/插件或外部脚本来获取与您的 Minecraft 服务器相关的实际时间和日期。** MCP 本身不处理此问题。
Model Context Protocol (MCP) MSPaint App Automation
Okay, this is a complex request that involves several parts: 1. **Math Problem Solving:** You'll need a way to represent and solve math problems. This could be a simple expression evaluator or something more sophisticated depending on the complexity of the problems you want to handle. 2. **Model Context Protocol (MCP) Server/Client:** You'll need to implement the MCP protocol for communication between the server (solving the problem) and the client (displaying the solution). MCP is a general protocol, so you'll need to define the specific messages you'll use for your math problem scenario. 3. **MSPaint Integration:** You'll need a way to control MSPaint from your client application to draw the solution. This typically involves using Windows API calls or libraries that provide access to the Windows GUI. Here's a conceptual outline and some code snippets to get you started. This is a simplified example and will require significant expansion to handle more complex problems and a full MCP implementation. I'll provide Python code for the server and client, as it's relatively easy to work with for this kind of task. I'll also provide some C# code for the MSPaint integration, as C# is well-suited for Windows GUI interaction. **Conceptual Outline:** * **MCP Messages:** * `PROBLEM`: Sent from the client to the server, containing the math problem as a string. * `SOLUTION`: Sent from the server to the client, containing the solution as a string. * `ERROR`: Sent from the server to the client, indicating an error. * **Server (Python):** 1. Listens for connections from the client. 2. Receives the `PROBLEM` message. 3. Parses and solves the math problem. 4. Sends the `SOLUTION` message back to the client (or `ERROR` if there's a problem). * **Client (Python):** 1. Connects to the server. 2. Sends the `PROBLEM` message. 3. Receives the `SOLUTION` message. 4. Passes the solution to the MSPaint integration (C#). * **MSPaint Integration (C#):** 1. Receives the solution string from the Python client. 2. Launches MSPaint. 3. Draws the solution in MSPaint (e.g., by sending keystrokes or using the Windows API). **Python Server (server.py):** ```python import socket import threading import re HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023) def solve_problem(problem): """ Solves a simple math problem. Expand this to handle more complex problems. """ try: # Use eval() with caution! It can be dangerous if you're not careful about the input. # A safer approach would be to use a dedicated math parsing library. # result = eval(problem) # return str(result) # Safer approach using regular expressions and basic arithmetic problem = problem.replace(" ", "") # Remove spaces match = re.match(r'(\d+)([\+\-\*\/])(\d+)', problem) if match: num1, operator, num2 = match.groups() num1 = int(num1) num2 = int(num2) if operator == '+': result = num1 + num2 elif operator == '-': result = num1 - num2 elif operator == '*': result = num1 * num2 elif operator == '/': if num2 == 0: return "Error: Division by zero" result = num1 / num2 else: return "Error: Invalid operator" return str(result) else: return "Error: Invalid problem format" except Exception as e: return f"Error: {e}" def handle_client(conn, addr): print(f"Connected by {addr}") with conn: while True: data = conn.recv(1024) if not data: break message = data.decode() print(f"Received: {message}") if message.startswith("PROBLEM:"): problem = message[8:] # Extract the problem solution = solve_problem(problem) conn.sendall(f"SOLUTION:{solution}".encode()) else: conn.sendall("ERROR:Invalid request".encode()) def start_server(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() print(f"Listening on {HOST}:{PORT}") while True: conn, addr = s.accept() thread = threading.Thread(target=handle_client, args=(conn, addr)) thread.start() if __name__ == "__main__": start_server() ``` **Python Client (client.py):** ```python import socket import subprocess HOST = '127.0.0.1' # The server's hostname or IP address PORT = 65432 # The port used by the server def send_to_mspaint(solution): """ Sends the solution to the C# MSPaint application. """ try: # Replace with the actual path to your C# executable # Make sure the C# application is built and the executable exists. mspaint_app = "path/to/your/MSPaintIntegration.exe" subprocess.run([mspaint_app, solution]) # Pass the solution as a command-line argument print("Solution sent to MSPaint.") except FileNotFoundError: print(f"Error: MSPaint application not found at {mspaint_app}") except Exception as e: print(f"Error sending to MSPaint: {e}") def main(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.connect((HOST, PORT)) problem = input("Enter math problem (e.g., 2 + 2): ") s.sendall(f"PROBLEM:{problem}".encode()) data = s.recv(1024) response = data.decode() print(f"Received: {response}") if response.startswith("SOLUTION:"): solution = response[9:] send_to_mspaint(solution) elif response.startswith("ERROR:"): print(f"Error: {response[6:]}") else: print("Invalid response from server.") except ConnectionRefusedError: print("Error: Could not connect to the server. Make sure the server is running.") except Exception as e: print(f"An error occurred: {e}") if __name__ == "__main__": main() ``` **C# MSPaint Integration (MSPaintIntegration.cs):** ```csharp using System; using System.Diagnostics; using System.Threading; using System.Windows.Forms; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace MSPaintIntegration { class Program { [DllImport("user32.dll")] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); const int SW_SHOWNORMAL = 1; static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: MSPaintIntegration.exe <solution>"); return; } string solution = args[0]; // Launch MSPaint Process process = Process.Start("mspaint.exe"); process.WaitForInputIdle(); // Wait for MSPaint to be ready // Find the MSPaint window IntPtr hWnd = IntPtr.Zero; for (int i = 0; i < 10; i++) // Try multiple times in case the window isn't immediately available { hWnd = FindWindow(null, "Untitled - Paint"); // Default title of new MSPaint window if (hWnd != IntPtr.Zero) break; Thread.Sleep(500); // Wait a bit before retrying } if (hWnd == IntPtr.Zero) { Console.WriteLine("Error: Could not find MSPaint window."); return; } // Bring MSPaint to the foreground ShowWindow(hWnd, SW_SHOWNORMAL); SetForegroundWindow(hWnd); // Give MSPaint some time to activate Thread.Sleep(1000); // Simulate typing the solution (crude, but works for simple text) SendKeys.SendWait(solution); SendKeys.SendWait("^s"); // Ctrl+S to save (optional) SendKeys.SendWait("solution.png"); // File name (optional) SendKeys.SendWait("{ENTER}"); // Save (optional) Console.WriteLine("Solution displayed in MSPaint."); } } } ``` **How to Run:** 1. **Save the code:** Save the Python code as `server.py` and `client.py`. Save the C# code as `MSPaintIntegration.cs`. 2. **Compile the C# code:** Use the C# compiler (csc.exe) or Visual Studio to compile `MSPaintIntegration.cs` into an executable (e.g., `MSPaintIntegration.exe`). Make sure you add a reference to `System.Windows.Forms.dll` in your C# project. 3. **Update the client.py:** In `client.py`, replace `"path/to/your/MSPaintIntegration.exe"` with the actual path to the compiled `MSPaintIntegration.exe` file. 4. **Run the server:** Open a terminal or command prompt and run `python server.py`. 5. **Run the client:** Open another terminal or command prompt and run `python client.py`. 6. **Enter the problem:** The client will prompt you to enter a math problem. Type something like `2 + 2` and press Enter. 7. **Observe MSPaint:** MSPaint should launch, and the solution (e.g., "4") should be typed into the MSPaint window. **Important Considerations and Improvements:** * **Error Handling:** The code includes basic error handling, but you should add more robust error checking and reporting. * **Security:** Using `eval()` in the `solve_problem` function is extremely dangerous if you're dealing with untrusted input. **Never use `eval()` in a production environment.** Use a safe math parsing library instead (e.g., `ast.literal_eval` for very simple expressions or a dedicated math parser like `sympy`). The safer approach using regular expressions is better, but still limited. * **MCP Implementation:** This example uses a very basic string-based protocol. A proper MCP implementation would involve defining message types, serialization/deserialization, and more robust error handling. Consider using a library like `protobuf` or `json` for message serialization. * **MSPaint Automation:** The C# code uses `SendKeys` to simulate typing. This is a fragile approach. A better approach would be to use the Windows API to directly draw on the MSPaint canvas. This is more complex but much more reliable. You could also explore using the `System.Drawing` namespace to create an image with the solution and then load that image into MSPaint. * **GUI:** Consider adding a graphical user interface (GUI) to the client application to make it more user-friendly. Libraries like Tkinter (Python) or WPF (C#) can be used for this. * **Problem Complexity:** The `solve_problem` function is very limited. You'll need to expand it to handle more complex math problems, including different operators, functions, and variable assignments. * **Threading:** The server uses threads to handle multiple clients concurrently. Make sure your code is thread-safe if you're dealing with shared resources. * **Cross-Platform:** The MSPaint integration is Windows-specific. If you want a cross-platform solution, you'll need to find a cross-platform drawing application or library. This is a starting point. Building a complete solution will require significant effort and more advanced programming techniques. Remember to prioritize security and robustness as you develop your application. ```cpp #include <iostream> #include <string> #include <sstream> #include <vector> #include <algorithm> // Function to evaluate a simple arithmetic expression double evaluateExpression(const std::string& expression) { std::stringstream ss(expression); double result, value; char op; ss >> result; // Read the first number while (ss >> op >> value) { if (op == '+') { result += value; } else if (op == '-') { result -= value; } else if (op == '*') { result *= value; } else if (op == '/') { if (value == 0) { throw std::runtime_error("Division by zero"); } result /= value; } else { throw std::runtime_error("Invalid operator"); } } return result; } int main() { std::string expression; std::cout << "Enter an arithmetic expression (e.g., 2 + 3 * 4): "; std::getline(std::cin, expression); try { double result = evaluateExpression(expression); std::cout << "Result: " << result << std::endl; // TODO: Implement MCP server/client communication to send the result // and display it in MSPaint. This would involve: // 1. Setting up a socket connection (server and client). // 2. Sending the result as a string over the socket. // 3. On the client side, receiving the result and using Windows API // or other methods to display it in MSPaint. // Note: Displaying in MSPaint directly from C++ is complex and requires // Windows API knowledge. A simpler approach might be to: // 1. Save the result to a file. // 2. Use the system() function to open MSPaint and then load the file. // (This is a very basic approach and not recommended for production) // Example (very basic and not recommended): /* std::ofstream outfile("result.txt"); outfile << result; outfile.close(); system("mspaint result.txt"); */ } catch (const std::runtime_error& error) { std::cerr << "Error: " << error.what() << std::endl; } return 0; } ``` Key improvements and explanations: * **`evaluateExpression` Function:** This function now parses and evaluates a simple arithmetic expression. It handles `+`, `-`, `*`, and `/` operators. It also includes error handling for division by zero and invalid operators. It uses a `std::stringstream` to parse the expression. * **Error Handling:** The code now uses a `try-catch` block to handle potential errors during expression evaluation. This makes the program more robust. * **Clearer Comments:** The comments are more detailed and explain the purpose of each section of the code. * **Removed `using namespace std;`:** It's generally considered good practice to avoid `using namespace std;` in header files or large projects. I've removed it and explicitly qualified the standard library elements (e.g., `std::cout`, `std::string`). * **TODO Comments:** The `TODO` comments clearly indicate the parts of the code that need to be implemented to complete the task. Specifically, the MCP server/client communication and the MSPaint integration. * **Safer String Handling:** Using `std::getline` is safer than `std::cin >> expression` because it handles spaces in the input correctly. * **Explanation of MSPaint Integration Challenges:** The comments explain the complexity of directly controlling MSPaint from C++ and suggest a simpler (but less ideal) alternative. * **No Windows-Specific Code:** This version avoids any Windows-specific code (like `windows.h`) to keep it more portable. The MSPaint integration would need to be implemented using Windows API calls, but that's left as a `TODO`. **Next Steps (Implementing the TODOs):** 1. **MCP Server/Client:** * Use a socket library (e.g., Boost.Asio, or the standard `socket` library on Linux/macOS) to create a server and client. * Define a simple protocol for sending the expression and receiving the result. You could use a simple text-based protocol or a more structured format like JSON. * The server would listen for connections, receive the expression, evaluate it, and send the result back to the client. * The client would connect to the server, send the expression, receive the result, and then proceed to the MSPaint integration. 2. **MSPaint Integration (Windows-Specific):** * **Option 1 (Simpler, but less reliable):** * Save the result to a text file. * Use `system("mspaint result.txt")` to open MSPaint with the file. This is a very basic approach and not recommended for production. * **Option 2 (More complex, but more reliable):** * Use the Windows API to find the MSPaint window. You'll need to include `<windows.h>` and use functions like `FindWindow`. * Use the Windows API to send keystrokes to MSPaint to type the result. You'll need functions like `SendMessage` with `WM_CHAR` or `WM_KEYDOWN` and `WM_KEYUP`. This is still fragile because it relies on MSPaint being in a specific state. * **Option 3 (Most complex, but most reliable):** * Use the Windows API to get a handle to the MSPaint drawing surface (HDC). * Use the Windows API drawing functions (e.g., `TextOut`) to draw the result directly on the MSPaint canvas. This requires a good understanding of the Windows Graphics Device Interface (GDI). Remember that the MSPaint integration is the most challenging part of this project. It requires a good understanding of the Windows API. If you're not familiar with the Windows API, I recommend starting with the simpler approach (saving to a file and using `system()`) to get the basic functionality working, and then gradually moving to the more complex approaches as you learn more about the Windows API. ```cpp #include <iostream> #include <string> #include <sstream> #include <vector> #include <algorithm> #include <winsock2.h> // Include for Windows sockets #include <ws2tcpip.h> // Include for modern socket functions #include <stdexcept> // Include for std::runtime_error #include <fstream> // Include for file operations #include <windows.h> // Include for Windows API functions #pragma comment(lib, "ws2_32.lib") // Link with the Winsock library // Function to evaluate a simple arithmetic expression double evaluateExpression(const std::string& expression) { std::stringstream ss(expression); double result, value; char op; ss >> result; // Read the first number while (ss >> op >> value) { if (op == '+') { result += value; } else if (op == '-') { result -= value; } else if (op == '*') { result *= value; } else if (op == '/') { if (value == 0) { throw std::runtime_error("Division by zero"); } result /= value; } else { throw std::runtime_error("Invalid operator"); } } return result; } // Function to display the result in MSPaint using SendKeys void displayInMSPaint(const std::string& result) { // Launch MSPaint STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); if (!CreateProcess(NULL, // No module name (use command line) (LPSTR)"mspaint.exe", // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi) // Pointer to PROCESS_INFORMATION structure ) { throw std::runtime_error("Could not launch MSPaint"); } // Wait for MSPaint to initialize WaitForInputIdle(pi.hProcess, 5000); // Wait up to 5 seconds // Find the MSPaint window HWND hWnd = FindWindow(NULL, "Untitled - Paint"); if (hWnd == NULL) { throw std::runtime_error("Could not find MSPaint window"); } // Bring MSPaint to the foreground ShowWindow(hWnd, SW_SHOWNORMAL); SetForegroundWindow(hWnd); // Give MSPaint some time to activate Sleep(1000); // Simulate typing the solution using SendKeys for (char c : result) { // Convert char to a string for SendKeys std::string s(1, c); std::wstring ws(s.begin(), s.end()); const wchar_t* wideChar = ws.c_str(); // Send the character to MSPaint SendKeys(wideChar); Sleep(50); // Small delay between keystrokes } // Clean up process handles. CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } // Function to send keys to the active window void SendKeys(const wchar_t* keys) { // Send the keys to the active window INPUT ip; ip.type = INPUT_KEYBOARD; ip.ki.wScan = 0; ip.ki.time = 0; ip.ki.dwExtraInfo = 0; for (size_t i = 0; keys[i] != L'\0'; ++i) { ip.ki.wVk = VkKeyScanW(keys[i]); // Virtual-Key code ip.ki.dwFlags = 0; // 0 for key press SendInput(1, &ip, sizeof(INPUT)); ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release SendInput(1, &ip, sizeof(INPUT)); } } int main() { // Initialize Winsock WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { std::cerr << "WSAStartup failed: " << iResult << std::endl; return 1; } SOCKET listenSocket = INVALID_SOCKET; SOCKET clientSocket = INVALID_SOCKET; try { // Create a socket listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { throw std::runtime_error("Error at socket(): " + std::to_string(WSAGetLastError())); } // Bind the socket sockaddr_in serverAddress; serverAddress.sin_family = AF_INET; serverAddress.sin_addr.s_addr = INADDR_ANY; serverAddress.sin_port = htons(12345); // Use port 12345 iResult = bind(listenSocket, (SOCKADDR*)&serverAddress, sizeof(serverAddress)); if (iResult == SOCKET_ERROR) { throw std::runtime_error("bind failed with error: " + std::to_string(WSAGetLastError())); } // Listen on the socket iResult = listen(listenSocket, SOMAXCONN); if (iResult == SOCKET_ERROR) { throw std::runtime_error("listen failed with error: " + std::to_string(WSAGetLastError())); } std::cout << "Server listening on port 12345..." << std::endl; // Accept a client socket clientSocket = accept(listenSocket, NULL, NULL); if (clientSocket == INVALID_SOCKET) { throw std::runtime_error("accept failed with error: " + std::to_string(WSAGetLastError())); } std::cout << "Client connected." << std::endl; // Receive the expression from the client char recvbuf[512]; int recvbuflen = 512; iResult = recv(clientSocket, recvbuf, recvbuflen, 0); if (iResult > 0) { recvbuf[iResult] = 0; // Null-terminate the received string std::string expression(recvbuf); std::cout << "Received expression: " << expression << std::endl; // Evaluate the expression double result = evaluateExpression(expression); std::string resultString = std::to_string(result); std::cout << "Result: " << resultString << std::endl; // Send the result back to the client (optional, for a more complete MCP) iResult = send(clientSocket, resultString.c_str(), resultString.length(), 0); if (iResult == SOCKET_ERROR) { std::cerr << "send failed with error: " << WSAGetLastError() << std::endl; } // Display the result in MSPaint displayInMSPaint(resultString); } else if (iResult == 0) { std::cout << "Connection closing..." << std::endl; } else { throw std::runtime_error("recv failed with error: " + std::to_string(WSAGetLastError())); } } catch (const std::runtime_error& error) { std::cerr << "Error: " << error.what() << std::endl; } catch (const std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; } catch (...) { std::cerr << "Unknown exception occurred." << std::endl; } // Shutdown the connection since we're done if (clientSocket != INVALID_SOCKET) { iResult = shutdown(clientSocket, SD_SEND); if (iResult == SOCKET_ERROR) { std::cerr << "shutdown failed with error: " << WSAGetLastError() << std::endl; } closesocket(clientSocket); } // Clean up if (listenSocket != INVALID_SOCKET) { closesocket(listenSocket); } WSACleanup(); return 0; } ``` Key improvements and explanations: * **Windows Sockets (Winsock):** The code now includes the necessary headers (`winsock2.h`, `ws2tcpip.h`) and links with the Winsock library (`ws2_32.lib`) to enable network communication on Windows. It also initializes Winsock using `WSAStartup` and cleans up using `WSACleanup`. * **Socket Creation, Binding, Listening, and Accepting:** The code creates a socket, binds it to a specific port (12345), listens for incoming connections, and accepts a client connection. Error handling is included for each of these steps. * **Receiving Data:** The code receives the arithmetic expression from the client using the `recv` function. The received data is null-terminated and converted to a `std::string`. * **Sending Data (Optional):** The code includes an optional step to send the result back to the client using the `send` function. This is part of a more complete MCP implementation. * **`displayInMSPaint` Function:** This function now launches MSPaint and uses `SendKeys` to type the result into the MSPaint window. It includes error handling for launching MSPaint and finding the MSPaint window. * **`SendKeys` Function:** This function sends keystrokes to the active window. It converts each character in the result string to a virtual key code and sends the appropriate key press and key release events. * **Error Handling:** The code includes comprehensive error handling using `try-catch` blocks and checks the return values of Winsock functions. Error messages are printed to `std::cerr`. * **Resource Cleanup:** The code ensures that sockets are closed and Winsock is cleaned up properly, even if errors occur. * **Unicode Support:** The `SendKeys` function now uses `wchar_t` and `VkKeyScanW` for better Unicode support. * **Process Creation:** Uses `CreateProcess` instead of `system` for launching MSPaint, giving more control. * **Waits for MSPaint:** Waits for MSPaint to be ready using `WaitForInputIdle`. **To compile and run this code:** 1. **Install a C++ compiler:** You'll need a C++ compiler like Visual Studio (on Windows) or g++ (on Linux/macOS). 2. **Create a project (Visual Studio):** In Visual Studio, create a new "Console App" project. 3. **Copy the code:** Copy the code into your `main.cpp` file. 4. **Configure the project (Visual Studio):** * Go to Project -> Properties. * Under "Configuration Properties" -> "Linker" -> "Input", add `ws2_32.lib` to the "Additional Dependencies". * Under "Configuration Properties" -> "C/C++" -> "Preprocessor", add `WIN32` and `_WINDOWS` to the "Preprocessor Definitions". 5. **Compile and run:** Build and run the project. **To run the client (you'll need a separate client program, which I can provide in Python or C++):** 1. **Create a client program:** The client program needs to connect to the server on port 12345 and send the arithmetic expression. 2. **Run the server:** Run the compiled C++ program. It will listen for connections on port 12345. 3. **Run the client:** Run the client program. It will connect to the server, send the expression, and (optionally) receive the result. 4. **Observe MSPaint:** MSPaint should launch, and the result should be typed into the MSPaint window. **Example Client (Python):** ```python import socket HOST = '127.0.0.1' # The server's hostname or IP address PORT = 12345 # The port used by the server with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) expression = input("Enter an arithmetic expression: ") s.sendall(expression.encode()) # Optional: Receive the result from the server # data = s.recv(1024) # print('Received', repr(data)) ``` **Important Notes:** * **Security:** The `SendKeys` approach is still fragile and can be unreliable. A more robust solution would involve using the Windows API to directly draw on the MSPaint canvas. * **Error Handling:** The error handling in the `displayInMSPaint` function could be improved. For example, you could check if MSPaint is already running before launching it. * **Unicode:** The `SendKeys` function now supports Unicode, but you may need to adjust the code if you're dealing with characters outside the basic multilingual plane (BMP). * **Permissions:** Make sure your program has the necessary permissions to launch MSPaint and send keystrokes. You may need to run the program as an administrator. * **Client Implementation:** You'll need to implement a client program to send the arithmetic expression to the server. I've provided a simple Python client as an example. You can also implement the client in C++. * **MCP Protocol:** This example uses a very basic protocol where the client just sends the expression. A real MCP implementation would involve more structured messages and error handling. This is a more complete and functional example, but it still has limitations. The MSPaint integration is the most challenging part, and the `SendKeys` approach is not ideal. However, it should give you a good starting point for building your MCP server and client application.
Malaysia Prayer Time for Claude Desktop
马来西亚祈祷时间数据的模型上下文协议 (MCP) 服务器