# FinAgent MCP Server - Design Document

**Date:** 2026-02-22
**Status:** Approved
**Author:** Engineering Manager

## Overview

FinAgent is a financial analysis MCP server that provides live market data, SEC filings, and stock screening tools to any MCP-compatible AI application (Claude, ChatGPT, Cursor, etc.). It is the first listing on the MCP Marketplace (mcp-marketplace.io) and serves dual purpose: a genuinely useful financial tool and an end-to-end test of the marketplace's creator/consumer flows.

## Goals

1. Build a useful financial MCP server that people actually want to install
2. Test the full MCP Marketplace flow: submission, security scanning, install generation, freemium gating, payments
3. Demonstrate quality standards for future marketplace creators
4. Validate both stdio and HTTP transport for marketplace readiness

## Architecture

### High-Level Design

The host LLM (Claude, ChatGPT, etc.) acts as the orchestrator. FinAgent provides 4 compound tools that encapsulate financial data retrieval. No inner LLM. The server fetches, structures, and returns raw data. The host LLM does all reasoning and analysis.

Inspired by [Dexter](https://github.com/virattt/dexter)'s architecture with key adaptation: Dexter's subagent pattern (inner LLMs routing to specialized endpoints) becomes compound MCP tools (single tool interface, multiple API calls internally). The "small decision space" principle (5 tools, not 22) maps directly.

### Project Structure

```
~/Desktop/AI Projects/MCPs/finagent/
├── pyproject.toml              # Package config, dependencies
├── README.md                   # Marketplace listing description
├── .env.example                # Template for optional config
│
├── src/
│   └── finagent/
│       ├── __init__.py
│       ├── server.py           # FastMCP server + all tool registrations
│       ├── transport.py        # Stdio + HTTP entry points
│       │
│       ├── services/           # Data retrieval layer
│       │   ├── market_data.py  # yfinance wrapper
│       │   ├── sec_edgar.py    # SEC EDGAR API
│       │   ├── news.py         # Free news aggregation
│       │   └── screener.py     # Cross-ticker filtering
│       │
│       ├── cache/
│       │   └── file_cache.py   # Local JSON file cache
│       │
│       └── utils/
│           └── formatting.py   # Data formatting helpers
│
├── tests/
│   ├── test_market_data.py
│   ├── test_sec_edgar.py
│   ├── test_news.py
│   └── test_screener.py
│
└── cache/                      # Runtime cache (gitignored)
```

### Technology Choices

| Component | Choice | Rationale |
|-----------|--------|-----------|
| Language | Python | Primary language, best MCP SDK support (FastMCP) |
| Framework | FastMCP | Official Python MCP SDK, simple tool registration |
| Transport | Stdio + Streamable HTTP | Stdio for local installs (current marketplace), HTTP for future hosted MCPs |
| Market Data | yfinance | Free, no API key, no rate limits, rich data |
| SEC Filings | SEC EDGAR API | Free, no API key, comprehensive public filings |
| News | Free RSS/news APIs | Zero cost news aggregation |
| Caching | File-based JSON | Human-readable, debuggable, same pattern as Dexter |
| Testing | pytest | Standard, matches user preferences |
| Packaging | pyproject.toml (pip) | Standard Python packaging for marketplace distribution |

## Tool Design

4 compound tools. Small decision space. Each tool handles multiple API calls internally.

### 1. `financial_data` (Free tier)

**Description:** "Get financial data for any public stock: quotes, income statements, balance sheets, cash flow, analyst estimates, insider trades, and key ratios."

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| ticker | str | yes | Stock symbol (e.g., NVDA, AAPL) |
| data_type | str | yes | One of: quote, income_statement, balance_sheet, cash_flow, analyst_estimates, insider_trades, key_ratios |
| period | str | no | quarterly or annual (default: annual) |
| limit | int | no | Number of periods to return (default: 4) |

Returns raw structured data from yfinance. No summarization.

### 2. `market_news` (Free tier)

**Description:** "Search for financial news, analyst reactions, and market sentiment about a stock or topic."

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| query | str | yes | Search query (e.g., "NVDA earnings reaction") |
| ticker | str | no | Filter to a specific stock |
| days_back | int | no | How far back to search (default: 7) |

Returns array of articles: title, source, date, summary, URL.

### 3. `sec_filings` (Paid tier)

**Description:** "Read SEC filings for any public company: 10-K, 10-Q, 8-K, proxy statements. Extract specific sections like Item 7 (MD&A), risk factors, or management discussion."

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| ticker | str | yes | Stock symbol |
| filing_type | str | yes | One of: 10-K, 10-Q, 8-K, DEF-14A |
| section | str | no | Specific section (e.g., item_7, risk_factors). Omit for metadata. |
| date_range | str | no | e.g., "2024", "2023-2024" (default: most recent) |

Returns filing text for requested section, or metadata/TOC if no section specified.

### 4. `stock_screener` (Paid tier)

**Description:** "Screen stocks by financial criteria. Filter by P/E ratio, market cap, revenue growth, dividend yield, sector, and more."

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| filters | object | yes | Key-value criteria: sector, market_cap_min/max, pe_ratio_min/max, revenue_growth_min, dividend_yield_min |
| sort_by | str | no | Field to sort by |
| limit | int | no | Max results (default: 20) |

Returns array of matching stocks with key metrics.

## Freemium Gating

Free tools (`financial_data`, `market_news`) work with no configuration.

Paid tools (`sec_filings`, `stock_screener`) require `FINAGENT_LICENSE_KEY` env var. Without it, they return:

```json
{
  "error": "premium_required",
  "message": "sec_filings requires a FinAgent Pro license. Get one at mcp-marketplace.io/server/finagent",
  "tool": "sec_filings"
}
```

Key validation: `GET /api/licenses/verify?key=xxx` against the marketplace API. Maps to the marketplace's Option B license key system.

## Caching Strategy

Cache immutable data. Skip volatile data.

| Data | Cache Duration | Rationale |
|------|---------------|-----------|
| Current stock quote | Never | Changes every second |
| Market news | Never | Time-sensitive |
| Historical financials | 24 hours | Only changes at earnings |
| Analyst estimates | 1 hour | Updates throughout the day |
| Insider trades | 6 hours | Filed in batches |
| SEC filings | Forever | Legally immutable |
| Screener results | 1 hour | Metrics shift intraday |

Cache location: `~/.finagent/cache/` as human-readable JSON files.

## Error Handling

All errors return structured JSON, never raw exceptions:

- **Invalid ticker:** `{"error": "invalid_ticker", "message": "..."}`
- **API timeout:** Retry once, then return partial data with note
- **Rate limiting:** Exponential backoff retry
- **Missing data:** `{"data": null, "message": "No analyst estimates available for TICKER"}`

## Design Principles (from Dexter article)

1. **Small decision space.** 4 tools, not 22. The host LLM picks the right tool more reliably.
2. **Compound tools.** Each tool handles multiple API calls internally. Complexity is encapsulated.
3. **Raw data to the LLM.** No summarization middleware. The model sees structured data and does analysis itself.
4. **Cache what's immutable.** SEC filings forever, financials for 24h, quotes never.
5. **Structured errors.** The host LLM can reason about errors and communicate them to the user.

## Marketplace Integration

- First listing on mcp-marketplace.io
- Tests: submission flow, security scanning, install config generation, freemium gating, Stripe payment
- Listed under "Finance" category
- Security scanned by marketplace's 3-layer scanner
- Install configs generated for all supported MCP host apps

## Future Considerations

- Swap yfinance for premium data APIs (Financial Datasets, Polygon) to increase data quality and defensibility
- Collective Intelligence Layer: when hosted via HTTP, aggregate usage patterns can improve tool quality for all users (see marketplace KB for full vision)
- MCP Apps extension: rich UI for financial dashboards inline in conversations
