# SERPrecon API and MCP server: reference for AI agents

SERPrecon analyzes how well a web page matches a search query compared with the pages that rank for it. A **report** pairs one query with one page URL. Each **run** of a report fetches the search results (or uses results you send), scores your page and the ranking pages, and returns a SERPrecon score (0–100), metrics against the ranking average, your rank, and a prioritized action plan.

- REST API base URL: `https://api.serprecon.com/v1`
- MCP server: `https://api.serprecon.com/mcp` (Streamable HTTP)
- This file: `https://api.serprecon.com/docs/api.md` (also at `/llms.txt`)
- Human docs: https://www.serprecon.com/api, and in the app under Account → API Docs

## Essentials

- **Auth:** every request needs `Authorization: Bearer <key>`. Keys start with `sr_live_` (production) or `sr_test_` (staging). Users create them at https://app.serprecon.com/account/api-keys. Never put a key in browser code or a public repo.
- **Cost:** 1 credit per run, charged when the run starts. Failures on SERPrecon's side are refunded (see failure codes).
- **Runs are asynchronous.** Creating a report or a re-run returns `202` with a `run_id` immediately; the run takes about 2 minutes. Poll `GET /v1/runs/{run_id}` (honor the `Retry-After` header) or fetch it any time later. Finished runs are kept.
- **Limits:** up to 5 runs queued or running per account (more returns `429 too_many_active_runs`). An account's runs execute **one at a time**, so 5 queued runs take about 10 minutes in total. Up to 300 requests per minute per key (`429 rate_limited`).
- **Search engines:** `google` (default), `bing`, `chatgpt`. For `chatgpt`, SERPrecon asks ChatGPT the query and compares your page with the pages its answer cites (usually 3–5); answers vary between runs and `device` is ignored.
- **IDs** are UUIDs. A run keeps the same `run_id` from queued to complete.
- **JSON everywhere.** Errors always look like `{"error": {"code": "invalid_url", "message": "..."}}`. Branch on `error.code`.

## Typical workflow

1. `GET /v1/account` — check `credits.available` before starting many runs.
2. `GET /v1/reports?query=...&url=...` — if a report for this query and page already exists, re-run it (`POST /v1/reports/{id}/runs`) instead of creating a duplicate.
3. Otherwise `POST /v1/reports` with `query`, `url` and optional `search_engine` / `locale`. Use `GET /v1/locations?q=...` to get a valid `locale.location`.
4. Send an `Idempotency-Key` header on POSTs so a retried request never queues (or charges) twice.
5. Poll `GET /v1/runs/{run_id}` until `status` is `complete` or `failed`, waiting `Retry-After` seconds (15) between polls. Or queue several and collect them later.
6. Use `summary`, `rank` and `actions` from the completed run. `app_url` opens the full report in the SERPrecon app.

## Endpoints

### POST /v1/reports — create a report and queue its first run

Request body:

| Field | Type | Notes |
|---|---|---|
| `query` | string, required | The search query, up to 300 characters. |
| `url` | string, required | Full http(s) URL of the page to analyze. |
| `search_engine` | string | `google` (default), `bing` or `chatgpt`. |
| `locale.location` | string | Exact name from `GET /v1/locations`, e.g. `"Austin,Texas,United States"`. |
| `locale.country` | string | Two-letter code, used when no `location` is given. Default `us`. |
| `locale.language` | string | `en` (default), `es`, `fr`, `de`, `it`, `pt`, `ru`, `ja`, `ko`, `zh` (Simplified), `zh-TW` (Traditional). |
| `locale.device` | string | `desktop` (default) or `mobile`. Ignored for `chatgpt`. |
| `project_id` | string | Project to put the report in. Default: the user's project for the URL's domain, created (named after the domain) if none exists. |
| `serp` | object | Optional: search results you captured yourself; see "Supplied search results". SERPrecon then skips fetching results. |
| `webhook_url` | string | Optional https URL. Stored, but webhooks are not sent yet; poll instead. |

