truecalc-mcp 3.2.0

MCP server exposing truecalc formula evaluation as a tool for AI assistants
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
// truecalc MCP server — hand-rolled JSON-RPC over stdio (MCP protocol 2024-11-05)

use std::collections::HashMap;
use std::io::{self, BufRead, Write};

use truecalc_core::{Engine, Expr, Registry, Value};
use truecalc_workbook::{Address, CellInput, EngineFlavor as WbEngine, RecalcContext, Value as WbValue, Workbook};
use serde_json::{json, Value as JsonValue};

// ─── Conformance ─────────────────────────────────────────────────────────────

struct Engines {
    google_sheets: Engine,
}

impl Engines {
    fn new() -> Self {
        Self { google_sheets: Engine::sheets() }
    }

    fn select(&self, conformance: &str) -> Option<&Engine> {
        match conformance {
            "google-sheets" => Some(&self.google_sheets),
            _ => None,
        }
    }
}

fn parse_conformance_arg(args: &[String]) -> String {
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        if arg == "--conformance" {
            if let Some(val) = iter.next() {
                return val.clone();
            }
        }
    }
    "google-sheets".to_string()
}

// ─── Session store ────────────────────────────────────────────────────────────

const MAX_WORKBOOKS: usize = 32;
const MAX_TOTAL_BYTES: usize = 256 * 1024 * 1024;

struct SessionStore {
    workbooks: std::collections::HashMap<String, Workbook>,
    total_json_bytes: usize,
    next_id: u64,
}

impl SessionStore {
    fn new() -> Self {
        Self { workbooks: std::collections::HashMap::new(), total_json_bytes: 0, next_id: 0 }
    }

    fn allocate_id(&mut self) -> String {
        let id = format!("wb_{}", self.next_id);
        self.next_id += 1;
        id
    }

    fn create(&mut self, engine: WbEngine) -> Result<String, String> {
        if self.workbooks.len() >= MAX_WORKBOOKS {
            return Err(format!("session limit reached: max {} workbooks per process", MAX_WORKBOOKS));
        }
        let id = self.allocate_id();
        self.workbooks.insert(id.clone(), Workbook::new(engine));
        Ok(id)
    }

    fn import(&mut self, json: &str) -> Result<String, String> {
        if self.workbooks.len() >= MAX_WORKBOOKS {
            return Err(format!("session limit reached: max {} workbooks per process", MAX_WORKBOOKS));
        }
        if self.total_json_bytes.saturating_add(json.len()) > MAX_TOTAL_BYTES {
            return Err(format!("memory limit would be exceeded: aggregate session size capped at {} MiB", MAX_TOTAL_BYTES / (1024 * 1024)));
        }
        let wb = Workbook::from_json(json.as_bytes()).map_err(|e| e.to_string())?;
        let id = self.allocate_id();
        self.total_json_bytes = self.total_json_bytes.saturating_add(json.len());
        self.workbooks.insert(id.clone(), wb);
        Ok(id)
    }

    fn get_mut(&mut self, id: &str) -> Option<&mut Workbook> {
        self.workbooks.get_mut(id)
    }
}

// ─── Entry point ─────────────────────────────────────────────────────────────

