nereid 0.6.0

Source-available noncommercial terminal diagram TUI and MCP server for Mermaid-backed sessions
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
// SPDX-FileCopyrightText: 2026 Bruno Meilick
// SPDX-License-Identifier: LicenseRef-Nereid-FreeUse-NoCopy-NoDerivatives
//
// All rights reserved.
//
// This file is part of Nereid and is proprietary software.
// Unauthorized copying, modification, or distribution is prohibited.

//! Walkthrough MCP tools: list, open, render, and node-level reads.

use rmcp::handler::server::wrapper::{Json, Parameters};
use rmcp::{tool, tool_router};

use crate::render::render_walkthrough_unicode;

use super::*;

#[tool_router(router = walkthrough_tool_router, vis = "pub(super)")]
impl NereidMcp {
    /// Set the active walkthrough default for walkthrough-scoped tools; usually after
    /// `walkthrough_list`.
    #[tool(name = "walkthrough_open")]
    pub(super) async fn walkthrough_open(
        &self,
        params: Parameters<WalkthroughOpenParams>,
    ) -> Result<Json<WalkthroughOpenResponse>, ErrorData> {
        let walkthrough_id = params.0.walkthrough_id;
        let parsed = parse_walkthrough_id(&walkthrough_id)?;

        let mut state = self.lock_state_synced().await?;
        if !state.session.walkthroughs().contains_key(&parsed) {
            return Err(ErrorData::resource_not_found(
                "walkthrough not found",
                Some(serde_json::json!({ "walkthrough_id": walkthrough_id })),
            ));
        }

        if let Some(session_folder) = &self.session_folder {
            let candidate = {
                let mut update = session_folder.begin_session_update().map_err(|err| {
                    ErrorData::internal_error(
                        format!("failed to reload session before save: {err}"),
                        Some(serde_json::json!({ "walkthrough_id": walkthrough_id })),
                    )
                })?;
                let candidate = update.session_mut();
                if !candidate.walkthroughs().contains_key(&parsed) {
                    return Err(ErrorData::resource_not_found(
                        "walkthrough not found",
                        Some(serde_json::json!({ "walkthrough_id": walkthrough_id })),
                    ));
                }
                candidate.set_active_walkthrough_id(Some(parsed.clone()));
                update.commit().map_err(|err| {
                    ErrorData::internal_error(
                        format!("failed to persist session: {err}"),
                        Some(serde_json::json!({ "walkthrough_id": walkthrough_id })),
                    )
                })?
            };
            replace_committed_session(&mut state, candidate);
        } else {
            state.session.set_active_walkthrough_id(Some(parsed.clone()));
        }

        let response =
            Json(WalkthroughOpenResponse { active_walkthrough_id: parsed.as_str().to_owned() });
        drop(state);
        self.notify_ui_session_changed().await;
        Ok(response)
    }

