plugmem-mcp 0.3.0

plugmem MCP server (stdio JSON-RPC).
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
//! Black-box tests of the MCP server: drive it over stdio JSON-RPC and check
//! replies. Each test opens a fresh memory file under `CARGO_TARGET_TMPDIR`.

use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use std::process::{Command, Stdio};

use serde_json::Value;

/// A unique memory path under the cargo target tmp dir (no embedder needed —
/// the default config runs lexical/graph/time recall).
fn temp_db(tag: &str) -> PathBuf {
    let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!(
        "mcp-{tag}-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    dir.join("m.plugmem")
}

/// Feed each request line to a server opened on `db`, return the parsed replies.
fn roundtrip(db: &PathBuf, requests: &[&str]) -> Vec<Value> {
    roundtrip_args(db, &[], requests)
}

/// Like [`roundtrip`], with extra binary arguments (e.g. `--read-only`).
///
/// **Synchronous**: send one request, await its reply, then the next — the
/// behavior of a real MCP client. This keeps a causal chain (remember → recall)
/// deterministic no matter how many workers the pool has (only one request is
/// ever in flight). A notification (no `id`) gets no reply, so none is awaited.
fn roundtrip_args(db: &PathBuf, extra: &[&str], requests: &[&str]) -> Vec<Value> {
    let mut child = Command::new(env!("CARGO_BIN_EXE_plugmem-mcp"))
        .arg("--db")
        .arg(db)
        .args(extra)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("spawn plugmem-mcp");
    let mut stdin = child.stdin.take().unwrap();
    let mut stdout = BufReader::new(child.stdout.take().unwrap());

    let mut replies = Vec::new();
    for r in requests {
        writeln!(stdin, "{r}").unwrap();
        stdin.flush().unwrap();
        // A request carries an `id`; a notification does not (no reply to await).
        let is_request = serde_json::from_str::<Value>(r)
            .map(|v| v.get("id").is_some())
            .unwrap_or(false);
        if is_request {
            let mut line = String::new();
            stdout.read_line(&mut line).unwrap();
            replies.push(serde_json::from_str(line.trim()).unwrap());
        }
    }
    drop(stdin); // EOF → server exits
    let _ = child.wait();
    replies
}

/// Send every request at once (pipelined), then read all replies and index them
/// by `id`. Exercises the worker pool: independent requests may complete in any
/// order, so a positional read would be wrong — reply correlation is by `id`.
fn pipelined_by_id(
    db: &PathBuf,
    extra: &[&str],
    requests: &[&str],
) -> std::collections::HashMap<u64, Value> {
    let mut child = Command::new(env!("CARGO_BIN_EXE_plugmem-mcp"))
        .arg("--db")
        .arg(db)
        .args(extra)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("spawn plugmem-mcp");
    {
        let stdin = child.stdin.as_mut().unwrap();
        for r in requests {
            writeln!(stdin, "{r}").unwrap();
        }
    } // drop stdin → EOF → server exits
    let output = child.wait_with_output().unwrap();
    String::from_utf8(output.stdout)
        .unwrap()
        .lines()
        .filter(|l| !l.trim().is_empty())
        .map(|l| serde_json::from_str::<Value>(l).unwrap())
        .map(|v| (v["id"].as_u64().unwrap(), v))
        .collect()
}

#[test]
fn initialize_list_and_stats() {
    let db = temp_db("init");
    let resps = roundtrip(
        &db,
        &[
            r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#,
            r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, // notification → no reply
            r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#,
            r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"plugmem_stats","arguments":{}}}"#,
        ],
    );

    assert_eq!(resps.len(), 3, "the notification must not get a reply");
    assert_eq!(resps[0]["result"]["serverInfo"]["name"], "plugmem");
    assert_eq!(resps[0]["result"]["protocolVersion"], "2024-11-05");
    // The verb surface is advertised: write verbs first, meta last.
    let tools: Vec<&str> = resps[1]["result"]["tools"]
        .as_array()
        .unwrap()
        .iter()
        .map(|t| t["name"].as_str().unwrap())
        .collect();
    assert_eq!(tools[0], "plugmem_remember");
    assert_eq!(tools.last(), Some(&"plugmem_settings_help"));
    for expected in ["plugmem_recall", "plugmem_stats", "plugmem_version"] {
        assert!(
            tools.contains(&expected),
            "missing tool {expected} in {tools:?}"
        );
    }

    // stats returns machine JSON with the size counters; a fresh db has 0 facts.
    let text = resps[2]["result"]["content"][0]["text"].as_str().unwrap();
    let stats: Value = serde_json::from_str(text).unwrap();
    assert_eq!(stats["facts"], 0);
    assert_eq!(resps[2]["result"]["isError"], false);
}

