> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/agentclientprotocol/typescript-sdk/llms.txt
> Use this file to discover all available pages before exploring further.

# ClientSideConnection

> The main connection class for communicating with ACP agents

## Overview

The `ClientSideConnection` class provides the client's view of an ACP connection. It implements the `Agent` interface, giving you access to all agent methods.

## Constructor

Creates a new client-side connection to an agent.

```typescript theme={null}
new ClientSideConnection(
  toClient: (agent: Agent) => Client,
  stream: Stream
)
```

<ParamField path="toClient" type="(agent: Agent) => Client" required>
  A function that creates a Client handler to process incoming agent requests. The function receives the connection instance (implementing the Agent interface) and should return your Client implementation.
</ParamField>

<ParamField path="stream" type="Stream" required>
  The bidirectional message stream for communication. Typically created using `ndJsonStream()` for stdio-based connections.
</ParamField>

### Example

```typescript theme={null}
import * as acp from "@agentclientprotocol/acp";
import { spawn } from "node:child_process";
import { Writable, Readable } from "node:stream";

// Spawn the agent process
const agentProcess = spawn("my-agent", ["--flag"]);

// Create bidirectional stream
const input = Writable.toWeb(agentProcess.stdin);
const output = Readable.toWeb(agentProcess.stdout) as ReadableStream<Uint8Array>;
const stream = acp.ndJsonStream(input, output);

// Create the connection
const client = new MyClient();
const connection = new acp.ClientSideConnection(
  (_agent) => client,
  stream
);
```

## Methods

The `ClientSideConnection` implements the full `Agent` interface:

### initialize()

Establishes the connection and negotiates protocol capabilities.

```typescript theme={null}
await connection.initialize(
  params: InitializeRequest
): Promise<InitializeResponse>
```

<ParamField path="params.protocolVersion" type="string" required>
  The protocol version to use (e.g., `acp.PROTOCOL_VERSION`).
</ParamField>

<ParamField path="params.clientCapabilities" type="ClientCapabilities" required>
  Capabilities advertised by the client (file system, terminal support, etc.).
</ParamField>

<ResponseField name="protocolVersion" type="string">
  The negotiated protocol version.
</ResponseField>

<ResponseField name="agentCapabilities" type="AgentCapabilities">
  Capabilities supported by the agent.
</ResponseField>

<ResponseField name="authMethods" type="AuthMethod[]">
  Available authentication methods.
</ResponseField>

#### Example

```typescript theme={null}
const initResult = await connection.initialize({
  protocolVersion: acp.PROTOCOL_VERSION,
  clientCapabilities: {
    fs: {
      readTextFile: true,
      writeTextFile: true,
    },
    terminal: true,
  },
});

console.log(`Connected using protocol v${initResult.protocolVersion}`);
```

### newSession()

Creates a new conversation session with the agent.

```typescript theme={null}
await connection.newSession(
  params: NewSessionRequest
): Promise<NewSessionResponse>
```

<ParamField path="params.cwd" type="string" required>
  The working directory for the session (absolute path).
</ParamField>

<ParamField path="params.mcpServers" type="McpServer[]" required>
  MCP servers the agent should connect to for this session.
</ParamField>

<ResponseField name="sessionId" type="string">
  Unique identifier for the created session.
</ResponseField>

<ResponseField name="currentMode" type="SessionMode">
  The initial mode of the session.
</ResponseField>

<ResponseField name="availableModes" type="SessionMode[]">
  Modes available for this session.
</ResponseField>

#### Example

```typescript theme={null}
const session = await connection.newSession({
  cwd: "/home/user/project",
  mcpServers: [],
});

console.log(`Session created: ${session.sessionId}`);
```

### loadSession()

Loads an existing session to resume a previous conversation.

<Note>
  Only available if the agent advertises the `loadSession` capability.
</Note>

```typescript theme={null}
await connection.loadSession(
  params: LoadSessionRequest
): Promise<LoadSessionResponse>
```

<ParamField path="params.sessionId" type="string" required>
  The ID of the session to load.
</ParamField>

<ParamField path="params.mcpServers" type="McpServer[]" required>
  MCP servers to connect to for this session.
</ParamField>

### prompt()

Processes a user prompt within a session.

```typescript theme={null}
await connection.prompt(
  params: PromptRequest
): Promise<PromptResponse>
```

<ParamField path="params.sessionId" type="string" required>
  The session ID to send the prompt to.
</ParamField>

<ParamField path="params.prompt" type="PromptContent[]" required>
  Array of content items (text, images, files, etc.).
</ParamField>

<ResponseField name="stopReason" type="StopReason">
  Why the agent stopped (e.g., `"finished"`, `"cancelled"`, `"error"`).
</ResponseField>

#### Example

