Developer docs

Claude Agent SDK recipe

Give a Claude Agent SDK agent the redact-pdf tools: redact a PDF before it leaves the company, or pseudonymize, work on the tagged text and restore names locally.

Claude Agent SDK

Give an agent built with the Claude Agent SDK the Redact PDF AI tools through the local MCP server (npx -y redact-pdf-mcp@0.6.0, pinned exactly in the example). The server reads the PDF from disk by path, so the document never goes into the prompt.

Tested with claude-agent-sdk 0.2.x (Python). Runnable file: https://github.com/dambuchs/redact-pdf-mcp/tree/main/examples/claude-agent-sdk.

Setup

pip install claude-agent-sdk      # Node.js 20+ is needed for npx
export ANTHROPIC_API_KEY=...
export REDACT_PDF_API_KEY=...     # Dashboard -> Settings -> API keys

The MCP server is passed in mcp_servers; its tools are named mcp__redact-pdf__<tool>.

  • tools is the set of built-in tools that exist for the agent: none for the redact task, only Read and Write for the summary.

  • allowed_tools approves the listed tools without asking. It does not hide other tools, and it does not limit paths.

  • PreToolUse hooks decide every argument:

    • redact_pdf_and_wait gets its whole input replaced (updatedInput): this file, the task's mode, ephemeral retention, all eight categories.
    • restore_names gets its input replaced with the summary file and this document's correspondence table, with no output_path.
    • Write may write only <name>-summary.md.
    • Read may open only <name>-redacted.md, the tagged text the server writes when a document is too long to return inline.

    Only the tools of the task get a hook, because a hook's "allow" runs a tool even when it is not in allowed_tools. So text in the document that tells the agent to read the table, or to restore names into a file it can read, gets nowhere.

The two patterns

  1. Redact before a document leaves the company: the agent calls redact_pdf_and_wait and reports the -redacted.pdf path.
  2. Pseudonymize → work → restore names: the agent calls redact_pdf_and_wait with mode: "pseudonymize", works only from document_text, writes its result with Write, then calls restore_names with that file and correspondence_path. The real names go back into a copy on your disk; the model never sees the detected names.
"""Claude Agent SDK + the local redact-pdf-mcp server.

    pip install claude-agent-sdk          # needs Node.js 20+ for npx
    export ANTHROPIC_API_KEY=...          # or another auth method the SDK supports
    export REDACT_PDF_API_KEY=...

    # 1. Redact before a document leaves the company
    python agent.py redact /abs/path/contract.pdf

    # 2. Pseudonymize -> summarize -> restore names, without Claude seeing a name
    python agent.py summarize /abs/path/contract.pdf

The MCP server reads the file from disk by path and writes its outputs next to
it, so the document itself never goes into the prompt. It never overwrites a
file, so the script refuses to start while outputs of an earlier run (including
the -correspondence.csv) are still next to the PDF: use a fresh copy per run.

The document's text reaches the model (as tags in pseudonymize mode), and text
inside a document can try to steer an agent. So the hooks below decide every
file path and argument; the model only decides when to call the tools.
"""

from __future__ import annotations

import asyncio
import os
import sys
from pathlib import Path

from claude_agent_sdk import ClaudeAgentOptions, HookMatcher, ResultMessage, query

SERVER = "redact-pdf"
REDACT_TOOL = f"mcp__{SERVER}__redact_pdf_and_wait"
RESTORE_TOOL = f"mcp__{SERVER}__restore_names"
REDACT_PDF = {
    "command": "npx",
    "args": ["-y", "redact-pdf-mcp@0.6.0"],  # exact version; bump it when you upgrade
    "env": {
        "REDACT_PDF_API_KEY": os.environ.get("REDACT_PDF_API_KEY", ""),
        "REDACT_PDF_BASE_URL": os.environ.get("REDACT_PDF_BASE_URL", "https://www.redact-pdf.ai"),
    },
}

# Every category, so the account's saved dashboard categories cannot leave names
# (or IBANs, dates...) in the text the model reads. Drop one only on purpose.
ALL_CATEGORIES = ["Person", "Email", "PhoneNumber", "Address", "Organization", "Date", "IBAN", "CreditCard"]


