crabrix 0.5.0

Rust SDK and MCP launcher for end-to-end encrypted, temporary Crabrix Playgrounds shared by AI agents and people. Node.js 22+ required.
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! Typed Rust access to Crabrix's temporary encrypted Playground rooms.
//!
//! This SDK uses the same bundled local JavaScript protocol core as the npm SDK.
//! **Node.js 22+ is required**, but no npm install or iPhone app is needed.
//! It never compiles source on the relay. A browser/app must explicitly allow
//! local Run/Debug. Source and capability links are never logged by this SDK.
//!
//! ```no_run
//! use crabrix::{Client, CreateOptions};
//! let mut client = Client::new()?;
//! let room = client.create(&CreateOptions::new("Rust agent exercise"))?;
//! let source = client.read("main.rs")?;
//! assert!(!source.revision.is_empty());
//! // Explicit secret handoff; deliver only to the intended recipient.
//! let handoff = client.share("edit")?;
//! assert_eq!(handoff.mode, "edit");
//! # Ok::<(), crabrix::Error>(())
//! ```
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::{
    collections::BTreeMap,
    fmt,
    io::{BufRead, BufReader, Read, Write},
    path::PathBuf,
    process::{Child, ChildStdin, Command, Stdio},
    sync::mpsc::{self, Receiver},
    time::{Duration, Instant},
};

const BRIDGE: &str = include_str!("../runtime/bridge.mjs");
const MAX_LINE: usize = 2_000_000;

#[derive(Debug)]
pub struct Error(String, Option<String>);
impl Error {
    /// The bridge's stable reason, such as `REVISION_CONFLICT`, when it gave one.
    pub fn code(&self) -> Option<&str> {
        self.1.as_deref()
    }
}
impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}
impl std::error::Error for Error {}
impl From<std::io::Error> for Error {
    fn from(_: std::io::Error) -> Self {
        Self(
            "Crabrix local transport failed; no private source or link was logged.".into(),
            None,
        )
    }
}
impl From<serde_json::Error> for Error {
    fn from(_: serde_json::Error) -> Self {
        Self("Invalid Crabrix protocol JSON.".into(), None)
    }
}
pub type Result<T> = std::result::Result<T, Error>;

/// No network installation is performed. `node` is a local trusted executable.
#[derive(Clone, Debug)]
pub struct Options {
    pub node: PathBuf,
    pub timeout: Duration,
    pub name: String,
}
impl Default for Options {
    fn default() -> Self {
        Self {
            node: "node".into(),
            timeout: Duration::from_secs(30),
            name: "Rust agent".into(),
        }
    }
}

#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CreateOptions {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub files: Option<BTreeMap<String, String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entry_file: Option<String>,
    pub lifetime_minutes: u16,
}
impl CreateOptions {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            files: None,
            entry_file: None,
            lifetime_minutes: 60,
        }
    }
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Change {
    pub path: String,
    pub text: Option<String>,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplyOptions {
    pub expected_revision: String,
    pub changes: Vec<Change>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entry_file: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}
#[derive(Clone, Deserialize)]
pub struct SourceFile {
    pub path: String,
    pub text: String,
    pub revision: String,
}
/// A capability URL. Debug formatting deliberately redacts the link.
#[derive(Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Handoff {
    pub schema: String,
    pub link_type: String,
    pub link: String,
    pub expires_at: String,
    pub revision: String,
    pub mode: String,
}
impl fmt::Debug for Handoff {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Handoff")
            .field("link", &"[REDACTED]")
            .field("mode", &self.mode)
            .field("expires_at", &self.expires_at)
            .finish()
    }
}

