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 if let Err(error) = settings_validator.validate(&settings) {
168 return Err(anyhow::anyhow!(error.to_string()));
169 }
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 let language_registry = language_registry.clone();
265 move |_workspace, _: &AddContextServer, window, cx| {
266 let workspace_handle = cx.weak_entity();
267 let language_registry = language_registry.clone();
268 window
269 .spawn(cx, async move |cx| {
270 Self::show_modal(
271 ConfigurationTarget::New,
272 language_registry,
273 workspace_handle,
274 cx,
275 )
276 .await
277 })
278 .detach_and_log_err(cx);
279 }
280 });
281 }
282
283 pub fn show_modal_for_existing_server(
284 server_id: ContextServerId,
285 language_registry: Arc<LanguageRegistry>,
286 workspace: WeakEntity<Workspace>,
287 window: &mut Window,
288 cx: &mut App,
289 ) -> Task<Result<()>> {
290 let Some(settings) = ProjectSettings::get_global(cx)
291 .context_servers
292 .get(&server_id.0)
293 .cloned()
294 .or_else(|| {
295 ContextServerDescriptorRegistry::default_global(cx)
296 .read(cx)
297 .context_server_descriptor(&server_id.0)
298 .map(|_| ContextServerSettings::default_extension())
299 })
300 else {
301 return Task::ready(Err(anyhow::anyhow!("Context server not found")));
302 };
303
304 window.spawn(cx, async move |cx| {
305 let target = match settings {
306 ContextServerSettings::Custom {
307 enabled: _,
308 command,
309 } => Some(ConfigurationTarget::Existing {
310 id: server_id,
311 command,
312 }),
313 ContextServerSettings::Extension { .. } => {
314 match workspace
315 .update(cx, |workspace, cx| {
316 resolve_context_server_extension(
317 server_id,
318 workspace.project().read(cx).worktree_store(),
319 cx,
320 )
321 })
322 .ok()
323 {
324 Some(task) => task.await,
325 None => None,
326 }
327 }
328 };
329
330 match target {
331 Some(target) => Self::show_modal(target, language_registry, workspace, cx).await,
332 None => Err(anyhow::anyhow!("Failed to resolve context server")),
333 }
334 })
335 }
336
337 fn show_modal(
338 target: ConfigurationTarget,
339 language_registry: Arc<LanguageRegistry>,
340 workspace: WeakEntity<Workspace>,
341 cx: &mut AsyncWindowContext,
342 ) -> Task<Result<()>> {
343 cx.spawn(async move |cx| {
344 let jsonc_language = language_registry.language_for_name("jsonc").await.ok();
345 workspace.update_in(cx, |workspace, window, cx| {
346 let workspace_handle = cx.weak_entity();
347 let context_server_store = workspace.project().read(cx).context_server_store();
348 workspace.toggle_modal(window, cx, |window, cx| Self {
349 context_server_store,
350 workspace: workspace_handle,
351 state: State::Idle,
352 source: ConfigurationSource::from_target(
353 target,
354 language_registry,
355 jsonc_language,
356 window,
357 cx,
358 ),
359 })
360 })
361 })
362 }
363
364 fn set_error(&mut self, err: impl Into<SharedString>, cx: &mut Context<Self>) {
365 self.state = State::Error(err.into());
366 cx.notify();
367 }
368
369 fn confirm(&mut self, _: &menu::Confirm, cx: &mut Context<Self>) {
370 self.state = State::Idle;
371 let Some(workspace) = self.workspace.upgrade() else {
372 return;
373 };
374
375 let (id, settings) = match self.source.output(cx) {
376 Ok(val) => val,
377 Err(error) => {
378 self.set_error(error.to_string(), cx);
379 return;
380 }
381 };
382
383 self.state = State::Waiting;
384
385 let existing_server = self.context_server_store.read(cx).get_running_server(&id);
386 if existing_server.is_some() {
387 self.context_server_store.update(cx, |store, cx| {
388 store.stop_server(&id, cx).log_err();
389 });
390 }
391
392 let wait_for_context_server_task =
393 wait_for_context_server(&self.context_server_store, id.clone(), cx);
394 cx.spawn({
395 let id = id.clone();
396 async move |this, cx| {
397 let result = wait_for_context_server_task.await;
398 this.update(cx, |this, cx| match result {
399 Ok(_) => {
400 this.state = State::Idle;
401 this.show_configured_context_server_toast(id, cx);
402 cx.emit(DismissEvent);
403 }
404 Err(err) => {
405 this.set_error(err, cx);
406 }
407 })
408 }
409 })
410 .detach();
411
412 let settings_changed =
413 ProjectSettings::get_global(cx).context_servers.get(&id.0) != Some(&settings);
414
415 if settings_changed {
416 // When we write the settings to the file, the context server will be restarted.
417 workspace.update(cx, |workspace, cx| {
418 let fs = workspace.app_state().fs.clone();
419 update_settings_file::<ProjectSettings>(fs.clone(), cx, |project_settings, _| {
420 project_settings.context_servers.insert(id.0, settings);
421 });
422 });
423 } else if let Some(existing_server) = existing_server {
424 self.context_server_store
425 .update(cx, |store, cx| store.start_server(existing_server, cx));
426 }
427 }
428
429 fn cancel(&mut self, _: &menu::Cancel, cx: &mut Context<Self>) {
430 cx.emit(DismissEvent);
431 }
432
433 fn show_configured_context_server_toast(&self, id: ContextServerId, cx: &mut App) {
434 self.workspace
435 .update(cx, {
436 |workspace, cx| {
437 let status_toast = StatusToast::new(
438 format!("{} configured successfully.", id.0),
439 cx,
440 |this, _cx| {
441 this.icon(ToastIcon::new(IconName::ToolHammer).color(Color::Muted))
442 .action("Dismiss", |_, _| {})
443 },
444 );
445
446 workspace.toggle_status_toast(status_toast, cx);
447 }
448 })
449 .log_err();
450 }
451}
452
453fn parse_input(text: &str) -> Result<(ContextServerId, ContextServerCommand)> {
454 let value: serde_json::Value = serde_json_lenient::from_str(text)?;
455 let object = value.as_object().context("Expected object")?;
456 anyhow::ensure!(object.len() == 1, "Expected exactly one key-value pair");
457 let (context_server_name, value) = object.into_iter().next().unwrap();
458 let command: ContextServerCommand = serde_json::from_value(value.clone())?;
459 Ok((ContextServerId(context_server_name.clone().into()), command))
460}
461
462impl ModalView for ConfigureContextServerModal {}
463
464impl Focusable for ConfigureContextServerModal {
465 fn focus_handle(&self, cx: &App) -> FocusHandle {
466 match &self.source {
467 ConfigurationSource::New { editor } => editor.focus_handle(cx),
468 ConfigurationSource::Existing { editor, .. } => editor.focus_handle(cx),
469 ConfigurationSource::Extension { editor, .. } => editor
470 .as_ref()
471 .map(|editor| editor.focus_handle(cx))
472 .unwrap_or_else(|| cx.focus_handle()),
473 }
474 }
475}
476
477impl EventEmitter<DismissEvent> for ConfigureContextServerModal {}
478
479impl ConfigureContextServerModal {
480 fn render_modal_header(&self) -> ModalHeader {
481 let text: SharedString = match &self.source {
482 ConfigurationSource::New { .. } => "Add MCP Server".into(),
483 ConfigurationSource::Existing { .. } => "Configure MCP Server".into(),
484 ConfigurationSource::Extension { id, .. } => format!("Configure {}", id.0).into(),
485 };
486 ModalHeader::new().headline(text)
487 }
488
489 fn render_modal_description(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
490 const MODAL_DESCRIPTION: &'static str = "Visit the MCP server configuration docs to find all necessary arguments and environment variables.";
491
492 if let ConfigurationSource::Extension {
493 installation_instructions: Some(installation_instructions),
494 ..
495 } = &self.source
496 {
497 div()
498 .pb_2()
499 .text_sm()
500 .child(MarkdownElement::new(
501 installation_instructions.clone(),
502 default_markdown_style(window, cx),
503 ))
504 .into_any_element()
505 } else {
506 Label::new(MODAL_DESCRIPTION)
507 .color(Color::Muted)
508 .into_any_element()
509 }
510 }
511
512 fn render_modal_content(&self, cx: &App) -> AnyElement {
513 let editor = match &self.source {
514 ConfigurationSource::New { editor } => editor,
515 ConfigurationSource::Existing { editor } => editor,
516 ConfigurationSource::Extension { editor, .. } => {
517 let Some(editor) = editor else {
518 return div().into_any_element();
519 };
520 editor
521 }
522 };
523
524 div()
525 .p_2()
526 .rounded_md()
527 .border_1()
528 .border_color(cx.theme().colors().border_variant)
529 .bg(cx.theme().colors().editor_background)
530 .child({
531 let settings = ThemeSettings::get_global(cx);
532 let text_style = TextStyle {
533 color: cx.theme().colors().text,
534 font_family: settings.buffer_font.family.clone(),
535 font_fallbacks: settings.buffer_font.fallbacks.clone(),
536 font_size: settings.buffer_font_size(cx).into(),
537 font_weight: settings.buffer_font.weight,
538 line_height: relative(settings.buffer_line_height.value()),
539 ..Default::default()
540 };
541 EditorElement::new(
542 editor,
543 EditorStyle {
544 background: cx.theme().colors().editor_background,
545 local_player: cx.theme().players().local(),
546 text: text_style,
547 syntax: cx.theme().syntax().clone(),
548 ..Default::default()
549 },
550 )
551 })
552 .into_any_element()
553 }
554
555 fn render_modal_footer(&self, window: &mut Window, cx: &mut Context<Self>) -> ModalFooter {
556 let focus_handle = self.focus_handle(cx);
557 let is_connecting = matches!(self.state, State::Waiting);
558
559 ModalFooter::new()
560 .start_slot::<Button>(
561 if let ConfigurationSource::Extension {
562 repository_url: Some(repository_url),
563 ..
564 } = &self.source
565 {
566 Some(
567 Button::new("open-repository", "Open Repository")
568 .icon(IconName::ArrowUpRight)
569 .icon_color(Color::Muted)
570 .icon_size(IconSize::Small)
571 .tooltip({
572 let repository_url = repository_url.clone();
573 move |window, cx| {
574 Tooltip::with_meta(
575 "Open Repository",
576 None,
577 repository_url.clone(),
578 window,
579 cx,
580 )
581 }
582 })
583 .on_click({
584 let repository_url = repository_url.clone();
585 move |_, _, cx| cx.open_url(&repository_url)
586 }),
587 )
588 } else {
589 None
590 },
591 )
592 .end_slot(
593 h_flex()
594 .gap_2()
595 .child(
596 Button::new(
597 "cancel",
598 if self.source.has_configuration_options() {
599 "Cancel"
600 } else {
601 "Dismiss"
602 },
603 )
604 .key_binding(
605 KeyBinding::for_action_in(&menu::Cancel, &focus_handle, window, cx)
606 .map(|kb| kb.size(rems_from_px(12.))),
607 )
608 .on_click(
609 cx.listener(|this, _event, _window, cx| this.cancel(&menu::Cancel, cx)),
610 ),
611 )
612 .children(self.source.has_configuration_options().then(|| {
613 Button::new(
614 "add-server",
615 if self.source.is_new() {
616 "Add Server"
617 } else {
618 "Configure Server"
619 },
620 )
621 .disabled(is_connecting)
622 .key_binding(
623 KeyBinding::for_action_in(&menu::Confirm, &focus_handle, window, cx)
624 .map(|kb| kb.size(rems_from_px(12.))),
625 )
626 .on_click(
627 cx.listener(|this, _event, _window, cx| {
628 this.confirm(&menu::Confirm, cx)
629 }),
630 )
631 })),
632 )
633 }
634
635 fn render_waiting_for_context_server() -> Div {
636 h_flex()
637 .gap_2()
638 .child(
639 Icon::new(IconName::ArrowCircle)
640 .size(IconSize::XSmall)
641 .color(Color::Info)
642 .with_animation(
643 "arrow-circle",
644 Animation::new(Duration::from_secs(2)).repeat(),
645 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
646 )
647 .into_any_element(),
648 )
649 .child(
650 Label::new("Waiting for Context Server")
651 .size(LabelSize::Small)
652 .color(Color::Muted),
653 )
654 }
655
656 fn render_modal_error(error: SharedString) -> Div {
657 h_flex()
658 .gap_2()
659 .child(
660 Icon::new(IconName::Warning)
661 .size(IconSize::XSmall)
662 .color(Color::Warning),
663 )
664 .child(
665 div()
666 .w_full()
667 .child(Label::new(error).size(LabelSize::Small).color(Color::Muted)),
668 )
669 }
670}
671
672impl Render for ConfigureContextServerModal {
673 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
674 div()
675 .elevation_3(cx)
676 .w(rems(34.))
677 .key_context("ConfigureContextServerModal")
678 .on_action(
679 cx.listener(|this, _: &menu::Cancel, _window, cx| this.cancel(&menu::Cancel, cx)),
680 )
681 .on_action(
682 cx.listener(|this, _: &menu::Confirm, _window, cx| {
683 this.confirm(&menu::Confirm, cx)
684 }),
685 )
686 .capture_any_mouse_down(cx.listener(|this, _, window, cx| {
687 this.focus_handle(cx).focus(window);
688 }))
689 .child(
690 Modal::new("configure-context-server", None)
691 .header(self.render_modal_header())
692 .section(
693 Section::new()
694 .child(self.render_modal_description(window, cx))
695 .child(self.render_modal_content(cx))
696 .child(match &self.state {
697 State::Idle => div(),
698 State::Waiting => Self::render_waiting_for_context_server(),
699 State::Error(error) => Self::render_modal_error(error.clone()),
700 }),
701 )
702 .footer(self.render_modal_footer(window, cx)),
703 )
704 }
705}
706
707fn wait_for_context_server(
708 context_server_store: &Entity<ContextServerStore>,
709 context_server_id: ContextServerId,
710 cx: &mut App,
711) -> Task<Result<(), Arc<str>>> {
712 let (tx, rx) = futures::channel::oneshot::channel();
713 let tx = Arc::new(Mutex::new(Some(tx)));
714
715 let subscription = cx.subscribe(context_server_store, move |_, event, _cx| match event {
716 project::context_server_store::Event::ServerStatusChanged { server_id, status } => {
717 match status {
718 ContextServerStatus::Running => {
719 if server_id == &context_server_id {
720 if let Some(tx) = tx.lock().unwrap().take() {
721 let _ = tx.send(Ok(()));
722 }
723 }
724 }
725 ContextServerStatus::Stopped => {
726 if server_id == &context_server_id {
727 if let Some(tx) = tx.lock().unwrap().take() {
728 let _ = tx.send(Err("Context server stopped running".into()));
729 }
730 }
731 }
732 ContextServerStatus::Error(error) => {
733 if server_id == &context_server_id {
734 if let Some(tx) = tx.lock().unwrap().take() {
735 let _ = tx.send(Err(error.clone()));
736 }
737 }
738 }
739 _ => {}
740 }
741 }
742 });
743
744 cx.spawn(async move |_cx| {
745 let result = rx
746 .await
747 .map_err(|_| Arc::from("Context server store was dropped"))?;
748 drop(subscription);
749 result
750 })
751}
752
753pub(crate) fn default_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
754 let theme_settings = ThemeSettings::get_global(cx);
755 let colors = cx.theme().colors();
756 let mut text_style = window.text_style();
757 text_style.refine(&TextStyleRefinement {
758 font_family: Some(theme_settings.ui_font.family.clone()),
759 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
760 font_features: Some(theme_settings.ui_font.features.clone()),
761 font_size: Some(TextSize::XSmall.rems(cx).into()),
762 color: Some(colors.text_muted),
763 ..Default::default()
764 });
765
766 MarkdownStyle {
767 base_text_style: text_style.clone(),
768 selection_background_color: colors.element_selection_background,
769 link: TextStyleRefinement {
770 background_color: Some(colors.editor_foreground.opacity(0.025)),
771 underline: Some(UnderlineStyle {
772 color: Some(colors.text_accent.opacity(0.5)),
773 thickness: px(1.),
774 ..Default::default()
775 }),
776 ..Default::default()
777 },
778 ..Default::default()
779 }
780}