Developer docs

OpenAI Agents SDK recipe

Use Redact PDF AI from the OpenAI Agents SDK through MCPServerStdio: redact before sending, or pseudonymize, let the model work on tags and restore names.

OpenAI Agents SDK

Use Redact PDF AI from an agent built with the OpenAI Agents SDK through the local MCP server.

Tested with openai-agents 0.25 (Python). Runnable file: https://github.com/dambuchs/redact-pdf-mcp/tree/main/examples/openai-agents.

Setup

pip install openai-agents         # Node.js 20+ is needed for npx
export OPENAI_API_KEY=...
export REDACT_PDF_API_KEY=...     # Dashboard -> Settings -> API keys

Two settings matter:

  • client_session_timeout_seconds: the SDK's default is 5 seconds. redact_pdf_and_wait waits up to 300 seconds for the job, so the example uses 360.
  • run_config=RunConfig(tracing_disabled=True): the SDK traces runs by default, inputs included, which would send the tagged text to OpenAI's trace store.
  • The agent never gets the MCP tools themselves. It gets a function_tool with no arguments that calls redact_pdf_and_wait from code, with the file, mode and categories fixed and the result checked.

The two patterns

  1. Redact before a document leaves the company: the agent gets one tool, redact_document, which redacts this file and nothing else and returns the -redacted.pdf path.
  2. Pseudonymize → work → restore names: here your code calls the tools with server.call_tool(...) and the model only gets the tagged text, with no tools at all. The code stops if a category was left out or if restore_names made no replacement. The real names are put back by restore_names on your machine.
"""OpenAI Agents SDK + the local redact-pdf-mcp server.

    pip install openai-agents             # needs Node.js 20+ for npx
    export OPENAI_API_KEY=...
    export REDACT_PDF_API_KEY=...

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

    # 2. Pseudonymize -> summarize -> restore names (your code calls the tools,
    #    the model only ever gets the tagged text)
    python agent.py summarize /abs/path/contract.pdf

The server 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.
"""

from __future__ import annotations

import asyncio
import json
import os
import sys
from pathlib import Path

from agents import Agent, RunConfig, Runner, function_tool
from agents.mcp import MCPServerStdio

# Tracing is on by default in the Agents SDK and would send the inputs, the
# tagged text included, to OpenAI's trace store. Turn it off for documents.
NO_TRACING = RunConfig(tracing_disabled=True)

# 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 outputs(pdf: Path) -> list[Path]:
    """Every file a run writes next to the PDF."""
    suffixes = ["-redacted.pdf", "-redacted.md", "-correspondence.csv", "-summary.md", "-summary-restored.md"]
    return [pdf.with_name(pdf.stem + suffix) for suffix in suffixes]


def refuse_leftovers(pdf: Path) -> None:
    # Checked before anything is uploaded or billed: the server never
    # overwrites a file, and a leftover table belongs to another run.
    left = [str(path) for path in outputs(pdf) if path.exists()]
    if left:
        sys.exit("Outputs of an earlier run are still there; move them away first:\n" + "\n".join(left))


def warn_about_tags(restored: dict) -> None:
    # Tags left as tags: the model changed them, or a rename was ambiguous.
    for key in ("unresolved_tags", "ambiguous_tags"):
        if restored.get(key):
            print(f"warning: {key}: {restored[key]}", file=sys.stderr)


def redact_pdf_server() -> MCPServerStdio:
    return MCPServerStdio(
        name="redact-pdf",
        params={
            "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"),
            },
        },
        # The SDK's default is 5 s. redact_pdf_and_wait waits up to 300 s for
        # the job, so give the client a margin above that.
        client_session_timeout_seconds=360,
    )


def tool_json(result) -> dict:
    """The tools answer with one JSON text block."""
    text = result.content[0].text if result.content else ""
    if result.isError:
        raise RuntimeError(text or "tool error")
    return json.loads(text)


async def redact(server: MCPServerStdio, pdf: Path, mode: str) -> dict:
    """redact_pdf_and_wait with every argument fixed by code, result checked."""
    job = tool_json(
        await server.call_tool(
            "redact_pdf_and_wait",
            {"file_path": str(pdf), "mode": mode, "retention": "ephemeral", "pii_categories": ALL_CATEGORIES},
        )
    )
    if job.get("categories_not_redacted"):
        raise RuntimeError(job.get("categories_note", "a category was left out"))
    return job


async def redact_before_sending(pdf: Path) -> str:
    refuse_leftovers(pdf)
    async with redact_pdf_server() as server:
        # The agent gets one tool with no arguments: code decides the file, the
        # mode and the categories, and checks the result.
        # Errors from here name paths and reasons, never document content, so the
        # model (and the user) may see them; the SDK's default hides them.
        @function_tool(failure_error_function=lambda _ctx, error: f"Redaction failed: {error}")
        async def redact_document() -> str:
            """Redact the document the user named and return the redacted PDF's path."""
            return (await redact(server, pdf, "redact"))["output_path"]

        agent = Agent(
            name="Outbound documents",
            instructions="You prepare documents to be sent outside the company. Call redact_document and report the path it returns.",
            tools=[redact_document],
        )
        result = await Runner.run(agent, f"Redact {pdf.name} before I send it to the buyer's agent.", run_config=NO_TRACING)
        return str(result.final_output)


async def pseudonymize_summarize_restore(pdf: Path) -> Path:
    refuse_leftovers(pdf)
    async with redact_pdf_server() as server:
        # 1. Pseudonymize. The file is read by the MCP server, not by the model.
        job = await redact(server, pdf, "pseudonymize")
        if "correspondence_path" not in job:
            raise RuntimeError(job.get("correspondence_error", "no correspondence table"))
        tagged = job.get("document_text") or Path(job["document_text_path"]).read_text(encoding="utf-8")

        # 2. The model works on tags such as [Person 1], never on names.
        writer = Agent(
            name="Summarizer",
            instructions="Summarize the obligations of each party. Keep every tag such as [Person 1] exactly as written.",
        )
        summary = (await Runner.run(writer, tagged, run_config=NO_TRACING)).final_output
        draft = pdf.with_name(f"{pdf.stem}-summary.md")
        draft.write_text(str(summary), encoding="utf-8")

        # 3. Names back on this machine. Hand the path to the user; do not send
        #    the restored file (or the correspondence CSV) to any model.
        restored = tool_json(
            await server.call_tool(
                "restore_names",
                {"file_path": str(draft), "correspondence_path": job["correspondence_path"]},
            )
        )
        warn_about_tags(restored)
        if restored.get("replacements", 0) == 0:  # no tag survived in the draft
            Path(restored.get("output_path", draft.with_name(f"{draft.stem}-restored.md"))).unlink(missing_ok=True)
            raise RuntimeError(restored.get("note", json.dumps(restored)))
        return Path(restored["output_path"])


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

from agents.mcp import MCPServerStreamableHttp

MCPServerStreamableHttp(
    name="redact-pdf",
    params={"url": "https://mcp.redact-pdf.ai/mcp", "headers": {"X-API-Key": os.environ["REDACT_PDF_API_KEY"]}, "timeout": 30},
    client_session_timeout_seconds=360,
)

The remote server takes files as file_base64 (under 1 MB) or through an upload link, and returns download links. See the Claude connector reference for its tools.

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