Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

Settings UI agent providers (#58876)

Cameron Mcloughlin02b62a3d1f2f
diff --git a/Cargo.lock b/Cargo.lock
index 591b6310a6e..2f39bd37beb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -16621,13 +16621,17 @@ dependencies = [
"audio",
"cloud_api_types",
"codestral",
+ "collections",
"component",
+ "context_server",
"copilot",
"copilot_ui",
"cpal",
"edit_prediction",
"edit_prediction_ui",
"editor",
+ "extension",
+ "extension_host",
"feature_flags",
"fs",
"futures 0.3.32",
@@ -16637,6 +16641,7 @@ dependencies = [
"http_client",
"itertools 0.14.0",
"language",
+ "language_model",
"log",
"menu",
"paths",
@@ -16661,6 +16666,7 @@ dependencies = [
"title_bar",
"ui",
"ui_input",
+ "url",
"util",
"workspace",
"zed_actions",
diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rs
index 40ffc42b0ae..b414f60165b 100644
--- a/crates/agent_ui/src/agent_panel.rs
+++ b/crates/agent_ui/src/agent_panel.rs
@@ -70,7 +70,9 @@ use cloud_api_types::Plan;
use collections::HashMap;
use editor::{Editor, MultiBuffer};
use extension_host::ExtensionStore;
-use feature_flags::{CreateThreadToolFeatureFlag, FeatureFlagAppExt as _};
+use feature_flags::{
+ AgentSettingsUiFeatureFlag, CreateThreadToolFeatureFlag, FeatureFlagAppExt as _,
+};
use fs::Fs;
use gpui::{
@@ -3569,6 +3571,21 @@ impl AgentPanel {
}
pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ // When the agent settings have been moved into the settings UI, the
+ // panel no longer shows its own configuration overlay. Instead, route to
+ // the settings UI at the LLM providers page (where the model selector's
+ // "Configure" button expects to land).
+ if cx.has_flag::<AgentSettingsUiFeatureFlag>() {
+ window.dispatch_action(
+ Box::new(zed_actions::OpenSettingsAt {
+ path: "llm_providers".to_string(),
+ target: None,
+ }),
+ cx,
+ );
+ return;
+ }
+
if matches!(self.overlay_view, Some(OverlayView::Configuration)) {
self.clear_overlay(true, window, cx);
return;
diff --git a/crates/feature_flags/src/flags.rs b/crates/feature_flags/src/flags.rs
index e84b08d5772..2b7783514d1 100644
--- a/crates/feature_flags/src/flags.rs
+++ b/crates/feature_flags/src/flags.rs
@@ -119,6 +119,18 @@ impl FeatureFlag for AgentThreadWorktreeLabelFlag {
}
register_feature_flag!(AgentThreadWorktreeLabelFlag);
+/// Moves LLM provider and MCP server configuration out of the dedicated agent
+/// panel page and into the settings UI. When enabled, the agent panel no longer
+/// shows its configuration overlay and the settings UI exposes the "LLM
+/// Providers" and "MCP Servers" sub-pages instead.
+pub struct AgentSettingsUiFeatureFlag;
+
+impl FeatureFlag for AgentSettingsUiFeatureFlag {
+ const NAME: &'static str = "agent-settings-ui";
+ type Value = PresenceFlag;
+}
+register_feature_flag!(AgentSettingsUiFeatureFlag);
+
pub struct AutoWatchFeatureFlag;
impl FeatureFlag for AutoWatchFeatureFlag {
diff --git a/crates/language_model/src/language_model.rs b/crates/language_model/src/language_model.rs
index 461f4c80934..ff56c35ec83 100644
--- a/crates/language_model/src/language_model.rs
+++ b/crates/language_model/src/language_model.rs
@@ -340,6 +340,23 @@ pub trait LanguageModelProvider: 'static {
.into()
}
+ /// Returns the provider's configuration UI together with how it prefers to
+ /// be presented: [`ProviderConfigurationView::Inline`] for a compact control
+ /// that can sit in a list row (e.g. a single API-key field), or
+ /// [`ProviderConfigurationView::SubPage`] for a richer view that needs its
+ /// own surface.
+ ///
+ /// The default reuses [`Self::configuration_view`] as a sub-page, so
+ /// providers only override this when they have a compact inline form.
+ fn configuration_view_v2(
+ &self,
+ target_agent: ConfigurationViewTargetAgent,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> ProviderConfigurationView {
+ ProviderConfigurationView::SubPage(self.configuration_view(target_agent, window, cx))
+ }
+
/// Copy shown the first time a user enables fast mode for a model from
/// this provider. Returning `None` skips the confirmation prompt and lets
/// the toggle apply silently.
@@ -348,6 +365,16 @@ pub trait LanguageModelProvider: 'static {
}
}
+/// How a provider's configuration UI prefers to be presented by the settings UI.
+#[derive(Clone)]
+pub enum ProviderConfigurationView {
+ /// A compact control suitable for rendering inline in a list row, such as a
+ /// single API-key field.
+ Inline(AnyView),
+ /// A richer view that should be shown on its own dedicated sub-page.
+ SubPage(AnyView),
+}
+
/// Provider-specific copy shown the first time a user enables fast mode.
#[derive(Debug, Clone)]
pub struct FastModeConfirmation {
diff --git a/crates/language_models/src/api_key_editor.rs b/crates/language_models/src/api_key_editor.rs
new file mode 100644
index 00000000000..d6a9182a662
--- /dev/null
+++ b/crates/language_models/src/api_key_editor.rs
@@ -0,0 +1,155 @@
+use std::rc::Rc;
+
+use anyhow::Result;
+use gpui::{App, Context, Entity, Subscription, Task, Window};
+use language_model::ApiKeyState;
+use ui::{Tooltip, prelude::*};
+use ui_input::InputField;
+
+/// The current credential state of a single-API-key provider, as reported by the
+/// provider when constructing an [`ApiKeyEditor`].
+pub enum ApiKeyStatus {
+ /// No key is configured; show the input field.
+ Unset,
+ /// A key is configured via the UI; show a "configured" row with a reset.
+ Configured,
+ /// The key comes from an environment variable and can't be edited here.
+ FromEnvVar(SharedString),
+}
+
+/// Maps a provider's [`ApiKeyState`] to the [`ApiKeyStatus`] the editor renders.
+/// Shared so the API-key providers don't each duplicate this mapping.
+pub fn api_key_status(state: &ApiKeyState) -> ApiKeyStatus {
+ if state.is_from_env_var() {
+ ApiKeyStatus::FromEnvVar(state.env_var_name().clone())
+ } else if state.has_key() {
+ ApiKeyStatus::Configured
+ } else {
+ ApiKeyStatus::Unset
+ }
+}
+
+/// A compact, reusable control for editing a provider's single API key, intended
+/// to be returned from `LanguageModelProvider::configuration_view_v2` as an
+/// inline control.
+///
+/// It is deliberately provider-agnostic: the provider supplies closures that
+/// read the current [`ApiKeyStatus`] and store/clear the key against its own
+/// state, so all credential knowledge stays in the provider.
+pub struct ApiKeyEditor {
+ input: Entity<InputField>,
+ api_key_url: SharedString,
+ status: Rc<dyn Fn(&App) -> ApiKeyStatus>,
+ set_key: Rc<dyn Fn(String, &mut App) -> Task<Result<()>>>,
+ reset_key: Rc<dyn Fn(&mut App) -> Task<Result<()>>>,
+ _subscription: Subscription,
+}
+
+impl ApiKeyEditor {
+ pub fn new<S: 'static>(
+ state: Entity<S>,
+ api_key_url: impl Into<SharedString>,
+ placeholder: &str,
+ status: impl Fn(&S, &App) -> ApiKeyStatus + 'static,
+ set_key: impl Fn(&Entity<S>, String, &mut App) -> Task<Result<()>> + 'static,
+ reset_key: impl Fn(&Entity<S>, &mut App) -> Task<Result<()>> + 'static,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> Self {
+ let input = cx.new(|cx| {
+ InputField::new(window, cx, placeholder)
+ .masked(true)
+ .tab_index(0)
+ });
+ let subscription = cx.observe(&state, |_, _, cx| cx.notify());
+
+ let status_state = state.clone();
+ let set_state = state.clone();
+ Self {
+ input,
+ api_key_url: api_key_url.into(),
+ status: Rc::new(move |cx| status(status_state.read(cx), cx)),
+ set_key: Rc::new(move |key, cx| set_key(&set_state, key, cx)),
+ reset_key: Rc::new(move |cx| reset_key(&state, cx)),
+ _subscription: subscription,
+ }
+ }
+
+ fn save(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
+ let key = self.input.read(cx).text(cx).trim().to_string();
+ if key.is_empty() {
+ return;
+ }
+ self.input
+ .update(cx, |input, cx| input.set_text("", window, cx));
+ (self.set_key.clone())(key, cx).detach_and_log_err(cx);
+ }
+
+ fn reset(&mut self, cx: &mut Context<Self>) {
+ (self.reset_key.clone())(cx).detach_and_log_err(cx);
+ }
+
+ fn render_where_to_find_key(&self) -> impl IntoElement {
+ let url = self.api_key_url.clone();
+ let click_url = url.to_string();
+ h_flex()
+ .id("where-to-find-key")
+ .gap_0p5()
+ .cursor_pointer()
+ .child(
+ Icon::new(IconName::Info)
+ .size(IconSize::XSmall)
+ .color(Color::Muted),
+ )
+ .child(
+ Label::new("Where to find key")
+ .size(LabelSize::Small)
+ .color(Color::Muted),
+ )
+ .tooltip(Tooltip::text(format!("Create an API key at {url}")))
+ .on_click(move |_, _window, cx| cx.open_url(&click_url))
+ }
+}
+
+impl Render for ApiKeyEditor {
+ fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ match (self.status)(cx) {
+ ApiKeyStatus::FromEnvVar(env_var_name) => Label::new(format!("Set via {env_var_name}"))
+ .size(LabelSize::Small)
+ .color(Color::Muted)
+ .into_any_element(),
+ ApiKeyStatus::Configured => h_flex()
+ .gap_2()
+ .items_center()
+ .child(
+ Icon::new(IconName::Check)
+ .size(IconSize::Small)
+ .color(Color::Success),
+ )
+ .child(
+ Label::new("Configured")
+ .size(LabelSize::Small)
+ .color(Color::Muted),
+ )
+ .child(
+ Button::new("reset-api-key", "Reset")
+ .style(ButtonStyle::Outlined)
+ .label_size(LabelSize::Small)
+ .tab_index(0isize)
+ .on_click(cx.listener(|this, _, _window, cx| this.reset(cx))),
+ )
+ .into_any_element(),
+ ApiKeyStatus::Unset => v_flex()
+ .w_full()
+ .gap_1()
+ .child(self.render_where_to_find_key())
+ .child(
+ div()
+ .w_full()
+ .on_action(cx.listener(Self::save))
+ .child(self.input.clone()),
+ )
+ .into_any_element(),
+ }
+ }
+}
diff --git a/crates/language_models/src/language_models.rs b/crates/language_models/src/language_models.rs
index 717da683dc8..dc13cde1378 100644
--- a/crates/language_models/src/language_models.rs
+++ b/crates/language_models/src/language_models.rs
@@ -10,10 +10,12 @@ use language_model::{
};
use provider::deepseek::DeepSeekLanguageModelProvider;
+mod api_key_editor;
pub mod extension;
pub mod provider;
mod settings;
+pub use crate::api_key_editor::{ApiKeyEditor, ApiKeyStatus, api_key_status};
pub use crate::extension::init_proxy as init_extension_proxy;
use crate::provider::anthropic::AnthropicLanguageModelProvider;
diff --git a/crates/language_models/src/provider/anthropic.rs b/crates/language_models/src/provider/anthropic.rs
index 41127ff09f3..46ef381f312 100644
--- a/crates/language_models/src/provider/anthropic.rs
+++ b/crates/language_models/src/provider/anthropic.rs
@@ -12,8 +12,8 @@ use language_model::{
ConfigurationViewTargetAgent, EnvVar, FastModeConfirmation, IconOrSvg, LanguageModel,
LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId, LanguageModelName,
LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
- LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice, RateLimiter,
- env_var,
+ LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
+ ProviderConfigurationView, RateLimiter, env_var,
};
use settings::{Settings, SettingsStore};
use std::sync::{Arc, LazyLock};
@@ -290,6 +290,30 @@ impl LanguageModelProvider for AnthropicLanguageModelProvider {
.update(cx, |state, cx| state.set_api_key(None, cx))
}
+ fn configuration_view_v2(
+ &self,
+ _target_agent: language_model::ConfigurationViewTargetAgent,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> ProviderConfigurationView {
+ let state = self.state.clone();
+ ProviderConfigurationView::Inline(
+ cx.new(|cx| {
+ crate::ApiKeyEditor::new(
+ state,
+ "https://console.anthropic.com/settings/keys",
+ "sk-ant-...",
+ |state, _cx| crate::api_key_status(&state.api_key_state),
+ |state, key, cx| state.update(cx, |state, cx| state.set_api_key(Some(key), cx)),
+ |state, cx| state.update(cx, |state, cx| state.set_api_key(None, cx)),
+ window,
+ cx,
+ )
+ })
+ .into(),
+ )
+ }
+
fn fast_mode_confirmation(&self, _cx: &App) -> Option<FastModeConfirmation> {
Some(FastModeConfirmation {
title: "Enable Fast Mode for Anthropic?".into(),
diff --git a/crates/language_models/src/provider/cloud.rs b/crates/language_models/src/provider/cloud.rs
index a44f401c44a..07eb29f7253 100644
--- a/crates/language_models/src/provider/cloud.rs
+++ b/crates/language_models/src/provider/cloud.rs
@@ -13,7 +13,7 @@ use gpui::{AnyElement, AnyView, App, AppContext, Context, Entity, Subscription,
use language_model::{
AuthenticateError, FastModeConfirmation, IconOrSvg, LanguageModel, LanguageModelProvider,
LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
- ZED_CLOUD_PROVIDER_ID, ZED_CLOUD_PROVIDER_NAME,
+ ProviderConfigurationView, ZED_CLOUD_PROVIDER_ID, ZED_CLOUD_PROVIDER_NAME,
};
use language_models_cloud::{CloudLlmTokenProvider, CloudModelProvider};
use rand::{Rng as _, SeedableRng as _, rngs::StdRng};
@@ -369,6 +369,18 @@ impl LanguageModelProvider for CloudLanguageModelProvider {
.into()
}
+ fn configuration_view_v2(
+ &self,
+ target_agent: language_model::ConfigurationViewTargetAgent,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> ProviderConfigurationView {
+ // The Zed sign-in/plan control is small enough that sending users to a
+ // dedicated sub-page just to reach it would be annoying, so render it
+ // inline even though it isn't an API-key field.
+ ProviderConfigurationView::Inline(self.configuration_view(target_agent, window, cx))
+ }
+
fn reset_credentials(&self, _cx: &mut App) -> Task<Result<()>> {
Task::ready(Ok(()))
}
diff --git a/crates/language_models/src/provider/copilot_chat.rs b/crates/language_models/src/provider/copilot_chat.rs
index 21d358428bd..0d3b38d3115 100644
--- a/crates/language_models/src/provider/copilot_chat.rs
+++ b/crates/language_models/src/provider/copilot_chat.rs
@@ -25,7 +25,8 @@ use language_model::{
LanguageModelName, LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
LanguageModelProviderState, LanguageModelRequest, LanguageModelRequestMessage,
LanguageModelToolChoice, LanguageModelToolResultContent, LanguageModelToolSchemaFormat,
- LanguageModelToolUse, MessageContent, RateLimiter, Role, StopReason, TokenUsage,
+ LanguageModelToolUse, MessageContent, ProviderConfigurationView, RateLimiter, Role, StopReason,
+ TokenUsage,
};
use settings::SettingsStore;
use ui::prelude::*;
@@ -196,6 +197,17 @@ impl LanguageModelProvider for CopilotChatLanguageModelProvider {
.into()
}
+ fn configuration_view_v2(
+ &self,
+ target_agent: language_model::ConfigurationViewTargetAgent,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> ProviderConfigurationView {
+ // GitHub Copilot's control is just a sign-in button, so render it inline
+ // rather than behind a sub-page.
+ ProviderConfigurationView::Inline(self.configuration_view(target_agent, window, cx))
+ }
+
fn reset_credentials(&self, _cx: &mut App) -> Task<Result<()>> {
Task::ready(Err(anyhow!(
"Signing out of GitHub Copilot Chat is currently not supported."
diff --git a/crates/language_models/src/provider/deepseek.rs b/crates/language_models/src/provider/deepseek.rs
index a23afc52969..48096f16849 100644
--- a/crates/language_models/src/provider/deepseek.rs
+++ b/crates/language_models/src/provider/deepseek.rs
@@ -12,8 +12,8 @@ use language_model::{
LanguageModelCompletionEvent, LanguageModelEffortLevel, LanguageModelId, LanguageModelName,
LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
- LanguageModelToolResultContent, LanguageModelToolUse, MessageContent, RateLimiter, Role,
- StopReason, TokenUsage, env_var,
+ LanguageModelToolResultContent, LanguageModelToolUse, MessageContent,
+ ProviderConfigurationView, RateLimiter, Role, StopReason, TokenUsage, env_var,
};
pub use settings::DeepseekAvailableModel as AvailableModel;
use settings::{Settings, SettingsStore};
@@ -211,6 +211,30 @@ impl LanguageModelProvider for DeepSeekLanguageModelProvider {
self.state
.update(cx, |state, cx| state.set_api_key(None, cx))
}
+
+ fn configuration_view_v2(
+ &self,
+ _target_agent: language_model::ConfigurationViewTargetAgent,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> ProviderConfigurationView {
+ let state = self.state.clone();
+ ProviderConfigurationView::Inline(
+ cx.new(|cx| {
+ crate::ApiKeyEditor::new(
+ state,
+ "https://platform.deepseek.com/api_keys",
+ "Paste your DeepSeek API key",
+ |state, _cx| crate::api_key_status(&state.api_key_state),
+ |state, key, cx| state.update(cx, |state, cx| state.set_api_key(Some(key), cx)),
+ |state, cx| state.update(cx, |state, cx| state.set_api_key(None, cx)),
+ window,
+ cx,
+ )
+ })
+ .into(),
+ )
+ }
}
pub struct DeepSeekLanguageModel {
diff --git a/crates/language_models/src/provider/google.rs b/crates/language_models/src/provider/google.rs
index 392a81454bb..7ea54a51ba3 100644
--- a/crates/language_models/src/provider/google.rs
+++ b/crates/language_models/src/provider/google.rs
@@ -9,6 +9,7 @@ use http_client::{CustomHeaders, HttpClient};
use language_model::{
AuthenticateError, ConfigurationViewTargetAgent, EnvVar, LanguageModelCompletionError,
LanguageModelCompletionEvent, LanguageModelToolChoice, LanguageModelToolSchemaFormat,
+ ProviderConfigurationView,
};
use language_model::{
GOOGLE_PROVIDER_ID, GOOGLE_PROVIDER_NAME, IconOrSvg, LanguageModel, LanguageModelEffortLevel,
@@ -235,6 +236,30 @@ impl LanguageModelProvider for GoogleLanguageModelProvider {
self.state
.update(cx, |state, cx| state.set_api_key(None, cx))
}
+
+ fn configuration_view_v2(
+ &self,
+ _target_agent: language_model::ConfigurationViewTargetAgent,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> ProviderConfigurationView {
+ let state = self.state.clone();
+ ProviderConfigurationView::Inline(
+ cx.new(|cx| {
+ crate::ApiKeyEditor::new(
+ state,
+ "https://aistudio.google.com/app/apikey",
+ "AIza...",
+ |state, _cx| crate::api_key_status(&state.api_key_state),
+ |state, key, cx| state.update(cx, |state, cx| state.set_api_key(Some(key), cx)),
+ |state, cx| state.update(cx, |state, cx| state.set_api_key(None, cx)),
+ window,
+ cx,
+ )
+ })
+ .into(),
+ )
+ }
}
pub struct GoogleLanguageModel {
diff --git a/crates/language_models/src/provider/mistral.rs b/crates/language_models/src/provider/mistral.rs
index aa7e4820f77..24afcb669b5 100644
--- a/crates/language_models/src/provider/mistral.rs
+++ b/crates/language_models/src/provider/mistral.rs
@@ -10,7 +10,8 @@ use language_model::{
LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolResultContent,
- LanguageModelToolUse, MessageContent, RateLimiter, Role, StopReason, TokenUsage, env_var,
+ LanguageModelToolUse, MessageContent, ProviderConfigurationView, RateLimiter, Role, StopReason,
+ TokenUsage, env_var,
};
pub use mistral::{MISTRAL_API_URL, StreamResponse};
pub use settings::MistralAvailableModel as AvailableModel;
@@ -235,6 +236,30 @@ impl LanguageModelProvider for MistralLanguageModelProvider {
self.state
.update(cx, |state, cx| state.set_api_key(None, cx))
}
+
+ fn configuration_view_v2(
+ &self,
+ _target_agent: language_model::ConfigurationViewTargetAgent,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> ProviderConfigurationView {
+ let state = self.state.clone();
+ ProviderConfigurationView::Inline(
+ cx.new(|cx| {
+ crate::ApiKeyEditor::new(
+ state,
+ "https://console.mistral.ai/api-keys",
+ "Paste your Mistral API key",
+ |state, _cx| crate::api_key_status(&state.api_key_state),
+ |state, key, cx| state.update(cx, |state, cx| state.set_api_key(Some(key), cx)),
+ |state, cx| state.update(cx, |state, cx| state.set_api_key(None, cx)),
+ window,
+ cx,
+ )
+ })
+ .into(),
+ )
+ }
}
pub struct MistralLanguageModel {
diff --git a/crates/language_models/src/provider/open_ai.rs b/crates/language_models/src/provider/open_ai.rs
index 83a1505bdf6..e60a1f08ccc 100644
--- a/crates/language_models/src/provider/open_ai.rs
+++ b/crates/language_models/src/provider/open_ai.rs
@@ -9,7 +9,8 @@ use language_model::{
LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelEffortLevel,
LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
- LanguageModelToolChoice, OPEN_AI_PROVIDER_ID, OPEN_AI_PROVIDER_NAME, RateLimiter, env_var,
+ LanguageModelToolChoice, OPEN_AI_PROVIDER_ID, OPEN_AI_PROVIDER_NAME, ProviderConfigurationView,
+ RateLimiter, env_var,
};
use menu;
use open_ai::{
@@ -217,6 +218,30 @@ impl LanguageModelProvider for OpenAiLanguageModelProvider {
.update(cx, |state, cx| state.set_api_key(None, cx))
}
+ fn configuration_view_v2(
+ &self,
+ _target_agent: language_model::ConfigurationViewTargetAgent,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> ProviderConfigurationView {
+ let state = self.state.clone();
+ ProviderConfigurationView::Inline(
+ cx.new(|cx| {
+ crate::ApiKeyEditor::new(
+ state,
+ "https://platform.openai.com/api-keys",
+ "sk-...",
+ |state, _cx| crate::api_key_status(&state.api_key_state),
+ |state, key, cx| state.update(cx, |state, cx| state.set_api_key(Some(key), cx)),
+ |state, cx| state.update(cx, |state, cx| state.set_api_key(None, cx)),
+ window,
+ cx,
+ )
+ })
+ .into(),
+ )
+ }
+
fn fast_mode_confirmation(&self, _cx: &App) -> Option<FastModeConfirmation> {
Some(FastModeConfirmation {
title: "Enable Fast Mode for OpenAI?".into(),
diff --git a/crates/language_models/src/provider/open_router.rs b/crates/language_models/src/provider/open_router.rs
index 36dd69f928d..9fcb29b1fdf 100644
--- a/crates/language_models/src/provider/open_router.rs
+++ b/crates/language_models/src/provider/open_router.rs
@@ -9,8 +9,8 @@ use language_model::{
LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolResultContent,
- LanguageModelToolSchemaFormat, LanguageModelToolUse, MessageContent, RateLimiter, Role,
- StopReason, TokenUsage, env_var,
+ LanguageModelToolSchemaFormat, LanguageModelToolUse, MessageContent, ProviderConfigurationView,
+ RateLimiter, Role, StopReason, TokenUsage, env_var,
};
use open_router::{
Model, ModelMode as OpenRouterModelMode, OPEN_ROUTER_API_URL, ResponseStreamEvent, list_models,
@@ -272,6 +272,30 @@ impl LanguageModelProvider for OpenRouterLanguageModelProvider {
self.state
.update(cx, |state, cx| state.set_api_key(None, cx))
}
+
+ fn configuration_view_v2(
+ &self,
+ _target_agent: language_model::ConfigurationViewTargetAgent,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> ProviderConfigurationView {
+ let state = self.state.clone();
+ ProviderConfigurationView::Inline(
+ cx.new(|cx| {
+ crate::ApiKeyEditor::new(
+ state,
+ "https://openrouter.ai/keys",
+ "sk-or-...",
+ |state, _cx| crate::api_key_status(&state.api_key_state),
+ |state, key, cx| state.update(cx, |state, cx| state.set_api_key(Some(key), cx)),
+ |state, cx| state.update(cx, |state, cx| state.set_api_key(None, cx)),
+ window,
+ cx,
+ )
+ })
+ .into(),
+ )
+ }
}
pub struct OpenRouterLanguageModel {
diff --git a/crates/language_models/src/provider/vercel_ai_gateway.rs b/crates/language_models/src/provider/vercel_ai_gateway.rs
index 694972e48ae..21f0b7c7669 100644
--- a/crates/language_models/src/provider/vercel_ai_gateway.rs
+++ b/crates/language_models/src/provider/vercel_ai_gateway.rs
@@ -10,8 +10,8 @@ use language_model::{
ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
- LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolSchemaFormat, RateLimiter,
- env_var,
+ LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolSchemaFormat,
+ ProviderConfigurationView, RateLimiter, env_var,
};
use open_ai::ResponseStreamEvent;
use serde::Deserialize;
@@ -260,6 +260,30 @@ impl LanguageModelProvider for VercelAiGatewayLanguageModelProvider {
self.state
.update(cx, |state, cx| state.set_api_key(None, cx))
}
+
+ fn configuration_view_v2(
+ &self,
+ _target_agent: language_model::ConfigurationViewTargetAgent,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> ProviderConfigurationView {
+ let state = self.state.clone();
+ ProviderConfigurationView::Inline(
+ cx.new(|cx| {
+ crate::ApiKeyEditor::new(
+ state,
+ "https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys&title=Go+to+AI+Gateway",
+ "Paste your Vercel AI Gateway API key",
+ |state, _cx| crate::api_key_status(&state.api_key_state),
+ |state, key, cx| state.update(cx, |state, cx| state.set_api_key(Some(key), cx)),
+ |state, cx| state.update(cx, |state, cx| state.set_api_key(None, cx)),
+ window,
+ cx,
+ )
+ })
+ .into(),
+ )
+ }
}
pub struct VercelAiGatewayLanguageModel {
diff --git a/crates/language_models/src/provider/x_ai.rs b/crates/language_models/src/provider/x_ai.rs
index 8ac48213c0e..f66e31aa839 100644
--- a/crates/language_models/src/provider/x_ai.rs
+++ b/crates/language_models/src/provider/x_ai.rs
@@ -9,7 +9,7 @@ use language_model::{
LanguageModelCompletionEvent, LanguageModelEffortLevel, LanguageModelId, LanguageModelName,
LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
- LanguageModelToolSchemaFormat, RateLimiter, env_var,
+ LanguageModelToolSchemaFormat, ProviderConfigurationView, RateLimiter, env_var,
};
use open_ai::ResponseStreamEvent;
pub use settings::XaiAvailableModel as AvailableModel;
@@ -207,6 +207,30 @@ impl LanguageModelProvider for XAiLanguageModelProvider {
self.state
.update(cx, |state, cx| state.set_api_key(None, cx))
}
+
+ fn configuration_view_v2(
+ &self,
+ _target_agent: language_model::ConfigurationViewTargetAgent,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> ProviderConfigurationView {
+ let state = self.state.clone();
+ ProviderConfigurationView::Inline(
+ cx.new(|cx| {
+ crate::ApiKeyEditor::new(
+ state,
+ "https://console.x.ai/team/default/api-keys",
+ "xai-...",
+ |state, _cx| crate::api_key_status(&state.api_key_state),
+ |state, key, cx| state.update(cx, |state, cx| state.set_api_key(Some(key), cx)),
+ |state, cx| state.update(cx, |state, cx| state.set_api_key(None, cx)),
+ window,
+ cx,
+ )
+ })
+ .into(),
+ )
+ }
}
pub struct XAiLanguageModel {
diff --git a/crates/project/src/context_server_store.rs b/crates/project/src/context_server_store.rs
index 8dab25d8ab4..ef5077d53a2 100644
--- a/crates/project/src/context_server_store.rs
+++ b/crates/project/src/context_server_store.rs
@@ -535,6 +535,33 @@ impl ContextServerStore {
self.servers.get(id).map(|state| state.configuration())
}
+ /// Returns the configured settings for a server, if it is present in the user
+ /// or project settings. This is available regardless of whether the server is
+ /// currently running, unlike [`Self::configuration_for_server`].
+ pub fn settings_for_server(&self, id: &ContextServerId) -> Option<&ContextServerSettings> {
+ self.context_server_settings.get(&id.0)
+ }
+
+ /// Returns whether a server is provided by an extension (as opposed to a
+ /// custom Stdio/HTTP server configured directly in settings).
+ ///
+ /// This is derived from the configured settings rather than the runtime
+ /// configuration, so it stays correct even when a custom server is disabled
+ /// or has not been started yet (in which case it has no runtime state).
+ pub fn is_extension_provided(&self, id: &ContextServerId, cx: &App) -> bool {
+ match self.context_server_settings.get(&id.0) {
+ Some(ContextServerSettings::Stdio { .. } | ContextServerSettings::Http { .. }) => false,
+ Some(ContextServerSettings::Extension { .. }) => true,
+ // No custom settings entry: the server can only originate from an
+ // extension descriptor in the registry.
+ None => self
+ .registry
+ .read(cx)
+ .context_server_descriptor(&id.0)
+ .is_some(),
+ }
+ }
+
/// Returns a sorted slice of available unique context server IDs. Within the
/// slice, context servers which have `mcp-server-` as a prefix in their ID will
/// appear after servers that do not have this prefix in their ID.
diff --git a/crates/settings_ui/Cargo.toml b/crates/settings_ui/Cargo.toml
index cdd1b71f033..bb2f9c1f2b9 100644
--- a/crates/settings_ui/Cargo.toml
+++ b/crates/settings_ui/Cargo.toml
@@ -24,12 +24,16 @@ audio.workspace = true
cloud_api_types.workspace = true
component.workspace = true
codestral.workspace = true
+collections.workspace = true
+context_server.workspace = true
copilot.workspace = true
copilot_ui.workspace = true
cpal.workspace = true
edit_prediction.workspace = true
edit_prediction_ui.workspace = true
editor.workspace = true
+extension.workspace = true
+extension_host.workspace = true
fs.workspace = true
feature_flags.workspace = true
futures.workspace = true
@@ -39,6 +43,7 @@ heck.workspace = true
http_client.workspace = true
itertools.workspace = true
language.workspace = true
+language_model.workspace = true
log.workspace = true
menu.workspace = true
paths.workspace = true
@@ -60,6 +65,7 @@ telemetry.workspace = true
theme.workspace = true
theme_settings.workspace = true
ui.workspace = true
+url.workspace = true
ui_input.workspace = true
util.workspace = true
workspace.workspace = true
diff --git a/crates/settings_ui/src/page_data.rs b/crates/settings_ui/src/page_data.rs
index 57038d8a6ce..5f224e8b1f5 100644
--- a/crates/settings_ui/src/page_data.rs
+++ b/crates/settings_ui/src/page_data.rs
@@ -13,7 +13,8 @@ use crate::{
ActionLink, DynamicItem, PROJECT, SettingField, SettingItem, SettingsFieldMetadata,
SettingsPage, SettingsPageItem, SubPageLink, USER, active_language, all_language_names,
pages::{
- open_audio_test_window, render_edit_prediction_setup_page, render_skills_setup_page,
+ open_audio_test_window, render_edit_prediction_setup_page, render_external_agents_page,
+ render_llm_providers_page, render_mcp_servers_page, render_skills_setup_page,
render_tool_permissions_setup_page,
},
};
@@ -75,7 +76,7 @@ pub(crate) fn settings_data(cx: &App) -> Vec<SettingsPage> {
terminal_page(),
version_control_page(),
collaboration_page(),
- ai_page(),
+ ai_page(cx),
network_page(),
developer_page(cx),
]
@@ -7825,7 +7826,7 @@ fn collaboration_page() -> SettingsPage {
}
}
-fn ai_page() -> SettingsPage {
+fn ai_page(cx: &App) -> SettingsPage {
fn general_section() -> [SettingsPageItem; 3] {
[
SettingsPageItem::SectionHeader("General"),
@@ -7860,9 +7861,28 @@ fn ai_page() -> SettingsPage {
]
}
- fn agent_configuration_section() -> Box<[SettingsPageItem]> {
- let mut items = vec![
- SettingsPageItem::SectionHeader("Agent Configuration"),
+ fn agent_configuration_section(cx: &App) -> Box<[SettingsPageItem]> {
+ use feature_flags::FeatureFlagAppExt as _;
+
+ // The LLM provider and MCP server pages are gated behind a feature flag
+ // while their configuration is being moved out of the agent panel.
+ let agent_settings_ui_enabled = cx.has_flag::<feature_flags::AgentSettingsUiFeatureFlag>();
+
+ let mut items = vec![SettingsPageItem::SectionHeader("Agent Configuration")];
+
+ if agent_settings_ui_enabled {
+ items.push(SettingsPageItem::SubPageLink(SubPageLink {
+ title: "LLM Providers".into(),
+ r#type: Default::default(),
+ json_path: Some("llm_providers"),
+ description: Some("Configure API keys and settings for LLM providers.".into()),
+ in_json: false,
+ files: USER,
+ render: render_llm_providers_page,
+ }));
+ }
+
+ items.extend([
SettingsPageItem::SubPageLink(SubPageLink {
title: "Skills".into(),
r#type: Default::default(),
@@ -7881,7 +7901,33 @@ fn ai_page() -> SettingsPage {
files: USER,
render: render_tool_permissions_setup_page,
}),
- ];
+ ]);
+
+ if agent_settings_ui_enabled {
+ items.push(SettingsPageItem::SubPageLink(SubPageLink {
+ title: "MCP Servers".into(),
+ r#type: Default::default(),
+ json_path: Some("context_servers"),
+ description: Some(
+ "View, add, configure, and remove Model Context Protocol servers.".into(),
+ ),
+ in_json: false,
+ files: USER,
+ render: render_mcp_servers_page,
+ }));
+ items.push(SettingsPageItem::SubPageLink(SubPageLink {
+ title: "External Agents".into(),
+ r#type: Default::default(),
+ json_path: Some("agent_servers"),
+ description: Some(
+ "View, add, and remove agents connected through the Agent Client Protocol."
+ .into(),
+ ),
+ in_json: false,
+ files: USER,
+ render: render_external_agents_page,
+ }));
+ }
items.extend([
SettingsPageItem::SettingItem(SettingItem {
@@ -8265,7 +8311,7 @@ fn ai_page() -> SettingsPage {
title: "AI",
items: concat_sections![
general_section(),
- agent_configuration_section(),
+ agent_configuration_section(cx),
context_servers_section(),
edit_prediction_language_settings_section(),
edit_prediction_display_sub_section()
diff --git a/crates/settings_ui/src/pages.rs b/crates/settings_ui/src/pages.rs
index 7e5020779a0..83943a8087c 100644
--- a/crates/settings_ui/src/pages.rs
+++ b/crates/settings_ui/src/pages.rs
@@ -1,7 +1,10 @@
mod audio_input_output_setup;
mod audio_test_window;
mod edit_prediction_provider_setup;
+mod external_agents_page;
mod feature_flags;
+mod llm_providers_page;
+mod mcp_servers_page;
mod skill_creator;
mod skills_setup;
mod tool_permissions_setup;
@@ -11,7 +14,10 @@ pub(crate) use audio_input_output_setup::{
};
pub(crate) use audio_test_window::open_audio_test_window;
pub(crate) use edit_prediction_provider_setup::render_edit_prediction_setup_page;
+pub(crate) use external_agents_page::{CustomAgentForm, render_external_agents_page};
pub(crate) use feature_flags::render_feature_flags_page;
+pub(crate) use llm_providers_page::render_llm_providers_page;
+pub(crate) use mcp_servers_page::{McpServerForm, render_mcp_servers_page};
pub use skill_creator::SkillCreatorOpenMode;
pub(crate) use skill_creator::{
SkillCreatorEvent, SkillCreatorPage, render_skill_creator_page, skill_url_from_clipboard,
diff --git a/crates/settings_ui/src/pages/external_agents_page.rs b/crates/settings_ui/src/pages/external_agents_page.rs
new file mode 100644
index 00000000000..3369b58be0b
--- /dev/null
+++ b/crates/settings_ui/src/pages/external_agents_page.rs
@@ -0,0 +1,1200 @@
+use std::ops::Range;
+
+use anyhow::Result;
+use collections::HashMap;
+use editor::{Editor, MultiBufferOffset, SelectionEffects, scroll::Autoscroll};
+use gpui::{
+ AsyncWindowContext, Entity, FocusHandle, Focusable as _, ReadGlobal as _, ScrollHandle,
+ WeakEntity, WindowHandle, prelude::*,
+};
+use itertools::Itertools as _;
+use project::agent_server_store::{AgentId, AgentServerStore, ExternalAgentSource};
+use settings::{CustomAgentServerSettings, SettingsStore, update_settings_file};
+use ui::{
+ AiSettingItem, AiSettingItemSource, AiSettingItemStatus, ContextMenu, ContextMenuEntry,
+ Divider, DividerColor, PopoverMenu, Tooltip, prelude::*,
+};
+use util::ResultExt as _;
+use workspace::{MultiWorkspace, Workspace, create_and_open_local_file};
+use zed_actions::OpenBrowser;
+
+use crate::SettingsWindow;
+
+pub(crate) fn render_external_agents_page(
+ settings_window: &SettingsWindow,
+ scroll_handle: &ScrollHandle,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> AnyElement {
+ let agent_server_store = get_agent_server_store(settings_window, cx);
+
+ let agent_list = if let Some(store) = agent_server_store.as_ref() {
+ let agents = collect_agents(store, cx);
+ if agents.is_empty() {
+ render_empty_state(cx)
+ } else {
+ render_agent_list(agents, cx)
+ }
+ } else {
+ render_no_project_state(cx)
+ };
+
+ let add_agent_popover = render_add_agent_popover(settings_window, window, cx);
+
+ v_flex()
+ .id("external-agents-page")
+ .size_full()
+ .pt_2p5()
+ .px_8()
+ .pb_16()
+ .track_scroll(scroll_handle)
+ .overflow_y_scroll()
+ .child(
+ h_flex()
+ .w_full()
+ .justify_between()
+ .items_center()
+ .mb_4()
+ .child(
+ v_flex()
+ .child(Label::new("External Agents").size(LabelSize::Large))
+ .child(
+ Label::new("All agents connected through the Agent Client Protocol.")
+ .size(LabelSize::Small)
+ .color(Color::Muted),
+ ),
+ )
+ .child(add_agent_popover),
+ )
+ .child(agent_list)
+ .into_any_element()
+}
+
+fn get_agent_server_store(
+ settings_window: &SettingsWindow,
+ cx: &App,
+) -> Option<Entity<AgentServerStore>> {
+ let original_window = settings_window.original_window.as_ref()?;
+ let multi_workspace = original_window.read(cx).ok()?;
+ let workspace = multi_workspace.workspaces().next()?;
+ let project = workspace.read(cx).project().clone();
+ Some(project.read(cx).agent_server_store().clone())
+}
+
+/// An external agent listed on the page, paired with the data needed to render
+/// its row: the optional extension-provided icon path, a human-readable name,
+/// and where the agent came from.
+type AgentRow = (
+ AgentId,
+ Option<SharedString>,
+ SharedString,
+ ExternalAgentSource,
+);
+
+fn collect_agents(store: &Entity<AgentServerStore>, cx: &App) -> Vec<AgentRow> {
+ let store = store.read(cx);
+ store
+ .external_agents()
+ .cloned()
+ .collect::<Vec<_>>()
+ .into_iter()
+ .map(|name| {
+ let icon = store.agent_icon(&name);
+ let display_name = store
+ .agent_display_name(&name)
+ .unwrap_or_else(|| name.0.clone());
+ let source = store.agent_source(&name).unwrap_or_default();
+ (name, icon, display_name, source)
+ })
+ .sorted_unstable_by_key(|(_, _, display_name, _)| display_name.to_lowercase())
+ .collect()
+}
+
+/// Reads the raw, user-configured settings for a custom agent so the edit form
+/// can be pre-filled. Reading the parsed settings (rather than the resolved
+/// runtime server) keeps this resilient to malformed `settings.json`: the
+/// settings layer drops individual bad fields instead of failing.
+fn custom_agent_settings(id: &AgentId, cx: &App) -> Option<CustomAgentServerSettings> {
+ SettingsStore::global(cx)
+ .get_content_for_file(settings::SettingsFile::User)?
+ .agent_servers
+ .as_ref()?
+ .get(id.0.as_ref())
+ .cloned()
+}
+
+fn render_empty_state(cx: &App) -> AnyElement {
+ h_flex()
+ .p_4()
+ .justify_center()
+ .border_1()
+ .border_dashed()
+ .border_color(cx.theme().colors().border.opacity(0.6))
+ .rounded_sm()
+ .child(
+ Label::new("No external agents added yet. Click \"Add Agent\" to get started.")
+ .color(Color::Muted)
+ .size(LabelSize::Small),
+ )
+ .into_any_element()
+}
+
+fn render_no_project_state(cx: &App) -> AnyElement {
+ h_flex()
+ .p_4()
+ .justify_center()
+ .border_1()
+ .border_dashed()
+ .border_color(cx.theme().colors().border.opacity(0.6))
+ .rounded_sm()
+ .child(
+ Label::new("No active project found. Open a workspace to manage external agents.")
+ .color(Color::Muted)
+ .size(LabelSize::Small),
+ )
+ .into_any_element()
+}
+
+fn render_agent_list(agents: Vec<AgentRow>, cx: &mut Context<SettingsWindow>) -> AnyElement {
+ v_flex()
+ .w_full()
+ .gap_1()
+ .children(itertools::intersperse_with(
+ agents.into_iter().map(|(id, icon, display_name, source)| {
+ render_agent(id, icon, display_name, source, cx).into_any_element()
+ }),
+ || {
+ Divider::horizontal()
+ .color(DividerColor::BorderFaded)
+ .into_any_element()
+ },
+ ))
+ .into_any_element()
+}
+
+fn render_agent(
+ id: AgentId,
+ icon: Option<SharedString>,
+ display_name: SharedString,
+ source: ExternalAgentSource,
+ cx: &mut Context<SettingsWindow>,
+) -> impl IntoElement {
+ let id_string = id.0.clone();
+
+ let icon = match icon {
+ Some(icon_path) => Icon::from_external_svg(icon_path),
+ None => Icon::new(IconName::Sparkle),
+ }
+ .size(IconSize::Small)
+ .color(Color::Muted);
+
+ let source_kind = match source {
+ ExternalAgentSource::Registry => AiSettingItemSource::Registry,
+ ExternalAgentSource::Custom => AiSettingItemSource::Custom,
+ };
+
+ // Only custom agents are editable here; registry agents are managed via the
+ // ACP registry and only support removal.
+ let configure_button = (source == ExternalAgentSource::Custom).then(|| {
+ IconButton::new(
+ SharedString::from(format!("configure-{}", id_string)),
+ IconName::Settings,
+ )
+ .icon_color(Color::Muted)
+ .icon_size(IconSize::Small)
+ .tab_index(0isize)
+ .tooltip(Tooltip::text("Configure Agent"))
+ .on_click(cx.listener({
+ let id = id.clone();
+ move |this, _event, window, cx| {
+ let existing =
+ custom_agent_settings(&id, cx).map(|settings| (id.clone(), settings));
+ open_custom_agent_form(this, existing, window, cx);
+ }
+ }))
+ });
+
+ let remove_tooltip = match source {
+ ExternalAgentSource::Registry => "Remove Registry Agent",
+ ExternalAgentSource::Custom => "Remove Custom Agent",
+ };
+
+ let remove_button = IconButton::new(
+ SharedString::from(format!("uninstall-{}", id_string)),
+ IconName::Trash,
+ )
+ .icon_color(Color::Muted)
+ .icon_size(IconSize::Small)
+ .tab_index(0isize)
+ .tooltip(Tooltip::text(remove_tooltip))
+ .on_click(move |_event, _window, cx| {
+ remove_agent(&id, source, cx);
+ });
+
+ // The connection status of an external agent is tracked per agent-panel
+ // session (via the agent panel's `AgentConnectionStore`), which isn't
+ // available from the settings window. We therefore render a neutral status;
+ // the row still shows the agent's source and supports configure/removal.
+ AiSettingItem::new(
+ id_string,
+ display_name,
+ AiSettingItemStatus::Stopped,
+ source_kind,
+ )
+ .icon(icon)
+ .when_some(configure_button, |this, button| this.action(button))
+ .action(remove_button)
+}
+
+fn remove_agent(id: &AgentId, source: ExternalAgentSource, cx: &mut App) {
+ let fs = <dyn fs::Fs>::global(cx);
+ let id = id.clone();
+ update_settings_file(fs, cx, move |settings, _| {
+ let Some(agent_servers) = settings.agent_servers.as_mut() else {
+ return;
+ };
+ // Only remove the entry if it still matches the source we rendered, so a
+ // stale row can't clobber an entry that was changed in the meantime.
+ let matches_source = agent_servers
+ .get(id.0.as_ref())
+ .is_some_and(|entry| match source {
+ ExternalAgentSource::Registry => {
+ matches!(entry, CustomAgentServerSettings::Registry { .. })
+ }
+ ExternalAgentSource::Custom => {
+ matches!(entry, CustomAgentServerSettings::Custom { .. })
+ }
+ });
+ if matches_source {
+ agent_servers.remove(id.0.as_ref());
+ }
+ });
+}
+
+fn render_add_agent_popover(
+ settings_window: &SettingsWindow,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> impl IntoElement {
+ let original_window = settings_window.original_window;
+ // Stable handle so the button keeps focus state across renders and can show a
+ // focus ring even when the page is opened (and the button auto-focused) via a
+ // mouse click, where `focus_visible` styling is suppressed.
+ let focus_handle = settings_window
+ .external_agent_add_focus_handle
+ .clone()
+ .tab_index(0)
+ .tab_stop(true);
+ let border_color = focus_ring_color(&focus_handle, window, cx);
+ let settings_window = cx.entity().downgrade();
+
+ let popover = PopoverMenu::new("add-agent-server-popover")
+ .trigger(
+ Button::new("add-agent", "Add Agent")
+ .style(ButtonStyle::Outlined)
+ .track_focus(&focus_handle)
+ .start_icon(
+ Icon::new(IconName::Plus)
+ .size(IconSize::Small)
+ .color(Color::Muted),
+ )
+ .label_size(LabelSize::Small),
+ )
+ .anchor(gpui::Anchor::TopRight)
+ .menu(move |window, cx| {
+ let settings_window = settings_window.clone();
+ Some(ContextMenu::build(window, cx, move |menu, _window, _cx| {
+ menu.entry("Install from Registry", None, move |_window, cx| {
+ if let Some(original_window) = original_window {
+ cx.activate(true);
+ original_window
+ .update(cx, |_, window, cx| {
+ window.activate_window();
+ window.dispatch_action(Box::new(zed_actions::AcpRegistry), cx);
+ })
+ .log_err();
+ }
+ })
+ .entry("Add Custom Agent", None, move |window, cx| {
+ settings_window
+ .update(cx, |this, cx| {
+ open_custom_agent_form(this, None, window, cx);
+ })
+ .log_err();
+ })
+ .separator()
+ .header("Learn More")
+ .item(
+ ContextMenuEntry::new("ACP Docs")
+ .icon(IconName::ArrowUpRight)
+ .icon_color(Color::Muted)
+ .icon_position(IconPosition::End)
+ .handler(move |window, cx| {
+ window.dispatch_action(
+ Box::new(OpenBrowser {
+ url: "https://agentclientprotocol.com/".into(),
+ }),
+ cx,
+ );
+ }),
+ )
+ }))
+ });
+
+ div()
+ .rounded_md()
+ .border_1()
+ .border_color(border_color)
+ .child(popover)
+}
+
+// === Custom external agent add/edit form ===
+
+struct KeyValueRow {
+ key: Entity<Editor>,
+ value: Entity<Editor>,
+}
+
+/// Editor-backed state for the custom external agent add/edit form.
+pub(crate) struct CustomAgentForm {
+ /// `Some` when editing an existing agent (used to remove the old entry on rename).
+ original_id: Option<AgentId>,
+ name: Entity<Editor>,
+ command: Entity<Editor>,
+ args: Entity<Editor>,
+ env: Vec<KeyValueRow>,
+ /// Advanced fields not surfaced by the form. They're preserved verbatim so
+ /// editing the basic settings doesn't drop a user's hand-written config.
+ default_mode: Option<String>,
+ default_config_options: HashMap<String, String>,
+ favorite_config_option_values: HashMap<String, Vec<String>>,
+ /// Stable handles for the Cancel/Save buttons so they can render a focus
+ /// ring. `Filled`/`Subtle` buttons only get a subtle `focus_visible`
+ /// background change otherwise, which is hard to see.
+ cancel_focus_handle: FocusHandle,
+ save_focus_handle: FocusHandle,
+ error: Option<SharedString>,
+}
+
+impl CustomAgentForm {
+ fn new(
+ existing: Option<(AgentId, CustomAgentServerSettings)>,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+ ) -> Self {
+ let original_id = existing.as_ref().map(|(id, _)| id.clone());
+ let name_initial = original_id.as_ref().map(|id| id.0.to_string());
+
+ let mut command_initial = None;
+ let mut args_initial = None;
+ let mut env = Vec::new();
+ let mut default_mode = None;
+ let mut default_config_options = HashMap::default();
+ let mut favorite_config_option_values = HashMap::default();
+
+ // Pre-fill from the raw settings so invalid values typed directly into
+ // settings.json still load into the form for correction.
+ if let Some((_, settings)) = existing.as_ref() {
+ match settings {
+ CustomAgentServerSettings::Custom {
+ path,
+ args,
+ env: env_map,
+ default_mode: mode,
+ default_config_options: config_options,
+ favorite_config_option_values: favorites,
+ } => {
+ command_initial = Some(path.to_string_lossy().to_string());
+ if !args.is_empty() {
+ args_initial = Some(args.join(" "));
+ }
+ for (key, value) in sorted_pairs(env_map) {
+ env.push(new_kv_row(Some(&key), Some(&value), window, cx));
+ }
+ default_mode = mode.clone();
+ default_config_options = config_options.clone();
+ favorite_config_option_values = favorites.clone();
+ }
+ CustomAgentServerSettings::Registry {
+ env: env_map,
+ default_mode: mode,
+ default_config_options: config_options,
+ favorite_config_option_values: favorites,
+ } => {
+ for (key, value) in sorted_pairs(env_map) {
+ env.push(new_kv_row(Some(&key), Some(&value), window, cx));
+ }
+ default_mode = mode.clone();
+ default_config_options = config_options.clone();
+ favorite_config_option_values = favorites.clone();
+ }
+ }
+ }
+
+ Self {
+ original_id,
+ name: new_input("my-agent", name_initial.as_deref(), window, cx),
+ command: new_input("/path/to/agent", command_initial.as_deref(), window, cx),
+ args: new_input("--flag value", args_initial.as_deref(), window, cx),
+ env,
+ default_mode,
+ default_config_options,
+ favorite_config_option_values,
+ cancel_focus_handle: cx.focus_handle(),
+ save_focus_handle: cx.focus_handle(),
+ error: None,
+ }
+ }
+}
+
+fn sorted_pairs(map: &HashMap<String, String>) -> Vec<(String, String)> {
+ let mut pairs: Vec<(String, String)> = map
+ .iter()
+ .map(|(key, value)| (key.clone(), value.clone()))
+ .collect();
+ pairs.sort_by(|a, b| a.0.cmp(&b.0));
+ pairs
+}
+
+fn new_input(
+ placeholder: &str,
+ initial: Option<&str>,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> Entity<Editor> {
+ let placeholder = placeholder.to_string();
+ let initial = initial.map(|text| text.to_string());
+ cx.new(|cx| {
+ let mut editor = Editor::single_line(window, cx);
+ editor.set_placeholder_text(placeholder.as_str(), window, cx);
+ if let Some(text) = initial {
+ editor.set_text(text, window, cx);
+ }
+ editor
+ })
+}
+
+fn new_kv_row(
+ key: Option<&str>,
+ value: Option<&str>,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> KeyValueRow {
+ KeyValueRow {
+ key: new_input("Key", key, window, cx),
+ value: new_input("Value", value, window, cx),
+ }
+}
+
+/// Creates the form state and pushes the form sub-page onto the stack.
+pub(crate) fn open_custom_agent_form(
+ settings_window: &mut SettingsWindow,
+ existing: Option<(AgentId, CustomAgentServerSettings)>,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) {
+ let is_edit = existing.is_some();
+ settings_window.custom_agent_form = Some(CustomAgentForm::new(existing, window, cx));
+
+ let title = if is_edit {
+ "Configure External Agent"
+ } else {
+ "Add Custom Agent"
+ };
+
+ settings_window.push_dynamic_sub_page(
+ title,
+ "Agent Configuration",
+ Some("agent_servers"),
+ false,
+ render_custom_agent_form_page,
+ window,
+ cx,
+ );
+}
+
+fn render_custom_agent_form_page(
+ settings_window: &SettingsWindow,
+ scroll_handle: &ScrollHandle,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> AnyElement {
+ let Some(form) = settings_window.custom_agent_form.as_ref() else {
+ return div().into_any_element();
+ };
+ let error = form.error.clone();
+
+ let fields = v_flex()
+ .w_full()
+ .gap_4()
+ .child(
+ crate::render_settings_item_layout(
+ settings_window,
+ "Agent Name",
+ "Required. A unique name used to identify this agent.",
+ input_box(&form.name, cx).into_any_element(),
+ None,
+ None,
+ None,
+ false,
+ cx,
+ )
+ .into_any_element(),
+ )
+ .child(
+ crate::render_settings_item_layout(
+ settings_window,
+ "Command",
+ "Required. Path to the executable that launches the agent.",
+ input_box(&form.command, cx).into_any_element(),
+ None,
+ None,
+ None,
+ false,
+ cx,
+ )
+ .into_any_element(),
+ )
+ .child(
+ crate::render_settings_item_layout(
+ settings_window,
+ "Arguments",
+ "Space-separated arguments passed to the command.",
+ input_box(&form.args, cx).into_any_element(),
+ None,
+ None,
+ None,
+ false,
+ cx,
+ )
+ .into_any_element(),
+ )
+ .child(render_env_section(settings_window, &form.env, cx))
+ .when_some(error, |this, error| this.child(render_form_error(error)))
+ .child(render_form_actions(form, window, cx));
+
+ v_flex()
+ .id("custom-agent-form-page")
+ .size_full()
+ .pt_2p5()
+ .px_8()
+ .pb_16()
+ .track_scroll(scroll_handle)
+ .overflow_y_scroll()
+ .child(fields)
+ .into_any_element()
+}
+
+fn input_box(editor: &Entity<Editor>, cx: &App) -> impl IntoElement {
+ let colors = cx.theme().colors();
+ // All form inputs share tab index 0, so tab order follows render (insertion)
+ // order. Tracking the editor's focus handle makes the field a tab stop and
+ // routes keyboard focus into the editor when tabbed to.
+ let focus_handle = editor.focus_handle(cx).tab_index(0).tab_stop(true);
+ h_flex()
+ .min_w_64()
+ .py_1()
+ .px_2()
+ .h_8()
+ .rounded_md()
+ .border_1()
+ .border_color(colors.border)
+ .bg(colors.editor_background)
+ .track_focus(&focus_handle)
+ .focus(|style| style.border_color(colors.border_focused))
+ .child(editor.clone())
+}
+
+fn render_env_section(
+ settings_window: &SettingsWindow,
+ rows: &[KeyValueRow],
+ cx: &mut Context<SettingsWindow>,
+) -> impl IntoElement {
+ // The right-hand control column is narrower than a full row, so each
+ // variable stacks its key above its value (with the remove affordance next
+ // to the value) to stay readable.
+ let control = v_flex()
+ .min_w_64()
+ .gap_2()
+ .children(rows.iter().enumerate().map(|(ix, row)| {
+ v_flex().gap_1().child(input_box(&row.key, cx)).child(
+ h_flex()
+ .gap_1()
+ .items_center()
+ .child(input_box(&row.value, cx))
+ .child(
+ IconButton::new(("custom-agent-env-remove", ix), IconName::Close)
+ .icon_size(IconSize::Small)
+ .icon_color(Color::Muted)
+ .tab_index(0isize)
+ .tooltip(Tooltip::text("Remove"))
+ .on_click(cx.listener(move |this, _, _window, cx| {
+ if let Some(form) = this.custom_agent_form.as_mut()
+ && ix < form.env.len()
+ {
+ form.env.remove(ix);
+ }
+ cx.notify();
+ })),
+ ),
+ )
+ }))
+ .child(
+ Button::new("custom-agent-env-add", "Add")
+ .style(ButtonStyle::Outlined)
+ .label_size(LabelSize::Small)
+ .tab_index(0isize)
+ .start_icon(
+ Icon::new(IconName::Plus)
+ .size(IconSize::Small)
+ .color(Color::Muted),
+ )
+ .on_click(cx.listener(move |this, _, window, cx| {
+ let row = new_kv_row(None, None, window, cx);
+ // Focus the new key so the user can type immediately and tab
+ // through the new row (key -> value -> ... -> Add button).
+ let key_handle = row.key.focus_handle(cx);
+ if let Some(form) = this.custom_agent_form.as_mut() {
+ form.env.push(row);
+ }
+ key_handle.focus(window, cx);
+ cx.notify();
+ })),
+ )
+ .into_any_element();
+
+ crate::render_settings_item_layout(
+ settings_window,
+ "Environment Variables",
+ "Environment variables provided to the agent process.",
+ control,
+ None,
+ None,
+ None,
+ false,
+ cx,
+ )
+ .into_any_element()
+}
+
+fn render_form_error(error: SharedString) -> impl IntoElement {
+ h_flex()
+ .w_full()
+ .gap_2()
+ .items_start()
+ .child(
+ Icon::new(IconName::XCircle)
+ .size(IconSize::Small)
+ .color(Color::Error),
+ )
+ .child(Label::new(error).size(LabelSize::Small).color(Color::Error))
+}
+
+fn render_form_actions(
+ form: &CustomAgentForm,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> impl IntoElement {
+ let cancel_handle = form.cancel_focus_handle.clone().tab_index(0).tab_stop(true);
+ let save_handle = form.save_focus_handle.clone().tab_index(0).tab_stop(true);
+ let cancel_border = focus_ring_color(&cancel_handle, window, cx);
+ let save_border = focus_ring_color(&save_handle, window, cx);
+
+ h_flex()
+ .w_full()
+ .gap_2()
+ .justify_end()
+ .pt_2()
+ .child(
+ div()
+ .rounded_md()
+ .border_1()
+ .border_color(cancel_border)
+ .child(
+ Button::new("custom-agent-form-cancel", "Cancel")
+ .style(ButtonStyle::Subtle)
+ .track_focus(&cancel_handle)
+ .on_click(cx.listener(|this, _, window, cx| {
+ this.custom_agent_form = None;
+ this.pop_sub_page(window, cx);
+ })),
+ ),
+ )
+ .child(
+ div()
+ .rounded_md()
+ .border_1()
+ .border_color(save_border)
+ .child(
+ Button::new("custom-agent-form-save", "Save")
+ .style(ButtonStyle::Filled)
+ .track_focus(&save_handle)
+ .on_click(cx.listener(|this, _, window, cx| {
+ save_custom_agent_form(this, window, cx);
+ })),
+ ),
+ )
+}
+
+/// Returns the border color for a button's focus ring: visible when focused
+/// (keyboard or programmatic), transparent otherwise.
+fn focus_ring_color(handle: &FocusHandle, window: &Window, cx: &App) -> gpui::Hsla {
+ if handle.is_focused(window) {
+ cx.theme().colors().border_focused
+ } else {
+ gpui::transparent_black()
+ }
+}
+
+fn save_custom_agent_form(
+ settings_window: &mut SettingsWindow,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) {
+ let built = {
+ let Some(form) = settings_window.custom_agent_form.as_ref() else {
+ return;
+ };
+ build_settings_from_form(form, cx)
+ };
+
+ let (id, original_id, content) = match built {
+ Ok(value) => value,
+ Err(error) => {
+ if let Some(form) = settings_window.custom_agent_form.as_mut() {
+ form.error = Some(error);
+ }
+ cx.notify();
+ return;
+ }
+ };
+
+ // Reject names that would collide with a *different* existing agent. This
+ // covers both adding a new agent and renaming an existing one.
+ let collides_with_other_agent =
+ get_agent_server_store(settings_window, cx).is_some_and(|store| {
+ let existing_ids = store
+ .read(cx)
+ .external_agents()
+ .cloned()
+ .collect::<Vec<_>>();
+ name_collides_with_other_agent(&id, original_id.as_ref(), &existing_ids)
+ });
+ if collides_with_other_agent {
+ if let Some(form) = settings_window.custom_agent_form.as_mut() {
+ form.error = Some(format!("An agent named \"{}\" already exists.", id.0).into());
+ }
+ cx.notify();
+ return;
+ }
+
+ let fs = <dyn fs::Fs>::global(cx);
+ update_settings_file(fs, cx, move |settings, _| {
+ let agent_servers = settings.agent_servers.get_or_insert_default();
+ if let Some(original_id) = &original_id
+ && original_id.0 != id.0
+ {
+ agent_servers.remove(original_id.0.as_ref());
+ }
+ agent_servers.insert(id.0.to_string(), content);
+ });
+
+ settings_window.custom_agent_form = None;
+ settings_window.pop_sub_page(window, cx);
+}
+
+/// Plain (editor-free) snapshot of the form's contents, so the validation /
+/// build logic can be exercised without a GPUI context.
+struct CustomAgentFormValues {
+ original_id: Option<AgentId>,
+ name: String,
+ command: String,
+ args: String,
+ env: Vec<(String, String)>,
+ default_mode: Option<String>,
+ default_config_options: HashMap<String, String>,
+ favorite_config_option_values: HashMap<String, Vec<String>>,
+}
+
+fn build_settings_from_form(
+ form: &CustomAgentForm,
+ cx: &App,
+) -> Result<(AgentId, Option<AgentId>, CustomAgentServerSettings), SharedString> {
+ let values = CustomAgentFormValues {
+ original_id: form.original_id.clone(),
+ name: form.name.read(cx).text(cx),
+ command: form.command.read(cx).text(cx),
+ args: form.args.read(cx).text(cx),
+ env: read_kv(&form.env, cx),
+ default_mode: form.default_mode.clone(),
+ default_config_options: form.default_config_options.clone(),
+ favorite_config_option_values: form.favorite_config_option_values.clone(),
+ };
+ build_settings_from_values(values)
+}
+
+fn read_kv(rows: &[KeyValueRow], cx: &App) -> Vec<(String, String)> {
+ rows.iter()
+ .map(|row| (row.key.read(cx).text(cx), row.value.read(cx).text(cx)))
+ .collect()
+}
+
+fn build_settings_from_values(
+ values: CustomAgentFormValues,
+) -> Result<(AgentId, Option<AgentId>, CustomAgentServerSettings), SharedString> {
+ let name = values.name.trim().to_string();
+ if name.is_empty() {
+ return Err("Agent name is required.".into());
+ }
+
+ let command = values.command.trim().to_string();
+ if command.is_empty() {
+ return Err("Command is required.".into());
+ }
+
+ let args = values
+ .args
+ .split_whitespace()
+ .map(|arg| arg.to_string())
+ .collect::<Vec<_>>();
+ let env = collect_kv(&values.env, "environment variable")?;
+
+ let content = CustomAgentServerSettings::Custom {
+ path: command.into(),
+ args,
+ env,
+ default_mode: values.default_mode,
+ default_config_options: values.default_config_options,
+ favorite_config_option_values: values.favorite_config_option_values,
+ };
+
+ Ok((AgentId(name.into()), values.original_id, content))
+}
+
+/// Returns whether saving under `id` would overwrite a *different* existing
+/// agent. Editing an agent in place (`id == original_id`) is allowed.
+fn name_collides_with_other_agent(
+ id: &AgentId,
+ original_id: Option<&AgentId>,
+ existing_ids: &[AgentId],
+) -> bool {
+ original_id.is_none_or(|original| original.0 != id.0)
+ && existing_ids.iter().any(|existing| existing.0 == id.0)
+}
+
+fn collect_kv(
+ rows: &[(String, String)],
+ label: &str,
+) -> Result<HashMap<String, String>, SharedString> {
+ let mut map = HashMap::default();
+ for (key, value) in rows {
+ let key = key.trim().to_string();
+ if key.is_empty() {
+ continue;
+ }
+ if map.contains_key(&key) {
+ return Err(format!("Duplicate {label} \"{key}\".").into());
+ }
+ map.insert(key, value.clone());
+ }
+ Ok(map)
+}
+
+// === Open settings.json at the agent's position ===
+//
+// Retained for an upcoming "Edit in settings.json" affordance that jumps the
+// user to the relevant `agent_servers` entry. Not currently wired to any UI.
+
+/// Opens the user's `settings.json` in the original (editor) window, inserts a
+/// scaffold `agent_servers` entry, and selects its name so the user can fill in
+/// the executable path.
+#[allow(dead_code)]
+fn open_new_custom_agent_in_settings(original_window: WindowHandle<MultiWorkspace>, cx: &mut App) {
+ cx.activate(true);
+ original_window
+ .update(cx, |multi_workspace, window, cx| {
+ // Use the workspace handed to us by the update closure rather than
+ // `Workspace::for_window`, which would read the `MultiWorkspace`
+ // entity that this closure is already updating (a double borrow).
+ let Some(workspace) = multi_workspace.workspaces().next() else {
+ return;
+ };
+ let workspace = workspace.downgrade();
+ window.activate_window();
+ window
+ .spawn(cx, async move |cx| {
+ add_custom_agent_settings_entry(workspace, cx).await
+ })
+ .detach_and_log_err(cx);
+ })
+ .log_err();
+}
+
+#[allow(dead_code)]
+async fn add_custom_agent_settings_entry(
+ workspace: WeakEntity<Workspace>,
+ cx: &mut AsyncWindowContext,
+) -> Result<()> {
+ let item = workspace
+ .update_in(cx, |_, window, cx| {
+ create_and_open_local_file(paths::settings_file(), window, cx, || {
+ settings::initial_user_settings_content().as_ref().into()
+ })
+ })?
+ .await?;
+
+ let Some(settings_editor) = item.downcast::<Editor>() else {
+ return Ok(());
+ };
+
+ settings_editor
+ .downgrade()
+ .update_in(cx, |item, window, cx| {
+ let text = item.buffer().read(cx).snapshot(cx).text();
+
+ let settings = cx.global::<SettingsStore>();
+
+ let mut unique_server_name = None;
+ let Some(edits) = settings
+ .edits_for_update(&text, |settings| {
+ let server_name: Option<String> = (0..u8::MAX)
+ .map(|i| {
+ if i == 0 {
+ "your_agent".to_string()
+ } else {
+ format!("your_agent_{}", i)
+ }
+ })
+ .find(|name| {
+ !settings
+ .agent_servers
+ .as_ref()
+ .is_some_and(|agent_servers| {
+ agent_servers.contains_key(name.as_str())
+ })
+ });
+ if let Some(server_name) = server_name {
+ unique_server_name = Some(SharedString::from(server_name.clone()));
+ settings.agent_servers.get_or_insert_default().insert(
+ server_name,
+ CustomAgentServerSettings::Custom {
+ path: "path_to_executable".into(),
+ args: vec![],
+ env: HashMap::default(),
+ default_mode: None,
+ default_config_options: Default::default(),
+ favorite_config_option_values: Default::default(),
+ },
+ );
+ }
+ })
+ .log_err()
+ else {
+ return;
+ };
+
+ if edits.is_empty() {
+ return;
+ }
+
+ let ranges = edits
+ .iter()
+ .map(|(range, _)| range.clone())
+ .collect::<Vec<_>>();
+
+ item.edit(
+ edits.into_iter().map(|(range, s)| {
+ (
+ MultiBufferOffset(range.start)..MultiBufferOffset(range.end),
+ s,
+ )
+ }),
+ cx,
+ );
+
+ if let Some((unique_server_name, buffer)) =
+ unique_server_name.zip(item.buffer().read(cx).as_singleton())
+ {
+ let snapshot = buffer.read(cx).snapshot();
+ if let Some(range) =
+ find_text_in_buffer(&unique_server_name, ranges[0].start, &snapshot)
+ {
+ item.change_selections(
+ SelectionEffects::scroll(Autoscroll::newest()),
+ window,
+ cx,
+ |selections| {
+ selections.select_ranges(vec![
+ MultiBufferOffset(range.start)..MultiBufferOffset(range.end),
+ ]);
+ },
+ );
+ }
+ }
+ })
+ .log_err();
+
+ Ok(())
+}
+
+#[allow(dead_code)]
+fn find_text_in_buffer(
+ text: &str,
+ start: usize,
+ snapshot: &language::BufferSnapshot,
+) -> Option<Range<usize>> {
+ let chars = text.chars().collect::<Vec<char>>();
+
+ let mut offset = start;
+ let mut char_offset = 0;
+ for c in snapshot.chars_at(start) {
+ if char_offset >= chars.len() {
+ break;
+ }
+ offset += 1;
+
+ if c == chars[char_offset] {
+ char_offset += 1;
+ } else {
+ char_offset = 0;
+ }
+ }
+
+ if char_offset == chars.len() {
+ Some(offset.saturating_sub(chars.len())..offset)
+ } else {
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn values() -> CustomAgentFormValues {
+ CustomAgentFormValues {
+ original_id: None,
+ name: "my-agent".into(),
+ command: "/usr/bin/agent".into(),
+ args: String::new(),
+ env: Vec::new(),
+ default_mode: None,
+ default_config_options: HashMap::default(),
+ favorite_config_option_values: HashMap::default(),
+ }
+ }
+
+ fn id(name: &str) -> AgentId {
+ AgentId(name.into())
+ }
+
+ #[test]
+ fn requires_agent_name() {
+ let mut values = values();
+ values.name = " ".into();
+ assert_eq!(
+ build_settings_from_values(values).unwrap_err().as_ref(),
+ "Agent name is required."
+ );
+ }
+
+ #[test]
+ fn requires_command() {
+ let mut values = values();
+ values.command = " ".into();
+ assert_eq!(
+ build_settings_from_values(values).unwrap_err().as_ref(),
+ "Command is required."
+ );
+ }
+
+ #[test]
+ fn rejects_duplicate_environment_variables() {
+ let mut values = values();
+ values.env = vec![("FOO".into(), "1".into()), ("FOO".into(), "2".into())];
+ assert_eq!(
+ build_settings_from_values(values).unwrap_err().as_ref(),
+ "Duplicate environment variable \"FOO\"."
+ );
+ }
+
+ #[test]
+ fn builds_custom_agent() {
+ let mut values = values();
+ values.name = " my-agent ".into();
+ values.command = "/usr/bin/agent".into();
+ values.args = "--flag value".into();
+ // Empty values are kept, but rows with a blank key are ignored.
+ values.env = vec![
+ ("KEY".into(), "VALUE".into()),
+ ("EMPTY".into(), String::new()),
+ (" ".into(), "ignored".into()),
+ ];
+
+ let (id, original_id, content) = build_settings_from_values(values).unwrap();
+ assert_eq!(id.0.as_ref(), "my-agent");
+ assert_eq!(original_id, None);
+
+ let expected_env = HashMap::from_iter([
+ ("KEY".to_string(), "VALUE".to_string()),
+ ("EMPTY".to_string(), String::new()),
+ ]);
+ assert_eq!(
+ content,
+ CustomAgentServerSettings::Custom {
+ path: "/usr/bin/agent".into(),
+ args: vec!["--flag".into(), "value".into()],
+ env: expected_env,
+ default_mode: None,
+ default_config_options: HashMap::default(),
+ favorite_config_option_values: HashMap::default(),
+ }
+ );
+ }
+
+ #[test]
+ fn preserves_advanced_fields() {
+ let mut values = values();
+ values.default_mode = Some("ask".into());
+ values.default_config_options =
+ HashMap::from_iter([("opt".to_string(), "val".to_string())]);
+
+ let (_, _, content) = build_settings_from_values(values).unwrap();
+ match content {
+ CustomAgentServerSettings::Custom {
+ default_mode,
+ default_config_options,
+ ..
+ } => {
+ assert_eq!(default_mode.as_deref(), Some("ask"));
+ assert_eq!(
+ default_config_options.get("opt").map(String::as_str),
+ Some("val")
+ );
+ }
+ _ => panic!("expected a custom agent"),
+ }
+ }
+
+ #[test]
+ fn name_collision_covers_new_and_rename() {
+ let existing = vec![id("foo"), id("bar")];
+
+ // New agent taking an existing name collides.
+ assert!(name_collides_with_other_agent(&id("foo"), None, &existing));
+ // New agent with a free name is fine.
+ assert!(!name_collides_with_other_agent(&id("baz"), None, &existing));
+ // Editing an agent in place is allowed even though the name "exists".
+ assert!(!name_collides_with_other_agent(
+ &id("foo"),
+ Some(&id("foo")),
+ &existing
+ ));
+ // Renaming onto a different agent's name collides.
+ assert!(name_collides_with_other_agent(
+ &id("bar"),
+ Some(&id("foo")),
+ &existing
+ ));
+ }
+}
diff --git a/crates/settings_ui/src/pages/llm_providers_page.rs b/crates/settings_ui/src/pages/llm_providers_page.rs
new file mode 100644
index 00000000000..d663dbe7d94
--- /dev/null
+++ b/crates/settings_ui/src/pages/llm_providers_page.rs
@@ -0,0 +1,207 @@
+use std::sync::Arc;
+
+use gpui::{ScrollHandle, prelude::*};
+use language_model::{
+ ConfigurationViewTargetAgent, IconOrSvg, LanguageModelProvider, LanguageModelProviderId,
+ LanguageModelRegistry, ProviderConfigurationView,
+};
+use ui::{Divider, DividerColor, prelude::*};
+
+use crate::SettingsWindow;
+
+pub(crate) fn render_llm_providers_page(
+ settings_window: &SettingsWindow,
+ scroll_handle: &ScrollHandle,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> AnyElement {
+ let providers = LanguageModelRegistry::read_global(cx).visible_providers();
+
+ v_flex()
+ .id("llm-providers-page")
+ .size_full()
+ .pt_2p5()
+ .px_8()
+ .pb_16()
+ .track_scroll(scroll_handle)
+ .overflow_y_scroll()
+ .children(
+ providers
+ .iter()
+ .map(|provider| render_provider_row(settings_window, provider, window, cx))
+ .collect::<Vec<_>>(),
+ )
+ .into_any_element()
+}
+
+fn render_provider_row(
+ settings_window: &SettingsWindow,
+ provider: &Arc<dyn LanguageModelProvider>,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> AnyElement {
+ let provider_id = provider.id();
+ let provider_name = provider.name().0;
+ let is_authenticated = provider.is_authenticated(cx);
+
+ let icon = match provider.icon() {
+ IconOrSvg::Svg(path) => Icon::from_external_svg(path),
+ IconOrSvg::Icon(name) => Icon::new(name),
+ }
+ .size(IconSize::Small)
+ .color(Color::Muted);
+
+ let left = h_flex()
+ .flex_none()
+ .gap_1p5()
+ .child(icon)
+ .child(Label::new(provider_name))
+ .when(is_authenticated, |this| {
+ this.child(
+ Icon::new(IconName::Check)
+ .size(IconSize::Small)
+ .color(Color::Success),
+ )
+ });
+
+ // The provider tells us how it wants to be presented: a compact inline
+ // control, or a richer view that belongs on its own sub-page.
+ let control =
+ match get_or_create_configuration_view(settings_window, &provider_id, provider, window, cx)
+ {
+ ProviderConfigurationView::Inline(view) => v_flex()
+ .min_w_0()
+ .w_full()
+ .max_w(rems(24.))
+ .child(view)
+ .into_any_element(),
+ ProviderConfigurationView::SubPage(_) => render_configure_button(&provider_id, cx),
+ };
+
+ v_flex()
+ .min_w_0()
+ .w_full()
+ .child(
+ div()
+ .px_2()
+ .child(Divider::horizontal().color(DividerColor::BorderFaded)),
+ )
+ .child(
+ h_flex()
+ .w_full()
+ .py_2()
+ .px_2()
+ .gap_6()
+ .justify_between()
+ .items_start()
+ .child(left)
+ .child(control),
+ )
+ .into_any_element()
+}
+
+fn render_configure_button(
+ provider_id: &LanguageModelProviderId,
+ cx: &mut Context<SettingsWindow>,
+) -> AnyElement {
+ let provider_id = provider_id.clone();
+ Button::new(
+ SharedString::from(format!("configure-{}", provider_id.0)),
+ "Configure",
+ )
+ .style(ButtonStyle::Outlined)
+ .label_size(LabelSize::Small)
+ .tab_index(0isize)
+ .on_click(cx.listener(move |this, _, window, cx| {
+ open_provider_configuration(this, provider_id.clone(), window, cx);
+ }))
+ .into_any_element()
+}
+
+fn open_provider_configuration(
+ settings_window: &mut SettingsWindow,
+ provider_id: LanguageModelProviderId,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) {
+ let title = LanguageModelRegistry::read_global(cx)
+ .provider(&provider_id)
+ .map(|provider| provider.name().0)
+ .unwrap_or_else(|| provider_id.0.clone());
+
+ settings_window.configuring_provider = Some(provider_id);
+
+ settings_window.push_dynamic_sub_page(
+ title,
+ "Agent Configuration",
+ Some("llm_providers"),
+ false,
+ render_provider_config_sub_page,
+ window,
+ cx,
+ );
+}
+
+fn render_provider_config_sub_page(
+ settings_window: &SettingsWindow,
+ scroll_handle: &ScrollHandle,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> AnyElement {
+ let Some(provider_id) = settings_window.configuring_provider.clone() else {
+ return div().into_any_element();
+ };
+ let Some(provider) = LanguageModelRegistry::read_global(cx).provider(&provider_id) else {
+ return div().into_any_element();
+ };
+
+ // A provider routed to a sub-page always provides a `SubPage` view; fall
+ // back to whatever view it returns otherwise.
+ let view = match get_or_create_configuration_view(
+ settings_window,
+ &provider_id,
+ &provider,
+ window,
+ cx,
+ ) {
+ ProviderConfigurationView::Inline(view) | ProviderConfigurationView::SubPage(view) => view,
+ };
+
+ v_flex()
+ .id("provider-config-sub-page")
+ .size_full()
+ .pt_2p5()
+ .px_8()
+ .pb_16()
+ .track_scroll(scroll_handle)
+ .overflow_y_scroll()
+ .child(view)
+ .into_any_element()
+}
+
+fn get_or_create_configuration_view(
+ settings_window: &SettingsWindow,
+ provider_id: &LanguageModelProviderId,
+ provider: &Arc<dyn LanguageModelProvider>,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> ProviderConfigurationView {
+ if let Some(view) = settings_window
+ .provider_configuration_views
+ .get(provider_id)
+ {
+ return view.clone();
+ }
+
+ let view = provider.configuration_view_v2(ConfigurationViewTargetAgent::ZedAgent, window, cx);
+
+ // Store the view for future renders by deferring a mutation
+ let provider_id = provider_id.clone();
+ let view_clone = view.clone();
+ cx.defer_in(window, move |this, _window, _cx| {
+ this.provider_configuration_views
+ .insert(provider_id, view_clone);
+ });
+
+ view
+}
diff --git a/crates/settings_ui/src/pages/mcp_servers_page.rs b/crates/settings_ui/src/pages/mcp_servers_page.rs
new file mode 100644
index 00000000000..d31e158ce1e
--- /dev/null
+++ b/crates/settings_ui/src/pages/mcp_servers_page.rs
@@ -0,0 +1,1588 @@
+use std::sync::Arc;
+
+use collections::HashMap;
+use context_server::ContextServerId;
+use editor::Editor;
+use extension_host::ExtensionStore;
+use gpui::{Action as _, Entity, Focusable as _, ScrollHandle, WeakEntity, prelude::*};
+use project::context_server_store::{
+ ContextServerConfiguration, ContextServerStatus, ContextServerStore,
+};
+use project::project_settings::ContextServerSettings;
+use settings::{ContextServerCommand, ContextServerSettingsContent, OAuthClientSettings};
+use ui::{
+ AiSettingItem, AiSettingItemSource, AiSettingItemStatus, ContextMenu, Divider, DividerColor,
+ PopoverMenu, Switch, ToggleState, Tooltip, prelude::*,
+};
+use util::ResultExt as _;
+
+use zed_actions::ExtensionCategoryFilter;
+
+use crate::SettingsWindow;
+
+pub(crate) fn render_mcp_servers_page(
+ settings_window: &SettingsWindow,
+ scroll_handle: &ScrollHandle,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> AnyElement {
+ let context_server_store = get_context_server_store(settings_window, cx);
+
+ let server_list = if let Some(store) = context_server_store.as_ref() {
+ let server_ids = store.read(cx).server_ids().to_vec();
+
+ if server_ids.is_empty() {
+ render_empty_state(cx)
+ } else {
+ render_server_list(&server_ids, store, cx)
+ }
+ } else {
+ render_no_project_state(cx)
+ };
+
+ let add_server_popover = render_add_server_popover(settings_window, window, cx);
+
+ v_flex()
+ .id("mcp-servers-page")
+ .size_full()
+ .pt_2p5()
+ .px_8()
+ .pb_16()
+ .track_scroll(scroll_handle)
+ .overflow_y_scroll()
+ .child(
+ h_flex()
+ .w_full()
+ .justify_between()
+ .items_center()
+ .mb_4()
+ .child(
+ v_flex()
+ .child(Label::new("MCP Servers").size(LabelSize::Large))
+ .child(
+ Label::new("Manage Model Context Protocol servers connected directly or via extensions.")
+ .size(LabelSize::Small)
+ .color(Color::Muted),
+ ),
+ )
+ .child(add_server_popover),
+ )
+ .child(server_list)
+ .into_any_element()
+}
+
+fn get_context_server_store(
+ settings_window: &SettingsWindow,
+ cx: &App,
+) -> Option<Entity<ContextServerStore>> {
+ let original_window = settings_window.original_window.as_ref()?;
+ let multi_workspace = original_window.read(cx).ok()?;
+ let workspace = multi_workspace.workspaces().next()?;
+ let project = workspace.read(cx).project().clone();
+ Some(project.read(cx).context_server_store())
+}
+
+fn render_empty_state(cx: &App) -> AnyElement {
+ h_flex()
+ .p_4()
+ .justify_center()
+ .border_1()
+ .border_dashed()
+ .border_color(cx.theme().colors().border.opacity(0.6))
+ .rounded_sm()
+ .child(
+ Label::new("No MCP servers added yet. Click \"Add Server\" to get started.")
+ .color(Color::Muted)
+ .size(LabelSize::Small),
+ )
+ .into_any_element()
+}
+
+fn render_no_project_state(cx: &App) -> AnyElement {
+ h_flex()
+ .p_4()
+ .justify_center()
+ .border_1()
+ .border_dashed()
+ .border_color(cx.theme().colors().border.opacity(0.6))
+ .rounded_sm()
+ .child(
+ Label::new("No active project found. Open a workspace to manage MCP servers.")
+ .color(Color::Muted)
+ .size(LabelSize::Small),
+ )
+ .into_any_element()
+}
+
+fn render_server_list(
+ server_ids: &[ContextServerId],
+ store: &Entity<ContextServerStore>,
+ cx: &mut Context<SettingsWindow>,
+) -> AnyElement {
+ v_flex()
+ .w_full()
+ .gap_1()
+ .children(itertools::intersperse_with(
+ server_ids
+ .iter()
+ .map(|server_id| render_context_server(server_id, store, cx).into_any_element()),
+ || {
+ Divider::horizontal()
+ .color(DividerColor::BorderFaded)
+ .into_any_element()
+ },
+ ))
+ .into_any_element()
+}
+
+fn render_context_server(
+ context_server_id: &ContextServerId,
+ store: &Entity<ContextServerStore>,
+ cx: &mut Context<SettingsWindow>,
+) -> impl IntoElement {
+ let server_status = store
+ .read(cx)
+ .status_for_server(context_server_id)
+ .unwrap_or(ContextServerStatus::Stopped);
+ let server_configuration = store.read(cx).configuration_for_server(context_server_id);
+
+ let is_running = matches!(server_status, ContextServerStatus::Running);
+ let item_id = SharedString::from(context_server_id.0.to_string());
+
+ // Determine the source from the configured settings rather than the runtime
+ // configuration: a custom (Stdio/HTTP) server that is disabled or not yet
+ // started has no runtime configuration, and must not be mistaken for an
+ // extension-provided server.
+ let provided_by_extension = store.read(cx).is_extension_provided(context_server_id, cx);
+
+ let display_name = if provided_by_extension {
+ resolve_extension_display_name(context_server_id, cx).unwrap_or_else(|| item_id.clone())
+ } else {
+ item_id.clone()
+ };
+
+ let source = if provided_by_extension {
+ AiSettingItemSource::Extension
+ } else {
+ AiSettingItemSource::Custom
+ };
+
+ let status = map_server_status(&server_status);
+
+ let should_show_logout = server_configuration.as_ref().is_some_and(|config| {
+ matches!(config.as_ref(), ContextServerConfiguration::Http { .. })
+ && !config.has_static_auth_header()
+ });
+
+ // ContextServerRegistry is per-project (not a global), so we skip tool count
+ // in the settings UI for now.
+ let tool_count = 0usize;
+
+ let tool_label = if is_running && tool_count > 0 {
+ Some(if tool_count == 1 {
+ SharedString::from("1 tool")
+ } else {
+ SharedString::from(format!("{} tools", tool_count))
+ })
+ } else {
+ None
+ };
+
+ // Build gear menu. Pre-fill "Configure Server" from the raw configured
+ // settings (not the resolved runtime configuration) so the form is editable
+ // even when the settings contain invalid data (e.g. an unparsable URL) or
+ // the server is disabled / not yet started.
+ let server_settings = store
+ .read(cx)
+ .settings_for_server(context_server_id)
+ .cloned();
+ let gear_menu = render_gear_menu(
+ context_server_id,
+ store,
+ cx.entity().downgrade(),
+ server_settings.clone(),
+ provided_by_extension,
+ should_show_logout,
+ );
+
+ // Build toggle switch
+ let toggle_switch = render_toggle_switch(context_server_id, store, is_running);
+
+ // Surface invalid settings (which prevent the server from starting at all)
+ // ahead of runtime status feedback, so the misconfiguration is visible.
+ let details = match settings_validation_error(server_settings.as_ref()) {
+ Some(error) => Some(render_form_error(error).into_any_element()),
+ None => render_status_details(&server_status, context_server_id, store, should_show_logout),
+ };
+
+ AiSettingItem::new(item_id, display_name, status, source)
+ .action(gear_menu)
+ .action(toggle_switch)
+ .when_some(tool_label, |this, label| this.detail_label(label))
+ .when_some(details, |this, details| this.details(details))
+}
+
+fn map_server_status(status: &ContextServerStatus) -> AiSettingItemStatus {
+ match status {
+ ContextServerStatus::Starting => AiSettingItemStatus::Starting,
+ ContextServerStatus::Running => AiSettingItemStatus::Running,
+ ContextServerStatus::Stopped => AiSettingItemStatus::Stopped,
+ ContextServerStatus::Error(_) => AiSettingItemStatus::Error,
+ ContextServerStatus::AuthRequired => AiSettingItemStatus::AuthRequired,
+ ContextServerStatus::ClientSecretRequired { .. } => {
+ AiSettingItemStatus::ClientSecretRequired
+ }
+ ContextServerStatus::Authenticating => AiSettingItemStatus::Authenticating,
+ }
+}
+
+fn resolve_extension_display_name(id: &ContextServerId, cx: &App) -> Option<SharedString> {
+ ExtensionStore::global(cx)
+ .read(cx)
+ .installed_extensions()
+ .iter()
+ .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
+ .map(|(_, entry)| {
+ let name = entry.manifest.name.as_str();
+ let stripped = name
+ .strip_suffix(" MCP Server")
+ .or_else(|| name.strip_suffix(" MCP"))
+ .or_else(|| name.strip_suffix(" Context Server"))
+ .unwrap_or(name);
+ SharedString::from(stripped.to_string())
+ })
+}
+
+fn render_gear_menu(
+ context_server_id: &ContextServerId,
+ store: &Entity<ContextServerStore>,
+ settings_window: WeakEntity<SettingsWindow>,
+ server_settings: Option<ContextServerSettings>,
+ provided_by_extension: bool,
+ should_show_logout: bool,
+) -> impl IntoElement {
+ let context_server_id = context_server_id.clone();
+ let store = store.clone();
+
+ PopoverMenu::new(SharedString::from(format!(
+ "mcp-gear-{}",
+ context_server_id.0
+ )))
+ .trigger_with_tooltip(
+ IconButton::new(
+ SharedString::from(format!("mcp-gear-btn-{}", context_server_id.0)),
+ IconName::Settings,
+ )
+ .icon_color(Color::Muted)
+ .icon_size(IconSize::Small)
+ .tab_index(0isize),
+ Tooltip::text("Configure MCP Server"),
+ )
+ .anchor(gpui::Anchor::TopRight)
+ .menu({
+ move |window, cx| {
+ let context_server_id = context_server_id.clone();
+ let store = store.clone();
+ let settings_window = settings_window.clone();
+ let server_settings = server_settings.clone();
+
+ Some(ContextMenu::build(window, cx, move |menu, _window, _cx| {
+ menu.when(!provided_by_extension, |this| {
+ this.entry("Configure Server", None, {
+ let settings_window = settings_window.clone();
+ let context_server_id = context_server_id.clone();
+ let server_settings = server_settings.clone();
+ move |window, cx| {
+ let transport = match &server_settings {
+ Some(ContextServerSettings::Http { .. }) => McpTransport::Http,
+ _ => McpTransport::Stdio,
+ };
+ let existing = server_settings
+ .clone()
+ .map(|settings| (context_server_id.clone(), settings));
+ settings_window
+ .update(cx, |this, cx| {
+ open_mcp_server_form(this, transport, existing, window, cx);
+ })
+ .log_err();
+ }
+ })
+ })
+ .when(should_show_logout, |this| {
+ this.entry("Log Out", None, {
+ let store = store.clone();
+ let context_server_id = context_server_id.clone();
+ move |_window, cx| {
+ store.update(cx, |s, cx| {
+ s.logout_server(&context_server_id, cx).log_err();
+ });
+ }
+ })
+ })
+ // Only show a divider when there is an entry above "Uninstall".
+ // Extension servers have neither "Configure Server" nor "Log Out".
+ .when(!provided_by_extension || should_show_logout, |this| {
+ this.separator()
+ })
+ .entry("Uninstall", None, {
+ let context_server_id = context_server_id.clone();
+ move |_, cx| {
+ uninstall_server(&context_server_id, provided_by_extension, cx);
+ }
+ })
+ }))
+ }
+ })
+}
+
+fn render_toggle_switch(
+ context_server_id: &ContextServerId,
+ store: &Entity<ContextServerStore>,
+ is_running: bool,
+) -> impl IntoElement {
+ let context_server_id = context_server_id.clone();
+ let store = store.clone();
+
+ Switch::new(
+ SharedString::from(format!("mcp-toggle-{}", context_server_id.0)),
+ if is_running {
+ ToggleState::Selected
+ } else {
+ ToggleState::Unselected
+ },
+ )
+ .tab_index(0isize)
+ .on_click({
+ move |state, _window, cx| {
+ let is_enabled = match state {
+ ToggleState::Unselected | ToggleState::Indeterminate => {
+ store.update(cx, |this, cx| {
+ this.stop_server(&context_server_id, cx).log_err();
+ });
+ false
+ }
+ ToggleState::Selected => {
+ store.update(cx, |this, cx| {
+ if let Some(server) = this.get_server(&context_server_id) {
+ this.start_server(server, cx);
+ }
+ });
+ true
+ }
+ };
+
+ let fs = <dyn fs::Fs>::global(cx);
+ settings::update_settings_file(fs, cx, {
+ let context_server_id = context_server_id.clone();
+ move |settings, _| {
+ settings
+ .project
+ .context_servers
+ .entry(context_server_id.0.clone())
+ .or_insert_with(|| ContextServerSettingsContent::Extension {
+ enabled: is_enabled,
+ remote: false,
+ settings: serde_json::json!({}),
+ })
+ .set_enabled(is_enabled);
+ }
+ });
+ }
+ })
+}
+
+fn render_status_details(
+ server_status: &ContextServerStatus,
+ context_server_id: &ContextServerId,
+ store: &Entity<ContextServerStore>,
+ should_show_logout: bool,
+) -> Option<AnyElement> {
+ let feedback_base = || h_flex().py_1().min_w_0().w_full().gap_1().justify_between();
+
+ match server_status {
+ ContextServerStatus::Error(error) => {
+ let store = store.clone();
+ let context_server_id = context_server_id.clone();
+ Some(
+ feedback_base()
+ .child(
+ h_flex()
+ .pr_4()
+ .min_w_0()
+ .w_full()
+ .gap_2()
+ .child(
+ Icon::new(IconName::XCircle)
+ .size(IconSize::XSmall)
+ .color(Color::Error),
+ )
+ .child(
+ div().min_w_0().flex_1().child(
+ Label::new(error.to_string())
+ .color(Color::Muted)
+ .size(LabelSize::Small),
+ ),
+ ),
+ )
+ .when(should_show_logout, |this| {
+ this.child(
+ Button::new("error-logout", "Log Out")
+ .style(ButtonStyle::Outlined)
+ .label_size(LabelSize::Small)
+ .on_click({
+ let store = store.clone();
+ let context_server_id = context_server_id.clone();
+ move |_event, _window, cx| {
+ store.update(cx, |s, cx| {
+ s.logout_server(&context_server_id, cx).log_err();
+ });
+ }
+ }),
+ )
+ })
+ .into_any_element(),
+ )
+ }
+ ContextServerStatus::AuthRequired => {
+ let store = store.clone();
+ let context_server_id = context_server_id.clone();
+ Some(
+ feedback_base()
+ .child(
+ h_flex()
+ .pr_4()
+ .min_w_0()
+ .w_full()
+ .gap_2()
+ .child(
+ Icon::new(IconName::Info)
+ .size(IconSize::XSmall)
+ .color(Color::Muted),
+ )
+ .child(
+ Label::new("Authenticate to connect this server")
+ .color(Color::Muted)
+ .size(LabelSize::Small),
+ ),
+ )
+ .child(
+ Button::new("authenticate-server", "Authenticate")
+ .style(ButtonStyle::Outlined)
+ .label_size(LabelSize::Small)
+ .on_click({
+ move |_event, _window, cx| {
+ store.update(cx, |s, cx| {
+ s.authenticate_server(&context_server_id, cx).log_err();
+ });
+ }
+ }),
+ )
+ .into_any_element(),
+ )
+ }
+ ContextServerStatus::ClientSecretRequired { .. } => Some(
+ feedback_base()
+ .child(
+ h_flex()
+ .pr_4()
+ .min_w_0()
+ .w_full()
+ .gap_2()
+ .child(
+ Icon::new(IconName::Info)
+ .size(IconSize::XSmall)
+ .color(Color::Muted),
+ )
+ .child(
+ Label::new("A client secret is required to connect this server")
+ .color(Color::Muted)
+ .size(LabelSize::Small),
+ ),
+ )
+ .into_any_element(),
+ ),
+ ContextServerStatus::Authenticating => Some(
+ h_flex()
+ .mt_1()
+ .pr_4()
+ .min_w_0()
+ .w_full()
+ .gap_2()
+ .child(div().size_3().flex_shrink_0())
+ .child(
+ Label::new("Authenticating…")
+ .color(Color::Muted)
+ .size(LabelSize::Small),
+ )
+ .into_any_element(),
+ ),
+ _ => None,
+ }
+}
+
+fn render_add_server_popover(
+ settings_window: &SettingsWindow,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> impl IntoElement {
+ let original_window = settings_window.original_window;
+ // Stable handle so the button keeps focus state across renders and can show a
+ // focus ring even when the page is opened (and the button auto-focused) via a
+ // mouse click, where `focus_visible` styling is suppressed.
+ let focus_handle = settings_window
+ .mcp_add_server_focus_handle
+ .clone()
+ .tab_index(0)
+ .tab_stop(true);
+ let is_focused = focus_handle.is_focused(window);
+ let border_color = if is_focused {
+ cx.theme().colors().border_focused
+ } else {
+ gpui::transparent_black()
+ };
+ let settings_window = cx.entity().downgrade();
+
+ let popover = PopoverMenu::new("add-mcp-server-popover")
+ .trigger(
+ Button::new("add-mcp-server", "Add Server")
+ .style(ButtonStyle::Outlined)
+ .track_focus(&focus_handle)
+ .start_icon(
+ Icon::new(IconName::Plus)
+ .size(IconSize::Small)
+ .color(Color::Muted),
+ )
+ .label_size(LabelSize::Small),
+ )
+ .anchor(gpui::Anchor::TopRight)
+ .menu({
+ move |window, cx| {
+ let settings_window = settings_window.clone();
+ Some(ContextMenu::build(window, cx, move |menu, _window, _cx| {
+ menu.entry("Add Local Server", None, {
+ let settings_window = settings_window.clone();
+ move |window, cx| {
+ settings_window
+ .update(cx, |this, cx| {
+ open_mcp_server_form(
+ this,
+ McpTransport::Stdio,
+ None,
+ window,
+ cx,
+ );
+ })
+ .log_err();
+ }
+ })
+ .entry("Add Remote Server", None, {
+ let settings_window = settings_window.clone();
+ move |window, cx| {
+ settings_window
+ .update(cx, |this, cx| {
+ open_mcp_server_form(
+ this,
+ McpTransport::Http,
+ None,
+ window,
+ cx,
+ );
+ })
+ .log_err();
+ }
+ })
+ .separator()
+ .entry("Install from Extensions", None, {
+ move |_window, cx| {
+ if let Some(original_window) = original_window.as_ref() {
+ cx.activate(true);
+ original_window
+ .update(cx, |_, window, cx| {
+ window.activate_window();
+ window.dispatch_action(
+ zed_actions::Extensions {
+ category_filter: Some(
+ ExtensionCategoryFilter::ContextServers,
+ ),
+ id: None,
+ }
+ .boxed_clone(),
+ cx,
+ );
+ })
+ .log_err();
+ }
+ }
+ })
+ }))
+ }
+ });
+
+ div()
+ .rounded_md()
+ .border_1()
+ .border_color(border_color)
+ .child(popover)
+}
+
+fn uninstall_server(
+ context_server_id: &ContextServerId,
+ provided_by_extension: bool,
+ cx: &mut App,
+) {
+ if provided_by_extension {
+ if let Some((ext_id, manifest)) =
+ resolve_extension_for_context_server(context_server_id, cx)
+ {
+ if extension_only_provides_context_server(&manifest) {
+ ExtensionStore::global(cx)
+ .update(cx, |store, cx| store.uninstall_extension(ext_id, cx))
+ .detach_and_log_err(cx);
+ }
+ }
+ }
+
+ let fs = <dyn fs::Fs>::global(cx);
+ let context_server_id = context_server_id.clone();
+ settings::update_settings_file(fs, cx, move |settings, _| {
+ settings
+ .project
+ .context_servers
+ .remove(&context_server_id.0);
+ });
+}
+
+fn resolve_extension_for_context_server(
+ id: &ContextServerId,
+ cx: &App,
+) -> Option<(Arc<str>, Arc<extension::ExtensionManifest>)> {
+ ExtensionStore::global(cx)
+ .read(cx)
+ .installed_extensions()
+ .iter()
+ .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
+ .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
+}
+
+fn extension_only_provides_context_server(manifest: &extension::ExtensionManifest) -> bool {
+ manifest.context_servers.len() == 1
+ && manifest.themes.is_empty()
+ && manifest.icon_themes.is_empty()
+ && manifest.languages.is_empty()
+ && manifest.grammars.is_empty()
+ && manifest.language_servers.is_empty()
+ && manifest.slash_commands.is_empty()
+ && manifest.snippets.is_none()
+ && manifest.debug_locators.is_empty()
+}
+
+// === Custom (Stdio/HTTP) MCP server add/edit form ===
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum McpTransport {
+ /// Local server launched via stdin/stdout.
+ Stdio,
+ /// Remote server connected over HTTP.
+ Http,
+}
+
+#[derive(Clone, Copy)]
+enum McpKvKind {
+ Env,
+ Header,
+}
+
+impl McpKvKind {
+ fn rows_mut(self, form: &mut McpServerForm) -> &mut Vec<KeyValueRow> {
+ match self {
+ McpKvKind::Env => &mut form.env,
+ McpKvKind::Header => &mut form.headers,
+ }
+ }
+
+ fn remove_id(self) -> &'static str {
+ match self {
+ McpKvKind::Env => "mcp-env-remove",
+ McpKvKind::Header => "mcp-header-remove",
+ }
+ }
+
+ fn add_id(self) -> &'static str {
+ match self {
+ McpKvKind::Env => "mcp-env-add",
+ McpKvKind::Header => "mcp-header-add",
+ }
+ }
+}
+
+struct KeyValueRow {
+ key: Entity<Editor>,
+ value: Entity<Editor>,
+}
+
+/// Editor-backed state for the custom MCP server add/edit form.
+pub(crate) struct McpServerForm {
+ transport: McpTransport,
+ /// `Some` when editing an existing server (used to remove the old entry on rename).
+ original_id: Option<ContextServerId>,
+ name: Entity<Editor>,
+ command: Entity<Editor>,
+ args: Entity<Editor>,
+ url: Entity<Editor>,
+ timeout: Entity<Editor>,
+ oauth_client_id: Entity<Editor>,
+ env: Vec<KeyValueRow>,
+ headers: Vec<KeyValueRow>,
+ error: Option<SharedString>,
+}
+
+impl McpServerForm {
+ fn new(
+ transport: McpTransport,
+ existing: Option<(ContextServerId, ContextServerSettings)>,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+ ) -> Self {
+ let original_id = existing.as_ref().map(|(id, _)| id.clone());
+ let settings = existing.map(|(_, settings)| settings);
+ let name_initial = original_id.as_ref().map(|id| id.0.to_string());
+
+ let mut command_initial = None;
+ let mut args_initial = None;
+ let mut url_initial = None;
+ let mut timeout_initial = None;
+ let mut oauth_initial = None;
+ let mut env = Vec::new();
+ let mut headers = Vec::new();
+
+ // Pre-fill from the raw settings so invalid values (e.g. a malformed URL
+ // the user typed directly into settings.json) still load into the form
+ // for correction, rather than being dropped during resolution.
+ if let Some(settings) = settings.as_ref() {
+ match settings {
+ ContextServerSettings::Stdio { command, .. } => {
+ command_initial = Some(command.path.to_string_lossy().to_string());
+ if !command.args.is_empty() {
+ args_initial = Some(command.args.join(" "));
+ }
+ timeout_initial = command.timeout.map(|timeout| timeout.to_string());
+ if let Some(env_map) = &command.env {
+ for (key, value) in sorted_pairs(env_map) {
+ env.push(new_kv_row(Some(&key), Some(&value), window, cx));
+ }
+ }
+ }
+ ContextServerSettings::Http {
+ url,
+ headers: header_map,
+ timeout,
+ oauth,
+ ..
+ } => {
+ url_initial = Some(url.clone());
+ timeout_initial = timeout.map(|timeout| timeout.to_string());
+ for (key, value) in sorted_pairs(header_map) {
+ headers.push(new_kv_row(Some(&key), Some(&value), window, cx));
+ }
+ oauth_initial = oauth.as_ref().map(|oauth| oauth.client_id.clone());
+ }
+ ContextServerSettings::Extension { .. } => {}
+ }
+ }
+
+ Self {
+ transport,
+ original_id,
+ name: new_input("my-mcp-server", name_initial.as_deref(), window, cx),
+ command: new_input("/path/to/server", command_initial.as_deref(), window, cx),
+ args: new_input("--flag value", args_initial.as_deref(), window, cx),
+ url: new_input(
+ "https://example.com/mcp",
+ url_initial.as_deref(),
+ window,
+ cx,
+ ),
+ timeout: new_input("60", timeout_initial.as_deref(), window, cx),
+ oauth_client_id: new_input(
+ "Optional OAuth client ID",
+ oauth_initial.as_deref(),
+ window,
+ cx,
+ ),
+ env,
+ headers,
+ error: None,
+ }
+ }
+}
+
+fn sorted_pairs(map: &HashMap<String, String>) -> Vec<(String, String)> {
+ let mut pairs: Vec<(String, String)> = map
+ .iter()
+ .map(|(key, value)| (key.clone(), value.clone()))
+ .collect();
+ pairs.sort_by(|a, b| a.0.cmp(&b.0));
+ pairs
+}
+
+fn new_input(
+ placeholder: &str,
+ initial: Option<&str>,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> Entity<Editor> {
+ let placeholder = placeholder.to_string();
+ let initial = initial.map(|text| text.to_string());
+ cx.new(|cx| {
+ let mut editor = Editor::single_line(window, cx);
+ editor.set_placeholder_text(placeholder.as_str(), window, cx);
+ if let Some(text) = initial {
+ editor.set_text(text, window, cx);
+ }
+ editor
+ })
+}
+
+fn new_kv_row(
+ key: Option<&str>,
+ value: Option<&str>,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> KeyValueRow {
+ KeyValueRow {
+ key: new_input("Key", key, window, cx),
+ value: new_input("Value", value, window, cx),
+ }
+}
+
+/// Creates the form state and pushes the form sub-page onto the stack.
+pub(crate) fn open_mcp_server_form(
+ settings_window: &mut SettingsWindow,
+ transport: McpTransport,
+ existing: Option<(ContextServerId, ContextServerSettings)>,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) {
+ let is_edit = existing.is_some();
+ settings_window.mcp_server_form = Some(McpServerForm::new(transport, existing, window, cx));
+
+ let title = if is_edit {
+ "Configure MCP Server"
+ } else {
+ match transport {
+ McpTransport::Stdio => "Add Local MCP Server",
+ McpTransport::Http => "Add Remote MCP Server",
+ }
+ };
+
+ settings_window.push_dynamic_sub_page(
+ title,
+ "Agent Configuration",
+ Some("context_servers"),
+ false,
+ render_mcp_server_form_page,
+ window,
+ cx,
+ );
+}
+
+fn render_mcp_server_form_page(
+ settings_window: &SettingsWindow,
+ scroll_handle: &ScrollHandle,
+ _window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) -> AnyElement {
+ let Some(form) = settings_window.mcp_server_form.as_ref() else {
+ return div().into_any_element();
+ };
+ let transport = form.transport;
+ let error = form.error.clone();
+
+ let fields = v_flex()
+ .w_full()
+ .gap_4()
+ .child(render_form_field(
+ settings_window,
+ "Server Name",
+ "Required. A unique name used to identify this MCP server.",
+ &form.name,
+ cx,
+ ))
+ .map(|this| match transport {
+ McpTransport::Stdio => this
+ .child(render_form_field(
+ settings_window,
+ "Command",
+ "Required. Path to the executable that launches the server.",
+ &form.command,
+ cx,
+ ))
+ .child(render_form_field(
+ settings_window,
+ "Arguments",
+ "Space-separated arguments passed to the command.",
+ &form.args,
+ cx,
+ ))
+ .child(render_kv_section(
+ settings_window,
+ "Environment Variables",
+ "Environment variables provided to the server process.",
+ &form.env,
+ McpKvKind::Env,
+ cx,
+ ))
+ .child(render_form_field(
+ settings_window,
+ "Timeout (seconds)",
+ "How long to wait for the server to respond before timing out.",
+ &form.timeout,
+ cx,
+ )),
+ McpTransport::Http => this
+ .child(render_form_field(
+ settings_window,
+ "URL",
+ "Required. The base URL of the remote MCP server.",
+ &form.url,
+ cx,
+ ))
+ .child(render_kv_section(
+ settings_window,
+ "Headers",
+ "HTTP headers sent with each request to the server.",
+ &form.headers,
+ McpKvKind::Header,
+ cx,
+ ))
+ .child(render_form_field(
+ settings_window,
+ "Timeout (seconds)",
+ "How long to wait for the server to respond before timing out.",
+ &form.timeout,
+ cx,
+ ))
+ .child(render_form_field(
+ settings_window,
+ "OAuth Client ID",
+ "Optional OAuth client ID used to authenticate with the server.",
+ &form.oauth_client_id,
+ cx,
+ )),
+ })
+ .when_some(error, |this, error| this.child(render_form_error(error)))
+ .child(render_form_actions(cx));
+
+ v_flex()
+ .id("mcp-server-form-page")
+ .size_full()
+ .pt_2p5()
+ .px_8()
+ .pb_16()
+ .track_scroll(scroll_handle)
+ .overflow_y_scroll()
+ .child(fields)
+ .into_any_element()
+}
+
+fn input_box(editor: &Entity<Editor>, cx: &App) -> impl IntoElement {
+ let colors = cx.theme().colors();
+ // All form inputs share tab index 0, so tab order follows render (insertion)
+ // order. Tracking the editor's focus handle makes the field a tab stop and
+ // routes keyboard focus into the editor when tabbed to.
+ let focus_handle = editor.focus_handle(cx).tab_index(0).tab_stop(true);
+ h_flex()
+ .min_w_64()
+ .py_1()
+ .px_2()
+ .h_8()
+ .rounded_md()
+ .border_1()
+ .border_color(colors.border)
+ .bg(colors.editor_background)
+ .track_focus(&focus_handle)
+ .focus(|style| style.border_color(colors.border_focused))
+ .child(editor.clone())
+}
+
+fn render_form_field(
+ settings_window: &SettingsWindow,
+ title: &'static str,
+ description: &'static str,
+ editor: &Entity<Editor>,
+ cx: &mut Context<SettingsWindow>,
+) -> AnyElement {
+ let control = input_box(editor, cx).into_any_element();
+ crate::render_settings_item_layout(
+ settings_window,
+ title,
+ description,
+ control,
+ None,
+ None,
+ None,
+ false,
+ cx,
+ )
+ .into_any_element()
+}
+
+fn render_kv_section(
+ settings_window: &SettingsWindow,
+ title: &'static str,
+ description: &'static str,
+ rows: &[KeyValueRow],
+ kind: McpKvKind,
+ cx: &mut Context<SettingsWindow>,
+) -> AnyElement {
+ let control = v_flex()
+ .min_w_64()
+ .gap_2()
+ .children(rows.iter().enumerate().map(|(ix, row)| {
+ v_flex()
+ .gap_1()
+ .child(
+ h_flex()
+ .gap_1()
+ .items_center()
+ .child(div().flex_1().min_w_0().child(input_box(&row.key, cx)))
+ .child(
+ IconButton::new((kind.remove_id(), ix), IconName::Close)
+ .icon_size(IconSize::Small)
+ .icon_color(Color::Muted)
+ .tooltip(Tooltip::text("Remove"))
+ .on_click(cx.listener(move |this, _, _window, cx| {
+ if let Some(form) = this.mcp_server_form.as_mut() {
+ let rows = kind.rows_mut(form);
+ if ix < rows.len() {
+ rows.remove(ix);
+ }
+ }
+ cx.notify();
+ })),
+ ),
+ )
+ .child(input_box(&row.value, cx))
+ }))
+ .child(
+ Button::new(kind.add_id(), "Add")
+ .style(ButtonStyle::Outlined)
+ .label_size(LabelSize::Small)
+ .start_icon(
+ Icon::new(IconName::Plus)
+ .size(IconSize::Small)
+ .color(Color::Muted),
+ )
+ .on_click(cx.listener(move |this, _, window, cx| {
+ let row = new_kv_row(None, None, window, cx);
+ if let Some(form) = this.mcp_server_form.as_mut() {
+ kind.rows_mut(form).push(row);
+ }
+ cx.notify();
+ })),
+ )
+ .into_any_element();
+
+ crate::render_settings_item_layout(
+ settings_window,
+ title,
+ description,
+ control,
+ None,
+ None,
+ None,
+ false,
+ cx,
+ )
+ .into_any_element()
+}
+
+fn render_form_error(error: SharedString) -> impl IntoElement {
+ h_flex()
+ .w_full()
+ .gap_2()
+ .items_start()
+ .child(
+ Icon::new(IconName::XCircle)
+ .size(IconSize::Small)
+ .color(Color::Error),
+ )
+ .child(Label::new(error).size(LabelSize::Small).color(Color::Error))
+}
+
+fn render_form_actions(cx: &mut Context<SettingsWindow>) -> impl IntoElement {
+ h_flex()
+ .w_full()
+ .gap_2()
+ .justify_end()
+ .pt_2()
+ .child(
+ Button::new("mcp-form-cancel", "Cancel")
+ .style(ButtonStyle::Subtle)
+ .on_click(cx.listener(|this, _, window, cx| {
+ this.mcp_server_form = None;
+ this.pop_sub_page(window, cx);
+ })),
+ )
+ .child(
+ Button::new("mcp-form-save", "Save")
+ .style(ButtonStyle::Filled)
+ .on_click(cx.listener(|this, _, window, cx| {
+ save_mcp_server_form(this, window, cx);
+ })),
+ )
+}
+
+fn save_mcp_server_form(
+ settings_window: &mut SettingsWindow,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+) {
+ let built = {
+ let Some(form) = settings_window.mcp_server_form.as_ref() else {
+ return;
+ };
+ build_settings_from_form(form, cx)
+ };
+
+ let (id, original_id, content) = match built {
+ Ok(value) => value,
+ Err(error) => {
+ if let Some(form) = settings_window.mcp_server_form.as_mut() {
+ form.error = Some(error);
+ }
+ cx.notify();
+ return;
+ }
+ };
+
+ // Reject names that would collide with a *different* existing server. This
+ // covers both adding a new server and renaming an existing one (where the new
+ // name must not clobber another server's configuration).
+ let collides_with_other_server =
+ get_context_server_store(settings_window, cx).is_some_and(|store| {
+ name_collides_with_other_server(&id, original_id.as_ref(), store.read(cx).server_ids())
+ });
+ if collides_with_other_server {
+ if let Some(form) = settings_window.mcp_server_form.as_mut() {
+ form.error = Some(format!("A server named \"{}\" already exists.", id.0).into());
+ }
+ cx.notify();
+ return;
+ }
+
+ let fs = <dyn fs::Fs>::global(cx);
+ settings::update_settings_file(fs, cx, move |settings, _| {
+ if let Some(original_id) = &original_id
+ && original_id.0 != id.0
+ {
+ settings.project.context_servers.remove(&original_id.0);
+ }
+ settings
+ .project
+ .context_servers
+ .insert(id.0.clone(), content);
+ });
+
+ settings_window.mcp_server_form = None;
+ settings_window.pop_sub_page(window, cx);
+}
+
+/// Plain (editor-free) snapshot of the form's contents, so the validation /
+/// build logic can be exercised without a GPUI context.
+struct McpServerFormValues {
+ transport: McpTransport,
+ original_id: Option<ContextServerId>,
+ name: String,
+ command: String,
+ args: String,
+ url: String,
+ timeout: String,
+ oauth_client_id: String,
+ env: Vec<(String, String)>,
+ headers: Vec<(String, String)>,
+}
+
+fn build_settings_from_form(
+ form: &McpServerForm,
+ cx: &App,
+) -> Result<
+ (
+ ContextServerId,
+ Option<ContextServerId>,
+ ContextServerSettingsContent,
+ ),
+ SharedString,
+> {
+ let values = McpServerFormValues {
+ transport: form.transport,
+ original_id: form.original_id.clone(),
+ name: form.name.read(cx).text(cx),
+ command: form.command.read(cx).text(cx),
+ args: form.args.read(cx).text(cx),
+ url: form.url.read(cx).text(cx),
+ timeout: form.timeout.read(cx).text(cx),
+ oauth_client_id: form.oauth_client_id.read(cx).text(cx),
+ env: read_kv(&form.env, cx),
+ headers: read_kv(&form.headers, cx),
+ };
+ build_settings_from_values(&values)
+}
+
+fn read_kv(rows: &[KeyValueRow], cx: &App) -> Vec<(String, String)> {
+ rows.iter()
+ .map(|row| (row.key.read(cx).text(cx), row.value.read(cx).text(cx)))
+ .collect()
+}
+
+fn build_settings_from_values(
+ values: &McpServerFormValues,
+) -> Result<
+ (
+ ContextServerId,
+ Option<ContextServerId>,
+ ContextServerSettingsContent,
+ ),
+ SharedString,
+> {
+ let name = values.name.trim().to_string();
+ if name.is_empty() {
+ return Err("Server name is required.".into());
+ }
+
+ let timeout = parse_timeout(&values.timeout)?;
+
+ let content = match values.transport {
+ McpTransport::Stdio => {
+ let command = values.command.trim().to_string();
+ if command.is_empty() {
+ return Err("Command is required.".into());
+ }
+ let args = values
+ .args
+ .split_whitespace()
+ .map(|arg| arg.to_string())
+ .collect::<Vec<_>>();
+ let env = collect_kv(&values.env, "environment variable")?;
+ ContextServerSettingsContent::Stdio {
+ enabled: true,
+ remote: false,
+ command: ContextServerCommand {
+ path: command.into(),
+ args,
+ env: (!env.is_empty()).then_some(env),
+ timeout,
+ },
+ }
+ }
+ McpTransport::Http => {
+ let url = values.url.trim().to_string();
+ if url.is_empty() {
+ return Err("URL is required.".into());
+ }
+ // Validate the URL on save (a deliberate action) rather than on every
+ // render, so a clearly invalid URL is reported to the user instead of
+ // being silently written and failing later when the server starts.
+ if let Err(error) = url::Url::parse(&url) {
+ return Err(format!("Invalid URL: {error}").into());
+ }
+ let headers = collect_kv(&values.headers, "header")?;
+ let oauth_client_id = values.oauth_client_id.trim().to_string();
+ let oauth = (!oauth_client_id.is_empty()).then(|| OAuthClientSettings {
+ client_id: oauth_client_id,
+ client_secret: None,
+ });
+ ContextServerSettingsContent::Http {
+ enabled: true,
+ url,
+ headers,
+ timeout,
+ oauth,
+ }
+ }
+ };
+
+ Ok((
+ ContextServerId(name.into()),
+ values.original_id.clone(),
+ content,
+ ))
+}
+
+/// Returns a human-readable error when a server's configured settings are
+/// invalid in a way that prevents it from starting (currently: an HTTP server
+/// whose URL cannot be parsed). Used to surface misconfiguration in the list.
+fn settings_validation_error(settings: Option<&ContextServerSettings>) -> Option<SharedString> {
+ match settings? {
+ ContextServerSettings::Http { url, .. } if url::Url::parse(url).is_err() => {
+ Some("Invalid URL in settings.".into())
+ }
+ _ => None,
+ }
+}
+
+/// Returns whether saving under `id` would overwrite a *different* existing
+/// server. Editing a server in place (`id == original_id`) is allowed.
+fn name_collides_with_other_server(
+ id: &ContextServerId,
+ original_id: Option<&ContextServerId>,
+ existing_ids: &[ContextServerId],
+) -> bool {
+ original_id.is_none_or(|original| original.0 != id.0)
+ && existing_ids.iter().any(|existing| existing.0 == id.0)
+}
+
+fn parse_timeout(text: &str) -> Result<Option<u64>, SharedString> {
+ let text = text.trim();
+ if text.is_empty() {
+ return Ok(None);
+ }
+ text.parse::<u64>()
+ .map(Some)
+ .map_err(|_| "Timeout must be a positive whole number of seconds.".into())
+}
+
+fn collect_kv(
+ rows: &[(String, String)],
+ label: &str,
+) -> Result<HashMap<String, String>, SharedString> {
+ let mut map = HashMap::default();
+ for (key, value) in rows {
+ let key = key.trim().to_string();
+ if key.is_empty() {
+ continue;
+ }
+ if map.contains_key(&key) {
+ return Err(format!("Duplicate {label} \"{key}\".").into());
+ }
+ map.insert(key, value.clone());
+ }
+ Ok(map)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn values(transport: McpTransport) -> McpServerFormValues {
+ McpServerFormValues {
+ transport,
+ original_id: None,
+ name: "my-server".into(),
+ command: String::new(),
+ args: String::new(),
+ url: String::new(),
+ timeout: String::new(),
+ oauth_client_id: String::new(),
+ env: Vec::new(),
+ headers: Vec::new(),
+ }
+ }
+
+ fn id(name: &str) -> ContextServerId {
+ ContextServerId(name.into())
+ }
+
+ #[test]
+ fn parse_timeout_handles_empty_and_invalid() {
+ assert_eq!(parse_timeout(""), Ok(None));
+ assert_eq!(parse_timeout(" "), Ok(None));
+ assert_eq!(parse_timeout("60"), Ok(Some(60)));
+ assert_eq!(parse_timeout(" 90 "), Ok(Some(90)));
+ assert!(parse_timeout("abc").is_err());
+ assert!(parse_timeout("-5").is_err());
+ assert!(parse_timeout("1.5").is_err());
+ }
+
+ #[test]
+ fn requires_server_name() {
+ let mut values = values(McpTransport::Stdio);
+ values.name = " ".into();
+ values.command = "/bin/server".into();
+ assert_eq!(
+ build_settings_from_values(&values).unwrap_err().as_ref(),
+ "Server name is required."
+ );
+ }
+
+ #[test]
+ fn requires_command_for_local_server() {
+ let values = values(McpTransport::Stdio);
+ assert_eq!(
+ build_settings_from_values(&values).unwrap_err().as_ref(),
+ "Command is required."
+ );
+ }
+
+ #[test]
+ fn requires_url_for_remote_server() {
+ let values = values(McpTransport::Http);
+ assert_eq!(
+ build_settings_from_values(&values).unwrap_err().as_ref(),
+ "URL is required."
+ );
+ }
+
+ #[test]
+ fn rejects_invalid_url() {
+ let mut values = values(McpTransport::Http);
+ values.url = "not a url".into();
+ let error = build_settings_from_values(&values).unwrap_err();
+ assert!(
+ error.starts_with("Invalid URL"),
+ "unexpected error: {error}"
+ );
+ }
+
+ #[test]
+ fn rejects_invalid_timeout() {
+ let mut values = values(McpTransport::Stdio);
+ values.command = "/bin/server".into();
+ values.timeout = "soon".into();
+ assert_eq!(
+ build_settings_from_values(&values).unwrap_err().as_ref(),
+ "Timeout must be a positive whole number of seconds."
+ );
+ }
+
+ #[test]
+ fn rejects_duplicate_environment_variables() {
+ let mut values = values(McpTransport::Stdio);
+ values.command = "/bin/server".into();
+ values.env = vec![("FOO".into(), "1".into()), ("FOO".into(), "2".into())];
+ assert_eq!(
+ build_settings_from_values(&values).unwrap_err().as_ref(),
+ "Duplicate environment variable \"FOO\"."
+ );
+ }
+
+ #[test]
+ fn rejects_duplicate_headers() {
+ let mut values = values(McpTransport::Http);
+ values.url = "https://example.com/mcp".into();
+ values.headers = vec![
+ ("Authorization".into(), "a".into()),
+ ("Authorization".into(), "b".into()),
+ ];
+ assert_eq!(
+ build_settings_from_values(&values).unwrap_err().as_ref(),
+ "Duplicate header \"Authorization\"."
+ );
+ }
+
+ #[test]
+ fn builds_local_server() {
+ let mut values = values(McpTransport::Stdio);
+ values.name = " local ".into();
+ values.command = "/usr/bin/server".into();
+ values.args = "--flag value".into();
+ values.timeout = "30".into();
+ // Empty values are kept, but rows with a blank key are ignored.
+ values.env = vec![
+ ("KEY".into(), "VALUE".into()),
+ ("EMPTY".into(), String::new()),
+ (" ".into(), "ignored".into()),
+ ];
+
+ let (id, original_id, content) = build_settings_from_values(&values).unwrap();
+ assert_eq!(id.0.as_ref(), "local");
+ assert_eq!(original_id, None);
+
+ let expected_env = HashMap::from_iter([
+ ("KEY".to_string(), "VALUE".to_string()),
+ ("EMPTY".to_string(), String::new()),
+ ]);
+ assert_eq!(
+ content,
+ ContextServerSettingsContent::Stdio {
+ enabled: true,
+ remote: false,
+ command: ContextServerCommand {
+ path: "/usr/bin/server".into(),
+ args: vec!["--flag".into(), "value".into()],
+ env: Some(expected_env),
+ timeout: Some(30),
+ },
+ }
+ );
+ }
+
+ #[test]
+ fn builds_remote_server() {
+ let mut values = values(McpTransport::Http);
+ values.name = "remote".into();
+ values.url = "https://example.com/mcp".into();
+ values.oauth_client_id = "client-123".into();
+ values.headers = vec![("Authorization".into(), "Bearer token".into())];
+
+ let (id, _, content) = build_settings_from_values(&values).unwrap();
+ assert_eq!(id.0.as_ref(), "remote");
+
+ let expected_headers =
+ HashMap::from_iter([("Authorization".to_string(), "Bearer token".to_string())]);
+ assert_eq!(
+ content,
+ ContextServerSettingsContent::Http {
+ enabled: true,
+ url: "https://example.com/mcp".into(),
+ headers: expected_headers,
+ timeout: None,
+ oauth: Some(OAuthClientSettings {
+ client_id: "client-123".into(),
+ client_secret: None,
+ }),
+ }
+ );
+ }
+
+ #[test]
+ fn flags_invalid_url_in_settings() {
+ let http = |url: &str| ContextServerSettings::Http {
+ enabled: true,
+ url: url.into(),
+ headers: HashMap::default(),
+ timeout: None,
+ oauth: None,
+ };
+ assert_eq!(
+ settings_validation_error(Some(&http("not a url")))
+ .unwrap()
+ .as_ref(),
+ "Invalid URL in settings."
+ );
+ assert!(settings_validation_error(Some(&http("https://example.com/mcp"))).is_none());
+ assert!(settings_validation_error(None).is_none());
+ }
+
+ #[test]
+ fn name_collision_covers_new_and_rename() {
+ let existing = vec![id("foo"), id("bar")];
+
+ // New server taking an existing name collides.
+ assert!(name_collides_with_other_server(&id("foo"), None, &existing));
+ // New server with a free name is fine.
+ assert!(!name_collides_with_other_server(
+ &id("baz"),
+ None,
+ &existing
+ ));
+ // Editing a server in place is allowed even though the name "exists".
+ assert!(!name_collides_with_other_server(
+ &id("foo"),
+ Some(&id("foo")),
+ &existing
+ ));
+ // Renaming onto a different server's name collides.
+ assert!(name_collides_with_other_server(
+ &id("bar"),
+ Some(&id("foo")),
+ &existing
+ ));
+ // Renaming to a free name is fine.
+ assert!(!name_collides_with_other_server(
+ &id("baz"),
+ Some(&id("foo")),
+ &existing
+ ));
+ }
+}
diff --git a/crates/settings_ui/src/pages/tool_permissions_setup.rs b/crates/settings_ui/src/pages/tool_permissions_setup.rs
index a19a3c2100f..feb0ab173dc 100644
--- a/crates/settings_ui/src/pages/tool_permissions_setup.rs
+++ b/crates/settings_ui/src/pages/tool_permissions_setup.rs
@@ -288,6 +288,7 @@ fn render_tool_list_item(
tool_name,
"Tool Permissions",
None,
+ true,
render_fn,
window,
cx,
diff --git a/crates/settings_ui/src/settings_ui.rs b/crates/settings_ui/src/settings_ui.rs
index 57c284a228e..a1b69c9a7be 100644
--- a/crates/settings_ui/src/settings_ui.rs
+++ b/crates/settings_ui/src/settings_ui.rs
@@ -58,7 +58,10 @@ use crate::components::{
SettingsSectionHeader, font_picker, icon_theme_picker, render_ollama_model_picker,
theme_picker,
};
-use crate::pages::{render_input_audio_device_dropdown, render_output_audio_device_dropdown};
+use crate::pages::{
+ CustomAgentForm, McpServerForm, render_input_audio_device_dropdown,
+ render_output_audio_device_dropdown,
+};
const NAVBAR_CONTAINER_TAB_INDEX: isize = 0;
const NAVBAR_GROUP_TAB_INDEX: isize = 1;
@@ -886,9 +889,27 @@ pub struct SettingsWindow {
pub(crate) hidden_deleted_skill_directory_paths: HashSet<PathBuf>,
pub(crate) regex_validation_error: Option<String>,
last_copied_link_path: Option<&'static str>,
+ /// Cached configuration views per provider, created lazily. Holds the
+ /// provider's chosen presentation ([`Inline`] or [`SubPage`]).
+ pub(crate) provider_configuration_views:
+ HashMap<language_model::LanguageModelProviderId, language_model::ProviderConfigurationView>,
+ /// The provider whose configuration sub-page is currently open, if any.
+ pub(crate) configuring_provider: Option<language_model::LanguageModelProviderId>,
/// Directory path of the skill whose share link was most recently copied,
/// used to show a transient "copied" checkmark on its share button.
pub(crate) last_copied_skill_directory_path: Option<PathBuf>,
+ /// State for the active "add/edit custom MCP server" form sub-page, if open.
+ pub(crate) mcp_server_form: Option<McpServerForm>,
+ /// Stable focus handle for the MCP "Add Server" button, so it can show a
+ /// focus ring when the page auto-focuses it on open (which happens via mouse,
+ /// where `focus_visible` styling would otherwise be suppressed).
+ pub(crate) mcp_add_server_focus_handle: FocusHandle,
+ /// State for the active "add/edit custom external agent" form sub-page, if open.
+ pub(crate) custom_agent_form: Option<CustomAgentForm>,
+ /// Stable focus handle for the external agents "Add Agent" button, so it can
+ /// show a focus ring when the page auto-focuses it on open (which happens via
+ /// mouse, where `focus_visible` styling would otherwise be suppressed).
+ pub(crate) external_agent_add_focus_handle: FocusHandle,
skill_creator_page: Option<(Entity<pages::SkillCreatorPage>, Subscription)>,
}
@@ -1279,19 +1300,23 @@ impl SettingsPageItem {
}
}
-fn render_settings_item(
+/// Shared layout for both JSON-backed and non-JSON-backed setting items.
+///
+/// Renders title + description on the left, control on the right, with
+/// optional reset button and copy-link icon.
+fn render_settings_item_layout(
settings_window: &SettingsWindow,
- setting_item: &SettingItem,
- file: SettingsUiFile,
+ title: &'static str,
+ description: &'static str,
control: AnyElement,
+ reset_fn: Option<Box<dyn Fn(&mut Window, &mut App)>>,
+ modified_in: Option<String>,
+ json_path: Option<&'static str>,
sub_field: bool,
cx: &mut Context<'_, SettingsWindow>,
) -> Stateful<Div> {
- let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
- let file_set_in = SettingsUiFile::from_settings(found_in_file.clone());
-
h_flex()
- .id(setting_item.title)
+ .id(title)
.min_w_0()
.justify_between()
.child(
@@ -1304,84 +1329,38 @@ fn render_settings_item(
h_flex()
.w_full()
.gap_1()
- .child(Label::new(SharedString::new_static(setting_item.title)))
- .when_some(
- if sub_field {
- None
- } else {
- setting_item
- .field
- .reset_to_default_fn(&file, &found_in_file, cx)
- },
- |this, reset_to_default| {
- this.child(
- IconButton::new("reset-to-default-btn", IconName::Undo)
- .icon_color(Color::Muted)
- .icon_size(IconSize::Small)
- .tooltip(Tooltip::text("Reset to Default"))
- .on_click({
- move |_, window, cx| {
- reset_to_default(window, cx);
- }
- }),
- )
- },
- )
- .when_some(
- file_set_in.filter(|file_set_in| file_set_in != &file),
- |this, file_set_in| {
- this.child(
- Label::new(format!(
- "— Modified in {}",
- settings_window
- .display_name(&file_set_in)
- .expect("File name should exist")
- ))
+ .child(Label::new(SharedString::new_static(title)))
+ .when_some(reset_fn, |this, reset_to_default| {
+ this.child(
+ IconButton::new("reset-to-default-btn", IconName::Undo)
+ .icon_color(Color::Muted)
+ .icon_size(IconSize::Small)
+ .tooltip(Tooltip::text("Reset to Default"))
+ .on_click(move |_, window, cx| {
+ reset_to_default(window, cx);
+ }),
+ )
+ })
+ .when_some(modified_in, |this, modified_in| {
+ this.child(
+ Label::new(format!("\u{2014} Modified in {modified_in}"))
.color(Color::Muted)
.size(LabelSize::Small),
- )
- },
- ),
+ )
+ }),
)
.child(
- Label::new(SharedString::new_static(setting_item.description))
+ Label::new(SharedString::new_static(description))
.size(LabelSize::Small)
.color(Color::Muted)
.render_code_spans(),
),
)
- .child(if setting_item.field.is_overridden_by_organization(cx) {
- h_flex()
- .gap_2()
- .child(
- div()
- .id(format!(
- "{}-organization-configuration-warning",
- setting_item.title
- ))
- .child(
- Icon::new(IconName::Warning)
- .size(IconSize::Small)
- .color(Color::Warning),
- )
- .tooltip(|_, cx| {
- Tooltip::with_meta(
- "Overridden by Organization",
- None,
- "Contact your organization admins to adjust this setting.",
- cx,
- )
- }),
- )
- .child(control)
- .into_any_element()
- } else {
- control.into_any_element()
- })
+ .child(control)
.when(settings_window.sub_page_stack.is_empty(), |this| {
this.child(render_settings_item_link(
- setting_item.description,
- setting_item.field.json_path(),
+ description,
+ json_path,
sub_field,
settings_window,
cx,
@@ -1389,6 +1368,71 @@ fn render_settings_item(
})
}
+fn render_settings_item(
+ settings_window: &SettingsWindow,
+ setting_item: &SettingItem,
+ file: SettingsUiFile,
+ control: AnyElement,
+ sub_field: bool,
+ cx: &mut Context<'_, SettingsWindow>,
+) -> Stateful<Div> {
+ let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
+ let file_set_in = SettingsUiFile::from_settings(found_in_file.clone());
+
+ let reset_fn = if sub_field {
+ None
+ } else {
+ setting_item
+ .field
+ .reset_to_default_fn(&file, &found_in_file, cx)
+ };
+
+ let modified_in = file_set_in
+ .filter(|f| f != &file)
+ .and_then(|f| settings_window.display_name(&f));
+
+ let control = if setting_item.field.is_overridden_by_organization(cx) {
+ h_flex()
+ .gap_2()
+ .child(
+ div()
+ .id(format!(
+ "{}-organization-configuration-warning",
+ setting_item.title
+ ))
+ .child(
+ Icon::new(IconName::Warning)
+ .size(IconSize::Small)
+ .color(Color::Warning),
+ )
+ .tooltip(|_, cx| {
+ Tooltip::with_meta(
+ "Overridden by Organization",
+ None,
+ "Contact your organization admins to adjust this setting.",
+ cx,
+ )
+ }),
+ )
+ .child(control)
+ .into_any_element()
+ } else {
+ control
+ };
+
+ render_settings_item_layout(
+ settings_window,
+ setting_item.title,
+ setting_item.description,
+ control,
+ reset_fn,
+ modified_in,
+ setting_item.field.json_path(),
+ sub_field,
+ cx,
+ )
+}
+
fn render_settings_item_link(
id: impl Into<ElementId>,
json_path: Option<&'static str>,
@@ -1864,7 +1908,13 @@ impl SettingsWindow {
regex_validation_error: None,
list_state,
last_copied_link_path: None,
+ provider_configuration_views: HashMap::default(),
+ configuring_provider: None,
last_copied_skill_directory_path: None,
+ mcp_server_form: None,
+ mcp_add_server_focus_handle: cx.focus_handle(),
+ custom_agent_form: None,
+ external_agent_add_focus_handle: cx.focus_handle(),
skill_creator_page: None,
};
@@ -1984,7 +2034,9 @@ impl SettingsWindow {
move |this: &mut SettingsWindow,
window: &mut Window,
cx: &mut Context<SettingsWindow>| {
- this.open_and_scroll_to_navbar_entry(entry_index, None, false, window, cx);
+ if this.sub_page_stack.is_empty() {
+ this.open_and_scroll_to_navbar_entry(entry_index, None, false, window, cx);
+ }
},
);
focus_subscriptions.push(subscription);
@@ -2481,6 +2533,7 @@ impl SettingsWindow {
let is_new_page = self.navbar_entries[self.navbar_entry].page_index
!= self.navbar_entries[navbar_entry].page_index;
+
self.navbar_entry = navbar_entry;
// We only need to reset visible items when updating matches
@@ -3761,7 +3814,16 @@ impl SettingsWindow {
.id("settings-ui-page")
.on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
if !this.sub_page_stack.is_empty() {
+ // Keep Tab navigation within the sub-page content. Global
+ // `focus_next` would otherwise wrap past the last control to
+ // the navbar; instead, when focus leaves the content region we
+ // wrap back to the first content tab stop.
+ let content_handle = this.content_focus_handle.focus_handle(cx);
window.focus_next(cx);
+ if !content_handle.contains_focused(window, cx) {
+ content_handle.focus(window, cx);
+ window.focus_next(cx);
+ }
return;
}
for (logical_index, (actual_index, _)) in this.visible_page_items().enumerate() {
@@ -4016,6 +4078,7 @@ impl SettingsWindow {
title: impl Into<SharedString>,
section_header: impl Into<SharedString>,
json_path: Option<&'static str>,
+ in_json: bool,
render: fn(
&SettingsWindow,
&ScrollHandle,
@@ -4031,7 +4094,7 @@ impl SettingsWindow {
r#type: SubPageType::default(),
description: None,
json_path,
- in_json: true,
+ in_json,
files: USER,
render,
};
@@ -4204,7 +4267,7 @@ impl SettingsWindow {
false
}
- fn pop_sub_page(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
+ pub(crate) fn pop_sub_page(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
self.regex_validation_error = None;
if let Some(popped) = self.sub_page_stack.pop()
&& popped.link.r#type == SubPageType::SkillCreator
@@ -5020,7 +5083,13 @@ pub mod test {
hidden_deleted_skill_directory_paths: HashSet::default(),
regex_validation_error: None,
last_copied_link_path: None,
+ provider_configuration_views: HashMap::default(),
+ configuring_provider: None,
last_copied_skill_directory_path: None,
+ mcp_server_form: None,
+ mcp_add_server_focus_handle: cx.focus_handle(),
+ custom_agent_form: None,
+ external_agent_add_focus_handle: cx.focus_handle(),
skill_creator_page: None,
}
}
@@ -5149,7 +5218,13 @@ pub mod test {
hidden_deleted_skill_directory_paths: HashSet::default(),
regex_validation_error: None,
last_copied_link_path: None,
+ provider_configuration_views: HashMap::default(),
+ configuring_provider: None,
last_copied_skill_directory_path: None,
+ mcp_server_form: None,
+ mcp_add_server_focus_handle: cx.focus_handle(),
+ custom_agent_form: None,
+ external_agent_add_focus_handle: cx.focus_handle(),
skill_creator_page: None,
};
diff --git a/crates/zed/src/visual_test_runner.rs b/crates/zed/src/visual_test_runner.rs
index 609f5c180eb..0f4e84abcfc 100644
--- a/crates/zed/src/visual_test_runner.rs
+++ b/crates/zed/src/visual_test_runner.rs
@@ -2438,6 +2438,7 @@ fn run_tool_permissions_visual_tests(
"Terminal",
"Configure Tool Rules",
None,
+ true,
settings_ui::pages::render_terminal_tool_config,
window,
cx,