agent_client_protocol/session.rs
1use std::{future::Future, marker::PhantomData, path::Path};
2
3use futures::channel::{mpsc, oneshot};
4
5use crate::{
6 Agent, Client, ConnectionTo, Dispatch, HandleDispatchFrom, Handled, Responder, Role,
7 jsonrpc::{
8 DynamicHandlerRegistration,
9 run::{ChainRun, NullRun, RunWithConnectionTo},
10 },
11 mcp_server::McpServer,
12 role::{HasPeer, acp::ProxySessionMessages},
13 schema::v1::{
14 ContentBlock, ContentChunk, NewSessionRequest, NewSessionResponse, PromptRequest,
15 PromptResponse, SessionId, SessionModeState, SessionNotification, SessionUpdate,
16 StopReason,
17 },
18 util::{MatchDispatch, MatchDispatchFrom, run_until},
19};
20
21/// Marker type indicating the session builder will block the current task.
22#[derive(Debug)]
23pub struct Blocking;
24impl SessionBlockState for Blocking {}
25
26/// Marker type indicating the session builder will not block the current task.
27#[derive(Debug)]
28pub struct NonBlocking;
29impl SessionBlockState for NonBlocking {}
30
31/// Trait for marker types that indicate blocking vs blocking API.
32/// See [`SessionBuilder::block_task`].
33pub trait SessionBlockState: Send + 'static + Sync + std::fmt::Debug {}
34
35impl<Counterpart: Role> ConnectionTo<Counterpart>
36where
37 Counterpart: HasPeer<Agent>,
38{
39 /// Session builder for a new session request.
40 pub fn build_session(&self, cwd: impl AsRef<Path>) -> SessionBuilder<Counterpart, NullRun> {
41 SessionBuilder::new(self, NewSessionRequest::new(cwd.as_ref()))
42 }
43
44 /// Session builder using the current working directory.
45 ///
46 /// This is a convenience wrapper around [`build_session`](Self::build_session)
47 /// that uses [`std::env::current_dir`] to get the working directory.
48 ///
49 /// Returns an error if the current directory cannot be determined.
50 pub fn build_session_cwd(&self) -> Result<SessionBuilder<Counterpart, NullRun>, crate::Error> {
51 let cwd = std::env::current_dir().map_err(|e| {
52 crate::Error::internal_error().data(format!("cannot get current directory: {e}"))
53 })?;
54 Ok(self.build_session(cwd))
55 }
56
57 /// Session builder starting from an existing request.
58 ///
59 /// Use this when you've intercepted a `session.new` request and want to
60 /// modify it (e.g., inject MCP servers) before forwarding.
61 pub fn build_session_from(
62 &self,
63 request: NewSessionRequest,
64 ) -> SessionBuilder<Counterpart, NullRun> {
65 SessionBuilder::new(self, request)
66 }
67
68 /// Given a session response received from the agent,
69 /// attach a handler to process messages related to this session
70 /// and let you access them.
71 ///
72 /// Normally you would not use this method directly but would
73 /// instead use [`Self::build_session`] and then [`SessionBuilder::start_session`].
74 ///
75 /// The vector `dynamic_handler_registrations` contains any dynamic
76 /// handle registrations associated with this session (e.g., from MCP servers).
77 /// You can simply pass `Default::default()` if not applicable.
78 pub fn attach_session<'responder>(
79 &self,
80 response: NewSessionResponse,
81 mcp_handler_registrations: Vec<DynamicHandlerRegistration<Counterpart>>,
82 ) -> Result<ActiveSession<'responder, Counterpart>, crate::Error> {
83 let NewSessionResponse {
84 session_id,
85 modes,
86 meta,
87 ..
88 } = response;
89
90 let (update_tx, update_rx) = mpsc::unbounded();
91 let handler = ActiveSessionHandler::new(session_id.clone(), update_tx.clone());
92 let session_handler_registration = self.add_dynamic_handler(handler)?;
93
94 Ok(ActiveSession {
95 session_id,
96 modes,
97 meta,
98 update_rx,
99 update_tx,
100 connection: self.clone(),
101 session_handler_registration,
102 mcp_handler_registrations,
103 _responder: PhantomData,
104 })
105 }
106}
107
108/// Session builder for a new session request.
109/// Allows you to add MCP servers or set other details for this session.
110///
111/// The `BlockState` type parameter tracks whether blocking methods are available:
112/// - `NonBlocking` (default): Only [`on_session_start`](Self::on_session_start) is available
113/// - `Blocking` (after calling [`block_task`](Self::block_task)):
114/// [`run_until`](Self::run_until) and [`start_session`](Self::start_session) become available
115#[must_use = "use `start_session`, `run_until`, or `on_session_start` to start the session"]
116#[derive(Debug)]
117pub struct SessionBuilder<
118 Counterpart,
119 Run: RunWithConnectionTo<Counterpart> = NullRun,
120 BlockState: SessionBlockState = NonBlocking,
121> where
122 Counterpart: HasPeer<Agent>,
123{
124 connection: ConnectionTo<Counterpart>,
125 request: NewSessionRequest,
126 dynamic_handler_registrations: Vec<DynamicHandlerRegistration<Counterpart>>,
127 run: Run,
128 block_state: PhantomData<BlockState>,
129}
130
131impl<Counterpart> SessionBuilder<Counterpart, NullRun, NonBlocking>
132where
133 Counterpart: HasPeer<Agent>,
134{
135 fn new(connection: &ConnectionTo<Counterpart>, request: NewSessionRequest) -> Self {
136 SessionBuilder {
137 connection: connection.clone(),
138 request,
139 dynamic_handler_registrations: Vec::default(),
140 run: NullRun,
141 block_state: PhantomData,
142 }
143 }
144}
145
146impl<Counterpart, R, BlockState> SessionBuilder<Counterpart, R, BlockState>
147where
148 Counterpart: HasPeer<Agent>,
149 R: RunWithConnectionTo<Counterpart>,
150 BlockState: SessionBlockState,
151{
152 /// Add the MCP servers from the given registry to this session.
153 pub fn with_mcp_server<McpRun>(
154 mut self,
155 mcp_server: McpServer<Counterpart, McpRun>,
156 ) -> Result<SessionBuilder<Counterpart, ChainRun<R, McpRun>, BlockState>, crate::Error>
157 where
158 McpRun: RunWithConnectionTo<Counterpart>,
159 {
160 let (handler, mcp_run) = mcp_server.into_handler_and_responder();
161 self.dynamic_handler_registrations
162 .push(handler.into_dynamic_handler(&mut self.request, &self.connection)?);
163 Ok(SessionBuilder {
164 connection: self.connection,
165 request: self.request,
166 dynamic_handler_registrations: self.dynamic_handler_registrations,
167 run: ChainRun::new(self.run, mcp_run),
168 block_state: self.block_state,
169 })
170 }
171
172 /// Spawn a task that runs the provided closure once the session starts.
173 ///
174 /// Unlike [`start_session`](Self::start_session), this method returns immediately
175 /// without blocking the current task. The session handshake and closure execution
176 /// happen in a spawned background task.
177 ///
178 /// The closure receives an `ActiveSession<'static, _>` and should return
179 /// `Result<(), Error>`. If the closure returns an error, it will propagate
180 /// to the connection's error handling.
181 ///
182 /// # Example
183 ///
184 /// ```ignore
185 /// # use agent_client_protocol::{Client, Agent, ConnectTo};
186 /// # use agent_client_protocol::mcp_server::McpServer;
187 /// # use agent_client_protocol_rmcp::McpServerExt;
188 /// # async fn example(transport: impl ConnectTo<Client>) -> Result<(), agent_client_protocol::Error> {
189 /// # Client.builder().connect_with(transport, async |cx| {
190 /// # let mcp = McpServer::<Agent, _>::builder("tools").build();
191 /// cx.build_session_cwd()?
192 /// .with_mcp_server(mcp)?
193 /// .on_session_start(async |mut session| {
194 /// // Do something with the session
195 /// session.send_prompt("Hello")?;
196 /// let response = session.read_to_string().await?;
197 /// Ok(())
198 /// })?;
199 /// // Returns immediately, session runs in background
200 /// # Ok(())
201 /// # }).await?;
202 /// # Ok(())
203 /// # }
204 /// ```
205 ///
206 /// # Ordering
207 ///
208 /// This callback blocks the dispatch loop until the session starts and your
209 /// callback completes. See the [`ordering`](crate::concepts::ordering) module for details.
210 pub fn on_session_start<F, Fut>(self, op: F) -> Result<(), crate::Error>
211 where
212 R: 'static,
213 F: FnOnce(ActiveSession<'static, Counterpart>) -> Fut + Send + 'static,
214 Fut: Future<Output = Result<(), crate::Error>> + Send,
215 {
216 let Self {
217 connection,
218 request,
219 dynamic_handler_registrations,
220 run,
221 block_state: _,
222 } = self;
223
224 connection
225 .send_request_to(Agent, request)
226 .on_receiving_result({
227 let connection = connection.clone();
228 async move |result| {
229 let response = result?;
230
231 connection.spawn(run.run_with_connection_to(connection.clone()))?;
232
233 let active_session =
234 connection.attach_session(response, dynamic_handler_registrations)?;
235
236 op(active_session).await
237 }
238 })
239 }
240
241 /// Spawn a proxy session and run a closure with the session ID.
242 ///
243 /// A **proxy session** starts the session with the agent and then automatically
244 /// proxies all session updates (prompts, tool calls, etc.) from the agent back
245 /// to the client. You don't need to handle any messages yourself - the proxy
246 /// takes care of forwarding everything. This is useful when you want to inject
247 /// and/or filter prompts coming from the client but otherwise not be involved
248 /// in the session.
249 ///
250 /// Unlike [`start_session_proxy`](Self::start_session_proxy), this method returns
251 /// immediately without blocking the current task. The session handshake, client
252 /// response, and proxy setup all happen in a spawned background task.
253 ///
254 /// The closure receives the `SessionId` once the session is established, allowing
255 /// you to perform any custom work with that ID (e.g., tracking, logging).
256 ///
257 /// # Example
258 ///
259 /// ```ignore
260 /// # use agent_client_protocol::{Proxy, Client, Conductor, ConnectTo};
261 /// # use agent_client_protocol::schema::v1::NewSessionRequest;
262 /// # use agent_client_protocol::mcp_server::McpServer;
263 /// # use agent_client_protocol_rmcp::McpServerExt;
264 /// # async fn example(transport: impl ConnectTo<Proxy>) -> Result<(), agent_client_protocol::Error> {
265 /// Proxy.builder()
266 /// .on_receive_request_from(Client, async |request: NewSessionRequest, responder, cx| {
267 /// let mcp = McpServer::<Conductor, _>::builder("tools").build();
268 /// cx.build_session_from(request)
269 /// .with_mcp_server(mcp)?
270 /// .on_proxy_session_start(responder, async |session_id| {
271 /// // Session started
272 /// Ok(())
273 /// })
274 /// }, agent_client_protocol::on_receive_request!())
275 /// .connect_to(transport)
276 /// .await?;
277 /// # Ok(())
278 /// # }
279 /// ```
280 ///
281 /// # Ordering
282 ///
283 /// This callback blocks the dispatch loop until the session starts and your
284 /// callback completes. See the [`ordering`](crate::concepts::ordering) module for details.
285 pub fn on_proxy_session_start<F, Fut>(
286 self,
287 responder: Responder<NewSessionResponse>,
288 op: F,
289 ) -> Result<(), crate::Error>
290 where
291 F: FnOnce(SessionId) -> Fut + Send + 'static,
292 Fut: Future<Output = Result<(), crate::Error>> + Send,
293 Counterpart: HasPeer<Client>,
294 R: 'static,
295 {
296 let Self {
297 connection,
298 request,
299 dynamic_handler_registrations,
300 run,
301 block_state: _,
302 } = self;
303
304 // Send the "new session" request to the agent.
305 let sent = connection.send_request_to(Agent, request);
306 let sent = sent.forward_cancellation_from(responder.cancellation());
307
308 sent.on_receiving_ok_result(responder, {
309 let connection = connection.clone();
310 async move |response, responder| {
311 // Extract the session-id from the response and forward
312 // the response back to the client
313 let session_id = response.session_id.clone();
314 responder.respond(response)?;
315
316 // Install a dynamic handler to proxy messages from this session
317 connection
318 .add_dynamic_handler(ProxySessionMessages::new(session_id.clone()))?
319 .run_indefinitely();
320
321 // Spawn off the run and dynamic handlers to run indefinitely
322 connection.spawn(run.run_with_connection_to(connection.clone()))?;
323 dynamic_handler_registrations
324 .into_iter()
325 .for_each(super::jsonrpc::DynamicHandlerRegistration::run_indefinitely);
326
327 op(session_id).await
328 }
329 })
330 }
331}
332
333impl<Counterpart, R> SessionBuilder<Counterpart, R, NonBlocking>
334where
335 Counterpart: HasPeer<Agent>,
336 R: RunWithConnectionTo<Counterpart>,
337{
338 /// Mark this session builder as being able to block the current task.
339 ///
340 /// After calling this, you can use [`run_until`](Self::run_until) or
341 /// [`start_session`](Self::start_session) which block the current task.
342 ///
343 /// This should not be used from inside a message handler like
344 /// [`Builder::on_receive_request`](`crate::Builder::on_receive_request`) or [`HandleDispatchFrom`]
345 /// implementations.
346 pub fn block_task(self) -> SessionBuilder<Counterpart, R, Blocking> {
347 SessionBuilder {
348 connection: self.connection,
349 request: self.request,
350 dynamic_handler_registrations: self.dynamic_handler_registrations,
351 run: self.run,
352 block_state: PhantomData,
353 }
354 }
355}
356
357impl<Counterpart, R> SessionBuilder<Counterpart, R, Blocking>
358where
359 Counterpart: HasPeer<Agent>,
360 R: RunWithConnectionTo<Counterpart>,
361{
362 /// Run this session synchronously. The current task will be blocked
363 /// and `op` will be executed with the active session information.
364 /// This is useful when you have MCP servers that are borrowed from your local
365 /// stack frame.
366 ///
367 /// The `ActiveSession` passed to `op` has a non-`'static` lifetime, which
368 /// prevents calling [`ActiveSession::proxy_remaining_messages`] (since the
369 /// responders would terminate when `op` returns).
370 ///
371 /// Requires calling [`block_task`](Self::block_task) first.
372 pub async fn run_until<T>(
373 self,
374 op: impl for<'responder> AsyncFnOnce(
375 ActiveSession<'responder, Counterpart>,
376 ) -> Result<T, crate::Error>,
377 ) -> Result<T, crate::Error> {
378 let Self {
379 connection,
380 request,
381 dynamic_handler_registrations,
382 run,
383 block_state: _,
384 } = self;
385
386 let response = connection
387 .send_request_to(Agent, request)
388 .block_task()
389 .await?;
390
391 let active_session = connection.attach_session(response, dynamic_handler_registrations)?;
392
393 run_until(
394 run.run_with_connection_to(connection.clone()),
395 op(active_session),
396 )
397 .await
398 }
399
400 /// Send the request to create the session and return a handle.
401 /// This is an alternative to [`Self::run_until`] that avoids rightward
402 /// drift but at the cost of requiring MCP servers that are `Send` and
403 /// don't access data from the surrounding scope.
404 ///
405 /// Returns an `ActiveSession<'static, _>` because responders are spawned
406 /// into background tasks that live for the connection lifetime.
407 ///
408 /// Requires calling [`block_task`](Self::block_task) first.
409 pub async fn start_session(self) -> Result<ActiveSession<'static, Counterpart>, crate::Error>
410 where
411 R: 'static,
412 {
413 let Self {
414 connection,
415 request,
416 dynamic_handler_registrations,
417 run,
418 block_state: _,
419 } = self;
420
421 let (active_session_tx, active_session_rx) = oneshot::channel();
422
423 connection.clone().spawn(async move {
424 let response = connection
425 .send_request_to(Agent, request)
426 .block_task()
427 .await?;
428
429 connection.spawn(run.run_with_connection_to(connection.clone()))?;
430
431 let active_session =
432 connection.attach_session(response, dynamic_handler_registrations)?;
433
434 active_session_tx
435 .send(active_session)
436 .map_err(|_| crate::Error::internal_error())?;
437
438 Ok(())
439 })?;
440
441 active_session_rx
442 .await
443 .map_err(|_| crate::Error::internal_error())
444 }
445
446 /// Start a proxy session that forwards all messages between client and agent.
447 ///
448 /// A **proxy session** starts the session with the agent and then automatically
449 /// proxies all session updates (prompts, tool calls, etc.) from the agent back
450 /// to the client. You don't need to handle any messages yourself - the proxy
451 /// takes care of forwarding everything. This is useful when you want to inject
452 /// and/or filter prompts coming from the client but otherwise not be involved
453 /// in the session.
454 ///
455 /// This is a convenience method that combines [`start_session`](Self::start_session),
456 /// responding to the client, and [`ActiveSession::proxy_remaining_messages`].
457 ///
458 /// For more control (e.g., to send some messages before proxying), use
459 /// [`start_session`](Self::start_session) instead and call
460 /// [`proxy_remaining_messages`](ActiveSession::proxy_remaining_messages) manually.
461 ///
462 /// Requires calling [`block_task`](Self::block_task) first.
463 pub async fn start_session_proxy(
464 self,
465 responder: Responder<NewSessionResponse>,
466 ) -> Result<SessionId, crate::Error>
467 where
468 Counterpart: HasPeer<Client>,
469 R: 'static,
470 {
471 let active_session = self.start_session().await?;
472 let session_id = active_session.session_id().clone();
473 responder.respond(active_session.response())?;
474 active_session.proxy_remaining_messages()?;
475 Ok(session_id)
476 }
477}
478
479/// Active session struct that lets you send prompts and receive updates.
480///
481/// The `'responder` lifetime represents the span during which responders
482/// (e.g., MCP server handlers) are active. When created via [`SessionBuilder::start_session`],
483/// this is `'static` because responders are spawned into background tasks.
484/// When created via [`SessionBuilder::run_until`], this is tied to the
485/// closure scope, preventing [`Self::proxy_remaining_messages`] from being called
486/// (since the responders would die when the closure returns).
487#[derive(Debug)]
488pub struct ActiveSession<'responder, Link>
489where
490 Link: HasPeer<Agent>,
491{
492 session_id: SessionId,
493 update_rx: mpsc::UnboundedReceiver<SessionMessage>,
494 update_tx: mpsc::UnboundedSender<SessionMessage>,
495 modes: Option<SessionModeState>,
496 meta: Option<serde_json::Map<String, serde_json::Value>>,
497 connection: ConnectionTo<Link>,
498
499 /// Registration for the handler that routes session messages to `update_rx`.
500 /// This is separate from MCP handlers so it can be dropped independently
501 /// when switching to proxy mode.
502 session_handler_registration: DynamicHandlerRegistration<Link>,
503
504 /// Registrations for MCP server handlers.
505 /// These will be dropped once the active-session struct is dropped
506 /// which will cause them to be deregistered.
507 mcp_handler_registrations: Vec<DynamicHandlerRegistration<Link>>,
508
509 /// Phantom lifetime representing the responder lifetime.
510 _responder: PhantomData<&'responder ()>,
511}
512
513/// Incoming message from the agent
514#[non_exhaustive]
515#[derive(Debug)]
516#[allow(
517 clippy::large_enum_variant,
518 reason = "Dispatch messages vastly outnumber StopReason; boxing would add a heap allocation"
519)]
520pub enum SessionMessage {
521 /// Periodic updates with new content, tool requests, etc.
522 /// Use [`MatchDispatch`] to match on the message type.
523 SessionMessage(Dispatch),
524
525 /// When a prompt completes, the stop reason.
526 StopReason(StopReason),
527}
528
529impl<Link> ActiveSession<'_, Link>
530where
531 Link: HasPeer<Agent>,
532{
533 /// Access the session ID.
534 pub fn session_id(&self) -> &SessionId {
535 &self.session_id
536 }
537
538 /// Access modes available in this session.
539 pub fn modes(&self) -> &Option<SessionModeState> {
540 &self.modes
541 }
542
543 /// Access meta data from session response.
544 pub fn meta(&self) -> &Option<serde_json::Map<String, serde_json::Value>> {
545 &self.meta
546 }
547
548 /// Build a `NewSessionResponse` from the session information.
549 ///
550 /// Useful when you need to forward the session response to a client
551 /// after doing some processing.
552 pub fn response(&self) -> NewSessionResponse {
553 NewSessionResponse::new(self.session_id.clone())
554 .modes(self.modes.clone())
555 .meta(self.meta.clone())
556 }
557
558 /// Access the underlying connection context used to communicate with the agent.
559 pub fn connection(&self) -> ConnectionTo<Link> {
560 self.connection.clone()
561 }
562
563 /// Send a prompt to the agent. You can then read messages sent in response.
564 pub fn send_prompt(&mut self, prompt: impl ToString) -> Result<(), crate::Error> {
565 let update_tx = self.update_tx.clone();
566 self.connection
567 .send_request_to(
568 Agent,
569 PromptRequest::new(self.session_id.clone(), vec![prompt.to_string().into()]),
570 )
571 .on_receiving_result(async move |result| {
572 let PromptResponse { stop_reason, .. } = result?;
573
574 update_tx
575 .unbounded_send(SessionMessage::StopReason(stop_reason))
576 .map_err(crate::util::internal_error)?;
577
578 Ok(())
579 })
580 }
581
582 /// Read an update from the agent in response to the prompt.
583 pub async fn read_update(&mut self) -> Result<SessionMessage, crate::Error> {
584 use futures::StreamExt;
585 let message =
586 self.update_rx.next().await.ok_or_else(|| {
587 crate::util::internal_error("session channel closed unexpectedly")
588 })?;
589
590 Ok(message)
591 }
592
593 /// Read all updates until the end of the turn and create a string.
594 /// Ignores non-text updates.
595 pub async fn read_to_string(&mut self) -> Result<String, crate::Error> {
596 let mut output = String::new();
597 loop {
598 let update = self.read_update().await?;
599 tracing::trace!(?update, "read_to_string update");
600 match update {
601 SessionMessage::SessionMessage(dispatch) => MatchDispatch::new(dispatch)
602 .if_notification(async |notif: SessionNotification| match notif.update {
603 SessionUpdate::AgentMessageChunk(ContentChunk {
604 content: ContentBlock::Text(text),
605 ..
606 }) => {
607 output.push_str(&text.text);
608 Ok(())
609 }
610 _ => Ok(()),
611 })
612 .await
613 .otherwise_ignore()?,
614 SessionMessage::StopReason(_stop_reason) => break,
615 }
616 }
617 Ok(output)
618 }
619}
620
621impl<Link> ActiveSession<'static, Link>
622where
623 Link: HasPeer<Agent>,
624{
625 /// Proxy all remaining messages for this session between client and agent.
626 ///
627 /// Use this when you want to inject MCP servers into a session but don't need
628 /// to actively interact with it after setup. The session messages will be proxied
629 /// between client and agent automatically.
630 ///
631 /// This consumes the `ActiveSession` since you're giving up active control.
632 ///
633 /// This method is only available on `ActiveSession<'static, _>` (from
634 /// [`SessionBuilder::start_session`]) because it requires responders to
635 /// outlive the method call.
636 ///
637 /// # Message Ordering Guarantees
638 ///
639 /// This method ensures proper handoff from active session mode to proxy mode
640 /// without losing or reordering messages:
641 ///
642 /// 1. **Stop the session handler** - Drop the registration that routes messages
643 /// to `update_rx`. After this, no new messages will be queued.
644 /// 2. **Close the channel** - Drop `update_tx` so we can detect when the channel
645 /// is fully drained.
646 /// 3. **Drain queued messages** - Forward any messages that were already queued
647 /// in `update_rx` to the client, preserving order.
648 /// 4. **Install proxy handler** - Now that all queued messages are forwarded,
649 /// install the proxy handler to handle future messages.
650 ///
651 /// This sequence prevents the race condition where messages could be delivered
652 /// out of order or lost during the transition.
653 pub fn proxy_remaining_messages(self) -> Result<(), crate::Error>
654 where
655 Link: HasPeer<Client>,
656 {
657 // Destructure self to get ownership of all fields
658 let ActiveSession {
659 session_id,
660 mut update_rx,
661 update_tx,
662 connection,
663 session_handler_registration,
664 mcp_handler_registrations,
665 // These fields are not needed for proxying
666 modes: _,
667 meta: _,
668 _responder,
669 } = self;
670
671 // Step 1: Drop the session handler registration.
672 // This unregisters the handler that was routing messages to update_rx.
673 // After this point, no new messages will be added to the channel.
674 drop(session_handler_registration);
675
676 // Step 2: Drop the sender side of the channel.
677 // This allows us to detect when the channel is fully drained
678 // (recv will return None when empty and sender is dropped).
679 drop(update_tx);
680
681 // Step 3: Drain any messages that were already queued and forward to client.
682 // These messages arrived before we dropped the handler but haven't been
683 // consumed yet. We must forward them to maintain message ordering.
684 while let Ok(message) = update_rx.try_recv() {
685 match message {
686 SessionMessage::SessionMessage(dispatch) => {
687 // Forward the message to the client
688 connection.send_proxied_message_to(Client, dispatch)?;
689 }
690 SessionMessage::StopReason(_) => {
691 // StopReason is internal bookkeeping, not forwarded
692 }
693 }
694 }
695
696 // Step 4: Install the proxy handler for future messages.
697 // Now that all queued messages have been forwarded, the proxy handler
698 // can take over. Any new messages will go directly through the proxy.
699 connection
700 .add_dynamic_handler(ProxySessionMessages::new(session_id))?
701 .run_indefinitely();
702
703 // Keep MCP server handlers alive for the lifetime of the proxy
704 for registration in mcp_handler_registrations {
705 registration.run_indefinitely();
706 }
707
708 Ok(())
709 }
710}
711
712struct ActiveSessionHandler {
713 session_id: SessionId,
714 update_tx: mpsc::UnboundedSender<SessionMessage>,
715}
716
717impl ActiveSessionHandler {
718 pub fn new(session_id: SessionId, update_tx: mpsc::UnboundedSender<SessionMessage>) -> Self {
719 Self {
720 session_id,
721 update_tx,
722 }
723 }
724}
725
726impl<Counterpart: Role> HandleDispatchFrom<Counterpart> for ActiveSessionHandler
727where
728 Counterpart: HasPeer<Agent>,
729{
730 async fn handle_dispatch_from(
731 &mut self,
732 message: Dispatch,
733 cx: ConnectionTo<Counterpart>,
734 ) -> Result<Handled<Dispatch>, crate::Error> {
735 // If this is a message for our session, grab it.
736 tracing::trace!(
737 ?message,
738 handler_session_id = ?self.session_id,
739 "ActiveSessionHandler::handle_dispatch"
740 );
741 MatchDispatchFrom::new(message, &cx)
742 .if_message_from(Agent, async |message| {
743 if let Some(session_id) = message.get_session_id()? {
744 tracing::trace!(
745 message_session_id = ?session_id,
746 handler_session_id = ?self.session_id,
747 "ActiveSessionHandler::handle_dispatch"
748 );
749 if session_id == self.session_id {
750 self.update_tx
751 .unbounded_send(SessionMessage::SessionMessage(message))
752 .map_err(crate::util::internal_error)?;
753 return Ok(Handled::Yes);
754 }
755 }
756
757 // Otherwise, pass it through.
758 Ok(Handled::No {
759 message,
760 retry: false,
761 })
762 })
763 .await
764 .done()
765 }
766
767 fn describe_chain(&self) -> impl std::fmt::Debug {
768 format!("ActiveSessionHandler({})", self.session_id)
769 }
770}