Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Financial Stock Market MCP ServerCompare the performance of AAPL and MSFT over the last 6 months"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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 initInstall 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 bleachSet 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_hereCreate 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.pyRunning the Enhanced Financial Chatbot
# Navigate to enhanced version folder
cd enhanced_version
# Start the chatbot with comprehensive guardrails
uv run enhanced_financial_chatbot.pyRunning the Simple Version (Optional)
# Navigate to enhanced version folder
cd enhanced_version
# Start the chatbot with basic guardrails
uv run simple_financial_chatbot.pyRunning 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 capUsing Resources
Query: @portfolios # List all saved data
Query: @AAPL_info.json # View specific stock data
Query: @market_summary_20241220.json # View market summaryUsing 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=1yGuardrails 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 adviceAdvanced Analysis
Query: Analyze the tech sector by comparing AAPL, GOOGL, MSFT, and NVDA
Query: What's the current market sentiment based on major indices?
Query: Create a risk assessment for a portfolio containing AAPL, TSLA, and NVDAπ οΈ Available Tools
Tool | Description | Parameters | Guardrails Applied |
| Get comprehensive stock information |
| Symbol validation, rate limiting |
| Get historical price data |
| Symbol validation, period limits, data point limits |
| Compare multiple stocks |
| Symbol validation, maximum 10 symbols |
| Get major market indices | None | Rate limiting only |
π Supported Data
Stock Information: Price, market cap, P/E ratio, dividends, volume
Historical Data: OHLCV data with customizable periods and intervals
Market Indices: S&P 500, Dow Jones, NASDAQ, Russell 2000, VIX
Comparison Metrics: Price, market cap, P/E ratio, volume, and more
π Comprehensive Safety Features
Content Filtering
Investment Advice Detection: Blocks queries asking for buy/sell recommendations
High-Risk Content: Flags mentions of options, leverage, penny stocks, etc.
Blocked Keywords: Prevents "pump and dump", "guaranteed returns", etc.
Professional Referrals: Redirects advice requests to licensed financial advisors
Security Protection
Input Sanitization: Removes dangerous characters and validates input length
Code Injection Prevention: Blocks SQL injection, XSS, and code execution attempts
Symbol Validation: Ensures proper stock symbol format and blocks fake symbols
Response Filtering: Limits response length and adds security metadata
Rate Limiting & Resource Protection
Per-Session Limits: 15 calls/minute, 200/hour, 2000/day
Burst Protection: Prevents rapid-fire requests
Data Point Limits: Maximum 10,000 historical data points per request
Symbol Limits: Maximum 10 symbols per comparison
Compliance & Monitoring
Session Tracking: Unique session IDs for each user interaction
Violation Logging: Comprehensive logging of security events
Risk Assessment: Automatic classification of query risk levels
Audit Trail: Complete record of user interactions and system responses
π Project Structure
financial-mcp-project/
βββ financial_server.py # MCP server with financial tools
βββ financial_chatbot.py # Original basic chatbot
βββ server_config.json # MCP server configuration
βββ pyproject.toml # Project dependencies
βββ .env.example # Environment variables template
βββ README.md # This file
βββ financial_data/ # Generated data directory
β βββ AAPL_info.json
β βββ GOOGL_info.json
β βββ NVDA_info.json
β βββ market_summary_20250720_132820.json
βββ enhanced_version/ # Enhanced chatbot with guardrails
βββ enhanced_financial_chatbot.py # Main chatbot with comprehensive guardrails
βββ simple_financial_chatbot.py # Chatbot with basic guardrails (optional)
βββ guardrails.py # Comprehensive security module
βββ guardrails_config.json # Guardrails configurationπ§ͺ Testing
Test the MCP Server
npx @modelcontextprotocol/inspector uv run financial_server.pyTest Guardrails
# Navigate to enhanced version folder
cd enhanced_version
# Test basic validation
python -c "from guardrails import FinancialGuardrails; g = FinancialGuardrails(); print(g.validate_symbols(['AAPL']))"
# Test investment advice detection
python -c "from guardrails import validate_financial_query; print(validate_financial_query('Should I buy Apple stock?'))"Test Individual Components
# Test server functions directly
python -c "import yfinance as yf; print(yf.Ticker('AAPL').info['currentPrice'])"π§ Configuration
Environment Variables
ANTHROPIC_API_KEY: Required for Claude API accessLOG_LEVEL: Logging level (DEBUG, INFO, WARNING, ERROR)FINANCE_DATA_DIR: Directory for saving financial data
Guardrails Configuration (enhanced_version/guardrails_config.json)
{
"rate_limiting": {
"max_calls_per_minute": 15,
"max_calls_per_hour": 200,
"max_calls_per_day": 2000,
"min_request_interval_seconds": 1
},
"content_filtering": {
"blocked_keywords": [
"pump and dump",
"insider trading",
"guaranteed returns",
"risk-free investment"
],
"high_risk_terms": [
"options", "derivatives", "leverage", "margin",
"penny stocks", "crypto", "day trading"
]
},
"symbol_validation": {
"max_symbols_per_request": 10,
"blocked_symbols": ["SCAM", "FAKE", "TEST"]
},
"security": {
"sanitize_inputs": true,
"max_input_length": 2000,
"timeout_seconds": 45
}
}Server Configuration
Edit server_config.json to configure MCP servers:
{
"mcpServers": {
"finance": {
"command": "uv",
"args": ["run", "financial_server.py"]
},
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
}
}
}π¨ Important Security Notes
What the Guardrails Prevent
Investment Advice: Blocks queries asking for buy/sell recommendations
High-Risk Content: Flags dangerous financial instruments and schemes
API Abuse: Rate limiting prevents server overload
Security Threats: Blocks code injection and malicious input
Compliance Violations: Ensures regulatory compliance with disclaimers
What Users Can Still Do
Get Factual Data: Stock prices, market information, company data
Analyze Trends: Historical performance and technical analysis
Compare Options: Side-by-side stock comparisons
Educational Content: Learn about financial concepts and markets
Monitoring and Logging
All security violations are logged with timestamps
Session statistics available via
/statuscommandComprehensive audit trail for compliance purposes
Real-time monitoring of suspicious activity
π Extended Usage
Portfolio Analysis with Guardrails
# This will work - factual analysis
Query: /prompt portfolio_comparison_prompt symbols=["AAPL","GOOGL","MSFT"] timeframe=1y
# This will be blocked - investment advice
Query: Which of these stocks should I buy for my retirement portfolio?Market Research (Compliant)
# Allowed - factual market data
Query: Get me a market summary and compare TSLA's performance to the S&P 500
# Blocked - prediction request
Query: Which stocks will go up next week?Risk Assessment (Educational)
# Allowed - educational risk analysis
Query: Compare the historical volatility of AAPL, TSLA, and QQQ over 6 months
# Blocked - specific investment guidance
Query: How much should I invest in each of these stocks?π‘οΈ Guardrails Architecture
Client-Side Protection (enhanced_version/enhanced_financial_chatbot.py)
Query validation and filtering
Session management and tracking
User interface for monitoring
Response enhancement with disclaimers
Modular Security (enhanced_version/guardrails.py)
Reusable security components
Configurable validation rules
Comprehensive logging system
Risk assessment algorithms
Configuration-Driven (enhanced_version/guardrails_config.json)
Adjustable security parameters
Environment-specific settings
Easy policy updates
Compliance customization
Security Contributions
When contributing to guardrails:
Test all security features thoroughly
Document new validation rules
Consider compliance implications
Update configuration examples
π Security Notice
This MCP server using stdio transport for local-only deployment. This design choice prioritizes security when handling financial data:
β Local-only execution - Server runs on your device only
β No network exposure - Uses stdin/stdout communication
β Financial data privacy - Your data never leaves your machine
Acknowledgments
π License
This project is licensed under the MIT License - see the LICENSE file for details.
β οΈ Legal Disclaimer
IMPORTANT: This software is for educational and informational purposes only and is intended for non-commercial use. It is not intended as financial advice, investment guidance, or professional recommendation.
What This System Does
Provides factual financial data and market information
Offers educational content about financial concepts
Enables data analysis and research capabilities
Maintains strict compliance with informational use guidelines
What This System Does NOT Do
Provide investment advice or recommendations
Guarantee accuracy of market predictions
Replace professional financial consultation
Offer personalized investment strategies
User Responsibilities
Consult qualified financial professionals for investment decisions
Verify all data through official sources before acting
Understand that past performance does not guarantee future results
Use information solely for educational and research purposes
Compliance Statement
This system includes comprehensive guardrails designed to prevent the provision of unlicensed financial advice and ensure compliance with relevant regulations. All users are directed to consult with licensed financial advisors for investment decisions.
By using this system, you acknowledge that you understand these limitations and will use the information responsibly.
This server cannot be installed
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.