def _decision(allowed: bool, reason: str = "", updated: dict | None = None) -> dict:
    output = {"hookEventName": "PreToolUse", "permissionDecision": "allow" if allowed else "deny"}
    if reason:
        output["permissionDecisionReason"] = reason
    if updated is not None:
        output["updatedInput"] = updated
    return {"hookSpecificOutput": output}


def outputs(pdf: Path) -> dict[str, Path]:
    """Every file a run writes next to the PDF."""
    return {
        "redacted": pdf.with_name(f"{pdf.stem}-redacted.pdf"),
        "text": pdf.with_name(f"{pdf.stem}-redacted.md"),  # written only for long documents
        "table": pdf.with_name(f"{pdf.stem}-correspondence.csv"),  # real names: never readable
        "summary": pdf.with_name(f"{pdf.stem}-summary.md"),
        "restored": pdf.with_name(f"{pdf.stem}-summary-restored.md"),
    }


def refuse_leftovers(pdf: Path) -> None:
    # Checked before anything is uploaded or billed. A leftover table would
    # otherwise be used to restore names from another run's document.
    left = [str(path) for path in outputs(pdf).values() if path.exists()]
    if left:
        sys.exit("Outputs of an earlier run are still there; move them away first:\n" + "\n".join(left))


def guard(pdf: Path, mode: str) -> dict:
    """PreToolUse hooks that pin every path and argument to this one document.
    Only the tools of this task get a hook: an "allow" from a hook would run a
    tool even if it is not in allowed_tools."""
    pdf = pdf.resolve()
    paths = outputs(pdf)
    text_file, table, summary = paths["text"], paths["table"], paths["summary"]

    def target(hook_input) -> Path:
        return Path(hook_input["tool_input"].get("file_path", "")).resolve()

    async def redact(_hook_input, _tool_use_id, _context):
        # The whole input is replaced: no other file, no studio retention, no
        # category left out, whatever the model wrote.
        return _decision(
            True,
            updated={"file_path": str(pdf), "mode": mode, "retention": "ephemeral", "pii_categories": ALL_CATEGORIES},
        )

    async def restore(_hook_input, _tool_use_id, _context):
        # No output_path: the server writes <stem>-summary-restored.md, a path
        # the Read hook never allows.
        return _decision(True, updated={"file_path": str(summary), "correspondence_path": str(table)})

    async def read_tagged_text_only(hook_input, _tool_use_id, _context):
        ok = target(hook_input) == text_file
        return _decision(ok, "" if ok else f"Only {text_file} may be read.")

    async def write_summary_only(hook_input, _tool_use_id, _context):
        ok = target(hook_input) == summary
        return _decision(ok, "" if ok else f"Only {summary} may be written.")

    matchers = [HookMatcher(matcher=REDACT_TOOL, hooks=[redact], on_failure="block")]
    if mode == "pseudonymize":
        matchers += [
            HookMatcher(matcher=RESTORE_TOOL, hooks=[restore], on_failure="block"),
            HookMatcher(matcher="Read", hooks=[read_tagged_text_only], on_failure="block"),
            HookMatcher(matcher="Write", hooks=[write_summary_only], on_failure="block"),
        ]
    return {"PreToolUse": matchers}


def options(pdf: Path, mode: str, builtin_tools: list[str], mcp_tools: list[str], system_prompt: str) -> ClaudeAgentOptions:
    return ClaudeAgentOptions(
        system_prompt=system_prompt,
        tools=builtin_tools,  # the only built-in tools that exist for this agent
        mcp_servers={SERVER: REDACT_PDF},
        allowed_tools=mcp_tools + builtin_tools,  # auto-approved; the hooks still decide paths
        hooks=guard(pdf, mode),
        setting_sources=[],  # ignore local .claude settings and .mcp.json
        cwd=str(pdf.parent),
        max_turns=12,
    )


async def run(prompt: str, opts: ClaudeAgentOptions) -> str:
    result = ""
    async for message in query(prompt=prompt, options=opts):
        if isinstance(message, ResultMessage):
            result = message.result or message.subtype
    return result


