Financial data analysis with enterprise-grade guardrails for security.
A Financial MCP Project
A Model Context Protocol (MCP) implementation demonstrating financial data analysis as a use case, built with yfinance and featuring a comprehensive server with tools, resources, and prompts for stock market analysis. Now enhanced with enterprise-grade guardrails for security, compliance, and safety. This project was inspired after I enrolled in the MCP Course offered by DeepLearning.ai in collaboration with Anthropic.
🚀 Features
MCP Server (financial_server.py)
- Tools: 4 powerful financial analysis tools
get_stock_info: Get comprehensive stock informationget_historical_data: Retrieve historical price datacompare_stocks: Compare multiple stocks by metricsget_market_summary: Get major market indices summary
- Resources: Access saved financial data
finance://portfolios: List all saved analysesfinance://{filename}: Access specific data files
- Prompts: Pre-built analysis templates
analyze_stock_prompt: Comprehensive stock analysisportfolio_comparison_prompt: Multi-stock portfolio analysis
Enhanced MCP Client (enhanced_financial_chatbot.py)
- Interactive chat interface with financial focus
- 🛡️ Comprehensive guardrails system
- Support for resources (@portfolios, @filename)
- Support for prompts (/prompts, /prompt
) - Integration with multiple MCP servers
- Real-time financial data queries
- Session tracking and monitoring
- Investment advice detection and blocking
🛡️ Comprehensive Guardrails System (guardrails.py)
- Content Filtering: Blocks investment advice requests and high-risk content
- Rate Limiting: Prevents API abuse (15 calls/minute, 200/hour, 2000/day)
- Input Validation: Stock symbol format validation and sanitization
- Security Protection: Code injection detection and blocking
- Session Management: User session tracking with violation logging
- Risk Assessment: Automatic query risk level evaluation
- Response Enhancement: Automatic disclaimers and safety warnings
- Compliance Features: Regulatory compliance and professional referrals
📦 Installation
- Clone and setup the project:
# Create project directory
mkdir financial-mcp-project
cd financial-mcp-project
# Initialize with uv
uv init
- Install dependencies:
# Create virtual environment
uv venv
# Activate virtual environment
source .venv/bin/activate # Linux/Mac
# or
.venv\Scripts\activate # Windows
# Install core dependencies
uv add mcp yfinance anthropic python-dotenv nest-asyncio pandas numpy
# Install security libraries for guardrails
uv add ratelimit validators bleach
- Set up environment variables:
# Copy example environment file
cp .env.example .env
# Edit .env with your Anthropic API key
ANTHROPIC_API_KEY=your_actual_api_key_here
- Create required files and directories:
# Create data directory
mkdir -p financial_data
# Create enhanced version directory
mkdir -p enhanced_version
# Create guardrails configuration in enhanced_version folder
touch enhanced_version/guardrails_config.json
🏃♂️ Quick Start
Running the MCP Server (Testing)
# Test the server with MCP inspector
npx @modelcontextprotocol/inspector uv run financial_server.py
Running the Enhanced Financial Chatbot
# Navigate to enhanced version folder
cd enhanced_version
# Start the chatbot with comprehensive guardrails
uv run enhanced_financial_chatbot.py
Running the Simple Version (Optional)
# Navigate to enhanced version folder
cd enhanced_version
# Start the chatbot with basic guardrails
uv run simple_financial_chatbot.py
Running the Original Basic Chatbot
# From main directory
uv run financial_chatbot.py
💬 Usage Examples
Basic Stock Queries
Query: What's the current price of Apple stock?
Query: Get me historical data for TSLA over the past year
Query: Compare AAPL, GOOGL, and MSFT by market cap
Using Resources
Query: @portfolios # List all saved data
Query: @AAPL_info.json # View specific stock data
Query: @market_summary_20241220.json # View market summary
Using Prompts
Query: /prompts # List available prompts
Query: /prompt analyze_stock_prompt symbol=AAPL # Analyze Apple stock
Query: /prompt portfolio_comparison_prompt symbols=["AAPL","GOOGL","MSFT"] timeframe=1y
Guardrails Features
Query: /status # Check session statistics and violations
Query: Should I buy Apple stock? # Will be blocked - investment advice
Query: What's a good investment? # Will be blocked - investment advice
Advanced Analysis
Query: Analyze the tech sector by comparing AAPL
Tools (4)
get_stock_infoGet comprehensive stock informationget_historical_dataRetrieve historical price datacompare_stocksCompare multiple stocks by metricsget_market_summaryGet major market indices summaryEnvironment Variables
ANTHROPIC_API_KEYrequiredAPI key for Anthropic servicesConfiguration
{"mcpServers": {"financial-server": {"command": "uv", "args": ["run", "financial_server.py"], "env": {"ANTHROPIC_API_KEY": "your_actual_api_key_here"}}}}