# 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'<document title="{d["title"]}" url="{d["url"]}">\n{d["content"]}\n</document>' 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.
