Skip to main content

adk_surface/genui/mcp_apps/
mod.rs

1//! The MCP Apps host (spec 3.3 §6.1 `genui-apps`, wave 4 decisions 15–17): an MCP server's
2//! `_meta.ui` app shown in a thread, sandboxed on its own origin, which can never approve
3//! anything.
4//!
5//! | Step | What the host does |
6//! |---|---|
7//! | Projection | A tool call whose event carries the MCP tool's own `adk.mcp.app` record becomes [`ThreadItem::App`](crate::ThreadItem::App) |
8//! | Open | Reads the `ui://` resource from the server that published the tool, checks its MIME type, checks every declared site (nothing on this computer, its network, the home or the page's own origin, nor a wildcard over them), scans the HTML for a decision's words and undeclared sites, and frames it on the apps origin under a CSP built from what passed, which only the home's page may frame |
9//! | `tools/call` | Only a tool the same server publishes for both the model and the app, a tool without `_meta.ui` included, by the name the agent knows that tool by, asked for as a requested call held by the agent whose call showed the app and answered once the agent has held or refused it; an app-only tool is "This app needs a tool this home can't run yet"; the same call again is the same decision, and an app with three calls waiting asks for no more |
10//! | `ui/message` | "The app wants to send: …" with **Send it** and **Not now**; sent as the person's message inside an untrusted-content block labelled "Suggested by the Weather app", which every surface shows as the message and that label |
11//! | `ui/open-link` | "Open example.com?", opened only by the person's press; a link to this computer or its network is refused |
12//! | `ui/download-file` | "The Weather app wants to save forecast.csv (2 KB)", saved only by the person's press: an embedded resource up to 5 MB, its name sanitized, never a file that runs or opens as a page |
13//! | Origins | With a `localhost` apps origin, each server's apps on an origin of their own under it ([`McpAppsHostBuilder::origin_per_server`]); `ui/initialize` reports what the frame was granted (`hostCapabilities.sandbox`) |
14//! | `ui/update-model-context` | Logged, never forwarded to the model |
15//! | Anything else | "not supported here" |
16//!
17//! The apps origin is a second loopback listener ([`McpAppsHost::sandbox_router`]) or a remote
18//! home's `--apps-origin`; the surface API refuses every request from it
19//! ([`refuse_apps_origin`](crate::web::genui::refuse_apps_origin)). Without an apps origin, on
20//! the phone and in the terminal, an app is its text result and "Open the home on this
21//! computer to see this app".
22
23mod scan;
24mod sites;
25
26use std::collections::{HashMap, HashSet};
27use std::sync::{Arc, Mutex};
28use std::time::{Duration, Instant};
29
30use adk_core::{Event, Part, RequestedCall, RequestedVia, RequestedViaKind};
31use adk_tool::mcp::{
32    MCP_APP_STATE_KEY, MCP_APPS_VERSION, McpAppRecord, McpAppResource, McpServerManager,
33    McpUiBinding, McpUiVisibility, ResourceContents,
34};
35use async_trait::async_trait;
36use axum::Router;
37use axum::extract::{Path, State};
38use axum::http::{HeaderValue, StatusCode, header};
39use axum::response::{IntoResponse, Response};
40use axum::routing::get;
41use serde_json::{Value, json};
42
43use super::app_view::app_name;
44use super::{AppAnswer, AppBlockReason, AppError, AppOpen, AppPrompt, AppRequest, AppView};
45use crate::engine::{Command, CommandOutcome, SurfaceEngine};
46use crate::error::{Result, SurfaceError};
47use crate::model::{DecisionCard, ThreadItem};
48use crate::origin::{Caller, SurfaceKind};
49use crate::project::Projector;
50use crate::words;
51
52/// Audit record: an app was not framed, with its reason.
53pub const SURFACE_AUDIT_APP_BLOCKED: &str = "surface.app.blocked";
54/// Audit record: an app's tool call was refused, by the home or by the agent.
55pub const SURFACE_AUDIT_APP_CALL_REFUSED: &str = "surface.app.call_refused";
56/// Audit record: an app's tool call was asked of the agent whose call showed the app.
57pub const SURFACE_AUDIT_APP_CALL_ASKED: &str = "surface.app.call_asked";
58/// Audit record: the agent held an app's tool call for the person's decision.
59pub const SURFACE_AUDIT_APP_CALL_HELD: &str = "surface.app.call_held";
60/// Audit record: requests from the apps origin, or an app's opaque frame, were refused
61/// (at most one record a minute, with the count).
62pub const SURFACE_AUDIT_APP_ORIGIN_REFUSED: &str = "surface.app.origin_refused";
63/// Audit record: the person sent a message an app suggested.
64pub const SURFACE_AUDIT_APP_MESSAGE_SENT: &str = "surface.app.message_sent";
65
66/// The tallest an app's frame grows, in CSS pixels.
67const MAX_HEIGHT: u32 = 640;
68/// How long a framed app's page stays available on the apps origin.
69const FRAME_LIFETIME: Duration = Duration::from_secs(15 * 60);
70/// The longest message an app may suggest, in characters.
71const MAX_MESSAGE_CHARS: usize = 4_000;
72/// The largest view state an app may ask the host to keep.
73const MAX_VIEW_STATE_BYTES: usize = 64 * 1024;
74/// How many apps' grants are kept before the oldest are forgotten.
75const MAX_GRANTS_KEPT: usize = 1_024;
76/// JSON-RPC: the method is not offered here.
77const METHOD_NOT_FOUND: i64 = -32_601;
78/// JSON-RPC: the parameters are not what the method takes.
79const INVALID_PARAMS: i64 = -32_602;
80/// JSON-RPC: the home refused the request.
81const REFUSED: i64 = -32_000;
82/// The most calls one app may have waiting for the person at once.
83const MAX_WAITING: usize = 3;
84/// How long an app's tool call waits for the agent to hold or refuse it before the app is
85/// answered anyway.
86const OUTCOME_WAIT: Duration = Duration::from_secs(10);
87/// How often the thread is read for that outcome.
88const OUTCOME_POLL: Duration = Duration::from_millis(50);
89
90/// The MCP servers whose apps a home shows (spec 3.3 §6.1 `genui-apps`): each server's tool
91/// bindings and its `ui://` resources. [`McpServerManager`] is one.
92#[async_trait]
93pub trait AppServers: Send + Sync {
94    /// Every `_meta.ui` binding `server` publishes, the app-only tools included; `None` when
95    /// this set does not run `server`.
96    async fn ui_bindings(&self, server: &str) -> Option<adk_core::Result<Vec<McpUiBinding>>>;
97
98    /// The contents of `server`'s resource `uri`.
99    async fn read_resource(
100        &self,
101        server: &str,
102        uri: &str,
103    ) -> adk_core::Result<Vec<ResourceContents>>;
104
105    /// Who may call each tool `server` publishes, by its name on the server: its
106    /// `_meta.ui.visibility`, or the model and the app when it declares none; `None` when this
107    /// set does not run `server`. The default reads [`ui_bindings`](Self::ui_bindings), which
108    /// lists only the tools with an app.
109    async fn tool_visibility(
110        &self,
111        server: &str,
112    ) -> Option<adk_core::Result<Vec<(String, McpUiVisibility)>>> {
113        let bindings = self.ui_bindings(server).await?;
114        Some(bindings.map(|bindings| {
115            bindings.into_iter().map(|binding| (binding.tool, binding.visibility)).collect()
116        }))
117    }
118
119    /// The MCP definition of `server`'s tool `tool` (name, description, input schema,
120    /// annotations), when this set can read it: what the opt-in consent policy decides on
121    /// ([`AppConsent`]). `None` decides nothing: the call is held for the person.
122    ///
123    /// # Errors
124    ///
125    /// The set's error when it cannot list the server's tools.
126    async fn tool_definition(&self, _server: &str, _tool: &str) -> adk_core::Result<Option<Value>> {
127        Ok(None)
128    }
129
130    /// The name the agent's tools give `server`'s tool `tool`: prefixed with the server when
131    /// another server publishes the same name, or `None` when the agent is not given that
132    /// tool. The default is `tool` itself, for a set that renames nothing.
133    ///
134    /// # Errors
135    ///
136    /// The set's error when it cannot list the agent's tools.
137    async fn agent_tool_name(&self, _server: &str, tool: &str) -> adk_core::Result<Option<String>> {
138        Ok(Some(tool.to_string()))
139    }
140}
141
142#[async_trait]
143impl AppServers for McpServerManager {
144    async fn ui_bindings(&self, server: &str) -> Option<adk_core::Result<Vec<McpUiBinding>>> {
145        self.server_config(server).await.ok()?;
146        Some(self.server_ui_bindings(server).await)
147    }
148
149    async fn tool_visibility(
150        &self,
151        server: &str,
152    ) -> Option<adk_core::Result<Vec<(String, McpUiVisibility)>>> {
153        self.server_config(server).await.ok()?;
154        Some(self.server_tool_visibility(server).await)
155    }
156
157    async fn agent_tool_name(&self, server: &str, tool: &str) -> adk_core::Result<Option<String>> {
158        McpServerManager::agent_tool_name(self, server, tool).await
159    }
160
161    async fn read_resource(
162        &self,
163        server: &str,
164        uri: &str,
165    ) -> adk_core::Result<Vec<ResourceContents>> {
166        self.read_server_resource(server, uri).await
167    }
168}
169
170/// One MCP server's toolset: its name is the server's.
171#[async_trait]
172impl<S> AppServers for adk_tool::mcp::McpToolset<S>
173where
174    S: adk_tool::mcp::rmcp::service::Service<adk_tool::mcp::rmcp::RoleClient>
175        + Send
176        + Sync
177        + 'static,
178{
179    async fn ui_bindings(&self, server: &str) -> Option<adk_core::Result<Vec<McpUiBinding>>> {
180        if adk_core::Toolset::name(self) != server {
181            return None;
182        }
183        Some(adk_tool::mcp::McpToolset::ui_bindings(self).await)
184    }
185
186    async fn read_resource(
187        &self,
188        _server: &str,
189        uri: &str,
190    ) -> adk_core::Result<Vec<ResourceContents>> {
191        adk_tool::mcp::McpToolset::read_resource(self, uri).await
192    }
193
194    async fn tool_visibility(
195        &self,
196        server: &str,
197    ) -> Option<adk_core::Result<Vec<(String, McpUiVisibility)>>> {
198        if adk_core::Toolset::name(self) != server {
199            return None;
200        }
201        Some(adk_tool::mcp::McpToolset::tool_visibility(self).await)
202    }
203
204    async fn agent_tool_name(&self, server: &str, tool: &str) -> adk_core::Result<Option<String>> {
205        if adk_core::Toolset::name(self) != server {
206            return Ok(None);
207        }
208        let listing: Arc<dyn adk_core::ReadonlyContext> =
209            Arc::new(adk_tool::SimpleToolContext::new("mcp-apps"));
210        let tools = adk_core::Toolset::tools(self, listing).await?;
211        Ok(tools.iter().any(|known| known.name() == tool).then(|| tool.to_string()))
212    }
213
214    async fn tool_definition(&self, server: &str, tool: &str) -> adk_core::Result<Option<Value>> {
215        if adk_core::Toolset::name(self) != server {
216            return Ok(None);
217        }
218        let listing: Arc<dyn adk_core::ReadonlyContext> =
219            Arc::new(adk_tool::SimpleToolContext::new("mcp-apps"));
220        let tools = adk_core::Toolset::tools(self, listing).await?;
221        Ok(tools.iter().find(|known| known.name() == tool).map(|known| {
222            // The annotations the server declared, as the tool's effect carries them.
223            let read_only = matches!(known.effect(), adk_core::ToolEffect::ReadOnly);
224            json!({
225                "name": known.name(),
226                "description": known.description(),
227                "inputSchema": known.parameters_schema(),
228                "annotations": { "readOnlyHint": read_only },
229            })
230        }))
231    }
232}
233
234/// An app's page on the apps origin.
235struct Frame {
236    html: String,
237    policy: String,
238    /// The origin it is served on: the apps origin, or its server's own under it.
239    origin: String,
240    until: Instant,
241}
242
243/// When the home approves a call an app asks for without asking the person (spec 3.3 §6.1
244/// `genui-apps`): never, unless a deployment opts in. A drawn form's Send is always held;
245/// this is for apps only, and every approval it gives is recorded as
246/// `surface.app.call_auto_approved` with `initiator: "app"`.
247///
248/// # Example
249///
250/// ```rust
251/// use adk_surface::genui::{AppConsent, McpAppsHost};
252/// use serde_json::json;
253///
254/// let consent = AppConsent { read_only: true, ..AppConsent::default() };
255/// let definition = json!({ "name": "forecast", "annotations": { "readOnlyHint": true } });
256/// assert!(consent.allows("weather", "forecast", &definition));
257/// assert!(!AppConsent::default().allows("weather", "forecast", &definition), "off by default");
258/// // A standing grant holds only while the tool's definition is the one granted.
259/// let standing = AppConsent::default().standing("weather", "book", &json!({ "name": "book" }));
260/// assert!(standing.allows("weather", "book", &json!({ "name": "book" })));
261/// assert!(!standing.allows("weather", "book", &json!({ "name": "book", "description": "now pays too" })));
262/// ```
263#[derive(Debug, Clone, Default, PartialEq, Eq)]
264pub struct AppConsent {
265    /// Approve a call to a tool whose definition says `readOnlyHint: true` and not
266    /// `destructiveHint: true`.
267    pub read_only: bool,
268    /// Standing approvals: (server, tool, hash of the tool's definition) granted by the
269    /// person; a changed definition asks again.
270    pub standing: Vec<(String, String, String)>,
271}
272
273impl AppConsent {
274    /// The SHA-256 of a tool's definition, as standing grants key it.
275    pub fn definition_hash(definition: &Value) -> String {
276        use sha2::Digest;
277        let canonical = adk_core::tool_call_fingerprint("", definition);
278        sha2::Sha256::digest(canonical.as_bytes())
279            .iter()
280            .map(|byte| format!("{byte:02x}"))
281            .collect()
282    }
283
284    /// The same, with a standing approval of `server`'s tool `tool` as `definition` defines it.
285    #[must_use]
286    pub fn standing(mut self, server: &str, tool: &str, definition: &Value) -> Self {
287        self.standing.push((
288            server.to_string(),
289            tool.to_string(),
290            Self::definition_hash(definition),
291        ));
292        self
293    }
294
295    /// Whether a call to `server`'s tool `tool`, defined as `definition`, is approved without
296    /// the person, and by which rule.
297    pub fn allows(&self, server: &str, tool: &str, definition: &Value) -> bool {
298        self.rule(server, tool, definition).is_some()
299    }
300
301    fn rule(&self, server: &str, tool: &str, definition: &Value) -> Option<&'static str> {
302        let hash = Self::definition_hash(definition);
303        if self.standing.iter().any(|(s, t, h)| s == server && t == tool && *h == hash) {
304            return Some("app-consent:standing");
305        }
306        let annotations = definition.get("annotations");
307        let flag = |name: &str| annotations.and_then(|a| a.get(name)).and_then(Value::as_bool);
308        (self.read_only
309            && flag("readOnlyHint") == Some(true)
310            && flag("destructiveHint") != Some(true))
311        .then_some("app-consent:read-only")
312    }
313}
314
315/// The MCP Apps host (spec 3.3 §6.1 `genui-apps`). Mount its routes with
316/// [`web::genui::apps_router`](crate::web::genui::apps_router), serve
317/// [`sandbox_router`](Self::sandbox_router) on the apps origin, and wrap the home's API in
318/// [`refuse_apps_origin`](crate::web::genui::refuse_apps_origin).
319///
320/// # Example
321///
322/// ```rust,no_run
323/// use std::sync::Arc;
324/// use adk_surface::genui::McpAppsHost;
325///
326/// # fn example(manager: Arc<adk_tool::mcp::McpServerManager>) {
327/// let host = McpAppsHost::builder()
328///     .servers(manager)
329///     .apps_origin("http://127.0.0.1:41234")
330///     .home_origin("http://127.0.0.1:8080")
331///     .build();
332/// assert_eq!(host.apps_origin(), Some("http://127.0.0.1:41234"));
333/// # }
334/// ```
335#[derive(Clone)]
336pub struct McpAppsHost {
337    inner: Arc<Inner>,
338}
339
340struct Inner {
341    servers: Vec<Arc<dyn AppServers>>,
342    apps_origin: Option<String>,
343    /// Whether each server's apps are framed on an origin of their own under the apps origin.
344    per_server: bool,
345    home_origins: Vec<String>,
346    frames: Mutex<HashMap<String, Frame>>,
347    /// What each open app's frame was granted (`hostCapabilities.sandbox`), by session and call.
348    granted: Mutex<HashMap<String, Value>>,
349    /// What each app asked the host to keep for it (`ui/set-view-state`), by session and call.
350    view_states: Mutex<HashMap<String, Value>>,
351    /// When an app's call is approved without the person: never unless opted in.
352    consent: AppConsent,
353}
354
355impl std::fmt::Debug for McpAppsHost {
356    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
357        f.debug_struct("McpAppsHost")
358            .field("servers", &self.inner.servers.len())
359            .field("apps_origin", &self.inner.apps_origin)
360            .field("home_origins", &self.inner.home_origins)
361            .finish()
362    }
363}
364
365/// Builds an [`McpAppsHost`].
366#[derive(Default)]
367pub struct McpAppsHostBuilder {
368    servers: Vec<Arc<dyn AppServers>>,
369    apps_origin: Option<String>,
370    per_server: Option<bool>,
371    home_origins: Vec<String>,
372    consent: AppConsent,
373}
374
375impl McpAppsHostBuilder {
376    /// Shows the apps of the servers `servers` runs; may be called for several sets, which are
377    /// asked in order.
378    #[must_use]
379    pub fn servers(mut self, servers: Arc<dyn AppServers>) -> Self {
380        self.servers.push(servers);
381        self
382    }
383
384    /// Frames apps on `origin`: `http://127.0.0.1:<port>` of the second loopback listener, or
385    /// a remote home's `--apps-origin`. Without one, apps are their text result.
386    #[must_use]
387    pub fn apps_origin(mut self, origin: impl Into<String>) -> Self {
388        self.apps_origin = Some(origin.into().trim_end_matches('/').to_string());
389        self
390    }
391
392    /// Frames each server's apps on an origin of its own under the apps origin,
393    /// `<sha256(server)[..16]>.<apps host>`, so two servers' apps never share one (spec 3.3
394    /// §6.1 `genui-apps`). On by default when the apps origin's host is `localhost`, whose
395    /// subdomains every browser resolves to this computer; a remote apps origin needs wildcard
396    /// DNS and certificates first, and the home's page must name `*.<apps host>` in its
397    /// `frame-src` ([`web::home_with_apps_origin`](crate::web::home_with_apps_origin) does for
398    /// `localhost`).
399    #[must_use]
400    pub fn origin_per_server(mut self, per_server: bool) -> Self {
401        self.per_server = Some(per_server);
402        self
403    }
404
405    /// Approves some calls apps ask for without asking the person, by `consent` (off by
406    /// default): calls to read-only tools, or tools the person gave a standing approval whose
407    /// definition has not changed. A drawn form's Send is never affected.
408    #[must_use]
409    pub fn app_consent(mut self, consent: AppConsent) -> Self {
410        self.consent = consent;
411        self
412    }
413
414    /// An origin the home is served on: the only one that may frame apps, and one no app may
415    /// declare.
416    #[must_use]
417    pub fn home_origin(mut self, origin: impl Into<String>) -> Self {
418        self.home_origins.push(origin.into().trim_end_matches('/').to_string());
419        self
420    }
421
422    /// The host.
423    pub fn build(self) -> McpAppsHost {
424        let per_server = self.per_server.unwrap_or_else(|| {
425            self.apps_origin
426                .as_deref()
427                .and_then(origin_host)
428                .is_some_and(|host| host == "localhost")
429        });
430        McpAppsHost {
431            inner: Arc::new(Inner {
432                servers: self.servers,
433                apps_origin: self.apps_origin,
434                per_server,
435                home_origins: self.home_origins,
436                frames: Mutex::new(HashMap::new()),
437                granted: Mutex::new(HashMap::new()),
438                view_states: Mutex::new(HashMap::new()),
439                consent: self.consent,
440            }),
441        }
442    }
443}
444
445/// The app a session's tool call showed, as its events record it.
446pub(crate) struct ShownApp {
447    record: McpAppRecord,
448    args: Value,
449    response: Value,
450}
451
452impl McpAppsHost {
453    /// A builder.
454    pub fn builder() -> McpAppsHostBuilder {
455        McpAppsHostBuilder::default()
456    }
457
458    /// The origin apps are framed on, when there is one.
459    pub fn apps_origin(&self) -> Option<&str> {
460        self.inner.apps_origin.as_deref()
461    }
462
463    /// The origin `server`'s apps are framed on: its own under the apps origin when origins
464    /// are per server ([`McpAppsHostBuilder::origin_per_server`]), else the apps origin.
465    ///
466    /// # Example
467    ///
468    /// ```rust
469    /// use adk_surface::genui::McpAppsHost;
470    ///
471    /// let host = McpAppsHost::builder().apps_origin("http://localhost:41234").build();
472    /// let weather = host.server_origin("weather").unwrap();
473    /// assert!(weather.starts_with("http://") && weather.ends_with(".localhost:41234"));
474    /// assert_ne!(weather, host.server_origin("calendar").unwrap());
475    /// // An IP address has no subdomains: every app shares it.
476    /// let loopback = McpAppsHost::builder().apps_origin("http://127.0.0.1:41234").build();
477    /// assert_eq!(loopback.server_origin("weather").as_deref(), Some("http://127.0.0.1:41234"));
478    /// ```
479    pub fn server_origin(&self, server: &str) -> Option<String> {
480        let origin = self.inner.apps_origin.clone()?;
481        if !self.inner.per_server {
482            return Some(origin);
483        }
484        let (scheme, rest) = origin.split_once("://")?;
485        use sha2::Digest;
486        let digest = sha2::Sha256::digest(server.as_bytes());
487        let label: String = digest.iter().take(8).map(|byte| format!("{byte:02x}")).collect();
488        Some(format!("{scheme}://{label}.{rest}"))
489    }
490
491    /// The routes of the apps origin (spec 3.3 §6.1 `genui-apps`): `GET /app/{token}` serves a
492    /// checked app's page under its content security policy, sandboxed, framed only by the
493    /// home; nothing else is served. Serve it on its own listener, never beside the home.
494    pub fn sandbox_router(&self) -> Router {
495        Router::new().route("/app/{token}", get(frame)).with_state(self.clone())
496    }
497
498    /// The app `call_id` showed in `session`, from its events.
499    fn shown(events: &[Event], call_id: &str) -> Option<ShownApp> {
500        let mut args = Value::Null;
501        for event in events {
502            let Some(content) = &event.llm_response.content else {
503                continue;
504            };
505            for part in &content.parts {
506                match part {
507                    Part::FunctionCall { id: Some(id), args: called, .. } if id == call_id => {
508                        args = called.clone();
509                    }
510                    Part::FunctionResponse { function_response, id: Some(id), .. }
511                        if id == call_id =>
512                    {
513                        // A held call's placeholder answer carries no record; the answer of
514                        // the call once allowed follows under the same id.
515                        let Some(record) = record_of(event, call_id) else {
516                            continue;
517                        };
518                        return Some(ShownApp {
519                            record,
520                            args,
521                            response: function_response.response.clone(),
522                        });
523                    }
524                    _ => {}
525                }
526            }
527        }
528        None
529    }
530
531    async fn app(
532        &self,
533        engine: &SurfaceEngine,
534        caller: &Caller,
535        session: &str,
536        call_id: &str,
537    ) -> Result<ShownApp> {
538        let events = engine.app_transcript(caller, session).await?;
539        Self::shown(&events, call_id).ok_or_else(|| {
540            SurfaceError::not_found(format!("app '{call_id}' in session '{session}'"))
541        })
542    }
543
544    /// The bindings `server` publishes, from the first server set that runs it.
545    async fn bindings(&self, server: &str) -> adk_core::Result<Vec<McpUiBinding>> {
546        for servers in &self.inner.servers {
547            if let Some(bindings) = servers.ui_bindings(server).await {
548                return bindings;
549            }
550        }
551        Err(adk_core::AdkError::tool(format!("no MCP server named '{server}' runs on this home")))
552    }
553
554    async fn resource(&self, server: &str, uri: &str) -> adk_core::Result<Vec<ResourceContents>> {
555        for servers in &self.inner.servers {
556            if servers.ui_bindings(server).await.is_some() {
557                return servers.read_resource(server, uri).await;
558            }
559        }
560        Err(adk_core::AdkError::tool(format!("no MCP server named '{server}' runs on this home")))
561    }
562
563    /// The origin of the home's page that asked, from the request's `Host` and the apps
564    /// origin's scheme: a remote home's own origin, or the address a person opened a home
565    /// listening on every interface at.
566    fn page_origin(&self, host: Option<&str>) -> Option<String> {
567        let (scheme, _) = self.inner.apps_origin.as_deref()?.split_once("://")?;
568        let origin = format!("{scheme}://{}", host?.trim().to_ascii_lowercase());
569        sites::parse(&origin, false).filter(sites::Parsed::is_plain)?;
570        Some(origin)
571    }
572
573    /// Who may call `server`'s tool `tool`, and the name the agent knows it by when the model
574    /// and the app may both call it, from the first set that runs `server`; `None` when the
575    /// server does not publish it.
576    async fn app_tool(
577        &self,
578        server: &str,
579        tool: &str,
580    ) -> adk_core::Result<Option<(McpUiVisibility, Option<String>)>> {
581        for servers in &self.inner.servers {
582            let Some(listed) = servers.tool_visibility(server).await else {
583                continue;
584            };
585            let Some((_, visibility)) = listed?.into_iter().find(|(name, _)| name == tool) else {
586                return Ok(None);
587            };
588            let name = if visibility.model && visibility.app {
589                servers.agent_tool_name(server, tool).await?
590            } else {
591                None
592            };
593            return Ok(Some((visibility, name)));
594        }
595        Err(adk_core::AdkError::tool(format!("no MCP server named '{server}' runs on this home")))
596    }
597
598    /// The consent rule that approves a call to `server`'s tool `tool` without the person, if
599    /// any: read from the tool's definition, which the first set that runs `server` gives.
600    async fn consent_rule(&self, server: &str, tool: &str) -> Option<&'static str> {
601        let consent = &self.inner.consent;
602        if !consent.read_only && consent.standing.is_empty() {
603            return None;
604        }
605        for servers in &self.inner.servers {
606            if servers.ui_bindings(server).await.is_some() {
607                let definition = servers.tool_definition(server, tool).await.ok().flatten()?;
608                return consent.rule(server, tool, &definition);
609            }
610        }
611        None
612    }
613
614    /// The open decisions of the calls the app `call_id` asked for in `session`.
615    async fn waiting_calls(
616        engine: &SurfaceEngine,
617        caller: &Caller,
618        session: &str,
619        call_id: &str,
620    ) -> Result<Vec<DecisionCard>> {
621        let asked: HashSet<String> = engine
622            .thread(caller, session)
623            .await?
624            .into_iter()
625            .flat_map(|entry| entry.items)
626            .filter_map(|item| match item {
627                ThreadItem::DrawnSent { sent } if sent.surface_id == call_id => sent.decision_id,
628                _ => None,
629            })
630            .collect();
631        Ok(engine
632            .session_decisions(caller, session)
633            .await?
634            .into_iter()
635            .filter(|card| card.decided.is_none() && asked.contains(&card.id))
636            .collect())
637    }
638
639    /// Whether the agent held the requested call `requested` (`true`) or refused it, with the
640    /// thread's words for it, once its run took it; `None` when it has not within
641    /// [`OUTCOME_WAIT`].
642    async fn outcome(
643        engine: &SurfaceEngine,
644        caller: &Caller,
645        session: &str,
646        requested: &str,
647    ) -> Result<Option<(bool, String)>> {
648        let until = Instant::now() + OUTCOME_WAIT;
649        loop {
650            let sent = engine
651                .thread(caller, session)
652                .await?
653                .into_iter()
654                .flat_map(|entry| entry.items)
655                .find_map(|item| match item {
656                    ThreadItem::DrawnSent { sent } if sent.call_id == requested => Some(sent),
657                    _ => None,
658                });
659            if let Some(sent) = sent {
660                return Ok(Some((sent.held, sent.text)));
661            }
662            if Instant::now() >= until {
663                return Ok(None);
664            }
665            tokio::time::sleep(OUTCOME_POLL).await;
666        }
667    }
668
669    /// Opens the app `call_id` showed in `session` for `caller` (spec 3.3 §6.1 `genui-apps`):
670    /// framed when every check passes, blocked with its reason, or not shown on this surface.
671    /// `page_host` is the request's `Host`: the page that frames the app, which its policy
672    /// names beside the home's origins and no app may declare.
673    ///
674    /// # Errors
675    ///
676    /// `surface.not_found` when the session is not the caller's or holds no such app (S-I8).
677    pub(crate) async fn open(
678        &self,
679        engine: &SurfaceEngine,
680        caller: &Caller,
681        session: &str,
682        call_id: &str,
683        page_host: Option<&str>,
684    ) -> Result<AppOpen> {
685        let app = self.app(engine, caller, session, call_id).await?;
686        let result_text = result_text(&app.response);
687        let elsewhere = |text: &str| AppOpen::Elsewhere {
688            text: text.to_string(),
689            result_text: result_text.clone(),
690        };
691        // Phones never render apps: the apps origin is a loopback listener (decision 17).
692        let Some(origin) =
693            self.inner.apps_origin.clone().filter(|_| caller.surface == SurfaceKind::Web)
694        else {
695            return Ok(elsewhere(words::OPEN_THE_HOME_TO_SEE_THIS_APP));
696        };
697        let record = &app.record;
698        let mut home_origins = self.inner.home_origins.clone();
699        if let Some(page) = self.page_origin(page_host)
700            && !home_origins.contains(&page)
701        {
702            home_origins.push(page);
703        }
704        // Origins no app may declare or load from: the home's, the page's and the apps origin.
705        let refused: Vec<String> =
706            home_origins.iter().chain(&self.inner.apps_origin).cloned().collect();
707        let published = match self.bindings(&record.server).await {
708            Ok(bindings) => bindings,
709            Err(error) => {
710                tracing::warn!(app.server = %record.server, error = %error, "an app's server did not list its tools");
711                return Ok(elsewhere(words::APP_CANT_BE_OPENED));
712            }
713        };
714        if !published.iter().any(|binding| {
715            binding.tool == record.tool && binding.resource_uri == record.resource_uri
716        }) {
717            return Ok(elsewhere(words::APP_CANT_BE_OPENED));
718        }
719        let contents = match self.resource(&record.server, &record.resource_uri).await {
720            Ok(contents) => contents,
721            Err(error) => {
722                tracing::warn!(app.server = %record.server, error = %error, "an app's resource could not be read");
723                return Ok(elsewhere(words::APP_CANT_BE_OPENED));
724            }
725        };
726        let checked = McpAppResource::from_contents(&record.resource_uri, &contents)
727            .map_err(|error| (AppBlockReason::NotAnApp, error.message.clone()))
728            .and_then(|resource| {
729                let declared = sites::checked(&resource.csp, &refused)?;
730                let refused_hosts: Vec<String> = refused
731                    .iter()
732                    .filter_map(|origin| origin.split_once("://").map(|(_, rest)| rest))
733                    .map(|rest| rest.rsplit_once(':').map_or(rest, |(host, _)| host).to_string())
734                    .collect();
735                match scan::scan(&resource.html, &declared, &refused_hosts) {
736                    Some(refusal) => Err(refusal),
737                    None => Ok((resource, declared)),
738                }
739            });
740        let (resource, declared) = match checked {
741            Ok(passed) => passed,
742            Err((reason, detail)) => {
743                let text = match reason {
744                    AppBlockReason::ApprovalButtons => words::APP_BLOCKED_APPROVAL_BUTTONS,
745                    AppBlockReason::UndeclaredSites => words::APP_BLOCKED_UNDECLARED_SITES,
746                    AppBlockReason::ThisComputer => words::APP_BLOCKED_THIS_COMPUTER,
747                    AppBlockReason::NotAnApp => words::APP_BLOCKED_NOT_AN_APP,
748                };
749                engine
750                    .record(
751                        caller,
752                        SURFACE_AUDIT_APP_BLOCKED,
753                        json!({
754                            "sessionId": session,
755                            "callId": call_id,
756                            "server": record.server,
757                            "tool": record.tool,
758                            "resourceUri": record.resource_uri,
759                            "reason": reason,
760                            "detail": detail,
761                        }),
762                    )
763                    .await?;
764                return Ok(AppOpen::Blocked { reason, text: text.to_string(), detail });
765            }
766        };
767        let token = uuid::Uuid::new_v4().simple().to_string();
768        // Each server's apps on an origin of their own, when origins are per server.
769        let origin = self.server_origin(&record.server).unwrap_or(origin);
770        let frame = Frame {
771            html: resource.html.clone(),
772            policy: declared.policy(&home_origins),
773            origin: origin.clone(),
774            until: Instant::now() + FRAME_LIFETIME,
775        };
776        // What the frame is granted, reported to the app at ui/initialize: the sites that
777        // passed, and no permission (camera, microphone, geolocation, clipboard) at all.
778        {
779            let mut granted =
780                self.inner.granted.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
781            if granted.len() > MAX_GRANTS_KEPT {
782                granted.clear();
783            }
784            granted.insert(
785                format!("{session}/{call_id}"),
786                json!({ "permissions": {}, "csp": declared.granted() }),
787            );
788        }
789        {
790            let mut frames =
791                self.inner.frames.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
792            frames.retain(|_, frame| frame.until > Instant::now());
793            frames.insert(token.clone(), frame);
794        }
795        Ok(AppOpen::Shown {
796            frame_url: format!("{origin}/app/{token}"),
797            frame_origin: origin,
798            max_height: MAX_HEIGHT,
799            prefers_border: resource.prefers_border.unwrap_or(true),
800            tool_input: app.args.clone(),
801            tool_result: call_tool_result(&app.response),
802            refused_permissions: resource.permissions,
803        })
804    }
805
806    /// Answers a request the app `call_id` in `session` made (spec 3.3 §6.1 `genui-apps`).
807    ///
808    /// # Errors
809    ///
810    /// `surface.not_found` when the session is not the caller's or holds no such app (S-I8);
811    /// the source's error when a held call could not be asked for.
812    pub(crate) async fn request(
813        &self,
814        engine: &SurfaceEngine,
815        caller: &Caller,
816        session: &str,
817        call_id: &str,
818        request: AppRequest,
819    ) -> Result<AppAnswer> {
820        let app = self.app(engine, caller, session, call_id).await?;
821        let label = app_name(&app.record.server);
822        let ok = |result: Value| AppAnswer { result: Some(result), error: None, prompt: None };
823        let error = |code: i64, message: String, prompt: Option<AppPrompt>| AppAnswer {
824            result: None,
825            error: Some(AppError { code, message }),
826            prompt,
827        };
828        match request.method.as_str() {
829            "ui/initialize" => Ok(ok(json!({
830                "protocolVersion": MCP_APPS_VERSION,
831                "hostInfo": { "name": "adk-rust", "version": env!("CARGO_PKG_VERSION") },
832                "hostCapabilities": {
833                    "openLinks": {},
834                    "downloadFile": {},
835                    "serverTools": {},
836                    "logging": {},
837                    // What the frame was actually granted; never same-origin storage.
838                    "sandbox": self
839                        .inner
840                        .granted
841                        .lock()
842                        .unwrap_or_else(std::sync::PoisonError::into_inner)
843                        .get(&format!("{session}/{call_id}"))
844                        .cloned()
845                        .unwrap_or_else(|| json!({ "permissions": {}, "csp": {} })),
846                },
847                "hostContext": {
848                    "displayMode": "inline",
849                    "availableDisplayModes": ["inline"],
850                    "platform": "web",
851                    "containerDimensions": { "maxHeight": MAX_HEIGHT },
852                    // What the app asked the host to keep, for an app opened again.
853                    "viewState": self
854                        .inner
855                        .view_states
856                        .lock()
857                        .unwrap_or_else(std::sync::PoisonError::into_inner)
858                        .get(&format!("{session}/{call_id}"))
859                        .cloned()
860                        .unwrap_or(Value::Null),
861                },
862            }))),
863            "ping" => Ok(ok(json!({}))),
864            // The home frames apps inline only: a request for another mode gets inline back,
865            // and never without the person's gesture.
866            "ui/request-display-mode" => Ok(ok(json!({ "mode": "inline" }))),
867            // The host keeps an app's view state for the next time it opens (MCP Apps draft
868            // `ui/set-view-state`), at most `MAX_VIEW_STATE_BYTES`.
869            "ui/set-view-state" => {
870                let state = request.params.get("state").cloned().unwrap_or(Value::Null);
871                if state.to_string().len() > MAX_VIEW_STATE_BYTES {
872                    return Ok(error(
873                        INVALID_PARAMS,
874                        format!("a view state is at most {MAX_VIEW_STATE_BYTES} bytes"),
875                        None,
876                    ));
877                }
878                let mut states = self
879                    .inner
880                    .view_states
881                    .lock()
882                    .unwrap_or_else(std::sync::PoisonError::into_inner);
883                if states.len() > MAX_GRANTS_KEPT {
884                    states.clear();
885                }
886                states.insert(format!("{session}/{call_id}"), state);
887                Ok(ok(json!({})))
888            }
889            "tools/call" => {
890                // Only a tool's name, so nothing else the app sends reaches the home's words
891                // or the audit trail in its place.
892                let Some(tool) = request
893                    .params
894                    .get("name")
895                    .and_then(Value::as_str)
896                    .filter(|name| is_tool_name(name))
897                else {
898                    return Ok(error(
899                        INVALID_PARAMS,
900                        "tools/call needs the name of one of its server's tools".into(),
901                        None,
902                    ));
903                };
904                let args = request.params.get("arguments").cloned().unwrap_or_else(|| json!({}));
905                let server = app.record.server.as_str();
906                let found = match self.app_tool(server, tool).await {
907                    Ok(found) => found,
908                    Err(failure) => {
909                        tracing::warn!(app.server = %server, error = %failure, "an app's server did not list its tools");
910                        return Ok(error(REFUSED, words::APP_SERVER_DIDNT_ANSWER.into(), None));
911                    }
912                };
913                let record = |reason: &str, extra: Value| {
914                    let mut fields = json!({
915                        "sessionId": session,
916                        "callId": call_id,
917                        "server": server,
918                        "tool": tool,
919                        "via": "app",
920                        "reason": reason,
921                    });
922                    if let (Some(fields), Value::Object(extra)) = (fields.as_object_mut(), extra) {
923                        fields.extend(extra);
924                    }
925                    fields
926                };
927                let refused =
928                    |text: String| error(REFUSED, text.clone(), Some(AppPrompt::Notice { text }));
929                let tool_name = match found {
930                    Some((visibility, Some(name))) if visibility.model && visibility.app => name,
931                    Some((visibility, _)) if visibility.app && !visibility.model => {
932                        engine
933                            .record(
934                                caller,
935                                SURFACE_AUDIT_APP_CALL_REFUSED,
936                                record("appOnly", json!({})),
937                            )
938                            .await?;
939                        return Ok(refused(words::APP_NEEDS_A_TOOL.to_string()));
940                    }
941                    // A model-only tool, one the app's own server does not publish, or one the
942                    // agent is not given.
943                    _ => {
944                        engine
945                            .record(
946                                caller,
947                                SURFACE_AUDIT_APP_CALL_REFUSED,
948                                record("notTheApps", json!({})),
949                            )
950                            .await?;
951                        return Ok(refused(words::app_cant_use(tool)));
952                    }
953                };
954                // The same call again, as an app asks on every load, is the decision already
955                // waiting; an app with enough waiting asks for no more.
956                let waiting = Self::waiting_calls(engine, caller, session, call_id).await?;
957                if waiting.iter().any(|card| card.call.tool == tool_name && card.call.args == args)
958                {
959                    return Ok(ok(sent_text(words::APP_CALL_WAITS_FOR_YOU)));
960                }
961                if waiting.len() >= MAX_WAITING {
962                    engine
963                        .record(
964                            caller,
965                            SURFACE_AUDIT_APP_CALL_REFUSED,
966                            record("tooManyWaiting", json!({})),
967                        )
968                        .await?;
969                    return Ok(refused(words::app_asked_enough(MAX_WAITING)));
970                }
971                let (called_tool, called_args) = (tool_name.clone(), args.clone());
972                let call = RequestedCall::new(
973                    tool_name,
974                    args,
975                    caller.subject.clone(),
976                    RequestedVia {
977                        kind: RequestedViaKind::App,
978                        surface_id: call_id.to_string(),
979                        version: 1,
980                        action_id: tool.to_string(),
981                        digest: None,
982                    },
983                );
984                let requested = call.function_call_id.clone();
985                let fingerprint = adk_core::ToolConfirmationRequest::new(
986                    call.tool_name.clone(),
987                    call.args.clone(),
988                )
989                .fingerprint();
990                let asked = json!({ "requestedCallId": requested, "fingerprint": fingerprint });
991                engine
992                    .record(caller, SURFACE_AUDIT_APP_CALL_ASKED, record("asked", asked.clone()))
993                    .await?;
994                if let Err(failure) = engine.ask_for_app_call(caller, session, call, &label).await {
995                    let reason =
996                        json!({ "requestedCallId": requested, "detail": failure.to_string() });
997                    engine
998                        .record(caller, SURFACE_AUDIT_APP_CALL_REFUSED, record("notAsked", reason))
999                        .await?;
1000                    return Err(failure);
1001                }
1002                // Answered for what the agent did with the call, never before it did.
1003                match Self::outcome(engine, caller, session, &requested).await? {
1004                    Some((true, _)) => {
1005                        engine
1006                            .record(caller, SURFACE_AUDIT_APP_CALL_HELD, record("held", asked))
1007                            .await?;
1008                        // Opt-in consent: a call the policy allows is approved now, recorded
1009                        // with the rule and `initiator: "app"`; the rest waits for the person.
1010                        if let Some(rule) = self.consent_rule(server, tool).await {
1011                            let card = Self::waiting_calls(engine, caller, session, call_id)
1012                                .await?
1013                                .into_iter()
1014                                .find(|card| {
1015                                    card.call.tool == called_tool && card.call.args == called_args
1016                                });
1017                            if let Some(card) = card {
1018                                engine
1019                                    .approve_by_policy(
1020                                        caller,
1021                                        &card.id,
1022                                        card.version,
1023                                        rule,
1024                                        json!({ "server": server, "tool": tool, "callId": call_id }),
1025                                    )
1026                                    .await?;
1027                                return Ok(ok(sent_text(words::APP_CALL_SENT)));
1028                            }
1029                        }
1030                        Ok(ok(sent_text(words::APP_CALL_WAITS_FOR_YOU)))
1031                    }
1032                    Some((false, text)) => {
1033                        let reason = json!({ "requestedCallId": requested, "detail": text });
1034                        engine
1035                            .record(
1036                                caller,
1037                                SURFACE_AUDIT_APP_CALL_REFUSED,
1038                                record("byTheAgent", reason),
1039                            )
1040                            .await?;
1041                        Ok(error(REFUSED, text, None))
1042                    }
1043                    None => Ok(ok(sent_text(words::APP_CALL_SENT))),
1044                }
1045            }
1046            "ui/message" => {
1047                let message = message_text(&request.params);
1048                if message.trim().is_empty() {
1049                    return Ok(error(INVALID_PARAMS, "ui/message needs text content".into(), None));
1050                }
1051                let message: String = message.chars().take(MAX_MESSAGE_CHARS).collect();
1052                Ok(AppAnswer {
1053                    result: Some(json!({})),
1054                    error: None,
1055                    prompt: Some(AppPrompt::Message {
1056                        text: words::app_wants_to_send(&message),
1057                        message,
1058                        send_label: words::SEND_IT.to_string(),
1059                        dismiss_label: words::NOT_NOW.to_string(),
1060                        note: words::MARKED_AS_SUGGESTED_BY_THE_APP.to_string(),
1061                    }),
1062                })
1063            }
1064            "ui/open-link" => {
1065                let url = request.params.get("url").and_then(Value::as_str).unwrap_or_default();
1066                let parsed = sites::parse(url, true).filter(|parsed| {
1067                    parsed.is_plain() && (url.starts_with("https://") || url.starts_with("http://"))
1068                });
1069                match parsed {
1070                    Some(parsed) if sites::is_this_computer(parsed.host()) => Ok(error(
1071                        REFUSED,
1072                        "ui/open-link opens sites on the web, never this computer or its network"
1073                            .into(),
1074                        None,
1075                    )),
1076                    Some(_) => Ok(AppAnswer {
1077                        result: Some(json!({})),
1078                        error: None,
1079                        prompt: Some(AppPrompt::Link {
1080                            text: words::open_site(&link_host(url)),
1081                            url: url.to_string(),
1082                            open_label: words::OPEN.to_string(),
1083                            dismiss_label: words::CANCEL.to_string(),
1084                        }),
1085                    }),
1086                    None => Ok(error(
1087                        INVALID_PARAMS,
1088                        "ui/open-link opens http and https links only".into(),
1089                        None,
1090                    )),
1091                }
1092            }
1093            "ui/download-file" => Ok(match download(&request.params, &label) {
1094                Ok(prompt) => {
1095                    AppAnswer { result: Some(json!({})), error: None, prompt: Some(prompt) }
1096                }
1097                Err(why) => error(INVALID_PARAMS, why, None),
1098            }),
1099            "ui/update-model-context" => {
1100                // Logged, never forwarded: an app does not steer the model (decision 15).
1101                tracing::info!(
1102                    app.server = %app.record.server,
1103                    app.call_id = %call_id,
1104                    context.bytes = request.params.to_string().len(),
1105                    "an app's model context update was logged and not forwarded"
1106                );
1107                Ok(ok(json!({})))
1108            }
1109            other => Ok(error(METHOD_NOT_FOUND, format!("{other} is not supported here"), None)),
1110        }
1111    }
1112
1113    /// Sends `message`, which the app `call_id` suggested, as `caller`'s message in `session`,
1114    /// inside an untrusted-content block labelled as the app's suggestion (spec 3.3 §6.1
1115    /// `genui-apps`). It never answers a decision: it is the session's next message.
1116    ///
1117    /// # Errors
1118    ///
1119    /// `surface.not_found` when the session is not the caller's or holds no such app;
1120    /// `surface.invalid` for an empty or overlong message; the engine's error for the send.
1121    pub(crate) async fn send_message(
1122        &self,
1123        engine: &SurfaceEngine,
1124        caller: &Caller,
1125        session: &str,
1126        call_id: &str,
1127        message: &str,
1128    ) -> Result<CommandOutcome> {
1129        let app = self.app(engine, caller, session, call_id).await?;
1130        if message.trim().is_empty() || message.chars().count() > MAX_MESSAGE_CHARS {
1131            return Err(SurfaceError::Invalid(format!(
1132                "a suggested message has 1 to {MAX_MESSAGE_CHARS} characters"
1133            )));
1134        }
1135        let label = app_name(&app.record.server);
1136        let suggested = words::suggested_by_the_app(&label);
1137        let text = adk_harness::web::untrusted_block(
1138            "mcp-app",
1139            &[("app", app.record.server.as_str()), ("label", suggested.as_str())],
1140            message,
1141        );
1142        engine
1143            .record(
1144                caller,
1145                SURFACE_AUDIT_APP_MESSAGE_SENT,
1146                json!({ "sessionId": session, "callId": call_id, "server": app.record.server }),
1147            )
1148            .await?;
1149        engine
1150            .execute(
1151                caller,
1152                Command::Send { session_id: session.to_string(), text, images: Vec::new() },
1153            )
1154            .await
1155    }
1156}
1157
1158/// `GET /app/{token}` on the apps origin.
1159async fn frame(
1160    State(host): State<McpAppsHost>,
1161    Path(token): Path<String>,
1162    headers: axum::http::HeaderMap,
1163) -> Response {
1164    let asked_host = headers
1165        .get(header::HOST)
1166        .and_then(|value| value.to_str().ok())
1167        .map(|value| value.trim().to_ascii_lowercase());
1168    let page = {
1169        let frames = host.inner.frames.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
1170        frames
1171            .get(&token)
1172            .filter(|frame| frame.until > Instant::now())
1173            // Served only on its own server's origin, never another server's.
1174            .filter(|frame| {
1175                asked_host.is_none()
1176                    || frame.origin.split_once("://").map(|(_, rest)| rest.to_ascii_lowercase())
1177                        == asked_host
1178            })
1179            .map(|frame| (frame.html.clone(), frame.policy.clone()))
1180    };
1181    let Some((html, policy)) = page else {
1182        return StatusCode::NOT_FOUND.into_response();
1183    };
1184    // Never served without its policy.
1185    let Ok(policy) = HeaderValue::from_str(&policy) else {
1186        tracing::warn!(
1187            "an app's content security policy is not a header value; its page was not served"
1188        );
1189        return StatusCode::INTERNAL_SERVER_ERROR.into_response();
1190    };
1191    let mut response = html.into_response();
1192    let headers = response.headers_mut();
1193    headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/html; charset=utf-8"));
1194    headers.insert(header::CONTENT_SECURITY_POLICY, policy);
1195    headers.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
1196    headers.insert(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer"));
1197    headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
1198    headers.insert(
1199        "permissions-policy",
1200        HeaderValue::from_static("camera=(), microphone=(), geolocation=(), display-capture=()"),
1201    );
1202    headers.insert("cross-origin-resource-policy", HeaderValue::from_static("cross-origin"));
1203    response
1204}
1205
1206/// The host of `origin`, `scheme://host[:port]`, lowercased.
1207fn origin_host(origin: &str) -> Option<String> {
1208    let (_, rest) = origin.split_once("://")?;
1209    let host = rest.split('/').next()?;
1210    let host = host.rsplit_once(':').map_or(host, |(host, port)| {
1211        if port.bytes().all(|byte| byte.is_ascii_digit()) { host } else { rest }
1212    });
1213    Some(host.to_ascii_lowercase())
1214}
1215
1216/// The largest file an app may offer to save (`ui/download-file`).
1217const MAX_DOWNLOAD_BYTES: usize = 5 * 1024 * 1024;
1218
1219/// Extensions a saved file may not have: ones that run, or that a browser opens as a page.
1220const UNSAFE_EXTENSIONS: &[&str] = &[
1221    "exe", "msi", "bat", "cmd", "com", "scr", "ps1", "vbs", "js", "mjs", "jar", "sh", "app", "dmg",
1222    "pkg", "deb", "rpm", "html", "htm", "xhtml", "svg", "mht", "url", "lnk", "desktop",
1223];
1224
1225/// `ui/download-file`'s first embedded resource as a host prompt the person answers (spec
1226/// 3.3 §6.1 `genui-apps`): its name sanitized, its size capped, a link to fetch or a file
1227/// that runs refused.
1228fn download(params: &Value, app: &str) -> std::result::Result<AppPrompt, String> {
1229    let item = params
1230        .get("contents")
1231        .and_then(Value::as_array)
1232        .and_then(|contents| contents.first())
1233        .ok_or("ui/download-file needs contents: one embedded resource")?;
1234    if item.get("type").and_then(Value::as_str) != Some("resource") {
1235        return Err("ui/download-file saves an embedded resource; this home fetches no link".into());
1236    }
1237    let resource = item.get("resource").ok_or("an embedded resource needs its resource")?;
1238    let uri = resource.get("uri").and_then(Value::as_str).unwrap_or_default();
1239    let raw = uri.rsplit(['/', '\\', ':']).next().unwrap_or_default();
1240    let name: String = raw
1241        .chars()
1242        .filter(|c| !c.is_control() && !"<>:\"/\\|?*".contains(*c))
1243        .take(100)
1244        .collect::<String>()
1245        .trim_matches(['.', ' '])
1246        .to_string();
1247    let name = if name.is_empty() { "download".to_string() } else { name };
1248    let extension = name.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase());
1249    if extension.as_deref().is_some_and(|ext| UNSAFE_EXTENSIONS.contains(&ext)) {
1250        return Err(format!("this home does not save .{} files", extension.unwrap_or_default()));
1251    }
1252    let mime_type = resource
1253        .get("mimeType")
1254        .and_then(Value::as_str)
1255        .filter(|mime| {
1256            !mime.contains("html") && !mime.contains("svg") && !mime.contains("javascript")
1257        })
1258        .unwrap_or("application/octet-stream")
1259        .to_string();
1260    let (text, blob) = (
1261        resource.get("text").and_then(Value::as_str),
1262        resource.get("blob").and_then(Value::as_str),
1263    );
1264    let size = match (text, blob) {
1265        (Some(text), _) => text.len(),
1266        (None, Some(blob)) => blob.len() / 4 * 3,
1267        (None, None) => return Err("an embedded resource needs text or blob".into()),
1268    };
1269    if size > MAX_DOWNLOAD_BYTES {
1270        return Err(format!("this home saves files up to {} MB", MAX_DOWNLOAD_BYTES / 1024 / 1024));
1271    }
1272    Ok(AppPrompt::Download {
1273        text: words::app_wants_to_save(app, &name, size),
1274        name,
1275        mime_type,
1276        text_content: text.map(str::to_string),
1277        blob: if text.is_none() { blob.map(str::to_string) } else { None },
1278        save_label: words::SAVE.to_string(),
1279        dismiss_label: words::CANCEL.to_string(),
1280    })
1281}
1282
1283/// Whether `name` can be an MCP tool's name: 1 to 128 letters, digits, `_`, `-`, `.` and `/`.
1284fn is_tool_name(name: &str) -> bool {
1285    (1..=128).contains(&name.len())
1286        && name
1287            .bytes()
1288            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b'/'))
1289}
1290
1291/// The answer to an app's `tools/call` that ran nothing: `text` for the app.
1292fn sent_text(text: &str) -> Value {
1293    json!({ "content": [{ "type": "text", "text": text }], "isError": false })
1294}
1295
1296/// The app record `event` carries for `call_id`.
1297fn record_of(event: &Event, call_id: &str) -> Option<McpAppRecord> {
1298    let record = event.actions.state_delta.get(MCP_APP_STATE_KEY)?;
1299    let record: McpAppRecord = serde_json::from_value(record.clone()).ok()?;
1300    (record.call_id == call_id).then_some(record)
1301}
1302
1303/// The text of an MCP tool's result as `McpToolset` records it: `{"output": ...}`.
1304fn result_text(response: &Value) -> String {
1305    let output = response.get("response").unwrap_or(response);
1306    if let Some(text) = output.get("text").and_then(Value::as_array) {
1307        return text.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("\n");
1308    }
1309    match output.get("output") {
1310        Some(Value::String(text)) => text.clone(),
1311        Some(other) => other.to_string(),
1312        None => String::new(),
1313    }
1314}
1315
1316/// The MCP `CallToolResult` an app's `ui/notifications/tool-result` carries.
1317fn call_tool_result(response: &Value) -> Value {
1318    let output = response.get("response").unwrap_or(response);
1319    let mut result = json!({
1320        "content": [{ "type": "text", "text": result_text(response) }],
1321        "isError": false,
1322    });
1323    if let Some(structured) = output.get("output").filter(|output| output.is_object()) {
1324        result["structuredContent"] = structured.clone();
1325    }
1326    result
1327}
1328
1329/// The text of a `ui/message`: its content's text blocks.
1330fn message_text(params: &Value) -> String {
1331    let content = params.get("content").unwrap_or(params);
1332    let blocks: Vec<&Value> = match content {
1333        Value::Array(blocks) => blocks.iter().collect(),
1334        other => vec![other],
1335    };
1336    blocks
1337        .iter()
1338        .filter_map(|block| match block {
1339            Value::String(text) => Some(text.as_str()),
1340            block => block.get("text").and_then(Value::as_str),
1341        })
1342        .collect::<Vec<_>>()
1343        .join("\n")
1344}
1345
1346/// The host a link opens, without `www.`, as "Open example.com?" names it.
1347fn link_host(url: &str) -> String {
1348    let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
1349    let authority = &rest[..rest.find(['/', '?', '#']).unwrap_or(rest.len())];
1350    authority.trim_start_matches("www.").to_string()
1351}
1352
1353/// The thread item of `event`'s response to `call_id` when an MCP server's tool with an app
1354/// made it (spec 3.3 §6.1 `genui-apps`): the event carries the tool's own record for that
1355/// call. A same-named tool without it is an ordinary result.
1356pub(crate) fn project(
1357    projector: &Projector,
1358    event: &Event,
1359    response: &Value,
1360    call_id: Option<&String>,
1361) -> Option<ThreadItem> {
1362    let record = record_of(event, call_id?)?;
1363    let label = app_name(&record.server);
1364    Some(ThreadItem::App {
1365        app: Box::new(AppView {
1366            call_id: record.call_id.clone(),
1367            server: record.server.clone(),
1368            app_name: label.clone(),
1369            tool: record.tool.clone(),
1370            agent: projector.agent(&event.author),
1371            at: event.timestamp,
1372            header_text: words::app_from(&label),
1373            result_text: result_text(response),
1374            elsewhere_text: words::OPEN_THE_HOME_TO_SEE_THIS_APP.to_string(),
1375            terminal_text: words::app_in_the_terminal(&label),
1376        }),
1377    })
1378}
1379
1380#[cfg(test)]
1381mod tests {
1382    use super::*;
1383
1384    #[test]
1385    fn a_suggested_message_reads_its_text_blocks() {
1386        assert_eq!(
1387            message_text(
1388                &json!({ "role": "user", "content": [{ "type": "text", "text": "Approved" }] })
1389            ),
1390            "Approved"
1391        );
1392        assert_eq!(message_text(&json!({ "content": { "type": "text", "text": "hi" } })), "hi");
1393    }
1394
1395    #[tokio::test]
1396    async fn a_page_whose_policy_cannot_be_sent_is_not_served() {
1397        use axum::body::Body;
1398        use axum::http::Request;
1399        use tower::ServiceExt as _;
1400
1401        let host = McpAppsHost::builder().apps_origin("http://127.0.0.1:41234").build();
1402        host.inner.frames.lock().unwrap().insert(
1403            "token".into(),
1404            Frame {
1405                html: "<p>Nairobi</p>".into(),
1406                policy: "default-src 'none'; connect-src https://[a.b\u{1}]".into(),
1407                origin: "http://127.0.0.1:41234".into(),
1408                until: Instant::now() + FRAME_LIFETIME,
1409            },
1410        );
1411        let response = host
1412            .sandbox_router()
1413            .oneshot(Request::builder().uri("/app/token").body(Body::empty()).unwrap())
1414            .await
1415            .unwrap();
1416        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
1417        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
1418        assert!(!String::from_utf8_lossy(&body).contains("Nairobi"));
1419    }
1420
1421    #[tokio::test]
1422    async fn each_server_has_its_own_origin_and_a_frame_is_served_only_on_its_own() {
1423        use axum::body::Body;
1424        use axum::http::Request;
1425        use tower::ServiceExt as _;
1426
1427        let host = McpAppsHost::builder().apps_origin("http://localhost:41234").build();
1428        let weather = host.server_origin("weather").unwrap();
1429        let calendar = host.server_origin("calendar").unwrap();
1430        assert_ne!(weather, calendar);
1431        assert_eq!(weather, host.server_origin("weather").unwrap(), "stable");
1432        host.inner.frames.lock().unwrap().insert(
1433            "token".into(),
1434            Frame {
1435                html: "<p>Nairobi</p>".into(),
1436                policy: "default-src 'none'".into(),
1437                origin: weather.clone(),
1438                until: Instant::now() + FRAME_LIFETIME,
1439            },
1440        );
1441        let at = |origin: &str| {
1442            let host_header = origin.split_once("://").unwrap().1.to_string();
1443            Request::builder()
1444                .uri("/app/token")
1445                .header("host", host_header)
1446                .body(Body::empty())
1447                .unwrap()
1448        };
1449        let served = host.sandbox_router().oneshot(at(&weather)).await.unwrap();
1450        assert_eq!(served.status(), StatusCode::OK);
1451        let elsewhere = host.sandbox_router().oneshot(at(&calendar)).await.unwrap();
1452        assert_eq!(elsewhere.status(), StatusCode::NOT_FOUND, "never on another server's origin");
1453        // Per server only where subdomains resolve, unless asked for.
1454        let remote = McpAppsHost::builder().apps_origin("https://apps.example.net").build();
1455        assert_eq!(remote.server_origin("weather").as_deref(), Some("https://apps.example.net"));
1456        let opted = McpAppsHost::builder()
1457            .apps_origin("https://apps.example.net")
1458            .origin_per_server(true)
1459            .build();
1460        assert!(opted.server_origin("weather").unwrap().ends_with(".apps.example.net"));
1461    }
1462
1463    #[test]
1464    fn a_file_an_app_offers_is_a_prompt_with_a_safe_name_and_size() {
1465        let offered = |name: &str, mime: &str, text: &str| {
1466            download(
1467                &json!({ "contents": [{ "type": "resource",
1468                    "resource": { "uri": format!("file:///tmp/{name}"), "mimeType": mime, "text": text } }] }),
1469                "Weather",
1470            )
1471        };
1472        match offered("forecast.csv", "text/csv", "day,rain\nmon,4").unwrap() {
1473            AppPrompt::Download { text, name, mime_type, text_content, .. } => {
1474                assert_eq!(name, "forecast.csv");
1475                assert_eq!(mime_type, "text/csv");
1476                assert_eq!(text, "The Weather app wants to save forecast.csv (14 bytes)");
1477                assert_eq!(text_content.as_deref(), Some("day,rain\nmon,4"));
1478            }
1479            other => panic!("{other:?}"),
1480        }
1481        // A page or a program is never saved; a link is never fetched; a huge file is refused.
1482        assert!(offered("report.html", "text/html", "<p>").is_err());
1483        assert!(offered("setup.exe", "application/octet-stream", "MZ").is_err());
1484        assert!(download(&json!({ "contents": [{ "type": "resource_link", "uri": "https://x.test/a.csv" }] }), "W").is_err());
1485        let huge = "x".repeat(MAX_DOWNLOAD_BYTES + 1);
1486        assert!(offered("big.txt", "text/plain", &huge).is_err());
1487        // A name made of path tricks keeps only its last part.
1488        match offered("..%2F..%2Fpasswd", "text/plain", "x").unwrap() {
1489            AppPrompt::Download { name, .. } => {
1490                assert!(!name.contains('/') && !name.starts_with('.'))
1491            }
1492            other => panic!("{other:?}"),
1493        }
1494    }
1495
1496    #[test]
1497    fn the_pages_own_origin_takes_the_apps_origins_scheme() {
1498        let remote = McpAppsHost::builder().apps_origin("https://apps.example.net").build();
1499        assert_eq!(
1500            remote.page_origin(Some("home.example.net")),
1501            Some("https://home.example.net".to_string())
1502        );
1503        let local = McpAppsHost::builder().apps_origin("http://127.0.0.1:41234").build();
1504        assert_eq!(
1505            local.page_origin(Some("127.0.0.1:8080")),
1506            Some("http://127.0.0.1:8080".to_string())
1507        );
1508        for host in [
1509            None,
1510            Some(""),
1511            Some("a.example; frame-ancestors *"),
1512            Some("a b"),
1513            Some("*.example.net"),
1514        ] {
1515            assert_eq!(local.page_origin(host), None, "{host:?}");
1516        }
1517        assert!(is_tool_name("set_rain_alert") && is_tool_name("weather__set-alert.v2"));
1518        assert!(!is_tool_name("set_alert. You said yes") && !is_tool_name(&"a".repeat(129)));
1519    }
1520
1521    #[test]
1522    fn a_tools_text_result_is_what_every_surface_shows() {
1523        assert_eq!(result_text(&json!({ "output": "Nairobi: 24°" })), "Nairobi: 24°");
1524        assert_eq!(
1525            call_tool_result(&json!({ "output": { "temp": 24 }, "text": ["24°"] })),
1526            json!({
1527                "content": [{ "type": "text", "text": "24°" }],
1528                "isError": false,
1529                "structuredContent": { "temp": 24 },
1530            })
1531        );
1532    }
1533}