agent-client-protocol-conductor 0.11.0

Conductor for orchestrating Agent Client Protocol proxy chains
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
use agent_client_protocol::{BoxFuture, Channel, ConnectTo, jsonrpcmsg::Message, role::mcp};
use axum::{
    Router,
    extract::State,
    http::StatusCode,
    response::{IntoResponse, Response, Sse},
    routing::post,
};
use futures::{SinkExt, StreamExt as _, channel::mpsc, future::Either, stream::Stream};
use futures_concurrency::future::FutureExt as _;
use futures_concurrency::stream::StreamExt as _;
use rustc_hash::FxHashMap;
use std::{
    collections::{HashMap, VecDeque},
    pin::pin,
    sync::Arc,
};
use tokio::net::TcpListener;

use crate::conductor::{
    ConductorMessage,
    mcp_bridge::{McpBridgeConnection, McpBridgeConnectionActor},
};

/// Runs an HTTP listener for MCP bridge connections
pub async fn run_http_listener(
    tcp_listener: TcpListener,
    acp_url: String,
    mut conductor_tx: mpsc::Sender<ConductorMessage>,
) -> Result<(), agent_client_protocol::Error> {
    let (to_mcp_client_tx, to_mcp_client_rx) = mpsc::channel(128);

    // When we send this message to the conductor,
    // it is going to go through a step or two and eventually
    // spawn the McpBridgeConnectionActor, which will ferry MCP requests
    // back and forth.
    conductor_tx
        .send(ConductorMessage::McpConnectionReceived {
            acp_url,
            actor: McpBridgeConnectionActor::new(
                HttpMcpBridge::new(tcp_listener),
                conductor_tx.clone(),
                to_mcp_client_rx,
            ),
            connection: McpBridgeConnection::new(to_mcp_client_tx),
        })
        .await
        .map_err(|_| agent_client_protocol::Error::internal_error())?;

    Ok(())
}

/// A component that receives HTTP requests/responses using the HTTP transport defined by the MCP protocol.
struct HttpMcpBridge {
    listener: tokio::net::TcpListener,
}

impl HttpMcpBridge {
    /// Creates a new HTTP-MCP bridge from an existing TCP listener.
    fn new(listener: tokio::net::TcpListener) -> Self {
        Self { listener }
    }
}

impl ConnectTo<mcp::Client> for HttpMcpBridge {
    async fn connect_to(
        self,
        client: impl ConnectTo<mcp::Server>,
    ) -> Result<(), agent_client_protocol::Error> {
        let (channel, serve_self) = self.into_channel_and_future();
        match futures::future::select(pin!(client.connect_to(channel)), serve_self).await {
            Either::Left((result, _)) | Either::Right((result, _)) => result,
        }
    }

    fn into_channel_and_future(
        self,
    ) -> (
        Channel,
        BoxFuture<'static, Result<(), agent_client_protocol::Error>>,
    )
    where
        Self: Sized,
    {
        let (channel_a, channel_b) = Channel::duplex();
        (channel_a, Box::pin(run(self.listener, channel_b)))
    }
}

