noyalib-mcp 0.0.29

Model Context Protocol server exposing noyalib's lossless YAML editing to AI agents
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
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 Noyalib. All rights reserved.

//! Tool registry for the MCP server.
//!
//! Each entry in [`descriptors`] is the JSON Schema that a client
//! sees from `tools/list`; [`call`] is the dispatch entry point for
//! `tools/call`. Tools delegate the actual YAML work to noyalib's
//! `cst::Document` so edits round-trip with comments, indentation,
//! and sibling entries preserved byte-for-byte.

use noyalib::cst::{parse_document, parse_stream};
use serde_json::{Value as JsonValue, json};
use std::fs;

/// Descriptors returned to MCP clients via `tools/list`.
pub fn descriptors() -> Vec<JsonValue> {
    vec![
        json!({
            "name": "noyalib_get",
            "title": "Read a YAML value (lossless)",
            // Reads a caller-supplied YAML file without modifying it:
            // read-only, idempotent, never destructive, and open-world
            // (it touches the local filesystem). These MCP annotations let
            // clients and the Glama quality grader reason about safety and
            // auto-approval without executing the tool.
            "annotations": {
                "title": "Read a YAML value (lossless)",
                "readOnlyHint": true,
                "destructiveHint": false,
                "idempotentHint": true,
                "openWorldHint": true
            },
            "description": "Read the YAML value at a dotted/indexed path \
                in the given file and return the source slice exactly — no \
                re-quoting, no canonicalisation, comments and formatting \
                preserved. Use this to inspect a value before changing it; \
                use `noyalib_set` to write a value back losslessly.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "file": {
                        "type": "string",
                        "description": "Path to the YAML file on disk."
                    },
                    "path": {
                        "type": "string",
                        "description": "Dotted/indexed path into the YAML, \
                            e.g. `server.host` or `items[0].name`."
                    }
                },
                "required": ["file", "path"]
            }
        }),
        json!({
            "name": "noyalib_set",
            "title": "Write a YAML value (lossless)",
            // Overwrites the value at a path in a caller-supplied file on
            // disk: NOT read-only, and destructive (it replaces existing
            // content in place). Re-running with the same arguments yields
            // the same file state, so it is idempotent; it touches the
            // filesystem, so it is open-world.
            "annotations": {
                "title": "Write a YAML value (lossless)",
                "readOnlyHint": false,
                "destructiveHint": true,
                "idempotentHint": true,
                "openWorldHint": true
            },
            "description": "Set the YAML value at a dotted/indexed path in \
                the given file, rewriting only the touched span so every \
                comment, blank line, and sibling entry is preserved \
                byte-for-byte (written atomically). Use this for \
                Renovate-style version bumps and config patches; use \
                `noyalib_get` first when you need to read the current \
                value. On a parse error the document is left unchanged.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "file": {
                        "type": "string",
                        "description": "Path to the YAML file on disk."
                    },
                    "path": {
                        "type": "string",
                        "description": "Dotted/indexed path into the YAML."
                    },
                    "value": {
                        "type": "string",
                        "description": "Replacement value as a YAML \
                            fragment (e.g. `0.0.2`, `\\\"hello\\\"`, \
                            `[1, 2, 3]`). Must parse in the target \
                            position; the document is left unchanged on \
                            parse error."
                    }
                },
                "required": ["file", "path", "value"]
            }
        }),
        json!({
            "name": "noyalib_set_multidoc",
            "title": "Write a YAML value in one document of a multi-doc stream (lossless)",
            // Same write semantics as noyalib_set, but targets one
            // document of a `---`-separated multi-document YAML stream by
            // index: not read-only, destructive (replaces content in
            // place), idempotent, and open-world (touches the filesystem).
            "annotations": {
                "title": "Write a YAML value in one document of a multi-doc stream (lossless)",
                "readOnlyHint": false,
                "destructiveHint": true,
                "idempotentHint": true,
                "openWorldHint": true
            },
            "description": "Set the YAML value at a dotted/indexed path within \
                a single document of a multi-document (`---`-separated) YAML \
                stream, selected by zero-based document index. Only the touched \
                span of that one document is rewritten; every other document, \
                comment, blank line and separator is preserved byte-for-byte \
                (written atomically). Use `noyalib_set` for a single-document \
                file. On a parse error or out-of-range index the file is left \
                unchanged.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "file": {
                        "type": "string",
                        "description": "Path to the multi-document YAML file on disk."
                    },
                    "doc_index": {
                        "type": "integer",
                        "minimum": 0,
                        "description": "Zero-based index of the document within \
                            the `---`-separated stream to modify."
                    },
                    "path": {
                        "type": "string",
                        "description": "Dotted/indexed path into the selected document."
                    },
                    "value": {
                        "type": "string",
                        "description": "Replacement value as a YAML fragment. Must \
                            parse in the target position; the file is left \
                            unchanged on parse error."
                    }
                },
                "required": ["file", "doc_index", "path", "value"]
            }
        }),
    ]
}