    /// Get the active walkthrough id (`null` when unset); call after `walkthrough_list` and
    /// before `walkthrough_open`/`walkthrough_read`.
    #[tool(name = "walkthrough_current")]
    pub(super) async fn walkthrough_current(
        &self,
    ) -> Result<Json<WalkthroughCurrentResponse>, ErrorData> {
        let state = self.lock_state_synced().await?;
        let session_active_diagram_id =
            state.session.active_diagram_id().map(|diagram_id| diagram_id.as_str().to_owned());
        let active_walkthrough_id = state
            .session
            .active_walkthrough_id()
            .map(|walkthrough_id| walkthrough_id.as_str().to_owned());
        drop(state);
        let context = self.read_context(session_active_diagram_id).await;

        Ok(Json(WalkthroughCurrentResponse { active_walkthrough_id, context }))
    }
    /// List walkthroughs in the current session; start here, then `walkthrough_open`,
    /// `walkthrough_stat`, or `walkthrough_read`.
    #[tool(name = "walkthrough_list")]
    pub(super) async fn walkthrough_list(
        &self,
    ) -> Result<Json<ListWalkthroughsResponse>, ErrorData> {
        let state = self.lock_state_synced().await?;
        let session_active_diagram_id =
            state.session.active_diagram_id().map(|diagram_id| diagram_id.as_str().to_owned());
        let mut walkthroughs = state
            .session
            .walkthroughs()
            .iter()
            .map(|(walkthrough_id, walkthrough)| WalkthroughSummary {
                walkthrough_id: walkthrough_id.as_str().to_owned(),
                title: walkthrough.title().to_owned(),
                rev: walkthrough.rev(),
                nodes: walkthrough.nodes().len() as u64,
                edges: walkthrough.edges().len() as u64,
            })
            .collect::<Vec<_>>();
        walkthroughs.sort_by(|a, b| a.walkthrough_id.cmp(&b.walkthrough_id));
        drop(state);
        let context = self.read_context(session_active_diagram_id).await;

        Ok(Json(ListWalkthroughsResponse { walkthroughs, context }))
    }

    /// Read a full walkthrough (nodes/edges/refs); call after `walkthrough_stat` when you need
    /// complete node/edge detail, and before targeted `walkthrough_get_node`.
    #[tool(name = "walkthrough_read")]
    pub(super) async fn walkthrough_read(
        &self,
        params: Parameters<WalkthroughGetParams>,
    ) -> Result<Json<WalkthroughGetResponse>, ErrorData> {
        let walkthrough_id = params.0.walkthrough_id;
        let parsed = parse_walkthrough_id(&walkthrough_id)?;

        let state = self.lock_state_synced().await?;
        let session_active_diagram_id =
            state.session.active_diagram_id().map(|diagram_id| diagram_id.as_str().to_owned());
        let walkthrough = state.session.walkthroughs().get(&parsed).ok_or_else(|| {
            ErrorData::resource_not_found(
                "walkthrough not found",
                Some(serde_json::json!({ "walkthrough_id": walkthrough_id })),
            )
        })?;

        let nodes = walkthrough
            .nodes()
            .iter()
            .map(|node| McpWalkthroughNode {
                node_id: node.node_id().as_str().to_owned(),
                title: node.title().to_owned(),
                body_md: node.body_md().map(|body| body.to_owned()),
                refs: node.refs().iter().map(ToString::to_string).collect(),
                tags: node.tags().to_vec(),
                status: node.status().map(|status| status.to_owned()),
            })
            .collect::<Vec<_>>();

        let edges = walkthrough
            .edges()
            .iter()
            .map(|edge| McpWalkthroughEdge {
                from_node_id: edge.from_node_id().as_str().to_owned(),
                to_node_id: edge.to_node_id().as_str().to_owned(),
                kind: edge.kind().to_owned(),
                label: edge.label().map(|label| label.to_owned()),
            })
            .collect::<Vec<_>>();
        let walkthrough = McpWalkthrough {
            walkthrough_id: walkthrough.walkthrough_id().as_str().to_owned(),
            title: walkthrough.title().to_owned(),
            rev: walkthrough.rev(),
            nodes,
            edges,
        };

        drop(state);
        let context = self.read_context(session_active_diagram_id).await;

        Ok(Json(WalkthroughGetResponse { walkthrough, context }))
    }

