mermaid-cli 0.12.0

Open-source AI pair programmer with agentic capabilities. Local-first with Ollama, native tool calling, and beautiful TUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! Built-in MCP server registry and resolution chain.
//!
//! Resolution order:
//! A) Built-in registry — instant, offline, covers popular servers
//! B) Convention-based — try common npm package naming patterns
//! C) npm registry search — network lookup for unknown servers
//!
//! Entries may target either npm (`command: "npx"`, runs via
//! `npx -y <package>`) or PyPI (`command: "uvx"`, runs via
//! `uvx <package>`). Verify each entry against the appropriate
//! registry before releases:
//!
//! ```text
//! npm view <pkg> version deprecated
//! pip index versions <pkg>
//! ```
//!
//! These entries are load-bearing for the `mermaid add <name>` UX —
//! a stale or 404 package here produces a confusing first-run error.

use anyhow::{Result, anyhow, bail};
use std::collections::HashMap;
use std::io::{self, IsTerminal, Write};
use std::time::Duration;

use super::client::McpClient;
use super::transport::StdioTransport;
use crate::utils::{is_affirmative, should_refuse_noninteractive};

/// A resolved MCP server ready for configuration
pub struct ResolvedServer {
    /// Launcher command: "npx" (npm packages) or "uvx" (Python packages).
    pub command: String,
    pub package: String,
    pub env_vars: Vec<(String, String)>, // (name, description)
    pub extra_args: Vec<String>,
}

/// Built-in registry entry
struct RegistryEntry {
    name: &'static str,
    /// Launcher command: "npx" (npm) or "uvx" (PyPI).
    command: &'static str,
    package: &'static str,
    description: &'static str,
    env_vars: &'static [(&'static str, &'static str)],
    extra_args: &'static [&'static str],
}

