Skip to main content
Glama
cmc-market-mcp

cmc-market-mcp

by hungndp
README.md
# cmc-market-mcp

**Live CoinMarketCap data for LLM agents, over the Model Context Protocol.**

An MCP server that gives any MCP-compatible agent (Claude Desktop, Cursor, a
custom LangChain/CrewAI loop, …) six focused tools for live crypto market
awareness: latest quotes, brand-new listings, trending coins, top
gainers/losers, global market metrics with BTC-dominance trend, and the
Fear & Greed index with sentiment history.

Built for the **CoinMarketCap API Hackathon — Round 2**, track
**AI Agents and Automation**.

- **Zero dependencies.** Pure Python 3.10+ standard library — the MCP
  protocol, the HTTP client, retries, caching and the demo agent are all
  implemented in-repo. Clone it and it runs.
- **Credit-aware.** CoinMarketCap bills per API call; the client caches
  aggressively per endpoint, retries politely, and reports exactly how
  many credits each answer cost in the tool result metadata.
- **Runs offline.** A `--fixtures` mode replays recorded-shaped API
  responses, so the full demo and the whole test-suite work with no key
  and no network.

---

## Try it in 2 minutes (no API key needed)

```bash
git clone https://github.com/hungndp/cmc-market-mcp.git
cd cmc-market-mcp
python3 demo/demo_agent.py --fixtures
```

The demo spawns the real server, performs the MCP handshake, lists the
tools, then asks three market questions and prints the complete
question → plan → tool-calls → answer trace:

```
Q2: Is BTC dominance rising, and how big is the whole market?
[plan] 2 tool call(s): get_global_metrics, get_latest_quotes
  -> tools/call get_global_metrics({})
     summary: Total crypto market cap is $3.36T; BTC dominance is 57.40% and rising (+0.88% vs yesterday).
ANSWER: Yes — BTC dominance is rising: it is 57.40% of the market now versus
56.90% yesterday (+0.88%). The total crypto market cap is $3.36T ...
```

Full captured output: [`docs/evidence/demo-fixtures-output.txt`](docs/evidence/demo-fixtures-output.txt)
(sample data, clearly labelled as such by every tool result).

## Run it live

1. Get a free API key at <https://coinmarketcap.com/api/>.
2. Put it where the server can read it — environment or a `.env` file
   (copy `.env.example`); it is sent only as the `X-CMC_PRO_API_KEY`
   header and is **never** logged or committed.
3. Start the server:

```bash
export CMC_API_KEY=your_key_here
./cmc-mcp            # or: pip install . && cmc-market-mcp
```

### Connect an MCP host

```json
{
  "mcpServers": {
    "cmc-market": {
      "command": "/path/to/cmc-market-mcp/cmc-mcp",
      "env": { "CMC_API_KEY": "your_key_here" }
    }
  }
}
```

---

## Tools

| Tool | What it answers | Key arguments |
| --- | --- | --- |
| `get_latest_quotes` | Price, 1h/24h/7d changes, market cap, 24h volume for any symbols | `symbols` (e.g. `"BTC,ETH"`), `currency` |
| `get_new_listings` | Most recently listed coins, with platform and add date | `limit`, `currency` |
| `get_trending` | Coins trending on CMC right now | `limit`, `currency` |
| `get_top_movers` | Biggest gainers/losers over 1h / 24h / 7d / 30d | `limit`, `time_period`, `direction` |
| `get_global_metrics` | Total market cap & volume, BTC/ETH dominance — **including whether dominance is rising vs yesterday** | `currency` |
| `get_fear_and_greed` | Fear & Greed index; with `days > 1`, history + sentiment trend | `days` (1–30) |

Every result returns a one-line `summary`, a trimmed structured payload
(raw CMC responses are projected down to the fields an agent reasons
over), and `meta` with the serving endpoint, cumulative credits spent,
and data source (live vs fixture).

## CoinMarketCap endpoints used — and what they made possible

| Endpoint | Tool(s) | What the API helped with |
| --- | --- | --- |
| `GET /v1/cryptocurrency/quotes/latest` | `get_latest_quotes` | Grounding answers in real prices instead of model memory — the difference between an agent that *knows* BTC's price and one that *guesses* it. |
| `GET /v1/cryptocurrency/listings/new` | `get_new_listings` | Surfacing projects hours after they list — data an LLM cannot have in its weights at all. |
| `GET /v1/cryptocurrency/trending/latest` | `get_trending` | A real-time attention signal (search/watchlist heat) that complements price data. |
| `GET /v1/cryptocurrency/trending/gainers-losers` | `get_top_movers` | Pre-ranked movers across four time windows, so "what's moving?" costs one call, not a full listings scan. |
| `GET /v1/global-metrics/quotes/latest` | `get_global_metrics` | Market-wide context in a single call — crucially it ships `btc_dominance_yesterday`, which lets the agent answer *trend* questions ("is dominance rising?") from one snapshot instead of storing history. |
| `GET /v3/fear-and-greed/latest` + `/historical` | `get_fear_and_greed` | CMC's own sentiment index; pairing latest + history turns a number into a trend ("sentiment is getting more fearful"). |

