scrybe-tools 0.6.3

Scrybe tools — one ToolSpec registry shared by the CLI and the MCP server
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Shawn Hartsock and contributors

//! UI-parity + app-control tools — `state`, `set_theme`, `view_mode`,
//! `set_vim`, `logs`, `quit`, `close_tab` — dispatched to the live app over
//! typed socket methods (workstream A2). These replace the legacy MCP
//! handlers' `/tmp` signal files and `pkill` fallback: every control now
//! drives the same code path as the human toolbar and reports what actually
//! happened. With no live app they return a business `no_live_app`
//! tool_error, never an engine fault.

use serde_json::{json, Value};

use super::editor::{dispatch, str_arg};
use crate::{DataSchema, Facet, ToolSpec};

const DATA_VERSION: u32 = 1;

/// All UI-parity tools, in one call for registration.
pub(crate) fn specs() -> Vec<ToolSpec> {
    vec![
        state_spec(),
        set_theme_spec(),
        view_mode_spec(),
        set_vim_spec(),
        logs_spec(),
        quit_spec(),
        close_tab_spec(),
    ]
}

/// `quit` and `close_tab` share the socket's fire-and-forget ack shape.
fn ack_schema(kind: &'static str) -> Value {
    crate::schema::envelope(
        kind,
        DATA_VERSION,
        json!({
            "applied": { "type": "boolean", "description": "False when the command was a no-op (e.g. the path was not an open tab)." }
        }),
        &["applied"],
    )
}

// ── state ────────────────────────────────────────────────────────────────────

fn state_spec() -> ToolSpec {
    ToolSpec {
        name: "state",
        description: "Report the running Scrybe app's current UI state: the \
            active tab's path/title/dirty flag, view mode, theme, Vim and wrap \
            toggles, and every open path. Served live from the frontend — the \
            human equivalents are the path bar, tab mode icon, theme dropdown, \
            and Vim toggle.",
        input_schema: || json!({ "type": "object", "properties": {} }),
        data_schema: DataSchema {
            version: DATA_VERSION,
            schema: || {
                crate::schema::envelope(
                    "state",
                    DATA_VERSION,
                    json!({
                        "active_path": { "type": ["string", "null"], "description": "Canonical path of the active tab (null on the welcome screen)." },
                        "active_title": { "type": ["string", "null"] },
                        "is_dirty": { "type": "boolean" },
                        "view_mode": { "type": "string", "enum": ["both", "edit", "preview"] },
                        "theme": { "type": "string" },
                        "vim": { "type": "boolean" },
                        "wrap": { "type": "boolean" },
                        "open_paths": { "type": "array", "items": { "type": "string" } }
                    }),
                    &[
                        "active_path",
                        "active_title",
                        "is_dirty",
                        "view_mode",
                        "theme",
                        "vim",
                        "wrap",
                        "open_paths",
                    ],
                )
            },
        },
        mutates: false,
        facet: Facet::UiParity,
        handler: |ctx, _args| dispatch(ctx, "state", "state", json!({})),
    }
}

// ── set_theme ────────────────────────────────────────────────────────────────

fn set_theme_spec() -> ToolSpec {
    ToolSpec {
        name: "set_theme",
        description: "Set the editor + preview theme in the running Scrybe app \
            (same entry point as the toolbar dropdown). Returns the applied \
            theme.",
        input_schema: || {
            json!({
                "type": "object",
                "properties": {
                    "theme": { "type": "string", "enum": ["default", "dark", "solarized"] }
                },
                "required": ["theme"]
            })
        },
        data_schema: DataSchema {
            version: DATA_VERSION,
            schema: || {
                crate::schema::envelope(
                    "set_theme",
                    DATA_VERSION,
                    json!({
                        "theme": {
                            "type": "string",
                            "enum": ["default", "dark", "solarized"],
                            "description": "The theme now applied."
                        }
                    }),
                    &["theme"],
                )
            },
        },
        mutates: true,
        facet: Facet::UiParity,
        handler: |ctx, args| {
            dispatch(
                ctx,
                "set_theme",
                "set_theme",
                json!({ "theme": str_arg(args, "theme") }),
            )
        },
    }
}

// ── view_mode ────────────────────────────────────────────────────────────────

