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_impl(method, params, None).await
336    }
337
338    pub async fn cancellable_request<T: DeserializeOwned>(
339        &self,
340        method: &str,
341        params: impl Serialize,
342        cancel_rx: oneshot::Receiver<()>,
343    ) -> Result<T> {
344        self.request_impl(method, params, Some(cancel_rx)).await
345    }
346
347    pub async fn request_impl<T: DeserializeOwned>(
348        &self,
349        method: &str,
350        params: impl Serialize,
351        cancel_rx: Option<oneshot::Receiver<()>>,
352    ) -> Result<T> {
353        let id = self.next_id.fetch_add(1, SeqCst);
354        let request = serde_json::to_string(&Request {
355            jsonrpc: JSON_RPC_VERSION,
356            id: RequestId::Int(id),
357            method,
358            params,
359        })
360        .unwrap();
361
362        let (tx, rx) = oneshot::channel();
363        let handle_response = self
364            .response_handlers
365            .lock()
366            .as_mut()
367            .context("server shut down")
368            .map(|handlers| {
369                handlers.insert(
370                    RequestId::Int(id),
371                    Box::new(move |result| {
372                        let _ = tx.send(result);
373                    }),
374                );
375            });
376
377        let send = self
378            .outbound_tx
379            .try_send(request)
380            .context("failed to write to context server's stdin");
381
382        let executor = self.executor.clone();
383        let started = Instant::now();
384        handle_response?;
385        send?;
386
387        let mut timeout = executor.timer(REQUEST_TIMEOUT).fuse();
388        let mut cancel_fut = pin!(
389            match cancel_rx {
390                Some(rx) => future::Either::Left(async {
391                    rx.await.log_err();
392                }),
393                None => future::Either::Right(future::pending()),
394            }
395            .fuse()
396        );
397
398        select! {
399            response = rx.fuse() => {
400                let elapsed = started.elapsed();
401                log::trace!("took {elapsed:?} to receive response to {method:?} id {id}");
402                match response? {
403                    Ok(response) => {
404                        let parsed: AnyResponse = serde_json::from_str(&response)?;
405                        if let Some(error) = parsed.error {
406                            Err(anyhow!(error.message))
407                        } else if let Some(result) = parsed.result {
408                            Ok(serde_json::from_str(result.get())?)
409                        } else {
410                            anyhow::bail!("Invalid response: no result or error");
411                        }
412                    }
413                    Err(_) => anyhow::bail!("cancelled")
414                }
415            }
416            _ = cancel_fut => {
417                self.notify(
418                    Cancelled::METHOD,
419                    ClientNotification::Cancelled(CancelledParams {
420                        request_id: RequestId::Int(id),
421                        reason: None
422                    })
423                ).log_err();
424                anyhow::bail!("Request cancelled")
425            }
426            _ = timeout => {
427                log::error!("cancelled csp request task for {method:?} id {id} which took over {:?}", REQUEST_TIMEOUT);
428                anyhow::bail!("Context server request timeout");
429            }
430        }
431    }
432
433    /// Sends a notification to the context server without expecting a response.
434    /// This function serializes the notification and sends it through the outbound channel.
435    pub fn notify(&self, method: &str, params: impl Serialize) -> Result<()> {
436        let notification = serde_json::to_string(&Notification {
437            jsonrpc: JSON_RPC_VERSION,
438            method,
439            params,
440        })
441        .unwrap();
442        self.outbound_tx.try_send(notification)?;
443        Ok(())
444    }
445
446    #[allow(unused)]
447    pub fn on_notification<F>(&self, method: &'static str, f: F)
448    where
449        F: 'static + Send + FnMut(Value, AsyncApp),
450    {
451        self.notification_handlers
452            .lock()
453            .insert(method, Box::new(f));
454    }
455
456    pub fn on_request<R: crate::types::Request, F>(&self, mut f: F)
457    where
458        F: 'static + Send + FnMut(R::Params, AsyncApp) -> Task<Result<R::Response>>,
459    {
460        let outbound_tx = self.outbound_tx.clone();
461        self.request_handlers.lock().insert(
462            R::METHOD,
463            Box::new(move |id, json, cx| {
464                let outbound_tx = outbound_tx.clone();
465                match serde_json::from_str(json.get()) {
466                    Ok(req) => {
467                        let task = f(req, cx.clone());
468                        cx.foreground_executor()
469                            .spawn(async move {
470                                match task.await {
471                                    Ok(res) => {
472                                        outbound_tx
473                                            .send(
474                                                serde_json::to_string(&Response {
475                                                    jsonrpc: JSON_RPC_VERSION,
476                                                    id,
477                                                    value: CspResult::Ok(Some(res)),
478                                                })
479                                                .unwrap(),
480                                            )
481                                            .await
482                                            .ok();
483                                    }
484                                    Err(e) => {
485                                        outbound_tx
486                                            .send(
487                                                serde_json::to_string(&Response {
488                                                    jsonrpc: JSON_RPC_VERSION,
489                                                    id,
490                                                    value: CspResult::<()>::Error(Some(Error {
491                                                        code: -1, // todo!()
492                                                        message: format!("{e}"),
493                                                    })),
494                                                })
495                                                .unwrap(),
496                                            )
497                                            .await
498                                            .ok();
499                                    }
500                                }
501                            })
502                            .detach();
503                    }
504                    Err(e) => {
505                        cx.foreground_executor()
506                            .spawn(async move {
507                                outbound_tx
508                                    .send(
509                                        serde_json::to_string(&Response {
510                                            jsonrpc: JSON_RPC_VERSION,
511                                            id,
512                                            value: CspResult::<()>::Error(Some(Error {
513                                                code: -1, // todo!()
514                                                message: format!("{e}"),
515                                            })),
516                                        })
517                                        .unwrap(),
518                                    )
519                                    .await
520                                    .ok();
521                            })
522                            .detach();
523                    }
524                }
525            }),
526        );
527    }
528}
529
530impl fmt::Display for ContextServerId {
531    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532        self.0.fmt(f)
533    }
534}
535
536impl fmt::Debug for Client {
537    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
538        f.debug_struct("Context Server Client")
539            .field("id", &self.server_id.0)
540            .field("name", &self.name)
541            .finish_non_exhaustive()
542    }
543}