    /// Get one walkthrough node by id; use for drill-down after `walkthrough_list` or
    /// `walkthrough_read`.
    #[tool(name = "walkthrough_get_node")]
    pub(super) async fn walkthrough_get_node(
        &self,
        params: Parameters<WalkthroughGetNodeParams>,
    ) -> Result<Json<WalkthroughGetNodeResponse>, ErrorData> {
        let WalkthroughGetNodeParams { walkthrough_id, node_id } = params.0;
        let parsed_walkthrough_id = parse_walkthrough_id(&walkthrough_id)?;
        let parsed_node_id = parse_walkthrough_node_id(&node_id)?;

        let state = self.lock_state_synced().await?;
        let session_active_diagram_id =
            state.session.active_diagram_id().map(|diagram_id| diagram_id.as_str().to_owned());
        let walkthrough =
            state.session.walkthroughs().get(&parsed_walkthrough_id).ok_or_else(|| {
                ErrorData::resource_not_found(
                    "walkthrough not found",
                    Some(serde_json::json!({ "walkthrough_id": walkthrough_id.as_str() })),
                )
            })?;

        let node =
            walkthrough.nodes().iter().find(|node| node.node_id() == &parsed_node_id).ok_or_else(
                || {
                    ErrorData::resource_not_found(
                        "walkthrough node not found",
                        Some(serde_json::json!({
                            "walkthrough_id": walkthrough_id.as_str(),
                            "node_id": node_id.as_str(),
                        })),
                    )
                },
            )?;
        let node = McpWalkthroughNode {
            node_id: node.node_id().as_str().to_owned(),
            title: node.title().to_owned(),
            body_md: node.body_md().map(|body| body.to_owned()),
            refs: node.refs().iter().map(ToString::to_string).collect(),
            tags: node.tags().to_vec(),
            status: node.status().map(|status| status.to_owned()),
        };

        drop(state);
        let context = self.read_context(session_active_diagram_id).await;

        Ok(Json(WalkthroughGetNodeResponse { node, context }))
    }

    /// Read current walkthrough revision and counts; call before walkthrough mutations.
    #[tool(name = "walkthrough_stat")]
    pub(super) async fn walkthrough_stat(
        &self,
        params: Parameters<WalkthroughGetParams>,
    ) -> Result<Json<WalkthroughGetDigestResponse>, ErrorData> {
        let walkthrough_id = params.0.walkthrough_id;
        let parsed = parse_walkthrough_id(&walkthrough_id)?;

        let state = self.lock_state_synced().await?;
        let session_active_diagram_id =
            state.session.active_diagram_id().map(|diagram_id| diagram_id.as_str().to_owned());
        let walkthrough = state.session.walkthroughs().get(&parsed).ok_or_else(|| {
            ErrorData::resource_not_found(
                "walkthrough not found",
                Some(serde_json::json!({ "walkthrough_id": walkthrough_id })),
            )
        })?;
        let digest = digest_for_walkthrough(walkthrough);
        drop(state);
        let context = self.read_context(session_active_diagram_id).await;

        Ok(Json(WalkthroughGetDigestResponse { digest, context }))
    }

    /// Render walkthrough text for human-readable sharing/export; prefer
    /// `walkthrough_stat`/`walkthrough_read` for machine reasoning and follow-up edits.
    #[tool(name = "walkthrough_render_text")]
    pub(super) async fn walkthrough_render_text(
        &self,
        params: Parameters<WalkthroughGetParams>,
    ) -> Result<Json<WalkthroughRenderTextResponse>, ErrorData> {
        let walkthrough_id = params.0.walkthrough_id;
        let parsed = parse_walkthrough_id(&walkthrough_id)?;

        let state = self.lock_state_synced().await?;
        let session_active_diagram_id =
            state.session.active_diagram_id().map(|diagram_id| diagram_id.as_str().to_owned());
        let walkthrough = state.session.walkthroughs().get(&parsed).ok_or_else(|| {
            ErrorData::resource_not_found(
                "walkthrough not found",
                Some(serde_json::json!({ "walkthrough_id": walkthrough_id })),
            )
        })?;

        let text = render_walkthrough_unicode(walkthrough).map_err(|err| {
            ErrorData::invalid_request(
                format!("render error: {err}"),
                Some(serde_json::json!({ "walkthrough_id": walkthrough_id })),
            )
        })?;
        drop(state);
        let context = self.read_context(session_active_diagram_id).await;

        Ok(Json(WalkthroughRenderTextResponse { text, context }))
    }

