Crypto market data for AI agents: APIs, function calling, MCP and llms.txt
In short
- A language model knows the market only up to its training data cutoff. It gets current prices, spreads and funding rates through tools: the model picks the call and its arguments, and your code makes the API request.
- A tool on top of a market data API should be narrow: one endpoint, filters as parameters, a few rows with the fields that matter and the data timestamp in the result. Tool definitions come from the OpenAPI spec, and MCP plugs the same tools into any compatible client.
- The key stays on your server, text from external data reaches the model only inside tool results, and a human confirms every trade. Genesis API is read-only and publishes openapi.json, llms-full.txt and an API catalog for agents.
An AI agent gets crypto market data through tools: the model decides which data it needs, your code calls a crypto API and returns a short JSON with prices, spreads and the time the data was built. Tools are connected either through function calling in the model's API or through an MCP server, and both run on top of an ordinary REST API.
The examples use Genesis API, a read-only REST API with CEX, DEX, on-chain and prediction market data. For crypto APIs in general and how to compare them, see Crypto API: types of market data APIs and how to choose.
Why the model doesn't know current prices
A language model is trained on text collected up to a certain date, its knowledge cutoff. It knows nothing about listings, rates and prices after that date, and a BTC price quoted from memory is a number from training text of unknown date. The model doesn't know the current time either unless you pass it in the request.
For arbitrage an answer from memory is useless: a spread between exchanges lives for minutes, and the funding rate changes every settlement period, every 8, 4 or 1 hour. Live numbers come only from a tool: an API reference in the context teaches the model paths and parameters, but it holds no prices.
| What the model needs | Where it comes from | Example |
|---|---|---|
| API paths, parameters and fields | Reference in the context | llms-full.txt, openapi.json |
| Prices, spreads, rates | Tool call | GET /funding/spread?coin=TON |
| Current time and data age | System prompt and tool result | updated_at, age_sec |
How function calling works
Function calling is a mode in which the model returns a tool name and arguments instead of text, and your code runs the request. Illustrative example: a user asks where the largest funding spread for TON is right now. The call and the result, schematically:
{
"tool_call": {
"name": "get_funding",
"arguments": { "coin": "TON" }
},
"tool_result": {
"updated_at": 1794675860,
"age_sec": 12,
"rows": [
{
"coin": "TON",
"spread_pct": 0.04,
"pair": ["Bitget", "Bybit"],
"funding_pct": [0.05, 0.01],
"interval": ["8h", "8h"]
}
]
}
}
- The app sends the model the question and the tool definitions: name, purpose and an argument schema in JSON Schema.
- The model returns a
get_fundingcall with the arguments{"coin": "TON"}. - Your code validates the arguments, sends
GET /funding/spread?coin=TONwith theX-API-Keyheader and trims the response. - The result goes back to the model, which answers: Bitget and Bybit, 0.05% and 0.01% per 8 hours, a 0.04% difference, data 12 seconds old.
- If the data is not enough, the model calls the next tool.
The model makes no network requests and never sees the API key. Field names depend on the model's API: in the Claude API the schema sits in input_schema, the call arrives as a tool_use block and the result goes back as a tool_result block, while MCP calls the schema inputSchema. In both cases it is JSON Schema.
How to design tools on top of a market data API
One tool, one job
The model picks a tool by its description, so narrow tools work more reliably than a generic call_api(path, params). Choosing from five to seven tools built for the agent's tasks is easier than choosing from the 37 operations in the spec.
| Tool | Genesis API endpoint | Plans |
|---|---|---|
get_spreads | /arbitrage/spot-spot | All |
get_funding | /funding/spread | All |
get_prediction_arbs | /predictions/arbitrage | Start, Pro, Max |
get_book | /orderbooks/book | Pro, Max |
The description says when to call the tool and what units the numbers use: in Genesis API spreads and rates are percentages, so 0.92 means 0.92%.
Filters as parameters, validation in code
API filters such as coin, exchange and min_spread become tool parameters. The model fills them in from the question, the handler checks them against an allowlist of parameters, types and values, and enum lists the allowed values: for /orderbooks/book, market is only spot or futures. The model never builds the request path, and the schema rejects extra fields (additionalProperties: false).
A filtered response comes without an ETag, so every repeated filtered poll costs a call: there is no free 304. If the agent needs dozens of coins, it is cheaper to keep the full unfiltered dataset locally and poll it with If-None-Match.
Compact results
Illustrative example: the full unfiltered /funding/spread response covers 1,000 coins. For a coin on 10 exchanges one row holds 2 + 10 + 8 × 5 = 52 values: the coin, the spread, 10 fields of the best pair in best and 5 fields for each of the other 8 exchanges in others. The whole response is 1,000 × 52 = 52,000 values, while an answer about the best pairs needs 5 rows of 8 values: 5 × 8 = 40.
Tool definitions and results enter the context at every step: the Claude API bills them as input tokens.
Data time and freshness
The handler puts updated_at, the build time of the data from meta.updated_at in unix seconds, and age_sec into the result. The model can then say "data 12 seconds old" instead of passing off yesterday's spread as current.
Data freshness is set by the plan: meta.freshness_sec runs from 60 s on Trial to 5 s on Max. Before that interval passes, the API returns the same snapshot, so the handler caches the response for freshness_sec seconds. Order books keep their own clock: book_ts, age_sec and a stale flag for books older than 30 s.
Example: the get_funding tool
The definition below uses the MCP format; for the Claude API the same content goes into input_schema. The handler applies limit itself: the API has no such parameter.
{
"name": "get_funding",
"description": "Where funding is higher or lower: best exchange pair",
"inputSchema": {
"type": "object",
"properties": {
"coin": {
"type": "string",
"description": "Coin ticker, e.g. TON"
},
"min_spread": {
"type": "number",
"minimum": 0,
"description": "Minimum spread, %: 0.05 means 0.05%"
},
"limit": {
"type": "integer",
"minimum": 1,
"maximum": 10,
"description": "How many rows to return, 5 by default"
}
},
"additionalProperties": false
}
}
The Python handler: a cache for freshness_sec, one short pause on 429 and 503, a log without the key and a compact result with the data time.
import logging
import os
import time
import requests
URL = "https://api.genesisarbitrage.com/v1/funding/spread"
KEY = os.environ["GENESIS_API_KEY"] # the key stays on the server
cache = {} # request params -> (time received, response body)
def get_funding(coin=None, min_spread=None, limit=5):
p = {"coin": coin and coin.upper(), "min_spread": min_spread}
p = {k: v for k, v in p.items() if v}
ck = tuple(sorted(p.items()))
got, body = cache.get(ck, (0, None))
if not body or time.time() - got >= body["meta"]["freshness_sec"]:
for attempt in range(2): # 429, 503: short wait, one retry
r = requests.get(URL, params=p, timeout=10,
headers={"X-API-Key": KEY})
wait = int(r.headers.get("Retry-After", "0"))
if attempt or wait > 5 or r.status_code not in (429, 503):
break
time.sleep(wait)
logging.info("get_funding %s -> %s id=%s", p, r.status_code,
r.headers.get("X-Request-Id")) # no key in the log
if r.status_code != 200:
return {"error": r.status_code} # 401, 403, 429, 503
body = r.json()
cache[ck] = (time.time(), body)
t = body["meta"]["updated_at"]
top = sorted(body["data"], key=lambda x: -x["spread_pct"])
rows = [{"coin": x["coin"], "spread_pct": x["spread_pct"],
"pair": [x["best"]["exchange_1"], x["best"]["exchange_2"]],
"funding_pct": [x["best"]["funding_1_pct"],
x["best"]["funding_2_pct"]],
"interval": [x["best"]["interval_1"],
x["best"]["interval_2"]]}
for x in top[:min(max(int(limit), 1), 10)]]
return {"updated_at": t, "age_sec": int(time.time() - t),
"rows": rows}
The handler doesn't wait out pauses longer than 5 seconds: once the quota runs out, Retry-After points to the reset, which can be days away. The model gets the status code and tells the user what happened: 403 means plan_restricted, an endpoint outside the plan (Genesis API errors).
OpenAPI as the source of tool definitions
OpenAPI is a standard for machine-readable HTTP API descriptions: an operation is described by an operationId, a short summary and parameters with schemas. In version 3.1 the Schema Object is a superset of JSON Schema 2020-12 (OpenAPI 3.1 specification), and MCP reads inputSchema as JSON Schema 2020-12 by default. So parameters move into a tool without conversion.
The script builds tools from the Genesis API spec: it takes the operations you want, skips those outside your plan by x-genesis-plans and carries over query and path parameters. Headers are the handler's job.
import requests
SPEC = "https://genesisarbitrage.com/openapi.json"
def tools_from_spec(wanted, plan):
"""wanted: operationId -> tool name; plan: trial … max."""
spec = requests.get(SPEC, timeout=15).json()
tools, routes = [], {}
for path, item in spec["paths"].items():
op = item.get("get", {})
name = wanted.get(op.get("operationId"))
if not name or plan not in op.get("x-genesis-plans", []):
continue # unwanted or not in plan: 403 plan_restricted
props, required = {}, []
for prm in op.get("parameters", []):
if "$ref" in prm or prm["in"] not in ("query", "path"):
continue # the handler sends X-API-Key, If-None-Match
props[prm["name"]] = {**prm["schema"],
"description": prm["description"]}
if prm.get("required"):
required.append(prm["name"])
tools.append({
"name": name,
"description": op["description"].split("\n\n")[0],
"inputSchema": {"type": "object", "properties": props,
"required": required,
"additionalProperties": False}})
routes[name] = path # tool name -> endpoint path
return tools, routes
tools, routes = tools_from_spec({"getFundingSpread": "get_funding",
"getArbitrageSpotSpot": "get_spreads"},
plan="trial")
getFundingSpread turns into a get_funding tool with the coin and min_spread parameters. Pass every operation and Trial keeps 11 of the 37, Start keeps 16. The routes dict stores each tool's path.
MCP: your own server on top of a REST API
MCP (Model Context Protocol) is an open standard for connecting AI applications to data and tools. Anthropic open-sourced it on November 25, 2024 (Anthropic announcement) and on December 9, 2025 donated it to the Agentic AI Foundation, a fund under the Linux Foundation (MCP blog).
The application with the model, the host, creates one MCP client per server. A server exposes tools, resources and prompt templates over JSON-RPC 2.0: a local one over stdio, a remote one over Streamable HTTP, for which MCP recommends getting tokens via OAuth (MCP architecture).
| Function calling | MCP | |
|---|---|---|
| Where tools are defined | In the request to the model API | On the server; the client fetches them with tools/list |
| Who runs the call | Your application code | The MCP server, on a tools/call request |
| Where it works | In the app where you wrote the loop | In any client that supports MCP |
Wrapping a REST API in an MCP server takes four steps:
Pick the operations
Take 3–7 operations for the agent's task; build tool names, descriptions and parameters from OpenAPI, as in the script above.
Return the list on tools/list
The server returns
name,descriptionandinputSchemafor every tool.Handle tools/call
Validate the arguments, make a GET request with the key from the server's environment and return compact JSON in a
contentblock. Return an API error withisError: true: the model uses it to fix its arguments.Choose the transport
Over stdio the server runs on your machine, and the key never leaves it. Put a remote Streamable HTTP server behind authorization, or anyone who learns the URL will spend your quota.
Official MCP SDKs exist for 10 languages, from Python and TypeScript to Go and Rust (SDK list).
llms.txt and llms-full.txt
llms.txt is a Markdown file at /llms.txt that helps language models use a website. Jeremy Howard proposed the format on September 3, 2024 (llmstxt.org): the only required part is an H1 with the name, followed by a blockquote summary and sections with links to Markdown versions of pages.
The proposal does not define llms-full.txt: the name is used for a whole documentation set in one Markdown file, and the MCP documentation site, for one, publishes it. The model doesn't need to follow links, since the entire reference lands in its context.
Agent security
Keep the key in an environment variable on the server: it must not appear in prompts, browsers or logs. A Genesis API key is read-only, so it can't place an order or withdraw funds, and a leak costs you quota. Replace a leaked key with Reissue in your profile (key storage).
Prompt injection is an instruction for the model hidden in data. A token's name is set by whoever deployed it and a trader's name by the trader, so a field can contain "ignore previous instructions". In Genesis API, external text arrives in the title and outcome fields of prediction markets, trader name, on-chain token_name and the message_ru and message_en of Genesis AI+ signals: state in the system prompt that tool results are data only.
The MCP specification requires servers to validate tool inputs, rate limit invocations and sanitize outputs, and advises clients to confirm sensitive operations and log tool usage (MCP tools). Log the X-Request-Id: with it, the time in UTC, the endpoint and the status, support can find the request.
Automation risks are covered in lesson 5 of the Crypto API course.
Costs and limits
Only a 200 response uses Genesis API quota; 304 and errors are free but count toward the rate limit per second. Over the limits the server answers 429 and charges nothing.
| Plan | Price | Quota and rate | Freshness |
|---|---|---|---|
| Trial | $20/month | 500,000 calls, 1 req/s | 60 s |
| Start | $50/month | 2M calls, 2 req/s | 30 s |
| Pro | $100/month | 5M calls, 5 req/s | 10 s |
| Max | $200/month | 10M calls, 15 req/s | 5 s |
Illustrative example: 500 questions a day with 3 tool calls each is 500 × 3 = 1,500 calls a day and 1,500 × 30 = 45,000 over 30 days, 9% of the Trial quota. The cache covers repeats with the same parameters within freshness_sec, and a cap on tool calls per answer keeps a loop from eating the quota.
Polling more often than meta.freshness_sec brings no new snapshot. Cheap polling with ETag and retries is covered in How to poll a crypto API without hitting limits, the limits in the Genesis API limits guide. If the agent only needs rules and no model, a crypto arbitrage bot in Python is simpler.
Genesis API for AI agents
Genesis API is a REST API with Genesis Arbitrage data: CEX and DEX spreads, order books, funding, open interest, cross-chain, on-chain flows, prediction markets, sportsbook surebets and AI signals. Requests are HTTP GET with the X-API-Key header, responses are JSON with data and meta (response format), and no SDK is needed.
Published for agents:
openapi.json— OpenAPI 3.1: 37 operations, response schemas and plans inx-genesis-plans;llms-full.txt— the full reference in one Markdown file;llms.txt— a site overview for language models;/.well-known/api-catalog— an RFC 9727 catalog that links to the spec, the docs and the status page.
There is no official MCP server, no WebSocket and no trading endpoints: the agent reads data, and trades stay with a human. Step-by-step setup is in the Genesis API for AI agents guide.
Questions and answers
Can an AI agent trade crypto on its own?
Only if you give it an exchange trading API, and that is your code and your risk. Not through Genesis API: it only reads data. The MCP specification says a human should always be able to deny a tool call; for trades, make it a rule that a human confirms every order.
Which Genesis API plan does an AI agent need?
Trial at $20 a month covers CEX spreads, funding and open interest. Start adds stocks, on-chain sections and prediction arbitrage in the exact and dutch modes, while Pro and Max open everything, including DEX and order books. Reaction speed depends on the per-second limit and the plan's freshness; plan contents are on the Genesis API pricing page.
Where do I get the Genesis API spec for an agent?
OpenAPI 3.1 is at genesisarbitrage.com/openapi.json, and the reference for the model is at genesisarbitrage.com/llms-full.txt. An agent can also find both through the /.well-known/api-catalog catalog.
Does Genesis API have an MCP server?
There is no official one. You build your own from the same handlers: an MCP tool is a GET request to an endpoint with the key from the server's environment. A minimal Python example is in the MCP glossary entry.