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.
gahoccode
README
推荐服务器
Crypto Price & Market Analysis MCP Server
一个模型上下文协议 (MCP) 服务器,它使用 CoinCap API 提供全面的加密货币分析。该服务器通过一个易于使用的界面提供实时价格数据、市场分析和历史趋势。 (Alternative, slightly more formal and technical translation): 一个模型上下文协议 (MCP) 服务器,利用 CoinCap API 提供全面的加密货币分析服务。该服务器通过用户友好的界面,提供实时价格数据、市场分析以及历史趋势数据。
MCP PubMed Search
用于搜索 PubMed 的服务器(PubMed 是一个免费的在线数据库,用户可以在其中搜索生物医学和生命科学文献)。 我是在 MCP 发布当天创建的,但当时正在度假。 我看到有人在您的数据库中发布了类似的服务器,但还是决定发布我的服务器。
mixpanel
连接到您的 Mixpanel 数据。 从 Mixpanel 分析查询事件、留存和漏斗数据。

Sequential Thinking MCP Server
这个服务器通过将复杂问题分解为顺序步骤来促进结构化的问题解决,支持修订,并通过完整的 MCP 集成来实现多条解决方案路径。

Nefino MCP Server
为大型语言模型提供访问德国可再生能源项目新闻和信息的能力,允许按地点、主题(太阳能、风能、氢能)和日期范围进行筛选。
Vectorize
将 MCP 服务器向量化以实现高级检索、私有深度研究、Anything-to-Markdown 文件提取和文本分块。
Mathematica Documentation MCP server
一个服务器,通过 FastMCP 提供对 Mathematica 文档的访问,使用户能够从 Wolfram Mathematica 检索函数文档和列出软件包符号。
kb-mcp-server
一个 MCP 服务器,旨在实现便携性、本地化、简易性和便利性,以支持对 txtai “all in one” 嵌入数据库进行基于语义/图的检索。任何 tar.gz 格式的 txtai 嵌入数据库都可以被加载。
Research MCP Server
这个服务器用作 MCP 服务器,与 Notion 交互以检索和创建调查数据,并与 Claude Desktop Client 集成以进行和审查调查。

Cryo MCP Server
一个API服务器,实现了模型补全协议(MCP),用于Cryo区块链数据提取,允许用户通过任何兼容MCP的客户端查询以太坊区块链数据。