FinSight

A paid financial analytics API for AI agents on MPP

finsight-mpp MCP server

FinSight — Pay-per-use Portfolio Analytics API

What Are We Building?

FinSight is a pay-per-use financial portfolio analytics API designed to be consumed autonomously by AI agents (Claude, Cursor, Cline, and others) — no registration, no API key per user, just a USDC balance.

It combines two core technologies:

  • MCP (Model Context Protocol) — the standard for integrating AI agents with external tools and APIs
  • MPP (Machine Payment Protocol) + Tempo Blockchain — infrastructure for automated machine-to-machine micropayments

The result: an AI agent can analyze investment portfolios in real-time, pay per request on its own, and return quantitative results to the user — all without human intervention.

Live API: https://finsight-mpp.finsight-mpp.workers.dev


The Role of MPP + Tempo Blockchain

MPP (Machine Payment Protocol)

MPP is an HTTP standard for automated micropayments between machines. It works like HTTP auth but for payment challenge-response:

  1. Server returns HTTP 402 Payment Required with a payment challenge
  2. Client (AI agent) reads the challenge, pays on-chain, and attaches the payment proof
  3. Server verifies the proof and serves the request

MPP enables a registrationless paid API — anyone with a wallet and USDC can use it immediately.

Tempo Blockchain

Tempo is an L2 blockchain (chainId: 4217) used as the USDC payment rails. Chosen for:

  • ~500ms transaction confirmation — fast enough for per-request payments
  • ~$0.001 gas fee — cheap enough for micropayments
  • Native TIP-20 token support (USDC) for stablecoin settlement

Payment Flow

AI Agent / Client                  FinSight Worker                Tempo Blockchain
      │                                  │                               │
      ├─── POST /analyze/risk ──────────►│                               │
      │                                  │                               │
      │◄── HTTP 402 + challenge ─────────┤                               │
      │    (amount, recipient, chainId)  │                               │
      │                                  │                               │
      ├─── Send USDC ───────────────────────────────────────────────────►│
      │◄── TX Hash / Receipt ───────────────────────────────────────────┤
      │                                  │                               │
      ├─── POST /analyze/risk ──────────►│                               │
      │    Authorization: Bearer <hash>  ├─── Verify TX ────────────────►│
      │                                  │◄── Valid ─────────────────────┤
      │◄── HTTP 200 + Analysis Result ───┤                               │

Key Components

ComponentLocationPurpose
MPP_SECRET_KEYServer (Cloudflare Worker)Validates payment tokens from clients
MPPX_SECRET_KEYClient (MCP Server)Signs and generates payment tokens
RECIPIENT_ADDRESSServerUSDC recipient wallet address

MPP_SECRET_KEY (server) and MPPX_SECRET_KEY (client) must share the same value.


Dry-Run Mode (Development)

Test without any on-chain transaction:

curl -X POST https://finsight-mpp.finsight-mpp.workers.dev/analyze/risk?dry_run=true \
  -H "Authorization: Bearer <DRY_RUN_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"holdings":[{"asset":"BTC","ticker":"BTC","weight":0.6},{"asset":"ETH","ticker":"ETH","weight":0.4}]}'

Quantitative multi-asset portfolio analytics delivered as a Cloudflare Worker with micropayment gating via Tempo chain (USDC). Supports 70+ crypto tickers, 60+ US equity/ETF tickers, 30+ IDX Indonesia stocks, and macro indicators from FRED.

Data Sources

SourceCoverageCache TTL
CoinGecko70+ crypto tickers, 365-day daily history5 min
Twelve Data60+ US equity/ETF, 252-day daily history1 hr
Yahoo Finance30+ IDX Indonesia stocks (.JK suffix)1 hr
FREDVIX, yield curve, CPI, GDP, unemployment, M21 hr
Alternative.meFear & Greed Index (0-100)1 hr

Analytics Methodology

Correlation Matrix

Computes real Pearson correlation rho(X,Y) = Cov(X,Y) / (sigma_X * sigma_Y) from daily log returns when price history is available for both assets. Falls back to asset-class heuristic estimates when no price data exists.

Portfolio Volatility

Uses the full covariance matrix formula sigma_p = sqrt(w^T * Sigma * w) where Sigma_ij = rho_ij * sigma_i * sigma_j. This correctly accounts for cross-asset correlations rather than assuming a single average correlation for all pairs.

Beta (Market Sensitivity)

Computed via OLS regression against SPY benchmark: beta = Cov(r_asset, r_SPY) / Var(r_SPY) from aligned daily log returns. SPY is always fetched as benchmark even when not in the portfolio. Falls back to asset-class defaults when insufficient data.

Stress Testing

10 scenario simulations with beta-adjusted impacts. Market-wide scenarios (crash, recovery, recession) scale each asset's impact by its effective beta rather than using hardcoded constants. Sector-specific adjustments apply where relevant.

Executive Summary

Scores portfolios on a 0-100 scale across 4 components (Sharpe, diversification, drawdown, profile alignment). Produces 5+ items per category (strengths, risks, recommendations) with quantitative backing — e.g., specific ratios, percentages, and thresholds.