/// Error type that we use to respond to malformed HTTP requests.
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
struct HttpError(#[from] agent_client_protocol::Error);

impl From<axum::Error> for HttpError {
    fn from(error: axum::Error) -> Self {
        HttpError(agent_client_protocol::util::internal_error(error))
    }
}

impl IntoResponse for HttpError {
    fn into_response(self) -> Response {
        let message = format!("Error: {}", self.0);
        (StatusCode::INTERNAL_SERVER_ERROR, message).into_response()
    }
}

/// Run a webserver listening on `listener` for HTTP requests at `/`
/// and communicating those requests over `channel` to the JSON-RPC server.
async fn run(listener: TcpListener, channel: Channel) -> Result<(), agent_client_protocol::Error> {
    let (registration_tx, registration_rx) = mpsc::unbounded();

    let state = BridgeState { registration_tx };

    // The way that the MCP protocol works is a bit "special".
    //
    // Clients *POST* messages to `/`. Those are submitted to the MCP server.
    // If the message is a REQUEST, then the client waits until it gets a reply.
    // It expects the server to close the connection after responding.
    //
    // Clients can also issue a *GET* request. This will result in a stream of messages.
    //
    // Non-reply messages can be send to any open stream (POST, GET, etc) but must be sent to
    // exactly one.
    //
    // There are provisions for "resuming" from a blocked point by tagging each message in the SSE stream
    // with an id, but we are not implementing that because I am lazy.
    async {
        let app = Router::new()
            .route("/", post(handle_post).get(handle_get))
            .with_state(Arc::new(state));

        axum::serve(listener, app)
            .await
            .map_err(agent_client_protocol::util::internal_error)
    }
    .race(RunningServer::new().run(channel, registration_rx))
    .await
}

/// The state we pass to our POST/GET handlers.
struct BridgeState {
    /// Where to send registration messages.
    registration_tx: mpsc::UnboundedSender<HttpMessage>,
}

/// Messages from HTTP handlers to the bridge server.
#[derive(Debug)]
enum HttpMessage {
    /// A JSON-RPC request (has an id, expects a response via the channel)
    Request {
        http_request_id: uuid::Uuid,
        request: agent_client_protocol::jsonrpcmsg::Request,
        response_tx: mpsc::UnboundedSender<agent_client_protocol::jsonrpcmsg::Message>,
    },
    /// A JSON-RPC notification (no id, no response expected)
    Notification {
        http_request_id: uuid::Uuid,
        request: agent_client_protocol::jsonrpcmsg::Request,
    },
    /// A JSON-RPC response from the client
    Response {
        http_request_id: uuid::Uuid,
        response: agent_client_protocol::jsonrpcmsg::Response,
    },
    /// A GET request to open an SSE stream for server-initiated messages
    Get {
        http_request_id: uuid::Uuid,
        response_tx: mpsc::UnboundedSender<agent_client_protocol::jsonrpcmsg::Message>,
    },
}

/// Clone of `agent_client_protocol::jsonrpcmsg::Id` since for unfathomable reasons that does not impl Hash
#[derive(Eq, PartialEq, PartialOrd, Ord, Hash, Debug, Clone)]
enum JsonRpcId {
    /// String identifier
    String(String),
    /// Numeric identifier
    Number(u64),
    /// Null identifier (for notifications)
    Null,
}

impl From<agent_client_protocol::jsonrpcmsg::Id> for JsonRpcId {
    fn from(id: agent_client_protocol::jsonrpcmsg::Id) -> Self {
        match id {
            agent_client_protocol::jsonrpcmsg::Id::String(s) => JsonRpcId::String(s),
            agent_client_protocol::jsonrpcmsg::Id::Number(n) => JsonRpcId::Number(n),
            agent_client_protocol::jsonrpcmsg::Id::Null => JsonRpcId::Null,
        }
    }
}

struct RunningServer {
    waiting_sessions: FxHashMap<JsonRpcId, RegisteredSession>,
    general_sessions: Vec<RegisteredSession>,
    message_deque: VecDeque<agent_client_protocol::jsonrpcmsg::Message>,
}

impl RunningServer {
    fn new() -> Self {
        RunningServer {
            waiting_sessions: HashMap::default(),
            general_sessions: Vec::default(),
            message_deque: VecDeque::with_capacity(32),
        }
    }

    /// The main loop: listen for incoming HTTP messages and outgoing JSON-RPC messages.
    ///
    /// # Parameters
    ///
    /// * `channel`: The channel to use for sending/receiving JSON-RPC messages.
    /// * `http_rx`: The receiver for messages from HTTP handlers.
    async fn run(
        mut self,
        mut channel: Channel,
        http_rx: mpsc::UnboundedReceiver<HttpMessage>,
    ) -> Result<(), agent_client_protocol::Error> {
        #[derive(Debug)]
        enum MultiplexMessage {
            FromHttpToChannel(HttpMessage),
            FromChannelToHttp(
                Result<agent_client_protocol::jsonrpcmsg::Message, agent_client_protocol::Error>,
            ),
        }

        let mut merged_stream = http_rx
            .map(MultiplexMessage::FromHttpToChannel)
            .merge(channel.rx.map(MultiplexMessage::FromChannelToHttp));

        while let Some(message) = merged_stream.next().await {
            tracing::trace!(?message, "received message");

            match message {
                MultiplexMessage::FromHttpToChannel(http_message) => {
                    self.handle_http_message(http_message, &mut channel.tx)?;
                }

                MultiplexMessage::FromChannelToHttp(message) => {
                    let message = message.unwrap_or_else(|err| {
                        agent_client_protocol::jsonrpcmsg::Message::Response(
                            agent_client_protocol::jsonrpcmsg::Response::error(
                                agent_client_protocol::util::into_jsonrpc_error(err),
                                None,
                            ),
                        )
                    });
                    tracing::debug!(
                        queue_len = self.message_deque.len() + 1,
                        ?message,
                        "enqueuing outgoing message"
                    );
                    self.message_deque.push_back(message);
                }
            }

            self.drain_jsonrpc_messages();
        }

        tracing::trace!("http connection terminating");

        Ok(())
    }

    /// Handle an incoming HTTP message (request, notification, response, or GET).
    fn handle_http_message(
        &mut self,
        message: HttpMessage,
        channel_tx: &mut mpsc::UnboundedSender<
            Result<agent_client_protocol::jsonrpcmsg::Message, agent_client_protocol::Error>,
        >,
    ) -> Result<(), agent_client_protocol::Error> {
        match message {
            HttpMessage::Request {
                http_request_id,
                request,
                response_tx,
            } => {
                tracing::debug!(%http_request_id, ?request, "handling request");
                let request_id = request.id.clone().map(JsonRpcId::from);

                // Send to the JSON-RPC server
                channel_tx
                    .unbounded_send(Ok(Message::Request(request)))
                    .map_err(agent_client_protocol::util::internal_error)?;

                // Register to receive the response
                let session = RegisteredSession::new(response_tx);
                if let Some(id) = request_id {
                    tracing::debug!(%http_request_id, session_id = %session.id, ?id, "registering waiting session");
                    self.waiting_sessions.insert(id, session);
                } else {
                    // Request without id - treat like a general session
                    tracing::debug!(%http_request_id, session_id = %session.id, "registering general session (request without id)");
                    self.general_sessions.push(session);
                }
            }

            HttpMessage::Notification {
                http_request_id,
                request,
            } => {
                tracing::debug!(%http_request_id, ?request, "handling notification");
                // Just forward to the server, no response tracking needed
                channel_tx
                    .unbounded_send(Ok(Message::Request(request)))
                    .map_err(agent_client_protocol::util::internal_error)?;
            }

            HttpMessage::Response {
                http_request_id,
                response,
            } => {
                tracing::debug!(%http_request_id, ?response, "handling response");
                // Forward to the server
                channel_tx
                    .unbounded_send(Ok(Message::Response(response)))
                    .map_err(agent_client_protocol::util::internal_error)?;
            }

            HttpMessage::Get {
                http_request_id,
                response_tx,
            } => {
                let session = RegisteredSession::new(response_tx);
                tracing::debug!(
                    %http_request_id,
                    session_id = %session.id,
                    queued_messages = self.message_deque.len(),
                    "handling GET (opening SSE stream)"
                );
                // Register as a general session to receive server-initiated messages
                self.general_sessions.push(session);
            }
        }

        // Purge closed sessions for good hygiene
        self.purge_closed_sessions();

        Ok(())
    }

    /// Remove messages from the queue and send them.
    /// Stop if we cannot find places to send them.
    fn drain_jsonrpc_messages(&mut self) {
        if !self.message_deque.is_empty() {
            tracing::debug!(
                queue_len = self.message_deque.len(),
                general_sessions = self.general_sessions.len(),
                waiting_sessions = self.waiting_sessions.len(),
                "draining message queue"
            );
        }

        while let Some(message) = self.message_deque.pop_front() {
            match self.try_dispatch_jsonrpc_message(message) {
                None => {
                    tracing::debug!(
                        remaining = self.message_deque.len(),
                        "message dispatched successfully"
                    );
                }

                Some(message) => {
                    tracing::debug!(
                        remaining = self.message_deque.len() + 1,
                        "no available session, re-enqueuing message"
                    );
                    self.message_deque.push_front(message);
                    break;
                }
            }
        }
    }

    /// Invoked when there is an outgoing JSON-RPC message to send.
    /// Tries to find a suitable place to send it.
    /// If it succeeds, returns `None`.
    /// If there is no place to send it, returns `Some(message)`.
    fn try_dispatch_jsonrpc_message(
        &mut self,
        mut message: agent_client_protocol::jsonrpcmsg::Message,
    ) -> Option<agent_client_protocol::jsonrpcmsg::Message> {
        // Extract the id of the message we are replying to, if any
        let message_id = match &message {
            Message::Response(response) => response.id.as_ref().map(|v| v.clone().into()),
            Message::Request(_) => None,
        };

        tracing::debug!(?message_id, "attempting to dispatch JSON-RPC message");

        // If there is a specific id, try to send the message to that sender.
        // This also removes them from the list of waiting sessions.
        if let Some(ref message_id) = message_id
            && let Some(session) = self.waiting_sessions.remove(message_id)
        {
            tracing::debug!(session_id = %session.id, "found waiting session, attempting send");

            match session.outgoing_tx.unbounded_send(message) {
                // Successfully sent the message, return
                Ok(()) => {
                    tracing::debug!(session_id = %session.id, "sent to waiting session");
                    return None;
                }

                // If the sender died, just recover the message and send it to anyone.
                Err(m) => {
                    tracing::debug!(session_id = %session.id, "waiting session disconnected");
                    // If that sender is dead, remove them from the list
                    // and recover the message.
                    assert!(m.is_disconnected());
                    message = m.into_inner();
                }
            }
        }

        // Try to find *somewhere* to send the message
        self.purge_closed_sessions();
        tracing::debug!(
            general_sessions = self.general_sessions.len(),
            waiting_sessions = self.waiting_sessions.len(),
            "trying to find any active session"
        );
        let all_sessions = self
            .general_sessions
            .iter_mut()
            .chain(self.waiting_sessions.values_mut());
        for session in all_sessions {
            tracing::trace!(session_id = %session.id, "trying session");
            match session.outgoing_tx.unbounded_send(message) {
                Ok(()) => {
                    tracing::debug!(session_id = %session.id, "sent to session");
                    return None;
                }

                Err(m) => {
                    tracing::debug!(session_id = %session.id, "session disconnected, trying next");
                    assert!(m.is_disconnected());
                    message = m.into_inner();
                }
            }
        }

        // If we don't find anywhere to send the message, return it.
        Some(message)
    }

    /// Purge sessions from the bridge state where the receiver is closed.
    /// This happens when the HTTP client disconnects.
    fn purge_closed_sessions(&mut self) {
        self.general_sessions
            .retain(|session| !session.outgoing_tx.is_closed());
        self.waiting_sessions
            .retain(|_, session| !session.outgoing_tx.is_closed());
    }
}

struct RegisteredSession {
    id: uuid::Uuid,
    outgoing_tx: mpsc::UnboundedSender<agent_client_protocol::jsonrpcmsg::Message>,
}

impl RegisteredSession {
    fn new(outgoing_tx: mpsc::UnboundedSender<agent_client_protocol::jsonrpcmsg::Message>) -> Self {
        Self {
            id: uuid::Uuid::new_v4(),
            outgoing_tx,
        }
    }
}

/// Accept a POST request carrying a JSON-RPC message from an MCP client.
/// For requests (messages with id), we return an SSE stream.
/// For notifications/responses (messages without id), we return 202 Accepted.
async fn handle_post(
    State(state): State<Arc<BridgeState>>,
    body: String,
) -> Result<Response, HttpError> {
    let http_request_id = uuid::Uuid::new_v4();

    // Parse incoming JSON-RPC message
    let message: agent_client_protocol::jsonrpcmsg::Message =
        serde_json::from_str(&body).map_err(agent_client_protocol::util::parse_error)?;

    match message {
        Message::Request(request) if request.id.is_some() => {
            tracing::debug!(%http_request_id, method = %request.method, "POST request received");
            // Request with id - return SSE stream for response
            let (tx, mut rx) = mpsc::unbounded();
            state
                .registration_tx
                .unbounded_send(HttpMessage::Request {
                    http_request_id,
                    request,
                    response_tx: tx,
                })
                .map_err(agent_client_protocol::util::internal_error)?;

            let stream = async_stream::stream! {
                while let Some(message) = rx.next().await {
                    tracing::debug!(%http_request_id, "sending SSE event");
                    match axum::response::sse::Event::default().json_data(message) {
                        Ok(v) => yield Ok(v),
                        Err(e) => yield Err(HttpError::from(e)),
                    }
                }
                tracing::debug!(%http_request_id, "SSE stream completed");
            };
            Ok(Sse::new(stream).into_response())
        }

        Message::Request(request) => {
            tracing::debug!(%http_request_id, method = %request.method, "POST notification received");
            // Request without id is a notification
            state
                .registration_tx
                .unbounded_send(HttpMessage::Notification {
                    http_request_id,
                    request,
                })
                .map_err(agent_client_protocol::util::internal_error)?;
            Ok(StatusCode::ACCEPTED.into_response())
        }

        Message::Response(response) => {
            tracing::debug!(%http_request_id, "POST response received");
            // Response from client (rare, but possible in MCP)
            state
                .registration_tx
                .unbounded_send(HttpMessage::Response {
                    http_request_id,
                    response,
                })
                .map_err(agent_client_protocol::util::internal_error)?;
            Ok(StatusCode::ACCEPTED.into_response())
        }
    }
}

/// Accept a GET request from an MCP client.
/// Opens an SSE stream for server-initiated messages.
async fn handle_get(
    State(state): State<Arc<BridgeState>>,
) -> Result<Sse<impl Stream<Item = Result<axum::response::sse::Event, HttpError>>>, HttpError> {
    let http_request_id = uuid::Uuid::new_v4();
    tracing::debug!(%http_request_id, "GET request received");

    let (tx, mut rx) = mpsc::unbounded();
    state
        .registration_tx
        .unbounded_send(HttpMessage::Get {
            http_request_id,
            response_tx: tx,
        })
        .map_err(agent_client_protocol::util::internal_error)?;

    let stream = async_stream::stream! {
        while let Some(message) = rx.next().await {
            tracing::debug!(%http_request_id, "sending SSE event");
            match axum::response::sse::Event::default().json_data(message) {
                Ok(v) => yield Ok(v),
                Err(e) => yield Err(HttpError::from(e)),
            }
        }
        tracing::debug!(%http_request_id, "SSE stream completed");
    };

    Ok(Sse::new(stream))
}