> ## 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.

# Architecture

> Technical architecture and design patterns of the Financial MCP Server

## System Overview

The Financial MCP Server is built as a hybrid platform supporting both Model Context Protocol (MCP) and REST API interfaces, providing seamless access to financial data from multiple sources.

```mermaid theme={null}
graph TB
    subgraph "Client Layer"
        A[AI Agents]
        B[Web Applications]
        C[Mobile Apps]
        D[CLI Tools]
    end
    
    subgraph "Protocol Layer"
        E[MCP Protocol Handler]
        F[REST API Handler]
    end
    
    subgraph "Application Layer"
        G[Financial MCP Server]
        H[Tool Registry]
        I[Error Handling]
        J[Rate Limiting]
    end
    
    subgraph "Data Layer"
        K[YFinance Tools]
        L[FMP Tools]
        M[Data Validation]
        N[Response Formatting]
    end
    
    subgraph "External APIs"
        O[Yahoo Finance]
        P[Financial Modeling Prep]
    end
    
    A --> E
    B --> F
    C --> F
    D --> F
    
    E --> G
    F --> G
    
    G --> H
    G --> I
    G --> J
    
    H --> K
    H --> L
    K --> M
    L --> M
    M --> N
    
    K --> O
    L --> P
    
    style G fill:#0D9373
    style E fill:#07C983
    style F fill:#07C983
```

## Core Components

### 1. Protocol Handlers

#### MCP Protocol Handler

* **Purpose**: Native AI agent integration
* **Technology**: Model Context Protocol standard
* **Features**: Structured tool calls, type safety, error handling
* **Use Case**: Claude Desktop, custom AI agents

#### REST API Handler

* **Purpose**: Traditional web/mobile application integration
* **Technology**: FastAPI with automatic OpenAPI documentation
* **Features**: HTTP endpoints, JSON responses, CORS support
* **Use Case**: Frontend applications, mobile apps, webhooks

### 2. Application Core

#### Financial MCP Server (`main.py`)

```python theme={null}
# Hybrid server supporting both protocols
app = FastAPI(title="Financial MCP Server")
mcp = MCPServer("financial-data")

# Single server, dual protocols
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=PORT)
```

**Responsibilities**:

* Protocol routing and handling
* Server lifecycle management
* Configuration management
* Logging and monitoring

#### Tool Registry

```python theme={null}
# Centralized tool registration
@mcp.tool("get_stock_quote")
async def mcp_get_stock_quote(symbol: str):
    return await get_stock_quote(symbol)

@app.get("/api/v1/stock/{symbol}")
async def rest_get_stock_quote(symbol: str):
    return await get_stock_quote(symbol)
```

**Features**:

* Single function, dual exposure (MCP + REST)
* Consistent error handling
* Parameter validation
* Response formatting

### 3. Data Access Layer

#### YFinance Tools (`tools/yfinance_tools.py`)

```python theme={null}
# Native Python library integration
async def get_stock_quote(symbol: str) -> Dict[str, Any]:
    def _fetch_quote():
        ticker = yf.Ticker(symbol)
        return ticker.info
    
    return handle_yfinance_request(_fetch_quote)
```

**Features**:

* Rate limiting protection
* Automatic retry logic
* Error handling and fallback
* Data normalization

#### FMP Tools (`tools/fmp_tools.py`)

```python theme={null}
# Professional API integration
async def fmp_get_stock_quote(symbol: str) -> Dict[str, Any]:
    endpoint = f"quote/{symbol}"
    data = await fmp_request(endpoint)
    return format_response(data)
```

**Features**:

* Professional API reliability
* Structured data responses
* Comprehensive error handling
* Rate limit monitoring

#### Utility Layer (`tools/fmp_utils.py`)

```python theme={null}
# Shared utilities and helpers
async def fmp_request(endpoint: str, params: dict = None) -> dict:
    # Common request handling
    # Error processing
    # Response validation
```

## Design Patterns

### 1. Adapter Pattern

Each data source implements a common interface:

```python theme={null}
# Common interface for all data sources
class DataSource:
    async def get_quote(self, symbol: str) -> Dict[str, Any]
    async def get_company_info(self, symbol: str) -> Dict[str, Any]
    async def get_historical_data(self, symbol: str) -> Dict[str, Any]
```

### 2. Strategy Pattern

Different strategies for data retrieval:

```python theme={null}
# Strategy selection based on requirements
def select_data_source(requirement: str) -> DataSource:
    if requirement == "free":
        return YFinanceAdapter()
    elif requirement == "professional":
        return FMPAdapter()
    elif requirement == "hybrid":
        return HybridAdapter()  # Try YFinance, fallback to FMP
```

### 3. Decorator Pattern

Cross-cutting concerns handled via decorators:

```python theme={null}
@rate_limit_protection
@error_handling
@response_formatting
async def get_stock_quote(symbol: str):
    # Core business logic
    pass
```

## Modular Structure

