client.rs

  1use anyhow::{Context as _, Result, anyhow};
  2use collections::HashMap;
  3use futures::{FutureExt, StreamExt, channel::oneshot, future, select};
  4use gpui::{AppContext as _, AsyncApp, BackgroundExecutor, Task};
  5use parking_lot::Mutex;
  6use postage::barrier;
  7use serde::{Deserialize, Serialize, de::DeserializeOwned};
  8use serde_json::{Value, value::RawValue};
  9use smol::channel;
 10use std::{
 11    fmt,
 12    path::PathBuf,
 13    pin::pin,
 14    sync::{
 15        Arc,
 16        atomic::{AtomicI32, Ordering::SeqCst},
 17    },
 18    time::{Duration, Instant},
 19};
 20use util::{ResultExt, TryFutureExt};
 21
 22use crate::{
 23    transport::{StdioTransport, Transport},
 24    types::{CancelledParams, ClientNotification, Notification as _, notifications::Cancelled},
 25};
 26
 27const JSON_RPC_VERSION: &str = "2.0";
 28const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
 29
 30// Standard JSON-RPC error codes
 31pub const PARSE_ERROR: i32 = -32700;
 32pub const INVALID_REQUEST: i32 = -32600;
 33pub const METHOD_NOT_FOUND: i32 = -32601;
 34pub const INVALID_PARAMS: i32 = -32602;
 35pub const INTERNAL_ERROR: i32 = -32603;
 36
 37type ResponseHandler = Box<dyn Send + FnOnce(Result<String, Error>)>;
 38type NotificationHandler = Box<dyn Send + FnMut(Value, AsyncApp)>;
 39type RequestHandler = Box<dyn Send + FnMut(RequestId, &RawValue, AsyncApp)>;
 40
 41#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
 42#[serde(untagged)]
 43pub enum RequestId {
 44    Int(i32),
 45    Str(String),
 46}
 47
 48pub(crate) struct Client {
 49    server_id: ContextServerId,
 50    next_id: AtomicI32,
 51    outbound_tx: channel::Sender<String>,
 52    name: Arc<str>,
 53    notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
 54    request_handlers: Arc<Mutex<HashMap<&'static str, RequestHandler>>>,
 55    response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
 56    #[allow(clippy::type_complexity)]
 57    #[allow(dead_code)]
 58    io_tasks: Mutex<Option<(Task<Option<()>>, Task<Option<()>>)>>,
 59    #[allow(dead_code)]
 60    output_done_rx: Mutex<Option<barrier::Receiver>>,
 61    executor: BackgroundExecutor,
 62    #[allow(dead_code)]
 63    transport: Arc<dyn Transport>,
 64}
 65
 66#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
 67#[repr(transparent)]
 68pub(crate) struct ContextServerId(pub Arc<str>);
 69
 70fn is_null_value<T: Serialize>(value: &T) -> bool {
 71    if let Ok(Value::Null) = serde_json::to_value(value) {
 72        true
 73    } else {
 74        false
 75    }
 76}
 77
 78#[derive(Serialize, Deserialize)]
 79pub struct Request<'a, T> {
 80    pub jsonrpc: &'static str,
 81    pub id: RequestId,
 82    pub method: &'a str,
 83    #[serde(skip_serializing_if = "is_null_value")]
 84    pub params: T,
 85}
 86
 87#[derive(Serialize, Deserialize)]
 88pub struct AnyRequest<'a> {
 89    pub jsonrpc: &'a str,
 90    pub id: RequestId,
 91    pub method: &'a str,
 92    #[serde(skip_serializing_if = "is_null_value")]
 93    pub params: Option<&'a RawValue>,
 94}
 95
 96#[derive(Serialize, Deserialize)]
 97struct AnyResponse<'a> {
 98    jsonrpc: &'a str,
 99    id: RequestId,
