# Use Newhedge with AI agents

> Copy-paste prompts and code snippets for using the Newhedge API from
> Cursor, Claude Code, ChatGPT Code Interpreter, plain Claude.ai, and MCP clients.

The fastest way to teach an LLM what Newhedge offers is to point it at the
free machine catalog at `https://newhedge.io/api/v2/catalog`. One HTTP call,
no token, returns every chart, every metric, sample values, units, update
frequency, and the full request URL template. That's enough context for the
agent to answer most questions on its own.

## TL;DR — system prompt to drop into any agent

```
You can answer questions about Bitcoin on-chain, market, mining, and macro
metrics by calling the Newhedge API.

Discovery (free, no auth):
  GET https://newhedge.io/api/v2/catalog

The catalog returns every available chart and metric, with `slug`, `name`,
`shape`, `units`, `update_frequency`, a `sample`, and a
`request_url_template`. Use it to pick the right metric before issuing any
data call.

Auth: every data call needs `?api_token=YOUR_TOKEN` (24-character
alphanumeric, premium-only). Header auth is not supported.

Endpoints:
  GET https://newhedge.io/api/v2/metrics/{chart_slug}/{metric_name}?api_token=YOUR_TOKEN
  GET https://newhedge.io/api/v2/news/{query_type}?api_token=YOUR_TOKEN
  GET https://newhedge.io/api/v2/price/historical?api_token=YOUR_TOKEN
  GET https://newhedge.io/api/v2/price/live?api_token=YOUR_TOKEN

Quota: 10,000 calls/month per token. Cache catalog responses; metric data
updates daily for most series.
```

## Cursor / Claude Code

Add the system prompt above to a project rule (`.cursor/rules/newhedge-api.mdc`)
or a Claude Code memory note. Then ask in chat:

> Show me the Mayer Multiple over the last 90 days as a chart, and tell me
> whether the current value is above or below its long-term average.

The agent should:

1. Call `https://newhedge.io/api/v2/catalog` (free, no token), find the
   `mayer-multiple` chart slug and its metric name.
2. Call
   `https://newhedge.io/api/v2/metrics/mayer-multiple/{metric_name}?api_token=YOUR_TOKEN`.
3. Slice the last 90 entries from the returned `[[timestamp_ms, value], ...]`
   array, plot it, and compare the current value to the historical mean.

If you have an `OPENAPI_SPEC` import (e.g. via the Cursor "tools" config),
point it at `https://newhedge.io/api/v2/openapi.json` for typed parameter
hints.

## ChatGPT Code Interpreter

```python
import os
import requests
import matplotlib.pyplot as plt
from datetime import datetime

API_TOKEN = os.environ["NEWHEDGE_API_TOKEN"]

# 1. Discover (no token required).
catalog = requests.get("https://newhedge.io/api/v2/catalog", timeout=15).json()

# 2. Find the chart you want.
mayer = next(
    chart
    for group in catalog["groups"]
    for chart in group["charts"]
    if chart["slug"] == "mayer-multiple"
)
metric = mayer["metrics"][0]
url = metric["request_url_template"].replace("{token}", API_TOKEN)

# 3. Fetch and plot.
series = requests.get(url, timeout=15).json()
xs = [datetime.utcfromtimestamp(p[0] / 1000) for p in series[-180:]]
ys = [p[1] for p in series[-180:]]
plt.plot(xs, ys)
plt.title(f"{mayer['extended_name']} — last 180 days")
plt.show()
```

`requests` and `matplotlib` are pre-installed in ChatGPT Code Interpreter, so
this snippet runs as-is.

## Plain Claude.ai (no tools)

If you're in a Claude conversation without tool use, paste the contents of
`https://docs.newhedge.io/llms.txt` (a few KB) at the top of the chat and
say:

> The above is the index for the Newhedge API. When I ask you about Bitcoin
> on-chain or market metrics, identify the right metric from the catalog,
> show me the request URL with `YOUR_TOKEN` placeholder, and explain how to
> interpret the response shape. Don't hallucinate data — only describe what
> the API returns.

For longer sessions, paste `https://docs.newhedge.io/llms-full.txt`
(everything inlined, but larger). Both files are regenerated whenever a
chart or metric changes.

## MCP server

Hosted MCP endpoint (JSON-RPC over `POST`), same `api_token` query parameter as REST:

