# Vibecode a TCGGraph integration

Ready-to-paste prompts and a drop-in rules file for coding agents.

## Rules file

Save this as `AGENTS.md` (Codex and others), `CLAUDE.md` (Claude Code) or
`.cursor/rules/tcggraph.mdc` (Cursor). The content is the same in all three.

# TCGGraph

This project uses TCGGraph for trading card game data — one REST and GraphQL
API covering Pokémon, Magic: The Gathering, One Piece, Yu-Gi-Oh!, Disney Lorcana, Star Wars: Unlimited, Digimon, Grand Archive and Dragon Ball Super.

Full machine-readable reference: https://tcggraph.com/llms-full.txt
Every page has a plain-text twin at <path>.md, e.g. https://tcggraph.com/docs/rest.md and https://tcggraph.com/docs/webhooks.md

## Connection

- REST base URL: https://api.tcggraph.com/v1
- GraphQL endpoint: https://api.tcggraph.com/graphql
- Auth header: `Authorization: Bearer $TCGGRAPH_KEY`
- The version is the `/v1` in the path. There is no version header and nothing
  to pin; additions arrive in v1 without breaking it, and anything breaking would
  be a new path. Changes are listed at https://tcggraph.com/changelog
- Every 2xx response carries `X-Credits-Cost`; `X-Credits-Remaining` and
  `X-RateLimit-Remaining` say where the account stands. There is no daily cap.
  Errors and 304s are free and carry no credit headers, so don't read them there.
- OpenAPI 3.1: https://tcggraph.com/openapi.json

## Rules

- Never put TCGGRAPH_KEY in client-side code. Proxy through a server route.
- Never invent endpoints or fields. Check the reference above; if it is not
  there, say so rather than guessing.
- List responses are `{ data: [...], meta: {...} }`. Pagination lives in meta.
- Use `/v1/cards` with a `name` filter for lookups by name, and the other
  filters to narrow by set, rarity or game. One page returns up to 100 cards and
  costs the same as returning one, so page rather than fetching ids in a loop.
- Set codes repeat across games (`OP16` is One Piece and Yu-Gi-Oh!), so always
  pass `game` with `set=` and on `/v1/sets/{code}`. Without it an ambiguous
  code is a `400 invalid_request` whose `details.matches` lists the games.
- Filter names are the ones each game declares in the reference. An unknown
  parameter is a `400` with `details.allowed` and often `details.suggestion`;
  read the body and fix the name rather than dropping the filter.
- Prices are per source, per list type (retail or buylist) and per finish, each
  with its own currency and timestamp. Never convert between currencies and
  never sum across sources.
- `finish` is a closed list documented on /docs/prices (normal, foil, etched,
  reverse-holo, cosmos-holo, cracked-ice, pokeball, masterball, energy-symbol,
  duskball, loveball, friendball, quickball, team-rocket, staff, prerelease,
  league, pokemon-center, 1st-edition, 1st-edition-foil, shadowless, limited).
  A Cardmarket row and a TCGplayer row for the same
  physical card carry the same value. For a picker, read `printings[]`: the
  same quotes grouped per printing with `label`, `kind`, its own `images`
  and the stable `key` to store a user's choice under.
- When filtering or sorting by price, pass `source`. The bounds are in that
  source's currency: `source=cardmarket&minPrice=50` means €50, not $50.
- Every game carries a `tcgplayer` row (USD) and every game but Grand Archive
  a `cardmarket` row (EUR); Magic adds Card Kingdom and Mana Pool. A missing
  row is explained on `priceStatus`, so read that before calling it a bug.
- Card images come in small, normal and large. Always set explicit dimensions —
  cards are 5:7.
- `hashes` carries a `phash` and `phashColor` per printing for matching a
  photo against the catalogue. It is null until the artwork has been processed,
  so treat a missing hash as "not ready" rather than "no match".

## Errors worth handling explicitly

