Go library for the Agent Client Protocol (ACP) - a standardized communication protocol between code editors and AI‑powered coding agents.
Learn more about the protocol itself at https://agentclientprotocol.com.
go get github.com/coder/acp-go-sdk@v0.20.0The SDK has its own semver, separate from the ACP schema version.
acp.SchemaVersion names the ACP schema release that an SDK version targets.
Upgrading from v0.19.x? v0.20.0 makes every planned API break at once: follow MIGRATION_v0.20.md.
Start by reading the official ACP documentation to understand the core concepts and protocol specification.
The examples directory contains simple implementations of both Agents and Clients in Go. You can run them from your terminal or connect to external ACP agents.
go run ./example/agentstarts a minimal ACP agent over stdio.go run ./example/claude-codedemonstrates bridging to Claude Code.go run ./example/clientconnects to a running agent and streams a sample turn.go run ./example/geminibridges to the Gemini CLI in ACP mode (flags: -model, -sandbox, -yolo, -debug, -gemini /path/to/gemini).go run ./example/proxyis a proxy for a conductor to run between a client and an agent (see Proxy role (unstable)).
You can watch the interaction by running go run ./example/client locally.
Browse the Go package docs on pkg.go.dev for detailed API documentation:
If you're building an Agent:
- Implement the
acp.Agentinterface. Every other agent method has its own optional interface, such asacp.AgentLoaderforsession/loadandacp.AgentUnstableForkSessionfor the unstablesession/fork. Implement the ones you support: the connection answers the others with-32601(method not found), and ignores their notifications with a Debug log record. Assert each one you implement, for examplevar _ acp.AgentLoader = (*myAgent)(nil): when a schema release changes the method, your build fails, instead of the method turning into-32601. - Create a connection with
acp.NewAgentSideConnection(agent, os.Stdout, os.Stdin). Until yourInitializereturns without an error, the connection answers every other request with-32600(invalid request) and drops every notification, so your agent sees nothing beforeinitialize. - Send updates and make client requests using the returned connection.
If you're building a Client:
- Implement the
acp.Clientinterface. It includes the terminal methods (CreateTerminal,TerminalOutput,ReleaseTerminal,WaitForTerminalExit,KillTerminal) and the elicitation methods (CreateElicitation,CompleteElicitation). A client that does not offer a capability returnsacp.NewMethodNotFoundfrom its methods and leaves the capability out ofClientCapabilities. Every other client method, such as the unstablemcp/message, has its own optional interface (acp.ClientUnstableMessageMcp). - Launch or connect to your Agent process (stdio), then create a connection with
acp.NewClientSideConnection(client, stdin, stdout). - Call
Initialize,NewSession, andPromptto run a turn and stream updates.
Helper constructors are provided to reduce boilerplate when working with union types:
- Content blocks:
acp.TextBlock,acp.ImageBlock,acp.AudioBlock,acp.ResourceLinkBlock,acp.ResourceBlock. - Tool content:
acp.ToolContent,acp.ToolDiffContent,acp.ToolTerminalRef. - Utility:
acp.Ptr[T]for pointer fields in request/update structs.
ACP supports extension methods for custom JSON-RPC methods whose names start with _.
Use them to add functionality without conflicting with future ACP versions.
Implement acp.ExtensionMethodHandler on your Agent or Client. Your handler will be
invoked for any incoming method starting with _.
// HandleExtensionMethod handles ACP extension methods (names starting with "_").
func (a MyAgent) HandleExtensionMethod(ctx context.Context, method string, params json.RawMessage) (any, error) {
switch method {
case "_example.com/hello":
var p struct {
Name string `json:"name"`
}
if err := json.Unmarshal(params, &p); err != nil {
return nil, err
}
return map[string]any{"greeting": "hello " + p.Name}, nil
default:
return nil, acp.NewMethodNotFound(method)
}
}Note: Per the ACP spec, unknown extension notifications should be ignored. This SDK suppresses noisy logs for unhandled extension notifications that return “Method not found”.
From either side, use CallExtension / NotifyExtension on the connection.
raw, err := conn.CallExtension(ctx, "_example.com/hello", map[string]any{"name": "world"})
if err != nil {
return err
}
var resp struct {
Greeting string `json:"greeting"`
}
if err := json.Unmarshal(raw, &resp); err != nil {
return err
}
if err := conn.NotifyExtension(ctx, "_example.com/progress", map[string]any{"pct": 50}); err != nil {
return err
}Note: A request returns after the handlers of all notifications that arrived before its response have returned. To make a request from a notification handler, such as
SessionUpdate, pass the handler'sctxor a ctx derived from it. With any other ctx, the request waits for the handler that made it, so it returns only when that ctx ends or the peer disconnects. A goroutine that the handler starts with the handler'sctxalso skips the wait for later notifications while the handler runs: give it a ctx that does not derive from the handler'sctxif it needs the full wait.
ACP uses the _meta field inside capability objects as the negotiation/advertising
surface for extensions.
- Client -> Agent:
InitializeRequest.ClientCapabilities.Meta - Agent -> Client:
InitializeResponse.AgentCapabilities.Meta
Meta keeps each value as raw JSON. Set encodes a Go value and Get decodes one:
caps := acp.ClientCapabilities{}
if err := caps.Meta.Set("example.com/feature", map[string]any{"version": 2}); err != nil {
return err
}
var feature struct{ Version int }
if err := resp.AgentCapabilities.Meta.Get("example.com/feature", &feature); err == nil {
// The agent supports the extension.
}The ACP spec
reserves the root-level _meta keys traceparent, tracestate, and baggage for W3C
trace context/OpenTelemetry compatibility. This SDK does not read or set these keys.
In an ACP proxy chain, a conductor stands between a client and a chain of components: proxies, then the agent. Each proxy can read and change the messages that pass it. The RFD is a draft, so this API is unstable.
A proxy talks only to its conductor. Messages from the client side arrive as
they are, and messages to and from the proxy's successor travel wrapped in
proxy/successor. acp.NewUnstableProxySideConnection speaks both, so a
handler sees plain typed messages:
conn := acp.NewUnstableProxySideConnection(func(c *acp.UnstableProxySideConnection) acp.UnstableProxyHandlers {
return acp.UnstableProxyHandlers{FromSuccessor: acp.UnstableProxyFromSuccessor{
SessionUpdate: func(ctx context.Context, n acp.SessionNotification) error {
// Change n, then send it on to the client.
return c.Client().SessionUpdate(ctx, n)
},
}}
}, os.Stdout, os.Stdin)
<-conn.Done()FromClienthandles the messages from the client side,FromSuccessorthose from the successor. Each field is named and typed as theAgentorClientmethod, soFromClient.Prompt = c.Successor().Promptcompiles.- A nil handler forwards its message unchanged, so the zero handlers pass
everything through. Messages of unknown and extension methods are forwarded
too. The result of a forwarded request comes back unchanged, and an error
comes back with its
code,messageanddata; other members of the error object are dropped. c.Client()sends to the client side as it is.c.Successor()sends to the successor, wrapped inproxy/successor.- The conductor initializes a proxy with
proxy/initialize. Without anUnstableInitializeProxyhandler, the proxy sends it on asinitialize. A handler must sendinitializewithc.Successor().Initializebefore it answers, and must not changeprotocolVersion. A plaininitializegets-32600. - A handler gets its message decoded into this SDK's Go types, so members that
those types do not know are lost. A nil handler keeps the bytes. A message
that does not decode for its handler, such as a
session/updateof a kind from a newer schema, goes on unchanged as with a nil handler, with a Debug log. WithRejectUndecodable, such a request gets-32602and such a notification is dropped instead. $/cancel_requestis per hop and never forwarded. A plain one or one wrapped inproxy/successorcancels the handler of the request it names, and a request that the handler sent with its ctx gets the proxy's own$/cancel_request.session/cancelis forwarded like any notification.- Each side keeps its order: what the proxy sends on for the messages of one
side, including what a handler sends with its ctx in place of its message,
goes out in the order those messages arrived. So a
session/cancelsent right after itssession/promptreaches the agent second. A handler holds back the later messages of its side until it sends a request and waits for the answer, or returns, so one that answers a request itself or works long before it sends delays them, and notifications queued behind them count againstWithMaxQueuedNotifications. - The proxy knows which handler sends only by the ctx of the send, so a
handler must send with its ctx or one derived from it, such as
context.WithoutCancel(ctx). A handler that sends a request withcontext.Background()keeps holding back its side until it returns, so the proxy deadlocks when the answer needs a later message of that side, such as the client's answer to a permission request that the agent sends before it answers the prompt.
example/proxy adds [proxy] in front of each agent
message chunk. Run it in a chain with the Rust conductor
(cargo install agent-client-protocol-conductor):
agent-client-protocol-conductor agent "go run ./example/proxy" "go run ./example/agent"For a complete, production‑ready integration, see the
Gemini CLI Agent which exposes an
ACP interface. The Go example client example/gemini demonstrates connecting
to it via stdio.
Package acp (module github.com/coder/acp-go-sdk, go 1.21, no require directives) implements both ends of ACP as JSON-RPC 2.0 messages, one JSON object per line.
Connection reads lines from the peer, routes requests, responses, and notifications, and serializes writes [connection.go:Connection].
AgentSideConnection and ClientSideConnection wrap a Connection and dispatch inbound methods to your Agent or Client implementation [agent.go:AgentSideConnection] [client.go:ClientSideConnection].
The wire types, method-name constants, inbound dispatch switches, outbound wrapper methods, and union constructors live in the *_gen.go files.
cmd/generate writes these files from the schemas in schema/, and schema/version pins the ACP release.
The hand-written files add errors, extension methods, and builder helpers.
- Connections:
NewAgentSideConnection(agent Agent, peerInput io.Writer, peerOutput io.Reader, opts ...ConnectionOption) *AgentSideConnectionandNewClientSideConnection(client Client, peerInput io.Writer, peerOutput io.Reader, opts ...ConnectionOption) *ClientSideConnection. Both types haveDone() <-chan struct{}andSetLogger(*slog.Logger)[agent.go:NewAgentSideConnection] [client.go:NewClientSideConnection] - Connection limits: each
ConnectionOptionsets one limit on what a connection holds from the peer.WithByteBudget(n)sets the bytes of held requests, of held notifications, and of rejections that wait to be written, n for each (64 MiB by default),WithMaxInboundRequests(n)the held requests (1024), andWithMaxQueuedNotifications(n)the notifications that wait for the running notification handler (1024). Each panics when n < 1 [limits.go:ConnectionOption, WithByteBudget, WithMaxInboundRequests, WithMaxQueuedNotifications] - Interfaces you implement:
AgentandClient, whose methods are the stable methods of ACP schema 1.25.0, and one optional interface for each other method, named after the side and the Go method, such asAgentUnstableForkSessionandClientUnstableMessageMcp. The optional interface ofLoadSessionkeeps its nameAgentLoader. A schema release never adds a method toAgentorClient: a method that it adds or makes stable gets its own optional interface [types_gen.go:Agent, AgentLoader, Client] [cmd/generate/internal/ir/baseline.go:requiredMethods]. OptionallyExtensionMethodHandlerfor_-prefixed methods [extensions.go:ExtensionMethodHandler] - Outbound calls:
ClientSideConnectionhas one method per agent method, for exampleInitialize,NewSession,Prompt, andCancel[client_gen.go:Initialize, NewSession, Prompt, Cancel].AgentSideConnectionhas one method per client method, for exampleSessionUpdate,RequestPermission,ReadTextFile, andCreateTerminal[agent_gen.go:SessionUpdate, RequestPermission, ReadTextFile, CreateTerminal]. Both types haveCallExtensionandNotifyExtension[extensions.go:CallExtension, NotifyExtension] mcp/message(unstable) has two forms. An agent sends the request with(*AgentSideConnection).UnstableMessageMcp, and a client answers it inClientUnstableMessageMcp. A client sends the notification with(*ClientSideConnection).UnstableMessageMcp, and an agent receives it inAgentUnstableMessageMcp[agent_gen.go:handle, UnstableMessageMcp] [client_gen.go:handle, UnstableMessageMcp]- Proxy role (unstable):
NewUnstableProxySideConnection(handlers func(*UnstableProxySideConnection) UnstableProxyHandlers, peerInput io.Writer, peerOutput io.Reader, opts ...ConnectionOption).UnstableProxyHandlersholdsFromClient(proxy/initializeand every agent method butinitialize) andFromSuccessor(every client method), structs of func fields where nil forwards the message unchanged, andRejectUndecodable.Client()has one method per client method, andSuccessor()one per agent method,initializeincluded, each wrapped inproxy/successor[proxy.go] [proxy_gen.go] - Low-level transport:
Connection,NewConnection(handler MethodHandler, peerInput io.Writer, peerOutput io.Reader, opts ...ConnectionOption),MethodHandler,SendRequest[T](a generic function that takes the*Connection),(*Connection).SendRequestNoResult,(*Connection).SendNotification,(*Connection).SetLogger, and(*Connection).Done[connection.go:NewConnection, MethodHandler, SendRequest, SendRequestNoResult, SendNotification, SetLogger, Done] - Wire types: one struct per request, response, and notification, union wrappers with one pointer field per variant, and named
stringenums with constants such asStopReason,ToolKind,ToolCallStatus, andPermissionOptionKind[types_gen.go:StopReason, ToolKind, ToolCallStatus, PermissionOptionKind].ExtNotification,ExtRequest, andExtResponseare aliases ofjson.RawMessage, so they have no generated fields and noValidate[types_gen.go:ExtNotification, ExtRequest, ExtResponse] - Free-form values: a value that the schema leaves free holds the JSON as it was read, so a number keeps every digit.
_metais aMeta, amap[string]json.RawMessagewithNewMeta,Get, andSet, and an empty one is left out of the message.Getof a missing key returns an error that wrapsErrMetaKeyNotFound.rawInput,rawOutput, thedataof an error (RequestError.Dataincluded), and the result ofmcp/messagearejson.RawMessage, and the params ofmcp/messageare amap[string]json.RawMessage[meta.go:Meta, NewMeta, Get, Set] [types_gen.go:ToolCall, UnstableMcpError] [errors.go:RequestError].RequestError.Datakeeps"data": null, while the generatedErrorreads it as no data, as its schema asks withx-deserialize-default-on-error[errors_test.go:TestRequestError_KeepsNullDataThatErrorDrops] - Typed maps: a map whose members have a schema takes their Go type.
ElicitationSchema.Propertiesis amap[string]ElicitationPropertySchema, theContentof an accepted elicitation is amap[string]ElicitationContentValue, andenvandheadersaremap[string]string.NewElicitationContentValueString,...Integer(anint64, as the schema'sformat: int64asks),...Number,...Boolean, and...StringArraybuild a content value [types_gen.go:ElicitationSchema, ElicitationAcceptAction] [helpers.go:NewElicitationContentValueString] - Integers: each integer has the Go type of the Rust type that its schema
formatnames,int32,int64,uint16,uint32oruint64, such asuint32forReadTextFileRequest.Line,uint64for the token counts ofUsageanduint16forProtocolVersion. A value out of that range, a negative value or-0in an unsigned integer, and a number with a fraction or an exponent fail to decode, as in the Rust SDK, and no generated field can hold one.-0in a signed integer reads as 0, where the Rust SDK rejects it in most fields.RequestError.Codestays anint, so a handler can send a code outsideint32, which the Rust SDK rejects [errors.go:RequestError]. Auint64takes every value up to 2^64-1; a TypeScript peer reads one above 2^53 rounded to a JavaScript number [types_gen.go:ReadTextFileRequest, Usage, ProtocolVersion] [integer_test.go:TestIntegers_ReadTheRangeOfTheirFormat] - Patch fields: the optional fields of an update that changes a stored value, such as
ToolCallUpdate,SessionInfoUpdate,CompactionUpdate,SubagentUpdateandSessionMessage, arePatch[T]. Its zero value is unset (the member is absent: unchanged),PatchNull[T]()writesnull(clear),PatchSet(v)writesv, a nil slice or map as[]or{}(but a niljson.RawMessageasnull), andPatchFromPtr(p)sets*p, or leaves the field unset for a nilp. Read one withValue() (T, bool),Ptr()(nil unless set),IsNull(), andIsUnset(). ACP v1 defines no clear for the fields of aToolCallUpdate, for_metaof aSessionInfoUpdateand foranchorof the unstableCursorUpdate:nullthere leaves the stored value unchanged, as the protocol docs say forname,rawInput,rawOutputandanchor, and as the Rust SDK reads it. So the SDK reads such anullas unset, and leaves the member out forPatchNullthere. A setPatchwhose value encodes as JSONnull, such as a niljson.RawMessage, isnullon the wire and reads back asIsNull(), or as unset in such a field. The generated structs leave an unset field out; in a struct of your own, tag aPatchfieldomitzero(Go 1.24 or later), sinceomitemptywrites an unset one asnull. TheWithUpdate*options set their field withPatchSet, except that a nil slice toWithUpdateContentorWithUpdateLocations, or a nil value toWithUpdateRawInputorWithUpdateRawOutput, leaves it unset. A value thatjson.Marshalcannot encode, such as a channel or a NaN, makes an update fromWithUpdateRawInputorWithUpdateRawOutputfail to encode, so sending it returns the error, whileWithStartRawInputandWithStartRawOutputleave it out, because their field is a plainjson.RawMessage[patch.go:Patch, PatchFromPtr] [helpers.go:WithUpdateContent, WithUpdateRawInput, WithStartRawInput] [patch_test.go:TestPatch_NullWhereTheSchemaDefinesNoClearIsUnset] - Unstable types: one Go type per shape. The Request, Response, and Notification types of unstable-only methods, and the definitions that only they reach, get the
Unstableprefix, such asUnstableForkSessionRequestandUnstableProviderInfo. A type that stable and unstable methods share keeps its name and carries the unstable additions, each with a doc comment that starts with**UNSTABLE**, as the Rust SDK gates them behind a feature:SessionConfigOption,McpServerwith itsAcpvariant, and the constantSessionConfigOptionCategorySpeed. Definitions that exist only inschema/schema.unstable.jsonand that stable methods reach keep their names too, for exampleCursorUpdateandSessionCursorsCapabilities[cmd/generate/internal/load/merge.go:buildUnstableDuplicateSet, promoteChangedSharedDefs, markUnstableAdditions, ensureRefsAvailable] - Constants:
ProtocolVersionNumber(1),SchemaVersion(the ACP schema release inschema/version), plus 24AgentMethod*, 13ClientMethod*, 1ProtocolMethod*, and 2ProxyMethod*wire-name constants, for exampleAgentMethodSessionPrompt(session/prompt) andProtocolMethodCancelRequest($/cancel_request) [constants_gen.go:ProtocolVersionNumber, AgentMethodSessionPrompt] - Errors:
RequestError(Code,Message, andData, the raw JSON of the error's data) and its constructorsNewRequestError(code, message, data),NewParseError(-32700),NewInvalidRequest(-32600),NewMethodNotFound(-32601),NewInvalidParams(-32602),NewInternalError(-32603),NewRequestCancelled(-32800),NewAuthRequired(-32000), andNewResourceNotFound(-32002, for a session or file that does not exist; for a session, setdata.sessionId) [errors.go:RequestError]. Each constructor encodes itsdataargument as JSON; a nil one, or one that does not encode, gives noData.NewMethodNotFoundsetsDatato{"method": method}[errors.go:NewRequestError, NewMethodNotFound].(*RequestError).Errorreturns the JSON of code, message, and data,<nil>for a nil receiver, and the textcode %d: %s(with(data: %s)appended whenDatais set) whenDatais not valid JSON [errors.go:Error] - Builders: content blocks (
TextBlock,ImageBlock,AudioBlock,ResourceLinkBlock,ResourceBlock), tool content (ToolContent,ToolDiffContent,ToolTerminalRef), session updates (UpdateUserMessage,UpdateAgentMessage,UpdateAgentThought, their*Textforms, andUpdatePlan), tool calls (StartToolCall,StartReadToolCall, andStartEditToolCallwithWithStart*options,UpdateToolCallwithWithUpdate*options), andPtr[T][helpers.go]. GeneratedNew<Union><Variant>constructors, for exampleNewRequestPermissionOutcomeSelected[helpers_gen.go:NewRequestPermissionOutcomeSelected]
- The
*_gen.gofiles, andtypes_gen_test.gowith the type lists that the tests check, start withCode generated by acp-go-generator; DO NOT EDIT.Changecmd/generateinstead of editing them, then runmake generate[Makefile:generate] [constants_gen.go] [types_gen.go] [decode_fast_gen.go] [types_gen_test.go] [agent_gen.go] [client_gen.go] [proxy_gen.go] [helpers_gen.go] - Notifications from the peer run one at a time, in arrival order, on one goroutine [connection.go:processNotifications]
- A request from the peer starts its handler only after the handlers of all notifications that arrived before it have finished, so a slow notification handler delays every later request. Notifications that arrive after the request do not delay it. There are two exceptions. First, it also starts while the running notification handler waits for a peer response, because the peer can need this answer first. Second, when the peer disconnects during the wait, the handler starts at once with a cancelled ctx, so it can clean up while earlier notification handlers still run [connection.go:receive, waitInboundBarrier, waitNotifications, startPeerWait] [connection_inbound_request_barrier_test.go:TestConnection_SlowNotificationDelaysLaterMessages]
- After a response arrives,
SendRequestandSendRequestNoResultreturn only after the handlers of all notifications that arrived before the response have finished, or when the ctx ends or the peer disconnects. Before a response, they return at once when the params do not marshal (-32602) or the write fails (-32603). In a notification handler, a request made with the handler's ctx (or a ctx derived from it) waits only for the earlier notifications. While the handler of a request from the peer runs, a request made with the handler's ctx (or a ctx derived from it) also returns while the running notification handler waits for a peer response, as the handler's start does [connection.go:SendRequest, SendRequestNoResult, prepareRequest, waitNotificationsUpTo, runningRequestHandler] - A response that does not decode, such as one whose error
codeis not an integer or does not fit anint(2^63 on amd64, 2^31 on 386), still ends its call:SendRequestandSendRequestNoResultreturn a-32603error whose data holds the decode error (error) and the error object as it was read (response). A line that does not decode and is not a JSON object with anidand nomethodis logged and skipped [connection.go:receive, readUnreadableResponse] [connection_error_response_test.go:TestConnection_SendRequest_FailsOnAnErrorObjectThatDoesNotDecode] - The read loop handles a
$/cancel_requestnotification (a message without an id) from the peer at once, outside notification order. It cancels the in-flight request with the same id and ignores an unknown id. When that request still waits for earlier notification handlers, the peer gets a-32800error response and the handler never runs. A cancel that arrives after that wait has ended, even just before the handler starts, only cancels the handler's ctx. When the peer disconnects right after the cancel, the waiting request can see the disconnect first, and its handler then starts with a cancelled ctx, as on any disconnect during the wait. A$/cancel_requestnotification never reaches theMethodHandler; a$/cancel_requestsent with an id goes to theMethodHandleras an ordinary request [connection.go:receive, handleCancelRequest, waitInboundBarrier] [connection_inbound_request_barrier_test.go:TestConnection_InboundRequestBarrierCancelThenDisconnect] - When the ctx of an outbound request ends before the response, the connection sends
$/cancel_requestfor that id to the peer withcontext.Background(). At most 1024 cancels wait in the queue (maxPendingCancelRequests). Extra cancels are dropped with a Debug log [connection.go:waitForResponse, sendCancelRequest, sendCancelRequests] - JSON-RPC ids must be a string or a number. A
nullid unmarshals as no id: a request with"id": nullruns as a notification and gets no reply, and a response with"id": nullis logged and skipped. Numeric ids are canonicalized, so equal values match one pending request. A numeric id can have at most 4096 digits in canonical form and an exponent magnitude of at most 4096 (maxCanonicalJSONRPCIDKeyLen,maxCanonicalJSONRPCIDAbsExp10). When an inbound request id fails this check, the connection logs it and uses the raw id text [connection.go:canonicalJSONRPCIDKey, receive] - A connection holds each request from the peer from when it reads it until its reply is written, each notification until its handler returns, and each rejection until it is written. Requests, notifications, and rejections each count against their own byte budget (
WithByteBudget, 64 MiB by default), so held requests never close the connection on a notification such assession/cancel, and what the connection counts stays within three times the budget. A message counts the length of its line, and a request also the length of its canonical id, which the connection keeps a second time. A request that does not fit the budget, or that arrives while the connection holds the most requests (WithMaxInboundRequests, 1024 by default), gets a-32603reply, and its handler does not run. Responses and$/cancel_requestnotifications count against no limit [limits.go:peerBudget, holdRequest, holdNotification, holdRejection] [connection.go:receive, processNotifications] - The read loop never blocks on writing a rejection: it queues the
-32603reply for one writer goroutine with a non-blocking send, so two connections that flood each other with requests both go on reading. When 1024 rejections wait to be written (maxQueuedRejections), or a rejection does not fit the byte budget while another waits, the connection closes, because the peer does not read its replies [limits.go:maxQueuedRejections, holdRejection] [connection.go:receive, queueRejection, writeRejections] - The connection closes when a notification from the peer does not fit the byte budget, when more notifications are queued than
WithMaxQueuedNotificationsallows (1024 by default), when the rejection queue is full, or when an input line, without its newline, is 10 MiB (maxBufSize) or longer. Other bad input does not close it: the read loop skips blank lines, and it logs and skips a line that is not valid JSON or a message with neither id nor method. Every log record of the connection carries at most the first 1 KiB of each text value, such as that line, an id, a method, or an error that quotes the peer (a decode error copies a number that does not fit), and then the value's length (maxLoggedPeerBytes) [connection.go:log, logValue, peerText] - On disconnect,
Done()closes at once. Waiting callers fail, and the contexts of inbound request handlers (derived from the connection context) are cancelled at the same time. Queued notifications then drain for up to 5 s, and only then are the contexts of notification handlers cancelled [connection.go:shutdownReceive, receive, processNotifications, notificationQueueDrainTimeout] - The connection never closes
peerInputorpeerOutput. A write to a peer that stopped reading blocks, every later write waits behind it, and neitherDone()nor a ctx ends it.Done()closes when the peer's output ends or the connection closes itself on a limit, so a hung peer that sends nothing may never close it. Closing the transport ends the write: anio.Pipe, anos.Pipe, anet.Connor a child's stdin. Close it once you are done with the connection (afterDone()and the handlers that still reply, or on a deadline of your own), not at once whenDone()closes, because a peer that closed only its output still reads its replies. Closingos.Stdoutends the write only in non-blocking mode. A child's stdout pipe from os/exec, Node or Python is in blocking mode, soClosereturns nil and the write stays blocked: an agent on stdout must exit to end it [connection.go:NewConnection, writeLine] [connection_transport_test.go:TestConnection_CloseTransportEndsBlockedWrite] [connection_stdout_test.go:TestConnection_CloseStdoutEndsBlockedWriteOnlyIfNonBlocking] - For the generated ACP methods, inbound params are unmarshalled into the generated type and checked with
Validate(). Extension methods (_-prefixed) reachExtensionMethodHandleras the rawjson.RawMessage, so the handler must decode and validate them itself [extensions.go:handleWithExtensions]. For a request, a failure returns-32602(NewInvalidParams), and an unknown method returns-32601(NewMethodNotFound), as does a method of an optional interface that your implementation does not have. A notification never gets a reply: the connection logs a decode or handler failure at Error instead, and an unknown or unimplemented notification (-32601) at Debug asignored unhandled notification[agent_gen.go:handle] [client_gen.go:handle] [connection.go:handleInbound] - Handler errors pass through
toReqErr: a*RequestErroris sent unchanged,context.Canceledbecomes-32800, and any other error becomes-32603[errors.go:toReqErr]. A*RequestErrorwhoseDatais not valid JSON does not encode, so the request gets a-32603response instead [connection.go:handleInbound] - Extension method names must start with
_.CallExtensionandNotifyExtensionreject other names before they send. Inbound_methods go toExtensionMethodHandler. When it is not implemented, a_request gets-32601, and a_notification is dropped with no reply and no log line. Other unhandled notifications are logged at Debug [extensions.go:validateExtensionMethodName, handleWithExtensions] [connection.go:handleInbound] - Agent side: until the
Agent'sInitializereturns without an error, every other request from the client,_extension requests included, gets-32600with data{"error": "initialize must complete before <method>"}, and every notification is dropped with a Debug log record. Neither reaches theAgent. A message that arrived before theinitializethat succeeded is held back the same way even when its handler runs after thatinitializereturned, and a request whose handler starts whileinitializeruns gets-32600too, so a client sends other requests only after theinitializereply; a failedinitializeleaves the connection uninitialized, and aninitializeafter a successful one reaches theAgentagain. The read loop still handles$/cancel_requestbeforeinitialize[agent.go:handleBeforeInitialize] [extensions.go:handleWithExtensions] - Agent side: each inbound
session/promptruns with its own cancellable ctx, and an inboundsession/cancelcancels that ctx beforeAgent.Cancelruns. A prompt that arrived before a cancel but registers after it is cancelled at once. At most 1024 of these cancel markers are kept. The connection keys them by the SHA-256 of the sessionId, so a marker has a fixed size whatever the length of the id. The cancel runs in notification order, so it can reach a running prompt late: when an earlier notification handler waits for a client response, aRequestPermissioninPromptcan return the client's answer, sent after the cancel, while the prompt's ctx is still live. The ctx ends once the earlier handler returns and the cancel runs [agent_gen.go:handle] [agent.go:registerPrompt, cancelPrompt, maxCancelMarkers, sessionKey] [connection.go:waitNotificationsUpTo, runningRequestHandler] [agent_session_cancel_test.go:TestAgentSideConnection_SessionCancelReachesPromptLateAfterPeerWait] - Client side: when
ClientSideConnection.Promptfails after its ctx ended, it sendssession/cancelwithcontext.Background()[client_gen.go:Prompt] - Union wrappers:
Validateon aoneOfunion requires exactly one variant to be set, and on ananyOfunion one at least. It then validates the set variant, which rejects a missing required member at any depth, such as theserverIdof anacpMCP server, and an emptymessageofCreateElicitationRequest.MarshalJSONof a union with no variant set returns the error<Union> has no variant set, sojson.Marshaland the connection's send methods fail on it asValidatedoes.UnmarshalJSONreturnsno matching variant for unionwhen no variant fits [types_gen.go:ContentBlock.Validate, McpServer.Validate, CreateElicitationRequest.Validate, SessionUpdate.MarshalJSON, SessionUpdate.UnmarshalJSON] - Capability structs fill schema defaults on decode when a key is missing or
null. For example, a missingClientCapabilities.fsbecomes{"readTextFile":false,"writeTextFile":false}[types_gen.go:ClientCapabilities.UnmarshalJSON] StartReadToolCallapplies kindread, statuspending, one location, andrawInput {"path"}before the caller's options.StartEditToolCallapplies kindedit, statuspending, one location, andrawInput {"content", "path"}[helpers.go:StartReadToolCall, StartEditToolCall]
NewConnectionstarts 5 goroutines: a ctx-done broadcaster, the cancel sender, the read loop, the notification processor, and the rejection writer. Each inbound request that the connection holds runs in its own goroutine [connection.go:NewConnection, receive]- The read loop reads the peer output with a
bufio.Scanner(1 MiB initial buffer, 10 MiB maximum line).sendMessageandwriteRejectionswrite each message plus\nto the peer input while they holdwriteMu[connection.go:receive, sendMessage, writeRejections, writeLine] - Diagnostics go to the logger from
SetLogger, or toslog.Default()when none is set [connection.go:loggerOrDefault] - The connection panics when an internal sequence invariant breaks, for example a notification that would run out of order [connection.go:processNotifications, startPeerWait]
WithStartLocationswith exactly one location that has a non-emptyPathmirrors that path intoRawInput. It creates{"path": ...}whenRawInputis nil, adds apathmember to aRawInputobject that has none, and leaves any otherRawInputunchanged [helpers.go:WithStartLocations, withPath]
- cmd: ./cmd/README.md - Command-line programs.
cmd/generateis a separate Go module that readsschema/and writes the root*_gen.gofiles. - example: ./example/README.md - Five
package mainprograms on the publicacpAPI: a scripted agent, a demo client, REPL clients for Claude Code and the Gemini CLI, and a proxy. - schema (no contract file): the ACP JSON schemas (
meta.json,schema.json,meta.unstable.json,schema.unstable.json) and theversionpin. Input ofcmd/generate. - testdata (no contract file): golden JSON payloads in
testdata/json_golden, used byjson_parity_test.go.
versionholds the SDK's own semver, andschema/versionpins the ACP schema release. They move apart: a release can change the SDK without a new schema.make generateandmake releasenever derive one from the other.cmd/generatewritesschema/versioninto theSchemaVersionconstant, and themdshblock in this README prints thego getline fromversion. A schema bump commits the schemas, the generated Go, andschema/versiontogether [Makefile:generate, release] [cmd/generate/main.go:main]- The generated
handleswitches use unexported names from the hand-written root files:registerPrompt,cancelPrompt,sessionCancels, andmu[agent.go],handlers,isNotification,forward,undecodable,decodeParams,notify,proxyRequest,clientSide, andsuccessorSide[proxy.go], andtoReqErr[errors.go]. Rename them only together withcmd/generate/internal/emit[cmd/generate/internal/emit/dispatch.go] [cmd/generate/internal/emit/dispatch_helpers.go] [cmd/generate/internal/emit/proxy.go] cmd/generateemits no constructors forContentBlock,ToolCallContent, andSessionUpdate. Their builders are hand-written inhelpers.go[cmd/generate/internal/emit/helpers.go:WriteHelpersJen]- The root module uses only the standard library. Only
cmd/generatedepends ongithub.com/dave/jennifer[go.mod] [cmd/generate/go.mod] - The examples import only
github.com/coder/acp-go-sdkfrom this module, so they exercise the public API only [example/agent/main.go] [example/client/main.go] [example/claude-code/main.go] [example/gemini/main.go] [example/proxy/main.go]
make generatedownloads a schema file fromhttps://github.com/agentclientprotocol/agent-client-protocol/releasesonly when that file is older thanschema/version. A 0.x schema comes from thev<version>release tag, and 1.0 or later fromschema-v<version>. When the release has no unstable schema file (HTTP 404), it writes an empty placeholder ({"agentMethods":{},"clientMethods":{},"protocolMethods":{}}or{"$defs":{}}) and continues. It then runscmd/generate, which overwrites the five*_gen.gofiles.make release VERSION=<sdk> [SCHEMA=<schema>]writesversion(andschema/version), then runsgenerate,fmt, andtest[Makefile:generate, release]- The SDK speaks ACP only over the
io.Readerandio.Writeryou pass in. Its diagnostics (for example an Info line on every disconnect, and Error lines for malformed input) go toslog.Default(), which writes to stderr unless you change it, or to the logger set withSetLogger. The root package opens no file, network connection, or subprocess. The examples do: they start child processes (npx,gemini,go run) and read and write local files when the agent asks
- Run:
make test(runsgo vet ./...,go test ./...,go build ./example/...,go vetandgo testin the separatecmd/generatemodule, and theacpwiredriver tests) - Run:
make check(runstreefmt, thengit diff --exit-code. It needs the formatters frommise install)
Apache 2.0. See LICENSE.