client.rs

  1use anyhow::{anyhow, Context, Result};
  2use collections::HashMap;
  3use futures::{channel::oneshot, select, FutureExt, StreamExt};
  4use gpui::{AppContext as _, AsyncApp, BackgroundExecutor, Task};
  5use parking_lot::Mutex;
  6use postage::barrier;
  7use serde::{de::DeserializeOwned, Deserialize, Serialize};
  8use serde_json::{value::RawValue, Value};
  9use smol::channel;
 10use std::{
 11    fmt,
 12    path::PathBuf,
 13    sync::{
 14        atomic::{AtomicI32, Ordering::SeqCst},
 15        Arc,
 16    },
 17    time::{Duration, Instant},
 18};
 19use util::TryFutureExt;
 20
 21use crate::transport::{StdioTransport, Transport};
 22
 23const JSON_RPC_VERSION: &str = "2.0";
 24const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
 25
 26// Standard JSON-RPC error codes
 27pub const PARSE_ERROR: i32 = -32700;
 28pub const INVALID_REQUEST: i32 = -32600;
 29pub const METHOD_NOT_FOUND: i32 = -32601;
 30pub const INVALID_PARAMS: i32 = -32602;
 31pub const INTERNAL_ERROR: i32 = -32603;
 32
 33type ResponseHandler = Box<dyn Send + FnOnce(Result<String, Error>)>;
 34type NotificationHandler = Box<dyn Send + FnMut(Value, AsyncApp)>;
 35
 36#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
 37#[serde(untagged)]
 38pub enum RequestId {
 39    Int(i32),
 40    Str(String),
 41}
 42
 43pub struct Client {
 44    server_id: ContextServerId,
 45    next_id: AtomicI32,
 46    outbound_tx: channel::Sender<String>,
 47    name: Arc<str>,
 48    notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
 49    response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
 50    #[allow(clippy::type_complexity)]
 51    #[allow(dead_code)]
 52    io_tasks: Mutex<Option<(Task<Option<()>>, Task<Option<()>>)>>,
 53    #[allow(dead_code)]
 54    output_done_rx: Mutex<Option<barrier::Receiver>>,
 55    executor: BackgroundExecutor,
 56    #[allow(dead_code)]
 57    transport: Arc<dyn Transport>,
 58}
 59
 60#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
 61#[repr(transparent)]
 62pub struct ContextServerId(pub Arc<str>);
 63
 64fn is_null_value<T: Serialize>(value: &T) -> bool {
 65    if let Ok(Value::Null) = serde_json::to_value(value) {
 66        true
 67    } else {
 68        false
 69    }
 70}
 71
 72#[derive(Serialize, Deserialize)]
 73struct Request<'a, T> {
 74    jsonrpc: &'static str,
 75    id: RequestId,
 76    method: &'a str,
 77    #[serde(skip_serializing_if = "is_null_value")]
 78    params: T,
 79}
 80
 81#[derive(Serialize, Deserialize)]
 82struct AnyResponse<'a> {
 83    jsonrpc: &'a str,
 84    id: RequestId,
 85    #[serde(default)]
 86    error: Option<Error>,
 87    #[serde(borrow)]
 88    result: Option<&'a RawValue>,
 89}
 90
 91#[derive(Deserialize)]
 92#[allow(dead_code)]
 93struct Response<T> {
 94    jsonrpc: &'static str,
 95    id: RequestId,
 96    #[serde(flatten)]
 97    value: CspResult<T>,
 98}
 99
