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