use std::collections::BTreeSet;
use std::path::Path;
use crate::lsp::install::Provision;
use crate::lsp::manifest::{self, CommandDecl, McpServerDecl};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContributedCommand {
pub ext_id: String,
pub id: String,
pub title: String,
}
#[derive(Debug, Clone)]
pub struct ServerSpawn {
pub id: String,
pub command: String,
pub args: Vec<String>,
pub env: std::collections::BTreeMap<String, String>,
pub provision: Option<Provision>,
}
#[derive(Debug, Clone)]
pub struct ResolvedCommand {
pub ext_id: String,
pub command_id: String,
pub title: String,
pub tool: String,
pub arg: Option<String>,
pub prompt: Option<String>,
pub server: ServerSpawn,
}
fn server_spawn(decl: &McpServerDecl) -> ServerSpawn {
ServerSpawn {
id: decl.id.clone(),
command: decl.command.clone(),
args: decl.args.clone(),
env: decl.env.clone(),
provision: decl.provision.as_ref().map(|p| p.to_provision()),
}
}
fn all_sources_in_dir(config_dir: &Path) -> Vec<String> {
let mut sources: Vec<String> = manifest::BUNDLED_MANIFESTS
.iter()
.map(|s| s.to_string())
.collect();
if cfg!(test) && config_dir == crate::paths::config_dir() {
return sources;
}
sources.extend(manifest::read_extension_sources(
&config_dir.join("extensions"),
));
sources
}
fn contributed_in(sources: &[String], disabled: &BTreeSet<String>) -> Vec<ContributedCommand> {
sources
.iter()
.filter_map(|s| manifest::parse(s).ok())
.filter(|m| !disabled.contains(&m.id))
.flat_map(|m| {
let ext_id = m.id;
m.commands.into_iter().map(move |c| ContributedCommand {
ext_id: ext_id.clone(),
id: c.id,
title: c.title,
})
})
.collect()
}
fn resolve_in(
sources: &[String],
disabled: &BTreeSet<String>,
command_id: &str,
) -> Option<ResolvedCommand> {
for src in sources {
let Ok(m) = manifest::parse(src) else {
continue;
};
if disabled.contains(&m.id) {
continue;
}
let Some(cmd) = m.commands.iter().find(|c| c.id == command_id) else {
continue;
};
let server = m.mcp_servers.iter().find(|s| s.id == cmd.server)?;
return Some(resolved(&m.id, cmd, server));
}
None
}
fn resolved(ext_id: &str, cmd: &CommandDecl, server: &McpServerDecl) -> ResolvedCommand {
ResolvedCommand {
ext_id: ext_id.to_string(),
command_id: cmd.id.clone(),
title: cmd.title.clone(),
tool: cmd.tool.clone(),
arg: cmd.arg.clone(),
prompt: cmd.prompt.clone(),
server: server_spawn(server),
}
}
#[derive(Clone)]
pub struct ContributedViewer {
pub ext_id: String,
pub id: String,
pub label: String,
pub command: String,
pub args: Vec<String>,
pub extensions: Vec<String>,
pub provision: Option<crate::lsp::install::Provision>,
}
impl ContributedViewer {
pub fn key(&self) -> String {
format!("{}/{}", self.ext_id, self.id)
}
pub fn install_name(&self) -> String {
self.key()
}
}
pub const VIEWER_COMMAND_PREFIX: &str = "viewer:";
fn viewers_in(sources: &[String], disabled: &BTreeSet<String>) -> Vec<ContributedViewer> {
sources
.iter()
.filter_map(|s| manifest::parse(s).ok())
.filter(|m| !disabled.contains(&m.id))
.flat_map(|m| {
let ext_id = m.id;
m.viewers.into_iter().map(move |v| ContributedViewer {
ext_id: ext_id.clone(),
id: v.id,
label: v.label,
command: v.command,
args: {
let mut args = v.args;
if !args.iter().any(|a| a.contains("{file}")) {
args.push(String::from("{file}"));
}
args
},
extensions: v.extensions.iter().map(|e| e.to_lowercase()).collect(),
provision: v.provision.as_ref().map(|p| p.to_provision()),
})
})
.collect()
}
fn viewer_for_path_in(
sources: &[String],
disabled: &BTreeSet<String>,
path: &std::path::Path,
) -> Option<ContributedViewer> {
let ext = path.extension()?.to_string_lossy().to_lowercase();
viewers_in(sources, disabled)
.into_iter()
.find(|v| v.extensions.contains(&ext))
}
fn viewer_commands_in(sources: &[String], disabled: &BTreeSet<String>) -> Vec<ContributedCommand> {
viewers_in(sources, disabled)
.into_iter()
.map(|v| ContributedCommand {
title: format!("{}: {}", v.ext_id, v.label),
id: format!("{VIEWER_COMMAND_PREFIX}{}", v.key()),
ext_id: v.ext_id,
})
.collect()
}
pub fn viewer_for_path_in_dir(
config_dir: &Path,
disabled: &BTreeSet<String>,
path: &Path,
) -> Option<ContributedViewer> {
viewer_for_path_in(&all_sources_in_dir(config_dir), disabled, path)
}
fn viewer_by_key_in(
sources: &[String],
disabled: &BTreeSet<String>,
key: &str,
) -> Option<ContributedViewer> {
viewers_in(sources, disabled)
.into_iter()
.find(|v| v.key() == key)
}
pub fn viewer_by_id_in_dir(
config_dir: &Path,
disabled: &BTreeSet<String>,
key: &str,
) -> Option<ContributedViewer> {
viewer_by_key_in(&all_sources_in_dir(config_dir), disabled, key)
}
pub fn contributed_viewer_commands_in_dir(
config_dir: &Path,
disabled: &BTreeSet<String>,
) -> Vec<ContributedCommand> {
viewer_commands_in(&all_sources_in_dir(config_dir), disabled)
}
pub fn contributed_commands_in_dir(
config_dir: &Path,
disabled: &BTreeSet<String>,
) -> Vec<ContributedCommand> {
contributed_in(&all_sources_in_dir(config_dir), disabled)
}
pub fn command_ids_of_in_dir(config_dir: &Path, ext_id: &str) -> Vec<String> {
contributed_in(&all_sources_in_dir(config_dir), &BTreeSet::new())
.into_iter()
.filter(|c| c.ext_id == ext_id)
.map(|c| c.id)
.collect()
}
pub fn resolve_command_in_dir(
config_dir: &Path,
disabled: &BTreeSet<String>,
command_id: &str,
) -> Option<ResolvedCommand> {
resolve_in(&all_sources_in_dir(config_dir), disabled, command_id)
}
#[cfg(test)]
mod tests {
use super::*;
const CSVLENS: &str = r#"id = "csvlens"
name = "csvlens"
description = "Browse CSV and TSV files in csvlens, a terminal spreadsheet viewer."
builtin = false
api_version = 1
[[viewers]]
id = "csvlens"
label = "Open in csvlens"
command = "csvlens"
args = ["{file}"]
extensions = ["csv", "tsv"]
provision = { kind = "binary", bin = "csvlens", archive = "tar.xz", targets = { "macos-aarch64" = "https://example.invalid/csvlens-aarch64-apple-darwin.tar.xz" } }
"#;
#[test]
fn viewers_from_two_extensions_with_the_same_id_stay_distinct() {
let alpha = CSVLENS.replace("id = \"csvlens\"\nname", "id = \"alpha\"\nname");
let beta = CSVLENS
.replace("id = \"csvlens\"\nname", "id = \"beta\"\nname")
.replace("command = \"csvlens\"", "command = \"beta-bin\"")
.replace("bin = \"csvlens\"", "bin = \"beta-bin\"");
let sources = vec![alpha, beta];
let none = BTreeSet::new();
let ids: Vec<String> = viewer_commands_in(&sources, &none)
.into_iter()
.map(|c| c.id)
.collect();
assert_eq!(ids, vec!["viewer:alpha/csvlens", "viewer:beta/csvlens"]);
let picked = viewer_by_key_in(&sources, &none, "beta/csvlens").expect("beta's viewer");
assert_eq!(
picked.command, "beta-bin",
"the second row runs the second extension's tool"
);
let keys: BTreeSet<String> = viewers_in(&sources, &none)
.iter()
.map(|v| v.key())
.collect();
assert_eq!(
keys.len(),
2,
"install and dispatch identities do not collide"
);
}
#[test]
fn install_names_cannot_collide_across_extensions() {
let mk = |ext: &str, id: &str| ContributedViewer {
ext_id: ext.into(),
id: id.into(),
label: String::new(),
command: String::new(),
args: Vec::new(),
extensions: Vec::new(),
provision: None,
};
assert_ne!(
mk("alpha-x", "y").install_name(),
mk("alpha", "x-y").install_name(),
"hyphenated ids do not fold into one name"
);
}
#[test]
fn a_viewer_without_a_file_placeholder_gets_the_file_appended() {
let none = BTreeSet::new();
let bare = CSVLENS.replace("args = [\"{file}\"]\n", "");
let v = &viewers_in(&[bare], &none)[0];
assert_eq!(
v.args,
vec!["{file}"],
"no args at all means the file alone"
);
let flagged = CSVLENS.replace("args = [\"{file}\"]", "args = [\"--no-headers\"]");
let v = &viewers_in(&[flagged], &none)[0];
assert_eq!(
v.args,
vec!["--no-headers", "{file}"],
"the file follows the declared flags"
);
}
#[test]
fn an_enabled_viewer_is_offered_for_its_file_kinds_and_a_disabled_one_is_not() {
let sources = vec![CSVLENS.to_string()];
let none = BTreeSet::new();
let v = viewer_for_path_in(&sources, &none, std::path::Path::new("/tmp/data.CSV"))
.expect("csv is one of the viewer's kinds");
assert_eq!(
(v.ext_id.as_str(), v.id.as_str(), v.command.as_str()),
("csvlens", "csvlens", "csvlens")
);
assert_eq!(v.args, vec!["{file}"]);
assert!(
viewer_for_path_in(&sources, &none, std::path::Path::new("/tmp/notes.md")).is_none(),
"a kind no viewer claims gets nothing"
);
let disabled: BTreeSet<String> = ["csvlens".to_string()].into_iter().collect();
assert!(
viewer_for_path_in(&sources, &disabled, std::path::Path::new("/tmp/data.csv"))
.is_none(),
"a disabled extension contributes nothing"
);
let cmds = viewer_commands_in(&sources, &none);
assert_eq!(cmds.len(), 1, "one palette row per viewer");
assert_eq!(
(
cmds[0].ext_id.as_str(),
cmds[0].id.as_str(),
cmds[0].title.as_str()
),
(
"csvlens",
"viewer:csvlens/csvlens",
"csvlens: Open in csvlens"
)
);
assert!(viewer_commands_in(&sources, &disabled).is_empty());
}
const FETCH: &str = r#"
id = "mcp-fetch"
name = "Fetch"
api_version = 1
[[mcp_servers]]
id = "fetch"
command = "mcp-server-fetch"
provision = { kind = "uv", package = "mcp-server-fetch", version = "0.1.0", bin = "mcp-server-fetch" }
[[commands]]
id = "fetch.url"
title = "Fetch: URL to Markdown"
server = "fetch"
tool = "fetch"
prompt = "URL"
"#;
fn sources() -> Vec<String> {
vec![FETCH.to_string()]
}
#[test]
fn under_test_only_a_scratch_config_dir_gives_user_extensions() {
let bundled = manifest::BUNDLED_MANIFESTS.len();
assert_eq!(
all_sources_in_dir(&crate::paths::config_dir()).len(),
bundled
);
let scratch = tempfile::tempdir().unwrap();
let ext = scratch.path().join("extensions").join("mcp-fetch");
std::fs::create_dir_all(&ext).unwrap();
std::fs::write(ext.join("extension.toml"), FETCH).unwrap();
assert_eq!(all_sources_in_dir(scratch.path()).len(), bundled + 1);
}
#[test]
fn contributed_lists_enabled_commands_and_skips_disabled() {
let s = sources();
let none = BTreeSet::new();
let cmds = contributed_in(&s, &none);
assert_eq!(cmds.len(), 1);
assert_eq!(cmds[0].id, "fetch.url");
assert_eq!(cmds[0].title, "Fetch: URL to Markdown");
assert_eq!(cmds[0].ext_id, "mcp-fetch");
let mut disabled = BTreeSet::new();
disabled.insert("mcp-fetch".to_string());
assert!(contributed_in(&s, &disabled).is_empty());
}
#[test]
fn resolve_returns_tool_prompt_and_spawnable_server() {
let s = sources();
let none = BTreeSet::new();
let r = resolve_in(&s, &none, "fetch.url").expect("resolves");
assert_eq!(r.tool, "fetch");
assert_eq!(r.prompt.as_deref(), Some("URL"));
assert_eq!(r.server.id, "fetch");
assert_eq!(r.server.command, "mcp-server-fetch");
assert!(matches!(r.server.provision, Some(Provision::Uv { .. })));
}
#[test]
fn resolve_skips_disabled_and_unknown() {
let s = sources();
let mut disabled = BTreeSet::new();
disabled.insert("mcp-fetch".to_string());
assert!(resolve_in(&s, &disabled, "fetch.url").is_none());
let none = BTreeSet::new();
assert!(resolve_in(&s, &none, "nope.command").is_none());
}
#[test]
fn resolve_returns_none_when_command_references_an_absent_server() {
let src = r#"
id = "mcp-broken"
name = "Broken"
api_version = 1
[[commands]]
id = "x.run"
title = "X"
server = "missing"
tool = "t"
"#;
let s = vec![src.to_string()];
let none = BTreeSet::new();
assert!(resolve_in(&s, &none, "x.run").is_none());
}
}