# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
This is an MCP (Model Context Protocol) server implementation for financial/stock market research and analysis. The main server (`server.py`) provides tools for equity research, including technical analysis, fundamental analysis, SEC filings retrieval, and stock charting capabilities.
## Environment Setup
### Python Environment
This project requires Python 3.11 (for OpenBB compatibility). Use conda for environment management:
```bash
# Activate the mcp conda environment
conda activate mcp
# Install dependencies
pip install -r requirements.txt
```
### Required API Keys
Set these environment variables in `.env`:
- `TIINGO_API_KEY` - Required for historical market data
- `OPENBB_PAT` - OpenBB Platform access token for financial data
- `SEC_FIRM` - SEC API firm identifier
- `SEC_USER` - SEC API user email
- `ANTHROPIC_API_KEY` - For Claude API access (optional, for testing)
- `OPENAI_API_KEY` - For OpenAI API access (optional, for testing)
- `FIREFOX_PROFILE_PATH` - Path to Firefox profile for Playwright scraping
## Running the MCP Server
### Development Mode
```bash
# Run with debug logging
LOGLEVEL=DEBUG mcp dev server.py
# Test in MCP Inspector (opens web UI)
mcp dev server.py
```
### Production Mode
```bash
# Run directly
mcp run server.py
# Or use with Claude Desktop by installing
mcp install server.py
```
### Claude Desktop Integration
The server is configured in `claude_desktop_config.json` as the `stock-symbol-server`. Claude Desktop will automatically launch it when the client starts.
## Testing
### Interactive Testing with Jupyter
Use `Simple MCP demo.ipynb` to test the server interactively:
- Demonstrates MCP client/server communication
- Shows how to connect to the server programmatically
- Provides examples of tool calling with both Anthropic and OpenAI models
### Manual Testing
```bash
# Test imports and basic functionality
python -c "from server import MarketData, TechnicalAnalysis; print('OK')"
```
## Architecture
### Core Components
**server.py** - Main MCP server with FastMCP framework
- `MarketData` class - Fetches historical data from Tiingo API
- `TechnicalAnalysis` class - Calculates technical indicators using TA-Lib
- MCP tools (decorated with `@mcp.tool()`):
- `get_trades_for_symbol()` - Query trade blotter database
- `fetch_10k_item1()` - Retrieve SEC 10-K Item 1 filings
- `make_stock_chart()` - Generate stock charts with Plotly
- `technical_analysis()` - Calculate technical indicators
- `get_fundamental_ratios()` - Retrieve fundamental metrics
- `get_peers()` - Get peer companies
- `get_peers_ratios()` - Compare ratios across peers
**scrape.py** - Web scraping utilities using Playwright
- `get_browser()` - Initializes stealth browser with randomized fingerprinting
- `perform_human_like_actions()` - Simulates human browsing behavior
- `normalize_html()` - Extracts clean text from HTML using Trafilatura
**blotter.db** - SQLite database containing fake trade data
- Generated by `insert_fake_trades()` function
- Schema: `id, date, symbol, company, side, quantity, price`
### Data Storage Pattern
Tools create temporary directories named `{SYMBOL}-{YYYY-MM-DD}` to store:
- SEC filing text files (e.g., `10k_item_1.txt`)
- Technical analysis reports (`technical_analysis.txt`)
- Stock charts (`plotly_chart.png`)
- Fundamental ratios markdown tables (`peers_ratios.md`)
- Peer lists (`peers.json`)
### Key Dependencies
- **FastMCP** - MCP server framework
- **yfinance** - Yahoo Finance data
- **OpenBB** - Financial data platform (requires Python 3.11)
- **TA-Lib** - Technical analysis indicators (C library wrapper)
- **Plotly** - Interactive charting
- **sec-parser** - Parse SEC EDGAR filings
- **Playwright** - Browser automation for scraping
- **Tiingo API** - Market data provider
## Common Development Tasks
### Adding a New MCP Tool
1. Define function in `server.py` with `@mcp.tool()` decorator
2. Use Pydantic `Field()` for parameter descriptions
3. Return simple types (str, dict) or Pydantic models
4. For images, return `MCPImage(data=bytes, format="png")`
5. Test with `mcp dev server.py` in MCP Inspector
### Modifying Technical Indicators
Edit `TechnicalAnalysis.add_core_indicators()`:
- Uses TA-Lib functions for performance
- Input must be numpy arrays: `df["close"].values`
- All indicators should handle NaN values gracefully
### Working with SEC Filings
The `fetch_10k_item1()` tool:
1. Downloads HTML from SEC EDGAR using `sec_downloader`
2. Parses structure with `sec_parser`
3. Extracts sections by regex matching item headers
4. Saves to temp directory and returns text
## Project Context
This MCP server is part of a larger research initiative to build a multi-agent equity research system (see `Agent design.md`). The vision is a coordinator-based architecture where specialized agents collaborate to produce comprehensive stock analysis reports.
The current implementation provides foundational tools that can be orchestrated by AI assistants (like Claude Desktop) to perform deep research workflows.
## Related MCP Servers
This project integrates with several other MCP servers (configured in `claude_desktop_config.json`):
- **yahoo-finance-mcp** - Additional Yahoo Finance functionality
- **alphavantage** - Alpha Vantage market data
- **fmp-mcp-server** - Financial Modeling Prep data
- **wikipedia** - Wikipedia research
- **brave-search** / **perplexity-ask** - Web search capabilities
- **filesystem** - File access for Desktop/Downloads/projects
## Logging
Logs are written to `logs/{YYYY-MM-DD}.log` with DEBUG level information when `LOGLEVEL=DEBUG` is set.
## Important Notes
- The working directory is set to the script location on startup
- All file paths in temp directories are absolute paths
- The blotter database contains synthetic trade data for demonstration
- Stock charts use weekly data over a 4-year period
- Technical indicators require sufficient historical data (minimum 200 days for SMA-200)