100    #[serde(default)]
101    error: Option<Error>,
102    #[serde(borrow)]
103    result: Option<&'a RawValue>,
104}
105
106#[derive(Serialize, Deserialize)]
107#[allow(dead_code)]
108pub(crate) struct Response<T> {
109    pub jsonrpc: &'static str,
110    pub id: RequestId,
111    #[serde(flatten)]
112    pub value: CspResult<T>,
113}
114
115#[derive(Serialize, Deserialize)]
116#[serde(rename_all = "snake_case")]
117pub(crate) enum CspResult<T> {
118    #[serde(rename = "result")]
119    Ok(Option<T>),
120    #[allow(dead_code)]
121    Error(Option<Error>),
122}
123
124#[derive(Serialize, Deserialize)]
125struct Notification<'a, T> {
126    jsonrpc: &'static str,
127    #[serde(borrow)]
128    method: &'a str,
129    params: T,
130}
131
132#[derive(Debug, Clone, Deserialize)]
133struct AnyNotification<'a> {
134    jsonrpc: &'a str,
135    method: String,
136    #[serde(default)]
137    params: Option<Value>,
138}
139
140#[derive(Debug, Serialize, Deserialize)]
141pub(crate) struct Error {
142    pub message: String,
143    pub code: i32,
144}
145
146#[derive(Debug, Clone, Deserialize)]
147pub struct ModelContextServerBinary {
148    pub executable: PathBuf,
149    pub args: Vec<String>,
150    pub env: Option<HashMap<String, String>>,
151}
152
153impl Client {
154    /// Creates a new Client instance for a context server.
155    ///
156    /// This function initializes a new Client by spawning a child process for the context server,
157    /// setting up communication channels, and initializing handlers for input/output operations.
158    /// It takes a server ID, binary information, and an async app context as input.
159    pub fn stdio(
160        server_id: ContextServerId,
161        binary: ModelContextServerBinary,
162        cx: AsyncApp,
163    ) -> Result<Self> {
164        log::info!(
165            "starting context server (executable={:?}, args={:?})",
166            binary.executable,
167            &binary.args
168        );
169
170        let server_name = binary
171            .executable
172            .file_name()
173            .map(|name| name.to_string_lossy().to_string())
174            .unwrap_or_else(String::new);
175
176        let transport = Arc::new(StdioTransport::new(binary, &cx)?);
177        Self::new(server_id, server_name.into(), transport, cx)
178    }
179
180    /// Creates a new Client instance for a context server.
181    pub fn new(
182        server_id: ContextServerId,
183        server_name: Arc<str>,
184        transport: Arc<dyn Transport>,
185        cx: AsyncApp,
186    ) -> Result<Self> {
187        let (outbound_tx, outbound_rx) = channel::unbounded::<String>();
188        let (output_done_tx, output_done_rx) = barrier::channel();
189
190        let notification_handlers =
191            Arc::new(Mutex::new(HashMap::<_, NotificationHandler>::default()));
192        let response_handlers =
193            Arc::new(Mutex::new(Some(HashMap::<_, ResponseHandler>::default())));
194        let request_handlers = Arc::new(Mutex::new(HashMap::<_, RequestHandler>::default()));
195
196        let receive_input_task = cx.spawn({
197            let notification_handlers = notification_handlers.clone();
198            let response_handlers = response_handlers.clone();
199            let request_handlers = request_handlers.clone();
200            let transport = transport.clone();
201            async move |cx| {
202                Self::handle_input(
203                    transport,
204                    notification_handlers,
205                    request_handlers,
206                    response_handlers,
207                    cx,
208                )
209                .log_err()
210                .await
211            }
212        });
213        let receive_err_task = cx.spawn({
214            let transport = transport.clone();
215            async move |_| Self::handle_err(transport).log_err().await
216        });
217        let input_task = cx.spawn(async move |_| {
218            let (input, err) = futures::join!(receive_input_task, receive_err_task);
219            input.or(err)
220        });
221
222        let output_task = cx.background_spawn({
223            let transport = transport.clone();
224            Self::handle_output(
225                transport,
226                outbound_rx,
227                output_done_tx,
228                response_handlers.clone(),
229            )
230            .log_err()
231        });
232
233        Ok(Self {
234            server_id,
235            notification_handlers,
236            response_handlers,
237            request_handlers,
238            name: server_name,
239            next_id: Default::default(),
240            outbound_tx,
241            executor: cx.background_executor().clone(),
242            io_tasks: Mutex::new(Some((input_task, output_task))),
243            output_done_rx: Mutex::new(Some(output_done_rx)),
244            transport,
245        })
246    }
247
248    /// Handles input from the server's stdout.
249    ///
250    /// This function continuously reads lines from the provided stdout stream,
251    /// parses them as JSON-RPC responses or notifications, and dispatches them
252    /// to the appropriate handlers. It processes both responses (which are matched
253    /// to pending requests) and notifications (which trigger registered handlers).
254    async fn handle_input(
255        transport: Arc<dyn Transport>,
256        notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
257        request_handlers: Arc<Mutex<HashMap<&'static str, RequestHandler>>>,
258        response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
259        cx: &mut AsyncApp,
260    ) -> anyhow::Result<()> {
261        let mut receiver = transport.receive();
262
263        while let Some(message) = receiver.next().await {
264            log::trace!("recv: {}", &message);
265            if let Ok(request) = serde_json::from_str::<AnyRequest>(&message) {
266                let mut request_handlers = request_handlers.lock();
267                if let Some(handler) = request_handlers.get_mut(request.method) {
268                    handler(
269                        request.id,
270                        request.params.unwrap_or(RawValue::NULL),
271                        cx.clone(),
272                    );
273                }
274            } else if let Ok(response) = serde_json::from_str::<AnyResponse>(&message) {
275                if let Some(handlers) = response_handlers.lock().as_mut() {
276                    if let Some(handler) = handlers.remove(&response.id) {
277                        handler(Ok(message.to_string()));
278                    }
279                }
280            } else if let Ok(notification) = serde_json::from_str::<AnyNotification>(&message) {
281                let mut notification_handlers = notification_handlers.lock();
282                if let Some(handler) = notification_handlers.get_mut(notification.method.as_str()) {
283                    handler(notification.params.unwrap_or(Value::Null), cx.clone());
284                }
285            } else {
286                log::error!("Unhandled JSON from context_server: {}", message);
287            }
288        }
289
290        smol::future::yield_now().await;
291
292        Ok(())
293    }
294
295    /// Handles the stderr output from the context server.
296    /// Continuously reads and logs any error messages from the server.
297    async fn handle_err(transport: Arc<dyn Transport>) -> anyhow::Result<()> {
298        while let Some(err) = transport.receive_err().next().await {
299            log::warn!("context server stderr: {}", err.trim());
300        }
301
302        Ok(())
303    }
304
305    /// Handles the output to the context server's stdin.
306    /// This function continuously receives messages from the outbound channel,
307    /// writes them to the server's stdin, and manages the lifecycle of response handlers.
308    async fn handle_output(
309        transport: Arc<dyn Transport>,
310        outbound_rx: channel::Receiver<String>,
311        output_done_tx: barrier::Sender,
312        response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
313    ) -> anyhow::Result<()> {
314        let _clear_response_handlers = util::defer({
315            let response_handlers = response_handlers.clone();
316            move || {
317                response_handlers.lock().take();
318            }
319        });
320        while let Ok(message) = outbound_rx.recv().await {
321            log::trace!("outgoing message: {}", message);
322            transport.send(message).await?;
323        }
324        drop(output_done_tx);
325        Ok(())
326    }
327
328    /// Sends a JSON-RPC request to the context server and waits for a response.
329    /// This function handles serialization, deserialization, timeout, and error handling.
330    pub async fn request<T: DeserializeOwned>(
331        &self,
332        method: &str,
333        params: impl Serialize,
334    ) -> Result<T> {
335        self.request_with(method, params, None, Some(REQUEST_TIMEOUT))
336            .await
337    }
338
339    pub async fn request_with<T: DeserializeOwned>(
340        &self,
341        method: &str,
342        params: impl Serialize,
343        cancel_rx: Option<oneshot::Receiver<()>>,
344        timeout: Option<Duration>,
345    ) -> Result<T> {
346        let id = self.next_id.fetch_add(1, SeqCst);
347        let request = serde_json::to_string(&Request {
348            jsonrpc: JSON_RPC_VERSION,
349            id: RequestId::Int(id),
350            method,
351            params,
352        })
353        .unwrap();
354
355        let (tx, rx) = oneshot::channel();
356        let handle_response = self
357            .response_handlers
358            .lock()
359            .as_mut()
360            .context("server shut down")
361            .map(|handlers| {
362                handlers.insert(
363                    RequestId::Int(id),
364                    Box::new(move |result| {
365                        let _ = tx.send(result);
366                    }),
367                );
368            });
369
370        let send = self
371            .outbound_tx
372            .try_send(request)
373            .context("failed to write to context server's stdin");
374
375        let executor = self.executor.clone();
376        let started = Instant::now();
377        handle_response?;
378        send?;
379
380        let mut timeout_fut = pin!(
381            if let Some(timeout) = timeout {
382                future::Either::Left(executor.timer(timeout))
383            } else {
384                future::Either::Right(future::pending())
385            }
386            .fuse()
387        );
388
389        let mut cancel_fut = pin!(
390            match cancel_rx {
391                Some(rx) => future::Either::Left(async {
392                    rx.await.log_err();
393                }),
394                None => future::Either::Right(future::pending()),
395            }
396            .fuse()
397        );
398
399        select! {
400            response = rx.fuse() => {
401                let elapsed = started.elapsed();
402                log::trace!("took {elapsed:?} to receive response to {method:?} id {id}");
403                match response? {
404                    Ok(response) => {
405                        let parsed: AnyResponse = serde_json::from_str(&response)?;
406                        if let Some(error) = parsed.error {
407                            Err(anyhow!(error.message))
408                        } else if let Some(result) = parsed.result {
409                            Ok(serde_json::from_str(result.get())?)
410                        } else {
411                            anyhow::bail!("Invalid response: no result or error");
412                        }
413                    }
414                    Err(_) => anyhow::bail!("cancelled")
415                }
416            }
417            _ = cancel_fut => {
418                self.notify(
419                    Cancelled::METHOD,
420                    ClientNotification::Cancelled(CancelledParams {
421                        request_id: RequestId::Int(id),
422                        reason: None
423                    })
424                ).log_err();
425                anyhow::bail!("Request cancelled")
426            }
427            _ = timeout_fut => {
428                log::error!("cancelled csp request task for {method:?} id {id} which took over {:?}", timeout);
429                anyhow::bail!("Context server request timeout");
430            }
431        }
432    }
433
434    /// Sends a notification to the context server without expecting a response.
435    /// This function serializes the notification and sends it through the outbound channel.
436    pub fn notify(&self, method: &str, params: impl Serialize) -> Result<()> {
437        let notification = serde_json::to_string(&Notification {
438            jsonrpc: JSON_RPC_VERSION,
439            method,
440            params,
441        })
442        .unwrap();
443        self.outbound_tx.try_send(notification)?;
444        Ok(())
445    }
446
447    #[allow(unused)]
448    pub fn on_notification<F>(&self, method: &'static str, f: F)
449    where
450        F: 'static + Send + FnMut(Value, AsyncApp),
451    {
452        self.notification_handlers
453            .lock()
454            .insert(method, Box::new(f));
455    }
456
457    pub fn on_request<R: crate::types::Request, F>(&self, mut f: F)
458    where
459        F: 'static + Send + FnMut(R::Params, AsyncApp) -> Task<Result<R::Response>>,
460    {
461        let outbound_tx = self.outbound_tx.clone();
462        self.request_handlers.lock().insert(
463            R::METHOD,
464            Box::new(move |id, json, cx| {
465                let outbound_tx = outbound_tx.clone();
466                match serde_json::from_str(json.get()) {
467                    Ok(req) => {
468                        let task = f(req, cx.clone());
469                        cx.foreground_executor()
470                            .spawn(async move {
471                                match task.await {
472                                    Ok(res) => {
473                                        outbound_tx
474                                            .send(
475                                                serde_json::to_string(&Response {
476                                                    jsonrpc: JSON_RPC_VERSION,
477                                                    id,
478                                                    value: CspResult::Ok(Some(res)),
479                                                })
480                                                .unwrap(),
481                                            )
482                                            .await
483                                            .ok();
484                                    }
485                                    Err(e) => {
486                                        outbound_tx
487                                            .send(
488                                                serde_json::to_string(&Response {
489                                                    jsonrpc: JSON_RPC_VERSION,
490                                                    id,
491                                                    value: CspResult::<()>::Error(Some(Error {
492                                                        code: -1, // todo!()
493                                                        message: format!("{e}"),
494                                                    })),
495                                                })
496                                                .unwrap(),
497                                            )
498                                            .await
499                                            .ok();
500                                    }
501                                }
502                            })
503                            .detach();
504                    }
505                    Err(e) => {
506                        cx.foreground_executor()
507                            .spawn(async move {
508                                outbound_tx
509                                    .send(
510                                        serde_json::to_string(&Response {
511                                            jsonrpc: JSON_RPC_VERSION,
512                                            id,
513                                            value: CspResult::<()>::Error(Some(Error {
514                                                code: -1, // todo!()
515                                                message: format!("{e}"),
516                                            })),
517                                        })
518                                        .unwrap(),
519                                    )
520                                    .await
521                                    .ok();
522                            })
523                            .detach();
524                    }
525                }
526            }),
527        );
528    }
529}
530
531impl fmt::Display for ContextServerId {
532    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
533        self.0.fmt(f)
534    }
535}
536
537impl fmt::Debug for Client {
538    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
539        f.debug_struct("Context Server Client")
540            .field("id", &self.server_id.0)
541            .field("name", &self.name)
542            .finish_non_exhaustive()
543    }
544}