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

# MCP quickstart — connect Claude or Cursor to AI2Fin

> Connect AI assistants like Claude and Cursor to your AI2Fin financial data in minutes using OAuth or API key authentication methods.

# Finance MCP Quickstart

Connect your AI assistant to AI2Fin financial data in minutes. This guide covers both **OAuth (JWT)** and **API Key** authentication methods for finance MCP integration.

## Prerequisites

* An AI2Fin account (Free or Premium)
* An authentication method: OAuth (bearer token) or an [API key](/mcp/authentication)
* Basic familiarity with REST APIs and JSON-RPC 2.0

## Authentication Methods

<Tabs>
  <Tab title="OAuth (JWT Token)">
    For OAuth-based integrations
  </Tab>

  <Tab title="API Key">
    For MCP Inspector, automation, and server-to-server communication
  </Tab>
</Tabs>

***

## Method 1: OAuth (JWT Token)

### Step 1: Authenticate

Connect your AI assistant using OAuth. After you authorize AI2Fin, your assistant receives a bearer token it uses for all MCP calls. For scripted or server-to-server access, generate an [API key](/mcp/authentication) instead and skip to Method 2.

<Tip>
  Most AI clients (Claude, Cursor, and others) handle the OAuth flow for you—just add the MCP server URL and approve access. **Save your token or API key** securely; you'll need it for every MCP call.
</Tip>

### Step 2: Initialize MCP Connection

```bash theme={null}
curl -X POST https://api.ai2fin.com/mcp \
  -H "Authorization: Bearer <your_oauth_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {}
  }'
```

**Response:**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "tools": { "listChanged": false },
      "prompts": { "listChanged": false },
      "resources": { "subscribe": false, "listChanged": false }
    },
    "serverInfo": {
      "name": "ai2fin-mcp",
      "version": "1.0.0"
    }
  }
}
```

### Step 3: List Available Financial Tools

```bash theme={null}
curl -X POST https://api.ai2fin.com/mcp \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/list",
    "params": {}
  }'
```

**Response:** Returns list of 65+ financial tools (transactions, bills, tax, analytics, etc.)

### Step 4: Call a Financial Tool

**Example: Get Tax Deductible Expenses**

```bash theme={null}
curl -X POST https://api.ai2fin.com/mcp \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
      "name": "get_tax_deductible_summary",
      "arguments": {
        "startDate": "2024-01-01",
        "endDate": "2024-12-31"
      }
    }
  }'
```

**Response:**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "content": [{
      "type": "json",
      "json": {
        "success": true,
        "data": {
          "totalCount": 23,
          "totalAmount": 4532.67,
          "byCategory": [
            {"category": "Office Supplies", "total": 1234.56, "count": 12},
            {"category": "Travel", "total": 987.43, "count": 8}
          ]
        }
      }
    }]
  }
}
```

***

## Method 2: API Key - MCP Inspector & Automation

### Step 1: Generate API Key