/// The built-in registry of popular MCP servers.
///
/// Last npm/PyPI verification: 2026-04-16. TODO: re-verify quarterly —
/// stale/deprecated packages produce confusing `mermaid add` errors.
const REGISTRY: &[RegistryEntry] = &[
    RegistryEntry {
        name: "context7",
        command: "npx",
        package: "@upstash/context7-mcp",
        description: "Up-to-date library documentation and code examples",
        env_vars: &[],
        extra_args: &[],
    },
    RegistryEntry {
        name: "filesystem",
        command: "npx",
        package: "@modelcontextprotocol/server-filesystem",
        description: "Secure file operations with configurable access",
        env_vars: &[],
        extra_args: &["."],
    },
    RegistryEntry {
        name: "memory",
        command: "npx",
        package: "@modelcontextprotocol/server-memory",
        description: "Persistent memory via knowledge graph",
        env_vars: &[],
        extra_args: &[],
    },
    // Python-based MCP reference servers — published to PyPI, launched via uvx.
    RegistryEntry {
        name: "fetch",
        command: "uvx",
        package: "mcp-server-fetch",
        description: "Web content fetching and conversion (PyPI, uvx)",
        env_vars: &[],
        extra_args: &[],
    },
    RegistryEntry {
        name: "git",
        command: "uvx",
        package: "mcp-server-git",
        description: "Git repository tools — log, diff, status, blame (PyPI, uvx)",
        env_vars: &[],
        extra_args: &[],
    },
    RegistryEntry {
        name: "time",
        command: "uvx",
        package: "mcp-server-time",
        description: "Time and timezone conversion (PyPI, uvx)",
        env_vars: &[],
        extra_args: &[],
    },
    RegistryEntry {
        name: "playwright",
        command: "npx",
        package: "@playwright/mcp",
        description: "Browser automation and testing",
        env_vars: &[],
        extra_args: &[],
    },
    RegistryEntry {
        name: "notion",
        command: "npx",
        package: "@notionhq/notion-mcp-server",
        description: "Notion workspace — pages, databases, tasks",
        env_vars: &[("NOTION_API_KEY", "Notion API integration token")],
        extra_args: &[],
    },
    RegistryEntry {
        name: "slack",
        // @modelcontextprotocol/server-slack was deprecated 2026-02.
        // Maintenance handed off to Zencoder per upstream README.
        command: "npx",
        package: "@zencoderai/slack-mcp-server",
        description: "Slack messaging and channel management (maintained by Zencoder; handoff from deprecated @modelcontextprotocol/server-slack)",
        env_vars: &[
            ("SLACK_BOT_TOKEN", "Slack bot token (xoxb-...)"),
            ("SLACK_TEAM_ID", "Slack workspace/team ID"),
        ],
        extra_args: &[],
    },
    RegistryEntry {
        name: "postgres",
        // @modelcontextprotocol/server-postgres was archived 2026-02
        // with no official successor. crystaldba/postgres-mcp is the
        // most-cited community replacement (PyPI, uvx). Env var renamed
        // `DATABASE_URL` → `DATABASE_URI` per crystaldba convention.
        command: "uvx",
        package: "postgres-mcp",
        description: "PostgreSQL queries (community, crystaldba): RW access, EXPLAIN, index tuning, health checks",
        env_vars: &[(
            "DATABASE_URI",
            "PostgreSQL connection string (e.g., postgresql://user:pass@localhost:5432/db)",
        )],
        extra_args: &[],
    },
    RegistryEntry {
        name: "sequential-thinking",
        command: "npx",
        package: "@modelcontextprotocol/server-sequential-thinking",
        description: "Dynamic problem-solving through thought sequences",
        env_vars: &[],
        extra_args: &[],
    },
    RegistryEntry {
        name: "brave-search",
        // @modelcontextprotocol/server-brave-search was deprecated 2026-02.
        // Brave now publishes the official server themselves. Requires
        // `--transport stdio` flag (package supports multiple transports;
        // we always want stdio for our launcher pattern).
        command: "npx",
        package: "@brave/brave-search-mcp-server",
        description: "Brave Search (official, brave-maintained): web, local, image, video, news, AI summary",
        env_vars: &[(
            "BRAVE_API_KEY",
            "Brave Search API key (https://brave.com/search/api/)",
        )],
        extra_args: &["--transport", "stdio"],
    },
    RegistryEntry {
        name: "everything",
        command: "npx",
        package: "@modelcontextprotocol/server-everything",
        description: "Reference/test server with all MCP features",
        env_vars: &[],
        extra_args: &[],
    },
    RegistryEntry {
        name: "supabase",
        command: "npx",
        package: "@supabase/mcp-server-supabase",
        description: "Supabase — database, auth, edge functions",
        env_vars: &[
            ("SUPABASE_URL", "Supabase project URL"),
            ("SUPABASE_SERVICE_ROLE_KEY", "Supabase service role key"),
        ],
        extra_args: &[],
    },
    RegistryEntry {
        name: "perplexity",
        command: "npx",
        package: "perplexity-mcp",
        description: "Perplexity AI search API",
        env_vars: &[("PERPLEXITY_API_KEY", "Perplexity API key")],
        extra_args: &[],
    },
    RegistryEntry {
        name: "docker",
        command: "npx",
        package: "mcp-server-docker",
        description: "Docker container management (community)",
        env_vars: &[],
        extra_args: &[],
    },
    // Note: the official GitHub MCP server is distributed as a Go binary
    // (github.com/github/github-mcp-server), not an npm or PyPI package.
    // The previous @modelcontextprotocol/server-github npm package is
    // deprecated. Users who want GitHub MCP should install the Go binary
    // manually and add a custom entry to config.toml.
];

/// Step A: Look up in the built-in registry
fn lookup(name: &str) -> Option<&'static RegistryEntry> {
    REGISTRY.iter().find(|e| e.name == name)
}

/// Build the arg vector for a launcher command + package.
///
/// - `npx` uses `["-y", <package>, ...extra_args]` (auto-installs).
/// - `uvx` uses `[<package>, ...extra_args]` (no `-y` flag).
fn build_launch_args(command: &str, package: &str, extra_args: &[String]) -> Vec<String> {
    let mut args = match command {
        "npx" => vec!["-y".to_string(), package.to_string()],
        _ => vec![package.to_string()], // uvx and any other launcher
    };
    args.extend_from_slice(extra_args);
    args
}

