1mod add_llm_provider_modal;
2mod configure_context_server_modal;
3mod configure_context_server_tools_modal;
4mod manage_profiles_modal;
5mod tool_picker;
6
7use std::{ops::Range, sync::Arc};
8
9use agent::ContextServerRegistry;
10use anyhow::Result;
11use cloud_llm_client::{Plan, PlanV1, PlanV2};
12use collections::HashMap;
13use context_server::ContextServerId;
14use editor::{Editor, SelectionEffects, scroll::Autoscroll};
15use extension::ExtensionManifest;
16use extension_host::ExtensionStore;
17use fs::Fs;
18use gpui::{
19 Action, AnyView, App, AsyncWindowContext, Corner, Entity, EventEmitter, FocusHandle, Focusable,
20 ScrollHandle, Subscription, Task, WeakEntity,
21};
22use language::LanguageRegistry;
23use language_model::{
24 LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry, ZED_CLOUD_PROVIDER_ID,
25};
26use language_models::AllLanguageModelSettings;
27use notifications::status_toast::{StatusToast, ToastIcon};
28use project::{
29 agent_server_store::{AgentServerStore, CLAUDE_CODE_NAME, CODEX_NAME, GEMINI_NAME},
30 context_server_store::{ContextServerConfiguration, ContextServerStatus, ContextServerStore},
31};
32use settings::{Settings, SettingsStore, update_settings_file};
33use ui::{
34 Button, ButtonStyle, Chip, CommonAnimationExt, ContextMenu, Disclosure, Divider, DividerColor,
35 ElevationIndex, IconName, IconPosition, IconSize, Indicator, LabelSize, PopoverMenu, Switch,
36 SwitchColor, Tooltip, WithScrollbar, prelude::*,
37};
38use util::ResultExt as _;
39use workspace::{Workspace, create_and_open_local_file};
40use zed_actions::ExtensionCategoryFilter;
41
42pub(crate) use configure_context_server_modal::ConfigureContextServerModal;
43pub(crate) use configure_context_server_tools_modal::ConfigureContextServerToolsModal;
44pub(crate) use manage_profiles_modal::ManageProfilesModal;
45
46use crate::{
47 AddContextServer,
48 agent_configuration::add_llm_provider_modal::{AddLlmProviderModal, LlmCompatibleProvider},
49};
50
51pub struct AgentConfiguration {
52 fs: Arc<dyn Fs>,
53 language_registry: Arc<LanguageRegistry>,
54 agent_server_store: Entity<AgentServerStore>,
55 workspace: WeakEntity<Workspace>,
56 focus_handle: FocusHandle,
57 configuration_views_by_provider: HashMap<LanguageModelProviderId, AnyView>,
58 context_server_store: Entity<ContextServerStore>,
59 expanded_provider_configurations: HashMap<LanguageModelProviderId, bool>,
60 context_server_registry: Entity<ContextServerRegistry>,
61 _registry_subscription: Subscription,
62 scroll_handle: ScrollHandle,
63 _check_for_gemini: Task<()>,
64}
65
66impl AgentConfiguration {
67 pub fn new(
68 fs: Arc<dyn Fs>,
69 agent_server_store: Entity<AgentServerStore>,
70 context_server_store: Entity<ContextServerStore>,
71 context_server_registry: Entity<ContextServerRegistry>,
72 language_registry: Arc<LanguageRegistry>,
73 workspace: WeakEntity<Workspace>,
74 window: &mut Window,
75 cx: &mut Context<Self>,
76 ) -> Self {
77 let focus_handle = cx.focus_handle();
78
79 let registry_subscription = cx.subscribe_in(
80 &LanguageModelRegistry::global(cx),
81 window,
82 |this, _, event: &language_model::Event, window, cx| match event {
83 language_model::Event::AddedProvider(provider_id) => {
84 let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
85 if let Some(provider) = provider {
86 this.add_provider_configuration_view(&provider, window, cx);
87 }
88 }
89 language_model::Event::RemovedProvider(provider_id) => {
90 this.remove_provider_configuration_view(provider_id);
91 }
92 _ => {}
93 },
94 );
95
96 cx.subscribe(&context_server_store, |_, _, _, cx| cx.notify())
97 .detach();
98
99 let mut this = Self {
100 fs,
101 language_registry,
102 workspace,
103 focus_handle,
104 configuration_views_by_provider: HashMap::default(),
105 agent_server_store,
106 context_server_store,
107 expanded_provider_configurations: HashMap::default(),
108 context_server_registry,
109 _registry_subscription: registry_subscription,
110 scroll_handle: ScrollHandle::new(),
111 _check_for_gemini: Task::ready(()),
112 };
113 this.build_provider_configuration_views(window, cx);
114 this
115 }
116
117 fn build_provider_configuration_views(&mut self, window: &mut Window, cx: &mut Context<Self>) {
118 let providers = LanguageModelRegistry::read_global(cx).providers();
119 for provider in providers {
120 self.add_provider_configuration_view(&provider, window, cx);
121 }
122 }
123
124 fn remove_provider_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
125 self.configuration_views_by_provider.remove(provider_id);
126 self.expanded_provider_configurations.remove(provider_id);
127 }
128
129 fn add_provider_configuration_view(
130 &mut self,
131 provider: &Arc<dyn LanguageModelProvider>,
132 window: &mut Window,
133 cx: &mut Context<Self>,
134 ) {
135 let configuration_view = provider.configuration_view(
136 language_model::ConfigurationViewTargetAgent::ZedAgent,
137 window,
138 cx,
139 );
140 self.configuration_views_by_provider
141 .insert(provider.id(), configuration_view);
142 }
143}
144
145impl Focusable for AgentConfiguration {
146 fn focus_handle(&self, _: &App) -> FocusHandle {
147 self.focus_handle.clone()
148 }
149}
150
151pub enum AssistantConfigurationEvent {
152 NewThread(Arc<dyn LanguageModelProvider>),
153}
154
155impl EventEmitter<AssistantConfigurationEvent> for AgentConfiguration {}
156
157enum AgentIcon {
158 Name(IconName),
159 Path(SharedString),
160}
161
162impl AgentConfiguration {
163 fn render_section_title(
164 &mut self,
165 title: impl Into<SharedString>,
166 description: impl Into<SharedString>,
167 menu: AnyElement,
168 ) -> impl IntoElement {
169 h_flex()
170 .p_4()
171 .pb_0()
172 .mb_2p5()
173 .items_start()
174 .justify_between()
175 .child(
176 v_flex()
177 .w_full()
178 .gap_0p5()
179 .child(
180 h_flex()
181 .pr_1()
182 .w_full()
183 .gap_2()
184 .justify_between()
185 .flex_wrap()
186 .child(Headline::new(title.into()))
187 .child(menu),
188 )
189 .child(Label::new(description.into()).color(Color::Muted)),
190 )
191 }
192
193 fn render_provider_configuration_block(
194 &mut self,
195 provider: &Arc<dyn LanguageModelProvider>,
196 cx: &mut Context<Self>,
197 ) -> impl IntoElement + use<> {
198 let provider_id = provider.id().0;
199 let provider_name = provider.name().0;
200 let provider_id_string = SharedString::from(format!("provider-disclosure-{provider_id}"));
201
202 let configuration_view = self
203 .configuration_views_by_provider
204 .get(&provider.id())
205 .cloned();
206
207 let is_expanded = self
208 .expanded_provider_configurations
209 .get(&provider.id())
210 .copied()
211 .unwrap_or(false);
212
213 let is_zed_provider = provider.id() == ZED_CLOUD_PROVIDER_ID;
214 let current_plan = if is_zed_provider {
215 self.workspace
216 .upgrade()
217 .and_then(|workspace| workspace.read(cx).user_store().read(cx).plan())
218 } else {
219 None
220 };
221
222 let is_signed_in = self
223 .workspace
224 .read_with(cx, |workspace, _| {
225 !workspace.client().status().borrow().is_signed_out()
226 })
227 .unwrap_or(false);
228
229 v_flex()
230 .w_full()
231 .when(is_expanded, |this| this.mb_2())
232 .child(
233 div()
234 .px_2()
235 .child(Divider::horizontal().color(DividerColor::BorderFaded)),
236 )
237 .child(
238 h_flex()
239 .map(|this| {
240 if is_expanded {
241 this.mt_2().mb_1()
242 } else {
243 this.my_2()
244 }
245 })
246 .w_full()
247 .justify_between()
248 .child(
249 h_flex()
250 .id(provider_id_string.clone())
251 .px_2()
252 .py_0p5()
253 .w_full()
254 .justify_between()
255 .rounded_sm()
256 .hover(|hover| hover.bg(cx.theme().colors().element_hover))
257 .child(
258 h_flex()
259 .w_full()
260 .gap_1p5()
261 .child(
262 Icon::new(provider.icon())
263 .size(IconSize::Small)
264 .color(Color::Muted),
265 )
266 .child(
267 h_flex()
268 .w_full()
269 .gap_1()
270 .child(Label::new(provider_name.clone()))
271 .map(|this| {
272 if is_zed_provider && is_signed_in {
273 this.child(
274 self.render_zed_plan_info(current_plan, cx),
275 )
276 } else {
277 this.when(
278 provider.is_authenticated(cx)
279 && !is_expanded,
280 |parent| {
281 parent.child(
282 Icon::new(IconName::Check)
283 .color(Color::Success),
284 )
285 },
286 )
287 }
288 }),
289 ),
290 )
291 .child(
292 Disclosure::new(provider_id_string, is_expanded)
293 .opened_icon(IconName::ChevronUp)
294 .closed_icon(IconName::ChevronDown),
295 )
296 .on_click(cx.listener({
297 let provider_id = provider.id();
298 move |this, _event, _window, _cx| {
299 let is_expanded = this
300 .expanded_provider_configurations
301 .entry(provider_id.clone())
302 .or_insert(false);
303
304 *is_expanded = !*is_expanded;
305 }
306 })),
307 ),
308 )
309 .child(
310 v_flex()
311 .w_full()
312 .px_2()
313 .gap_1()
314 .when(is_expanded, |parent| match configuration_view {
315 Some(configuration_view) => parent.child(configuration_view),
316 None => parent.child(Label::new(format!(
317 "No configuration view for {provider_name}",
318 ))),
319 })
320 .when(is_expanded && provider.is_authenticated(cx), |parent| {
321 parent.child(
322 Button::new(
323 SharedString::from(format!("new-thread-{provider_id}")),
324 "Start New Thread",
325 )
326 .full_width()
327 .style(ButtonStyle::Outlined)
328 .layer(ElevationIndex::ModalSurface)
329 .icon_position(IconPosition::Start)
330 .icon(IconName::Thread)
331 .icon_size(IconSize::Small)
332 .icon_color(Color::Muted)
333 .label_size(LabelSize::Small)
334 .on_click(cx.listener({
335 let provider = provider.clone();
336 move |_this, _event, _window, cx| {
337 cx.emit(AssistantConfigurationEvent::NewThread(
338 provider.clone(),
339 ))
340 }
341 })),
342 )
343 })
344 .when(
345 is_expanded && is_removable_provider(&provider.id(), cx),
346 |this| {
347 this.child(
348 Button::new(
349 SharedString::from(format!("delete-provider-{provider_id}")),
350 "Remove Provider",
351 )
352 .full_width()
353 .style(ButtonStyle::Outlined)
354 .icon_position(IconPosition::Start)
355 .icon(IconName::Trash)
356 .icon_size(IconSize::Small)
357 .icon_color(Color::Muted)
358 .label_size(LabelSize::Small)
359 .on_click(cx.listener({
360 let provider = provider.clone();
361 move |this, _event, window, cx| {
362 this.delete_provider(provider.clone(), window, cx);
363 }
364 })),
365 )
366 },
367 ),
368 )
369 }
370
371 fn delete_provider(
372 &mut self,
373 provider: Arc<dyn LanguageModelProvider>,
374 window: &mut Window,
375 cx: &mut Context<Self>,
376 ) {
377 let fs = self.fs.clone();
378 let provider_id = provider.id();
379
380 cx.spawn_in(window, async move |_, cx| {
381 cx.update(|_window, cx| {
382 update_settings_file(fs.clone(), cx, {
383 let provider_id = provider_id.clone();
384 move |settings, _| {
385 if let Some(ref mut openai_compatible) = settings
386 .language_models
387 .as_mut()
388 .and_then(|lm| lm.openai_compatible.as_mut())
389 {
390 let key_to_remove: Arc<str> = Arc::from(provider_id.0.as_ref());
391 openai_compatible.remove(&key_to_remove);
392 }
393 }
394 });
395 })
396 .log_err();
397
398 cx.update(|_window, cx| {
399 LanguageModelRegistry::global(cx).update(cx, {
400 let provider_id = provider_id.clone();
401 move |registry, cx| {
402 registry.unregister_provider(provider_id, cx);
403 }
404 })
405 })
406 .log_err();
407
408 anyhow::Ok(())
409 })
410 .detach_and_log_err(cx);
411 }
412
413 fn render_provider_configuration_section(
414 &mut self,
415 cx: &mut Context<Self>,
416 ) -> impl IntoElement {
417 let providers = LanguageModelRegistry::read_global(cx).providers();
418 let popover_menu = PopoverMenu::new("add-provider-popover")
419 .trigger(
420 Button::new("add-provider", "Add Provider")
421 .style(ButtonStyle::Outlined)
422 .icon_position(IconPosition::Start)
423 .icon(IconName::Plus)
424 .icon_size(IconSize::Small)
425 .icon_color(Color::Muted)
426 .label_size(LabelSize::Small),
427 )
428 .anchor(gpui::Corner::TopRight)
429 .menu({
430 let workspace = self.workspace.clone();
431 move |window, cx| {
432 Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
433 menu.header("Compatible APIs").entry("OpenAI", None, {
434 let workspace = workspace.clone();
435 move |window, cx| {
436 workspace
437 .update(cx, |workspace, cx| {
438 AddLlmProviderModal::toggle(
439 LlmCompatibleProvider::OpenAi,
440 workspace,
441 window,
442 cx,
443 );
444 })
445 .log_err();
446 }
447 })
448 }))
449 }
450 });
451
452 v_flex()
453 .w_full()
454 .child(self.render_section_title(
455 "LLM Providers",
456 "Add at least one provider to use AI-powered features with Zed's native agent.",
457 popover_menu.into_any_element(),
458 ))
459 .child(
460 div()
461 .w_full()
462 .pl(DynamicSpacing::Base08.rems(cx))
463 .pr(DynamicSpacing::Base20.rems(cx))
464 .children(
465 providers.into_iter().map(|provider| {
466 self.render_provider_configuration_block(&provider, cx)
467 }),
468 ),
469 )
470 }
471
472 fn render_zed_plan_info(&self, plan: Option<Plan>, cx: &mut Context<Self>) -> impl IntoElement {
473 if let Some(plan) = plan {
474 let free_chip_bg = cx
475 .theme()
476 .colors()
477 .editor_background
478 .opacity(0.5)
479 .blend(cx.theme().colors().text_accent.opacity(0.05));
480
481 let pro_chip_bg = cx
482 .theme()
483 .colors()
484 .editor_background
485 .opacity(0.5)
486 .blend(cx.theme().colors().text_accent.opacity(0.2));
487
488 let (plan_name, label_color, bg_color) = match plan {
489 Plan::V1(PlanV1::ZedFree) | Plan::V2(PlanV2::ZedFree) => {
490 ("Free", Color::Default, free_chip_bg)
491 }
492 Plan::V1(PlanV1::ZedProTrial) | Plan::V2(PlanV2::ZedProTrial) => {
493 ("Pro Trial", Color::Accent, pro_chip_bg)
494 }
495 Plan::V1(PlanV1::ZedPro) | Plan::V2(PlanV2::ZedPro) => {
496 ("Pro", Color::Accent, pro_chip_bg)
497 }
498 };
499
500 Chip::new(plan_name.to_string())
501 .bg_color(bg_color)
502 .label_color(label_color)
503 .into_any_element()
504 } else {
505 div().into_any_element()
506 }
507 }
508
509 fn render_context_servers_section(
510 &mut self,
511 window: &mut Window,
512 cx: &mut Context<Self>,
513 ) -> impl IntoElement {
514 let mut context_server_ids = self
515 .context_server_store
516 .read(cx)
517 .server_ids(cx)
518 .into_iter()
519 .collect::<Vec<_>>();
520
521 // Sort context servers: ones without mcp-server- prefix first, then prefixed ones
522 context_server_ids.sort_by(|a, b| {
523 const MCP_PREFIX: &str = "mcp-server-";
524 match (a.0.strip_prefix(MCP_PREFIX), b.0.strip_prefix(MCP_PREFIX)) {
525 // If one has mcp-server- prefix and other doesn't, non-mcp comes first
526 (Some(_), None) => std::cmp::Ordering::Greater,
527 (None, Some(_)) => std::cmp::Ordering::Less,
528 // If both have same prefix status, sort by appropriate key
529 (Some(a), Some(b)) => a.cmp(b),
530 (None, None) => a.0.cmp(&b.0),
531 }
532 });
533
534 let add_server_popover = PopoverMenu::new("add-server-popover")
535 .trigger(
536 Button::new("add-server", "Add Server")
537 .style(ButtonStyle::Outlined)
538 .icon_position(IconPosition::Start)
539 .icon(IconName::Plus)
540 .icon_size(IconSize::Small)
541 .icon_color(Color::Muted)
542 .label_size(LabelSize::Small),
543 )
544 .anchor(gpui::Corner::TopRight)
545 .menu({
546 move |window, cx| {
547 Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
548 menu.entry("Add Custom Server", None, {
549 |window, cx| window.dispatch_action(AddContextServer.boxed_clone(), cx)
550 })
551 .entry("Install from Extensions", None, {
552 |window, cx| {
553 window.dispatch_action(
554 zed_actions::Extensions {
555 category_filter: Some(
556 ExtensionCategoryFilter::ContextServers,
557 ),
558 id: None,
559 }
560 .boxed_clone(),
561 cx,
562 )
563 }
564 })
565 }))
566 }
567 });
568
569 v_flex()
570 .border_b_1()
571 .border_color(cx.theme().colors().border)
572 .child(self.render_section_title(
573 "Model Context Protocol (MCP) Servers",
574 "All MCP servers connected directly or via a Zed extension.",
575 add_server_popover.into_any_element(),
576 ))
577 .child(
578 v_flex()
579 .pl_4()
580 .pb_4()
581 .pr_5()
582 .w_full()
583 .gap_1()
584 .map(|mut parent| {
585 if context_server_ids.is_empty() {
586 parent.child(
587 h_flex()
588 .p_4()
589 .justify_center()
590 .border_1()
591 .border_dashed()
592 .border_color(cx.theme().colors().border.opacity(0.6))
593 .rounded_sm()
594 .child(
595 Label::new("No MCP servers added yet.")
596 .color(Color::Muted)
597 .size(LabelSize::Small),
598 ),
599 )
600 } else {
601 for (index, context_server_id) in
602 context_server_ids.into_iter().enumerate()
603 {
604 if index > 0 {
605 parent = parent.child(
606 Divider::horizontal()
607 .color(DividerColor::BorderFaded)
608 .into_any_element(),
609 );
610 }
611 parent = parent.child(self.render_context_server(
612 context_server_id,
613 window,
614 cx,
615 ));
616 }
617 parent
618 }
619 }),
620 )
621 }
622
623 fn render_context_server(
624 &self,
625 context_server_id: ContextServerId,
626 window: &mut Window,
627 cx: &mut Context<Self>,
628 ) -> impl use<> + IntoElement {
629 let server_status = self
630 .context_server_store
631 .read(cx)
632 .status_for_server(&context_server_id)
633 .unwrap_or(ContextServerStatus::Stopped);
634 let server_configuration = self
635 .context_server_store
636 .read(cx)
637 .configuration_for_server(&context_server_id);
638
639 let is_running = matches!(server_status, ContextServerStatus::Running);
640 let item_id = SharedString::from(context_server_id.0.clone());
641 // Servers without a configuration can only be provided by extensions.
642 let provided_by_extension = server_configuration.is_none_or(|config| {
643 matches!(
644 config.as_ref(),
645 ContextServerConfiguration::Extension { .. }
646 )
647 });
648
649 let error = if let ContextServerStatus::Error(error) = server_status.clone() {
650 Some(error)
651 } else {
652 None
653 };
654
655 let tool_count = self
656 .context_server_registry
657 .read(cx)
658 .tools_for_server(&context_server_id)
659 .count();
660
661 let (source_icon, source_tooltip) = if provided_by_extension {
662 (
663 IconName::ZedSrcExtension,
664 "This MCP server was installed from an extension.",
665 )
666 } else {
667 (
668 IconName::ZedSrcCustom,
669 "This custom MCP server was installed directly.",
670 )
671 };
672
673 let (status_indicator, tooltip_text) = match server_status {
674 ContextServerStatus::Starting => (
675 Icon::new(IconName::LoadCircle)
676 .size(IconSize::XSmall)
677 .color(Color::Accent)
678 .with_keyed_rotate_animation(
679 SharedString::from(format!("{}-starting", context_server_id.0)),
680 3,
681 )
682 .into_any_element(),
683 "Server is starting.",
684 ),
685 ContextServerStatus::Running => (
686 Indicator::dot().color(Color::Success).into_any_element(),
687 "Server is active.",
688 ),
689 ContextServerStatus::Error(_) => (
690 Indicator::dot().color(Color::Error).into_any_element(),
691 "Server has an error.",
692 ),
693 ContextServerStatus::Stopped => (
694 Indicator::dot().color(Color::Muted).into_any_element(),
695 "Server is stopped.",
696 ),
697 };
698
699 let context_server_configuration_menu = PopoverMenu::new("context-server-config-menu")
700 .trigger_with_tooltip(
701 IconButton::new("context-server-config-menu", IconName::Settings)
702 .icon_color(Color::Muted)
703 .icon_size(IconSize::Small),
704 Tooltip::text("Configure MCP Server"),
705 )
706 .anchor(Corner::TopRight)
707 .menu({
708 let fs = self.fs.clone();
709 let context_server_id = context_server_id.clone();
710 let language_registry = self.language_registry.clone();
711 let workspace = self.workspace.clone();
712 let context_server_registry = self.context_server_registry.clone();
713
714 move |window, cx| {
715 Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
716 menu.entry("Configure Server", None, {
717 let context_server_id = context_server_id.clone();
718 let language_registry = language_registry.clone();
719 let workspace = workspace.clone();
720 move |window, cx| {
721 ConfigureContextServerModal::show_modal_for_existing_server(
722 context_server_id.clone(),
723 language_registry.clone(),
724 workspace.clone(),
725 window,
726 cx,
727 )
728 .detach_and_log_err(cx);
729 }
730 }).when(tool_count > 0, |this| this.entry("View Tools", None, {
731 let context_server_id = context_server_id.clone();
732 let context_server_registry = context_server_registry.clone();
733 let workspace = workspace.clone();
734 move |window, cx| {
735 let context_server_id = context_server_id.clone();
736 workspace.update(cx, |workspace, cx| {
737 ConfigureContextServerToolsModal::toggle(
738 context_server_id,
739 context_server_registry.clone(),
740 workspace,
741 window,
742 cx,
743 );
744 })
745 .ok();
746 }
747 }))
748 .separator()
749 .entry("Uninstall", None, {
750 let fs = fs.clone();
751 let context_server_id = context_server_id.clone();
752 let workspace = workspace.clone();
753 move |_, cx| {
754 let uninstall_extension_task = match (
755 provided_by_extension,
756 resolve_extension_for_context_server(&context_server_id, cx),
757 ) {
758 (true, Some((id, manifest))) => {
759 if extension_only_provides_context_server(manifest.as_ref())
760 {
761 ExtensionStore::global(cx).update(cx, |store, cx| {
762 store.uninstall_extension(id, cx)
763 })
764 } else {
765 workspace.update(cx, |workspace, cx| {
766 show_unable_to_uninstall_extension_with_context_server(workspace, context_server_id.clone(), cx);
767 }).log_err();
768 Task::ready(Ok(()))
769 }
770 }
771 _ => Task::ready(Ok(())),
772 };
773
774 cx.spawn({
775 let fs = fs.clone();
776 let context_server_id = context_server_id.clone();
777 async move |cx| {
778 uninstall_extension_task.await?;
779 cx.update(|cx| {
780 update_settings_file(
781 fs.clone(),
782 cx,
783 {
784 let context_server_id =
785 context_server_id.clone();
786 move |settings, _| {
787 settings.project
788 .context_servers
789 .remove(&context_server_id.0);
790 }
791 },
792 )
793 })
794 }
795 })
796 .detach_and_log_err(cx);
797 }
798 })
799 }))
800 }
801 });
802
803 v_flex()
804 .id(item_id.clone())
805 .child(
806 h_flex()
807 .justify_between()
808 .child(
809 h_flex()
810 .flex_1()
811 .min_w_0()
812 .child(
813 h_flex()
814 .id(SharedString::from(format!("tooltip-{}", item_id)))
815 .h_full()
816 .w_3()
817 .mr_2()
818 .justify_center()
819 .tooltip(Tooltip::text(tooltip_text))
820 .child(status_indicator),
821 )
822 .child(Label::new(item_id).truncate())
823 .child(
824 div()
825 .id("extension-source")
826 .mt_0p5()
827 .mx_1()
828 .flex_none()
829 .tooltip(Tooltip::text(source_tooltip))
830 .child(
831 Icon::new(source_icon)
832 .size(IconSize::Small)
833 .color(Color::Muted),
834 ),
835 )
836 .when(is_running, |this| {
837 this.child(
838 Label::new(if tool_count == 1 {
839 SharedString::from("1 tool")
840 } else {
841 SharedString::from(format!("{} tools", tool_count))
842 })
843 .color(Color::Muted)
844 .size(LabelSize::Small),
845 )
846 }),
847 )
848 .child(
849 h_flex()
850 .gap_0p5()
851 .flex_none()
852 .child(context_server_configuration_menu)
853 .child(
854 Switch::new("context-server-switch", is_running.into())
855 .color(SwitchColor::Accent)
856 .on_click({
857 let context_server_manager = self.context_server_store.clone();
858 let fs = self.fs.clone();
859
860 move |state, _window, cx| {
861 let is_enabled = match state {
862 ToggleState::Unselected
863 | ToggleState::Indeterminate => {
864 context_server_manager.update(cx, |this, cx| {
865 this.stop_server(&context_server_id, cx)
866 .log_err();
867 });
868 false
869 }
870 ToggleState::Selected => {
871 context_server_manager.update(cx, |this, cx| {
872 if let Some(server) =
873 this.get_server(&context_server_id)
874 {
875 this.start_server(server, cx);
876 }
877 });
878 true
879 }
880 };
881 update_settings_file(fs.clone(), cx, {
882 let context_server_id = context_server_id.clone();
883
884 move |settings, _| {
885 settings
886 .project
887 .context_servers
888 .entry(context_server_id.0)
889 .or_insert_with(|| {
890 settings::ContextServerSettingsContent::Extension {
891 enabled: is_enabled,
892 settings: serde_json::json!({}),
893 }
894 })
895 .set_enabled(is_enabled);
896 }
897 });
898 }
899 }),
900 ),
901 ),
902 )
903 .map(|parent| {
904 if let Some(error) = error {
905 return parent.child(
906 h_flex()
907 .gap_2()
908 .pr_4()
909 .items_start()
910 .child(
911 h_flex()
912 .flex_none()
913 .h(window.line_height() / 1.6_f32)
914 .justify_center()
915 .child(
916 Icon::new(IconName::XCircle)
917 .size(IconSize::XSmall)
918 .color(Color::Error),
919 ),
920 )
921 .child(
922 div().w_full().child(
923 Label::new(error)
924 .buffer_font(cx)
925 .color(Color::Muted)
926 .size(LabelSize::Small),
927 ),
928 ),
929 );
930 }
931 parent
932 })
933 }
934
935 fn render_agent_servers_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
936 let agent_server_store = self.agent_server_store.read(cx);
937
938 let user_defined_agents = agent_server_store
939 .external_agents()
940 .filter(|name| {
941 name.0 != GEMINI_NAME && name.0 != CLAUDE_CODE_NAME && name.0 != CODEX_NAME
942 })
943 .cloned()
944 .collect::<Vec<_>>();
945
946 let user_defined_agents = user_defined_agents
947 .into_iter()
948 .map(|name| {
949 let icon = if let Some(icon_path) = agent_server_store.agent_icon(&name) {
950 AgentIcon::Path(icon_path)
951 } else {
952 AgentIcon::Name(IconName::Ai)
953 };
954 self.render_agent_server(icon, name, true)
955 .into_any_element()
956 })
957 .collect::<Vec<_>>();
958
959 let add_agens_button = Button::new("add-agent", "Add Agent")
960 .style(ButtonStyle::Outlined)
961 .icon_position(IconPosition::Start)
962 .icon(IconName::Plus)
963 .icon_size(IconSize::Small)
964 .icon_color(Color::Muted)
965 .label_size(LabelSize::Small)
966 .on_click(move |_, window, cx| {
967 if let Some(workspace) = window.root().flatten() {
968 let workspace = workspace.downgrade();
969 window
970 .spawn(cx, async |cx| {
971 open_new_agent_servers_entry_in_settings_editor(workspace, cx).await
972 })
973 .detach_and_log_err(cx);
974 }
975 });
976
977 v_flex()
978 .border_b_1()
979 .border_color(cx.theme().colors().border)
980 .child(
981 v_flex()
982 .child(self.render_section_title(
983 "External Agents",
984 "All agents connected through the Agent Client Protocol.",
985 add_agens_button.into_any_element(),
986 ))
987 .child(
988 v_flex()
989 .p_4()
990 .pt_0()
991 .gap_2()
992 .child(self.render_agent_server(
993 AgentIcon::Name(IconName::AiClaude),
994 "Claude Code",
995 false,
996 ))
997 .child(Divider::horizontal().color(DividerColor::BorderFaded))
998 .child(self.render_agent_server(
999 AgentIcon::Name(IconName::AiOpenAi),
1000 "Codex CLI",
1001 false,
1002 ))
1003 .child(Divider::horizontal().color(DividerColor::BorderFaded))
1004 .child(self.render_agent_server(
1005 AgentIcon::Name(IconName::AiGemini),
1006 "Gemini CLI",
1007 false,
1008 ))
1009 .map(|mut parent| {
1010 for agent in user_defined_agents {
1011 parent = parent
1012 .child(
1013 Divider::horizontal().color(DividerColor::BorderFaded),
1014 )
1015 .child(agent);
1016 }
1017 parent
1018 }),
1019 ),
1020 )
1021 }
1022
1023 fn render_agent_server(
1024 &self,
1025 icon: AgentIcon,
1026 name: impl Into<SharedString>,
1027 external: bool,
1028 ) -> impl IntoElement {
1029 let name = name.into();
1030 let icon = match icon {
1031 AgentIcon::Name(icon_name) => Icon::new(icon_name)
1032 .size(IconSize::Small)
1033 .color(Color::Muted),
1034 AgentIcon::Path(icon_path) => Icon::from_external_svg(icon_path)
1035 .size(IconSize::Small)
1036 .color(Color::Muted),
1037 };
1038
1039 let tooltip_id = SharedString::new(format!("agent-source-{}", name));
1040 let tooltip_message = format!("The {} agent was installed from an extension.", name);
1041
1042 h_flex()
1043 .gap_1p5()
1044 .child(icon)
1045 .child(Label::new(name))
1046 .when(external, |this| {
1047 this.child(
1048 div()
1049 .id(tooltip_id)
1050 .flex_none()
1051 .tooltip(Tooltip::text(tooltip_message))
1052 .child(
1053 Icon::new(IconName::ZedSrcExtension)
1054 .size(IconSize::Small)
1055 .color(Color::Muted),
1056 ),
1057 )
1058 })
1059 .child(
1060 Icon::new(IconName::Check)
1061 .color(Color::Success)
1062 .size(IconSize::Small),
1063 )
1064 }
1065}
1066
1067impl Render for AgentConfiguration {
1068 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1069 v_flex()
1070 .id("assistant-configuration")
1071 .key_context("AgentConfiguration")
1072 .track_focus(&self.focus_handle(cx))
1073 .relative()
1074 .size_full()
1075 .pb_8()
1076 .bg(cx.theme().colors().panel_background)
1077 .child(
1078 div()
1079 .size_full()
1080 .child(
1081 v_flex()
1082 .id("assistant-configuration-content")
1083 .track_scroll(&self.scroll_handle)
1084 .size_full()
1085 .overflow_y_scroll()
1086 .child(self.render_agent_servers_section(cx))
1087 .child(self.render_context_servers_section(window, cx))
1088 .child(self.render_provider_configuration_section(cx)),
1089 )
1090 .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx),
1091 )
1092 }
1093}
1094
1095fn extension_only_provides_context_server(manifest: &ExtensionManifest) -> bool {
1096 manifest.context_servers.len() == 1
1097 && manifest.themes.is_empty()
1098 && manifest.icon_themes.is_empty()
1099 && manifest.languages.is_empty()
1100 && manifest.grammars.is_empty()
1101 && manifest.language_servers.is_empty()
1102 && manifest.slash_commands.is_empty()
1103 && manifest.snippets.is_none()
1104 && manifest.debug_locators.is_empty()
1105}
1106
1107pub(crate) fn resolve_extension_for_context_server(
1108 id: &ContextServerId,
1109 cx: &App,
1110) -> Option<(Arc<str>, Arc<ExtensionManifest>)> {
1111 ExtensionStore::global(cx)
1112 .read(cx)
1113 .installed_extensions()
1114 .iter()
1115 .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
1116 .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1117}
1118
1119// This notification appears when trying to delete
1120// an MCP server extension that not only provides
1121// the server, but other things, too, like language servers and more.
1122fn show_unable_to_uninstall_extension_with_context_server(
1123 workspace: &mut Workspace,
1124 id: ContextServerId,
1125 cx: &mut App,
1126) {
1127 let workspace_handle = workspace.weak_handle();
1128 let context_server_id = id.clone();
1129
1130 let status_toast = StatusToast::new(
1131 format!(
1132 "The {} extension provides more than just the MCP server. Proceed to uninstall anyway?",
1133 id.0
1134 ),
1135 cx,
1136 move |this, _cx| {
1137 let workspace_handle = workspace_handle.clone();
1138
1139 this.icon(ToastIcon::new(IconName::Warning).color(Color::Warning))
1140 .dismiss_button(true)
1141 .action("Uninstall", move |_, _cx| {
1142 if let Some((extension_id, _)) =
1143 resolve_extension_for_context_server(&context_server_id, _cx)
1144 {
1145 ExtensionStore::global(_cx).update(_cx, |store, cx| {
1146 store
1147 .uninstall_extension(extension_id, cx)
1148 .detach_and_log_err(cx);
1149 });
1150
1151 workspace_handle
1152 .update(_cx, |workspace, cx| {
1153 let fs = workspace.app_state().fs.clone();
1154 cx.spawn({
1155 let context_server_id = context_server_id.clone();
1156 async move |_workspace_handle, cx| {
1157 cx.update(|cx| {
1158 update_settings_file(fs, cx, move |settings, _| {
1159 settings
1160 .project
1161 .context_servers
1162 .remove(&context_server_id.0);
1163 });
1164 })?;
1165 anyhow::Ok(())
1166 }
1167 })
1168 .detach_and_log_err(cx);
1169 })
1170 .log_err();
1171 }
1172 })
1173 },
1174 );
1175
1176 workspace.toggle_status_toast(status_toast, cx);
1177}
1178
1179async fn open_new_agent_servers_entry_in_settings_editor(
1180 workspace: WeakEntity<Workspace>,
1181 cx: &mut AsyncWindowContext,
1182) -> Result<()> {
1183 let settings_editor = workspace
1184 .update_in(cx, |_, window, cx| {
1185 create_and_open_local_file(paths::settings_file(), window, cx, || {
1186 settings::initial_user_settings_content().as_ref().into()
1187 })
1188 })?
1189 .await?
1190 .downcast::<Editor>()
1191 .unwrap();
1192
1193 settings_editor
1194 .downgrade()
1195 .update_in(cx, |item, window, cx| {
1196 let text = item.buffer().read(cx).snapshot(cx).text();
1197
1198 let settings = cx.global::<SettingsStore>();
1199
1200 let mut unique_server_name = None;
1201 let edits = settings.edits_for_update(&text, |settings| {
1202 let server_name: Option<SharedString> = (0..u8::MAX)
1203 .map(|i| {
1204 if i == 0 {
1205 "your_agent".into()
1206 } else {
1207 format!("your_agent_{}", i).into()
1208 }
1209 })
1210 .find(|name| {
1211 !settings
1212 .agent_servers
1213 .as_ref()
1214 .is_some_and(|agent_servers| agent_servers.custom.contains_key(name))
1215 });
1216 if let Some(server_name) = server_name {
1217 unique_server_name = Some(server_name.clone());
1218 settings
1219 .agent_servers
1220 .get_or_insert_default()
1221 .custom
1222 .insert(
1223 server_name,
1224 settings::CustomAgentServerSettings {
1225 path: "path_to_executable".into(),
1226 args: vec![],
1227 env: Some(HashMap::default()),
1228 default_mode: None,
1229 },
1230 );
1231 }
1232 });
1233
1234 if edits.is_empty() {
1235 return;
1236 }
1237
1238 let ranges = edits
1239 .iter()
1240 .map(|(range, _)| range.clone())
1241 .collect::<Vec<_>>();
1242
1243 item.edit(edits, cx);
1244 if let Some((unique_server_name, buffer)) =
1245 unique_server_name.zip(item.buffer().read(cx).as_singleton())
1246 {
1247 let snapshot = buffer.read(cx).snapshot();
1248 if let Some(range) =
1249 find_text_in_buffer(&unique_server_name, ranges[0].start, &snapshot)
1250 {
1251 item.change_selections(
1252 SelectionEffects::scroll(Autoscroll::newest()),
1253 window,
1254 cx,
1255 |selections| {
1256 selections.select_ranges(vec![range]);
1257 },
1258 );
1259 }
1260 }
1261 })
1262}
1263
1264fn find_text_in_buffer(
1265 text: &str,
1266 start: usize,
1267 snapshot: &language::BufferSnapshot,
1268) -> Option<Range<usize>> {
1269 let chars = text.chars().collect::<Vec<char>>();
1270
1271 let mut offset = start;
1272 let mut char_offset = 0;
1273 for c in snapshot.chars_at(start) {
1274 if char_offset >= chars.len() {
1275 break;
1276 }
1277 offset += 1;
1278
1279 if c == chars[char_offset] {
1280 char_offset += 1;
1281 } else {
1282 char_offset = 0;
1283 }
1284 }
1285
1286 if char_offset == chars.len() {
1287 Some(offset.saturating_sub(chars.len())..offset)
1288 } else {
1289 None
1290 }
1291}
1292
1293// OpenAI-compatible providers are user-configured and can be removed,
1294// whereas built-in providers (like Anthropic, OpenAI, Google, etc.) can't.
1295//
1296// If in the future we have more "API-compatible-type" of providers,
1297// they should be included here as removable providers.
1298fn is_removable_provider(provider_id: &LanguageModelProviderId, cx: &App) -> bool {
1299 AllLanguageModelSettings::get_global(cx)
1300 .openai_compatible
1301 .contains_key(provider_id.0.as_ref())
1302}