The envelope's `credit_count` field also drives the client's credit
accounting, so agents can budget their own API spend.

## Architecture

```
            ┌──────────────────── MCP host / agent ────────────────────┐
            │  Claude Desktop · Cursor · demo/demo_agent.py · your bot │
            └──────────────────────────┬─────────────────────────────────┘
                       MCP over stdio  │  JSON-RPC 2.0 (newline-delimited)
            ┌──────────────────────────▼─────────────────────────────────┐
            │  server.py — protocol layer                            │
            │  initialize · tools/list · tools/call · ping           │
            ├────────────────────────────────────────────────────────┤
            │  tools.py — 6 tools: validation, projection of raw     │
            │  payloads into compact results, summaries, metadata    │
            ├────────────────────────────────────────────────────────┤
            │  client.py — CMC Pro API client                        │
            │  TTL cache · retry + backoff (honours Retry-After) ·   │
            │  typed errors · credit accounting                      │
            └───────────────┬───────────────────────────┬────────────┘
                    live transport              fixture transport
                 (urllib, stdlib)          (recorded-shaped JSON)
                            │                           │
                 pro-api.coinmarketcap.com        fixtures/*.json
```

| Module | Responsibility |
| --- | --- |
| `src/cmc_market_mcp/server.py` | MCP stdio server, `.env` loading, CLI |
| `src/cmc_market_mcp/tools.py` | Tool schemas, handlers, formatting |
| `src/cmc_market_mcp/client.py` | API client: transport, retries, errors, credits |
| `src/cmc_market_mcp/cache.py` | Thread-safe per-entry TTL cache |
| `src/cmc_market_mcp/fixtures.py` | Offline fixture transport |
| `src/cmc_market_mcp/errors.py` | Typed error hierarchy |
| `demo/demo_agent.py` | Scripted agent: planner → tool calls → grounded answers |
| `tests/` | 32 unit/protocol/end-to-end tests (stdlib `unittest`) |

### Design decisions worth noting

- **Per-endpoint cache TTLs** — quotes 60 s, listings/trending/metrics
  5 min, Fear & Greed 30 min (CMC updates it daily). An agent asking the
  same question twice in one reasoning loop pays once.
- **Retries only where safe** — 429/5xx/network failures retry with
  exponential backoff + jitter (max 3 attempts); 4xx client errors fail
  fast as typed exceptions and surface to the agent as clean tool errors,
  never tracebacks.
- **Deterministic demo** — the demo agent's planner/composer are
  rule-based so judges get a byte-identical, reproducible trace; swap in
  an LLM where `plan()` and `compose()` sit and the same server serves a
  fully autonomous agent.

## Tests

```bash
python3 -m unittest discover -s tests -t .
```

32 tests covering: envelope parsing, error mapping (401/400/429/5xx),
retry-then-succeed, cache hit/miss behaviour, credit accounting, every
tool handler against fixtures, argument validation, the MCP protocol
in-process, and a full stdio round-trip against the spawned server.

## Project layout

```
cmc-market-mcp/
├── cmc-mcp                  # one-command launcher (no install needed)
├── demo/demo_agent.py       # scripted demo agent with full trace
├── docs/
│   ├── SUBMISSION.md        # hackathon submission checklist
│   └── evidence/            # captured demo output (fixtures mode)
├── fixtures/                # recorded-shaped sample API responses
├── src/cmc_market_mcp/      # the server package
└── tests/                   # unittest suite
```

## License

MIT — see [LICENSE](LICENSE).

TDQS

A3.7/5.0

Scored across 6 tools

Disambiguation5/5

Each tool targets a clearly distinct data view: latest quotes, new listings, trending coins, top movers, global metrics, and fear/greed sentiment. Overlap is minimal, and descriptions make boundaries explicit.

Naming Consistency5/5

All six tools use a consistent get_ + descriptive noun phrase pattern. The convention is predictable and readable throughout.

Tool Count5/5

Six focused tools are well-scoped for a CoinMarketCap market-data server. Each tool earns its place without bloat.

Completeness4/5

The surface covers common market snapshot needs: quotes, listings, trending, movers, global metrics, and sentiment. Minor gaps remain, such as historical OHLC price data or coin metadata lookup, but core workflows are covered.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues