# Workflow examples

> Draft

How to choose between the three ways to get results, plus two complete recipes.

## Choosing an approach

| You’re building | Use | Endpoint |
| --- | --- | --- |
| A script, CLI tool or batch job | Direct requests | [Citation lookup](https://paperpurr.com/en/docs/lookup), [Reference verification](https://paperpurr.com/en/docs/verify), synchronous |
| Rewriting in a backend service | Submit, then poll or use a webhook | [Rewrite](https://paperpurr.com/en/docs/rewrite) → [Job status](https://paperpurr.com/en/docs/jobs) / [Webhook](https://paperpurr.com/en/docs/webhooks) |
| An AI coding tool or agent | MCP | [MCP](https://paperpurr.com/en/docs/mcp) tools |

## Batch-verify references after finishing a paper

Save your reference list as `references.txt`, one entry per line. The script submits 20 at a time, prints only the entries with problems and what differs, and backs off on `429` and `5xx` using `Retry-After`.

Python:

```python
import os
import time
import requests

API = "https://paperpurr.com/v1/citations/verify"
HEADERS = {"Authorization": f"Bearer {os.environ['PAPERPURR_API_KEY']}"}


def verify(batch):
    for attempt in range(5):
        r = requests.post(API, headers=HEADERS, json={"references": batch}, timeout=60)
        if r.status_code == 429 or r.status_code >= 500:
            time.sleep(int(r.headers.get("Retry-After", 2 ** attempt)))
            continue
        r.raise_for_status()
        return r.json()
    raise RuntimeError(f"gave up, request_id={r.headers.get('X-Request-Id')}")


# references.txt: one full reference per line
refs = [s.strip() for s in open("references.txt", encoding="utf-8") if s.strip()]

for start in range(0, len(refs), 20):
    batch = refs[start:start + 20]
    data = verify(batch)
    for item in data["results"]:
        if item["status"] in ("mismatch", "not_found", "error"):
            print(f"[{start + item['index'] + 1}] {item['status']}: {batch[item['index']][:70]}")
            for d in item.get("diffs", []):
                print(f"    {d['field']}: cited {d.get('ours')!r}, found {d.get('found')!r}")
    print("units", data["usage"]["units"], "remaining", data["usage"]["remaining"])
```

JS:

```javascript
const API = "https://paperpurr.com/v1/citations/verify";
const headers = {
  Authorization: `Bearer ${process.env.PAPERPURR_API_KEY}`,
  "Content-Type": "application/json",
};

async function verify(batch) {
  for (let attempt = 0; attempt < 5; attempt++) {
    const r = await fetch(API, { method: "POST", headers, body: JSON.stringify({ references: batch }) });
    if (r.status === 429 || r.status >= 500) {
      const wait = Number(r.headers.get("Retry-After") ?? 2 ** attempt);
      await new Promise((ok) => setTimeout(ok, wait * 1000));
      continue;
    }
    if (!r.ok) throw new Error((await r.json()).error.code);
    return r.json();
  }
  throw new Error("gave up");
}
```

- Chinese entries come back as `skipped` (`reason: cjk`). They aren’t charged; check them yourself.
- For `mismatch`, `diffs` shows which field is wrong and `match` has the correct record to copy from.
- A batch of 20 costs at most 20 units. Check [`/v1/usage`](https://paperpurr.com/en/docs/usage) first: if you don’t have enough for the whole batch, it returns `402`.

## Have an agent in Claude Code find and insert citations

Once `paperpurr` is set up as described in [MCP](https://paperpurr.com/en/docs/mcp), give instructions in your paper’s repository:

Verify references:

```text
Read refs.bib and check it with paperpurr’s verify_references, 20 entries at a time. Fix mismatch entries using the bibliographic data in match and tell me what changed. List not_found and skipped entries without changing them.
```

Find and insert a citation:

```text
Chapter 3, paragraph 2 mentions the original Transformer paper. Find it with lookup_citation, add an APA 7th edition in-text citation and append an entry to refs.bib.
```

The agent calls the tools in turn:

```json
[
  {
    "tool": "verify_references",
    "arguments": {
      "references": [
        "Vaswani, A. et al. (2017). Attention is all you need. NeurIPS.",
        "…"
      ]
    }
  },
  {
    "tool": "lookup_citation",
    "arguments": {
      "query": "Attention Is All You Need"
    }
  },
  {
    "tool": "get_usage",
    "arguments": {}
  }
]
```

> **Warning:** The agent is editing your files. Keep tool approval on and review `git diff` before committing. `not_found` doesn’t mean the work doesn’t exist; it may just not be indexed.

## Rewriting: polling or webhooks

1. **Submit**

   `POST /v1/rewrite` with an `Idempotency-Key`, so retries after network errors never charge twice.

2. **Wait for the result**

   In a script, poll `GET /v1/jobs/{id}` every 3–5 seconds. On a server, set `webhook_url` and we’ll push when the job ends; dedupe by `job_id`.

3. **Collect the drafts**

   After `completed`, read `result.drafts` before `expires_at`.

> **Note:** Rewriting opens after the first release.

- [Reference verification](https://paperpurr.com/en/docs/verify)：Check each reference against Crossref and OpenAlex and flag whether it matches, differs or can’t be found.
- [MCP](https://paperpurr.com/en/docs/mcp)：Use PaperPurr from Claude Code, Cursor, VS Code, Codex and other AI clients: server address, per-client setup, tools and connection check.
- [Errors](https://paperpurr.com/en/docs/errors)：The error format, the cause and fix for every error code, which ones to retry, and the correct way to handle common mistakes.

Next: [Webhook](https://paperpurr.com/en/docs/webhooks.md)
