{
  "markdown": "# Spiral Stake — `mcp` read-data backbone (Step 1a)\n\nThe **composition authority + read API** for Spiral Stake strategy data. It ports the app's\nclient-side data composition **server-side** and serves it back as JSON, so three consumers run\noff one core:\n\n1. **The app** — the complete read surface it currently fetches, for a like-for-like Step-2 swap.\n2. **Agents** — the frozen [`/strategies` contract](./CONTRACT.md).\n3. **Partners (later)** — a clean, versioned, self-documenting REST surface (OpenAPI).\n\n**Read-only.** No contract writes, no tx building, no signing, no private keys. It composes\nnumbers and serves JSON. The MCP tool layer, execution/`build_*`, and partner auth are **later\nsteps** — the seams are pre-cut (`core` + `http`) but not built.\n\n---\n\n## Architecture\n\n```\nsrc/\n  core/        pure composition — no I/O, unit-testable\n    leverage.ts        ← VERBATIM copy of v2-client/src/utils/leverage.ts (byte-diff gated)\n    apy.ts             collateral-APY resolution (Pendle/DeFiLlama/Royco/StableWatch/on-chain)\n    leverageApy.ts     30/60/90d leveraged-APY windows + lumpy-token smoothing\n    compose.ts         Market assembly from warm raw (port of FlashLeverage.createInstance)\n    strategy.ts        Market → frozen /strategies contract (ladder, freshness, spiralHints)\n    exitLiquidity.ts   exit-liquidity tier (the single verdict) + thresholds\n  sources/     one adapter per upstream (fetch + parse). native fetch + viem; no axios/wagmi\n  cache/       two-layer cache — RAW store (last-good) + warming policy (CONTRACT cadences)\n  warmer/      background scheduler (stale-while-revalidate); reads NEVER fetch\n  http/        thin hono REST layer (the only thing that knows about requests)\n  data/        static market config (copied from the app) + readMarkets port\n  config/      env (validated) + structured logger with correlation ids\n```\n\n**Data flow:** `warmer` fetches upstreams on the CONTRACT cadence → writes **raw** to the cache\n(last-good on failure) → `core` composes strategies from **warm raw only** → `http` serves them.\nA stale/failed upstream serves **last-good with a visible stale age** per field-group — never\ndropped, never coerced to 0.\n\n---\n\n## Run\n\n```bash\ncp .env.example .env      # fill in RPC + API keys (secrets via env only)\nnpm install\nnpm run dev               # tsx watch; serves on :$PORT (default 8787)\nnpm test                  # golden + parity gates\nnpm run typecheck         # tsc --noEmit\nnpm run openapi           # (re)emit openapi.json\nnode --import tsx scripts/smoke.ts   # live: prime + print one composed strategy\n```\n\n`/health` (liveness + cache diagnostics) and `/ready` (503 until the warmer primes the required\ndata) are available immediately on boot.\n\n---\n\n## Endpoints — app-read inventory → endpoint mapping\n\nEvery data read the app performs in `v2-client/src/api-services/*` maps to an endpoint here\n(positions stay on the dashboard backend and are **not** reimplemented):\n\n| App read (`api-services/*`) | mcp endpoint |\n|---|---|\n| `getTokenApy`, `getAllMorphoMarketsData`, `fetchMerklSpotIncentives`, prices, on-chain value → composed markets | `GET /v1/strategies`, `GET /v1/strategies/:id` |\n| `FlashLeverage.createInstance` → the app's full client-side `Market[]` composition | `GET /v1/app/markets` (raw domain model; `BigNumber`→`{\"$bn\":…}`, `bigint`→`{\"$bigint\":…}` — revive before use) |\n| `morpho.ts` `getAllBorrowApyHistories` / `getBorrowApyHistory` | `GET /v1/markets/borrow-apy-history`, `GET /v1/markets/:id/borrow-apy-history` |\n| `apy.ts` `resolveTokenApyHistory` (DeFiLlama/Royco/StableWatch history), `chart.ts` `getApyChart` | `GET /v1/collateral/apy-history`, `GET /v1/collateral/:id/apy-history` |\n| `merkl.ts` `fetchMerklIncentiveData` (borrow-incentive APR history) | `GET /v1/markets/:id/incentive-history` |\n| `token.ts` `getAllLoanTokenPrices` / `getTokenPrice` | `GET /v1/prices` |\n| `chart.ts` `getMarketChart` (CoinGecko price chart) | `GET /v1/prices/chart?coinId=&days=&currency=` (on-demand proxy) |\n| `dashboard.ts` `getApySnapshot` (StableWatch stable APY) | `GET /v1/stable-apy` — fetched directly from StableWatch as a warmed upstream; the mcp **owns** this data now and no longer depends on the dashboard `/apy` endpoint |\n| swap/meta-dex aggregators, referral, positions | **out of scope** (execution / backend domains) |\n\nCross-cutting: `/v1` versioning, CORS limited to `CORS_ORIGINS`, a consistent error envelope\n(`{ error: { code, message, correlationId } }`), a correlation id per request (echoed as\n`x-correlation-id`), structured JSON logs, and an OpenAPI 3.1 spec at `/openapi.json` (+ committed\n`openapi.json`).\n\n---\n\n## Parity gates\n\n1. **`leverage.ts` golden-vector** — `test/golden/leverage.golden.test.ts` freezes fixed inputs →\n   exact outputs; `leverage.parity.test.ts` asserts the file is a **byte-for-byte** copy of the\n   app's `leverage.ts`. This locks every APY/LTV/ladder number to the app.\n2. **`/strategies` composition** — `test/parity/strategies.compose.test.ts` seeds the raw cache\n   with a controlled fixture and asserts the composed contract field-by-field (sourcing, LTV math,\n   ladder via the verbatim `leverage.ts`, freshness cadences, `null`-vs-absent, `spiralHints`\n   isolation). Runs offline in CI.\n3. **Live golden-set + app-surface parity** — `scripts/capture-parity.ts` primes the warmer\n   against real upstreams and writes the composed `/strategies` (+ apy/borrow histories) for a\n   fixed market set to `test/fixtures/`. The parity **diff vs the app** is produced by feeding the\n   same fixed inputs to the app's client-side composition and comparing (the app logs its composed\n   markets); the PR commits the fixtures and the empty diff. This is the gate that lets us offload\n   TVL safely.\n\n---\n\n## Frozen decisions (parity-critical)\n\n- `bignumber.js` pinned to the app's `9.3.1`; **no** global `BigNumber.config` change →\n  `toFixed(2)` / rounding (`ROUND_HALF_UP`) identical.\n- On-chain reads via **viem** replace wagmi: `getCollateralValueInLoanToken` (multicall3), stUSDS\n  `str()`, spUSDG `vsr()` (chain 4663). The app's (intentionally lossy) `BigInt(liqLtv)` from the\n  JSON number is matched exactly, not \"fixed\".\n- `maxLeverage = calcLeverage(maxLtv)`; `defaultLeverage = calcLeverage(safeLtv)`,\n  `safeLtv = maxLtv% − 0.75` — exactly as the app derives them. Ladder = integer steps\n  `1x … ⌊maxLeverage⌋` (LTV `=(1 − 1/lev)·100`) then the exact `max`.\n- Exit slippage is baked into `collateralTokens.json` by the app's weekly refresh script; its file\n  mtime is the `exitLiquidity.asOf`. The **tier** (the only verdict) lives in `spiralHints` with\n  its thresholds; raw `slippagePct` stays under `exitLiquidity`, `null` (no route) preserved.\n",
  "bytes": 6723,
  "sha": "de12d476e4e5b9e2d8a59736ac5d64570681bca5b34ad29561ed53696504a335",
  "repo_slug": "spiral-stake/mcp",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_xyz_spiralstake_leverage_a0ecd349/readme"
}