Skip to main content
Glama
bensacc

defi-yield-mcp

by bensacc
README.md
# defi-yield-mcp

An MCP server for querying DeFi yield pool data and (eventually) risk signals —
built for anyone deciding where idle funds should earn yield, without having
to manually cross-reference DefiLlama, protocol docs, and exploit trackers.

## Why this exists

DefiLlama has the raw data but no MCP server exposing it in agent-friendly 
form with any risk framing layered on.

## Setup

```bash
pip install -r requirements.txt
python server.py
```

Add to your MCP client config (e.g. Claude Desktop `claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "defi-yield": {
      "command": "python",
      "args": ["/absolute/path/to/server.py"]
    }
  }
}
```

No API key required — DefiLlama's public endpoints are used as-is.

## Tools — implemented

| Tool | Description |
|---|---|
| `get_pool_apy` | Current APY/TVL for pools on a given protocol, optionally filtered by asset symbol and chain |
| `list_pools` | Filter/sort pools across all protocols by APY, TVL, chain, symbol |
| `compare_pools` | Side-by-side comparison of specific pools by DefiLlama pool id |
| `get_exploit_history` | Historical hack/exploit records, optionally filtered by protocol |
| `get_pool_risk_score` | Gated risk assessment (audit + liquidity gates, then yield/TVL stability score) — see methodology below |
| `get_protocol_audit_status` | Audit firm(s), count, launch date, bug bounty status, liquidity category — from the curated dataset |

`get_pool_risk_score` and `get_protocol_audit_status` are only populated for
protocols in `CURATED_PROTOCOL_DATA` in `server.py` (currently: aave-v3,
compound-v3, morpho-blue, curve-dex, makerdao). Anything else returns an
honest "not in dataset" response rather than a fabricated score.

## Data sources

- **DefiLlama Yields API** (`yields.llama.fi/pools`) — APY, TVL, pool metadata. Free, no key, refreshes ~hourly. Responses are cached in-process for 5 minutes to avoid redundant calls.
- **DefiLlama hacks dataset** (`api.llama.fi/hacks`) — historical exploit records.

## Risk scoring methodology (implemented)

This is deliberately **not** a single blended score. For a payments protocol
holding funds earmarked for payees, some failures shouldn't be averaged away
by a good number elsewhere — so the design is gate-then-score:

**Hard gates (fail either → pool is excluded, no score computed):**
1. **Audit gate** — protocol must have ≥ 2 audits from recognized firms and
   be live ≥ 12 months (`MIN_AUDIT_COUNT`, `MIN_PROTOCOL_AGE_DAYS` in `server.py`).
2. **Liquidity gate** — protocol category must support instant withdrawal
   (lending markets, savings-style primitives, stable AMMs — not locked farms),
   **and** the specific pool's TVL must be ≥ 20x the assumed position size
   (`MIN_TVL_DEPTH_MULTIPLE`), so an exit doesn't move the market.

**Secondary score (only computed if both gates pass):**
- **Yield stability** — coefficient of variation of daily APY over the
  trailing 30 days, converted to a 0–100 score (lower variance → higher score).
- **TVL stability** — same calculation applied to daily TVL.
- These are averaged into a `composite_stability_score`. Note this ranks
  *steadiness*, not *size* — a steady 4% outranks a volatile 9% by design.

The curated dataset and thresholds are plain module-level constants in
`server.py`, not hidden in a black box — adjust `MIN_AUDIT_COUNT`,
`MIN_PROTOCOL_AGE_DAYS`, or `MIN_TVL_DEPTH_MULTIPLE` to fit a different
risk appetite.

## Extending the curated dataset

To add a protocol, add an entry to `CURATED_PROTOCOL_DATA` in `server.py`
with `audits`, `audit_count`, `live_since`, `bug_bounty`, `category`, and
`instant_liquidity`, sourced from the protocol's own docs/GitHub. There's no
public API for audit status across protocols, so this stays hand-maintained
by design — a fabricated automated score would be worse than an honest gap.

## Testing

**Offline (no network needed):**

```bash
pip install "mcp[cli]" httpx
python test_offline.py
```

Runs all six tools against realistic mock fixtures (patched in place of the
real HTTP calls) so you can see the gate-then-score logic execute end to end —
including one fixture deliberately sized to fail the liquidity gate, and one
protocol deliberately left out of the curated dataset, so you can see both
failure paths behave correctly, not just the happy path.

**Live (hits the real DefiLlama API):**

```bash
pip install "mcp[cli]" httpx
python server.py
```

Then connect via an MCP client (see Setup above) and call the tools directly,
or add a small `if __name__ == "__main__":` block calling the async functions
with `asyncio.run(...)` the same way `test_offline.py` does, minus the
monkeypatch. Worth checking the live `/pools` and `/chart/{pool}` response
shapes against what's assumed in `server.py` the first time you run it —
those field names were reconstructed from documentation, not verified live.



## Known limitations

- **`_looks_locked` is a keyword heuristic, not a guarantee.** It catches
  obvious cases (a `poolMeta` or `symbol` containing "stake", "umbrella",
  "vault", "lock", etc. — added after live testing surfaced an Aave "Umbrella"
  staking pool passing the liquidity gate incorrectly) but a new locked
  product with unrelated naming could still slip through the protocol-level
  `instant_liquidity` flag. Treat `gate_status: passed` as a strong signal,
  not a certainty — check the `pool_meta` field in the response yourself for
  anything unfamiliar.
- No risk scoring for protocols outside `CURATED_PROTOCOL_DATA` — those
  correctly come back `gate_status: unknown` rather than a fabricated score.
- Exploit history depends on DefiLlama's dataset being current; cross-check
  anything decision-relevant against the protocol's own disclosures.
- Not audited or battle-tested — this is a portfolio/reference project, not
  a production risk tool. Don't make real allocation decisions off
  `get_pool_apy` alone.