client.rs

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