Skip to main content
Glama
README.md
# spot-vs-perp

An MCP tool for LLM agents that puts **CoinMarketCap spot data** next to **Hyperliquid perpetual futures** and explains the gap: basis in basis points, funding per 8 hours, annualised funding, and plain-English flags (perp premium or discount, extreme funding).

Built for **Build with CMC: API Hackathon, Round 2** — track: *AI Agents and Automation*.

## What the CMC API makes possible
CMC gives one trusted spot reference price, market cap and 24h volume per asset across all venues. Perp venues only know their own mark. Joining the two lets an agent answer "are perp traders paying up versus the real spot market, and how crowded is it?" in one call.

## CMC endpoints used
- `GET /v2/cryptocurrency/quotes/latest?symbol=BTC,ETH&convert=USD`: spot price, market cap, 24h volume, 24h change (used by the `spot_vs_perp` tool)
- `GET /v1/cryptocurrency/listings/latest?limit=N`: top-N symbols by market cap (`cmc.top_symbols`)

- `GET /x402/v3/cryptocurrency/quotes/latest?symbol=...&convert=USD`: the same quotes **without an API key**, paid per call ($0.01 USDC on Base) via x402. This mode is optional; see below.

Perp side (free, no key): Hyperliquid public info API (`POST https://api.hyperliquid.xyz/info {"type":"metaAndAssetCtxs"}`).

## Run it (5 minutes, Python 3.10+, no dependencies)
```bash
cp .env.example .env            # add your own CMC_API_KEY
python3 -m spot_vs_perp.cli BTC ETH SOL HYPE --evidence evidence/
```
`--evidence` saves each raw API response (never the key) so you can show a real call.