- `402 no_active_plan` — the account has no plan. Show an actionable message.
- `402 balance_empty` — the prepaid balance will not cover the call.
- `429 rate_limited` — honour Retry-After. Do not retry in a tight loop.


## What agents get wrong about card data

### Converting EUR to USD

Typically: Reads a Cardmarket quote in EUR, multiplies by a hardcoded rate and shows one price.

Instead: Shows both markets separately in their own currency. Cardmarket and TCGplayer diverge for reasons that have nothing to do with the exchange rate — different supply, different grading conventions, different demand.

### Filtering price without a source

Typically: Sends minPrice=50 and assumes dollars.

Instead: Passes source explicitly and reads meta.priceSource back. A silent currency mismatch produces a plausible-looking list that is simply wrong, which is far worse than an error.

### Treating card names as unique

Typically: Keys a lookup or a cache on the card name.

Instead: Keys on id, which is stable and unique per printing, groups languages with englishId and printings with game plus name. Charizard exists hundreds of times across sets, languages and finishes.

### Pricing a catalog one card at a time

Typically: Loops /v1/prices/{id} over every card it holds, one credit each, every night.

Instead: Pages /v1/cards?game=&limit=100, which returns the prices on every card for 2 credits a page. Twenty thousand printings is 400 credits a run, not twenty thousand.

### Ignoring condition and finish

Typically: Takes the first price in the array and calls it the card's price.

Instead: Selects by condition and finish. A near-mint first-edition holo and a played reprint share a name and nothing else.

### Shipping the key to the browser

Typically: Calls the API from a client component with the key inlined at build time.

Instead: Calls from a server route. A key in a JS bundle is a public key, and the first sign of it is usually the bill.

## Prompts

### First integration

A typed client module plus one working card search, wired into the existing stack.

```
Before writing any code, fetch https://tcggraph.com/llms-full.txt and treat it as the source of truth for TCGGraph. Do not guess at endpoints, parameters or field names — if something you need is not in that document, stop and say so instead of inventing it.

Add TCGGraph to this project as the card data source.

1. Detect the language, framework and HTTP conventions already in use here and match them. Do not introduce a new HTTP library if one is already present.
2. Create a single client module that wraps the REST API at https://api.tcggraph.com/v1. Expose three functions to begin with: searchCards, getCard and listGames.
3. Type the responses from the core card fields exactly as the reference lists them: id, game, name, language, printedName, englishId, baseCardId, pricesFrom, set, collectorNumber, rarity, artist, text, images, hashes, prices, printings, gradedPrices, priceStatus, legalities, externalIds and gameData. Finish and the quote timestamp live on each price row (prices[].finish, prices[].updatedAt), not on the card; printings[] is the same rows grouped per physical printing with a label and picture.
4. The list envelope is { data: [...], meta: {...} }. Read pagination from meta and do not assume the array is at the top level.
5. Add one working example: search for a card by name in a chosen game and render the name, set code, collector number and the small image.

Constraints:
- The API key is a server-side secret. Read it from the TCGGRAPH_KEY environment variable and never expose it to the browser. If this project has a client-side component that needs card data, proxy the request through a server route.
- Authenticate with the "Authorization: Bearer $TCGGRAPH_KEY" header.
- An account with no plan attached gets HTTP 402 with an error code of "no_active_plan". Surface that as a clear, actionable message rather than an empty result set.
- Handle 429 by honouring the Retry-After header. Do not retry in a tight loop.
- Keep the integration in one module so the whole surface is easy to review.

When you are done, list every file you touched and show me the one call that proves it works.
```

### EU and US prices side by side

A price panel showing Cardmarket in EUR next to TCGplayer in USD, correctly labelled.

