> ## Documentation Index
> Fetch the complete documentation index at: https://finance.chiefpriest.design/llms.txt
> Use this file to discover all available pages before exploring further.

# Model Context Protocol (MCP)

> Understanding MCP integration for AI agents and tools

## What is MCP?

The Model Context Protocol (MCP) is a standardized protocol that enables AI agents to interact with external tools and data sources. Our Financial MCP Server implements this protocol to provide seamless financial data access to AI systems like Claude.

<Info>
  MCP allows AI agents to call financial tools directly, making it perfect for building AI-powered financial analysis applications.
</Info>

## How It Works

```mermaid theme={null}
sequenceDiagram
    participant AI as AI Agent (Claude)
    participant MCP as MCP Server
    participant FMP as Financial APIs
    
    AI->>MCP: Request stock quote for AAPL
    MCP->>FMP: Fetch AAPL data
    FMP->>MCP: Return stock data
    MCP->>AI: Formatted response
```

## MCP vs REST API

<CardGroup cols={2}>
  <Card title="MCP Protocol" icon="robot">
    **For AI Agents**

    * Native AI integration
    * Structured tool calls
    * Type-safe parameters
    * Error handling optimized for AI
  </Card>

  <Card title="REST API" icon="code">
    **For Applications**

    * Standard HTTP endpoints
    * Web framework integration
    * Frontend/mobile apps
    * Traditional API consumers
  </Card>
</CardGroup>

## Available MCP Tools

### YFinance Tools (6 tools)

```json theme={null}
{
  "method": "tools/call",
  "params": {
    "name": "get_stock_quote",
    "arguments": {"symbol": "AAPL"}
  }
}
```

**Available Tools:**

* `get_stock_quote` - Real-time stock quotes
* `get_company_overview` - Company information
* `get_time_series_daily` - Historical data
* `search_symbol` - Symbol search
* `get_recommendations` - Analyst recommendations
* `get_insider_transactions` - Insider trading data

### FMP Tools (26 tools)

```json theme={null}
{
  "method": "tools/call",
  "params": {
    "name": "fmp_get_market_gainers",
    "arguments": {"random_string": "dummy"}
  }
}
```

**Categories:**

* **Core Financial**: `fmp_get_stock_quote`, `fmp_get_financial_statements`, `fmp_get_key_metrics`, `fmp_get_dcf_valuation`
* **Market Data**: `fmp_get_market_gainers`, `fmp_get_market_losers`, `fmp_get_most_active`, `fmp_get_sector_performance`
* **Screening**: `fmp_stock_screener`, `fmp_search_advanced`, `fmp_get_stock_news`, `fmp_get_price_targets`
* **Advanced**: `fmp_get_options_chain`, `fmp_get_technical_indicators`, `fmp_get_crypto_prices`

## Integration Examples

### Claude Desktop Integration

Add to your Claude Desktop MCP configuration:

```json theme={null}
{
  "mcpServers": {
    "financial-data": {
      "command": "python",
      "args": ["/path/to/financial-mcp-server/main.py"],
      "env": {
        "FMP_API_KEY": "your_api_key_here"
      }
    }
  }
}
```

### Custom AI Agent Integration

<CodeGroup>
  ```python Python MCP Client theme={null}
  import asyncio
  from mcp import ClientSession, StdioServerParameters
  from mcp.client.stdio import stdio_client

  async def call_financial_tool():
      server_params = StdioServerParameters(
          command="python",
          args=["main.py"],
          env={"FMP_API_KEY": "your_key"}
      )
      
      async with stdio_client(server_params) as (read, write):
          async with ClientSession(read, write) as session:
              # Initialize the session
              await session.initialize()
              
              # Call a tool
              result = await session.call_tool(
                  "get_stock_quote",
                  {"symbol": "AAPL"}
              )
              
              print(f"AAPL Price: ${result.content[0].text}")

  asyncio.run(call_financial_tool())
  ```

  ```javascript Node.js MCP Client theme={null}
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
  import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';

  const transport = new StdioClientTransport({
    command: 'python',
    args: ['main.py'],
    env: { FMP_API_KEY: 'your_key' }
  });

  const client = new Client({
    name: "financial-client",
    version: "1.0.0"
  }, {
    capabilities: {}
  });

  await client.connect(transport);

  const result = await client.callTool({
    name: "get_stock_quote",
    arguments: { symbol: "AAPL" }
  });

  console.log(`AAPL Price: $${JSON.parse(result.content[0].text).price}`);
  ```
</CodeGroup>

## Tool Response Format

All MCP tools return structured responses:

```json theme={null}
{
  "content": [
    {
      "type": "text",
      "text": "{\"symbol\": \"AAPL\", \"price\": 201.08, \"source\": \"FMP\"}"
    }
  ],
  "isError": false
}
```

## Error Handling

MCP tools provide detailed error information:

```json theme={null}
{
  "content": [
    {
      "type": "text", 
      "text": "{\"error\": \"Invalid symbol\", \"detail\": \"Symbol 'INVALID' not found\"}"
    }
  ],
  "isError": true
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="Tool Selection">
    * Use FMP tools for reliability and comprehensive data
    * Use YFinance tools for basic data when FMP quota is exceeded
    * Always handle potential rate limiting and errors
  </Accordion>

  <Accordion title="Parameter Validation">
    * Validate stock symbols before making calls
    * Use uppercase symbols (AAPL, not aapl)
    * Check required vs optional parameters for each tool
  </Accordion>

  <Accordion title="Response Processing">
    * Parse JSON responses properly
    * Handle both success and error cases
    * Cache responses when appropriate to reduce API calls
  </Accordion>

  <Accordion title="Rate Limiting">
    * Monitor API usage, especially with FMP free tier (250/day)
    * Implement exponential backoff for retries
    * Consider upgrading to paid plans for production use
  </Accordion>
</AccordionGroup>

## Server Configuration

The MCP server automatically starts with both protocols:

```bash theme={null}
🚀 Starting Enhanced Financial MCP Server
📡 MCP Protocol: http://0.0.0.0:8001/
🌐 REST API: http://0.0.0.0:8001/api/v1/
🔧 Tools Available: 32 (6 YFinance + 26 FMP)
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="Connection Issues">
    **Symptoms**: Cannot connect to MCP server

    **Solutions**:

    * Verify server is running on correct port
    * Check environment variables are set
    * Ensure Python dependencies are installed
  </Accordion>

  <Accordion title="Tool Call Failures">
    **Symptoms**: Tools return errors or timeout

    **Solutions**:

    * Verify FMP API key is valid
    * Check internet connectivity
    * Monitor rate limits
    * Review tool parameters
  </Accordion>

  <Accordion title="Response Parsing">
    **Symptoms**: Cannot parse tool responses

    **Solutions**:

    * Ensure JSON parsing handles both success/error cases
    * Check for nested response structures
    * Validate data types match expectations
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Tool Reference" icon="wrench" href="/api-reference/introduction">
    Complete list of all 32 available MCP tools
  </Card>

  <Card title="Integration Guide" icon="puzzle" href="/guides/frontend-integration">
    Step-by-step integration with your AI application
  </Card>
</CardGroup>
