1use std::path::Path;
9
10use crate::agents::{AgentAdapter, McpEntry, McpScope, Workdir};
11use crate::config::UserConfig;
12use crate::finding::{command_line, Finding, Fix, FixAction, Severity};
13use crate::suite::SuiteMap;
14
15const COMPONENT: &str = "bazaar";
16
17pub const BAZAAR_CLIENT_ID: &str = "visdom-context-mcp";
20
21pub const BAZAAR_SERVER_NAME: &str = "bazaar";
23
24pub fn resolve_bazaar_url(
28 env: Option<String>,
29 user: &UserConfig,
30 suite: &Result<SuiteMap, String>,
31) -> Result<Option<String>, String> {
32 let set = |v: Option<String>| v.filter(|v| !v.trim().is_empty());
33 if let Some(url) = set(env).or_else(|| set(user.bazaar_url.clone())) {
34 return Ok(Some(url));
35 }
36 suite
37 .as_ref()
38 .map(|map| map.bazaar_mcp_url.clone())
39 .map_err(Clone::clone)
40}
41
42pub fn is_http_url(raw: &str) -> bool {
45 url::Url::parse(raw).is_ok_and(|u| matches!(u.scheme(), "http" | "https") && u.has_host())
46 && !raw.starts_with('-')
47 && !raw.contains(char::is_whitespace)
48}
49
50fn unused_name(entries: &[McpEntry]) -> String {
53 let taken = |name: &str| entries.iter().any(|e| e.name == name);
54 [BAZAAR_SERVER_NAME, "visdom-bazaar"]
55 .into_iter()
56 .map(String::from)
57 .chain((2..).map(|n| format!("visdom-bazaar-{n}")))
58 .find(|name| !taken(name))
59 .unwrap_or_else(|| BAZAAR_SERVER_NAME.to_string())
60}
61
62pub fn same_bazaar(a: &str, b: &str) -> bool {
65 fn parts(raw: &str) -> Option<(String, String, Option<u16>)> {
66 let url = url::Url::parse(raw.trim()).ok()?;
67 let path = url.path().trim_end_matches('/');
68 if path != "/mcp" && path != "/mcp/remote" {
69 return None;
70 }
71 Some((
72 url.scheme().to_string(),
73 url.host_str()?.to_ascii_lowercase(),
74 url.port_or_known_default(),
75 ))
76 }
77 match (parts(a), parts(b)) {
78 (Some(a), Some(b)) => a == b,
79 _ => false,
80 }
81}
82
83pub fn registered_name(
88 url: Option<&str>,
89 adapter: &dyn AgentAdapter,
90 workdir: &Workdir,
91) -> Option<String> {
92 let url = url.filter(|url| is_http_url(url))?;
93 adapter
94 .mcp_entries(workdir)
95 .ok()?
96 .into_iter()
97 .find(|e| !e.disabled && e.url.as_deref().is_some_and(|u| same_bazaar(u, url)))
98 .map(|e| e.name)
99}
100
101fn describe(action: &FixAction) -> String {
102 match action {
103 FixAction::RunCommand { program, args, cwd } => {
104 let line = format!("`{}`", command_line(program, args));
105 match cwd {
106 Some(dir) => format!("{line} in {}", dir.display()),
107 None => line,
108 }
109 }
110 FixAction::Sequence { steps } => steps
111 .iter()
112 .map(describe)
113 .collect::<Vec<_>>()
114 .join(", then "),
115 other => format!("{other:?}"),
116 }
117}
118
119fn fix(action: FixAction) -> Fix {
120 Fix {
121 description: format!("run {}", describe(&action)),
122 action,
123 }
124}
125
126pub fn check(
127 bazaar_url: Result<Option<&str>, &str>,
128 adapter: &dyn AgentAdapter,
129 workdir: &Workdir,
130 user_config_path: &Path,
131 register_scope: McpScope,
132) -> Vec<Finding> {
133 let label = adapter.agent().label();
134 let bazaar_url = match bazaar_url {
135 Ok(url) => url,
136 Err(reason) => {
137 return vec![Finding::new(
138 COMPONENT,
139 "bazaar.url",
140 Severity::Unknown,
141 format!(
142 "could not find out the bazaar URL, so its MCP registration was not checked \
143 — {reason}"
144 ),
145 )]
146 }
147 };
148 let Some(url) = bazaar_url else {
149 return vec![Finding::new(
150 COMPONENT,
151 "bazaar.url",
152 Severity::Warn,
153 format!(
154 "the bazaar URL is unknown, so its MCP registration was not checked — set \
155 `bazaar_url` in {} or VISDOM_BAZAAR_URL",
156 user_config_path.display()
157 ),
158 )];
159 };
160 if !is_http_url(url) {
163 return vec![Finding::new(
164 COMPONENT,
165 "bazaar.url",
166 Severity::Warn,
167 format!("the bazaar URL `{url}` is not an http(s) URL, so nothing was checked"),
168 )];
169 }
170 const ID: &str = "bazaar.mcp";
171 let entries = match adapter.mcp_entries(workdir) {
172 Ok(entries) => entries,
173 Err(e) => {
174 return vec![Finding::new(
175 COMPONENT,
176 ID,
177 Severity::Unknown,
178 format!("could not read the {label} MCP configuration — {e}"),
179 )]
180 }
181 };
182 let all_matching: Vec<&McpEntry> = entries
186 .iter()
187 .filter(|e| e.url.as_deref().is_some_and(|u| same_bazaar(u, url)))
188 .filter(|e| register_scope != McpScope::User || e.scope == McpScope::User)
189 .collect();
190 let matching: Vec<&McpEntry> = all_matching
191 .iter()
192 .copied()
193 .filter(|e| !e.disabled)
194 .collect();
195 if let (true, Some(off)) = (matching.is_empty(), all_matching.first()) {
196 return vec![Finding::new(
197 COMPONENT,
198 ID,
199 Severity::Error,
200 format!(
201 "bazaar MCP is registered for {label} as `{}` but switched off: the agent works \
202 without bazaar context — enable it in the {label} MCP settings",
203 off.name
204 ),
205 )];
206 }
207
208 if let Some(entry) = matching
209 .iter()
210 .find(|e| e.oauth_client_id.as_deref() == Some(BAZAAR_CLIENT_ID))
211 {
212 return vec![Finding::new(
213 COMPONENT,
214 ID,
215 Severity::Ok,
216 format!(
217 "bazaar MCP registered for {label} as `{}` (sign in with /mcp if the agent asks)",
218 entry.name
219 ),
220 )];
221 }
222
223 let Some(entry) = matching.first() else {
224 return vec![Finding::new(
225 COMPONENT,
226 ID,
227 Severity::Error,
228 format!(
229 "bazaar MCP is not registered for {label}: the agent works without bazaar context"
230 ),
231 )
232 .with_fix(fix(adapter.register_mcp(
233 &unused_name(&entries),
234 url,
235 BAZAAR_CLIENT_ID,
236 register_scope,
237 workdir,
238 )))];
239 };
240 let found = match &entry.oauth_client_id {
241 Some(id) => format!("with OAuth client `{id}`"),
242 None => "without an OAuth client".to_string(),
243 };
244 let message = format!(
245 "bazaar MCP is registered for {label} as `{}` {found}; it needs `{BAZAAR_CLIENT_ID}`, \
246 otherwise sign-in fails with a 403 on client registration",
247 entry.name
248 );
249 vec![if entry.scope == McpScope::Project {
250 Finding::new(
252 COMPONENT,
253 ID,
254 Severity::Error,
255 format!(
256 "{message} — it comes from a configuration file in the repository; set its \
257 OAuth client to `{BAZAAR_CLIENT_ID}` there"
258 ),
259 )
260 } else if entry.extra_settings || entry.name.starts_with('-') {
261 Finding::new(
263 COMPONENT,
264 ID,
265 Severity::Error,
266 format!(
267 "{message} — the entry has other settings, so it is not replaced automatically; \
268 set its OAuth client to `{BAZAAR_CLIENT_ID}` by hand"
269 ),
270 )
271 } else {
272 Finding::new(COMPONENT, ID, Severity::Error, message).with_fix(fix(FixAction::Sequence {
273 steps: vec![
274 adapter.remove_mcp(entry, workdir),
275 adapter.register_mcp(&entry.name, url, BAZAAR_CLIENT_ID, entry.scope, workdir),
277 ],
278 }))
279 }]
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285 use std::path::PathBuf;
286 use tracevault_cli::agent::Agent;
287
288 const URL: &str = "https://ctx.example.com/mcp/remote";
289
290 struct Fake {
291 entries: Result<Vec<McpEntry>, String>,
292 }
293
294 impl AgentAdapter for Fake {
295 fn agent(&self) -> Agent {
296 Agent::ClaudeCode
297 }
298 fn program(&self) -> &str {
299 "agent"
300 }
301 fn mcp_entries(&self, _: &Workdir) -> Result<Vec<McpEntry>, String> {
302 self.entries.clone()
303 }
304 fn register_mcp(
305 &self,
306 name: &str,
307 url: &str,
308 client_id: &str,
309 scope: McpScope,
310 w: &Workdir,
311 ) -> FixAction {
312 let scope = format!("{scope:?}").to_lowercase();
313 FixAction::RunCommand {
314 program: "agent".to_string(),
315 args: ["add", &scope, name, url, client_id]
316 .map(String::from)
317 .to_vec(),
318 cwd: Some(w.start_dir.clone()),
319 }
320 }
321 fn remove_mcp(&self, entry: &McpEntry, w: &Workdir) -> FixAction {
322 FixAction::RunCommand {
323 program: "agent".to_string(),
324 args: ["remove", &entry.name].map(String::from).to_vec(),
325 cwd: Some(w.start_dir.clone()),
326 }
327 }
328 }
329
330 fn fake(entries: Vec<McpEntry>) -> Fake {
331 Fake {
332 entries: Ok(entries),
333 }
334 }
335
336 fn entry(name: &str, url: &str, client: Option<&str>, scope: McpScope) -> McpEntry {
337 McpEntry {
338 name: name.to_string(),
339 url: Some(url.to_string()),
340 oauth_client_id: client.map(String::from),
341 scope,
342 extra_settings: false,
343 disabled: false,
344 }
345 }
346
347 fn run(adapter: &Fake, url: Option<&str>, workdir: &Workdir) -> Finding {
348 let mut findings = check(
349 Ok(url),
350 adapter,
351 workdir,
352 Path::new("/cfg/visdom/config.toml"),
353 McpScope::Local,
354 );
355 assert_eq!(findings.len(), 1, "{findings:?}");
356 findings.remove(0)
357 }
358
359 fn repo() -> Workdir {
360 Workdir::checkout("/work/repo")
361 }
362
363 #[test]
364 fn url_variants_match_bazaar() {
365 for other in [
366 "https://ctx.example.com/mcp/remote/",
367 "https://ctx.example.com/mcp",
368 "https://ctx.example.com/mcp/",
369 "https://CTX.example.com/mcp/remote",
370 "https://ctx.example.com:443/mcp/remote",
371 " https://ctx.example.com/mcp/remote ",
372 ] {
373 assert!(same_bazaar(URL, other), "{other} is the same server");
374 assert!(same_bazaar(other, URL), "{other} is the same server");
375 }
376 for other in [
377 "https://ctx.example.com/mcp/workspace",
378 "https://other.example.com/mcp/remote",
379 "http://ctx.example.com/mcp/remote",
380 "https://ctx.example.com:8443/mcp/remote",
381 "https://ctx.example.com/",
382 "not a url",
383 "",
384 ] {
385 assert!(!same_bazaar(URL, other), "{other} is a different server");
386 }
387 assert!(!same_bazaar(
389 "https://ctx.example.com/mcp/workspace",
390 "https://ctx.example.com/mcp/workspace"
391 ));
392 }
393
394 #[test]
395 fn unknown_url_is_warn_only() {
396 let finding = run(&fake(vec![]), None, &repo());
397 assert_eq!(finding.id, "bazaar.url");
398 assert_eq!(finding.severity, Severity::Warn);
399 assert!(finding.fix.is_none());
400 assert!(finding.message.contains("/cfg/visdom/config.toml"));
401 assert!(finding.message.contains("VISDOM_BAZAAR_URL"));
402 }
403
404 #[test]
405 fn missing_entry_offers_register_with_client_id() {
406 let other = entry("sentry", "https://mcp.sentry.dev/mcp", None, McpScope::User);
407 let finding = run(&fake(vec![other]), Some(URL), &repo());
408 assert_eq!(finding.id, "bazaar.mcp");
409 assert_eq!(finding.severity, Severity::Error);
410 let fix = finding.fix.expect("a fix");
411 assert_eq!(
412 fix.action,
413 FixAction::RunCommand {
414 program: "agent".to_string(),
415 args: ["add", "local", "bazaar", URL, BAZAAR_CLIENT_ID]
416 .map(String::from)
417 .to_vec(),
418 cwd: Some(PathBuf::from("/work/repo")),
419 }
420 );
421 assert_eq!(
422 fix.description,
423 format!("run `agent add local bazaar {URL} {BAZAAR_CLIENT_ID}` in /work/repo")
424 );
425 }
426
427 #[test]
428 fn unresolvable_url_is_unknown_with_the_reason() {
429 let findings = check(
430 Err("https://tv.example.com could not be asked for it: timeout"),
431 &fake(vec![]),
432 &repo(),
433 Path::new("/cfg"),
434 McpScope::Local,
435 );
436 assert_eq!(findings.len(), 1);
437 assert_eq!(findings[0].id, "bazaar.url");
438 assert_eq!(findings[0].severity, Severity::Unknown);
439 assert!(findings[0].message.contains("timeout"), "{findings:?}");
440 assert!(findings[0].fix.is_none());
441 }
442
443 #[test]
445 fn registration_never_takes_a_name_in_use() {
446 let name_offered = |taken: &[&str]| {
447 let entries = taken
448 .iter()
449 .map(|n| entry(n, "https://other.example.com/x", None, McpScope::User))
450 .collect();
451 match run(&fake(entries), Some(URL), &repo()).fix.unwrap().action {
452 FixAction::RunCommand { args, .. } => args[2].clone(),
453 other => panic!("{other:?}"),
454 }
455 };
456 assert_eq!(name_offered(&[]), "bazaar");
457 assert_eq!(name_offered(&["bazaar"]), "visdom-bazaar");
458 assert_eq!(
459 name_offered(&["bazaar", "visdom-bazaar"]),
460 "visdom-bazaar-2"
461 );
462 }
463
464 #[test]
465 fn entry_with_other_settings_is_not_replaced_automatically() {
466 let mut wrong = entry("bazaar", URL, None, McpScope::User);
467 wrong.extra_settings = true;
468 let finding = run(&fake(vec![wrong]), Some(URL), &repo());
469 assert_eq!(finding.severity, Severity::Error);
470 assert!(finding.fix.is_none());
471 assert!(finding.message.contains("by hand"), "{finding:?}");
472 }
473
474 #[test]
475 fn a_switched_off_entry_is_not_a_registration() {
476 let mut off = entry("bazaar", URL, Some(BAZAAR_CLIENT_ID), McpScope::User);
477 off.disabled = true;
478 let finding = run(&fake(vec![off.clone()]), Some(URL), &repo());
479 assert_eq!(finding.severity, Severity::Error);
480 assert!(finding.message.contains("switched off"), "{finding:?}");
481 assert!(finding.fix.is_none(), "re-adding would replace the entry");
482 let on = entry("visdom", URL, Some(BAZAAR_CLIENT_ID), McpScope::User);
484 assert_eq!(
485 run(&fake(vec![off, on]), Some(URL), &repo()).severity,
486 Severity::Ok
487 );
488 }
489
490 #[test]
492 fn only_a_plain_http_url_is_passed_to_the_agent_cli() {
493 for bad in [
494 "--header=X: y",
495 "-s",
496 "file:///etc/passwd",
497 "ctx.example.com/mcp",
498 "https://ctx.example.com/mcp --scope user",
499 ] {
500 let finding = run(&fake(vec![]), Some(bad), &repo());
501 assert_eq!(finding.id, "bazaar.url", "{bad}");
502 assert_eq!(finding.severity, Severity::Warn, "{bad}");
503 assert!(finding.fix.is_none(), "{bad}");
504 }
505 let finding = run(
507 &fake(vec![entry("--scope", URL, None, McpScope::User)]),
508 Some(URL),
509 &repo(),
510 );
511 assert_eq!(finding.severity, Severity::Error);
512 assert!(finding.fix.is_none());
513 }
514
515 #[test]
516 fn entry_under_other_name_is_found() {
517 let adapter = fake(vec![entry(
518 "visdom",
519 "https://ctx.example.com/mcp",
520 Some(BAZAAR_CLIENT_ID),
521 McpScope::User,
522 )]);
523 let finding = run(&adapter, Some(URL), &repo());
524 assert_eq!(finding.severity, Severity::Ok);
525 assert!(finding.message.contains("`visdom`"), "{finding:?}");
526 assert!(finding.fix.is_none());
527 }
528
529 #[test]
532 fn a_machine_wide_setup_needs_the_registration_at_user_scope() {
533 let local = entry("bazaar", URL, Some(BAZAAR_CLIENT_ID), McpScope::Local);
534 let adapter = fake(vec![local.clone()]);
535 let check_for = |adapter: &Fake, scope| {
536 check(
537 Ok(Some(URL)),
538 adapter,
539 &repo(),
540 Path::new("/cfg/visdom/config.toml"),
541 scope,
542 )
543 .remove(0)
544 };
545 assert_eq!(check_for(&adapter, McpScope::Local).severity, Severity::Ok);
546 let finding = check_for(&adapter, McpScope::User);
547 assert_eq!(finding.severity, Severity::Error);
548 assert!(finding.fix.is_some(), "{finding:?}");
549
550 let user = entry("visdom", URL, Some(BAZAAR_CLIENT_ID), McpScope::User);
551 let adapter = fake(vec![local, user]);
552 assert_eq!(check_for(&adapter, McpScope::User).severity, Severity::Ok);
553 }
554
555 #[test]
556 fn wrong_client_id_offers_remove_then_add() {
557 for (client, scope, scope_name) in [
558 (None, McpScope::Local, "local"),
559 (Some("something-else"), McpScope::User, "user"),
562 ] {
563 let adapter = fake(vec![entry("visdom", URL, client, scope)]);
564 let finding = run(&adapter, Some(URL), &repo());
565 assert_eq!(finding.severity, Severity::Error);
566 assert!(finding.message.contains("403"), "{finding:?}");
567 let steps = match finding.fix.expect("a fix").action {
568 FixAction::Sequence { steps } => steps,
569 other => panic!("expected a sequence, got {other:?}"),
570 };
571 let args: Vec<Vec<String>> = steps
572 .iter()
573 .map(|s| match s {
574 FixAction::RunCommand { args, .. } => args.clone(),
575 other => panic!("{other:?}"),
576 })
577 .collect();
578 assert_eq!(args[0], ["remove", "visdom"]);
580 assert_eq!(
581 args[1],
582 ["add", scope_name, "visdom", URL, BAZAAR_CLIENT_ID]
583 );
584 }
585 }
586
587 #[test]
588 fn a_correct_entry_wins_over_a_wrong_one() {
589 let adapter = fake(vec![
590 entry("old", URL, None, McpScope::User),
591 entry("bazaar", URL, Some(BAZAAR_CLIENT_ID), McpScope::Local),
592 ]);
593 assert_eq!(run(&adapter, Some(URL), &repo()).severity, Severity::Ok);
594 }
595
596 #[test]
597 fn wrong_client_id_in_committed_file_has_no_automatic_fix() {
598 let adapter = fake(vec![entry("bazaar", URL, None, McpScope::Project)]);
599 let finding = run(&adapter, Some(URL), &repo());
600 assert_eq!(finding.severity, Severity::Error);
601 assert!(finding.fix.is_none());
602 assert!(
603 finding.message.contains("file in the repository"),
604 "{finding:?}"
605 );
606 }
607
608 #[test]
609 fn adapter_error_is_unknown() {
610 let adapter = Fake {
611 entries: Err("cannot parse /home/u/.claude.json: eof".to_string()),
612 };
613 let finding = run(&adapter, Some(URL), &repo());
614 assert_eq!(finding.severity, Severity::Unknown);
615 assert!(finding.fix.is_none());
616 assert!(finding.message.contains(".claude.json"), "{finding:?}");
617 }
618
619 #[test]
622 fn outside_a_repository_registration_is_offered_in_the_start_directory() {
623 let finding = run(&fake(vec![]), Some(URL), &Workdir::plain("/work/umbrella"));
624 assert_eq!(finding.severity, Severity::Error);
625 match finding.fix.expect("a fix").action {
626 FixAction::RunCommand { cwd, .. } => {
627 assert_eq!(cwd, Some(PathBuf::from("/work/umbrella")))
628 }
629 other => panic!("{other:?}"),
630 }
631 }
632
633 #[test]
634 fn url_precedence_env_user_server() {
635 let user = UserConfig {
636 bazaar_url: Some("https://user.example.com/mcp".to_string()),
637 ..Default::default()
638 };
639 let none = UserConfig::default();
640 let published: Result<SuiteMap, String> = Ok(SuiteMap {
641 bazaar_mcp_url: Some("https://srv.example.com/mcp/remote".to_string()),
642 ..SuiteMap::default()
643 });
644 let unreachable: Result<SuiteMap, String> = Err("tv.example.com: refused".to_string());
645 assert_eq!(
647 resolve_bazaar_url(
648 Some("https://env.example.com/mcp".to_string()),
649 &user,
650 &unreachable
651 )
652 .unwrap()
653 .as_deref(),
654 Some("https://env.example.com/mcp")
655 );
656 assert_eq!(
658 resolve_bazaar_url(Some(" ".to_string()), &user, &unreachable)
659 .unwrap()
660 .as_deref(),
661 Some("https://user.example.com/mcp")
662 );
663 assert_eq!(
665 resolve_bazaar_url(None, &none, &published)
666 .unwrap()
667 .as_deref(),
668 Some("https://srv.example.com/mcp/remote")
669 );
670 assert_eq!(
672 resolve_bazaar_url(None, &none, &Ok(SuiteMap::default())),
673 Ok(None)
674 );
675 assert_eq!(
677 resolve_bazaar_url(None, &none, &unreachable),
678 Err("tv.example.com: refused".to_string())
679 );
680 }
681}