/// Validate an MCP server by spawning it, initializing, and listing tools.
/// Returns tool names on success. Kills the process after validation.
pub async fn validate_server(
    command: &str,
    package: &str,
    extra_args: &[String],
    env: &HashMap<String, String>,
) -> Result<Vec<String>> {
    let args = build_launch_args(command, package, extra_args);

    let transport = tokio::time::timeout(
        Duration::from_secs(60),
        StdioTransport::spawn(command, &args, env),
    )
    .await
    .map_err(|_| {
        anyhow!(
            "Server startup timed out (60s). Is {} installed?",
            match command {
                "npx" => "Node.js/npx",
                "uvx" => "uv/uvx",
                other => other,
            }
        )
    })?
    .map_err(|e| anyhow!("Failed to spawn server: {}", e))?;

    let mut client = McpClient::new(transport);

    tokio::time::timeout(Duration::from_secs(60), async {
        client.initialize().await?;
        let tools = client.list_tools().await?;
        let tool_names: Vec<String> = tools.iter().map(|t| t.name.clone()).collect();
        client.shutdown().await;
        Ok::<Vec<String>, anyhow::Error>(tool_names)
    })
    .await
    .map_err(|_| anyhow!("Server initialization timed out (60s)"))?
}

/// The npm package-name conventions tried for an unknown server name. Pure (no
/// I/O) so the set and ordering are unit-tested.
fn convention_patterns(name: &str) -> Vec<String> {
    vec![
        format!("@{}/mcp-server", name),
        format!("{}-mcp-server", name),
        format!("@modelcontextprotocol/server-{}", name),
        format!("{}-mcp", name),
    ]
}

/// Check whether an npm package *exists* via a registry metadata lookup —
/// WITHOUT executing it. This is the #10 fix: the old code probed convention
/// names by running `npx -y <guess>`, so a typosquatted guess executed before
/// any confirmation. A metadata GET never runs the package.
async fn npm_package_exists(client: &reqwest::Client, package: &str) -> Result<bool> {
    // Scoped names (`@scope/name`) must percent-encode the slash for the
    // packument path.
    let encoded = package.replace('/', "%2F");
    let url = format!("https://registry.npmjs.org/{}", encoded);
    let response = client
        .get(&url)
        // Abbreviated packument — we only inspect the status code.
        .header("Accept", "application/vnd.npm.install-v1+json")
        .send()
        .await
        .map_err(|e| anyhow!("npm registry lookup failed (network unavailable?): {}", e))?;
    match response.status() {
        reqwest::StatusCode::OK => Ok(true),
        reqwest::StatusCode::NOT_FOUND => Ok(false),
        other => Err(anyhow!(
            "npm registry returned HTTP {} for '{}'",
            other,
            package
        )),
    }
}

/// Step B: probe convention-based npm names for *existence* (a metadata
/// lookup), NOT by spawning them (the #10 RCE). Returns the first that exists.
async fn try_conventions(client: &reqwest::Client, name: &str) -> Option<String> {
    for pattern in convention_patterns(name) {
        println!("  Checking npm for {}...", pattern);
        if npm_package_exists(client, &pattern).await.unwrap_or(false) {
            return Some(pattern);
        }
    }
    None
}

/// Confirm (default NO) before fetching+running a package that is NOT in the
/// trusted built-in registry — the #10 gate. `assume_yes` (`--yes`) is an
/// explicit opt-in for scripted use; without it a non-interactive session
/// refuses rather than silently running untrusted code.
fn confirm_untrusted_package(package: &str, command: &str, assume_yes: bool) -> Result<bool> {
    if assume_yes {
        return Ok(true);
    }
    if should_refuse_noninteractive(io::stdin().is_terminal(), assume_yes) {
        bail!(
            "Refusing to fetch and run untrusted package '{package}' via `{command} -y {package}` \
             non-interactively — it is not in Mermaid's trusted registry, and a typosquatted \
             package could run arbitrary code. Re-run in an interactive terminal to confirm, or \
             pass --yes to allow it."
        );
    }
    print!(
        "About to fetch and run UNTRUSTED package '{package}' via `{command} -y {package}`.\n\
         It is not in Mermaid's trusted registry; a typosquatted package could run arbitrary \
         code. Continue? [y/N]: "
    );
    io::stdout().flush()?;
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    Ok(is_affirmative(input.trim()))
}

