1use serde::{Deserialize, Serialize};
22use serde_json::Value;
23
24pub const CAP_WEB_BRIDGE: &str = "web_bridge";
27
28pub const MCP_UI_EXTENSION: &str = "io.modelcontextprotocol/ui";
30pub const MCP_APP_MIME: &str = "text/html;profile=mcp-app";
32pub const MCP_APPS_VERSION: &str = "2026-01-26";
34
35pub const MAX_CALL_BYTES: usize = 256 * 1024;
37pub const MAX_DOCUMENT_BYTES: usize = 3 * 1024 * 1024;
39pub const MAX_METHOD_CHARS: usize = 64;
41pub const MAX_URI_CHARS: usize = 2048;
43
44#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
46#[serde(tag = "kind", rename_all = "snake_case")]
47pub enum WebOwner {
48 Mcp { plugin: String, server: String, uri: String },
50 Plugin {
53 plugin: String,
54 view: String,
55 #[serde(default, skip_serializing_if = "String::is_empty")]
56 key: String,
57 },
58 #[serde(other)]
60 Other,
61}
62
63impl WebOwner {
64 pub fn plugin(&self) -> Option<&str> {
66 match self {
67 Self::Mcp { plugin, .. } | Self::Plugin { plugin, .. } => Some(plugin),
68 Self::Other => None,
69 }
70 }
71
72 pub fn check(&self) -> Result<(), String> {
74 let id = |s: &str| {
75 if byob_types::config::plugin_id_ok(s) { Ok(()) } else { Err(format!("{:?} isn't a plugin id", s.chars().take(60).collect::<String>())) }
76 };
77 match self {
78 Self::Mcp { plugin, server, uri } => {
79 id(plugin)?;
80 if server.is_empty() || server.chars().count() > 128 {
81 return Err("bad server name".into());
82 }
83 if !uri.starts_with("ui://") || uri.chars().count() > MAX_URI_CHARS {
84 return Err("an MCP App's resource must be a ui:// URI".into());
85 }
86 Ok(())
87 }
88 Self::Plugin { plugin, view, key } => {
89 id(plugin)?;
90 if view.is_empty() || view.chars().count() > 300 {
91 return Err("bad view id".into());
92 }
93 if key.chars().count() > crate::sites::MAX_VIEW_KEY_CHARS {
94 return Err("bad view key".into());
95 }
96 Ok(())
97 }
98 Self::Other => Err("unknown web surface owner".into()),
99 }
100 }
101}
102
103#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct WebApproval {
108 pub title: String,
110 pub access: crate::ToolAccess,
111}
112
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115pub struct WebError {
116 pub code: i64,
118 pub message: String,
119 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub approval: Option<WebApproval>,
122}
123
124impl WebError {
125 pub fn new(code: i64, message: impl Into<String>) -> Self {
126 Self { code, message: message.into(), approval: None }
127 }
128}
129
130#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
132pub struct WebDocument {
133 pub html: String,
134 #[serde(default, skip_serializing_if = "Value::is_null")]
137 pub csp: Value,
138 #[serde(default, skip_serializing_if = "Value::is_null")]
140 pub permissions: Value,
141 #[serde(default, skip_serializing_if = "Option::is_none")]
143 pub prefers_border: Option<bool>,
144}
145
146#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
150pub struct McpApp {
151 pub plugin: String,
152 pub server: String,
153 pub tool: String,
155 pub uri: String,
157 #[serde(default)]
159 pub title: String,
160 #[serde(default)]
162 pub input: Value,
163 #[serde(default)]
165 pub result: Value,
166 #[serde(default, skip_serializing_if = "Value::is_null")]
168 pub tool_def: Value,
169}
170
171impl McpApp {
172 pub fn owner(&self) -> WebOwner {
173 WebOwner::Mcp { plugin: self.plugin.clone(), server: self.server.clone(), uri: self.uri.clone() }
174 }
175}
176
177impl crate::ViewData for McpApp {
178 const KIND: &'static str = "byob.mcp_app";
179 const V: u32 = 1;
180 fn fallback(&self) -> String {
181 let text: String = self
182 .result
183 .get("content")
184 .and_then(Value::as_array)
185 .map(|c| c.iter().filter_map(|p| p.get("text").and_then(Value::as_str)).collect::<Vec<_>>().join("\n"))
186 .unwrap_or_default();
187 let title = if self.title.is_empty() { &self.tool } else { &self.title };
188 let text: String = text.chars().take(4000).collect();
189 format!("**{title}** (an app; this version of byob can't show it)\n\n{text}")
190 }
191}
192
193#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
196pub struct WebCard {
197 pub plugin: String,
198 pub view: String,
199 #[serde(default)]
200 pub key: String,
201 #[serde(default)]
203 pub data: Value,
204 #[serde(default)]
205 pub text: String,
206}
207
208impl WebCard {
209 pub fn owner(&self) -> WebOwner {
210 WebOwner::Plugin { plugin: self.plugin.clone(), view: self.view.clone(), key: self.key.clone() }
211 }
212}
213
214impl crate::ViewData for WebCard {
215 const KIND: &'static str = "byob.web";
216 const V: u32 = 1;
217 fn fallback(&self) -> String {
218 self.text.chars().take(4000).collect()
219 }
220}
221
222pub(crate) fn check_call(owner: &WebOwner, method: &str, params: &Value) -> Result<(), String> {
224 owner.check()?;
225 if method.is_empty() || method.chars().count() > MAX_METHOD_CHARS {
226 return Err("bad method".into());
227 }
228 let size = serde_json::to_string(params).map_or(usize::MAX, |s| s.len());
229 if size > MAX_CALL_BYTES {
230 return Err(format!("web call too large ({size} bytes, at most {MAX_CALL_BYTES})"));
231 }
232 Ok(())
233}
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238 use crate::{ClientMsg, ServerMsg, ViewData as _};
239 use serde_json::json;
240
241 fn mcp() -> WebOwner {
242 WebOwner::Mcp { plugin: "weather".into(), server: "main".into(), uri: "ui://weather/dash".into() }
243 }
244
245 #[test]
246 fn bridge_messages_round_trip_and_are_checked() {
247 let call = ClientMsg::WebCall { call: 7, owner: mcp(), method: "tools/call".into(), params: json!({"name": "refresh"}), approved: false };
248 assert_eq!(ClientMsg::from_json(&call.to_json()).unwrap(), call);
249 assert!(call.check_sizes().is_ok());
250 let j = call.to_json();
251 assert!(j.contains(r#""owner":{"kind":"mcp","plugin":"weather","server":"main","uri":"ui://weather/dash"}"#), "{j}");
252 let plugin = WebOwner::Plugin { plugin: "sheets".into(), view: "grid".into(), key: String::new() };
253 assert_eq!(serde_json::to_string(&plugin).unwrap(), r#"{"kind":"plugin","plugin":"sheets","view":"grid"}"#);
254 for bad in [
255 WebOwner::Mcp { plugin: "Weather".into(), server: "main".into(), uri: "ui://x".into() },
256 WebOwner::Mcp { plugin: "weather".into(), server: "main".into(), uri: "https://x".into() },
257 WebOwner::Plugin { plugin: "p".into(), view: String::new(), key: String::new() },
258 WebOwner::Other,
259 ] {
260 assert!(ClientMsg::WebCall { call: 1, owner: bad, method: "x".into(), params: Value::Null, approved: false }.check_sizes().is_err());
261 }
262 let big = ClientMsg::WebCall { call: 1, owner: mcp(), method: "x".into(), params: json!("x".repeat(MAX_CALL_BYTES)), approved: false };
263 assert!(big.check_sizes().is_err());
264 let other: WebOwner = serde_json::from_str(r#"{"kind":"canvas","x":1}"#).unwrap();
266 assert_eq!(other, WebOwner::Other);
267
268 for m in [
269 ServerMsg::WebReply { call: 7, result: Some(json!({"content": []})), error: None },
270 ServerMsg::WebReply {
271 call: 8,
272 result: None,
273 error: Some(WebError {
274 code: -32000,
275 message: "ask first".into(),
276 approval: Some(WebApproval { title: "t".into(), access: crate::ToolAccess::Network }),
277 }),
278 },
279 ServerMsg::WebPush { owner: plugin, msg: json!({"jsonrpc": "2.0", "method": "byob/message", "params": {"n": 1}}) },
280 ] {
281 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
282 }
283 }
284
285 #[test]
286 fn mcp_app_views_fall_back_to_their_text() {
287 let app = McpApp {
288 plugin: "weather".into(),
289 server: "main".into(),
290 tool: "get_weather".into(),
291 uri: "ui://weather/dash".into(),
292 title: "Weather".into(),
293 input: json!({"city": "Lisbon"}),
294 result: json!({"content": [{"type": "text", "text": "21°C"}]}),
295 tool_def: Value::Null,
296 };
297 let v = crate::View::of(&app);
298 assert_eq!(v.kind, "byob.mcp_app");
299 assert!(v.fallback.contains("21°C") && v.fallback.contains("Weather"));
300 assert_eq!(v.get::<McpApp>(), Some(app.clone()));
301 assert_eq!(app.owner(), mcp());
302 assert!(v.check().is_ok());
303 assert!(!serde_json::to_string(&app).unwrap().contains("tool_def"));
304 assert_eq!(WebCard { plugin: "p".into(), view: "v".into(), key: "k".into(), data: Value::Null, text: "hi".into() }.fallback(), "hi");
305 }
306}