#[test]
fn version_and_about_are_listed_and_callable() {
    let db = temp_db("meta");
    let resps = roundtrip(
        &db,
        &[
            r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#,
            r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"plugmem_version","arguments":{}}}"#,
            r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"plugmem_about","arguments":{}}}"#,
        ],
    );

    // plugmem_version returns the running version, matching serverInfo.
    let version = resps[0]["result"]["serverInfo"]["version"]
        .as_str()
        .unwrap();
    let vtext = resps[1]["result"]["content"][0]["text"].as_str().unwrap();
    assert_eq!(resps[1]["result"]["isError"], false);
    assert!(
        vtext.contains(version),
        "version tool `{vtext}` should contain {version}"
    );

    // about points at the skill and the project.
    let atext = resps[2]["result"]["content"][0]["text"].as_str().unwrap();
    assert_eq!(resps[2]["result"]["isError"], false);
    assert!(
        atext.contains("skill"),
        "about should mention the skill: {atext}"
    );
    assert!(
        atext.contains("github.com/m62624/plugmem"),
        "about should link the project: {atext}"
    );
}

#[test]
fn unknown_method_is_a_jsonrpc_error_and_unknown_tool_is_a_tool_error() {
    let db = temp_db("errors");
    let resps = roundtrip(
        &db,
        &[
            r#"{"jsonrpc":"2.0","id":1,"method":"does/not/exist"}"#,
            r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"plugmem_nope","arguments":{}}}"#,
            r#"{"jsonrpc":"2.0","id":3,"method":"tools/call"}"#,
        ],
    );
    // Unknown method → JSON-RPC error -32601.
    assert_eq!(resps[0]["error"]["code"], -32601);
    // Unknown tool → tool-level error (in the result, not a protocol error).
    assert_eq!(resps[1]["result"]["isError"], true);
    // Missing params → JSON-RPC error -32602.
    assert_eq!(resps[2]["error"]["code"], -32602);
}

