# Build on PlaybookOps
> Connect your code and AI agents to your projects, tasks, knowledge, automations, apps, people and KPIs.
PlaybookOps has a REST API for your own code and an MCP server for AI agents. Both use the same API keys and offer the same actions, and a key can only reach what the person who made it can reach in the app.
- [Quickstart](https://developers.playbookops.ai/quickstart): Make a key and get your projects back in about two minutes.
- [Connect an AI agent](https://developers.playbookops.ai/agents/mcp): Give Claude, Cursor, Codex or ChatGPT access to PlaybookOps over MCP.
- [Cookbooks](https://developers.playbookops.ai/cookbooks): Use your playbooks as your agents' context, in place of a repo of Markdown files.
- [Guides](https://developers.playbookops.ai/guides/projects-and-items): Walkthroughs for boards, tasks, knowledge, automations and apps.
- [API reference](https://developers.playbookops.ai/reference): Every endpoint, with examples and a Try it button that uses your key.
## Two ways in
**The REST API** is JSON over HTTPS at `https://developers.playbookops.ai/v1`. Use it for code with fixed steps: syncing items with another system, a webhook handler, a dashboard, a script that files tasks.
**The MCP server** at `https://mcp.playbookops.ai` offers the same actions as tools for AI agents. The agent reads each tool's description and decides what to call: "what's overdue on the launch board?" becomes `list_projects`, then `list_items`.
## What you can reach
| Area | Read | Change |
| --- | --- | --- |
| Projects and items | Projects, groups, columns, items, updates, search | Create, update, move and complete items; post updates |
| Tasks | Your tasks across projects and personal lists | Create personal tasks; update and complete your own |
| Knowledge | Playbooks, documents, search, who knows about a topic | [Create documents in Markdown](https://developers.playbookops.ai/guides/documents) and patch them section by section |
| Automations | Automations, runs and their steps | Start automations that are started by hand |
| Apps | Apps you can open, their collections and Live records | Create and update records |
| People and KPIs | People, job roles, KPIs and their values | |
## Good to know
- **A key acts as you.** It sees the projects you're on and the apps you can open, and its changes show up in the app as yours, with notifications and automations as usual. See [API keys and scopes](https://developers.playbookops.ai/authentication).
- **Admins stay in control.** Org admins see every key in the organization, can revoke any of them, can turn the API off, and can see the organization's API and MCP traffic under **Admin → API**.
- **Most calls are free.** Knowledge search and who knows use AI credits. Each key can make 120 requests a minute. See [limits and credits](https://developers.playbookops.ai/limits-and-credits).
- **Docs for models.** Every page is available as Markdown, and [`/llms.txt`](https://developers.playbookops.ai/llms.txt) lists them all for coding agents.
---
# Quickstart
> Make an API key, check it works, and read your first project.
You'll need a PlaybookOps account. Any member can make keys, unless an admin has turned the API off for your organization.
### Make a key
Open Account → API keys in PlaybookOps and click **New key**. Name it after what will use it, like "Zapier" or "Support agent". Then choose:
- **Read-only** to look around safely. Nothing can be changed with it.
- **Full access** when your code needs to create or update things.
You can also set it to expire after 30, 90 or 365 days. Copy the key when it's shown. It starts with `pbo_live_`, and you won't see it again. Keep it in an environment variable rather than in your code:
```bash
export PLAYBOOKOPS_API_KEY="pbo_live_…"
```
### Check who you are
`GET /v1/me` tells you who the key belongs to and what it's allowed to do.
**curl**
```bash
curl https://developers.playbookops.ai/v1/me \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY"
```
**Python**
```python
import os
import httpx
api = httpx.Client(
base_url="https://developers.playbookops.ai/v1",
headers={"Authorization": f"Bearer {os.environ['PLAYBOOKOPS_API_KEY']}"},
)
print(api.get("/me").json())
```
**JavaScript**
```javascript
const res = await fetch("https://developers.playbookops.ai/v1/me", {
headers: { Authorization: `Bearer ${process.env.PLAYBOOKOPS_API_KEY}` },
});
console.log(await res.json());
```
You'll get your name, organization and the key's scopes:
```json
{
"id": "4b1c…",
"name": "Ana Ruiz",
"organization_id": "9f20…",
"role": "member",
"scopes": ["projects:read", "tasks:read", "knowledge:read", "automations:read", "apps:read", "people:read", "kpis:read"],
"via": "api_key"
}
```
A `401` means the key is wrong, expired or revoked. See [errors](https://developers.playbookops.ai/errors) for the rest.
### Read a project
List your projects, then the open items in one of them:
**curl**
```bash
curl "https://developers.playbookops.ai/v1/projects?limit=5" \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY"
curl "https://developers.playbookops.ai/v1/projects/PROJECT_ID/items?include_completed=false" \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY"
```
**Python**
```python
projects = api.get("/projects", params={"limit": 5}).json()["data"]
for project in projects:
print(project["name"], project["url"])
items = api.get(f"/projects/{projects[0]['id']}/items", params={"include_completed": False}).json()
for item in items["data"]:
print(item["title"], item["status"], item["due_date"])
```
**JavaScript**
```javascript
const headers = { Authorization: `Bearer ${process.env.PLAYBOOKOPS_API_KEY}` };
const base = "https://developers.playbookops.ai/v1";
const { data: projects } = await (await fetch(`${base}/projects?limit=5`, { headers })).json();
const items = await (await fetch(`${base}/projects/${projects[0].id}/items?include_completed=false`, { headers })).json();
console.log(items.data.map((i) => i.title));
```
Everything you can open in the app has a `url`, so you can link people straight to it.
### Go further
- Follow a guide: [projects and items](https://developers.playbookops.ai/guides/projects-and-items), [tasks](https://developers.playbookops.ai/guides/tasks) or [knowledge](https://developers.playbookops.ai/guides/knowledge).
- Open the [API reference](https://developers.playbookops.ai/reference) and use **Try it** on any endpoint. It runs against your own organization, so changes made there are real.
- [Connect an AI agent](https://developers.playbookops.ai/agents/mcp) with the same key.
> **Explore with a read-only key**
> A read-only key can't change anything, so it's safe for exploring, reports and dashboards. Make a separate Full access key for code that needs to write.
---
# Connect an AI agent
> Give Claude, Cursor, Codex, ChatGPT or your own agent access to PlaybookOps over MCP.
PlaybookOps runs a remote [Model Context Protocol](https://modelcontextprotocol.io) server. Point your client at this address and send an API key:
```text
https://mcp.playbookops.ai
```
The tools are the API's actions, like `list_projects`, `search_knowledge`, `create_item` and `update_document`, with the same inputs and answers as the [API reference](https://developers.playbookops.ai/reference). An agent only sees the tools its key's scopes allow, so with a read-only key it has no way to change anything.
> **Make a key just for the agent**
> Make a key named after the agent, with the least access that works. Every change the agent makes is recorded against that key, and you can revoke it at any time.
## Set up your client
**Claude Code**
```bash
claude mcp add --transport http playbookops https://mcp.playbookops.ai \
--header "Authorization: Bearer $PLAYBOOKOPS_API_KEY"
```
Run `/mcp` inside Claude Code to check that it's connected.
**Cursor**
Add this to `~/.cursor/mcp.json`, or to `.cursor/mcp.json` in a project, and set `PLAYBOOKOPS_API_KEY` in your environment:
```json
{
"mcpServers": {
"playbookops": {
"url": "https://mcp.playbookops.ai",
"headers": { "Authorization": "Bearer ${env:PLAYBOOKOPS_API_KEY}" }
}
}
}
```
**Codex**
The Codex CLI, the Codex IDE extension and the ChatGPT desktop app share one config, so you only set this up once. Put your key in your shell profile (like `~/.zshrc`), then add the server:
```bash
export PLAYBOOKOPS_API_KEY="pbo_live_…"
codex mcp add playbookops --url https://mcp.playbookops.ai \
--bearer-token-env-var PLAYBOOKOPS_API_KEY
```
That adds the server to `~/.codex/config.toml`. You can also write it by hand, there or in a project's `.codex/config.toml`:
```toml
[mcp_servers.playbookops]
url = "https://mcp.playbookops.ai"
bearer_token_env_var = "PLAYBOOKOPS_API_KEY"
# Reads run straight away; Codex asks before anything that makes a change.
default_tools_approval_mode = "writes"
```
Run `codex mcp list` to see it, or `/mcp` inside Codex to check that it's connected. To keep Codex to a few tools, add `enabled_tools = ["search_knowledge", "read_document"]`.
> **Connecting from the desktop app**
> Apps opened from the Dock or Start menu may not see variables from your shell profile. If PlaybookOps shows as unauthorized there, put the key in the config instead with `http_headers = { Authorization = "Bearer pbo_live_…" }`. The key is then stored in that file as plain text, so only do this in `~/.codex/config.toml`, never in a project's config that might be committed.
**Claude Desktop**
Claude Desktop starts servers on your computer, so it connects through [`mcp-remote`](https://www.npmjs.com/package/mcp-remote), which needs [Node.js](https://nodejs.org). Open **Settings → Developer → Edit Config** and add:
```json
{
"mcpServers": {
"playbookops": {
"command": "npx",
"args": ["-y", "mcp-remote", "https://mcp.playbookops.ai", "--header", "Authorization:${PLAYBOOKOPS_AUTH}"],
"env": { "PLAYBOOKOPS_AUTH": "Bearer pbo_live_…" }
}
}
}
```
Replace `pbo_live_…` with your key, and keep `Bearer ` and its space in front of it. You don't set `PLAYBOOKOPS_AUTH` on your computer: Claude Desktop passes the `env` value to `mcp-remote`, which puts it in the `Authorization` header. The key lives in `env` because some systems split arguments that contain spaces, so leave out the space after `Authorization:`.
If the file already has other servers, add `"playbookops"` inside the existing `mcpServers`. Then quit and reopen Claude Desktop, which reads the file only when it starts.
**Python**
With the official [`mcp`](https://pypi.org/project/mcp/) package:
```python
import asyncio
import os
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
async def main():
headers = {"Authorization": f"Bearer {os.environ['PLAYBOOKOPS_API_KEY']}"}
async with streamablehttp_client("https://mcp.playbookops.ai", headers=headers) as (read, write, _):
async with ClientSession(read, write) as session:
await session.initialize()
tools = await session.list_tools()
print([t.name for t in tools.tools])
result = await session.call_tool("list_projects", {"limit": 5})
print(result.structuredContent)
asyncio.run(main())
```
**TypeScript**
With the official [`@modelcontextprotocol/sdk`](https://www.npmjs.com/package/@modelcontextprotocol/sdk) package:
```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
const transport = new StreamableHTTPClientTransport(new URL("https://mcp.playbookops.ai"), {
requestInit: { headers: { Authorization: `Bearer ${process.env.PLAYBOOKOPS_API_KEY}` } },
});
const client = new Client({ name: "my-agent", version: "1.0.0" });
await client.connect(transport);
const { tools } = await client.listTools();
const result = await client.callTool({ name: "list_projects", arguments: { limit: 5 } });
console.log(result.structuredContent);
```
Model APIs that connect to MCP servers themselves, like Anthropic's MCP connector and OpenAI's remote MCP tool, need the same two things: the address `https://mcp.playbookops.ai` and the key as a Bearer token.
## Try it out
Once connected, ask your agent something like:
- "What's due this week on my PlaybookOps tasks?"
- "Search our playbooks for how we handle refunds over $500, and link the document."
- "Who knows the most about payroll?"
- "Add an item to the Launch board for calling the venue, due Friday, assigned to me."
## What the agent gets back
- Every tool returns structured JSON (`structuredContent`) that matches its output schema, plus the same JSON as text.
- A failed call comes back with `isError: true` and a plain sentence, like "This key can't do that. It needs the projects:write scope." The agent can read it and adjust.
- Tools that change things are marked as such, and `delete_item` and `delete_task` are also marked as destructive, so clients that ask before running them will ask.
- Calls count toward the same [rate limits and credits](https://developers.playbookops.ai/limits-and-credits) as the REST API.
## Retrying changes
Every tool that changes something takes an optional `idempotency_key` argument. Retry with the same key and the agent gets the first answer back instead of making the change twice, just like the REST API's `Idempotency-Key` header. Ask your agent to send one with every change. See [retries and idempotency](https://developers.playbookops.ai/idempotency).
## Resources
Playbooks and documents are also MCP resources, for clients that let you attach context directly (like adding a document to a chat) instead of having the agent call tools. They need `knowledge:read`.
| Address | What you get |
| --- | --- |
| `playbookops://playbooks/{playbook_id}` | The playbook as a Markdown outline: its folders, and each document with its own resource address |
| `playbookops://documents/{document_id}` | The document's full Markdown |
Listing resources returns your 15 newest playbooks. Any playbook or document you can open in the app can be read by its address.
`https://developers.playbookops.ai/mcp` is the same server, if you'd rather use one address for everything.
---
# Building agents
> Patterns for agents and integrations that read and change PlaybookOps safely.
## Pick the right way in
| You're building | Use |
| --- | --- |
| An AI agent that decides what to do | The [MCP server](https://developers.playbookops.ai/agents/mcp). The model reads each tool's description and picks what it needs. |
| Code with fixed steps: a sync job, a webhook handler, a dashboard | The REST API. Same actions, plain HTTP, and [safe retries](https://developers.playbookops.ai/idempotency). |
| A custom agent with your own model calls | Either. MCP SDKs list the tools for you; or describe a few REST calls as your own tools. |
## Give each agent its own key
One key per agent or integration, named after it, with the least access that works:
- **Read-only** for anything that answers questions or reports. It can't change anything, whatever the model decides to do.
- **Custom** when it only works in one area, like `knowledge:write` for an agent that keeps documents current.
- **Full access** only when it must make changes everywhere. Over MCP the agent then sees the tools that change things too.
Keys act as the person who made them, so an agent never sees more than its owner. Admins can see each key's traffic under **Admin → API** and revoke it there.
## Ground answers in your knowledge
For questions about how your organization works, have the agent:
1. Call `search_knowledge` with the whole question, not keywords. Search matches meaning.
2. Call `read_document` for the documents that matter, to read beyond the passage.
3. Cite the `url` of each document it used, so people can check.
4. Call `who_knows` to find someone to ask when the documents don't cover it.
The [cookbooks](https://developers.playbookops.ai/cookbooks) take this further: moving a docs repo in, coding agents, citations, mirroring to files and keeping documents current.
A system prompt line that works well:
```text
When asked how we do something, search PlaybookOps knowledge first and answer only from what you find. Link each document you used. If nothing covers it, say so and suggest who to ask using who_knows.
```
## Make changes safely
- **Read before you write.** Call `get_project` for the board's groups and columns before setting values, and `list_people` before assigning someone.
- **Don't repeat changes.** Over REST, send an `Idempotency-Key` with every change ([how](https://developers.playbookops.ai/idempotency)). Over MCP, pass an `idempotency_key` argument to any tool that makes a change.
- **Handle limits.** On `429`, wait `Retry-After` seconds. On `402`, tell the person their organization is out of AI credits.
- **Let the app notify people.** Changes made through the API behave like changes in the app: assignees are notified and automations run. Your agent doesn't need to send its own messages.
## Docs for models
These docs come in plain text for models and coding agents:
- [`/llms.txt`](https://developers.playbookops.ai/llms.txt) lists every page with a one-line summary.
- [`/llms-full.txt`](https://developers.playbookops.ai/llms-full.txt) has every guide in one file.
- Every page is also available as Markdown: add `.md` to its address.
- [`/v1/openapi.json`](https://developers.playbookops.ai/v1/openapi.json) describes the API in OpenAPI 3.1, for code generators.
---
# PlaybookOps as your agents' context
> Use PlaybookOps as the context repository for your AI agents, in place of a Git repo full of Markdown files.
A lot of teams keep their agents' context in a Git repository of Markdown: an `AGENTS.md`, runbooks, style guides, product notes, how-we-work docs. It's a good start. Then the gaps show:
- Only people comfortable with Git can fix a wrong instruction, so the docs drift away from how the team really works.
- Every agent loads the same files into its prompt, whether they're relevant or not, and the prompt grows until it's too big.
- Nothing says who owns a document, whether it's still right, or who to ask when it's silent.
- Everyone who can read the repo can read all of it.
PlaybookOps keeps what works about that setup, Markdown in and Markdown out, and adds the rest. Anyone on the team can edit in the app. Agents find what they need by meaning instead of loading everything. Every change is versioned, documents have owners and reviewers, and each agent sees only what its key's owner can see.
## What maps to what
| In a docs repo | In PlaybookOps |
| --- | --- |
| A top-level folder, like `runbooks/` | A playbook |
| A subfolder | A folder in the playbook |
| A `.md` file | A document. You write it in [Markdown](https://developers.playbookops.ai/guides/markdown) and read it back as Markdown. |
| Front matter: `title`, `tags`, `type` | The document's title, `tags` and `document_type` |
| A commit | A new version in the document's history, under the name of whoever made it |
| A merge conflict | A `409 version_conflict` when you send a stale `base_version` |
| `CODEOWNERS` | The document's owner and reviewers. `who_knows` finds the right person for a topic. |
| `grep` | `search_knowledge` searches by meaning; `list_content` by title |
| `git pull` | `GET /v1/document-changes`: what changed, moved or was deleted since a time |
| A file path | An MCP resource address, like `playbookops://documents/{id}` |
| Pull request review | Documents start as drafts, and a body change asks reviewers to review again |
| Who can clone the repo | Who can open each playbook, plus the key's scopes |
## Four ways agents use it
Most agents combine two or three of these.
| Pattern | How | Use it when |
| --- | --- | --- |
| **Look it up** | `search_knowledge`, then `read_document` for the documents that matter, then cite their links | The default. It scales to thousands of documents and keeps prompts small. Each search uses 1 AI credit. |
| **Pin a few documents** | Read a handful of documents by id when the agent starts, and put them in its instructions | Rules the agent must always follow, like coding conventions or a tone of voice. This is your `AGENTS.md`. Reads are free. |
| **Mirror to files** | Copy a playbook into a folder of `.md` files and refresh what changed | Tools that only read files, offline or CI runs, or your own search index |
| **Write back** | `update_document` with section edits and `base_version` | Agents that learn something worth keeping: a fixed runbook step, a new FAQ, an incident timeline |
## Cookbooks
- [Move a docs repo into PlaybookOps](https://developers.playbookops.ai/cookbooks/import-a-docs-repo): A script that imports a folder of Markdown files into playbooks and folders, keeps tags and links, and is safe to run again.
- [Give coding agents your playbooks](https://developers.playbookops.ai/cookbooks/coding-agents): Claude Code, Cursor and Codex look things up in PlaybookOps instead of a docs folder.
- [Answer with citations](https://developers.playbookops.ai/cookbooks/grounded-answers): An agent that answers only from your documents and links what it used, with Claude, OpenAI or your own loop.
- [Mirror a playbook to files](https://developers.playbookops.ai/cookbooks/sync-to-files): Keep a folder of Markdown in step with a playbook, fetching only what changed.
- [Have agents keep docs current](https://developers.playbookops.ai/cookbooks/keep-docs-current): Agents that fix a runbook step or log what they learned, without overwriting anyone.
## Write documents agents can use
Agents read your documents the way a new starter would, only faster and more literally. A few habits make a big difference:
- **One topic per document, titled as what it answers.** "How we deploy the backend" is found by search and understood at a glance. "Deploy notes v2" isn't.
- **Headings that name things.** Search returns passages, and edits target headings, so `## Rolling back` beats `## Step 4`.
- **The rule first, then the reason.** "Never run migrations on Fridays. Weekend on-call is one person." The rule survives being quoted out of context.
- **Say who to ask.** A [mention](https://developers.playbookops.ai/guides/markdown#mentions) of the owner gives agents and people somewhere to go when the document is silent.
- **Keep documents under 24,000 characters.** Longer ones come back cut short unless the agent asks for `full=true`, and long documents are harder to search well. Split them by topic.
- **A playbook for agent instructions.** Keep the always-on rules, the ones you'd put in `AGENTS.md`, in their own playbook so they're easy to pin and easy to review.
> **A key for each agent**
> Keys act as the person who made them, so an agent sees exactly what its key's owner can open. For a shared agent, have a dedicated account (like `agents@yourcompany.com`) make the key, and give that account access to just the playbooks the agent should use. See [building agents](https://developers.playbookops.ai/agents) for more.
---
# Move a docs repo into PlaybookOps
> Import a folder of Markdown files into playbooks and folders, keeping titles, tags and links between documents. Safe to run again.
This recipe moves a Git repository of Markdown, like `docs/` or an agent-context repo, into PlaybookOps. Each top-level folder becomes a playbook, each subfolder becomes a folder inside it, and each `.md` file becomes a document. The script can run as often as you like: it only sends files that changed, and it never overwrites an edit someone made in the app.
### Make a key
Make a Custom key named "Docs import" with **Playbooks and documents** set to **Read and change**, and nothing else. The playbooks and documents will show it as their author, so use your own account or the account that should own them.
```bash
export PLAYBOOKOPS_API_KEY="pbo_live_…"
pip install httpx pyyaml
```
### Run the import
Save this as `import_docs.py` and run `python import_docs.py path/to/docs`. To put a folder into a playbook you already have, add it to `PLAYBOOKS`; every other top-level folder gets a new playbook named after it.
```python
"""Import a folder of Markdown files into PlaybookOps.
Each top-level folder becomes a playbook (or goes into the one mapped to it
below), and subfolders become folders. Running it again sends only the files
that changed since the last run.
"""
import hashlib
import json
import os
import posixpath
import re
import sys
import time
import uuid
from pathlib import Path
from urllib.parse import urlparse
import httpx
import yaml
# Top-level folder -> an existing playbook's id. "." is for files at the root.
# Anything not listed gets a new playbook.
PLAYBOOKS = {
# "runbooks": "PLAYBOOK_ID",
}
MAX_FOLDER_DEPTH = 6
DOCUMENT_TYPES = {
"sop", "process", "training", "policy", "procedure", "manual", "workflow",
"internal_document", "job_description", "project_plan", "proven_process", "general",
}
STATE_FILE = Path(".playbookops-import.json")
FRONT_MATTER = re.compile(r"\A---\n(.*?)\n---\n?", re.S)
TITLE = re.compile(r"\A#\s+(.+)\n*")
MD_LINK = re.compile(r"\]\((?!https?:|mailto:|#)([^)\s]+?\.md)(#[^)\s]*)?\)")
LOCAL_IMAGE = re.compile(r"!\[[^\]]*\]\((?!https:)[^)]+\)")
api = httpx.Client(
base_url="https://developers.playbookops.ai/v1",
headers={"Authorization": f"Bearer {os.environ['PLAYBOOKOPS_API_KEY']}"},
timeout=60,
)
def call(method: str, path: str, body: dict, key: str) -> dict:
"""Send one change, waiting out rate limits. The key makes retries safe."""
while True:
res = api.request(method, path, json=body, headers={"Idempotency-Key": key})
if res.status_code == 429:
time.sleep(int(res.headers.get("Retry-After", "5")))
continue
if res.is_error:
raise RuntimeError(res.json()["error"]["message"])
return res.json()
def nice(name: str) -> str:
name = name.replace("-", " ").replace("_", " ").strip()
return name[:1].upper() + name[1:]
def playbook_for(top: str, name: str, state: dict) -> str:
"""The playbook for a top-level folder, made the first time it's needed."""
if top in PLAYBOOKS:
return PLAYBOOKS[top]
playbooks = state.setdefault("_playbooks", {})
if top not in playbooks:
made = call("POST", "/playbooks", {"name": nice(name), "description": f"Imported from {name}/"}, str(uuid.uuid4()))
playbooks[top] = made["id"]
print(f"playbook {made['name']}")
return playbooks[top]
def folder_for(playbook_id: str, rel: str, state: dict) -> str | None:
"""The folder matching a file's subfolders, made as needed."""
folders = state.setdefault("_folders", {})
parts = rel.split("/")
parent = None
for depth in range(1, min(len(parts) - 1, MAX_FOLDER_DEPTH + 1)):
path = "/".join(parts[: depth + 1])
if path not in folders:
body = {"name": nice(parts[depth]), "parent_folder_id": parent}
folders[path] = call("POST", f"/playbooks/{playbook_id}/folders", body, str(uuid.uuid4()))["id"]
parent = folders[path]
return parent
def parse(rel: str, text: str) -> dict:
"""A document from a Markdown file: front matter for details and the
first heading as the title."""
meta = {}
if found := FRONT_MATTER.match(text):
meta = yaml.safe_load(found.group(1)) or {}
text = text[found.end():]
text = text.strip()
title = meta.get("title")
if heading := TITLE.match(text):
title = title or heading.group(1).strip()
text = text[heading.end():] # the app shows the title above the body
kind = meta.get("type", "general")
return {
"title": str(title or nice(posixpath.basename(rel)[:-3]))[:300],
"description": str(meta.get("description") or "")[:2000],
"document_type": kind if kind in DOCUMENT_TYPES else "general",
"tags": [str(t) for t in meta.get("tags") or []][:20],
"content": text,
}
def import_file(root: Path, rel: str, text: str, state: dict) -> None:
top = rel.split("/")[0] if "/" in rel else "."
doc = parse(rel, text)
digest = hashlib.sha256(json.dumps(doc, sort_keys=True).encode()).hexdigest()
known = state.get(rel)
if known and known["digest"] == digest:
return
playbook_id = playbook_for(top, root.resolve().name if top == "." else top, state)
doc["folder_id"] = folder_for(playbook_id, rel, state)
key = str(uuid.uuid5(uuid.NAMESPACE_URL, f"{rel}:{digest}"))
if known:
changes = {k: doc[k] for k in ("title", "description", "tags", "folder_id")}
if doc["content"]:
changes["content"] = doc["content"]
try:
# base_version: if someone edited it in the app since, leave it alone
saved = call("PATCH", f"/documents/{known['id']}", {**changes, "base_version": known["version"]}, key)
except RuntimeError as error:
return print(f"kept {rel}: {error}")
print(f"updated {rel}")
else:
saved = call("POST", f"/playbooks/{playbook_id}/documents", doc, key)
print(f"created {rel}")
if LOCAL_IMAGE.search(text):
print(f" {rel} has images with local paths; give them https links")
state[rel] = {"id": saved["id"], "version": saved["version"], "url": saved["url"], "digest": digest}
def link_file(rel: str, text: str, state: dict) -> None:
"""Point links to other imported files at their documents in the app."""
known = state.get(rel)
if not known or known.get("linked") == known["digest"]:
return
def to_document(match: re.Match) -> str:
target = state.get(posixpath.normpath(posixpath.join(posixpath.dirname(rel), match.group(1))))
if not target:
return match.group(0)
url = urlparse(target["url"])
return f"]({url.path}?{url.query})"
content = parse(rel, text)["content"]
linked = MD_LINK.sub(to_document, content)
if linked != content:
key = str(uuid.uuid5(uuid.NAMESPACE_URL, f"{rel}:{known['digest']}:links"))
try:
saved = call("PATCH", f"/documents/{known['id']}", {"content": linked, "base_version": known["version"]}, key)
except RuntimeError as error:
return print(f"kept {rel}: {error}")
known["version"] = saved["version"]
print(f"linked {rel}")
known["linked"] = known["digest"]
def main(root: Path) -> None:
state = json.loads(STATE_FILE.read_text()) if STATE_FILE.exists() else {}
files = {p.relative_to(root).as_posix(): p.read_text(encoding="utf-8") for p in sorted(root.rglob("*.md"))}
try:
for rel, text in files.items():
import_file(root, rel, text, state)
for rel, text in files.items():
link_file(rel, text, state)
finally:
STATE_FILE.write_text(json.dumps(state, indent=2))
if __name__ == "__main__":
main(Path(sys.argv[1]))
```
The script works in two passes. The first creates or updates each document. The second points links between files, like `[deploys](../runbooks/deploy.md)`, at the new documents in the app.
```text
playbook Runbooks
created runbooks/deploy.md
created runbooks/rollback.md
playbook Engineering
created engineering/conventions/python.md
linked runbooks/deploy.md
```
### Check the result
Open the playbooks in the app. New playbooks can be seen by everyone in the organization, so limit access on any that should be private. Documents arrive as drafts: read through them and publish them when they're right. `engineering/conventions/python.md` is in the **Conventions** folder of the **Engineering** playbook.
## What carries over
| From the file | Becomes |
| --- | --- |
| `title` in the front matter, or else the first `# Heading`, or else the file name | The title. The heading is taken out of the body, since the app shows the title above it. |
| `description` | The one-line summary shown in lists |
| `type`, if it's one of the [document types](https://developers.playbookops.ai/guides/documents#create-a-document) | `document_type`. Anything else becomes `general`. |
| The top-level folder | A playbook |
| Subfolders | Folders in the playbook, up to six levels deep. Deeper files go in the sixth. |
| `tags` | `tags`, up to 20 |
| Links to other `.md` files | Links to their documents in the app |
| Everything else | The body, as [Markdown](https://developers.playbookops.ai/guides/markdown) |
Images need public `https` links, and the script lists files whose images use local paths. Mermaid diagrams stay as code blocks; for a diagram people can edit, make a flowchart in the playbook and link to it.
## Running it again
`.playbookops-import.json` remembers each file's document, version and contents, and the playbooks and folders it made, so a second run only sends files that changed. If someone edited a document in the app since the last run, the script leaves it alone and prints `kept`, because its `base_version` no longer matches. That's the point at which PlaybookOps becomes the place to edit: change it there, not in the repo.
While both exist, you can run the import from CI on every push to the repo's main branch, with the key in a CI secret and `.playbookops-import.json` committed. When the team has moved over, replace the repo's README with a link to the playbooks, or turn it around and [mirror the playbooks into the repo](https://developers.playbookops.ai/cookbooks/sync-to-files).
## Next
- [Give coding agents your playbooks](https://developers.playbookops.ai/cookbooks/coding-agents) so they look things up instead of reading a docs folder.
- [Writing in Markdown](https://developers.playbookops.ai/guides/markdown) covers callouts, checklists, toggles and mentions, which most docs repos don't use yet.
---
# Give coding agents your playbooks
> Claude Code, Cursor and Codex look up your conventions and runbooks in PlaybookOps instead of a docs folder in the repo.
Coding agents read context from files in the repo: `AGENTS.md`, `CLAUDE.md`, `.cursor/rules`, a `docs/` folder. This recipe keeps one short instructions file in the repo and moves everything else to PlaybookOps. The agent looks up what it needs, when it needs it, and the people who own the conventions can change them without a pull request.
You'll commit three small things to the repo: the server config, the instructions, and which tools the agent may run without asking. None of them contain a key.
### Each developer makes a read-only key
Each person makes their own Read-only key, named something like "Claude Code on my laptop", and adds it to their shell profile:
```bash
export PLAYBOOKOPS_API_KEY="pbo_live_…"
```
A read-only key means the agent can look things up but can't change anything, whatever it decides to do. Because a key acts as its owner, everyone's agent sees exactly the playbooks they can.
### Commit the server config
Project config files let the whole team share one setup. Each reads the key from the environment.
**Claude Code**
`.mcp.json` at the root of the repo:
```json
{
"mcpServers": {
"playbookops": {
"type": "http",
"url": "https://mcp.playbookops.ai",
"headers": { "Authorization": "Bearer ${PLAYBOOKOPS_API_KEY}" }
}
}
}
```
Claude Code asks each person once before using a project's servers.
**Cursor**
`.cursor/mcp.json`:
```json
{
"mcpServers": {
"playbookops": {
"url": "https://mcp.playbookops.ai",
"headers": { "Authorization": "Bearer ${env:PLAYBOOKOPS_API_KEY}" }
}
}
}
```
**Codex**
`.codex/config.toml`. Codex reads project config once you've marked the project as trusted.
```toml
[mcp_servers.playbookops]
url = "https://mcp.playbookops.ai"
bearer_token_env_var = "PLAYBOOKOPS_API_KEY"
enabled_tools = [
"search_knowledge", "read_document", "list_content", "list_playbooks", "who_knows",
]
```
### Tell the agent how to use it
Put this in `AGENTS.md` at the root of the repo. Codex and Cursor read it as it is. For Claude Code, add a `CLAUDE.md` containing `@AGENTS.md`.
```markdown
## Team knowledge lives in PlaybookOps
Our conventions, runbooks and architecture notes are in PlaybookOps, not in
this repo. Use the playbookops tools to read them.
- At the start of a task, read the "Engineering conventions" document with
read_document (id: DOCUMENT_ID) and follow it.
- Before changing an area you haven't worked on in this session, look up how
we do it: search_knowledge with a whole question, like "How do we write
database migrations?". Read the documents that match with read_document;
a passage on its own can mislead.
- Don't search for every small step. Each search uses an AI credit.
- If a document and the code disagree, follow the code, finish the task, and
tell me which document looks out of date and why.
- List the documents you relied on, with their links, in your summary.
- If nothing covers a question, say so and use who_knows to suggest who to ask.
```
`DOCUMENT_ID` is the `contentId` in the document's address in the app. Pin only what every task needs; everything else is better looked up.
### Let the lookups run without asking
Lookups are read-only, so there's no need to approve each one.
**Claude Code**
`.claude/settings.json`:
```json
{
"permissions": {
"allow": [
"mcp__playbookops__search_knowledge",
"mcp__playbookops__read_document",
"mcp__playbookops__list_content",
"mcp__playbookops__list_playbooks",
"mcp__playbookops__who_knows"
]
}
}
```
**Cursor**
In Cursor's settings, find the agent's auto-run options and add the same five tools to its MCP allowlist.
**Codex**
Add `default_tools_approval_mode = "writes"` under `[mcp_servers.playbookops]`. Codex then runs read-only tools without asking.
## Try it
Ask your agent for something that depends on how your team works:
- "Add a column for the customer's region to the orders table." The agent should look up how you write migrations before writing one.
- "The deploy failed with a health check timeout. What do we do?" It should find and follow the runbook, and link it.
- "Review this branch against our conventions."
## What to move out of the repo
| Keep in the repo | Move to PlaybookOps |
| --- | --- |
| How to build, test and run the code: commands, scripts, environment setup | How the team works: conventions, review standards, release and on-call process |
| Instructions about this repo's layout | Runbooks, incident write-ups, architecture decisions |
| A short `AGENTS.md` that points at PlaybookOps | Anything people outside engineering read or write: product notes, support playbooks, policies |
The rule of thumb: if it changes when the code changes, keep it next to the code. If it changes when the team changes its mind, put it where the team can edit it.
## Next
- [Move a docs repo into PlaybookOps](https://developers.playbookops.ai/cookbooks/import-a-docs-repo) to bring the existing `docs/` folder across.
- [Have agents keep docs current](https://developers.playbookops.ai/cookbooks/keep-docs-current) once you trust them to suggest fixes.
---
# Answer with citations
> An agent that answers questions only from your playbooks and links every document it used, with Claude, OpenAI or a pipeline of your own.
The most common thing a context repository does is answer "how do we…?" questions: in a support tool, a Slack bot, an internal assistant. The answer has to come from your documents, not the model's general knowledge, and people need to be able to check it.
The shape is the same whichever way you build it:
1. **Search** with the whole question. `search_knowledge` matches meaning, so "can I refund $800 without asking anyone?" finds the refund policy even though it never says "asking anyone".
2. **Read** the documents behind the best passages. A passage alone can miss the exception two paragraphs down.
3. **Answer** only from what was read, and **cite** each document's `url`.
4. **Admit gaps.** If nothing covers it, say so and suggest who to ask with `who_knows`.
## Instructions that work
Every option below uses these instructions:
```text
You answer questions about how our company works, using only PlaybookOps.
Search with search_knowledge using the person's whole question. Then read the
documents that look relevant with read_document; don't answer from search
passages alone. Answer from what the documents say, briefly, in plain words.
End with "Sources:" and a Markdown link to the url of each document you used.
If the documents don't answer the question, say so plainly. Don't fill the gap
from general knowledge. Use who_knows to suggest who to ask.
If two documents disagree, say which says what and link both.
```
## Build it
Make a Read-only key for the agent first.
**Claude**
The Claude API connects to the MCP server itself, so there's no tool loop to write. The toolset turns everything off except the three tools the agent needs.
```python
import os
import anthropic
INSTRUCTIONS = "..." # the instructions above
client = anthropic.Anthropic()
response = client.beta.messages.create(
model="claude-opus-5-5",
max_tokens=2000,
system=INSTRUCTIONS,
messages=[{"role": "user", "content": "Can I refund a customer $800 without approval?"}],
mcp_servers=[
{
"type": "url",
"url": "https://mcp.playbookops.ai",
"name": "playbookops",
"authorization_token": os.environ["PLAYBOOKOPS_API_KEY"],
}
],
tools=[
{
"type": "mcp_toolset",
"mcp_server_name": "playbookops",
"default_config": {"enabled": False},
"configs": {name: {"enabled": True} for name in ("search_knowledge", "read_document", "who_knows")},
}
],
betas=["mcp-client-2025-11-20"],
)
print("".join(block.text for block in response.content if block.type == "text"))
```
**OpenAI**
The Responses API connects to the MCP server itself. `allowed_tools` keeps the model to the three tools it needs.
```python
import os
from openai import OpenAI
INSTRUCTIONS = "..." # the instructions above
client = OpenAI()
response = client.responses.create(
model="gpt-6.2-astra",
instructions=INSTRUCTIONS,
input="Can I refund a customer $800 without approval?",
tools=[
{
"type": "mcp",
"server_label": "playbookops",
"server_url": "https://mcp.playbookops.ai",
"authorization": os.environ["PLAYBOOKOPS_API_KEY"],
"allowed_tools": ["search_knowledge", "read_document", "who_knows"],
"require_approval": "never",
}
],
)
print(response.output_text)
```
**Your own pipeline**
When you want the same steps every time, and any model, call the REST API yourself and hand the model the documents. This is cheaper and easier to test, at the cost of the model not choosing a second search.
```python
import os
import httpx
api = httpx.Client(
base_url="https://developers.playbookops.ai/v1",
headers={"Authorization": f"Bearer {os.environ['PLAYBOOKOPS_API_KEY']}"},
timeout=60,
)
def gather(question: str, max_documents: int = 3) -> list[dict]:
"""The documents behind the best passages, best first."""
hits = api.post("/knowledge/search", json={"query": question}).json()["data"]
documents: dict[str, dict] = {}
for hit in hits:
doc_id = hit["document_id"] or hit["file_id"]
if doc_id and doc_id not in documents and len(documents) < max_documents:
documents[doc_id] = api.get(f"/documents/{doc_id}").json()
return list(documents.values())
def prompt(question: str, documents: list[dict]) -> str:
sources = "\n\n".join(
f'\n{d["content"]}\n' for d in documents
)
return (
f"{sources}\n\nAnswer the question using only the documents above. End with "
f'"Sources:" and a Markdown link to each document you used. If they don\'t '
f"answer it, say so.\n\nQuestion: {question}"
)
question = "Can I refund a customer $800 without approval?"
documents = gather(question)
if not documents:
experts = api.post("/knowledge/who-knows", json={"topic": question}).json()["data"]
print("Nothing in PlaybookOps covers that. Try asking:", ", ".join(e["name"] for e in experts[:3]))
else:
print(prompt(question, documents)) # send this to the model of your choice
```
A good answer looks like this:
```markdown
No. Refunds over $500 need a manager's approval before you issue them. Ask in
#support-leads with the order number, and refund once a manager confirms.
Sources:
- [Refunds and credits](https://app.playbookops.ai/playbooks/…)
```
## Make it trustworthy
- **Think about whose key it is.** A bot that answers many people uses one key, so everyone asking sees what that key's owner can see. Make the key from an account that can open only the playbooks every asker should read. If people need different answers based on their own access, have each person connect with their own key instead.
- **Keep a test set.** Write down 20 real questions and the document each should cite. Run them after you change the instructions or reorganize playbooks, and check the citations, not just the wording.
- **Fix the documents, not the prompt.** When an answer is wrong, the cause is usually a missing or unclear document. Fix it in the app and every agent gets better at once.
- **Watch the credits.** Each search uses 1 AI credit; reads are free. Keep one search per question and let the agent read more documents rather than search again. Usage is under **Admin → API**.
## Next
- [Give coding agents your playbooks](https://developers.playbookops.ai/cookbooks/coding-agents) for the same pattern inside Claude Code, Cursor and Codex.
- [Have agents keep docs current](https://developers.playbookops.ai/cookbooks/keep-docs-current) so gaps the agent finds get filled.
---
# Mirror a playbook to files
> Keep a folder of Markdown files in step with your playbooks, fetching only what changed, for tools and pipelines that read files.
Some tools only read files: a coding agent without MCP, a CI job, a static site, your own search index. This recipe keeps a folder of Markdown in step with one or more playbooks. People keep editing in PlaybookOps, and the folder follows.
Each run asks [what changed](https://developers.playbookops.ai/guides/knowledge#keep-up-with-changes) since the last one, including deleted documents, so it's cheap to run every few minutes. Listing and reading are free; they only count toward the [rate limit](https://developers.playbookops.ai/limits-and-credits).
## The script
You need a Read-only key, or a Custom key that can read **Playbooks and documents**, and `pip install httpx`. Save this as `sync_playbooks.py`, fill in `PLAYBOOKS`, and run `python sync_playbooks.py context/`.
```python
"""Mirror PlaybookOps playbooks into a folder of Markdown files.
python sync_playbooks.py context/ # what changed since the last run
python sync_playbooks.py context/ --full # rewrite everything, like after renaming folders
"""
import json
import os
import re
import sys
import time
from pathlib import Path
import httpx
# Playbook id -> folder name
PLAYBOOKS = {
"PLAYBOOK_ID": "engineering",
"ANOTHER_PLAYBOOK_ID": "runbooks",
}
BEGINNING = "2000-01-01T00:00:00Z"
SKIP_STATUSES = {"archived"}
api = httpx.Client(
base_url="https://developers.playbookops.ai/v1",
headers={"Authorization": f"Bearer {os.environ['PLAYBOOKOPS_API_KEY']}"},
timeout=60,
)
def get(path: str, **params) -> dict:
while True:
res = api.get(path, params=params)
if res.status_code == 429:
time.sleep(int(res.headers.get("Retry-After", "5")))
continue
res.raise_for_status()
return res.json()
def safe(name: str) -> str:
return re.sub(r"[^\w .-]+", "-", name).strip(" .") or "untitled"
def folder_paths(playbook_id: str) -> dict:
"""Folder id -> its path on disk, like "Runbooks/Database"."""
folders = get(f"/playbooks/{playbook_id}/folders")["data"]
return {f["id"]: "/".join(safe(part) for part in f["path"].split(" / ")) for f in folders}
def render(doc: dict) -> str:
"""The document as Markdown, with its details as front matter."""
details = {k: doc[k] for k in ("id", "title", "version", "status", "tags", "updated_at", "url")}
front = "\n".join(f"{k}: {json.dumps(v)}" for k, v in details.items())
return f"---\n{front}\n---\n\n# {doc['title']}\n\n{doc['content']}\n"
def file_name(doc: dict) -> str:
slug = re.sub(r"[^a-z0-9]+", "-", doc["title"].lower()).strip("-")[:60] or "untitled"
return f"{slug}-{doc['id'][:8]}.md"
def remove(root: Path, state: dict, doc_id: str) -> None:
path = state["files"].pop(doc_id, None)
if path:
(root / path).unlink(missing_ok=True)
print(f"removed {path}")
def write(root: Path, state: dict, doc: dict, folders: dict) -> None:
sub = folders.get(doc["folder_id"])
path = "/".join(p for p in (PLAYBOOKS[doc["playbook_id"]], sub, file_name(doc)) if p)
old = state["files"].get(doc["id"])
if old and old != path:
(root / old).unlink(missing_ok=True) # renamed or moved
(root / path).parent.mkdir(parents=True, exist_ok=True)
(root / path).write_text(render(doc), encoding="utf-8")
state["files"][doc["id"]] = path
print(f"wrote {path}")
def sync(root: Path, full: bool) -> None:
state_file = root / ".playbookops-sync.json"
state = json.loads(state_file.read_text()) if state_file.exists() else {"since": None, "files": {}}
since = BEGINNING if full or not state["since"] else state["since"]
folders = {}
while True:
page = get("/document-changes", since=since, limit=200)
for change in page["changed"]:
playbook_id = change["playbook_id"]
if playbook_id not in PLAYBOOKS or change["status"] in SKIP_STATUSES:
remove(root, state, change["id"]) # moved elsewhere, or archived
continue
if playbook_id not in folders:
folders[playbook_id] = folder_paths(playbook_id)
try:
doc = get(f"/documents/{change['id']}", full="true")
except httpx.HTTPStatusError as error:
if error.response.status_code != 404:
raise
remove(root, state, change["id"]) # deleted since
continue
write(root, state, doc, folders[playbook_id])
for gone in page["removed"]:
remove(root, state, gone["id"])
since = state["since"] = page["next_since"]
state_file.write_text(json.dumps(state, indent=2))
if not page["has_more"]:
return
if __name__ == "__main__":
sync(Path(sys.argv[1]), full="--full" in sys.argv)
```
Each file starts with the document's details, so tools and people can get back to the source:
```markdown
---
id: "6f1d2c1e-…"
title: "How we deploy the backend"
version: 7
status: "published"
tags: ["deploys"]
updated_at: "2026-11-21T15:04:05Z"
url: "https://app.playbookops.ai/playbooks/…"
---
# How we deploy the backend
Deploys go out from main through the Deploy workflow…
```
## Deleted, moved and archived documents
The change feed reports documents that were deleted or moved to another playbook, and the script removes their files. Archived documents come through as changes with `status: "archived"`; the script removes those too, so take `archived` out of `SKIP_STATUSES` to keep them.
Documents land in subfolders that match their folders in the playbook. Renaming a folder doesn't change its documents, so after reorganizing a playbook, run once with `--full` to rewrite every file in its new place. Removals are kept for 90 days, so if the sync hasn't run in that long, run `--full` too.
## Keep a repo in step
To keep a mirror in a Git repository, for agents that read the repo or as a plain-text backup, run the sync from CI and commit what changed. With GitHub Actions:
```yaml
name: Sync playbooks
on:
schedule:
- cron: "*/30 * * * *"
workflow_dispatch:
jobs:
sync:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install httpx
- run: python scripts/sync_playbooks.py context/
env:
PLAYBOOKOPS_API_KEY: ${{ secrets.PLAYBOOKOPS_API_KEY }}
- run: |
git config user.name "playbookops-sync"
git config user.email "playbookops-sync@users.noreply.github.com"
git add context
git diff --cached --quiet || git commit -m "Sync playbooks" && git push
```
Treat the folder as read-only: edits made there are overwritten on the next sync. Add a `context/README.md` that says so and links to the playbooks.
## Load documents into a prompt
When an agent must always follow a few documents, like coding conventions or a support tone guide, read them when the agent starts instead of syncing files. This is the PlaybookOps version of an `AGENTS.md`:
```python
PINNED = ["DOCUMENT_ID", "ANOTHER_DOCUMENT_ID"]
def pinned_context() -> str:
docs = [get(f"/documents/{doc_id}", full="true") for doc_id in PINNED]
return "\n\n".join(f"# {d['title']}\n\n{d['content']}" for d in docs)
system_prompt = BASE_INSTRUCTIONS + "\n\n" + pinned_context()
```
Reads are free, but cache the result for a few minutes if the agent starts often. Keep it to a handful of short documents, and let the agent [look up](https://developers.playbookops.ai/cookbooks/grounded-answers) the rest.
## Next
- [Move a docs repo into PlaybookOps](https://developers.playbookops.ai/cookbooks/import-a-docs-repo) goes the other way, from files into playbooks.
- [Keeping up with changes](https://developers.playbookops.ai/guides/knowledge#keep-up-with-changes) explains `since`, `next_since` and removals.
---
# Have agents keep docs current
> Agents that fix a runbook step, log what they learned or draft a new document, without overwriting anyone's work.
A context repository is only as good as it is current. Agents are often the first to notice a document is wrong: the runbook step that no longer works, the question nobody has written up. This recipe lets them fix it, safely.
Three rules make agent edits safe:
- **Change a part, not the whole.** Use `edits` to change one section or sentence. People editing other parts of the document in the app keep their work.
- **Send the version you read.** With `base_version`, a change based on an old copy fails with `409 version_conflict` instead of quietly undoing someone's edit.
- **Leave a trail.** Every change is a new version under the key owner's name, and reviewers are asked to review the document again when its body changes. Use a key made for the agent, so its changes are easy to tell apart.
Agents that write need `knowledge:write`. Make a Custom key with **Playbooks and documents** set to **Read and change** and nothing else, so the agent can't touch projects, tasks or anything outside your playbooks. Name it after the agent, and over MCP limit the agent to the document tools it needs (`enabled_tools` in Codex, the toolset `configs` with Claude, `allowed_tools` with OpenAI).
## Fix a step in place
The agent followed a runbook, found a step was wrong, and knows the fix. Over REST, read the document, send a targeted edit with its version, and on a conflict read it again and retry:
```python
import os
import time
import uuid
import httpx
api = httpx.Client(
base_url="https://developers.playbookops.ai/v1",
headers={"Authorization": f"Bearer {os.environ['PLAYBOOKOPS_API_KEY']}"},
timeout=60,
)
def edit_document(document_id: str, edits: list[dict], attempts: int = 3) -> dict:
"""Apply edits to the latest version, re-reading if someone else saved first."""
for _ in range(attempts):
doc = api.get(f"/documents/{document_id}").json()
res = api.patch(
f"/documents/{document_id}",
json={"base_version": doc["version"], "edits": edits},
headers={"Idempotency-Key": str(uuid.uuid4())},
)
if res.status_code == 409 and res.json()["error"]["code"] == "version_conflict":
time.sleep(1)
continue # someone saved in between: read again and retry
if res.is_error:
raise RuntimeError(res.json()["error"]["message"])
return res.json()
raise RuntimeError("The document kept changing; try again later")
edit_document(
"DOCUMENT_ID",
[
{
"op": "replace_text",
"find": "Run `fly deploy` from your laptop.",
"replace": "Run the **Deploy** workflow in GitHub Actions. Deploying from a laptop is no longer allowed.",
}
],
)
```
Edits find their place by text and headings, so retrying them on a newer version usually just works. If an edit no longer applies, because someone already fixed the step, you get `400 edit_failed` saying why, and nothing changes. That's the right outcome. See [edits](https://developers.playbookops.ai/guides/documents#edits) for every kind of change.
## Log what was learned
Some documents grow by adding to them: a known-issues list, an FAQ, a decisions log. An `append` to a section is safe without `base_version`, because it doesn't depend on what else the document says:
```python
api.patch(
"/documents/DOCUMENT_ID",
json={
"edits": [
{
"op": "append",
"section": "Known issues",
"markdown": "- **Health check timeouts after deploy** (Nov 21): the worker needs 90 seconds to warm up. "
"Wait before rolling back. Found by the on-call agent; "
"[@Ana Ruiz](mention://user/PERSON_ID) to confirm.",
}
]
},
headers={"Idempotency-Key": str(uuid.uuid4())},
)
```
Mentioning the document's owner notifies them, so a person checks what the agent added.
## Draft, don't publish
For anything new, have the agent write a draft and let a person decide. Documents are created as drafts unless you say otherwise:
```python
playbook_id = "PLAYBOOK_ID"
api.post(
f"/playbooks/{playbook_id}/documents",
json={
"title": "Rotating the Stripe webhook secret",
"document_type": "procedure",
"tags": ["agent-draft"],
"content": "Written by the on-call agent after the Nov 21 incident. "
"[@Ana Ruiz](mention://user/PERSON_ID) please review.\n\n## Steps\n\n1. …",
},
headers={"Idempotency-Key": str(uuid.uuid4())},
)
```
The `agent-draft` tag makes the agent's drafts easy to find and review together.
## Over MCP
Agents connected over [MCP](https://developers.playbookops.ai/agents/mcp) have the same tools: `read_document`, `update_document` and `create_document`. Tell them how to use them:
```text
When you find that a PlaybookOps document is wrong or missing something:
- Read it with read_document first, and note its version.
- Change only what's wrong, with update_document edits (replace_text or
replace_section) and base_version set to the version you read. Never send
content to replace the whole document.
- If you get version_conflict, read the document again and redo your edit on
the new version.
- For something new, create a draft with create_document, tagged agent-draft,
and mention the playbook's owner so they review it.
- Send an idempotency_key (any new UUID) with every change, and send the same
one if you retry that change after a timeout or error.
- Tell me what you changed, with a link to the document.
```
Most clients ask before running a tool that changes something; keep that on for document changes until you trust the agent. In Codex, `default_tools_approval_mode = "writes"` does this for you.
The `idempotency_key` matters most for appends and new documents: `base_version` already stops an edit from applying twice, but nothing else stops a retried append. See [retries over MCP](https://developers.playbookops.ai/idempotency#over-mcp).
## Next
- [Documents](https://developers.playbookops.ai/guides/documents) covers every field and edit.
- [Answer with citations](https://developers.playbookops.ai/cookbooks/grounded-answers) finds the gaps worth writing up.
---
# Projects and items
> Read a board, add items to it, and keep them up to date.
A project is a board of **items** arranged in **groups**, with **columns** for custom values. The API uses the same words as the app. Reading needs `projects:read`; changing needs `projects:write`.
## Read a board
### Find the project
`GET /v1/projects` lists the projects the key's owner owns or is a member of.
```bash
curl https://developers.playbookops.ai/v1/projects \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY"
```
### Learn its groups and columns
`GET /v1/projects/PROJECT_ID` returns the groups in board order and every column with its type and, for select columns, its options.
```bash
curl https://developers.playbookops.ai/v1/projects/PROJECT_ID \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY"
```
### Read the items
`GET /v1/projects/PROJECT_ID/items` returns items in board order. Filter by group, by title, and by whether they're done:
```bash
curl "https://developers.playbookops.ai/v1/projects/PROJECT_ID/items?group_id=GROUP_ID&include_completed=false&include_subitems=true" \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY"
```
Built-in fields like `status`, `assignee_id`, `due_date` and `priority` are top-level fields on each item. Custom column values are in `values`, keyed by column id. Use the project's `columns` to turn ids into names, and option ids into labels.
To find an item without knowing its project, search by title with `GET /v1/items/search?query=venue`.
## Add an item
`POST /v1/projects/PROJECT_ID/items`:
**curl**
```bash
curl -X POST https://developers.playbookops.ai/v1/projects/PROJECT_ID/items \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $(uuidgen)" \
-d '{
"title": "Call the venue",
"group_id": "GROUP_ID",
"assignee_id": "PERSON_ID",
"due_date": "2026-12-05",
"priority": "high",
"values": { "COLUMN_ID": "Ask about parking" }
}'
```
**Python**
```python
import uuid
item = api.post(
f"/projects/{project_id}/items",
headers={"Idempotency-Key": str(uuid.uuid4())},
json={
"title": "Call the venue",
"group_id": group_id,
"assignee_id": person_id,
"due_date": "2026-12-05",
"priority": "high",
"values": {column_id: "Ask about parking"},
},
).json()
print(item["url"])
```
**JavaScript**
```javascript
const res = await fetch(`${base}/projects/${projectId}/items`, {
method: "POST",
headers: { ...headers, "Content-Type": "application/json", "Idempotency-Key": crypto.randomUUID() },
body: JSON.stringify({
title: "Call the venue",
group_id: groupId,
assignee_id: personId,
due_date: "2026-12-05",
priority: "high",
values: { [columnId]: "Ask about parking" },
}),
});
const item = await res.json();
```
- Without `group_id`, the item goes in the project's first group.
- With `parent_id`, it's a subitem, in its parent's group.
- `values` takes column ids or column keys, and each value is checked against its column's type, as in the app.
- `assignee_id` is a person's `id` from `GET /v1/people`.
## Update an item
`PATCH /v1/items/ITEM_ID` changes only the fields you send. Send `null` to clear one:
```json
{ "status": "in_progress", "due_date": null, "values": { "COLUMN_ID": null } }
```
Send `group_id` to move the item to another group in the same project.
## Move it to another project
`POST /v1/items/ITEM_ID/move` with a `project_id`, and optionally a `group_id`. Subitems go with it, and column values carry over to columns with the same name and type.
## Complete it and post an update
```bash
# Mark it done
curl -X POST https://developers.playbookops.ai/v1/items/ITEM_ID/complete \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY" -H "Content-Type: application/json" -d '{}'
# Reopen it
curl -X POST https://developers.playbookops.ai/v1/items/ITEM_ID/complete \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY" -H "Content-Type: application/json" -d '{"completed": false}'
# Post an update that mentions someone
curl -X POST https://developers.playbookops.ai/v1/items/ITEM_ID/comments \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY" -H "Content-Type: application/json" \
-d '{"body": "Booked for the 5th. [@Bea](mention://user/PERSON_ID) can you confirm?"}'
```
Updates on an item are listed by `GET /v1/items/ITEM_ID/comments`.
> **Changes behave like the app's**
> Assignees and mentioned people are notified, automations watching the project run, and the item's activity shows who made the change. Project viewers can read a project but can't change it.
## Archive or delete it
`POST /v1/items/ITEM_ID/archive` archives an item and its subitems. They drop out of the project's lists, and the item's `archived_at` is set. List them with `GET /v1/projects/PROJECT_ID/items?archived=true`, and bring one back with `POST /v1/items/ITEM_ID/restore`.
`DELETE /v1/items/ITEM_ID` removes the item, its subitems and its updates for good. The answer is `{"id": "ITEM_ID", "deleted": true}`.
> **Deleting can't be undone**
> Archive unless the item should be gone completely. Send an `Idempotency-Key` with deletes too: a retry with the same key gets the first answer instead of a `404`. Over MCP, `delete_item` is marked as destructive, so clients that ask before running such tools will ask.
## Reference
| Action | Endpoint | MCP tool |
| --- | --- | --- |
| List projects | `GET /v1/projects` | `list_projects` |
| Groups and columns | `GET /v1/projects/{id}` | `get_project` |
| List items | `GET /v1/projects/{id}/items` | `list_items` |
| Search items | `GET /v1/items/search` | `search_items` |
| One item | `GET /v1/items/{id}` | `get_item` |
| Add an item | `POST /v1/projects/{id}/items` | `create_item` |
| Update an item | `PATCH /v1/items/{id}` | `update_item` |
| Move an item | `POST /v1/items/{id}/move` | `move_item` |
| Complete or reopen | `POST /v1/items/{id}/complete` | `complete_item` |
| Updates | `GET` and `POST /v1/items/{id}/comments` | `list_item_comments`, `add_item_comment` |
| Archive an item | `POST /v1/items/{id}/archive` | `archive_item` |
| Restore an item | `POST /v1/items/{id}/restore` | `restore_item` |
| Delete an item | `DELETE /v1/items/{id}` | `delete_item` |
Every parameter is in the [API reference](https://developers.playbookops.ai/reference/projects-and-items).
---
# Tasks
> Everything assigned to you across projects, and your personal tasks.
The task endpoints work on the key owner's own work: items assigned to them in any project, plus personal tasks that aren't in a project. They're a good fit for personal assistants and daily digests, because a key only needs `tasks` scopes, not access to whole projects.
## See what's on your plate
`GET /v1/tasks/mine` needs `tasks:read`. It sorts everything assigned to you into `overdue`, `due_today`, `upcoming` and `no_due_date`:
**curl**
```bash
curl https://developers.playbookops.ai/v1/tasks/mine \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY"
```
**Python**
```python
tasks = api.get("/tasks/mine").json()
for task in tasks["overdue"] + tasks["due_today"]:
print(f"{task['title']} (due {task['due_date']}) {task['url']}")
```
Add `include_completed=true` to include finished ones.
## Personal tasks
With `tasks:write`:
| Call | What it does |
| --- | --- |
| `POST /v1/tasks` | Creates a task outside any project. It's yours unless you pass `assignee_id`. |
| `PATCH /v1/tasks/TASK_ID` | Updates a personal task, or a project item assigned to you. |
| `POST /v1/tasks/TASK_ID/complete` | Completes it, or reopens it with `{"completed": false}`. |
| `DELETE /v1/tasks/TASK_ID` | Deletes a personal task and its subtasks for good. Project items and workflow run steps can't be deleted this way. |
```bash
curl -X POST https://developers.playbookops.ai/v1/tasks \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY" -H "Content-Type: application/json" \
-d '{"title": "Renew the domain", "due_date": "2026-12-01", "priority": "urgent"}'
```
To change project items that aren't assigned to you, use the [item endpoints](https://developers.playbookops.ai/guides/projects-and-items) with a `projects:write` key.
## Reference
| Action | Endpoint | MCP tool |
| --- | --- | --- |
| Your tasks | `GET /v1/tasks/mine` | `my_tasks` |
| Add a task | `POST /v1/tasks` | `create_task` |
| Update a task | `PATCH /v1/tasks/{id}` | `update_task` |
| Complete or reopen | `POST /v1/tasks/{id}/complete` | `complete_task` |
| Delete a personal task | `DELETE /v1/tasks/{id}` | `delete_task` |
Every parameter is in the [API reference](https://developers.playbookops.ai/reference/tasks).
---
# Knowledge
> Search your playbooks and documents, read them, and find who knows about a topic.
Everything here needs `knowledge:read`, and only returns what the key's owner can open in the app. To write documents, see [Documents](https://developers.playbookops.ai/guides/documents).
## Answer a question from your documents
### Search
`POST /v1/knowledge/search` finds the passages that best answer a question. Ask a whole question: search matches meaning, not just words.
**curl**
```bash
curl -X POST https://developers.playbookops.ai/v1/knowledge/search \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY" -H "Content-Type: application/json" \
-d '{"query": "How do we handle refunds over $500?"}'
```
**Python**
```python
results = api.post("/knowledge/search", json={"query": "How do we handle refunds over $500?"}).json()
for hit in results["data"]:
print(hit["title"], hit["url"])
print(hit["passage"])
```
```json
{
"data": [
{
"document_id": "…",
"title": "Refunds and credits",
"passage": "Refunds over $500 need a manager's approval…",
"similarity": 0.87,
"playbook_name": "Support",
"url": "https://app.playbookops.ai/playbooks/…"
}
],
"credits_used": 1
}
```
### Read the document
If the passage isn't enough, `GET /v1/documents/DOCUMENT_ID` returns the whole document as Markdown. Documents over 24,000 characters are cut off, with `truncated: true`; add `?full=true` for all of it.
### Find someone to ask
When the documents don't cover it, `POST /v1/knowledge/who-knows` with a topic returns the people who know about it, and why.
```bash
curl -X POST https://developers.playbookops.ai/v1/knowledge/who-knows \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY" -H "Content-Type: application/json" \
-d '{"topic": "payroll"}'
```
> **Search and who knows use AI credits**
> Each call uses 1 AI credit from your organization, and says so in `credits_used`. Everything else on this page is free. See [limits and credits](https://developers.playbookops.ai/limits-and-credits).
## Browse
- `GET /v1/playbooks?search=onboarding` lists playbooks, with how many documents each has.
- `GET /v1/playbooks/PLAYBOOK_ID/folders` lists a playbook's folders, each with its path, like `Runbooks / Database`.
- `GET /v1/content?kinds=document&playbook_id=PLAYBOOK_ID` lists documents, files, flowcharts, videos and more, most recently changed first.
## Organize
With `knowledge:write`, a key can set up the structure documents go in. The key's owner needs a role above viewer.
- `POST /v1/playbooks` with a `name` and `description` makes a playbook. Everyone in the organization can see it until someone limits access in the app.
- `POST /v1/playbooks/PLAYBOOK_ID/folders` with a `name`, and a `parent_folder_id` to nest it, makes a folder. Folders go up to six levels deep, and need edit access to the playbook.
```bash
curl -X POST https://developers.playbookops.ai/v1/playbooks/PLAYBOOK_ID/folders \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY" -H "Content-Type: application/json" \
-H "Idempotency-Key: folder:runbooks" \
-d '{"name": "Runbooks"}'
```
## Keep up with changes
`GET /v1/document-changes?since=TIME` returns what happened to documents after a time, for keeping a copy somewhere else in step: a folder of Markdown files, a search index, an agent's cache.
```json
{
"changed": [
{ "id": "…", "title": "Restore a backup", "playbook_id": "…", "folder_id": "…", "version": 4, "status": "published", "updated_at": "2026-11-21T18:02:11Z", "url": "…" }
],
"removed": [
{ "id": "…", "playbook_id": "…", "removed_at": "2026-11-21T18:05:40Z" }
],
"has_more": false,
"next_since": "2026-11-21T18:09:00Z"
}
```
- `changed` has documents created or edited, oldest change first. Read the ones you need with `GET /v1/documents/{id}`. Archived documents show up here with `status: "archived"`.
- `removed` has documents deleted, or moved to another playbook, including every document in a deleted playbook. Removals are kept for 90 days, so poll more often than that.
- Send `next_since` as `since` next time. When `has_more` is true, ask again straight away. Answers overlap a little so nothing is missed between polls, so treat a document you've already seen as a no-op.
- Add `playbook_id` to follow one playbook.
## Reference
| Action | Endpoint | MCP tool |
| --- | --- | --- |
| Search | `POST /v1/knowledge/search` | `search_knowledge` |
| Who knows | `POST /v1/knowledge/who-knows` | `who_knows` |
| Read a document | `GET /v1/documents/{id}` | `read_document` |
| Create a document | `POST /v1/playbooks/{id}/documents` | `create_document` |
| Change a document | `PATCH /v1/documents/{id}` | `update_document` |
| Playbooks | `GET /v1/playbooks` | `list_playbooks` |
| Create a playbook | `POST /v1/playbooks` | `create_playbook` |
| Folders | `GET /v1/playbooks/{id}/folders` | `list_folders` |
| Create a folder | `POST /v1/playbooks/{id}/folders` | `create_folder` |
| Content | `GET /v1/content` | `list_content` |
| What changed | `GET /v1/document-changes` | `list_document_changes` |
Every parameter is in the [API reference](https://developers.playbookops.ai/reference/knowledge).
---
# Documents
> Create playbook documents from Markdown, then change them safely: replace the body or patch one section at a time.
Documents are written in Markdown, in the API and in the app. Whatever you send is what people see in the editor, with the same headings, checklists, callouts, tables and mentions. [Writing in Markdown](https://developers.playbookops.ai/guides/markdown) shows the syntax for each kind of content.
Writing needs the `knowledge:write` scope, and the key's owner needs a role above viewer and edit access to the playbook. Reading needs `knowledge:read`.
## Create a document
### Pick a playbook
Documents live in playbooks. `GET /v1/playbooks` lists the ones the key's owner can see; use the `id`.
### Post the Markdown
`POST /v1/playbooks/PLAYBOOK_ID/documents` with a title and the body in `content`.
**curl**
```bash
curl -X POST https://developers.playbookops.ai/v1/playbooks/PLAYBOOK_ID/documents \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY" -H "Content-Type: application/json" \
-H "Idempotency-Key: $(uuidgen)" \
-d @- <<'JSON'
{
"title": "Refund policy",
"document_type": "policy",
"status": "published",
"tags": ["support"],
"content": "## Who can ask\n\nAnyone who paid in the last 30 days.\n\n:::note\nRefunds over $500 need a manager's approval.\n:::\n\n## How to refund\n\n1. Find the payment in Stripe\n2. Refund it to the original card\n3. Reply to the customer"
}
JSON
```
**Python**
```python
from pathlib import Path
import uuid
doc = api.post(
f"/playbooks/{playbook_id}/documents",
json={
"title": "Refund policy",
"document_type": "policy",
"status": "published",
"content": Path("refund-policy.md").read_text(),
},
headers={"Idempotency-Key": str(uuid.uuid4())},
).json()
print(doc["id"], doc["version"], doc["url"])
```
**JavaScript**
```js
import { readFile } from "node:fs/promises";
const res = await fetch(`https://developers.playbookops.ai/v1/playbooks/${playbookId}/documents`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.PLAYBOOKOPS_API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": crypto.randomUUID(),
},
body: JSON.stringify({
title: "Refund policy",
content: await readFile("refund-policy.md", "utf8"),
}),
});
const doc = await res.json();
```
You get the document back with its `id`, `version` (1) and a `url` that opens it in the app.
Optional fields:
| Field | What it does |
| --- | --- |
| `description` | A one-line summary shown in lists. |
| `document_type` | `sop`, `process`, `training`, `policy`, `procedure`, `manual`, `workflow`, `internal_document`, `job_description`, `project_plan`, `proven_process` or `general` (the default). It can't change later. |
| `status` | `draft` (the default) or `published`. A label in the app; it doesn't change who can see the document. |
| `tags` | Up to 20. |
| `folder_id` | A folder in the same playbook. Leave it out for the top level. |
> **Retries are safe**
> Send an `Idempotency-Key` with every create. If the connection drops and you retry with the same key, you get the first document back instead of a duplicate. See [idempotency](https://developers.playbookops.ai/idempotency).
## Read it back
`GET /v1/documents/DOCUMENT_ID` returns the Markdown in `content` and the current `version`. Long documents are cut at 24,000 characters with `truncated: true`; add `?full=true` to get all of it.
```json
{
"id": "6f1d2c1e-…",
"title": "Refund policy",
"kind": "policy",
"content": "## Who can ask\n\nAnyone who paid in the last 30 days.\n\n…",
"truncated": false,
"version": 1,
"status": "published",
"playbook_id": "…",
"folder_id": null,
"tags": ["support"],
"updated_at": "2026-11-21T15:04:05Z",
"url": "https://app.playbookops.ai/playbooks/…?content=document&contentId=…"
}
```
## Change a document
`PATCH /v1/documents/DOCUMENT_ID` changes what you send and leaves the rest alone. Every change that touches the body or details saves a new version in the document's history.
There are two ways to change the body:
- **`content`** replaces the whole body. Use it when your system owns the document, like a policy generated from another source.
- **`edits`** change part of it: one section, one sentence, or something added at the end. Use them when people also edit the document in the app, so you don't undo their work.
### Edits
Edits find their place by heading text or by exact text, never by line numbers, so they still work after someone adds a paragraph elsewhere.
| `op` | Fields | What it does |
| --- | --- | --- |
| `replace_section` | `section`, `markdown` | Replaces everything under a heading, subsections included. The heading stays. |
| `append` | `markdown`, optional `section` | Adds to the end of the document, or to the end of that section. |
| `insert` | `markdown`, and `before` or `after` | Adds blocks just before a section's heading, or just after the section ends. |
| `remove_section` | `section` | Deletes a heading and everything under it. |
| `replace_text` | `find`, `replace`, optional `all` | Swaps exact text, including its Markdown. It must appear once unless `all` is `true`. Use it to fix a sentence or rename a heading. |
A `section` is a heading's text, with or without its `#`s, ignoring case. A section runs until the next heading of the same or a higher level, so `## Day one` includes its `### Steps`. If two headings share a name, give the path: `Day two > Steps`. Headings inside code blocks don't count.
```bash
curl -X PATCH https://developers.playbookops.ai/v1/documents/DOCUMENT_ID \
-H "Authorization: Bearer $PLAYBOOKOPS_API_KEY" -H "Content-Type: application/json" \
-H "Idempotency-Key: $(uuidgen)" \
-d '{
"base_version": 3,
"edits": [
{ "op": "replace_section", "section": "Who can ask", "markdown": "Anyone who paid in the last 60 days." },
{ "op": "insert", "after": "Who can ask", "markdown": "## Exceptions\n\n- Gift cards can'\''t be refunded" },
{ "op": "replace_text", "find": "Refund it to the original card", "replace": "Refund it to the original payment method" },
{ "op": "append", "markdown": "## Questions\n\nAsk [@Ana Ruiz](mention://user/PERSON_ID)." }
]
}'
```
Edits apply in order, each to the result of the one before, and they're all or nothing: if one can't apply, nothing changes and you get a `400` with the code `edit_failed`, saying which edit failed and why. Here the second edit misspelled a heading:
```json
{
"error": {
"code": "edit_failed",
"message": "Edit 2 (insert): There's no heading called \"Exeptions\". Headings: \"Who can ask\", \"How to refund\"."
}
}
```
### Details
The same call changes `title`, `description`, `tags` (replaces them all) and `folder_id` (`null` moves it to the top level). `status` can be `draft`, `published` or `archived`, and only the document's owner can change it. You can send details with or without a body change.
## Don't overwrite someone else's change
Send the `version` you read as `base_version`. If anyone changed the document since, nothing is saved and you get a `409`:
```json
{
"error": {
"code": "version_conflict",
"message": "The document is at version 5, not 4. Read it again, then make your change on the latest version."
}
}
```
Read the document again, check your edits still make sense, and send them with the new version. Without `base_version`, edits still apply to whatever the document says now, which is usually what you want for small appends; `content` without it replaces whatever is there.
## What happens in the app
Saves through the API work like saves in the editor:
- A new version is added to the document's history, under the key owner's name.
- Search catches up within a minute or so.
- People and groups you [mention](https://developers.playbookops.ai/guides/markdown#mentions) for the first time get a notification. Mentions already in the previous version don't notify again.
- If people had confirmed they'd reviewed the document, a body change asks them to review it again.
- A body that doesn't actually change doesn't create a version.
## With an AI agent
Over [MCP](https://developers.playbookops.ai/agents/mcp) the same actions are the `create_document` and `update_document` tools, with the same fields. Agents do best when you ask them to read first and patch sections rather than rewrite:
```text
Read the "Refund policy" document. Change the refund window to 60 days and add
an Exceptions section after "Who can ask" saying gift cards can't be refunded.
Use update_document with edits and base_version; don't rewrite the whole document.
```
## Reference
| Action | Endpoint | MCP tool |
| --- | --- | --- |
| Create a document | `POST /v1/playbooks/{playbook_id}/documents` | `create_document` |
| Read a document | `GET /v1/documents/{id}` | `read_document` |
| Change a document | `PATCH /v1/documents/{id}` | `update_document` |
| Find a playbook | `GET /v1/playbooks` | `list_playbooks` |
| Create a playbook | `POST /v1/playbooks` | `create_playbook` |
| Find or create a folder | `GET` or `POST /v1/playbooks/{playbook_id}/folders` | `list_folders`, `create_folder` |
| Find a document | `GET /v1/content?kinds=document` | `list_content` |
| What changed | `GET /v1/document-changes` | `list_document_changes` |
Every field is in the [API reference](https://developers.playbookops.ai/reference/knowledge).
---
# Writing in Markdown
> The Markdown PlaybookOps documents understand, for every kind of content: headings, checklists, tables, callouts, toggles, images, video, mentions and links.
PlaybookOps stores every document as Markdown. What you send to [create or change a document](https://developers.playbookops.ai/guides/documents) is exactly what the editor opens, so anything on this page round-trips: people can edit your document in the app, and you can read it back and patch it again.
It's [GitHub-flavored Markdown](https://github.github.com/gfm/) with a few additions for callouts, toggles, alignment, media and mentions. Where it differs from GitHub, this page says so.
> **Start from the app**
> The quickest way to see the Markdown for something is to make it in the editor and read the document back with `GET /v1/documents/{id}`. The `content` you get is the source.
## Structure
The document's title is its own field, so the body doesn't need to repeat it. Start with a short introduction, then use `##` headings for the main parts.
```markdown
A one-paragraph summary of what this is for and who uses it.
## Before you start
## Steps
### Taking the call
### Logging it
## If something goes wrong
```
- Headings go from `#` to `######`. The toolbar offers four levels, so stick to `##`, `###` and `####` for documents people will edit.
- `##` headings are the sections that [patches](https://developers.playbookops.ai/guides/documents#edits) and the in-app assistant work with. A section includes the smaller headings under it.
- Keep heading names unique where you can. Patches can still reach a repeated name by its path, like `Day two > Steps`.
## Paragraphs and line breaks
A blank line starts a new paragraph. A single line break is kept as a line break, unlike on GitHub, so you can write an address or a short poem line by line.
```markdown
Send returns to:
Acme Warehouse
12 Dock Road
This starts a new paragraph.
```
The editor saves a line break as two spaces at the end of the line. Both forms mean the same thing.
## Text styles
| Style | Markdown |
| --- | --- |
| Bold | `**bold**` |
| Italic | `*italic*` |
| Strikethrough | `~~struck~~` |
| Inline code | `` `code` `` |
| Underline | `underlined` |
| Highlight | `highlighted` |
| Colored highlight | `…`, also `blue`, `pink` or `purple` |
There's no font color. Emoji work as they are (✅ 🚚), but `:shortcodes:` stay as text.
## Lists and checklists
```markdown
- Bullets start with a dash
- Indent two spaces to nest
- Another point
1. Numbered steps
2. Count themselves
- Indent three spaces under a number
- [ ] An open checklist item
- [x] A done one
- [ ] Checklists nest too
```
When someone ticks an item in the editor, it's saved as `[x]`.
## Quotes
```markdown
> Every refund over $500 needs a manager's approval.
> A second line stays in the same quote.
```
## Code
Fence code with three backticks and name the language for coloring.
~~~markdown
```bash
curl https://example.com/health
```
~~~
The editor offers `bash`, `shell`, `powershell`, `python`, `javascript`, `typescript`, `jsx`, `tsx`, `json`, `yaml`, `sql`, `html`, `xml`, `css`, `scss`, `markdown`, `dockerfile`, `java`, `go`, `rust`, `c`, `cpp`, `php`, `ruby`, `swift` and `kotlin`. Use fences rather than indenting code by four spaces.
## Tables
```markdown
| Plan | Refund window | Who approves |
| --- | --- | --- |
| Monthly | 30 days | Support |
| Annual | 60 days | **Finance** |
```
Tables need a header row. Cells hold one line of text with styles, links and mentions, but not lists or several paragraphs. Column alignment (`:---:`) isn't kept once someone edits the document in the app.
## Dividers
A line with `---` on its own, with a blank line above it, draws a divider. Without the blank line it turns the line above into a heading.
## Callouts
Callouts box a note, tip or warning. Open with `:::` and the type, close with `:::` on its own line.
```markdown
:::note
Refunds go back to the original payment method.
:::
:::caution
Don't refund a payment that's still disputed in Stripe.
1. Check the Disputes tab first
2. If there's a dispute, hand it to Finance
:::
```
| Type | Use it for |
| --- | --- |
| `note` | Useful context |
| `tip` | A better way to do something |
| `info` | Background or a reference |
| `caution` | Something that can go wrong |
| `danger` | Something that can't be undone |
A callout can hold anything: paragraphs, lists, tables, code, even another callout. Other types, titles like `:::note[Heads up]` and GitHub's `> [!NOTE]` aren't supported; the title is dropped when the document is edited, and `> [!NOTE]` stays a plain quote.
## Toggles
A toggle hides detail until someone opens it. Put a blank line after `` and before ``.
```markdown
What if the customer paid by bank transfer?
Ask Finance to send the refund. It takes 3 to 5 working days.
```
`` starts it open. The summary is plain text; the body is any Markdown.
## Alignment
Center, right-align or justify paragraphs and headings by wrapping them:
```markdown
:::center
## Welcome to the team
We're glad you're here.
:::
```
Use `center`, `right`, `justify` or `left`. It applies to text, not images or tables, and works inside callouts.
## Links
```markdown
[Stripe dashboard](https://dashboard.stripe.com)
```
Links to other sites open in a new tab. Links to things in PlaybookOps open in the app and show as a chip with the item's live name. Write them as paths, without the domain:
| Link to | Markdown |
| --- | --- |
| A document | `[Refund policy](https://developers.playbookops.ai/playbooks/PLAYBOOK_ID?content=document&contentId=DOCUMENT_ID)` |
| A project | `[Spring launch](https://developers.playbookops.ai/projects/PROJECT_ID)` |
| An item or task | `[Call the venue](https://developers.playbookops.ai/projects/PROJECT_ID?task=ITEM_ID)` |
| A workflow | `[Onboarding](https://developers.playbookops.ai/workflows/WORKFLOW_ID)` |
| A course | `[New starter course](https://developers.playbookops.ai/learning/COURSE_ID)` |
| A flowchart, video or file | `/playbooks/PLAYBOOK_ID?content=flowchart&contentId=ID`, with `image`, `audio`, `video`, `pdf`, `word_document` or `powerpoint` in place of `flowchart` |
The `url` fields the API returns are full links. Drop the `https://app.playbookops.ai` part to get the path.
## Mentions
Mention a person or a group to notify them and show their name as a chip:
```markdown
Questions go to [@Ana Ruiz](mention://user/PERSON_ID) or [@Support team](mention://group/GROUP_ID).
```
- Get people's ids from `GET /v1/people`.
- The name after `@` is what people see on the chip, so use their current name. Leave out `[`, `]`, `(` and `)`.
- People are notified the first time they're mentioned in a document, when you create it or when a change adds them. They must be active members of your organization; other ids are left as text and nobody is notified.
## Images
```markdown

```
- Use a public `https` link. It shows in the app and is included when someone exports the document to PDF or Word.
- Images uploaded in the app live in private storage. When you read a document you get temporary links to them; send them back as they are and they keep working.
- There's no size or alignment option. Images fit the page width.
## Video and audio
```markdown
::media{kind="video" src="https://www.youtube.com/watch?v=VIDEO_ID" title="How to issue a refund"}
::media{kind="audio" src="https://example.com/calls/refund-call.mp3" title="A good refund call"}
```
- `kind` is `video` or `audio`, and `src` must be `https`.
- YouTube, Vimeo and Loom links play in their own player. Other links play as a file, so point them at the video or audio file itself.
- Put each one on its own line. PDF and Word exports don't play media, and show the line as text.
## Not supported
These have no Markdown in PlaybookOps yet. They're kept as text, so nothing is lost, but they won't look special:
- Diagrams, like Mermaid. A `mermaid` code block shows as code; make a flowchart in the playbook and [link to it](#links) instead.
- Math, footnotes, columns and text color.
- Embedded pages (`