Skip to main content

agent_client_protocol/concepts/
connections.rs

1//! Establishing connections using role types and connection builders.
2//!
3//! To communicate over ACP, you need to establish a connection. This involves
4//! choosing a **role type** that matches your role and using a **connection builder**
5//! to configure and run the connection.
6//!
7//! # Choosing a Role Type
8//!
9//! Your role type determines what messages you can send and who you can send them to.
10//! Choose based on what you're building:
11//!
12//! | You are building... | Use this role type |
13//! |---------------------|-------------------|
14//! | A client that talks to an agent | [`Client`] |
15//! | An agent that responds to clients | [`Agent`] |
16//! | A proxy in a conductor chain | [`Proxy`] |
17//!
18//! # The Connection Builder Pattern
19//!
20//! Every role type has a `builder()` method that returns a connection builder.
21//! The builder lets you configure handlers, then connect to a transport:
22//!
23//! ```
24//! # use agent_client_protocol::{Client, Agent, ConnectTo};
25//! # async fn example(transport: impl ConnectTo<Client>) -> Result<(), agent_client_protocol::Error> {
26//! Client.builder()
27//!     .name("my-client")
28//!     .connect_with(transport, async |cx| {
29//!         // Use `cx` to send requests and handle responses
30//!         Ok(())
31//!     })
32//!     .await?;
33//! # Ok(())
34//! # }
35//! ```
36//!
37//! # The Connection Context
38//!
39//! Inside `connect_with`, you receive a [`ConnectionTo`] (connection context) that
40//! lets you interact with the remote peer:
41//!
42//! ```
43//! # use agent_client_protocol::{Client, Agent, ConnectTo};
44//! # use agent_client_protocol::schema::{ProtocolVersion, v1::InitializeRequest};
45//! # use agent_client_protocol_test::StatusUpdate;
46//! # async fn example(transport: impl ConnectTo<Client>) -> Result<(), agent_client_protocol::Error> {
47//! # Client.builder().connect_with(transport, async |cx| {
48//! // Send a request and wait for the response
49//! let response = cx.send_request(InitializeRequest::new(ProtocolVersion::V1))
50//!     .block_task()
51//!     .await?;
52//!
53//! // Send a notification (fire-and-forget)
54//! cx.send_notification(StatusUpdate { message: "hello".into() })?;
55//! # Ok(())
56//! # }).await?;
57//! # Ok(())
58//! # }
59//! ```
60//!
61//! # Clean Incoming EOF
62//!
63//! [`Builder::connect_to`](crate::Builder::connect_to) is reactive: it returns
64//! `Ok(())` when the incoming transport reaches clean EOF, after draining
65//! responses and notifications already accepted by its outgoing queue through
66//! the transport sink.
67//! [`Builder::connect_with`](crate::Builder::connect_with) is foreground-owned:
68//! EOF fails pending requests, but does not cancel unrelated work in its
69//! closure. This avoids dropping application futures at an arbitrary await
70//! point.
71//!
72//! Use [`ConnectionTo::incoming_closed`](crate::ConnectionTo::incoming_closed)
73//! to await EOF directly, or [`Builder::on_close`](crate::Builder::on_close)
74//! for cleanup and application-specific shutdown policy:
75//!
76//! ```
77//! # use agent_client_protocol::{Client, ConnectTo, Error};
78//! # async fn example(transport: impl ConnectTo<Client>) -> Result<(), Error> {
79//! Client.builder()
80//!     .on_close(async |_cx| {
81//!         // Notify application-owned work here. Returning an error also
82//!         // terminates a still-running connect_with foreground.
83//!         Ok(())
84//!     })
85//!     .connect_with(transport, async |cx| {
86//!         cx.incoming_closed().await;
87//!         Ok(())
88//!     })
89//!     .await?;
90//! # Ok(())
91//! # }
92//! ```
93//!
94//! Every request still waiting for a response at EOF is completed with an
95//! internal error whose data contains
96//! `{"reason":"incoming_transport_closed","method":"..."}`. Requests made
97//! after EOF fail the same way; use
98//! [`is_incoming_transport_closed`](crate::is_incoming_transport_closed) to
99//! identify this error. In `connect_with`, notification and response sends
100//! remain available so applications can choose their own half-close policy;
101//! reactive `connect_to` stops accepting them when its final drain begins.
102//!
103//! Pending requests are failed before close callbacks begin. The close signal
104//! is published after callbacks finish, so a callback must not await
105//! [`ConnectionTo::incoming_closed`](crate::ConnectionTo::incoming_closed)
106//! itself.
107//!
108//! # Sending Requests
109//!
110//! When you call `send_request()`, you get back a [`SentRequest`] that represents
111//! the pending response. You have two main ways to handle it:
112//!
113//! ## Option 1: Block and wait
114//!
115//! Use `block_task()` when you need the response before continuing:
116//!
117//! ```
118//! # use agent_client_protocol::{Client, Agent, ConnectTo};
119//! # use agent_client_protocol_test::MyRequest;
120//! # async fn example(transport: impl ConnectTo<Client>) -> Result<(), agent_client_protocol::Error> {
121//! # Client.builder().connect_with(transport, async |cx| {
122//! let response = cx.send_request(MyRequest {})
123//!     .block_task()
124//!     .await?;
125//! // Use response here
126//! # Ok(())
127//! # }).await?;
128//! # Ok(())
129//! # }
130//! ```
131//!
132//! ## Option 2: Schedule a callback
133//!
134//! Use `on_receiving_result()` when you want to handle the response asynchronously:
135//!
136//! ```
137//! # use agent_client_protocol::{Client, Agent, ConnectTo};
138//! # use agent_client_protocol_test::MyRequest;
139//! # async fn example(transport: impl ConnectTo<Client>) -> Result<(), agent_client_protocol::Error> {
140//! # Client.builder().connect_with(transport, async |cx| {
141//! cx.send_request(MyRequest {})
142//!     .on_receiving_result(async |result| {
143//!         match result {
144//!             Ok(response) => { /* handle success */ }
145//!             Err(error) => { /* handle error */ }
146//!         }
147//!         Ok(())
148//!     })?;
149//! // Continues immediately, callback runs when response arrives
150//! # Ok(())
151//! # }).await?;
152//! # Ok(())
153//! # }
154//! ```
155//!
156//! See [Ordering](super::ordering) for important details about how these differ.
157//!
158//! ## Dropping a `SentRequest`
159//!
160//! Dropping a [`SentRequest`] before the SDK has received the response sends a
161//! `$/cancel_request` notification asking the peer to cancel the request, then
162//! discards the response when it arrives. For a request whose eventual response
163//! should be ignored, but which should keep running on the peer, call
164//! [`SentRequest::detach`] instead. If no response is expected at all, use a
165//! notification. See the request cancellation chapter
166//! ([`concepts::cancellation`](super::cancellation)) for details.
167//!
168//! # Next Steps
169//!
170//! - [Sessions](super::sessions) - Create multi-turn conversations
171//! - [Callbacks](super::callbacks) - Handle incoming requests from the remote peer
172//!
173//! [`Client`]: crate::Client
174//! [`Agent`]: crate::Agent
175//! [`Proxy`]: crate::Proxy
176//! [`ConnectionTo`]: crate::ConnectionTo
177//! [`SentRequest`]: crate::SentRequest
178//! [`SentRequest::detach`]: crate::SentRequest::detach