Additional Modules

  • VaR/CVaR — Parametric Value-at-Risk at 95% and 99% confidence
  • Monte Carlo — 10,000-path Geometric Brownian Motion simulation (Box-Muller RNG)
  • Diversification — HHI, effective asset count, asset-class/region/sector breakdown
  • Factor Exposure — Market beta, duration, dividend yield, currency exposure
  • Market Regime — Detection from macro indicators (VIX, yield curve, credit spreads)
  • Rebalancing — Risk parity, minimum variance, equal weight, profile-based
  • Portfolio Comparison — Side-by-side delta across 9 metrics

Endpoints

EndpointMethodPriceDescription
/GETFreeAPI info and supported assets
/demoGETFree (2/day/IP)Live demo with BTC+ETH+SPY+GLD
/pricingGETFreeFull pricing table
/healthGETFreeHealth check
/llms.txtGETFreeMCP integration docs
/analyze/riskPOST$0.005Sharpe, Sortino, Calmar, beta, risk tier
/analyze/rebalancePOST$0.01Target weights by method
/analyze/diversificationPOST$0.005HHI, breakdown, warnings
/analyze/stressPOST$0.0110 beta-adjusted scenarios
/analyze/varPOST$0.01VaR/CVaR at 95% and 99%
/analyze/factorsPOST$0.01Factor exposure analysis
/analyze/correlationPOST$0.01Pearson correlation matrix
/analyze/regimePOST$0.01Market regime detection
/analyze/montecarloPOST$0.0210,000-path Monte Carlo
/analyze/reportPOST$0.05Full report: all modules + executive summary
/analyze/comparePOST$0.03Compare two portfolios

Payment

All paid endpoints require USDC payment on Tempo chain (chainId: 4217) via the Machine Payment Protocol (MPP). Settlement is ~500ms with ~$0.001 gas.

Dry-run mode is available for development only when DRY_RUN_TOKEN is configured as a Wrangler secret. Requires Authorization: Bearer <token> header. Not publicly accessible.

Request Format

{
  "holdings": [
    { "asset": "BTC", "weight": 0.4, "assetClass": "crypto" },
    { "asset": "ETH", "weight": 0.3, "assetClass": "crypto" },
    { "asset": "SPY", "weight": 0.2, "assetClass": "equity" },
    { "asset": "GLD", "weight": 0.1, "assetClass": "commodity" }
  ],
  "profile": "balanced",
  "benchmarkReturn": 0.08,
  "riskFreeRate": 0.05,
  "rebalanceMethod": "risk_parity"
}

Fields like avgReturn, volatility, and maxDrawdown are auto-populated from live data when the ticker is recognized. User-provided non-default values always take precedence.

Supported Tickers

Crypto (CoinGecko — 70+)

BTC, ETH, SOL, BNB, XRP, ADA, AVAX, DOGE, DOT, TRX, TON, HBAR, ALGO, FTM, ICP, VET, XMR, BCH, KAS, FIL, FLOW, STX, ROSE, MATIC/POL, ARB, OP, STRK, IMX, MANTA, LINK, UNI, AAVE, MKR, CRV, LDO, SNX, COMP, GMX, DYDX, 1INCH, CAKE, ATOM, NEAR, APT, SUI, SEI, TIA, LTC, ETC, XLM, INJ, JUP, PYTH, RNDR, GRT, OCEAN, ENS, WLD, HYPE, ZRO, LIT, EIGEN, VIRTUAL, PEPE, WIF, BONK, TRUMP, SHIB, FLOKI, POPCAT, USDC, USDT, DAI, FRAX, USDS

US Equity/ETF (Twelve Data — 60+)

SPY, QQQ, IWM, DIA, VTI, VOO, VEA, VWO, ARKK, GLD, SLV, TLT, IEF, BND, AGG, HYG, XLK, XLF, XLE, XLV, SOXX, SMH, AAPL, MSFT, GOOGL, AMZN, NVDA, TSLA, META, AMD, CRM, PLTR, COIN, MSTR, JPM, BAC, GS, V, MA, XOM, CVX, JNJ, UNH, LLY, WMT, COST, VNQ, O, AMT, BIL, SGOV, and more

IDX Indonesia (Yahoo Finance — 30+)

BBCA, BBRI, BMRI, BBNI, TLKM, ASII, ADRO, PTBA, ANTM, GOTO, BUKA, KLBF, SIDO, BSDE, SMGR, and more

MCP Integration

FinSight works as an MCP (Model Context Protocol) server for AI agents like Claude, Cursor, and Cline. See /llms.txt for setup instructions.

Development

# Install dependencies
npm install

# Local development
npx wrangler dev

# Set secrets
wrangler secret put MPP_SECRET_KEY
wrangler secret put COINGECKO_API_KEY
wrangler secret put TWELVE_DATA_API_KEY
wrangler secret put FRED_API_KEY
wrangler secret put DRY_RUN_TOKEN

# Deploy
npx wrangler deploy

KV Namespaces

  • RATE_LIMITS — IP-based rate limiting (60 req/min)
  • CACHE — Report result cache (30s TTL)
  • MARKET_DATA — Price data and macro indicator cache

Architecture

  • Runtime: Cloudflare Workers (edge deployment)
  • Framework: Hono (TypeScript)
  • Payment: MPP via Tempo chain (USDC)
  • Validation: Zod schemas with weight-sum verification
  • Caching: Cloudflare KV with versioned keys

Version

v3.1.0 — Twelve Data equity provider, lower pricing, demo rate limiting (2/day/IP), real Pearson correlation, OLS beta, beta-adjusted stress tests.

関連サーバー