#[test]
fn writer_verbs_round_trip() {
    let db = temp_db("writer");
    let resps = roundtrip(
        &db,
        &[
            // remember a fact with an entity and a tag → id 0
            r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"plugmem_remember","arguments":{"text":"prefers tokio","entity":"user","tags":["pref"]}}}"#,
            // recall it (json) — should surface the fact
            r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"plugmem_recall","arguments":{"query":"runtime tokio"}}}"#,
            // show fact 0
            r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"plugmem_show","arguments":{"id":0}}}"#,
            // revise fact 0
            r#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"plugmem_revise","arguments":{"id":0,"text":"prefers async-std","entity":"user"}}}"#,
            // link two entities
            r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"plugmem_link","arguments":{"src":"user","rel":"works_at","dst":"acme"}}}"#,
            // close that current edge
            r#"{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"plugmem_unlink","arguments":{"src":"user","rel":"works_at","dst":"acme"}}}"#,
            // export the open facts
            r#"{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"plugmem_export","arguments":{}}}"#,
            // operational verbs
            r#"{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"plugmem_maintain","arguments":{}}}"#,
            r#"{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"plugmem_checkpoint","arguments":{}}}"#,
            r#"{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"plugmem_verify","arguments":{}}}"#,
            // forget the (revised) successor fact 1
            r#"{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"plugmem_forget","arguments":{"id":1}}}"#,
        ],
    );

    // remember → id 0, no error.
    let remembered: Value =
        serde_json::from_str(resps[0]["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
    assert_eq!(remembered["id"], 0);
    assert_eq!(resps[0]["result"]["isError"], false);

    // recall → structured result carrying fact 0.
    let recalled: Value =
        serde_json::from_str(resps[1]["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
    assert!(
        recalled["facts"]
            .as_array()
            .map(|a| !a.is_empty())
            .unwrap_or(false),
        "recall should surface the fact: {recalled}"
    );

    // show fact 0 → its text.
    let shown = resps[2]["result"]["content"][0]["text"].as_str().unwrap();
    assert!(shown.contains("prefers tokio"), "show: {shown}");

    // revise → the successor id (1), no error.
    let revised: Value =
        serde_json::from_str(resps[3]["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
    assert_eq!(revised["id"], 1);

    // link ok.
    assert_eq!(resps[4]["result"]["isError"], false);

    // unlink ok.
    let unlinked: Value =
        serde_json::from_str(resps[5]["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
    assert_eq!(unlinked["unlinked"], true);

    // export → a JSON array of the open facts (>=1).
    let exported: Value =
        serde_json::from_str(resps[6]["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
    assert!(exported.as_array().map(|a| !a.is_empty()).unwrap_or(false));

    // maintain/checkpoint/verify all succeed.
    assert_eq!(resps[7]["result"]["isError"], false);
    assert_eq!(resps[8]["result"]["isError"], false);
    assert_eq!(resps[9]["result"]["isError"], false);

    // forget the live successor → forgotten: true.
    let forgotten: Value =
        serde_json::from_str(resps[10]["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
    assert_eq!(forgotten["forgotten"], true);
}

#[test]
fn recall_human_format_is_the_prompt_block() {
    let db = temp_db("recall-human");
    let resps = roundtrip(
        &db,
        &[
            r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"plugmem_remember","arguments":{"text":"the sky is blue","entity":"sky"}}}"#,
            r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"plugmem_recall","arguments":{"query":"sky colour","format":"human"}}}"#,
        ],
    );
    // The human block carries the fact id marker `[f0]` (the prompt-ready text),
    // not a JSON object.
    let block = resps[1]["result"]["content"][0]["text"].as_str().unwrap();
    assert!(
        block.contains("[f0]"),
        "human recall should be the block: {block}"
    );
}

#[test]
fn missing_required_argument_is_a_tool_error() {
    let db = temp_db("missing-arg");
    let resps = roundtrip(
        &db,
        &[
            // remember without text
            r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"plugmem_remember","arguments":{"entity":"x"}}}"#,
            // show a non-existent fact
            r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"plugmem_show","arguments":{"id":999}}}"#,
        ],
    );
    assert_eq!(resps[0]["result"]["isError"], true);
    assert_eq!(resps[1]["result"]["isError"], true);
}

#[test]
fn read_only_serves_reads_and_refuses_writes() {
    let db = temp_db("ro");
    // A writer process stores a fact and checkpoints (so a read-only open has a
    // published snapshot), then exits when its stdin closes.
    let w = roundtrip(
        &db,
        &[
            r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"plugmem_remember","arguments":{"text":"prefers tokio","entity":"user"}}}"#,
            r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"plugmem_checkpoint","arguments":{}}}"#,
        ],
    );
    assert_eq!(
        w[1]["result"]["isError"], false,
        "checkpoint should succeed"
    );

    // A separate read-only process observes that snapshot.
    let r = roundtrip_args(
        &db,
        &["--read-only"],
        &[
            r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#,
            r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"plugmem_stats","arguments":{}}}"#,
            r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"plugmem_recall","arguments":{"query":"tokio"}}}"#,
            r#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"plugmem_generation","arguments":{}}}"#,
            r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"plugmem_refresh","arguments":{}}}"#,
            // a write verb must be refused
            r#"{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"plugmem_remember","arguments":{"text":"nope"}}}"#,
        ],
    );

    // The advertised set is read-only: refresh is offered, remember is not.
    let tools: Vec<&str> = r[0]["result"]["tools"]
        .as_array()
        .unwrap()
        .iter()
        .map(|t| t["name"].as_str().unwrap())
        .collect();
    assert!(tools.contains(&"plugmem_refresh"), "ro tools: {tools:?}");
    assert!(tools.contains(&"plugmem_generation"), "ro tools: {tools:?}");
    assert!(
        !tools.contains(&"plugmem_remember"),
        "ro must not offer writes: {tools:?}"
    );

    // stats sees the checkpointed fact.
    let stats: Value =
        serde_json::from_str(r[1]["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
    assert_eq!(stats["facts"], 1);

    // recall (lexical, no embedder) surfaces it.
    let recalled: Value =
        serde_json::from_str(r[2]["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
    assert!(
        recalled["facts"]
            .as_array()
            .map(|a| !a.is_empty())
            .unwrap_or(false),
        "ro recall should find the fact: {recalled}"
    );

    // generation is a number; refresh reports current generation, nothing newer.
    let generation: Value =
        serde_json::from_str(r[3]["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
    assert!(generation["generation"].is_number());
    let refreshed: Value =
        serde_json::from_str(r[4]["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
    assert_eq!(
        refreshed["refreshed"], false,
        "nothing published since open"
    );

    // the write verb is refused as a tool-level error.
    assert_eq!(r[5]["result"]["isError"], true);
}

#[test]
fn worker_pool_answers_every_pipelined_request() {
    let db = temp_db("pool");
    // Fire many independent read-only requests at once with several workers; the
    // pool may answer in any order, but every id must get exactly one correct
    // reply and no line may be interleaved/garbled (Mutex<Stdout>).
    let mut reqs: Vec<String> = Vec::new();
    for i in 1..=20u64 {
        let verb = if i % 2 == 0 {
            "plugmem_stats"
        } else {
            "plugmem_version"
        };
        reqs.push(format!(
            r#"{{"jsonrpc":"2.0","id":{i},"method":"tools/call","params":{{"name":"{verb}","arguments":{{}}}}}}"#
        ));
    }
    let req_refs: Vec<&str> = reqs.iter().map(String::as_str).collect();
    let replies = pipelined_by_id(&db, &["--workers", "4"], &req_refs);

    assert_eq!(
        replies.len(),
        20,
        "every request must be answered exactly once"
    );
    for i in 1..=20u64 {
        let reply = replies
            .get(&i)
            .unwrap_or_else(|| panic!("no reply for id {i}"));
        assert_eq!(reply["result"]["isError"], false, "id {i}: {reply}");
        let text = reply["result"]["content"][0]["text"].as_str().unwrap();
        if i % 2 == 0 {
            // stats → valid JSON with the counters.
            assert!(
                serde_json::from_str::<Value>(text).is_ok(),
                "id {i} stats: {text}"
            );
        } else {
            assert!(text.contains("plugmem"), "id {i} version: {text}");
        }
    }
}

#[test]
fn human_format_pretty_prints() {
    let db = temp_db("human");
    let resps = roundtrip(
        &db,
        &[
            r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"plugmem_stats","arguments":{"format":"human"}}}"#,
        ],
    );
    let text = resps[0]["result"]["content"][0]["text"].as_str().unwrap();
    // Pretty JSON is multi-line and indented; compact JSON is not.
    assert!(text.contains('\n'), "human format should be pretty: {text}");
}

/// A unique workspace directory under the cargo target tmp dir.
fn temp_workspace(tag: &str) -> PathBuf {
    let dir = temp_db(tag);
    dir.parent().unwrap().to_path_buf()
}

/// Drive a server started over a workspace directory rather than one file.
/// `extra` carries the rest of the flags (`--db NAME`, `--allow`, `--no-create`).
fn workspace_roundtrip(root: &PathBuf, extra: &[&str], requests: &[&str]) -> Vec<Value> {
    let mut child = Command::new(env!("CARGO_BIN_EXE_plugmem-mcp"))
        .arg("--workspace")
        .arg(root)
        .args(extra)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("spawn plugmem-mcp");
    let mut stdin = child.stdin.take().unwrap();
    let mut stdout = BufReader::new(child.stdout.take().unwrap());

    let mut replies = Vec::new();
    for r in requests {
        writeln!(stdin, "{r}").unwrap();
        stdin.flush().unwrap();
        let mut line = String::new();
        stdout.read_line(&mut line).unwrap();
        replies.push(serde_json::from_str(line.trim()).unwrap());
    }
    drop(stdin);
    let _ = child.wait();
    replies
}

/// The `text` of a tool-call reply.
fn reply_text(v: &Value) -> &str {
    v["result"]["content"][0]["text"].as_str().unwrap()
}

#[test]
fn a_workspace_server_routes_by_name_and_keeps_memories_apart() {
    let root = temp_workspace("ws-route");
    let replies = workspace_roundtrip(
        &root,
        &[],
        &[
            r#"{"id":1,"method":"tools/call","params":{"name":"plugmem_remember","arguments":{"db":"chat-42","text":"the sky is blue"}}}"#,
            r#"{"id":2,"method":"tools/call","params":{"name":"plugmem_remember","arguments":{"db":"chat-43","text":"the grass is green"}}}"#,
            r#"{"id":3,"method":"tools/call","params":{"name":"plugmem_recall","arguments":{"db":"chat-42","query":"sky grass","format":"human"}}}"#,
        ],
    );
    assert_eq!(replies[0]["result"]["isError"], false);
    let recalled = reply_text(&replies[2]);
    assert!(recalled.contains("the sky is blue"), "{recalled}");
    assert!(!recalled.contains("the grass is green"), "{recalled}");

    // Both memories are files in the workspace, created by their first write.
    assert!(root.join("db/chat-42.plugmem.journal").exists());
    assert!(root.join("db/chat-43.plugmem.journal").exists());
}

#[test]
fn the_db_argument_tracks_how_the_server_was_started() {
    let root = temp_workspace("ws-schema");
    let list = r#"{"id":1,"method":"tools/list"}"#;

    // No default: `db` is advertised and required.
    let bare = workspace_roundtrip(&root, &[], &[list]);
    let remember = &bare[0]["result"]["tools"][0];
    assert_eq!(remember["name"], "plugmem_remember");
    assert!(remember["inputSchema"]["properties"]["db"].is_object());
    assert_eq!(remember["inputSchema"]["required"][0], "db");

    // A default: still advertised, no longer required, and it says the default.
    let defaulted = workspace_roundtrip(&root, &["--db", "chat-42"], &[list]);
    let remember = &defaulted[0]["result"]["tools"][0];
    assert_eq!(
        remember["inputSchema"]["properties"]["db"]["default"],
        "chat-42"
    );
    assert_eq!(remember["inputSchema"]["required"][0], "text");
}

#[test]
fn one_memory_at_a_path_is_untouched_by_any_of_this() {
    // The guard on the default: started the old way, the server advertises no
    // `db` argument at all and creates nothing but the file it was given.
    let db = temp_db("ws-default-guard");
    let replies = roundtrip(&db, &[r#"{"id":1,"method":"tools/list"}"#]);
    let tools = replies[0]["result"]["tools"].as_array().unwrap();
    for tool in tools {
        assert!(
            tool["inputSchema"]["properties"]["db"].is_null(),
            "{} advertises a db argument",
            tool["name"]
        );
        let name = tool["name"].as_str().unwrap();
        assert!(
            !name.starts_with("plugmem_workspace"),
            "{name} is advertised"
        );
    }
    let dir = db.parent().unwrap();
    assert!(!dir.join("registry.plugmem").exists());
    assert!(!dir.join("db").exists());
}

#[test]
fn a_workspace_server_finds_a_memory_by_what_it_is_for() {
    let root = temp_workspace("ws-find");
    let replies = workspace_roundtrip(
        &root,
        &[],
        &[
            r#"{"id":1,"method":"tools/call","params":{"name":"plugmem_remember","arguments":{"db":"chat-42","text":"a fact"}}}"#,
            r#"{"id":2,"method":"tools/call","params":{"name":"plugmem_workspace_list","arguments":{}}}"#,
            r#"{"id":3,"method":"tools/call","params":{"name":"plugmem_stats","arguments":{}}}"#,
        ],
    );
    // Nothing described yet: the list is empty rather than an error.
    assert_eq!(reply_text(&replies[1]), "[]");
    // And a call with no `db` on a server with no default is refused, with the
    // way out named in the message.
    assert_eq!(replies[2]["result"]["isError"], true);
    assert!(reply_text(&replies[2]).contains("plugmem_workspace_find"));
}

#[test]
fn a_workspace_server_refuses_read_only_rather_than_pretending() {
    let root = temp_workspace("ws-readonly");
    let out = Command::new(env!("CARGO_BIN_EXE_plugmem-mcp"))
        .arg("--workspace")
        .arg(&root)
        .arg("--read-only")
        .output()
        .expect("spawn plugmem-mcp");
    assert_eq!(out.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--read-only has no workspace form"),
        "{stderr}"
    );
}

#[test]
fn a_startup_name_that_is_not_a_name_stops_the_server() {
    let root = temp_workspace("ws-badname");
    for (flag, value) in [("--db", "../etc"), ("--allow", "Nope")] {
        let out = Command::new(env!("CARGO_BIN_EXE_plugmem-mcp"))
            .arg("--workspace")
            .arg(&root)
            .arg(flag)
            .arg(value)
            .output()
            .expect("spawn plugmem-mcp");
        assert_eq!(out.status.code(), Some(2), "{flag} {value}");
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(stderr.contains(flag), "{stderr}");
    }

    // A default outside its own allow set could never be served, so saying so
    // at startup beats failing on every call.
    let out = Command::new(env!("CARGO_BIN_EXE_plugmem-mcp"))
        .arg("--workspace")
        .arg(&root)
        .args(["--db", "work", "--allow", "other"])
        .output()
        .expect("spawn plugmem-mcp");
    assert_eq!(out.status.code(), Some(2));
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("could never be served"),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
}