/// `tools/call` dispatcher. Returns the JSON-RPC `result` payload on
/// success, or `(code, message)` for an error envelope.
pub fn call(params: JsonValue) -> Result<JsonValue, (i32, String)> {
    let name = params
        .get("name")
        .and_then(|v| v.as_str())
        .ok_or_else(|| (-32602, "missing field: name".to_string()))?;
    let args = params.get("arguments").cloned().unwrap_or(JsonValue::Null);

    match name {
        "noyalib_get" => tool_get(&args),
        "noyalib_set" => tool_set(&args),
        "noyalib_set_multidoc" => tool_set_multidoc(&args),
        _ => Err((-32601, format!("unknown tool: {name}"))),
    }
}

/// Wrap a tool result string into the MCP `tools/call` reply shape.
fn ok_text(text: String) -> JsonValue {
    json!({
        "content": [
            { "type": "text", "text": text }
        ]
    })
}

fn tool_get(args: &JsonValue) -> Result<JsonValue, (i32, String)> {
    let file = arg_str(args, "file")?;
    let path = arg_str(args, "path")?;
    let src = fs::read_to_string(file).map_err(|e| (-32000, format!("read {file}: {e}")))?;
    let doc = parse_document(&src).map_err(|e| (-32001, format!("parse {file}: {e}")))?;
    match doc.get(path) {
        Some(value) => Ok(ok_text(value.to_string())),
        None => Err((-32002, format!("path not found in {file}: {path}"))),
    }
}

fn tool_set(args: &JsonValue) -> Result<JsonValue, (i32, String)> {
    let file = arg_str(args, "file")?;
    let path = arg_str(args, "path")?;
    let value = arg_str(args, "value")?;
    let src = fs::read_to_string(file).map_err(|e| (-32000, format!("read {file}: {e}")))?;
    let mut doc = parse_document(&src).map_err(|e| (-32001, format!("parse {file}: {e}")))?;
    doc.set(path, value)
        .map_err(|e| (-32003, format!("set {path} = {value}: {e}")))?;
    write_atomic(file, doc.to_string().as_bytes())
        .map_err(|e| (-32000, format!("write {file}: {e}")))?;
    Ok(ok_text(format!(
        "set {path} = {value} in {file} (lossless: comments and formatting preserved)"
    )))
}

fn tool_set_multidoc(args: &JsonValue) -> Result<JsonValue, (i32, String)> {
    let file = arg_str(args, "file")?;
    let doc_index = args
        .get("doc_index")
        .and_then(JsonValue::as_u64)
        .ok_or_else(|| (-32602, "missing integer argument: doc_index".to_string()))?
        as usize;
    let path = arg_str(args, "path")?;
    let value = arg_str(args, "value")?;
    let src = fs::read_to_string(file).map_err(|e| (-32000, format!("read {file}: {e}")))?;
    // parse_stream keeps each `---`-delimited document as its own
    // lossless Document, retaining its separator; concatenating their
    // rendered forms reproduces the stream byte-for-byte, so editing one
    // document leaves every other document untouched.
    let mut docs = parse_stream(&src).map_err(|e| (-32001, format!("parse {file}: {e}")))?;
    if doc_index >= docs.len() {
        return Err((
            -32602,
            format!(
                "doc_index {doc_index} out of range: stream has {} document(s)",
                docs.len()
            ),
        ));
    }
    docs[doc_index]
        .set(path, value)
        .map_err(|e| (-32003, format!("set {path} = {value}: {e}")))?;
    let out: String = docs.iter().map(ToString::to_string).collect();
    write_atomic(file, out.as_bytes()).map_err(|e| (-32000, format!("write {file}: {e}")))?;
    Ok(ok_text(format!(
        "set {path} = {value} in document {doc_index} of {file} \
         (lossless: other documents, comments and formatting preserved)"
    )))
}

