Financial Stock Market MCP Server

1

Add it to Claude Code

Run this in a terminal.

Run in terminal
claude mcp add -e "ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}" financial-stock-market -- uv run financial_server.py
Required:ANTHROPIC_API_KEY
README.md

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 information
    • get_historical_data: Retrieve historical price data
    • compare_stocks: Compare multiple stocks by metrics
    • get_market_summary: Get major market indices summary
  • Resources: Access saved financial data
    • finance://portfolios: List all saved analyses
    • finance://{filename}: Access specific data files
  • Prompts: Pre-built analysis templates
    • analyze_stock_prompt: Comprehensive stock analysis
    • portfolio_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

  1. Clone and setup the project:
# Create project directory
mkdir financial-mcp-project
cd financial-mcp-project

# Initialize with uv
uv init
  1. 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
  1. 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
  1. 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 information
get_historical_dataRetrieve historical price data
compare_stocksCompare multiple stocks by metrics
get_market_summaryGet major market indices summary

Environment Variables

ANTHROPIC_API_KEYrequiredAPI key for Anthropic services

Configuration

claude_desktop_config.json
{"mcpServers": {"financial-server": {"command": "uv", "args": ["run", "financial_server.py"], "env": {"ANTHROPIC_API_KEY": "your_actual_api_key_here"}}}}

Try it

What is the current price of Apple stock?
Get me historical data for TSLA over the past year.
Compare AAPL, GOOGL, and MSFT by market cap.
Get a summary of the major market indices.
Analyze the tech sector by comparing AAPL.

Frequently Asked Questions

What are the key features of Financial Stock Market MCP Server?

Comprehensive stock information retrieval. Historical price data analysis. Multi-stock comparison metrics. Enterprise-grade guardrails for security and compliance. Investment advice detection and blocking.

What can I use Financial Stock Market MCP Server for?

Performing historical stock price analysis for research. Comparing performance metrics across multiple stock tickers. Monitoring major market indices summaries. Building secure financial chatbots with regulatory compliance.

How do I install Financial Stock Market MCP Server?

Install Financial Stock Market MCP Server by running: uv add mcp yfinance anthropic python-dotenv nest-asyncio pandas numpy ratelimit validators bleach

What MCP clients work with Financial Stock Market MCP Server?

Financial Stock Market MCP Server works with any MCP-compatible client including Claude Desktop, Claude Code, Cursor, and other editors with MCP support.

Turn this server into reusable context

Keep Financial Stock Market MCP Server docs, env vars, and workflow notes in Conare so your agent carries them across sessions.

Need the old visual installer? Open Conare IDE.
Open Conare