/// Step C: Search npm registry for MCP server packages.
///
/// Query-param encoding is handled by `reqwest::Url::parse_with_params`,
/// which delegates to the `url` crate's RFC-3986 form-urlencoded
/// serializer. No hand-rolled escaping — special characters in `name`
/// (%, &, =, UTF-8, …) are all handled correctly.
async fn search_npm(client: &reqwest::Client, name: &str) -> Result<Option<(String, String)>> {
    let query = format!("{} mcp server", name);

    let url = reqwest::Url::parse_with_params(
        "https://registry.npmjs.org/-/v1/search",
        &[("text", query.as_str()), ("size", "5")],
    )
    .map_err(|e| anyhow!("Failed to build npm search URL: {}", e))?;

    let response = client
        .get(url)
        .send()
        .await
        .map_err(|e| anyhow!("npm registry search failed (network unavailable?): {}", e))?;

    if !response.status().is_success() {
        return Err(anyhow!("npm registry returned HTTP {}", response.status()));
    }

    let body: serde_json::Value = response.json().await?;
    let objects = body
        .get("objects")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();

    for obj in &objects {
        let pkg_name = obj
            .pointer("/package/name")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let description = obj
            .pointer("/package/description")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let keywords = obj
            .pointer("/package/keywords")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|k| k.as_str())
                    .collect::<Vec<_>>()
                    .join(" ")
            })
            .unwrap_or_default();

        // Check if this looks like an MCP server
        let combined = format!("{} {} {}", pkg_name, description, keywords).to_lowercase();
        if combined.contains("mcp") {
            return Ok(Some((pkg_name.to_string(), description.to_string())));
        }
    }

    Ok(None)
}

