deckle-desktop 0.4.2

Deckle — open-source UI design tool with MCP server for AI agents
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
// MCP (Model Context Protocol) server — exposes Deckle tools to AI agents on port 29979.
//
// Replaces: extracted_app/src/mcp/server.ts
//
// Architecture: This is a PROXY server. It receives MCP tool calls from AI clients
// (Claude Code, Cursor, etc.) and forwards them to the Deckle web app running in a
// webview. When no webview is connected, it returns static tool definitions and an
// error message for tool calls.
//
// Uses the rmcp crate's StreamableHttpService as a Tower service mounted on axum,
// with a custom ServerHandler implementation that dynamically proxies tool calls
// through the McpBridge trait.

use std::collections::HashMap;
use std::convert::Infallible;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

use async_trait::async_trait;
use axum::{
    extract::Request,
    http,
    middleware::{self, Next},
    response::{IntoResponse, Response},
    Router,
};
use http::StatusCode;
use rmcp::{
    model::{
        CallToolRequestParams, CallToolResult, ClientCapabilities, Content, Implementation,
        InitializeRequestParams, ListToolsResult, PaginatedRequestParams, ServerCapabilities,
        ServerInfo, Tool, ToolAnnotations,
    },
    service::{RequestContext, RoleServer},
    transport::streamable_http_server::{
        session::{
            local::LocalSessionManager,
            store::{SessionState, SessionStore, SessionStoreError},
        },
        StreamableHttpServerConfig, StreamableHttpService,
    },
    ServerHandler,
};
use serde::Deserialize;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use tauri::{AppHandle, Manager};
use tokio::sync::oneshot;
use tokio::time::{timeout, Duration};
use tokio_util::sync::CancellationToken;
use tower::Service;
use uuid::Uuid;

// ---------------------------------------------------------------------------
// Bridge trait — the seam between the MCP server and the webview
// ---------------------------------------------------------------------------

/// Result of a tool call forwarded through the bridge.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct McpToolResult {
    /// Content items to return to the MCP client.
    pub content: Vec<Content>,
    /// Whether the result represents an error condition.
    pub is_error: bool,
}

/// Contract for communicating with the Deckle editor.
///
/// In standalone mode, `StandaloneBridge` returns static tool definitions and
/// an error for all tool calls. When a Tauri webview is available, a
/// `WebviewBridge` implementation will forward calls via IPC.
pub trait McpBridge: Send + Sync + 'static {
    /// Return the MCP server configuration: instructions text and tool definitions.
    fn get_server_config(
        &self,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = McpServerConfig> + Send>>;

    /// Forward a tool call to the editor. `session_id` identifies the MCP
    /// session (one per agent conversation). `name` is the tool name,
    /// `args` is the JSON arguments object.
    fn call_tool(
        &self,
        session_id: &str,
        name: &str,
        args: Value,
    ) -> Pin<Box<dyn Future<Output = Result<McpToolResult, String>> + Send>>;

    /// Notify the editor that an agent session has ended, so it can clean up
    /// any session-scoped state (selections, highlights, undo groups).
    fn remove_agent(&self, session_id: &str) -> Pin<Box<dyn Future<Output = ()> + Send>>;

    /// Send a log message to the editor's developer console (visible in
    /// webview devtools). The `level` parameter is optional and defaults to
    /// "log" — valid values are "log", "warn", "error".
    fn mcp_log(
        &self,
        message: &str,
        level: Option<&str>,
    ) -> Pin<Box<dyn Future<Output = ()> + Send>>;
}

/// Server configuration returned by the bridge (mirrors MCPServerConfig in TS).
pub struct McpServerConfig {
    pub instructions: Option<String>,
    pub tools: Vec<Tool>,
}

// ---------------------------------------------------------------------------
// StandaloneBridge — works without a webview
// ---------------------------------------------------------------------------

/// Bridge implementation for standalone mode. Returns static tool definitions
/// and a "no editor" error for all tool calls.
pub struct StandaloneBridge {
    config: McpServerConfig,
}

impl StandaloneBridge {
    pub fn new() -> Self {
        Self {
            config: McpServerConfig {
                instructions: Some(INSTRUCTIONS.to_string()),
                tools: build_static_tools(),
            },
        }
    }
}

impl McpBridge for StandaloneBridge {
    fn get_server_config(&self) -> Pin<Box<dyn Future<Output = McpServerConfig> + Send>> {
        let instructions = self.config.instructions.clone();
        let tools = self.config.tools.clone();
        Box::pin(async move {
            McpServerConfig {
                instructions,
                tools,
            }
        })
    }

    fn call_tool(
        &self,
        _session_id: &str,
        _name: &str,
        _args: Value,
    ) -> Pin<Box<dyn Future<Output = Result<McpToolResult, String>> + Send>> {
        Box::pin(async move {
            Err("No editor window is open. Please open Deckle Desktop and try again.".to_string())
        })
    }

    fn remove_agent(&self, _session_id: &str) -> Pin<Box<dyn Future<Output = ()> + Send>> {
        Box::pin(async {})
    }

    fn mcp_log(
        &self,
        _message: &str,
        _level: Option<&str>,
    ) -> Pin<Box<dyn Future<Output = ()> + Send>> {
        Box::pin(async {})
    }
}

// ---------------------------------------------------------------------------
// Shared state for WebviewBridge IPC callbacks
// ---------------------------------------------------------------------------

/// State shared between `WebviewBridge` and the Tauri `__mcp_callback` command.
/// Maps unique call IDs to oneshot senders so eval'd JS can send results back.
pub struct McpBridgeState {
    pending_calls: Mutex<HashMap<String, oneshot::Sender<Result<Value, String>>>>,
}

