blyte 0.88.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! CLI handlers for `blyte mcp list|add|remove|auth|logout`.

use std::collections::BTreeMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Duration;

use serde::Serialize;

use crate::cli::{McpAction, McpAddArgs, McpArgs};
use crate::mcp::client::McpClient;
use crate::mcp::config::{
    add_user_server, load_configured_servers, remove_user_server, trust_store_path,
    user_config_path, ConfiguredServer, EnvLookup, OAuthClientConfig, ServerConfig,
    ServerTransport, TransportKind,
};
use crate::mcp::oauth::{
    logout_server, prepare_oauth_flow_with_config, McpAuthStore, DEFAULT_CALLBACK_TIMEOUT,
    DEFAULT_OAUTH_HTTP_TIMEOUT,
};
use crate::mcp::protocol::McpError;

#[derive(Serialize)]
struct ListEntryJson<'a> {
    name: &'a str,
    transport: &'a str,
    target: String,
    source: &'a str,
    enabled: bool,
    approval: &'a str,
    trusted: bool,
}

/// Runs `blyte mcp <subcommand>` using standard I/O and default config paths.
pub fn run(args: &McpArgs) -> i32 {
    let mut out = std::io::stdout();
    let mut err = std::io::stderr();
    let user_path = match user_config_path() {
        Ok(p) => p,
        Err(e) => {
            let _ = writeln!(err, "error: {e}");
            return 1;
        }
    };
    let trust_path = match trust_store_path() {
        Ok(p) => p,
        Err(e) => {
            let _ = writeln!(err, "error: {e}");
            return 1;
        }
    };
    let auth_path = match McpAuthStore::default_path() {
        Ok(p) => p,
        Err(e) => {
            let _ = writeln!(err, "error: {e}");
            return 1;
        }
    };
    let cwd = std::env::current_dir().ok();
    let project_root = cwd.as_deref().and_then(find_project_root);
    run_with_all_paths(
        args,
        &user_path,
        project_root.as_deref(),
        &trust_path,
        &auth_path,
        &mut out,
        &mut err,
    )
}

/// Runs `blyte mcp <subcommand>` with explicit config/trust paths and output writers.
pub fn run_with_paths(
    args: &McpArgs,
    user_path: &Path,
    project_root: Option<&Path>,
    trust_path: &Path,
    out: &mut impl Write,
    err: &mut impl Write,
) -> i32 {
    let Some(parent) = user_path.parent() else {
        let _ = writeln!(
            err,
            "error: cannot determine parent directory for MCP config path '{}'",
            user_path.display()
        );
        return 1;
    };
    let auth_path = parent.join("mcp-auth.json");
    run_with_all_paths(
        args,
        user_path,
        project_root,
        trust_path,
        &auth_path,
        out,
        err,
    )
}

/// Runs `blyte mcp <subcommand>` with explicit config, trust, and OAuth auth-store paths.
pub fn run_with_all_paths(
    args: &McpArgs,
    user_path: &Path,
    project_root: Option<&Path>,
    trust_path: &Path,
    auth_path: &Path,
    out: &mut impl Write,
    err: &mut impl Write,
) -> i32 {
    match &args.action {
        McpAction::List { json } => run_list(user_path, project_root, trust_path, *json, out, err),
        McpAction::Add(add_args) => run_add(user_path, add_args, out, err),
        McpAction::Remove { name } => run_remove(user_path, name, out, err),
        McpAction::Auth { name, no_open } => run_auth(
            user_path,
            project_root,
            trust_path,
            auth_path,
            name,
            *no_open,
            DEFAULT_OAUTH_HTTP_TIMEOUT,
            DEFAULT_CALLBACK_TIMEOUT,
            None,
            out,
            err,
        ),
        McpAction::Logout { name } => run_logout(
            user_path,
            project_root,
            trust_path,
            auth_path,
            name,
            out,
            err,
        ),
    }
}