/// Resolve an MCP server name to a ready-to-configure server.
/// Tries: A (built-in registry, trusted) → B (npm convention names) →
/// C (npm search). Any non-registry result must be confirmed before it is
/// returned, because configuring it leads to executing it via `npx -y` (#10).
/// `assume_yes` (from `--yes`) is an explicit opt-in for non-interactive use.
pub async fn resolve(name: &str, assume_yes: bool) -> Result<ResolvedServer> {
    // Step A: Built-in registry — curated/trusted, no confirmation needed.
    if let Some(entry) = lookup(name) {
        println!("Found: {} ({})", entry.package, entry.description);
        return Ok(ResolvedServer {
            command: entry.command.to_string(),
            package: entry.package.to_string(),
            env_vars: entry
                .env_vars
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            extra_args: entry.extra_args.iter().map(|s| s.to_string()).collect(),
        });
    }

    println!("Not in built-in registry, trying conventions...");

    // One HTTP client shared by the existence check (B) and the search (C).
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(10))
        .build()?;

    // Step B: convention names — existence check only (no spawn), then confirm.
    if let Some(package) = try_conventions(&client, name).await {
        println!("Found: {}", package);
        if !confirm_untrusted_package(&package, "npx", assume_yes)? {
            bail!(
                "Cancelled: did not confirm running untrusted package '{}'.",
                package
            );
        }
        return Ok(ResolvedServer {
            command: "npx".to_string(),
            package,
            env_vars: Vec::new(),
            extra_args: Vec::new(),
        });
    }

    println!("Searching npm registry...");

    // Step C: npm search — HTTP only (safe). Confirm before returning; the
    // package is validated (executed) exactly once afterwards, by `add_server`.
    match search_npm(&client, name).await {
        Ok(Some((package, description))) => {
            println!("Found: {}{}", package, description);
            if !confirm_untrusted_package(&package, "npx", assume_yes)? {
                bail!(
                    "Cancelled: did not confirm running untrusted package '{}'.",
                    package
                );
            }
            Ok(ResolvedServer {
                command: "npx".to_string(),
                package,
                env_vars: Vec::new(),
                extra_args: Vec::new(),
            })
        },
        Ok(None) => Err(anyhow!(
            "Could not find MCP server '{}'\n\n\
            You can add it manually in ~/.config/mermaid/config.toml:\n\
            [mcp_servers.{}]\n\
            command = \"npx\"\n\
            args = [\"-y\", \"PACKAGE_NAME\"]",
            name,
            name
        )),
        Err(e) => Err(anyhow!(
            "Convention-based lookup failed, and npm search also failed: {}\n\n\
            You can add it manually in ~/.config/mermaid/config.toml:\n\
            [mcp_servers.{}]\n\
            command = \"npx\"\n\
            args = [\"-y\", \"PACKAGE_NAME\"]",
            e,
            name
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Every registry entry must use a supported launcher and have a
    /// non-empty package. Guards against typo-level regressions when
    /// adding / updating entries.
    #[test]
    fn registry_entries_are_well_formed() {
        assert!(!REGISTRY.is_empty(), "registry must not be empty");
        for entry in REGISTRY {
            assert!(
                matches!(entry.command, "npx" | "uvx"),
                "entry {:?} has unsupported launcher {:?}",
                entry.name,
                entry.command
            );
            assert!(
                !entry.package.is_empty(),
                "entry {:?} has empty package",
                entry.name
            );
            assert!(
                !entry.name.is_empty(),
                "registry entry has empty name (package: {:?})",
                entry.package
            );
        }
    }

    /// Regression guard: no deprecated modelcontextprotocol npm packages
    /// should remain in the registry. @modelcontextprotocol/server-slack,
    /// -postgres, -brave-search were all deprecated upstream in 2026-02.
    #[test]
    fn registry_does_not_reference_deprecated_modelcontextprotocol_packages() {
        let deprecated = [
            "@modelcontextprotocol/server-slack",
            "@modelcontextprotocol/server-postgres",
            "@modelcontextprotocol/server-brave-search",
            "@modelcontextprotocol/server-github",
        ];
        for entry in REGISTRY {
            for pkg in &deprecated {
                assert_ne!(
                    entry.package, *pkg,
                    "registry entry {:?} still references deprecated package {}",
                    entry.name, pkg
                );
            }
        }
    }

    #[test]
    fn lookup_resolves_replacement_packages() {
        // Sanity: the three replacement entries land where expected.
        assert_eq!(
            lookup("slack").unwrap().package,
            "@zencoderai/slack-mcp-server"
        );
        assert_eq!(lookup("postgres").unwrap().package, "postgres-mcp");
        assert_eq!(lookup("postgres").unwrap().command, "uvx");
        assert_eq!(
            lookup("brave-search").unwrap().package,
            "@brave/brave-search-mcp-server"
        );
        assert_eq!(
            lookup("brave-search").unwrap().extra_args,
            &["--transport", "stdio"]
        );
    }

    #[test]
    fn convention_patterns_are_exact_and_ordered() {
        assert_eq!(
            convention_patterns("foo"),
            vec![
                "@foo/mcp-server".to_string(),
                "foo-mcp-server".to_string(),
                "@modelcontextprotocol/server-foo".to_string(),
                "foo-mcp".to_string(),
            ]
        );
    }

    #[test]
    fn assume_yes_confirms_without_io() {
        // --yes short-circuits before any TTY check / stdin read, so it never
        // blocks. (The assume_yes=false path is NOT exercised here: under a TTY
        // it would block on stdin.read_line.)
        assert!(confirm_untrusted_package("evil-pkg", "npx", true).unwrap());
    }

    #[tokio::test]
    async fn resolve_registry_name_needs_no_network_or_confirmation() {
        // A trusted built-in entry resolves via lookup() alone — no HTTP, no
        // prompt — so the untrusted-package gate never fires for curated entries.
        let resolved = resolve("context7", false).await.expect("registry resolve");
        assert_eq!(resolved.command, "npx");
        assert_eq!(resolved.package, "@upstash/context7-mcp");
    }
}