100#[derive(Deserialize)]
101#[serde(rename_all = "snake_case")]
102enum CspResult<T> {
103    #[serde(rename = "result")]
104    Ok(Option<T>),
105    #[allow(dead_code)]
106    Error(Option<Error>),
107}
108
109#[derive(Serialize, Deserialize)]
110struct Notification<'a, T> {
111    jsonrpc: &'static str,
112    #[serde(borrow)]
113    method: &'a str,
114    params: T,
115}
116
117#[derive(Debug, Clone, Deserialize)]
118struct AnyNotification<'a> {
119    jsonrpc: &'a str,
120    method: String,
121    #[serde(default)]
122    params: Option<Value>,
123}
124
125#[derive(Debug, Serialize, Deserialize)]
126struct Error {
127    message: String,
128}
129
130#[derive(Debug, Clone, Deserialize)]
131pub struct ModelContextServerBinary {
132    pub executable: PathBuf,
133    pub args: Vec<String>,
134    pub env: Option<HashMap<String, String>>,
135}
136
137impl Client {
138    /// Creates a new Client instance for a context server.
139    ///
140    /// This function initializes a new Client by spawning a child process for the context server,
141    /// setting up communication channels, and initializing handlers for input/output operations.
142    /// It takes a server ID, binary information, and an async app context as input.
143    pub fn new(
144        server_id: ContextServerId,
145        binary: ModelContextServerBinary,
146        cx: AsyncApp,
147    ) -> Result<Self> {
148        log::info!(
149            "starting context server (executable={:?}, args={:?})",
150            binary.executable,
151            &binary.args
152        );
153
154        let server_name = binary
155            .executable
156            .file_name()
157            .map(|name| name.to_string_lossy().to_string())
158            .unwrap_or_else(String::new);
159
160        let transport = Arc::new(StdioTransport::new(binary, &cx)?);
161
162        let (outbound_tx, outbound_rx) = channel::unbounded::<String>();
163        let (output_done_tx, output_done_rx) = barrier::channel();
164
165        let notification_handlers =
166            Arc::new(Mutex::new(HashMap::<_, NotificationHandler>::default()));
167        let response_handlers =
168            Arc::new(Mutex::new(Some(HashMap::<_, ResponseHandler>::default())));
169
170        let stdout_input_task = cx.spawn({
171            let notification_handlers = notification_handlers.clone();
172            let response_handlers = response_handlers.clone();
173            let transport = transport.clone();
174            move |cx| {
175                Self::handle_input(transport, notification_handlers, response_handlers, cx)
176                    .log_err()
177            }
178        });
179        let stderr_input_task = cx.spawn(|_| Self::handle_stderr(transport.clone()).log_err());
180        let input_task = cx.spawn(|_| async move {
181            let (stdout, stderr) = futures::join!(stdout_input_task, stderr_input_task);
182            stdout.or(stderr)
183        });
184
185        let output_task = cx.background_spawn({
186            let transport = transport.clone();
187            Self::handle_output(
188                transport,
189                outbound_rx,
190                output_done_tx,
191                response_handlers.clone(),
192            )
193            .log_err()
194        });
195
196        Ok(Self {
197            server_id,
198            notification_handlers,
199            response_handlers,
200            name: server_name.into(),
201            next_id: Default::default(),
202            outbound_tx,
203            executor: cx.background_executor().clone(),
204            io_tasks: Mutex::new(Some((input_task, output_task))),
205            output_done_rx: Mutex::new(Some(output_done_rx)),
206            transport,
207        })
208    }
209
210    /// Handles input from the server's stdout.
211    ///
212    /// This function continuously reads lines from the provided stdout stream,
213    /// parses them as JSON-RPC responses or notifications, and dispatches them
214    /// to the appropriate handlers. It processes both responses (which are matched
215    /// to pending requests) and notifications (which trigger registered handlers).
216    async fn handle_input(
217        transport: Arc<dyn Transport>,
218        notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
219        response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
220        cx: AsyncApp,
221    ) -> anyhow::Result<()> {
222        let mut receiver = transport.receive();
223
224        while let Some(message) = receiver.next().await {
225            if let Ok(response) = serde_json::from_str::<AnyResponse>(&message) {
226                if let Some(handlers) = response_handlers.lock().as_mut() {
227                    if let Some(handler) = handlers.remove(&response.id) {
228                        handler(Ok(message.to_string()));
229                    }
230                }
231            } else if let Ok(notification) = serde_json::from_str::<AnyNotification>(&message) {
232                let mut notification_handlers = notification_handlers.lock();
233                if let Some(handler) = notification_handlers.get_mut(notification.method.as_str()) {
234                    handler(notification.params.unwrap_or(Value::Null), cx.clone());
235                }
236            }
237        }
238
239        smol::future::yield_now().await;
240
241        Ok(())
242    }
243
244    /// Handles the stderr output from the context server.
245    /// Continuously reads and logs any error messages from the server.
246    async fn handle_stderr(transport: Arc<dyn Transport>) -> anyhow::Result<()> {
247        while let Some(err) = transport.receive_err().next().await {
248            log::warn!("context server stderr: {}", err.trim());
249        }
250
251        Ok(())
252    }
253
254    /// Handles the output to the context server's stdin.
255    /// This function continuously receives messages from the outbound channel,
256    /// writes them to the server's stdin, and manages the lifecycle of response handlers.
257    async fn handle_output(
258        transport: Arc<dyn Transport>,
259        outbound_rx: channel::Receiver<String>,
260        output_done_tx: barrier::Sender,
261        response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
262    ) -> anyhow::Result<()> {
263        let _clear_response_handlers = util::defer({
264            let response_handlers = response_handlers.clone();
265            move || {
266                response_handlers.lock().take();
267            }
268        });
269        while let Ok(message) = outbound_rx.recv().await {
270            log::trace!("outgoing message: {}", message);
271            transport.send(message).await?;
272        }
273        drop(output_done_tx);
274        Ok(())
275    }
276
277    /// Sends a JSON-RPC request to the context server and waits for a response.
278    /// This function handles serialization, deserialization, timeout, and error handling.
279    pub async fn request<T: DeserializeOwned>(
280        &self,
281        method: &str,
282        params: impl Serialize,
283    ) -> Result<T> {
284        let id = self.next_id.fetch_add(1, SeqCst);
285        let request = serde_json::to_string(&Request {
286            jsonrpc: JSON_RPC_VERSION,
287            id: RequestId::Int(id),
288            method,
289            params,
290        })
291        .unwrap();
292
293        let (tx, rx) = oneshot::channel();
294        let handle_response = self
295            .response_handlers
296            .lock()
297            .as_mut()
298            .ok_or_else(|| anyhow!("server shut down"))
299            .map(|handlers| {
300                handlers.insert(
301                    RequestId::Int(id),
302                    Box::new(move |result| {
303                        let _ = tx.send(result);
304                    }),
305                );
306            });
307
308        let send = self
309            .outbound_tx
310            .try_send(request)
311            .context("failed to write to context server's stdin");
312
313        let executor = self.executor.clone();
314        let started = Instant::now();
315        handle_response?;
316        send?;
317
318        let mut timeout = executor.timer(REQUEST_TIMEOUT).fuse();
319        select! {
320            response = rx.fuse() => {
321                let elapsed = started.elapsed();
322                log::trace!("took {elapsed:?} to receive response to {method:?} id {id}");
323                match response? {
324                    Ok(response) => {
325                        let parsed: AnyResponse = serde_json::from_str(&response)?;
326                        if let Some(error) = parsed.error {
327                            Err(anyhow!(error.message))
328                        } else if let Some(result) = parsed.result {
329                            Ok(serde_json::from_str(result.get())?)
330                        } else {
331                            Err(anyhow!("Invalid response: no result or error"))
332                        }
333                    }
334                    Err(_) => anyhow::bail!("cancelled")
335                }
336            }
337            _ = timeout => {
338                log::error!("cancelled csp request task for {method:?} id {id} which took over {:?}", REQUEST_TIMEOUT);
339                anyhow::bail!("Context server request timeout");
340            }
341        }
342    }
343
344    /// Sends a notification to the context server without expecting a response.
345    /// This function serializes the notification and sends it through the outbound channel.
346    pub fn notify(&self, method: &str, params: impl Serialize) -> Result<()> {
347        let notification = serde_json::to_string(&Notification {
348            jsonrpc: JSON_RPC_VERSION,
349            method,
350            params,
351        })
352        .unwrap();
353        self.outbound_tx.try_send(notification)?;
354        Ok(())
355    }
356
357    pub fn on_notification<F>(&self, method: &'static str, f: F)
358    where
359        F: 'static + Send + FnMut(Value, AsyncApp),
360    {
361        self.notification_handlers
362            .lock()
363            .insert(method, Box::new(f));
364    }
365
366    pub fn name(&self) -> &str {
367        &self.name
368    }
369
370    pub fn server_id(&self) -> ContextServerId {
371        self.server_id.clone()
372    }
373}
374
375impl fmt::Display for ContextServerId {
376    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377        self.0.fmt(f)
378    }
379}
380
381impl fmt::Debug for Client {
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        f.debug_struct("Context Server Client")
384            .field("id", &self.server_id.0)
385            .field("name", &self.name)
386            .finish_non_exhaustive()
387    }
388}