Skip to main content

byob_protocol/
web.rs

1//! Web surfaces and their bridge (13.5+, cap [`CAP_WEB_BRIDGE`]).
2//!
3//! A web surface is HTML byob runs sandboxed (the Servo helper on the desktop, an iframe in
4//! the browser) that talks to byob over a typed bridge: JSON-RPC 2.0 messages, the
5//! [MCP Apps](https://github.com/modelcontextprotocol/ext-apps) dialect (`ui/initialize`,
6//! `tools/call`, `ui/message`, `ui/update-model-context`, `ui/open-link`, …). Who answers a
7//! surface's calls is its [`WebOwner`]: an MCP server (an MCP App: a tool that declares
8//! `_meta.ui.resourceUri`), or a plugin (a view declared with `html`, or an artifact
9//! renderer `web:<file>`).
10//!
11//! The client is the host the page talks to. It answers what is about the client itself
12//! (`ui/initialize` with the theme as CSS variables, `ui/open-link`, size changes) and sends
13//! the rest to the engine as a [`crate::ClientMsg::WebCall`], answered by one
14//! [`crate::ServerMsg::WebReply`] with the same `call` number. The engine routes a call to
15//! the owner (`tools/call` to the same MCP server through the permission gate, or to the
16//! plugin's backend tools; `byob/send` to the plugin's backend), or handles it itself
17//! (`byob/document`: the surface's HTML; `ui/message`: a user message in the chat;
18//! `ui/update-model-context`: text for the model's next request). Owners push messages to
19//! their surfaces with [`crate::ServerMsg::WebPush`].
20
21use serde::{Deserialize, Serialize};
22use serde_json::Value;
23
24/// Cap: the peer handles [`crate::ClientMsg::WebCall`], [`crate::ServerMsg::WebReply`],
25/// [`crate::ServerMsg::WebPush`] and the `byob.mcp_app` / `byob.web` step views.
26pub const CAP_WEB_BRIDGE: &str = "web_bridge";
27
28/// The MCP Apps extension id (in `initialize` capabilities).
29pub const MCP_UI_EXTENSION: &str = "io.modelcontextprotocol/ui";
30/// The MIME type of an MCP App's HTML resource.
31pub const MCP_APP_MIME: &str = "text/html;profile=mcp-app";
32/// The MCP Apps protocol version byob speaks with views.
33pub const MCP_APPS_VERSION: &str = "2026-01-26";
34
35/// Largest call or push (the JSON of `params` / `msg`).
36pub const MAX_CALL_BYTES: usize = 256 * 1024;
37/// Largest HTML document the engine sends for a surface.
38pub const MAX_DOCUMENT_BYTES: usize = 3 * 1024 * 1024;
39/// Longest method name.
40pub const MAX_METHOD_CHARS: usize = 64;
41/// Longest resource URI.
42pub const MAX_URI_CHARS: usize = 2048;
43
44/// Who answers a web surface's calls.
45#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
46#[serde(tag = "kind", rename_all = "snake_case")]
47pub enum WebOwner {
48    /// An MCP App: the `ui://` resource `uri` of server `server` of plugin `plugin`.
49    Mcp { plugin: String, server: String, uri: String },
50    /// A plugin's web view (`views: [{site, id, html}]`; `key` as for tree views) or a
51    /// `web:<file>` artifact renderer (`view` is `artifact:<file>`, `key` the artifact id).
52    Plugin {
53        plugin: String,
54        view: String,
55        #[serde(default, skip_serializing_if = "String::is_empty")]
56        key: String,
57    },
58    /// An owner a newer peer knows (its calls are refused).
59    #[serde(other)]
60    Other,
61}
62
63impl WebOwner {
64    /// The plugin behind the surface.
65    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    /// Check an untrusted owner's ids and sizes.
73    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/// What the engine says when a call needs the user's go-ahead first (a `tools/call` the
104/// permission gate would ask about): the client asks and sends the call again with
105/// `approved`.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct WebApproval {
108    /// What would run, e.g. "Weather: refresh_dashboard".
109    pub title: String,
110    pub access: crate::ToolAccess,
111}
112
113/// Why a call failed (a JSON-RPC error for the page).
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115pub struct WebError {
116    /// JSON-RPC error code (-32601 method not found, -32602 bad params, -32000 refused).
117    pub code: i64,
118    pub message: String,
119    /// Set when the user has to allow it first.
120    #[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/// The answer to `byob/document`: the surface's HTML and what it asks of the sandbox.
131#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
132pub struct WebDocument {
133    pub html: String,
134    /// The resource's `_meta.ui.csp` as declared (byob keeps its own strict policy and only
135    /// reports these; see the module docs of the client).
136    #[serde(default, skip_serializing_if = "Value::is_null")]
137    pub csp: Value,
138    /// `_meta.ui.permissions` as declared (none are granted).
139    #[serde(default, skip_serializing_if = "Value::is_null")]
140    pub permissions: Value,
141    /// `_meta.ui.prefersBorder`.
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub prefers_border: Option<bool>,
144}
145
146/// An MCP App on a tool's step (a [`crate::View`] of kind [`McpApp::KIND`]): the tool
147/// declared `_meta.ui.resourceUri`, so clients render that resource with the call's input
148/// and result.
149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
150pub struct McpApp {
151    pub plugin: String,
152    pub server: String,
153    /// The server's name for the tool.
154    pub tool: String,
155    /// The `ui://` resource.
156    pub uri: String,
157    /// What the step is called (the tool's title).
158    #[serde(default)]
159    pub title: String,
160    /// The call's arguments.
161    #[serde(default)]
162    pub input: Value,
163    /// The `CallToolResult` (content, structuredContent, isError), possibly shortened.
164    #[serde(default)]
165    pub result: Value,
166    /// The tool's definition as the server listed it (for `hostContext.toolInfo`).
167    #[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/// A plugin's web view on a step (a [`crate::View`] of kind [`WebCard::KIND`]): a backend
194/// tool returned `card_view` naming a view with `html`.
195#[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    /// What the tool gave the card (sent to the page as `byob/card`).
202    #[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
222/// Size checks of the bridge messages (see [`crate::ClientMsg::check_sizes`]).
223pub(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        // A newer peer's owner kind decodes (and is refused).
265        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}