loading…
Search for a command to run...
loading…
Provides tools for stock data retrieval, historical analysis, and market comparison using yfinance. It features robust guardrails to ensure secure interactions
Provides tools for stock data retrieval, historical analysis, and market comparison using yfinance. It features robust guardrails to ensure secure interactions and blocks restricted content like investment advice.
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.
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 summaryfinance://portfolios: List all saved analysesfinance://{filename}: Access specific data filesanalyze_stock_prompt: Comprehensive stock analysisportfolio_comparison_prompt: Multi-stock portfolio analysis# Create project directory
mkdir financial-mcp-project
cd financial-mcp-project
# Initialize with uv
uv init
# 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
# Copy example environment file
cp .env.example .env
# Edit .env with your Anthropic API key
ANTHROPIC_API_KEY=your_actual_api_key_here
# 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
# Test the server with MCP inspector
npx @modelcontextprotocol/inspector uv run financial_server.py
# Navigate to enhanced version folder
cd enhanced_version
# Start the chatbot with comprehensive guardrails
uv run enhanced_financial_chatbot.py
# Navigate to enhanced version folder
cd enhanced_version
# Start the chatbot with basic guardrails
uv run simple_financial_chatbot.py
# From main directory
uv run financial_chatbot.py
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
Query: @portfolios # List all saved data
Query: @AAPL_info.json # View specific stock data
Query: @market_summary_20241220.json # View market summary
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
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
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
| Tool | Description | Parameters | Guardrails Applied |
|---|---|---|---|
get_stock_info |
Get comprehensive stock information | symbol (required) |
Symbol validation, rate limiting |
get_historical_data |
Get historical price data | symbol, period, interval |
Symbol validation, period limits, data point limits |
compare_stocks |
Compare multiple stocks | symbols (list), metric |
Symbol validation, maximum 10 symbols |
get_market_summary |
Get major market indices | None | Rate limiting only |
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
npx @modelcontextprotocol/inspector uv run financial_server.py
# 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 server functions directly
python -c "import yfinance as yf; print(yf.Ticker('AAPL').info['currentPrice'])"
ANTHROPIC_API_KEY: Required for Claude API accessLOG_LEVEL: Logging level (DEBUG, INFO, WARNING, ERROR)FINANCE_DATA_DIR: Directory for saving financial data{
"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
}
}
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", "."]
}
}
}
/status command# 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?
# 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?
# 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?
When contributing to guardrails:
This MCP server using stdio transport for local-only deployment. This design choice prioritizes security when handling financial data:
This project is licensed under the MIT License - see the LICENSE file for details.
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.
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.
from github.com/NatalieCheong/MCP_for_Simple_Financial_Stock_Market
Добавь это в claude_desktop_config.json и перезапусти Claude Desktop.
{
"mcpServers": {
"financial-stock-market-mcp-server": {
"command": "npx",
"args": []
}
}
}PRs, issues, code search, CI status
Database, auth and storage
Reference / test server with prompts, resources, and tools.
Secure file operations with configurable access controls.