fix(agents): ask for approval before a plugin's language servers can run

An agent plugin's language server definitions (.lsp.json, lsp.json or the manifest's lspServers) start commands as the user once the plugin is enabled, but the install and enable approvals covered only stdio MCP servers and lifecycle hooks: a plugin with only a language server was enabled without an approval and its command was not listed. Language server commands are now part of a plugin's executable capabilities and their hash, listed in the install preview and the approval dialog. A plugin without language servers keeps its hash, so earlier approvals stay valid; an installed plugin with one asks for approval once.
Цей коміт міститься в:
l0ng-ai committed 2026-12-06 09:48:16 +08:00
1 джерело c2f984720d
коміт cc1a5cccb3
9 files changed
+188 -19

No files matched your search

+4 -1
Переглянути файл
@@ -1574,6 +1574,9 @@ pub struct AgentPluginCapabilities {
pub hook_files: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub stdio_commands: Vec<String>,
/// Language server commands (`.lsp.json`, `lsp.json`, a manifest's `lspServers`) the agent starts.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub lsp_commands: Vec<String>,
#[serde(default)]
pub has_lsp: bool,
#[serde(default)]
@@ -1581,7 +1584,7 @@ pub struct AgentPluginCapabilities {
/// Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub native_harnesses: Vec<String>,
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents).
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands`, `lsp_commands` and `hook_files` contents).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub capability_hash: Option<String>,
+145 -4
Переглянути файл
@@ -2203,13 +2203,15 @@ fn inspect_fetched_subtree(
}
skill_names.sort();
skill_names.dedup();
let ExecutableCapabilities { mcp_names, stdio_commands, hook_files, capability_hash, .. } = executable;
let ExecutableCapabilities { mcp_names, stdio_commands, lsp_commands, hook_files, capability_hash, .. } =
executable;
if formats.is_empty()
&& skill_names.is_empty()
&& mcp_names.is_empty()
&& rule_count == 0
&& hook_files.is_empty()
&& lsp_commands.is_empty()
&& subagent_count == 0
&& command_count == 0
{
@@ -2241,6 +2243,7 @@ fn inspect_fetched_subtree(
command_count,
hook_files,
stdio_commands,
lsp_commands,
has_lsp,
has_canvas_or_app,
native_harnesses: native_harnesses.into_iter().collect(),
@@ -2337,6 +2340,7 @@ impl PluginFiles for DiskPluginFiles<'_> {
struct ExecutableCapabilities {
mcp_names: BTreeSet<String>,
stdio_commands: Vec<String>,
lsp_commands: Vec<String>,
hook_files: Vec<String>,
hook_harnesses: BTreeSet<String>,
capability_hash: Option<String>,
@@ -2345,6 +2349,7 @@ struct ExecutableCapabilities {
fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabilities {
let mut mcp_names = BTreeSet::new();
let mut stdio_commands = BTreeSet::new();
let mut lsp_commands = BTreeSet::new();
let mut hook_files = BTreeSet::new();
let mut hook_harnesses = BTreeSet::new();
let mut hook_contents: BTreeMap<String, Vec<u8>> = BTreeMap::new();
@@ -2369,6 +2374,9 @@ fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabil
if let Some(mcp) = manifest.get("mcpServers") {
collect_in_memory_mcp_summary(mcp, files, &mut mcp_names, &mut stdio_commands);
}
if let Some(lsp) = manifest.get("lspServers") {
collect_lsp_commands(lsp, files, &mut lsp_commands, &mut HashSet::new());
}
let (paths, objects) = manifest_hook_declarations(rel, &manifest);
for path in paths {
add_hook_file(path, &mut hook_contents);
@@ -2382,6 +2390,13 @@ fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabil
collect_in_memory_mcp_summary(&value, files, &mut mcp_names, &mut stdio_commands);
}
}
for rel in [".lsp.json", "lsp.json"] {
if let Some(bytes) = files.read(rel)
&& let Ok(value) = parse_jsonc(&String::from_utf8_lossy(&bytes))
{
collect_lsp_commands(&value, files, &mut lsp_commands, &mut HashSet::new());
}
}
for (label, bytes) in inline_hooks {
hook_files.insert(label.clone());
hook_contents.insert(label, bytes);
@@ -2400,12 +2415,14 @@ fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabil
}
}
let stdio_commands: Vec<String> = stdio_commands.into_iter().collect();
let lsp_commands: Vec<String> = lsp_commands.into_iter().collect();
let digests: Vec<(&str, &[u8])> =
hook_contents.iter().map(|(rel, bytes)| (rel.as_str(), bytes.as_slice())).collect();
let capability_hash = compute_capability_hash(&stdio_commands, &digests);
let capability_hash = compute_capability_hash(&stdio_commands, &lsp_commands, &digests);
ExecutableCapabilities {
mcp_names,
stdio_commands,
lsp_commands,
hook_files: hook_files.into_iter().collect(),
hook_harnesses,
capability_hash,
@@ -2478,6 +2495,59 @@ fn collect_in_memory_mcp_summary_inner(
}
}
/// `name: command args env:K=V` for each language server a `.lsp.json` file, a manifest's
/// `lspServers` value (an object, a path to such a file, or a list of either) declares.
fn collect_lsp_commands(
val: &Value,
files: &dyn PluginFiles,
out: &mut BTreeSet<String>,
visited_files: &mut HashSet<String>,
) {
match val {
Value::String(rel) => {
let clean = rel.trim().trim_start_matches("./").trim_start_matches('/');
if visited_files.insert(clean.to_owned())
&& let Some(bytes) = files.read(clean)
&& let Ok(parsed) = parse_jsonc(&String::from_utf8_lossy(&bytes))
{
collect_lsp_commands(&parsed, files, out, visited_files);
}
}
Value::Array(items) => {
for item in items {
collect_lsp_commands(item, files, out, visited_files);
}
}
Value::Object(obj) => {
if let Some(nested) = obj.get("lspServers") {
collect_lsp_commands(nested, files, out, visited_files);
return;
}
for (name, entry) in obj {
let Some(cmd) = entry.get("command").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
else {
continue;
};
let mut parts = vec![cmd.to_owned()];
parts.extend(extract_string_array(entry.get("args")));
let env = entry
.get("env")
.and_then(Value::as_object)
.into_iter()
.flatten()
.map(|(key, value)| format!("{}={}", key, scalar_capability_value(value)))
.collect::<Vec<_>>()
.join(" ");
if !env.is_empty() {
parts.push(format!("env:{env}"));
}
out.insert(format!("{name}: {}", parts.join(" ")));
}
}
_ => {}
}
}
fn scalar_capability_value(value: &Value) -> String {
match value {
Value::String(value) => value.clone(),
@@ -2746,6 +2816,7 @@ pub fn inspect_plugin_dir(
&& mcp_names.is_empty()
&& rule_files.is_empty()
&& hook_rel_names.is_empty()
&& executable.lsp_commands.is_empty()
&& subagent_count == 0
&& command_count == 0)
{
@@ -2803,6 +2874,7 @@ pub fn inspect_plugin_dir(
command_count,
hook_files: hook_rel_names,
stdio_commands: executable.stdio_commands,
lsp_commands: executable.lsp_commands,
has_lsp,
has_canvas_or_app,
native_harnesses: native_harnesses.into_iter().collect(),
@@ -2815,8 +2887,12 @@ pub fn inspect_plugin_dir(
})
}
fn compute_capability_hash(stdio_commands: &[String], hooks: &[(&str, &[u8])]) -> Option<String> {
if stdio_commands.is_empty() && hooks.is_empty() {
fn compute_capability_hash(
stdio_commands: &[String],
lsp_commands: &[String],
hooks: &[(&str, &[u8])],
) -> Option<String> {
if stdio_commands.is_empty() && lsp_commands.is_empty() && hooks.is_empty() {
return None;
}
let mut hasher = blake3::Hasher::new();
@@ -2828,6 +2904,14 @@ fn compute_capability_hash(stdio_commands: &[String], hooks: &[(&str, &[u8])]) -
hasher.update(cmd.as_bytes());
hasher.update(b"\0");
}
// Only added when present, so the hash of a plugin without language servers stays as approved before.
let mut sorted_lsp = lsp_commands.to_vec();
sorted_lsp.sort();
for cmd in sorted_lsp {
hasher.update(b"lsp:");
hasher.update(cmd.as_bytes());
hasher.update(b"\0");
}
for (rel, bytes) in hooks {
hasher.update(b"hook:");
hasher.update(rel.as_bytes());
@@ -5682,6 +5766,63 @@ mod tests {
assert!(codex_text.contains("https://github.com/acme/plugins.git"));
}
#[test]
fn language_servers_a_plugin_ships_need_execution_consent() {
let tmp = tempfile::tempdir().unwrap();
// A `.lsp.json` file, an inline `lspServers` object and a path to one in the manifest.
let file = tmp.path().join("lsp-file");
write(&file.join(".claude-plugin/plugin.json"), r#"{"name":"lsp-file","version":"1.0.0"}"#);
write(&file.join(".lsp.json"), r#"{"go":{"command":"/bin/sh","args":["-c","touch /tmp/x"]}}"#);
let inline = tmp.path().join("lsp-inline");
write(
&inline.join(".claude-plugin/plugin.json"),
r#"{"name":"lsp-inline","lspServers":{"py":{"command":"pyright-langserver","args":["--stdio"],"env":{"A":"1"}}}}"#,
);
let linked = tmp.path().join("lsp-linked");
write(&linked.join(".claude-plugin/plugin.json"), r#"{"name":"lsp-linked","lspServers":"./servers.json"}"#);
write(&linked.join("servers.json"), r#"{"rs":{"command":"rust-analyzer"}}"#);
let cases = [
(&file, "go: /bin/sh -c touch /tmp/x"),
(&inline, "py: pyright-langserver --stdio env:A=1"),
(&linked, "rs: rust-analyzer"),
];
for (dir, command) in cases {
let installed = inspect_plugin_dir(dir, AgentPluginSource::ClaudeUser, McpScope::User, None, true)
.unwrap()
.capabilities;
let scanned = scan_local_subtree(dir, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin").unwrap();
let preview = inspect_fetched_subtree(&scanned, "plugin", None).unwrap().capabilities;
for caps in [&installed, &preview] {
assert_eq!(caps.lsp_commands, vec![command.to_owned()], "{}", dir.display());
assert!(caps.requires_consent, "{}", dir.display());
assert!(caps.capability_hash.is_some());
}
// The install dialog's approval matches the hash of the installed folder.
assert_eq!(installed.capability_hash, preview.capability_hash);
}
// Changing the server command invalidates an earlier approval.
let before = inspect_plugin_dir(&file, AgentPluginSource::ClaudeUser, McpScope::User, None, true).unwrap();
write(&file.join(".lsp.json"), r#"{"go":{"command":"gopls"}}"#);
let after = inspect_plugin_dir(&file, AgentPluginSource::ClaudeUser, McpScope::User, None, true).unwrap();
assert_ne!(before.capabilities.capability_hash, after.capabilities.capability_hash);
// A plugin without language servers keeps its hash: approvals given before stay valid.
let mut v1 = blake3::Hasher::new();
v1.update(b"openidea-agent-plugin-caps-v1\0mcp:k8s: npx -y k8s-mcp\0");
assert_eq!(
compute_capability_hash(&["k8s: npx -y k8s-mcp".to_owned()], &[], &[]),
Some(v1.finalize().to_hex().to_string())
);
let skills_only = tmp.path().join("skills-only");
write(&skills_only.join(".claude-plugin/plugin.json"), r#"{"name":"skills-only"}"#);
write(&skills_only.join("skills/a/SKILL.md"), "---\nname: a\ndescription: A\n---\n");
let caps = inspect_plugin_dir(&skills_only, AgentPluginSource::ClaudeUser, McpScope::User, None, true)
.unwrap()
.capabilities;
assert!(caps.lsp_commands.is_empty() && !caps.requires_consent && caps.capability_hash.is_none());
}
#[test]
fn marketplace_browse_preview_and_pinned_native_install_roundtrip() {
let tmp = tempfile::tempdir().unwrap();
+6 -2
Переглянути файл
@@ -4244,11 +4244,13 @@ export type AgentPluginCapabilities_Deserialize = {
commandCount: number,
hookFiles?: string[],
stdioCommands?: string[],
/** Language server commands (`.lsp.json`, `lsp.json`, a manifest's `lspServers`) the agent starts. */
lspCommands?: string[],
hasLsp?: boolean,
hasCanvasOrApp?: boolean,
/** Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle. */
nativeHarnesses?: string[],
/** Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents). */
/** Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands`, `lsp_commands` and `hook_files` contents). */
capabilityHash?: string | null,
requiresConsent?: boolean,
};
@@ -4264,11 +4266,13 @@ export type AgentPluginCapabilities_Serialize = {
commandCount: number,
hookFiles?: string[],
stdioCommands?: string[],
/** Language server commands (`.lsp.json`, `lsp.json`, a manifest's `lspServers`) the agent starts. */
lspCommands?: string[],
hasLsp: boolean,
hasCanvasOrApp: boolean,
/** Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle. */
nativeHarnesses?: string[],
/** Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents). */
/** Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands`, `lsp_commands` and `hook_files` contents). */
capabilityHash?: string | null,
requiresConsent: boolean,
};
+6 -1
Переглянути файл
@@ -101,6 +101,7 @@ const SAMPLE_CATALOG: AgentPluginCatalog = {
commandCount: 0,
hookFiles: ["hooks/hooks.json"],
stdioCommands: ["azure: npx -y @azure/mcp server start"],
lspCommands: ["go: gopls serve"],
capabilityHash: "abc123",
requiresConsent: true,
},
@@ -297,6 +298,8 @@ describe("AgentPluginsPage", () => {
fireEvent.click(await screen.findByRole("button", { name: "Review & Enable…" }));
const dialog = await screen.findByRole("dialog", { name: /Approve Plugin Capabilities/ });
expect(within(dialog).getByText("azure: npx -y @azure/mcp server start")).toBeInTheDocument();
expect(within(dialog).getByText("Language Server Process")).toBeInTheDocument();
expect(within(dialog).getByText("go: gopls serve")).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: "Trust & Enable Plugin" }));
await waitFor(() =>
@@ -347,7 +350,9 @@ describe("AgentPluginsPage", () => {
const install = within(installDlg).getByRole("button", { name: "Trust & Install Plugin" });
expect(install).toBeDisabled();
fireEvent.click(within(installDlg).getByLabelText("Approve bundled MCP server and lifecycle hook execution"));
fireEvent.click(
within(installDlg).getByLabelText("Approve bundled MCP server, language server and lifecycle hook execution"),
);
fireEvent.click(within(installDlg).getByLabelText("Confirm static security scan warnings"));
expect(install).toBeDisabled();
fireEvent.click(within(installDlg).getByLabelText("Replace the existing plugin directory"));
+18 -3
Переглянути файл
@@ -1022,8 +1022,8 @@ function CapabilityConsentDialog({
<div className={styles.dialogBody}>
<span className={styles.hint}>
<T>
This agent plugin declares local MCP processes or lifecycle hooks that execute commands when active. Review
its capabilities before enabling:
This agent plugin declares local MCP processes, language servers or lifecycle hooks that execute commands
when active. Review its capabilities before enabling:
</T>
</span>
@@ -1038,6 +1038,16 @@ function CapabilityConsentDialog({
<div className={styles.codeLine}>{cmd}</div>
</div>
))}
{(cap.lspCommands ?? []).map((cmd) => (
<div key={`lsp:${cmd}`}>
<div>
<strong>
<T>Language Server Process</T>
</strong>
</div>
<div className={styles.codeLine}>{cmd}</div>
</div>
))}
{(cap.hookFiles ?? []).map((hf) => (
<div key={hf}>
<div>
@@ -1564,6 +1574,11 @@ function InstallPluginDialog({
MCP: {cmd}
</div>
))}
{(preview.capabilities.lspCommands ?? []).map((cmd) => (
<div key={`lsp:${cmd}`} className={styles.codeLine}>
LSP: {cmd}
</div>
))}
{(preview.capabilities.hookFiles ?? []).map((hf) => (
<div key={hf} className={styles.codeLine}>
Hook: {hf}
@@ -1580,7 +1595,7 @@ function InstallPluginDialog({
<Checkbox
checked={approveCaps}
onChange={setApproveCaps}
label={tx("Approve bundled MCP server and lifecycle hook execution")}
label={tx("Approve bundled MCP server, language server and lifecycle hook execution")}
/>
)}
{hasScanWarnings && (
+3 -2
Переглянути файл
@@ -5259,7 +5259,8 @@
"Open Manifest": "Open Manifest",
"Approve Plugin Capabilities — {name}": "Approve Plugin Capabilities — {name}",
"Trust & Enable Plugin": "Trust & Enable Plugin",
"This agent plugin declares local MCP processes or lifecycle hooks that execute commands when active. Review its capabilities before enabling:": "This agent plugin declares local MCP processes or lifecycle hooks that execute commands when active. Review its capabilities before enabling:",
"This agent plugin declares local MCP processes, language servers or lifecycle hooks that execute commands when active. Review its capabilities before enabling:": "This agent plugin declares local MCP processes, language servers or lifecycle hooks that execute commands when active. Review its capabilities before enabling:",
"Language Server Process": "Language Server Process",
"Stdio MCP Process": "Stdio MCP Process",
"Lifecycle Hook File": "Lifecycle Hook File",
"Plugin Marketplaces": "Plugin Marketplaces",
@@ -5274,7 +5275,7 @@
"Preview…": "Preview…",
"Install scope": "Install scope",
"{skills} skills · {mcp} MCP servers · {rules} rules · {files} files": "{skills} skills · {mcp} MCP servers · {rules} rules · {files} files",
"Approve bundled MCP server and lifecycle hook execution": "Approve bundled MCP server and lifecycle hook execution",
"Approve bundled MCP server, language server and lifecycle hook execution": "Approve bundled MCP server, language server and lifecycle hook execution",
"Confirm static security scan warnings": "Confirm static security scan warnings",
"from plugin {id}": "from plugin {id}",
"unsupported manifest": "unsupported manifest",
-2
Переглянути файл
@@ -10275,7 +10275,6 @@
"Open Manifest": "Открыть манифест",
"Approve Plugin Capabilities — {name}": "Подтверждение возможностей плагина — {name}",
"Trust & Enable Plugin": "Доверять и включить плагин",
"This agent plugin declares local MCP processes or lifecycle hooks that execute commands when active. Review its capabilities before enabling:": "Этот плагин агента объявляет локальные процессы MCP или хуки жизненного цикла, которые выполняют команды, когда плагин активен. Проверьте его возможности перед включением:",
"Stdio MCP Process": "Процесс MCP (stdio)",
"Lifecycle Hook File": "Файл хуков жизненного цикла",
"Plugin Marketplaces": "Маркетплейсы плагинов",
@@ -10289,7 +10288,6 @@
"Preview…": "Предпросмотр…",
"Install scope": "Область установки",
"{skills} skills · {mcp} MCP servers · {rules} rules · {files} files": "Навыков: {skills} · серверов MCP: {mcp} · правил: {rules} · файлов: {files}",
"Approve bundled MCP server and lifecycle hook execution": "Разрешить запуск встроенных серверов MCP и хуков жизненного цикла",
"Confirm static security scan warnings": "Подтвердить предупреждения статической проверки безопасности",
"from plugin {id}": "из плагина {id}",
"unsupported manifest": "неподдерживаемый манифест",
+3 -2
Переглянути файл
@@ -9641,7 +9641,8 @@
"Open Manifest": "開啟清單",
"Approve Plugin Capabilities — {name}": "確認外掛執行權限 — {name}",
"Trust & Enable Plugin": "信任並啟用外掛",
"This agent plugin declares local MCP processes or lifecycle hooks that execute commands when active. Review its capabilities before enabling:": "此代理外掛宣告了本機 MCP 程序或生命週期鉤子,啟用後會執行命令。啟用前請檢查以下權限:",
"This agent plugin declares local MCP processes, language servers or lifecycle hooks that execute commands when active. Review its capabilities before enabling:": "此代理外掛宣告了本機 MCP 程序、語言伺服器或生命週期鉤子,啟用後會執行命令。啟用前請檢查以下權限:",
"Language Server Process": "語言伺服器程序",
"Stdio MCP Process": "本機 Stdio MCP 程序",
"Lifecycle Hook File": "生命週期鉤子檔案",
"Plugin Marketplaces": "外掛市場",
@@ -9655,7 +9656,7 @@
"Preview…": "預覽…",
"Install scope": "安裝位置",
"{skills} skills · {mcp} MCP servers · {rules} rules · {files} files": "{skills} 項技能 · {mcp} 個 MCP 伺服器 · {rules} 條規則 · {files} 個檔案",
"Approve bundled MCP server and lifecycle hook execution": "確認允許執行內建的 MCP 伺服器與生命週期鉤子",
"Approve bundled MCP server, language server and lifecycle hook execution": "確認允許執行內建的 MCP 伺服器、語言伺服器與生命週期鉤子",
"Confirm static security scan warnings": "已閱讀並確認靜態安全掃描警告",
"from plugin {id}": "來自外掛 {id}",
"unsupported manifest": "不支援的清單格式",
+3 -2
Переглянути файл
@@ -12123,7 +12123,8 @@
"Open Manifest": "打开清单",
"Approve Plugin Capabilities — {name}": "确认插件执行权限 — {name}",
"Trust & Enable Plugin": "信任并启用插件",
"This agent plugin declares local MCP processes or lifecycle hooks that execute commands when active. Review its capabilities before enabling:": "此智能体插件声明了本地 MCP 进程或生命周期钩子,启用后会执行命令。启用前请检查以下权限:",
"This agent plugin declares local MCP processes, language servers or lifecycle hooks that execute commands when active. Review its capabilities before enabling:": "此智能体插件声明了本地 MCP 进程、语言服务器或生命周期钩子,启用后会执行命令。启用前请检查以下权限:",
"Language Server Process": "语言服务器进程",
"Stdio MCP Process": "本地 Stdio MCP 进程",
"Lifecycle Hook File": "生命周期钩子文件",
"Plugin Marketplaces": "插件市场",
@@ -12137,7 +12138,7 @@
"Preview…": "预览…",
"Install scope": "安装位置",
"{skills} skills · {mcp} MCP servers · {rules} rules · {files} files": "{skills} 项技能 · {mcp} 个 MCP 服务器 · {rules} 条规则 · {files} 个文件",
"Approve bundled MCP server and lifecycle hook execution": "确认允许执行内置的 MCP 服务器与生命周期钩子",
"Approve bundled MCP server, language server and lifecycle hook execution": "确认允许执行内置的 MCP 服务器、语言服务器与生命周期钩子",
"Confirm static security scan warnings": "已阅读并确认静态安全扫描警告",
"from plugin {id}": "来自插件 {id}",
"unsupported manifest": "不支持的清单格式",