fn view_mode_spec() -> ToolSpec {
    ToolSpec {
        name: "view_mode",
        description: "Set the active tab's view mode in the running Scrybe app \
            — `both`, `edit`, `preview`, or `cycle` to advance both→edit→preview \
            (same entry point as the toolbar View button). Returns the CONCRETE \
            mode now active (a code/text tab pins to `edit`).",
        input_schema: || {
            json!({
                "type": "object",
                "properties": {
                    "mode": { "type": "string", "enum": ["both", "edit", "preview", "cycle"] }
                },
                "required": ["mode"]
            })
        },
        data_schema: DataSchema {
            version: DATA_VERSION,
            schema: || {
                crate::schema::envelope(
                    "view_mode",
                    DATA_VERSION,
                    json!({
                        "mode": {
                            "type": "string",
                            "enum": ["both", "edit", "preview"],
                            "description": "The CONCRETE mode now active (never `cycle`)."
                        }
                    }),
                    &["mode"],
                )
            },
        },
        mutates: true,
        facet: Facet::UiParity,
        handler: |ctx, args| {
            dispatch(
                ctx,
                "view_mode",
                "view_mode",
                json!({ "mode": str_arg(args, "mode") }),
            )
        },
    }
}

// ── set_vim ──────────────────────────────────────────────────────────────────

fn set_vim_spec() -> ToolSpec {
    ToolSpec {
        name: "set_vim",
        description: "Enable or disable Vim keybindings in the running Scrybe \
            editor (same entry point as the toolbar Vim toggle). Returns the \
            applied setting.",
        input_schema: || {
            json!({
                "type": "object",
                "properties": { "enabled": { "type": "boolean" } },
                "required": ["enabled"]
            })
        },
        data_schema: DataSchema {
            version: DATA_VERSION,
            schema: || {
                crate::schema::envelope(
                    "set_vim",
                    DATA_VERSION,
                    json!({
                        "enabled": { "type": "boolean", "description": "The setting now applied." }
                    }),
                    &["enabled"],
                )
            },
        },
        mutates: true,
        facet: Facet::UiParity,
        handler: |ctx, args| {
            let enabled = args
                .get("enabled")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            dispatch(ctx, "set_vim", "set_vim", json!({ "enabled": enabled }))
        },
    }
}

// ── logs ─────────────────────────────────────────────────────────────────────

fn logs_spec() -> ToolSpec {
    ToolSpec {
        name: "logs",
        description: "Read recent console output from the running Scrybe app \
            (errors, warnings, info) — newest last, up to `tail` lines (default \
            50). Served from the app's in-memory ring; nothing is written to \
            disk.",
        input_schema: || {
            json!({
                "type": "object",
                "properties": {
                    "tail": { "type": "integer", "minimum": 1, "maximum": 500 }
                }
            })
        },
        data_schema: DataSchema {
            version: DATA_VERSION,
            schema: || {
                crate::schema::envelope(
                    "logs",
                    DATA_VERSION,
                    json!({
                        "lines": {
                            "type": "array",
                            "items": { "type": "string" },
                            "description": "Recent console lines, newest last."
                        }
                    }),
                    &["lines"],
                )
            },
        },
        mutates: false,
        facet: Facet::UiParity,
        handler: |ctx, args| {
            let tail = args.get("tail").and_then(Value::as_u64);
            dispatch(ctx, "logs", "logs", json!({ "tail": tail }))
        },
    }
}

// ── quit ─────────────────────────────────────────────────────────────────────

fn quit_spec() -> ToolSpec {
    ToolSpec {
        name: "quit",
        description: "Gracefully close the running Scrybe app via the socket. \
            The app runs its dirty-buffer checks and may refuse (unsaved \
            edits); pass `force: true` to discard them. Never signals or kills \
            processes.",
        input_schema: || {
            json!({
                "type": "object",
                "properties": {
                    "force": { "type": "boolean", "description": "Quit even with unsaved edits." }
                }
            })
        },
        data_schema: DataSchema {
            version: DATA_VERSION,
            schema: || ack_schema("quit"),
        },
        mutates: true,
        facet: Facet::UiParity,
        handler: |ctx, args| {
            let force = args.get("force").and_then(Value::as_bool).unwrap_or(false);
            dispatch(ctx, "quit", "quit", json!({ "force": force }))
        },
    }
}