```
Before writing any code, fetch https://tcggraph.com/llms-full.txt and treat it as the source of truth for TCGGraph. Do not guess at endpoints, parameters or field names — if something you need is not in that document, stop and say so instead of inventing it.

Build a price panel for a single card that shows the European and American markets side by side.

1. Read prices from GET /v1/prices/{cardId}. Every card returns every quote it has, each tagged with a source and a region.
2. Show Cardmarket in EUR and TCGplayer in USD as two separate columns. Never convert between them and never add them together — they are different markets with different spreads, and a converted number is a number nobody quoted.
3. Render the currency symbol from the quote's own currency field rather than hardcoding one.
4. Group quotes by condition and finish. A near-mint holo and a lightly-played nonfoil are not the same product.
5. Show the quote timestamp. Stale prices presented as live are the single most common bug in card price UIs.

The currency trap: when you filter or sort by price you must pass source, and the bounds are in that source's own currency. source=cardmarket&minPrice=50 means €50, not $50. The response echoes meta.priceSource — assert on it in a test.

Constraints:
- The API key is a server-side secret. Read it from the TCGGRAPH_KEY environment variable and never expose it to the browser. If this project has a client-side component that needs card data, proxy the request through a server route.
- Authenticate with the "Authorization: Bearer $TCGGRAPH_KEY" header.
- An account with no plan attached gets HTTP 402 with an error code of "no_active_plan". Surface that as a clear, actionable message rather than an empty result set.
- Handle 429 by honouring the Retry-After header. Do not retry in a tight loop.
- Keep the integration in one module so the whole surface is easy to review.
```

### Search with autocomplete

A debounced typeahead that tolerates accents, punctuation and half-typed names.

```
Before writing any code, fetch https://tcggraph.com/llms-full.txt and treat it as the source of truth for TCGGraph. Do not guess at endpoints, parameters or field names — if something you need is not in that document, stop and say so instead of inventing it.

Add a card search box with autocomplete to this project.

1. Call GET /v1/cards?name= for the typeahead. The name filter is a partial match, so "chariz" finds "Charizard ex" — there is no separate search endpoint and you do not need one.
2. Debounce input by about 250ms and cancel the in-flight request when a new keystroke arrives. Every uncancelled request is a credit spent on a result nobody sees.
3. Matching happens against an accent-folded, lowercased form of the name, which is what makes "pokemon" find "Pokémon". Send the raw text and let the server normalise it.
4. Cap results with limit and show the set code and collector number next to each name — card names are not unique across sets, and a bare list of six identical names is useless.
5. Render images.small in the dropdown, with width and height set so the list does not reflow as thumbnails load.
6. Route the request through a server endpoint in this project so the key stays server-side. Cache identical queries briefly.

Constraints:
- The API key is a server-side secret. Read it from the TCGGRAPH_KEY environment variable and never expose it to the browser. If this project has a client-side component that needs card data, proxy the request through a server route.
- Authenticate with the "Authorization: Bearer $TCGGRAPH_KEY" header.
- An account with no plan attached gets HTTP 402 with an error code of "no_active_plan". Surface that as a clear, actionable message rather than an empty result set.
- Handle 429 by honouring the Retry-After header. Do not retry in a tight loop.
- Keep the integration in one module so the whole surface is easy to review.
```

### Nightly catalog sync

A scheduled job that keeps a local copy of the games you sell, with prices refreshed daily.

