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 DEFAULT_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 response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
55 #[allow(clippy::type_complexity)]
56 #[allow(dead_code)]
57 io_tasks: Mutex<Option<(Task<Option<()>>, Task<Option<()>>)>>,
58 #[allow(dead_code)]
59 output_done_rx: Mutex<Option<barrier::Receiver>>,
60 executor: BackgroundExecutor,
61 #[allow(dead_code)]
62 transport: Arc<dyn Transport>,
63 request_timeout: Option<Duration>,
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 matches!(serde_json::to_value(value), Ok(Value::Null))
72}
73
74#[derive(Serialize, Deserialize)]
75pub struct Request<'a, T> {
76 pub jsonrpc: &'static str,
77 pub id: RequestId,
78 pub method: &'a str,
79 #[serde(skip_serializing_if = "is_null_value")]
80 pub params: T,
81}
82
83#[derive(Serialize, Deserialize)]
84pub struct AnyRequest<'a> {
85 pub jsonrpc: &'a str,
86 pub id: RequestId,
87 pub method: &'a str,
88 #[serde(skip_serializing_if = "is_null_value")]
89 pub params: Option<&'a RawValue>,
90}
91
92#[derive(Serialize, Deserialize)]
93struct AnyResponse<'a> {
94 jsonrpc: &'a str,
95 id: RequestId,
96 #[serde(default)]
97 error: Option<Error>,
98 #[serde(borrow)]
99 result: Option<&'a RawValue>,
100}
101
102#[derive(Serialize, Deserialize)]
103#[allow(dead_code)]
104pub(crate) struct Response<T> {
105 pub jsonrpc: &'static str,
106 pub id: RequestId,
107 #[serde(flatten)]
108 pub value: CspResult<T>,
109}
110
111#[derive(Serialize, Deserialize)]
112#[serde(rename_all = "snake_case")]
113pub(crate) enum CspResult<T> {
114 #[serde(rename = "result")]
115 Ok(Option<T>),
116 #[allow(dead_code)]
117 Error(Option<Error>),
118}
119
120#[derive(Serialize, Deserialize)]
121struct Notification<'a, T> {
122 jsonrpc: &'static str,
123 #[serde(borrow)]
124 method: &'a str,
125 params: T,
126}
127
128#[derive(Debug, Clone, Deserialize)]
129struct AnyNotification<'a> {
130 jsonrpc: &'a str,
131 method: String,
132 #[serde(default)]
133 params: Option<Value>,
134}
135
136#[derive(Debug, Serialize, Deserialize)]
137pub(crate) struct Error {
138 pub message: String,
139 pub code: i32,
140}
141
142#[derive(Debug, Clone, Deserialize)]
143pub struct ModelContextServerBinary {
144 pub executable: PathBuf,
145 pub args: Vec<String>,
146 pub env: Option<HashMap<String, String>>,
147 pub timeout: Option<u64>,
148}
149
150impl Client {
151 /// Creates a new Client instance for a context server.
152 ///
153 /// This function initializes a new Client by spawning a child process for the context server,
154 /// setting up communication channels, and initializing handlers for input/output operations.
155 /// It takes a server ID, binary information, and an async app context as input.
156 pub fn stdio(
157 server_id: ContextServerId,
158 binary: ModelContextServerBinary,
159 working_directory: &Option<PathBuf>,
160 cx: AsyncApp,
161 ) -> Result<Self> {
162 log::debug!(
163 "starting context server (executable={:?}, args={:?})",
164 binary.executable,
165 &binary.args
166 );
167
168 let server_name = binary
169 .executable
170 .file_name()
171 .map(|name| name.to_string_lossy().to_string())
172 .unwrap_or_else(String::new);
173
174 let timeout = binary.timeout.map(Duration::from_millis);
175 let transport = Arc::new(StdioTransport::new(binary, working_directory, &cx)?);
176 Self::new(server_id, server_name.into(), transport, timeout, cx)
177 }
178
179 /// Creates a new Client instance for a context server.
180 pub fn new(
181 server_id: ContextServerId,
182 server_name: Arc<str>,
183 transport: Arc<dyn Transport>,
184 request_timeout: Option<Duration>,
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 name: server_name,
238 next_id: Default::default(),
239 outbound_tx,
240 executor: cx.background_executor().clone(),
241 io_tasks: Mutex::new(Some((input_task, output_task))),
242 output_done_rx: Mutex::new(Some(output_done_rx)),
243 transport,
244 request_timeout,
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 && let Some(handler) = handlers.remove(&response.id)
277 {
278 handler(Ok(message.to_string()));
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::debug!("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(
336 method,
337 params,
338 None,
339 self.request_timeout.or(Some(DEFAULT_REQUEST_TIMEOUT)),
340 )
341 .await
342 }
343
344 pub async fn request_with<T: DeserializeOwned>(
345 &self,
346 method: &str,
347 params: impl Serialize,
348 cancel_rx: Option<oneshot::Receiver<()>>,
349 timeout: Option<Duration>,
350 ) -> Result<T> {
351 let id = self.next_id.fetch_add(1, SeqCst);
352 let request = serde_json::to_string(&Request {
353 jsonrpc: JSON_RPC_VERSION,
354 id: RequestId::Int(id),
355 method,
356 params,
357 })
358 .unwrap();
359
360 let (tx, rx) = oneshot::channel();
361 let handle_response = self
362 .response_handlers
363 .lock()
364 .as_mut()
365 .context("server shut down")
366 .map(|handlers| {
367 handlers.insert(
368 RequestId::Int(id),
369 Box::new(move |result| {
370 let _ = tx.send(result);
371 }),
372 );
373 });
374
375 let send = self
376 .outbound_tx
377 .try_send(request)
378 .context("failed to write to context server's stdin");
379
380 let executor = self.executor.clone();
381 let started = Instant::now();
382 handle_response?;
383 send?;
384
385 let mut timeout_fut = pin!(
386 match timeout {
387 Some(timeout) => future::Either::Left(executor.timer(timeout)),
388 None => future::Either::Right(future::pending()),
389 }
390 .fuse()
391 );
392 let mut cancel_fut = pin!(
393 match cancel_rx {
394 Some(rx) => future::Either::Left(async {
395 rx.await.log_err();
396 }),
397 None => future::Either::Right(future::pending()),
398 }
399 .fuse()
400 );
401
402 select! {
403 response = rx.fuse() => {
404 let elapsed = started.elapsed();
405 log::trace!("took {elapsed:?} to receive response to {method:?} id {id}");
406 match response? {
407 Ok(response) => {
408 let parsed: AnyResponse = serde_json::from_str(&response)?;
409 if let Some(error) = parsed.error {
410 Err(anyhow!(error.message))
411 } else if let Some(result) = parsed.result {
412 Ok(serde_json::from_str(result.get())?)
413 } else {
414 anyhow::bail!("Invalid response: no result or error");
415 }
416 }
417 Err(_) => anyhow::bail!("cancelled")
418 }
419 }
420 _ = cancel_fut => {
421 self.notify(
422 Cancelled::METHOD,
423 ClientNotification::Cancelled(CancelledParams {
424 request_id: RequestId::Int(id),
425 reason: None
426 })
427 ).log_err();
428 anyhow::bail!(RequestCanceled)
429 }
430 _ = timeout_fut => {
431 log::error!("cancelled csp request task for {method:?} id {id} which took over {:?}", timeout.unwrap());
432 anyhow::bail!("Context server request timeout");
433 }
434 }
435 }
436
437 /// Sends a notification to the context server without expecting a response.
438 /// This function serializes the notification and sends it through the outbound channel.
439 pub fn notify(&self, method: &str, params: impl Serialize) -> Result<()> {
440 let notification = serde_json::to_string(&Notification {
441 jsonrpc: JSON_RPC_VERSION,
442 method,
443 params,
444 })
445 .unwrap();
446 self.outbound_tx.try_send(notification)?;
447 Ok(())
448 }
449
450 pub fn on_notification(
451 &self,
452 method: &'static str,
453 f: Box<dyn 'static + Send + FnMut(Value, AsyncApp)>,
454 ) {
455 self.notification_handlers.lock().insert(method, f);
456 }
457}
458
459#[derive(Debug)]
460pub struct RequestCanceled;
461
462impl std::error::Error for RequestCanceled {}
463
464impl std::fmt::Display for RequestCanceled {
465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466 f.write_str("Context server request was canceled")
467 }
468}
469
470impl fmt::Display for ContextServerId {
471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 self.0.fmt(f)
473 }
474}
475
476impl fmt::Debug for Client {
477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478 f.debug_struct("Context Server Client")
479 .field("id", &self.server_id.0)
480 .field("name", &self.name)
481 .finish_non_exhaustive()
482 }
483}