Skip to main content

visdom_cli/components/
bazaar.rs

1//! Is the bazaar (context) MCP server registered for the agent, with the
2//! OAuth client it needs?
3//!
4//! The entry is found by its URL, not its name: bazaar's own guide registers
5//! it as `visdom`, other notes as `bazaar`. Whether the user is signed in is
6//! not checked — the tokens live in the agent's own store.
7
8use 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
17/// The pre-registered OAuth client of the bazaar MCP endpoint. Without it the
18/// agent tries Dynamic Client Registration, which the realm refuses.
19pub const BAZAAR_CLIENT_ID: &str = "visdom-context-mcp";
20
21/// The name a new registration gets.
22pub const BAZAAR_SERVER_NAME: &str = "bazaar";
23
24/// The bazaar MCP endpoint: `VISDOM_BAZAAR_URL`, then the user config, then
25/// what the tracing server publishes (`suite`). `Ok(None)` when none of them
26/// knows it; `Err` with the reason when the server could not be asked.
27pub 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
42/// Whether `raw` is an absolute http(s) URL — which also means it cannot be
43/// mistaken for an option by the command it is handed to.
44pub 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
50/// A name for a new registration that no configured server has: agents
51/// replace an entry registered again under its name.
52fn 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
62/// Whether two URLs name the same bazaar developer endpoint: same scheme, host
63/// and port, and each path one of `/mcp/remote` and its alias `/mcp`.
64pub 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
83fn describe(action: &FixAction) -> String {
84    match action {
85        FixAction::RunCommand { program, args, cwd } => {
86            let line = format!("`{}`", command_line(program, args));
87            match cwd {
88                Some(dir) => format!("{line} in {}", dir.display()),
89                None => line,
90            }
91        }
92        FixAction::Sequence { steps } => steps
93            .iter()
94            .map(describe)
95            .collect::<Vec<_>>()
96            .join(", then "),
97        other => format!("{other:?}"),
98    }
99}
100
101fn fix(action: FixAction) -> Fix {
102    Fix {
103        description: format!("run {}", describe(&action)),
104        action,
105    }
106}
107
108pub fn check(
109    bazaar_url: Result<Option<&str>, &str>,
110    adapter: &dyn AgentAdapter,
111    workdir: &Workdir,
112    user_config_path: &Path,
113) -> Vec<Finding> {
114    let label = adapter.agent().label();
115    let bazaar_url = match bazaar_url {
116        Ok(url) => url,
117        Err(reason) => {
118            return vec![Finding::new(
119                COMPONENT,
120                "bazaar.url",
121                Severity::Unknown,
122                format!(
123                    "could not find out the bazaar URL, so its MCP registration was not checked \
124                     — {reason}"
125                ),
126            )]
127        }
128    };
129    let Some(url) = bazaar_url else {
130        return vec![Finding::new(
131            COMPONENT,
132            "bazaar.url",
133            Severity::Warn,
134            format!(
135                "the bazaar URL is unknown, so its MCP registration was not checked — set \
136                 `bazaar_url` in {} or VISDOM_BAZAAR_URL",
137                user_config_path.display()
138            ),
139        )];
140    };
141    // The URL becomes an argument of the agent's CLI, and it may come from a
142    // server: only a plain http(s) URL is ever passed on.
143    if !is_http_url(url) {
144        return vec![Finding::new(
145            COMPONENT,
146            "bazaar.url",
147            Severity::Warn,
148            format!("the bazaar URL `{url}` is not an http(s) URL, so nothing was checked"),
149        )];
150    }
151    const ID: &str = "bazaar.mcp";
152    let entries = match adapter.mcp_entries(workdir) {
153        Ok(entries) => entries,
154        Err(e) => {
155            return vec![Finding::new(
156                COMPONENT,
157                ID,
158                Severity::Unknown,
159                format!("could not read the {label} MCP configuration — {e}"),
160            )]
161        }
162    };
163    let all_matching: Vec<&McpEntry> = entries
164        .iter()
165        .filter(|e| e.url.as_deref().is_some_and(|u| same_bazaar(u, url)))
166        .collect();
167    let matching: Vec<&McpEntry> = all_matching
168        .iter()
169        .copied()
170        .filter(|e| !e.disabled)
171        .collect();
172    if let (true, Some(off)) = (matching.is_empty(), all_matching.first()) {
173        return vec![Finding::new(
174            COMPONENT,
175            ID,
176            Severity::Error,
177            format!(
178                "bazaar MCP is registered for {label} as `{}` but switched off: the agent works \
179                 without bazaar context — enable it in the {label} MCP settings",
180                off.name
181            ),
182        )];
183    }
184
185    if let Some(entry) = matching
186        .iter()
187        .find(|e| e.oauth_client_id.as_deref() == Some(BAZAAR_CLIENT_ID))
188    {
189        return vec![Finding::new(
190            COMPONENT,
191            ID,
192            Severity::Ok,
193            format!(
194                "bazaar MCP registered for {label} as `{}` (sign in with /mcp if the agent asks)",
195                entry.name
196            ),
197        )];
198    }
199
200    let Some(entry) = matching.first() else {
201        return vec![Finding::new(
202            COMPONENT,
203            ID,
204            Severity::Error,
205            format!(
206                "bazaar MCP is not registered for {label}: the agent works without bazaar context"
207            ),
208        )
209        .with_fix(fix(adapter.register_mcp(
210            &unused_name(&entries),
211            url,
212            BAZAAR_CLIENT_ID,
213            McpScope::Local,
214            workdir,
215        )))];
216    };
217    let found = match &entry.oauth_client_id {
218        Some(id) => format!("with OAuth client `{id}`"),
219        None => "without an OAuth client".to_string(),
220    };
221    let message = format!(
222        "bazaar MCP is registered for {label} as `{}` {found}; it needs `{BAZAAR_CLIENT_ID}`, \
223         otherwise sign-in fails with a 403 on client registration",
224        entry.name
225    );
226    vec![if entry.scope == McpScope::Project {
227        // A committed file: the team's, not visdom's to rewrite.
228        Finding::new(
229            COMPONENT,
230            ID,
231            Severity::Error,
232            format!(
233                "{message} — it comes from a configuration file in the repository; set its \
234                 OAuth client to `{BAZAAR_CLIENT_ID}` there"
235            ),
236        )
237    } else if entry.extra_settings || entry.name.starts_with('-') {
238        // Removing and re-adding it would drop its other settings.
239        Finding::new(
240            COMPONENT,
241            ID,
242            Severity::Error,
243            format!(
244                "{message} — the entry has other settings, so it is not replaced automatically; \
245                 set its OAuth client to `{BAZAAR_CLIENT_ID}` by hand"
246            ),
247        )
248    } else {
249        Finding::new(COMPONENT, ID, Severity::Error, message).with_fix(fix(FixAction::Sequence {
250            steps: vec![
251                adapter.remove_mcp(entry, workdir),
252                // Back where it was: a user-scope entry serves every project.
253                adapter.register_mcp(&entry.name, url, BAZAAR_CLIENT_ID, entry.scope, workdir),
254            ],
255        }))
256    }]
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262    use std::path::PathBuf;
263    use tracevault_cli::agent::Agent;
264
265    const URL: &str = "https://ctx.example.com/mcp/remote";
266
267    struct Fake {
268        entries: Result<Vec<McpEntry>, String>,
269    }
270
271    impl AgentAdapter for Fake {
272        fn agent(&self) -> Agent {
273            Agent::ClaudeCode
274        }
275        fn program(&self) -> &str {
276            "agent"
277        }
278        fn mcp_entries(&self, _: &Workdir) -> Result<Vec<McpEntry>, String> {
279            self.entries.clone()
280        }
281        fn register_mcp(
282            &self,
283            name: &str,
284            url: &str,
285            client_id: &str,
286            scope: McpScope,
287            w: &Workdir,
288        ) -> FixAction {
289            let scope = format!("{scope:?}").to_lowercase();
290            FixAction::RunCommand {
291                program: "agent".to_string(),
292                args: ["add", &scope, name, url, client_id]
293                    .map(String::from)
294                    .to_vec(),
295                cwd: Some(w.start_dir.clone()),
296            }
297        }
298        fn remove_mcp(&self, entry: &McpEntry, w: &Workdir) -> FixAction {
299            FixAction::RunCommand {
300                program: "agent".to_string(),
301                args: ["remove", &entry.name].map(String::from).to_vec(),
302                cwd: Some(w.start_dir.clone()),
303            }
304        }
305    }
306
307    fn fake(entries: Vec<McpEntry>) -> Fake {
308        Fake {
309            entries: Ok(entries),
310        }
311    }
312
313    fn entry(name: &str, url: &str, client: Option<&str>, scope: McpScope) -> McpEntry {
314        McpEntry {
315            name: name.to_string(),
316            url: Some(url.to_string()),
317            oauth_client_id: client.map(String::from),
318            scope,
319            extra_settings: false,
320            disabled: false,
321        }
322    }
323
324    fn run(adapter: &Fake, url: Option<&str>, workdir: &Workdir) -> Finding {
325        let mut findings = check(
326            Ok(url),
327            adapter,
328            workdir,
329            Path::new("/cfg/visdom/config.toml"),
330        );
331        assert_eq!(findings.len(), 1, "{findings:?}");
332        findings.remove(0)
333    }
334
335    fn repo() -> Workdir {
336        Workdir::checkout("/work/repo")
337    }
338
339    #[test]
340    fn url_variants_match_bazaar() {
341        for other in [
342            "https://ctx.example.com/mcp/remote/",
343            "https://ctx.example.com/mcp",
344            "https://ctx.example.com/mcp/",
345            "https://CTX.example.com/mcp/remote",
346            "https://ctx.example.com:443/mcp/remote",
347            " https://ctx.example.com/mcp/remote ",
348        ] {
349            assert!(same_bazaar(URL, other), "{other} is the same server");
350            assert!(same_bazaar(other, URL), "{other} is the same server");
351        }
352        for other in [
353            "https://ctx.example.com/mcp/workspace",
354            "https://other.example.com/mcp/remote",
355            "http://ctx.example.com/mcp/remote",
356            "https://ctx.example.com:8443/mcp/remote",
357            "https://ctx.example.com/",
358            "not a url",
359            "",
360        ] {
361            assert!(!same_bazaar(URL, other), "{other} is a different server");
362        }
363        // Two workspace endpoints are not "the same bazaar" either.
364        assert!(!same_bazaar(
365            "https://ctx.example.com/mcp/workspace",
366            "https://ctx.example.com/mcp/workspace"
367        ));
368    }
369
370    #[test]
371    fn unknown_url_is_warn_only() {
372        let finding = run(&fake(vec![]), None, &repo());
373        assert_eq!(finding.id, "bazaar.url");
374        assert_eq!(finding.severity, Severity::Warn);
375        assert!(finding.fix.is_none());
376        assert!(finding.message.contains("/cfg/visdom/config.toml"));
377        assert!(finding.message.contains("VISDOM_BAZAAR_URL"));
378    }
379
380    #[test]
381    fn missing_entry_offers_register_with_client_id() {
382        let other = entry("sentry", "https://mcp.sentry.dev/mcp", None, McpScope::User);
383        let finding = run(&fake(vec![other]), Some(URL), &repo());
384        assert_eq!(finding.id, "bazaar.mcp");
385        assert_eq!(finding.severity, Severity::Error);
386        let fix = finding.fix.expect("a fix");
387        assert_eq!(
388            fix.action,
389            FixAction::RunCommand {
390                program: "agent".to_string(),
391                args: ["add", "local", "bazaar", URL, BAZAAR_CLIENT_ID]
392                    .map(String::from)
393                    .to_vec(),
394                cwd: Some(PathBuf::from("/work/repo")),
395            }
396        );
397        assert_eq!(
398            fix.description,
399            format!("run `agent add local bazaar {URL} {BAZAAR_CLIENT_ID}` in /work/repo")
400        );
401    }
402
403    #[test]
404    fn unresolvable_url_is_unknown_with_the_reason() {
405        let findings = check(
406            Err("https://tv.example.com could not be asked for it: timeout"),
407            &fake(vec![]),
408            &repo(),
409            Path::new("/cfg"),
410        );
411        assert_eq!(findings.len(), 1);
412        assert_eq!(findings[0].id, "bazaar.url");
413        assert_eq!(findings[0].severity, Severity::Unknown);
414        assert!(findings[0].message.contains("timeout"), "{findings:?}");
415        assert!(findings[0].fix.is_none());
416    }
417
418    /// Registering under a name another server has would replace that server.
419    #[test]
420    fn registration_never_takes_a_name_in_use() {
421        let name_offered = |taken: &[&str]| {
422            let entries = taken
423                .iter()
424                .map(|n| entry(n, "https://other.example.com/x", None, McpScope::User))
425                .collect();
426            match run(&fake(entries), Some(URL), &repo()).fix.unwrap().action {
427                FixAction::RunCommand { args, .. } => args[2].clone(),
428                other => panic!("{other:?}"),
429            }
430        };
431        assert_eq!(name_offered(&[]), "bazaar");
432        assert_eq!(name_offered(&["bazaar"]), "visdom-bazaar");
433        assert_eq!(
434            name_offered(&["bazaar", "visdom-bazaar"]),
435            "visdom-bazaar-2"
436        );
437    }
438
439    #[test]
440    fn entry_with_other_settings_is_not_replaced_automatically() {
441        let mut wrong = entry("bazaar", URL, None, McpScope::User);
442        wrong.extra_settings = true;
443        let finding = run(&fake(vec![wrong]), Some(URL), &repo());
444        assert_eq!(finding.severity, Severity::Error);
445        assert!(finding.fix.is_none());
446        assert!(finding.message.contains("by hand"), "{finding:?}");
447    }
448
449    #[test]
450    fn a_switched_off_entry_is_not_a_registration() {
451        let mut off = entry("bazaar", URL, Some(BAZAAR_CLIENT_ID), McpScope::User);
452        off.disabled = true;
453        let finding = run(&fake(vec![off.clone()]), Some(URL), &repo());
454        assert_eq!(finding.severity, Severity::Error);
455        assert!(finding.message.contains("switched off"), "{finding:?}");
456        assert!(finding.fix.is_none(), "re-adding would replace the entry");
457        // An enabled one beside it is what counts.
458        let on = entry("visdom", URL, Some(BAZAAR_CLIENT_ID), McpScope::User);
459        assert_eq!(
460            run(&fake(vec![off, on]), Some(URL), &repo()).severity,
461            Severity::Ok
462        );
463    }
464
465    /// Nothing that could read as an option reaches the agent's command line.
466    #[test]
467    fn only_a_plain_http_url_is_passed_to_the_agent_cli() {
468        for bad in [
469            "--header=X: y",
470            "-s",
471            "file:///etc/passwd",
472            "ctx.example.com/mcp",
473            "https://ctx.example.com/mcp --scope user",
474        ] {
475            let finding = run(&fake(vec![]), Some(bad), &repo());
476            assert_eq!(finding.id, "bazaar.url", "{bad}");
477            assert_eq!(finding.severity, Severity::Warn, "{bad}");
478            assert!(finding.fix.is_none(), "{bad}");
479        }
480        // An entry whose name would read as an option is not re-added.
481        let finding = run(
482            &fake(vec![entry("--scope", URL, None, McpScope::User)]),
483            Some(URL),
484            &repo(),
485        );
486        assert_eq!(finding.severity, Severity::Error);
487        assert!(finding.fix.is_none());
488    }
489
490    #[test]
491    fn entry_under_other_name_is_found() {
492        let adapter = fake(vec![entry(
493            "visdom",
494            "https://ctx.example.com/mcp",
495            Some(BAZAAR_CLIENT_ID),
496            McpScope::User,
497        )]);
498        let finding = run(&adapter, Some(URL), &repo());
499        assert_eq!(finding.severity, Severity::Ok);
500        assert!(finding.message.contains("`visdom`"), "{finding:?}");
501        assert!(finding.fix.is_none());
502    }
503
504    #[test]
505    fn wrong_client_id_offers_remove_then_add() {
506        for (client, scope, scope_name) in [
507            (None, McpScope::Local, "local"),
508            // A user-scope entry serves every project: it must not come back
509            // as a registration of this project only.
510            (Some("something-else"), McpScope::User, "user"),
511        ] {
512            let adapter = fake(vec![entry("visdom", URL, client, scope)]);
513            let finding = run(&adapter, Some(URL), &repo());
514            assert_eq!(finding.severity, Severity::Error);
515            assert!(finding.message.contains("403"), "{finding:?}");
516            let steps = match finding.fix.expect("a fix").action {
517                FixAction::Sequence { steps } => steps,
518                other => panic!("expected a sequence, got {other:?}"),
519            };
520            let args: Vec<Vec<String>> = steps
521                .iter()
522                .map(|s| match s {
523                    FixAction::RunCommand { args, .. } => args.clone(),
524                    other => panic!("{other:?}"),
525                })
526                .collect();
527            // Removed, then added back under the name it had.
528            assert_eq!(args[0], ["remove", "visdom"]);
529            assert_eq!(
530                args[1],
531                ["add", scope_name, "visdom", URL, BAZAAR_CLIENT_ID]
532            );
533        }
534    }
535
536    #[test]
537    fn a_correct_entry_wins_over_a_wrong_one() {
538        let adapter = fake(vec![
539            entry("old", URL, None, McpScope::User),
540            entry("bazaar", URL, Some(BAZAAR_CLIENT_ID), McpScope::Local),
541        ]);
542        assert_eq!(run(&adapter, Some(URL), &repo()).severity, Severity::Ok);
543    }
544
545    #[test]
546    fn wrong_client_id_in_committed_file_has_no_automatic_fix() {
547        let adapter = fake(vec![entry("bazaar", URL, None, McpScope::Project)]);
548        let finding = run(&adapter, Some(URL), &repo());
549        assert_eq!(finding.severity, Severity::Error);
550        assert!(finding.fix.is_none());
551        assert!(
552            finding.message.contains("file in the repository"),
553            "{finding:?}"
554        );
555    }
556
557    #[test]
558    fn adapter_error_is_unknown() {
559        let adapter = Fake {
560            entries: Err("cannot parse /home/u/.claude.json: eof".to_string()),
561        };
562        let finding = run(&adapter, Some(URL), &repo());
563        assert_eq!(finding.severity, Severity::Unknown);
564        assert!(finding.fix.is_none());
565        assert!(finding.message.contains(".claude.json"), "{finding:?}");
566    }
567
568    /// Outside a repository the agent still has a project (the directory it
569    /// starts in), so the registration is offered there.
570    #[test]
571    fn outside_a_repository_registration_is_offered_in_the_start_directory() {
572        let finding = run(&fake(vec![]), Some(URL), &Workdir::plain("/work/umbrella"));
573        assert_eq!(finding.severity, Severity::Error);
574        match finding.fix.expect("a fix").action {
575            FixAction::RunCommand { cwd, .. } => {
576                assert_eq!(cwd, Some(PathBuf::from("/work/umbrella")))
577            }
578            other => panic!("{other:?}"),
579        }
580    }
581
582    #[test]
583    fn url_precedence_env_user_server() {
584        let user = UserConfig {
585            bazaar_url: Some("https://user.example.com/mcp".to_string()),
586            ..Default::default()
587        };
588        let none = UserConfig::default();
589        let published: Result<SuiteMap, String> = Ok(SuiteMap {
590            bazaar_mcp_url: Some("https://srv.example.com/mcp/remote".to_string()),
591            ..SuiteMap::default()
592        });
593        let unreachable: Result<SuiteMap, String> = Err("tv.example.com: refused".to_string());
594        // The environment wins, whatever the server says or fails to say.
595        assert_eq!(
596            resolve_bazaar_url(
597                Some("https://env.example.com/mcp".to_string()),
598                &user,
599                &unreachable
600            )
601            .unwrap()
602            .as_deref(),
603            Some("https://env.example.com/mcp")
604        );
605        // An empty variable is unset; the user config is next.
606        assert_eq!(
607            resolve_bazaar_url(Some(" ".to_string()), &user, &unreachable)
608                .unwrap()
609                .as_deref(),
610            Some("https://user.example.com/mcp")
611        );
612        // Last, what the tracing server publishes.
613        assert_eq!(
614            resolve_bazaar_url(None, &none, &published)
615                .unwrap()
616                .as_deref(),
617            Some("https://srv.example.com/mcp/remote")
618        );
619        // A server that does not publish it does not know…
620        assert_eq!(
621            resolve_bazaar_url(None, &none, &Ok(SuiteMap::default())),
622            Ok(None)
623        );
624        // …one that could not be asked is an error with the reason.
625        assert_eq!(
626            resolve_bazaar_url(None, &none, &unreachable),
627            Err("tv.example.com: refused".to_string())
628        );
629    }
630}