# ThrumFeed Database API v1 — Guide for developers and AI assistants

> Private, server-to-server API that returns a track's identity, its SongSeed, and its best available Suno V6 prompt with ten descriptors: the full **Pro analysis** when one has already been run, otherwise the quick **API Prompt**.

## Two ways to use ThrumFeed Database
| Way | For | Sign-in |
|---|---|---|
| **REST API** (this guide, below) | Your own server or app (such as the Club) that needs a track's API Prompt and SongSeed | API key (`Authorization: Bearer tfk_…`) issued by the owner |
| **ChatGPT connector (MCP)** (see the last section) | The owner talking to ChatGPT: search, add songs, run Pro analyses, read results | Owner sign-in (OAuth), no key |

## Quick start (REST API) in 4 steps
1. **Get a key.** The owner creates one on the *API Keys* page of the app (keys are shown once; copy it then). Store it as a server secret named `THRUMFEED_API_KEY`.
2. **Find the Spotify track ID** (22 letters/digits): in Spotify choose *Share → Copy Song Link*; the ID is the part after `/track/`.
3. **Look it up (read-only):**
```bash
curl -H "Authorization: Bearer $THRUMFEED_API_KEY" \
  https://strumfeed.com/api/public/v1/tracks/by-spotify/<spotifyTrackId>
```
4. **Read the result.** If `status` is `ready`, use `interpretations.api_prompt.suno_v6_prompt`. If it is `not_found` or `not_analyzed`, call the `POST …/analyze` endpoint described below.

## Rules an AI assistant must follow
1. **Never put the API key in browser code**, a mobile app, a URL, a query string, git, or logs. Call the API only from a server (backend route, server function, edge/worker). Store the key as a server environment secret, e.g. `THRUMFEED_API_KEY`.
2. **GET lookups are read-only**: they never start an analysis or change data. Only `POST /tracks/by-spotify/{id}/analyze` adds a missing track and generates a missing API Prompt.
3. Treat a **SongSeed as a human-readable memory clue, not an ID**. Always use `tfid` as the permanent identifier. Seeds can change (improve) over time.
4. GET for lookups, POST only for `/analyze`. Never send a request body. No CORS: browsers cannot call this API directly.

## Base URL
`https://strumfeed.com/api/public/v1`

The earlier `https://tfdbv2.lovable.app` address still works but only redirects here; call `https://strumfeed.com` directly.

## Authentication
Send the key in the Authorization header:
```
Authorization: Bearer tfk_<12 characters>_<43 characters>
```
Keys are issued and revoked by the owner. Every key problem (missing, wrong, expired, revoked) returns the same `401 {"error":"unauthorized"}`.

## Endpoints
| Method | Path | Use |
|---|---|---|
| GET | `/tracks/{tfid}` | Look up by ThrumFeed ID (UUID) |
| GET | `/tracks/by-spotify/{spotifyTrackId}` | Look up by Spotify track ID (22 letters/digits) |
| POST | `/tracks/by-spotify/{spotifyTrackId}/analyze` | Lookup-or-generate: returns the saved Pro analysis or API Prompt; if neither exists, adds the track (from Spotify) and generates the API Prompt in one grounded research step. It never starts a Pro analysis |

## Getting a track that has no API Prompt yet
1. `GET /tracks/by-spotify/{id}`. If `status` is `ready`, use it.
2. Otherwise (`not_found` or `not_analyzed`), call `POST /tracks/by-spotify/{id}/analyze` from your server **with a timeout of at least 120 seconds**. The request stays open while the API Prompt is generated (one Gemini step with Google Search; if search is not proven it retries once), then returns the same `200 ready` body as GET. Calling it for a track that is already `ready` (saved Pro analysis or API Prompt) returns the saved result with no new run.
3. If it returns `202` with body `{"api_version":"1","status":"pending","request_id":"…","tfid":"…","retry_after_seconds":30}` (header `Retry-After: 30`), a generation for that track started in the last 3 minutes and is still running. Wait 30 seconds and re-check with GET until `ready`. Do not start a second POST meanwhile.
4. On `502 analysis_failed` / `502 intake_failed` / `503 analysis_unavailable` (body `{"error":"…","request_id":"…","retryable":true}`, header `Retry-After: 60`), retry later with backoff (at least 60 s); do not loop.
5. If POST returns `404 not_found`, Spotify does not know that track ID.

Lookup by ISRC or by SongSeed is not available in v1.