fn main() {
    let cli_args: Vec<String> = std::env::args().collect();
    let default_conformance = parse_conformance_arg(&cli_args);
    let engines = Engines::new();
    let mut session_store = SessionStore::new();

    let stdin = io::stdin();
    let stdout = io::stdout();
    let mut out = stdout.lock();

    for line in stdin.lock().lines() {
        let line = match line {
            Ok(l) => l,
            Err(_) => break,
        };
        if line.is_empty() {
            continue;
        }

        let request: JsonValue = match serde_json::from_str(&line) {
            Ok(v) => v,
            Err(_) => {
                let err = json!({
                    "jsonrpc": "2.0",
                    "id": null,
                    "error": { "code": -32700, "message": "Parse error" }
                });
                writeln!(out, "{}", serde_json::to_string(&err).unwrap()).unwrap();
                out.flush().unwrap();
                continue;
            }
        };

        if !request.is_object() {
            let err = json!({
                "jsonrpc": "2.0",
                "id": null,
                "error": { "code": -32700, "message": "Parse error" }
            });
            writeln!(out, "{}", serde_json::to_string(&err).unwrap()).unwrap();
            out.flush().unwrap();
            continue;
        }

        if request.get("id").is_none() {
            continue;
        }

        let response = handle_request(&request, &default_conformance, &engines, &mut session_store);
        let mut response_str = serde_json::to_string(&response).expect("serialisation error");
        response_str.push('\n');
        out.write_all(response_str.as_bytes()).expect("stdout write error");
        out.flush().expect("stdout flush error");
    }
}

fn handle_request(req: &JsonValue, default_conformance: &str, engines: &Engines, store: &mut SessionStore) -> JsonValue {
    let id = &req["id"];
    let method = req["method"].as_str().unwrap_or("");
    let params = &req["params"];

    match method {
        "initialize" => json!({
            "jsonrpc": "2.0",
            "id": id,
            "result": {
                "protocolVersion": "2024-11-05",
                "capabilities": { "tools": {} },
                "serverInfo": { "name": "truecalc-mcp", "version": "0.1.0" }
            }
        }),

        "tools/list" => json!({
            "jsonrpc": "2.0",
            "id": id,
            "result": { "tools": tools_list() }
        }),

        "tools/call" => {
            let name = params["name"].as_str().unwrap_or("");
            let args = &params["arguments"];
            let result = dispatch_tool(name, args, default_conformance, engines, store);
            let is_error = result.get("error").is_some();
            let mut tool_result = json!({
                "content": [{ "type": "text", "text": serde_json::to_string(&result).expect("result serialisation is infallible") }]
            });
            if is_error {
                tool_result["isError"] = json!(true);
            }
            json!({
                "jsonrpc": "2.0",
                "id": id,
                "result": tool_result
            })
        }

        _ => json!({
            "jsonrpc": "2.0",
            "id": id,
            "error": { "code": -32601, "message": "Method not found" }
        }),
    }
}

// ─── Tool dispatch ────────────────────────────────────────────────────────────

fn dispatch_tool(name: &str, args: &JsonValue, default_conformance: &str, engines: &Engines, store: &mut SessionStore) -> JsonValue {
    match name {
        "evaluate" => tool_evaluate(args, default_conformance, engines),
        "validate" => tool_validate(args, engines),
        "explain" => tool_explain(args, engines),
        "batch_evaluate" => tool_batch_evaluate(args, default_conformance, engines),
        "list_functions" => tool_list_functions(),
        "get_stats" => tool_get_stats(),
        "workbook_create" => tool_workbook_create(args, store),
        "workbook_set" => tool_workbook_set(args, store),
        "workbook_get" => tool_workbook_get(args, store),
        "workbook_recalc" => tool_workbook_recalc(args, store),
        "workbook_export" => tool_workbook_export(args, store),
        "workbook_import" => tool_workbook_import(args, store),
        _ => json!({ "error": format!("Unknown tool: {}", name) }),
    }
}

// ─── Individual tools ─────────────────────────────────────────────────────────

fn tool_evaluate(args: &JsonValue, default_conformance: &str, engines: &Engines) -> JsonValue {
    let formula = match args["formula"].as_str() {
        Some(f) => f,
        None => return json!({ "error": "missing formula" }),
    };
    let conformance = args["conformance"].as_str().unwrap_or(default_conformance);
    let engine = match engines.select(conformance) {
        Some(e) => e,
        None => return json!({ "error": format!("Unknown conformance target: '{}'", conformance) }),
    };
    let vars = parse_variables(&args["variables"]);
    let value = engine.evaluate(formula, &vars);
    value_to_json(&value)
}

