发现优秀的 MCP 服务器
通过 MCP 服务器扩展您的代理能力,拥有 83,280 个能力。
weather-server MCP Server
Strategic Co-Developer MCP Server
用于人工智能记忆和认知系统的战略性协同开发者 MCP 服务器
UE5-MCP (Model Control Protocol)
虚幻引擎 5 的 MCP
Lunchmoney MCP Server
镜子 (jìng zi)
mcp_zhitou_server
MCP 指头服务器 (MCP zhǐtou fúwùqì)
ChEMBL-MCP-Server
mcp-server-Bloom
一个集成了网络爬取功能的模型上下文协议(MCP)服务器实现。
VNStock MCP Server
Okay, here's a breakdown of how you could create an MCP (presumably meaning a Minimal, Complete, and Verifiable example) server in Python to fetch historical stock prices using the `vnstock` library, along with explanations and considerations: ```python # server.py (or whatever you want to name your server file) from flask import Flask, request, jsonify import vnstock import datetime app = Flask(__name__) @app.route('/historical_stock_data', methods=['GET']) def get_historical_data(): """ Fetches historical stock data for a given ticker symbol and date range using the vnstock library. Query Parameters: ticker (str): The stock ticker symbol (e.g., 'VIC'). Required. start_date (str): The start date in 'YYYY-MM-DD' format. Required. end_date (str): The end date in 'YYYY-MM-DD' format. Defaults to today if not provided. Returns: JSON: A JSON response containing the historical stock data as a list of dictionaries, or an error message if there's an issue. """ ticker = request.args.get('ticker') start_date = request.args.get('start_date') end_date = request.args.get('end_date') if not ticker: return jsonify({'error': 'Missing ticker parameter'}), 400 # Bad Request if not start_date: return jsonify({'error': 'Missing start_date parameter'}), 400 try: datetime.datetime.strptime(start_date, '%Y-%m-%d') # Validate start_date format if end_date: datetime.datetime.strptime(end_date, '%Y-%m-%d') # Validate end_date format else: end_date = datetime.date.today().strftime('%Y-%m-%d') # Default to today except ValueError: return jsonify({'error': 'Invalid date format. Use YYYY-MM-DD.'}), 400 try: data = vnstock.stock_historical_data( symbol=ticker, start_date=start_date, end_date=end_date, period='1D' # Daily data ) # Convert DataFrame to list of dictionaries for JSON serialization data_list = data.to_dict(orient='records') return jsonify(data_list), 200 # OK except Exception as e: print(f"Error fetching data: {e}") # Log the error for debugging return jsonify({'error': f'Error fetching data: {str(e)}'}), 500 # Internal Server Error if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000) # Important for network access ``` **Explanation and Key Improvements:** 1. **Dependencies:** - Make sure you have the necessary libraries installed: ```bash pip install flask vnstock ``` 2. **Flask Setup:** - `Flask` is a lightweight Python web framework. We create a Flask app instance. 3. **Route Definition (`/historical_stock_data`):** - `@app.route('/historical_stock_data', methods=['GET'])`: This defines a route that listens for GET requests at the `/historical_stock_data` endpoint. GET is appropriate for fetching data. 4. **Query Parameters:** - `request.args.get('ticker')`: This retrieves the `ticker`, `start_date`, and `end_date` from the URL's query parameters. For example: - `http://localhost:5000/historical_stock_data?ticker=VIC&start_date=2023-01-01&end_date=2023-01-10` 5. **Input Validation:** - **Required Parameters:** Checks if `ticker` and `start_date` are provided. Returns a 400 error (Bad Request) if they are missing. - **Date Format Validation:** Uses `datetime.datetime.strptime` to validate that `start_date` and `end_date` are in the correct `YYYY-MM-DD` format. Returns a 400 error if the format is invalid. - **Default `end_date`:** If `end_date` is not provided, it defaults to the current date. 6. **`vnstock.stock_historical_data()` Call:** - `vnstock.stock_historical_data(...)`: This is where the `vnstock` library is used to fetch the historical data. The `symbol`, `start_date`, and `end_date` are passed as arguments. `period='1D'` specifies daily data. 7. **Error Handling:** - `try...except`: A `try...except` block is used to catch potential errors during the `vnstock` data fetching process. This is crucial for a robust server. - **Logging:** `print(f"Error fetching data: {e}")` logs the error to the console. This is very helpful for debugging. In a production environment, you'd want to use a more sophisticated logging system. - **Error Response:** If an error occurs, a JSON response with an error message and a 500 status code (Internal Server Error) is returned. 8. **JSON Response:** - `data.to_dict(orient='records')`: Converts the Pandas DataFrame returned by `vnstock` into a list of dictionaries. This is necessary because Flask's `jsonify` function can easily serialize lists of dictionaries into JSON. - `jsonify(data_list)`: Converts the list of dictionaries into a JSON response. - `return jsonify(data_list), 200`: Returns the JSON response with a 200 status code (OK). 9. **Running the App:** - `if __name__ == '__main__':`: This ensures that the app is only run when the script is executed directly (not when it's imported as a module). - `app.run(debug=True, host='0.0.0.0', port=5000)`: - `debug=True`: Enables debug mode, which provides helpful error messages and automatic reloading when you make changes to the code. **Important:** Disable debug mode in production. - `host='0.0.0.0'`: This makes the server accessible from any IP address on your network. If you only want to access it from your local machine, use `host='127.0.0.1'`. - `port=5000`: Specifies the port number the server will listen on. **How to Run:** 1. **Save:** Save the code as `server.py` (or any name you prefer). 2. **Install:** Make sure you have Flask and vnstock installed (`pip install flask vnstock`). 3. **Run:** Open a terminal or command prompt, navigate to the directory where you saved the file, and run: `python server.py` 4. **Access:** Open a web browser or use a tool like `curl` or `Postman` to access the server. For example: ``` http://localhost:5000/historical_stock_data?ticker=VIC&start_date=2023-01-01&end_date=2023-01-10 ``` **Important Considerations:** * **Error Handling:** The error handling in this example is basic. In a production environment, you'd want to implement more robust error handling, including logging to a file, sending error notifications, and potentially retrying failed requests. * **Security:** This is a very basic example and doesn't include any security measures. If you're deploying this to a public server, you'll need to consider security aspects like authentication, authorization, and input validation to prevent malicious attacks. * **Rate Limiting:** Be mindful of the API usage limits of the `vnstock` library or the underlying data source. Implement rate limiting in your server to avoid being blocked. * **Asynchronous Operations:** For handling multiple concurrent requests efficiently, consider using asynchronous frameworks like `asyncio` and `aiohttp` instead of Flask. * **Configuration:** Use environment variables or a configuration file to store sensitive information like API keys or database credentials. * **Deployment:** Consider using a production-ready web server like Gunicorn or uWSGI to deploy your Flask application. **Chinese Translation of Key Terms:** * **Stock Price:** 股票价格 (gǔpiào jiàgé) * **Historical Data:** 历史数据 (lìshǐ shùjù) * **Ticker Symbol:** 股票代码 (gǔpiào dàimǎ) * **Start Date:** 开始日期 (kāishǐ rìqí) * **End Date:** 结束日期 (jiéshù rìqí) * **Server:** 服务器 (fúwùqì) * **API:** 应用程序接口 (yìngyòng chéngxù jiēkǒu) * **JSON:** JSON 数据格式 (JSON shùjù géshì) * **Error:** 错误 (cuòwù) * **Request:** 请求 (qǐngqiú) * **Response:** 响应 (xiǎngyìng) This comprehensive example should give you a solid foundation for building your stock price API using `vnstock` and Flask. Remember to adapt it to your specific needs and consider the important considerations mentioned above.
automcp
轻松地将现有代理框架中的工具、代理和编排器转换为 MCP 服务器。
微信读书 MCP 服务器
Sunwood Ai Labs_mcp Weather Service Server
镜子 (jìng zi)
MikeCreighton.com Content MCP Server
一个模型上下文协议 (MCP) 服务器,它将把 Mike Creighton Consulting 网站的所有页面作为资源提供给任何 MCP 客户端。
OpenSCAD MCP Server
镜子 (jìng zi)
trial-mcp-server
test
测试 (cè shì)
CISA Vulnerability Checker
kev-mcp 服务器 (kev-mcp fúwùqì)
MCP-Recon-Server
带有用于域名侦察的工具的 MCP 服务器 (Dài yǒu yòng yú yú míng zhēnchá de gōngjù de MCP fúwùqì) Alternatively, a more technical translation could be: 配备域名侦察工具的 MCP 服务器 (Pèibèi yú míng zhēnchá gōngjù de MCP fúwùqì) Which one is better depends on the context. The first is more general, while the second is more precise.
weather-mcp-server
天气 MCP 服务器 (Tiānqì MCP fúwùqì)
mcp-cps-data MCP serverWhat is mcp-cps-data?How to use mcp-cps-data?Key features of mcp-cps-data?Use cases of mcp-cps-data?FAQ from mcp-cps-data?
芝加哥公立学校本地托管数据的 MCP 服务器
MCP_server_example
Korea Weather MCP Server
使用韩国气象厅 (KWS) 的 MCP 服务器
EOL MCP Server 📅
镜子 (jìng zi)
mentor-mcp-server
镜子 (jìng zi)
mcpServerStudy
MCP服务器研究 (MCP fúwùqì yánjiū)
Mcp Gaodeweather Server
YR MCP Server
使用 Yr 天气数据作为 LLM 工具上下文的 MCP 服务器。
Cryptocurrency Market Data MCP Server
镜子 (jìng zi)
Weather MCP Server
镜子 (jìng zi)
Story IP Creator Agent
一个使用我们 MCP 服务器的演示代理
Time MCP Server by PHP
好的,这是使用 PHP 实现的 MCP (Model Context Protocol) 服务器,用于检索时间信息的示例: ```php <?php // 定义 MCP 服务器的地址和端口 $address = 'tcp://127.0.0.1:12345'; // 创建一个 TCP 套接字 $socket = stream_socket_server($address, $errno, $errstr); if (!$socket) { die("Could not create socket: $errstr ($errno)\n"); } echo "MCP Server listening on $address...\n"; while (true) { // 接受客户端连接 $client = stream_socket_accept($socket, -1); if ($client) { echo "Client connected.\n"; // 读取客户端请求 $request = fread($client, 1024); // 处理请求 $response = handleRequest($request); // 发送响应 fwrite($client, $response); // 关闭客户端连接 fclose($client); echo "Client disconnected.\n"; } } fclose($socket); /** * 处理客户端请求并返回响应。 * * @param string $request 客户端请求 * @return string MCP 响应 */ function handleRequest(string $request): string { // 假设请求是简单的 "get_time" if (trim($request) === 'get_time') { $currentTime = date('Y-m-d H:i:s'); $response = "time: " . $currentTime . "\n"; // MCP 响应格式,可以根据需要调整 } else { $response = "error: invalid request\n"; // 错误响应 } return $response; } ?> ``` **代码解释:** 1. **`$address = 'tcp://127.0.0.1:12345';`**: 定义了服务器监听的地址和端口。 `tcp://127.0.0.1` 表示监听本地回环地址,`12345` 是端口号。 你可以根据需要修改这些值。 2. **`$socket = stream_socket_server($address, $errno, $errstr);`**: 使用 `stream_socket_server` 函数创建一个 TCP 套接字服务器。 `$errno` 和 `$errstr` 用于存储错误代码和错误信息,如果套接字创建失败。 3. **`while (true)`**: 进入一个无限循环,等待客户端连接。 4. **`$client = stream_socket_accept($socket, -1);`**: 使用 `stream_socket_accept` 函数接受客户端连接。 `-1` 表示无限期等待连接。 5. **`$request = fread($client, 1024);`**: 从客户端读取请求数据。 `1024` 是读取的最大字节数。 6. **`$response = handleRequest($request);`**: 调用 `handleRequest` 函数处理客户端请求并生成响应。 7. **`fwrite($client, $response);`**: 将响应数据发送给客户端。 8. **`fclose($client);`**: 关闭客户端连接。 9. **`handleRequest(string $request): string`**: 这个函数负责处理客户端请求。 在这个例子中,它检查请求是否为 "get_time"。 如果是,它获取当前时间并将其格式化为 `Y-m-d H:i:s`。 然后,它构建一个 MCP 响应,格式为 `time: <当前时间>\n`。 如果请求无效,它返回一个错误响应。 **如何运行:** 1. 将代码保存为 `mcp_server.php`。 2. 在命令行中运行 `php mcp_server.php`。 3. 服务器将开始监听 `tcp://127.0.0.1:12345`。 **如何测试:** 你可以使用 `telnet` 或 `netcat` 等工具来测试服务器。 * **使用 telnet:** ```bash telnet 127.0.0.1 12345 ``` 连接成功后,输入 `get_time` 并按回车键。 服务器应该返回当前时间。 * **使用 netcat:** ```bash nc 127.0.0.1 12345 ``` 连接成功后,输入 `get_time` 并按回车键。 服务器应该返回当前时间。 **重要注意事项:** * **错误处理:** 这个示例代码只包含基本的错误处理。 在生产环境中,你需要添加更完善的错误处理机制,例如记录错误日志。 * **安全性:** 这个示例代码没有考虑安全性。 在生产环境中,你需要采取安全措施,例如验证客户端身份、防止注入攻击等。 * **MCP 协议:** 这个示例代码只是一个简单的 MCP 服务器的演示。 真正的 MCP 协议可能更复杂,需要根据实际需求进行调整。 你需要定义清晰的请求和响应格式。 * **并发:** 这个示例代码是单线程的,一次只能处理一个客户端连接。 如果需要处理大量并发连接,你需要使用多线程或异步编程。 可以使用 `pcntl_fork` 创建子进程来处理并发连接,或者使用 `ReactPHP` 等异步框架。 * **扩展性:** 这个示例代码只提供了一个简单的 `get_time` 功能。 你可以根据需要添加更多功能,例如获取系统信息、执行命令等。 **更完善的示例 (使用 `pcntl_fork` 实现并发):** ```php <?php // 定义 MCP 服务器的地址和端口 $address = 'tcp://127.0.0.1:12345'; // 创建一个 TCP 套接字 $socket = stream_socket_server($address, $errno, $errstr); if (!$socket) { die("Could not create socket: $errstr ($errno)\n"); } echo "MCP Server listening on $address...\n"; // 设置信号处理函数,防止僵尸进程 pcntl_signal(SIGCHLD, SIG_IGN); while (true) { // 接受客户端连接 $client = stream_socket_accept($socket, -1); if ($client) { // 创建一个子进程来处理客户端连接 $pid = pcntl_fork(); if ($pid == -1) { // Fork 失败 fclose($client); echo "Fork failed.\n"; } elseif ($pid == 0) { // 子进程 fclose($socket); // 子进程不需要监听套接字 echo "Client connected (PID: " . getmypid() . ").\n"; // 读取客户端请求 $request = fread($client, 1024); // 处理请求 $response = handleRequest($request); // 发送响应 fwrite($client, $response); // 关闭客户端连接 fclose($client); echo "Client disconnected (PID: " . getmypid() . ").\n"; exit(0); // 子进程退出 } else { // 父进程 fclose($client); // 父进程不需要客户端套接字 } } } fclose($socket); /** * 处理客户端请求并返回响应。 * * @param string $request 客户端请求 * @return string MCP 响应 */ function handleRequest(string $request): string { // 假设请求是简单的 "get_time" if (trim($request) === 'get_time') { $currentTime = date('Y-m-d H:i:s'); $response = "time: " . $currentTime . "\n"; // MCP 响应格式,可以根据需要调整 } else { $response = "error: invalid request\n"; // 错误响应 } return $response; } ?> ``` 这个并发版本使用 `pcntl_fork` 创建子进程来处理每个客户端连接。 这允许多个客户端同时连接到服务器。 `pcntl_signal(SIGCHLD, SIG_IGN);` 用于忽略子进程结束的信号,防止产生僵尸进程。 记住,这只是一个基本的示例。 你需要根据你的具体需求进行修改和扩展。 在生产环境中使用之前,请务必进行充分的测试和安全审查。