use std::path::Path;
use crate::agents::{AgentAdapter, McpEntry, McpScope, Workdir};
use crate::config::UserConfig;
use crate::finding::{command_line, Finding, Fix, FixAction, Severity};
use crate::suite::SuiteMap;
const COMPONENT: &str = "bazaar";
pub const BAZAAR_CLIENT_ID: &str = "visdom-context-mcp";
pub const BAZAAR_SERVER_NAME: &str = "bazaar";
pub fn resolve_bazaar_url(
env: Option<String>,
user: &UserConfig,
suite: &Result<SuiteMap, String>,
) -> Result<Option<String>, String> {
let set = |v: Option<String>| v.filter(|v| !v.trim().is_empty());
if let Some(url) = set(env).or_else(|| set(user.bazaar_url.clone())) {
return Ok(Some(url));
}
suite
.as_ref()
.map(|map| map.bazaar_mcp_url.clone())
.map_err(Clone::clone)
}
pub fn is_http_url(raw: &str) -> bool {
url::Url::parse(raw).is_ok_and(|u| matches!(u.scheme(), "http" | "https") && u.has_host())
&& !raw.starts_with('-')
&& !raw.contains(char::is_whitespace)
}
fn unused_name(entries: &[McpEntry]) -> String {
let taken = |name: &str| entries.iter().any(|e| e.name == name);
[BAZAAR_SERVER_NAME, "visdom-bazaar"]
.into_iter()
.map(String::from)
.chain((2..).map(|n| format!("visdom-bazaar-{n}")))
.find(|name| !taken(name))
.unwrap_or_else(|| BAZAAR_SERVER_NAME.to_string())
}
pub fn same_bazaar(a: &str, b: &str) -> bool {
fn parts(raw: &str) -> Option<(String, String, Option<u16>)> {
let url = url::Url::parse(raw.trim()).ok()?;
let path = url.path().trim_end_matches('/');
if path != "/mcp" && path != "/mcp/remote" {
return None;
}
Some((
url.scheme().to_string(),
url.host_str()?.to_ascii_lowercase(),
url.port_or_known_default(),
))
}
match (parts(a), parts(b)) {
(Some(a), Some(b)) => a == b,
_ => false,
}
}
pub fn registered_name(
url: Option<&str>,
adapter: &dyn AgentAdapter,
workdir: &Workdir,
) -> Option<String> {
let url = url.filter(|url| is_http_url(url))?;
adapter
.mcp_entries(workdir)
.ok()?
.into_iter()
.find(|e| !e.disabled && e.url.as_deref().is_some_and(|u| same_bazaar(u, url)))
.map(|e| e.name)
}
fn describe(action: &FixAction) -> String {
match action {
FixAction::RunCommand { program, args, cwd } => {
let line = format!("`{}`", command_line(program, args));
match cwd {
Some(dir) => format!("{line} in {}", dir.display()),
None => line,
}
}
FixAction::Sequence { steps } => steps
.iter()
.map(describe)
.collect::<Vec<_>>()
.join(", then "),
other => format!("{other:?}"),
}
}
fn fix(action: FixAction) -> Fix {
Fix {
description: format!("run {}", describe(&action)),
action,
}
}
pub fn check(
bazaar_url: Result<Option<&str>, &str>,
adapter: &dyn AgentAdapter,
workdir: &Workdir,
user_config_path: &Path,
register_scope: McpScope,
) -> Vec<Finding> {
let label = adapter.agent().label();
let bazaar_url = match bazaar_url {
Ok(url) => url,
Err(reason) => {
return vec![Finding::new(
COMPONENT,
"bazaar.url",
Severity::Unknown,
format!(
"could not find out the bazaar URL, so its MCP registration was not checked \
— {reason}"
),
)]
}
};
let Some(url) = bazaar_url else {
return vec![Finding::new(
COMPONENT,
"bazaar.url",
Severity::Warn,
format!(
"the bazaar URL is unknown, so its MCP registration was not checked — set \
`bazaar_url` in {} or VISDOM_BAZAAR_URL",
user_config_path.display()
),
)];
};
if !is_http_url(url) {
return vec![Finding::new(
COMPONENT,
"bazaar.url",
Severity::Warn,
format!("the bazaar URL `{url}` is not an http(s) URL, so nothing was checked"),
)];
}
const ID: &str = "bazaar.mcp";
let entries = match adapter.mcp_entries(workdir) {
Ok(entries) => entries,
Err(e) => {
return vec![Finding::new(
COMPONENT,
ID,
Severity::Unknown,
format!("could not read the {label} MCP configuration — {e}"),
)]
}
};
let all_matching: Vec<&McpEntry> = entries
.iter()
.filter(|e| e.url.as_deref().is_some_and(|u| same_bazaar(u, url)))
.filter(|e| register_scope != McpScope::User || e.scope == McpScope::User)
.collect();
let matching: Vec<&McpEntry> = all_matching
.iter()
.copied()
.filter(|e| !e.disabled)
.collect();
if let (true, Some(off)) = (matching.is_empty(), all_matching.first()) {
return vec![Finding::new(
COMPONENT,
ID,
Severity::Error,
format!(
"bazaar MCP is registered for {label} as `{}` but switched off: the agent works \
without bazaar context — enable it in the {label} MCP settings",
off.name
),
)];
}
if let Some(entry) = matching
.iter()
.find(|e| e.oauth_client_id.as_deref() == Some(BAZAAR_CLIENT_ID))
{
return vec![Finding::new(
COMPONENT,
ID,
Severity::Ok,
format!(
"bazaar MCP registered for {label} as `{}` (sign in with /mcp if the agent asks)",
entry.name
),
)];
}
let Some(entry) = matching.first() else {
return vec![Finding::new(
COMPONENT,
ID,
Severity::Error,
format!(
"bazaar MCP is not registered for {label}: the agent works without bazaar context"
),
)
.with_fix(fix(adapter.register_mcp(
&unused_name(&entries),
url,
BAZAAR_CLIENT_ID,
register_scope,
workdir,
)))];
};
let found = match &entry.oauth_client_id {
Some(id) => format!("with OAuth client `{id}`"),
None => "without an OAuth client".to_string(),
};
let message = format!(
"bazaar MCP is registered for {label} as `{}` {found}; it needs `{BAZAAR_CLIENT_ID}`, \
otherwise sign-in fails with a 403 on client registration",
entry.name
);
vec![if entry.scope == McpScope::Project {
Finding::new(
COMPONENT,
ID,
Severity::Error,
format!(
"{message} — it comes from a configuration file in the repository; set its \
OAuth client to `{BAZAAR_CLIENT_ID}` there"
),
)
} else if entry.extra_settings || entry.name.starts_with('-') {
Finding::new(
COMPONENT,
ID,
Severity::Error,
format!(
"{message} — the entry has other settings, so it is not replaced automatically; \
set its OAuth client to `{BAZAAR_CLIENT_ID}` by hand"
),
)
} else {
Finding::new(COMPONENT, ID, Severity::Error, message).with_fix(fix(FixAction::Sequence {
steps: vec![
adapter.remove_mcp(entry, workdir),
adapter.register_mcp(&entry.name, url, BAZAAR_CLIENT_ID, entry.scope, workdir),
],
}))
}]
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
use tracevault_cli::agent::Agent;
const URL: &str = "https://ctx.example.com/mcp/remote";
struct Fake {
entries: Result<Vec<McpEntry>, String>,
}
impl AgentAdapter for Fake {
fn agent(&self) -> Agent {
Agent::ClaudeCode
}
fn program(&self) -> &str {
"agent"
}
fn mcp_entries(&self, _: &Workdir) -> Result<Vec<McpEntry>, String> {
self.entries.clone()
}
fn register_mcp(
&self,
name: &str,
url: &str,
client_id: &str,
scope: McpScope,
w: &Workdir,
) -> FixAction {
let scope = format!("{scope:?}").to_lowercase();
FixAction::RunCommand {
program: "agent".to_string(),
args: ["add", &scope, name, url, client_id]
.map(String::from)
.to_vec(),
cwd: Some(w.start_dir.clone()),
}
}
fn remove_mcp(&self, entry: &McpEntry, w: &Workdir) -> FixAction {
FixAction::RunCommand {
program: "agent".to_string(),
args: ["remove", &entry.name].map(String::from).to_vec(),
cwd: Some(w.start_dir.clone()),
}
}
}
fn fake(entries: Vec<McpEntry>) -> Fake {
Fake {
entries: Ok(entries),
}
}
fn entry(name: &str, url: &str, client: Option<&str>, scope: McpScope) -> McpEntry {
McpEntry {
name: name.to_string(),
url: Some(url.to_string()),
oauth_client_id: client.map(String::from),
scope,
extra_settings: false,
disabled: false,
}
}
fn run(adapter: &Fake, url: Option<&str>, workdir: &Workdir) -> Finding {
let mut findings = check(
Ok(url),
adapter,
workdir,
Path::new("/cfg/visdom/config.toml"),
McpScope::Local,
);
assert_eq!(findings.len(), 1, "{findings:?}");
findings.remove(0)
}
fn repo() -> Workdir {
Workdir::checkout("/work/repo")
}
#[test]
fn url_variants_match_bazaar() {
for other in [
"https://ctx.example.com/mcp/remote/",
"https://ctx.example.com/mcp",
"https://ctx.example.com/mcp/",
"https://CTX.example.com/mcp/remote",
"https://ctx.example.com:443/mcp/remote",
" https://ctx.example.com/mcp/remote ",
] {
assert!(same_bazaar(URL, other), "{other} is the same server");
assert!(same_bazaar(other, URL), "{other} is the same server");
}
for other in [
"https://ctx.example.com/mcp/workspace",
"https://other.example.com/mcp/remote",
"http://ctx.example.com/mcp/remote",
"https://ctx.example.com:8443/mcp/remote",
"https://ctx.example.com/",
"not a url",
"",
] {
assert!(!same_bazaar(URL, other), "{other} is a different server");
}
assert!(!same_bazaar(
"https://ctx.example.com/mcp/workspace",
"https://ctx.example.com/mcp/workspace"
));
}
#[test]
fn unknown_url_is_warn_only() {
let finding = run(&fake(vec![]), None, &repo());
assert_eq!(finding.id, "bazaar.url");
assert_eq!(finding.severity, Severity::Warn);
assert!(finding.fix.is_none());
assert!(finding.message.contains("/cfg/visdom/config.toml"));
assert!(finding.message.contains("VISDOM_BAZAAR_URL"));
}
#[test]
fn missing_entry_offers_register_with_client_id() {
let other = entry("sentry", "https://mcp.sentry.dev/mcp", None, McpScope::User);
let finding = run(&fake(vec![other]), Some(URL), &repo());
assert_eq!(finding.id, "bazaar.mcp");
assert_eq!(finding.severity, Severity::Error);
let fix = finding.fix.expect("a fix");
assert_eq!(
fix.action,
FixAction::RunCommand {
program: "agent".to_string(),
args: ["add", "local", "bazaar", URL, BAZAAR_CLIENT_ID]
.map(String::from)
.to_vec(),
cwd: Some(PathBuf::from("/work/repo")),
}
);
assert_eq!(
fix.description,
format!("run `agent add local bazaar {URL} {BAZAAR_CLIENT_ID}` in /work/repo")
);
}
#[test]
fn unresolvable_url_is_unknown_with_the_reason() {
let findings = check(
Err("https://tv.example.com could not be asked for it: timeout"),
&fake(vec![]),
&repo(),
Path::new("/cfg"),
McpScope::Local,
);
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].id, "bazaar.url");
assert_eq!(findings[0].severity, Severity::Unknown);
assert!(findings[0].message.contains("timeout"), "{findings:?}");
assert!(findings[0].fix.is_none());
}
#[test]
fn registration_never_takes_a_name_in_use() {
let name_offered = |taken: &[&str]| {
let entries = taken
.iter()
.map(|n| entry(n, "https://other.example.com/x", None, McpScope::User))
.collect();
match run(&fake(entries), Some(URL), &repo()).fix.unwrap().action {
FixAction::RunCommand { args, .. } => args[2].clone(),
other => panic!("{other:?}"),
}
};
assert_eq!(name_offered(&[]), "bazaar");
assert_eq!(name_offered(&["bazaar"]), "visdom-bazaar");
assert_eq!(
name_offered(&["bazaar", "visdom-bazaar"]),
"visdom-bazaar-2"
);
}
#[test]
fn entry_with_other_settings_is_not_replaced_automatically() {
let mut wrong = entry("bazaar", URL, None, McpScope::User);
wrong.extra_settings = true;
let finding = run(&fake(vec![wrong]), Some(URL), &repo());
assert_eq!(finding.severity, Severity::Error);
assert!(finding.fix.is_none());
assert!(finding.message.contains("by hand"), "{finding:?}");
}
#[test]
fn a_switched_off_entry_is_not_a_registration() {
let mut off = entry("bazaar", URL, Some(BAZAAR_CLIENT_ID), McpScope::User);
off.disabled = true;
let finding = run(&fake(vec![off.clone()]), Some(URL), &repo());
assert_eq!(finding.severity, Severity::Error);
assert!(finding.message.contains("switched off"), "{finding:?}");
assert!(finding.fix.is_none(), "re-adding would replace the entry");
let on = entry("visdom", URL, Some(BAZAAR_CLIENT_ID), McpScope::User);
assert_eq!(
run(&fake(vec![off, on]), Some(URL), &repo()).severity,
Severity::Ok
);
}
#[test]
fn only_a_plain_http_url_is_passed_to_the_agent_cli() {
for bad in [
"--header=X: y",
"-s",
"file:///etc/passwd",
"ctx.example.com/mcp",
"https://ctx.example.com/mcp --scope user",
] {
let finding = run(&fake(vec![]), Some(bad), &repo());
assert_eq!(finding.id, "bazaar.url", "{bad}");
assert_eq!(finding.severity, Severity::Warn, "{bad}");
assert!(finding.fix.is_none(), "{bad}");
}
let finding = run(
&fake(vec![entry("--scope", URL, None, McpScope::User)]),
Some(URL),
&repo(),
);
assert_eq!(finding.severity, Severity::Error);
assert!(finding.fix.is_none());
}
#[test]
fn entry_under_other_name_is_found() {
let adapter = fake(vec![entry(
"visdom",
"https://ctx.example.com/mcp",
Some(BAZAAR_CLIENT_ID),
McpScope::User,
)]);
let finding = run(&adapter, Some(URL), &repo());
assert_eq!(finding.severity, Severity::Ok);
assert!(finding.message.contains("`visdom`"), "{finding:?}");
assert!(finding.fix.is_none());
}
#[test]
fn a_machine_wide_setup_needs_the_registration_at_user_scope() {
let local = entry("bazaar", URL, Some(BAZAAR_CLIENT_ID), McpScope::Local);
let adapter = fake(vec![local.clone()]);
let check_for = |adapter: &Fake, scope| {
check(
Ok(Some(URL)),
adapter,
&repo(),
Path::new("/cfg/visdom/config.toml"),
scope,
)
.remove(0)
};
assert_eq!(check_for(&adapter, McpScope::Local).severity, Severity::Ok);
let finding = check_for(&adapter, McpScope::User);
assert_eq!(finding.severity, Severity::Error);
assert!(finding.fix.is_some(), "{finding:?}");
let user = entry("visdom", URL, Some(BAZAAR_CLIENT_ID), McpScope::User);
let adapter = fake(vec![local, user]);
assert_eq!(check_for(&adapter, McpScope::User).severity, Severity::Ok);
}
#[test]
fn wrong_client_id_offers_remove_then_add() {
for (client, scope, scope_name) in [
(None, McpScope::Local, "local"),
(Some("something-else"), McpScope::User, "user"),
] {
let adapter = fake(vec![entry("visdom", URL, client, scope)]);
let finding = run(&adapter, Some(URL), &repo());
assert_eq!(finding.severity, Severity::Error);
assert!(finding.message.contains("403"), "{finding:?}");
let steps = match finding.fix.expect("a fix").action {
FixAction::Sequence { steps } => steps,
other => panic!("expected a sequence, got {other:?}"),
};
let args: Vec<Vec<String>> = steps
.iter()
.map(|s| match s {
FixAction::RunCommand { args, .. } => args.clone(),
other => panic!("{other:?}"),
})
.collect();
assert_eq!(args[0], ["remove", "visdom"]);
assert_eq!(
args[1],
["add", scope_name, "visdom", URL, BAZAAR_CLIENT_ID]
);
}
}
#[test]
fn a_correct_entry_wins_over_a_wrong_one() {
let adapter = fake(vec![
entry("old", URL, None, McpScope::User),
entry("bazaar", URL, Some(BAZAAR_CLIENT_ID), McpScope::Local),
]);
assert_eq!(run(&adapter, Some(URL), &repo()).severity, Severity::Ok);
}
#[test]
fn wrong_client_id_in_committed_file_has_no_automatic_fix() {
let adapter = fake(vec![entry("bazaar", URL, None, McpScope::Project)]);
let finding = run(&adapter, Some(URL), &repo());
assert_eq!(finding.severity, Severity::Error);
assert!(finding.fix.is_none());
assert!(
finding.message.contains("file in the repository"),
"{finding:?}"
);
}
#[test]
fn adapter_error_is_unknown() {
let adapter = Fake {
entries: Err("cannot parse /home/u/.claude.json: eof".to_string()),
};
let finding = run(&adapter, Some(URL), &repo());
assert_eq!(finding.severity, Severity::Unknown);
assert!(finding.fix.is_none());
assert!(finding.message.contains(".claude.json"), "{finding:?}");
}
#[test]
fn outside_a_repository_registration_is_offered_in_the_start_directory() {
let finding = run(&fake(vec![]), Some(URL), &Workdir::plain("/work/umbrella"));
assert_eq!(finding.severity, Severity::Error);
match finding.fix.expect("a fix").action {
FixAction::RunCommand { cwd, .. } => {
assert_eq!(cwd, Some(PathBuf::from("/work/umbrella")))
}
other => panic!("{other:?}"),
}
}
#[test]
fn url_precedence_env_user_server() {
let user = UserConfig {
bazaar_url: Some("https://user.example.com/mcp".to_string()),
..Default::default()
};
let none = UserConfig::default();
let published: Result<SuiteMap, String> = Ok(SuiteMap {
bazaar_mcp_url: Some("https://srv.example.com/mcp/remote".to_string()),
..SuiteMap::default()
});
let unreachable: Result<SuiteMap, String> = Err("tv.example.com: refused".to_string());
assert_eq!(
resolve_bazaar_url(
Some("https://env.example.com/mcp".to_string()),
&user,
&unreachable
)
.unwrap()
.as_deref(),
Some("https://env.example.com/mcp")
);
assert_eq!(
resolve_bazaar_url(Some(" ".to_string()), &user, &unreachable)
.unwrap()
.as_deref(),
Some("https://user.example.com/mcp")
);
assert_eq!(
resolve_bazaar_url(None, &none, &published)
.unwrap()
.as_deref(),
Some("https://srv.example.com/mcp/remote")
);
assert_eq!(
resolve_bazaar_url(None, &none, &Ok(SuiteMap::default())),
Ok(None)
);
assert_eq!(
resolve_bazaar_url(None, &none, &unreachable),
Err("tv.example.com: refused".to_string())
);
}
}