```
Before writing any code, fetch https://tcggraph.com/llms-full.txt and treat it as the source of truth for TCGGraph. Do not guess at endpoints, parameters or field names — if something you need is not in that document, stop and say so instead of inventing it.

Write a scheduled job that keeps a local copy of the TCGGraph catalog for the games this project uses.

1. Page GET /v1/cards?game=<slug>&limit=100 per game, following meta.hasMore. There is no bulk export and no changed-since filter, so the job re-reads the games it needs in full. A page of 100 costs 2 credits whatever it holds, so size the plan on pages, not cards: 20,000 printings is 200 pages and 400 credits a run.
2. Prices are the part that moves every day, and every card already carries its prices[], gradedPrices[] and priceStatus. One nightly pass therefore refreshes the catalog and the prices together — do not add a second pass over /v1/prices/{id}, which is a charge per card for data the page already returned.
3. Upsert on id, which is stable per printing. Group localized rows with englishId (the English printing they share set and number with) and read pricesFrom to know whether a row's prices are its own or the English twin's. Across printings of the same card, group on game and name.
4. New sets do not need a full pass to be noticed: subscribe to set.published and card.created on a webhook, or poll GET /v1/sets?game=<slug>&releasedAfter=<last run> between runs.
5. Make the job idempotent and safe to re-run. Record the run as complete only after every page landed, so a crash halfway through re-reads rather than skips.
6. Respect the daily credit cap of the plan and 429 Retry-After; a sync that trips the cap at 3am is what the log line for inserted, updated and unchanged rows is there to catch.

Constraints:
- The API key is a server-side secret. Read it from the TCGGRAPH_KEY environment variable and never expose it to the browser. If this project has a client-side component that needs card data, proxy the request through a server route.
- Authenticate with the "Authorization: Bearer $TCGGRAPH_KEY" header.
- An account with no plan attached gets HTTP 402 with an error code of "no_active_plan". Surface that as a clear, actionable message rather than an empty result set.
- Handle 429 by honouring the Retry-After header. Do not retry in a tight loop.
- Keep the integration in one module so the whole surface is easy to review.
```

### Deck builder with legality checks

A deck list that validates against real format rules instead of a hardcoded guess.

```
Before writing any code, fetch https://tcggraph.com/llms-full.txt and treat it as the source of truth for TCGGraph. Do not guess at endpoints, parameters or field names — if something you need is not in that document, stop and say so instead of inventing it.

Add deck building with format legality validation.

1. Read the legalities object on each card. It is a per-format map for that card's game — do not hardcode format names, since they differ per game and change over time.
2. Validate three things separately: whether each card is legal in the chosen format, whether copy limits are respected, and whether the deck size is within the format's bounds.
3. Treat restricted and banned as different states with different messages. "Banned" means remove it; "restricted" usually means one copy.
4. Ban lists change. Store the card id in saved decks and re-validate on load rather than caching a legality verdict.
5. Show why a deck is invalid, per card, not just a single failing badge.

Constraints:
- The API key is a server-side secret. Read it from the TCGGRAPH_KEY environment variable and never expose it to the browser. If this project has a client-side component that needs card data, proxy the request through a server route.
- Authenticate with the "Authorization: Bearer $TCGGRAPH_KEY" header.
- An account with no plan attached gets HTTP 402 with an error code of "no_active_plan". Surface that as a clear, actionable message rather than an empty result set.
- Handle 429 by honouring the Retry-After header. Do not retry in a tight loop.
- Keep the integration in one module so the whole surface is easy to review.
```

### Card images done properly

Fast, correctly-sized card art with no layout shift and no hotlinking surprises.

```
Before writing any code, fetch https://tcggraph.com/llms-full.txt and treat it as the source of truth for TCGGraph. Do not guess at endpoints, parameters or field names — if something you need is not in that document, stop and say so instead of inventing it.

Wire up card images from the TCGGraph CDN.

1. Each card carries an images object with small, normal and large URLs. Pick per context: small for lists, normal for detail views, large for a full-card display.
2. Every URL is served as AVIF with a WebP twin at the same path, so you can offer both in a picture element and let the browser choose.
3. Always set explicit width and height, or an aspect ratio. Trading cards are a consistent 5:7 — without dimensions a grid reflows as every thumbnail lands.
4. Lazy-load everything below the fold, but eagerly load the hero image on a card detail page.
5. Use the card name as alt text, including the set, so the page is navigable without images.
6. If this project uses a framework image component with its own optimizer, configure the TCGGraph CDN hostname as an allowed remote source rather than proxying the bytes yourself.

Constraints:
- The API key is a server-side secret. Read it from the TCGGRAPH_KEY environment variable and never expose it to the browser. If this project has a client-side component that needs card data, proxy the request through a server route.
- Authenticate with the "Authorization: Bearer $TCGGRAPH_KEY" header.
- An account with no plan attached gets HTTP 402 with an error code of "no_active_plan". Surface that as a clear, actionable message rather than an empty result set.
- Handle 429 by honouring the Retry-After header. Do not retry in a tight loop.
- Keep the integration in one module so the whole surface is easy to review.
```