#[allow(clippy::too_many_arguments)]
pub fn run_auth(
    user_path: &Path,
    project_root: Option<&Path>,
    trust_path: &Path,
    auth_path: &Path,
    name: &str,
    no_open: bool,
    http_timeout: Duration,
    callback_timeout: Duration,
    on_authorize_url: Option<&dyn Fn(&str)>,
    out: &mut impl Write,
    err: &mut impl Write,
) -> i32 {
    let servers = match load_configured_servers(user_path, project_root, trust_path) {
        Ok(s) => s,
        Err(e) => {
            let _ = writeln!(err, "error: {e}");
            return 1;
        }
    };
    let Some(server) = servers.into_iter().find(|s| s.name == name) else {
        let _ = writeln!(err, "error: MCP server '{name}' not found");
        return 1;
    };
    if server.transport_kind != TransportKind::Http {
        let _ = writeln!(
            err,
            "error: MCP server '{name}' uses stdio transport; OAuth authentication is only supported for HTTP servers"
        );
        return 2;
    }
    if !server.trusted {
        let _ = writeln!(
            err,
            "error: MCP server '{name}' is an untrusted project server; trust it before authenticating"
        );
        return 1;
    }
    let lookup = match EnvLookup::from_system() {
        Ok(l) => l,
        Err(e) => {
            let _ = writeln!(err, "error: {e}");
            return 1;
        }
    };
    let server_url = match server.resolve_transport(&lookup) {
        Ok(ServerTransport::Http { url, .. }) => url,
        Ok(ServerTransport::Stdio { .. }) => {
            let _ = writeln!(
                err,
                "error: MCP server '{name}' uses stdio transport; OAuth authentication is only supported for HTTP servers"
            );
            return 2;
        }
        Err(e) => {
            let _ = writeln!(err, "error: {e}");
            return 1;
        }
    };

    let resolved_oauth = match server.resolve_oauth(&lookup) {
        Ok(o) => o,
        Err(e) => {
            let _ = writeln!(err, "error: {e}");
            return 1;
        }
    };

    let mut initial_www_authenticate = None;
    match McpClient::connect_server(&server, &lookup, None, http_timeout) {
        Ok((mut client, _)) => {
            if let Ok(tools) = client.list_tools() {
                let _ = writeln!(
                    out,
                    "MCP server '{name}' is already accessible without OAuth ({} tools discovered).",
                    tools.len()
                );
                return 0;
            }
        }
        Err(McpError::NeedsAuth {
            www_authenticate, ..
        }) => {
            initial_www_authenticate = www_authenticate;
        }
        Err(_) => {}
    }

    let pending = match prepare_oauth_flow_with_config(
        auth_path,
        name,
        &server_url,
        initial_www_authenticate.as_deref(),
        resolved_oauth.as_ref(),
        http_timeout,
    ) {
        Ok(p) => p,
        Err(e) => {
            let _ = writeln!(err, "error: failed to start OAuth flow for '{name}': {e}");
            return 1;
        }
    };

    let authorize_url = pending.authorize_url().to_string();
    let _ = writeln!(out, "Authorize MCP server '{name}' at:\n{authorize_url}");
    let _ = out.flush();

    if let Some(hook) = on_authorize_url {
        hook(&authorize_url);
    } else if !no_open {
        crate::open_window::open_url(crate::open_window::OpenIn::Browser, &authorize_url);
    }

    let stored = match pending.complete(callback_timeout) {
        Ok(s) => s,
        Err(e) => {
            let _ = writeln!(err, "error: OAuth authentication failed for '{name}': {e}");
            return 1;
        }
    };

    let Some(token) = stored.access_token else {
        let _ = writeln!(
            err,
            "error: OAuth authentication completed for '{name}' but did not return an access token"
        );
        return 1;
    };

    match McpClient::connect_server(&server, &lookup, Some(token), http_timeout) {
        Ok((mut client, _)) => match client.list_tools() {
            Ok(tools) => {
                let _ = writeln!(
                    out,
                    "authenticated MCP server '{name}' ({} tools discovered)",
                    tools.len()
                );
                0
            }
            Err(e) => {
                let _ = writeln!(
                    err,
                    "error: authenticated '{name}', but listing tools failed: {e}"
                );
                1
            }
        },
        Err(e) => {
            let _ = writeln!(
                err,
                "error: stored credentials for '{name}', but verifying connection failed: {e}"
            );
            1
        }
    }
}

