1use std::{
2 path::PathBuf,
3 sync::{Arc, Mutex},
4 time::Duration,
5};
6
7use anyhow::{Context as _, Result};
8use context_server::{ContextServerCommand, ContextServerId};
9use editor::{Editor, EditorElement, EditorStyle};
10use gpui::{
11 Animation, AnimationExt as _, AsyncWindowContext, DismissEvent, Entity, EventEmitter,
12 FocusHandle, Focusable, Task, TextStyle, TextStyleRefinement, Transformation, UnderlineStyle,
13 WeakEntity, percentage, prelude::*,
14};
15use language::{Language, LanguageRegistry};
16use markdown::{Markdown, MarkdownElement, MarkdownStyle};
17use notifications::status_toast::{StatusToast, ToastIcon};
18use project::{
19 context_server_store::{
20 ContextServerStatus, ContextServerStore, registry::ContextServerDescriptorRegistry,
21 },
22 project_settings::{ContextServerSettings, ProjectSettings},
23 worktree_store::WorktreeStore,
24};
25use settings::{Settings as _, update_settings_file};
26use theme::ThemeSettings;
27use ui::{KeyBinding, Modal, ModalFooter, ModalHeader, Section, Tooltip, prelude::*};
28use util::ResultExt as _;
29use workspace::{ModalView, Workspace};
30
31use crate::AddContextServer;
32
33enum ConfigurationTarget {
34 New,
35 Existing {
36 id: ContextServerId,
37 command: ContextServerCommand,
38 },
39 Extension {
40 id: ContextServerId,
41 repository_url: Option<SharedString>,
42 installation: Option<extension::ContextServerConfiguration>,
43 },
44}
45
46enum ConfigurationSource {
47 New {
48 editor: Entity<Editor>,
49 },
50 Existing {
51 editor: Entity<Editor>,
52 },
53 Extension {
54 id: ContextServerId,
55 editor: Option<Entity<Editor>>,
56 repository_url: Option<SharedString>,
57 installation_instructions: Option<Entity<markdown::Markdown>>,
58 settings_validator: Option<jsonschema::Validator>,
59 },
60}
61
62impl ConfigurationSource {
63 fn has_configuration_options(&self) -> bool {
64 !matches!(self, ConfigurationSource::Extension { editor: None, .. })
65 }
66
67 fn is_new(&self) -> bool {
68 matches!(self, ConfigurationSource::New { .. })
69 }
70
71 fn from_target(
72 target: ConfigurationTarget,
73 language_registry: Arc<LanguageRegistry>,
74 jsonc_language: Option<Arc<Language>>,
75 window: &mut Window,
76 cx: &mut App,
77 ) -> Self {
78 fn create_editor(
79 json: String,
80 jsonc_language: Option<Arc<Language>>,
81 window: &mut Window,
82 cx: &mut App,
83 ) -> Entity<Editor> {
84 cx.new(|cx| {
85 let mut editor = Editor::auto_height(4, 16, window, cx);
86 editor.set_text(json, window, cx);
87 editor.set_show_gutter(false, cx);
88 editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
89 if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
90 buffer.update(cx, |buffer, cx| buffer.set_language(jsonc_language, cx))
91 }
92 editor
93 })
94 }
95
96 match target {
97 ConfigurationTarget::New => ConfigurationSource::New {
98 editor: create_editor(context_server_input(None), jsonc_language, window, cx),
99 },
100 ConfigurationTarget::Existing { id, command } => ConfigurationSource::Existing {
101 editor: create_editor(
102 context_server_input(Some((id, command))),
103 jsonc_language,
104 window,
105 cx,
106 ),
107 },
108 ConfigurationTarget::Extension {
109 id,
110 repository_url,
111 installation,
112 } => {
113 let settings_validator = installation.as_ref().and_then(|installation| {
114 jsonschema::validator_for(&installation.settings_schema)
115 .context("Failed to load JSON schema for context server settings")
116 .log_err()
117 });
118 let installation_instructions = installation.as_ref().map(|installation| {
119 cx.new(|cx| {
120 Markdown::new(
121 installation.installation_instructions.clone().into(),
122 Some(language_registry.clone()),
123 None,
124 cx,
125 )
126 })
127 });
128 ConfigurationSource::Extension {
129 id,
130 repository_url,
131 installation_instructions,
132 settings_validator,
133 editor: installation.map(|installation| {
134 create_editor(installation.default_settings, jsonc_language, window, cx)
135 }),
136 }
137 }
138 }
139 }
140
141 fn output(&self, cx: &mut App) -> Result<(ContextServerId, ContextServerSettings)> {
142 match self {
143 ConfigurationSource::New { editor } | ConfigurationSource::Existing { editor } => {
144 parse_input(&editor.read(cx).text(cx)).map(|(id, command)| {
145 (
146 id,
147 ContextServerSettings::Custom {
148 enabled: true,
149 command,
150 },
151 )
152 })
153 }
154 ConfigurationSource::Extension {
155 id,
156 editor,
157 settings_validator,
158 ..
159 } => {
160 let text = editor
161 .as_ref()
162 .context("No output available")?
163 .read(cx)
164 .text(cx);
165 let settings = serde_json_lenient::from_str::<serde_json::Value>(&text)?;
166 if let Some(settings_validator) = settings_validator
167 && let Err(error) = settings_validator.validate(&settings)
168 {
169 return Err(anyhow::anyhow!(error.to_string()));
170 }
171 Ok((
172 id.clone(),
173 ContextServerSettings::Extension {
174 enabled: true,
175 settings,
176 },
177 ))
178 }
179 }
180 }
181}
182
183fn context_server_input(existing: Option<(ContextServerId, ContextServerCommand)>) -> String {
184 let (name, command, args, env) = match existing {
185 Some((id, cmd)) => {
186 let args = serde_json::to_string(&cmd.args).unwrap();
187 let env = serde_json::to_string(&cmd.env.unwrap_or_default()).unwrap();
188 (id.0.to_string(), cmd.path, args, env)
189 }
190 None => (
191 "some-mcp-server".to_string(),
192 PathBuf::new(),
193 "[]".to_string(),
194 "{}".to_string(),
195 ),
196 };
197
198 format!(
199 r#"{{
200 /// The name of your MCP server
201 "{name}": {{
202 /// The command which runs the MCP server
203 "command": "{}",
204 /// The arguments to pass to the MCP server
205 "args": {args},
206 /// The environment variables to set
207 "env": {env}
208 }}
209}}"#,
210 command.display()
211 )
212}
213
214fn resolve_context_server_extension(
215 id: ContextServerId,
216 worktree_store: Entity<WorktreeStore>,
217 cx: &mut App,
218) -> Task<Option<ConfigurationTarget>> {
219 let registry = ContextServerDescriptorRegistry::default_global(cx).read(cx);
220
221 let Some(descriptor) = registry.context_server_descriptor(&id.0) else {
222 return Task::ready(None);
223 };
224
225 let extension = crate::agent_configuration::resolve_extension_for_context_server(&id, cx);
226 cx.spawn(async move |cx| {
227 let installation = descriptor
228 .configuration(worktree_store, cx)
229 .await
230 .context("Failed to resolve context server configuration")
231 .log_err()
232 .flatten();
233
234 Some(ConfigurationTarget::Extension {
235 id,
236 repository_url: extension
237 .and_then(|(_, manifest)| manifest.repository.clone().map(SharedString::from)),
238 installation,
239 })
240 })
241}
242
243enum State {
244 Idle,
245 Waiting,
246 Error(SharedString),
247}
248
249pub struct ConfigureContextServerModal {
250 context_server_store: Entity<ContextServerStore>,
251 workspace: WeakEntity<Workspace>,
252 source: ConfigurationSource,
253 state: State,
254}
255
256impl ConfigureContextServerModal {
257 pub fn register(
258 workspace: &mut Workspace,
259 language_registry: Arc<LanguageRegistry>,
260 _window: Option<&mut Window>,
261 _cx: &mut Context<Workspace>,
262 ) {
263 workspace.register_action({
264 move |_workspace, _: &AddContextServer, window, cx| {
265 let workspace_handle = cx.weak_entity();
266 let language_registry = language_registry.clone();
267 window
268 .spawn(cx, async move |cx| {
269 Self::show_modal(
270 ConfigurationTarget::New,
271 language_registry,
272 workspace_handle,
273 cx,
274 )
275 .await
276 })
277 .detach_and_log_err(cx);
278 }
279 });
280 }
281
282 pub fn show_modal_for_existing_server(
283 server_id: ContextServerId,
284 language_registry: Arc<LanguageRegistry>,
285 workspace: WeakEntity<Workspace>,
286 window: &mut Window,
287 cx: &mut App,
288 ) -> Task<Result<()>> {
289 let Some(settings) = ProjectSettings::get_global(cx)
290 .context_servers
291 .get(&server_id.0)
292 .cloned()
293 .or_else(|| {
294 ContextServerDescriptorRegistry::default_global(cx)
295 .read(cx)
296 .context_server_descriptor(&server_id.0)
297 .map(|_| ContextServerSettings::default_extension())
298 })
299 else {
300 return Task::ready(Err(anyhow::anyhow!("Context server not found")));
301 };
302
303 window.spawn(cx, async move |cx| {
304 let target = match settings {
305 ContextServerSettings::Custom {
306 enabled: _,
307 command,
308 } => Some(ConfigurationTarget::Existing {
309 id: server_id,
310 command,
311 }),
312 ContextServerSettings::Extension { .. } => {
313 match workspace
314 .update(cx, |workspace, cx| {
315 resolve_context_server_extension(
316 server_id,
317 workspace.project().read(cx).worktree_store(),
318 cx,
319 )
320 })
321 .ok()
322 {
323 Some(task) => task.await,
324 None => None,
325 }
326 }
327 };
328
329 match target {
330 Some(target) => Self::show_modal(target, language_registry, workspace, cx).await,
331 None => Err(anyhow::anyhow!("Failed to resolve context server")),
332 }
333 })
334 }
335
336 fn show_modal(
337 target: ConfigurationTarget,
338 language_registry: Arc<LanguageRegistry>,
339 workspace: WeakEntity<Workspace>,
340 cx: &mut AsyncWindowContext,
341 ) -> Task<Result<()>> {
342 cx.spawn(async move |cx| {
343 let jsonc_language = language_registry.language_for_name("jsonc").await.ok();
344 workspace.update_in(cx, |workspace, window, cx| {
345 let workspace_handle = cx.weak_entity();
346 let context_server_store = workspace.project().read(cx).context_server_store();
347 workspace.toggle_modal(window, cx, |window, cx| Self {
348 context_server_store,
349 workspace: workspace_handle,
350 state: State::Idle,
351 source: ConfigurationSource::from_target(
352 target,
353 language_registry,
354 jsonc_language,
355 window,
356 cx,
357 ),
358 })
359 })
360 })
361 }
362
363 fn set_error(&mut self, err: impl Into<SharedString>, cx: &mut Context<Self>) {
364 self.state = State::Error(err.into());
365 cx.notify();
366 }
367
368 fn confirm(&mut self, _: &menu::Confirm, cx: &mut Context<Self>) {
369 self.state = State::Idle;
370 let Some(workspace) = self.workspace.upgrade() else {
371 return;
372 };
373
374 let (id, settings) = match self.source.output(cx) {
375 Ok(val) => val,
376 Err(error) => {
377 self.set_error(error.to_string(), cx);
378 return;
379 }
380 };
381
382 self.state = State::Waiting;
383
384 let existing_server = self.context_server_store.read(cx).get_running_server(&id);
385 if existing_server.is_some() {
386 self.context_server_store.update(cx, |store, cx| {
387 store.stop_server(&id, cx).log_err();
388 });
389 }
390
391 let wait_for_context_server_task =
392 wait_for_context_server(&self.context_server_store, id.clone(), cx);
393 cx.spawn({
394 let id = id.clone();
395 async move |this, cx| {
396 let result = wait_for_context_server_task.await;
397 this.update(cx, |this, cx| match result {
398 Ok(_) => {
399 this.state = State::Idle;
400 this.show_configured_context_server_toast(id, cx);
401 cx.emit(DismissEvent);
402 }
403 Err(err) => {
404 this.set_error(err, cx);
405 }
406 })
407 }
408 })
409 .detach();
410
411 let settings_changed =
412 ProjectSettings::get_global(cx).context_servers.get(&id.0) != Some(&settings);
413
414 if settings_changed {
415 // When we write the settings to the file, the context server will be restarted.
416 workspace.update(cx, |workspace, cx| {
417 let fs = workspace.app_state().fs.clone();
418 update_settings_file::<ProjectSettings>(fs.clone(), cx, |project_settings, _| {
419 project_settings.context_servers.insert(id.0, settings);
420 });
421 });
422 } else if let Some(existing_server) = existing_server {
423 self.context_server_store
424 .update(cx, |store, cx| store.start_server(existing_server, cx));
425 }
426 }
427
428 fn cancel(&mut self, _: &menu::Cancel, cx: &mut Context<Self>) {
429 cx.emit(DismissEvent);
430 }
431
432 fn show_configured_context_server_toast(&self, id: ContextServerId, cx: &mut App) {
433 self.workspace
434 .update(cx, {
435 |workspace, cx| {
436 let status_toast = StatusToast::new(
437 format!("{} configured successfully.", id.0),
438 cx,
439 |this, _cx| {
440 this.icon(ToastIcon::new(IconName::ToolHammer).color(Color::Muted))
441 .action("Dismiss", |_, _| {})
442 },
443 );
444
445 workspace.toggle_status_toast(status_toast, cx);
446 }
447 })
448 .log_err();
449 }
450}
451
452fn parse_input(text: &str) -> Result<(ContextServerId, ContextServerCommand)> {
453 let value: serde_json::Value = serde_json_lenient::from_str(text)?;
454 let object = value.as_object().context("Expected object")?;
455 anyhow::ensure!(object.len() == 1, "Expected exactly one key-value pair");
456 let (context_server_name, value) = object.into_iter().next().unwrap();
457 let command: ContextServerCommand = serde_json::from_value(value.clone())?;
458 Ok((ContextServerId(context_server_name.clone().into()), command))
459}
460
461impl ModalView for ConfigureContextServerModal {}
462
463impl Focusable for ConfigureContextServerModal {
464 fn focus_handle(&self, cx: &App) -> FocusHandle {
465 match &self.source {
466 ConfigurationSource::New { editor } => editor.focus_handle(cx),
467 ConfigurationSource::Existing { editor, .. } => editor.focus_handle(cx),
468 ConfigurationSource::Extension { editor, .. } => editor
469 .as_ref()
470 .map(|editor| editor.focus_handle(cx))
471 .unwrap_or_else(|| cx.focus_handle()),
472 }
473 }
474}
475
476impl EventEmitter<DismissEvent> for ConfigureContextServerModal {}
477
478impl ConfigureContextServerModal {
479 fn render_modal_header(&self) -> ModalHeader {
480 let text: SharedString = match &self.source {
481 ConfigurationSource::New { .. } => "Add MCP Server".into(),
482 ConfigurationSource::Existing { .. } => "Configure MCP Server".into(),
483 ConfigurationSource::Extension { id, .. } => format!("Configure {}", id.0).into(),
484 };
485 ModalHeader::new().headline(text)
486 }
487
488 fn render_modal_description(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
489 const MODAL_DESCRIPTION: &str = "Visit the MCP server configuration docs to find all necessary arguments and environment variables.";
490
491 if let ConfigurationSource::Extension {
492 installation_instructions: Some(installation_instructions),
493 ..
494 } = &self.source
495 {
496 div()
497 .pb_2()
498 .text_sm()
499 .child(MarkdownElement::new(
500 installation_instructions.clone(),
501 default_markdown_style(window, cx),
502 ))
503 .into_any_element()
504 } else {
505 Label::new(MODAL_DESCRIPTION)
506 .color(Color::Muted)
507 .into_any_element()
508 }
509 }
510
511 fn render_modal_content(&self, cx: &App) -> AnyElement {
512 let editor = match &self.source {
513 ConfigurationSource::New { editor } => editor,
514 ConfigurationSource::Existing { editor } => editor,
515 ConfigurationSource::Extension { editor, .. } => {
516 let Some(editor) = editor else {
517 return div().into_any_element();
518 };
519 editor
520 }
521 };
522
523 div()
524 .p_2()
525 .rounded_md()
526 .border_1()
527 .border_color(cx.theme().colors().border_variant)
528 .bg(cx.theme().colors().editor_background)
529 .child({
530 let settings = ThemeSettings::get_global(cx);
531 let text_style = TextStyle {
532 color: cx.theme().colors().text,
533 font_family: settings.buffer_font.family.clone(),
534 font_fallbacks: settings.buffer_font.fallbacks.clone(),
535 font_size: settings.buffer_font_size(cx).into(),
536 font_weight: settings.buffer_font.weight,
537 line_height: relative(settings.buffer_line_height.value()),
538 ..Default::default()
539 };
540 EditorElement::new(
541 editor,
542 EditorStyle {
543 background: cx.theme().colors().editor_background,
544 local_player: cx.theme().players().local(),
545 text: text_style,
546 syntax: cx.theme().syntax().clone(),
547 ..Default::default()
548 },
549 )
550 })
551 .into_any_element()
552 }
553
554 fn render_modal_footer(&self, window: &mut Window, cx: &mut Context<Self>) -> ModalFooter {
555 let focus_handle = self.focus_handle(cx);
556 let is_connecting = matches!(self.state, State::Waiting);
557
558 ModalFooter::new()
559 .start_slot::<Button>(
560 if let ConfigurationSource::Extension {
561 repository_url: Some(repository_url),
562 ..
563 } = &self.source
564 {
565 Some(
566 Button::new("open-repository", "Open Repository")
567 .icon(IconName::ArrowUpRight)
568 .icon_color(Color::Muted)
569 .icon_size(IconSize::Small)
570 .tooltip({
571 let repository_url = repository_url.clone();
572 move |window, cx| {
573 Tooltip::with_meta(
574 "Open Repository",
575 None,
576 repository_url.clone(),
577 window,
578 cx,
579 )
580 }
581 })
582 .on_click({
583 let repository_url = repository_url.clone();
584 move |_, _, cx| cx.open_url(&repository_url)
585 }),
586 )
587 } else {
588 None
589 },
590 )
591 .end_slot(
592 h_flex()
593 .gap_2()
594 .child(
595 Button::new(
596 "cancel",
597 if self.source.has_configuration_options() {
598 "Cancel"
599 } else {
600 "Dismiss"
601 },
602 )
603 .key_binding(
604 KeyBinding::for_action_in(&menu::Cancel, &focus_handle, window, cx)
605 .map(|kb| kb.size(rems_from_px(12.))),
606 )
607 .on_click(
608 cx.listener(|this, _event, _window, cx| this.cancel(&menu::Cancel, cx)),
609 ),
610 )
611 .children(self.source.has_configuration_options().then(|| {
612 Button::new(
613 "add-server",
614 if self.source.is_new() {
615 "Add Server"
616 } else {
617 "Configure Server"
618 },
619 )
620 .disabled(is_connecting)
621 .key_binding(
622 KeyBinding::for_action_in(&menu::Confirm, &focus_handle, window, cx)
623 .map(|kb| kb.size(rems_from_px(12.))),
624 )
625 .on_click(
626 cx.listener(|this, _event, _window, cx| {
627 this.confirm(&menu::Confirm, cx)
628 }),
629 )
630 })),
631 )
632 }
633
634 fn render_waiting_for_context_server() -> Div {
635 h_flex()
636 .gap_2()
637 .child(
638 Icon::new(IconName::ArrowCircle)
639 .size(IconSize::XSmall)
640 .color(Color::Info)
641 .with_animation(
642 "arrow-circle",
643 Animation::new(Duration::from_secs(2)).repeat(),
644 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
645 )
646 .into_any_element(),
647 )
648 .child(
649 Label::new("Waiting for Context Server")
650 .size(LabelSize::Small)
651 .color(Color::Muted),
652 )
653 }
654
655 fn render_modal_error(error: SharedString) -> Div {
656 h_flex()
657 .gap_2()
658 .child(
659 Icon::new(IconName::Warning)
660 .size(IconSize::XSmall)
661 .color(Color::Warning),
662 )
663 .child(
664 div()
665 .w_full()
666 .child(Label::new(error).size(LabelSize::Small).color(Color::Muted)),
667 )
668 }
669}
670
671impl Render for ConfigureContextServerModal {
672 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
673 div()
674 .elevation_3(cx)
675 .w(rems(34.))
676 .key_context("ConfigureContextServerModal")
677 .on_action(
678 cx.listener(|this, _: &menu::Cancel, _window, cx| this.cancel(&menu::Cancel, cx)),
679 )
680 .on_action(
681 cx.listener(|this, _: &menu::Confirm, _window, cx| {
682 this.confirm(&menu::Confirm, cx)
683 }),
684 )
685 .capture_any_mouse_down(cx.listener(|this, _, window, cx| {
686 this.focus_handle(cx).focus(window);
687 }))
688 .child(
689 Modal::new("configure-context-server", None)
690 .header(self.render_modal_header())
691 .section(
692 Section::new()
693 .child(self.render_modal_description(window, cx))
694 .child(self.render_modal_content(cx))
695 .child(match &self.state {
696 State::Idle => div(),
697 State::Waiting => Self::render_waiting_for_context_server(),
698 State::Error(error) => Self::render_modal_error(error.clone()),
699 }),
700 )
701 .footer(self.render_modal_footer(window, cx)),
702 )
703 }
704}
705
706fn wait_for_context_server(
707 context_server_store: &Entity<ContextServerStore>,
708 context_server_id: ContextServerId,
709 cx: &mut App,
710) -> Task<Result<(), Arc<str>>> {
711 let (tx, rx) = futures::channel::oneshot::channel();
712 let tx = Arc::new(Mutex::new(Some(tx)));
713
714 let subscription = cx.subscribe(context_server_store, move |_, event, _cx| match event {
715 project::context_server_store::Event::ServerStatusChanged { server_id, status } => {
716 match status {
717 ContextServerStatus::Running => {
718 if server_id == &context_server_id
719 && let Some(tx) = tx.lock().unwrap().take()
720 {
721 let _ = tx.send(Ok(()));
722 }
723 }
724 ContextServerStatus::Stopped => {
725 if server_id == &context_server_id
726 && let Some(tx) = tx.lock().unwrap().take()
727 {
728 let _ = tx.send(Err("Context server stopped running".into()));
729 }
730 }
731 ContextServerStatus::Error(error) => {
732 if server_id == &context_server_id
733 && let Some(tx) = tx.lock().unwrap().take()
734 {
735 let _ = tx.send(Err(error.clone()));
736 }
737 }
738 _ => {}
739 }
740 }
741 });
742
743 cx.spawn(async move |_cx| {
744 let result = rx
745 .await
746 .map_err(|_| Arc::from("Context server store was dropped"))?;
747 drop(subscription);
748 result
749 })
750}
751
752pub(crate) fn default_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
753 let theme_settings = ThemeSettings::get_global(cx);
754 let colors = cx.theme().colors();
755 let mut text_style = window.text_style();
756 text_style.refine(&TextStyleRefinement {
757 font_family: Some(theme_settings.ui_font.family.clone()),
758 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
759 font_features: Some(theme_settings.ui_font.features.clone()),
760 font_size: Some(TextSize::XSmall.rems(cx).into()),
761 color: Some(colors.text_muted),
762 ..Default::default()
763 });
764
765 MarkdownStyle {
766 base_text_style: text_style.clone(),
767 selection_background_color: colors.element_selection_background,
768 link: TextStyleRefinement {
769 background_color: Some(colors.editor_foreground.opacity(0.025)),
770 underline: Some(UnderlineStyle {
771 color: Some(colors.text_accent.opacity(0.5)),
772 thickness: px(1.),
773 ..Default::default()
774 }),
775 ..Default::default()
776 },
777 ..Default::default()
778 }
779}