# ACP (Agent Client Protocol)

Mastra supports the [Agent Client Protocol (ACP)](https://agentclientprotocol.com/overview/introduction) for running ACP-compatible coding agents from a Mastra agent. Use `@mastra/acp` to wrap a coding agent process as a Mastra tool or as a subagent.

ACP is useful for coding agents such as Claude Code, Amp, Codex, or any other executable that implements the Agent Client Protocol over standard input and output.

## When to use ACP

- A Mastra agent should delegate code inspection, editing, or repository tasks to an external coding agent.
- An ACP-compatible agent process should stay alive across calls so it can keep session context.
- A parent agent needs real-time output from a coding agent while the task runs.
- An ACP-compatible agent needs permission prompts before it reads files, writes files, or runs actions.
- File access should go through Mastra's workspace abstraction instead of direct process-only file access.

## How ACP works

`@mastra/acp` starts the configured ACP agent command as a child process and communicates with it using newline-delimited JSON over standard input and output.

The flow is:

1. Configure `command`, `args`, and optional connection settings.
2. `@mastra/acp` spawns the ACP agent process on first use.
3. The client sends ACP `initialize` and `session/new` requests.
4. Mastra sends the user task to the ACP agent with `session/prompt`.
5. The ACP agent streams session updates and message chunks back to Mastra.
6. Mastra returns the buffered output, emits streaming chunks, or suspends for permission input.
7. The ACP process stays alive by default, or stops after the prompt when `persistSession` is `false`.

During execution, the ACP client also handles permission requests and file operations. File reads and writes go through Mastra's `Workspace`, so the ACP agent operates inside the workspace you provide.

## Getting started

Install `@mastra/acp` in a project that already uses `@mastra/core`:

**npm**:

```bash
npm install @mastra/acp
```

**pnpm**:

```bash
pnpm add @mastra/acp
```

**Yarn**:

```bash
yarn add @mastra/acp
```

**Bun**:

```bash
bun add @mastra/acp
```

`@mastra/acp` exports two APIs:

- `createACPTool`: Create a Mastra tool that sends a `task` string to an ACP agent and returns an `output` string.
- `AcpAgent`: Wrap an ACP agent as a Mastra subagent with `generate()` and `stream()` support.

The package requires `@mastra/core` version `1.34.0` or later.

## Use ACP as a subagent

Use `AcpAgent` when a parent Mastra agent should delegate directly to an ACP-compatible coding agent as a subagent. Create the ACP agent, then register it in the parent agent's `agents` map.

```typescript
import { AcpAgent } from '@mastra/acp'
import { Agent } from '@mastra/core/agent'

const codeAgent = new AcpAgent({
  id: 'code-agent',
  name: 'Code Agent',
  description: 'An ACP-compatible coding agent that can inspect and edit files',
  command: 'acp-agent',
  args: ['--stdio'],
  cwd: process.cwd(),
})

export const codeSupervisor = new Agent({
  id: 'code-supervisor',
  name: 'Code Supervisor',
  instructions: 'Delegate code editing tasks to the code-agent subagent.',
  model: 'openai/gpt-5.4',
  agents: {
    codeAgent,
  },
})
```

`AcpAgent.generate()` buffers the ACP response and returns it as text. `AcpAgent.stream()` emits Mastra `text-delta` chunks as ACP `agent_message_chunk` updates arrive.

## Use ACP as a tool

Use `createACPTool` when the parent Mastra agent should decide when to call the ACP agent as a tool. The following example creates a code editing tool and registers it on a parent agent:

```typescript
import { createACPTool } from '@mastra/acp'
import { Agent } from '@mastra/core/agent'

const codeAgentTool = createACPTool({
  id: 'code-agent',
  description: 'Use an ACP-compatible coding agent to inspect and edit code',
  command: 'acp-agent',
  args: ['--stdio'],
  cwd: process.cwd(),
})

export const codeSupervisor = new Agent({
  id: 'code-supervisor',
  name: 'Code Supervisor',
  instructions: 'Use the code-agent tool when a task requires repository inspection or code edits.',
  model: 'openai/gpt-5.4',
  tools: {
    codeAgentTool,
  },
})
```

Use the `command` and `args` required by the ACP-compatible agent you run. The tool input schema has a single `task` string, and the output schema returns the final ACP response as `output`.

If the ACP agent requests permission, the tool can suspend and resume through Mastra's tool suspension flow. Use `onPermissionRequest` when you need custom permission behavior.

## Options reference

`createACPTool` and `AcpAgent` accept the same ACP connection options. `AcpAgent` also accepts `name` to set the display name used during agent delegation.

| Option                | Type                             | Description                                                                             |
| --------------------- | -------------------------------- | --------------------------------------------------------------------------------------- |
| `id`                  | `string`                         | Unique tool or subagent identifier.                                                     |
| `description`         | `string`                         | Description shown to the model when it can call the tool or delegate to the subagent.   |
| `command`             | `string`                         | ACP agent executable to spawn.                                                          |
| `args`                | `string[]`                       | Arguments passed to the ACP agent executable.                                           |
| `env`                 | `Record<string, string>`         | Environment variables to merge with the current process environment.                    |
| `cwd`                 | `string`                         | Working directory for the ACP process, ACP session, and default workspace.              |
| `session`             | `Partial<NewSessionRequest>`     | ACP session creation options. Defaults to `cwd` or `process.cwd()` and no MCP servers.  |
| `initialize`          | `Partial<InitializeRequest>`     | ACP initialization options. Defaults to Mastra client information and protocol version. |
| `authMethodId`        | `string`                         | ACP authentication method ID to invoke after initialization.                            |
| `persistSession`      | `boolean`                        | Keep the ACP process alive after execution. Defaults to `true`.                         |
| `onPermissionRequest` | `(request) => Promise<Response>` | Callback for ACP permission requests. Defaults to selecting the first option.           |
| `workspace`           | `Workspace`                      | Workspace used for ACP file reads and writes.                                           |
| `model`               | `string`                         | Model ID to select after session creation via the ACP `session/set_model` method.       |

## Model selection

ACP agents may expose selectable models. Instead of setting an environment variable like `ANTHROPIC_MODEL`, you can pass a `model` ID directly in the configuration.

### Discover available models

Call `getAvailableModels()` to see which models the ACP agent supports. This starts the agent process and returns the model list from the session:

```typescript
import { AcpAgent } from '@mastra/acp'

const codeAgent = new AcpAgent({
  id: 'code-agent',
  description: 'An ACP-compatible coding agent',
  command: 'claude',
  args: ['--acp'],
})

const models = await codeAgent.getAvailableModels()
// [{ modelId: 'claude-sonnet-4-20250514', name: 'Claude Sonnet' }, ...]
```

### Set the model

Pass the `model` option to select a model at connection time:

```typescript
import { AcpAgent } from '@mastra/acp'

export const codeAgent = new AcpAgent({
  id: 'code-agent',
  description: 'An ACP-compatible coding agent',
  command: 'claude',
  args: ['--acp'],
  model: '__AI_SDK_ANTHROPIC_MODEL_SONNET__',
})
```

You can also change the model at runtime with `setModel()`:

```typescript
await codeAgent.setModel('__AI_SDK_ANTHROPIC_MODEL_SONNET__')
```

If the ACP agent advertises available models and your model ID doesn't match any of them, Mastra throws an error listing the valid options:

```text
Model "bad-model-id" is not available. Available models: claude-sonnet-4-20250514, claude-haiku-4-20250514
```

If the agent doesn't advertise a model list, the value is passed through without validation.

## Session lifecycle

`createACPTool` and `AcpAgent` start the configured command on first use and create an ACP session. By default, `persistSession` is `true`, so the child process stays alive across calls.

Use the default persistent session when:

- The ACP agent benefits from keeping conversation or repository context.
- Startup is expensive and repeated calls should reuse the same process.
- A parent agent may delegate several related tasks to the same coding agent.

Set `persistSession: false` when each prompt should run in an isolated process:

```typescript
import { AcpAgent } from '@mastra/acp'

export const codeAgent = new AcpAgent({
  id: 'code-agent',
  description: 'Run one isolated ACP coding task',
  command: 'acp-agent',
  args: ['--stdio'],
  cwd: process.cwd(),
  persistSession: false,
})
```

With `persistSession: false`, `@mastra/acp` stops the ACP process after each prompt completes.

## Permission handling

ACP agents may ask the client to choose a permission option before they continue. By default, `@mastra/acp` selects the first option returned by the ACP agent.

Pass `onPermissionRequest` to inspect the request and return the selected option yourself:

```typescript
import { createACPTool } from '@mastra/acp'

export const codeAgentTool = createACPTool({
  id: 'code-agent',
  description: 'Use an ACP-compatible coding agent',
  command: 'acp-agent',
  args: ['--stdio'],
  async onPermissionRequest(request) {
    const allowOption = request.options.find(option => option.name === 'Allow')

    if (!allowOption) {
      return { outcome: { outcome: 'cancelled' } }
    }

    return {
      outcome: {
        outcome: 'selected',
        optionId: allowOption.optionId,
      },
    }
  },
})
```

Use this callback to enforce local policy, inspect the permission title, or route the decision to your own approval flow.

## Workspace integration

ACP file operations go through Mastra's workspace abstraction. If you don't pass `workspace`, `@mastra/acp` creates a `Workspace` backed by `LocalFilesystem` and uses `cwd` as the filesystem root.

Pass a custom `Workspace` when the ACP agent should read and write through a specific filesystem implementation:

```typescript
import { AcpAgent } from '@mastra/acp'
import { LocalFilesystem, Workspace } from '@mastra/core/workspace'

const workspace = new Workspace({
  filesystem: new LocalFilesystem({
    root: process.cwd(),
  }),
})

export const codeAgent = new AcpAgent({
  id: 'code-agent',
  description: 'Run coding tasks in a controlled workspace',
  command: 'acp-agent',
  args: ['--stdio'],
  workspace,
})
```

Use `cwd` and `workspace` together when the ACP process should start in one directory but file operations should use an explicitly configured workspace root.

## Related

- [Agent reference](https://mastra.ai/reference/agents/agent)
- [Subagents](https://mastra.ai/docs/agents/supervisor-agents)
- [Agent Client Protocol introduction](https://agentclientprotocol.com/overview/introduction)
- [Agent Client Protocol schema](https://agentclientprotocol.com/protocol/schema)