# https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server Project Manual

Generated at: 2026-05-28 02:58:17 UTC

## Table of Contents

- [Overview](#overview)
- [Installation Guide](#installation)
- [Configuration Guide](#configuration)
- [Quick Start Guide](#quick-start)
- [Usage Guide](#usage-guide)
- [API Reference](#api-reference)
- [System Architecture](#architecture)
- [Tool Development Guide](#tool-development)
- [Contributing Guide](#contributing)
- [Troubleshooting](#troubleshooting)

<a id='overview'></a>

## Overview

### Related Pages

Related topics: [Installation Guide](#installation), [System Architecture](#architecture), [Quick Start Guide](#quick-start)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)
- [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)
- [package.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json)
- [server.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)
- [src/tools/quotes.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)
- [src/tools/sec-filings.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/sec-filings.ts)
- [src/toolception-adapters/ToolCollector.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/ToolCollector.ts)
- [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md)
- [AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/AGENTS.md)
</details>

# Overview

The Financial Modeling Prep MCP Server is a Model Context Protocol (MCP) server implementation that exposes 250+ financial data tools to AI assistants through the Financial Modeling Prep (FMP) API. Built on Node.js with the toolception framework and Fastify HTTP server, it provides a bridge between AI assistants and comprehensive financial market data including stocks, ETFs, crypto, forex, commodities, economics, and more.

Source: [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

## Purpose and Scope

The server serves as an intermediary layer that:

1. **Translates MCP tool calls** into FMP API requests
2. **Manages authentication** using FMP API tokens
3. **Organizes 250+ endpoints** into logical tool sets
4. **Provides multiple deployment modes** for different use cases

The MCP protocol enables AI assistants like Claude to interact with financial data tools using a standardized interface. The FMP API provides underlying market data including real-time quotes, financial statements, SEC filings, insider trading data, and macroeconomic indicators.

Source: [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)

## Architecture

The server follows a layered architecture with clear separation of concerns:

```mermaid
graph TD
    subgraph "MCP Protocol Layer"
        MCP[MCP Protocol<br/>Client Connection]
    end
    
    subgraph "Toolception Framework"
        Meta[Meta-Tools<br/>Tool Discovery]
        Sets[Tool Set<br/>Management]
    end
    
    subgraph "Tools Layer"
        T1[Quotes Tools]
        T2[Statements Tools]
        T3[SEC Filings Tools]
        TN[...25 more<br/>tool modules]
    end
    
    subgraph "API Client Layer"
        FMP[FMP Client]
        DC[Domain Clients<br/>28 total]
    end
    
    subgraph "External Services"
        FMP_API[Financial Modeling<br/>Prep API]
    end
    
    MCP --> Meta
    MCP --> Sets
    Meta --> T1
    Meta --> T2
    Meta --> T3
    Sets --> TN
    T1 --> FMP
    T2 --> FMP
    T3 --> DC
    TN --> DC
    FMP --> FMP_API
    DC --> FMP_API
```

### Directory Structure

| Directory | Purpose |
|-----------|---------|
| `src/api/` | HTTP clients for FMP API endpoints |
| `src/tools/` | MCP tool registrations (28 modules) |
| `src/toolception-adapters/` | Framework integration for dynamic tool management |
| `src/server-mode-enforcer/` | Mode configuration singleton |
| `src/constants/` | Tool sets and defaults |
| `src/endpoints/` | HTTP endpoints (health, ready) |
| `src/prompts/` | MCP prompt definitions |

Source: [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)

## Server Modes

The server supports three operational modes configured at startup:

| Mode | Description | Meta-Tools | Tool Loading |
|------|-------------|------------|--------------|
| **Dynamic** | Runtime tool discovery and loading | 5 meta-tools available | Tools loaded on demand |
| **Static** | Pre-configured tool sets | None | Fixed at startup |
| **All Tools** | Complete tool suite | None | All 250+ tools at startup |

The mode is determined by the `DYNAMIC_TOOL_DISCOVERY` environment variable or `--dynamic-tool-discovery` CLI flag. In Dynamic mode, users can load specific tool sets using meta-tools rather than receiving all tools at once.

Source: [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)
Source: [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)

## Tool Categories

The server exposes 250+ tools organized into 24 categories:

| Category | Example Tools |
|----------|---------------|
| Search | Symbol search, company lookup |
| Directory & Symbol Lists | Stock lists, ETF compositions |
| Company Information | Profile, logo, description |
| Financial Statements | Income statement, balance sheet, cash flow |
| Financial Metrics & Analysis | Key metrics, ratios, valuation |
| Technical Indicators | Moving averages, RSI, MACD |
| Quotes & Price Data | Real-time quotes, historical prices |
| Market Indexes & Performance | S&P 500, Dow Jones, sector performance |
| Market Data | Pre/after market, market movers |
| News & Press Releases | Company news, press releases |
| SEC Filings | 8-K, 10-K, 10-Q filings |
| Insider & Institutional Trading | Insider trades, institutional holdings |
| ETFs & Funds | ETF holdings, fund analysis |
| Government Trading | Senate/house trading data |
| Cryptocurrency & Forex | Crypto prices, forex rates |
| Earnings | Earnings calendar, estimates, surprises |
| Special Data Sets | ESG scores, supply chain, bankruptcy |
| Commodities | Gold, silver, oil prices |
| Economics | GDP, inflation, employment data |
| Bulk Data Tools | Batch operations for multiple symbols |

Source: [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

## Configuration Options

### Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| `FMP_ACCESS_TOKEN` | Yes | Financial Modeling Prep API access token |
| `PORT` | No | HTTP server port (default: 3000) |
| `DYNAMIC_TOOL_DISCOVERY` | No | Enable dynamic tool discovery mode |
| `FMP_TOOL_SETS` | No | Comma-separated list of tool sets to load |

### CLI Arguments

| Argument | Description |
|----------|-------------|
| `--fmp-token` | FMP API access token |
| `--port` | HTTP server port |
| `--dynamic-tool-discovery` | Enable dynamic tool discovery |
| `--fmp-tool-sets` | Comma-separated tool sets |

Source: [server.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)

## Authentication

The server uses API key authentication where the FMP token is passed as a query parameter to the FMP API (not as HTTP headers). Token precedence follows this order:

1. **Context token** — Provided per-session by the MCP client
2. **Instance token** — Set via `--fmp-token` CLI argument
3. **Environment variable** — Set via `FMP_ACCESS_TOKEN`

Source: [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)

> ⚠️ **Known Issue**: Users have reported difficulty setting the API key via certain registry interfaces (Smithery.ai). The recommended approach is to set `FMP_ACCESS_TOKEN` as an environment variable or use the `--fmp-token` CLI argument directly.

Source: [Issue #81](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/81)

## Key Invariants

Understanding these fundamental rules is essential for working with the server:

| # | Rule | Description |
|---|------|-------------|
| 1 | **API Key as Query Parameter** | FMP requires `?apikey=` format, never headers |
| 2 | **Token Precedence** | Context > Instance > Environment |
| 3 | **Fail-Fast Validation** | Invalid tool sets cause `process.exit(1)` at startup |
| 4 | **Session Restrictions** | Only `FMP_ACCESS_TOKEN` takes effect per-session |
| 5 | **Read-Only Tools** | All tools are read-only data fetchers |
| 6 | **Error Handling** | Tools never throw; return `{ isError: true }` |

Source: [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)

## Error Handling Pattern

All tool handlers follow a strict pattern to ensure MCP protocol compatibility:

```typescript
async function toolHandler(params) {
  try {
    const results = await client.method(params);
    return {
      content: [{ type: "text", text: JSON.stringify(results, null, 2) }],
    };
  } catch (error) {
    return {
      content: [
        {
          type: "text",
          text: `Error: ${error instanceof Error ? error.message : String(error)}`,
        },
      ],
      isError: true,
    };
  }
}
```

**Important**: Tools must never throw exceptions. The MCP protocol expects errors in the response object, not as thrown exceptions.

Source: [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)

## Tool Registration

Tools are registered using the MCP SDK's `server.tool()` method with Zod schemas for parameter validation:

```typescript
server.tool(
  "getQuote",
  "Access real-time stock quotes with the FMP Stock Quote API.",
  {
    symbol: z.string().describe("Stock symbol"),
  },
  async ({ symbol }) => {
    // handler implementation
  }
);
```

Source: [src/tools/quotes.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)

## Deployment Options

### Hosted Instance (Fastest)

Connect directly to the production server without installation:

```
https://financial-modeling-prep-mcp-server-production.up.railway.app/mcp
```

### Self-Hosted via NPM

```bash
npm install -g financial-modeling-prep-mcp-server
fmp-mcp --fmp-token=YOUR_FMP_API_KEY
```

### Self-Hosted via NPX

```bash
npx financial-modeling-prep-mcp-server --fmp-token=YOUR_FMP_API_KEY
```

### Docker

```bash
docker build -t fmp-mcp .
docker run -e FMP_ACCESS_TOKEN=YOUR_FMP_API_KEY -p 3000:3000 fmp-mcp
```

Source: [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

## Runtime Requirements

| Requirement | Minimum Version |
|-------------|-----------------|
| Node.js | >= 25.3.0 |
| npm | >= 11.11.0 |

Source: [package.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json)

## Known Limitations and Issues

### Python Reserved Keywords in Parameter Names

Some tool schemas use parameter names that conflict with Python reserved keywords, causing issues with Python-based MCP clients. For example, the `from` parameter in SEC filings tools conflicts with Python's `from` keyword.

> **Status**: Version 2.6.9 addressed this by renaming `from` to `from_date` in affected schemas.

Source: [Issue #93](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/93)
Source: [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md)

### Batch Quote Endpoint False Positive

The `getBatchQuotesShort` tool may incorrectly return "ACCESS DENIED" errors for Ultimate plan users. This is a false positive in the MCP layer's plan-gate logic that blocks the request before it reaches the FMP API.

> **Status**: This issue is tracked in [Issue #100](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/100).

Source: [Issue #100](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/100)

## Registry Integration

The server is listed on multiple MCP registries for discovery:

| Registry | URL |
|----------|-----|
| Smithery.ai | https://smithery.ai/server/@imbenrabi/financial-modeling-prep-mcp-server |
| Glama.ai | https://glama.ai/mcp/servers/@imbenrabi/financial-modeling-prep-mcp-server |
| MCP Registry | https://registry.modelcontextprotocol.io/servers/io.github.imbenrabi/financial-modeling-prep-mcp-server |

Source: [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

## Version History

| Version | Release Date | Key Changes |
|---------|--------------|-------------|
| 2.6.10 | 2026-04-30 | Latest release |
| 2.6.9 | 2026-04-24 | Fixed Python reserved keyword issues (`from` → `from_date`) |
| 2.6.8 | 2026-02-03 | Improved codebase organization |
| 2.6.7 | 2026-02-02 | Clarified session configuration restrictions |

Source: [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md)

## See Also

- [Configuration Guide](docs/CONFIGURATION.md) — Detailed configuration options and environment setup
- [Usage Guide](docs/USAGE.md) — Client-specific setup and session management
- [API Reference](docs/API_REFERENCE.md) — Complete tool catalog with parameters
- [AGENTS.md](AGENTS.md) — Non-obvious pitfalls, invariants, and anti-patterns
- [Contributing Guide](CONTRIBUTING.md) — Development setup and contribution guidelines

---

<a id='installation'></a>

## Installation Guide

### Related Pages

Related topics: [Configuration Guide](#configuration), [Troubleshooting](#troubleshooting)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [package.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json)
- [Dockerfile](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/Dockerfile)
- [server.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)
- [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)
- [scripts/verify-installation-methods.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/scripts/verify-installation-methods.ts)
- [docs/USAGE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/USAGE.md)
</details>

# Installation Guide

This guide covers all supported methods for installing and deploying the Financial Modeling Prep MCP Server. The server provides 250+ financial data tools via the Model Context Protocol (MCP), enabling AI assistants to access real-time stock quotes, financial statements, SEC filings, and other market data through the [Financial Modeling Prep API](https://financialmodelingprep.com/).

## Prerequisites

Before installing the MCP server, ensure your environment meets the following requirements:

| Requirement | Minimum Version | Notes |
|-------------|-----------------|-------|
| Node.js | >= 25.3.0 | Required for ES modules and modern async features |
| npm | >= 11.11.0 | Required for package management |
| Docker | 20.x+ | Optional, for containerized deployment |
| FMP API Key | Valid subscription | Required for API access |

Source: [package.json:engines](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json)

### Verifying Node.js Version

```bash
node --version
npm --version
```

If you need to upgrade Node.js, consider using [nvm](https://github.com/nvm-sh/nvm) or downloading directly from [nodejs.org](https://nodejs.org/).

## Installation Methods

The FMP MCP Server supports multiple installation approaches depending on your use case and infrastructure preferences.

### Hosted Instance (No Installation)

The fastest way to get started without any local installation:

```
https://financial-modeling-prep-mcp-server-production.up.railway.app/mcp
```

Provide your `FMP_ACCESS_TOKEN` in session configuration and connect directly. This method requires no installation but relies on an external service.

Source: [README.md#Quick-Start](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

### NPX (Zero Install)

Use `npx` to run the server without global installation:

```bash
npx financial-modeling-prep-mcp-server --fmp-token=YOUR_FMP_API_KEY
```

This approach downloads the package temporarily and runs it. Suitable for quick testing or one-off usage.

Source: [README.md#Self-Hosted](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

### NPM Global Installation

For persistent local installations:

```bash
npm install -g financial-modeling-prep-mcp-server
```

After installation, verify the binary is available:

```bash
fmp-mcp --help
```

Run the server with your API token:

```bash
fmp-mcp --fmp-token=YOUR_FMP_API_KEY
```

Source: [package.json#bin](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json)

### Docker Installation

For containerized deployments, build and run the server using Docker:

#### Building the Image

```bash
docker build -t fmp-mcp-server .
```

The Dockerfile uses a multi-stage build to compile TypeScript and create a minimal production image.

Source: [Dockerfile](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/Dockerfile)

#### Running the Container

```bash
docker run -d \
  --name fmp-mcp \
  -p 3000:3000 \
  -e FMP_ACCESS_TOKEN=YOUR_FMP_API_KEY \
  fmp-mcp-server
```

#### Docker Compose Example

```yaml
version: '3.8'

services:
  fmp-mcp:
    build: .
    ports:
      - "3000:3000"
    environment:
      - FMP_ACCESS_TOKEN=${FMP_ACCESS_TOKEN}
    restart: unless-stopped
```

### MCP Registry Installation

The server is listed on multiple MCP registries for easy discovery and integration with MCP clients:

| Registry | URL |
|----------|-----|
| Smithery.ai | https://smithery.ai/server/@imbenrabi/financial-modeling-prep-mcp-server |
| Glama.ai | https://glama.ai/mcp/servers/@imbenrabi/financial-modeling-prep-mcp-server |
| MCP Registry | https://registry.modelcontextprotocol.io/servers/io.github.imbenrabi/financial-modeling-prep-mcp-server |

Source: [README.md#Registries](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

## Configuration

### Command-Line Arguments

The server accepts the following CLI arguments:

| Argument | Description | Default |
|----------|-------------|---------|
| `--fmp-token` | FMP API access token | From environment |
| `--port` | HTTP server port | 3000 |
| `--dynamic-tool-discovery` | Enable Dynamic mode with meta-tools | false |
| `--fmp-tool-sets` | Comma-separated list of tool sets | all |

Example:

```bash
fmp-mcp --fmp-token=YOUR_KEY --port=8080 --dynamic-tool-discovery
```

Source: [server.json#arguments](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)

### Environment Variables

| Variable | Description | Required |
|----------|-------------|----------|
| `FMP_ACCESS_TOKEN` | Financial Modeling Prep API key | Yes |
| `PORT` | HTTP server port | No |
| `DYNAMIC_TOOL_DISCOVERY` | Enable Dynamic mode | No |
| `FMP_TOOL_SETS` | Comma-separated tool set names | No |

Source: [server.json#environmentVariables](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)

### Server Modes

The FMP MCP Server operates in three modes:

```mermaid
graph TD
    A[FMP MCP Server Startup] --> B{Mode Selection}
    B -->|Dynamic| C[Load Meta-Tools + All Tool Definitions]
    B -->|Static| D[Load Selected Tool Sets at Startup]
    B -->|All Tools| E[Load All 253+ Tools]
    
    C --> F[Runtime Tool Discovery Available]
    D --> G[Meta-Tools Disabled]
    E --> H[Full Tool Suite]
```

- **Dynamic Mode**: Provides 5 meta-tools to load/unload tool sets at runtime
- **Static Mode**: Pre-loads specific tool sets defined at startup
- **All Tools Mode**: Loads the complete tool suite (default)

Source: [README.md#Features](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

## Token Configuration

### Obtaining an FMP API Key

1. Sign up at [financialmodelingprep.com](https://financialmodelingprep.com/)
2. Navigate to your dashboard
3. Copy your API key

### Token Precedence

The server uses the following precedence order for API token resolution:

1. **Context/Session Token**: Provided during MCP session initialization
2. **Instance Configuration**: Command-line `--fmp-token` argument
3. **Environment Variable**: `FMP_ACCESS_TOKEN` in the environment

Source: [CLAUDE.md#Key-Invariants](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)

### Common Configuration Issues

#### Issue: "Missing FMP_API_TOKEN"

Users have reported difficulty setting the FMP API key through certain MCP clients, particularly when using Smithery.ai or similar registry-based connections. This manifests as connection failures or "Missing FMP_API_TOKEN" errors.

**Resolution Steps:**

1. Verify the environment variable is set: `echo $FMP_ACCESS_TOKEN`
2. If using Docker, pass the variable: `-e FMP_ACCESS_TOKEN=your_key`
3. If using command line, use the explicit flag: `--fmp-token=your_key`
4. For Smithery.ai integration, ensure the OAuth fields are properly configured in Settings > Apps

Source: [GitHub Issue #81](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/81)

## Verification

After installation, verify the server is functioning correctly:

### Health Check Endpoint

```bash
curl http://localhost:3000/health
```

Expected response:

```json
{
  "status": "healthy"
}
```

### CLI Help Verification

```bash
fmp-mcp --help
```

Expected output should display all available command-line options including `--fmp-token`, `--port`, and `--dynamic-tool-discovery`.

Source: [scripts/verify-installation-methods.ts#HELP_PATTERNS](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/scripts/verify-installation-methods.ts)

### Required Files Verification

The installation should include these core files:

| File | Purpose |
|------|---------|
| `dist/index.js` | Server entry point |
| `README.md` | Documentation |
| `LICENSE` | Apache 2.0 license |
| `server.json` | MCP server manifest |

Source: [scripts/verify-installation-methods.ts#REQUIRED_FILES](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/scripts/verify-installation-methods.ts)

## Build from Source

For development or custom deployments, build the server from source:

### Clone and Setup

```bash
git clone https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server.git
cd Financial-Modeling-Prep-MCP-Server
npm install
```

### Build

```bash
npm run build
```

This compiles TypeScript to JavaScript in the `dist/` directory.

Source: [package.json#scripts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json)

### Development Mode

For active development with hot-reload:

```bash
npm run dev
```

### Production Start

```bash
npm start
```

## Integration with AI Clients

### Claude Desktop

Add to your Claude Desktop configuration file:

```json
{
  "mcpServers": {
    "financial-modeling-prep": {
      "command": "fmp-mcp",
      "args": ["--fmp-token", "YOUR_API_KEY"]
    }
  }
}
```

### Custom MCP Clients

Connect using the HTTP/SSE endpoint:

```
http://localhost:3000/mcp
```

Configure your MCP client to use this URL with session headers for authentication.

Source: [docs/USAGE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/USAGE.md)

## Troubleshooting

### Installation Fails with Permission Error

If you encounter `EACCES` errors during global npm installation:

```bash
sudo npm install -g financial-modeling-prep-mcp-server
```

Or configure npm to use a different directory:

```bash
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH
```

### Server Starts but Returns 401

A 401 Unauthorized response typically means:

1. The FMP API key is invalid or expired
2. The token is not being passed correctly to the server
3. Your FMP subscription has expired

Verify your token is valid by checking the [FMP dashboard](https://financialmodelingprep.com/plan).

### Docker Container Exits Immediately

Check container logs:

```bash
docker logs fmp-mcp
```

Common causes include missing `FMP_ACCESS_TOKEN` environment variable or port conflicts.

### MCP Client Cannot Connect

Ensure the server is listening on the correct interface:

```bash
fmp-mcp --port=3000
```

Verify the endpoint is accessible:

```bash
curl http://localhost:3000/health
```

## See Also

- [Configuration Reference](docs/CONFIGURATION.md) — Detailed configuration options
- [Usage Guide](docs/USAGE.md) — Client integration and session management
- [API Reference](docs/API_REFERENCE.md) — Complete tool catalog
- [Architecture Overview](docs/ARCHITECTURE.md) — System design and components
- [Troubleshooting Guide](docs/TROUBLESHOOTING.md) — Common issues and solutions

---

<a id='configuration'></a>

## Configuration Guide

### Related Pages

Related topics: [Installation Guide](#installation), [Quick Start Guide](#quick-start), [Troubleshooting](#troubleshooting)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [docs/CONFIGURATION.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/CONFIGURATION.md)
- [src/schemas/SessionConfigSchema.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/schemas/SessionConfigSchema.ts)
- [src/server-mode-enforcer/ServerModeEnforcer.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/server-mode-enforcer/ServerModeEnforcer.ts)
- [src/constants/toolSets.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/constants/toolSets.ts)
- [src/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/index.ts)
- [server.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)
- [src/toolception-adapters/ToolCollector.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/ToolCollector.ts)
- [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)
- [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md)
</details>

# Configuration Guide

This guide covers all configuration options for the Financial Modeling Prep MCP Server, including environment variables, CLI arguments, server modes, tool set management, and session-level configuration. Understanding these options is essential for proper deployment and operation.

## Overview

The FMP MCP Server provides flexible configuration through multiple mechanisms:

- **Environment Variables**: Persistent configuration for containerized or production deployments
- **CLI Arguments**: Quick configuration for command-line usage
- **Session Configuration**: Per-request authentication via MCP session headers

Configuration follows a clear precedence hierarchy, and the server enforces validation at startup to prevent runtime errors. Source: [docs/CONFIGURATION.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/CONFIGURATION.md)

## Configuration Precedence

The server resolves configuration values using a strict precedence order. Higher-precedence sources override lower-precedence ones:

```mermaid
graph TD
    A["1. Session Config<br/>(MCP Request Headers)"] --> B["2. CLI Arguments"]
    A --> B
    B --> C["3. Environment Variables"]
    B --> C
    C --> D["4. Defaults"]
    
    style A fill:#90EE90
    style B fill:#FFE4B5
    style C fill:#ADD8E6
    style D fill:#D3D3D3
```

**Token Precedence** (for authentication):
1. `FMP_ACCESS_TOKEN` from session configuration headers
2. `--fmp-token` CLI argument
3. `FMP_ACCESS_TOKEN` environment variable

Source: [CLAUDE.md - Key Invariants](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)

## Environment Variables

Environment variables provide the most common configuration method for self-hosted deployments.

### Core Configuration

| Variable | Type | Default | Description |
|----------|------|---------|-------------|
| `FMP_ACCESS_TOKEN` | string | - | Financial Modeling Prep API access token |
| `PORT` | number | `3000` | HTTP server port |
| `NODE_ENV` | string | `production` | Node environment (`development`, `production`) |

### Tool Set Configuration

| Variable | Type | Default | Description |
|----------|------|---------|-------------|
| `FMP_TOOL_SETS` | string | `"all"` | Comma-separated list of tool sets to load |
| `DYNAMIC_TOOL_DISCOVERY` | boolean | `false` | Enable dynamic tool discovery mode |

### Security

| Variable | Type | Default | Description |
|----------|------|---------|-------------|
| `ALLOWED_ORIGINS` | string | `"*"` | Comma-separated list of allowed CORS origins |
| `RATE_LIMIT_MAX` | number | `100` | Maximum requests per window |
| `RATE_LIMIT_WINDOW` | number | `60000` | Rate limit window in milliseconds |

Source: [server.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)

### Setting Environment Variables

**Linux/macOS:**
```bash
export FMP_ACCESS_TOKEN="your_fmp_api_key"
export FMP_TOOL_SETS="quotes,statements,news"
export PORT=3000
```

**Docker:**
```bash
docker run -e FMP_ACCESS_TOKEN="your_fmp_api_key" \
           -e FMP_TOOL_SETS="quotes,statements" \
           -p 3000:3000 \
           imbentabi/financial-modeling-prep-mcp-server
```

**Docker Compose:**
```yaml
services:
  fmp-mcp:
    image: imbentabi/financial-modeling-prep-mcp-server
    environment:
      - FMP_ACCESS_TOKEN=${FMP_ACCESS_TOKEN}
      - FMP_TOOL_SETS=quotes,statements,news
      - PORT=3000
    ports:
      - "3000:3000"
```

## CLI Arguments

The server accepts CLI arguments for quick configuration:

```bash
npx financial-modeling-prep-mcp-server [options]
```

### Available Options

| Argument | Short | Type | Default | Description |
|----------|-------|------|---------|-------------|
| `--fmp-token` | `-t` | string | - | FMP API access token |
| `--port` | `-p` | number | `3000` | Server port |
| `--fmp-tool-sets` | - | string | `"all"` | Tool sets to load |
| `--dynamic-tool-discovery` | - | boolean | `false` | Enable dynamic discovery |
| `--allowed-origins` | - | string | `"*"` | CORS origins |
| `--help` | `-h` | - | - | Show help |

### Examples

```bash
# Basic usage with token
npx financial-modeling-prep-mcp-server --fmp-token=YOUR_FMP_API_KEY

# Custom port
npx financial-modeling-prep-mcp-server --fmp-token=YOUR_FMP_API_KEY --port=8080

# Specific tool sets
npx financial-modeling-prep-mcp-server --fmp-token=YOUR_FMP_API_KEY --fmp-tool-sets=quotes,statements

# Dynamic discovery mode
npx financial-modeling-prep-mcp-server --fmp-token=YOUR_FMP_API_KEY --dynamic-tool-discovery
```

Source: [server.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)

## Session Configuration

Session configuration allows per-request authentication through MCP session headers. This is the highest-precedence configuration source.

### Supported Session Parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `FMP_ACCESS_TOKEN` | string | FMP API access token for this session |

### Important Limitations

> **Note**: Only `FMP_ACCESS_TOKEN` takes effect at the session level. The following parameters exist in the schema but are **not** honored per-session:
> - `FMP_TOOL_SETS`
> - `DYNAMIC_TOOL_DISCOVERY`

The server mode is fixed at startup and cannot be changed during runtime. Source: [CHANGELOG.md - v2.6.7](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md)

### Setting Session Headers

When connecting to the hosted instance or making direct MCP requests:

```json
{
  "jsonrpc": "2.0",
  "method": "initialize",
  "params": {
    "headers": {
      "FMP_ACCESS_TOKEN": "your_fmp_api_key"
    }
  }
}
```

### Smithery.ai Integration

When using Smithery.ai to configure the MCP server, ensure you set the `FMP_ACCESS_TOKEN` in the App configuration under **Settings > Apps**. The token must be provided even if OAuth fields are left blank.

> **Troubleshooting**: If you encounter "ACCESS DENIED" errors despite having a valid token, verify that the token is properly set in the session configuration. See [Issue #81](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/81) for common pitfalls.

## Server Modes

The server operates in one of three modes, determined at startup:

```mermaid
graph TD
    A[Server Start] --> B{Mode Configuration}
    B -->|Dynamic| C["Dynamic Mode<br/>(Meta-tools enabled)<br/>250+ tools + 5 meta-tools"]
    B -->|Static| D["Static Mode<br/>(Pre-loaded toolsets)<br/>Selected tools only"]
    B -->|All| E["All Tools Mode<br/>(Default)<br/>250+ tools"]
    
    style C fill:#90EE90
    style D fill:#FFE4B5
    style E fill:#ADD8E6
```

### Mode Comparison

| Mode | Meta-Tools | Tool Sets | Use Case |
|------|------------|-----------|----------|
| Dynamic | Yes (5 meta-tools) | Runtime selection | Flexible tooling |
| Static | No | Pre-selected at startup | Predictable scope |
| All Tools | No | All 250+ tools | Full access |

### Dynamic Mode (Meta-Tools)

When `--dynamic-tool-discovery` is enabled, the server exposes meta-tools for runtime tool management:

| Meta-Tool | Description |
|-----------|-------------|
| `enableToolSet` | Load a specific tool set at runtime |
| `disableToolSet` | Unload a specific tool set |
| `listToolSets` | List available tool sets |
| `getActiveToolSets` | Show currently loaded tool sets |
| `searchTools` | Search for tools by name or description |

Source: [src/toolception-adapters/ToolCollector.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/ToolCollector.ts)

## Tool Sets

Tool sets group related tools for selective loading. The server includes 24 predefined tool sets covering different financial data categories.

### Available Tool Sets

| Tool Set | Description | Tool Count |
|----------|-------------|------------|
| `search` | Symbol search tools | ~5 |
| `directory` | Company directory and lists | ~8 |
| `company` | Company information | ~10 |
| `statements` | Financial statements | ~15 |
| `metrics` | Financial metrics | ~12 |
| `technicals` | Technical indicators | ~10 |
| `quotes` | Real-time quotes | ~8 |
| `indexes` | Market indexes | ~6 |
| `market` | Market data | ~8 |
| `news` | News and press releases | ~5 |
| `sec-filings` | SEC filings | ~6 |
| `insider` | Insider trading | ~8 |
| `etf` | ETF data | ~8 |
| `government` | Government trading | ~5 |
| `crypto` | Cryptocurrency data | ~6 |
| `forex` | Foreign exchange | ~5 |
| `earnings` | Earnings data | ~8 |
| `special` | Special data sets | ~6 |
| `commodities` | Commodities data | ~5 |
| `economics` | Economic indicators | ~6 |
| `bulk` | Bulk data tools | ~5 |

### Loading Specific Tool Sets

```bash
# Via CLI
npx financial-modeling-prep-mcp-server \
  --fmp-token=YOUR_FMP_API_KEY \
  --fmp-tool-sets=quotes,statements,news

# Via environment variable
export FMP_TOOL_SETS="quotes,statements,news"
```

### Loading Multiple Tool Sets

```bash
# Comma-separated list
--fmp-tool-sets=quotes,statements,indexes,crypto

# All tools (default)
--fmp-tool-sets=all
```

Source: [src/constants/toolSets.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/constants/toolSets.ts)

## Validation and Startup

The server performs strict validation at startup to ensure configuration correctness.

### Validation Rules

```mermaid
graph LR
    A[Startup] --> B{Token Valid?}
    B -->|No| C[Warning - API calls will fail]
    B -->|Yes| D{Tool Sets Valid?}
    D -->|Invalid| E[process.exit(1)]
    D -->|Valid| F{Mode Enforced?}
    F -->|Yes| G[Server Ready]
    E --> H[Error logged]
    
    style C fill:#FFE4B5
    style E fill:#FFB6C1
    style G fill:#90EE90
```

### Key Invariants

1. **API Key as Query Parameter**: FMP requires the API key as a query parameter (`?apikey=`), never as a header
2. **Token Precedence**: Context > Instance > Environment
3. **Fail-Fast Validation**: Invalid tool sets cause `process.exit(1)` at startup
4. **Session Restrictions**: Only `FMP_ACCESS_TOKEN` takes effect at session level
5. **Read-Only Tools**: All tools are read-only data fetchers
6. **Error Handling**: Tools never throw; return `{ isError: true }`

Source: [CLAUDE.md - Key Invariants](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)

### Startup Warnings

The server logs warnings when configuration may cause issues:

```bash
[FMP MCP Server] No server-level FMP access token configured.
Provide via: (1) FMP_ACCESS_TOKEN env var, (2) --fmp-token CLI arg,
or (3) session config {"FMP_ACCESS_TOKEN":"your_token"}.
Without auth, API calls will fail.
```

Source: [src/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/index.ts)

## Authentication Configuration

### Obtaining an FMP API Token

1. Sign up at [Financial Modeling Prep](https://financialmodelingprep.com/)
2. Navigate to your dashboard
3. Copy your API key from the API section

### Token Configuration Examples

**Hosted Instance (Smithery.ai, Claude.ai, etc.):**
Set `FMP_ACCESS_TOKEN` in your client's session configuration.

**Self-Hosted (npm):**
```bash
npx financial-modeling-prep-mcp-server --fmp-token=YOUR_API_KEY
```

**Self-Hosted (Docker):**
```bash
docker run -e FMP_ACCESS_TOKEN=YOUR_API_KEY \
           -p 3000:3000 \
           imbentabi/financial-modeling-prep-mcp-server
```

**Environment File (.env):**
```bash
FMP_ACCESS_TOKEN=YOUR_API_KEY
PORT=3000
FMP_TOOL_SETS=quotes,statements
```

### Authentication Flow

```mermaid
sequenceDiagram
    participant Client
    participant MCP_Server
    participant FMP_API
    
    Client->>MCP_Server: MCP Request + FMP_ACCESS_TOKEN
    MCP_Server->>MCP_Server: Validate token presence
    MCP_Server->>FMP_API: API Request + apikey query param
    FMP_API->>MCP_Server: Financial Data
    MCP_Server->>Client: MCP Response
```

## Known Configuration Issues

### Issue: FMP API KEY Impossible to Set

**Symptom**: "ACCESS DENIED" error claiming missing `FMP_API_TOKEN`

**Common Causes**:
1. Token not provided in session configuration
2. Using wrong token variable name (`FMP_API_TOKEN` instead of `FMP_ACCESS_TOKEN`)
3. Smithery.ai app not configured with the token

**Solution**:
```bash
# Verify token is set
echo $FMP_ACCESS_TOKEN

# Set explicitly
export FMP_ACCESS_TOKEN="your_actual_token"

# For Smithery, ensure Settings > Apps has the token configured
```

Source: [Issue #81](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/81)

### Issue: Batch Quote Endpoint False Positive

**Symptom**: Ultimate plan users get "ACCESS DENIED" for batch-quote endpoint

**Cause**: The MCP layer performs plan-gating before the request reaches FMP API. This is a known false positive in the plan validation logic.

**Status**: Reported in [Issue #100](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/100)

### Issue: Python Reserved Keywords in Parameters

**Symptom**: Python MCP clients fail to parse tool schemas

**Cause**: Some tool parameters used reserved Python keywords (e.g., `from`, `class`) or invalid identifiers

**Resolution**: In v2.6.9, the `from` parameter was renamed to `from_date` to avoid Python conflicts.

Source: [Issue #93](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/93), [CHANGELOG.md v2.6.9](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md)

## Production Deployment

### Recommended Production Configuration

```yaml
# docker-compose.yml
services:
  fmp-mcp:
    image: imbentabi/financial-modeling-prep-mcp-server:latest
    environment:
      - FMP_ACCESS_TOKEN=${FMP_ACCESS_TOKEN}
      - FMP_TOOL_SETS=all
      - PORT=3000
      - NODE_ENV=production
      - ALLOWED_ORIGINS=https://your-app.com
      - RATE_LIMIT_MAX=100
      - RATE_LIMIT_WINDOW=60000
    deploy:
      resources:
        limits:
          cpus: '2'
          memory: 1G
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
```

### Health Check Endpoint

The server exposes a health check endpoint:

```
GET http://localhost:3000/health
```

Response:
```json
{
  "status": "healthy",
  "version": "2.6.10",
  "timestamp": "2026-04-30T00:00:00.000Z"
}
```

### Readiness Check

```
GET http://localhost:3000/ready
```

Returns `200 OK` when the server is ready to accept requests.

## Configuration Reference

### Complete Environment Variables

```bash
# Required
FMP_ACCESS_TOKEN=your_fmp_api_key

# Server
PORT=3000
NODE_ENV=production

# Tool Sets
FMP_TOOL_SETS=all  # or: quotes,statements,news,crypto
DYNAMIC_TOOL_DISCOVERY=false

# Security
ALLOWED_ORIGINS=https://your-domain.com
RATE_LIMIT_MAX=100
RATE_LIMIT_WINDOW=60000

# Logging
LOG_LEVEL=info
```

### Complete CLI Options

```bash
fmp-mcp [options]

Options:
  -t, --fmp-token <token>        FMP API access token
  -p, --port <port>              Server port (default: 3000)
  --fmp-tool-sets <sets>         Comma-separated tool sets
  --dynamic-tool-discovery       Enable dynamic tool discovery
  --allowed-origins <origins>   CORS allowed origins
  -h, --help                     Show help
```

## See Also

- [Usage Guide](USAGE.md) — Client-specific setup and session management
- [API Reference](API_REFERENCE.md) — Complete tool catalog
- [Architecture Overview](ARCHITECTURE.md) — Server architecture and components
- [Contributing Guide](../CONTRIBUTING.md) — Development setup

---

<a id='quick-start'></a>

## Quick Start Guide

### Related Pages

Related topics: [Installation Guide](#installation), [Configuration Guide](#configuration), [Usage Guide](#usage-guide)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)
- [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)
- [docs/USAGE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/USAGE.md)
- [package.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json)
- [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)
- [src/toolception-adapters/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/AGENTS.md)
- [server.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)
</details>

# Quick Start Guide

This guide provides a rapid path to getting the Financial Modeling Prep MCP Server operational. It covers installation methods, authentication configuration, server modes, and resolution of common setup issues.

## Overview

The Financial Modeling Prep MCP Server is a Model Context Protocol (MCP) server that exposes 250+ financial data tools to AI assistants. It acts as a bridge between AI clients (such as Claude Desktop) and the Financial Modeling Prep API, enabling real-time access to stock quotes, financial statements, SEC filings, market data, and more.

**Key capabilities:**
- 250+ financial data tools across 24 categories
- Three server modes: Dynamic (meta-tools for on-demand loading), Static (pre-loaded toolsets), and All Tools
- HTTP/SSE transport for compatibility with Claude.ai, Claude Desktop, and MCP registries
- Token-based authentication with flexible configuration options

Source: [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

## Prerequisites

Before beginning, ensure your environment meets the following requirements:

| Requirement | Version | Notes |
|-------------|---------|-------|
| Node.js | ≥ 25.3.0 | Required for running the server |
| npm | ≥ 11.11.0 | For package installation |
| FMP API Key | Valid subscription | Required for data access |

Source: [package.json:34-36](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json#L34-L36)

## Installation Methods

The server can be deployed using several methods, ranging from zero-configuration hosted access to full self-hosting.

### Hosted Instance (Fastest)

The hosted instance requires no installation. Connect directly using the provided endpoint:

```
https://financial-modeling-prep-mcp-server-production.up.railway.app/mcp
```

Provide your `FMP_ACCESS_TOKEN` in your session configuration to authenticate.

Source: [README.md:19-23](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md#L19-L23)

### NPM Installation (Self-Hosted)

Install globally via npm for local execution:

```bash
npm install -g financial-modeling-prep-mcp-server
```

Run with your API token:

```bash
npx financial-modeling-prep-mcp-server --fmp-token=YOUR_FMP_API_KEY
```

Or using the CLI binary directly:

```bash
fmp-mcp --fmp-token=YOUR_FMP_API_KEY
```

Source: [README.md:26-32](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md#L26-L32)

### NPX (No Installation Required)

Execute directly without installing:

```bash
npx financial-modeling-prep-mcp-server --fmp-token=YOUR_FMP_API_KEY
```

Source: [README.md:26](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md#L26)

## Authentication Configuration

Authentication is performed using the Financial Modeling Prep API key. The server supports multiple configuration methods with a defined precedence order.

### Token Precedence (Highest to Lowest)

| Priority | Source | How to Set |
|----------|--------|------------|
| 1 | Session context | Pass `FMP_ACCESS_TOKEN` in MCP session configuration |
| 2 | Instance configuration | CLI flag `--fmp-token` or environment variable |
| 3 | Environment variable | `FMP_ACCESS_TOKEN` in shell environment |

Source: [CLAUDE.md:17](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md#L17)

### Configuration via Environment Variable

Set the API token as an environment variable before starting the server:

```bash
export FMP_ACCESS_TOKEN="your_fmp_api_key"
fmp-mcp
```

### Configuration via CLI Flag

Pass the token directly to the server binary:

```bash
fmp-mcp --fmp-token=your_fmp_api_key
```

### Configuration via Session (Dynamic Mode)

In Dynamic mode, the server accepts session-level configuration. Pass `FMP_ACCESS_TOKEN` when initiating an MCP session:

```json
{
  "FMP_ACCESS_TOKEN": "your_fmp_api_key"
}
```

> **Important:** Only `FMP_ACCESS_TOKEN` takes effect at the session level. The schema also accepts `FMP_TOOL_SETS` and `DYNAMIC_TOOL_DISCOVERY`, but these are no-ops at session time—server mode is fixed at startup from environment and CLI arguments.

Source: [src/toolception-adapters/AGENTS.md:8-10](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/AGENTS.md#L8-L10)

### Common Authentication Issues

**Issue: "Missing FMP_API_TOKEN" error**

This commonly occurs when deploying via MCP registries like Smithery.ai. Users report difficulties setting the API key through registry interfaces.

**Resolution:**
1. Ensure `FMP_ACCESS_TOKEN` is set as an environment variable in your deployment environment
2. When using Smithery or similar registries, verify the OAuth fields are properly configured or left blank if not required
3. Check that your MCP client is passing the token in session configuration

Source: [GitHub Issue #81](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/81)

## Server Modes

The server operates in three distinct modes, determined by configuration at startup.

### Mode Comparison

| Mode | Description | Use Case |
|------|-------------|----------|
| **Dynamic** | 5 meta-tools load toolsets on-demand | Minimal resource usage, selective tool access |
| **Static** | Pre-loaded specific toolsets | Predictable toolset, faster initial response |
| **All Tools** | All 250+ tools available | Full access, no restrictions |

Source: [README.md:14-16](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md#L14-L16)

### Enabling Dynamic Mode

Dynamic mode provides meta-tools for runtime toolset management. Enable via:

**CLI flag:**
```bash
fmp-mcp --dynamic-tool-discovery
```

**Environment variable:**
```bash
export DYNAMIC_TOOL_DISCOVERY=true
fmp-mcp
```

Source: [server.json:24-30](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json#L24-L30)

### Loading Specific Tool Sets (Static Mode)

Specify which toolsets to load at startup using the `--fmp-tool-sets` option:

```bash
fmp-mcp --fmp-tool-sets=quotes,statements,sec-filings
```

Available tool sets include: `quotes`, `statements`, `sec-filings`, `search`, `directory`, `company`, `metrics`, `technicals`, `indexes`, `market`, `news`, `insider`, `etfs`, `government`, `crypto`, `earnings`, `special`, `commodities`, `economics`, and `bulk`.

Source: [CLAUDE.md:11](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md#L11)

## Available Tools

The server exposes financial tools across 24 categories. Below are the primary tool sets:

| Category | Description | Example Tools |
|----------|-------------|---------------|
| Quotes & Price Data | Real-time and historical stock quotes | `getQuote`, `getBatchQuotesShort`, `getQuoteShort` |
| Financial Statements | Income statements, balance sheets, cash flow | `getIncomeStatement`, `getBalanceSheet`, `getCashFlowStatement` |
| SEC Filings | 8-K, 10-K, 10-Q filings | `getLatest8KFilings` |
| Company Information | Symbol lists, company profiles | `searchSymbols`, `getCompanyProfile` |
| Technical Indicators | Chart patterns, technical metrics | Various technical analysis tools |
| Market Data | Indexes, commodities, forex | Market index and performance data |
| News & Press Releases | Financial news and events | Company news retrieval |

Source: [README.md:43-48](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md#L43-L48)

## MCP Client Configuration

Different MCP clients have varying configuration requirements. Below are common setup patterns.

### Claude Desktop Configuration

Add the server to your Claude Desktop configuration file:

**macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`

**Windows:** `%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "financial-modeling-prep": {
      "command": "npx",
      "args": ["financial-modeling-prep-mcp-server", "--fmp-token", "YOUR_FMP_API_KEY"]
    }
  }
}
```

Source: [docs/USAGE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/USAGE.md)

### Session Header Configuration

When using Dynamic mode with the hosted instance, pass authentication via session headers:

```json
{
  "FMP_ACCESS_TOKEN": "your_api_key"
}
```

## Architecture Overview

The following diagram illustrates the server's layered architecture:

```mermaid
graph TD
    A[MCP Client<br/>Claude, etc.] --> B[MCP Protocol Layer<br/>toolception]
    B --> C[Tools Layer<br/>28 modules, 250+ tools]
    C --> D[API Layer<br/>FMPClient + Domain Clients]
    D --> E[Financial Modeling Prep API]
    
    F[CLI/Env Config] -->|Mode & Token| B
    G[Session Config] -->|Token Only| B
```

**Key architectural characteristics:**
- **Toolception framework**: Enables dynamic tool registration and runtime management
- **Never-throw pattern**: Tools return `{ isError: true }` instead of throwing exceptions
- **API key as query parameter**: FMP requires `?apikey=` on requests, never headers

Source: [CLAUDE.md:1-10](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md#L1-L10)
Source: [src/tools/AGENTS.md:4-6](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md#L4-L6)

## Tool Usage Example

### Fetching a Stock Quote

```typescript
// Tool name: getQuote
// Parameters: symbol (required)
{
  "symbol": "AAPL"
}
```

Response:
```json
{
  "content": [
    {
      "type": "text",
      "text": "{\n  \"symbol\": \"AAPL\",\n  \"name\": \"Apple Inc.\",\n  \"price\": 178.50,\n  \"change\": 2.35,\n  \"changePercent\": 1.33\n}"
    }
  ]
}
```

### Batch Quotes

Fetch multiple quotes in a single request:

```typescript
// Tool name: getBatchQuotesShort
// Parameters: symbols (comma-separated)
{
  "symbols": "AAPL,GOOGL,MSFT"
}
```

> **Note:** If you receive an "ACCESS DENIED" error claiming your plan is insufficient when using batch quotes with an Ultimate plan subscription, this may indicate a false positive in the MCP layer's plan-gate logic. This issue is being tracked in [GitHub Issue #100](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/100).

## Known Limitations and Workarounds

### Python Reserved Keywords (v2.6.9+)

Some tools previously used parameter names that conflict with Python reserved keywords, causing issues for Python-based MCP clients.

**Affected patterns (fixed in v2.6.9):**
- `from` → renamed to `from_date` (Python reserved keyword)
- Other reserved keywords and invalid identifiers

**Workaround for older versions:** Quote parameters explicitly when calling tools that may have reserved keyword conflicts.

Source: [CHANGELOG.md:12-15](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md#L12-L15)
Source: [GitHub Issue #93](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/93)

### Batch Quote Plan-Gate False Positive

The batch-quote endpoint may incorrectly block requests from Ultimate plan users with an "ACCESS DENIED" error. This is a false positive in the MCP layer's plan-gate logic that occurs before the request reaches the FMP API.

**Status:** Issue [#100](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/100) is open and being tracked.

## Port Configuration

The server defaults to port 3000 but can be configured:

| Method | Configuration |
|--------|---------------|
| CLI flag | `--port=8080` |
| Environment | `PORT=8080` |

Example:
```bash
fmp-mcp --fmp-token=YOUR_KEY --port=8080
```

Source: [server.json:16-22](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json#L16-L22)

## Registry Integration

The server is listed on multiple MCP registries for discovery:

| Registry | URL |
|----------|-----|
| Smithery.ai | https://smithery.ai/server/@imbenrabi/financial-modeling-prep-mcp-server |
| Glama.ai | https://glama.ai/mcp/servers/@imbenrabi/financial-modeling-prep-mcp-server |
| MCP Registry | https://registry.modelcontextprotocol.io/servers/io.github.imbenrabi/financial-modeling-prep-mcp-server |

Source: [README.md:55-61](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md#L55-L61)

## Troubleshooting Checklist

If you encounter issues, verify the following:

- [ ] Node.js version ≥ 25.3.0
- [ ] npm version ≥ 11.11.0
- [ ] Valid FMP API key with appropriate subscription tier
- [ ] `FMP_ACCESS_TOKEN` environment variable set (or passed via CLI/session)
- [ ] Port 3000 available (or custom port configured)
- [ ] Server started successfully with `fmp-mcp --fmp-token=YOUR_KEY`

### Verifying Installation

Test your installation:

```bash
npx financial-modeling-prep-mcp-server --fmp-token=YOUR_KEY
```

The server should start and listen on the configured port.

### Health Check

The server provides health and readiness endpoints:

- `GET /health` - Basic health check
- `GET /ready` - Readiness probe

## Next Steps

- **Explore tools:** See [docs/API_REFERENCE.md](docs/API_REFERENCE.md) for the complete tool catalog
- **Detailed usage:** Review [docs/USAGE.md](docs/USAGE.md) for client-specific configuration
- **Development:** See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup
- **Architecture deep-dive:** See [AGENTS.md](AGENTS.md) for architectural invariants

## See Also

- [README.md](README.md) - Project overview and features
- [docs/USAGE.md](docs/USAGE.md) - Detailed usage documentation
- [docs/API_REFERENCE.md](docs/API_REFERENCE.md) - Complete tool catalog
- [AGENTS.md](AGENTS.md) - Architectural invariants and pitfalls
- [CHANGELOG.md](CHANGELOG.md) - Version history and release notes

---

<a id='usage-guide'></a>

## Usage Guide

### Related Pages

Related topics: [API Reference](#api-reference), [Quick Start Guide](#quick-start), [Troubleshooting](#troubleshooting)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [docs/USAGE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/USAGE.md)
- [docs/REGISTRIES.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/REGISTRIES.md)
- [src/endpoints/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/endpoints/index.ts)
- [smithery.yaml](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/smithery.yaml)
- [package.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json)
- [src/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/index.ts)
- [src/tools/quotes.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)
- [src/api/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/api/AGENTS.md)
</details>

# Usage Guide

This guide covers how to install, configure, and use the Financial Modeling Prep MCP Server. It explains the different server modes, tool sets, authentication mechanisms, and integration patterns for various MCP clients.

## Overview

The Financial Modeling Prep MCP Server is a Model Context Protocol server that exposes 250+ financial data tools via the FMP API. The server supports multiple deployment methods and provides flexible configuration options for different use cases.

**Key characteristics:**
- HTTP/SSE transport (no stdio support)
- Three server modes: Dynamic, Static, and All Tools
- Token-based authentication with environment, CLI, and session-level configuration
- Built on the [toolception](https://www.npmjs.com/package/toolception) framework for runtime tool management
- Source: [README.md:1-30](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

```mermaid
graph TD
    A[MCP Client] -->|HTTP/SSE| B[FMP MCP Server]
    B -->|Token Validation| C{Token Source}
    C -->|Environment| D[Environment Variable]
    C -->|CLI| E[Command Line Flag]
    C -->|Session| F[Request Context]
    B -->|API Calls| G[FMP API]
    G -->|Financial Data| B
```

## Installation Methods

The server can be installed and run through several methods depending on your environment and requirements.

### NPM Installation (Global)

Install globally for command-line usage across your system:

```bash
npm install -g financial-modeling-prep-mcp-server
```

After installation, run the server with your API token:

```bash
fmp-mcp --fmp-token=YOUR_FMP_API_KEY
```

Source: [package.json:7-20](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json)

### NPX (No Installation)

Run directly without installation using NPX:

```bash
npx financial-modeling-prep-mcp-server --fmp-token=YOUR_FMP_API_KEY
```

This method is useful for testing or temporary usage without modifying your system.

### Docker Deployment

For containerized environments, build and run the Docker image:

```dockerfile
FROM node:25-alpine
RUN npm install -g financial-modeling-prep-mcp-server
EXPOSE 3000
CMD ["fmp-mcp", "--port=3000", "--fmp-token=${FMP_API_TOKEN}"]
```

Source: [docs/USAGE.md:1-50](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/USAGE.md)

### Hosted Instance

Use the hosted server without any installation:

```
https://financial-modeling-prep-mcp-server-production.up.railway.app/mcp
```

This requires providing your `FMP_ACCESS_TOKEN` in session configuration.

## Configuration

### Environment Variables

| Variable | Description | Required | Default |
|----------|-------------|----------|---------|
| `FMP_ACCESS_TOKEN` | Financial Modeling Prep API key | Yes | - |
| `PORT` | HTTP server port | No | `3000` |
| `FMP_TOOL_SETS` | Comma-separated list of tool sets to load | No | All tools |
| `DYNAMIC_TOOL_DISCOVERY` | Enable dynamic tool discovery mode | No | `false` |

Source: [server.json:15-45](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)

### Command Line Arguments

| Argument | Description | Format |
|----------|-------------|--------|
| `--fmp-token` | FMP API access token | `string` |
| `--port` | Port number for HTTP server | `number` |
| `--fmp-tool-sets` | Comma-separated tool set names | `string` |
| `--dynamic-tool-discovery` | Enable dynamic mode | `boolean` |

### Token Configuration Precedence

The server uses the following precedence order for token resolution (highest to lowest):

1. **Session Context** — Token provided in the MCP session configuration
2. **CLI Arguments** — `--fmp-token` flag at startup
3. **Environment Variables** — `FMP_ACCESS_TOKEN` environment variable

> **Important:** The FMP API requires the token as a query parameter (`?apikey=`), never as an HTTP header. This is handled automatically by the server's API clients.
> Source: [src/api/AGENTS.md:1-20](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/api/AGENTS.md)

## Server Modes

The MCP server operates in three modes, determined by environment variables and CLI flags at startup.

### Mode Comparison

| Mode | Flag | Behavior | Meta-Tools |
|------|------|----------|------------|
| **All Tools** (Default) | Not set | Loads all 250+ tools at startup | No |
| **Static Tool Sets** | `FMP_TOOL_SETS` | Loads only specified tool sets | No |
| **Dynamic Discovery** | `DYNAMIC_TOOL_DISCOVERY=true` | Provides 5 meta-tools for runtime loading | Yes |

### Dynamic Tool Discovery Mode

When `DYNAMIC_TOOL_DISCOVERY=true` is set, the server provides five meta-tools for runtime tool management:

```mermaid
graph LR
    A[Session Start] --> B[Load 5 Meta-Tools]
    B --> C[getAvailableToolSets]
    B --> D[loadToolSet]
    B --> E[unloadToolSet]
    B --> F[getLoadedToolSets]
    B --> G[searchTools]
    
    C --> H[List All Available Tool Sets]
    D --> I[Load Selected Tool Set]
    E --> J[Remove Tool Set from Session]
```

**Meta-tools available:**
- `getAvailableToolSets` — List all available tool sets
- `getLoadedToolSets` — List currently loaded tool sets
- `loadToolSet` — Load a specific tool set by name
- `unloadToolSet` — Unload a specific tool set
- `searchTools` — Search tools across all sets

> **Note:** Only `FMP_ACCESS_TOKEN` can be configured per-session. Other parameters like `FMP_TOOL_SETS` and `DYNAMIC_TOOL_DISCOVERY` are fixed at startup and cannot be changed during a session.
> Source: [src/toolception-adapters/AGENTS.md:1-25](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/AGENTS.md)

### Static Tool Sets Mode

Load specific tool sets by comma-separating their names:

```bash
FMP_TOOL_SETS=quotes,statements,fcas npx financial-modeling-prep-mcp-server
```

## Tool Sets and Categories

The server organizes its 250+ tools into 24 tool sets. Each tool set corresponds to a functional domain of financial data.

### Available Tool Sets

| Tool Set | Description | Example Tools |
|----------|-------------|---------------|
| `search` | Symbol and company search | `searchSymbols`, `searchCompanies` |
| `directory` | Stock screeners and listings | `getNYSEStocks`, `getNASDAQStocks` |
| `quotes` | Real-time and batch quotes | `getQuote`, `getBatchQuotesShort` |
| `statements` | Financial statements | `getIncomeStatement`, `getBalanceSheet` |
| `metrics` | Financial ratios and metrics | `getFinancialRatios`, `getKeyMetrics` |
| `technicals` | Technical indicators | `getTechnicalIndicators` |
| `market` | Market data and indexes | `getMarketIndexes`, `getMarketPerformance` |
| `news` | News and press releases | `getMarketNews`, `getStockNews` |
| `sec-filings` | SEC filing data | `getLatest8KFilings`, `getSECFilings` |
| `insider` | Insider and institutional trading | `getInsiderTrading`, `getInstitutionalHoldings` |
| `etfs` | ETF data and holdings | `getETFHoldings`, `getETFPrice` |
| `crypto` | Cryptocurrency data | `getCryptoPrice`, `getCryptoHistorical` |
| `forex` | Foreign exchange data | `getForexPrice`, `getForexHistorical` |
| `commodities` | Commodity prices | `getCommoditiesPrice` |
| `economics` | Economic indicators | `getEconomicIndicators` |
| `earnings` | Earnings data and estimates | `getEarningsCalendar` |
| `fcas` | Fundamental analysis scores | `getFCASScores` |

Source: [src/constants/toolSets.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/constants/toolSets.ts)

### Using Tools

Tools are called via the MCP protocol using the tool name and parameters. Example for getting a stock quote:

```json
{
  "name": "getQuote",
  "arguments": {
    "symbol": "AAPL"
  }
}
```

**Batch quotes example:**

```json
{
  "name": "getBatchQuotesShort",
  "arguments": {
    "symbols": "AAPL,MSFT,GOOGL"
  }
}
```

Source: [src/tools/quotes.ts:40-75](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)

## MCP Client Integration

### Claude Desktop

Add to your Claude Desktop configuration file:

**macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
**Windows:** `%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "financial-modeling-prep": {
      "url": "https://financial-modeling-prep-mcp-server-production.up.railway.app/mcp",
      "headers": {
        "FMP_ACCESS_TOKEN": "your_api_key_here"
      }
    }
  }
}
```

### Smithery.ai

The server is registered on Smithery.ai. Configuration varies by client, but typically requires:

1. Server URL: `https://financial-modeling-prep-mcp-server-production.up.railway.app/mcp`
2. OAuth fields: Leave blank (the server uses token-based auth)
3. Headers: Provide `FMP_ACCESS_TOKEN` in session configuration

Source: [docs/REGISTRIES.md:1-60](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/REGISTRIES.md)

### Python MCP Clients

> **Known Issue:** Some tool schemas use parameter names that conflict with Python reserved keywords or contain invalid identifiers. This can break Python-based MCP clients.
> 
> **Workaround:** Version 2.6.9+ renamed the `from` parameter to `from_date` in affected tools to avoid Python reserved keyword conflicts.
> 
> See: [Issue #93](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/93)

## HTTP Endpoints

The server exposes HTTP endpoints for health checking and readiness verification.

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/health` | GET | Basic health check |
| `/ready` | GET | Readiness check with tool count |
| `/mcp` | POST | MCP JSON-RPC endpoint |
| `/mcp` | GET | SSE stream endpoint |

Source: [src/endpoints/index.ts:1-80](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/endpoints/index.ts)

**Health check response:**

```json
{
  "status": "ok",
  "timestamp": "2026-04-30T12:00:00.000Z"
}
```

**Readiness check response:**

```json
{
  "status": "ready",
  "toolsLoaded": 253,
  "version": "2.6.10"
}
```

## Common Issues and Troubleshooting

### Issue: "ACCESS DENIED" for Ultimate Plan Users

> **Known Bug:** The batch-quote endpoint may incorrectly return ACCESS DENIED for Ultimate plan users. This is a false positive in the MCP layer's plan-gating logic that occurs before the request reaches the FMP API.
> 
> See: [Issue #100](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/100)

**Workaround:** Use individual `getQuote` calls instead of `getBatchQuotesShort` until this is fixed.

### Issue: FMP API Key Configuration

> Users have reported difficulty setting the API key, especially when using Smithery.ai integration.
> 
> See: [Issue #81](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/81)

**Resolution steps:**
1. Ensure `FMP_ACCESS_TOKEN` is set as an environment variable or CLI flag
2. For Smithery, provide the token in session headers, not OAuth fields
3. Verify the token is valid at [financialmodelingprep.com](https://site.financialmodelingprep.com/)

### Issue: Session Not Found Errors

In dynamic mode, "Session not found" errors typically indicate:
- The `clientId` changed between requests
- The `sessionConfigHash` differs from the original session

**Ensure consistent session parameters:**
```json
{
  "clientId": "consistent-client-id",
  "sessionConfig": {
    "FMP_ACCESS_TOKEN": "your_token"
  }
}
```

Source: [src/toolception-adapters/AGENTS.md:20-25](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/AGENTS.md)

## Error Handling

Tools follow a consistent error handling pattern:

1. **Never throw exceptions** — Tools return error responses with `isError: true`
2. **Error format** — Error messages follow the pattern `Error: ${message}`
3. **Response structure:**

```json
{
  "content": [
    {
      "type": "text",
      "text": "Error: Invalid symbol provided"
    }
  ],
  "isError": true
}
```

Source: [src/tools/AGENTS.md:1-20](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)

## See Also

- [Configuration Reference](CONFIGURATION.md) — Detailed configuration options
- [API Reference](API_REFERENCE.md) — Complete tool catalog
- [Architecture Overview](ARCHITECTURE.md) — System architecture and components
- [Registry Setup](REGISTRIES.md) — MCP registry integration guides
- [Contributing Guide](../CONTRIBUTING.md) — Development setup and PR guidelines

---

<a id='api-reference'></a>

## API Reference

### Related Pages

Related topics: [Usage Guide](#usage-guide), [Tool Development Guide](#tool-development)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [docs/API_REFERENCE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/API_REFERENCE.md)
- [FMP_API_Tools_Documentation.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/FMP_API_Tools_Documentation.md)
- [src/tools/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/index.ts)
- [src/api/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/api/index.ts)
- [src/tools/quotes.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)
- [src/tools/statements.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/statements.ts)
- [src/tools/sec-filings.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/sec-filings.ts)
- [src/tools/earnings-transcript.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/earnings-transcript.ts)
- [src/toolception-adapters/ToolCollector.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/ToolCollector.ts)
- [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)
- [src/api/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/api/AGENTS.md)
- [server.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)
- [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)
</details>

# API Reference

## Overview

The Financial Modeling Prep MCP Server exposes 250+ financial data tools via the Model Context Protocol (MCP), providing AI assistants with access to the Financial Modeling Prep (FMP) API. The API layer serves as the foundational bridge between the MCP protocol layer and the external FMP financial data service.

Source: [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

## Architecture

The MCP server follows a layered architecture with three distinct levels:

```mermaid
graph TD
    A["MCP Protocol Layer<br/>(toolception + Fastify)"] --> B["Tools Layer<br/>(28 modules, 253+ tools)"]
    B --> C["API Layer<br/>(FMPClient + 28 domain clients)"]
    C --> D["Financial Modeling Prep API"]
```

### API Client Structure

The API layer consists of an abstract base client and 28 domain-specific clients, each responsible for a particular category of financial data. Source: [src/api/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/api/index.ts)

| Component | Purpose |
|-----------|---------|
| `FMPClient` | Abstract base class for all domain clients |
| `QuotesClient` | Stock quotes, batch quotes, aftermarket trades |
| `StatementsClient` | Income statements, balance sheets, cash flow |
| `SECFilingsClient` | 8-K filings, 10-K, 10-Q documents |
| `EarningsTranscriptClient` | Earnings call transcripts |
| 24 other domain clients | Specialized data categories |

### Key Invariant: API Key as Query Parameter

FMP requires the API key to be passed as a query parameter, never as an HTTP header. This is a critical constraint enforced throughout the codebase.

> FMP requires `?apikey=`, never headers

Source: [src/api/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/api/AGENTS.md)

## Tool Categories

The server organizes 253+ tools into 24 logical categories. Each category maps to one or more API clients and exposes multiple related tools.

Source: [docs/API_REFERENCE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/API_REFERENCE.md)

### Complete Tool Category Reference

| Category | Tools | Description |
|----------|-------|-------------|
| Search | Multiple | Symbol search and lookup |
| Directory & Symbol Lists | Multiple | Stock listings, exchange data |
| Company Information | Multiple | Profile, founders, executives, HR metrics |
| Financial Statements | 20+ | Income statements, balance sheets, cash flow |
| Financial Metrics & Analysis | 15+ | Ratios, scoring, DCF, Graham number |
| Technical Indicators | 10+ | Moving averages, RSI, MACD, Bollinger |
| Quotes & Price Data | 8+ | Real-time quotes, batch quotes, aftermarket |
| Market Indexes & Performance | Multiple | Index components, performance tracking |
| Market Data | Multiple | EOD prices, historical data |
| News & Press Releases | Multiple | Financial news, press releases |
| SEC Filings | 6+ | 8-K, 10-K, 10-Q, 8-K filings |
| Insider & Institutional Trading | Multiple | Insider transactions, institutional holdings |
| ETFs & Funds | Multiple | ETF holdings, fund data |
| Government Trading | Multiple | Senate/house trading, government contracts |
| Cryptocurrency & Forex | Multiple | Crypto quotes, forex pairs |
| Earnings | 8+ | Calendar, estimates, surprise data |
| Special Data Sets | Multiple | Economic indicators, commodities |
| Commodities | Multiple | Precious metals, commodities pricing |
| Economics | Multiple | GDP, inflation, employment data |
| Bulk Data Tools | Multiple | Batch operations, bulk downloads |

Source: [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

## Tool Registration Pattern

All MCP tools follow a consistent registration pattern defined in `src/tools/`. Each tool module exports a registration function that binds domain-specific handlers to the MCP server instance.

Source: [src/tools/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/index.ts)

### Registration Function Signature

```typescript
export function registerQuotesTools(
  server: McpServer,
  accessToken?: string
): void
```

Each registration function:
1. Creates a domain-specific API client instance
2. Registers each tool with `server.tool()`
3. Wraps API calls in error handling that returns `{ isError: true }` instead of throwing

Source: [src/tools/quotes.ts:6-16](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)

### Required Tool Rules

Tools must adhere to strict rules to maintain protocol compatibility:

| Rule | Description |
|------|-------------|
| Never throw | Always return `{ content: [...], isError: true }` on failure |
| Unique names | Tool names must be globally unique across all 28 modules |
| Annotations | All tools receive identical annotations: `readOnlyHint`, `idempotentHint`, `openWorldHint` |
| Error format | Error messages must follow `Error: ${message}` pattern |

Source: [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)

## Quotes Tools Reference

The Quotes category provides access to real-time and historical stock quote data.

Source: [src/tools/quotes.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)

### getQuote

Get real-time stock quote data for a single symbol.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `symbol` | string | Yes | Stock ticker symbol |

```typescript
server.tool(
  "getQuote",
  "Access real-time stock quotes with the FMP Stock Quote API.",
  {
    symbol: z.string().describe("Stock symbol"),
  },
  async ({ symbol }) => {
    const results = await quotesClient.getQuote({ symbol });
    return { content: [{ type: "text", text: JSON.stringify(results) }] };
  }
);
```

### getBatchQuotesShort

Get short-form quotes for multiple stocks in a single request.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `symbols` | string | Yes | Comma-separated list of stock symbols |

**Note:** There is a known issue where batch-quote endpoints may be incorrectly blocked for Ultimate plan users due to a false positive in the MCP layer plan-gate logic. See [Issue #100](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/100).

### getBatchAftermarketTrade

Retrieve aftermarket trading data for multiple symbols.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `symbols` | string | Yes | Comma-separated list of stock symbols |

## Financial Statements Tools Reference

Access company financial statements including income statements, balance sheets, and cash flow statements.

Source: [src/tools/statements.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/statements.ts)

### getIncomeStatement

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `symbol` | string | Yes | Stock ticker symbol |
| `limit` | number | No | Number of periods to return (default: 100, max: 1000) |
| `period` | enum | No | Period filter: `Q1`, `Q2`, `Q3`, `Q4`, or `FY` |

```typescript
server.tool(
  "getIncomeStatement",
  "Access real-time income statement data for public companies.",
  {
    symbol: z.string().describe("Stock symbol"),
    limit: z.number().optional().describe("Limit on number of results"),
    period: z.enum(["Q1", "Q2", "Q3", "Q4", "FY"]).optional().describe("Period"),
  },
  async ({ symbol, limit, period }) => {
    const results = await statementsClient.getIncomeStatement(symbol, { limit, period });
    return { content: [{ type: "text", text: JSON.stringify(results) }] };
  }
);
```

## SEC Filings Tools Reference

Access SEC filing documents including 8-K, 10-K, and 10-Q reports.

Source: [src/tools/sec-filings.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/sec-filings.ts)

### getLatest8KFilings

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `from_date` | string | Yes | Start date (YYYY-MM-DD format) |
| `to` | string | Yes | End date (YYYY-MM-DD format) |
| `page` | number | No | Page number for pagination |
| `limit` | number | No | Limit the number of results |

**Important:** The parameter `from_date` was renamed from `from` in v2.6.9 to avoid Python reserved keyword conflicts. See [Issue #93](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/93) and [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md).

## Earnings Tools Reference

Access earnings data including transcripts, calendar, and estimates.

Source: [src/tools/earnings-transcript.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/earnings-transcript.ts)

### getLatestEarningsTranscripts

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `limit` | number | No | Limit the number of results |
| `page` | number | No | Page number for pagination |

## Toolception Integration

The server uses [toolception](https://www.npmjs.com/package/toolception) to enable dynamic tool management, supporting three server modes:

Source: [src/toolception-adapters/ToolCollector.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/ToolCollector.ts)

### Server Modes

| Mode | Description | Meta-tools Available |
|------|-------------|---------------------|
| Dynamic | Load toolsets on-demand | Yes (5 meta-tools) |
| Static | Pre-loaded specific toolsets | No |
| All Tools | Load all 253+ tools at startup | No |

Source: [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

### ToolCollector Architecture

The `ToolCollector` class serves as a virtual MCP server that intercepts tool registrations from existing `registerXxxTools()` functions and converts them to toolception's `McpToolDefinition` format.

```mermaid
classDiagram
    class ToolCollector {
        +tools: McpToolDefinition[]
        +tool(name, description, schema, handler): void
        +getTools(): McpToolDefinition[]
    }
    
    class McpToolDefinition {
        +name: string
        +description: string
        +inputSchema: Record
        +handler: Function
        +annotations: object
    }
```

Source: [src/toolception-adapters/ToolCollector.ts:1-50](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/ToolCollector.ts)

## Configuration Reference

### Command-Line Arguments

Source: [server.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--fmp-token` | string | No | Financial Modeling Prep API access token |
| `--port` | number | No | Port number for HTTP server mode |
| `--dynamic-tool-discovery` | boolean | No | Enable dynamic tool discovery mode |
| `--fmp-tool-sets` | string | No | Comma-separated list of tool sets to load |

### Environment Variables

| Variable | Type | Required | Description |
|----------|------|----------|-------------|
| `FMP_ACCESS_TOKEN` | string | Yes* | FMP API access token |
| `PORT` | number | No | HTTP server port |
| `DYNAMIC_TOOL_DISCOVERY` | boolean | No | Enable dynamic tool discovery |
| `FMP_TOOL_SETS` | string | No | Comma-separated tool set names |

*Required for API access. May be provided via CLI arg `--fmp-token` or session configuration.

### Token Precedence

The system enforces the following precedence for API token resolution:

1. **Context** — Token provided in session configuration
2. **Instance** — Token provided via CLI argument
3. **Environment** — Token provided via `FMP_ACCESS_TOKEN` environment variable

Source: [src/api/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/api/AGENTS.md)

## Known Limitations and Issues

### Issue #100: Batch-Quote False Positive Blocking

The batch-quote endpoint may incorrectly return `ACCESS DENIED` errors for Ultimate plan users. This occurs at the MCP layer before the request reaches the FMP API, representing a false positive in the plan-gate logic.

**Status:** Open issue requiring investigation of MCP layer access control.

Source: [Issue #100](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/100)

### Issue #93: Python Reserved Keywords in Parameter Names

Several tools use parameter names that conflict with Python reserved keywords or contain invalid identifiers, breaking Python-based MCP clients.

**Resolved in v2.6.9:** The `from` parameter was renamed to `from_date` in relevant tools (e.g., SEC filings).

**Status:** Ongoing effort to identify and rename all problematic parameter names.

Source: [Issue #93](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/93), [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md)

### Issue #81: FMP API Key Configuration

Users have reported difficulty setting the FMP API key, particularly when using registry integrations like Smithery.ai.

**Recommended Solutions:**
1. Set `FMP_ACCESS_TOKEN` environment variable directly
2. Use `--fmp-token` CLI argument for self-hosted deployments
3. Provide via session configuration when supported by the MCP client

Source: [Issue #81](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/81)

## Error Handling

All tools follow a consistent error handling pattern that prevents exceptions from propagating to the MCP protocol layer:

```typescript
try {
  const results = await quotesClient.getQuote({ symbol });
  return {
    content: [{ type: "text", text: JSON.stringify(results, null, 2) }],
  };
} catch (error) {
  return {
    content: [
      {
        type: "text",
        text: `Error: ${
          error instanceof Error ? error.message : String(error)
        }`,
      },
    ],
    isError: true,
  };
}
```

This ensures that MCP clients receive well-formed responses regardless of API failures.

Source: [src/tools/quotes.ts:22-35](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)

## API Version Compatibility

The server targets specific versions of Node.js and npm:

| Dependency | Minimum Version |
|------------|-----------------|
| Node.js | >= 25.3.0 |
| npm | >= 11.11.0 |

Source: [package.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json)

## See Also

- [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md) — Project overview and quick start
- [docs/USAGE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/USAGE.md) — Client-specific setup instructions
- [docs/REGISTRIES.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/REGISTRIES.md) — MCP registry integration guides
- [AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/AGENTS.md) — Agent-focused invariants and anti-patterns
- [CONTRIBUTING.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CONTRIBUTING.md) — Development setup and contribution guidelines

---

<a id='architecture'></a>

## System Architecture

### Related Pages

Related topics: [Overview](#overview), [Tool Development Guide](#tool-development)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)
- [src/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/AGENTS.md)
- [src/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/index.ts)
- [src/api/FMPClient.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/api/FMPClient.ts)
- [src/toolception-adapters/ToolCollector.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/ToolCollector.ts)
- [src/toolception-adapters/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/AGENTS.md)
- [src/server-mode-enforcer/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/server-mode-enforcer/AGENTS.md)
- [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)
- [src/tools/quotes.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)
- [src/tools/sec-filings.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/sec-filings.ts)
- [src/tools/statements.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/statements.ts)
- [package.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json)
- [server.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)
- [CONTRIBUTING.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CONTRIBUTING.md)

</details>

# System Architecture

## Overview

The Financial Modeling Prep MCP Server is a Model Context Protocol (MCP) server implementation that exposes 250+ financial data tools to AI assistants through the Financial Modeling Prep (FMP) API. Built on Node.js with the toolception framework, it provides a middleware layer that translates MCP tool invocations into FMP API calls.

**Purpose:** Enable AI assistants like Claude to access real-time and historical financial data including stock quotes, financial statements, SEC filings, market indexes, cryptocurrency data, and more.

**Scope:** The server operates as a read-only data proxy—it fetches data from FMP's API endpoints and returns structured JSON responses. It does not perform any write operations, market analysis, or calculations.

Source: [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)

---

## High-Level Architecture

The system follows a layered architecture with four primary tiers:

```mermaid
graph TD
    subgraph "Client Layer"
        A["AI Assistant<br/>(Claude, etc.)"]
    end
    
    subgraph "MCP Protocol Layer"
        B["MCP SDK"]
        C["toolception Framework"]
    end
    
    subgraph "Tools Layer"
        D["28 Tool Modules<br/>(253+ tools)"]
    end
    
    subgraph "API Layer"
        E["FMPClient"]
        F["28 Domain Clients"]
    end
    
    subgraph "External"
        G["FMP API<br/>financialmodelingprep.com"]
    end
    
    A --> B
    B --> C
    C --> D
    D --> E
    E --> F
    F --> G
```

| Layer | Component Count | Responsibility |
|-------|-----------------|----------------|
| MCP Protocol | 1 | Protocol handling, JSON-RPC over HTTP/SSE |
| Tools | 28 modules | Tool registration, input validation, error handling |
| API | 1 + 28 clients | HTTP requests, response transformation, caching |
| External | 1 | Third-party financial data provider |

Source: [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)

---

## Directory Structure

```
src/
├── api/                          # HTTP clients for FMP API
│   ├── FMPClient.ts              # Base HTTP client
│   ├── quotes/
│   │   └── QuotesClient.ts       # Stock quote domain client
│   ├── statements/
│   │   └── StatementsClient.ts   # Financial statements client
│   ├── sec-filings/
│   │   └── SECFilingsClient.ts   # SEC filings client
│   └── ... (25 more domain clients)
├── tools/                        # MCP tool registrations
│   ├── quotes.ts                 # Quote-related tools
│   ├── statements.ts             # Statement-related tools
│   ├── sec-filings.ts            # SEC filing tools
│   └── ... (25 more tool modules)
├── toolception-adapters/         # toolception framework integration
│   ├── ToolCollector.ts          # Tool registration capture
│   └── AGENTS.md                 # Adapter invariants
├── server-mode-enforcer/         # Mode configuration singleton
│   └── AGENTS.md                 # Mode enforcement rules
├── constants/                    # Tool sets and defaults
├── endpoints/                    # HTTP endpoints (health, ready)
├── prompts/                      # MCP prompt definitions
└── index.ts                      # Server entry point
```

Source: [CONTRIBUTING.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CONTRIBUTING.md)

---

## Core Components

### 1. Server Entry Point (`src/index.ts`)

The entry point initializes the MCP server, configures the Fastify HTTP server, and wires all components together:

```mermaid
sequenceDiagram
    participant Main as index.ts
    participant Fastify
    participant Toolception
    participant Enforcer
    participant Adapters
    
    Main->>Enforcer: Initialize server mode
    Main->>Adapters: Collect all tool definitions
    Main->>Toolception: Build config from mode + adapters
    Main->>Fastify: Create HTTP server with middleware
    Fastify->>Toolception: Register routes
    Main->>Main: Start listening
```

**Key initialization steps:**
1. Validate environment variables and CLI arguments
2. Initialize the `ServerModeEnforcer` singleton to determine operational mode
3. Collect all tool definitions via `ToolCollector`
4. Build toolception configuration using `ModeConfigMapper`
5. Create Fastify server with client ID injection middleware
6. Register MCP protocol routes and expose tools

Source: [src/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/index.ts)

### 2. FMPClient (`src/api/FMPClient.ts`)

The base HTTP client that handles all communication with the FMP API:

**Key responsibilities:**
- Appends API key as a query parameter (`?apikey=`)
- Sets appropriate headers for JSON responses
- Handles token precedence (context → instance → environment)
- Transforms API errors into structured responses

```typescript
// Token precedence: Context > Instance > Environment
const effectiveToken = contextToken || instanceToken || envToken;
```

> **Important:** FMP requires the API key as a query parameter, never as an HTTP header. This is a common source of integration errors.

Source: [src/api/FMPClient.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/api/FMPClient.ts)

### 3. Domain API Clients

Each domain has a dedicated client class (e.g., `QuotesClient`, `StatementsClient`, `SECFilingsClient`). These clients:

- Extend or use `FMPClient` for base HTTP operations
- Define domain-specific method signatures
- Handle parameter validation before API calls
- Transform responses into consistent formats

| Domain Client | Purpose | Example Tools |
|----------------|---------|---------------|
| `QuotesClient` | Real-time and historical stock quotes | `getQuote`, `getBatchQuotesShort` |
| `StatementsClient` | Income, balance sheet, cash flow statements | `getIncomeStatement` |
| `SECFilingsClient` | SEC filing documents and metadata | `getLatest8KFilings` |
| `CryptoClient` | Cryptocurrency price and market data | `getCryptoPrice` |
| ... | 24 more domains | 240+ additional tools |

Source: [src/tools/quotes.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)

### 4. Tool Registration Modules (`src/tools/`)

Each tool module follows a consistent registration pattern:

```typescript
export function registerQuotesTools(
  server: McpServer,
  accessToken?: string
): void {
  const quotesClient = new QuotesClient(accessToken);

  server.tool(
    "getQuote",                          // Tool name (globally unique)
    "Description of what this tool does",
    { symbol: z.string().describe("...") }, // Zod schema
    async ({ symbol }) => {              // Handler
      try {
        const results = await quotesClient.getQuote({ symbol });
        return { content: [{ type: "text", text: JSON.stringify(results) }] };
      } catch (error) {
        return {
          content: [{ type: "text", text: `Error: ${error.message}` }],
          isError: true
        };
      }
    }
  );
}
```

**Critical rules for tool handlers:**
- **Never throw** — Always return `{ isError: true }` for failures
- **Error format** — Messages must be `Error: ${message}` for MCP client compatibility
- **Global uniqueness** — Tool names must not conflict across all 28 modules

Source: [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)

### 5. ToolCollector (`src/toolception-adapters/ToolCollector.ts`)

The `ToolCollector` is a virtual MCP server that intercepts tool registrations during startup:

```mermaid
classDiagram
    class ToolCollector {
        -tools: McpToolDefinition[]
        +tool(name, description, schema, handler)
        +getTools(): McpToolDefinition[]
    }
    
    class McpServer {
        +tool(name, description, schema, handler)
    }
    
    ToolCollector ..> McpServer : mocks
```

It captures tool definitions from all `registerXxxTools()` functions and converts them into toolception's `McpToolDefinition` format, enabling runtime tool management.

Source: [src/toolception-adapters/ToolCollector.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/ToolCollector.ts)

---

## Server Modes

The MCP server operates in three modes, controlled by environment variables and CLI arguments:

```mermaid
graph LR
    A[Server Start] --> B{Mode?}
    
    B -->|Dynamic| C[Meta-tools only at startup]
    B -->|Static| D[Pre-selected toolsets]
    B -->|All Tools| E[253+ tools exposed]
    
    C --> F[enableToolSet / disableToolSet<br/>availableToolSets meta-tools]
    D --> G[Tools from FMP_TOOL_SETS]
    E --> H[All 28 modules loaded]
```

| Mode | Configuration | Behavior |
|------|---------------|----------|
| **Dynamic** | `DYNAMIC_TOOL_DISCOVERY=true` | Only 5 meta-tools loaded at startup; toolsets loaded on-demand |
| **Static** | `FMP_TOOL_SETS=quotes,statements` | Pre-defined subset of toolsets loaded |
| **All Tools** | Default (no config) | All 253+ tools available immediately |

Source: [src/server-mode-enforcer/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/server-mode-enforcer/AGENTS.md)

---

## Configuration Options

### Environment Variables

| Variable | Type | Required | Description |
|----------|------|----------|-------------|
| `FMP_ACCESS_TOKEN` | string | Yes* | FMP API access token |
| `PORT` | number | No | HTTP server port (default: 3000) |
| `DYNAMIC_TOOL_DISCOVERY` | boolean | No | Enable dynamic mode |
| `FMP_TOOL_SETS` | string | No | Comma-separated list of tool sets |

\*Can be provided via CLI (`--fmp-token`) or session configuration instead.

### CLI Arguments

```bash
fmp-mcp --fmp-token=YOUR_API_KEY --port=8080 --dynamic-tool-discovery
```

| Argument | Format | Description |
|----------|--------|-------------|
| `--fmp-token` | string | FMP API access token |
| `--port` | number | HTTP server port |
| `--dynamic-tool-discovery` | boolean | Enable dynamic tool loading |
| `--fmp-tool-sets` | string | Comma-separated tool set names |

Source: [server.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/server.json)

---

## Key Invariants

These rules must never be violated during development:

| # | Invariant | Rationale |
|---|-----------|-----------|
| 1 | API key as query parameter | FMP API requires `?apikey=`, not headers |
| 2 | Token precedence: Context > Instance > Environment | Supports multiple authentication strategies |
| 3 | Fail-fast validation | Invalid tool sets cause `process.exit(1)` at startup |
| 4 | Session-level: Only `FMP_ACCESS_TOKEN` is configurable per-session | Tool sets are fixed at server start |
| 5 | Read-only tools | All tools fetch data; none perform write operations |
| 6 | Never throw from tool handlers | Return `{ isError: true }` instead |

Source: [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)

---

## Data Flow

### Tool Invocation Flow

```mermaid
sequenceDiagram
    participant AI as AI Assistant
    participant MCP as MCP SDK
    participant Tool as Tool Handler
    participant Client as Domain Client
    participant FMP as FMP API
    
    AI->>MCP: listTools() / callTool()
    MCP->>Tool: Execute handler
    Tool->>Client: Fetch data
    Client->>FMP: HTTP GET ?apikey=xxx
    FMP-->>Client: JSON Response
    Client-->>Tool: Structured data
    Tool-->>MCP: { content: [...], isError? }
    MCP-->>AI: Tool result
    
    Note over Tool: Error handling:<br/>Return { isError: true }<br/>NEVER throw
```

### Error Response Pattern

All tool handlers must follow this pattern:

```typescript
try {
  const results = await quotesClient.getQuote({ symbol });
  return {
    content: [{ type: "text", text: JSON.stringify(results, null, 2) }],
  };
} catch (error) {
  return {
    content: [
      {
        type: "text",
        text: `Error: ${error instanceof Error ? error.message : String(error)}`,
      },
    ],
    isError: true,
  };
}
```

Source: [src/tools/quotes.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)

---

## Deployment Architecture

### Hosted Instance

The server provides a hosted endpoint for immediate use:

```
https://financial-modeling-prep-mcp-server-production.up.railway.app/mcp
```

No installation required. Users provide `FMP_ACCESS_TOKEN` in session configuration.

### Self-Hosted Options

| Method | Command |
|--------|---------|
| **NPX** | `npx financial-modeling-prep-mcp-server --fmp-token=YOUR_KEY` |
| **NPM Global** | `npm install -g financial-modeling-prep-mcp-server` |
| **Docker** | `docker run -e FMP_ACCESS_TOKEN=xxx imb/enrabi/fmp-mcp-server` |
| **Source** | `npm install && npm run build && npm start` |

### MCP Registry Integration

The server is listed on multiple MCP registries for discovery:

- [Smithery.ai](https://smithery.ai/server/@imbenrabi/financial-modeling-prep-mcp-server)
- [Glama.ai](https://glama.ai/mcp/servers/@imbenrabi/financial-modeling-Prep-MCP-Server)
- [MCP Registry](https://registry.modelcontextprotocol.io/servers/io.github.imbenrabi/financial-modeling-prep-mcp-server)

Source: [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md)

---

## Known Limitations and Issues

### Community-Reported Issues

| Issue | Description | Status |
|-------|-------------|--------|
| [#100](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/100) | Batch-quote endpoint incorrectly blocked for Ultimate plan users | Open |
| [#93](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/93) | Tool schemas use Python reserved keywords (`from`, `class`, etc.) | Fixed in v2.6.9 |
| [#81](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/81) | FMP API KEY configuration difficulties | Documentation clarified |

### Issue #100: Plan-Gate False Positive

**Problem:** The batch-quote endpoint returns `ACCESS DENIED` for Ultimate plan users even though the request never reaches the FMP API.

**Root cause:** The block occurs at the MCP layer before the API call is made—a false positive in plan validation logic.

### Issue #93: Python Reserved Keywords

**Problem:** Tool parameter names like `from` conflicted with Python MCP clients.

**Fix:** Renamed `from` to `from_date` in MCP tool schemas (v2.6.9+).

```typescript
// Before (v2.6.8)
{ from: z.string() }

// After (v2.6.9+)
{ from_date: z.string() }
```

Source: [src/tools/sec-filings.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/sec-filings.ts)

---

## Tool Categories (28 Domains)

| # | Domain | Tools | Example Data |
|---|--------|-------|--------------|
| 1 | Quotes & Price Data | 8 | Real-time quotes, batch quotes |
| 2 | Financial Statements | 12 | Income, balance sheet, cash flow |
| 3 | Financial Metrics | 15 | Ratios, margins, growth |
| 4 | SEC Filings | 10 | 8-K, 10-K, 10-Q, proxy |
| 5 | Company Information | 8 | Profile, officers, website |
| 6 | Stock Market | 12 | Indexes, movers, sectors |
| 7 | News & Press Releases | 6 | Company news, press releases |
| 8 | ETFs & Funds | 10 | Holdings, NAV, performance |
| 9 | Cryptocurrency | 8 | Price, historical, quotes |
| 10 | Forex | 6 | Currency pairs, rates |
| 11 | Commodities | 8 | Precious metals, energy |
| 12 | Economics | 10 | GDP, inflation, employment |
| 13 | Earnings | 8 | Estimates, surprises, guidance |
| 14 | Insider Trading | 6 | Insider transactions |
| 15 | Institutional Trading | 6 | 13F filings |
| 16 | Search & Directory | 8 | Symbol search, exchange list |
| 17 | Technical Indicators | 15 | SMA, EMA, RSI, MACD |
| 18 | Bulk Data Tools | 6 | Large dataset downloads |
| 19 | Government Trading | 6 | Senate, house trading |
| 20 | Special Data Sets | 8 | Various premium datasets |
| 21 | Market Data | 6 | Pre/post market |
| 22 | Historical Data | 12 | Historical prices, dividends |
| 23 | Symbol Lists | 6 | Available symbols |
| 24 | Social Sentiment | 4 | Stocktwits, social sentiment |
| 25 | Analyst Estimates | 6 | Analyst ratings, targets |
| 26 | Stock Screener | 6 | Filtered stock lists |
| 27 | Options Data | 6 | Options chains, expirations |
| 28 | Splits & Dividends | 4 | Corporate actions |

**Total: 253+ tools**

---

## Runtime Requirements

| Requirement | Version |
|-------------|---------|
| Node.js | >= 25.3.0 |
| npm | >= 11.11.0 |

The server is built as an ES module (`"type": "module"`) and compiled with TypeScript.

Source: [package.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json)

---

## Anti-Patterns

These patterns must be avoided:

### Never Throw from Tool Handlers

```typescript
// ❌ WRONG - Will break MCP protocol
async function toolHandler({ symbol }) {
  if (!symbol) throw new Error("Symbol required");
  return await client.getQuote(symbol);
}

// ✅ CORRECT - Return error response
async function toolHandler({ symbol }) {
  if (!symbol) {
    return { content: [{ type: "text", text: "Error: Symbol required" }], isError: true };
  }
  try {
    const result = await client.getQuote(symbol);
    return { content: [{ type: "text", text: JSON.stringify(result) }] };
  } catch (error) {
    return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
  }
}
```

### Never Use Duplicate Tool Names

Later registrations silently overwrite earlier ones. Tool names must be globally unique across all 28 modules.

### Never Use Python Reserved Keywords

Avoid `from`, `class`, `for`, `while`, `return`, `import`, `export`, `default`, `const`, `let`, `var`, `function`, `try`, `catch`, `finally`, `throw`, `async`, `await`, `new`, `this`, `super`, `extends`, `static`, `get`, `set`.

Source: [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)

---

## See Also

- [AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/AGENTS.md) — Developer invariants and pitfalls
- [API Reference](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/API_REFERENCE.md) — Complete tool catalog
- [Usage Guide](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/USAGE.md) — Client setup and examples
- [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md) — Version history
- [CONTRIBUTING.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CONTRIBUTING.md) — Development setup

---

<a id='tool-development'></a>

## Tool Development Guide

### Related Pages

Related topics: [System Architecture](#architecture), [Contributing Guide](#contributing)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [GUIDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/GUIDE.md)
- [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)
- [src/tools/quotes.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)
- [src/tools/statements.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/statements.ts)
- [src/tools/sec-filings.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/sec-filings.ts)
- [src/toolception-adapters/ToolCollector.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/ToolCollector.ts)
- [src/constants/toolSets.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/constants/toolSets.ts)
</details>

# Tool Development Guide

This guide provides comprehensive instructions for extending the Financial Modeling Prep MCP Server with new tools, modules, and tool sets. It covers the complete development workflow, from adding a single tool to creating entirely new functional modules.

## Overview

The FMP MCP Server exposes 250+ financial data tools organized into 24 categories. These tools bridge the gap between the Model Context Protocol (MCP) and the Financial Modeling Prep API. The tool development framework follows a layered architecture where each new capability flows through four distinct layers: API client → tool registration → toolception adapter → tool set mapping.

**Purpose**: Enable contributors to add new financial data tools without understanding the full MCP protocol internals.

**Scope**: Adding individual tools, creating new modules, and defining tool sets for dynamic discovery.

Source: [GUIDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/GUIDE.md)

## Architecture

### Tool Registration Flow

The following diagram illustrates how a new tool moves from development through to runtime availability:

```mermaid
graph TD
    A[Create API Client Method] --> B[Register Tool in Module]
    B --> C[Create Toolception Adapter]
    C --> D[Map to Tool Set]
    D --> E[Dynamic Discovery Available]
    
    F[MCP Client Request] --> G[toolception Framework]
    G --> H[Tool Handler Execution]
    H --> I[API Client Method]
    I --> J[FMP API]
    
    style A fill:#e1f5fe
    style E fill:#c8e6c9
    style J fill:#fff3e0
```

### Layer Responsibilities

| Layer | Location | Purpose |
|-------|----------|---------|
| **API Client** | `src/api/{domain}/` | HTTP communication with FMP API |
| **Tool Registration** | `src/tools/{module}.ts` | MCP tool definitions with Zod schemas |
| **Toolception Adapter** | `src/toolception-adapters/` | Framework integration for dynamic loading |
| **Tool Set Config** | `src/constants/toolSets.ts` | Logical groupings for discovery |

Source: [GUIDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/GUIDE.md)

## Adding a New Tool

When extending existing functionality within a module, follow this three-step process:

### Step 1: Add Method to API Client

API clients live in `src/api/{domain}/`. Each domain has its own client class. Add a method that handles the HTTP request to FMP:

```typescript
// src/api/quotes/QuotesClient.ts
async getBatchQuotes(params: BatchQuotesParams): Promise<Quote[]> {
  const queryParams = new URLSearchParams({
    apikey: this.accessToken,
    ...params,
  });
  
  const response = await fetch(
    `${FMP_BASE_URL}/v3/quotes?${queryParams}`
  );
  
  if (!response.ok) {
    throw new Error(`FMP API error: ${response.status}`);
  }
  
  return response.json();
}
```

Source: [src/tools/quotes.ts:38-54](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)

### Step 2: Register Tool in Module

Add the tool registration to the corresponding module file under `src/tools/`. Use the `server.tool()` method with a Zod schema:

```typescript
import { z } from "zod";
import { QuotesClient } from "../api/quotes/QuotesClient.js";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";

export function registerQuotesTools(
  server: McpServer,
  accessToken?: string
): void {
  const quotesClient = new QuotesClient(accessToken);

  server.tool(
    "getBatchQuotes",
    "Retrieve batch stock quotes for multiple symbols in a single request.",
    {
      symbols: z.string().describe("Comma-separated list of stock symbols"),
    },
    async ({ symbols }) => {
      try {
        const results = await quotesClient.getBatchQuotes({ symbols });
        return {
          content: [{ type: "text", text: JSON.stringify(results, null, 2) }],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Error: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
          isError: true,
        };
      }
    }
  );
}
```

Source: [src/tools/quotes.ts:1-47](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)

### Step 3: Verify Zod Schema Pattern

Ensure your parameter schema follows these conventions:

| Convention | Reason | Example |
|------------|--------|---------|
| Use `from_date` not `from` | Avoids Python reserved keyword conflicts | `from_date: z.string()` |
| Use `to_date` not `to` | Avoids Python reserved keyword conflicts | `to_date: z.string()` |
| Descriptive descriptions | Required for MCP client tooling | `.describe("Start date YYYY-MM-DD")` |
| Optional parameters marked | Clarity for MCP clients | `z.number().optional()` |

> **⚠️ Known Issue**: Issue [#93](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/93) reported that Python reserved keywords in parameter names break Python MCP clients. The project addressed this by renaming `from` to `from_date` in version 2.6.9.

Source: [src/tools/sec-filings.ts:20-29](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/sec-filings.ts)

## Creating a New Module

A complete module consists of four components that must be created together:

### Module Creation Checklist

| Step | File Location | Purpose |
|------|---------------|---------|
| 1 | `src/api/{domain}/{Domain}Client.ts` | API client class |
| 2 | `src/tools/{module}.ts` | Tool registration function |
| 3 | `src/toolception-adapters/moduleAdapters.ts` | Framework adapter |
| 4 | `src/constants/toolSets.ts` | Tool set mapping |

Source: [GUIDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/GUIDE.md)

### Step 1: Create the API Client

Create a new directory under `src/api/` with your domain name and implement a client class:

```typescript
// src/api/example/ExampleClient.ts
export class ExampleClient {
  private accessToken: string;
  private baseUrl = "https://financialmodelingprep.com/api/v4";

  constructor(accessToken?: string) {
    this.accessToken = accessToken || process.env.FMP_ACCESS_TOKEN || "";
  }

  async getExampleData(params: ExampleParams): Promise<ExampleResult[]> {
    // Implementation
  }
}
```

### Step 2: Create Tool Registration Module

Create the corresponding tool registration file:

```typescript
// src/tools/example.ts
import { z } from "zod";
import { ExampleClient } from "../api/example/ExampleClient.js";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";

export function registerExampleTools(
  server: McpServer,
  accessToken?: string
): void {
  const exampleClient = new ExampleClient(accessToken);

  server.tool(
    "getExample",
    "Description of what this tool does.",
    {
      param: z.string().describe("Parameter description"),
    },
    async ({ param }) => {
      try {
        const results = await exampleClient.getExampleData({ param });
        return {
          content: [{ type: "text", text: JSON.stringify(results, null, 2) }],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Error: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
          isError: true,
        };
      }
    }
  );
}
```

Source: [src/tools/statements.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/statements.ts)

### Step 3: Create Toolception Adapter

The toolception framework enables dynamic tool discovery. Create an adapter that wraps your registration function:

```typescript
// src/toolception-adapters/moduleAdapters.ts
import { createModuleAdapter } from "./createModuleAdapter.js";
import { registerExampleTools } from "../tools/example.js";

export const exampleAdapter = createModuleAdapter(
  "example",
  "Example Module Description",
  registerExampleTools
);
```

Source: [src/toolception-adapters/ToolCollector.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/ToolCollector.ts)

### Step 4: Map to Tool Set

Add your module to the tool sets configuration:

```typescript
// src/constants/toolSets.ts
export const TOOL_SETS = {
  // ... existing sets
  example: {
    description: "Example financial data tools",
    modules: ["example"],
  },
} as const;
```

Source: [GUIDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/GUIDE.md)

## Toolception Integration

The server uses the [toolception](https://www.npmjs.com/package/toolception) framework to enable dynamic tool loading. This allows meta-tools that can enable/disable toolsets at runtime.

### How Toolception Works

```mermaid
graph LR
    A[MCP Client] -->|list_tools| B[toolception]
    B --> C[Available Tool Definitions]
    A -->|call_tool| D[Tool Handler]
    D --> E[API Client]
    E --> F[FMP API]
    
    G[Dynamic Request] -->|enable_toolset| B
    B -->|loads| H[New Tools Available]
```

### ToolCollector Pattern

The `ToolCollector` class mocks the MCP server to capture tool registrations during initialization:

```typescript
// src/toolception-adapters/ToolCollector.ts
export class ToolCollector implements ToolRegistrar {
  private tools: McpToolDefinition[] = [];

  tool(
    name: string,
    description: string,
    schema: Record<string, any>,
    handler: (params: any) => Promise<any>
  ): void {
    this.tools.push({
      name,
      description,
      inputSchema: schema,
      handler,
    });
  }
}
```

Source: [src/toolception-adapters/ToolCollector.ts:30-45](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/toolception-adapters/ToolCollector.ts)

## Critical Rules and Anti-patterns

### Key Rules

The following rules are enforced by the tools layer and must be followed:

| Rule | Description | Enforcement |
|------|-------------|-------------|
| **Never throw** | Tools must return error responses, not exceptions | Runtime validation |
| **Unique names** | Tool names must be globally unique across all modules | No duplicate detection |
| **Error format** | Error messages must use `Error: ${message}` format | MCP client compatibility |
| **Async handlers** | Tool handlers must be async functions | TypeScript types |

Source: [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)

### Anti-patterns to Avoid

```typescript
// ❌ WRONG: Throwing from tool handler
async handler({ symbol }) {
  throw new Error("Invalid symbol"); // Breaks MCP protocol
}

// ✅ CORRECT: Return error response
async handler({ symbol }) {
  return {
    content: [{ type: "text", text: "Error: Invalid symbol" }],
    isError: true,
  };
}
```

```typescript
// ❌ WRONG: Missing Error: prefix
return {
  content: [{ type: "text", text: "Something went wrong" }],
  isError: true,
};

// ✅ CORRECT: Error: prefix required
return {
  content: [{ type: "text", text: "Error: Something went wrong" }],
  isError: true,
};
```

Source: [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)

### Tool Annotations

All tools receive identical annotations for MCP compatibility:

| Annotation | Value | Purpose |
|------------|-------|---------|
| `readOnlyHint` | `true` | Indicates read-only data access |
| `idempotentHint` | `true` | Safe to retry without side effects |
| `openWorldHint` | `true` | Accesses external API |

## Common Issues and Troubleshooting

### Issue: Python Reserved Keywords

> **Community Issue [#93](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/93)**: Parameter names like `from` and `to` broke Python MCP clients.

**Symptoms**: Python-based MCP clients fail to parse tool schemas.

**Resolution**: Always use `from_date` and `to_date` instead of `from` and `to`:

```typescript
// src/tools/sec-filings.ts
async ({ from_date: from, to, page, limit }) => {
  // Note: Destructured as 'from_date' but passed as 'from' to API
  const results = await secFilingsClient.getLatest8KFilings({
    from,  // Variable is 'from' after destructuring
    to,
    page,
    limit,
  });
}
```

Source: [src/tools/sec-filings.ts:20-36](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/sec-filings.ts)

### Issue: Duplicate Tool Names

> **Symptom**: Later registration silently overwrites earlier tools with the same name.

**Prevention**: Check existing tool names in all module files before adding new tools.

### Issue: API Token Configuration

> **Community Issue [#81](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/81)**: Users struggled to set the FMP API token.

**Resolution**: The token can be configured via:
- `FMP_ACCESS_TOKEN` environment variable
- `--fmp-token` command-line argument
- Session configuration (for hosted instances)

## Testing New Tools

### Manual Testing

```bash
# Start the server in development mode
npm run dev

# Test with a MCP inspector or client
npx @modelcontextprotocol/inspector
```

### Automated Testing

Add tests to the appropriate test directory following the existing patterns in `__tests__/`.

## See Also

- [Architecture Overview](../Architecture) - High-level system design
- [Configuration Guide](../Configuration) - Server configuration options
- [Usage Guide](../Usage) - Client integration patterns
- [API Reference](../API_Reference) - Complete tool catalog
- [Contributing Guide](../Contributing) - Development setup

---

<a id='contributing'></a>

## Contributing Guide

### Related Pages

Related topics: [Tool Development Guide](#tool-development), [System Architecture](#architecture)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [CONTRIBUTING.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CONTRIBUTING.md)
- [GUIDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/GUIDE.md)
- [package.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json)
- [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md)
- [AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/AGENTS.md)
- [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)
- [src/api/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/api/AGENTS.md)
- [scripts/version-sync.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/scripts/version-sync.ts)
</details>

# Contributing Guide

This guide covers how to contribute to the Financial Modeling Prep MCP Server project. It addresses development environment setup, code architecture patterns, testing requirements, and the release process.

## Prerequisites

Before contributing, ensure your development environment meets the following requirements:

| Requirement | Minimum Version | Notes |
|-------------|-----------------|-------|
| Node.js | >= 25.3.0 | Required for ES modules and async features |
| npm | >= 11.11.0 | Package management |
| TypeScript | 5.9.2 | Strongly typed codebase |
| Git | Any recent version | Source control |

Source: [package.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json#L51-L52)

## Repository Structure

Understanding the codebase structure is essential before making contributions. The project follows a layered architecture:

```mermaid
graph TD
    A[MCP Protocol Layer<br/>toolception framework] --> B[Tools Layer<br/>28 modules, 253+ tools]
    B --> C[API Layer<br/>FMPClient + 28 domain clients]
    C --> D[Financial Modeling Prep API]

    subgraph src/
        E[api/] --> F[HTTP clients for FMP API]
        G[tools/] --> H[MCP tool registrations]
        I[toolception-adapters/] --> J[Framework integration]
        K[server-mode-enforcer/] --> L[Mode configuration]
        M[constants/] --> N[Tool sets and defaults]
        O[endpoints/] --> P[HTTP endpoints]
        Q[prompts/] --> R[MCP prompt definitions]
    end
```

Source: [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)

### Directory Reference

| Directory | Purpose |
|-----------|---------|
| `src/api/` | HTTP clients that communicate with the FMP API |
| `src/tools/` | MCP tool registrations for all FMP API endpoints |
| `src/toolception-adapters/` | Integration with the toolception framework |
| `src/server-mode-enforcer/` | Singleton for mode configuration |
| `src/constants/` | Tool set definitions and defaults |
| `src/endpoints/` | Health check and ready endpoints |
| `src/prompts/` | MCP prompt definitions |
| `scripts/` | Build, test, and publishing automation |
| `__tests__/` | Test suites including smoke tests |

Source: [CONTRIBUTING.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CONTRIBUTING.md)

## Development Setup

### Initializing the Environment

1. **Clone the repository:**
```bash
git clone https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server.git
cd Financial-Modeling-Prep-MCP-Server
```

2. **Install dependencies:**
```bash
npm install
```

3. **Build the project:**
```bash
npm run build
```

### Available npm Scripts

The project provides comprehensive npm scripts for development and quality assurance:

| Script | Purpose |
|--------|---------|
| `npm run build` | Compile TypeScript to JavaScript |
| `npm run start` | Run the production server |
| `npm run dev` | Run in development mode with watch |
| `npm run test` | Run tests in watch mode |
| `npm run test:run` | Run tests once |
| `npm run test:coverage` | Run tests with coverage report |
| `npm run typecheck` | Run TypeScript type checking |
| `npm run lint` | Run linter with warnings as errors |
| `npm run lint:fix` | Auto-fix linting issues |
| `npm run knip` | Find unused dependencies and exports |
| `npm run knip:fix` | Remove unused code automatically |

Source: [package.json](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/package.json#L23-L40)

### Development Workflow

```mermaid
graph LR
    A[Edit Code] --> B[npm run dev]
    B --> C[TypeScript compiles<br/>with watch mode]
    C --> D[Run Tests]
    D --> E{Tests Pass?}
    E -->|No| A
    E -->|Yes| F[npm run lint]
    F --> G{Lint Clean?}
    G -->|No| A
    G -->|Yes| H[Submit Pull Request]
```

## Architecture Rules and Anti-Patterns

### Key Invariants

The codebase enforces several critical rules that contributors must understand:

1. **API Key as Query Parameter** — The FMP API requires the API key as a query parameter (`?apikey=`), never as HTTP headers.
2. **Token Precedence** — Context > Instance > Environment variable hierarchy.
3. **Fail-Fast Validation** — Invalid tool sets cause `process.exit(1)` at startup.
4. **Read-Only Tools** — All tools are read-only data fetchers.
5. **Error Handling** — Tools never throw; they return `{ isError: true }` with an error message.

Source: [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md)

### Tool Layer Rules

When working in `src/tools/`, follow these rules:

| Rule | Description |
|------|-------------|
| **Never throw** | Tools must always return `{ content: [...], isError: true }` on failure |
| **Global uniqueness** | Tool names must be unique across all 28 modules |
| **Consistent annotations** | All tools get identical annotations: `readOnlyHint`, `idempotentHint`, `openWorldHint` |
| **Error format** | Error messages must use `Error: ${message}` format |

Source: [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)

### Anti-Patterns to Avoid

- **Never throw from tool handlers** — The MCP protocol expects errors in the response, not exceptions
- **Never use duplicate tool names** — Later registration silently overwrites earlier ones

Source: [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)

## Adding New Tools

### Adding a Tool to an Existing Module

For extending existing functionality:

1. Add the API method to the appropriate client in `src/api/{domain}/`
2. Register the tool in `src/tools/{module}.ts`
3. Follow the Zod schema pattern for parameters

Example tool registration pattern:

```typescript
server.tool(
  "getQuote",
  "Access real-time stock quotes with the FMP Stock Quote API.",
  {
    symbol: z.string().describe("Stock symbol"),
  },
  async ({ symbol }) => {
    try {
      const results = await quotesClient.getQuote({ symbol });
      return {
        content: [{ type: "text", text: JSON.stringify(results, null, 2) }],
      };
    } catch (error) {
      return {
        content: [
          {
            type: "text",
            text: `Error: ${error instanceof Error ? error.message : String(error)}`,
          },
        ],
        isError: true,
      };
    }
  }
);
```

Source: [src/tools/quotes.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts#L1-L42)

### Adding a New Module

When creating an entirely new domain:

1. Create `src/api/{domain}/{Domain}Client.ts` — HTTP client for FMP API
2. Create `src/tools/{module}.ts` — Tool registration function
3. Add adapter in `src/toolception-adapters/moduleAdapters.ts` — Framework integration
4. Map to tool set in `src/constants/toolSets.ts` — Tool set definition

### Adding a New Tool Set

1. Add definition to `TOOL_SETS` in `src/constants/toolSets.ts`
2. Add type to `ToolSet` union in `src/types/index.ts`

Source: [GUIDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/GUIDE.md)

## Testing Requirements

### Test Suite Structure

| Test Type | Location | Purpose |
|-----------|----------|---------|
| Unit Tests | `__tests__/unit/` | Individual component testing |
| Smoke Tests | `__tests__/smoke/` | End-to-end integration testing |
| Registry Tests | `__tests__/unit/registry-tests/` | MCP registry publishing |

Source: [AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/AGENTS.md)

### Running Tests

```bash
# Run tests in watch mode during development
npm run test

# Run tests once (CI/CD)
npm run test:run

# Run with coverage report
npm run test:coverage
```

### Smoke Test Requirements

Smoke tests have specific requirements that must be met:

- **Build first** — Run `npm run build` before executing smoke tests
- **SSE parsing** — Verify Server-Sent Events are properly parsed
- **Global session state** — Tests must handle singleton state correctly

Source: [AGENTS.md - __tests__/smoke/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/AGENTS.md)

## Code Quality Standards

### TypeScript

The project uses strict TypeScript typing throughout. Before committing:

```bash
# Check types without emitting
npm run typecheck
```

### Linting

The project uses oxlint with warnings treated as errors:

```bash
# Check for linting issues
npm run lint

# Auto-fix issues
npm run lint:fix
```

### Dependency Management

Use `knip` to identify unused dependencies and exports:

```bash
# Find unused code
npm run knip

# Remove unused code
npm run knip:fix
```

## Version Management

### Version Synchronization

The project uses a version synchronization script to keep version numbers consistent across files:

```bash
# Validate version consistency
npm run version:validate

# Sync versions across all files
npm run version:sync

# Display version information
npm run version:info
```

The script maintains version consistency in:
- `package.json`
- `package-lock.json`
- `README.md`
- `CHANGELOG.md`

Source: [docs/version-sync.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/version-sync.md)

### Versioning Policy

The project follows Semantic Versioning:

| Version Type | Description |
|--------------|-------------|
| **MAJOR** | Incompatible API changes |
| **MINOR** | Backwards-compatible functionality additions |
| **PATCH** | Backwards-compatible bug fixes |

Source: [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md)

## Release Process

### Release Checklist

Before creating a release:

1. Update version in `package.json`
2. Run version synchronization: `npm run version:sync`
3. Update `CHANGELOG.md` with new version section
4. Verify GitHub secrets are configured: `npm run verify:github-secrets`
5. Create git tag: `git tag v{version}`
6. Push changes and tag: `git push origin main --tags`

### Automated Publishing

Starting with version 2.5.0, releases are fully automated through GitHub Actions:

| Trigger | Action |
|---------|--------|
| Git tag push (`v*` pattern) | NPM publishing, MCP registry update, GitHub release creation |
| Requires `NPM_TOKEN` secret | Authenticates with NPM registry |
| Uses GitHub OIDC | Authenticates with MCP registry |

Source: [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md)

### Publishing Workflow

```mermaid
graph TD
    A[git tag v{version}] --> B[Push to origin]
    B --> C[GitHub Actions Triggered]
    C --> D{NPM_TOKEN valid?}
    D -->|Yes| E[Publish to NPM Registry]
    D -->|No| F[Fail with clear error]
    E --> G[Update MCP Registry]
    G --> H[Create GitHub Release]
    H --> I[Release Notes Generated]
```

### Manual Publishing

For manual deployment, use the `scripts/manual-publish.ts` script:

```bash
npx tsx scripts/manual-publish.ts [options]
```

Options include `--dry-run`, `--skip-npm`, `--skip-registry`, `--skip-validation`, and `--force`.

## Pull Request Guidelines

### Before Submitting

1. **Run all checks locally:**
```bash
npm run build && npm run test:run && npm run lint && npm run typecheck
```

2. **Update documentation** if adding features or changing behavior

3. **Update CHANGELOG.md** under the `[Unreleased]` section

4. **Follow the directory structure** — place related code in appropriate directories

### Commit Messages

Use clear, descriptive commit messages that explain what changed and why.

### Handling Known Issues

Be aware of known issues that may affect contributions:

| Issue | Description | Mitigation |
|-------|-------------|------------|
| Python reserved keywords | Tool schemas use keywords that break Python MCP clients | Use alternative parameter names (e.g., `from_date` instead of `from`) |
| Plan-gate false positives | Some endpoints incorrectly blocked for Ultimate plan users | Test with appropriate API keys |

Source: [Community Issues #93](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/93), [#100](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/100)

## Navigation to Related Documentation

| Document | Purpose |
|----------|---------|
| [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md) | Architecture overview and key invariants |
| [GUIDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/GUIDE.md) | How-to guides and procedural content |
| [AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/AGENTS.md) | Agent-specific pitfalls and rules |
| [src/api/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/api/AGENTS.md) | API layer invariants |
| [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md) | Tool layer rules |
| [docs/automated-publishing.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/automated-publishing.md) | Publishing automation details |

## See Also

- [README.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/README.md) — Project overview and quick start
- [AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/AGENTS.md) — Non-obvious pitfalls and invariants
- [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md) — Version history and release notes
- [docs/USAGE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/USAGE.md) — Client-specific setup instructions

---

<a id='troubleshooting'></a>

## Troubleshooting

### Related Pages

Related topics: [Configuration Guide](#configuration), [Installation Guide](#installation), [Usage Guide](#usage-guide)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [src/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/index.ts)
- [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)
- [docs/USAGE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/USAGE.md)
- [src/tools/quotes.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/quotes.ts)
- [src/schemas/SessionConfigSchema.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/schemas/SessionConfigSchema.ts)
- [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md)
</details>

# Troubleshooting

This page provides guidance for diagnosing and resolving common issues with the Financial Modeling Prep MCP Server. It covers configuration problems, error patterns, and debugging techniques based on the server's architecture and known issues.

## Overview

The FMP MCP Server exposes 250+ financial data tools via the Model Context Protocol, acting as a bridge between AI assistants and the Financial Modeling Prep API. Troubleshooting typically involves three layers:

1. **Configuration Layer** — API token setup, environment variables, and session configuration
2. **MCP Protocol Layer** — Tool registration, schema validation, and plan-gate enforcement
3. **API Layer** — HTTP client communication with FMP endpoints

Understanding which layer an error originates from is essential for effective troubleshooting.

## Common Issues

### API Token Configuration

The most frequently reported issue involves setting the FMP API token correctly. The server supports three configuration methods with a specific precedence order.

#### Token Precedence

```
Session Config > Instance Config > Environment Variable
```

Source: [docs/USAGE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/docs/USAGE.md)

#### Configuration Methods

| Method | Description | Use Case |
|--------|-------------|----------|
| Session Config | Pass `{"FMP_ACCESS_TOKEN":"your_token"}` in MCP session initialization | Per-session tokens, hosted deployments |
| `--fmp-token` CLI Flag | Pass token via command line argument | Self-hosted installations |
| `FMP_ACCESS_TOKEN` env var | Set environment variable | Containerized or persistent deployments |

#### Resolving "Missing FMP_ACCESS_TOKEN" Errors

If you encounter errors indicating the token is missing, verify the following:

1. **For Smithery.ai deployments**: The token must be set in session configuration, not OAuth fields. Create your app with blank OAuth fields and provide `FMP_ACCESS_TOKEN` through the session config interface.

2. **For self-hosted deployments**: Ensure the token is available at startup:
   ```bash
   FMP_ACCESS_TOKEN=your_token npx financial-modeling-prep-mcp-server
   ```

3. **Check server logs**: The server logs a warning if no token is configured:
   ```
   [FMP MCP Server] No server-level FMP access token configured.
   ```

Source: [src/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/index.ts)

#### Session Configuration Schema

Only `FMP_ACCESS_TOKEN` is effective at the session level. Other parameters like `FMP_TOOL_SETS` and `DYNAMIC_TOOL_DISCOVERY` exist in the schema but are no-ops—mode configuration is fixed at server startup.

```typescript
interface SessionConfig {
  FMP_ACCESS_TOKEN: string;
}
```

Source: [src/schemas/SessionConfigSchema.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/schemas/SessionConfigSchema.ts)

### Plan-Gate False Positives

#### Issue: Batch Quote Endpoint Blocked for Ultimate Plan Users

A known issue ([#100](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/100)) causes the `getBatchQuotesShort` tool to return "ACCESS DENIED" errors for users on the Ultimate plan. The block occurs at the MCP layer before the request reaches the FMP API.

**Symptom:**
```
Error: ACCESS DENIED - This endpoint is available on higher-tier plans
```

**Root Cause:** The MCP layer's plan-gate validation incorrectly identifies batch quote endpoints as requiring a premium tier even when the user's FMP plan includes access.

**Workaround:** Use individual quote requests instead of batch requests:
- Instead of `getBatchQuotesShort`, use multiple `getQuote` calls
- Individual quote requests bypass the faulty plan-gate validation

**Status:** This is a known bug tracked in [issue #100](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/100).

### Python Reserved Keywords in Parameter Names

#### Issue: Tool Schemas Incompatible with Python MCP Clients

Issue [#93](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/93) identifies that several tools use parameter names that conflict with Python reserved keywords or contain invalid identifiers.

**Two Categories of Problems:**

1. **Python Reserved Keywords**: Parameters named `from`, `list`, `type`, `id`, `str`, `int`, `float`, `bool`, `lambda`, `class`, `def`, `return`, `import`, `export`, `async`, `await`, `try`, `except`, `finally`, `with`, `as`, `pass`, `break`, `continue`, `raise`, `yield`, `global`, `nonlocal`, `assert`, `del`, `in`, `is`, `not`, `or`, `and`, `None`, `True`, `False`.

2. **Invalid Identifiers**: Parameters starting with numbers or containing special characters.

**Resolution (v2.6.9+)**: Starting with version 2.6.9, the `from` parameter was renamed to `from_date` in affected tools. Check the [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md) for the complete list of renamed parameters.

**Example Fix:**
```typescript
// Before (v2.6.8)
async ({ from, to, page, limit }) => { ... }

// After (v2.6.9+)
async ({ from_date: from, to, page, limit }) => { ... }
```

Source: [src/tools/sec-filings.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/sec-filings.ts)

## Error Handling Patterns

### Tool Layer Error Contract

All MCP tools follow a strict error handling contract defined in [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md):

| Rule | Description |
|------|-------------|
| **Never Throw** | Tools must never throw exceptions |
| **Always Return** | Return `{ content: [...], isError: true }` for errors |
| **Error Format** | Error message must be `Error: ${message}` |

Source: [src/tools/AGENTS.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/tools/AGENTS.md)

### Standard Error Response Format

```typescript
{
  content: [{
    type: "text",
    text: "Error: descriptive error message"
  }],
  isError: true
}
```

### Common Error Messages

| Error Pattern | Likely Cause | Resolution |
|---------------|--------------|------------|
| `Error: ACCESS DENIED` | Invalid or missing API token, or plan-gate false positive | Verify token, check plan tier, use workaround for batch endpoints |
| `Error: Missing FMP_ACCESS_TOKEN` | No token configured | Set token via session config, CLI arg, or environment variable |
| `Error: Network request failed` | FMP API unreachable | Check network connectivity, verify FMP API status |
| `Error: Invalid parameter` | Schema validation failure | Check parameter types and constraints |
| `Error: 4xx` | FMP API returned client error | Check API key validity and rate limits |

## Debugging Techniques

### Enabling Verbose Logging

The server outputs detailed configuration information at startup. Review the logs for:

```
[FMP MCP Server] Toolception config: {
  "startup": "...",
  "exposurePolicy": "...",
  "catalogKeys": [...],
  "moduleLoaderKeys": [...]
}
```

Source: [src/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/index.ts)

### Client ID Header Injection

The server includes middleware that injects an `mcp-client-id` header when missing. This addresses compatibility issues with MCP clients that don't send the required header:

```typescript
// If mcp-client-id is missing, a stable client ID is generated
// based on request fingerprint (IP, user-agent, etc.)
```

Source: [src/index.ts](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/src/index.ts)

### Key Invariants for Diagnostics

These invariants, defined in [CLAUDE.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CLAUDE.md), help identify where issues occur:

| Invariant | Implication |
|-----------|-------------|
| API Key as Query Parameter | FMP requires `?apikey=`, never headers |
| Token Precedence | Context > Instance > Environment |
| Session Restrictions | Only `FMP_ACCESS_TOKEN` takes effect per-session |
| Read-Only Tools | All tools are read-only data fetchers |

## Version-Specific Issues

### Version 2.6.9 — Python Keyword Fix

This release renamed `from` to `from_date` to avoid Python reserved keyword conflicts. If you're using older tooling that relies on the old parameter name, update to match the new schema.

### Version 2.6.7 — Session Config Clarification

Documentation was clarified to explicitly state that only `FMP_ACCESS_TOKEN` can be set per-session. Previous confusion arose from other parameters appearing in the schema.

## Getting Help

If you encounter an issue not covered here:

1. **Check the [Issues](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues)** to see if it's a known bug
2. **Search the [CHANGELOG.md](https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/blob/main/CHANGELOG.md)** for recent fixes
3. **Enable verbose logging** to capture detailed error information
4. **Report new issues** with:
   - Server version (`npm list financial-modeling-prep-mcp-server`)
   - Complete error message
   - Steps to reproduce
   - MCP client and configuration details

## See Also

- [README.md](README.md) — Project overview and quick start
- [docs/USAGE.md](docs/USAGE.md) — Detailed usage instructions
- [docs/API_REFERENCE.md](docs/API_REFERENCE.md) — Complete tool catalog
- [src/tools/AGENTS.md](src/tools/AGENTS.md) — Tool layer implementation guidelines

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Pitfall Log

# Pitfall Log

Project: imbenrabi/financial-modeling-prep-mcp-server

Summary: 发现 10 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 来源证据：Tool input schemas use Python reserved keywords and invalid identifiers as parameter names, breaking Python MCP clients。

## 1. 安装坑 · 来源证据：Tool input schemas use Python reserved keywords and invalid identifiers as parameter names, breaking Python MCP clients

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Tool input schemas use Python reserved keywords and invalid identifiers as parameter names, breaking Python MCP clients
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_75b7a65ba21a4165943ec8a7ebcd0091 | https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/93 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 2. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | mcp_registry:io.github.imbenrabi/financial-modeling-prep-mcp-server:2.6.10 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.imbenrabi%2Ffinancial-modeling-prep-mcp-server/versions/2.6.10 | README/documentation is current enough for a first validation pass.

## 3. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | mcp_registry:io.github.imbenrabi/financial-modeling-prep-mcp-server:2.6.10 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.imbenrabi%2Ffinancial-modeling-prep-mcp-server/versions/2.6.10 | last_activity_observed missing

## 4. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | mcp_registry:io.github.imbenrabi/financial-modeling-prep-mcp-server:2.6.10 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.imbenrabi%2Ffinancial-modeling-prep-mcp-server/versions/2.6.10 | no_demo; severity=medium

## 5. 安全/权限坑 · 存在安全注意事项

- 严重度：medium
- 证据强度：source_linked
- 发现：No sandbox install has been executed yet; downstream must verify before user use.
- 对用户的影响：用户安装前需要知道权限边界和敏感操作。
- 建议检查：转成明确权限清单和安全审查提示。
- 防护动作：安全注意事项必须面向用户前置展示。
- 证据：risks.safety_notes | mcp_registry:io.github.imbenrabi/financial-modeling-prep-mcp-server:2.6.10 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.imbenrabi%2Ffinancial-modeling-prep-mcp-server/versions/2.6.10 | No sandbox install has been executed yet; downstream must verify before user use.

## 6. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | mcp_registry:io.github.imbenrabi/financial-modeling-prep-mcp-server:2.6.10 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.imbenrabi%2Ffinancial-modeling-prep-mcp-server/versions/2.6.10 | no_demo; severity=medium

## 7. 安全/权限坑 · 来源证据：FMP API KEY impossible to set

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：FMP API KEY impossible to set
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_9ae13b6fa15041539df40160e45bb1b0 | https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/81 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。

## 8. 安全/权限坑 · 来源证据：batch-quote endpoint incorrectly blocked for Ultimate plan users — MCP plan-gate false positive

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：batch-quote endpoint incorrectly blocked for Ultimate plan users — MCP plan-gate false positive
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_e69c7ecfae6b40be92a4af0220588aaf | https://github.com/imbenrabi/Financial-Modeling-Prep-MCP-Server/issues/100 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。

## 9. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | mcp_registry:io.github.imbenrabi/financial-modeling-prep-mcp-server:2.6.10 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.imbenrabi%2Ffinancial-modeling-prep-mcp-server/versions/2.6.10 | issue_or_pr_quality=unknown

## 10. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | mcp_registry:io.github.imbenrabi/financial-modeling-prep-mcp-server:2.6.10 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.imbenrabi%2Ffinancial-modeling-prep-mcp-server/versions/2.6.10 | release_recency=unknown

<!-- canonical_name: imbenrabi/financial-modeling-prep-mcp-server; human_manual_source: deepwiki_human_wiki -->