The simplest way is to create a key from your [AI2Fin dashboard](https://app.ai2fin.com/#/api). You can also create one programmatically with an authenticated request:

```bash theme={null}
# Creates an API key for your account
curl -X POST https://api.ai2fin.com/api/api-keys \
  -H "Authorization: Bearer <your_oauth_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "MCP Inspector - Production",
    "scopes": ["mcp:full"],
    "expiresInDays": 90
  }'
```

<Tip>
  **Default Scope:** If you don't specify `scopes`, it defaults to `["mcp:full"]` for full MCP Inspector capability. You can also use specific scopes like `["mcp:read", "mcp:tools:list", "mcp:tools:call"]`.
</Tip>

**Response:**

```json theme={null}
{
  "success": true,
  "data": {
    "id": "key_abc123",
    "name": "MCP Inspector - Production",
    "key": "mcp_a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456",
    "scopes": ["mcp:read", "mcp:tools:list", "mcp:tools:call"],
    "expiresAt": "2024-04-01T00:00:00Z"
  }
}
```

<Warning>
  **Save the `key` value immediately** - it's only shown once during creation!
</Warning>

### Step 2: Use API Key with MCP Inspector Endpoint

```bash theme={null}
curl -X POST https://api.ai2fin.com/mcp/inspector \
  -H "X-API-Key: mcp_a1b2c3d4e5f6..." \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {}
  }'
```

### Step 3: Query Financial Data

**Example: Get Spending by Category**

```bash theme={null}
curl -X POST https://api.ai2fin.com/mcp/inspector \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "get_category_spending_summary",
      "arguments": {
        "startDate": "2024-01-01",
        "endDate": "2024-12-31"
      }
    }
  }'
```

Response:

```json theme={null}
{
  "success": true,
  "data": {
    "conversationId": "conv-xyz-789",
    "message": {
      "id": "msg-abc-123",
      "role": "assistant",
      "content": "You have 47 transactions in your account...",
      "metadata": {
        "tokens": 450,
        "duration": 1200
      }
    },
    "toolsUsed": ["get_transactions"]
  }
}
```

<Success>
  **Success!** The AI assistant accessed your data securely and responded with your transaction count.
</Success>

## Real-World Financial Queries

Try these common financial queries using MCP tools:

<CodeGroup>
  ```bash Tax Deductible Expenses theme={null}
  # Get all tax deductible expenses for financial year
  curl -X POST https://api.ai2fin.com/mcp \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "tools/call",
      "params": {
        "name": "get_tax_deductible_summary",
        "arguments": {
          "startDate": "2024-07-01",
          "endDate": "2025-06-30"
        }
      }
    }'
  ```

  ```bash Spending by Category theme={null}
  # Analyze spending breakdown by category
  curl -X POST https://api.ai2fin.com/mcp \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "jsonrpc": "2.0",
      "id": 2,
      "method": "tools/call",
      "params": {
        "name": "get_category_spending_summary",
        "arguments": {
          "startDate": "2024-01-01",
          "endDate": "2024-12-31"
        }
      }
    }'
  ```

  ```bash Upcoming Bills theme={null}
  # Get bills due in the next 30 days
  curl -X POST https://api.ai2fin.com/mcp \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "jsonrpc": "2.0",
      "id": 3,
      "method": "tools/call",
      "params": {
        "name": "get_upcoming_bills",
        "arguments": {
          "daysAhead": 30
        }
      }
    }'
  ```

  ```bash Top Merchants theme={null}
  # Find where you spend the most
  curl -X POST https://api.ai2fin.com/mcp \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "jsonrpc": "2.0",
      "id": 4,
      "method": "tools/call",
      "params": {
        "name": "get_top_merchants",
        "arguments": {
          "startDate": "2024-01-01",
          "endDate": "2024-12-31",
          "limit": 10
        }
      }
    }'
  ```
</CodeGroup>

## Common Financial Use Cases

### Use Case 1: Tax Deduction Analysis

**User Intent:** "I need to know what expenses are tax deductible"

```bash theme={null}
# Get comprehensive tax deductible summary
curl -X POST https://api.ai2fin.com/mcp \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "get_tax_deductible_summary",
      "arguments": {
        "startDate": "2024-07-01",
        "endDate": "2025-06-30"
      }
    }
  }'
```

### Use Case 2: Spending Analysis

**User Intent:** "Where does my money go?"

```bash theme={null}
# Get spending breakdown by category
curl -X POST https://api.ai2fin.com/mcp \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "get_category_spending_summary",
      "arguments": {
        "startDate": "2024-01-01",
        "endDate": "2024-12-31"
      }
    }
  }'
```

### Use Case 3: Bill Management

**User Intent:** "What bills are due soon?"

```bash theme={null}
# Get upcoming and overdue bills
curl -X POST https://api.ai2fin.com/mcp \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
      "name": "get_overdue_bills",
      "arguments": {}
    }
  }'
```

### Use Case 4: Receipt Processing

**User Intent:** "I need to process this receipt"

```bash theme={null}
# Step 1: Analyze receipt image
curl -X POST https://api.ai2fin.com/mcp \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 4,
    "method": "tools/call",
    "params": {
      "name": "analyze_receipt",
      "arguments": {
        "assetUrl": "https://example.com/receipt.jpg",
        "mimeType": "image/jpeg",
        "size": 245123
      }
    }
  }'

# Step 2: Create expense from receipt
curl -X POST https://api.ai2fin.com/mcp \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 5,
    "method": "tools/call",
    "params": {
      "name": "commit_receipt",
      "arguments": {
        "assetUrl": "https://example.com/receipt.jpg",
        "mimeType": "image/jpeg",
        "size": 245123,
        "action": {
          "type": "create_expense",
          "merchant": "Office Supplies Co",
          "amount": -45.67,
          "date": "2024-01-15"
        }
      }
    }
  }'
```

## Understanding MCP Responses

### Successful Tool Call Response

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [{
      "type": "json",
      "json": {
        "success": true,
        "data": {
          "totalCount": 23,
          "totalAmount": 4532.67,
          "byCategory": [...]
        }
      }
    }]
  }
}
```

### Error Response

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": 401,
    "message": "Unauthorized",
    "data": {
      "errorType": "INVALID_TOKEN",
      "message": "Invalid or expired authentication token"
    }
  }
}
```