async def redact_before_sending(pdf: Path) -> str:
    refuse_leftovers(pdf)
    opts = options(
        pdf,
        mode="redact",
        builtin_tools=[],
        mcp_tools=[REDACT_TOOL],
        system_prompt=(
            "You prepare documents to be sent outside the company. Redact the file the "
            "user names with redact_pdf_and_wait and report output_path."
        ),
    )
    return await run(f"Redact {pdf} before I send it to the buyer's agent.", opts)


async def pseudonymize_summarize_restore(pdf: Path) -> str:
    refuse_leftovers(pdf)
    summary = outputs(pdf)["summary"]
    opts = options(
        pdf,
        mode="pseudonymize",
        builtin_tools=["Read", "Write"],
        mcp_tools=[REDACT_TOOL, RESTORE_TOOL],
        system_prompt=(
            "You work on confidential documents without seeing the real names.\n"
            "1. Call redact_pdf_and_wait with the file path and mode 'pseudonymize'.\n"
            "2. Work only from document_text, or read the file at document_text_path. "
            "Keep every tag such as [Person 1] exactly as written.\n"
            f"3. Write your result to {summary} with the Write tool.\n"
            "4. Call restore_names with that file and correspondence_path. If it reports "
            "0 replacements, say so. Report the restored file's path; do not open it."
        ),
    )
    return await run(f"Summarize the obligations of each party in {pdf}.", opts)


if __name__ == "__main__":
    if len(sys.argv) != 3 or sys.argv[1] not in {"redact", "summarize"}:
        sys.exit(__doc__)
    path = Path(sys.argv[2]).resolve()
    task = redact_before_sending if sys.argv[1] == "redact" else pseudonymize_summarize_restore
    print(asyncio.run(task(path)))

Run it:

python agent.py redact /abs/path/contract.pdf
python agent.py summarize /abs/path/contract.pdf

The server never overwrites a file, so the script refuses to start while an earlier run's outputs (-redacted.pdf, -redacted.md, -correspondence.csv, -summary.md, -summary-restored.md) are next to the PDF. The check runs before anything is uploaded, so nothing is billed. Run each command on its own copy of the PDF.

Remote connector instead of npx

The hosted server at https://mcp.redact-pdf.ai/mcp also accepts an API key. Use it when the agent runs where Node.js is not available:

mcp_servers={"redact-pdf": {"type": "http", "url": "https://mcp.redact-pdf.ai/mcp",
                            "headers": {"X-API-Key": os.environ["REDACT_PDF_API_KEY"]}}}

This is not a drop-in swap. The remote server cannot read local paths: it takes a file as file_base64 (under 1 MB) or through an upload link, returns download links instead of files, and restores names on our side (restore_names with document_id, text_version and the text). The hooks above are written for the local tools' arguments and must be rewritten for these. Its pseudonymize result also carries a 15-minute download link to the correspondence table: keep any tool that can fetch a URL away from such an agent. See the Claude connector reference.

Keep the names away from the model

  • Pass the document by path. Never let the agent Read, cat or preview the original, the -correspondence.csv or the -restored file: those hold the real names.
  • Let your code, not the model, set the file, the mode and pii_categories (all eight), as the examples do. Without pii_categories, the account's saved dashboard categories decide, and one unticked there (Person, say) stays in the output. The result then lists it in categories_not_redacted.
  • The account's saved "never redact" terms (Dashboard → Settings) still apply to MCP jobs: the MCP tools cannot send an empty list to override them. If you have whitelisted names there, they stay in the text the model reads.
  • Text inside a document can try to steer an agent. Give the agent as few tools and paths as the job needs; the examples fix every path and argument in code.
  • In pseudonymize mode the model sees everything that is not a detected entity, health or financial details included, and any name the detection missed. If that is too much, use redact mode.
  • File names reach the model when the agent passes paths: give confidential files neutral names.
  • Traces and transcripts keep what the model saw, the tagged text included: OpenAI Agents SDK tracing (on by default; the example turns it off), LangSmith when LANGSMITH_TRACING is set, and the session transcripts Claude Code and the Claude Agent SDK write under ~/.claude/projects.
  • Jobs default to retention: "ephemeral": the original is deleted right after a successful redaction, and the outputs when your account's retention window ends. See Retention.

Related pages