# Retries and idempotency

> Retry changes safely with an Idempotency-Key, over REST or MCP.

Networks fail. If a request that changes something times out, you can't tell whether it went through, and retrying might do it twice. Send an `Idempotency-Key` header with every change, and retry with the same key:

```bash
curl -X POST https://developers.playbookops.ai/v1/projects/PROJECT_ID/items \
  -H "Authorization: Bearer $PLAYBOOKOPS_API_KEY" \
  -H "Idempotency-Key: 6f1d2c1e-8a3b-4b8e-9d55-2c0f9e7a1b42" \
  -H "Content-Type: application/json" \
  -d '{"title": "Call the venue"}'
```

## How it works

- The first request makes the change. Retries with the same key and the same body return the first answer and change nothing.
- Using the key again with a different body or endpoint returns `409` with the code `idempotency_key_reused`.
- Keys are remembered per API key. Use a new UUID for each change.
- Only changes that succeed are remembered, so a request that failed with an error can be retried with the same key.

## Retrying in code

Make the key once per change, outside the retry loop:

**Python**

```python
import time
import uuid

import httpx

def create_item(api, project_id, body, attempts=4):
    key = str(uuid.uuid4())
    for attempt in range(attempts):
        try:
            res = api.post(f"/projects/{project_id}/items", json=body, headers={"Idempotency-Key": key})
        except httpx.TransportError:
            time.sleep(2**attempt)
            continue
        if res.status_code == 429 or res.status_code >= 500:
            time.sleep(int(res.headers.get("Retry-After", 2**attempt)))
            continue
        res.raise_for_status()
        return res.json()
    raise RuntimeError("Gave up after retries")
```

**JavaScript**

```javascript
async function createItem(projectId, body, attempts = 4) {
  const key = crypto.randomUUID();
  for (let attempt = 0; attempt < attempts; attempt++) {
    try {
      const res = await fetch(`${base}/projects/${projectId}/items`, {
        method: "POST",
        headers: { ...headers, "Content-Type": "application/json", "Idempotency-Key": key },
        body: JSON.stringify(body),
      });
      if (res.status !== 429 && res.status < 500) {
        if (!res.ok) throw new Error((await res.json()).error.message);
        return await res.json();
      }
    } catch (e) {
      if (!(e instanceof TypeError)) throw e;
    }
    await new Promise((r) => setTimeout(r, 2 ** attempt * 1000));
  }
  throw new Error("Gave up after retries");
}
```

## Over MCP

MCP has no headers per call, so every tool that changes something takes an optional `idempotency_key` argument instead. It works the same way: retry a tool call with the same `idempotency_key` and you get the first answer back.

```json
{
  "name": "create_document",
  "arguments": {
    "playbook_id": "…",
    "title": "Restore a backup",
    "content": "## Steps\n\n1. …",
    "idempotency_key": "import:runbooks/restore.md"
  }
}
```

Agents rarely send one unless you ask. If you run an agent that makes changes, tell it in the prompt: "When you create or change something, send an idempotency_key, and reuse it if you retry." Programs calling the MCP server should always send one.