impl McpBridgeState {
    /// Create a new state (wrapped in `Arc` for sharing).
    pub fn new_arc() -> Arc<Self> {
        Arc::new(Self {
            pending_calls: Mutex::new(HashMap::new()),
        })
    }

    /// Register a pending call. The sender will be notified when the webview
    /// sends back a result via `__mcp_callback`.
    pub fn register(&self, id: String, sender: oneshot::Sender<Result<Value, String>>) {
        let mut map = self.pending_calls.lock().unwrap();
        map.insert(id, sender);
    }

    /// Resolve a pending call by its ID. This is called from the Tauri command
    /// handler when the webview sends back a result.
    pub fn resolve(&self, id: &str, result: Result<Value, String>) {
        let sender = {
            let mut map = self.pending_calls.lock().unwrap();
            map.remove(id)
        };
        if let Some(sender) = sender {
            let _ = sender.send(result);
        }
    }
}

// ---------------------------------------------------------------------------
// WebviewBridge — proxies MCP calls into the Tauri webview via IPC
// ---------------------------------------------------------------------------

/// Bridge implementation that forwards MCP calls to the Deckle editor running
/// in a Tauri webview. Uses `eval()` to call methods on
/// `window.resolveMCPHandlers` and `__TAURI_INTERNALS__.invoke()` to receive
/// the results back.
pub struct WebviewBridge {
    app_handle: AppHandle,
    state: Arc<McpBridgeState>,
}

impl WebviewBridge {
    pub fn new(app_handle: AppHandle, state: Arc<McpBridgeState>) -> Self {
        Self { app_handle, state }
    }

    /// Evaluate JavaScript in the main webview and wait for a result via the
    /// IPC callback channel. The `js_await_expr` should be a JS expression that
    /// can be `await`ed — it will be placed inside `await ({js_await_expr})`.
    async fn eval_with_callback(&self, js_await_expr: &str) -> Result<Value, String> {
        let id = Uuid::new_v4().to_string();
        let (tx, rx) = oneshot::channel();

        self.state.register(id.clone(), tx);

        // Build the JS that will be evaluated in the webview.
        // It polls for resolveMCPHandlers, runs the expression, and sends the
        // result back via Tauri IPC.
        let js = format!(
            "(async () => {{
                const deadline = Date.now() + 10000;
                while (typeof window.resolveMCPHandlers === 'undefined') {{
                    if (Date.now() > deadline) {{
                        throw new Error('MCP handlers not loaded after 10s');
                    }}
                    await new Promise(r => setTimeout(r, 50));
                }}
                try {{
                    const h = await window.resolveMCPHandlers;
                    const result = await ({js_await_expr});
                    await window.__TAURI_INTERNALS__.invoke('__mcp_callback', {{
                        id: '{id}',
                        result: JSON.stringify(result)
                    }});
                }} catch(e) {{
                    await window.__TAURI_INTERNALS__.invoke('__mcp_callback', {{
                        id: '{id}',
                        error: (e && e.message) ? e.message : String(e)
                    }});
                }}
            }})()",
            js_await_expr = js_await_expr,
            id = id,
        );

        let webview = self
            .app_handle
            .get_webview_window("main")
            .ok_or_else(|| "Deckle window is not open".to_string())?;
        webview
            .eval(&js)
            .map_err(|e| format!("Failed to evaluate JS in webview: {}", e))?;

        match timeout(Duration::from_secs(30), rx).await {
            Ok(Ok(result)) => result,
            Ok(Err(_)) => Err("Bridge callback channel closed unexpectedly".to_string()),
            Err(_) => Err("Timeout waiting for Deckle webview to respond".to_string()),
        }
    }

    /// Fire-and-forget JS evaluation. No result is expected back.
    async fn eval_ff(&self, js_await_expr: &str) {
        let js = format!(
            "(async () => {{
                const deadline = Date.now() + 5000;
                while (typeof window.resolveMCPHandlers === 'undefined') {{
                    if (Date.now() > deadline) return;
                    await new Promise(r => setTimeout(r, 50));
                }}
                try {{
                    const h = await window.resolveMCPHandlers;
                    await ({js_await_expr});
                }} catch(e) {{
                    console.error('[MCP Bridge]', String(e));
                }}
            }})()",
            js_await_expr = js_await_expr,
        );
        if let Some(webview) = self.app_handle.get_webview_window("main") {
            let _ = webview.eval(&js);
        }
    }
}

impl McpBridge for WebviewBridge {
    fn get_server_config(&self) -> Pin<Box<dyn Future<Output = McpServerConfig> + Send>> {
        let app_handle = self.app_handle.clone();
        let state = self.state.clone();
        Box::pin(async move {
            let bridge = WebviewBridge { app_handle, state };
            match bridge.eval_with_callback("h.getMCPServerConfig()").await {
                Ok(val) => {
                    let tools = val
                        .get("tools")
                        .and_then(|t| serde_json::from_value(t.clone()).ok())
                        .unwrap_or_default();
                    let instructions = val
                        .get("instructions")
                        .and_then(|i| i.as_str().map(|s| s.to_string()));
                    McpServerConfig {
                        instructions,
                        tools,
                    }
                }
                Err(e) => {
                    tracing::warn!(
                        "[mcp-server] get_server_config failed: {}; using static config",
                        e
                    );
                    McpServerConfig {
                        instructions: Some(INSTRUCTIONS.to_string()),
                        tools: build_static_tools(),
                    }
                }
            }
        })
    }

