agent_client_protocol/jsonrpc/v2_connection.rs
1//! The protocol-v2 connection type, `agent_client_protocol::v2::ConnectionTo`.
2
3use super::ConnectionTo as RawConnectionTo;
4use super::{
5 Builder, ConnectTo, ConnectionTermination, Dispatch, DynamicHandlerGuard,
6 HandleConnectionClose, HandleDispatchFrom, JsonRpcNotification, JsonRpcRequest,
7 PreparedRequest, Protocol, SentRequest, V2, protocol_compat, run::RunWithConnectionTo,
8};
9use crate::Agent;
10use crate::role::{HasPeer, Role};
11use crate::v2::InitializeOutcome;
12
13/// A protocol-v2 connection context.
14///
15/// Values of this type are supplied to callbacks registered on a
16/// [`v2::Builder`](crate::v2::Builder). It exposes the general connection operations that are valid
17/// for protocol v2 while keeping version-specific high-level helpers for other
18/// protocol versions out of the typed context. The generic JSON-RPC send
19/// methods remain intentionally schema-agnostic.
20///
21/// This is a thin, cheaply cloneable handle to the underlying JSON-RPC
22/// connection. It intentionally does not implement [`Deref`](std::ops::Deref)
23/// to the version-neutral [`ConnectionTo`](crate::ConnectionTo); convert
24/// explicitly with [`into_raw`](Self::into_raw) and
25/// [`ConnectionTo::into_protocol`](crate::ConnectionTo::into_protocol).
26#[derive(Clone, Debug)]
27pub struct ConnectionTo<Counterpart: Role> {
28 pub(crate) inner: RawConnectionTo<Counterpart>,
29}
30
31impl ConnectionTo<Agent> {
32 /// Send the client's `initialize` request and report how the agent
33 /// negotiated.
34 ///
35 /// Unlike [`send_request`](Self::send_request), a v1-only agent's valid v1
36 /// response resolves successfully as [`InitializeOutcome::LowerVersion`]
37 /// with the agent's typed response, so the caller can decide whether to
38 /// fall back to a v1 client implementation. The connection stays
39 /// uninitialized in that case; the SDK never converts it to v1.
40 ///
41 /// The request still resolves with an error for errors returned by the
42 /// agent (including the `-32022` version mismatch), malformed responses,
43 /// and transport failures.
44 ///
45 /// After an initialization completes, `initialize` may be sent again
46 /// before any other request; the agent treats the latest one as
47 /// authoritative. Once another request has been sent, a repeat resolves
48 /// with an `-32600` error without being sent.
49 ///
50 /// ```no_run
51 /// # use agent_client_protocol::{schema::ProtocolVersion, v2::schema};
52 /// # use agent_client_protocol::{Client, ConnectTo};
53 /// use agent_client_protocol::SelectedInitializeResponse;
54 /// use agent_client_protocol::v2::InitializeOutcome;
55 /// # async fn example(agent: impl ConnectTo<Client>) -> agent_client_protocol::Result<()> {
56 /// let outcome = Client
57 /// .v2()
58 /// .connect_with(agent, async |cx| {
59 /// let request = schema::InitializeRequest::new(
60 /// ProtocolVersion::V2,
61 /// schema::Implementation::new("example", "0.1.0"),
62 /// );
63 /// match cx.send_initialize(request).block_task().await? {
64 /// InitializeOutcome::Initialized(_response) => {
65 /// // Continue with v2 traffic.
66 /// Ok(None)
67 /// }
68 /// InitializeOutcome::LowerVersion(mismatch) => Ok(Some(mismatch)),
69 /// _ => Err(agent_client_protocol::Error::internal_error().data("unexpected outcome")),
70 /// }
71 /// })
72 /// .await?;
73 /// if let Some(mismatch) = outcome
74 /// && let SelectedInitializeResponse::V1(_v1_response) = mismatch.response
75 /// {
76 /// // Reconnect with a v1 client implementation.
77 /// }
78 /// # Ok(())
79 /// # }
80 /// ```
81 pub fn send_initialize(
82 &self,
83 request: crate::v2::schema::InitializeRequest,
84 ) -> SentRequest<InitializeOutcome, V2> {
85 let mut prepared = self.inner.prepare_request_to_with_options::<V2, _, _>(
86 self.inner.counterpart(),
87 protocol_compat::InitializeNegotiation(request),
88 None,
89 None,
90 );
91 prepared
92 .publication
93 .pending_reply
94 .accepts_lower_initialize_version = true;
95 prepared.into_sent_request(false)
96 }
97}
98
99impl<Counterpart: Role> From<ConnectionTo<Counterpart>> for RawConnectionTo<Counterpart> {
100 /// The same as [`ConnectionTo::into_raw`]. Generic code over
101 /// [`Protocol`] uses it to turn a `P::Connection<Counterpart>` back into
102 /// the version-neutral connection.
103 fn from(connection: ConnectionTo<Counterpart>) -> Self {
104 connection.into_raw()
105 }
106}
107
108impl<Counterpart: Role> ConnectionTo<Counterpart> {
109 /// Access the underlying version-neutral connection inside the SDK.
110 pub(crate) fn raw_connection(&self) -> &RawConnectionTo<Counterpart> {
111 &self.inner
112 }
113
114 /// The underlying version-neutral connection.
115 ///
116 /// Requests sent through it return [`Raw`](crate::Raw) handles. Convert
117 /// back with [`ConnectionTo::into_protocol`](crate::ConnectionTo::into_protocol).
118 #[must_use]
119 pub fn into_raw(self) -> RawConnectionTo<Counterpart> {
120 self.inner
121 }
122
123 /// Return the counterpart role this connection is talking to.
124 pub fn counterpart(&self) -> Counterpart {
125 self.inner.counterpart()
126 }
127
128 /// Wait until the incoming transport reaches clean EOF.
129 pub async fn incoming_closed(&self) {
130 self.inner.incoming_closed().await;
131 }
132
133 /// Return whether clean incoming-EOF processing has completed.
134 #[must_use]
135 pub fn is_incoming_closed(&self) -> bool {
136 self.inner.is_incoming_closed()
137 }
138
139 /// Wait until the connection driver has terminated, for any reason.
140 ///
141 /// See [`ConnectionTo::terminated`](crate::ConnectionTo::terminated).
142 pub async fn terminated(&self) -> ConnectionTermination {
143 self.inner.terminated().await
144 }
145
146 /// Return the termination reason if the connection driver has terminated.
147 #[must_use]
148 pub fn termination(&self) -> Option<ConnectionTermination> {
149 self.inner.termination()
150 }
151
152 /// Spawn a task that runs for as long as the JSON-RPC connection is served.
153 ///
154 /// # Errors
155 ///
156 /// Returns an error if the connection's task queue is closed.
157 #[track_caller]
158 pub fn spawn(
159 &self,
160 task: impl IntoFuture<Output = Result<(), crate::Error>, IntoFuture: Send + 'static>,
161 ) -> Result<(), crate::Error> {
162 self.inner.spawn(task)
163 }
164
165 /// Spawn a JSON-RPC connection in the background.
166 ///
167 /// The returned connection context is selected by `builder`; spawning a
168 /// [`v2::Builder`](crate::v2::Builder) therefore returns another
169 /// [`v2::ConnectionTo`](ConnectionTo).
170 ///
171 /// # Errors
172 ///
173 /// Returns an error if the parent connection cannot queue the child connection's task.
174 ///
175 /// ```no_run
176 /// # use agent_client_protocol::{
177 /// # Agent, Client, ConnectTo, Error,
178 /// # };
179 /// # use agent_client_protocol::v2::ConnectionTo;
180 /// # fn example(
181 /// # connection: ConnectionTo<Agent>,
182 /// # transport: impl ConnectTo<Client> + 'static,
183 /// # ) -> Result<(), Error> {
184 /// let child: ConnectionTo<Agent> =
185 /// connection.spawn_connection(Client.v2(), transport)?;
186 /// # drop(child);
187 /// # Ok(())
188 /// # }
189 /// ```
190 #[track_caller]
191 pub fn spawn_connection<R: Role, P: Protocol>(
192 &self,
193 builder: Builder<
194 R,
195 impl HandleDispatchFrom<R::Counterpart> + 'static,
196 impl RunWithConnectionTo<R::Counterpart> + 'static,
197 impl HandleConnectionClose<R::Counterpart> + 'static,
198 P,
199 >,
200 transport: impl ConnectTo<R> + 'static,
201 ) -> Result<P::Connection<R::Counterpart>, crate::Error> {
202 self.inner.spawn_connection(builder, transport)
203 }
204
205 /// Send a request or notification and forward its response appropriately.
206 ///
207 /// # Errors
208 ///
209 /// Returns the forwarding error from [`send_proxied_message_to`](crate::ConnectionTo::send_proxied_message_to).
210 pub fn send_proxied_message<
211 Req: JsonRpcRequest<Response: Send>,
212 Notif: JsonRpcNotification,
213 Q: Protocol,
214 >(
215 &self,
216 message: Dispatch<Req, Notif, Q>,
217 ) -> Result<(), crate::Error>
218 where
219 Counterpart: HasPeer<Counterpart>,
220 {
221 self.inner.send_proxied_message(message)
222 }
223
224 /// Send a request or notification to a specific peer and forward its
225 /// response appropriately.
226 ///
227 /// # Errors
228 ///
229 /// Returns the forwarding error from [`send_proxied_message_to`](crate::ConnectionTo::send_proxied_message_to).
230 pub fn send_proxied_message_to<
231 Peer: Role,
232 Req: JsonRpcRequest<Response: Send>,
233 Notif: JsonRpcNotification,
234 Q: Protocol,
235 >(
236 &self,
237 peer: Peer,
238 message: Dispatch<Req, Notif, Q>,
239 ) -> Result<(), crate::Error>
240 where
241 Counterpart: HasPeer<Peer>,
242 {
243 self.inner.send_proxied_message_to(peer, message)
244 }
245
246 /// Send an outgoing request to the default counterpart peer.
247 pub fn send_request<Req: JsonRpcRequest>(&self, request: Req) -> SentRequest<Req::Response, V2>
248 where
249 Counterpart: HasPeer<Counterpart>,
250 {
251 self.send_request_to(self.inner.counterpart(), request)
252 }
253
254 /// Send an outgoing request to a specific peer.
255 pub fn send_request_to<Peer: Role, Req: JsonRpcRequest>(
256 &self,
257 peer: Peer,
258 request: Req,
259 ) -> SentRequest<Req::Response, V2>
260 where
261 Counterpart: HasPeer<Peer>,
262 {
263 self.inner
264 .send_request_to_with_options(peer, request, false, None, None)
265 }
266
267 /// Prepare a request without sending it until response handling is selected.
268 ///
269 /// See [`ConnectionTo::prepare_request`](crate::ConnectionTo::prepare_request) for publication and ordering semantics.
270 pub fn prepare_request<Req: JsonRpcRequest>(
271 &self,
272 request: Req,
273 ) -> PreparedRequest<Req::Response, V2>
274 where
275 Counterpart: HasPeer<Counterpart>,
276 {
277 self.prepare_request_to(self.inner.counterpart(), request)
278 }
279
280 /// Prepare a request to a specific peer without sending it.
281 ///
282 /// See [`ConnectionTo::prepare_request_to`](crate::ConnectionTo::prepare_request_to) for publication and ordering semantics.
283 pub fn prepare_request_to<Peer: Role, Req: JsonRpcRequest>(
284 &self,
285 peer: Peer,
286 request: Req,
287 ) -> PreparedRequest<Req::Response, V2>
288 where
289 Counterpart: HasPeer<Peer>,
290 {
291 self.inner
292 .prepare_request_to_with_options(peer, request, None, None)
293 }
294
295 /// Send an outgoing notification to the default counterpart peer.
296 ///
297 /// # Errors
298 ///
299 /// Returns an error if the notification cannot be encoded or queued.
300 pub fn send_notification<N: JsonRpcNotification>(
301 &self,
302 notification: N,
303 ) -> Result<(), crate::Error>
304 where
305 Counterpart: HasPeer<Counterpart>,
306 {
307 self.inner.send_notification(notification)
308 }
309
310 /// Send an outgoing notification to a specific peer.
311 ///
312 /// # Errors
313 ///
314 /// Returns an error if the notification cannot be encoded for the peer or queued.
315 pub fn send_notification_to<Peer: Role, N: JsonRpcNotification>(
316 &self,
317 peer: Peer,
318 notification: N,
319 ) -> Result<(), crate::Error>
320 where
321 Counterpart: HasPeer<Peer>,
322 {
323 self.inner.send_notification_to(peer, notification)
324 }
325
326 /// Send a `$/cancel_request` notification to the default counterpart peer.
327 ///
328 /// Prefer [`SentRequest::cancel`](crate::SentRequest::cancel) when you
329 /// have the request handle. `request_id` is a v2 request ID, such as the
330 /// [`id`](crate::SentRequest::id) of a request sent through this
331 /// connection. The raw [`ConnectionTo::send_cancel_request`](crate::ConnectionTo::send_cancel_request)
332 /// takes any [`RawJsonRpcId`](crate::RawJsonRpcId).
333 ///
334 /// # Errors
335 ///
336 /// Returns an error if the cancellation notification cannot be encoded or queued.
337 pub fn send_cancel_request(
338 &self,
339 request_id: impl Into<crate::v2::schema::RequestId>,
340 ) -> Result<(), crate::Error>
341 where
342 Counterpart: HasPeer<Counterpart>,
343 {
344 self.inner.send_cancel_request(request_id.into())
345 }
346
347 /// Send a `$/cancel_request` notification to a specific peer.
348 ///
349 /// The notification is always sent plain, never wrapped in
350 /// `proxy/successor`, as the raw
351 /// [`ConnectionTo::send_cancel_request_to`](crate::ConnectionTo::send_cancel_request_to)
352 /// describes. See [`send_cancel_request`](Self::send_cancel_request).
353 ///
354 /// # Errors
355 ///
356 /// Returns an error if the cancellation notification cannot be encoded or queued.
357 pub fn send_cancel_request_to<Peer: Role>(
358 &self,
359 peer: Peer,
360 request_id: impl Into<crate::v2::schema::RequestId>,
361 ) -> Result<(), crate::Error>
362 where
363 Counterpart: HasPeer<Peer>,
364 {
365 self.inner.send_cancel_request_to(peer, request_id.into())
366 }
367
368 /// Register a low-level dynamic message handler.
369 ///
370 /// Dynamic handlers use the version-neutral [`HandleDispatchFrom`] trait,
371 /// so their callback receives the underlying version-neutral
372 /// [`ConnectionTo`](crate::ConnectionTo). Prefer typed handlers on
373 /// [`v2::Builder`](crate::v2::Builder) when registration can happen before the
374 /// connection starts.
375 ///
376 /// # Errors
377 ///
378 /// Returns an error if the connection no longer accepts handler registrations.
379 ///
380 /// ```no_run
381 /// # use agent_client_protocol::{
382 /// # Agent, Client, ConnectTo, DynamicHandlerGuard, Error, NullHandler,
383 /// # };
384 /// # async fn example(
385 /// # transport: impl ConnectTo<Client> + 'static,
386 /// # ) -> Result<(), Error> {
387 /// Client.v2().connect_with(transport, async |connection| {
388 /// let guard: DynamicHandlerGuard<Agent> =
389 /// connection.add_dynamic_handler(NullHandler)?;
390 ///
391 /// // Keep `guard` alive for as long as the modal handler is needed.
392 /// drop(guard);
393 /// Ok(())
394 /// }).await
395 /// # }
396 /// ```
397 pub fn add_dynamic_handler(
398 &self,
399 handler: impl HandleDispatchFrom<Counterpart> + 'static,
400 ) -> Result<DynamicHandlerGuard<Counterpart>, crate::Error> {
401 self.inner.add_dynamic_handler(handler)
402 }
403}