## Response statuses
| HTTP | `status` | Meaning | What your code should do |
|---|---|---|---|
| 200 | `ready` | A prompt (Pro or API Prompt) and SongSeed available | Use `interpretations.api_prompt` and `track.song_seed` |
| 200 | `not_analyzed` | Track exists, no Pro analysis or API Prompt yet | Call POST analyze; seed is still included when possible |
| 200 | `data_incomplete` | Track is missing artist or title, so no seed | Show "catalog data incomplete" |
| 400 | — `invalid_identifier` | Bad TFID or Spotify ID format | Fix the input |
| 401 | — `unauthorized` | Key problem | Check the server secret; do not retry in a loop |
| 404 | `not_found` | GET: track not in database. POST: Spotify does not know this ID | GET: call POST analyze. POST: show "not found" |
| 409 | `ambiguous` | Spotify ID matches several tracks | Let a person pick from `candidates` (TFIDs) |
| 429 | — `rate_limited` | Too many requests | Wait `Retry-After` seconds |
| 202 | `pending` | (POST analyze) A generation for this track is already in progress | Re-check with GET after `retry_after_seconds` (30) |
| 502 | — `analysis_failed` / `intake_failed` | (POST analyze) API Prompt generation or Spotify intake failed | Retry later with backoff |
| 503 | — `analysis_unavailable` | (POST analyze) API Prompt generation is not configured right now | Retry later |
| 413 | — `body_not_allowed` | A request body was sent | Send no body |
| 414 | — `uri_too_long` | URL longer than 512 characters | Fix the URL |
| 500 | — `internal` | Server error | Retry later with backoff |

Limits: 60 requests/minute and 5,000/day per key (POST counts like GET). After 30 failed key attempts from one address within 10 minutes, that address gets `429` until the window passes.

## Example ready response
```json
{
  "api_version": "1",
  "status": "ready",
  "request_id": "6f1c…",
  "data_quality": [],
  "track": {
    "tfid": "00000000-0000-4000-8000-000000000000",
    "title": "Example Title",
    "artists": [{ "name": "Example Artist", "role": "primary" }],
    "identifiers": { "spotify_track": "0123456789abcdefghijkl", "isrc": ["XX0000000001"] },
    "song_seed": {
      "seed_version": "sg1",
      "display_seed": "sg1-exa-co-st-exle-02-92",
      "provider_type": "spotify_id",
      "collision_risk": "low",
      "origin": "stored",
      "created_at": "2026-01-01T00:00:00Z"
    }
  },
  "interpretations": {
    "pro_text": null,
    "api_prompt": {
      "source": "api_prompt",
      "revision": 1,
      "evidence_method": "text_research_no_direct_listening",
      "descriptors": ["d1","d2","d3","d4","d5","d6","d7","d8","d9","d10"],
      "suno_v6_prompt": "…up to 950 characters…",
      "exclusions": "…or null…",
      "confidence_note": "…or null…",
      "created_at": "2026-01-02T00:00:00Z"
    },
    "audio": null
  }
}
```
Fields not listed here are never returned.

## The API Prompt
- `interpretations.api_prompt` is the prompt to use. `status: ready` means it exists. Its `source` says where it came from:
  - `"pro"`: the track already has a full Pro analysis (the longer, two-step study). It is always preferred when it exists. `exclusions` and `confidence_note` are `null` for Pro.
  - `"api_prompt"`: no Pro analysis exists, so the quick single-pass API Prompt is served.
- Shape: `source`, `revision`, `evidence_method`, `descriptors` (10), `suno_v6_prompt` (max 950), `exclusions` (string or null), `confidence_note` (string or null), `created_at`.
- `interpretations.pro_text` holds the Pro result when one exists (same prompt and descriptors), otherwise `null`. Reading `api_prompt` is enough.
- `POST /analyze` only ever generates the quick API Prompt, and only when the track has neither. Pro analyses are started by the owner, never by this API.
- Text research only: the song is not listened to.

## SongSeed retrieval
- Every `ready` response always includes `track.song_seed`.
- `display_seed` format: `sg1-AAA-GG-ZZ-T-NN-YY`
  - `AAA` first 3 letters of the primary artist
  - `GG` first 2 letters of the genre, or `xx` if unknown
  - `ZZ` last 2 letters of the artist name
  - `T` title signature, **variable length (1–4 characters), not always 4**:
    - one meaningful word of 3 letters or fewer → the word itself (1–3 chars)
    - one longer word → its first 3 letters + last letter (4 chars)
    - two or more words → first 2 letters of word 1 + first letter of word 2 + last letter of the last word (usually 4 chars; shorter when word 1 is a single letter)
    - Real example: "I Cross My Heart - From "Pure Country" Soundtrack" → `sg1-geo-so-it-ick-08-92` (3-character signature `ick`).
  - `NN` meaningful title word count (2 digits)
  - `YY` last 2 digits of the release year, or `xx` if unknown
