ribir_core 0.4.0-alpha.60

A non-intrusive declarative GUI framework, to build modern native/wasm cross-platform applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
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
//! MCP Protocol Implementation
//!
//! This module implements the Model Context Protocol (MCP) for the Ribir debug
//! server. See: https://modelcontextprotocol.io

use std::sync::Arc;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::debug_tool::server::DebugServerState;

// === JSON-RPC Types ===

/// JSON-RPC 2.0 Request
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct JsonRpcRequest {
  #[serde(rename = "jsonrpc")]
  pub jsonrpc: String,
  pub method: String,
  #[serde(default)]
  pub params: Option<Value>,
  pub id: Option<Value>,
}

/// JSON-RPC 2.0 Response
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct JsonRpcResponse {
  #[serde(rename = "jsonrpc")]
  pub jsonrpc: String,
  #[serde(skip_serializing_if = "Option::is_none")]
  pub result: Option<Value>,
  #[serde(skip_serializing_if = "Option::is_none")]
  pub error: Option<JsonRpcError>,
  pub id: Option<Value>,
}

impl JsonRpcResponse {
  pub fn result(id: Option<Value>, result: Value) -> Self {
    Self { jsonrpc: "2.0".to_string(), result: Some(result), error: None, id }
  }

  pub fn error(id: Option<Value>, code: i32, message: impl Into<String>) -> Self {
    Self {
      jsonrpc: "2.0".to_string(),
      result: None,
      error: Some(JsonRpcError { code, message: message.into(), data: None }),
      id,
    }
  }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct JsonRpcError {
  pub code: i32,
  pub message: String,
  #[serde(skip_serializing_if = "Option::is_none")]
  pub data: Option<Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct InitializeResult {
  #[serde(rename = "protocolVersion")]
  pub protocol_version: String,
  pub capabilities: ServerCapabilities,
  #[serde(rename = "serverInfo")]
  pub server_info: ServerInfo,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ServerCapabilities {
  #[serde(skip_serializing_if = "Option::is_none")]
  pub tools: Option<Value>,
  #[serde(skip_serializing_if = "Option::is_none")]
  pub resources: Option<Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ServerInfo {
  pub name: String,
  pub version: String,
  pub description: String,
}

// === Tools ===

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Tool {
  pub name: String,
  pub description: String,
  #[serde(rename = "inputSchema")]
  pub input_schema: Value,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ListToolsResult {
  pub tools: Vec<Tool>,
}

#[derive(Deserialize, Debug)]
pub struct CallToolParams {
  pub name: String,
  #[serde(default)]
  pub arguments: Option<Value>,
}

#[derive(Serialize, Debug)]
pub struct CallToolResult {
  pub content: Vec<ToolContent>,
  #[serde(default)]
  #[serde(rename = "isError")]
  pub is_error: bool,
}

#[derive(Serialize, Debug)]
#[serde(tag = "type")]
pub enum ToolContent {
  #[serde(rename = "text")]
  Text { text: String },
  #[serde(rename = "image")]
  Image {
    data: String,
    #[serde(rename = "mimeType")]
    mime_type: String,
  },
}

// === Resources ===

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Resource {
  pub uri: String,
  pub name: String,
  #[serde(skip_serializing_if = "Option::is_none")]
  pub description: Option<String>,
  #[serde(skip_serializing_if = "Option::is_none")]
  #[serde(rename = "mimeType")]
  pub mime_type: Option<String>,
}

#[derive(Serialize, Debug)]
pub struct ListResourcesResult {
  pub resources: Vec<Resource>,
}

#[derive(Deserialize, Debug)]
pub struct ReadResourceParams {
  pub uri: String,
}

#[derive(Serialize, Debug)]
pub struct ReadResourceResult {
  pub contents: Vec<ResourceContent>,
}

#[derive(Serialize, Debug)]
pub struct ResourceContent {
  pub uri: String,
  #[serde(skip_serializing_if = "Option::is_none")]
  #[serde(rename = "mimeType")]
  pub mime_type: Option<String>,
  #[serde(skip_serializing_if = "Option::is_none")]
  pub text: Option<String>,
  #[serde(skip_serializing_if = "Option::is_none")]
  pub blob: Option<String>,
}

// === Request Handler ===

pub async fn handle_mcp_request(
  request: JsonRpcRequest, state: Arc<DebugServerState>,
) -> JsonRpcResponse {
  let id = request.id.clone();

  match request.method.as_str() {
    "initialize" => {
      tracing::info!("MCP: initialize request from client");

      #[derive(Deserialize)]
      struct McpSchemaInit {
        fallback_init_result: InitializeResult,
      }

      let schema_json = include_str!("mcp_schema.json");
      let schema: McpSchemaInit =
        serde_json::from_str(schema_json).expect("Failed to parse mcp_schema.json");

      let mut result = schema.fallback_init_result;
      // Overwrite dynamic fields if necessary (like version if not in JSON)
      result.server_info.version = env!("CARGO_PKG_VERSION").to_string();

      JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
    }

    "notifications/initialized" => {
      tracing::info!("MCP: client initialized");
      // Notification - return success with no result
      JsonRpcResponse::result(id, Value::Null)
    }

    "tools/list" => {
      tracing::info!("MCP: tools/list request");

      #[derive(Deserialize)]
      struct McpSchemaTools {
        tools: Vec<Tool>,
      }

      let schema_json = include_str!("mcp_schema.json");
      let schema: McpSchemaTools =
        serde_json::from_str(schema_json).expect("Failed to parse mcp_schema.json");

      JsonRpcResponse::result(
        id,
        serde_json::to_value(ListToolsResult { tools: schema.tools }).unwrap(),
      )
    }

    "tools/call" => handle_tool_call(request.params, state, id).await,

    "resources/list" => {
      tracing::info!("MCP: resources/list request");

      #[derive(Deserialize)]
      struct McpSchemaResources {
        resources: Vec<Resource>,
      }
      let schema_json = include_str!("mcp_schema.json");
      let schema: McpSchemaResources =
        serde_json::from_str(schema_json).expect("Failed to parse mcp_schema.json");

      JsonRpcResponse::result(
        id,
        serde_json::to_value(ListResourcesResult { resources: schema.resources }).unwrap(),
      )
    }

    "resources/read" => handle_read_resource(request.params, state, id).await,

    _ => {
      tracing::warn!("MCP: unknown method: {}", request.method);
      JsonRpcResponse::error(id, -32601, format!("Method not found: {}", request.method))
    }
  }
}

async fn handle_tool_call(
  params: Option<Value>, state: Arc<DebugServerState>, id: Option<Value>,
) -> JsonRpcResponse {
  use crate::debug_tool::service::*;

  let params: CallToolParams = match serde_json::from_value(params.unwrap_or(Value::Null)) {
    Ok(p) => p,
    Err(e) => return JsonRpcResponse::error(id, -32602, format!("Invalid params: {}", e)),
  };

  tracing::info!("MCP: tools/call - {}", params.name);

  // Helper to extract common arguments
  let args = params.arguments.as_ref();
  let get_str = |key: &str| -> Option<&str> {
    args
      .and_then(|a| a.get(key))
      .and_then(|v| v.as_str())
  };
  let parse_window_id = |v: &Value| -> Option<crate::window::WindowId> {
    match v {
      Value::String(s) => s
        .parse::<u64>()
        .ok()
        .map(crate::window::WindowId::from),
      Value::Number(n) => n.as_u64().map(crate::window::WindowId::from),
      _ => None,
    }
  };
  let get_window_id = || -> Option<crate::window::WindowId> {
    args
      .and_then(|a| a.get("window_id"))
      .and_then(parse_window_id)
  };

  match params.name.as_str() {
    "capture_screenshot" => match capture_screenshot_svc(&state).await {
      Ok(img) => {
        let mut png_data = Vec::new();
        if img.write_as_png(&mut png_data).is_ok() {
          use base64::{Engine as _, engine::general_purpose};
          let b64 = general_purpose::STANDARD.encode(&png_data);
          let result = CallToolResult {
            content: vec![ToolContent::Image { data: b64, mime_type: "image/png".to_string() }],
            is_error: false,
          };
          JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
        } else {
          JsonRpcResponse::error(id, -32000, "Failed to encode image")
        }
      }
      Err(e) => JsonRpcResponse::error(id, -32000, e.to_string()),
    },

    "inspect_tree" => {
      let options = parse_options(get_str("options"));
      match inspect_tree_svc(&state, get_window_id(), options).await {
        Ok(tree) => {
          let json_str = serde_json::to_string_pretty(&tree).unwrap_or_default();
          let result =
            CallToolResult { content: vec![ToolContent::Text { text: json_str }], is_error: false };
          JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
        }
        Err(e) => JsonRpcResponse::error(id, -32000, e.to_string()),
      }
    }

    "inspect_widget" => {
      let options = parse_options(get_str("options"));
      let Some(widget_id) = get_str("id").map(String::from) else {
        return JsonRpcResponse::error(id, -32602, "Missing required argument: id");
      };

      match inspect_widget_svc(&state, get_window_id(), widget_id, options).await {
        Ok(info) => {
          let json_str = serde_json::to_string_pretty(&info).unwrap_or_default();
          let result =
            CallToolResult { content: vec![ToolContent::Text { text: json_str }], is_error: false };
          JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
        }
        Err(ServiceError::NotFound) => JsonRpcResponse::error(
          id,
          -32001,
          "Widget not found. Supported id formats: \'3\', \'3:0\', \
           \'{\"index1\":3,\"stamp\":0}\', or \'name:<debug_name>\'. Tip: call \
           inspect_tree(options='id') to discover valid IDs.",
        ),
        Err(e) => JsonRpcResponse::error(id, -32000, e.to_string()),
      }
    }

    "get_overlays" => {
      // If no window_id provided, get the default window
      let w_id = if let Some(wid) = get_window_id() {
        Some(wid)
      } else {
        get_windows_svc(&state)
          .await
          .ok()
          .and_then(|list| list.first().map(|w| w.id))
      };

      if let Some(wid) = w_id {
        let overlays = get_overlays_svc(wid);
        let json_str = serde_json::to_string_pretty(&overlays).unwrap_or_default();
        let result =
          CallToolResult { content: vec![ToolContent::Text { text: json_str }], is_error: false };
        JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
      } else {
        JsonRpcResponse::error(id, -32000, "No active window found")
      }
    }

    "set_log_filter" => {
      let Some(filter) = get_str("filter") else {
        return JsonRpcResponse::error(id, -32602, "Missing filter argument");
      };

      if let Err(e) = crate::logging::update_filter(filter) {
        JsonRpcResponse::error(id, -32000, format!("Failed to update filter: {}", e))
      } else {
        let result = CallToolResult {
          content: vec![ToolContent::Text { text: format!("Log filter set to: {}", filter) }],
          is_error: false,
        };
        JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
      }
    }

    "add_overlay" => {
      let Some(widget_id) = get_str("id").map(String::from) else {
        return JsonRpcResponse::error(id, -32602, "Missing required argument: id");
      };
      let color = get_str("color")
        .unwrap_or("#FF000080")
        .to_string();

      match add_overlay_svc(&state, get_window_id(), widget_id.clone(), color).await {
        Ok(()) => {
          let result = CallToolResult {
            content: vec![ToolContent::Text { text: format!("Overlay added to {}", widget_id) }],
            is_error: false,
          };
          JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
        }
        Err(ServiceError::NotFound) => JsonRpcResponse::error(
          id,
          -32001,
          "Widget not found for overlay. Supported id formats: \'3\', \'3:0\', \
           \'{\"index1\":3,\"stamp\":0}\', or \'name:<debug_name>\'.",
        ),
        Err(e) => JsonRpcResponse::error(id, -32000, format!("Failed to add overlay: {}", e)),
      }
    }

    "remove_overlay" => {
      let Some(widget_id) = get_str("id").map(String::from) else {
        return JsonRpcResponse::error(id, -32602, "Missing required argument: id");
      };

      match remove_overlay_svc(&state, get_window_id(), widget_id.clone()).await {
        Ok(()) => {
          let result = CallToolResult {
            content: vec![ToolContent::Text {
              text: format!("Overlay removed from {}", widget_id),
            }],
            is_error: false,
          };
          JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
        }
        Err(ServiceError::NotFound) => JsonRpcResponse::error(
          id,
          -32001,
          "Overlay/widget not found. Supported id formats: '3', '3:0', or \
           '{\"index1\":3,\"stamp\":0}'.",
        ),
        Err(e) => JsonRpcResponse::error(id, -32000, format!("Failed to remove overlay: {}", e)),
      }
    }

    "clear_overlays" => match clear_overlays_svc(&state, get_window_id()).await {
      Ok(()) => {
        let result = CallToolResult {
          content: vec![ToolContent::Text { text: "Overlays cleared".to_string() }],
          is_error: false,
        };
        JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
      }
      Err(e) => JsonRpcResponse::error(id, -32000, e.to_string()),
    },

    "start_recording" => {
      #[derive(Deserialize)]
      struct StartRecordingArgs {
        #[serde(default)]
        include: Vec<String>,
      }

      let include = if let Some(raw) = params.arguments.clone() {
        let parsed: StartRecordingArgs = match serde_json::from_value(raw) {
          Ok(v) => v,
          Err(e) => return JsonRpcResponse::error(id, -32602, format!("Invalid params: {}", e)),
        };

        if parsed.include.is_empty() {
          vec!["images".to_string()]
        } else if parsed
          .include
          .iter()
          .all(|v| matches!(v.as_str(), "logs" | "images"))
        {
          parsed.include
        } else {
          return JsonRpcResponse::error(
            id,
            -32602,
            "Invalid 'include'. Allowed values: 'logs', 'images'.",
          );
        }
      } else {
        vec!["images".to_string()]
      };

      match crate::debug_tool::server::capture_start_inner(
        state.clone(),
        include,
        2_000,
        1_000,
        None,
      )
      .await
      {
        Ok(axum::Json(resp)) => {
          state
            .recording
            .store(true, std::sync::atomic::Ordering::Relaxed);
          let result = CallToolResult {
            content: vec![ToolContent::Text {
              text: format!("Recording started. Capture dir: {}", resp.capture_dir),
            }],
            is_error: false,
          };
          JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
        }
        Err(axum::http::StatusCode::CONFLICT) => {
          JsonRpcResponse::error(id, -32000, "Recording already active")
        }
        Err(code) => {
          JsonRpcResponse::error(id, -32000, format!("Failed to start recording: status {}", code))
        }
      }
    }

    "stop_recording" => {
      match crate::debug_tool::server::capture_stop_inner(
        state.clone(),
        crate::debug_tool::server::CaptureStopRequest { capture_id: None },
      )
      .await
      {
        Ok(axum::Json(resp)) => {
          state
            .recording
            .store(false, std::sync::atomic::Ordering::Relaxed);
          let result = CallToolResult {
            content: vec![ToolContent::Text {
              text: format!(
                "Recording stopped.\nCapture: {}\nManifest: {}",
                resp.capture_dir, resp.manifest_path
              ),
            }],
            is_error: false,
          };
          JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
        }
        Err(axum::http::StatusCode::NOT_FOUND) => {
          JsonRpcResponse::error(id, -32001, "No active recording session")
        }
        Err(code) => {
          JsonRpcResponse::error(id, -32000, format!("Failed to stop recording: status {}", code))
        }
      }
    }

    "capture_one_shot" => {
      let req: crate::debug_tool::server::CaptureOneShotRequest =
        match serde_json::from_value(params.arguments.unwrap_or(Value::Null)) {
          Ok(r) => r,
          Err(e) => return JsonRpcResponse::error(id, -32602, format!("Invalid params: {}", e)),
        };

      match crate::debug_tool::server::capture_one_shot_inner(state, req).await {
        Ok(axum::Json(resp)) => {
          let result = CallToolResult {
            content: vec![ToolContent::Text {
              text: format!(
                "Capture saved to {}\nManifest: {}",
                resp.capture_dir, resp.manifest_path
              ),
            }],
            is_error: false,
          };
          JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
        }
        Err(code) => {
          JsonRpcResponse::error(id, -32000, format!("Failed to capture one shot: status {}", code))
        }
      }
    }

    "inject_events" => {
      let args = params.arguments.unwrap_or(Value::Null);
      let args_obj = match args.as_object() {
        Some(obj) => obj,
        None => return JsonRpcResponse::error(id, -32602, "Invalid params: expected object"),
      };

      let window_id = args_obj
        .get("window_id")
        .and_then(parse_window_id);

      let Some(events_value) = args_obj.get("events").cloned() else {
        return JsonRpcResponse::error(id, -32602, "Missing required argument: events");
      };
      let events: Vec<crate::debug_tool::types::InjectedUiEvent> =
        match serde_json::from_value(events_value) {
          Ok(v) => v,
          Err(e) => return JsonRpcResponse::error(id, -32602, format!("Invalid params: {}", e)),
        };

      match inject_events_svc(&state, window_id, events).await {
        Ok(result) => {
          let text = serde_json::to_string_pretty(&result).unwrap_or_default();
          let result =
            CallToolResult { content: vec![ToolContent::Text { text }], is_error: false };
          JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
        }
        Err(e) => JsonRpcResponse::error(id, -32000, format!("Failed to inject events: {}", e)),
      }
    }

    _ => JsonRpcResponse::error(id, -32601, format!("Tool not found: {}", params.name)),
  }
}

async fn handle_read_resource(
  params: Option<Value>, state: Arc<DebugServerState>, id: Option<Value>,
) -> JsonRpcResponse {
  let params: ReadResourceParams = match serde_json::from_value(params.unwrap_or(Value::Null)) {
    Ok(p) => p,
    Err(e) => return JsonRpcResponse::error(id, -32602, format!("Invalid params: {}", e)),
  };

  match params.uri.as_str() {
    "ribir://logs" => {
      let lines = {
        let ring = state.log_ring.lock().await;
        ring.query_lines(None, None, Some(100))
      };
      let text = lines
        .iter()
        .map(|s| s.as_ref())
        .collect::<Vec<_>>()
        .join("\n");
      let result = ReadResourceResult {
        contents: vec![ResourceContent {
          uri: params.uri,
          mime_type: Some("text/plain".to_string()),
          text: Some(text),
          blob: None,
        }],
      };
      JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
    }
    "ribir://windows" => {
      use tokio::sync::oneshot;
      let (tx, rx) = oneshot::channel();
      let _ = state
        .command_tx
        .send(crate::debug_tool::types::DebugCommand::GetWindows { reply: tx })
        .await;
      match rx.await {
        Ok(windows) => {
          let text = serde_json::to_string_pretty(&windows).unwrap_or_default();
          let result = ReadResourceResult {
            contents: vec![ResourceContent {
              uri: params.uri,
              mime_type: Some("application/json".to_string()),
              text: Some(text),
              blob: None,
            }],
          };
          JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
        }
        Err(_) => JsonRpcResponse::error(id, -32000, "Failed to retrieve windows"),
      }
    }
    "ribir://status" => {
      let status = crate::debug_tool::server::build_status_response(&state).await;

      let result = ReadResourceResult {
        contents: vec![ResourceContent {
          uri: params.uri,
          mime_type: Some("application/json".to_string()),
          text: Some(serde_json::to_string(&status).unwrap_or_else(|_| "{}".to_string())),
          blob: None,
        }],
      };
      JsonRpcResponse::result(id, serde_json::to_value(result).unwrap())
    }
    _ => JsonRpcResponse::error(id, -32002, "Resource not found"),
  }
}