### Write Operation (Requires Confirmation)

For write operations (create, update, delete), you'll receive a confirmation token:

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [{
      "type": "json",
      "json": {
        "ok": false,
        "needsConfirmation": true,
        "confirmToken": "confirm_abc123...",
        "expiresAtMs": 1705320000000,
        "preview": {
          "tool": "create_transaction",
          "arguments": {...}
        }
      }
    }]
  }
}
```

Then call again with the `confirmToken` to execute.

## Key Features

<CardGroup cols={2}>
  <Card title="Conversation Memory" icon="brain">
    Your assistant remembers context across messages for natural follow-up questions. You control your data and can delete it any time.
  </Card>

  <Card title="Function Calling" icon="wrench">
    Your assistant automatically calls the right tools based on your question.
  </Card>

  <Card title="Account Isolated" icon="shield">
    Your data is scoped to your account only and is never shared with other users.
  </Card>

  <Card title="AI Powered" icon="sparkles">
    Intelligent, accurate answers grounded in your real financial data.
  </Card>
</CardGroup>

## High-Value Financial Queries

<AccordionGroup>
  <Accordion title="Tax & Deduction Queries" icon="file-invoice-dollar">
    **User Intent:** Maximize tax deductions and prepare for tax season

    **MCP Tools:**

    * `get_tax_deductible_summary` - Complete tax deduction report
    * `analyze_transaction_tax_deductibility` - AI analysis of specific transactions
    * `suggest_tax_deductions` - Find deduction opportunities
    * `get_bill_pattern_financial_summary` - FY summaries for tax reporting

    **Example Queries:**

    * "Show all tax deductible expenses this financial year"
    * "What percentage of my expenses are tax deductible?"
    * "Which categories have the most tax deductions?"
    * "Am I missing any potential tax deductions?"
  </Accordion>

  <Accordion title="Spending Analysis" icon="chart-line">
    **User Intent:** Understand spending patterns and optimize budget

    **MCP Tools:**

    * `get_category_spending_summary` - Spending by category
    * `get_top_merchants` - Top vendors by spending
    * `compare_spending_periods` - Month-over-month comparison
    * `get_spending_analytics` - Comprehensive insights

    **Example Queries:**

    * "What's my biggest expense category this month?"
    * "How much did I spend on groceries vs dining out?"
    * "Did I spend more this month than last month?"
    * "Where do I spend the most money?"
  </Accordion>

  <Accordion title="Bill Management" icon="calendar-check">
    **User Intent:** Track and pay recurring bills on time

    **MCP Tools:**

    * `get_upcoming_bills` - Bills due soon
    * `get_overdue_bills` - Past due bills
    * `mark_bill_as_paid` - Record payments
    * `get_bill_pattern_financial_summary` - Annual totals

    **Example Queries:**

    * "What bills are due this week?"
    * "Do I have any overdue bills?"
    * "How much do I spend on bills monthly?"
    * "Mark Netflix as paid for this month"
  </Accordion>

  <Accordion title="Transaction Organization" icon="tags">
    **User Intent:** Organize and categorize transactions efficiently

    **MCP Tools:**

    * `trigger_smart_categorization` - AI-powered categorization
    * `bulk_categorize_transactions` - Batch operations
    * `analyze_transaction_categorization` - Get AI suggestions
    * `find_duplicate_transactions` - Detect duplicates

    **Example Queries:**

    * "Categorize all my uncategorized transactions"
    * "Categorize all Uber rides as Transport"
    * "Find duplicate transactions"
    * "What category should this transaction be?"
  </Accordion>
</AccordionGroup>

## Rate Limits

Both MCP endpoints are rate limited to keep the service fast and fair for everyone. Some heavier operations (such as bulk actions and AI analysis) have their own limits. The API key endpoint is **read-only by default**—write access requires the `mcp:full` scope.

If you exceed a limit you'll receive a `429 Too Many Requests` response. Wait for the window to reset and retry with exponential backoff.

### Rate Limit Headers

All responses include rate limit information so you can pace your requests:

```
X-RateLimit-Limit: <limit>
X-RateLimit-Remaining: <remaining>
X-RateLimit-Reset: <reset-timestamp>
```

### Handling Rate Limits

```typescript theme={null}
// Exponential backoff retry
async function callWithRetry(fn: () => Promise<any>, retries = 3) {
  for (let i = 0; i < retries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (error.status === 429 && i < retries - 1) {
        const waitTime = Math.pow(2, i) * 1000; // 1s, 2s, 4s
        await new Promise(resolve => setTimeout(resolve, waitTime));
        continue;
      }
      throw error;
    }
  }
}
```

## Common Issues & Solutions

<AccordionGroup>
  <Accordion title="Authentication Errors" icon="key">
    **Error:** `401 Unauthorized` or `Invalid token`

    **Causes:**

    * Missing or expired JWT token
    * Invalid API key
    * Token/key has been revoked

    **Solutions:**

    * ✅ Re-authenticate and get new token
    * ✅ Check token expiration time
    * ✅ Verify API key hasn't been revoked
    * ✅ Ensure token/key is in correct header (`Authorization: Bearer` or `X-API-Key`)
  </Accordion>

  <Accordion title="Rate Limit Exceeded" icon="gauge">
    **Error:** `429 Too Many Requests`

    **Causes:**

    * Too many requests in 15-minute window
    * Per-tool rate limit exceeded

    **Solutions:**

    * ✅ Wait for rate limit window to reset (15 minutes)
    * ✅ Implement exponential backoff retry logic
    * ✅ Use batch operations instead of individual calls
    * ✅ Check `X-RateLimit-Reset` header for reset time
  </Accordion>

  <Accordion title="Invalid Request Format" icon="code">
    **Error:** `400 Bad Request` or `-32600 Invalid Request`

    **Causes:**

    * Missing required JSON-RPC fields (`jsonrpc`, `id`, `method`)
    * Invalid tool parameters
    * Missing required tool arguments

    **Solutions:**

    * ✅ Ensure request follows JSON-RPC 2.0 format
    * ✅ Check tool parameter requirements
    * ✅ Validate all required fields are present
    * ✅ Review tool documentation for correct parameter types
  </Accordion>

  <Accordion title="Tool Not Found" icon="search">
    **Error:** `-32601 Method not found` or tool execution fails

    **Causes:**

    * Tool name misspelled
    * Tool not available for your subscription tier
    * API key doesn't have required scope

    **Solutions:**

    * ✅ Use `tools/list` to see available tools
    * ✅ Check tool name spelling (case-sensitive)
    * ✅ Verify subscription tier includes the tool
    * ✅ Ensure API key has `mcp:tools:call` scope
  </Accordion>

  <Accordion title="Timeout Errors" icon="clock">
    **Error:** Request times out

    **Causes:**

    * Querying too much data at once
    * Network connectivity issues
    * Server under heavy load

    **Solutions:**

    * ✅ Use summary tools instead of fetching all data
    * ✅ Add date filters to limit scope
    * ✅ Use pagination for large datasets
    * ✅ Check network connectivity
    * ✅ Retry with exponential backoff
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Explore All Tools" icon="wrench" href="/mcp/tools">
    See complete tool reference with parameters
  </Card>

  <Card title="Security Model" icon="shield" href="/mcp/security">
    Understand how data isolation works
  </Card>

  <Card title="Code Examples" icon="code" href="/mcp/examples">
    Ready-to-use integration code
  </Card>

  <Card title="RAG System" icon="database" href="/mcp/rag-system">
    How docs.ai2fin.com knowledge works
  </Card>
</CardGroup>
