# Model Context Protocol (MCP) Integration

Dexorder uses the Model Context Protocol for user-specific tool execution and state management.

## Container Architecture

Each user has a dedicated Kubernetes pod running:
- **Agent Container**: Python environment with conda packages
- **Lifecycle Sidecar**: Manages container lifecycle and communication
- **Persistent Storage**: User's git repository with indicators/strategies

## Authentication Modes

Three MCP authentication modes:

### 1. Public Mode (Free Tier)
- No authentication required
- Container creates anonymous session
- Limited to read-only resources
- Session expires after timeout

### 2. Gateway Auth Mode (Standard)
- Gateway authenticates user
- Passes verified user ID to container
- Container trusts gateway's authentication
- Full access to user's tools and data

### 3. Direct Auth Mode (Enterprise)
- User authenticates directly with container
- Gateway forwards encrypted credentials
- Container validates credentials independently
- Highest security for sensitive operations

## MCP Resources

The container exposes standard resources:

### context://user-profile
User preferences and trading style

### context://conversation-summary
Recent conversation context and history

### context://workspace-state
Current chart, indicators, and analysis state

### context://system-prompt
User's custom agent instructions

### indicators://list
Available indicators with signatures

### strategies://list
User's trading strategies

## Tool Execution Flow

1. User sends message to gateway
2. Gateway queries user's MCP resources for context
3. LLM generates response with tool calls
4. Gateway routes tool calls:
   - Platform tools → handled by gateway
   - User tools → proxied to MCP container
5. Tool results returned to LLM
6. Final response sent to user
7. Conversation saved to MCP container

## Container Lifecycle

### Startup
1. Gateway receives user connection
2. Checks if container exists
3. Creates pod if needed (cold start ~5-10s)
4. Waits for container ready
5. Establishes MCP connection

### Active
- Container stays alive during active session
- Receives tool calls via MCP
- Maintains workspace state
- Saves files to persistent storage

### Shutdown
- Free users: timeout after 15 minutes idle
- Paid users: longer timeout based on license
- Graceful shutdown saves state
- Persistent storage retained
- Fast restart on next connection