pub struct Client {
    child: Child,
    input: Option<ChildStdin>,
    replies: Receiver<Result<Value>>,
    next_id: u64,
    options: Options,
    _directory: tempfile::TempDir,
    closed: bool,
}
impl Client {
    pub fn new() -> Result<Self> {
        Self::with_options(Options::default())
    }
    pub fn with_options(options: Options) -> Result<Self> {
        if options.timeout < Duration::from_millis(1) || options.timeout > Duration::from_secs(120)
        {
            return Err(Error(
                "Choose a transport timeout from 1 ms to 120 seconds.".into(),
                None,
            ));
        }
        let directory = tempfile::tempdir()?;
        let file = directory.path().join("bridge.mjs");
        std::fs::write(&file, BRIDGE)?;
        let mut child=command(&options.node,&file).arg("--name").arg(&options.name).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().map_err(|_|Error("Cannot start Crabrix. Install Node.js 22+ or set Options.node to its trusted executable.".into(), None))?;
        let input = child.stdin.take();
        let output = child
            .stdout
            .take()
            .ok_or_else(|| Error("Cannot open Crabrix output.".into(), None))?;
        // A bounded queue and bounded lines prevent an unresponsive consumer from
        // accumulating notifications or plaintext source without limit.
        let (sender, replies) = mpsc::sync_channel(16);
        std::thread::spawn(move || {
            let mut reader = BufReader::new(output);
            loop {
                let mut line = Vec::new();
                let result = reader
                    .by_ref()
                    .take((MAX_LINE + 1) as u64)
                    .read_until(b'\n', &mut line);
                match result {
                    Ok(0) => break,
                    Ok(_) if line.len() <= MAX_LINE => {
                        let value = serde_json::from_slice(&line).map_err(Error::from);
                        let invalid = value.is_err();
                        if sender.try_send(value).is_err() || invalid {
                            break;
                        }
                    }
                    _ => {
                        let _ = sender.try_send(Err(Error(
                            "Crabrix protocol frame exceeds its limit.".into(),
                            None,
                        )));
                        break;
                    }
                }
            }
        });
        let mut client = Self {
            child,
            input,
            replies,
            next_id: 1,
            options,
            _directory: directory,
            closed: false,
        };
        client.rpc("initialize",json!({"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"crabrix-rust-sdk","version":env!("CARGO_PKG_VERSION")}}))?;
        client.notify("notifications/initialized", json!({}))?;
        Ok(client)
    }
    fn send(&mut self, value: &Value) -> Result<()> {
        if self.closed {
            return Err(Error("This Crabrix client is closed.".into(), None));
        }
        let mut bytes = serde_json::to_vec(value)?;
        if bytes.len() > MAX_LINE {
            return Err(Error("Crabrix request exceeds its limit.".into(), None));
        }
        bytes.push(b'\n');
        let input = self
            .input
            .as_mut()
            .ok_or_else(|| Error("Crabrix input is closed.".into(), None))?;
        input.write_all(&bytes)?;
        input.flush()?;
        Ok(())
    }
    fn notify(&mut self, method: &str, params: Value) -> Result<()> {
        self.send(&json!({"jsonrpc":"2.0","method":method,"params":params}))
    }
    fn rpc(&mut self, method: &str, params: Value) -> Result<Value> {
        let id = self.next_id;
        self.next_id += 1;
        self.send(&json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}))?;
        let deadline = Instant::now() + self.options.timeout;
        for _ in 0..64 {
            let Some(wait) = deadline.checked_duration_since(Instant::now()) else {
                break;
            };
            let value = match self.replies.recv_timeout(wait) {
                Ok(value) => value?,
                Err(_) => break,
            };
            if value.get("id").and_then(Value::as_u64) != Some(id) {
                continue;
            }
            if value.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
                self.close();
                return Err(Error("Invalid Crabrix RPC response.".into(), None));
            }
            if value.get("error").is_some() {
                return Err(Error("Crabrix rejected the protocol request.".into(), None));
            }
            return value
                .get("result")
                .cloned()
                .ok_or_else(|| Error("Missing Crabrix RPC result.".into(), None));
        }
        self.close();
        Err(Error("Crabrix request timed out or disconnected. Its outcome may be unknown; reconcile before retrying an edit or execution.".into(), None))
    }
    /// Calls one allowlisted room tool; no arbitrary shell command exists.
    pub fn call(&mut self, name: &str, arguments: Value) -> Result<Value> {
        const TOOLS: &[&str] = &[
            "crabrix_create",
            "crabrix_connect",
            "crabrix_status",
            "crabrix_snapshot",
            "crabrix_read_file",
            "crabrix_apply_changes",
            "crabrix_select",
            "crabrix_plan_changes",
            "crabrix_apply_operations",
            "crabrix_handoff",
            "crabrix_disconnect",
            "crabrix_end_room",
            "crabrix_runtime_clients",
            "crabrix_runtime_request",
            "crabrix_runtime_start",
            "crabrix_runtime_job",
            "crabrix_runtime_inspect",
            "crabrix_runtime_control",
        ];
        if !TOOLS.contains(&name) {
            return Err(Error("Unknown Crabrix room tool.".into(), None));
        }
        let result = self.rpc("tools/call", json!({"name":name,"arguments":arguments}))?;
        if result.get("isError") == Some(&Value::Bool(true)) {
            let message = result
                .pointer("/content/0/text")
                .and_then(Value::as_str)
                .unwrap_or("Crabrix operation failed.");
            let code = result
                .pointer("/structuredContent/error/code")
                .and_then(Value::as_str)
                .map(str::to_owned);
            return Err(Error(message.chars().take(400).collect(), code));
        }
        if let Some(value) = result.get("structuredContent") {
            return Ok(value.clone());
        }
        let text = result
            .pointer("/content/0/text")
            .and_then(Value::as_str)
            .ok_or_else(|| Error("Missing Crabrix tool result.".into(), None))?;
        Ok(serde_json::from_str(text)?)
    }
    pub fn create(&mut self, options: &CreateOptions) -> Result<Value> {
        self.call("crabrix_create", serde_json::to_value(options)?)
    }
    /// Like `create`, with Rust edition `2021` or `2024`.
    pub fn create_with_edition(&mut self, options: &CreateOptions, edition: &str) -> Result<Value> {
        let mut args = serde_json::to_value(options)?;
        args["edition"] = json!(edition);
        self.call("crabrix_create", args)
    }
    pub fn connect(&mut self, link: &str) -> Result<Value> {
        self.call("crabrix_connect", json!({"link":link}))
    }
    pub fn status(&mut self) -> Result<Value> {
        self.call("crabrix_status", json!({}))
    }
    pub fn snapshot(&mut self) -> Result<Value> {
        self.call("crabrix_snapshot", json!({}))
    }
    pub fn read(&mut self, path: &str) -> Result<SourceFile> {
        Ok(serde_json::from_value(
            self.call("crabrix_read_file", json!({"path":path}))?,
        )?)
    }
    pub fn apply(&mut self, options: &ApplyOptions) -> Result<Value> {
        self.call("crabrix_apply_changes", serde_json::to_value(options)?)
    }
    /// Like `apply`, also setting Rust edition `2021` or `2024`. This changes the revision.
    pub fn apply_with_edition(&mut self, options: &ApplyOptions, edition: &str) -> Result<Value> {
        let mut args = serde_json::to_value(options)?;
        args["edition"] = json!(edition);
        self.call("crabrix_apply_changes", args)
    }
    pub fn select(
        &mut self,
        path: &str,
        anchor: u32,
        head: u32,
        expected_revision: &str,
    ) -> Result<Value> {
        self.call(
            "crabrix_select",
            json!({"path":path,"anchor":anchor,"head":head,"expectedRevision":expected_revision}),
        )
    }
    /// Checks up to 32 file operations in a format 2 (stable file ID) room without
    /// changing anything, e.g. `json!([{"kind":"move","file":{"path":"a.rs"},"path":"src/a.rs"}])`.
    /// Returns the plan, its revision and `planHash`.
    pub fn plan_changes(&mut self, operations: Value) -> Result<Value> {
        self.call("crabrix_plan_changes", json!({"operations":operations}))
    }
    /// Applies a reviewed plan once. Retrying with the same `operation_id` and
    /// operations reports `alreadyApplied` instead of applying twice.
    pub fn apply_operations(
        &mut self,
        operations: Value,
        expected_revision: &str,
        plan_hash: &str,
        operation_id: &str,
    ) -> Result<Value> {
        self.call(
            "crabrix_apply_operations",
            json!({"operations":operations,"expectedRevision":expected_revision,"planHash":plan_hash,"operationId":operation_id}),
        )
    }
    pub fn share(&mut self, mode: &str) -> Result<Handoff> {
        Ok(serde_json::from_value(
            self.call("crabrix_handoff", json!({"mode":mode}))?,
        )?)
    }
    pub fn runtime_clients(&mut self) -> Result<Value> {
        self.call("crabrix_runtime_clients", json!({}))
    }
    pub fn request_runtime(&mut self, target: &str, operations: &[&str]) -> Result<Value> {
        self.call(
            "crabrix_runtime_request",
            json!({"target":target,"operations":operations}),
        )
    }
    pub fn start(&mut self, target: &str, operation: &str, source_revision: &str) -> Result<Value> {
        self.call(
            "crabrix_runtime_start",
            json!({"target":target,"operation":operation,"sourceRevision":source_revision}),
        )
    }
    pub fn job(
        &mut self,
        target: &str,
        source_revision: &str,
        job: &str,
        operation: &str,
        options: Value,
    ) -> Result<Value> {
        self.job_tool(
            "crabrix_runtime_job",
            target,
            source_revision,
            job,
            operation,
            options,
        )
    }
    fn job_tool(
        &mut self,
        tool: &str,
        target: &str,
        source_revision: &str,
        job: &str,
        operation: &str,
        options: Value,
    ) -> Result<Value> {
        let mut args = options
            .as_object()
            .cloned()
            .ok_or_else(|| Error("Job options must be an object.".into(), None))?;
        for (k, v) in [
            ("target", target),
            ("sourceRevision", source_revision),
            ("job", job),
            ("operation", operation),
        ] {
            args.insert(k.into(), Value::String(v.into()));
        }
        self.call(tool, Value::Object(args))
    }
    /// Reads a job's status or output without changing it.
    pub fn inspect(
        &mut self,
        target: &str,
        source_revision: &str,
        job: &str,
        operation: &str,
        options: Value,
    ) -> Result<Value> {
        self.job_tool(
            "crabrix_runtime_inspect",
            target,
            source_revision,
            job,
            operation,
            options,
        )
    }
    /// Stops or steps a job this controller owns.
    pub fn control(
        &mut self,
        target: &str,
        source_revision: &str,
        job: &str,
        operation: &str,
        options: Value,
    ) -> Result<Value> {
        self.job_tool(
            "crabrix_runtime_control",
            target,
            source_revision,
            job,
            operation,
            options,
        )
    }
    pub fn end_room(&mut self) -> Result<Value> {
        self.call("crabrix_end_room", json!({}))
    }
    pub fn disconnect(&mut self) -> Result<Value> {
        self.call("crabrix_disconnect", json!({}))
    }
    pub fn close(&mut self) {
        if self.closed {
            return;
        }
        self.closed = true;
        self.input.take();
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}
impl Drop for Client {
    fn drop(&mut self) {
        self.close();
    }
}
fn command(node: &std::path::Path, file: &std::path::Path) -> Command {
    let mut cmd = Command::new(node);
    cmd.arg(file)
        .env_remove("NODE_OPTIONS")
        .env_remove("NODE_PATH");
    cmd
}
/// Run the bundled `crabrix doctor` diagnostics. It opens no room and reads no source.
pub fn doctor(json_output: bool) -> Result<i32> {
    let directory = tempfile::tempdir()?;
    let file = directory.path().join("bridge.mjs");
    std::fs::write(&file, BRIDGE)?;
    let mut cmd = command(std::path::Path::new("node"), &file);
    cmd.arg("doctor");
    if json_output {
        cmd.arg("--json");
    }
    Ok(cmd.status()?.code().unwrap_or(1))
}
/// Run the exact bundled MCP server over stdio, without an npm download.
pub fn serve_mcp() -> Result<i32> {
    use std::sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    };
    let directory = tempfile::tempdir()?;
    let file = directory.path().join("bridge.mjs");
    std::fs::write(&file, BRIDGE)?;
    let stopping = Arc::new(AtomicBool::new(false));
    let signal = stopping.clone();
    ctrlc::set_handler(move || {
        signal.store(true, Ordering::SeqCst);
    })
    .map_err(|_| Error("Cannot install Crabrix MCP signal handler.".into(), None))?;
    let mut child = command(std::path::Path::new("node"), &file)
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .spawn()?;
    loop {
        if stopping.load(Ordering::SeqCst) {
            let _ = child.kill();
            let _ = child.wait();
            return Ok(130);
        }
        if let Some(status) = child.try_wait()? {
            return Ok(status.code().unwrap_or(1));
        }
        std::thread::sleep(Duration::from_millis(30));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn disconnected_stdio_is_real() {
        let mut c = Client::new().unwrap();
        assert_eq!(c.status().unwrap()["connected"], false);
        assert!(c.call("shell", json!({})).is_err());
        let e = c
            .connect("https://example.com/#private-never-return")
            .unwrap_err();
        assert!(!e.to_string().contains("private-never-return"));
        assert_eq!(e.code(), Some("INVALID_LINK"));
        let operations = json!([{"kind":"create","path":"notes.md","text":"x"}]);
        let e = c.plan_changes(operations.clone()).unwrap_err();
        assert_eq!(e.code(), Some("NOT_CONNECTED"));
        let e = c
            .apply_operations(
                operations,
                &"a".repeat(32),
                &"b".repeat(32),
                "rust-operation-1",
            )
            .unwrap_err();
        assert_eq!(e.code(), Some("NOT_CONNECTED"));
        let e = c
            .create_with_edition(&CreateOptions::new("Old edition"), "2018")
            .unwrap_err();
        assert!(!e.to_string().is_empty());
        c.close();
        assert!(c.status().is_err());
    }

    #[test]
    fn flag_like_participant_names_start_the_embedded_server() {
        for name in ["--help", "--version"] {
            let mut client = Client::with_options(Options {
                name: name.into(),
                ..Options::default()
            })
            .unwrap();
            assert_eq!(client.status().unwrap()["connected"], false);
        }
    }
    #[test]
    fn handoff_debug_redacts_capabilities() {
        let h = Handoff {
            schema: "crabrix-handoff-v1".into(),
            link_type: "temporary edit Playground".into(),
            link: "private-key".into(),
            expires_at: "date".into(),
            revision: "rev".into(),
            mode: "edit".into(),
        };
        assert!(!format!("{h:?}").contains("private-key"));
    }
    #[test]
    fn timeout_is_bounded() {
        assert!(
            Client::with_options(Options {
                timeout: Duration::ZERO,
                ..Options::default()
            })
            .is_err()
        );
    }
}