fn run_logout(
    user_path: &Path,
    project_root: Option<&Path>,
    trust_path: &Path,
    auth_path: &Path,
    name: &str,
    out: &mut impl Write,
    err: &mut impl Write,
) -> i32 {
    let servers = match load_configured_servers(user_path, project_root, trust_path) {
        Ok(s) => s,
        Err(e) => {
            let _ = writeln!(err, "error: {e}");
            return 1;
        }
    };
    let Some(server) = servers.into_iter().find(|s| s.name == name) else {
        let _ = writeln!(err, "error: MCP server '{name}' not found");
        return 1;
    };
    if server.transport_kind != TransportKind::Http {
        let _ = writeln!(
            err,
            "error: MCP server '{name}' uses stdio transport and does not store OAuth credentials"
        );
        return 2;
    }
    match logout_server(auth_path, name) {
        Ok(true) => {
            let _ = writeln!(out, "cleared OAuth credentials for MCP server '{name}'");
            0
        }
        Ok(false) => {
            let _ = writeln!(
                out,
                "no stored OAuth credentials found for MCP server '{name}'"
            );
            0
        }
        Err(e) => {
            let _ = writeln!(err, "error: failed to clear OAuth credentials: {e}");
            1
        }
    }
}

fn find_project_root(cwd: &Path) -> Option<PathBuf> {
    for dir in cwd.ancestors() {
        if dir.join(".mcp.json").exists() {
            return Some(dir.to_path_buf());
        }
        if dir.join(".git").exists() {
            return Some(dir.to_path_buf());
        }
    }
    None
}

fn run_list(
    user_path: &Path,
    project_root: Option<&Path>,
    trust_path: &Path,
    json: bool,
    out: &mut impl Write,
    err: &mut impl Write,
) -> i32 {
    let servers = match load_configured_servers(user_path, project_root, trust_path) {
        Ok(s) => s,
        Err(e) => {
            let _ = writeln!(err, "error: {e}");
            return 1;
        }
    };

    if json {
        let entries: Vec<ListEntryJson<'_>> = servers
            .iter()
            .map(|s| ListEntryJson {
                name: &s.name,
                transport: s.transport_kind.as_str(),
                target: s.config.target_display(),
                source: s.source.as_str(),
                enabled: s.enabled,
                approval: s.approval.as_str(),
                trusted: s.trusted,
            })
            .collect();
        match serde_json::to_string_pretty(&entries) {
            Ok(rendered) => {
                let _ = writeln!(out, "{rendered}");
                return 0;
            }
            Err(e) => {
                let _ = writeln!(err, "error: failed to serialize server list: {e}");
                return 1;
            }
        }
    }

    if servers.is_empty() {
        let _ = writeln!(out, "No MCP servers configured.");
        return 0;
    }

    format_server_table(&servers, out);
    0
}

fn format_server_table(servers: &[ConfiguredServer], out: &mut impl Write) {
    let rows: Vec<[String; 5]> = servers
        .iter()
        .map(|s| {
            let transport_target = format!("{} {}", s.transport_kind, s.config.target_display());
            let source = if s.trusted {
                s.source.as_str().to_string()
            } else {
                format!("{} (untrusted)", s.source)
            };
            let state = if s.enabled { "enabled" } else { "disabled" }.to_string();
            [
                s.name.clone(),
                transport_target,
                source,
                state,
                s.approval.as_str().to_string(),
            ]
        })
        .collect();

    let headers = ["NAME", "TRANSPORT / TARGET", "SOURCE", "STATE", "APPROVAL"];
    let mut widths = [
        headers[0].len(),
        headers[1].len(),
        headers[2].len(),
        headers[3].len(),
        headers[4].len(),
    ];
    for row in &rows {
        for (i, col) in row.iter().enumerate() {
            widths[i] = widths[i].max(col.len());
        }
    }

    let _ = writeln!(
        out,
        "{:<w0$}  {:<w1$}  {:<w2$}  {:<w3$}  {}",
        headers[0],
        headers[1],
        headers[2],
        headers[3],
        headers[4],
        w0 = widths[0],
        w1 = widths[1],
        w2 = widths[2],
        w3 = widths[3],
    );
    for row in &rows {
        let _ = writeln!(
            out,
            "{:<w0$}  {:<w1$}  {:<w2$}  {:<w3$}  {}",
            row[0],
            row[1],
            row[2],
            row[3],
            row[4],
            w0 = widths[0],
            w1 = widths[1],
            w2 = widths[2],
            w3 = widths[3],
        );
    }
}

