nodus 0.15.1

Local-first CLI for managing project-scoped agent packages.
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
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use toml::Value as TomlValue;

use crate::paths::display_path;
use crate::report::Reporter;

const SERVER_NAME: &str = "nodus";
const EXPECTED_COMMAND: &str = "nodus";
const EXPECTED_ARGS: [&str; 2] = ["mcp", "serve"];

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum McpStatusState {
    Configured,
    NotFound,
    MissingServer,
    Misconfigured,
    ParseError,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum McpOverallStatus {
    Healthy,
    NotConfigured,
    Broken,
}

#[derive(Debug, Clone, Serialize)]
pub struct McpCommandStatus {
    pub command: String,
    pub found_on_path: bool,
    pub resolved_path: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct McpConfigStatus {
    pub runtime: String,
    pub path: String,
    pub exists: bool,
    pub state: McpStatusState,
    pub message: String,
    pub observed_command: Option<Vec<String>>,
}

#[derive(Debug, Clone, Serialize)]
pub struct McpStatusSummary {
    pub overall_status: McpOverallStatus,
    pub configured_count: usize,
    pub issue_count: usize,
}

#[derive(Debug, Clone, Serialize)]
pub struct McpStatusReport {
    pub project_root: String,
    pub manifest_exists: bool,
    pub lockfile_exists: bool,
    pub command: McpCommandStatus,
    pub configs: Vec<McpConfigStatus>,
    pub summary: McpStatusSummary,
}

#[derive(Debug, Default, Deserialize)]
struct ProjectMcpConfig {
    #[serde(rename = "mcpServers", default)]
    mcp_servers: std::collections::BTreeMap<String, ProjectMcpServer>,
}

#[derive(Debug, Default, Deserialize)]
struct ProjectMcpServer {
    #[serde(default)]
    command: Option<String>,
    #[serde(default)]
    args: Vec<String>,
}

#[derive(Debug, Default, Deserialize)]
struct ProjectCodexConfig {
    #[serde(default)]
    mcp_servers: std::collections::BTreeMap<String, TomlValue>,
}

#[derive(Debug, Default, Deserialize)]
struct ProjectOpenCodeConfig {
    #[serde(rename = "mcp", default)]
    mcp_servers: std::collections::BTreeMap<String, JsonValue>,
}

pub fn inspect_status_in_dir(project_root: &Path) -> Result<McpStatusReport> {
    let command = command_status();
    let configs = vec![
        inspect_project_json(project_root)?,
        inspect_codex_config(project_root)?,
        inspect_opencode_config(project_root)?,
    ];
    let configured_count = configs
        .iter()
        .filter(|status| status.state == McpStatusState::Configured)
        .count();
    let issue_count = configs
        .iter()
        .filter(|status| {
            matches!(
                status.state,
                McpStatusState::MissingServer
                    | McpStatusState::Misconfigured
                    | McpStatusState::ParseError
            )
        })
        .count();
    let overall_status = if issue_count > 0 {
        McpOverallStatus::Broken
    } else if configured_count == 0 {
        McpOverallStatus::NotConfigured
    } else {
        McpOverallStatus::Healthy
    };

    Ok(McpStatusReport {
        project_root: display_path(project_root),
        manifest_exists: project_root.join("nodus.toml").exists(),
        lockfile_exists: project_root.join("nodus.lock").exists(),
        command,
        configs,
        summary: McpStatusSummary {
            overall_status,
            configured_count,
            issue_count,
        },
    })
}

pub fn render_status(report: &McpStatusReport, reporter: &Reporter) -> Result<()> {
    reporter.line(format!("Project root: {}", report.project_root))?;
    reporter.line(format!(
        "Manifest: {}",
        if report.manifest_exists {
            "present"
        } else {
            "missing"
        }
    ))?;
    reporter.line(format!(
        "Lockfile: {}",
        if report.lockfile_exists {
            "present"
        } else {
            "missing"
        }
    ))?;

    let command_status = if let Some(path) = &report.command.resolved_path {
        format!("{} ({path})", report.command.command)
    } else {
        format!("{} (not found on PATH)", report.command.command)
    };
    reporter.line(format!("PATH command: {command_status}"))?;

    for config in &report.configs {
        reporter.line(format!("{}: {}", config.path, render_config_state(config)))?;
    }

    if !report.command.found_on_path {
        reporter.note("the configured nodus command is not currently resolvable on PATH")?;
    }
    if report.summary.overall_status == McpOverallStatus::NotConfigured {
        if report.manifest_exists || report.lockfile_exists {
            reporter.note("no managed MCP config is present yet; run `nodus sync` to emit it")?;
        } else {
            reporter.note(
                "this directory does not look like a synced nodus project yet, so no MCP config is expected",
            )?;
        }
    }

    Ok(())
}

fn render_config_state(config: &McpConfigStatus) -> String {
    match &config.observed_command {
        Some(command) if !command.is_empty() => {
            format!("{} ({})", config.message, format_command(command))
        }
        _ => config.message.clone(),
    }
}

fn inspect_project_json(project_root: &Path) -> Result<McpConfigStatus> {
    let path = project_root.join(".mcp.json");
    let display = display_path(&path);
    if !path.exists() {
        return Ok(McpConfigStatus {
            runtime: "project".into(),
            path: display,
            exists: false,
            state: McpStatusState::NotFound,
            message: "not found".into(),
            observed_command: None,
        });
    }

    let contents =
        fs::read_to_string(&path).with_context(|| format!("failed to read {}", path.display()))?;
    let config: ProjectMcpConfig = match serde_json::from_str(&contents) {
        Ok(config) => config,
        Err(error) => {
            return Ok(McpConfigStatus {
                runtime: "project".into(),
                path: display,
                exists: true,
                state: McpStatusState::ParseError,
                message: format!("parse error: {error}"),
                observed_command: None,
            });
        }
    };

    let Some(server) = config.mcp_servers.get(SERVER_NAME) else {
        return Ok(McpConfigStatus {
            runtime: "project".into(),
            path: display,
            exists: true,
            state: McpStatusState::MissingServer,
            message: "missing `nodus` server entry".into(),
            observed_command: None,
        });
    };

    let observed = command_parts(server.command.as_deref(), &server.args);
    Ok(match observed.as_deref() {
        Some(command) if command_matches_project_command(command) => McpConfigStatus {
            runtime: "project".into(),
            path: display,
            exists: true,
            state: McpStatusState::Configured,
            message: "configured".into(),
            observed_command: Some(command.to_vec()),
        },
        Some(command) => McpConfigStatus {
            runtime: "project".into(),
            path: display,
            exists: true,
            state: McpStatusState::Misconfigured,
            message: "expected `nodus mcp serve`".into(),
            observed_command: Some(command.to_vec()),
        },
        None => McpConfigStatus {
            runtime: "project".into(),
            path: display,
            exists: true,
            state: McpStatusState::Misconfigured,
            message: "expected `nodus mcp serve`".into(),
            observed_command: None,
        },
    })
}

fn inspect_codex_config(project_root: &Path) -> Result<McpConfigStatus> {
    let path = project_root.join(".codex/config.toml");
    let display = display_path(&path);
    if !path.exists() {
        return Ok(McpConfigStatus {
            runtime: "codex".into(),
            path: display,
            exists: false,
            state: McpStatusState::NotFound,
            message: "not found".into(),
            observed_command: None,
        });
    }

    let contents =
        fs::read_to_string(&path).with_context(|| format!("failed to read {}", path.display()))?;
    let config: ProjectCodexConfig = match toml::from_str(&contents) {
        Ok(config) => config,
        Err(error) => {
            return Ok(McpConfigStatus {
                runtime: "codex".into(),
                path: display,
                exists: true,
                state: McpStatusState::ParseError,
                message: format!("parse error: {error}"),
                observed_command: None,
            });
        }
    };

    let Some(server) = config.mcp_servers.get(SERVER_NAME) else {
        return Ok(McpConfigStatus {
            runtime: "codex".into(),
            path: display,
            exists: true,
            state: McpStatusState::MissingServer,
            message: "missing `nodus` server entry".into(),
            observed_command: None,
        });
    };

    let observed = codex_command(server);
    Ok(match observed.as_deref() {
        Some(command) if command_matches_project_command(command) => McpConfigStatus {
            runtime: "codex".into(),
            path: display,
            exists: true,
            state: McpStatusState::Configured,
            message: "configured".into(),
            observed_command: Some(command.to_vec()),
        },
        Some(command) => McpConfigStatus {
            runtime: "codex".into(),
            path: display,
            exists: true,
            state: McpStatusState::Misconfigured,
            message: "expected `nodus mcp serve`".into(),
            observed_command: Some(command.to_vec()),
        },
        None => McpConfigStatus {
            runtime: "codex".into(),
            path: display,
            exists: true,
            state: McpStatusState::Misconfigured,
            message: "expected `nodus mcp serve`".into(),
            observed_command: None,
        },
    })
}

fn inspect_opencode_config(project_root: &Path) -> Result<McpConfigStatus> {
    let path = project_root.join("opencode.json");
    let display = display_path(&path);
    if !path.exists() {
        return Ok(McpConfigStatus {
            runtime: "opencode".into(),
            path: display,
            exists: false,
            state: McpStatusState::NotFound,
            message: "not found".into(),
            observed_command: None,
        });
    }

    let contents =
        fs::read_to_string(&path).with_context(|| format!("failed to read {}", path.display()))?;
    let config: ProjectOpenCodeConfig = match serde_json::from_str(&contents) {
        Ok(config) => config,
        Err(error) => {
            return Ok(McpConfigStatus {
                runtime: "opencode".into(),
                path: display,
                exists: true,
                state: McpStatusState::ParseError,
                message: format!("parse error: {error}"),
                observed_command: None,
            });
        }
    };

    let Some(server) = config.mcp_servers.get(SERVER_NAME) else {
        return Ok(McpConfigStatus {
            runtime: "opencode".into(),
            path: display,
            exists: true,
            state: McpStatusState::MissingServer,
            message: "missing `nodus` server entry".into(),
            observed_command: None,
        });
    };

    let observed = opencode_command(server);
    Ok(match observed.as_deref() {
        Some(command) if command_matches_project_command(command) => McpConfigStatus {
            runtime: "opencode".into(),
            path: display,
            exists: true,
            state: McpStatusState::Configured,
            message: "configured".into(),
            observed_command: Some(command.to_vec()),
        },
        Some(command) => McpConfigStatus {
            runtime: "opencode".into(),
            path: display,
            exists: true,
            state: McpStatusState::Misconfigured,
            message: "expected `nodus mcp serve`".into(),
            observed_command: Some(command.to_vec()),
        },
        None => McpConfigStatus {
            runtime: "opencode".into(),
            path: display,
            exists: true,
            state: McpStatusState::Misconfigured,
            message: "expected `nodus mcp serve`".into(),
            observed_command: None,
        },
    })
}

fn command_status() -> McpCommandStatus {
    let resolved = resolve_command_on_path(EXPECTED_COMMAND);
    McpCommandStatus {
        command: EXPECTED_COMMAND.into(),
        found_on_path: resolved.is_some(),
        resolved_path: resolved.as_deref().map(display_path),
    }
}

fn command_parts(command: Option<&str>, args: &[String]) -> Option<Vec<String>> {
    let command = command?.trim();
    if command.is_empty() {
        return None;
    }

    Some(
        std::iter::once(command.to_string())
            .chain(args.iter().cloned())
            .collect(),
    )
}

fn codex_command(value: &TomlValue) -> Option<Vec<String>> {
    let table = value.as_table()?;
    let command = table.get("command")?.as_str()?.trim();
    if command.is_empty() {
        return None;
    }

    let mut observed = vec![command.to_string()];
    let args = match table.get("args") {
        Some(value) => value
            .as_array()?
            .iter()
            .map(TomlValue::as_str)
            .collect::<Option<Vec<_>>>()?,
        None => Vec::new(),
    };
    observed.extend(args.into_iter().map(ToOwned::to_owned));
    Some(observed)
}

fn opencode_command(value: &JsonValue) -> Option<Vec<String>> {
    let object = value.as_object()?;
    if object.get("type").and_then(JsonValue::as_str) != Some("local") {
        return None;
    }
    object
        .get("command")?
        .as_array()?
        .iter()
        .map(JsonValue::as_str)
        .collect::<Option<Vec<_>>>()
        .map(|parts| parts.into_iter().map(ToOwned::to_owned).collect())
}

fn command_matches_project_command(command: &[String]) -> bool {
    let Some((binary, args)) = command.split_first() else {
        return false;
    };
    if !binary_looks_like_nodus(binary) {
        return false;
    }
    normalized_server_args(args)
        .is_some_and(|args| args.iter().copied().eq(EXPECTED_ARGS.iter().copied()))
}

fn binary_looks_like_nodus(command: &str) -> bool {
    Path::new(command)
        .file_name()
        .and_then(|value| value.to_str())
        .is_some_and(|value| value == "nodus" || value.starts_with("nodus-"))
}

fn normalized_server_args(args: &[String]) -> Option<Vec<&str>> {
    let args = args.iter().map(String::as_str).collect::<Vec<_>>();
    match args.as_slice() {
        ["--store-path", store_path, rest @ ..] if !store_path.is_empty() => Some(rest.to_vec()),
        rest => Some(rest.to_vec()),
    }
}

fn format_command(command: &[String]) -> String {
    command.join(" ")
}

fn resolve_command_on_path(command: &str) -> Option<PathBuf> {
    let path_var = env::var_os("PATH")?;
    for directory in env::split_paths(&path_var) {
        for candidate in executable_candidates(directory.join(command)) {
            if candidate.is_file() {
                return Some(candidate);
            }
        }
    }
    None
}

#[cfg(not(windows))]
fn executable_candidates(path: PathBuf) -> Vec<PathBuf> {
    vec![path]
}

#[cfg(windows)]
fn executable_candidates(path: PathBuf) -> Vec<PathBuf> {
    use std::ffi::OsString;

    if path.extension().is_some() {
        return vec![path];
    }

    let pathext = env::var_os("PATHEXT").unwrap_or_else(|| OsString::from(".COM;.EXE;.BAT;.CMD"));
    let extensions = pathext
        .to_string_lossy()
        .split(';')
        .filter_map(|value| {
            let trimmed = value.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.trim_start_matches('.').to_string())
            }
        })
        .collect::<Vec<_>>();

    let mut candidates = vec![path.clone()];
    for extension in extensions {
        candidates.push(path.with_extension(extension));
    }
    candidates
}