Headers: `Idempotency-Key: <any unique string, up to 200 chars>` (recommended). Repeating a request with the same key within 24 hours returns the original run (status `202`, header `Idempotent-Replayed: true`, `credits_remaining: null`) without charging again.

Response `202`:

```json
{
  "report_id": "f3b2c9d8-1e4a-4b6f-8c2d-9a0e7b5c3d21",
  "run_id": "7c1f6a52-3d0e-4f7a-9a51-2f0e8d1c4b77",
  "status": "queued",
  "estimated_seconds": 120,
  "credits_used": 1,
  "credits_remaining": 295,
  "app_url": "https://app.serprecon.com/project/example.com/f3b2c9d8-..."
}
```

`estimated_seconds` grows with the number of runs already queued for the account. Until the first run starts, the report is visible through the API (`is_running: true`) but not yet in the SERPrecon app.

### POST /v1/reports/{report_id}/runs — re-run a report

Body (all optional): `serp` (supplied results; must be from the report's own search engine), `webhook_url`. Same headers and `202` response as creating a report. Re-runs always use the report's stored query, URL, engine and locale. `409 run_in_progress` if the report is already running.

### GET /v1/reports — list or find reports

Query parameters (all optional): `query` (exact match, case-insensitive), `url` (matches with or without `www` and a trailing slash), `project_id`, `limit` (1–200, default 50), `cursor` (the previous response's `next_cursor`). Newest first.

```json
{
  "data": [
    {
      "id": "f3b2c9d8-...",
      "query": "geo share of voice tool",
      "url": "https://www.example.com/",
      "project": { "id": "a1b2...", "name": "example.com" },
      "search_engine": "google",
      "locale": { "device": "desktop", "language": "en", "location": "Austin,Texas,United States" },
      "schedule": "once",
      "created_at": "2026-10-14T15:02:11.000Z",
      "last_run_at": "2026-11-11T15:04:20.000Z",
      "is_running": false,
      "latest_score": 72,
      "latest_run_id": "7c1f6a52-...",
      "app_url": "https://app.serprecon.com/project/example.com/f3b2c9d8-..."
    }
  ],
  "next_cursor": null
}
```

`latest_run_id` points to a queued or running run when one is in progress, otherwise the most recent completed run.

### GET /v1/reports/{report_id}

One report object (same shape as above). `404 not_found` if it doesn't exist or belongs to another account.

### DELETE /v1/reports/{report_id}

Deletes the report and all its runs. Permanent. `409 run_in_progress` while it's running. Response: `{"id": "...", "deleted": true}`.

### GET /v1/reports/{report_id}/runs — run history

Newest first, including runs started in the SERPrecon app.

```json
{
  "data": [
    { "run_id": "7c1f6a52-...", "status": "complete", "created_at": "2026-11-11T15:02:11.000Z", "serprecon_score": 72, "rank": 7, "source": "dataforseo:google" }
  ]
}
```

`rank` here only covers the top 10 (`null` = outside the top 10, or not recorded). Fetch the run for its exact rank and details.

### GET /v1/runs/{run_id} — status and results

While `queued` or `running`, the response carries `Retry-After: 15`. Fields on every run: `run_id`, `report_id`, `status` (`queued` | `running` | `complete` | `failed`), `created_at`, `started_at`, `completed_at`, `source`, `query`, `url`, `app_url`.

A completed run adds:

```json
{
  "rank": 7,
  "summary": {
    "serprecon_score": 72,
    "serp_avg_score": 80.5,
    "intent": { "query": "commercial", "page": "informational", "matches": false },
    "metrics": {
      "semantic_similarity": { "you": 0.81, "serp_avg": 0.84 },
      "keyword_match": { "you": 11.2, "serp_avg": 13.9 },
      "title_keyword_match": { "you": 4.1, "serp_avg": 5.3 },
      "trigram": { "you": 0.32, "serp_avg": 0.38 },
      "word_count": { "you": 1450, "serp_avg": 2210 },
      "authority": { "you": 40, "serp_avg": 55 }
    },
    "keywords_to_consider": ["share of voice", "AI visibility", "citations"]
  },
  "actions": [
    {
      "id": 1,
      "type": "fix",
      "severity": "high",
      "area": "intent",
      "metric": "intent",
      "issue": "The page doesn't match the query's commercial intent",
      "why_it_matters": "Most ranking pages are product pages...",
      "fix": "Add pricing, a demo call to action and a feature comparison.",
      "example": "Pricing from $49/month · Book a demo · Compare plans",
      "examples": [],
      "done": false
    }
  ],
  "top_results": [
    { "position": 1, "url": "https://optimizegeo.ai/...", "title": "...", "serprecon_score": 88 }
  ]
}
```

- `rank`: your page's position in this run's results, or `null` if it isn't in them.
- `summary.intent.query` is the dominant intent of the ranking pages; `page` is your page's intent.
- Metrics: `semantic_similarity` and `trigram` are 0–1; the others are raw values. `serp_avg` is the average across the ranking pages. Higher is better except where noted in the action plan.
- `actions` are in plan order. `type` is `fix` (a gap to close) or `stay_ahead` (already on track; keep the lead). `severity`: `high` | `medium` | `low`. `area`: `intent` | `content` | `authority`. `metric` names match `summary.metrics` (plus `intent`, `keywords_to_consider`, `topical_coherence`, `title_body_alignment`, `commodity`, `spam_score`, `page_speed`). `done` is true once the user ticked it off in the app. Runs from before the current action-plan format have `type`, `severity`, `area` and `metric` set to `null` and their examples in `examples`.
- `top_results` lists every listing in the engine's order (a URL that ranks twice appears twice), each with its own SERPrecon score.
- Runs made from supplied results add `"captured": {"note": "Results captured from your browser", "captured_at": "...", "parser_version": "..."}`.

A failed run adds `failure_code`, `failure_reason` and `credits_refunded`:

| `failure_code` | Meaning | Credit refunded |
|---|---|---|
| `serp_fetch_failed` | Search results couldn't be fetched. | yes |
| `scoring_failed` | The pages in the results couldn't be analyzed. | yes |
| `insufficient_credits` / `subscription_inactive` | No credits or no active subscription when the run started. | not charged |
| `invalid_job` | The run was missing data. | not charged |
| `run_failed` | Something broke partway through. | no |
| `timeout` | The run took too long and was stopped. | no |

A first run that fails with `scoring_failed` removes its report, so that `report_id` then returns `404`.

### GET /v1/runs — the account's runs

`?status=active` (queued or running), or `queued`, `running`, `complete`, `failed`; omit for all. Returns the last 100 API runs, newest first:

```json
{
  "data": [
    { "run_id": "...", "report_id": "...", "status": "running", "query": "...", "url": "...", "source": "dataforseo:google", "created_at": "...", "started_at": "...", "completed_at": null }
  ]
}
```

Only runs created through the API (including the Chrome extension) are listed; runs started in the app appear in a report's run history.

### GET /v1/account

```json
{
  "user_id": "...",
  "name": "...",
  "plan": { "name": "Pro" },
  "subscription_status": "active",
  "credits": { "available": 296, "reserved": 0, "breakdown": { "trial": 0, "plan": 296, "gifted": 0 } },
  "limits": { "max_active_runs": 5, "active_runs": 0, "credits_per_run": 1 }
}
```

`reserved` is the number of queued runs that will be charged when they start. A new run needs `available - active_runs >= 1`.

### GET /v1/locations

`?q=` (at least 2 characters, required), `country` (two-letter filter), `limit` (1–100, default 20).

```json
{ "data": [ { "location": "Austin,Texas,United States", "label": "Austin, Texas, United States", "type": "City", "country": "us" } ] }
```

Pass `location` exactly as returned.

## Run sources

`source` says where a run's results came from: `dataforseo:google`, `dataforseo:bing`, `openai:chatgpt`, or `extension:google` / `extension:bing` for supplied results. Runs are only compared with runs from the same source.

## Supplied search results (`serp`)

Instead of letting SERPrecon fetch results, send the results you captured (this is what the SERPrecon Chrome extension does). Allowed on create and re-run; a re-run must send results from the report's own engine.

```json
{
  "engine": "google",
  "captured_at": "2026-11-11T15:02:11Z",
  "page_url": "https://www.google.com/search?q=geo+tool&gl=us&hl=en",
  "locale": { "domain": "google.com", "gl": "us", "hl": "en", "device": "desktop" },
  "parser_version": "my-scraper-1.0",
  "organic": [
    { "position": 1, "url": "https://optimizegeo.ai/blog/geo", "title": "...", "snippet": "..." },
    { "position": 2, "url": "https://www.example.com/", "title": "..." }
  ],
  "features": {
    "ai_overview": { "text": "...", "sources": [{ "url": "https://...", "title": "..." }] },
    "featured_snippet": { "url": "https://...", "title": "...", "text": "..." },
    "people_also_ask": ["What is AI share of voice?"],
    "related_searches": ["geo tools"],
    "videos": [{ "url": "https://...", "title": "..." }],
    "local_pack": [{ "name": "...", "url": "https://..." }],
    "knowledge_panel": { "title": "..." },
    "ads": { "top": 2, "bottom": 1 }
  }
}
```

Rules (violations return `400 invalid_serp`):

- `engine`: `google` or `bing`; `locale.domain` like `google.com` / `google.co.uk` or `bing.com`.
- `organic`: 1–20 results; `position` a whole number 1–100; `url` http(s). Keep every listing in the engine's order, **including a URL that appears twice**.
- Text is trimmed: titles to 500 characters, snippets 2,000, AI Overview text 20,000. Feature lists keep up to 30 items. `features` and all its keys are optional. `ads` may be counts (`{top, bottom}`) or a list of `{url, title, position: "top"|"bottom"}`.
- `locale.gl` / `hl` set the report's country and language; scheduled or later fetched runs use a location for that country.

## Errors

| HTTP | `error.code` | Meaning |
|---|---|---|
| 400 | `invalid_query`, `invalid_url`, `invalid_locale`, `invalid_engine`, `invalid_serp`, `invalid_json`, `invalid_webhook_url`, `invalid_idempotency_key`, `invalid_status` | Fix the request; `message` says what's wrong. |
| 401 | `unauthorized` | Missing, wrong, expired or revoked key. |
| 402 | `insufficient_credits`, `subscription_inactive` | Out of credits (queued runs count) or no active subscription. |
| 404 | `not_found` | No such report, run or endpoint for this account. |
| 409 | `run_in_progress` | The report is already running. |
| 429 | `too_many_active_runs`, `rate_limited` | Wait `Retry-After` seconds, then retry. |
| 500 | `internal_error` | Retry later; contact support if it persists. |

## MCP server

`https://api.serprecon.com/mcp` — Streamable HTTP, stateless (JSON responses; no sessions or SSE stream). Authenticate with the same API key as an `Authorization: Bearer` header. Same data, credits and limits as the REST API.

Connect:

```bash
# Claude Code
claude mcp add --transport http serprecon https://api.serprecon.com/mcp \
  --header "Authorization: Bearer sr_live_..."
```

```json
// Cursor: ~/.cursor/mcp.json
{ "mcpServers": { "serprecon": { "url": "https://api.serprecon.com/mcp", "headers": { "Authorization": "Bearer sr_live_..." } } } }
```

```json
// Claude Desktop: claude_desktop_config.json (needs Node.js)
{ "mcpServers": { "serprecon": { "command": "npx", "args": ["mcp-remote", "https://api.serprecon.com/mcp", "--header", "Authorization:${SERPRECON_AUTH}"], "env": { "SERPRECON_AUTH": "Bearer sr_live_..." } } } }
```

Tools (results are JSON text; errors come back with `isError: true` and the same `{"error": {...}}` body):

| Tool | Arguments | Does |
|---|---|---|
| `create_report` | `query`, `url`, optional `search_engine`, `location`, `country`, `language`, `device`, `project_id` | Creates a report and queues its first run (1 credit). Returns `run_id`. |
| `rerun_report` | `report_id` | Queues a new run with fresh results (1 credit). |
| `wait_for_run` | `run_id`, optional `timeout_seconds` (1–50, default 50) | Waits for the run, then returns it. Call again while `status` is `queued` or `running`. |
| `get_run` | `run_id` | The run, as `GET /v1/runs/{id}`. |
| `list_reports` | optional `query`, `url`, `project_id`, `limit`, `cursor` | As `GET /v1/reports`. |
| `get_report` | `report_id` | As `GET /v1/reports/{id}`. |
| `list_report_runs` | `report_id` | As `GET /v1/reports/{id}/runs`. |
| `list_active_runs` | none | Runs queued or running now. |
| `delete_report` | `report_id` | Permanently deletes a report. Only when the user explicitly asks. |
| `get_account` | none | Credits, plan and limits. |
| `find_locations` | `q`, optional `country`, `limit` | Valid `location` names. |

Recommended agent workflow: `list_reports` (query + url) → `rerun_report` if it exists, else `create_report` → `wait_for_run` (repeat until done; a run takes about 2 minutes) → summarize the score, rank and top `actions` for the user, and share `app_url`. Check `get_account` before starting many runs.

## Recipes

Create a report and wait for it (Python):

```python
import os, time, uuid, requests

API = "https://api.serprecon.com/v1"
H = {"Authorization": f"Bearer {os.environ['SERPRECON_API_KEY']}"}

res = requests.post(f"{API}/reports", headers={**H, "Idempotency-Key": str(uuid.uuid4())},
                    json={"query": "geo share of voice tool", "url": "https://www.example.com/"})
res.raise_for_status()
run_id = res.json()["run_id"]

while True:
    r = requests.get(f"{API}/runs/{run_id}", headers=H)
    run = r.json()
    if run["status"] in ("complete", "failed"):
        break
    time.sleep(int(r.headers.get("Retry-After", 15)))

if run["status"] == "complete":
    print(run["summary"]["serprecon_score"], run["rank"])
    for a in run["actions"]:
        print(a["severity"], a["issue"], "->", a["fix"])
else:
    print(run["failure_code"], run["failure_reason"])
```

Queue several reports, collect later (JavaScript, Node 18+):

```js
const API = "https://api.serprecon.com/v1";
const headers = { Authorization: `Bearer ${process.env.SERPRECON_API_KEY}`, "Content-Type": "application/json" };

const runIds = [];
for (const [query, url] of [["geo tool", "https://www.example.com/geo"], ["ai visibility", "https://www.example.com/ai"]]) {
  let res;
  while (true) {
    res = await fetch(`${API}/reports`, { method: "POST", headers, body: JSON.stringify({ query, url }) });
    if (res.status !== 429) break; // 5 runs already active: wait and retry
    await new Promise((r) => setTimeout(r, Number(res.headers.get("Retry-After") || 30) * 1000));
  }
  runIds.push((await res.json()).run_id);
}
// later:
for (const id of runIds) {
  const run = await (await fetch(`${API}/runs/${id}`, { headers })).json();
  console.log(run.query, run.status, run.summary?.serprecon_score);
}
```

Track a page over time: find the report (`GET /v1/reports?query=&url=`), re-run it on your schedule (`POST /v1/reports/{id}/runs`), and read `GET /v1/reports/{id}/runs` for the score and rank history.

## Gotchas

- Don't create a new report for a query and page that already has one; re-run it, or the user's account fills with duplicates.
- Always send `Idempotency-Key` on POSTs, and reuse it when retrying the same request.
- 5 queued runs take about 10 minutes, not 2: an account's runs execute one at a time.
- `rank` in run history is top-10 only; the run itself has the exact rank.
- `schedule` is always `"once"` for API-created reports; scheduling isn't available through the API yet.
- `webhook_url` is accepted and stored, but no webhooks are sent yet.
- There's no endpoint to mark actions done; `done` reflects the SERPrecon app.