### Webhook consumer

A verified endpoint that reacts to new sets, price moves and ban list changes.

```
Before writing any code, fetch https://tcggraph.com/llms-full.txt and treat it as the source of truth for TCGGraph. Do not guess at endpoints, parameters or field names — if something you need is not in that document, stop and say so instead of inventing it.

Add a TCGGraph webhook receiver to this project.

1. Register the endpoint with POST /v1/webhooks and subscribe only to the events actually used: set.published, card.created, card.updated, card.legality.changed and price.threshold.crossed. Every extra event is work you will do and throw away.
2. Verify the TCGGraph-Signature header (t=<unix seconds>,v1=<hex>, HMAC-SHA256 over "<t>.<raw body>") on every request before parsing the body, and compare digests in constant time. An unverified webhook endpoint is a public write API.
3. Verify against the raw request body. If this framework parses JSON before your handler runs, disable that for this route — a re-serialised body will not match the signature.
4. Respond 2xx immediately and hand the work to a queue. Slow handlers get retried, and retries on a non-idempotent handler cause duplicates.
5. Deduplicate on the payload's top-level id (also sent as the TCGGraph-Event-Id header). At-least-once delivery means you will eventually see the same event twice.
6. Price moves arrive only through price.threshold.crossed, which fires for cards you have put a watch on with POST /v1/watches. There is no per-card "price changed" event; a job that needs every price refreshed re-reads the cards.
7. Log rejected signatures loudly. That is either a misconfiguration or someone probing.

Constraints:
- The API key is a server-side secret. Read it from the TCGGRAPH_KEY environment variable and never expose it to the browser. If this project has a client-side component that needs card data, proxy the request through a server route.
- Authenticate with the "Authorization: Bearer $TCGGRAPH_KEY" header.
- An account with no plan attached gets HTTP 402 with an error code of "no_active_plan". Surface that as a clear, actionable message rather than an empty result set.
- Handle 429 by honouring the Retry-After header. Do not retry in a tight loop.
- Keep the integration in one module so the whole surface is easy to review.
```

### Card scanner from a camera

A live scanning view that identifies cards off the camera feed and adds them to a list.