/// Write `bytes` to `file` atomically: write to a sibling temp
/// file, fsync it, then `rename` over the target. The rename is
/// atomic on POSIX and `MoveFileExW(MOVEFILE_REPLACE_EXISTING |
/// MOVEFILE_WRITE_THROUGH)` semantics on Windows, so concurrent
/// readers always see either the old or the new contents — never
/// a half-written truncation. The fsync also closes a Windows
/// race where `fs::write` returned before the kernel page cache
/// flushed, leaving a freshly-spawned reader to observe the old
/// bytes.
fn write_atomic(file: &str, bytes: &[u8]) -> std::io::Result<()> {
    use std::io::Write;
    use std::path::Path;
    let target = Path::new(file);
    let parent = target.parent().unwrap_or(Path::new("."));
    let stem = target
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("noyalib-set");
    let pid = std::process::id();
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let tmp = parent.join(format!(".{stem}.{pid}.{nanos}.tmp"));
    {
        let mut f = std::fs::File::create(&tmp)?;
        f.write_all(bytes)?;
        f.sync_all()?;
    }
    std::fs::rename(&tmp, target)
}

fn arg_str<'a>(args: &'a JsonValue, key: &str) -> Result<&'a str, (i32, String)> {
    args.get(key)
        .and_then(|v| v.as_str())
        .ok_or_else(|| (-32602, format!("missing string argument: {key}")))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicU32, Ordering};

    /// Allocate a unique scratch path under the system temp dir so
    /// parallel test runs don't collide.
    fn temp_path(label: &str) -> PathBuf {
        static COUNTER: AtomicU32 = AtomicU32::new(0);
        let id = COUNTER.fetch_add(1, Ordering::Relaxed);
        let pid = std::process::id();
        std::env::temp_dir().join(format!("noyalib-mcp-{label}-{pid}-{id}.yml"))
    }

    fn write_temp(label: &str, contents: &str) -> PathBuf {
        let p = temp_path(label);
        fs::write(&p, contents).unwrap();
        p
    }

    // ── descriptors ────────────────────────────────────────────────

    #[test]
    fn descriptors_lists_all_tools_with_input_schemas() {
        let d = descriptors();
        assert_eq!(d.len(), 3);
        let names: Vec<&str> = d.iter().map(|t| t["name"].as_str().unwrap()).collect();
        assert!(names.contains(&"noyalib_get"));
        assert!(names.contains(&"noyalib_set"));
        assert!(names.contains(&"noyalib_set_multidoc"));
        for tool in &d {
            assert!(tool["description"].is_string());
            assert_eq!(tool["inputSchema"]["type"].as_str(), Some("object"));
            assert!(tool["inputSchema"]["required"].is_array());
        }
    }

    // ── call dispatcher ────────────────────────────────────────────

    #[test]
    fn call_rejects_missing_name() {
        let err = call(json!({})).unwrap_err();
        assert_eq!(err.0, -32602);
        assert!(err.1.contains("name"));
    }

    #[test]
    fn call_rejects_unknown_tool() {
        let err = call(json!({"name": "frobnicate", "arguments": {}})).unwrap_err();
        assert_eq!(err.0, -32601);
        assert!(err.1.contains("frobnicate"));
    }

    #[test]
    fn call_routes_to_get() {
        let p = write_temp("call-get", "name: noyalib\n");
        let v = call(json!({
            "name": "noyalib_get",
            "arguments": { "file": p.to_str().unwrap(), "path": "name" }
        }))
        .unwrap();
        let text = v["content"][0]["text"].as_str().unwrap();
        assert_eq!(text, "noyalib");
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn call_routes_to_set() {
        let p = write_temp("call-set", "version: 1\n");
        let v = call(json!({
            "name": "noyalib_set",
            "arguments": {
                "file": p.to_str().unwrap(),
                "path": "version",
                "value": "2"
            }
        }))
        .unwrap();
        assert!(
            v["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("set version")
        );
        let updated = fs::read_to_string(&p).unwrap();
        assert_eq!(updated, "version: 2\n");
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn call_routes_to_set_multidoc() {
        let p = write_temp("call-set-multidoc", "name: first\n---\nname: second\n");
        let v = call(json!({
            "name": "noyalib_set_multidoc",
            "arguments": {
                "file": p.to_str().unwrap(),
                "doc_index": 1,
                "path": "name",
                "value": "changed"
            }
        }))
        .unwrap();
        assert!(
            v["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("document 1")
        );
        let updated = fs::read_to_string(&p).unwrap();
        // First document is preserved byte-for-byte; only the second changed.
        assert!(updated.contains("name: first"));
        assert!(updated.contains("name: changed"));
        assert!(!updated.contains("name: second"));
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn set_multidoc_missing_doc_index_errors() {
        let p = write_temp("md-no-index", "a: 1\n");
        let err = tool_set_multidoc(&json!({
            "file": p.to_str().unwrap(),
            "path": "a",
            "value": "2"
        }))
        .unwrap_err();
        assert_eq!(err.0, -32602);
        assert!(err.1.contains("doc_index"));
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn set_multidoc_index_out_of_range_errors() {
        let p = write_temp("md-oob", "a: 1\n---\nb: 2\n");
        let err = tool_set_multidoc(&json!({
            "file": p.to_str().unwrap(),
            "doc_index": 9,
            "path": "b",
            "value": "3"
        }))
        .unwrap_err();
        assert_eq!(err.0, -32602);
        assert!(err.1.contains("out of range"));
        // File left unchanged.
        assert_eq!(fs::read_to_string(&p).unwrap(), "a: 1\n---\nb: 2\n");
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn set_multidoc_unreadable_file_errors() {
        let err = tool_set_multidoc(&json!({
            "file": "/this/path/does/not/exist.yml",
            "doc_index": 0,
            "path": "a",
            "value": "1"
        }))
        .unwrap_err();
        assert_eq!(err.0, -32000);
    }

    #[test]
    fn set_multidoc_unparseable_source_errors() {
        let p = write_temp("md-parse", "a: [\n");
        let err = tool_set_multidoc(&json!({
            "file": p.to_str().unwrap(),
            "doc_index": 0,
            "path": "a",
            "value": "1"
        }))
        .unwrap_err();
        assert_eq!(err.0, -32001);
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn set_multidoc_unknown_path_errors() {
        let p = write_temp("md-badpath", "a: 1\n---\nb: 2\n");
        let err = tool_set_multidoc(&json!({
            "file": p.to_str().unwrap(),
            "doc_index": 0,
            "path": "missing.deep",
            "value": "1"
        }))
        .unwrap_err();
        assert_eq!(err.0, -32003);
        let _ = fs::remove_file(&p);
    }

    // ── tool_get error paths ───────────────────────────────────────

    #[test]
    fn tool_get_missing_file_arg_errors() {
        let err = tool_get(&json!({"path": "k"})).unwrap_err();
        assert_eq!(err.0, -32602);
    }

    #[test]
    fn tool_get_missing_path_arg_errors() {
        let err = tool_get(&json!({"file": "/tmp/x.yml"})).unwrap_err();
        assert_eq!(err.0, -32602);
    }

    #[test]
    fn tool_get_unreadable_file_errors() {
        let err = tool_get(&json!({
            "file": "/this/path/definitely/does/not/exist.yml",
            "path": "k"
        }))
        .unwrap_err();
        assert_eq!(err.0, -32000);
    }

    #[test]
    fn tool_get_unparseable_yaml_errors() {
        let p = write_temp("get-parse", "key: [\n");
        let err = tool_get(&json!({
            "file": p.to_str().unwrap(),
            "path": "key"
        }))
        .unwrap_err();
        assert_eq!(err.0, -32001);
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn tool_get_path_not_found_errors() {
        let p = write_temp("get-missing", "a: 1\n");
        let err = tool_get(&json!({
            "file": p.to_str().unwrap(),
            "path": "missing"
        }))
        .unwrap_err();
        assert_eq!(err.0, -32002);
        let _ = fs::remove_file(&p);
    }

    // ── tool_set error paths ───────────────────────────────────────

    #[test]
    fn tool_set_missing_args_errors() {
        let err = tool_set(&json!({})).unwrap_err();
        assert_eq!(err.0, -32602);
    }

    #[test]
    fn tool_set_unreadable_file_errors() {
        let err = tool_set(&json!({
            "file": "/this/path/does/not/exist.yml",
            "path": "k",
            "value": "v"
        }))
        .unwrap_err();
        assert_eq!(err.0, -32000);
    }

    #[test]
    fn tool_set_unparseable_source_errors() {
        let p = write_temp("set-parse", "k: [\n");
        let err = tool_set(&json!({
            "file": p.to_str().unwrap(),
            "path": "k",
            "value": "v"
        }))
        .unwrap_err();
        assert_eq!(err.0, -32001);
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn tool_set_unknown_path_errors() {
        let p = write_temp("set-bad-path", "a: 1\n");
        let err = tool_set(&json!({
            "file": p.to_str().unwrap(),
            "path": "missing.path",
            "value": "v"
        }))
        .unwrap_err();
        assert_eq!(err.0, -32003);
        let _ = fs::remove_file(&p);
    }
}