- `xx` placeholders are normal and valid.
- `origin: "stored"` = the saved seed (`created_at` set). `origin: "derived"` = computed on the fly because none was saved (`created_at` is null, and `data_quality` contains `song_seed_derived`). A derived seed may later be replaced by an improved stored seed.
- `collision_risk`: low / medium / high — how likely another song shares this seed.
- To get the seed: call either endpoint and read `track.song_seed.display_seed`.

## data_quality flags
`song_seed_missing`, `song_seed_derived`, `song_seed_invalid`, `song_seed_unavailable`. They are informational; rely on `status`.

## Example server code (Node/TypeScript)
```ts
// Runs on the server only. THRUMFEED_API_KEY is a server secret.
// THRUMFEED_API_BASE = https://strumfeed.com/api/public/v1
const base = process.env.THRUMFEED_API_BASE!;
const auth = { Authorization: `Bearer ${process.env.THRUMFEED_API_KEY}` };

/** Returns the API Prompt + SongSeed for a Spotify track, generating the prompt if needed. */
export async function getApiPrompt(spotifyId: string) {
  const path = `${base}/tracks/by-spotify/${encodeURIComponent(spotifyId)}`;
  let res = await fetch(path, { headers: auth });                       // read-only lookup
  let body = await res.json();
  if (res.status === 401) throw new Error("ThrumFeed API key rejected");
  if (body.status !== "ready" && (res.status === 404 || body.status === "not_analyzed")) {
    res = await fetch(`${path}/analyze`, { method: "POST", headers: auth, signal: AbortSignal.timeout(120_000) });
    body = await res.json();
    if (res.status === 202) return { pending: true, retryAfter: body.retry_after_seconds }; // re-check with GET later
    if (res.status >= 500) throw new Error(`Retry later (${body.error})`);
  }
  if (body.status !== "ready") return { status: body.status };          // not_found | ambiguous | data_incomplete
  const p = body.interpretations.api_prompt;
  return {
    tfid: body.track.tfid,
    songSeed: body.track.song_seed.display_seed,
    prompt: p.suno_v6_prompt,
    source: p.source,                // "pro" (preferred) or "api_prompt"
    exclusions: p.exclusions,        // string or null
    descriptors: p.descriptors,      // 10 strings
    confidence: p.confidence_note,   // string or null
  };
}
```

## curl
```bash
# Read-only lookup
curl -H "Authorization: Bearer $THRUMFEED_API_KEY" \
  https://strumfeed.com/api/public/v1/tracks/by-spotify/<spotifyTrackId>

# Lookup-or-generate (no body)
curl -X POST --max-time 120 -H "Authorization: Bearer $THRUMFEED_API_KEY" \
  https://strumfeed.com/api/public/v1/tracks/by-spotify/<spotifyTrackId>/analyze
```

## Connecting ChatGPT (MCP connector)
The owner can connect ChatGPT directly, with no API key. The connector signs in as the owner and only works for the owner.

**Setup (ChatGPT, once):** Settings → Connectors → Advanced → turn on *Developer mode* → *Create* a connector (availability depends on your ChatGPT plan). Use the server URL `https://strumfeed.com/mcp`, choose OAuth, then sign in to ThrumFeed Database and approve access.

**Tools it offers**
| Tool | What it does |
|---|---|
| `find` | Search the catalog by text, or look up by TFID, ISRC or Spotify track ID. Always used before adding. |
| `spotify_lookup` | Search Spotify for tracks and albums (adds nothing). |
| `add_to_catalog` | Add a track or album through the normal Spotify intake. Adds by artist+title only when Spotify has exactly one exact match; otherwise it returns candidates and asks you to choose. |
| `get_album` | Album details, tracklist and per-track Pro status. |
| `start_pro` | Start a full Pro analysis for one track (works for standalone singles) or the missing tracks of an album. Paid, text research only. Returns immediately; the run takes several minutes in the background. |
| `pro_study` | Check progress (`none / queued / running / done / failed`) and read the finished prompt, report, run history or diagnostics. |
| `label_catalog` | Read and edit the label's managed distribution data; the ISRC ledger is read-only. |

**Example requests:** "Find *Tim McGraw* by Taylor Swift in ThrumFeed; add it if missing, then start a Pro analysis." Then later: "How is that analysis going? Show me the Pro prompt."

**Safety:** ISRC assignment, bulk import and deletes are not available over the connector. Starting an analysis never duplicates an existing result or a run already in progress. The connector never exposes keys, secrets or system prompts.

## Plain-text version
This same guide is available as raw Markdown at `https://strumfeed.com/api-docs.md` for AI tools, and as a web page at `https://strumfeed.com/api-docs`. Both come from one source and always match.
