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 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}
64
65#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
66#[repr(transparent)]
67pub(crate) struct ContextServerId(pub Arc<str>);
68
69fn is_null_value<T: Serialize>(value: &T) -> bool {
70 if let Ok(Value::Null) = serde_json::to_value(value) {
71 true
72 } else {
73 false
74 }
75}
76
77#[derive(Serialize, Deserialize)]
78pub struct Request<'a, T> {
79 pub jsonrpc: &'static str,
80 pub id: RequestId,
81 pub method: &'a str,
82 #[serde(skip_serializing_if = "is_null_value")]
83 pub params: T,
84}
85
86#[derive(Serialize, Deserialize)]
87pub struct AnyRequest<'a> {
88 pub jsonrpc: &'a str,
89 pub id: RequestId,
90 pub method: &'a str,
91 #[serde(skip_serializing_if = "is_null_value")]
92 pub params: Option<&'a RawValue>,
93}
94
95#[derive(Serialize, Deserialize)]
96struct AnyResponse<'a> {
97 jsonrpc: &'a str,
98 id: RequestId,
99 #[serde(default)]
100 error: Option<Error>,
101 #[serde(borrow)]
102 result: Option<&'a RawValue>,
103}
104
105#[derive(Serialize, Deserialize)]
106#[allow(dead_code)]
107pub(crate) struct Response<T> {
108 pub jsonrpc: &'static str,
109 pub id: RequestId,
110 #[serde(flatten)]
111 pub value: CspResult<T>,
112}
113
114#[derive(Serialize, Deserialize)]
115#[serde(rename_all = "snake_case")]
116pub(crate) enum CspResult<T> {
117 #[serde(rename = "result")]
118 Ok(Option<T>),
119 #[allow(dead_code)]
120 Error(Option<Error>),
121}
122
123#[derive(Serialize, Deserialize)]
124struct Notification<'a, T> {
125 jsonrpc: &'static str,
126 #[serde(borrow)]
127 method: &'a str,
128 params: T,
129}
130
131#[derive(Debug, Clone, Deserialize)]
132struct AnyNotification<'a> {
133 jsonrpc: &'a str,
134 method: String,
135 #[serde(default)]
136 params: Option<Value>,
137}
138
139#[derive(Debug, Serialize, Deserialize)]
140pub(crate) struct Error {
141 pub message: String,
142 pub code: i32,
143}
144
145#[derive(Debug, Clone, Deserialize)]
146pub struct ModelContextServerBinary {
147 pub executable: PathBuf,
148 pub args: Vec<String>,
149 pub env: Option<HashMap<String, String>>,
150}
151
152impl Client {
153 /// Creates a new Client instance for a context server.
154 ///
155 /// This function initializes a new Client by spawning a child process for the context server,
156 /// setting up communication channels, and initializing handlers for input/output operations.
157 /// It takes a server ID, binary information, and an async app context as input.
158 pub fn stdio(
159 server_id: ContextServerId,
160 binary: ModelContextServerBinary,
161 working_directory: &Option<PathBuf>,
162 cx: AsyncApp,
163 ) -> Result<Self> {
164 log::debug!(
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, working_directory, &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 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 })
245 }
246
247 /// Handles input from the server's stdout.
248 ///
249 /// This function continuously reads lines from the provided stdout stream,
250 /// parses them as JSON-RPC responses or notifications, and dispatches them
251 /// to the appropriate handlers. It processes both responses (which are matched
252 /// to pending requests) and notifications (which trigger registered handlers).
253 async fn handle_input(
254 transport: Arc<dyn Transport>,
255 notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
256 request_handlers: Arc<Mutex<HashMap<&'static str, RequestHandler>>>,
257 response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
258 cx: &mut AsyncApp,
259 ) -> anyhow::Result<()> {
260 let mut receiver = transport.receive();
261
262 while let Some(message) = receiver.next().await {
263 log::trace!("recv: {}", &message);
264 if let Ok(request) = serde_json::from_str::<AnyRequest>(&message) {
265 let mut request_handlers = request_handlers.lock();
266 if let Some(handler) = request_handlers.get_mut(request.method) {
267 handler(
268 request.id,
269 request.params.unwrap_or(RawValue::NULL),
270 cx.clone(),
271 );
272 }
273 } else if let Ok(response) = serde_json::from_str::<AnyResponse>(&message) {
274 if let Some(handlers) = response_handlers.lock().as_mut()
275 && let Some(handler) = handlers.remove(&response.id)
276 {
277 handler(Ok(message.to_string()));
278 }
279 } else if let Ok(notification) = serde_json::from_str::<AnyNotification>(&message) {
280 let mut notification_handlers = notification_handlers.lock();
281 if let Some(handler) = notification_handlers.get_mut(notification.method.as_str()) {
282 handler(notification.params.unwrap_or(Value::Null), cx.clone());
283 }
284 } else {
285 log::error!("Unhandled JSON from context_server: {}", message);
286 }
287 }
288
289 smol::future::yield_now().await;
290
291 Ok(())
292 }
293
294 /// Handles the stderr output from the context server.
295 /// Continuously reads and logs any error messages from the server.
296 async fn handle_err(transport: Arc<dyn Transport>) -> anyhow::Result<()> {
297 while let Some(err) = transport.receive_err().next().await {
298 log::debug!("context server stderr: {}", err.trim());
299 }
300
301 Ok(())
302 }
303
304 /// Handles the output to the context server's stdin.
305 /// This function continuously receives messages from the outbound channel,
306 /// writes them to the server's stdin, and manages the lifecycle of response handlers.
307 async fn handle_output(
308 transport: Arc<dyn Transport>,
309 outbound_rx: channel::Receiver<String>,
310 output_done_tx: barrier::Sender,
311 response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
312 ) -> anyhow::Result<()> {
313 let _clear_response_handlers = util::defer({
314 let response_handlers = response_handlers.clone();
315 move || {
316 response_handlers.lock().take();
317 }
318 });
319 while let Ok(message) = outbound_rx.recv().await {
320 log::trace!("outgoing message: {}", message);
321 transport.send(message).await?;
322 }
323 drop(output_done_tx);
324 Ok(())
325 }
326
327 /// Sends a JSON-RPC request to the context server and waits for a response.
328 /// This function handles serialization, deserialization, timeout, and error handling.
329 pub async fn request<T: DeserializeOwned>(
330 &self,
331 method: &str,
332 params: impl Serialize,
333 ) -> Result<T> {
334 self.request_with(method, params, None, Some(REQUEST_TIMEOUT))
335 .await
336 }
337
338 pub async fn request_with<T: DeserializeOwned>(
339 &self,
340 method: &str,
341 params: impl Serialize,
342 cancel_rx: Option<oneshot::Receiver<()>>,
343 timeout: Option<Duration>,
344 ) -> Result<T> {
345 let id = self.next_id.fetch_add(1, SeqCst);
346 let request = serde_json::to_string(&Request {
347 jsonrpc: JSON_RPC_VERSION,
348 id: RequestId::Int(id),
349 method,
350 params,
351 })
352 .unwrap();
353
354 let (tx, rx) = oneshot::channel();
355 let handle_response = self
356 .response_handlers
357 .lock()
358 .as_mut()
359 .context("server shut down")
360 .map(|handlers| {
361 handlers.insert(
362 RequestId::Int(id),
363 Box::new(move |result| {
364 let _ = tx.send(result);
365 }),
366 );
367 });
368
369 let send = self
370 .outbound_tx
371 .try_send(request)
372 .context("failed to write to context server's stdin");
373
374 let executor = self.executor.clone();
375 let started = Instant::now();
376 handle_response?;
377 send?;
378
379 let mut timeout_fut = pin!(
380 match timeout {
381 Some(timeout) => future::Either::Left(executor.timer(timeout)),
382 None => future::Either::Right(future::pending()),
383 }
384 .fuse()
385 );
386 let mut cancel_fut = pin!(
387 match cancel_rx {
388 Some(rx) => future::Either::Left(async {
389 rx.await.log_err();
390 }),
391 None => future::Either::Right(future::pending()),
392 }
393 .fuse()
394 );
395
396 select! {
397 response = rx.fuse() => {
398 let elapsed = started.elapsed();
399 log::trace!("took {elapsed:?} to receive response to {method:?} id {id}");
400 match response? {
401 Ok(response) => {
402 let parsed: AnyResponse = serde_json::from_str(&response)?;
403 if let Some(error) = parsed.error {
404 Err(anyhow!(error.message))
405 } else if let Some(result) = parsed.result {
406 Ok(serde_json::from_str(result.get())?)
407 } else {
408 anyhow::bail!("Invalid response: no result or error");
409 }
410 }
411 Err(_) => anyhow::bail!("cancelled")
412 }
413 }
414 _ = cancel_fut => {
415 self.notify(
416 Cancelled::METHOD,
417 ClientNotification::Cancelled(CancelledParams {
418 request_id: RequestId::Int(id),
419 reason: None
420 })
421 ).log_err();
422 anyhow::bail!(RequestCanceled)
423 }
424 _ = timeout_fut => {
425 log::error!("cancelled csp request task for {method:?} id {id} which took over {:?}", timeout.unwrap());
426 anyhow::bail!("Context server request timeout");
427 }
428 }
429 }
430
431 /// Sends a notification to the context server without expecting a response.
432 /// This function serializes the notification and sends it through the outbound channel.
433 pub fn notify(&self, method: &str, params: impl Serialize) -> Result<()> {
434 let notification = serde_json::to_string(&Notification {
435 jsonrpc: JSON_RPC_VERSION,
436 method,
437 params,
438 })
439 .unwrap();
440 self.outbound_tx.try_send(notification)?;
441 Ok(())
442 }
443
444 pub fn on_notification(
445 &self,
446 method: &'static str,
447 f: Box<dyn 'static + Send + FnMut(Value, AsyncApp)>,
448 ) {
449 self.notification_handlers.lock().insert(method, f);
450 }
451}
452
453#[derive(Debug)]
454pub struct RequestCanceled;
455
456impl std::error::Error for RequestCanceled {}
457
458impl std::fmt::Display for RequestCanceled {
459 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460 f.write_str("Context server request was canceled")
461 }
462}
463
464impl fmt::Display for ContextServerId {
465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466 self.0.fmt(f)
467 }
468}
469
470impl fmt::Debug for Client {
471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 f.debug_struct("Context Server Client")
473 .field("id", &self.server_id.0)
474 .field("name", &self.name)
475 .finish_non_exhaustive()
476 }
477}