Developer docs

LangGraph recipe

Load the redact-pdf MCP tools into a LangChain v1 agent with langchain-mcp-adapters: redact before sending, or pseudonymize, summarize and restore names.

LangGraph and LangChain

Load the Redact PDF AI tools into a LangChain v1 agent (create_agent, which runs on LangGraph) with langchain-mcp-adapters.

Tested with langchain 1.5, langgraph 1.2 and langchain-mcp-adapters 0.3 (Python). Runnable file: https://github.com/dambuchs/redact-pdf-mcp/tree/main/examples/langgraph.

Setup

pip install langchain langgraph langchain-mcp-adapters langchain-anthropic   # Node.js 20+ for npx
export ANTHROPIC_API_KEY=...      # or set MODEL to another provider, e.g. "openai:..."
export REDACT_PDF_API_KEY=...

MultiServerMCPClient starts npx -y redact-pdf-mcp@0.6.0 (once per tool call, without a session) and turns its tools into LangChain tools. Calling a tool directly (await tool.ainvoke({...})) returns a list of content blocks; the tools answer with one JSON text block, which the example parses. The adapter does not raise when a tool reports an error, so tool_json raises on an error field itself.

langgraph.prebuilt.create_react_agent is deprecated in LangGraph v1; the example uses langchain.agents.create_agent.

The two patterns

  1. Redact before a document leaves the company: the agent gets one @tool with no arguments, redact_document, which calls redact_pdf_and_wait from code with the file, mode and categories fixed and checks the result.
  2. Pseudonymize → work → restore names: your code calls redact_pdf_and_wait and restore_names, and the model works on the tagged text with no tools.
"""LangGraph (LangChain v1 create_agent) + the local redact-pdf-mcp server.

    pip install langchain langgraph langchain-mcp-adapters langchain-anthropic
    export ANTHROPIC_API_KEY=...          # or swap MODEL for another provider
    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 langchain.agents import create_agent
from langchain.tools import tool
from langchain_mcp_adapters.client import MultiServerMCPClient

MODEL = os.environ.get("MODEL", "anthropic:claude-sonnet-5-5")
# With LANGSMITH_TRACING set, LangSmith stores every model input, the tagged
# text included. Leave it off for confidential documents.

# 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)

client = MultiServerMCPClient(
    {
        "redact-pdf": {
            "transport": "stdio",
            "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"),
            },
        }
    }
)


async def tools_by_name(*names: str) -> dict:
    tools = {tool.name: tool for tool in await client.get_tools()}
    return {name: tools[name] for name in names}


def tool_json(content) -> dict:
    """A tool's answer: one JSON text block (a list of content blocks, or a string).

    The adapter does not raise when a tool reports an error, so check here."""
    if isinstance(content, list):
        content = "".join(block.get("text", "") for block in content if isinstance(block, dict))
    try:
        data = json.loads(content)
    except json.JSONDecodeError:
        raise RuntimeError(content) from None
    if isinstance(data, dict) and "error" in data:
        raise RuntimeError(json.dumps(data))
    return data


async def redact(pdf: Path, mode: str) -> dict:
    """redact_pdf_and_wait with every argument fixed by code, result checked."""
    tools = await tools_by_name("redact_pdf_and_wait")
    job = tool_json(
        await tools["redact_pdf_and_wait"].ainvoke(
            {"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)
    # The agent gets one tool with no arguments: code decides the file, the
    # mode and the categories, and checks the result.
    @tool
    async def redact_document() -> str:
        """Redact the document the user named and return the redacted PDF's path."""
        return (await redact(pdf, "redact"))["output_path"]

    agent = create_agent(
        MODEL,
        [redact_document],
        system_prompt="You prepare documents to be sent outside the company. Call redact_document and report the path it returns.",
    )
    result = await agent.ainvoke(
        {"messages": [{"role": "user", "content": f"Redact {pdf.name} before I send it to the buyer's agent."}]}
    )
    return result["messages"][-1].content


async def pseudonymize_summarize_restore(pdf: Path) -> Path:
    refuse_leftovers(pdf)
    # 1. Pseudonymize. The file is read by the MCP server, not by the model.
    job = await redact(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. No tools.
    writer = create_agent(
        MODEL,
        [],
        system_prompt="Summarize the obligations of each party. Keep every tag such as [Person 1] exactly as written.",
    )
    summary = (await writer.ainvoke({"messages": [{"role": "user", "content": tagged}]}))["messages"][-1].content
    draft = pdf.with_name(f"{pdf.stem}-summary.md")
    draft.write_text(str(summary), encoding="utf-8")

    # 3. Names back on this machine. Do not send the restored file to a model.
    restore = (await tools_by_name("restore_names"))["restore_names"]
    restored = tool_json(await restore.ainvoke({"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

MultiServerMCPClient({"redact-pdf": {"transport": "http", "url": "https://mcp.redact-pdf.ai/mcp",
                                     "headers": {"X-API-Key": os.environ["REDACT_PDF_API_KEY"]}}})

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.

Without MCP

To call the REST API instead, use the helpers in https://github.com/dambuchs/redact-pdf-mcp/tree/main/examples/rest. Only redact_file is safe to wrap with @tool, best in a no-argument wrapper like redact_document above. pseudonymize_file returns the correspondence table and restore_names the restored text, and a tool's return value goes to the model, so call those two from your own code: pseudonymize, give the model the tagged text, then restore (restore_names returns the text and the number of replacements). The helpers drop the CSV's byte-order mark and delete the job at the end.

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