# Deep Agents + ACP: Policy & Audit Install Guide

Put a LangChain Deep Agent under per-user policy, PII detection, and audit, main agent and subagents. One pip install, one import swap, every tool call checked, including inside task delegation.

# Deep Agents + ACP: Policy & Audit Install Guide

[Deep Agents](https://github.com/langchain-ai/deepagents) is LangChain's open-source harness for Claude Code-style agents. It adds planning, a filesystem, subagent delegation, context management, memory, skills and human-in-the-loop on top of LangChain 1.x `create_agent`. It is MIT licensed and works with any model.

It takes the same `middleware=` list as `create_agent`. So `ACPMiddleware()` from [`acp-langchain`](/integrations/langgraph) already checks the main agent's tools: the filesystem tools, skill reads, the `task` delegation call and your own. It does not reach the subagents. `acp-langchain` 0.3 fixes that with one import swap.

ACP uses the same `/govern/tool-use` endpoint and the same workspace policies as Claude Code. Two differences. An `ask` comes back to the model as a denied tool call (approve it on the console and re-run). And the shell-command safety floor applies only to tools that carry a shell command.

> **5-minute install.** `pip install "acp-langchain[deepagents]"`, import `create_deep_agent` from `acp_langchain.deepagents`, bind the JWT per request. See [the runnable starter](https://github.com/agentic-control-plane/acp-governance-sdks/tree/main/examples/starters/deepagents), [how a call is decided](/docs/governance-model), or the [frameworks index](/frameworks).

## Install

```bash
pip install "acp-langchain[deepagents]"
```

You need `deepagents >= 0.7` and `langchain >= 1.3.3`.

## A minimal agent under policy, subagents included

```python
from fastapi import FastAPI, Header
from langchain.tools import tool
from acp_langchain import configure, set_context
from acp_langchain.deepagents import create_deep_agent   # not from deepagents

configure(base_url="https://api.agenticcontrolplane.com")
app = FastAPI()

@tool
def lookup_record(id: str) -> str:
    """Look up a record by ID."""
    return json.dumps(db.records.find_one({"id": id}))

@tool
def send_email(to: str, subject: str, body: str) -> str:
    """Send an email."""
    return mailer.send(to=to, subject=subject, body=body)

# Same signature as deepagents.create_deep_agent.
agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    tools=[lookup_record, send_email],
    subagents=[{
        "name": "researcher",
        "description": "Looks up records and summarises them.",
        "system_prompt": "Use lookup_record, then report.",
    }],
)

@app.post("/run")
def run(prompt: str, authorization: str = Header(...)):
    set_context(
        user_token=authorization.removeprefix("Bearer ").strip(),
        agent_name="my-deep-agent",
        agent_tier="background",
    )
    result = agent.invoke({"messages": [{"role": "user", "content": prompt}]})
    return {"result": result["messages"][-1].content}
```

Neither tool has a decorator, and the subagent spec is unchanged. ACP is on the main agent, on `researcher`, and on the `general-purpose` subagent that Deep Agents adds on its own. When the model delegates with `task`, the subagent's `lookup_record` call is checked and recorded the same way the parent's would be, in the same session.

## Why the plain middleware line is not enough

`create_deep_agent` builds a separate middleware stack for each declarative subagent. The parent's user-supplied middleware is passed down only for `mode="fork"` subagents. The auto-added `general-purpose` subagent inherits only parent middleware whose name matches one of its default slots, and `ACPMiddleware` never does.

So with `create_deep_agent(..., middleware=[ACPMiddleware()])` the trail shows one checked `task` row, then nothing while the subagent reads, writes and calls tools with no policy check and no audit row. It looks covered and isn't.

We verified this against deepagents 0.7.13. [`tests/test_deepagents.py`](https://github.com/agentic-control-plane/acp-governance-sdks/blob/main/python/acp-langchain/tests/test_deepagents.py) runs a scripted model through main, `task`, then a subagent tool call, using stock `create_deep_agent`, and asserts ACP saw only `task`. The same script through the ACP wrapper asserts it saw `task` and the subagent's tool. You don't need a model key to run it.

If you build with `deepagents.create_deep_agent` directly, wrap the subagents list instead:

```python
from deepagents import create_deep_agent
from acp_langchain import ACPMiddleware
from acp_langchain.deepagents import govern_subagents

agent = create_deep_agent(
    model=..., tools=[...],
    middleware=[ACPMiddleware()],
    subagents=govern_subagents(my_subagents),
)
```

`govern_subagents` adds `ACPMiddleware` to every declarative spec. Unless you supplied your own, it also adds a governed `general-purpose` spec with the same name, description and prompt as the stock one, so the model's view of `task` doesn't change.

**Compiled and remote subagents.** A `CompiledSubAgent` (`runnable=`) or an `AsyncSubAgent` (`graph_id=`) is built elsewhere, so ACP can't be added here. They pass through unchanged and a `UserWarning` names each one. Register `ACPMiddleware` on those graphs where you build them.

## What happens on every tool call

1. `ACPMiddleware`'s tool-call wrapper POSTs to ACP's `/govern/tool-use` with the tool name, the arguments and the user JWT bound by `set_context`.
2. **Deny or ask:** the tool function is **never called**. The model gets `"tool_error: <reason>"` as the tool result and adapts. For an `ask`, approve it on the console [Approvals](https://cloud.agenticcontrolplane.com/approvals) page or from the approval email, then re-run.
3. **Allow:** your function runs.
4. After the tool returns, ACP scans the output for PII and secrets. With `redact`, the redacted version replaces the original before the model sees it. With `block`, the model sees `"[ACP] Blocked: <reason>"`. An audit row is written under the end user's identity.

Filesystem tools (`read_file`, `write_file`, `edit_file`, `ls`, `glob`, `grep`), skill file reads and `task` itself are tool calls, so they take the same path. Memory files loaded at startup are read outside any tool call, so ACP does not see them.

## What Deep Agents already has, and what ACP adds

Deep Agents has controls of its own. Here is the overlap.

| Already in Deep Agents / LangChain | What it is | What ACP adds |
|---|---|---|
| `interrupt_on` / `HumanInTheLoopMiddleware` | The pause. Approve, edit or reject a proposed call. Subagents inherit it. | The decision behind the pause, from one workspace policy, with the approval on the record. An approved call still passes the ACP check when it executes. |
| `permissions` (`FilesystemPermission`) | Allow, deny or interrupt rules for filesystem paths, per agent, in code. Subagents inherit it. | Policy on every tool, not just the filesystem, keyed on the end user and changed in the workspace without a redeploy. |
| `PIIMiddleware` | Redacts PII in one agent's message stream. | PII and secret detection on tool input and output, recorded as findings on the audit row. |
| `ToolCallLimitMiddleware`, `ModelCallLimitMiddleware` | Caps per run, in code. | Rate limits per user and per tool, across every run and every harness. |
| Tracing (LangSmith or your own) | Records what happened. | Records what was decided, and why, before it happened, in one trail beside Claude Code, Cursor, Codex and CrewAI. |

If you run one Deep Agent and nothing else, the built-in controls cover a lot. What they leave open is that every rule lives in that agent's code, applies only to that agent, and doesn't say which human triggered the call. ACP applies the same control from outside the harness, across all of them.

## Using it with Deep Agents' own controls

Keep `interrupt_on` and `permissions`. The wrappers nest, so the interrupt fires after the model proposes the call and ACP runs when it executes:

```python
agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    tools=[lookup_record, send_email],
    interrupt_on={"send_email": True},      # the pause
    permissions=[FilesystemPermission(operations=["write"], paths=["/secrets/**"], mode="deny")],
)
```

To narrow what ACP checks:

```python
from acp_langchain import ACPMiddleware
create_deep_agent(..., acp=ACPMiddleware(exclude=["ls", "glob", "grep"]))
```

## Per-tier policy

`set_context(agent_tier="...")` picks the policy tier:

- **`interactive`**: a human at the keyboard, permissive default.
- **`subagent`**: invoked by another agent, with no human directly in the loop.
- **`background`**: autonomous, the most restrictive.
- **`api`**: a programmatic call from your backend.

Subagent tool calls carry the tier and session bound on the request. Context variables pass through the `task` call.

## Price and meter the model calls

`ACPMiddleware` covers what your agent does. A second piece, the proxy, covers what it spends. Both talk to the same gateway, and `init()` sets up the proxy side:

```python
import acp_governance as acp

acp.init()            # call before you construct any model client
```

Model calls then land on the same trail as tool calls, with cost, tokens and cache data. Deep Agents resolves `model="anthropic:..."` and `"openai:..."` strings through the provider clients `init()` configures, so one call covers the main agent and every subagent.

`init()` handles each provider all or nothing. It sets the base URL and the key, or it leaves that provider alone and tells you which one it skipped.

**Your coverage:** tool calls checked (main agent and subagents), model calls metered (proxy).

## FAQ

**Do I have to change my subagent specs?**
No. Pass them as you do today. The wrapper adds the middleware and doesn't change your specs.

**I disabled the general-purpose subagent through a profile.**
Pass `general_purpose=False` to `govern_subagents`, or supply your own spec with that name. The wrapper keeps yours and governs it.

**What does the model see on a denial inside a subagent?**
The same as in the parent: `"tool_error: <reason>"` as the tool result. The subagent adapts and returns its final message to the parent as usual.

**Does this touch my LLM traffic?**
Not by default. You opt in with the proxy above.

**What if the ACP gateway is unreachable?**
It fails open. The tool runs, and the reason is marked `"fail-open"`. The check is never a single point of failure for your agent. The timeout is 5 seconds, and you can change it with `configure(timeout_s=...)`.

**Which versions?**
`acp-langchain >= 0.3`, `deepagents >= 0.7`, `langchain >= 1.3.3`. The subagent behavior described above is what deepagents 0.7.13 does. The test in the SDK repo will fail the day upstream starts passing user middleware down, and that is your signal to drop the wrapper.

## Related

- [Deep Agents on GitHub](https://github.com/langchain-ai/deepagents)
- [`acp-langchain` on PyPI](https://pypi.org/project/acp-langchain)
- [`acp-governance` (core SDK)](https://pypi.org/project/acp-governance)
- [LangChain / LangGraph integration](/integrations/langgraph)
- [Pydantic AI integration](/integrations/pydantic-ai)
- [CrewAI integration](/integrations/crewai)

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "HowTo",
  "name": "Add policy and audit to LangChain Deep Agents with Agentic Control Plane",
  "totalTime": "PT5M",
  "step": [
    {"@type": "HowToStep", "name": "Install acp-langchain with the deepagents extra", "text": "pip install \"acp-langchain[deepagents]\""},
    {"@type": "HowToStep", "name": "Swap the import", "text": "from acp_langchain.deepagents import create_deep_agent — same signature; ACP is registered on the main agent and every subagent."},
    {"@type": "HowToStep", "name": "Bind the user's JWT per request", "text": "Call set_context(user_token=...) at the start of each request."}
  ]
}
</script>