    fn call_tool(
        &self,
        session_id: &str,
        name: &str,
        args: Value,
    ) -> Pin<Box<dyn Future<Output = Result<McpToolResult, String>> + Send>> {
        let app_handle = self.app_handle.clone();
        let state = self.state.clone();
        let session_id = session_id.to_string();
        let name = name.to_string();
        Box::pin(async move {
            let bridge = WebviewBridge { app_handle, state };
            let args_json = serde_json::to_string(&args).unwrap_or_else(|_| "{}".to_string());
            let js = format!(
                "h.handleToolCall({}, {}, {})",
                serde_json::Value::String(session_id),
                serde_json::Value::String(name),
                args_json,
            );
            let val = bridge.eval_with_callback(&js).await?;
            serde_json::from_value(val).map_err(|e| format!("Failed to parse tool result: {}", e))
        })
    }

    fn remove_agent(&self, session_id: &str) -> Pin<Box<dyn Future<Output = ()> + Send>> {
        let app_handle = self.app_handle.clone();
        let state = self.state.clone();
        let session_id = session_id.to_string();
        Box::pin(async move {
            let bridge = WebviewBridge { app_handle, state };
            let js = format!("h.removeAgent({})", serde_json::Value::String(session_id),);
            bridge.eval_ff(&js).await;
        })
    }

    fn mcp_log(
        &self,
        message: &str,
        level: Option<&str>,
    ) -> Pin<Box<dyn Future<Output = ()> + Send>> {
        let app_handle = self.app_handle.clone();
        let state = self.state.clone();
        let message = message.to_string();
        let level = level.map(|s| s.to_string());
        Box::pin(async move {
            let bridge = WebviewBridge { app_handle, state };
            if let Some(lvl) = level {
                let js = format!(
                    "h.mcpLog({}, {})",
                    serde_json::Value::String(message),
                    serde_json::Value::String(lvl),
                );
                bridge.eval_ff(&js).await;
            } else {
                let js = format!("h.mcpLog({})", serde_json::Value::String(message),);
                bridge.eval_ff(&js).await;
            }
        })
    }
}

// ---------------------------------------------------------------------------
// DeckleMcpHandler — implements rmcp::ServerHandler
// ---------------------------------------------------------------------------

/// The MCP server handler. Each session gets its own instance (created by the
/// service factory closure), but they all share the same bridge.
struct DeckleMcpHandler {
    bridge: Arc<dyn McpBridge>,
    /// Cached tool definitions, loaded once when the handler is created.
    tools: Vec<Tool>,
    /// Cached instructions text.
    instructions: Option<String>,
    /// The session ID, recorded from the first request so it can be used in
    /// `Drop` to notify the editor that this session ended.
    session_id: Mutex<Option<String>>,
}

impl DeckleMcpHandler {
    async fn new(bridge: Arc<dyn McpBridge>) -> Self {
        let config = bridge.get_server_config().await;
        Self {
            bridge,
            tools: config.tools,
            instructions: config.instructions,
            session_id: Mutex::new(None),
        }
    }
}

impl Drop for DeckleMcpHandler {
    fn drop(&mut self) {
        let sid = self.session_id.lock().unwrap().take();
        if let Some(sid) = sid {
            let bridge = self.bridge.clone();
            tokio::spawn(async move {
                bridge.remove_agent(&sid).await;
            });
        }
    }
}

impl ServerHandler for DeckleMcpHandler {
    fn get_info(&self) -> ServerInfo {
        let mut info = ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(Implementation::new("deckle-desktop", "0.4.2"));
        if let Some(ref instructions) = self.instructions {
            info = info.with_instructions(instructions.clone());
        }
        info
    }

    fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<Output = Result<ListToolsResult, rmcp::ErrorData>> + Send + '_
    {
        let tools = self.tools.clone();
        async move { Ok(ListToolsResult::with_all_items(tools)) }
    }

    fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<Output = Result<CallToolResult, rmcp::ErrorData>> + Send + '_
    {
        // Extract all owned data from self before the async block so the
        // future is 'static (only captures owned values, not &self refs).
        let bridge = self.bridge.clone();
        let tool_name = request.name.to_string();
        let args = match request.arguments {
            Some(map) => Value::Object(map),
            None => Value::Object(serde_json::Map::new()),
        };

        // Extract session ID from the HTTP request parts if available.
        let session_id = context
            .extensions
            .get::<http::request::Parts>()
            .and_then(|parts: &http::request::Parts| {
                parts
                    .headers
                    .get("mcp-session-id")
                    .and_then(|v: &http::HeaderValue| v.to_str().ok())
                    .map(|s: &str| s.to_string())
            })
            .unwrap_or_else(|| Uuid::new_v4().to_string());

        // Record session ID so Drop can notify the editor on cleanup.
        *self.session_id.lock().unwrap() = Some(session_id.clone());

        async move {
            // Log the tool call to the editor console (mirrors Electron).
            bridge
                .mcp_log(
                    &format!(
                        "[mcp-server] Tool call: {} (session: {})",
                        tool_name, session_id
                    ),
                    Some("info"),
                )
                .await;

            match bridge.call_tool(&session_id, &tool_name, args).await {
                Ok(result) => {
                    if result.is_error {
                        bridge
                            .mcp_log(
                                &format!(
                                    "[mcp-server] Tool error: {} (session: {})",
                                    tool_name, session_id
                                ),
                                Some("warn"),
                            )
                            .await;
                        Ok(CallToolResult::error(result.content))
                    } else {
                        Ok(CallToolResult::success(result.content))
                    }
                }
                Err(e) => {
                    bridge
                        .mcp_log(
                            &format!(
                                "[mcp-server] Tool call failed: {}{} (session: {})",
                                tool_name, e, session_id
                            ),
                            Some("error"),
                        )
                        .await;
                    Ok(CallToolResult::error(vec![Content::text(e)]))
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Security middleware
// ---------------------------------------------------------------------------

/// Middleware that ensures the Accept header contains both `application/json`
/// and `text/event-stream` as required by the Streamable HTTP spec.
///
/// Some MCP clients (e.g. Claude Code) omit the Accept header or send an
/// incomplete value, causing rmcp's `StreamableHttpService` to return 406
/// which the client then misinterprets as an auth failure.
/// See: https://github.com/anthropics/claude-code/issues/42470
///
/// Mirrors the fix in `extracted_app/src/mcp/server.ts` (lines 180-195).
async fn accept_header_middleware(mut request: Request, next: Next) -> Response {
    let accept = request
        .headers()
        .get(http::header::ACCEPT)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    if !accept.contains("application/json") || !accept.contains("text/event-stream") {
        request.headers_mut().insert(
            http::header::ACCEPT,
            http::HeaderValue::from_static("application/json, text/event-stream"),
        );
    }

    next.run(request).await
}

/// Middleware that blocks browser requests (Origin header) and validates
/// the Host header for DNS rebinding protection. This mirrors the security
/// checks in the original TypeScript server.
async fn security_middleware(request: Request, next: Next) -> Response {
    let headers = request.headers();
    let method = request.method().clone();

    // Block CORS preflight requests.
    if method == http::Method::OPTIONS {
        tracing::warn!("[mcp-server] Blocked CORS preflight request");
        return StatusCode::FORBIDDEN.into_response();
    }

    // Block requests with Origin header — browsers send this, MCP clients do not.
    if headers.contains_key(http::header::ORIGIN) {
        let origin = headers
            .get(http::header::ORIGIN)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("unknown");
        tracing::warn!(
            "[mcp-server] Blocked browser request from origin: {}",
            origin
        );
        return (
            StatusCode::FORBIDDEN,
            axum::Json(json!({
                "status": "forbidden",
                "message": "Browser requests not allowed"
            })),
        )
            .into_response();
    }

    // Validate Host header to prevent DNS rebinding attacks.
    // Mirrors the TypeScript server's allowedHosts check.
    if let Some(host) = headers.get(http::header::HOST) {
        if let Ok(host_str) = host.to_str() {
            let allowed_hosts = ["127.0.0.1:29979", "localhost:29979"];
            if !allowed_hosts.contains(&host_str) {
                tracing::warn!(
                    "[mcp-server] Blocked DNS rebinding attempt with host: {}",
                    host_str
                );
                return (
                    StatusCode::FORBIDDEN,
                    axum::Json(json!({
                        "status": "forbidden",
                        "message": "Invalid host"
                    })),
                )
                    .into_response();
            }
        }
    }

    next.run(request).await
}

// ---------------------------------------------------------------------------
// TokenStore — bearer token auth for headless mode
// ---------------------------------------------------------------------------

/// Result of setting a token for the first time vs. refreshing.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum TokenState {
    /// The first token was set — this locks the process to a user.
    Initial,
    /// The token was updated (e.g. refreshed by the auth server).
    Refresh,
}

/// Stores a bearer token and provides constant-time comparison of SHA-256
/// hashes. Mirrors the Electron `createTokenStore()` in auth-through-mcp.ts.
///
/// In this mock/local server there is no real API to validate against, so any
/// bearer token is accepted as the first token. Subsequent requests must
/// present a token whose SHA-256 hash matches the stored one (constant-time).
struct TokenStore {
    current_token: Option<String>,
}

impl TokenStore {
    fn new() -> Self {
        Self {
            current_token: None,
        }
    }

    fn read(&self) -> Option<&str> {
        self.current_token.as_deref()
    }

    /// Set the token. If a token is already stored, this treats the new token
    /// as a refresh (matching the Electron behavior where the store trusts the
    /// caller has already validated the token).
    fn set(&mut self, token: &str) -> Result<TokenState, String> {
        if self.current_token.is_some() {
            // Already set — treat as a refresh (mirrors Electron TokenStore.set)
            self.current_token = Some(token.to_string());
            return Ok(TokenState::Refresh);
        }
        // First token — accept unconditionally (mock server, no remote
        // validation needed).
        self.current_token = Some(token.to_string());
        Ok(TokenState::Initial)
    }

    /// Returns true if `plaintext` has the same SHA-256 hash as the stored
    /// token. Comparison is constant-time to prevent timing side-channels.
    /// Returns false when no token is stored.
    fn matches(&self, plaintext: &str) -> bool {
        let current = match &self.current_token {
            Some(t) => t,
            None => return false,
        };
        let incoming_hash = sha256(plaintext);
        let current_hash = sha256(current);
        constant_time_eq_32(&incoming_hash, &current_hash)
    }
}

/// SHA-256 hash of a string, returned as a 32-byte array.
fn sha256(input: &str) -> [u8; 32] {
    let mut hasher = Sha256::new();
    hasher.update(input.as_bytes());
    let result = hasher.finalize();
    let mut out = [0u8; 32];
    out.copy_from_slice(&result);
    out
}

/// Constant-time comparison of two 32-byte arrays. Every byte is compared and
/// the result is ORed together, so no early-exit branch is taken. Mirrors
/// Node.js `crypto.timingSafeEqual`.
fn constant_time_eq_32(a: &[u8; 32], b: &[u8; 32]) -> bool {
    let mut result: u8 = 0;
    for i in 0..32 {
        result |= a[i] ^ b[i];
    }
    result == 0
}

/// Global token store for bearer token auth in headless mode.
/// Mirrors the Electron `TokenStore` singleton from `createTokenStore()`.
static TOKEN_STORE: std::sync::OnceLock<Mutex<TokenStore>> = std::sync::OnceLock::new();

/// One-shot callback fired when the first token is received.
static FIRST_TOKEN_ONCE: std::sync::Once = std::sync::Once::new();

fn get_token_store() -> &'static Mutex<TokenStore> {
    TOKEN_STORE.get_or_init(|| Mutex::new(TokenStore::new()))
}

/// Bearer token wrapper service for headless mode.
///
/// Wraps an inner Tower service and checks the Authorization header against the
/// global [`TOKEN_STORE`]. Only active when `DECKLE_HEADLESS_MCP=true`.
///
/// Mirrors the Electron middleware in server.ts.
#[derive(Clone)]
struct BearerTokenService<S> {
    inner: S,
}

impl<S> BearerTokenService<S> {
    /// Forward the request to the inner service, converting the response to
    /// axum's [`Response`] type via `IntoResponse`.
    fn forward(
        &mut self,
        req: Request,
    ) -> Pin<Box<dyn Future<Output = Result<Response, Infallible>> + Send>>
    where
        S: Service<Request, Error = Infallible> + Clone + Send + 'static,
        S::Response: IntoResponse + 'static,
        S::Future: Send + 'static,
    {
        let mut inner = self.inner.clone();
        Box::pin(async move { inner.call(req).await.map(IntoResponse::into_response) })
    }
}

impl<S> Service<Request> for BearerTokenService<S>
where
    S: Service<Request, Error = Infallible> + Clone + Send + 'static,
    S::Response: IntoResponse + 'static,
    S::Future: Send + 'static,
{
    type Response = Response;
    type Error = Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Request) -> Self::Future {
        let headless = std::env::var("DECKLE_HEADLESS_MCP").as_deref() == Ok("true");
        let is_delete = req.method() == http::Method::DELETE;

        // Early exit: not headless or DELETE — pass through without auth.
        if !headless || is_delete {
            return self.forward(req);
        }

        // Read the Authorization header without consuming the request.
        let auth_value = req
            .headers()
            .get(http::header::AUTHORIZATION)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("")
            .to_string();

        // Validate the header format.
        if !auth_value.starts_with("Bearer ") {
            return Box::pin(
                async move { Ok(bearer_unauthorized_response("Missing bearer token")) },
            );
        }

        let auth_token = auth_value["Bearer ".len()..].trim().to_string();
        if auth_token.is_empty() {
            return Box::pin(async move { Ok(bearer_unauthorized_response("Empty bearer token")) });
        }

        // Check against the token store.
        let mut store = get_token_store().lock().unwrap();

        if store.matches(&auth_token) {
            // Already authenticated — forward the request.
            drop(store);
            return self.forward(req);
        }

        match store.set(&auth_token) {
            Ok(TokenState::Initial) => {
                drop(store);
                FIRST_TOKEN_ONCE.call_once(|| {
                    tracing::info!("[mcp-server] First token received in headless mode");
                });
                self.forward(req)
            }
            Ok(TokenState::Refresh) => {
                drop(store);
                self.forward(req)
            }
            Err(reason) => {
                drop(store);
                tracing::warn!("[mcp-server] Token auth failed: {}", reason);
                Box::pin(async move { Ok(bearer_unauthorized_response(&reason)) })
            }
        }
    }
}

/// Build a 401 JSON response with the given message.
///
/// NOTE: does NOT use `error` / `error_description` field names — Claude
/// Code's MCP SDK interprets that shape as an OAuth challenge.
fn bearer_unauthorized_response(message: &str) -> Response {
    let body = serde_json::to_vec(&json!({
        "status": "unauthorized",
        "message": message,
    }))
    .unwrap_or_default();
    Response::builder()
        .status(StatusCode::UNAUTHORIZED)
        .header("content-type", "application/json")
        .body(axum::body::Body::from(body))
        .unwrap()
}

/// A session store that enables transparent session resurrection after server
/// restart.
///
/// When the server restarts, clients may send requests with session IDs from
/// before the restart. This store returns a default [`SessionState`] for any
/// session ID, allowing rmcp's `try_restore_from_store` to recreate the session
/// transparently by replaying a synthetic `initialize` handshake. The handler
/// ([`DeckleMcpHandler`]) does not depend on the client's initialize params, so
/// using defaults is safe.
///
/// The Electron reference implementation achieves the same effect by omitting
/// the `sessionIdGenerator` option, which allows the transport to process any
/// request (not just `initialize`) on a new session. rmcp lacks equivalent API
/// control, so the same outcome is achieved through this store + rmcp's
/// cross-instance restore mechanism.
struct ResurrectionStore;

#[async_trait]
impl SessionStore for ResurrectionStore {
    async fn load(&self, _session_id: &str) -> Result<Option<SessionState>, SessionStoreError> {
        Ok(Some(SessionState::new(InitializeRequestParams::new(
            ClientCapabilities::default(),
            Implementation::default(),
        ))))
    }

    async fn store(
        &self,
        _session_id: &str,
        _state: &SessionState,
    ) -> Result<(), SessionStoreError> {
        // The synthetic initialize params are not meaningful to persist.
        Ok(())
    }

    async fn delete(&self, _session_id: &str) -> Result<(), SessionStoreError> {
        // Nothing to delete — our store is stateless.
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Start the MCP server on the given port.
///
/// The server exposes Deckle's design tools over the MCP Streamable HTTP
/// protocol. AI clients connect to `http://127.0.0.1:{port}/mcp`.
pub async fn start(
    port: u16,
    bridge: Arc<dyn McpBridge>,
    shutdown: CancellationToken,
) -> Result<(), Box<dyn std::error::Error>> {
    let ct = shutdown;

    // The service factory creates a new DeckleMcpHandler for each session.
    // We need to block on getting the config once so the factory closure
    // can clone it without being async.
    let initial_config = bridge.get_server_config().await;
    let shared_tools = Arc::new(initial_config.tools);
    let shared_instructions = Arc::new(initial_config.instructions);

    let bridge_for_factory = bridge.clone();
    let tools_for_factory = shared_tools.clone();
    let instructions_for_factory = shared_instructions.clone();

    // Build the config using the builder, then set session_store directly
    // (the struct is #[non_exhaustive], so we cannot use struct literal syntax).
    let mut config = StreamableHttpServerConfig::default()
        .with_stateful_mode(true)
        // rmcp handles host validation for us — allow localhost and
        // 127.0.0.1 with our port.
        .with_allowed_hosts([
            format!("127.0.0.1:{port}"),
            format!("localhost:{port}"),
            "127.0.0.1".to_string(),
            "localhost".to_string(),
        ])
        // Empty = skip origin check (our middleware blocks ALL origins).
        .disable_allowed_origins()
        .with_cancellation_token(ct.child_token());
    // Enable session resurrection via a store that returns a default
    // SessionState for ANY session ID. When rmcp's handle_post sees
    // an unknown session ID, it calls try_restore_from_store, which
    // loads this state, creates a new session worker, and replays a
    // synthetic initialize handshake — transparently resurrecting the
    // session without requiring the client to re-initialize.
    config.session_store = Some(Arc::new(ResurrectionStore));

    let service: StreamableHttpService<DeckleMcpHandler, LocalSessionManager> =
        StreamableHttpService::new(
            move || {
                let handler = DeckleMcpHandler {
                    bridge: bridge_for_factory.clone(),
                    tools: (*tools_for_factory).clone(),
                    instructions: (*instructions_for_factory).clone(),
                    session_id: Mutex::new(None),
                };
                Ok(handler)
            },
            Default::default(),
            config,
        );

    // Wrap the MCP service with bearer token auth (only active when
    // DECKLE_HEADLESS_MCP=true). Uses a custom Tower Service wrapper
    // instead of axum middleware to avoid type compatibility issues
    // between StreamableHttpService and axum's FromFn extractor macro.
    let auth_service = BearerTokenService { inner: service };

    // Build the axum router.
    let app = Router::new()
        // Mount the MCP service at /mcp.
        .nest_service("/mcp", auth_service)
        // OAuth/OIDC discovery endpoints — return bare 404 to prevent
        // Claude Code from misclassifying this server as an OAuth provider.
        .route(
            "/.well-known/oauth-authorization-server",
            axum::routing::get(|| async { StatusCode::NOT_FOUND }),
        )
        .route(
            "/.well-known/openid-configuration",
            axum::routing::get(|| async { StatusCode::NOT_FOUND }),
        )
        .route(
            "/.well-known/oauth-protected-resource",
            axum::routing::get(|| async { StatusCode::NOT_FOUND }),
        )
        // Catch-all fallback — avoid OAuth-shaped field names.
        .fallback(|| async {
            (
                StatusCode::NOT_FOUND,
                axum::Json(json!({
                    "status": "not_found",
                    "message": "Route not found. The MCP endpoint is /mcp. Try restarting your agent and Deckle."
                })),
            )
        })
        // Accept header middleware runs first (outermost) to patch missing
        // Accept headers before they reach any handler or the security layer.
        .layer(middleware::from_fn(accept_header_middleware))
        // Security middleware runs on all routes.
        .layer(middleware::from_fn(security_middleware));

    // Bind to localhost only (security).
    let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{port}")).await?;
    tracing::info!("[mcp-server] Deckle MCP server listening on http://127.0.0.1:{port}/mcp");
    tracing::info!(
        "[mcp-server]   POST /mcp - JSON-RPC; GET /mcp - SSE stream; DELETE /mcp - session cleanup"
    );

    axum::serve(listener, app)
        .with_graceful_shutdown(async move { ct.cancelled().await })
        .await?;

    Ok(())
}

// ---------------------------------------------------------------------------
// Static tool definitions
// ---------------------------------------------------------------------------

/// Instructions text returned to MCP clients.
const INSTRUCTIONS: &str = r#"Deckle is a professional design tool for creating user interfaces. The Deckle MCP server gives you tools to be a talented designer for web and mobile apps and websites. You can read designs from the user's file, understand what the user is currently doing, and write HTML back into the design as new nodes.

You MUST load the full guide before other Deckle tools: get_guide({ topic: "deckle-mcp-instructions" }). Do this once per session; call again if a long thread may have compressed or dropped guide text.

- Context: call get_basic_info first to understand artboards and dimensions; use get_selection to see user focus.
- Typography: you MUST call get_font_family_info before your first typographic styling in a session. Prefer font families already listed in get_basic_info unless the user specifies otherwise. Use px for font sizes, em for letter-spacing, px for line-height.
- New designs: before writing HTML, generate a brief (palette, type scale, spacing, direction) unless the user provides a design system.
- Creating/editing: each write_html call should add roughly one visual group; prefer duplicate_nodes with update_styles and set_text_content when it is faster than rewriting HTML.
- Quality: use get_screenshot to review after meaningful changes. Artboard height is a starting point — when content clips switch the artboard to height: "fit-content" via update_styles rather than guessing fixed heights.
- Repeated rows (lists, nav): use fixed-width slots for icons and trailing actions (flexShrink: 0); do not rely on gap alone to align columns across rows.
- When done creating or editing, you MUST call finish_working_on_nodes.
- User-facing output: do not include raw node IDs.
- Export to the user's codebase: use get_jsx, get_computed_styles, get_fill_image, etc. for exact values — do not read sizes or colors from screenshots alone."#;

/// Build the 30 static tool definitions that mirror the Deckle webapp's MCP handler.
/// These are returned when the webview bridge is not connected so that AI clients
/// can still see the tool catalog.
fn build_static_tools() -> Vec<Tool> {
    // Helper to create a tool with a JSON Schema input.
    // Mirrors the TS webapp's Zod-to-JSON-Schema output which always includes
    // `$schema` (draft-2020-12) and `additionalProperties: false` on every
    // root-level object schema.
    fn tool(name: &str, description: &str, schema: Value) -> Tool {
        let mut input_schema: serde_json::Map<String, Value> = match schema {
            Value::Object(map) => map,
            _ => {
                let mut m = serde_json::Map::new();
                m.insert("type".to_string(), json!("object"));
                m
            }
        };
        // Match the TS server's Zod-to-JSON-Schema output format.
        input_schema
            .entry("$schema".to_string())
            .or_insert_with(|| json!("https://json-schema.org/draft/2020-12/schema"));
        input_schema
            .entry("additionalProperties".to_string())
            .or_insert_with(|| json!(false));
        Tool::new(
            name.to_string(),
            description.to_string(),
            Arc::new(input_schema),
        )
    }

    // Annotation helpers matching the original webapp's MCPHandlers.
    let read_only = || ToolAnnotations::new().read_only(true);
    let destructive = || ToolAnnotations::new().destructive(true);

    vec![
        // get_guide has no annotation in the original
        tool(
            "get_guide",
            "Load the Deckle MCP guide. You MUST call this before using any other Deckle tools. Pass topic: \"deckle-mcp-instructions\" for the full guide.",
            json!({
                "type": "object",
                "properties": {
                    "topic": { "type": "string", "description": "The guide topic to load, e.g. \"deckle-mcp-instructions\"" }
                },
                "required": ["topic"]
            }),
        ),
        tool(
            "get_basic_info",
            "Get basic information about the current file: pages, artboards, fonts, tokens, and active page.",
            json!({ "type": "object", "properties": {} }),
        ).with_annotations(read_only()),
        tool(
            "get_selection",
            "Get information about the current user selection in the editor.",
            json!({
                "type": "object",
                "properties": {
                    "include_ancestors": { "type": "boolean", "description": "Include ancestor nodes in the response" }
                }
            }),
        ).with_annotations(read_only()),
        tool(
            "get_node_info",
            "Get detailed information about a specific node by ID.",
            json!({
                "type": "object",
                "properties": {
                    "node_id": { "type": "string", "description": "The ID of the node to inspect" },
                    "include_children": { "type": "boolean" }
                },
                "required": ["node_id"]
            }),
        ).with_annotations(read_only()),
        tool(
            "get_children",
            "Get the children of a node.",
            json!({
                "type": "object",
                "properties": {
                    "node_id": { "type": "string", "description": "The ID of the parent node" },
                    "depth": { "type": "number", "description": "How many levels deep to traverse" }
                },
                "required": ["node_id"]
            }),
        ).with_annotations(read_only()),
        tool(
            "get_screenshot",
            "Capture a screenshot of a node as a PNG or JPEG image.",
            json!({
                "type": "object",
                "properties": {
                    "node_id": { "type": "string", "description": "The ID of the node to capture" },
                    "scale": { "type": "number", "description": "Scale factor for the screenshot (default 1)" },
                    "format": { "type": "string", "enum": ["png", "jpeg"], "description": "Image format" }
                },
                "required": ["node_id"]
            }),
        ).with_annotations(read_only()),
        tool(
            "get_jsx",
            "Get the JSX representation of a node, useful for exporting to code.",
            json!({
                "type": "object",
                "properties": {
                    "node_id": { "type": "string", "description": "The ID of the node to export" }
                },
                "required": ["node_id"]
            }),
        ).with_annotations(read_only()),
        tool(
            "get_tree_summary",
            "Get a summary of the node tree structure from a given root.",
            json!({
                "type": "object",
                "properties": {
                    "node_id": { "type": "string", "description": "The root node ID" },
                    "depth": { "type": "number", "description": "Maximum depth to traverse" }
                },
                "required": ["node_id"]
            }),
        ).with_annotations(read_only()),
        tool(
            "get_computed_styles",
            "Get the computed CSS styles for one or more nodes.",
            json!({
                "type": "object",
                "properties": {
                    "node_ids": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Array of node IDs to get styles for"
                    },
                    "format": { "type": "string", "enum": ["css", "tailwind"] }
                },
                "required": ["node_ids"]
            }),
        ).with_annotations(read_only()),
        tool(
            "get_fill_image",
            "Get the fill image data for a node (base64-encoded).",
            json!({
                "type": "object",
                "properties": {
                    "node_id": { "type": "string", "description": "The ID of the node with an image fill" }
                },
                "required": ["node_id"]
            }),
        ).with_annotations(read_only()),
        tool(
            "get_font_family_info",
            "Get detailed information about a font family, including available weights and styles. You MUST call this before your first typographic styling in a session.",
            json!({
                "type": "object",
                "properties": {
                    "family": { "type": "string", "description": "The font family name to look up" }
                },
                "required": ["family"]
            }),
        ).with_annotations(read_only()),
        tool(
            "open_file",
            "Open a Deckle file by ID or URL.",
            json!({
                "type": "object",
                "properties": {
                    "file_id": { "type": "string", "description": "The file ID or Deckle URL to open" }
                },
                "required": ["file_id"]
            }),
        ).with_annotations(read_only()),
        tool(
            "list_files",
            "List files in the user's team workspace.",
            json!({
                "type": "object",
                "properties": {
                    "limit": { "type": "number", "description": "Maximum number of files to return (default 50)" }
                }
            }),
        ).with_annotations(read_only()),
        tool(
            "create_file",
            "Create a new Deckle file.",
            json!({
                "type": "object",
                "properties": {
                    "file_name": { "type": "string", "description": "Name for the new file" },
                    "clone_file_id": { "type": "string", "description": "Optional file ID to clone from" }
                }
            }),
        ).with_annotations(destructive()),
        tool(
            "open_page",
            "Navigate to a specific page in the current file.",
            json!({
                "type": "object",
                "properties": {
                    "page_id": { "type": "string", "description": "The ID of the page to open" }
                },
                "required": ["page_id"]
            }),
        ).with_annotations(read_only()),
        tool(
            "create_page",
            "Create a new page in the current file.",
            json!({
                "type": "object",
                "properties": {
                    "name": { "type": "string", "description": "Name for the new page" }
                }
            }),
        ).with_annotations(destructive()),
        tool(
            "write_html",
            "Write HTML content into the design as new nodes. Each call should add roughly one visual group.",
            json!({
                "type": "object",
                "properties": {
                    "html": { "type": "string", "description": "The HTML to write into the design" },
                    "parent_id": { "type": "string", "description": "The parent node ID to insert into" },
                    "mode": { "type": "string", "enum": ["insert-children", "replace"], "description": "Insert mode" }
                },
                "required": ["html", "parent_id"]
            }),
        ).with_annotations(destructive()),
        tool(
            "create_artboard",
            "Create a new artboard on the current page.",
            json!({
                "type": "object",
                "properties": {
                    "name": { "type": "string", "description": "Name for the artboard" },
                    "width": { "type": "number", "description": "Width in pixels" },
                    "height": { "type": "number", "description": "Height in pixels" },
                    "x": { "type": "number", "description": "X position" },
                    "y": { "type": "number", "description": "Y position" }
                }
            }),
        ).with_annotations(destructive()),
        tool(
            "delete_nodes",
            "Delete one or more nodes from the design.",
            json!({
                "type": "object",
                "properties": {
                    "node_ids": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Array of node IDs to delete"
                    }
                },
                "required": ["node_ids"]
            }),
        ).with_annotations(destructive()),
        tool(
            "set_text_content",
            "Set the text content of a text node.",
            json!({
                "type": "object",
                "properties": {
                    "node_id": { "type": "string", "description": "The text node ID" },
                    "text": { "type": "string", "description": "The new text content" }
                },
                "required": ["node_id", "text"]
            }),
        ).with_annotations(destructive()),
        tool(
            "rename_nodes",
            "Rename one or more nodes in the design tree.",
            json!({
                "type": "object",
                "properties": {
                    "renames": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "node_id": { "type": "string" },
                                "name": { "type": "string" }
                            },
                            "required": ["node_id", "name"]
                        },
                        "description": "Array of {node_id, name} pairs"
                    }
                },
                "required": ["renames"]
            }),
        ).with_annotations(destructive()),
        tool(
            "update_styles",
            "Update CSS styles on one or more nodes.",
            json!({
                "type": "object",
                "properties": {
                    "updates": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "node_id": { "type": "string" },
                                "styles": { "type": "object" }
                            },
                            "required": ["node_id", "styles"]
                        },
                        "description": "Array of {node_id, styles} pairs"
                    }
                },
                "required": ["updates"]
            }),
        ).with_annotations(destructive()),
        tool(
            "duplicate_nodes",
            "Duplicate one or more nodes.",
            json!({
                "type": "object",
                "properties": {
                    "node_ids": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Array of node IDs to duplicate"
                    }
                },
                "required": ["node_ids"]
            }),
        ).with_annotations(destructive()),
        tool(
            "move_nodes",
            "Move nodes to a new parent or position.",
            json!({
                "type": "object",
                "properties": {
                    "node_ids": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Array of node IDs to move"
                    },
                    "parent_id": { "type": "string", "description": "The target parent node ID" },
                    "index": { "type": "number", "description": "Position index within the parent" }
                },
                "required": ["node_ids", "parent_id"]
            }),
        ).with_annotations(destructive()),
        tool(
            "finish_working_on_nodes",
            "Signal that you are done creating or editing nodes. You MUST call this after creating or editing operations.",
            json!({
                "type": "object",
                "properties": {
                    "node_ids": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Array of node IDs you were working on"
                    }
                }
            }),
        ).with_annotations(read_only()),
        tool(
            "export",
            "Export one or more nodes as images (PNG, JPEG, SVG, PDF, WebP).",
            json!({
                "type": "object",
                "properties": {
                    "node_ids": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Array of node IDs to export"
                    },
                    "format": { "type": "string", "enum": ["png", "jpeg", "svg", "pdf", "webp"] },
                    "scale": { "type": "number", "description": "Scale factor for the export" }
                },
                "required": ["node_ids"]
            }),
        ).with_annotations(read_only()),
        tool(
            "export_combined_pdf",
            "Export multiple nodes as a single combined PDF document.",
            json!({
                "type": "object",
                "properties": {
                    "node_ids": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Array of node IDs to include in the PDF"
                    }
                },
                "required": ["node_ids"]
            }),
        ).with_annotations(read_only()),
        tool(
            "get_tokens",
            "Get design tokens defined in the current file.",
            json!({
                "type": "object",
                "properties": {
                    "filter": { "type": "string", "description": "Optional filter for token names" }
                }
            }),
        ).with_annotations(read_only()),
        tool(
            "create_tokens",
            "Create new design tokens in the current file.",
            json!({
                "type": "object",
                "properties": {
                    "tokens": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "name": { "type": "string" },
                                "value": { "type": "string" },
                                "type": { "type": "string" }
                            },
                            "required": ["name", "value"]
                        },
                        "description": "Array of tokens to create"
                    }
                },
                "required": ["tokens"]
            }),
        ).with_annotations(destructive()),
        tool(
            "set_tokens",
            "Update existing design tokens.",
            json!({
                "type": "object",
                "properties": {
                    "tokens": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "name": { "type": "string" },
                                "value": { "type": "string" }
                            },
                            "required": ["name", "value"]
                        },
                        "description": "Array of token updates"
                    }
                },
                "required": ["tokens"]
            }),
        ).with_annotations(destructive()),
    ]
}