`POST https://newhedge.io/api/v2/mcp?api_token=YOUR_TOKEN`

**Protocol:** JSON-RPC 2.0. Send a JSON body with `Content-Type: application/json`. Include `api_token` on the query string for every request (including `initialize` and `tools/list`); header auth is not supported.

**Transport methods:** `initialize`, `tools/list`, `tools/call`, and `ping`. Typical clients call `initialize`, then `tools/list` to read tool schemas, then `tools/call` for work.

**`tools/call`:** set `params.name` to the tool name and `params.arguments` to a JSON object of tool-specific keys (strings for slugs/names, as in the table below).

| Tool | Arguments | Monthly quota |
|------|-----------|---------------|
| `list_metrics` | Optional `group` (chart category key); omit for full catalog-shaped payload | none |
| `search_metrics` | `query` (string) | none |
| `get_api_docs` | `topic` (string; searches inlined sections from the same cache as `llms-full.txt`) | none |
| `get_metric` | `chart_slug`, `metric_name`; optional `limit`, `start_ms`, `end_ms` | one unit per successful call (same as `GET /api/v2/metrics/...`) |
| `get_latest_value` | `chart_slug`, `metric_name` | one unit per successful call |
| `compare_metrics` | `specs` array of `{ "chart_slug", "metric_name" }`; optional `limit` / `start_ms` / `end_ms` apply to each fetched series | one unit per spec per successful fetch |

Discovery tools (`list_metrics`, `search_metrics`, `get_api_docs`) read the same warmed catalog / docs caches as `GET https://newhedge.io/api/v2/catalog` and the generated LLM docs.

**Example — list tools:**

```bash
curl -sS -X POST "https://newhedge.io/api/v2/mcp?api_token=YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```

**Example — call a tool** (replace `chart_slug`, `metric_name`, and token using rows from the catalog):

```bash
curl -sS -X POST "https://newhedge.io/api/v2/mcp?api_token=YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_latest_value","arguments":{"chart_slug":"mayer-multiple","metric_name":"mayer_multiple"}}}'
```

**Claude Code / Desktop** — Claude Desktop: add this to `claude_desktop_config.json`. Claude Code uses the same server URL; follow Claude Code's MCP docs for where to register the server on your platform.

```json
{
  "mcpServers": {
    "newhedge": {
      "url": "https://newhedge.io/api/v2/mcp?api_token=YOUR_TOKEN"
    }
  }
}
```

**Cursor** — `.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "newhedge": {
      "url": "https://newhedge.io/api/v2/mcp?api_token=YOUR_TOKEN"
    }
  }
}
```

**Continue** — `~/.continue/config.json` excerpt:

```json
{
  "mcpServers": [
    {
      "name": "newhedge",
      "url": "https://newhedge.io/api/v2/mcp?api_token=YOUR_TOKEN"
    }
  ]
}
```

Always use `https://` in production. For local development, use your dev host and token (e.g. `http://localhost:3000/api/v2/mcp?api_token=...`).

## Troubleshooting

| Symptom | Likely cause | Fix |
|---------|--------------|-----|
| `{"error":"Token is required"}` | No `api_token` query param. | Append `?api_token=...`. |
| `{"error":"Invalid token"}` | Token is wrong, not 24 chars, or the user is not on the Advanced plan. | Regenerate at https://newhedge.io/account/api-settings. |
| `{"error":"Monthly API calls limit reached"}` | Token is at the 10,000 calls / month cap. | Wait until next month, or contact sales. |
| `{"error":"Chart not found"}` / `{"error":"Metric not found"}` | Wrong slug / metric name. | Re-fetch the catalog and pick a valid `(chart_slug, metric_name)` pair from `x-newhedge-allowed-pairs` in the OpenAPI spec. |
| `{"error":"Currency not found"}` | `currency` query param doesn't match a row in `CurrencyRate`. | Use a code from the `currencies` array in the catalog. |

## Related

- Catalog: https://newhedge.io/api/v2/catalog
- OpenAPI 3.1: https://newhedge.io/api/v2/openapi.json
- `llms.txt`: https://docs.newhedge.io/llms.txt
- `llms-full.txt`: https://docs.newhedge.io/llms-full.txt
- API token: https://newhedge.io/account/api-settings