#[cfg(test)]
mod tests {
    use std::fs;

    use tempfile::TempDir;

    use super::*;

    #[test]
    fn reports_configured_project_json_entry() {
        let temp = TempDir::new().unwrap();
        fs::write(
            temp.path().join(".mcp.json"),
            format!(
                r#"{{"mcpServers":{{"nodus":{{"command":"{}","args":["mcp","serve"]}}}}}}"#,
                display_path(&env::current_exe().unwrap())
            ),
        )
        .unwrap();

        let status = inspect_project_json(temp.path()).unwrap();
        assert_eq!(status.state, McpStatusState::Configured);
        assert!(status.observed_command.unwrap()[0].contains("nodus"));
    }

    #[test]
    fn reports_plain_nodus_project_json_entry_as_configured() {
        let temp = TempDir::new().unwrap();
        fs::write(
            temp.path().join(".mcp.json"),
            r#"{"mcpServers":{"nodus":{"command":"nodus","args":["mcp","serve"]}}}"#,
        )
        .unwrap();

        let status = inspect_project_json(temp.path()).unwrap();
        assert_eq!(status.state, McpStatusState::Configured);
    }

    #[test]
    fn reports_misconfigured_opencode_entry() {
        let temp = TempDir::new().unwrap();
        fs::write(
            temp.path().join("opencode.json"),
            r#"{"mcp":{"nodus":{"type":"local","command":["cargo","run"]}}}"#,
        )
        .unwrap();

        let status = inspect_opencode_config(temp.path()).unwrap();
        assert_eq!(status.state, McpStatusState::Misconfigured);
        assert_eq!(
            status.observed_command,
            Some(vec!["cargo".into(), "run".into()])
        );
    }
}