### Optional: pay per call with x402 (no CMC key)
CMC also sells the quotes endpoint per request over [x402](https://coinmarketcap.com/api/documentation/ai-agent-hub/x402). The first GET returns HTTP 402 with a base64 `PAYMENT-REQUIRED` header. The tool checks those terms, signs a USDC `transferWithAuthorization` (EIP-3009) locally, and resends the request with `PAYMENT-SIGNATURE`.
```bash
CMC_MODE=x402 python3 -m spot_vs_perp.cli BTC ETH SOL                       # dry-run (default): real unpaid 402, shows the price, signs nothing
CMC_MODE=x402 CMC_X402_MODE=mock python3 -m spot_vs_perp.cli BTC SOL        # full flow offline: real captured 402, fake signer, synthetic data
# live: pip install eth-account; a dedicated, tiny payer wallet only
CMC_MODE=x402 CMC_X402_MODE=live CMC_X402_ALLOW_PAY=yes CMC_X402_PAYER_KEY=... python3 -m spot_vs_perp.cli BTC
```
Enforced in code (`spot_vs_perp/x402.py`):
- Only one payment option is accepted: scheme `exact`, network `eip155:8453` (Base), native USDC `0x8335…2913` with EIP-712 domain "USD Coin" v2, transfer method `eip3009`, and the pinned CMC `payTo`. CMC's 402 offers seven options, six of them on BNB Chain, and the other six are refused.
- Caps are checked **before signing**: `CMC_X402_MAX_USD_CALL` (default 0.01) and `CMC_X402_MAX_USD_SESSION` (default 0.05).
- Requests are GET only, to `pro-api.coinmarketcap.com` only, with no redirects.
- **Dry-run is the default.** Live mode needs both `CMC_X402_ALLOW_PAY=yes` and a key.
- The payer key is read only from `CMC_X402_PAYER_KEY` and stays in memory. It is never printed, never written to `--evidence`, and never put in an error message. Signatures aren't logged either.
- With EIP-3009 the payer pays no gas: CMC's facilitator submits the transfer, and the authorisation expires after 30 s.
- **Status: live mode exists but is untested with real funds.** Dry-run was run against CMC's real 402. Mock mode and signing are covered by tests that use a throwaway key and are checked against the official x402 SDK. No real payment has been made.

### As an MCP server (stdio)
```json
{"mcpServers": {"spot-vs-perp": {"command": "python3", "args": ["-m", "spot_vs_perp.mcp_server"], "cwd": "/path/to/spot-vs-perp", "env": {"CMC_API_KEY": "..."}}}}
```
Tool: `spot_vs_perp(symbols: string[])` returns rows plus a summary, for example:
`SOL: CMC spot $71.64, Hyperliquid perp $71.99 (+50.0 bps), funding +0.0033% per 8h; perps trade above spot: leveraged longs are paying up.` (from the test fixture)

## Tests
```bash
pip install pytest && pytest -q
```
Tests use fixtures: **synthetic** CMC responses in the documented v2 and v3 shapes, a **real** captured x402 402 challenge (unpaid probe), and a trimmed real Hyperliquid snapshot. They need no key and no network. With `pip install eth-account` (and optionally the official `x402` SDK), two more tests sign with a throwaway in-memory key. They check that the signature recovers to the payer and matches the official SDK's EIP-3009 digest.

## Data use
- CMC data is fetched with **your own key or your own x402 payment** and shown to **you**. This tool does not store, resell or forward it to any other service. (It is kept out of the operator's separate paid feed, cryptofeed402.)
- Attribution: *Data provided by CoinMarketCap.com.*
- Not financial advice.

## Where the API got in the way
From real calls on Nov 27, 2026, made with a Basic-plan key plus unpaid x402 probes. A summary is in [`docs/EVIDENCE.md`](docs/EVIDENCE.md). Raw responses stay local in the git-ignored `evidence/` folder, and the key is never written.

**Key mode**
- **Symbol lookups return every asset that shares the ticker.** `quotes/latest?symbol=BTC,ETH,SOL,HYPE,DOGE` returned **56 assets for 5 tickers**: 14 "BTC"s, 23 "DOGE"s, and meme tokens with names like "THE TICKER IS". The response was about 80 KB of JSON (44 KB after the change below). The tool keeps the highest-market-cap entry per ticker and now sends `aux=cmc_rank` to skip the tags, platform and supply blobs. Using `id=` avoids the ambiguity, but an agent usually starts from a ticker.
- **The quote is older than the call.** The BTC quote's `last_updated` was about 90 s before the response timestamp. Hyperliquid's mark is live, so a basis of a few bps is within that lag. The tool now reports `cmc_quote_age_s` and says so in the summary.
- **The top-N by market cap is full of things with no perp.** Our `listings/latest?limit=20` returned USDT, USDC, USDe, DAI and LEO. The tool reports "no Hyperliquid perp" for these instead of skipping them silently.
- **Credits are cheap, but you need to know the rule.** The 5-ticker quote cost 1 credit, and the listing cost 1. `key/info` (free) shows a 15,000-credit monthly allowance and 50 calls per minute on this key. The whole evidence run used a handful of credits.

**x402 mode**
- **x402 asks for payment before it checks the request.** `?symbol=BTC,ETH`, `?id=1,1027`, `?slug=bitcoin` and no parameters at all get the identical 402. A typo is only found after paying. The tool builds its query from validated symbols for this reason.
- **The 402 offers seven payment options, and only one is the advertised one.** Six are on BNB Chain, mostly with `permit2-exact`, which needs a one-time on-chain approval. A client that takes `accepts[0]` would sign on the wrong chain. The tool picks only Base USDC with EIP-3009.
- **Unknown paths also return 402, not 404.** `/x402/v3/cryptocurrency/listing/latest` returns 402 with an empty `accepts` list and "Path not configured for x402 payment". The real path is `listings` (plural).
- **The docs disagree on the v3 response shape.** The landing page shows `data` keyed by id (`"data": {"1": {...}}`), while the reference has `data` as an array with `quote` as an array. The parser accepts both, plus v2's `quote.USD`.
- **The keyless `/public-api/v3/...` route** answered our very first call with HTTP 429 ("limit for anonymous access"), so it isn't a dependable fallback.
- **Ticker collisions:** `quotes/latest` by symbol can return several assets per ticker. The tool keeps the highest market cap.

## License
MIT

TDQS

B3.3/5.0

Scored across 1 tool

Disambiguation5/5

With only one tool in the set, there is no possibility of overlap or misselection. The single tool's purpose (spot vs. perp basis/funding comparison) is clearly stated and unambiguous.

Naming Consistency5/5

The lone tool uses a clear snake_case descriptive name that reads as a predicate on the domain concept. There are no competing conventions to create inconsistency.

Tool Count2/5

A single tool is a very thin surface for a market-data comparison server; agents cannot discover symbols, list supported assets, or filter/batch requests. The narrow scope avoids bloat, but one tool leaves little room for real workflows.

Completeness3/5

The tool covers the core comparison itself (basis in bps, funding, flags, summary), which is a reasonable end-to-end output. However, there is no symbol-discovery or metadata operation, so an agent that doesn't already know valid Hyperliquid/CMC symbols has a dead end.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues