Uses Google's Gemini AI to interpret natural language stock queries and automatically map them to appropriate stock data retrieval tools
Enhanced MCP Stock Query System
An intelligent, production-ready stock data retrieval system built on the Model Context Protocol (MCP) that combines AI-powered query understanding with reliable financial data access. The system uses Google's Gemini AI to interpret natural language queries and automatically selects the appropriate tools to fetch comprehensive stock market information.
๐ Features
Core Functionality
๐ค AI-Powered Query Understanding: Uses Google Gemini to interpret natural language stock queries
๐ Dual Data Sources: Primary Yahoo Finance API with CSV fallback for reliability
๐ Automatic Tool Selection: Intelligent mapping of user queries to appropriate stock tools
๐ฌ Interactive Chat Interface: Enhanced command-line interface with error handling
๐ก๏ธ Robust Error Handling: Comprehensive fallback mechanisms and error recovery
โก Asynchronous Processing: High-performance async operations for better responsiveness
Enhanced MCP Features
๐ MCP Resources: Exposes stock data and market information as discoverable resources
๐ฏ MCP Prompts: Pre-built prompt templates for stock analysis and comparisons
๐ง Enhanced Tools: Improved tools with better validation and error handling
๐ Market Summary: New tool for getting overview of key market data
Production-Ready Improvements
๐๏ธ Type Safety: Comprehensive type hints throughout the codebase
๐ Comprehensive Logging: Structured logging for debugging and monitoring
โ๏ธ Configuration Management: Environment-based configuration with validation
๐งช Testing Suite: Unit tests for core functionality
๐ Input Validation: Sanitization and validation of all user inputs
๐ Retry Logic: Automatic retry with exponential backoff for failed operations
๐ Available Tools
get_stock_price
Purpose: Retrieve current stock price for a single symbol
Parameters:
symbol
(string): Stock ticker symbol (e.g., "AAPL", "MSFT")Enhanced Features: Input validation, detailed error messages, data source indication
compare_stocks
Purpose: Compare prices between two stock symbols with percentage differences
Parameters:
symbol1
(string): First stock ticker symbolsymbol2
(string): Second stock ticker symbol
Enhanced Features: Percentage calculations, data source tracking, comprehensive comparisons
get_market_summary
Purpose: Get overview of key market stocks and data availability
Parameters: None
Features: Shows availability status, data sources, and key stock prices
๐ง MCP Resources
stock_data
URI:
stock://data
Description: Information about available stocks and data sources
Content: JSON with available symbols, data sources, and freshness information
market_info
URI:
stock://market-info
Description: Server capabilities and market information
Content: JSON with server features and supported operations
๐ฏ MCP Prompts
stock_analysis
Purpose: Template for comprehensive stock analysis
Usage: Provides structured approach to analyzing individual stocks
comparison_prompt
Purpose: Template for comparing multiple stocks
Usage: Guides comparative analysis between different stocks
๐๏ธ Architecture
The system consists of two main components with enhanced error handling and configuration:
Enhanced MCP Server (mcp_server.py
)
Provides stock data tools through the MCP protocol
Implements Yahoo Finance API integration with robust CSV fallback
Exposes MCP resources and prompts for better discoverability
Comprehensive error handling with custom exception types
Input validation and sanitization
Structured logging for monitoring
Enhanced MCP Client (mcp_client.py
)
Handles user input and natural language processing
Connects to the MCP server via stdio communication
Uses Gemini AI to identify appropriate tools and arguments
Configuration management and environment validation
Retry logic with exponential backoff
Interactive user session with graceful error handling
๐ฆ Installation
Prerequisites
Python 3.10 or higher
Google AI API key (Gemini)
Internet connection for Yahoo Finance data
Setup Steps
Clone or download the project files
Install dependencies:
pip install -r requirements.txtConfigure environment variables:
cp .env.example .env # Edit .env with your actual valuesRequired environment variables (
.env
):GEMINI_API_KEY=your_gemini_api_key_hereOptional environment variables:
MCP_SERVER_CWD=/path/to/your/project MCP_MAX_RETRIES=3 MCP_TIMEOUT_SECONDS=30 LOG_LEVEL=INFOVerify data file: Ensure
stocks_data.csv
is present with the correct format:symbol,price,last_updated AAPL,175.64,2024-01-15 MSFT,330.21,2024-01-15 GOOGL,135.45,2024-01-15
๐ Usage
Starting the System
Run the enhanced client:
python mcp_client.pyEnter natural language queries:
What is your query? โ What's the current price of Apple? What is your query? โ Compare stock prices of Apple and Microsoft What is your query? โ Get market summaryExit commands:
Type
quit
,exit
, orq
to stopUse
Ctrl+C
for immediate exit
Example Interactions
Single Stock Query:
Stock Comparison with Percentage:
Market Summary:
Fallback Data Example:
๐ Project Structure
๐งช Testing
Running Tests
Test Coverage
Stock symbol validation
CSV data handling and error cases
Yahoo Finance integration mocking
Fallback mechanism testing
Error handling scenarios
โ๏ธ Configuration
Environment Variables
Variable | Required | Default | Description |
| Yes | - | Google Gemini API key for AI processing |
| No | Current directory | Working directory for MCP server |
| No | 3 | Maximum retry attempts for failed operations |
| No | 30 | Timeout for MCP operations |
| No | INFO | Logging level (DEBUG, INFO, WARNING, ERROR) |
| No | stocks_data.csv | Path to fallback CSV data file |
CSV Data Format
The fallback CSV file must follow this exact structure:
Required columns:
symbol
: Stock ticker symbol (uppercase recommended)price
: Current stock price (numeric)last_updated
: Date when price was last updated (YYYY-MM-DD format)
๐ Data Sources
Primary: Yahoo Finance
Real-time stock data via yfinance library
Comprehensive market coverage
Automatic retry mechanisms
Live market data during trading hours
Fallback: Local CSV
Offline data access when Yahoo Finance is unavailable
Customizable stock universe
Fast local lookups
Timestamped data for freshness tracking
๐ Troubleshooting
Common Issues
Network/SSL Issues with Yahoo Finance
Error: TLS connect error
or OpenSSL invalid library
Causes:
Corporate networks with strict SSL/TLS policies
Outdated OpenSSL libraries or certificates
VPN or proxy configurations blocking financial APIs
Restricted network environments
Solutions:
System automatically falls back to local CSV data
Verify your query symbol exists in
stocks_data.csv
Update system OpenSSL libraries
Configure proxy settings if behind corporate firewall
Contact network administrator for API access permissions
Configuration Errors
Error: Configuration error: GEMINI_API_KEY environment variable is required
Solution:
Copy
.env.example
to.env
Add your actual Gemini API key
Ensure
.env
file is in the project root directory
MCP Connection Issues
Error: MCP connection error: Server script not found
Solutions:
Verify
mcp_server.py
is in the correct directoryCheck the
MCP_SERVER_CWD
environment variableEnsure Python is in your system PATH
Verify file permissions
Data Retrieval Issues
Error: Could not retrieve price for SYMBOL
Solutions:
Verify stock symbol is correct (use uppercase)
Check internet connection for Yahoo Finance
Ensure
stocks_data.csv
exists and has correct formatCheck CSV file has all required columns
Debug Mode
Enable detailed debugging by setting:
This provides detailed information about:
MCP connection status
AI tool identification process
Data source selection logic
Detailed error traces
๐ Performance Considerations
Optimization Features
Asynchronous operations for better responsiveness
Intelligent caching of frequently requested data
Efficient CSV parsing with pandas
Connection reuse for external APIs
Graceful degradation when services are unavailable
Scalability Notes
Current implementation is designed for moderate query volumes
For high-volume production use, consider:
Adding Redis for caching
Implementing connection pooling
Using a proper database instead of CSV
Adding rate limiting for external APIs
๐ Security Considerations
Implemented Security Features
Input validation and sanitization
Environment-based configuration (no hardcoded secrets)
Proper error handling without information leakage
Type checking to prevent injection attacks
Recommendations for Production
Use proper secrets management (e.g., AWS Secrets Manager)
Implement rate limiting
Add authentication for client connections
Use HTTPS for all external API calls
Regular security audits of dependencies
๐ Dependencies
Core Dependencies
mcp[cli]==1.8.1
- Model Context Protocol frameworkyfinance==0.2.61
- Yahoo Finance API wrappergoogle-genai==1.15.0
- Google Gemini AI clientpython-dotenv==1.1.0
- Environment variable managementpandas>=2.0.0
- Data processing and CSV handling
Development Dependencies
pytest>=7.0.0
- Testing frameworkpytest-asyncio>=0.21.0
- Async testing supportblack>=23.0.0
- Code formattingmypy>=1.0.0
- Type checking
๐ค Contributing
Development Setup
Clone the repository
Install development dependencies:
pip install -r requirements.txt
Run tests:
pytest tests/
Format code:
black .
Type check:
mypy .
Code Quality Standards
All code must have type hints
Minimum 80% test coverage
Follow PEP 8 style guidelines
Comprehensive error handling
Detailed docstrings for all functions
๐ License
This project is provided as-is for educational and development purposes. Please ensure compliance with all relevant APIs' terms of service when using in production.
๐ Version History
v2.0.0 (Enhanced Version)
Added MCP resources and prompts
Comprehensive error handling and logging
Type safety and input validation
Configuration management
Testing suite
Enhanced documentation
v1.0.0 (Original Version)
Basic MCP server and client
Yahoo Finance integration
CSV fallback mechanism
AI-powered query understanding
This server cannot be installed
remote-capable server
The server can be hosted and run remotely because it primarily relies on remote services or has no dependency on the local environment.
Enables AI-powered natural language stock market queries with real-time data from Yahoo Finance and CSV fallback. Uses Google Gemini to interpret queries and automatically fetch stock prices, comparisons, and market summaries.
- ๐ Features
- ๐ Available Tools
- ๐ง MCP Resources
- ๐ฏ MCP Prompts
- ๐๏ธ Architecture
- ๐ฆ Installation
- ๐ Usage
- ๐ Project Structure
- ๐งช Testing
- โ๏ธ Configuration
- ๐ Data Sources
- ๐ Troubleshooting
- ๐ Performance Considerations
- ๐ Security Considerations
- ๐ Dependencies
- ๐ค Contributing
- ๐ License
- ๐ Version History