    /// Read walkthrough delta since a revision; call after mutations to verify applied changes.
    #[tool(name = "walkthrough_diff")]
    pub(super) async fn walkthrough_diff(
        &self,
        params: Parameters<WalkthroughGetDeltaParams>,
    ) -> Result<Json<WalkthroughDeltaResponse>, ErrorData> {
        let walkthrough_id = params.0.walkthrough_id;
        let parsed = parse_walkthrough_id(&walkthrough_id)?;

        let state = self.lock_state_synced().await?;
        let walkthrough = state.session.walkthroughs().get(&parsed).ok_or_else(|| {
            ErrorData::resource_not_found(
                "walkthrough not found",
                Some(serde_json::json!({ "walkthrough_id": walkthrough_id })),
            )
        })?;

        let current_rev = walkthrough.rev();
        let since_rev = params.0.since_rev;
        if since_rev > current_rev {
            return Err(ErrorData::invalid_params(
                "since_rev must be <= current rev",
                Some(serde_json::json!({ "since_rev": since_rev, "current_rev": current_rev })),
            ));
        }

        if since_rev == current_rev {
            return Ok(Json(WalkthroughDeltaResponse {
                from_rev: current_rev,
                to_rev: current_rev,
                changes: Vec::new(),
            }));
        }

        let Some(history) = state.walkthrough_delta_history.get(&parsed) else {
            return Err(walkthrough_delta_unavailable(since_rev, current_rev, current_rev));
        };

        let supported_since_rev = history.front().map(|d| d.from_rev).unwrap_or(current_rev);
        if since_rev < supported_since_rev {
            return Err(walkthrough_delta_unavailable(since_rev, current_rev, supported_since_rev));
        }

        let Some(delta) = walkthrough_delta_response_from_history(history, since_rev, current_rev)
        else {
            return Err(walkthrough_delta_unavailable(since_rev, current_rev, supported_since_rev));
        };

        Ok(Json(delta))
    }

