CLAUDE.md•6.31 kB
# Stock Ticker MCP Server - Claude Integration Guide
## Implementation Overview
This MCP server provides Claude AI with real-time and historical stock market data capabilities through the Alpha Vantage API. The implementation follows MCP best practices and provides robust error handling for production use.
## Architecture
### Core Components
1. **FastMCP Framework**: Lightweight MCP server implementation
2. **Alpha Vantage API Integration**: Professional-grade financial data provider
3. **Docker Container**: Isolated, reproducible deployment environment
4. **Tool Functions**: Two primary tools for stock data retrieval
### Tool Specifications
#### `get_current_price(symbol: str)`
- **Purpose**: Retrieve real-time stock quote data
- **API Endpoint**: GLOBAL_QUOTE function
- **Parameters**:
- `symbol`: Stock ticker symbol (e.g., "AAPL", "MSFT")
- **Returns**: Current price, change, volume, OHLC data
- **Error Handling**: Invalid symbols, API limits, network issues
#### `get_historical_price(symbol: str, date: str)`
- **Purpose**: Retrieve historical stock data for specific dates
- **API Endpoint**: TIME_SERIES_DAILY function
- **Parameters**:
- `symbol`: Stock ticker symbol
- `date`: Date in YYYY-MM-DD format
- **Returns**: OHLCV data for the specified trading day
- **Error Handling**: Invalid dates, non-trading days, missing data
## Implementation Guidelines
### Error Handling Strategy
The server implements comprehensive error handling for:
- **API Key Issues**: Missing or invalid Alpha Vantage API key
- **Rate Limiting**: Free tier has 25 requests/day limit
- **Invalid Symbols**: Non-existent or delisted stocks
- **Date Validation**: Weekend/holiday/non-trading day handling
- **Network Issues**: Timeouts and connectivity problems
- **Data Parsing**: Malformed API responses
### Security Considerations
1. **API Key Management**: Stored as environment variable only
2. **Container Security**: Non-root user execution
3. **Input Validation**: All user inputs are validated and sanitized
4. **Network Security**: Minimal container attack surface
### Performance Optimization
1. **Request Timeouts**: 30-second timeout for API calls
2. **Error Caching**: Prevents repeated failed requests
3. **Data Validation**: Early validation prevents unnecessary API calls
4. **Container Health**: Built-in health checks for monitoring
## Claude AI Integration
### Setup Process
1. **Server Deployment**: Container must be running and accessible
2. **MCP Configuration**: Add server to Claude's MCP configuration
3. **API Key Setup**: Configure Alpha Vantage API key
4. **Tool Registration**: Claude automatically discovers available tools
### Usage Patterns
#### Current Price Queries
```
User: "What's the current price of Apple stock?"
Claude: Uses get_current_price("AAPL")
Response: Current price, change, volume, etc.
```
#### Historical Price Queries
```
User: "What was Tesla's stock price on January 15, 2024?"
Claude: Uses get_historical_price("TSLA", "2024-01-15")
Response: Historical OHLCV data for that date
```
### Best Practices for Claude
1. **Symbol Validation**: Always validate stock symbols before API calls
2. **Date Formatting**: Ensure dates are in YYYY-MM-DD format
3. **Error Communication**: Clearly explain API limitations to users
4. **Rate Limit Awareness**: Inform users about daily request limits
5. **Market Hours**: Consider market schedules for real-time data
## Development Guidelines
### Code Quality Standards
1. **Type Hints**: All functions include comprehensive type annotations
2. **Documentation**: Detailed docstrings for all public functions
3. **Error Messages**: User-friendly error descriptions
4. **Logging**: Structured logging for debugging and monitoring
5. **Testing**: Comprehensive test coverage (implement separately)
### API Integration Best Practices
1. **Timeout Handling**: All API calls include timeout configuration
2. **Rate Limit Respect**: Built-in delays and retry logic
3. **Data Validation**: Verify API response structure before processing
4. **Graceful Degradation**: Fallback behavior for API failures
### Container Best Practices
1. **Multi-stage Builds**: Optimized image size
2. **Security Updates**: Regular base image updates
3. **Health Checks**: Container monitoring capabilities
4. **Resource Limits**: Appropriate CPU and memory constraints
## Monitoring and Maintenance
### Health Monitoring
- Container health checks every 30 seconds
- API connectivity validation
- Response time monitoring
- Error rate tracking
### Maintenance Tasks
1. **API Key Rotation**: Regular key updates
2. **Dependency Updates**: Keep packages current
3. **Log Monitoring**: Watch for API limit warnings
4. **Performance Tuning**: Optimize response times
### Troubleshooting Guide
#### Common Issues
1. **API Limit Exceeded**: Wait for reset or upgrade plan
2. **Invalid Symbols**: Verify symbol exists and is actively traded
3. **Network Timeouts**: Check connectivity and API status
4. **Container Issues**: Verify Docker configuration and resources
#### Debugging Steps
1. Check container logs for error messages
2. Verify environment variables are set correctly
3. Test API connectivity outside container
4. Validate MCP configuration in Claude
5. Monitor API usage through Alpha Vantage dashboard
## Future Enhancements
### Potential Additions
1. **Real-time Streaming**: WebSocket integration for live data
2. **Additional Endpoints**: Options data, company fundamentals
3. **Caching Layer**: Redis integration for response caching
4. **Multiple Providers**: Fallback to other data sources
5. **Advanced Analytics**: Technical indicators and analysis
### Scalability Considerations
1. **Load Balancing**: Multiple container instances
2. **API Key Pool**: Rotate between multiple keys
3. **Database Integration**: Historical data caching
4. **Microservices**: Split functionality into specialized services
## Testing Strategy
### Unit Tests
- Function-level testing for all tools
- Mock API responses for consistent testing
- Error condition validation
### Integration Tests
- End-to-end MCP communication
- API connectivity verification
- Container deployment validation
### Performance Tests
- Response time benchmarking
- Concurrent request handling
- Resource usage profiling