```
yfi-deployment/
├── main.py                 # Server entry point
├── api/
│   ├── __init__.py
│   └── rest_routes.py      # REST endpoint definitions
├── tools/
│   ├── __init__.py
│   ├── yfinance_tools.py   # YFinance integration (6 tools)
│   ├── fmp_tools.py        # FMP integration (26 tools)
│   └── fmp_utils.py        # Shared FMP utilities
├── requirements.txt        # Dependencies
├── Procfile               # Deployment configuration
└── docs/                  # Documentation (separate folder)
```

### Benefits of Modular Design

<AccordionGroup>
  <Accordion title="Maintainability">
    * Clear separation of concerns
    * Easy to locate and modify specific functionality
    * Reduced coupling between components
  </Accordion>

  <Accordion title="Scalability">
    * Add new data sources without affecting existing code
    * Independent scaling of different components
    * Easy to extend with additional tools
  </Accordion>

  <Accordion title="Testability">
    * Unit test individual components in isolation
    * Mock external dependencies easily
    * Clear interfaces for testing
  </Accordion>

  <Accordion title="Reusability">
    * Tools can be used in both MCP and REST contexts
    * Utilities shared across different data sources
    * Easy integration into other projects
  </Accordion>
</AccordionGroup>

## Data Flow

### Request Processing Flow

```mermaid theme={null}
sequenceDiagram
    participant C as Client
    participant S as Server
    participant T as Tool
    participant D as Data Source
    participant E as External API
    
    C->>S: Request (MCP/REST)
    S->>S: Validate Parameters
    S->>T: Call Tool Function
    T->>T: Apply Rate Limiting
    T->>D: Data Source Request
    D->>E: External API Call
    E->>D: Raw Data Response
    D->>T: Formatted Data
    T->>S: Tool Response
    S->>C: Final Response (JSON)
```

### Error Handling Flow

```mermaid theme={null}
flowchart TD
    A[Request] --> B{Validate Parameters}
    B -->|Invalid| C[Return 400 Error]
    B -->|Valid| D[Call Tool]
    D --> E{Data Source Available?}
    E -->|No| F[Return 503 Error]
    E -->|Yes| G[Make API Call]
    G --> H{Rate Limited?}
    H -->|Yes| I[Apply Backoff]
    I --> J{Retry Successful?}
    J -->|No| K[Return 429 Error]
    J -->|Yes| L[Return Data]
    H -->|No| M{API Error?}
    M -->|Yes| N[Return 500 Error]
    M -->|No| L
    G --> L[Format & Return Data]
```

## Performance Considerations

### 1. Asynchronous Processing

```python theme={null}
# Non-blocking I/O for concurrent requests
async def handle_multiple_requests():
    tasks = [
        get_stock_quote("AAPL"),
        get_stock_quote("MSFT"),
        get_stock_quote("GOOGL")
    ]
    results = await asyncio.gather(*tasks)
    return results
```

### 2. Connection Pooling

```python theme={null}
# Reuse HTTP connections
session = aiohttp.ClientSession(
    connector=aiohttp.TCPConnector(
        limit=100,
        limit_per_host=30
    )
)
```

### 3. Response Caching

```python theme={null}
# Cache frequently requested data
@lru_cache(maxsize=1000)
def get_cached_quote(symbol: str, timestamp: int):
    # Cache for 1 minute intervals
    return fetch_quote(symbol)
```

## Security Architecture

### 1. API Key Management

```python theme={null}
# Secure environment variable handling
FMP_API_KEY = os.getenv("FMP_API_KEY", "demo")
if FMP_API_KEY == "demo":
    logger.warning("Using demo API key - limited functionality")
```

### 2. Input Validation

```python theme={null}
# Strict parameter validation
def validate_symbol(symbol: str) -> str:
    if not symbol or len(symbol) > 10:
        raise ValueError("Invalid symbol")
    return symbol.upper().strip()
```

### 3. Rate Limiting

```python theme={null}
# Protect against abuse
@rate_limit(requests_per_minute=60)
async def protected_endpoint():
    pass
```

## Deployment Architecture

### Development

```
Local Machine
├── Python 3.11+
├── Virtual Environment
├── Environment Variables
└── Direct API Access
```

### Production (Railway)

```
Railway Platform
├── Automatic Deployment
├── Environment Management
├── Load Balancing
├── SSL Termination
└── Monitoring & Logs
```

### Container (Docker)

```
Docker Container
├── Python Runtime
├── Application Code
├── Dependencies
├── Environment Config
└── Health Checks
```

## Monitoring & Observability

### Logging Strategy

```python theme={null}
import logging

# Structured logging
logger = logging.getLogger(__name__)
logger.info("Stock quote requested", extra={
    "symbol": symbol,
    "source": "FMP",
    "response_time": response_time
})
```

### Health Checks

```python theme={null}
@app.get("/api/v1/health")
async def health_check():
    return {
        "status": "healthy",
        "tools_available": 32,
        "data_sources": ["YFinance", "FMP"],
        "timestamp": datetime.now().isoformat()
    }
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Development Setup" icon="code" href="/installation">
    Set up local development environment
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Explore all available endpoints and tools
  </Card>

  <Card title="Deployment Guide" icon="rocket" href="/guides/deployment">
    Deploy to production environments
  </Card>

  <Card title="Contributing" icon="git-branch" href="/guides/configuration">
    Extend and customize the server
  </Card>
</CardGroup>
