Skip to main content

Overview

The AgentSideConnection class provides the agent’s view of an ACP connection, allowing agents to communicate with clients. It implements the Client interface and manages the bidirectional JSON-RPC communication channel.

Class Definition

class AgentSideConnection implements Client
This class:
  • Wraps the low-level Connection for agent-to-client communication
  • Routes incoming client requests to the appropriate Agent handler methods
  • Provides methods for agents to call client endpoints (file system, terminals, permissions)
  • Handles protocol-level concerns like request validation and method routing

Constructor

AgentSideConnection

Creates a new agent-side connection to a client.
AgentSideConnection(
  Agent Function(AgentSideConnection) toAgent,
  AcpStream stream,
)
This establishes the communication channel from the agent’s perspective following the ACP specification.
toAgent
Agent Function(AgentSideConnection)
required
A function that creates an Agent handler to process incoming client requests. The function receives the connection instance and returns an Agent implementation.
stream
AcpStream
required
The bidirectional message stream for communication. Typically created using ndJsonStream for stdio-based connections.

Client Interface Methods

The following methods implement the Client interface and allow agents to make requests to the client.

requestPermission

Requests permission from the user for a tool call operation.
Future<RequestPermissionResponse> requestPermission(
  RequestPermissionRequest params,
)
params
RequestPermissionRequest
required
The permission request with tool details and options
RequestPermissionResponse
RequestPermissionResponse
The user’s permission decision

sessionUpdate

Sends session update notifications to the client.
Future<void> sessionUpdate(SessionNotification params)
params
SessionNotification
required
Notification containing session updates, messages, and tool calls

readTextFile

Reads content from a text file in the client’s file system.
Future<ReadTextFileResponse> readTextFile(ReadTextFileRequest params)
params
ReadTextFileRequest
required
Request containing the file path to read
ReadTextFileResponse
ReadTextFileResponse
The file content

writeTextFile

Writes content to a text file in the client’s file system.
Future<WriteTextFileResponse> writeTextFile(WriteTextFileRequest params)
params
WriteTextFileRequest
required
Request containing the file path and content to write
WriteTextFileResponse
WriteTextFileResponse
Confirmation of the write operation

Terminal Methods

createTerminal

Creates a new terminal to execute a command.
Future<CreateTerminalResponse>? createTerminal(CreateTerminalRequest params)
params
CreateTerminalRequest
required
Request containing the command and terminal configuration
CreateTerminalResponse
CreateTerminalResponse
The terminal ID for future operations

terminalOutput

Gets the current output and exit status of a terminal.
Future<TerminalOutputResponse>? terminalOutput(TerminalOutputRequest params)
params
TerminalOutputRequest
required
Request containing the session ID and terminal ID
TerminalOutputResponse
TerminalOutputResponse
Current stdout, stderr, and exit status

releaseTerminal

Releases a terminal and frees all associated resources.
Future<ReleaseTerminalResponse?>? releaseTerminal(
  ReleaseTerminalRequest params,
)
params
ReleaseTerminalRequest
required
Request containing the session ID and terminal ID
ReleaseTerminalResponse
ReleaseTerminalResponse
Confirmation of terminal release

waitForTerminalExit

Waits for a terminal command to exit and returns its exit status.
Future<WaitForTerminalExitResponse>? waitForTerminalExit(
  WaitForTerminalExitRequest params,
)
params
WaitForTerminalExitRequest
required
Request containing the session ID and terminal ID
WaitForTerminalExitResponse
WaitForTerminalExitResponse
Exit code and signal information

killTerminal

Kills a terminal command without releasing the terminal.
Future<KillTerminalCommandResponse?>? killTerminal(
  KillTerminalCommandRequest params,
)
params
KillTerminalCommandRequest
required
Request containing the session ID and terminal ID
KillTerminalCommandResponse
KillTerminalCommandResponse
Confirmation of terminal termination

Extension Methods

extMethod

Sends an arbitrary request that is not part of the ACP spec.
Future<Map<String, dynamic>>? extMethod(
  String method,
  Map<String, dynamic> params,
)
method
String
required
The extension method name
params
Map<String, dynamic>
required
Method parameters
result
Map<String, dynamic>
Extension method response

extNotification

Sends an arbitrary notification that is not part of the ACP spec.
Future<void>? extNotification(String method, Map<String, dynamic> params)
method
String
required
The extension notification name
params
Map<String, dynamic>
required
Notification parameters

Protocol-Level Methods

sendCancelRequest

Sends the protocol-level $/cancel_request notification.
Future<void> sendCancelRequest(CancelRequestNotification params)
params
CancelRequestNotification
required
Cancellation notification with request ID and optional metadata

cancelPendingRequest

Cancels a pending outbound request and sends $/cancel_request.
Future<bool> cancelPendingRequest(
  RequestId requestId, {
  Map<String, dynamic>? meta,
})
Returns true if the request ID was still pending locally.
requestId
RequestId
required
The ID of the request to cancel
meta
Map<String, dynamic>
Optional metadata to include in the cancellation notification
result
bool
true if the request was pending and was cancelled, false otherwise

Usage Example

import 'package:acp_dart/acp_dart.dart';

class MyAgent implements Agent {
  late AgentSideConnection connection;
  
  @override
  Future<InitializeResponse> initialize(InitializeRequest params) async {
    return InitializeResponse(
      protocolVersion: '1.0',
      capabilities: AgentCapabilities(
        loadSession: true,
        sessionModes: ['ask', 'code'],
      ),
    );
  }

  @override
  Future<PromptResponse> prompt(PromptRequest params) async {
    // Send a session update to the client
    await connection.sessionUpdate(SessionNotification(
      sessionId: params.sessionId,
      message: ContentMessage(
        role: Role.assistant,
        content: [TextContent(text: 'Processing your request...')],
      ),
    ));

    // Request permission before running a tool
    final permission = await connection.requestPermission(
      RequestPermissionRequest(
        sessionId: params.sessionId,
        tool: 'execute_command',
        description: 'Run npm install',
      ),
    );

    if (permission.outcome == RequestPermissionOutcome.allow) {
      // Read a file from the client's file system
      final fileContent = await connection.readTextFile(
        ReadTextFileRequest(path: '/path/to/file.txt'),
      );
      
      // Write results back
      await connection.writeTextFile(
        WriteTextFileRequest(
          path: '/path/to/output.txt',
          content: 'Results: ${fileContent.content}',
        ),
      );
    }

    return PromptResponse(stopReason: StopReason.endTurn);
  }

  // ... implement other Agent methods
}

void main() async {
  // Create stdio stream for communication
  final stream = ndJsonStream(
    stdin: stdin,
    stdout: stdout,
  );

  // Create the agent-side connection
  final connection = AgentSideConnection(
    (conn) {
      final agent = MyAgent();
      agent.connection = conn;
      return agent;
    },
    stream,
  );

  // Connection is now active and handling requests
}

Request Routing

The AgentSideConnection automatically routes incoming JSON-RPC requests to the appropriate Agent methods:

Error Handling

The connection automatically handles errors and converts them to JSON-RPC error responses:
  • RequestError instances are sent directly with their error codes
  • TypeError, FormatException, ArgumentError are converted to InvalidParams errors
  • Other exceptions become InternalError responses
  • Unknown methods return MethodNotFound errors

See Also

  • Agent - The Agent interface implemented by agent handlers
  • Client - The Client interface this class implements
  • Connection - The underlying connection class
  • ClientSideConnection - The client-side equivalent

Build docs developers (and LLMs) love