Skip to main content
Glama
mutual-fund-mcp

mutual-fund-mcp

by vibhuti93
README.md
# Mutual Fund MCP (`mutual-fund-mcp`)

A zero-cost (**\$0/month**), stateless **Model Context Protocol (MCP)** server deployed on **Cloudflare Workers (Free Tier)** for **Indian Mutual Fund analytics**, backed by the public [MFapi.in](https://api.mfapi.in) AMFI REST API.

> **Disclaimer:** Historical AMFI/MFapi.in NAV data and deterministic calculations only. Not SEBI-registered investment advice.

## What It Does

- **Live & Historical NAV Tracking:** Look up latest Net Asset Values (NAVs), fund house metadata, categories, ISINs, and downsampled historical NAV trends by AMFI scheme code.
- **Deterministic Return Calculations:** Compute historical **Monthly SIP XIRR (`Actual/365`)** (with automatic Indian AMC next-business-day holiday allotment shifting) and **Lumpsum CAGR** (omitting annualization under 365 days).
- **Rolling Return Consistency & Risk:** Calculate $O(N)$ sliding-window **1Y / 3Y / 5Y / 7Y rolling CAGR** stats (min, max, mean, median, `% positive`, `% >= 12%`) alongside peak-to-trough **Max Drawdown**.
- **Apples-to-Apples Scheme Comparison:** Compare **2 to 4 mutual fund schemes** over their exact overlapping date window, automatically flagging **Direct vs. Regular** plan and **Growth vs. IDCW/Dividend** option mismatches.

## Live Endpoint

| Service | URL |
| --- | --- |
| **MCP Server (Streamable HTTP)** | `https://mutual-fund-mcp.mutualfund-mcp-vk.workers.dev/mcp` |
| **Health Check (`GET`)** | `https://mutual-fund-mcp.mutualfund-mcp-vk.workers.dev/health` |
| **OpenAI Challenge (`GET`)** | `https://mutual-fund-mcp.mutualfund-mcp-vk.workers.dev/.well-known/openai-apps-challenge` |

Quick health check:

```bash
curl https://mutual-fund-mcp.mutualfund-mcp-vk.workers.dev/health
```

---

## Quick Connect: Copy-Paste Client Configs

### Cursor

Add to `~/.cursor/mcp.json` (global) or `.cursor/mcp.json` (project):

```json
{
  "mcpServers": {
    "mutual-fund-mcp": {
      "url": "https://mutual-fund-mcp.mutualfund-mcp-vk.workers.dev/mcp"
    }
  }
}
```

### Claude Code

Run a single CLI command to add the remote Streamable HTTP server:

```bash
claude mcp add --transport http mutual-fund-mcp https://mutual-fund-mcp.mutualfund-mcp-vk.workers.dev/mcp
```

Or add `.mcp.json` in your project root:

```json
{
  "mcpServers": {
    "mutual-fund-mcp": {
      "type": "http",
      "url": "https://mutual-fund-mcp.mutualfund-mcp-vk.workers.dev/mcp"
    }
  }
}
```

### Claude Desktop

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

```json
{
  "mcpServers": {
    "mutual-fund-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://mutual-fund-mcp.mutualfund-mcp-vk.workers.dev/mcp"
      ]
    }
  }
}
```

*(Alternatively, on Claude plans with Custom Connectors UI, go to **Settings -> Connectors -> Add custom connector** and enter `https://mutual-fund-mcp.mutualfund-mcp-vk.workers.dev/mcp` directly.)*

### ChatGPT

1. Open ChatGPT **Settings -> Connectors / Plugins -> `+` -> Add custom MCP server** (or Developer Mode MCP connector).
2. Enter `https://mutual-fund-mcp.mutualfund-mcp-vk.workers.dev/mcp`.
3. Select **No authentication** (public read-only AMFI/MFapi data).
4. Enable the connector in a new chat.

---

## Available Tools

All 4 tools are strictly read-only (`readOnlyHint: true`, `destructiveHint: false`, `idempotentHint: true`, `openWorldHint: false`) and return both human-readable text summaries and strict JSON `structuredContent`.

### 1. `search_indian_mf_schemes`

Search AMFI mutual fund schemes by fund name, AMC, or keywords and disambiguate between Direct/Regular plans and Growth/IDCW options before fetching NAVs.

**Expected Arguments:**
- `query` (`string`, **required**, trimmed min `2` chars): Fund name, AMC, or keywords (e.g., `"Parag Parikh Flexi Cap"`, `"HDFC Mid Cap"`).
- `planFilter` (`"direct" | "regular" | "all"`, optional, default `"all"`): Filter by Direct or Regular plan.
- `optionFilter` (`"growth" | "idcw" | "all"`, optional, default `"all"`): Filter by Growth or IDCW/Dividend option.
- `limit` (`integer`, optional, `1–25`, default `10`): Maximum number of matching schemes to return.

### 2. `get_indian_mf_nav`

Retrieve the latest NAV, scheme metadata (fund house, category, ISIN), optional period high/low/change stats, and a downsampled historical NAV series for a given AMFI scheme code.

**Expected Arguments:**
- `schemeCode` (`integer > 0`, **required**): Numeric AMFI scheme code (e.g., `122639`).
- `startDate` (`string`, optional, `YYYY-MM-DD`): Start date for historical NAV trend.
- `endDate` (`string`, optional, `YYYY-MM-DD`): End date for historical NAV trend.
- `maxPoints` (`integer`, optional, `1–60`, default `12`): Maximum downsampled NAV points to return (always preserves first and latest points).

### 3. `calculate_indian_mf_returns`

Compute deterministic historical **Lumpsum CAGR**, **Monthly SIP XIRR (`Actual/365`)**, and **Rolling Return consistency (`1Y`/`3Y`/`5Y`/`7Y`) + Max Drawdown** for a single mutual fund scheme.

**Expected Arguments:**
- `schemeCode` (`integer > 0`, **required**): Numeric AMFI scheme code.
- `mode` (`"sip" | "lumpsum" | "rolling" | "all"`, optional, default `"all"`): Calculation mode.
- `amount` (`number > 0`, optional): Investment amount in INR (defaults to `10000` for SIP / `100000` for lumpsum).
- `startDate` (`string`, optional, `YYYY-MM-DD`): Analysis start date (defaults to 5 years before latest NAV, or scheme inception if newer).
- `endDate` (`string`, optional, `YYYY-MM-DD`): Valuation end date (defaults to latest available NAV).
- `sipDay` (`integer`, optional, `1–28`, default `5`): Monthly SIP allotment day of month.
- `rollingWindowYears` (`1 | 3 | 5 | 7`, optional, default `3`): Rolling return window length in years.

### 4. `compare_indian_mf_schemes`

Run an apples-to-apples side-by-side historical comparison of **2 to 4 schemes** over their exact overlapping date window (latest NAV, Lumpsum CAGR, SIP XIRR, rolling return median/range, and max drawdown), flagging Direct vs. Regular or Growth vs. IDCW mismatches.

**Expected Arguments:**
- `schemeCodes` (`integer[]`, **required**, `2–4` unique positive integers): AMFI scheme codes to compare (e.g., `[122639, 100119]`).
- `startDate` (`string`, optional, `YYYY-MM-DD`): Common start date (defaults to common overlapping inception across schemes, capped at 5 years back).
- `endDate` (`string`, optional, `YYYY-MM-DD`): Common end date (defaults to the earliest latest-NAV date across compared schemes).
- `monthlySipAmount` (`number > 0`, optional, default `10000`): Monthly SIP amount in INR for XIRR comparison.
- `rollingWindowYears` (`1 | 3 | 5`, optional, default `3`): Rolling return window length in years.

---

## Architecture & Production Safeguards

- **Stateless MCP Runtime:** Built with `createMcpHandler` (`agents/mcp/server`) and `McpServer` (`@modelcontextprotocol/server`) using `CfWorkerJsonSchemaValidator` (zero `eval`/`new Function`).
- **Edge Caching & Resilience:** Wraps `https://api.mfapi.in` with `AbortSignal.timeout(5000)`, 1-shot retry on network errors or HTTP `502`/`503`/`504`, HTML error-page detection, and non-blocking `ctx.waitUntil` writes to `caches.default` (TTLs: Search `6h`, History `4h`, Latest `1h`).
- **Abuse Protection:** Streaming 100KB POST body limit (`HTTP 413`, no full-body heap buffering) and bounded per-isolate sliding-window rate limiter (`60 req/min/IP` -> `HTTP 429` with `Retry-After: 60`, capped at `2000` tracked IPs).
- **Origin & Host Validation:** Allows `localhost`, `127.0.0.1`, `*.workers.dev`, ChatGPT, MCPJam Inspector, same-origin custom domains, and optional `env.ALLOWED_ORIGIN_HOSTNAMES`, rejecting untrusted browser Origins with `HTTP 403`.
- **Structured Observability:** `AsyncLocalStorage` request tracing (`requestId`, `path`, `method`, `tool`, `durationMs`, `cacheHit`, `status`, `error`) formatted as single-line JSON for `wrangler tail`.

---

## Local Development, Testing & Deployment

```bash
npm install
npm run typecheck
npm test
npm run dev
```

`npm run dev` starts Wrangler locally at `http://localhost:8787`.

### Live End-to-End Smoke Verification

Run live JSON-RPC checks against live MFapi.in (local or deployed):

```bash
# Against local wrangler dev (http://localhost:8787)
npm run smoke:live

# Against deployed Cloudflare Worker
node scripts/live-smoke.mjs --url https://mutual-fund-mcp.mutualfund-mcp-vk.workers.dev
```

### Local Inspection with MCPJam Inspector

With `npm run dev` running, launch MCPJam Inspector and connect via **Streamable HTTP** to `http://localhost:8787/mcp`:

```bash
npx @mcpjam/inspector@latest
```

### Deploy to Cloudflare Workers

```bash
npx wrangler login
npx wrangler deploy
npx wrangler tail
```

*(Optional)* Set an OpenAI App domain challenge token:

```bash
npx wrangler secret put OPENAI_APPS_CHALLENGE_TOKEN
```

---

## Example Prompts to Validate Tool Routing

### Positive Prompts (Should Invoke Tools)

1. `"Find the AMFI scheme code for Parag Parikh Flexi Cap Fund Direct Growth."` -> invokes `search_indian_mf_schemes`
2. `"What is the latest NAV and ISIN of scheme 122639, and how did its NAV move in 2024?"` -> invokes `get_indian_mf_nav`
3. `"If I invested ₹10,000/month via SIP on the 5th in Parag Parikh Flexi Cap Direct Growth over the last 5 years, what would my XIRR and corpus be?"` -> invokes `search_indian_mf_schemes` + `calculate_indian_mf_returns`
4. `"Show 3-year rolling return consistency (median, min, max, % positive) and max drawdown for HDFC Mid-Cap Opportunities Direct Growth."` -> invokes `search_indian_mf_schemes` + `calculate_indian_mf_returns`
5. `"Compare Parag Parikh Flexi Cap Direct Growth vs HDFC Flexi Cap Direct Growth vs Nippon India Small Cap Direct Growth over their common overlapping window."` -> invokes `search_indian_mf_schemes` + `compare_indian_mf_schemes`

### Negative / Out-of-Scope Prompts (Should NOT Invoke Tools)

6. `"Which Indian mutual fund should I buy right now to beat Nifty 50 over the next 2 years?"` -> decline investment advice / speculative predictions
7. `"What is the current share price and P/E ratio of Reliance Industries on NSE?"` -> out of scope (equities, not AMFI mutual fund schemes)
8. `"Calculate the 5-year SIP return of Vanguard S&P 500 ETF (VOO) in USD."` -> out of scope (US ETF, not Indian AMFI mutual fund)