```
Before writing any code, fetch https://tcggraph.com/llms-full.txt and treat it as the source of truth for TCGGraph. Do not guess at endpoints, parameters or field names — if something you need is not in that document, stop and say so instead of inventing it.

Add card scanning to this project using TCGGraph recognition. Reference: https://tcggraph.com/docs/recognition (plain text at https://tcggraph.com/docs/recognition.md)

1. Two transports exist and they share one response shape. POST /v1/scan for a single image; the WebSocket at wss://api.tcggraph.com/v1/scan for a continuous camera feed. Build the socket path if there is a live camera, the POST path if images already exist.
2. Never put the API key in browser code. Add a server route in this project that POSTs to /v1/scan/tickets with the key and returns the ticket; the browser opens the socket as wss://api.tcggraph.com/v1/scan?ticket=TICKET. Tickets are single-use and expire in sixty seconds, so mint one per connection.
3. Reconnect on close. The connection is bounded by a function duration, so it will end while the camera is still running — reconnect with backoff, mint a fresh ticket, resend the config frame. Reconnecting is never billed.
4. Send one JSON config frame on open — {"type":"config","games":["pokemon"],"minConfidence":0.9}, both fields optional — and wait for the {"type":"ready"} reply. Then push JPEG frames as binary — 1280 pixels across, quality 70. Keep exactly one frame in flight: send the next when the reply to the last arrives (match, unresolved or error). A frame sent while another is still being processed replaces it and is never answered, so a client that queues frames will see replies go missing.
5. Replies carry the seq of the frame they answer. Binary frames are numbered by the server in the order received; send {"type":"frame","image":"<base64>","seq":n} instead if the client needs to choose the number. Key the UI on seq.
6. Handle unresolved frames as a normal outcome, not an error. They carry a box and corners, a reason — blurred, glare, cropped, occluded, ambiguous, not_in_catalog — a detail with the measurement behind it, bestDistance in bits, and how many candidates remained, but not which: identification only arrives on a billed match. Show the reason and detail to the person holding the card. These frames are billed zero.
7. Check matches[].printingResolved and matches[].finishResolved before writing to inventory. printingResolved true means the set, collector number and language on matches[].card are the matched ones — the artwork was unique or the line printed on the card was read and settled it. False means the card is certain and the record is not: the candidates are in matches[].alternatives, each with name, set, collectorNumber, language, rarity, images and printings. finishResolved is true only when the record has exactly one entry in printings; the finish (normal, reverse-holo, foil, etched, 1st-edition) is never read from the photo. When either is false, build the options as [card, ...alternatives] crossed with each one's printings, and pick using context you have or ask the operator; store the cardId and the printing key. Do not silently store the first one. Keep the card at least about 400 pixels wide in the frame so the number can be read.
8. Draw the overlay from matches[].corners — four points, normalised 0-1 against the frame you sent, clockwise from the card's top-left — as a polygon; fall back to matches[].box when corners is null. Any rotation and perspective are handled server-side, so do not ask the user to square the card up.
9. Prices are already on matches[].card.prices. Do not make a second call to price a card you just scanned — that is a second charge for data you already have.

Metering: one matched card is one scan, a frame is one card, and scans are a separate meter from data credits. Do not retry a scan on a low-confidence result in a loop; raise or lower minConfidence deliberately instead.

Constraints:
- The API key is a server-side secret. Read it from the TCGGRAPH_KEY environment variable and never expose it to the browser. If this project has a client-side component that needs card data, proxy the request through a server route.
- Authenticate with the "Authorization: Bearer $TCGGRAPH_KEY" header.
- An account with no plan attached gets HTTP 402 with an error code of "no_active_plan". Surface that as a clear, actionable message rather than an empty result set.
- Handle 429 by honouring the Retry-After header. Do not retry in a tight loop.
- Keep the integration in one module so the whole surface is easy to review.
```

## Questions

**Do I need an API key before an agent can write the integration?**

No. An agent can write and review the whole integration against the published reference without ever making a call. You need a key with a plan attached before it returns data — until then every endpoint answers 402 no_active_plan, which the prompts here tell the agent to handle explicitly.

**Why point the agent at llms-full.txt instead of the docs?**

It is the same content with the navigation, markup and styling stripped out. That means far fewer tokens, no risk of the model reading a code sample out of its surrounding caveat, and nothing that looks like an instruction to the model but was meant for a human. Every page also has a plain-text twin at <path>.md if you only need one.

**Which file should the rules go in?**

AGENTS.md is the most portable — Codex reads it and a growing number of other agents do too. Claude Code reads CLAUDE.md, and Cursor reads .cursor/rules/*.mdc. The content is identical in all three, so if you use more than one tool, put the real file in AGENTS.md and have the others reference it in a single line.

**Will these prompts work with a local or open-weights model?**

The prompts are plain text with no tool-specific syntax, so yes. A smaller model is more likely to drift from the reference, so keep the rules file in context rather than relying on it having fetched the document once, and review the generated client by hand.

**Can I use these commercially?**

Yes. The prompts and the rules file are yours to copy, edit and ship. No attribution required.

---

Canonical page: https://tcggraph.com/vibecode
Full machine-readable reference: https://tcggraph.com/llms-full.txt
