client.rs

  1use anyhow::{Context as _, Result, anyhow};
  2use collections::HashMap;
  3use futures::{FutureExt, StreamExt, channel::oneshot, 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    sync::{
 14        Arc,
 15        atomic::{AtomicI32, Ordering::SeqCst},
 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(crate) 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(crate) 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 stdio(
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        Self::new(server_id, server_name.into(), transport, cx)
162    }
163
164    /// Creates a new Client instance for a context server.
165    pub fn new(
166        server_id: ContextServerId,
167        server_name: Arc<str>,
168        transport: Arc<dyn Transport>,
169        cx: AsyncApp,
170    ) -> Result<Self> {
171        let (outbound_tx, outbound_rx) = channel::unbounded::<String>();
172        let (output_done_tx, output_done_rx) = barrier::channel();
173
174        let notification_handlers =
175            Arc::new(Mutex::new(HashMap::<_, NotificationHandler>::default()));
176        let response_handlers =
177            Arc::new(Mutex::new(Some(HashMap::<_, ResponseHandler>::default())));
178
179        let receive_input_task = cx.spawn({
180            let notification_handlers = notification_handlers.clone();
181            let response_handlers = response_handlers.clone();
182            let transport = transport.clone();
183            async move |cx| {
184                Self::handle_input(transport, notification_handlers, response_handlers, cx)
185                    .log_err()
186                    .await
187            }
188        });
189        let receive_err_task = cx.spawn({
190            let transport = transport.clone();
191            async move |_| Self::handle_err(transport).log_err().await
192        });
193        let input_task = cx.spawn(async move |_| {
194            let (input, err) = futures::join!(receive_input_task, receive_err_task);
195            input.or(err)
196        });
197
198        let output_task = cx.background_spawn({
199            let transport = transport.clone();
200            Self::handle_output(
201                transport,
202                outbound_rx,
203                output_done_tx,
204                response_handlers.clone(),
205            )
206            .log_err()
207        });
208
209        Ok(Self {
210            server_id,
211            notification_handlers,
212            response_handlers,
213            name: server_name,
214            next_id: Default::default(),
215            outbound_tx,
216            executor: cx.background_executor().clone(),
217            io_tasks: Mutex::new(Some((input_task, output_task))),
218            output_done_rx: Mutex::new(Some(output_done_rx)),
219            transport,
220        })
221    }
222
223    /// Handles input from the server's stdout.
224    ///
225    /// This function continuously reads lines from the provided stdout stream,
226    /// parses them as JSON-RPC responses or notifications, and dispatches them
227    /// to the appropriate handlers. It processes both responses (which are matched
228    /// to pending requests) and notifications (which trigger registered handlers).
229    async fn handle_input(
230        transport: Arc<dyn Transport>,
231        notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
232        response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
233        cx: &mut AsyncApp,
234    ) -> anyhow::Result<()> {
235        let mut receiver = transport.receive();
236
237        while let Some(message) = receiver.next().await {
238            if let Ok(response) = serde_json::from_str::<AnyResponse>(&message) {
239                if let Some(handlers) = response_handlers.lock().as_mut() {
240                    if let Some(handler) = handlers.remove(&response.id) {
241                        handler(Ok(message.to_string()));
242                    }
243                }
244            } else if let Ok(notification) = serde_json::from_str::<AnyNotification>(&message) {
245                let mut notification_handlers = notification_handlers.lock();
246                if let Some(handler) = notification_handlers.get_mut(notification.method.as_str()) {
247                    handler(notification.params.unwrap_or(Value::Null), cx.clone());
248                }
249            }
250        }
251
252        smol::future::yield_now().await;
253
254        Ok(())
255    }
256
257    /// Handles the stderr output from the context server.
258    /// Continuously reads and logs any error messages from the server.
259    async fn handle_err(transport: Arc<dyn Transport>) -> anyhow::Result<()> {
260        while let Some(err) = transport.receive_err().next().await {
261            log::warn!("context server stderr: {}", err.trim());
262        }
263
264        Ok(())
265    }
266
267    /// Handles the output to the context server's stdin.
268    /// This function continuously receives messages from the outbound channel,
269    /// writes them to the server's stdin, and manages the lifecycle of response handlers.
270    async fn handle_output(
271        transport: Arc<dyn Transport>,
272        outbound_rx: channel::Receiver<String>,
273        output_done_tx: barrier::Sender,
274        response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
275    ) -> anyhow::Result<()> {
276        let _clear_response_handlers = util::defer({
277            let response_handlers = response_handlers.clone();
278            move || {
279                response_handlers.lock().take();
280            }
281        });
282        while let Ok(message) = outbound_rx.recv().await {
283            log::trace!("outgoing message: {}", message);
284            transport.send(message).await?;
285        }
286        drop(output_done_tx);
287        Ok(())
288    }
289
290    /// Sends a JSON-RPC request to the context server and waits for a response.
291    /// This function handles serialization, deserialization, timeout, and error handling.
292    pub async fn request<T: DeserializeOwned>(
293        &self,
294        method: &str,
295        params: impl Serialize,
296    ) -> Result<T> {
297        let id = self.next_id.fetch_add(1, SeqCst);
298        let request = serde_json::to_string(&Request {
299            jsonrpc: JSON_RPC_VERSION,
300            id: RequestId::Int(id),
301            method,
302            params,
303        })
304        .unwrap();
305
306        let (tx, rx) = oneshot::channel();
307        let handle_response = self
308            .response_handlers
309            .lock()
310            .as_mut()
311            .context("server shut down")
312            .map(|handlers| {
313                handlers.insert(
314                    RequestId::Int(id),
315                    Box::new(move |result| {
316                        let _ = tx.send(result);
317                    }),
318                );
319            });
320
321        let send = self
322            .outbound_tx
323            .try_send(request)
324            .context("failed to write to context server's stdin");
325
326        let executor = self.executor.clone();
327        let started = Instant::now();
328        handle_response?;
329        send?;
330
331        let mut timeout = executor.timer(REQUEST_TIMEOUT).fuse();
332        select! {
333            response = rx.fuse() => {
334                let elapsed = started.elapsed();
335                log::trace!("took {elapsed:?} to receive response to {method:?} id {id}");
336                match response? {
337                    Ok(response) => {
338                        let parsed: AnyResponse = serde_json::from_str(&response)?;
339                        if let Some(error) = parsed.error {
340                            Err(anyhow!(error.message))
341                        } else if let Some(result) = parsed.result {
342                            Ok(serde_json::from_str(result.get())?)
343                        } else {
344                            anyhow::bail!("Invalid response: no result or error");
345                        }
346                    }
347                    Err(_) => anyhow::bail!("cancelled")
348                }
349            }
350            _ = timeout => {
351                log::error!("cancelled csp request task for {method:?} id {id} which took over {:?}", REQUEST_TIMEOUT);
352                anyhow::bail!("Context server request timeout");
353            }
354        }
355    }
356
357    /// Sends a notification to the context server without expecting a response.
358    /// This function serializes the notification and sends it through the outbound channel.
359    pub fn notify(&self, method: &str, params: impl Serialize) -> Result<()> {
360        let notification = serde_json::to_string(&Notification {
361            jsonrpc: JSON_RPC_VERSION,
362            method,
363            params,
364        })
365        .unwrap();
366        self.outbound_tx.try_send(notification)?;
367        Ok(())
368    }
369
370    #[allow(unused)]
371    pub fn on_notification<F>(&self, method: &'static str, f: F)
372    where
373        F: 'static + Send + FnMut(Value, AsyncApp),
374    {
375        self.notification_handlers
376            .lock()
377            .insert(method, Box::new(f));
378    }
379}
380
381impl fmt::Display for ContextServerId {
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        self.0.fmt(f)
384    }
385}
386
387impl fmt::Debug for Client {
388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389        f.debug_struct("Context Server Client")
390            .field("id", &self.server_id.0)
391            .field("name", &self.name)
392            .finish_non_exhaustive()
393    }
394}