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