fn run_add(user_path: &Path, args: &McpAddArgs, out: &mut impl Write, err: &mut impl Write) -> i32 {
    let transport = args.transport.unwrap_or_else(|| {
        if args.target.starts_with("http://") || args.target.starts_with("https://") {
            TransportKind::Http
        } else {
            TransportKind::Stdio
        }
    });

    let config = match transport {
        TransportKind::Http => {
            if !args.env.is_empty() {
                let _ = writeln!(err, "error: --env can only be used with stdio servers");
                return 2;
            }
            if !args.args.is_empty() {
                let _ = writeln!(err, "error: trailing command arguments after `--` can only be used with stdio servers");
                return 2;
            }
            let headers = match parse_key_values(&args.headers, "header") {
                Ok(h) => h,
                Err(e) => {
                    let _ = writeln!(err, "error: {e}");
                    return 2;
                }
            };
            let mut cfg = ServerConfig::http(args.target.clone(), headers, args.approval);
            let scopes: Vec<String> = args
                .scopes
                .iter()
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            let oauth_candidate = OAuthClientConfig {
                client_id: args
                    .client_id
                    .as_deref()
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .map(str::to_string),
                client_secret: args
                    .client_secret
                    .as_deref()
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .map(str::to_string),
                callback_port: args.callback_port,
                scopes: if scopes.is_empty() {
                    None
                } else {
                    Some(scopes)
                },
            };
            if !oauth_candidate.is_empty() {
                cfg.oauth = Some(oauth_candidate);
            }
            cfg
        }
        TransportKind::Stdio => {
            if !args.headers.is_empty() {
                let _ = writeln!(err, "error: --header can only be used with http servers");
                return 2;
            }
            if args.client_id.is_some()
                || args.client_secret.is_some()
                || args.callback_port.is_some()
                || !args.scopes.is_empty()
            {
                let _ = writeln!(
                    err,
                    "error: --client-id, --client-secret, --callback-port, and --scope can only be used with http servers"
                );
                return 2;
            }
            let env = match parse_key_values(&args.env, "env") {
                Ok(e) => e,
                Err(e) => {
                    let _ = writeln!(err, "error: {e}");
                    return 2;
                }
            };
            ServerConfig::stdio(args.target.clone(), args.args.clone(), env, args.approval)
        }
    };

    if let Err(e) = add_user_server(user_path, &args.name, config, args.replace) {
        let _ = writeln!(err, "error: {e}");
        return 1;
    }

    let action = if args.replace { "saved" } else { "added" };
    let _ = writeln!(
        out,
        "{action} MCP server '{}' ({}) in {}",
        args.name,
        transport,
        user_path.display()
    );
    0
}

fn run_remove(user_path: &Path, name: &str, out: &mut impl Write, err: &mut impl Write) -> i32 {
    if let Err(e) = remove_user_server(user_path, name) {
        let _ = writeln!(err, "error: {e}");
        return 1;
    }
    let _ = writeln!(
        out,
        "removed MCP server '{}' from {}",
        name,
        user_path.display()
    );
    0
}

fn parse_key_values(items: &[String], label: &str) -> Result<BTreeMap<String, String>, String> {
    let mut map = BTreeMap::new();
    for item in items {
        let Some((raw_key, value)) = item.split_once('=') else {
            return Err(format!("invalid --{label} '{item}': expected KEY=VAL"));
        };
        let key = raw_key.trim();
        if key.is_empty() {
            return Err(format!("invalid --{label} '{item}': key cannot be empty"));
        }
        if key.chars().any(|c| c.is_whitespace()) {
            return Err(format!(
                "invalid --{label} '{item}': key cannot contain whitespace"
            ));
        }
        map.insert(key.to_string(), value.to_string());
    }
    Ok(map)
}

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

    #[test]
    fn run_with_paths_errors_when_user_config_path_has_no_parent() {
        let td = tempfile::tempdir().unwrap();
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run_with_paths(
            &McpArgs {
                action: McpAction::List { json: false },
            },
            Path::new("/"),
            None,
            &td.path().join("mcp-trust.json"),
            &mut out,
            &mut err,
        );
        assert_eq!(code, 1);
        let stderr = String::from_utf8_lossy(&err);
        assert!(
            stderr.contains("parent directory"),
            "expected parent directory error, got: {stderr}"
        );
    }
}