mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-18 16:08:55 +00:00
feat(agents): multi-level MCP hub, CLI config discovery, and per-session MCP picker (#3626)
MCP servers can be configured at user and project level, imported from pasted JSON, tested with their tool list shown, and discovered from other agent CLIs' config files. Discovery reports only env and header key names, never values, and importing is explicit; external config files are never modified. Testing a server requires a trusted project. Each agent session can turn individual servers on or off from a picker; the overrides are stored with the task and applied when the session opens. Closes #3608 Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com>
This commit is contained in:
@@ -155,6 +155,7 @@ async fn a_task_runs_on_a_v2_agent_and_resumes_its_session() {
|
||||
config: vec![AgentConfigChoice { id: "model".into(), value: "haiku".into() }],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
+90
-11
@@ -208,10 +208,19 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp_servers_for_session(&self, provider: &str, init: &acp::Negotiated) -> Vec<Value> {
|
||||
let mut servers = mcp_servers_for(init.mcp_stdio(), &self.paths.project_root);
|
||||
fn mcp_servers_for_session(
|
||||
&self,
|
||||
provider: &str,
|
||||
init: &acp::Negotiated,
|
||||
overrides: &BTreeMap<String, bool>,
|
||||
) -> Vec<Value> {
|
||||
let mut servers = if overrides.get(mcp::BUILTIN_MCP_NAME) == Some(&false) {
|
||||
Vec::new()
|
||||
} else {
|
||||
mcp_servers_for(init.mcp_stdio(), &self.paths.project_root)
|
||||
};
|
||||
let configured = self.mcp_servers_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
servers.extend(mcp::acp_mcp_servers(&configured, provider, init));
|
||||
servers.extend(mcp::acp_mcp_servers(&configured, provider, init, overrides));
|
||||
servers
|
||||
}
|
||||
|
||||
@@ -409,6 +418,8 @@ struct Task {
|
||||
/// Bumped when the agent's last background task finishes: an idle release scheduled
|
||||
/// before that is void, the usual delay starts over from the report.
|
||||
idle_epoch: AtomicU64,
|
||||
/// Turned on when per-session MCP overrides changed while a turn was busy; dropped once idle.
|
||||
mcp_reload_pending: AtomicBool,
|
||||
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
|
||||
config_sent: Mutex<HashSet<(String, String)>>,
|
||||
dirty: Mutex<BTreeSet<(Session, usize)>>,
|
||||
@@ -724,6 +735,7 @@ impl AgentManager {
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
};
|
||||
let handle = self.register(TaskFile {
|
||||
task: task.clone(),
|
||||
@@ -815,6 +827,7 @@ impl AgentManager {
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
mcp_overrides: req.mcp_overrides,
|
||||
};
|
||||
let handle = self.register(TaskFile {
|
||||
task: task.clone(),
|
||||
@@ -916,6 +929,7 @@ impl AgentManager {
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
mcp_overrides: req.mcp_overrides,
|
||||
config,
|
||||
};
|
||||
let handle = self.register(TaskFile {
|
||||
@@ -1117,9 +1131,11 @@ impl AgentManager {
|
||||
if !live.capabilities.fork || (keep < total && !live.capabilities.rollback) {
|
||||
return Err(IdeError::invalid("this agent can't copy a conversation from there"));
|
||||
}
|
||||
let cwd = source.state.lock().task.cwd.0.clone();
|
||||
let provider_id = source.state.lock().task.provider.clone();
|
||||
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init);
|
||||
let (cwd, provider_id, mcp_overrides) = {
|
||||
let s = source.state.lock();
|
||||
(s.task.cwd.0.clone(), s.task.provider.clone(), s.task.mcp_overrides.clone())
|
||||
};
|
||||
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
|
||||
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
|
||||
let reply: Value = live
|
||||
.peer
|
||||
@@ -1603,6 +1619,43 @@ impl AgentManager {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Updates per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
|
||||
/// When the task is idle and holds a resumable live session without running background tasks,
|
||||
/// stops the idle process so the next turn reloads the session with the updated MCP servers;
|
||||
/// when busy, schedules the reload for as soon as the turn finishes.
|
||||
pub fn set_mcp_overrides(&self, id: &str, overrides: BTreeMap<String, bool>) -> IdeResult<AgentTask> {
|
||||
let task = self.task(id)?;
|
||||
let cleaned: BTreeMap<String, bool> = overrides
|
||||
.into_iter()
|
||||
.filter_map(|(k, v)| {
|
||||
let k = k.trim();
|
||||
(!k.is_empty()).then(|| (k.to_owned(), v))
|
||||
})
|
||||
.collect();
|
||||
let (changed, busy, has_bg, out) = {
|
||||
let mut s = task.state.lock();
|
||||
if s.task.status == AgentStatus::Archived {
|
||||
return Err(IdeError::invalid("the task is archived"));
|
||||
}
|
||||
let changed = s.task.mcp_overrides != cleaned;
|
||||
if changed {
|
||||
s.task.mcp_overrides = cleaned;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
|
||||
};
|
||||
if changed {
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
if busy || has_bg || !task.permissions.lock().is_empty() {
|
||||
task.mcp_reload_pending.store(true, Ordering::Release);
|
||||
} else {
|
||||
task.recycle_resumable_session();
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Stops every agent (project closed).
|
||||
pub fn shutdown(&self) {
|
||||
for task in self.tasks.read().values() {
|
||||
@@ -1647,6 +1700,7 @@ impl Task {
|
||||
turn_started: AtomicBool::new(false),
|
||||
turns: AtomicU64::new(0),
|
||||
idle_epoch: AtomicU64::new(0),
|
||||
mcp_reload_pending: AtomicBool::new(false),
|
||||
config_sent: Mutex::new(HashSet::new()),
|
||||
dirty: Mutex::new(BTreeSet::new()),
|
||||
streamed: Mutex::new(HashMap::new()),
|
||||
@@ -1704,7 +1758,7 @@ impl Task {
|
||||
|
||||
fn emit_task(&self) {
|
||||
let task = self.state.lock().task.clone();
|
||||
self.shared.emit(AgentEvent::Task { task });
|
||||
self.shared.emit(AgentEvent::Task { task: Box::new(task) });
|
||||
}
|
||||
|
||||
/// Shows (or clears) the agent's pending retry; emitted only when it changes.
|
||||
@@ -1894,6 +1948,12 @@ impl Task {
|
||||
if stop != "cancelled" {
|
||||
self.emit_attention(AgentAttentionReason::Finished);
|
||||
}
|
||||
if self.mcp_reload_pending.swap(false, Ordering::AcqRel)
|
||||
&& self.state.lock().background_tasks.is_empty()
|
||||
{
|
||||
self.recycle_resumable_session();
|
||||
return;
|
||||
}
|
||||
return self.release_when_idle();
|
||||
}
|
||||
(None, Err(failure)) => return self.fail(failure),
|
||||
@@ -1901,6 +1961,20 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops an idle resumable live session so the next turn reloads it with fresh MCP servers.
|
||||
fn recycle_resumable_session(&self) {
|
||||
self.mcp_reload_pending.store(false, Ordering::Release);
|
||||
let live = {
|
||||
let mut live = self.live.lock();
|
||||
if live.as_ref().is_some_and(|l| l.resumable && !l.peer.is_closed()) { live.take() } else { None }
|
||||
};
|
||||
if let Some(live) = live {
|
||||
tracing::debug!("agent task {}: restarting idle resumable session for MCP override update", self.id);
|
||||
live.peer.kill();
|
||||
self.clear_shown_background();
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops the agent's process once the task has stayed idle for [`IDLE_RELEASE`], so
|
||||
/// finished tasks don't keep an agent (and what it started) running. Only an agent that
|
||||
/// reloads its session: the next message starts it again with the conversation intact.
|
||||
@@ -2231,7 +2305,8 @@ impl Task {
|
||||
let sign_in_message = spec.sign_in_message(&init.auth_methods);
|
||||
let can_load = init.load_session();
|
||||
let (capabilities, embedded) = capabilities_of(&init);
|
||||
let mcp_servers = self.shared.mcp_servers_for_session(provider_id, &init);
|
||||
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
|
||||
let mcp_servers = self.shared.mcp_servers_for_session(provider_id, &init, &mcp_overrides);
|
||||
// Agents that compare canonical paths fail in a symlinked directory (macOS `/tmp`).
|
||||
let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned();
|
||||
|
||||
@@ -3047,9 +3122,13 @@ fn embeddable(path: &Path) -> Option<String> {
|
||||
/// A task file from before a field existed, with that field's empty value.
|
||||
fn upgrade(mut file: Value) -> Value {
|
||||
if let Some(task) = file.get_mut("task").and_then(Value::as_object_mut) {
|
||||
for (key, empty) in
|
||||
[("config", json!([])), ("commands", json!([])), ("usage", Value::Null), ("queue", json!([]))]
|
||||
{
|
||||
for (key, empty) in [
|
||||
("config", json!([])),
|
||||
("commands", json!([])),
|
||||
("usage", Value::Null),
|
||||
("queue", json!([])),
|
||||
("mcpOverrides", json!({})),
|
||||
] {
|
||||
task.entry(key).or_insert(empty);
|
||||
}
|
||||
}
|
||||
|
||||
+822
-64
@@ -1,13 +1,24 @@
|
||||
//! Model Context Protocol (MCP) server configurations stored in OpenIDEA's own settings
|
||||
//! (global `settings.toml` and project `.openidea/settings.toml`), passed to ACP agents in
|
||||
//! `session/new`, `session/load`, and `session/fork`, plus one-way import from `.mcp.json` /
|
||||
//! `.vscode/mcp.json`.
|
||||
//! `session/new`, `session/load`, and `session/fork`, plus discovery and one-way import from
|
||||
//! external CLI and workspace MCP configuration files.
|
||||
|
||||
use crate::acp::Negotiated;
|
||||
use crate::{AgentMcpServer, McpKeyValue, McpScope, McpServer, McpServerInput, McpTransport};
|
||||
use crate::{
|
||||
AgentMcpServer, McpDiscoveredServer, McpExternalSource, McpImportSelection, McpKeyValue, McpProbeResult, McpScope,
|
||||
McpServer, McpServerInput, McpToolSummary, McpTransport,
|
||||
};
|
||||
use ide_core::IpcPath;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Reserved server name for OpenIDEA's built-in IDE MCP server in per-session overrides.
|
||||
pub const BUILTIN_MCP_NAME: &str = "openidea";
|
||||
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(12);
|
||||
const PROBE_PROTOCOL_VERSION: &str = "2024-11-05";
|
||||
|
||||
/// Stable ID for a server in a given scope (`"user::<name>"` or `"workspace::<name>"`).
|
||||
pub fn server_id(scope: McpScope, name: &str) -> String {
|
||||
@@ -56,6 +67,7 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
|
||||
url: cfg.url.clone(),
|
||||
headers: cfg.headers.iter().map(|(k, v)| McpKeyValue { name: k.clone(), value: v.clone() }).collect(),
|
||||
agents: cfg.agents.clone(),
|
||||
unapproved: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,8 +87,15 @@ fn matches_agent(agents: &[String], provider: &str) -> bool {
|
||||
}
|
||||
|
||||
/// Builds the ACP `mcpServers` array for `session/new`, `session/load`, and `session/fork`.
|
||||
/// Workspace entries take precedence over User entries with the same name.
|
||||
pub(crate) fn acp_mcp_servers(all: &[McpServer], provider: &str, init: &Negotiated) -> Vec<Value> {
|
||||
/// Workspace entries take precedence over User entries with the same name. Per-session
|
||||
/// `overrides` (`server_name` -> `enabled`) can enable a disabled server or disable an enabled one
|
||||
/// for this session only.
|
||||
pub(crate) fn acp_mcp_servers(
|
||||
all: &[McpServer],
|
||||
provider: &str,
|
||||
init: &Negotiated,
|
||||
overrides: &BTreeMap<String, bool>,
|
||||
) -> Vec<Value> {
|
||||
let supports_stdio = init.mcp_stdio();
|
||||
let supports_http = init.mcp("http");
|
||||
let supports_sse = init.mcp("sse");
|
||||
@@ -87,7 +106,16 @@ pub(crate) fn acp_mcp_servers(all: &[McpServer], provider: &str, init: &Negotiat
|
||||
all.iter().filter(|s| s.scope == McpScope::Workspace).chain(all.iter().filter(|s| s.scope == McpScope::User));
|
||||
|
||||
for srv in ordered {
|
||||
if !srv.enabled || !matches_agent(&srv.agents, provider) || !seen.insert(srv.name.clone()) {
|
||||
if srv.unapproved {
|
||||
continue;
|
||||
}
|
||||
let explicit = overrides.get(&srv.name).copied();
|
||||
let active = explicit.unwrap_or(srv.enabled);
|
||||
if !active || !seen.insert(srv.name.clone()) {
|
||||
continue;
|
||||
}
|
||||
// An explicit per-session enable (`Some(true)`) overrides the server's default agent filter.
|
||||
if explicit != Some(true) && !matches_agent(&srv.agents, provider) {
|
||||
continue;
|
||||
}
|
||||
match srv.transport {
|
||||
@@ -276,6 +304,306 @@ pub fn apply_import(workspace: &mut BTreeMap<String, AgentMcpServer>, workspace_
|
||||
added
|
||||
}
|
||||
|
||||
/// Parses a raw MCP JSON snippet pasted by the user and merges its servers into `user` or
|
||||
/// `workspace`. Supports `{"mcpServers": {...}}`, `{"servers": {...}}`, top-level server maps
|
||||
/// (`{"my-server": {"command": ...}}`), and single-server objects when `fallback_name` is given.
|
||||
pub fn apply_save_json(
|
||||
user: &mut BTreeMap<String, AgentMcpServer>,
|
||||
workspace: &mut BTreeMap<String, AgentMcpServer>,
|
||||
has_workspace: bool,
|
||||
scope: McpScope,
|
||||
raw_json: &str,
|
||||
fallback_name: Option<&str>,
|
||||
agents: Vec<String>,
|
||||
) -> Result<Vec<String>, String> {
|
||||
if scope == McpScope::Workspace && !has_workspace {
|
||||
return Err("Open a project to configure workspace MCP servers".into());
|
||||
}
|
||||
let parsed = parse_mcp_json_text(raw_json, fallback_name)?;
|
||||
if parsed.is_empty() {
|
||||
return Err("No valid MCP servers found in JSON".into());
|
||||
}
|
||||
let normalized_agents = normalize_agents_list(agents);
|
||||
let target = match scope {
|
||||
McpScope::User => user,
|
||||
McpScope::Workspace => workspace,
|
||||
};
|
||||
let mut saved_names = Vec::with_capacity(parsed.len());
|
||||
for (name, mut srv) in parsed {
|
||||
if srv.agents.is_empty() && !normalized_agents.is_empty() {
|
||||
srv.agents = normalized_agents.clone();
|
||||
}
|
||||
saved_names.push(name.clone());
|
||||
target.insert(name, srv);
|
||||
}
|
||||
Ok(saved_names)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum SourceFormat {
|
||||
Jsonc,
|
||||
CodexToml,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct SourceSpec {
|
||||
id: &'static str,
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
format: SourceFormat,
|
||||
suggested_scope: McpScope,
|
||||
native_provider: Option<&'static str>,
|
||||
claude_project_lookup: bool,
|
||||
}
|
||||
|
||||
fn external_source_specs(home_dir: Option<&Path>, workspace_root: Option<&Path>) -> Vec<SourceSpec> {
|
||||
let mut specs = Vec::new();
|
||||
if let Some(root) = workspace_root {
|
||||
specs.push(SourceSpec {
|
||||
id: "workspace-mcp",
|
||||
label: "Project (.mcp.json)",
|
||||
path: root.join(".mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("claude"),
|
||||
claude_project_lookup: false,
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "vscode-mcp",
|
||||
label: "VS Code (.vscode/mcp.json)",
|
||||
path: root.join(".vscode").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: None,
|
||||
claude_project_lookup: false,
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "cursor-project",
|
||||
label: "Cursor Project (.cursor/mcp.json)",
|
||||
path: root.join(".cursor").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("cursor"),
|
||||
claude_project_lookup: false,
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "codex-project",
|
||||
label: "Codex Project (.codex/config.toml)",
|
||||
path: root.join(".codex").join("config.toml"),
|
||||
format: SourceFormat::CodexToml,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("codex"),
|
||||
claude_project_lookup: false,
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "gemini-project",
|
||||
label: "Gemini Project (.gemini/settings.json)",
|
||||
path: root.join(".gemini").join("settings.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("gemini"),
|
||||
claude_project_lookup: false,
|
||||
});
|
||||
}
|
||||
if let Some(home) = home_dir {
|
||||
specs.push(SourceSpec {
|
||||
id: "copilot-cli",
|
||||
label: "GitHub Copilot CLI",
|
||||
path: home.join(".copilot").join("mcp-config.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("copilot"),
|
||||
claude_project_lookup: false,
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "claude-code",
|
||||
label: "Claude Code",
|
||||
path: home.join(".claude.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("claude"),
|
||||
claude_project_lookup: true,
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "codex",
|
||||
label: "Codex",
|
||||
path: home.join(".codex").join("config.toml"),
|
||||
format: SourceFormat::CodexToml,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("codex"),
|
||||
claude_project_lookup: false,
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "cursor",
|
||||
label: "Cursor",
|
||||
path: home.join(".cursor").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("cursor"),
|
||||
claude_project_lookup: false,
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "gemini",
|
||||
label: "Gemini CLI",
|
||||
path: home.join(".gemini").join("settings.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("gemini"),
|
||||
claude_project_lookup: false,
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "jetbrains-air",
|
||||
label: "JetBrains Air",
|
||||
path: home.join(".jetbrains").join("mcp").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: None,
|
||||
claude_project_lookup: false,
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "copilot-intellij",
|
||||
label: "GitHub Copilot (JetBrains)",
|
||||
path: home.join(".config").join("github-copilot").join("intellij").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: None,
|
||||
claude_project_lookup: false,
|
||||
});
|
||||
}
|
||||
specs
|
||||
}
|
||||
|
||||
fn read_source_servers(spec: &SourceSpec, workspace_root: Option<&Path>) -> BTreeMap<String, AgentMcpServer> {
|
||||
let Ok(text) = std::fs::read_to_string(&spec.path) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
if spec.format == SourceFormat::CodexToml {
|
||||
return parse_codex_toml_servers(&text);
|
||||
}
|
||||
let Ok(root) = parse_jsonc_value(&text) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let mut servers = extract_servers_from_root(&root, None);
|
||||
if spec.claude_project_lookup
|
||||
&& let Some(ws) = workspace_root
|
||||
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
|
||||
{
|
||||
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
|
||||
for (proj_key, proj_val) in projects {
|
||||
let matches = Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
|
||||
if matches {
|
||||
for (name, srv) in extract_servers_from_root(proj_val, None) {
|
||||
servers.insert(name, srv);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
servers
|
||||
}
|
||||
|
||||
fn parse_codex_toml_servers(text: &str) -> BTreeMap<String, AgentMcpServer> {
|
||||
let Ok(doc) = toml::from_str::<toml::Value>(text) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let Ok(json_doc) = serde_json::to_value(doc) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let Some(table) = json_doc.get("mcp_servers").or_else(|| json_doc.get("mcpServers")).and_then(Value::as_object)
|
||||
else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let mut out = BTreeMap::new();
|
||||
for (name, raw) in table {
|
||||
let name = name.trim();
|
||||
let Some(mut obj) = raw.as_object().cloned().filter(|_| !name.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
if !obj.contains_key("headers")
|
||||
&& let Some(http_headers) = obj.remove("http_headers")
|
||||
{
|
||||
obj.insert("headers".to_owned(), http_headers);
|
||||
}
|
||||
if let Some(srv) = parse_one_server_def(&obj) {
|
||||
out.insert(name.to_owned(), srv);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Discovers external MCP configuration files on disk (without exposing secret values).
|
||||
pub fn discover_external_sources(home_dir: Option<&Path>, workspace_root: Option<&Path>) -> Vec<McpExternalSource> {
|
||||
let mut out = Vec::new();
|
||||
for spec in external_source_specs(home_dir, workspace_root) {
|
||||
let map = read_source_servers(&spec, workspace_root);
|
||||
if map.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let servers = map
|
||||
.into_iter()
|
||||
.map(|(name, cfg)| McpDiscoveredServer {
|
||||
name,
|
||||
transport: cfg.transport,
|
||||
enabled: cfg.enabled,
|
||||
command: cfg.command,
|
||||
args: cfg.args,
|
||||
url: cfg.url,
|
||||
env_keys: cfg.env.into_keys().collect(),
|
||||
header_keys: cfg.headers.into_keys().collect(),
|
||||
})
|
||||
.collect();
|
||||
out.push(McpExternalSource {
|
||||
id: spec.id.to_owned(),
|
||||
label: spec.label.to_owned(),
|
||||
path: IpcPath(spec.path),
|
||||
suggested_scope: spec.suggested_scope,
|
||||
native_provider: spec.native_provider.map(str::to_owned),
|
||||
servers,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Imports selected `(source_id, name)` entries from discovered external MCP config files into
|
||||
/// `user` or `workspace` without modifying the external files. Returns imported server names.
|
||||
pub fn apply_import_selected(
|
||||
user: &mut BTreeMap<String, AgentMcpServer>,
|
||||
workspace: &mut BTreeMap<String, AgentMcpServer>,
|
||||
home_dir: Option<&Path>,
|
||||
workspace_root: Option<&Path>,
|
||||
scope: McpScope,
|
||||
selections: &[McpImportSelection],
|
||||
overwrite: bool,
|
||||
) -> Result<Vec<String>, String> {
|
||||
if scope == McpScope::Workspace && workspace_root.is_none() {
|
||||
return Err("Open a project to import workspace MCP servers".into());
|
||||
}
|
||||
let specs = external_source_specs(home_dir, workspace_root);
|
||||
let mut by_source: BTreeMap<&str, BTreeMap<String, AgentMcpServer>> = BTreeMap::new();
|
||||
for spec in &specs {
|
||||
if selections.iter().any(|s| s.source_id == spec.id) {
|
||||
by_source.insert(spec.id, read_source_servers(spec, workspace_root));
|
||||
}
|
||||
}
|
||||
let target = match scope {
|
||||
McpScope::User => user,
|
||||
McpScope::Workspace => workspace,
|
||||
};
|
||||
let mut imported = Vec::new();
|
||||
for sel in selections {
|
||||
let Some(source_map) = by_source.get(sel.source_id.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
let Some(srv) = source_map.get(&sel.name) else {
|
||||
continue;
|
||||
};
|
||||
if overwrite || !target.contains_key(&sel.name) {
|
||||
target.insert(sel.name.clone(), srv.clone());
|
||||
imported.push(sel.name.clone());
|
||||
}
|
||||
}
|
||||
Ok(imported)
|
||||
}
|
||||
|
||||
fn normalize_agents_list(agents: Vec<String>) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
for a in agents {
|
||||
@@ -287,73 +615,376 @@ fn normalize_agents_list(agents: Vec<String>) -> Vec<String> {
|
||||
out
|
||||
}
|
||||
|
||||
fn read_external_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
|
||||
let Ok(bytes) = std::fs::read(path) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let Ok(root) = serde_json::from_slice::<Value>(&bytes) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let Some(servers_obj) = root.get("mcpServers").or_else(|| root.get("servers")).and_then(Value::as_object) else {
|
||||
return BTreeMap::new();
|
||||
/// Strips `//` line comments, `/* ... */` block comments, and trailing commas before `}` or `]`
|
||||
/// outside JSON string literals so JSONC config files parse cleanly with `serde_json`.
|
||||
pub(crate) fn strip_jsonc(input: &str) -> String {
|
||||
let bytes = input.as_bytes();
|
||||
let mut out = String::with_capacity(input.len());
|
||||
let mut i = 0;
|
||||
let mut in_str = false;
|
||||
while i < bytes.len() {
|
||||
if in_str {
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
if ch == '\\' && i < bytes.len() {
|
||||
let next = input[i..].chars().next().unwrap();
|
||||
out.push(next);
|
||||
i += next.len_utf8();
|
||||
} else if ch == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'"' {
|
||||
in_str = true;
|
||||
out.push('"');
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
|
||||
i += 2;
|
||||
while i < bytes.len() && bytes[i] != b'\n' {
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
|
||||
i += 2;
|
||||
while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
|
||||
if bytes[i] == b'\n' {
|
||||
out.push('\n');
|
||||
i += 1;
|
||||
} else {
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
}
|
||||
i = (i + 2).min(bytes.len());
|
||||
continue;
|
||||
}
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
remove_trailing_commas(&out)
|
||||
}
|
||||
|
||||
fn remove_trailing_commas(input: &str) -> String {
|
||||
let bytes = input.as_bytes();
|
||||
let mut out = String::with_capacity(input.len());
|
||||
let mut i = 0;
|
||||
let mut in_str = false;
|
||||
while i < bytes.len() {
|
||||
if in_str {
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
if ch == '\\' && i < bytes.len() {
|
||||
let next = input[i..].chars().next().unwrap();
|
||||
out.push(next);
|
||||
i += next.len_utf8();
|
||||
} else if ch == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'"' {
|
||||
in_str = true;
|
||||
out.push('"');
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b',' {
|
||||
let mut j = i + 1;
|
||||
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
|
||||
j += 1;
|
||||
}
|
||||
if j < bytes.len() && (bytes[j] == b'}' || bytes[j] == b']') {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn parse_jsonc_value(raw: &str) -> Result<Value, String> {
|
||||
let trimmed = raw.trim().trim_start_matches('\u{feff}');
|
||||
serde_json::from_str::<Value>(trimmed)
|
||||
.or_else(|_| serde_json::from_str::<Value>(&strip_jsonc(trimmed)))
|
||||
.map_err(|e| format!("Invalid JSON: {e}"))
|
||||
}
|
||||
|
||||
pub fn parse_mcp_json_text(raw: &str, fallback_name: Option<&str>) -> Result<BTreeMap<String, AgentMcpServer>, String> {
|
||||
let root = parse_jsonc_value(raw)?;
|
||||
Ok(extract_servers_from_root(&root, fallback_name))
|
||||
}
|
||||
|
||||
fn is_server_def_object(obj: &serde_json::Map<String, Value>) -> bool {
|
||||
obj.get("command").and_then(Value::as_str).is_some_and(|s| !s.trim().is_empty())
|
||||
|| obj.get("url").and_then(Value::as_str).is_some_and(|s| !s.trim().is_empty())
|
||||
|| obj.get("serverUrl").and_then(Value::as_str).is_some_and(|s| !s.trim().is_empty())
|
||||
}
|
||||
|
||||
fn parse_one_server_def(obj: &serde_json::Map<String, Value>) -> Option<AgentMcpServer> {
|
||||
let disabled = obj.get("disabled").and_then(Value::as_bool).unwrap_or(false)
|
||||
|| obj.get("enabled").and_then(Value::as_bool) == Some(false);
|
||||
let type_str = obj.get("type").and_then(Value::as_str).unwrap_or_default().to_ascii_lowercase();
|
||||
let url = obj
|
||||
.get("url")
|
||||
.or_else(|| obj.get("serverUrl"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
let command =
|
||||
obj.get("command").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
|
||||
let transport = match type_str.as_str() {
|
||||
"sse" => McpTransport::Sse,
|
||||
"http" | "streamable-http" | "streamable_http" => McpTransport::Http,
|
||||
"stdio" | "local" => McpTransport::Stdio,
|
||||
_ if url.is_some() && command.is_none() => McpTransport::Http,
|
||||
_ => McpTransport::Stdio,
|
||||
};
|
||||
|
||||
match transport {
|
||||
McpTransport::Stdio => command.as_ref()?,
|
||||
McpTransport::Http | McpTransport::Sse => url.as_ref()?,
|
||||
};
|
||||
|
||||
let args = obj
|
||||
.get("args")
|
||||
.and_then(Value::as_array)
|
||||
.map(|arr| arr.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect())
|
||||
.unwrap_or_default();
|
||||
|
||||
let agents = obj
|
||||
.get("agents")
|
||||
.and_then(Value::as_array)
|
||||
.map(|arr| normalize_agents_list(arr.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect()))
|
||||
.unwrap_or_default();
|
||||
|
||||
Some(AgentMcpServer {
|
||||
transport,
|
||||
enabled: !disabled,
|
||||
command,
|
||||
args,
|
||||
env: parse_key_values_map(obj.get("env")),
|
||||
url,
|
||||
headers: parse_key_values_map(obj.get("headers")),
|
||||
agents,
|
||||
})
|
||||
}
|
||||
|
||||
fn extract_servers_from_root(root: &Value, fallback_name: Option<&str>) -> BTreeMap<String, AgentMcpServer> {
|
||||
let mut out = BTreeMap::new();
|
||||
for (name, def) in servers_obj {
|
||||
let name = name.trim();
|
||||
let Some(obj) = def.as_object().filter(|_| !name.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
let disabled = obj.get("disabled").and_then(Value::as_bool).unwrap_or(false)
|
||||
|| obj.get("enabled").and_then(Value::as_bool) == Some(false);
|
||||
let type_str = obj.get("type").and_then(Value::as_str).unwrap_or_default().to_ascii_lowercase();
|
||||
let url = obj
|
||||
.get("url")
|
||||
.or_else(|| obj.get("serverUrl"))
|
||||
let Some(root_obj) = root.as_object() else {
|
||||
return out;
|
||||
};
|
||||
|
||||
// Single server definition object pasted directly (`{"command": "npx", ...}`).
|
||||
if is_server_def_object(root_obj) {
|
||||
let name = root_obj
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
let command =
|
||||
obj.get("command").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
|
||||
let transport = match type_str.as_str() {
|
||||
"sse" => McpTransport::Sse,
|
||||
"http" | "streamable-http" | "streamable_http" => McpTransport::Http,
|
||||
"stdio" | "local" => McpTransport::Stdio,
|
||||
_ if url.is_some() && command.is_none() => McpTransport::Http,
|
||||
_ => McpTransport::Stdio,
|
||||
};
|
||||
|
||||
match transport {
|
||||
McpTransport::Stdio if command.is_none() => continue,
|
||||
McpTransport::Http | McpTransport::Sse if url.is_none() => continue,
|
||||
_ => {}
|
||||
.or_else(|| fallback_name.map(str::trim).filter(|s| !s.is_empty()));
|
||||
if let (Some(name), Some(srv)) = (name, parse_one_server_def(root_obj)) {
|
||||
out.insert(name.to_owned(), srv);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
let args = obj
|
||||
.get("args")
|
||||
.and_then(Value::as_array)
|
||||
.map(|arr| arr.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect())
|
||||
.unwrap_or_default();
|
||||
let servers_obj =
|
||||
root_obj.get("mcpServers").or_else(|| root_obj.get("servers")).and_then(Value::as_object).unwrap_or(root_obj);
|
||||
|
||||
out.insert(
|
||||
name.to_owned(),
|
||||
AgentMcpServer {
|
||||
transport,
|
||||
enabled: !disabled,
|
||||
command,
|
||||
args,
|
||||
env: parse_key_values_map(obj.get("env")),
|
||||
url,
|
||||
headers: parse_key_values_map(obj.get("headers")),
|
||||
agents: Vec::new(),
|
||||
},
|
||||
);
|
||||
for (name, def) in servers_obj {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || matches!(name, "$schema" | "inputs" | "version") {
|
||||
continue;
|
||||
}
|
||||
let Some(obj) = def.as_object() else {
|
||||
continue;
|
||||
};
|
||||
if !is_server_def_object(obj) {
|
||||
continue;
|
||||
}
|
||||
if let Some(srv) = parse_one_server_def(obj) {
|
||||
out.insert(name.to_owned(), srv);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn read_external_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let Ok(root) = parse_jsonc_value(&text) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
extract_servers_from_root(&root, None)
|
||||
}
|
||||
|
||||
/// Probes a stdio MCP server by launching its command, performing the MCP `initialize` handshake,
|
||||
/// and requesting `tools/list`. For HTTP/SSE servers, use `ide-host`'s HTTP probe helper.
|
||||
pub async fn probe_stdio_server(server: &AgentMcpServer, cwd: &Path) -> McpProbeResult {
|
||||
let started = Instant::now();
|
||||
let elapsed_ms = || u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
|
||||
let Some(raw_cmd) = server.command.as_deref().map(str::trim).filter(|s| !s.is_empty()) else {
|
||||
return McpProbeResult {
|
||||
ok: false,
|
||||
server_name: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
tools: Vec::new(),
|
||||
duration_ms: elapsed_ms(),
|
||||
error: Some("Command is empty".into()),
|
||||
};
|
||||
};
|
||||
|
||||
let mut env: Vec<(String, String)> = ide_core::process::shell_env()
|
||||
.map(|(k, v)| (k.to_string_lossy().into_owned(), v.to_string_lossy().into_owned()))
|
||||
.collect();
|
||||
for (k, v) in &server.env {
|
||||
if let Some((_, existing)) = env.iter_mut().find(|(ek, _)| ek == k) {
|
||||
*existing = v.clone();
|
||||
} else {
|
||||
env.push((k.clone(), v.clone()));
|
||||
}
|
||||
}
|
||||
let search_path = env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"))
|
||||
.unwrap_or_default();
|
||||
let program = ide_core::process::find_executable(raw_cmd, &search_path)
|
||||
.map(|p| p.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| raw_cmd.to_owned());
|
||||
|
||||
let stderr_lines = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
|
||||
let stderr_capture = stderr_lines.clone();
|
||||
let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(move |line| {
|
||||
let mut guard = stderr_capture.lock();
|
||||
if guard.len() < 12 && !line.trim().is_empty() {
|
||||
guard.push(line);
|
||||
}
|
||||
});
|
||||
|
||||
let peer = match ide_jsonrpc::Peer::spawn_framed(
|
||||
&program,
|
||||
&server.args,
|
||||
cwd,
|
||||
&env,
|
||||
std::sync::Arc::new(ide_jsonrpc::NoopHandler),
|
||||
on_stderr,
|
||||
ide_jsonrpc::Framing::Lines,
|
||||
) {
|
||||
Ok(peer) => peer,
|
||||
Err(e) => {
|
||||
return McpProbeResult {
|
||||
ok: false,
|
||||
server_name: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
tools: Vec::new(),
|
||||
duration_ms: elapsed_ms(),
|
||||
error: Some(format!("Failed to launch `{raw_cmd}`: {e}")),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
let outcome = tokio::time::timeout(PROBE_TIMEOUT, async {
|
||||
let init: Value = peer
|
||||
.request(
|
||||
"initialize",
|
||||
json!({
|
||||
"protocolVersion": PROBE_PROTOCOL_VERSION,
|
||||
"capabilities": {},
|
||||
"clientInfo": crate::client_info(),
|
||||
}),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let _ = peer.notify("notifications/initialized", json!({}));
|
||||
let tools_reply: Value = peer.request("tools/list", json!({}), None).await.unwrap_or_else(|_| json!({}));
|
||||
Ok::<(Value, Value), String>((init, tools_reply))
|
||||
})
|
||||
.await;
|
||||
|
||||
peer.kill();
|
||||
|
||||
match outcome {
|
||||
Ok(Ok((init, tools_reply))) => parse_probe_payloads(&init, &tools_reply, elapsed_ms()),
|
||||
Ok(Err(err)) => {
|
||||
let tail = stderr_lines.lock().join("\n");
|
||||
let error = if tail.is_empty() { err } else { format!("{err}\n{tail}") };
|
||||
McpProbeResult {
|
||||
ok: false,
|
||||
server_name: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
tools: Vec::new(),
|
||||
duration_ms: elapsed_ms(),
|
||||
error: Some(error),
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
let tail = stderr_lines.lock().join("\n");
|
||||
let error = if tail.is_empty() {
|
||||
format!("Timed out after {}s waiting for MCP handshake", PROBE_TIMEOUT.as_secs())
|
||||
} else {
|
||||
format!("Timed out after {}s waiting for MCP handshake:\n{tail}", PROBE_TIMEOUT.as_secs())
|
||||
};
|
||||
McpProbeResult {
|
||||
ok: false,
|
||||
server_name: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
tools: Vec::new(),
|
||||
duration_ms: elapsed_ms(),
|
||||
error: Some(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_probe_payloads(init: &Value, tools_reply: &Value, duration_ms: u32) -> McpProbeResult {
|
||||
let server_name = init.pointer("/serverInfo/name").and_then(Value::as_str).map(str::to_owned);
|
||||
let server_version = init.pointer("/serverInfo/version").and_then(Value::as_str).map(str::to_owned);
|
||||
let protocol_version = init.get("protocolVersion").and_then(Value::as_str).map(str::to_owned);
|
||||
let tools = tools_reply
|
||||
.get("tools")
|
||||
.and_then(Value::as_array)
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|t| {
|
||||
let name = t.get("name")?.as_str()?.trim();
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let description = t
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
Some(McpToolSummary { name: name.to_owned(), description })
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
McpProbeResult { ok: true, server_name, server_version, protocol_version, tools, duration_ms, error: None }
|
||||
}
|
||||
|
||||
fn parse_key_values_map(val: Option<&Value>) -> BTreeMap<String, String> {
|
||||
match val {
|
||||
Some(Value::Object(map)) => map
|
||||
@@ -457,22 +1088,29 @@ mod tests {
|
||||
let init_http = Negotiated::from_initialize(&json!({
|
||||
"agentCapabilities": { "mcpCapabilities": { "http": true, "sse": false } }
|
||||
}));
|
||||
let claude_servers = acp_mcp_servers(&list, "claude-acp", &init_http);
|
||||
let empty_overrides = BTreeMap::new();
|
||||
let claude_servers = acp_mcp_servers(&list, "claude-acp", &init_http, &empty_overrides);
|
||||
assert_eq!(claude_servers.len(), 2);
|
||||
assert_eq!(claude_servers[0]["name"], "shared");
|
||||
assert_eq!(claude_servers[0]["args"], json!(["-y", "workspace-pkg"]));
|
||||
assert_eq!(claude_servers[1]["name"], "claude-http");
|
||||
assert_eq!(claude_servers[1]["type"], "http");
|
||||
|
||||
let codex_servers = acp_mcp_servers(&list, "codex", &init_http);
|
||||
let codex_servers = acp_mcp_servers(&list, "codex", &init_http, &empty_overrides);
|
||||
assert_eq!(codex_servers.len(), 1);
|
||||
assert_eq!(codex_servers[0]["name"], "shared");
|
||||
|
||||
// Per-session overrides can disable an enabled server or enable an agent-scoped server.
|
||||
let overrides = BTreeMap::from([("shared".to_owned(), false), ("claude-http".to_owned(), true)]);
|
||||
let codex_overridden = acp_mcp_servers(&list, "codex", &init_http, &overrides);
|
||||
assert_eq!(codex_overridden.len(), 1);
|
||||
assert_eq!(codex_overridden[0]["name"], "claude-http");
|
||||
|
||||
// Disable workspace `shared` and remove user `claude-http`.
|
||||
apply_set_enabled(&mut user, &mut workspace, "workspace::shared", false).unwrap();
|
||||
apply_remove(&mut user, &mut workspace, "user::claude-http").unwrap();
|
||||
let list = servers_from_settings(&user, &workspace);
|
||||
let after = acp_mcp_servers(&list, "claude", &init_http);
|
||||
let after = acp_mcp_servers(&list, "claude", &init_http, &empty_overrides);
|
||||
assert_eq!(after.len(), 1);
|
||||
assert_eq!(after[0]["args"], json!(["-y", "user-pkg"]));
|
||||
}
|
||||
@@ -504,4 +1142,124 @@ mod tests {
|
||||
assert_eq!(std::fs::read_to_string(&mcp_json).unwrap(), raw_mcp);
|
||||
assert_eq!(std::fs::read_to_string(&vscode_mcp).unwrap(), raw_vscode);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovers_cli_sources_top_level_maps_and_jsonc_and_imports_selected() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
let proj = tmp.path().join("project");
|
||||
std::fs::create_dir_all(home.join(".copilot")).unwrap();
|
||||
std::fs::create_dir_all(home.join(".codex")).unwrap();
|
||||
std::fs::create_dir_all(home.join(".gemini")).unwrap();
|
||||
std::fs::create_dir_all(home.join(".jetbrains").join("mcp")).unwrap();
|
||||
std::fs::create_dir_all(home.join(".config").join("github-copilot").join("intellij")).unwrap();
|
||||
std::fs::create_dir_all(&proj).unwrap();
|
||||
|
||||
std::fs::write(
|
||||
home.join(".copilot").join("mcp-config.json"),
|
||||
r#"{"mcpServers":{"github":{"type":"http","url":"https://api.githubcopilot.com/mcp/","headers":{"Authorization":"Bearer tok"}},"slack":{"type":"local","command":"npx","args":["-y","slack-mcp"],"env":{"SLACK_TOKEN":"xoxb"}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Codex `~/.codex/config.toml` `[mcp_servers]` format.
|
||||
std::fs::write(
|
||||
home.join(".codex").join("config.toml"),
|
||||
"[mcp_servers.postgres]\ncommand = \"npx\"\nargs = [\"-y\", \"@modelcontextprotocol/server-postgres\"]\n\n[mcp_servers.remote_api]\nurl = \"https://mcp.example.com/sse\"\ntype = \"sse\"\nhttp_headers = { Authorization = \"Bearer codex-tok\" }\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Gemini `~/.gemini/settings.json` with unrelated top-level settings alongside `mcpServers`.
|
||||
std::fs::write(
|
||||
home.join(".gemini").join("settings.json"),
|
||||
r#"{"theme":"Default","mcpServers":{"fetch":{"command":"uvx","args":["mcp-server-fetch"]}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// JetBrains Air top-level server map (not nested under `mcpServers`).
|
||||
std::fs::write(
|
||||
home.join(".jetbrains").join("mcp").join("mcp.json"),
|
||||
r#"{"linear":{"type":"stdio","command":"npx","args":["-y","mcp-remote","https://mcp.linear.app/mcp"]}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// JSONC comments + trailing commas.
|
||||
std::fs::write(
|
||||
home.join(".config").join("github-copilot").join("intellij").join("mcp.json"),
|
||||
"// comment with https://url/inside\n{\n /* block comment */\n \"servers\": {\n \"docs\": { \"command\": \"uvx\", \"args\": [\"docs-mcp\",], },\n },\n}\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let sources = discover_external_sources(Some(&home), Some(&proj));
|
||||
assert_eq!(sources.len(), 5);
|
||||
let copilot = sources.iter().find(|s| s.id == "copilot-cli").unwrap();
|
||||
assert_eq!(copilot.native_provider.as_deref(), Some("copilot"));
|
||||
assert_eq!(copilot.servers.len(), 2);
|
||||
let gh_srv = copilot.servers.iter().find(|s| s.name == "github").unwrap();
|
||||
assert_eq!(gh_srv.header_keys, vec!["Authorization".to_string()]);
|
||||
|
||||
let codex = sources.iter().find(|s| s.id == "codex").unwrap();
|
||||
assert_eq!(codex.native_provider.as_deref(), Some("codex"));
|
||||
assert_eq!(codex.servers.len(), 2);
|
||||
|
||||
let gemini = sources.iter().find(|s| s.id == "gemini").unwrap();
|
||||
assert_eq!(gemini.servers[0].name, "fetch");
|
||||
|
||||
let air = sources.iter().find(|s| s.id == "jetbrains-air").unwrap();
|
||||
assert_eq!(air.servers[0].name, "linear");
|
||||
|
||||
let ij = sources.iter().find(|s| s.id == "copilot-intellij").unwrap();
|
||||
assert_eq!(ij.servers[0].name, "docs");
|
||||
|
||||
let mut user = BTreeMap::new();
|
||||
let mut workspace = BTreeMap::new();
|
||||
let imported = apply_import_selected(
|
||||
&mut user,
|
||||
&mut workspace,
|
||||
Some(&home),
|
||||
Some(&proj),
|
||||
McpScope::User,
|
||||
&[
|
||||
McpImportSelection { source_id: "copilot-cli".into(), name: "github".into() },
|
||||
McpImportSelection { source_id: "jetbrains-air".into(), name: "linear".into() },
|
||||
],
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(imported, vec!["github".to_string(), "linear".to_string()]);
|
||||
assert_eq!(user["github"].headers.get("Authorization").map(String::as_str), Some("Bearer tok"));
|
||||
assert_eq!(user["linear"].command.as_deref(), Some("npx"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_save_json_accepts_mcp_servers_map_and_single_server_object() {
|
||||
let mut user = BTreeMap::new();
|
||||
let mut workspace = BTreeMap::new();
|
||||
|
||||
let names = apply_save_json(
|
||||
&mut user,
|
||||
&mut workspace,
|
||||
true,
|
||||
McpScope::User,
|
||||
r#"{"mcpServers":{"playwright":{"command":"npx","args":["@playwright/mcp@latest"]}}}"#,
|
||||
None,
|
||||
vec!["copilot".into(), "claude".into()],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(names, vec!["playwright".to_string()]);
|
||||
assert_eq!(user["playwright"].agents, vec!["copilot".to_string(), "claude".to_string()]);
|
||||
|
||||
let single = apply_save_json(
|
||||
&mut user,
|
||||
&mut workspace,
|
||||
true,
|
||||
McpScope::Workspace,
|
||||
r#"{"type":"sse","serverUrl":"https://sse.example.com/events"}"#,
|
||||
Some("events-sse"),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(single, vec!["events-sse".to_string()]);
|
||||
assert_eq!(workspace["events-sse"].transport, McpTransport::Sse);
|
||||
assert_eq!(workspace["events-sse"].url.as_deref(), Some("https://sse.example.com/events"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,12 +50,13 @@ pub struct AgentCapabilities {
|
||||
pub read_only: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Isolation {
|
||||
/// A new git worktree on its own branch.
|
||||
Worktree,
|
||||
/// The project's own checkout.
|
||||
#[default]
|
||||
Local,
|
||||
}
|
||||
|
||||
@@ -107,6 +108,9 @@ pub struct AgentTask {
|
||||
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
|
||||
#[serde(default)]
|
||||
pub background: Box<Vec<AgentBackgroundTask>>,
|
||||
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub mcp_overrides: BTreeMap<String, bool>,
|
||||
}
|
||||
|
||||
/// A task the agent runs in the background while the conversation goes on.
|
||||
@@ -592,7 +596,7 @@ pub struct AgentProbe {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NewAgentTask {
|
||||
/// Validated by the host; defaults to the window project root.
|
||||
@@ -605,6 +609,9 @@ pub struct NewAgentTask {
|
||||
pub isolation: Isolation,
|
||||
/// Branch to start the worktree from; the current branch when `None`.
|
||||
pub base: Option<String>,
|
||||
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
|
||||
#[serde(default)]
|
||||
pub mcp_overrides: BTreeMap<String, bool>,
|
||||
}
|
||||
|
||||
/// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the
|
||||
@@ -676,7 +683,7 @@ pub struct AgentModelCatalog {
|
||||
pub enum AgentEvent {
|
||||
/// A task was created or its metadata changed.
|
||||
Task {
|
||||
task: AgentTask,
|
||||
task: Box<AgentTask>,
|
||||
},
|
||||
Removed {
|
||||
id: String,
|
||||
@@ -756,6 +763,9 @@ pub struct McpServer {
|
||||
/// Agent provider ids this server is enabled for; empty means enabled for all agents.
|
||||
#[serde(default)]
|
||||
pub agents: Vec<String>,
|
||||
/// True when this Workspace server was added outside OpenIDEA and has not been approved yet.
|
||||
#[serde(default)]
|
||||
pub unapproved: bool,
|
||||
}
|
||||
|
||||
/// Payload for creating or updating a user or workspace MCP server.
|
||||
@@ -788,6 +798,69 @@ fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// An external MCP configuration file discovered on disk (user CLI config or workspace file).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct McpExternalSource {
|
||||
/// Stable source identifier (e.g. `"copilot-cli"`, `"jetbrains-air"`, `"claude-code"`, `"cursor"`, `"workspace-mcp"`, `"vscode-mcp"`).
|
||||
pub id: String,
|
||||
/// Human-readable source label (e.g. `"GitHub Copilot CLI"`).
|
||||
pub label: String,
|
||||
/// Absolute path of the discovered configuration file.
|
||||
pub path: IpcPath,
|
||||
/// Suggested target scope when importing this source into OpenIDEA settings.
|
||||
pub suggested_scope: McpScope,
|
||||
/// Agent provider ID this external CLI reads natively (`Some("copilot")`, `Some("claude")`, `Some("cursor")`, or `None`).
|
||||
pub native_provider: Option<String>,
|
||||
/// Servers found inside this external configuration file (values omitted for safety; imported directly on the host).
|
||||
pub servers: Vec<McpDiscoveredServer>,
|
||||
}
|
||||
|
||||
/// Summary of one server discovered inside an external MCP configuration file.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct McpDiscoveredServer {
|
||||
pub name: String,
|
||||
pub transport: McpTransport,
|
||||
pub enabled: bool,
|
||||
pub command: Option<String>,
|
||||
pub args: Vec<String>,
|
||||
pub url: Option<String>,
|
||||
/// Environment variable names declared on this server (values stay on the host).
|
||||
pub env_keys: Vec<String>,
|
||||
/// HTTP header names declared on this server (values stay on the host).
|
||||
pub header_keys: Vec<String>,
|
||||
}
|
||||
|
||||
/// Selection of one server from an external MCP configuration source to import.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct McpImportSelection {
|
||||
pub source_id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// One tool advertised by an MCP server during `tools/list`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct McpToolSummary {
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
/// Result of testing/probing an MCP server (`initialize` + `tools/list`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct McpProbeResult {
|
||||
pub ok: bool,
|
||||
pub server_name: Option<String>,
|
||||
pub server_version: Option<String>,
|
||||
pub protocol_version: Option<String>,
|
||||
pub tools: Vec<McpToolSummary>,
|
||||
pub duration_ms: u32,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload for creating a custom ACP agent (always the ACP driver); the id
|
||||
/// becomes the `<config>/agents/<id>.toml` file name.
|
||||
#[derive(Clone, Debug, Deserialize, Type)]
|
||||
|
||||
@@ -64,6 +64,7 @@ async fn create(mgr: &AgentManager, provider: &str, prompt: &str) -> String {
|
||||
config: config(provider),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
};
|
||||
mgr.create(req).await.unwrap().id
|
||||
}
|
||||
|
||||
@@ -54,6 +54,8 @@ struct FakeAgent {
|
||||
/// Advertises steering as OMP does (`_meta.steering` at the top of `initialize`)
|
||||
/// instead of `_meta.openidea.steer`.
|
||||
session_steering: bool,
|
||||
/// Records the `mcpServers` array passed to `session/new`, `session/load`, and `session/fork`.
|
||||
mcp_calls: Mutex<Vec<(String, Vec<String>)>>,
|
||||
}
|
||||
|
||||
impl FakeAgent {
|
||||
@@ -153,6 +155,18 @@ impl Handler for FakeAgent {
|
||||
// Let the prompt's permission request reach the task before the mode changes.
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
if matches!(method, "session/new" | "session/load" | "session/fork") {
|
||||
let names = params
|
||||
.get("mcpServers")
|
||||
.and_then(Value::as_array)
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|v| v.get("name").and_then(Value::as_str).map(str::to_owned))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
self.mcp_calls.lock().push((method.to_owned(), names));
|
||||
}
|
||||
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
|
||||
match method {
|
||||
"initialize" => {
|
||||
@@ -456,6 +470,7 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -649,6 +664,7 @@ async fn authentication_failures_name_the_session_executable_at_start_and_during
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -699,6 +715,7 @@ async fn sign_in_errors_preserve_details_and_leave_unrelated_errors_unchanged()
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -754,6 +771,7 @@ async fn registry_sign_in_errors_use_the_advertised_terminal_login() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -801,6 +819,7 @@ async fn authenticates_and_retries_session_setup_once_on_auth_error() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -883,6 +902,7 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -923,6 +943,7 @@ async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metada
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -981,6 +1002,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
config: vec![AgentConfigChoice { id: "model".into(), value: "small".into() }],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1104,6 +1126,7 @@ async fn steers_through_session_steering() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1140,6 +1163,7 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1195,6 +1219,7 @@ async fn subagents_get_their_own_conversation() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1290,6 +1315,7 @@ async fn claude_questions_keep_the_answer_object_as_the_option_id() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1339,6 +1365,7 @@ async fn qwen_questions_answer_by_index_beside_the_submit_option() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1407,6 +1434,7 @@ async fn skipped_qwen_questions_cancel_the_request() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1446,6 +1474,7 @@ async fn cancelling_resolves_the_open_permission_and_delete_forgets_the_task() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1467,7 +1496,8 @@ async fn cancelling_resolves_the_open_permission_and_delete_forgets_the_task() {
|
||||
provider: "codex".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
@@ -1516,6 +1546,7 @@ async fn real_claude_task_in_a_worktree() {
|
||||
config: vec![AgentConfigChoice { id: "model".into(), value: "haiku".into() }],
|
||||
isolation: Isolation::Worktree,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1566,6 +1597,7 @@ async fn renamed_titles_survive_updates_forks_and_restart() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1603,6 +1635,7 @@ async fn forks_rollbacks_and_steering() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
};
|
||||
let task = mgr.create(new("again")).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
@@ -1682,6 +1715,7 @@ async fn usage_limits_and_late_settings() {
|
||||
config: vec![AgentConfigChoice { id: "effort".into(), value: "high".into() }],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1735,6 +1769,7 @@ async fn remembered_settings_drop_per_model_choices_for_the_next_task() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1769,6 +1804,7 @@ async fn thinking_levels_are_remembered_per_provider_and_model() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1815,6 +1851,7 @@ async fn changing_an_idle_tasks_settings_keeps_its_models_effort_levels() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1856,6 +1893,7 @@ async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
|
||||
],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1887,6 +1925,7 @@ async fn unreported_model_switch_does_not_cache_the_previous_models_levels() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1911,6 +1950,7 @@ async fn cached_effort_is_not_sent_without_real_session_options() {
|
||||
config,
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
};
|
||||
let warm = mgr.create(new(vec![])).await.unwrap();
|
||||
wait_for(&mgr, &warm.id, AgentStatus::Ready).await;
|
||||
@@ -1946,6 +1986,7 @@ async fn reported_levels_refresh_even_without_a_model_option() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1999,6 +2040,7 @@ async fn cursor_approval_switch_resolves_pending_and_survives_restart() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
};
|
||||
let task = mgr.create(new()).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
@@ -2052,6 +2094,7 @@ async fn bypass_approvals_keeps_both_question_dialects_pending_but_allows_permis
|
||||
},
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -2113,6 +2156,7 @@ async fn an_agent_form_is_answered_declined_or_cancelled_even_when_approvals_are
|
||||
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -2155,6 +2199,7 @@ async fn cursor_approval_choice_applies_before_first_prompt() {
|
||||
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -2179,6 +2224,7 @@ async fn a_full_access_mode_approves_tool_requests() {
|
||||
config: vec![AgentConfigChoice { id: "mode".into(), value: "full-access".into() }],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -2200,6 +2246,7 @@ async fn a_full_access_mode_approves_tool_requests() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -2228,6 +2275,7 @@ async fn a_late_full_access_option_approves_a_pending_request() {
|
||||
config: vec![AgentConfigChoice { id: "mode".into(), value: "full-access".into() }],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -2275,6 +2323,7 @@ async fn an_allow_all_permissions_option_approves_tool_requests() {
|
||||
config: vec![AgentConfigChoice { id: "allow_all".into(), value: "on".into() }],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -2302,6 +2351,7 @@ async fn archived_tasks_can_be_restored_and_continue_their_session() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -2354,6 +2404,7 @@ async fn task_project_root_controls_local_and_worktree_repositories() {
|
||||
config: vec![],
|
||||
isolation,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -2560,6 +2611,7 @@ async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
};
|
||||
let live =
|
||||
|mgr: &AgentManager, id: &str| mgr.task(id).unwrap().live.lock().as_ref().is_some_and(|l| !l.peer.is_closed());
|
||||
@@ -2638,6 +2690,7 @@ async fn an_idle_agent_waits_for_its_background_tasks_before_it_stops() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -2672,6 +2725,7 @@ async fn the_task_shows_what_runs_in_the_background() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -2724,6 +2778,7 @@ async fn a_background_task_is_stopped_on_its_own() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -2811,6 +2866,7 @@ async fn delete_running_agent(no_load: bool) {
|
||||
config: vec![],
|
||||
isolation: Isolation::Worktree,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -2926,6 +2982,7 @@ async fn config_choice_shows_before_the_agent_answers() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3031,6 +3088,7 @@ async fn rolling_back_restores_the_start_of_the_task_and_keeps_the_users_own_edi
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3137,6 +3195,7 @@ impl Checkout {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3343,6 +3402,7 @@ async fn security_policy_auto_approves_whitelist_and_rejects_blacklist() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3373,6 +3433,7 @@ async fn security_policy_auto_approves_whitelist_and_rejects_blacklist() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3410,6 +3471,7 @@ async fn security_policy_never_auto_approves_a_request_that_only_reads_like_a_co
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3447,6 +3509,7 @@ async fn ephemeral_tasks_stay_in_memory_only() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3461,6 +3524,7 @@ async fn ephemeral_tasks_stay_in_memory_only() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
},
|
||||
&source.id,
|
||||
)
|
||||
@@ -3562,6 +3626,7 @@ async fn ephemeral_tasks_deny_write_permissions() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3587,6 +3652,7 @@ async fn ephemeral_tasks_deny_write_permissions() {
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
},
|
||||
&source.id,
|
||||
)
|
||||
@@ -3659,6 +3725,7 @@ async fn attention_finished_not_cancelled() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3674,6 +3741,7 @@ async fn attention_finished_not_cancelled() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3710,6 +3778,7 @@ async fn attention_failed() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3735,6 +3804,7 @@ async fn attention_input_not_auto_bypass() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3752,6 +3822,7 @@ async fn attention_input_not_auto_bypass() {
|
||||
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3778,6 +3849,7 @@ async fn attention_not_emitted_on_restore() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3794,6 +3866,80 @@ async fn attention_not_emitted_on_restore() {
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
mgr.set_mcp_servers_hook(Box::new(|| {
|
||||
vec![
|
||||
McpServer {
|
||||
id: "user::github".into(),
|
||||
name: "github".into(),
|
||||
scope: McpScope::User,
|
||||
transport: McpTransport::Stdio,
|
||||
enabled: true,
|
||||
command: Some("npx".into()),
|
||||
args: vec!["gh-mcp".into()],
|
||||
env: Vec::new(),
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
},
|
||||
McpServer {
|
||||
id: "user::slack".into(),
|
||||
name: "slack".into(),
|
||||
scope: McpScope::User,
|
||||
transport: McpTransport::Stdio,
|
||||
enabled: true,
|
||||
command: Some("npx".into()),
|
||||
args: vec!["slack-mcp".into()],
|
||||
env: Vec::new(),
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
},
|
||||
]
|
||||
}));
|
||||
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let first_mcp = agent.mcp_calls.lock().last().cloned().unwrap();
|
||||
assert_eq!(first_mcp.0, "session/new");
|
||||
assert!(first_mcp.1.contains(&"github".to_string()));
|
||||
assert!(!first_mcp.1.contains(&"slack".to_string()));
|
||||
|
||||
// Toggle `slack` back on and `github` off while idle -> recycles the resumable session,
|
||||
// so the next prompt calls `session/load` with the updated MCP servers.
|
||||
let updated =
|
||||
mgr.set_mcp_overrides(&task.id, BTreeMap::from([("github".into(), false), ("slack".into(), true)])).unwrap();
|
||||
assert_eq!(updated.mcp_overrides.get("github"), Some(&false));
|
||||
assert_eq!(updated.mcp_overrides.get("slack"), Some(&true));
|
||||
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let reloaded = agent.mcp_calls.lock().last().cloned().unwrap();
|
||||
assert_eq!(reloaded.0, "session/load");
|
||||
assert!(!reloaded.1.contains(&"github".to_string()));
|
||||
assert!(reloaded.1.contains(&"slack".to_string()));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails() {
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -3893,6 +4039,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
config: vec![AgentConfigChoice { id: "context_tier".into(), value: "long_context".into() }],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -3916,6 +4063,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -8,7 +8,8 @@ use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCommand, AgentEntry,
|
||||
AgentEvent, AgentModelCatalog, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput,
|
||||
ExternalSession, McpScope, McpServer, McpServerInput, NewAgentTask,
|
||||
ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput,
|
||||
McpTransport, NewAgentTask,
|
||||
};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult, IpcPath, RequestId, SharedSink, TaskId};
|
||||
@@ -477,19 +478,21 @@ fn persist_mcp_map(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update_mcp_maps<F>(host: &Host, window: &str, approve: Option<&str>, f: F) -> IdeResult<Vec<McpServer>>
|
||||
fn update_mcp_maps<F>(host: &Host, window: &str, approve: &[String], f: F) -> IdeResult<Vec<McpServer>>
|
||||
where
|
||||
F: FnOnce(&mut McpServerMap, &mut McpServerMap, Option<&std::path::Path>) -> Result<(), String>,
|
||||
F: FnOnce(&mut McpServerMap, &mut McpServerMap, Option<&std::path::Path>) -> Result<Vec<String>, String>,
|
||||
{
|
||||
let (mut user, mut workspace, project) = mcp_maps(host, window);
|
||||
let prev_user = user.clone();
|
||||
let prev_workspace = workspace.clone();
|
||||
let project_root = project.as_ref().map(|p| p.root.as_path());
|
||||
f(&mut user, &mut workspace, project_root).map_err(IdeError::invalid)?;
|
||||
if let (Some(name), Some(p)) = (approve, &project)
|
||||
&& let Some(server) = workspace.get(name)
|
||||
{
|
||||
host.mcp_approvals.approve(&p.root, name, server)?;
|
||||
let extra_approved = f(&mut user, &mut workspace, project_root).map_err(IdeError::invalid)?;
|
||||
if let Some(p) = &project {
|
||||
for name in approve.iter().chain(extra_approved.iter()) {
|
||||
if let Some(server) = workspace.get(name.as_str()) {
|
||||
host.mcp_approvals.approve(&p.root, name, server)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if workspace != prev_workspace {
|
||||
persist_mcp_map(host, project.as_ref(), McpScope::Workspace, &workspace)?;
|
||||
@@ -507,11 +510,22 @@ fn listed(
|
||||
user: &McpServerMap,
|
||||
workspace: McpServerMap,
|
||||
) -> Vec<McpServer> {
|
||||
let raw_workspace = workspace.clone();
|
||||
let workspace = match project {
|
||||
Some(p) => host.mcp_approvals.apply(&p.root, workspace),
|
||||
None => workspace,
|
||||
};
|
||||
ide_agent::mcp::servers_from_settings(user, &workspace)
|
||||
let mut out = ide_agent::mcp::servers_from_settings(user, &workspace);
|
||||
if let Some(p) = project {
|
||||
for srv in &mut out {
|
||||
if srv.scope == McpScope::Workspace
|
||||
&& let Some(raw) = raw_workspace.get(&srv.name)
|
||||
{
|
||||
srv.unapproved = !host.mcp_approvals.approved(&p.root, &srv.name, raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The MCP servers agent sessions of the project at `root` get: the user's, values filled in, and
|
||||
@@ -525,7 +539,8 @@ pub(crate) fn session_mcp_servers(
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
let mut user = settings.layer(SettingsScope::Global).agents.mcp_servers;
|
||||
fill_mcp_values(secrets, &mut user);
|
||||
let workspace = approvals.apply(root, settings.layer(SettingsScope::Project).agents.mcp_servers);
|
||||
let mut workspace = settings.layer(SettingsScope::Project).agents.mcp_servers;
|
||||
workspace.retain(|name, srv| approvals.approved(root, name, srv));
|
||||
ide_agent::mcp::servers_from_settings(&user, &workspace)
|
||||
}
|
||||
|
||||
@@ -538,39 +553,289 @@ pub fn mcp_list(host: &Host, window: &str) -> IdeResult<Vec<McpServer>> {
|
||||
/// Creates or updates a User or Workspace MCP server and returns the updated list. A Workspace
|
||||
/// server saved here is one the user turned on.
|
||||
pub fn mcp_save(host: &Host, window: &str, input: McpServerInput) -> IdeResult<Vec<McpServer>> {
|
||||
let approve = (input.scope == McpScope::Workspace).then(|| input.name.trim().to_owned());
|
||||
update_mcp_maps(host, window, approve.as_deref(), |user, workspace, project_root| {
|
||||
ide_agent::mcp::apply_save(user, workspace, project_root.is_some(), input)
|
||||
let approve: Vec<String> =
|
||||
(input.scope == McpScope::Workspace).then(|| input.name.trim().to_owned()).into_iter().collect();
|
||||
update_mcp_maps(host, window, &approve, |user, workspace, project_root| {
|
||||
ide_agent::mcp::apply_save(user, workspace, project_root.is_some(), input).map(|()| Vec::new())
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses and saves one or more MCP servers from a pasted JSON snippet (`{"mcpServers": {...}}` or
|
||||
/// single server object). Workspace servers explicitly saved here by the user are approved.
|
||||
pub fn mcp_save_json(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
scope: McpScope,
|
||||
raw_json: String,
|
||||
fallback_name: Option<String>,
|
||||
agents: Vec<String>,
|
||||
) -> IdeResult<Vec<McpServer>> {
|
||||
update_mcp_maps(host, window, &[], |user, workspace, project_root| {
|
||||
let saved = ide_agent::mcp::apply_save_json(
|
||||
user,
|
||||
workspace,
|
||||
project_root.is_some(),
|
||||
scope,
|
||||
&raw_json,
|
||||
fallback_name.as_deref(),
|
||||
agents,
|
||||
)?;
|
||||
Ok(if scope == McpScope::Workspace { saved } else { Vec::new() })
|
||||
})
|
||||
}
|
||||
|
||||
/// Enables or disables an MCP server and returns the updated list.
|
||||
pub fn mcp_set_enabled(host: &Host, window: &str, id: String, enabled: bool) -> IdeResult<Vec<McpServer>> {
|
||||
let approve = ide_agent::mcp::parse_server_id(&id)
|
||||
let approve: Vec<String> = ide_agent::mcp::parse_server_id(&id)
|
||||
.filter(|(scope, _)| enabled && *scope == McpScope::Workspace)
|
||||
.map(|(_, name)| name.to_owned());
|
||||
update_mcp_maps(host, window, approve.as_deref(), |user, workspace, _| {
|
||||
ide_agent::mcp::apply_set_enabled(user, workspace, &id, enabled).map(|_| ())
|
||||
.map(|(_, name)| name.to_owned())
|
||||
.into_iter()
|
||||
.collect();
|
||||
update_mcp_maps(host, window, &approve, |user, workspace, _| {
|
||||
ide_agent::mcp::apply_set_enabled(user, workspace, &id, enabled).map(|_| Vec::new())
|
||||
})
|
||||
}
|
||||
|
||||
/// Removes a User or Workspace MCP server and returns the updated list.
|
||||
pub fn mcp_remove(host: &Host, window: &str, id: String) -> IdeResult<Vec<McpServer>> {
|
||||
update_mcp_maps(host, window, None, |user, workspace, _| {
|
||||
ide_agent::mcp::apply_remove(user, workspace, &id).map(|_| ())
|
||||
update_mcp_maps(host, window, &[], |user, workspace, _| {
|
||||
ide_agent::mcp::apply_remove(user, workspace, &id).map(|_| Vec::new())
|
||||
})
|
||||
}
|
||||
|
||||
/// Copies MCP servers from `.mcp.json` and `.vscode/mcp.json` into the workspace settings once;
|
||||
/// they stay off until the user turns them on.
|
||||
pub fn mcp_import(host: &Host, window: &str) -> IdeResult<Vec<McpServer>> {
|
||||
update_mcp_maps(host, window, None, |_, workspace, project_root| {
|
||||
update_mcp_maps(host, window, &[], |_, workspace, project_root| {
|
||||
let root = project_root.ok_or_else(|| "Open a project to import workspace MCP servers".to_string())?;
|
||||
ide_agent::mcp::apply_import(workspace, root);
|
||||
Ok(())
|
||||
Ok(Vec::new())
|
||||
})
|
||||
}
|
||||
|
||||
/// Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`).
|
||||
pub async fn mcp_discover_sources(host: &Host, window: &str) -> IdeResult<Vec<McpExternalSource>> {
|
||||
let project_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
|
||||
let home = dirs::home_dir();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
ide_agent::mcp::discover_external_sources(home.as_deref(), project_root.as_deref())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
}
|
||||
|
||||
/// Imports selected servers from discovered external MCP configuration files into User or Workspace scope.
|
||||
/// Imported Workspace entries remain unapproved (disabled) until the user explicitly enables them.
|
||||
pub async fn mcp_import_selected(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
scope: McpScope,
|
||||
selections: Vec<McpImportSelection>,
|
||||
overwrite: bool,
|
||||
) -> IdeResult<Vec<McpServer>> {
|
||||
let home = dirs::home_dir();
|
||||
update_mcp_maps(host, window, &[], move |user, workspace, project_root| {
|
||||
ide_agent::mcp::apply_import_selected(
|
||||
user,
|
||||
workspace,
|
||||
home.as_deref(),
|
||||
project_root,
|
||||
scope,
|
||||
&selections,
|
||||
overwrite,
|
||||
)?;
|
||||
Ok(Vec::new())
|
||||
})
|
||||
}
|
||||
|
||||
/// Tests an MCP server by connecting (`initialize`) and listing its tools (`tools/list`).
|
||||
pub async fn mcp_test(host: &Host, window: &str, id: String) -> IdeResult<McpProbeResult> {
|
||||
host.require_trust(window)?;
|
||||
let (user, workspace, project) = mcp_maps(host, window);
|
||||
let (scope, name) = ide_agent::mcp::parse_server_id(&id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("MCP server `{id}` not found")))?;
|
||||
let server = match scope {
|
||||
McpScope::User => user.get(name),
|
||||
McpScope::Workspace => workspace.get(name),
|
||||
}
|
||||
.cloned()
|
||||
.ok_or_else(|| IdeError::not_found(format!("MCP server `{name}` not found")))?;
|
||||
if scope == McpScope::Workspace {
|
||||
let p = project.as_ref().ok_or_else(|| IdeError::invalid("Open a project to test workspace MCP servers"))?;
|
||||
if !host.mcp_approvals.approved(&p.root, name, &server) {
|
||||
return Err(IdeError::invalid("Enable this workspace MCP server first before testing it"));
|
||||
}
|
||||
}
|
||||
let cwd = project.as_ref().map(|p| p.root.clone()).or_else(dirs::home_dir).unwrap_or_else(std::env::temp_dir);
|
||||
match server.transport {
|
||||
McpTransport::Stdio => Ok(ide_agent::mcp::probe_stdio_server(&server, &cwd).await),
|
||||
McpTransport::Http | McpTransport::Sse => Ok(probe_http_mcp_server(&server).await),
|
||||
}
|
||||
}
|
||||
|
||||
async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> McpProbeResult {
|
||||
let started = std::time::Instant::now();
|
||||
let elapsed_ms = || u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
|
||||
let Some(url) = server.url.as_deref().map(str::trim).filter(|u| !u.is_empty()) else {
|
||||
return McpProbeResult {
|
||||
ok: false,
|
||||
server_name: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
tools: Vec::new(),
|
||||
duration_ms: elapsed_ms(),
|
||||
error: Some("URL is empty".into()),
|
||||
};
|
||||
};
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
headers.insert(
|
||||
reqwest::header::ACCEPT,
|
||||
reqwest::header::HeaderValue::from_static("application/json, text/event-stream"),
|
||||
);
|
||||
for (k, v) in &server.headers {
|
||||
if let (Ok(name), Ok(val)) =
|
||||
(reqwest::header::HeaderName::from_bytes(k.as_bytes()), reqwest::header::HeaderValue::from_str(v))
|
||||
{
|
||||
headers.insert(name, val);
|
||||
}
|
||||
}
|
||||
let client =
|
||||
match reqwest::Client::builder().default_headers(headers).timeout(std::time::Duration::from_secs(12)).build() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
return McpProbeResult {
|
||||
ok: false,
|
||||
server_name: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
tools: Vec::new(),
|
||||
duration_ms: elapsed_ms(),
|
||||
error: Some(format!("HTTP client error: {e}")),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
let post_rpc = |session_id: Option<String>, body: serde_json::Value| {
|
||||
let client = client.clone();
|
||||
let url = url.to_owned();
|
||||
async move {
|
||||
let mut req =
|
||||
client.post(&url).header(reqwest::header::CONTENT_TYPE, "application/json").body(body.to_string());
|
||||
if let Some(sid) = session_id.as_deref() {
|
||||
req = req.header("Mcp-Session-Id", sid);
|
||||
}
|
||||
let resp = req.send().await.map_err(|e| format!("Request to `{url}` failed: {e}"))?;
|
||||
let status = resp.status();
|
||||
let next_session =
|
||||
resp.headers().get("mcp-session-id").and_then(|v| v.to_str().ok()).map(str::to_owned).or(session_id);
|
||||
let text = resp.text().await.map_err(|e| format!("Failed reading response: {e}"))?;
|
||||
if !status.is_success() {
|
||||
let detail = text.trim();
|
||||
let msg = if detail.is_empty() {
|
||||
format!("HTTP {status}")
|
||||
} else {
|
||||
format!("HTTP {status}: {}", detail.chars().take(240).collect::<String>())
|
||||
};
|
||||
return Err(msg);
|
||||
}
|
||||
Ok((next_session, parse_mcp_http_response(&text)?))
|
||||
}
|
||||
};
|
||||
|
||||
let init_req = serde_json::json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": {
|
||||
"protocolVersion": "2024-11-05",
|
||||
"capabilities": {},
|
||||
"clientInfo": { "name": "OpenIDEA", "version": env!("CARGO_PKG_VERSION") },
|
||||
}
|
||||
});
|
||||
|
||||
let (session_id, init_res) = match post_rpc(None, init_req).await {
|
||||
Ok(v) => v,
|
||||
Err(err) => {
|
||||
return McpProbeResult {
|
||||
ok: false,
|
||||
server_name: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
tools: Vec::new(),
|
||||
duration_ms: elapsed_ms(),
|
||||
error: Some(err),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Best-effort `notifications/initialized` + `tools/list`.
|
||||
let mut not_req = client.post(url).header(reqwest::header::CONTENT_TYPE, "application/json").body(
|
||||
serde_json::json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/initialized",
|
||||
"params": {},
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
if let Some(sid) = session_id.as_deref() {
|
||||
not_req = not_req.header("Mcp-Session-Id", sid);
|
||||
}
|
||||
let _ = not_req.send().await;
|
||||
|
||||
let tools_res = post_rpc(
|
||||
session_id,
|
||||
serde_json::json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 2,
|
||||
"method": "tools/list",
|
||||
"params": {},
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.map(|(_, v)| v)
|
||||
.unwrap_or_else(|_| serde_json::json!({}));
|
||||
|
||||
ide_agent::mcp::parse_probe_payloads(&init_res, &tools_res, elapsed_ms())
|
||||
}
|
||||
|
||||
fn parse_mcp_http_response(body: &str) -> Result<serde_json::Value, String> {
|
||||
let trimmed = body.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(serde_json::json!({}));
|
||||
}
|
||||
if let Ok(msg) = serde_json::from_str::<serde_json::Value>(trimmed) {
|
||||
if let Some(err) = msg.get("error") {
|
||||
let em = err.get("message").and_then(serde_json::Value::as_str).unwrap_or("JSON-RPC error");
|
||||
return Err(em.to_owned());
|
||||
}
|
||||
return Ok(msg.get("result").cloned().unwrap_or(msg));
|
||||
}
|
||||
// Streamable HTTP SSE frames (`data: {...}`).
|
||||
for line in trimmed.lines() {
|
||||
if let Some(rest) = line.strip_prefix("data:")
|
||||
&& let Ok(msg) = serde_json::from_str::<serde_json::Value>(rest.trim())
|
||||
&& (msg.get("result").is_some() || msg.get("error").is_some())
|
||||
{
|
||||
if let Some(err) = msg.get("error") {
|
||||
let em = err.get("message").and_then(serde_json::Value::as_str).unwrap_or("JSON-RPC error");
|
||||
return Err(em.to_owned());
|
||||
}
|
||||
return Ok(msg.get("result").cloned().unwrap_or(msg));
|
||||
}
|
||||
}
|
||||
Err("Unexpected non-JSON MCP response".into())
|
||||
}
|
||||
|
||||
/// Updates per-session MCP server enable/disable overrides on task `task`.
|
||||
pub fn set_mcp_overrides(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
overrides: std::collections::BTreeMap<String, bool>,
|
||||
) -> IdeResult<AgentTask> {
|
||||
host.project(window)?.agents.set_mcp_overrides(&task, overrides)
|
||||
}
|
||||
|
||||
/// Commands of this module the remote server answers.
|
||||
pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("agent_subscribe", |c| async move { subscribe(&c.host, &c.window, c.channel("onEvent")?) });
|
||||
@@ -587,12 +852,23 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("agent_registry_remove", |c| async move { registry_remove(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("agent_mcp_list", |c| async move { mcp_list(&c.host, &c.window) });
|
||||
d.add("agent_mcp_save", |c| async move { mcp_save(&c.host, &c.window, c.arg("input")?) });
|
||||
d.add("agent_mcp_save_json", |c| async move {
|
||||
mcp_save_json(&c.host, &c.window, c.arg("scope")?, c.arg("rawJson")?, c.arg("fallbackName")?, c.arg("agents")?)
|
||||
});
|
||||
d.add(
|
||||
"agent_mcp_set_enabled",
|
||||
|c| async move { mcp_set_enabled(&c.host, &c.window, c.arg("id")?, c.arg("enabled")?) },
|
||||
);
|
||||
d.add("agent_mcp_remove", |c| async move { mcp_remove(&c.host, &c.window, c.arg("id")?) });
|
||||
d.add("agent_mcp_import", |c| async move { mcp_import(&c.host, &c.window) });
|
||||
d.add("agent_mcp_discover_sources", |c| async move { mcp_discover_sources(&c.host, &c.window).await });
|
||||
d.add("agent_mcp_import_selected", |c| async move {
|
||||
mcp_import_selected(&c.host, &c.window, c.arg("scope")?, c.arg("selections")?, c.arg("overwrite")?).await
|
||||
});
|
||||
d.add("agent_mcp_test", |c| async move { mcp_test(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("agent_set_mcp_overrides", |c| async move {
|
||||
set_mcp_overrides(&c.host, &c.window, c.arg("task")?, c.arg("overrides")?)
|
||||
});
|
||||
d.add("agent_commands", |c| async move { commands(&c.host, &c.window, c.arg("provider")?, c.arg("task")?).await });
|
||||
d.add("agent_entries", |c| async move { entries(&c.host, &c.window, c.arg("task")?, c.arg("subagent")?) });
|
||||
d.add("agent_create", |c| async move { create(&c.host, &c.window, c.arg("request")?).await });
|
||||
|
||||
@@ -547,9 +547,13 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "agent_registry_remove"
|
||||
| "agent_mcp_list"
|
||||
| "agent_mcp_save"
|
||||
| "agent_mcp_save_json"
|
||||
| "agent_mcp_set_enabled"
|
||||
| "agent_mcp_remove"
|
||||
| "agent_mcp_import"
|
||||
| "agent_mcp_discover_sources"
|
||||
| "agent_mcp_import_selected"
|
||||
| "agent_set_mcp_overrides"
|
||||
| "coverage_import"
|
||||
| "system_font_families"
|
||||
| "user_font_data"
|
||||
|
||||
@@ -121,6 +121,15 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
|
||||
|
||||
**Settings › Tools › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
|
||||
|
||||
### External MCP servers
|
||||
|
||||
**Settings › Agents › External MCP Servers** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
|
||||
|
||||
- **Global (`User`)**: saved in `settings.toml` with environment variable and HTTP header values stored in the OS credential store, shared across projects and agents (or scoped to selected agents).
|
||||
- **Project (`Workspace`)**: saved in `.openidea/settings.toml`; entries with the same name override Global servers, and servers added outside OpenIDEA stay off until approved.
|
||||
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json`, `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
|
||||
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
|
||||
|
||||
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply. **Settings › Agents › Working Status** can show playful words for what it does there instead; they are off by default. Once turned on, they take turns from the moment the work changes, or only after the agent reports nothing new for a number of seconds (0 to 600, 0 by default); screen readers still hear what the agent is doing. Each word stays eight seconds while the agent keeps at the same work, and at least three when it moves on, so the line doesn't flicker. The same page replaces the words: pick what the status says (**Reading…**, **Running a command…**…) and add or remove its words. **Restore Built-in Words** brings back OpenIDEA's; an activity left without words keeps its plain status.
|
||||
|
||||
## Add a custom agent
|
||||
|
||||
@@ -121,6 +121,15 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
**设置 › 工具 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
|
||||
|
||||
### 外部 MCP 服务器
|
||||
|
||||
**设置 › 智能体 › 外部 MCP 服务器** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
|
||||
|
||||
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
|
||||
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
|
||||
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
|
||||
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
|
||||
|
||||
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
|
||||
|
||||
## 添加自定义 agent
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
import type {
|
||||
AgentEntry,
|
||||
AgentProvider,
|
||||
AgentTask,
|
||||
McpExternalSource,
|
||||
McpProbeResult,
|
||||
McpServer,
|
||||
} from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const copilotProvider: AgentProvider = {
|
||||
id: "copilot",
|
||||
name: "GitHub Copilot",
|
||||
command: "copilot",
|
||||
program: "copilot",
|
||||
args: [],
|
||||
defaultProgram: "copilot",
|
||||
defaultArgs: [],
|
||||
loginHint: null,
|
||||
commandOverridden: false,
|
||||
commandEditable: true,
|
||||
commandReadOnlyReason: null,
|
||||
installed: true,
|
||||
env: {},
|
||||
commands: [],
|
||||
source: { kind: "builtin" },
|
||||
config: [
|
||||
{
|
||||
id: "model",
|
||||
category: "model",
|
||||
name: "Model",
|
||||
description: null,
|
||||
current: "claude-sonnet-4.6",
|
||||
via: "option",
|
||||
values: [{ value: "claude-sonnet-4.6", name: "Claude Sonnet 4.6", description: null }],
|
||||
},
|
||||
{
|
||||
id: "mode",
|
||||
category: "mode",
|
||||
name: "Mode",
|
||||
description: null,
|
||||
current: "agent",
|
||||
via: "option",
|
||||
values: [
|
||||
{ value: "agent", name: "Agent", description: null },
|
||||
{ value: "plan", name: "Plan", description: null },
|
||||
],
|
||||
},
|
||||
],
|
||||
thoughtLevels: {},
|
||||
};
|
||||
|
||||
const sampleTask: AgentTask = {
|
||||
id: "mcp-session-1",
|
||||
title: "Investigate authentication service latency",
|
||||
provider: "copilot",
|
||||
status: "ready",
|
||||
isolation: "local",
|
||||
model: "claude-sonnet-4.6",
|
||||
cwd: "/dev/acme-api",
|
||||
branch: "main",
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 0,
|
||||
updatedMs: 0,
|
||||
config: copilotProvider.config,
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
mcpOverrides: {},
|
||||
};
|
||||
|
||||
const initialServers: McpServer[] = [
|
||||
{
|
||||
id: "user::github-mcp-server",
|
||||
name: "github-mcp-server",
|
||||
scope: "user",
|
||||
transport: "http",
|
||||
enabled: true,
|
||||
command: null,
|
||||
args: [],
|
||||
env: [],
|
||||
url: "https://api.githubcopilot.com/mcp/",
|
||||
headers: [{ name: "Authorization", value: "Bearer ***" }],
|
||||
agents: [],
|
||||
unapproved: false,
|
||||
},
|
||||
{
|
||||
id: "user::slack-official",
|
||||
name: "slack-official",
|
||||
scope: "user",
|
||||
transport: "stdio",
|
||||
enabled: true,
|
||||
command: "npx",
|
||||
args: ["-y", "mcp-remote", "https://mcp.slack.com/mcp"],
|
||||
env: [],
|
||||
url: null,
|
||||
headers: [],
|
||||
agents: [],
|
||||
unapproved: false,
|
||||
},
|
||||
{
|
||||
id: "workspace::postgres-local",
|
||||
name: "postgres-local",
|
||||
scope: "workspace",
|
||||
transport: "stdio",
|
||||
enabled: true,
|
||||
command: "npx",
|
||||
args: ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/acme"],
|
||||
env: [{ name: "PGPASSWORD", value: "***" }],
|
||||
url: null,
|
||||
headers: [],
|
||||
agents: [],
|
||||
unapproved: false,
|
||||
},
|
||||
];
|
||||
|
||||
const discoveredSources: McpExternalSource[] = [
|
||||
{
|
||||
id: "copilot-cli",
|
||||
label: "GitHub Copilot CLI",
|
||||
path: "/Users/dev/.copilot/mcp-config.json",
|
||||
suggestedScope: "user",
|
||||
nativeProvider: "copilot",
|
||||
servers: [
|
||||
{
|
||||
name: "workiq",
|
||||
transport: "stdio",
|
||||
enabled: true,
|
||||
command: "npx",
|
||||
args: ["-y", "@microsoft/workiq", "mcp"],
|
||||
url: null,
|
||||
envKeys: [],
|
||||
headerKeys: [],
|
||||
},
|
||||
{
|
||||
name: "datadog",
|
||||
transport: "http",
|
||||
enabled: true,
|
||||
command: null,
|
||||
args: [],
|
||||
url: "https://mcp.datadoghq.com/api/unstable/mcp-server/mcp",
|
||||
envKeys: [],
|
||||
headerKeys: ["DD-API-KEY"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "jetbrains-air",
|
||||
label: "JetBrains Air",
|
||||
path: "/Users/dev/.jetbrains/mcp/mcp.json",
|
||||
suggestedScope: "user",
|
||||
nativeProvider: null,
|
||||
servers: [
|
||||
{
|
||||
name: "linear",
|
||||
transport: "stdio",
|
||||
enabled: true,
|
||||
command: "npx",
|
||||
args: ["-y", "mcp-remote", "https://mcp.linear.app/mcp"],
|
||||
url: null,
|
||||
envKeys: [],
|
||||
headerKeys: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const probeResult: McpProbeResult = {
|
||||
ok: true,
|
||||
serverName: "github-mcp-server",
|
||||
serverVersion: "0.18.2",
|
||||
protocolVersion: "2024-11-05",
|
||||
durationMs: 68,
|
||||
error: null,
|
||||
tools: [
|
||||
{ name: "search_issues", description: "Search issues across GitHub repositories using semantic matching" },
|
||||
{ name: "pull_request_read", description: "Read pull request details, diff, reviews, and CI check runs" },
|
||||
{ name: "list_commits", description: "List commits on a branch in a GitHub repository" },
|
||||
],
|
||||
};
|
||||
|
||||
test("manages multi-level MCP servers in Settings and per-session overrides via Composer /mcp", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1280, height: 840 });
|
||||
await stubDesktop(page);
|
||||
|
||||
await page.evaluate(
|
||||
async ({ copilotProvider, sampleTask, initialServers, discoveredSources, probeResult }) => {
|
||||
const storeModule = "/src/features/agents/store.ts";
|
||||
const store = await import(/* @vite-ignore */ storeModule);
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ projectModule);
|
||||
|
||||
const prevSettings = useProject.getState().settings ?? {};
|
||||
useProject.setState({
|
||||
settings: {
|
||||
...prevSettings,
|
||||
mcpServer: { ...(prevSettings as { mcpServer?: object }).mcpServer, enabled: true },
|
||||
} as never,
|
||||
});
|
||||
|
||||
let servers = structuredClone(initialServers);
|
||||
let currentTask = structuredClone(sampleTask);
|
||||
const entries: AgentEntry[] = [
|
||||
{ type: "user", text: "Can you check why p95 latency spiked on /v1/token?", attachments: [] },
|
||||
{
|
||||
type: "agent",
|
||||
text: "I inspected the token endpoint traces and local Postgres pool configuration. Ready for follow-up.",
|
||||
},
|
||||
];
|
||||
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.agent_subscribe = () => [currentTask];
|
||||
handlers.agent_providers = () => [copilotProvider];
|
||||
handlers.agent_refresh_models = () => ({
|
||||
provider: copilotProvider.id,
|
||||
config: copilotProvider.config,
|
||||
thoughtLevels: {},
|
||||
refreshing: false,
|
||||
refreshedAtMs: Date.now(),
|
||||
retryAtMs: null,
|
||||
error: null,
|
||||
});
|
||||
handlers.agent_probe = () => null;
|
||||
handlers.agent_commands = () => [];
|
||||
handlers.agent_entries = () => entries;
|
||||
handlers.agent_changes = () => [];
|
||||
handlers.agent_grouped_changes = () => ({ uncommitted: [], commits: [] });
|
||||
handlers.vcs_branch_info = () => ({ head: "main" });
|
||||
handlers.vcs_branches = () => [];
|
||||
handlers.agent_mcp_list = () => servers;
|
||||
handlers.agent_mcp_discover_sources = () => discoveredSources;
|
||||
handlers.agent_mcp_test = () => probeResult;
|
||||
handlers.agent_mcp_set_enabled = ({ id, enabled }) => {
|
||||
servers = servers.map((s) => (s.id === id ? { ...s, enabled: Boolean(enabled) } : s));
|
||||
return servers;
|
||||
};
|
||||
handlers.agent_mcp_import_selected = ({ scope, selections }) => {
|
||||
for (const sel of selections as Array<{ sourceId: string; name: string }>) {
|
||||
const src = discoveredSources.find((d) => d.id === sel.sourceId);
|
||||
const srv = src?.servers.find((d) => d.name === sel.name);
|
||||
if (!srv) continue;
|
||||
const id = `${String(scope)}::${srv.name}`;
|
||||
if (!servers.some((s) => s.id === id)) {
|
||||
servers = [
|
||||
...servers,
|
||||
{
|
||||
id,
|
||||
name: srv.name,
|
||||
scope: scope as "user" | "workspace",
|
||||
transport: srv.transport,
|
||||
enabled: true,
|
||||
command: srv.command,
|
||||
args: srv.args,
|
||||
env: [],
|
||||
url: srv.url,
|
||||
headers: [],
|
||||
agents: [],
|
||||
unapproved: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
return servers;
|
||||
};
|
||||
handlers.agent_set_mcp_overrides = ({ overrides }) => {
|
||||
currentTask = { ...currentTask, mcpOverrides: overrides as Record<string, boolean> };
|
||||
return currentTask;
|
||||
};
|
||||
|
||||
await store.connect();
|
||||
store.openTask(currentTask.id);
|
||||
},
|
||||
{ copilotProvider, sampleTask, initialServers, discoveredSources, probeResult },
|
||||
);
|
||||
|
||||
// 1. Open per-session MCP picker via `/mcp` in the active session composer.
|
||||
const composerBox = page.getByRole("textbox", { name: "Message" });
|
||||
await expect(composerBox).toBeVisible();
|
||||
await composerBox.click();
|
||||
await page.keyboard.type("/mc");
|
||||
await expect(page.getByRole("listbox", { name: "Commands" })).toContainText("/mcp");
|
||||
await page.keyboard.press("Enter");
|
||||
|
||||
const sessionPopup = page.getByRole("dialog", { name: "Session MCP Servers" });
|
||||
await expect(sessionPopup).toBeVisible();
|
||||
await expect(sessionPopup).toContainText("openidea");
|
||||
await expect(sessionPopup).toContainText("postgres-local");
|
||||
await expect(sessionPopup).toContainText("github-mcp-server");
|
||||
await expect(sessionPopup).toContainText("workiq");
|
||||
|
||||
// Disable `slack-official` for this session only and verify IPC call + `Session` badge.
|
||||
await sessionPopup.getByRole("switch", { name: "Enable slack-official for this session" }).click();
|
||||
await expect(sessionPopup).toContainText("Session");
|
||||
const overrideCalls = await ipcCalls(page, "agent_set_mcp_overrides");
|
||||
expect(overrideCalls.at(-1)?.overrides).toEqual({ "slack-official": false });
|
||||
|
||||
const screenshotDir = process.env.CAPTURE_MCP_SCREENSHOTS;
|
||||
if (screenshotDir) {
|
||||
await page.screenshot({ path: `${screenshotDir}/mcp-session-picker.png` });
|
||||
}
|
||||
|
||||
await sessionPopup.getByRole("button", { name: "Reset" }).click();
|
||||
await expect(sessionPopup.getByRole("button", { name: "Reset" })).toHaveCount(0);
|
||||
|
||||
// 2. Jump directly from the session MCP popover's gear button to Settings › External MCP Servers.
|
||||
await sessionPopup.getByRole("button", { name: "External MCP Servers…" }).click();
|
||||
const settingsDialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await expect(settingsDialog).toBeVisible();
|
||||
await expect(settingsDialog.getByRole("heading", { name: "External MCP Servers" })).toBeVisible();
|
||||
|
||||
// Probe `github-mcp-server` and inspect discovered tools inside the expandable card.
|
||||
await settingsDialog.getByRole("button", { name: "Test github-mcp-server" }).click();
|
||||
await expect(settingsDialog.getByText("Tools (3)")).toBeVisible();
|
||||
await expect(settingsDialog.getByText("pull_request_read")).toBeVisible();
|
||||
|
||||
if (screenshotDir) {
|
||||
await settingsDialog
|
||||
.getByRole("heading", { name: "External MCP Servers" })
|
||||
.evaluate((el) => el.scrollIntoView({ block: "start" }));
|
||||
await settingsDialog.screenshot({ path: `${screenshotDir}/mcp-hub-levels.png` });
|
||||
await settingsDialog.getByRole("button", { name: "Add from JSON" }).click();
|
||||
const addDialog = page.getByRole("dialog", { name: "Add MCP Server" });
|
||||
await expect(addDialog).toBeVisible();
|
||||
await addDialog.screenshot({ path: `${screenshotDir}/mcp-hub-add-json.png` });
|
||||
await addDialog.getByRole("button", { name: "Cancel" }).click();
|
||||
}
|
||||
|
||||
// Switch to `Agent Configs` tab and verify discovered Copilot CLI + JetBrains Air configs.
|
||||
await settingsDialog.getByRole("tab", { name: /Agent Configs/ }).click();
|
||||
await expect(settingsDialog.getByText("GitHub Copilot CLI")).toBeVisible();
|
||||
await expect(settingsDialog.getByText("JetBrains Air")).toBeVisible();
|
||||
|
||||
if (screenshotDir) {
|
||||
await settingsDialog.screenshot({ path: `${screenshotDir}/mcp-hub-agent-configs.png` });
|
||||
}
|
||||
|
||||
await settingsDialog.getByRole("checkbox", { name: "Select linear" }).click();
|
||||
await settingsDialog.getByRole("button", { name: "Import Selected (1)" }).click();
|
||||
await expect(settingsDialog.getByText("Imported 1 MCP servers into Global settings.")).toBeVisible();
|
||||
});
|
||||
@@ -5,7 +5,8 @@ use ide_agent::registry::AgentRegistry;
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCommand, AgentEntry,
|
||||
AgentEvent, AgentModelCatalog, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput,
|
||||
ExternalSession, McpServer, McpServerInput, NewAgentTask,
|
||||
ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput,
|
||||
NewAgentTask,
|
||||
};
|
||||
use ide_core::{IdeResult, IpcPath, RequestId};
|
||||
use ide_host::ops::agent;
|
||||
@@ -174,6 +175,63 @@ pub fn agent_mcp_import(window: Window, state: State<'_, AppState>) -> IdeResult
|
||||
agent::mcp_import(&state.host, window.label())
|
||||
}
|
||||
|
||||
/// Parses and saves one or more MCP servers from a pasted JSON snippet (`{"mcpServers": {...}}` or
|
||||
/// single server object).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn agent_mcp_save_json(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
scope: McpScope,
|
||||
raw_json: String,
|
||||
fallback_name: Option<String>,
|
||||
agents: Vec<String>,
|
||||
) -> IdeResult<Vec<McpServer>> {
|
||||
agent::mcp_save_json(&state.host, window.label(), scope, raw_json, fallback_name, agents)
|
||||
}
|
||||
|
||||
/// Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn agent_mcp_discover_sources(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
) -> IdeResult<Vec<McpExternalSource>> {
|
||||
agent::mcp_discover_sources(&state.host, window.label()).await
|
||||
}
|
||||
|
||||
/// Imports selected servers from discovered external MCP configuration files into User or Workspace scope.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn agent_mcp_import_selected(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
scope: McpScope,
|
||||
selections: Vec<McpImportSelection>,
|
||||
overwrite: bool,
|
||||
) -> IdeResult<Vec<McpServer>> {
|
||||
agent::mcp_import_selected(&state.host, window.label(), scope, selections, overwrite).await
|
||||
}
|
||||
|
||||
/// Tests an MCP server by connecting (`initialize`) and listing its tools (`tools/list`).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn agent_mcp_test(window: Window, state: State<'_, AppState>, id: String) -> IdeResult<McpProbeResult> {
|
||||
agent::mcp_test(&state.host, window.label(), id).await
|
||||
}
|
||||
|
||||
/// Updates per-session MCP server enable/disable overrides on `task`.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn agent_set_mcp_overrides(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
task: String,
|
||||
overrides: std::collections::BTreeMap<String, bool>,
|
||||
) -> IdeResult<AgentTask> {
|
||||
agent::set_mcp_overrides(&state.host, window.label(), task, overrides)
|
||||
}
|
||||
|
||||
/// Slash commands to complete for `provider` in `task`'s directory, or in the project
|
||||
/// before a task exists (skills and custom commands on disk included).
|
||||
#[tauri::command]
|
||||
|
||||
@@ -137,9 +137,14 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
agent::agent_registry_remove,
|
||||
agent::agent_mcp_list,
|
||||
agent::agent_mcp_save,
|
||||
agent::agent_mcp_save_json,
|
||||
agent::agent_mcp_set_enabled,
|
||||
agent::agent_mcp_remove,
|
||||
agent::agent_mcp_import,
|
||||
agent::agent_mcp_discover_sources,
|
||||
agent::agent_mcp_import_selected,
|
||||
agent::agent_mcp_test,
|
||||
agent::agent_set_mcp_overrides,
|
||||
agent::agent_commands,
|
||||
agent::agent_entries,
|
||||
agent::agent_create,
|
||||
|
||||
@@ -17,11 +17,15 @@ agent_external_sessions trusted project_host bin
|
||||
agent_fork trusted project_host bindings async
|
||||
agent_grouped_changes trusted project_host bindings async
|
||||
agent_import_session trusted project_host bindings async
|
||||
agent_mcp_discover_sources always project_host bindings async
|
||||
agent_mcp_import always project_host bindings sync
|
||||
agent_mcp_import_selected always project_host bindings async
|
||||
agent_mcp_list always project_host bindings sync
|
||||
agent_mcp_remove always project_host bindings sync
|
||||
agent_mcp_save always project_host bindings sync
|
||||
agent_mcp_save_json always project_host bindings sync
|
||||
agent_mcp_set_enabled always project_host bindings sync
|
||||
agent_mcp_test trusted project_host bindings async
|
||||
agent_probe trusted project_host bindings async
|
||||
agent_prompt trusted project_host bindings async
|
||||
agent_providers trusted project_host bindings sync
|
||||
@@ -37,6 +41,7 @@ agent_send_queued_now trusted project_host bin
|
||||
agent_set_command trusted project_host bindings sync
|
||||
agent_set_config trusted project_host bindings async
|
||||
agent_set_env trusted project_host bindings sync
|
||||
agent_set_mcp_overrides always project_host bindings sync
|
||||
agent_stop_background always project_host bindings async
|
||||
agent_subscribe always project_host bindings sync
|
||||
agent_unarchive always project_host bindings sync
|
||||
|
||||
+162
-15
@@ -145,7 +145,7 @@ export const commands = {
|
||||
/** Routes frontend logs into the backend `tracing` pipeline. */
|
||||
logFrontend: (level: LogLevel, message: string) => __TAURI_INVOKE<void>("log_frontend", { level, message }),
|
||||
/** Streams the project's agent events to this window; returns every task. */
|
||||
agentSubscribe: (onEvent: Channel<AgentEvent>) => typedError<AgentTask[], IdeError>(__TAURI_INVOKE("agent_subscribe", { onEvent })),
|
||||
agentSubscribe: (onEvent: Channel<AgentEvent_Deserialize>) => typedError<AgentTask_Serialize[], IdeError>(__TAURI_INVOKE("agent_subscribe", { onEvent })),
|
||||
agentProviders: () => typedError<AgentProvider[], IdeError>(__TAURI_INVOKE("agent_providers")),
|
||||
/** Refreshes the model catalog; force bypasses freshness, not the cooldown. */
|
||||
agentRefreshModels: (provider: string, force: boolean) => typedError<AgentModelCatalog, IdeError>(__TAURI_INVOKE("agent_refresh_models", { provider, force })),
|
||||
@@ -184,12 +184,25 @@ export const commands = {
|
||||
agentMcpList: () => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_list")),
|
||||
/** Creates or updates a User or Workspace MCP server and returns the updated list. */
|
||||
agentMcpSave: (input: McpServerInput) => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_save", { input })),
|
||||
/**
|
||||
* Parses and saves one or more MCP servers from a pasted JSON snippet (`{"mcpServers": {...}}` or
|
||||
* single server object).
|
||||
*/
|
||||
agentMcpSaveJson: (scope: McpScope, rawJson: string, fallbackName: string | null, agents: string[]) => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_save_json", { scope, rawJson, fallbackName, agents })),
|
||||
/** Enables or disables an MCP server and returns the updated list. */
|
||||
agentMcpSetEnabled: (id: string, enabled: boolean) => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_set_enabled", { id, enabled })),
|
||||
/** Removes a User or Workspace MCP server and returns the updated list. */
|
||||
agentMcpRemove: (id: string) => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_remove", { id })),
|
||||
/** Copies MCP servers from `.mcp.json` and `.vscode/mcp.json` into the workspace settings once. */
|
||||
agentMcpImport: () => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_import")),
|
||||
/** Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`). */
|
||||
agentMcpDiscoverSources: () => typedError<McpExternalSource[], IdeError>(__TAURI_INVOKE("agent_mcp_discover_sources")),
|
||||
/** Imports selected servers from discovered external MCP configuration files into User or Workspace scope. */
|
||||
agentMcpImportSelected: (scope: McpScope, selections: McpImportSelection[], overwrite: boolean) => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_import_selected", { scope, selections, overwrite })),
|
||||
/** Tests an MCP server by connecting (`initialize`) and listing its tools (`tools/list`). */
|
||||
agentMcpTest: (id: string) => typedError<McpProbeResult, IdeError>(__TAURI_INVOKE("agent_mcp_test", { id })),
|
||||
/** Updates per-session MCP server enable/disable overrides on `task`. */
|
||||
agentSetMcpOverrides: (task: string, overrides: { [key in string]: boolean }) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_set_mcp_overrides", { task, overrides })),
|
||||
/**
|
||||
* Slash commands to complete for `provider` in `task`'s directory, or in the project
|
||||
* before a task exists (skills and custom commands on disk included).
|
||||
@@ -197,11 +210,11 @@ export const commands = {
|
||||
agentCommands: (provider: string, task: string | null) => typedError<AgentCommand[], IdeError>(__TAURI_INVOKE("agent_commands", { provider, task })),
|
||||
/** Entries of `task`'s conversation, or of its subagent `subagent`'s. */
|
||||
agentEntries: (task: string, subagent: string | null) => typedError<AgentEntry[], IdeError>(__TAURI_INVOKE("agent_entries", { task, subagent })),
|
||||
agentCreate: (request: NewAgentTask) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_create", { request })),
|
||||
agentCreate: (request: NewAgentTask) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_create", { request })),
|
||||
/** Sessions of the project on this machine that no task holds yet, newest first. */
|
||||
agentExternalSessions: () => typedError<ExternalSession[], IdeError>(__TAURI_INVOKE("agent_external_sessions")),
|
||||
/** Imports an external session as a task: its first turn loads and replays it. */
|
||||
agentImportSession: (provider: string, sessionId: string) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_import_session", { provider, sessionId })),
|
||||
agentImportSession: (provider: string, sessionId: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_import_session", { provider, sessionId })),
|
||||
/** Sends a message; while the agent works it is queued, or with `now` it interrupts the turn. */
|
||||
agentPrompt: (task: string, prompt: AgentPrompt, now: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("agent_prompt", { task, prompt, now })),
|
||||
/** Drops a queued message and returns it (to edit it). */
|
||||
@@ -211,12 +224,12 @@ export const commands = {
|
||||
/** Changes a session setting (model, mode, thinking effort…). */
|
||||
agentSetConfig: (task: string, option: string, value: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_config", { task, option, value })),
|
||||
/** Copies the task's conversation into a new task, up to its first `turns` turns (all when `None`). */
|
||||
agentFork: (task: string, turns: number | null) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_fork", { task, turns })),
|
||||
agentFork: (task: string, turns: number | null) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_fork", { task, turns })),
|
||||
/**
|
||||
* Creates a temporary side conversation of `source`: lives in memory only, never
|
||||
* persisted, not listed, and its session starts with the first message sent to it.
|
||||
*/
|
||||
agentCreateEphemeral: (request: NewAgentTask, source: string) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_create_ephemeral", { request, source })),
|
||||
agentCreateEphemeral: (request: NewAgentTask, source: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_create_ephemeral", { request, source })),
|
||||
/** Drops the task's turns after its first `turns`; returns the message of the first dropped one. */
|
||||
agentRollback: (task: string, turns: number) => typedError<{
|
||||
text: string,
|
||||
@@ -2111,26 +2124,51 @@ form?: AgentForm | null;
|
||||
chosen: string | null } | { type: "error"; message: string };
|
||||
|
||||
/** Streamed to the window that subscribed (`AgentManager::subscribe`). */
|
||||
export type AgentEvent =
|
||||
export type AgentEvent = AgentEvent_Serialize | AgentEvent_Deserialize;
|
||||
|
||||
/** Streamed to the window that subscribed (`AgentManager::subscribe`). */
|
||||
export type AgentEvent_Deserialize =
|
||||
/** A task was created or its metadata changed. */
|
||||
{ type: "task"; task: AgentTask } | { type: "removed"; id: string } |
|
||||
({ type: "task"; task: AgentTask_Deserialize }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; text?: never } | ({ type: "removed"; id: string }) & { catalog?: never; entry?: never; eventId?: never; from?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; task?: never; text?: never } |
|
||||
/** The task's conversation was cut to its first `length` entries (turns rolled back). */
|
||||
{ type: "truncated"; task: string; length: number } |
|
||||
({ type: "truncated"; task: string; length: number }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; limits?: never; provider?: never; reason?: never; subagent?: never; text?: never } |
|
||||
/** Entry `index` of `task` (of its subagent `subagent`) was added or replaced. */
|
||||
{ type: "entry"; task: string; subagent: string | null; index: number; entry: AgentEntry } |
|
||||
({ type: "entry"; task: string; subagent: string | null; index: number; entry: AgentEntry }) & { catalog?: never; eventId?: never; from?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never; text?: never } |
|
||||
/**
|
||||
* Text was appended to entry `index` (an agent message or a thought): it read the first
|
||||
* `from` UTF-16 units of its text when the previous event for it was sent.
|
||||
*/
|
||||
{ type: "append"; task: string; subagent: string | null; index: number; from: number; text: string } |
|
||||
({ type: "append"; task: string; subagent: string | null; index: number; from: number; text: string }) & { catalog?: never; entry?: never; eventId?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never } |
|
||||
/** An agent reported the usage limits of its account (shared by every task of `provider`). */
|
||||
{ type: "limits"; provider: string; limits: AgentLimit[] } |
|
||||
({ type: "limits"; provider: string; limits: AgentLimit[] }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; reason?: never; subagent?: never; task?: never; text?: never } |
|
||||
/** A model lookup started or completed, including unsuccessful lookups. */
|
||||
{ type: "modelCatalog"; catalog: AgentModelCatalog } |
|
||||
({ type: "modelCatalog"; catalog: AgentModelCatalog }) & { entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; task?: never; text?: never } |
|
||||
/** The installed or configured agent providers changed. */
|
||||
{ type: "providers" } |
|
||||
({ type: "providers" }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; task?: never; text?: never } |
|
||||
/** The task needs attention once (finished turn, explicit input, or failure). */
|
||||
{ type: "attention"; task: string; eventId: string; reason: AgentAttentionReason };
|
||||
({ type: "attention"; task: string; eventId: string; reason: AgentAttentionReason }) & { catalog?: never; entry?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; subagent?: never; text?: never };
|
||||
|
||||
/** Streamed to the window that subscribed (`AgentManager::subscribe`). */
|
||||
export type AgentEvent_Serialize =
|
||||
/** A task was created or its metadata changed. */
|
||||
({ type: "task"; task: AgentTask_Serialize }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; text?: never } | ({ type: "removed"; id: string }) & { catalog?: never; entry?: never; eventId?: never; from?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; task?: never; text?: never } |
|
||||
/** The task's conversation was cut to its first `length` entries (turns rolled back). */
|
||||
({ type: "truncated"; task: string; length: number }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; limits?: never; provider?: never; reason?: never; subagent?: never; text?: never } |
|
||||
/** Entry `index` of `task` (of its subagent `subagent`) was added or replaced. */
|
||||
({ type: "entry"; task: string; subagent: string | null; index: number; entry: AgentEntry }) & { catalog?: never; eventId?: never; from?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never; text?: never } |
|
||||
/**
|
||||
* Text was appended to entry `index` (an agent message or a thought): it read the first
|
||||
* `from` UTF-16 units of its text when the previous event for it was sent.
|
||||
*/
|
||||
({ type: "append"; task: string; subagent: string | null; index: number; from: number; text: string }) & { catalog?: never; entry?: never; eventId?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never } |
|
||||
/** An agent reported the usage limits of its account (shared by every task of `provider`). */
|
||||
({ type: "limits"; provider: string; limits: AgentLimit[] }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; reason?: never; subagent?: never; task?: never; text?: never } |
|
||||
/** A model lookup started or completed, including unsuccessful lookups. */
|
||||
({ type: "modelCatalog"; catalog: AgentModelCatalog }) & { entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; task?: never; text?: never } |
|
||||
/** The installed or configured agent providers changed. */
|
||||
({ type: "providers" }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; task?: never; text?: never } |
|
||||
/** The task needs attention once (finished turn, explicit input, or failure). */
|
||||
({ type: "attention"; task: string; eventId: string; reason: AgentAttentionReason }) & { catalog?: never; entry?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; subagent?: never; text?: never };
|
||||
|
||||
/** A form the agent asks the user to fill in (ACP `elicitation/create`, form mode). */
|
||||
export type AgentForm = {
|
||||
@@ -2478,7 +2516,9 @@ export type AgentSubagentStatus = "running" |
|
||||
/** One of its requests (a permission) waits for an answer. */
|
||||
"needsInput" | "done" | "cancelled" | "failed";
|
||||
|
||||
export type AgentTask = {
|
||||
export type AgentTask = AgentTask_Serialize | AgentTask_Deserialize;
|
||||
|
||||
export type AgentTask_Deserialize = {
|
||||
/** Original project folder; absent in tasks saved before per-task roots. */
|
||||
projectRoot?: IpcPath | null,
|
||||
id: string,
|
||||
@@ -2522,6 +2562,56 @@ export type AgentTask = {
|
||||
retry?: AgentRetry | null,
|
||||
/** What the agent runs in the background (shells, subagents, monitors), oldest first. */
|
||||
background?: AgentBackgroundTask[],
|
||||
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
|
||||
mcpOverrides?: { [key in string]: boolean },
|
||||
};
|
||||
|
||||
export type AgentTask_Serialize = {
|
||||
/** Original project folder; absent in tasks saved before per-task roots. */
|
||||
projectRoot: IpcPath | null,
|
||||
id: string,
|
||||
title: string,
|
||||
/** [`AgentProvider::id`]. */
|
||||
provider: string,
|
||||
/** Model the task runs on (its `model` setting), when known. */
|
||||
model: string | null,
|
||||
status: AgentStatus,
|
||||
isolation: Isolation,
|
||||
/** Directory the agent works in (the worktree, or the project root). */
|
||||
cwd: IpcPath,
|
||||
/** Branch of the task's worktree. */
|
||||
branch: string | null,
|
||||
/** Branch (or revision) the worktree was created from. */
|
||||
base: string | null,
|
||||
/** Commit the task's changes are compared against (worktree tasks; local ones use `HEAD`). */
|
||||
baseCommit: string | null,
|
||||
/** Why the task failed, when it did. */
|
||||
error: string | null,
|
||||
createdMs: number | null,
|
||||
updatedMs: number | null,
|
||||
/**
|
||||
* The session's settings (model, mode, thinking effort…) as last reported, with the
|
||||
* user's choices applied.
|
||||
*/
|
||||
config: AgentConfigOption[],
|
||||
/** Slash commands the agent offers. */
|
||||
commands: AgentCommand[],
|
||||
/** Context window use, when the agent reports it. */
|
||||
usage: AgentUsage | null,
|
||||
/** Messages waiting for the current turn to end, oldest first. */
|
||||
queue: AgentQueued[],
|
||||
capabilities: AgentCapabilities,
|
||||
/** When a [`AgentStatus::Limited`] task's limit resets (ms since the epoch), if the agent said. */
|
||||
resetsMs: number | null,
|
||||
/**
|
||||
* The agent is retrying a failed API request (connection lost, overloaded…); cleared
|
||||
* by its next output or any status change.
|
||||
*/
|
||||
retry: AgentRetry | null,
|
||||
/** What the agent runs in the background (shells, subagents, monitors), oldest first. */
|
||||
background: AgentBackgroundTask[],
|
||||
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
|
||||
mcpOverrides?: { [key in string]: boolean },
|
||||
};
|
||||
|
||||
/** Token pricing (Credits per 1M tokens) and context window capacity for one tier. */
|
||||
@@ -7646,12 +7736,59 @@ export type MavenSettings = {
|
||||
delegateBuild?: boolean,
|
||||
};
|
||||
|
||||
/** Summary of one server discovered inside an external MCP configuration file. */
|
||||
export type McpDiscoveredServer = {
|
||||
name: string,
|
||||
transport: McpTransport,
|
||||
enabled: boolean,
|
||||
command: string | null,
|
||||
args: string[],
|
||||
url: string | null,
|
||||
/** Environment variable names declared on this server (values stay on the host). */
|
||||
envKeys: string[],
|
||||
/** HTTP header names declared on this server (values stay on the host). */
|
||||
headerKeys: string[],
|
||||
};
|
||||
|
||||
/** An external MCP configuration file discovered on disk (user CLI config or workspace file). */
|
||||
export type McpExternalSource = {
|
||||
/** Stable source identifier (e.g. `"copilot-cli"`, `"jetbrains-air"`, `"claude-code"`, `"cursor"`, `"workspace-mcp"`, `"vscode-mcp"`). */
|
||||
id: string,
|
||||
/** Human-readable source label (e.g. `"GitHub Copilot CLI"`). */
|
||||
label: string,
|
||||
/** Absolute path of the discovered configuration file. */
|
||||
path: IpcPath,
|
||||
/** Suggested target scope when importing this source into OpenIDEA settings. */
|
||||
suggestedScope: McpScope,
|
||||
/** Agent provider ID this external CLI reads natively (`Some("copilot")`, `Some("claude")`, `Some("cursor")`, or `None`). */
|
||||
nativeProvider: string | null,
|
||||
/** Servers found inside this external configuration file (values omitted for safety; imported directly on the host). */
|
||||
servers: McpDiscoveredServer[],
|
||||
};
|
||||
|
||||
/** Selection of one server from an external MCP configuration source to import. */
|
||||
export type McpImportSelection = {
|
||||
sourceId: string,
|
||||
name: string,
|
||||
};
|
||||
|
||||
/** A named environment variable or HTTP header for an MCP server. */
|
||||
export type McpKeyValue = {
|
||||
name: string,
|
||||
value: string,
|
||||
};
|
||||
|
||||
/** Result of testing/probing an MCP server (`initialize` + `tools/list`). */
|
||||
export type McpProbeResult = {
|
||||
ok: boolean,
|
||||
serverName: string | null,
|
||||
serverVersion: string | null,
|
||||
protocolVersion: string | null,
|
||||
tools: McpToolSummary[],
|
||||
durationMs: number,
|
||||
error: string | null,
|
||||
};
|
||||
|
||||
/** Where an MCP server configuration is stored (`settings.toml` vs `.openidea/settings.toml`). */
|
||||
export type McpScope = "user" | "workspace";
|
||||
|
||||
@@ -7669,6 +7806,8 @@ export type McpServer = {
|
||||
headers: McpKeyValue[],
|
||||
/** Agent provider ids this server is enabled for; empty means enabled for all agents. */
|
||||
agents?: string[],
|
||||
/** True when this Workspace server was added outside OpenIDEA and has not been approved yet. */
|
||||
unapproved?: boolean,
|
||||
};
|
||||
|
||||
/** Payload for creating or updating a user or workspace MCP server. */
|
||||
@@ -7742,6 +7881,12 @@ export type McpServerStatus = {
|
||||
stdioCommand: string[],
|
||||
};
|
||||
|
||||
/** One tool advertised by an MCP server during `tools/list`. */
|
||||
export type McpToolSummary = {
|
||||
name: string,
|
||||
description: string | null,
|
||||
};
|
||||
|
||||
/** Transport of an MCP server configured in Settings › Agents › MCP Servers. */
|
||||
export type McpTransport = "stdio" | "http" | "sse";
|
||||
|
||||
@@ -7922,6 +8067,8 @@ export type NewAgentTask = {
|
||||
isolation: Isolation,
|
||||
/** Branch to start the worktree from; the current branch when `None`. */
|
||||
base: string | null,
|
||||
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`). */
|
||||
mcpOverrides?: { [key in string]: boolean },
|
||||
};
|
||||
|
||||
/** The approvals new agent tasks start with. */
|
||||
|
||||
@@ -131,6 +131,8 @@ export interface ComposerProps {
|
||||
onConfig?: (option: string, value: string) => void;
|
||||
/** `now`: send even while the agent works, into its turn (by default ⌘↵). */
|
||||
onSubmit: (now: boolean) => void;
|
||||
/** Opens the per-session MCP servers picker when `/mcp` is run. */
|
||||
onOpenMcp?: () => void;
|
||||
disabled?: boolean;
|
||||
autoFocus?: boolean;
|
||||
/** A request from this host to focus its input without changing the selection. */
|
||||
@@ -468,9 +470,21 @@ export function Composer(props: ComposerProps) {
|
||||
...rest,
|
||||
];
|
||||
}
|
||||
const availableCommands =
|
||||
props.onOpenMcp && completion.query.length > 0 && !props.commands.some((c) => c.name === "mcp")
|
||||
? [
|
||||
{
|
||||
name: "mcp",
|
||||
description: tx("Configure MCP servers for this session"),
|
||||
hint: null,
|
||||
source: "command" as const,
|
||||
},
|
||||
...props.commands,
|
||||
]
|
||||
: props.commands;
|
||||
const out: Item[] = [];
|
||||
let source: "command" | "skill" | undefined;
|
||||
for (const command of matchCommands(props.commands, completion.query)) {
|
||||
for (const command of matchCommands(availableCommands, completion.query)) {
|
||||
const next = command.source ?? "command";
|
||||
if (source !== next) {
|
||||
source = next;
|
||||
@@ -479,7 +493,7 @@ export function Composer(props: ComposerProps) {
|
||||
out.push({ kind: "command", command });
|
||||
}
|
||||
return out;
|
||||
}, [completion, files, props.commands]);
|
||||
}, [completion, files, props.commands, props.onOpenMcp, tx]);
|
||||
const activeIndex = items[active] && !isSection(items[active]!) ? active : firstSelectable(items, isSection);
|
||||
const open = !!completion && items.some((item) => !isSection(item));
|
||||
const anchorAt = open ? completion.to : null;
|
||||
@@ -552,6 +566,11 @@ export function Composer(props: ComposerProps) {
|
||||
}
|
||||
const next = applyCompletion(current, completion, mentionOf(rel));
|
||||
setText(next.text, next.caret);
|
||||
} else if (item.command.name === "mcp" && props.onOpenMcp) {
|
||||
replace(completion.from, completion.to, "");
|
||||
setCompletion(null);
|
||||
props.onOpenMcp();
|
||||
return;
|
||||
} else {
|
||||
const next = applyCompletion(current, completion, `/${item.command.name}`);
|
||||
setText(next.text, next.caret);
|
||||
@@ -886,6 +905,12 @@ export function Composer(props: ComposerProps) {
|
||||
}
|
||||
const send = sendKeyAction(e, sendWith, whileRunning);
|
||||
if (send) {
|
||||
if (props.onOpenMcp && view.state.doc.toString().trim() === "/mcp") {
|
||||
setText("");
|
||||
setCompletion(null);
|
||||
props.onOpenMcp();
|
||||
return handled();
|
||||
}
|
||||
if (!props.disabled) props.onSubmit(send === "now");
|
||||
recalled.current = { index: -1, stash: "" };
|
||||
return handled();
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Composer } from "./Composer";
|
||||
import { SubmitButton } from "./SubmitButton";
|
||||
import { canSend, emptyDraft } from "./composerModel";
|
||||
import { ConfigPickers } from "./ConfigPickers";
|
||||
import { McpPicker } from "./McpPicker";
|
||||
import { useEffortFocus } from "./effortFocus";
|
||||
import { useAgentFontZoomSurface } from "./fontZoom";
|
||||
import { HOME_KEY, providerIcon } from "./model";
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
draftConfig,
|
||||
refreshProviders,
|
||||
refreshModels,
|
||||
setDraftMcpOverrides,
|
||||
setDraftOption,
|
||||
startTask,
|
||||
updateDraft,
|
||||
@@ -57,6 +59,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
|
||||
const current = repoState?.root === root ? repoState.current : null;
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [starting, setStarting] = useState(false);
|
||||
const [mcpOpenRequest, setMcpOpenRequest] = useState(0);
|
||||
|
||||
// Agents installed in Settings (its own window) show up when this one is back in front.
|
||||
useEffect(() => {
|
||||
@@ -228,6 +231,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
|
||||
config={config}
|
||||
onConfig={setDraftOption}
|
||||
onSubmit={start}
|
||||
onOpenMcp={() => setMcpOpenRequest((n) => n + 1)}
|
||||
disabled={!canStart}
|
||||
toolbar={
|
||||
<>
|
||||
@@ -255,6 +259,14 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{provider && (
|
||||
<McpPicker
|
||||
provider={provider.id}
|
||||
overrides={draft.mcpOverrides}
|
||||
onChange={setDraftMcpOverrides}
|
||||
openRequest={mcpOpenRequest}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
actions={
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
.trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
height: var(--h-control);
|
||||
min-width: 0;
|
||||
padding: 0 6px;
|
||||
border: 0;
|
||||
border-radius: var(--radius-control);
|
||||
background: transparent;
|
||||
color: var(--fg-secondary);
|
||||
font: inherit;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition: background var(--dur-fast) var(--ease);
|
||||
}
|
||||
|
||||
.trigger:hover,
|
||||
.trigger[aria-expanded="true"] {
|
||||
background: var(--bg-toolbar-hover);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
|
||||
.triggerLabel {
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.triggerCount {
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.overrideDot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--accent);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.popup {
|
||||
width: min(352px, calc(100vw - 24px));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 8px 0 6px;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
padding: 0 10px 6px 12px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.title {
|
||||
font-weight: 600;
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
|
||||
.headerActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.resetBtn {
|
||||
padding: 2px 6px;
|
||||
border: 0;
|
||||
border-radius: var(--radius-small, 3px);
|
||||
background: transparent;
|
||||
color: var(--link);
|
||||
font: inherit;
|
||||
font-size: var(--fs-small);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.resetBtn:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.searchWrap {
|
||||
padding: 6px 10px 2px;
|
||||
}
|
||||
|
||||
.list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: 340px;
|
||||
overflow-y: auto;
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.groupLabel {
|
||||
padding: 6px 12px 2px;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-tiny);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.03em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
padding: 5px 10px 5px 12px;
|
||||
}
|
||||
|
||||
.row:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.rowInfo {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.rowTitle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.name {
|
||||
font-weight: 500;
|
||||
color: var(--fg-strong);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sub {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-tiny);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 16px;
|
||||
padding: 0 5px;
|
||||
border-radius: var(--radius-small, 3px);
|
||||
background: var(--bg-floating-toolbar);
|
||||
color: var(--fg-secondary);
|
||||
font-size: 10px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.pillSession {
|
||||
background: color-mix(in srgb, var(--accent) 20%, var(--bg-elev));
|
||||
color: var(--link);
|
||||
}
|
||||
|
||||
.rowControls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--control-off);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.dotOn {
|
||||
background: var(--success);
|
||||
}
|
||||
|
||||
.inlineLink {
|
||||
padding: 2px 6px;
|
||||
border: 0;
|
||||
border-radius: var(--radius-small, 3px);
|
||||
background: var(--bg-elev);
|
||||
box-shadow: inset 0 0 0 1px var(--border-button);
|
||||
color: var(--fg-secondary);
|
||||
font: inherit;
|
||||
font-size: var(--fs-tiny);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.inlineLink:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 12px;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.footer {
|
||||
padding: 6px 12px 2px;
|
||||
border-top: 1px solid var(--border);
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-tiny);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { useState } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { McpExternalSource, McpServer } from "@/bindings";
|
||||
import { McpPicker } from "./McpPicker";
|
||||
import type { McpBackend } from "./mcpModel";
|
||||
|
||||
const SERVERS: McpServer[] = [
|
||||
{
|
||||
id: "user::shared",
|
||||
name: "shared",
|
||||
scope: "user",
|
||||
transport: "stdio",
|
||||
enabled: true,
|
||||
command: "npx",
|
||||
args: ["user-shared"],
|
||||
env: [],
|
||||
url: null,
|
||||
headers: [],
|
||||
agents: [],
|
||||
unapproved: false,
|
||||
},
|
||||
{
|
||||
id: "workspace::shared",
|
||||
name: "shared",
|
||||
scope: "workspace",
|
||||
transport: "stdio",
|
||||
enabled: true,
|
||||
command: "npx",
|
||||
args: ["workspace-shared"],
|
||||
env: [],
|
||||
url: null,
|
||||
headers: [],
|
||||
agents: [],
|
||||
unapproved: false,
|
||||
},
|
||||
{
|
||||
id: "user::claude-only",
|
||||
name: "claude-only",
|
||||
scope: "user",
|
||||
transport: "http",
|
||||
enabled: true,
|
||||
command: null,
|
||||
args: [],
|
||||
env: [],
|
||||
url: "https://mcp.example.com",
|
||||
headers: [],
|
||||
agents: ["claude"],
|
||||
unapproved: false,
|
||||
},
|
||||
];
|
||||
|
||||
const SOURCES: McpExternalSource[] = [
|
||||
{
|
||||
id: "copilot-cli",
|
||||
label: "GitHub Copilot CLI",
|
||||
path: "/Users/dev/.copilot/mcp-config.json",
|
||||
suggestedScope: "user",
|
||||
nativeProvider: "copilot",
|
||||
servers: [
|
||||
{
|
||||
name: "workiq",
|
||||
transport: "stdio",
|
||||
enabled: true,
|
||||
command: "npx",
|
||||
args: ["-y", "@microsoft/workiq", "mcp"],
|
||||
url: null,
|
||||
envKeys: [],
|
||||
headerKeys: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
function Harness({
|
||||
provider = "copilot",
|
||||
openRequest = 0,
|
||||
backend,
|
||||
}: {
|
||||
provider?: string;
|
||||
openRequest?: number;
|
||||
backend?: McpBackend;
|
||||
}) {
|
||||
const [overrides, setOverrides] = useState<Record<string, boolean>>({});
|
||||
return (
|
||||
<McpPicker
|
||||
provider={provider}
|
||||
overrides={overrides}
|
||||
onChange={setOverrides}
|
||||
openRequest={openRequest}
|
||||
backend={backend}
|
||||
testData={{
|
||||
servers: SERVERS,
|
||||
sources: SOURCES,
|
||||
ideMcpEnabled: true,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe("McpPicker", () => {
|
||||
it("resolves IDE, Project override over Global, agent-scoped defaults, and native CLI configs", async () => {
|
||||
render(<Harness provider="copilot" />);
|
||||
|
||||
// Active by default for copilot: openidea (IDE) + shared (Project) + workiq (Copilot CLI) = 3 of 4 (claude-only is off).
|
||||
const trigger = screen.getByRole("button", { name: "MCP servers" });
|
||||
expect(trigger).toHaveTextContent("MCP3/4");
|
||||
|
||||
fireEvent.click(trigger);
|
||||
expect(await screen.findByText("Session MCP Servers")).toBeInTheDocument();
|
||||
expect(screen.getByText("Overrides Global")).toBeInTheDocument();
|
||||
expect(screen.getByText("workiq")).toBeInTheDocument();
|
||||
expect(screen.getByText("Active via GitHub Copilot CLI")).toBeInTheDocument();
|
||||
|
||||
// Toggle `shared` off and `claude-only` on for this session only, then Reset.
|
||||
const sharedSwitch = screen.getByRole("switch", { name: "Enable shared for this session" });
|
||||
const claudeSwitch = screen.getByRole("switch", { name: "Enable claude-only for this session" });
|
||||
expect(sharedSwitch).toHaveAttribute("aria-checked", "true");
|
||||
expect(claudeSwitch).toHaveAttribute("aria-checked", "false");
|
||||
|
||||
fireEvent.click(sharedSwitch);
|
||||
fireEvent.click(claudeSwitch);
|
||||
expect(sharedSwitch).toHaveAttribute("aria-checked", "false");
|
||||
expect(claudeSwitch).toHaveAttribute("aria-checked", "true");
|
||||
expect(screen.getAllByText("Session")).toHaveLength(2);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reset" }));
|
||||
expect(sharedSwitch).toHaveAttribute("aria-checked", "true");
|
||||
expect(claudeSwitch).toHaveAttribute("aria-checked", "false");
|
||||
expect(screen.queryByRole("button", { name: "Reset" })).toBeNull();
|
||||
});
|
||||
|
||||
it("opens automatically when openRequest increments (e.g. /mcp slash command)", async () => {
|
||||
const importSelected = vi.fn(async () => SERVERS);
|
||||
const backend: McpBackend = {
|
||||
list: async () => SERVERS,
|
||||
save: async () => SERVERS,
|
||||
setEnabled: async () => SERVERS,
|
||||
remove: async () => SERVERS,
|
||||
importWorkspace: async () => SERVERS,
|
||||
importSelected,
|
||||
};
|
||||
|
||||
const { rerender } = render(<Harness provider="copilot" openRequest={0} backend={backend} />);
|
||||
expect(screen.queryByText("Session MCP Servers")).toBeNull();
|
||||
|
||||
rerender(<Harness provider="copilot" openRequest={1} backend={backend} />);
|
||||
expect(await screen.findByText("Session MCP Servers")).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Import" }));
|
||||
await waitFor(() =>
|
||||
expect(importSelected).toHaveBeenCalledWith("user", [{ sourceId: "copilot-cli", name: "workiq" }], false),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,407 @@
|
||||
/**
|
||||
* Per-session MCP picker for the New Task and Session composers: shows inherited IDE, Project,
|
||||
* Global, and Agent-Native CLI MCP servers, lets the user toggle servers for this session only,
|
||||
* reset session overrides, or jump to Settings › Agents › External MCP Servers.
|
||||
*/
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { McpExternalSource, McpServer } from "@/bindings";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { formatMessage, useTx } from "@/platform/i18n";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { Icon, IconButton, Popup, SearchField, T, Toggle } from "@/ui";
|
||||
import {
|
||||
IDE_MCP_SETTINGS_PAGE,
|
||||
defaultMcpBackend,
|
||||
nextSessionOverrides,
|
||||
refreshMcpCatalog,
|
||||
resolveSessionMcp,
|
||||
useMcpCatalog,
|
||||
useMcpCatalogSync,
|
||||
type McpBackend,
|
||||
type NativeCliMcpItem,
|
||||
type SessionMcpItem,
|
||||
} from "./mcpModel";
|
||||
import { MCP_PAGE } from "./model";
|
||||
import styles from "./McpPicker.module.css";
|
||||
|
||||
export interface McpPickerProps {
|
||||
provider: string;
|
||||
overrides: Readonly<Record<string, boolean>> | undefined;
|
||||
onChange: (nextOverrides: Record<string, boolean>) => void;
|
||||
disabled?: boolean;
|
||||
/** True while the session is actively running a turn (changes apply on the next turn). */
|
||||
busy?: boolean;
|
||||
/** Bumped when `/mcp` is invoked from the composer to open this popover. */
|
||||
openRequest?: number;
|
||||
/** Optional overrides for unit tests. */
|
||||
backend?: McpBackend;
|
||||
testData?: {
|
||||
servers: readonly McpServer[];
|
||||
sources?: readonly McpExternalSource[];
|
||||
ideMcpEnabled?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export function McpPicker({
|
||||
provider,
|
||||
overrides,
|
||||
onChange,
|
||||
disabled = false,
|
||||
busy = false,
|
||||
openRequest = 0,
|
||||
backend = defaultMcpBackend,
|
||||
testData,
|
||||
}: McpPickerProps) {
|
||||
const tx = useTx();
|
||||
useMcpCatalogSync();
|
||||
const catalogServers = useMcpCatalog((s) => s.servers);
|
||||
const catalogSources = useMcpCatalog((s) => s.sources);
|
||||
const projectIdeMcp = useProject((s) => s.settings?.mcpServer?.enabled ?? false);
|
||||
|
||||
const servers = testData?.servers ?? catalogServers;
|
||||
const sources = testData?.sources ?? catalogSources;
|
||||
const ideMcpEnabled = testData?.ideMcpEnabled ?? projectIdeMcp;
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [seenOpenRequest, setSeenOpenRequest] = useState(openRequest);
|
||||
const [query, setQuery] = useState("");
|
||||
const [importingKey, setImportingKey] = useState<string | null>(null);
|
||||
const anchor = useRef<HTMLButtonElement>(null);
|
||||
|
||||
if (openRequest !== seenOpenRequest) {
|
||||
setSeenOpenRequest(openRequest);
|
||||
if (openRequest > 0 && !disabled) setOpen(true);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (openRequest > 0 && !disabled && !testData) {
|
||||
void refreshMcpCatalog();
|
||||
}
|
||||
}, [openRequest, disabled, testData]);
|
||||
|
||||
const toggleOpen = () => {
|
||||
const next = !open;
|
||||
if (next && !testData) void refreshMcpCatalog();
|
||||
if (!next) setQuery("");
|
||||
setOpen(next);
|
||||
};
|
||||
|
||||
const resolved = useMemo(
|
||||
() => resolveSessionMcp(servers, sources, ideMcpEnabled, provider, overrides ?? {}),
|
||||
[servers, sources, ideMcpEnabled, provider, overrides],
|
||||
);
|
||||
|
||||
const q = query.trim().toLowerCase();
|
||||
const matchesQuery = (name: string, detail?: string) =>
|
||||
!q || name.toLowerCase().includes(q) || (detail ?? "").toLowerCase().includes(q);
|
||||
|
||||
const showIde = matchesQuery(resolved.ide.name, "openidea ide");
|
||||
const filteredWorkspace = resolved.workspace.filter((i) =>
|
||||
matchesQuery(i.name, i.server?.command ?? i.server?.url ?? undefined),
|
||||
);
|
||||
const filteredUser = resolved.user.filter((i) =>
|
||||
matchesQuery(i.name, i.server?.command ?? i.server?.url ?? undefined),
|
||||
);
|
||||
const filteredNative = resolved.nativeCli.filter((i) => matchesQuery(i.name, i.sourceLabel));
|
||||
|
||||
const totalRows = 1 + resolved.workspace.length + resolved.user.length + resolved.nativeCli.length;
|
||||
|
||||
const countLabel =
|
||||
resolved.totalCount === 0
|
||||
? "0"
|
||||
: resolved.activeCount === resolved.totalCount
|
||||
? String(resolved.activeCount)
|
||||
: `${resolved.activeCount}/${resolved.totalCount}`;
|
||||
|
||||
const handleToggleItem = (item: SessionMcpItem, nextEnabled: boolean) => {
|
||||
onChange(nextSessionOverrides(overrides, item, nextEnabled));
|
||||
};
|
||||
|
||||
const handleImportNative = async (item: NativeCliMcpItem) => {
|
||||
if (!backend.importSelected) return;
|
||||
const key = `${item.sourceId}::${item.name}`;
|
||||
setImportingKey(key);
|
||||
try {
|
||||
const next = await backend.importSelected("user", [{ sourceId: item.sourceId, name: item.name }], false);
|
||||
if (!testData) {
|
||||
useMcpCatalog.setState({ servers: next, loaded: true });
|
||||
}
|
||||
} finally {
|
||||
setImportingKey(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
ref={anchor}
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
className={styles.trigger}
|
||||
title={
|
||||
resolved.overrideCount > 0
|
||||
? formatMessage(tx("MCP servers ({active}/{total} active · {overrides} session overrides)"), {
|
||||
active: resolved.activeCount,
|
||||
total: resolved.totalCount,
|
||||
overrides: resolved.overrideCount,
|
||||
})
|
||||
: formatMessage(tx("MCP servers ({active}/{total} active)"), {
|
||||
active: resolved.activeCount,
|
||||
total: resolved.totalCount,
|
||||
})
|
||||
}
|
||||
aria-label={tx("MCP servers")}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
onClick={toggleOpen}
|
||||
>
|
||||
<Icon name="plugin" size={13} />
|
||||
<span className={styles.triggerLabel}>MCP</span>
|
||||
<span className={styles.triggerCount}>{countLabel}</span>
|
||||
{resolved.overrideCount > 0 && <span className={styles.overrideDot} aria-hidden />}
|
||||
</button>
|
||||
|
||||
<Popup
|
||||
open={open}
|
||||
anchor={anchor}
|
||||
placement="top-start"
|
||||
offset={6}
|
||||
onClose={() => {
|
||||
setOpen(false);
|
||||
setQuery("");
|
||||
}}
|
||||
aria-label={tx("Session MCP Servers")}
|
||||
className={styles.popup}
|
||||
>
|
||||
<div className={styles.header}>
|
||||
<span className={styles.title}>
|
||||
<T>Session MCP Servers</T>
|
||||
</span>
|
||||
<div className={styles.headerActions}>
|
||||
{resolved.overrideCount > 0 && (
|
||||
<button type="button" className={styles.resetBtn} onClick={() => onChange({})}>
|
||||
<T>Reset</T>
|
||||
</button>
|
||||
)}
|
||||
<IconButton
|
||||
icon="settings"
|
||||
size="small"
|
||||
title={tx("External MCP Servers…")}
|
||||
aria-label={tx("External MCP Servers…")}
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
void executeAction("file.settings", MCP_PAGE);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{totalRows > 5 && (
|
||||
<div className={styles.searchWrap}>
|
||||
<SearchField
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder={tx("Filter MCP servers…")}
|
||||
aria-label={tx("Filter MCP servers")}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.list}>
|
||||
{showIde && (
|
||||
<>
|
||||
<div className={styles.groupLabel}>
|
||||
<T>IDE</T>
|
||||
</div>
|
||||
<div className={styles.row}>
|
||||
<div className={styles.rowInfo}>
|
||||
<div className={styles.rowTitle}>
|
||||
<span className={styles.name}>openidea</span>
|
||||
{resolved.ide.overridden && (
|
||||
<span className={clsx(styles.pill, styles.pillSession)}>
|
||||
<T>Session</T>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className={styles.sub}>
|
||||
<T>Built-in IDE tools</T>
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.rowControls}>
|
||||
{resolved.ide.lockedReason === "ideDisabled" ? (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.inlineLink}
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
void executeAction("file.settings", IDE_MCP_SETTINGS_PAGE);
|
||||
}}
|
||||
>
|
||||
<T>Enable in Settings</T>
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
<Toggle
|
||||
checked={resolved.ide.enabled}
|
||||
aria-label={tx("Enable openidea for this session")}
|
||||
onChange={(on) => handleToggleItem(resolved.ide, on)}
|
||||
/>
|
||||
<span className={clsx(styles.dot, resolved.ide.enabled && styles.dotOn)} aria-hidden />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{filteredWorkspace.length > 0 && (
|
||||
<>
|
||||
<div className={styles.groupLabel}>
|
||||
<T>Project</T>
|
||||
</div>
|
||||
{filteredWorkspace.map((item) => (
|
||||
<SessionServerRow
|
||||
key={`ws:${item.name}`}
|
||||
item={item}
|
||||
onToggle={(on) => handleToggleItem(item, on)}
|
||||
onOpenSettings={() => {
|
||||
setOpen(false);
|
||||
void executeAction("file.settings", MCP_PAGE);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
|
||||
{filteredUser.length > 0 && (
|
||||
<>
|
||||
<div className={styles.groupLabel}>
|
||||
<T>Global</T>
|
||||
</div>
|
||||
{filteredUser.map((item) => (
|
||||
<SessionServerRow
|
||||
key={`user:${item.name}`}
|
||||
item={item}
|
||||
onToggle={(on) => handleToggleItem(item, on)}
|
||||
onOpenSettings={() => {
|
||||
setOpen(false);
|
||||
void executeAction("file.settings", MCP_PAGE);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
|
||||
{filteredNative.length > 0 && (
|
||||
<>
|
||||
<div className={styles.groupLabel}>
|
||||
<T>Agent Config</T>
|
||||
</div>
|
||||
{filteredNative.map((item) => {
|
||||
const key = `${item.sourceId}::${item.name}`;
|
||||
return (
|
||||
<div key={key} className={styles.row}>
|
||||
<div className={styles.rowInfo}>
|
||||
<div className={styles.rowTitle}>
|
||||
<span className={styles.name}>{item.name}</span>
|
||||
<span className={styles.pill}>{item.server.transport.toUpperCase()}</span>
|
||||
</div>
|
||||
<span className={styles.sub} title={item.sourcePath}>
|
||||
{formatMessage(tx("Active via {source}"), { source: item.sourceLabel })}
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.rowControls}>
|
||||
{backend.importSelected && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={importingKey === key}
|
||||
className={styles.inlineLink}
|
||||
title={tx("Import into Global settings to toggle per session and share across agents")}
|
||||
onClick={() => void handleImportNative(item)}
|
||||
>
|
||||
<T>Import</T>
|
||||
</button>
|
||||
)}
|
||||
<span className={clsx(styles.dot, styles.dotOn)} aria-hidden />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
|
||||
{!showIde && filteredWorkspace.length === 0 && filteredUser.length === 0 && filteredNative.length === 0 && (
|
||||
<div className={styles.empty}>
|
||||
<T>No matching MCP servers.</T>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={styles.footer}>
|
||||
{busy ? <T>Changes apply on the next message.</T> : <T>Toggles here apply to this session only.</T>}
|
||||
</div>
|
||||
</Popup>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SessionServerRow({
|
||||
item,
|
||||
onToggle,
|
||||
onOpenSettings,
|
||||
}: {
|
||||
item: SessionMcpItem;
|
||||
onToggle: (enabled: boolean) => void;
|
||||
onOpenSettings: () => void;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const srv = item.server!;
|
||||
const sub =
|
||||
srv.transport === "stdio"
|
||||
? [srv.command, ...srv.args].filter(Boolean).join(" ")
|
||||
: (srv.url ?? srv.transport.toUpperCase());
|
||||
|
||||
return (
|
||||
<div className={styles.row}>
|
||||
<div className={styles.rowInfo}>
|
||||
<div className={styles.rowTitle}>
|
||||
<span className={styles.name}>{item.name}</span>
|
||||
<span className={styles.pill}>{srv.transport.toUpperCase()}</span>
|
||||
{item.shadowsGlobal && (
|
||||
<span className={styles.pill}>
|
||||
<T>Overrides Global</T>
|
||||
</span>
|
||||
)}
|
||||
{item.overridden && (
|
||||
<span className={clsx(styles.pill, styles.pillSession)}>
|
||||
<T>Session</T>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{sub && (
|
||||
<span className={styles.sub} title={sub}>
|
||||
{sub}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={styles.rowControls}>
|
||||
{item.lockedReason === "unapproved" ? (
|
||||
<button type="button" className={styles.inlineLink} onClick={onOpenSettings}>
|
||||
<T>Approve…</T>
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
<Toggle
|
||||
checked={item.enabled}
|
||||
aria-label={formatMessage(tx("Enable {name} for this session"), { name: item.name })}
|
||||
onChange={onToggle}
|
||||
/>
|
||||
<span className={clsx(styles.dot, item.enabled && styles.dotOn)} aria-hidden />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
.page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
gap: var(--space-2);
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
@@ -10,13 +10,15 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.headerActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
|
||||
.title {
|
||||
@@ -45,50 +47,95 @@
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.topControls {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.tabBar {
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.search {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.error {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-1-5);
|
||||
padding: 6px 8px;
|
||||
border-radius: var(--radius-control);
|
||||
background: color-mix(in srgb, var(--danger) 12%, transparent);
|
||||
color: var(--danger);
|
||||
font-size: var(--fs-small);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.notice {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
padding: 6px 8px;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
padding: 6px 10px;
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--accent-soft);
|
||||
background: color-mix(in srgb, var(--accent) 14%, var(--bg-elev));
|
||||
color: var(--fg);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.noticeMain {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.builtinCard {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg-elev);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
}
|
||||
|
||||
.builtinMain {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.builtinHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.sections {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-top: 1px solid var(--border);
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-bottom: 1px solid var(--border);
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
|
||||
.sectionBar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
min-height: 32px;
|
||||
padding: 2px 4px;
|
||||
min-height: 28px;
|
||||
padding: 2px 2px;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
@@ -108,10 +155,6 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.sectionToggle:hover {
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
|
||||
.chevron {
|
||||
color: var(--fg-muted);
|
||||
flex-shrink: 0;
|
||||
@@ -122,6 +165,12 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.sectionHint {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -140,31 +189,64 @@
|
||||
.sectionBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 2px 0 6px;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
|
||||
.sectionNote {
|
||||
margin: 0;
|
||||
padding: 2px 24px 6px;
|
||||
padding: 0 4px 2px 20px;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.row {
|
||||
.emptyBox {
|
||||
padding: 12px 14px;
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg-elev);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
/* Cline-inspired expandable server card with OpenIDEA multi-level badges. */
|
||||
.card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg-elev);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.cardHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
padding: 6px 8px 6px 22px;
|
||||
border-radius: var(--radius-control);
|
||||
gap: var(--space-2);
|
||||
padding: 8px 10px;
|
||||
}
|
||||
|
||||
.row:hover {
|
||||
.cardHeader:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.rowMain {
|
||||
.cardExpandBtn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cardMain {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
@@ -172,6 +254,14 @@
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.cardTitleRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.serverName {
|
||||
font-weight: 600;
|
||||
color: var(--fg-strong);
|
||||
@@ -180,8 +270,38 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
height: 18px;
|
||||
padding: 0 6px;
|
||||
border-radius: var(--radius-small, 3px);
|
||||
background: var(--bg-floating-toolbar);
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-tiny);
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tagAccent {
|
||||
background: color-mix(in srgb, var(--accent) 18%, var(--bg-elev));
|
||||
color: var(--link);
|
||||
}
|
||||
|
||||
.tagWarning {
|
||||
background: color-mix(in srgb, var(--warning) 18%, var(--bg-elev));
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
.tagSuccess {
|
||||
background: color-mix(in srgb, var(--success) 18%, var(--bg-elev));
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: var(--fg-muted);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -195,6 +315,283 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.statusDot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
background: var(--control-off);
|
||||
}
|
||||
|
||||
.statusOn {
|
||||
background: var(--success);
|
||||
}
|
||||
|
||||
.statusProbing {
|
||||
background: var(--warning);
|
||||
}
|
||||
|
||||
.statusError {
|
||||
background: var(--danger);
|
||||
}
|
||||
|
||||
.cardDrawer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
padding: 8px 12px 10px 28px;
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--bg-app);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.metaGrid {
|
||||
display: grid;
|
||||
grid-template-columns: max-content minmax(0, 1fr);
|
||||
gap: var(--space-1) var(--space-3);
|
||||
align-items: baseline;
|
||||
}
|
||||
|
||||
.metaLabel {
|
||||
color: var(--fg-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.metaValue {
|
||||
color: var(--fg);
|
||||
font-family: var(--font-mono);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.toolsPanel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
padding-top: 4px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.toolsHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
color: var(--fg-secondary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.toolsMeta {
|
||||
color: var(--fg-muted);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.toolsList {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
max-height: 220px;
|
||||
overflow-y: auto;
|
||||
padding-right: 2px;
|
||||
}
|
||||
|
||||
.toolRow {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
padding: 5px 8px;
|
||||
border-radius: var(--radius-small, 3px);
|
||||
background: var(--bg-elev);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
}
|
||||
|
||||
.toolName {
|
||||
font-family: var(--font-mono);
|
||||
font-weight: 600;
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
|
||||
.toolDesc {
|
||||
color: var(--fg-muted);
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.drawerFooter {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.drawerButtons {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
|
||||
/* Discovered external agent CLI sources. */
|
||||
.importToolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
padding: 8px 10px;
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg-elev);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
}
|
||||
|
||||
.importControls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.sourceCard {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg-elev);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.sourceHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
padding: 8px 12px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.sourceTitleGroup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.sourceTitleRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.sourcePath {
|
||||
color: var(--fg-muted);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-tiny);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.discoveredList {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.discoveredRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
padding: 6px 12px;
|
||||
}
|
||||
|
||||
.discoveredRow + .discoveredRow {
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.discoveredMain {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.discoveredInfo {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* Modal Form / JSON switcher and agent pills. */
|
||||
.modalModeBar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
padding: 8px 16px 0;
|
||||
}
|
||||
|
||||
.segmented {
|
||||
display: inline-flex;
|
||||
padding: 2px;
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg-elev);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
}
|
||||
|
||||
.segmentBtn {
|
||||
padding: 3px 10px;
|
||||
border: 0;
|
||||
border-radius: var(--radius-small, 3px);
|
||||
background: transparent;
|
||||
color: var(--fg-muted);
|
||||
font: inherit;
|
||||
font-size: var(--fs-small);
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.segmentActive {
|
||||
background: var(--bg-selected);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
|
||||
.agentPicker {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.agentChip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
height: 24px;
|
||||
padding: 0 8px;
|
||||
border: 0;
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg-elev);
|
||||
box-shadow: inset 0 0 0 1px var(--border-button);
|
||||
color: var(--fg-secondary);
|
||||
font: inherit;
|
||||
font-size: var(--fs-small);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.agentChip:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
|
||||
.agentChipSelected {
|
||||
background: var(--bg-selected);
|
||||
box-shadow: inset 0 0 0 1px var(--accent);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
|
||||
/* Server form: a label column, controls filling the rest. */
|
||||
.form {
|
||||
display: grid;
|
||||
@@ -247,6 +644,10 @@
|
||||
transition: box-shadow var(--dur-fast) var(--ease);
|
||||
}
|
||||
|
||||
.jsonArea {
|
||||
min-height: 168px;
|
||||
}
|
||||
|
||||
.textarea::placeholder {
|
||||
color: var(--fg-faint);
|
||||
}
|
||||
|
||||
+1187
-237
File diff suppressed because it is too large
Load Diff
@@ -80,6 +80,7 @@ import {
|
||||
workTime,
|
||||
} from "./composerModel";
|
||||
import { ConfigPickers } from "./ConfigPickers";
|
||||
import { McpPicker } from "./McpPicker";
|
||||
import { useEffortFocus } from "./effortFocus";
|
||||
import { useAgentFontZoomSurface } from "./fontZoom";
|
||||
import { findRanges, formatDuration, formatSentAt, isFindRangeShown } from "./conversation";
|
||||
@@ -147,6 +148,7 @@ import {
|
||||
sendMessage,
|
||||
sendQueuedNow,
|
||||
setTaskConfig,
|
||||
setTaskMcpOverrides,
|
||||
useAgentCommands,
|
||||
useAgents,
|
||||
} from "./store";
|
||||
@@ -2868,6 +2870,7 @@ function SessionComposer({
|
||||
const project = useProject((s) => s.project);
|
||||
const composer = useAgents((s) => s.composers.get(task.id)) ?? emptyDraft();
|
||||
const [sending, setSending] = useState(false);
|
||||
const [mcpOpenRequest, setMcpOpenRequest] = useState(0);
|
||||
const agentCommands = useAgentCommands(task.provider, task.id, task.commands);
|
||||
const busy = isBusy(task.status);
|
||||
// ↑ recalls this conversation's messages, newest first.
|
||||
@@ -2955,8 +2958,29 @@ function SessionComposer({
|
||||
config={task.config}
|
||||
onConfig={setOption}
|
||||
onSubmit={send}
|
||||
onOpenMcp={() => setMcpOpenRequest((n) => n + 1)}
|
||||
disabled={task.status === "archived"}
|
||||
toolbar={<ConfigPickers config={task.config} onChange={setOption} />}
|
||||
toolbar={
|
||||
<>
|
||||
<ConfigPickers config={task.config} onChange={setOption} />
|
||||
<McpPicker
|
||||
provider={task.provider}
|
||||
overrides={task.mcpOverrides}
|
||||
disabled={task.status === "archived"}
|
||||
busy={busy}
|
||||
openRequest={mcpOpenRequest}
|
||||
onChange={(next) =>
|
||||
void setTaskMcpOverrides(task.id, next).catch((e: unknown) =>
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Couldn't change the setting",
|
||||
body: String(e),
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
actions={
|
||||
<>
|
||||
{busy && <IconButton icon="stop" title="Stop" onClick={() => void cancelTask(task.id)} />}
|
||||
|
||||
@@ -170,6 +170,18 @@ describe("New Task composer commands", () => {
|
||||
expect((await screen.findByRole("listbox", { name: "Commands" })).textContent).toBe("Commands/compact");
|
||||
});
|
||||
|
||||
it("opens the per-session MCP picker when /mcp is completed in the composer", async () => {
|
||||
agentCommands.mockResolvedValue({ status: "ok", data: [] });
|
||||
render(<HomeEditor />);
|
||||
const box = screen.getByRole("textbox");
|
||||
typeIn(box, "/mc");
|
||||
const list = await screen.findByRole("listbox", { name: "Commands" });
|
||||
expect(within(list).getByRole("option", { selected: true })).toHaveTextContent("/mcp");
|
||||
fireEvent.keyDown(box, { key: "Enter" });
|
||||
expect(textOf(box)).toBe("");
|
||||
expect(await screen.findByText("Session MCP Servers")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("names the icon-only Start action and disables it while starting", async () => {
|
||||
agentCommands.mockResolvedValue({ status: "ok", data: [] });
|
||||
let finish!: (value: unknown) => void;
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* Shared MCP server model, multi-level inheritance resolution (IDE -> Project -> Global -> Agent CLI),
|
||||
* and reactive cache for Settings › Agents › External MCP Servers and the Composer MCP picker.
|
||||
*/
|
||||
import { useEffect } from "react";
|
||||
import { create } from "zustand";
|
||||
import type {
|
||||
McpDiscoveredServer,
|
||||
McpExternalSource,
|
||||
McpImportSelection,
|
||||
McpProbeResult,
|
||||
McpScope,
|
||||
McpServer,
|
||||
McpServerInput,
|
||||
} from "@/bindings";
|
||||
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
export const BUILTIN_MCP_NAME = "openidea";
|
||||
export const IDE_MCP_SETTINGS_PAGE = "agents.mcpServer";
|
||||
|
||||
export interface McpBackend {
|
||||
list(): Promise<McpServer[]>;
|
||||
save(input: McpServerInput): Promise<McpServer[]>;
|
||||
saveJson?(scope: McpScope, rawJson: string, fallbackName: string | null, agents: string[]): Promise<McpServer[]>;
|
||||
setEnabled(id: string, enabled: boolean): Promise<McpServer[]>;
|
||||
remove(id: string): Promise<McpServer[]>;
|
||||
importWorkspace(): Promise<McpServer[]>;
|
||||
discoverSources?(): Promise<McpExternalSource[]>;
|
||||
importSelected?(scope: McpScope, selections: McpImportSelection[], overwrite: boolean): Promise<McpServer[]>;
|
||||
testServer?(id: string): Promise<McpProbeResult>;
|
||||
}
|
||||
|
||||
export const defaultMcpBackend: McpBackend = {
|
||||
list: () => (typeof commands.agentMcpList === "function" ? call(commands.agentMcpList()) : Promise.resolve([])),
|
||||
save: (input) => call(commands.agentMcpSave(input)),
|
||||
saveJson: (scope, rawJson, fallbackName, agents) =>
|
||||
call(commands.agentMcpSaveJson(scope, rawJson, fallbackName, agents)),
|
||||
setEnabled: (id, enabled) => call(commands.agentMcpSetEnabled(id, enabled)),
|
||||
remove: (id) => call(commands.agentMcpRemove(id)),
|
||||
importWorkspace: () => call(commands.agentMcpImport()),
|
||||
discoverSources: () =>
|
||||
typeof commands.agentMcpDiscoverSources === "function"
|
||||
? call(commands.agentMcpDiscoverSources())
|
||||
: Promise.resolve([]),
|
||||
importSelected: (scope, selections, overwrite) => call(commands.agentMcpImportSelected(scope, selections, overwrite)),
|
||||
testServer: (id) => call(commands.agentMcpTest(id)),
|
||||
};
|
||||
|
||||
export const normalizeProviderId = (id: string): string => (id.endsWith("-acp") ? id.slice(0, -4) : id);
|
||||
|
||||
export function matchesAgentProvider(agents: readonly string[] | undefined, provider: string): boolean {
|
||||
if (!agents || agents.length === 0) return true;
|
||||
const target = normalizeProviderId(provider);
|
||||
return agents.some((raw) => {
|
||||
const trimmed = raw.trim();
|
||||
return trimmed === provider || normalizeProviderId(trimmed) === target;
|
||||
});
|
||||
}
|
||||
|
||||
export interface SessionMcpItem {
|
||||
name: string;
|
||||
level: "ide" | "workspace" | "user";
|
||||
server?: McpServer;
|
||||
/** Default state inherited from IDE / Project / Global settings for `provider`. */
|
||||
defaultEnabled: boolean;
|
||||
/** Effective state for this session after applying `overrides`. */
|
||||
enabled: boolean;
|
||||
/** True when `overrides` explicitly diverges from `defaultEnabled`. */
|
||||
overridden: boolean;
|
||||
/** True when a Project server shadows a Global server of the same name. */
|
||||
shadowsGlobal: boolean;
|
||||
/** Cannot be toggled in-session (e.g. IDE MCP server is off globally, or unapproved Project server). */
|
||||
lockedReason: "ideDisabled" | "unapproved" | null;
|
||||
}
|
||||
|
||||
export interface NativeCliMcpItem {
|
||||
name: string;
|
||||
sourceId: string;
|
||||
sourceLabel: string;
|
||||
sourcePath: string;
|
||||
server: McpDiscoveredServer;
|
||||
}
|
||||
|
||||
export interface ResolvedSessionMcp {
|
||||
ide: SessionMcpItem;
|
||||
workspace: SessionMcpItem[];
|
||||
user: SessionMcpItem[];
|
||||
nativeCli: NativeCliMcpItem[];
|
||||
activeCount: number;
|
||||
totalCount: number;
|
||||
overrideCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the effective MCP servers for a session running `provider` across all levels:
|
||||
* 1. Built-in IDE MCP server (`openidea`)
|
||||
* 2. Project (`workspace` scope — overrides `user` servers with the same name)
|
||||
* 3. Global (`user` scope)
|
||||
* 4. Agent-native CLI config directories not yet imported into OpenIDEA (`~/.copilot/...`, `~/.claude.json`, etc.)
|
||||
*/
|
||||
export function resolveSessionMcp(
|
||||
servers: readonly McpServer[],
|
||||
sources: readonly McpExternalSource[],
|
||||
ideMcpEnabled: boolean,
|
||||
provider: string,
|
||||
overrides: Readonly<Record<string, boolean>> = {},
|
||||
): ResolvedSessionMcp {
|
||||
const ideOverride = overrides[BUILTIN_MCP_NAME];
|
||||
const ideEffective = ideMcpEnabled ? (ideOverride ?? true) : false;
|
||||
const ide: SessionMcpItem = {
|
||||
name: BUILTIN_MCP_NAME,
|
||||
level: "ide",
|
||||
defaultEnabled: ideMcpEnabled,
|
||||
enabled: ideEffective,
|
||||
overridden: ideMcpEnabled && ideOverride !== undefined && ideOverride !== ideMcpEnabled,
|
||||
shadowsGlobal: false,
|
||||
lockedReason: ideMcpEnabled ? null : "ideDisabled",
|
||||
};
|
||||
|
||||
const userNames = new Set(servers.filter((s) => s.scope === "user").map((s) => s.name));
|
||||
const seenNames = new Set<string>([BUILTIN_MCP_NAME]);
|
||||
const workspace: SessionMcpItem[] = [];
|
||||
const user: SessionMcpItem[] = [];
|
||||
|
||||
for (const srv of servers.filter((s) => s.scope === "workspace")) {
|
||||
seenNames.add(srv.name);
|
||||
const unapproved = !!srv.unapproved;
|
||||
const defaultEnabled = !unapproved && srv.enabled && matchesAgentProvider(srv.agents, provider);
|
||||
const explicit = overrides[srv.name];
|
||||
const enabled = unapproved ? false : (explicit ?? defaultEnabled);
|
||||
workspace.push({
|
||||
name: srv.name,
|
||||
level: "workspace",
|
||||
server: srv,
|
||||
defaultEnabled,
|
||||
enabled,
|
||||
overridden: !unapproved && explicit !== undefined && explicit !== defaultEnabled,
|
||||
shadowsGlobal: userNames.has(srv.name),
|
||||
lockedReason: unapproved ? "unapproved" : null,
|
||||
});
|
||||
}
|
||||
|
||||
for (const srv of servers.filter((s) => s.scope === "user")) {
|
||||
if (seenNames.has(srv.name)) continue;
|
||||
seenNames.add(srv.name);
|
||||
const defaultEnabled = srv.enabled && matchesAgentProvider(srv.agents, provider);
|
||||
const explicit = overrides[srv.name];
|
||||
const enabled = explicit ?? defaultEnabled;
|
||||
user.push({
|
||||
name: srv.name,
|
||||
level: "user",
|
||||
server: srv,
|
||||
defaultEnabled,
|
||||
enabled,
|
||||
overridden: explicit !== undefined && explicit !== defaultEnabled,
|
||||
shadowsGlobal: false,
|
||||
lockedReason: null,
|
||||
});
|
||||
}
|
||||
|
||||
const normalizedProvider = normalizeProviderId(provider);
|
||||
const nativeCli: NativeCliMcpItem[] = [];
|
||||
for (const src of sources) {
|
||||
if (!src.nativeProvider || normalizeProviderId(src.nativeProvider) !== normalizedProvider) continue;
|
||||
for (const srv of src.servers) {
|
||||
if (seenNames.has(srv.name) || !srv.enabled) continue;
|
||||
seenNames.add(srv.name);
|
||||
nativeCli.push({
|
||||
name: srv.name,
|
||||
sourceId: src.id,
|
||||
sourceLabel: src.label,
|
||||
sourcePath: src.path,
|
||||
server: srv,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const controllable = [...(ideMcpEnabled ? [ide] : []), ...workspace.filter((i) => !i.lockedReason), ...user];
|
||||
const activeCount = controllable.filter((i) => i.enabled).length + nativeCli.length;
|
||||
const totalCount = controllable.length + nativeCli.length;
|
||||
const overrideCount = controllable.filter((i) => i.overridden).length;
|
||||
|
||||
return { ide, workspace, user, nativeCli, activeCount, totalCount, overrideCount };
|
||||
}
|
||||
|
||||
/** Computes the minimal `mcpOverrides` map after toggling `name` to `nextEnabled`. */
|
||||
export function nextSessionOverrides(
|
||||
current: Readonly<Record<string, boolean>> | undefined,
|
||||
item: SessionMcpItem,
|
||||
nextEnabled: boolean,
|
||||
): Record<string, boolean> {
|
||||
const next = { ...(current ?? {}) };
|
||||
if (nextEnabled === item.defaultEnabled) {
|
||||
delete next[item.name];
|
||||
} else {
|
||||
next[item.name] = nextEnabled;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Shared window-level cache of configured MCP servers and discovered external CLI configs. */
|
||||
interface McpCatalogState {
|
||||
servers: McpServer[];
|
||||
sources: McpExternalSource[];
|
||||
loaded: boolean;
|
||||
probes: Record<string, McpProbeResult>;
|
||||
probing: Record<string, boolean>;
|
||||
}
|
||||
|
||||
export const useMcpCatalog = create<McpCatalogState>(() => ({
|
||||
servers: [],
|
||||
sources: [],
|
||||
loaded: false,
|
||||
probes: {},
|
||||
probing: {},
|
||||
}));
|
||||
|
||||
let listenerAttached = false;
|
||||
|
||||
export async function refreshMcpCatalog(): Promise<void> {
|
||||
if (!isTauri()) return;
|
||||
const [servers, sources] = await Promise.all([
|
||||
defaultMcpBackend.list().catch(() => null),
|
||||
defaultMcpBackend.discoverSources?.().catch(() => null) ?? Promise.resolve(null),
|
||||
]);
|
||||
useMcpCatalog.setState((prev) => ({
|
||||
servers: servers ?? prev.servers,
|
||||
sources: sources ?? prev.sources,
|
||||
loaded: true,
|
||||
}));
|
||||
}
|
||||
|
||||
export function useMcpCatalogSync(): void {
|
||||
const root = useProject((s) => s.project?.root);
|
||||
useEffect(() => {
|
||||
if (!isTauri()) return;
|
||||
void refreshMcpCatalog();
|
||||
const onFocus = () => void refreshMcpCatalog();
|
||||
window.addEventListener("focus", onFocus);
|
||||
if (!listenerAttached && typeof onIdeEvent === "function") {
|
||||
listenerAttached = true;
|
||||
onIdeEvent("settingsChanged", (e) => {
|
||||
if (!e.key || e.key.startsWith("agents.mcpServers") || e.key.startsWith("mcpServer")) {
|
||||
void refreshMcpCatalog();
|
||||
}
|
||||
});
|
||||
}
|
||||
return () => window.removeEventListener("focus", onFocus);
|
||||
}, [root]);
|
||||
}
|
||||
@@ -1,6 +1,13 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import type { McpServer, McpServerInput } from "@/bindings";
|
||||
import type {
|
||||
McpExternalSource,
|
||||
McpImportSelection,
|
||||
McpProbeResult,
|
||||
McpScope,
|
||||
McpServer,
|
||||
McpServerInput,
|
||||
} from "@/bindings";
|
||||
import { McpServersPage, type McpBackend } from "./McpServersPage";
|
||||
|
||||
const server = (partial: Partial<McpServer> & Pick<McpServer, "id" | "name" | "scope">): McpServer => ({
|
||||
@@ -12,6 +19,7 @@ const server = (partial: Partial<McpServer> & Pick<McpServer, "id" | "name" | "s
|
||||
env: [],
|
||||
headers: [],
|
||||
agents: [],
|
||||
unapproved: false,
|
||||
...partial,
|
||||
});
|
||||
|
||||
@@ -29,18 +37,45 @@ const INITIAL_SERVERS: McpServer[] = [
|
||||
}),
|
||||
];
|
||||
|
||||
const INITIAL_SOURCES: McpExternalSource[] = [
|
||||
{
|
||||
id: "copilot-cli",
|
||||
label: "GitHub Copilot CLI",
|
||||
path: "/Users/dev/.copilot/mcp-config.json",
|
||||
suggestedScope: "user",
|
||||
nativeProvider: "copilot",
|
||||
servers: [
|
||||
{
|
||||
name: "github-mcp-server",
|
||||
transport: "http",
|
||||
enabled: true,
|
||||
command: null,
|
||||
args: [],
|
||||
url: "https://api.githubcopilot.com/mcp/",
|
||||
envKeys: [],
|
||||
headerKeys: ["Authorization"],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
class FakeMcpBackend implements McpBackend {
|
||||
servers: McpServer[] = [...INITIAL_SERVERS];
|
||||
sources: McpExternalSource[] = [...INITIAL_SOURCES];
|
||||
toggled: Array<{ id: string; enabled: boolean }> = [];
|
||||
saved: McpServerInput[] = [];
|
||||
savedJson: Array<{ scope: McpScope; rawJson: string; agents: string[] }> = [];
|
||||
importedSelected: Array<{ scope: McpScope; selections: McpImportSelection[]; overwrite: boolean }> = [];
|
||||
removed: string[] = [];
|
||||
imported = 0;
|
||||
|
||||
list = vi.fn(async () => this.servers);
|
||||
|
||||
discoverSources = vi.fn(async () => this.sources);
|
||||
|
||||
setEnabled = vi.fn(async (id: string, enabled: boolean) => {
|
||||
this.toggled.push({ id, enabled });
|
||||
this.servers = this.servers.map((s) => (s.id === id ? { ...s, enabled } : s));
|
||||
this.servers = this.servers.map((s) => (s.id === id ? { ...s, enabled, unapproved: false } : s));
|
||||
return this.servers;
|
||||
});
|
||||
|
||||
@@ -63,6 +98,62 @@ class FakeMcpBackend implements McpBackend {
|
||||
return this.servers;
|
||||
});
|
||||
|
||||
saveJson = vi.fn(async (scope: McpScope, rawJson: string, _fallback: string | null, agents: string[]) => {
|
||||
this.savedJson.push({ scope, rawJson, agents });
|
||||
const parsed = JSON.parse(rawJson) as { mcpServers?: Record<string, { command?: string; args?: string[] }> };
|
||||
for (const [name, cfg] of Object.entries(parsed.mcpServers ?? {})) {
|
||||
this.servers = [
|
||||
...this.servers.filter((s) => s.id !== `${scope}::${name}`),
|
||||
server({
|
||||
id: `${scope}::${name}`,
|
||||
name,
|
||||
scope,
|
||||
transport: "stdio",
|
||||
command: cfg.command ?? "npx",
|
||||
args: cfg.args ?? [],
|
||||
url: null,
|
||||
agents,
|
||||
}),
|
||||
];
|
||||
}
|
||||
return this.servers;
|
||||
});
|
||||
|
||||
importSelected = vi.fn(async (scope: McpScope, selections: McpImportSelection[], overwrite: boolean) => {
|
||||
this.importedSelected.push({ scope, selections, overwrite });
|
||||
for (const sel of selections) {
|
||||
const src = this.sources.find((s) => s.id === sel.sourceId);
|
||||
const found = src?.servers.find((s) => s.name === sel.name);
|
||||
if (!found) continue;
|
||||
this.servers = [
|
||||
...this.servers.filter((s) => s.id !== `${scope}::${found.name}`),
|
||||
server({
|
||||
id: `${scope}::${found.name}`,
|
||||
name: found.name,
|
||||
scope,
|
||||
transport: found.transport,
|
||||
command: found.command,
|
||||
args: found.args,
|
||||
url: found.url,
|
||||
}),
|
||||
];
|
||||
}
|
||||
return this.servers;
|
||||
});
|
||||
|
||||
testServer = vi.fn(async (_id: string): Promise<McpProbeResult> => ({
|
||||
ok: true,
|
||||
serverName: "mock-mcp",
|
||||
serverVersion: "1.2.0",
|
||||
protocolVersion: "2024-11-05",
|
||||
durationMs: 42,
|
||||
error: null,
|
||||
tools: [
|
||||
{ name: "search_issues", description: "Search issues across repositories" },
|
||||
{ name: "create_pr", description: "Open a pull request" },
|
||||
],
|
||||
}));
|
||||
|
||||
remove = vi.fn(async (id: string) => {
|
||||
this.removed.push(id);
|
||||
this.servers = this.servers.filter((s) => s.id !== id);
|
||||
@@ -80,7 +171,6 @@ class FakeMcpBackend implements McpBackend {
|
||||
args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
|
||||
url: null,
|
||||
});
|
||||
// Like the backend, a server already in the workspace is not imported again.
|
||||
if (!this.servers.some((s) => s.id === importedServer.id)) this.servers = [...this.servers, importedServer];
|
||||
return this.servers;
|
||||
});
|
||||
@@ -112,17 +202,76 @@ describe("McpServersPage", () => {
|
||||
expect(screen.queryByText("slack-official")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("toggles server enabled state via its checkbox", async () => {
|
||||
it("toggles server enabled state via its switch", async () => {
|
||||
const backend = new FakeMcpBackend();
|
||||
render(<McpServersPage backend={backend} />);
|
||||
|
||||
await waitFor(() => expect(screen.getByText("slack-official")).toBeInTheDocument());
|
||||
const box = screen.getByRole("checkbox", { name: "Enable slack-official" });
|
||||
expect(box).toBeChecked();
|
||||
const sw = screen.getByRole("switch", { name: "Enable slack-official" });
|
||||
expect(sw).toHaveAttribute("aria-checked", "true");
|
||||
|
||||
fireEvent.click(box);
|
||||
fireEvent.click(sw);
|
||||
await waitFor(() => expect(backend.toggled).toEqual([{ id: "user::slack-official", enabled: false }]));
|
||||
expect(screen.getByRole("checkbox", { name: "Enable slack-official" })).not.toBeChecked();
|
||||
expect(screen.getByRole("switch", { name: "Enable slack-official" })).toHaveAttribute("aria-checked", "false");
|
||||
});
|
||||
|
||||
it("probes a server and displays discovered tools inside its expandable card", async () => {
|
||||
const backend = new FakeMcpBackend();
|
||||
render(<McpServersPage backend={backend} />);
|
||||
|
||||
await waitFor(() => expect(screen.getByText("slack-official")).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByRole("button", { name: "Test slack-official" }));
|
||||
|
||||
await waitFor(() => expect(backend.testServer).toHaveBeenCalledWith("user::slack-official"));
|
||||
expect(await screen.findByText("search_issues")).toBeInTheDocument();
|
||||
expect(screen.getByText("Search issues across repositories")).toBeInTheDocument();
|
||||
expect(screen.getByText("Tools (2)")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("discovers external agent CLI configs and imports into Global settings", async () => {
|
||||
const backend = new FakeMcpBackend();
|
||||
render(<McpServersPage backend={backend} />);
|
||||
|
||||
await waitFor(() => expect(screen.getByText("slack-official")).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByRole("button", { name: "Review & Import" }));
|
||||
|
||||
expect(await screen.findByText("GitHub Copilot CLI")).toBeInTheDocument();
|
||||
expect(screen.getByText("github-mcp-server")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Select github-mcp-server" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Import Selected (1)" }));
|
||||
|
||||
await waitFor(() => expect(backend.importedSelected).toHaveLength(1));
|
||||
expect(backend.importedSelected[0]).toEqual({
|
||||
scope: "user",
|
||||
selections: [{ sourceId: "copilot-cli", name: "github-mcp-server" }],
|
||||
overwrite: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("saves servers from pasted mcpServers JSON with selected agent chips", async () => {
|
||||
const backend = new FakeMcpBackend();
|
||||
render(<McpServersPage backend={backend} />);
|
||||
|
||||
await waitFor(() => expect(screen.getByText("slack-official")).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add from JSON" }));
|
||||
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
const jsonField = within(dialog).getByLabelText("JSON:");
|
||||
fireEvent.change(jsonField, {
|
||||
target: {
|
||||
value: JSON.stringify({
|
||||
mcpServers: {
|
||||
playwright: { command: "npx", args: ["@playwright/mcp@latest"] },
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "GitHub Copilot" }));
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Add" }));
|
||||
|
||||
await waitFor(() => expect(backend.savedJson).toHaveLength(1));
|
||||
expect(backend.savedJson[0]?.agents).toEqual(["copilot"]);
|
||||
await waitFor(() => expect(screen.getByText("playwright")).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("adds a new workspace MCP server with optional agent filter", async () => {
|
||||
|
||||
@@ -75,6 +75,8 @@ export interface Draft {
|
||||
isolationChosen?: boolean;
|
||||
/** `null`: the current branch. */
|
||||
base: string | null;
|
||||
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`) for the next task. */
|
||||
mcpOverrides?: Record<string, boolean>;
|
||||
}
|
||||
|
||||
/** Composer key of the New Task page; sessions use their task id. */
|
||||
@@ -984,6 +986,7 @@ export async function startTask(
|
||||
config,
|
||||
isolation,
|
||||
base: isolation === "worktree" ? draft.base : null,
|
||||
mcpOverrides: draft.mcpOverrides ?? {},
|
||||
}),
|
||||
);
|
||||
if (generation !== started) return;
|
||||
@@ -1235,6 +1238,7 @@ export async function startSideConversation(task: string, text: string): Promise
|
||||
config: source.config.filter((o) => o.current != null).map((o) => ({ id: o.id, value: o.current as string })),
|
||||
isolation: "local" as const,
|
||||
base: null,
|
||||
mcpOverrides: source.mcpOverrides ?? {},
|
||||
},
|
||||
task,
|
||||
),
|
||||
@@ -1413,6 +1417,23 @@ export const sendQueuedNow = (task: string, queued: string) => call(commands.age
|
||||
export const setTaskConfig = (task: string, option: string, value: string) =>
|
||||
call(commands.agentSetConfig(task, option, value));
|
||||
|
||||
export function setDraftMcpOverrides(mcpOverrides: Record<string, boolean>) {
|
||||
updateDraft({ mcpOverrides });
|
||||
}
|
||||
|
||||
export async function setTaskMcpOverrides(task: string, overrides: Record<string, boolean>): Promise<void> {
|
||||
const prev = useAgents.getState().tasks.get(task);
|
||||
if (prev) {
|
||||
useAgents.setState((s) => ({
|
||||
tasks: new Map(s.tasks).set(task, { ...prev, mcpOverrides: overrides }),
|
||||
}));
|
||||
}
|
||||
const updated = await call(commands.agentSetMcpOverrides(task, overrides));
|
||||
useAgents.setState((s) => ({
|
||||
tasks: new Map(s.tasks).set(task, updated),
|
||||
}));
|
||||
}
|
||||
|
||||
/** The composer the user is looking at: the Agents surface on show, else the one typed in last. */
|
||||
function activeComposerKey(): string {
|
||||
const s = useAgents.getState();
|
||||
|
||||
@@ -1306,7 +1306,6 @@
|
||||
"sse (Server-Sent Events)": "sse (Server-Sent Events)",
|
||||
"One KEY=VALUE entry per line.": "One KEY=VALUE entry per line.",
|
||||
"One Header=Value entry per line.": "One Header=Value entry per line.",
|
||||
"Leave empty to enable for all agents, or list agent IDs separated by commas.": "Leave empty to enable for all agents, or list agent IDs separated by commas.",
|
||||
"External MCP Servers…": "External MCP Servers…",
|
||||
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.": "Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.",
|
||||
"No matching remote branches": "No matching remote branches",
|
||||
@@ -2033,5 +2032,78 @@
|
||||
"Create Step Definition": "Create Step Definition",
|
||||
"Create step definition '{text}'": "Create step definition '{text}'",
|
||||
"Undefined step": "Undefined step",
|
||||
"Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.": "Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition."
|
||||
"Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.": "Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.",
|
||||
"Configure MCP servers for this session": "Configure MCP servers for this session",
|
||||
"MCP servers ({active}/{total} active · {overrides} session overrides)": "MCP servers ({active}/{total} active · {overrides} session overrides)",
|
||||
"MCP servers ({active}/{total} active)": "MCP servers ({active}/{total} active)",
|
||||
"MCP servers": "MCP servers",
|
||||
"Session MCP Servers": "Session MCP Servers",
|
||||
"Filter MCP servers…": "Filter MCP servers…",
|
||||
"Filter MCP servers": "Filter MCP servers",
|
||||
"Session": "Session",
|
||||
"Built-in IDE tools": "Built-in IDE tools",
|
||||
"Enable in Settings": "Enable in Settings",
|
||||
"Enable openidea for this session": "Enable openidea for this session",
|
||||
"Agent Config": "Agent Config",
|
||||
"Active via {source}": "Active via {source}",
|
||||
"Import into Global settings to toggle per session and share across agents": "Import into Global settings to toggle per session and share across agents",
|
||||
"No matching MCP servers.": "No matching MCP servers.",
|
||||
"Changes apply on the next message.": "Changes apply on the next message.",
|
||||
"Toggles here apply to this session only.": "Toggles here apply to this session only.",
|
||||
"Overrides Global": "Overrides Global",
|
||||
"Approve…": "Approve…",
|
||||
"Enable {name} for this session": "Enable {name} for this session",
|
||||
"Shared across projects · secrets stored in Keychain": "Shared across projects · secrets stored in Keychain",
|
||||
".openidea/settings.toml · overrides Global by name": ".openidea/settings.toml · overrides Global by name",
|
||||
"Copied {name} to Global MCP servers.": "Copied {name} to Global MCP servers.",
|
||||
"Copied {name} to Project MCP servers.": "Copied {name} to Project MCP servers.",
|
||||
"Selected MCP servers are already configured in that scope.": "Selected MCP servers are already configured in that scope.",
|
||||
"Imported {count} MCP servers into Global settings.": "Imported {count} MCP servers into Global settings.",
|
||||
"Imported {count} MCP servers into Project settings.": "Imported {count} MCP servers into Project settings.",
|
||||
"Edit as JSON…": "Edit as JSON…",
|
||||
"Copy to Global": "Copy to Global",
|
||||
"Copy to Project": "Copy to Project",
|
||||
"Add Server": "Add Server",
|
||||
"Add from JSON": "Add from JSON",
|
||||
"MCP configuration levels": "MCP configuration levels",
|
||||
"All Levels": "All Levels",
|
||||
"Agent Configs": "Agent Configs",
|
||||
"Built-in IDE": "Built-in IDE",
|
||||
"All agents": "All agents",
|
||||
"Exposes OpenIDEA's code intelligence, diagnostics, refactorings, and run configurations to coding agents. Can also be toggled per session from the composer MCP menu.": "Exposes OpenIDEA's code intelligence, diagnostics, refactorings, and run configurations to coding agents. Can also be toggled per session from the composer MCP menu.",
|
||||
"IDE MCP Settings": "IDE MCP Settings",
|
||||
"Overridden by Project": "Overridden by Project",
|
||||
"Needs Approval": "Needs Approval",
|
||||
"{count} MCP tools": "{count} MCP tools",
|
||||
"Test {name}": "Test {name}",
|
||||
"Testing connection…": "Testing connection…",
|
||||
"Connection failed": "Connection failed",
|
||||
"Env vars": "Env vars",
|
||||
"Tools ({count})": "Tools ({count})",
|
||||
"Tools & Connection": "Tools & Connection",
|
||||
"Connecting and listing tools…": "Connecting and listing tools…",
|
||||
"Connected, no tools advertised by this server.": "Connected, no tools advertised by this server.",
|
||||
"Click Test Connection to run MCP handshake and inspect available tools.": "Click Test Connection to run MCP handshake and inspect available tools.",
|
||||
"Test Connection": "Test Connection",
|
||||
"Retry Connection": "Retry Connection",
|
||||
"Detected {count} MCP servers in external agent config directories ({sources}).": "Detected {count} MCP servers in external agent config directories ({sources}).",
|
||||
"Review & Import": "Review & Import",
|
||||
"Import target scope": "Import target scope",
|
||||
"Import into Global (settings.toml)": "Import into Global (settings.toml)",
|
||||
"Import into Project (.openidea/settings.toml)": "Import into Project (.openidea/settings.toml)",
|
||||
"Overwrite existing": "Overwrite existing",
|
||||
"Rescan": "Rescan",
|
||||
"Import Selected ({count})": "Import Selected ({count})",
|
||||
"Import Selected": "Import Selected",
|
||||
"No external MCP configuration files found in ~/.copilot, ~/.claude.json, ~/.codex, ~/.cursor, ~/.gemini, ~/.jetbrains/mcp, or the current project.": "No external MCP configuration files found in ~/.copilot, ~/.claude.json, ~/.codex, ~/.cursor, ~/.gemini, ~/.jetbrains/mcp, or the current project.",
|
||||
"Native to {agent}": "Native to {agent}",
|
||||
"In Global": "In Global",
|
||||
"In Project": "In Project",
|
||||
"{count} env": "{count} env",
|
||||
"{count} headers": "{count} headers",
|
||||
"Configure via structured fields or paste a standard mcpServers JSON snippet.": "Configure via structured fields or paste a standard mcpServers JSON snippet.",
|
||||
"Editor mode": "Editor mode",
|
||||
"JSON:": "JSON:",
|
||||
"Accepts mcpServers, servers, or a single server JSON object.": "Accepts mcpServers, servers, or a single server JSON object.",
|
||||
"Leave empty to enable for all agents, or pick specific coding agents.": "Leave empty to enable for all agents, or pick specific coding agents."
|
||||
}
|
||||
|
||||
@@ -1548,7 +1548,7 @@
|
||||
"Implement Members": "实现成员",
|
||||
"Implementation(s)": "实现",
|
||||
"Imports": "导入",
|
||||
"In Project": "在项目",
|
||||
"In Project": "已在项目",
|
||||
"Include": "包括",
|
||||
"Include non-project items": "包括非项目项",
|
||||
"Include untracked files": "包括未跟踪的文件",
|
||||
@@ -7700,7 +7700,6 @@
|
||||
"sse (Server-Sent Events)": "sse(服务器发送事件)",
|
||||
"One KEY=VALUE entry per line.": "每行一个 KEY=VALUE 条目。",
|
||||
"One Header=Value entry per line.": "每行一个 Header=Value 条目。",
|
||||
"Leave empty to enable for all agents, or list agent IDs separated by commas.": "留空则为所有代理启用,或用逗号分隔列出代理 ID。",
|
||||
"Maven project could not be configured": "无法配置 Maven 项目",
|
||||
"External MCP Servers…": "外部 MCP 服务器…",
|
||||
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.": "打开“设置 › 智能体 › 外部 MCP 服务器”:配置编程智能体使用的用户级和工作区级 MCP 服务器。",
|
||||
@@ -8420,5 +8419,75 @@
|
||||
"Create Step Definition": "创建步骤定义",
|
||||
"Create step definition '{text}'": "创建步骤定义“{text}”",
|
||||
"Undefined step": "未定义的步骤",
|
||||
"Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.": "报告 .feature 文件中项目里没有任何步骤定义匹配的步骤(按 JavaScript、TypeScript、Java 和 Kotlin 文件中的 Cucumber 表达式和正则表达式匹配)。这些文件里没有步骤定义的项目不做检查。按 Alt+Enter 可创建定义。"
|
||||
"Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.": "报告 .feature 文件中项目里没有任何步骤定义匹配的步骤(按 JavaScript、TypeScript、Java 和 Kotlin 文件中的 Cucumber 表达式和正则表达式匹配)。这些文件里没有步骤定义的项目不做检查。按 Alt+Enter 可创建定义。",
|
||||
"Configure MCP servers for this session": "配置当前会话的 MCP 服务器",
|
||||
"MCP servers ({active}/{total} active · {overrides} session overrides)": "MCP 服务器(已启用 {active}/{total} · {overrides} 项会话覆盖)",
|
||||
"MCP servers ({active}/{total} active)": "MCP 服务器(已启用 {active}/{total})",
|
||||
"MCP servers": "MCP 服务器",
|
||||
"Session MCP Servers": "会话 MCP 服务器",
|
||||
"Filter MCP servers…": "筛选 MCP 服务器…",
|
||||
"Filter MCP servers": "筛选 MCP 服务器",
|
||||
"Session": "会话",
|
||||
"Built-in IDE tools": "内置 IDE 工具",
|
||||
"Enable in Settings": "在设置中启用",
|
||||
"Enable openidea for this session": "在当前会话启用 openidea",
|
||||
"Agent Config": "智能体配置",
|
||||
"Active via {source}": "通过 {source} 生效",
|
||||
"Import into Global settings to toggle per session and share across agents": "导入到全局设置以支持按会话开关并在所有智能体间共享",
|
||||
"No matching MCP servers.": "没有匹配的 MCP 服务器。",
|
||||
"Changes apply on the next message.": "更改将在下一条消息生效。",
|
||||
"Toggles here apply to this session only.": "此处的开关仅对当前会话生效。",
|
||||
"Overrides Global": "覆盖全局配置",
|
||||
"Approve…": "批准…",
|
||||
"Enable {name} for this session": "在当前会话启用 {name}",
|
||||
"Shared across projects · secrets stored in Keychain": "跨项目共享 · 密钥保存在系统钥匙串中",
|
||||
".openidea/settings.toml · overrides Global by name": ".openidea/settings.toml · 同名项覆盖全局配置",
|
||||
"Copied {name} to Global MCP servers.": "已将 {name} 复制到全局 MCP 服务器。",
|
||||
"Copied {name} to Project MCP servers.": "已将 {name} 复制到项目 MCP 服务器。",
|
||||
"Selected MCP servers are already configured in that scope.": "所选 MCP 服务器已在该作用域中配置。",
|
||||
"Imported {count} MCP servers into Global settings.": "已将 {count} 个 MCP 服务器导入到全局设置。",
|
||||
"Imported {count} MCP servers into Project settings.": "已将 {count} 个 MCP 服务器导入到项目设置。",
|
||||
"Edit as JSON…": "以 JSON 编辑…",
|
||||
"Copy to Global": "复制到全局",
|
||||
"Add Server": "添加服务器",
|
||||
"Add from JSON": "从 JSON 添加",
|
||||
"MCP configuration levels": "MCP 配置层级",
|
||||
"All Levels": "全部层级",
|
||||
"Agent Configs": "智能体配置",
|
||||
"Built-in IDE": "内置 IDE",
|
||||
"All agents": "所有智能体",
|
||||
"Exposes OpenIDEA's code intelligence, diagnostics, refactorings, and run configurations to coding agents. Can also be toggled per session from the composer MCP menu.": "向编码智能体提供 OpenIDEA 的代码智能、诊断、重构和运行配置能力。也可在输入框的 MCP 菜单中按会话单独开关。",
|
||||
"IDE MCP Settings": "IDE MCP 设置",
|
||||
"Overridden by Project": "已被项目覆盖",
|
||||
"Needs Approval": "需批准",
|
||||
"{count} MCP tools": "{count} 个 MCP 工具",
|
||||
"Test {name}": "测试 {name}",
|
||||
"Testing connection…": "正在测试连接…",
|
||||
"Connection failed": "连接失败",
|
||||
"Env vars": "环境变量",
|
||||
"Tools ({count})": "工具({count})",
|
||||
"Tools & Connection": "工具与连接",
|
||||
"Connecting and listing tools…": "正在连接并获取工具列表…",
|
||||
"Connected, no tools advertised by this server.": "已连接,该服务器未声明任何工具。",
|
||||
"Click Test Connection to run MCP handshake and inspect available tools.": "点击“测试连接”以执行 MCP 握手并查看可用工具。",
|
||||
"Retry Connection": "重试连接",
|
||||
"Detected {count} MCP servers in external agent config directories ({sources}).": "在外部智能体配置目录({sources})中检测到 {count} 个 MCP 服务器。",
|
||||
"Review & Import": "查看并导入",
|
||||
"Import target scope": "导入目标作用域",
|
||||
"Import into Global (settings.toml)": "导入到全局(settings.toml)",
|
||||
"Import into Project (.openidea/settings.toml)": "导入到项目(.openidea/settings.toml)",
|
||||
"Overwrite existing": "覆盖已有同名项",
|
||||
"Rescan": "重新扫描",
|
||||
"Import Selected ({count})": "导入所选({count})",
|
||||
"Import Selected": "导入所选",
|
||||
"No external MCP configuration files found in ~/.copilot, ~/.claude.json, ~/.codex, ~/.cursor, ~/.gemini, ~/.jetbrains/mcp, or the current project.": "在 ~/.copilot、~/.claude.json、~/.codex、~/.cursor、~/.gemini、~/.jetbrains/mcp 或当前项目中未发现外部 MCP 配置文件。",
|
||||
"Native to {agent}": "原生归属 {agent}",
|
||||
"In Global": "已在全局",
|
||||
"{count} env": "{count} 项环境变量",
|
||||
"{count} headers": "{count} 项请求头",
|
||||
"Configure via structured fields or paste a standard mcpServers JSON snippet.": "可通过表单字段配置,也可直接粘贴标准 mcpServers JSON 片段。",
|
||||
"Editor mode": "编辑模式",
|
||||
"JSON:": "JSON:",
|
||||
"Accepts mcpServers, servers, or a single server JSON object.": "支持 mcpServers、servers 或单个服务器 JSON 对象。",
|
||||
"Leave empty to enable for all agents, or pick specific coding agents.": "留空则对所有智能体启用,也可选择特定的编码智能体。"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user