```typescript theme={null}
const result = await connection.prompt({
  sessionId: session.sessionId,
  prompt: [
    {
      type: "text",
      text: "Refactor the parseConfig function",
    },
  ],
});

console.log(`Agent stopped: ${result.stopReason}`);
```

### cancel()

Cancels ongoing operations for a session.

```typescript theme={null}
await connection.cancel(
  params: CancelNotification
): Promise<void>
```

<ParamField path="params.sessionId" type="string" required>
  The session ID to cancel operations for.
</ParamField>

#### Example

```typescript theme={null}
// Cancel the ongoing prompt
await connection.cancel({
  sessionId: session.sessionId,
});
```

### setSessionMode()

Sets the operational mode for a session.

```typescript theme={null}
await connection.setSessionMode(
  params: SetSessionModeRequest
): Promise<SetSessionModeResponse>
```

<ParamField path="params.sessionId" type="string" required>
  The session ID.
</ParamField>

<ParamField path="params.mode" type="string" required>
  The mode to switch to (must be in `availableModes`).
</ParamField>

### authenticate()

Authenticates the client using the specified authentication method.

```typescript theme={null}
await connection.authenticate(
  params: AuthenticateRequest
): Promise<AuthenticateResponse>
```

<ParamField path="params.methodId" type="string" required>
  The ID of the authentication method to use.
</ParamField>

### setSessionConfigOption()

Sets a configuration option for a session.

```typescript theme={null}
await connection.setSessionConfigOption(
  params: SetSessionConfigOptionRequest
): Promise<SetSessionConfigOptionResponse>
```

## Properties

### signal

AbortSignal that aborts when the connection closes.

```typescript theme={null}
const signal: AbortSignal = connection.signal;
```

Useful for:

* Listening for connection closure
* Checking connection status synchronously
* Passing to other APIs for automatic cancellation

#### Example

```typescript theme={null}
// Listen for closure
connection.signal.addEventListener('abort', () => {
  console.log('Connection closed - cleaning up');
  cleanupResources();
});

// Check status
if (connection.signal.aborted) {
  console.log('Connection is already closed');
}

// Pass to fetch for automatic cancellation
fetch(url, { signal: connection.signal });
```

### closed

Promise that resolves when the connection closes.

```typescript theme={null}
const closed: Promise<void> = connection.closed;
```

#### Example

```typescript theme={null}
// Wait for closure
await connection.closed;
console.log('Connection closed - performing cleanup');

// Or use it in a race
const result = await Promise.race([
  connection.prompt({ sessionId, prompt }),
  connection.closed.then(() => {
    throw new Error('Connection closed unexpectedly');
  }),
]);
```

## Extension Methods

### extMethod()

Sends an arbitrary request that is not part of the ACP spec.

```typescript theme={null}
await connection.extMethod(
  method: string,
  params: Record<string, unknown>
): Promise<Record<string, unknown>>
```

<Warning>
  To avoid conflicts, prefix extension methods with a unique identifier (e.g., domain name).
</Warning>

### extNotification()

Sends an arbitrary notification that is not part of the ACP spec.

```typescript theme={null}
await connection.extNotification(
  method: string,
  params: Record<string, unknown>
): Promise<void>
```

## Complete Example

```typescript theme={null}
import * as acp from "@agentclientprotocol/acp";
import { spawn } from "node:child_process";
import { Writable, Readable } from "node:stream";

class MyClient implements acp.Client {
  async requestPermission(params: acp.RequestPermissionRequest) {
    // Implementation
    return { outcome: { outcome: "approved" } };
  }
  
  async sessionUpdate(params: acp.SessionNotification) {
    console.log("Update:", params.update);
  }
}

async function main() {
  // Spawn agent
  const agentProcess = spawn("my-agent");
  const stream = acp.ndJsonStream(
    Writable.toWeb(agentProcess.stdin),
    Readable.toWeb(agentProcess.stdout) as ReadableStream<Uint8Array>
  );

  // Create connection
  const client = new MyClient();
  const connection = new acp.ClientSideConnection(
    (_agent) => client,
    stream
  );

  // Initialize
  await connection.initialize({
    protocolVersion: acp.PROTOCOL_VERSION,
    clientCapabilities: { fs: { readTextFile: true } },
  });

  // Create session
  const session = await connection.newSession({
    cwd: process.cwd(),
    mcpServers: [],
  });

  // Send prompt
  await connection.prompt({
    sessionId: session.sessionId,
    prompt: [{ type: "text", text: "Hello!" }],
  });

  // Wait for completion
  await connection.closed;
}

main().catch(console.error);
```

## See Also

* [Implementing the Client Interface](/clients/implementing-client-interface)
* [Handling Session Updates](/clients/handling-updates)
* [Protocol Documentation](https://agentclientprotocol.com/protocol/overview)