fn tool_validate(args: &JsonValue, engines: &Engines) -> JsonValue {
    let formula = match args["formula"].as_str() {
        Some(f) => f,
        None => return json!({ "error": "missing formula" }),
    };
    match engines.google_sheets.validate(formula) {
        Ok(_) => json!({ "valid": true }),
        Err(e) => json!({ "valid": false, "error": e.to_string() }),
    }
}

fn tool_explain(args: &JsonValue, engines: &Engines) -> JsonValue {
    let formula = match args["formula"].as_str() {
        Some(f) => f,
        None => return json!({ "error": "missing formula" }),
    };
    match engines.google_sheets.parse(formula) {
        Ok(expr) => {
            let mut functions = Vec::new();
            collect_functions(&expr, &mut functions);
            functions.sort_unstable();
            functions.dedup();
            let description = if functions.is_empty() {
                "Formula with no function calls".to_string()
            } else {
                format!("Formula using: {}", functions.join(", "))
            };
            json!({ "description": description, "functions_used": functions })
        }
        Err(e) => json!({
            "description": format!("Invalid formula: {}", e),
            "functions_used": []
        }),
    }
}

fn tool_batch_evaluate(args: &JsonValue, default_conformance: &str, engines: &Engines) -> JsonValue {
    let formulas = match args["formulas"].as_array() {
        Some(a) => a,
        None => return json!({ "error": "missing formulas array" }),
    };
    let conformance = args["conformance"].as_str().unwrap_or(default_conformance);
    let engine = match engines.select(conformance) {
        Some(e) => e,
        None => return json!({ "error": format!("Unknown conformance target: '{}'", conformance) }),
    };
    let vars = parse_variables(&args["variables"]);
    let results: Vec<JsonValue> = formulas
        .iter()
        .map(|f| {
            let formula = f.as_str().unwrap_or("");
            let value = engine.evaluate(formula, &vars);
            value_to_json(&value)
        })
        .collect();
    json!(results)
}

fn tool_list_functions() -> JsonValue {
    let registry = Registry::new();
    let mut entries: Vec<JsonValue> = registry
        .list_functions()
        .map(|(name, meta)| json!({
            "name": name,
            "category": meta.category,
            "syntax": meta.signature,
            "description": meta.description,
        }))
        .collect();
    entries.sort_by_key(|e| e["name"].as_str().unwrap_or("").to_owned());
    json!({ "functions": entries })
}

fn tool_get_stats() -> JsonValue {
    let registry = Registry::new();
    let mut by_category: std::collections::BTreeMap<&str, u32> = std::collections::BTreeMap::new();
    let mut total: u32 = 0;
    for (_name, meta) in registry.list_functions() {
        *by_category.entry(meta.category).or_insert(0) += 1;
        total += 1;
    }
    let categories: Vec<JsonValue> = by_category
        .iter()
        .map(|(cat, count)| json!({ "category": cat, "count": count }))
        .collect();
    json!({
        "version": env!("CARGO_PKG_VERSION"),
        "total_functions": total,
        "by_category": categories
    })
}

// ─── Workbook tools ───────────────────────────────────────────────────────────

fn tool_workbook_create(args: &JsonValue, store: &mut SessionStore) -> JsonValue {
    let engine_str = match args["engine"].as_str() {
        Some(e) => e,
        None => return json!({ "error": "missing engine" }),
    };
    let engine = match engine_str {
        "sheets" => WbEngine::Sheets,
        "excel" => WbEngine::Excel,
        other => return json!({ "error": format!("unknown engine: {}", other) }),
    };
    match store.create(engine) {
        Ok(id) => json!({ "workbook_id": id }),
        Err(e) => json!({ "error": e }),
    }
}