// ── close_tab ────────────────────────────────────────────────────────────────

fn close_tab_spec() -> ToolSpec {
    ToolSpec {
        name: "close_tab",
        description: "Close an open tab in the running Scrybe app by its \
            canonical `path`. (Closing the active tab without naming it was a \
            legacy /tmp-signal behavior and is retired — name the path.)",
        input_schema: || {
            json!({
                "type": "object",
                "properties": { "path": { "type": "string" } },
                "required": ["path"]
            })
        },
        data_schema: DataSchema {
            version: DATA_VERSION,
            schema: || ack_schema("close_tab"),
        },
        mutates: true,
        facet: Facet::UiParity,
        handler: |ctx, args| {
            dispatch(
                ctx,
                "close",
                "close_tab",
                json!({ "path": str_arg(args, "path") }),
            )
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Ctx, Registry, Transport, TransportError};

    struct Spy {
        reply: Value,
        seen: std::sync::Mutex<Option<(String, Value)>>,
    }
    impl Transport for Spy {
        fn call(&self, method: &str, params: Value) -> Result<Value, TransportError> {
            *self.seen.lock().unwrap() = Some((method.to_string(), params));
            Ok(self.reply.clone())
        }
        fn is_live(&self) -> bool {
            true
        }
    }

    #[test]
    fn all_ui_tools_registered_and_no_app_is_business_failure() {
        let reg = Registry::default();
        for name in [
            "state",
            "set_theme",
            "view_mode",
            "set_vim",
            "logs",
            "quit",
            "close_tab",
        ] {
            assert!(reg.get(name).is_some(), "missing tool: {name}");
        }
        let out = reg.call("state", &Ctx::headless(), &json!({})).unwrap();
        assert!(!out.is_ok());
        assert_eq!(out.tool_error.unwrap().code, "no_live_app");
    }

    #[test]
    fn set_theme_forwards_theme_and_wraps_reply() {
        let spy = std::sync::Arc::new(Spy {
            reply: json!({ "theme": "dark" }),
            seen: std::sync::Mutex::new(None),
        });
        struct Fwd(std::sync::Arc<Spy>);
        impl Transport for Fwd {
            fn call(&self, m: &str, p: Value) -> Result<Value, TransportError> {
                self.0.call(m, p)
            }
            fn is_live(&self) -> bool {
                true
            }
        }
        let reg = Registry::default();
        let out = reg
            .call(
                "set_theme",
                &Ctx::with_transport(Box::new(Fwd(spy.clone()))),
                &json!({ "theme": "dark" }),
            )
            .unwrap();
        assert!(out.is_ok());
        assert_eq!(out.data["kind"], "set_theme");
        assert_eq!(out.data["theme"], "dark");
        let (method, params) = spy.seen.lock().unwrap().clone().unwrap();
        assert_eq!(method, "set_theme");
        assert_eq!(params["theme"], "dark");
    }

    #[test]
    fn close_tab_dispatches_the_socket_close_method() {
        let spy = std::sync::Arc::new(Spy {
            reply: json!({ "applied": true }),
            seen: std::sync::Mutex::new(None),
        });
        struct Fwd(std::sync::Arc<Spy>);
        impl Transport for Fwd {
            fn call(&self, m: &str, p: Value) -> Result<Value, TransportError> {
                self.0.call(m, p)
            }
            fn is_live(&self) -> bool {
                true
            }
        }
        let reg = Registry::default();
        let out = reg
            .call(
                "close_tab",
                &Ctx::with_transport(Box::new(Fwd(spy.clone()))),
                &json!({ "path": "/a.md" }),
            )
            .unwrap();
        assert!(out.is_ok());
        let (method, params) = spy.seen.lock().unwrap().clone().unwrap();
        assert_eq!(method, "close", "close_tab rides the socket `close` method");
        assert_eq!(params["path"], "/a.md");
    }

    #[test]
    fn mutability_flags_are_honest() {
        let reg = Registry::default();
        for (name, mutates) in [
            ("state", false),
            ("logs", false),
            ("set_theme", true),
            ("view_mode", true),
            ("set_vim", true),
            ("quit", true),
            ("close_tab", true),
        ] {
            assert_eq!(reg.get(name).unwrap().mutates, mutates, "tool {name}");
        }
    }
}