    /// Apply walkthrough ops using `base_rev` from `walkthrough_stat`; on conflict, refresh and retry.
    #[tool(name = "walkthrough_apply_ops")]
    pub(super) async fn walkthrough_apply_ops(
        &self,
        params: Parameters<WalkthroughApplyOpsParams>,
    ) -> Result<Json<ApplyOpsResponse>, ErrorData> {
        let WalkthroughApplyOpsParams { walkthrough_id, base_rev, ops } = params.0;
        let parsed = parse_walkthrough_id(&walkthrough_id)?;

        let mut state = self.lock_state_synced().await?;

        if let Some(session_folder) = &self.session_folder {
            let (candidate_session, history, response) = {
                let mut update = session_folder.begin_session_update().map_err(|err| {
                    ErrorData::internal_error(
                        format!("failed to reload session before save: {err}"),
                        Some(serde_json::json!({ "walkthrough_id": walkthrough_id, "base_rev": base_rev })),
                    )
                })?;
                let candidate_session = update.session_mut();
                let walkthrough =
                    candidate_session.walkthroughs_mut().get_mut(&parsed).ok_or_else(|| {
                        ErrorData::resource_not_found(
                            "walkthrough not found",
                            Some(serde_json::json!({ "walkthrough_id": walkthrough_id })),
                        )
                    })?;

                let current_rev = walkthrough.rev();
                if base_rev != current_rev {
                    let digest = digest_for_walkthrough(walkthrough);
                    return Err(ErrorData::invalid_request(
                        "conflict: stale base_rev",
                        Some(serde_json::json!({
                            "base_rev": base_rev,
                            "current_rev": current_rev,
                            "snapshot_tool": "walkthrough_stat",
                            "digest": {
                                "rev": digest.rev,
                                "counts": {
                                    "nodes": digest.counts.nodes,
                                    "edges": digest.counts.edges,
                                },
                            },
                        })),
                    ));
                }

                if ops.is_empty() {
                    return Ok(Json(ApplyOpsResponse {
                        new_rev: current_rev,
                        applied: 0,
                        delta: DeltaSummary {
                            added: Vec::new(),
                            removed: Vec::new(),
                            updated: Vec::new(),
                        },
                    }));
                }

                let delta = apply_walkthrough_ops(walkthrough, &parsed, &ops)?;
                walkthrough.bump_rev();
                let new_rev = walkthrough.rev();

                let mut history = state
                    .walkthrough_delta_history
                    .get(&parsed)
                    .cloned()
                    .unwrap_or_else(VecDeque::new);
                history.push_back(WalkthroughLastDelta {
                    from_rev: base_rev,
                    to_rev: new_rev,
                    delta: delta.clone(),
                });
                while history.len() > DELTA_HISTORY_LIMIT {
                    history.pop_front();
                }

                let candidate_session = update.commit().map_err(|err| {
                    ErrorData::internal_error(
                        format!("failed to persist session: {err}"),
                        Some(serde_json::json!({ "walkthrough_id": walkthrough_id, "base_rev": base_rev })),
                    )
                })?;

                let response = Json(ApplyOpsResponse {
                    new_rev,
                    applied: ops.len() as u64,
                    delta: DeltaSummary {
                        added: delta.added.iter().cloned().collect(),
                        removed: delta.removed.iter().cloned().collect(),
                        updated: delta.updated.iter().cloned().collect(),
                    },
                });

                (candidate_session, history, response)
            };

            replace_committed_session(&mut state, candidate_session);
            state.walkthrough_delta_history.insert(parsed, history);
            drop(state);
            self.notify_ui_session_changed().await;
            return Ok(response);
        }

        let walkthrough = state.session.walkthroughs_mut().get_mut(&parsed).ok_or_else(|| {
            ErrorData::resource_not_found(
                "walkthrough not found",
                Some(serde_json::json!({ "walkthrough_id": walkthrough_id })),
            )
        })?;

        let current_rev = walkthrough.rev();
        if base_rev != current_rev {
            let digest = digest_for_walkthrough(walkthrough);
            return Err(ErrorData::invalid_request(
                "conflict: stale base_rev",
                Some(serde_json::json!({
                    "base_rev": base_rev,
                    "current_rev": current_rev,
                    "snapshot_tool": "walkthrough_stat",
                    "digest": {
                        "rev": digest.rev,
                        "counts": {
                            "nodes": digest.counts.nodes,
                            "edges": digest.counts.edges,
                        },
                    },
                })),
            ));
        }

        if ops.is_empty() {
            return Ok(Json(ApplyOpsResponse {
                new_rev: current_rev,
                applied: 0,
                delta: DeltaSummary { added: Vec::new(), removed: Vec::new(), updated: Vec::new() },
            }));
        }

        let mut candidate = walkthrough.clone();
        let delta = apply_walkthrough_ops(&mut candidate, &parsed, &ops)?;
        candidate.bump_rev();
        let new_rev = candidate.rev();
        *walkthrough = candidate;

        let history = state.walkthrough_delta_history.entry(parsed).or_insert_with(VecDeque::new);
        history.push_back(WalkthroughLastDelta {
            from_rev: base_rev,
            to_rev: new_rev,
            delta: delta.clone(),
        });
        while history.len() > DELTA_HISTORY_LIMIT {
            history.pop_front();
        }

        let response = Json(ApplyOpsResponse {
            new_rev,
            applied: ops.len() as u64,
            delta: DeltaSummary {
                added: delta.added.iter().cloned().collect(),
                removed: delta.removed.iter().cloned().collect(),
                updated: delta.updated.iter().cloned().collect(),
            },
        });
        drop(state);
        self.notify_ui_session_changed().await;
        Ok(response)
    }
}