fn tool_workbook_set(args: &JsonValue, store: &mut SessionStore) -> JsonValue {
    let workbook_id = match args["workbook_id"].as_str() {
        Some(id) => id,
        None => return json!({ "error": "missing workbook_id" }),
    };
    let sheet = match args["sheet"].as_str() {
        Some(s) => s,
        None => return json!({ "error": "missing sheet" }),
    };
    let cell = match args["cell"].as_str() {
        Some(c) => c,
        None => return json!({ "error": "missing cell" }),
    };
    let value = match args["value"].as_str() {
        Some(v) => v,
        None => return json!({ "error": "missing value" }),
    };

    let wb = match store.get_mut(workbook_id) {
        Some(wb) => wb,
        None => return json!({ "error": format!("workbook not found: {}", workbook_id) }),
    };

    let addr = match Address::from_a1(&cell.to_uppercase()) {
        Some(a) => a,
        None => return json!({ "error": format!("invalid cell address: {}", cell) }),
    };

    let input = if value.starts_with('=') {
        CellInput::Formula(value.to_owned())
    } else if value == "TRUE" || value == "true" {
        CellInput::Literal(WbValue::Boolean(true))
    } else if value == "FALSE" || value == "false" {
        CellInput::Literal(WbValue::Boolean(false))
    } else if let Ok(n) = value.parse::<f64>() {
        CellInput::Literal(WbValue::Number(n))
    } else if let Some(zi) = truecalc_core::types::zoned::parse_rfc9557(value) {
        CellInput::Literal(WbValue::Zoned(Box::new(zi)))
    } else {
        CellInput::Literal(WbValue::Text(value.to_owned()))
    };

    match wb.set(sheet, addr, input) {
        Ok(_) => json!({ "ok": true }),
        Err(e) => json!({ "error": e.to_string() }),
    }
}

fn tool_workbook_get(args: &JsonValue, store: &mut SessionStore) -> JsonValue {
    let workbook_id = match args["workbook_id"].as_str() {
        Some(id) => id,
        None => return json!({ "error": "missing workbook_id" }),
    };
    let sheet = match args["sheet"].as_str() {
        Some(s) => s,
        None => return json!({ "error": "missing sheet" }),
    };
    let cell = match args["cell"].as_str() {
        Some(c) => c,
        None => return json!({ "error": "missing cell" }),
    };

    let wb = match store.get_mut(workbook_id) {
        Some(wb) => wb,
        None => return json!({ "error": format!("workbook not found: {}", workbook_id) }),
    };

    let addr = match Address::from_a1(&cell.to_uppercase()) {
        Some(a) => a,
        None => return json!({ "error": format!("invalid cell address: {}", cell) }),
    };

    match wb.resolved(sheet, addr) {
        Some(resolved) => wb_value_to_json(&resolved.value),
        None => json!({ "error": "cell is empty or not found" }),
    }
}

fn tool_workbook_recalc(args: &JsonValue, store: &mut SessionStore) -> JsonValue {
    let workbook_id = match args["workbook_id"].as_str() {
        Some(id) => id,
        None => return json!({ "error": "missing workbook_id" }),
    };

    let timestamp_ms = args["timestamp_ms"].as_i64().unwrap_or(0);
    let timezone = args["timezone"].as_str().unwrap_or("UTC");
    let rng_seed = args["rng_seed"].as_u64().unwrap_or(0);

    let ctx = match RecalcContext::new(timestamp_ms, timezone, rng_seed) {
        Some(c) => c,
        None => return json!({ "error": format!("unknown timezone: {}", timezone) }),
    };

    let wb = match store.get_mut(workbook_id) {
        Some(wb) => wb,
        None => return json!({ "error": format!("workbook not found: {}", workbook_id) }),
    };

    let changes = wb.recalc(&ctx);
    let change_list: Vec<JsonValue> = changes
        .iter()
        .map(|c| json!({
            "sheet": c.sheet,
            "cell": c.addr.to_a1(),
            "before": wb_value_to_json(&c.old),
            "after": wb_value_to_json(&c.new),
        }))
        .collect();
    json!({ "changes": change_list })
}

fn tool_workbook_export(args: &JsonValue, store: &mut SessionStore) -> JsonValue {
    let workbook_id = match args["workbook_id"].as_str() {
        Some(id) => id,
        None => return json!({ "error": "missing workbook_id" }),
    };

    let wb = match store.get_mut(workbook_id) {
        Some(wb) => wb,
        None => return json!({ "error": format!("workbook not found: {}", workbook_id) }),
    };

    wb.to_json()
        .map(|s| json!({ "json": s }))
        .unwrap_or_else(|e| json!({ "error": e.to_string() }))
}

fn tool_workbook_import(args: &JsonValue, store: &mut SessionStore) -> JsonValue {
    let json_str = match args["json"].as_str() {
        Some(s) => s,
        None => return json!({ "error": "missing json" }),
    };

    match store.import(json_str) {
        Ok(id) => json!({ "workbook_id": id }),
        Err(e) => json!({ "error": e }),
    }
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

fn wb_value_to_json(v: &WbValue) -> JsonValue {
    match v {
        WbValue::Number(n) => json!({ "type": "number", "value": n }),
        WbValue::Text(s) => json!({ "type": "text", "value": s }),
        WbValue::Boolean(b) => json!({ "type": "boolean", "value": b }),
        WbValue::Error(e) => json!({ "type": "error", "error": e }),
        WbValue::Empty => json!({ "type": "empty", "value": null }),
        WbValue::Date(d) => json!({ "type": "date", "value": d }),
        WbValue::Zoned(z) => json!({ "type": "zoned", "value": z.to_rfc9557() }),
        WbValue::Array(rows) => {
            let arr: Vec<Vec<JsonValue>> = rows.iter()
                .map(|r| r.iter().map(wb_value_to_json).collect())
                .collect();
            json!({ "type": "array", "value": arr })
        }
    }
}

fn parse_variables(vars_json: &JsonValue) -> HashMap<String, Value> {
    let mut map = HashMap::new();
    if let Some(obj) = vars_json.as_object() {
        for (k, v) in obj {
            let val = match v {
                JsonValue::Number(n) => {
                    if let Some(f) = n.as_f64() {
                        Value::Number(f)
                    } else {
                        continue;
                    }
                }
                JsonValue::String(s) => Value::Text(s.clone()),
                JsonValue::Bool(b) => Value::Bool(*b),
                // Self-describing zoned instant: { "type": "zoned", "value": "<RFC-9557>" }.
                JsonValue::Object(o)
                    if o.get("type").and_then(|t| t.as_str()) == Some("zoned") =>
                {
                    match o
                        .get("value")
                        .and_then(|x| x.as_str())
                        .and_then(truecalc_core::types::zoned::parse_rfc9557)
                    {
                        Some(zi) => Value::Zoned(Box::new(zi)),
                        None => continue,
                    }
                }
                _ => continue,
            };
            map.insert(k.clone(), val);
        }
    }
    map
}

fn value_to_json(v: &Value) -> JsonValue {
    match v {
        Value::Number(n) | Value::Date(n) => json!({ "value": n, "type": "number" }),
        Value::Text(s) => json!({ "value": s, "type": "text" }),
        Value::Bool(b) => json!({ "value": b, "type": "bool" }),
        Value::Empty => json!({ "value": null, "type": "empty" }),
        Value::Error(e) => json!({ "value": e.to_string(), "type": "error" }),
        // Self-describing RFC-9557; deliberately NOT collapsed to "number".
        Value::Zoned(z) => json!({ "value": z.to_rfc9557(), "type": "zoned" }),
        Value::Array(arr) => {
            let items: Vec<JsonValue> = arr.iter().map(value_to_json).collect();
            json!({ "value": items, "type": "array" })
        }
    }
}

fn collect_functions(expr: &Expr, out: &mut Vec<String>) {
    match expr {
        Expr::FunctionCall { name, args, .. } => {
            out.push(name.clone());
            for arg in args {
                collect_functions(arg, out);
            }
        }
        Expr::UnaryOp { operand, .. } => collect_functions(operand, out),
        Expr::BinaryOp { left, right, .. } => {
            collect_functions(left, out);
            collect_functions(right, out);
        }
        _ => {}
    }
}

// ─── tools/list metadata ─────────────────────────────────────────────────────

fn tools_list() -> JsonValue {
    json!([
        {
            "name": "evaluate",
            "description": "Evaluate a spreadsheet formula with optional variable bindings.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "formula": { "type": "string", "description": "Formula string, e.g. \"SUM(A,B)\"" },
                    "variables": { "type": "object", "description": "Variable bindings (name → number/string/bool)" },
                    "conformance": { "type": "string", "description": "Conformance target (default: server default). Supported: \"google-sheets\"" }
                },
                "required": ["formula"]
            }
        },
        {
            "name": "validate",
            "description": "Check whether a formula parses without errors.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "formula": { "type": "string" }
                },
                "required": ["formula"]
            }
        },
        {
            "name": "explain",
            "description": "Describe a formula and list the functions it uses.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "formula": { "type": "string" }
                },
                "required": ["formula"]
            }
        },
        {
            "name": "batch_evaluate",
            "description": "Evaluate multiple formulas sharing the same variable bindings.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "formulas": { "type": "array", "items": { "type": "string" } },
                    "variables": { "type": "object" },
                    "conformance": { "type": "string", "description": "Conformance target (default: server default). Supported: \"google-sheets\"" }
                },
                "required": ["formulas"]
            }
        },
        {
            "name": "list_functions",
            "description": "Return the catalogue of supported spreadsheet functions.",
            "inputSchema": { "type": "object", "properties": {} }
        },
        {
            "name": "get_stats",
            "description": "Return the total number of supported functions, the library version, and a per-category breakdown.",
            "inputSchema": { "type": "object", "properties": {} }
        },
        {
            "name": "workbook_create",
            "description": "Create a new in-memory workbook. Engine is locked at creation.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "engine": { "type": "string", "enum": ["sheets", "excel"], "description": "Spreadsheet dialect" }
                },
                "required": ["engine"]
            }
        },
        {
            "name": "workbook_set",
            "description": "Write a value or formula to a cell in an existing workbook sheet.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "workbook_id": { "type": "string", "description": "Workbook session ID" },
                    "sheet": { "type": "string", "description": "Sheet name" },
                    "cell": { "type": "string", "description": "Cell address in A1 notation" },
                    "value": { "type": "string", "description": "Cell value; prefix with '=' for a formula" }
                },
                "required": ["workbook_id", "sheet", "cell", "value"]
            }
        },
        {
            "name": "workbook_get",
            "description": "Read the effective value of a cell (resolves spills).",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "workbook_id": { "type": "string" },
                    "sheet": { "type": "string" },
                    "cell": { "type": "string", "description": "Cell address in A1 notation" }
                },
                "required": ["workbook_id", "sheet", "cell"]
            }
        },
        {
            "name": "workbook_recalc",
            "description": "Recalculate all formula cells and return the list of changed cells.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "workbook_id": { "type": "string" },
                    "timestamp_ms": { "type": "integer", "description": "UTC epoch milliseconds for NOW()/TODAY() (default: 0)" },
                    "timezone": { "type": "string", "description": "IANA timezone name (default: UTC)" },
                    "rng_seed": { "type": "integer", "description": "RNG seed for RAND() etc. (default: 0)" }
                },
                "required": ["workbook_id"]
            }
        },
        {
            "name": "workbook_export",
            "description": "Export a workbook session as canonical JSON.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "workbook_id": { "type": "string" }
                },
                "required": ["workbook_id"]
            }
        },
        {
            "name": "workbook_import",
            "description": "Import a workbook from canonical JSON and return a new session ID.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "json": { "type": "string", "description": "Canonical workbook JSON" }
                },
                "required": ["json"]
            }
        }
    ])
}