Skip to main content

adk_surface/web/
genui.rs

1//! The web home's agent-drawn UI routes (spec 3.3 §6.1 `genui`, §7.4 rule 5).
2//!
3//! | Route (under `/api`) | Answer |
4//! |---|---|
5//! | `GET /surface/genui/capabilities` | [`GenuiCapabilities`]: what this home claims of A2UI, AG-UI and MCP Apps, and the catalogs it renders, which the developer panel's Protocols tab shows |
6//! | `GET /surface/genui/catalogs?version=1.0` | [`CatalogDocuments`]: every catalog this home renders, as documents of that A2UI version (`1.0`, the default, or `v0.9.1`) |
7//! | `GET /surface/genui/sessions/{session}/forms` | [`FormsResponse`]: the state of each form sent in the session, from its decision and its call's result |
8//! | `GET /surface/genui/sessions/{session}/apps/{call}` | [`AppOpen`]: an app from an MCP server, framed, blocked, or not shown here (`genui-apps`) |
9//! | `POST /surface/genui/sessions/{session}/apps/{call}/requests` | [`AppRequest`] → [`AppAnswer`]: what the app asked the home, which never approves anything (`genui-apps`) |
10//! | `POST /surface/genui/sessions/{session}/apps/{call}/message` | [`AppMessageRequest`] → `CommandOutcome`: the person pressed **Send it** on what the app suggested (`genui-apps`) |
11//!
12//! A drawn form is sent with `POST /surface/commands` and a `submitDrawn` command. The routes
13//! are mounted with `genui::router` by a host built with `genui`; the page probes them and hides
14//! what a server built without `genui` lacks. Their types are in the OpenAPI document of
15//! every `web` build.
16
17use schemars::JsonSchema;
18use serde::{Deserialize, Serialize};
19
20use crate::genui::FormState;
21pub use crate::genui::{AppAnswer, AppMessageRequest, AppOpen, AppRequest, GenuiCapabilities};
22
23/// The routes' paths, relative to `/api`.
24pub mod paths {
25    /// `GET`: what this home claims of the UI protocols agents draw in.
26    pub const CAPABILITIES: &str = "/surface/genui/capabilities";
27    /// `GET`: the catalogs this home renders, as A2UI catalog documents.
28    pub const CATALOGS: &str = "/surface/genui/catalogs";
29    /// `GET`: the state of each drawn form sent in a session.
30    pub const FORMS: &str = "/surface/genui/sessions/{session}/forms";
31    /// `GET`: an app from an MCP server, opened (spec 3.3 §6.1 `genui-apps`).
32    pub const APP: &str = "/surface/genui/sessions/{session}/apps/{call}";
33    /// `POST`: a request an app made of the home.
34    pub const APP_REQUESTS: &str = "/surface/genui/sessions/{session}/apps/{call}/requests";
35    /// `POST`: the person sends what an app suggested.
36    pub const APP_MESSAGE: &str = "/surface/genui/sessions/{session}/apps/{call}/message";
37}
38
39/// `GET /surface/genui/catalogs` answer (spec 3.3 §6.1 `genui`): the catalogs this home
40/// renders, `forms` first, as documents of one A2UI version. In 1.0 an extension catalog's
41/// document holds only the components it adds, which a surface mixes with `forms`.
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
43#[serde(rename_all = "camelCase")]
44pub struct CatalogDocuments {
45    /// The A2UI version of the documents: `1.0` or `v0.9.1`.
46    pub version: String,
47    /// Each catalog's document, by the A2UI catalog meta-schema of that version.
48    pub catalogs: Vec<serde_json::Value>,
49}
50
51/// `GET /surface/genui/catalogs` query.
52#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]
53pub struct CatalogsQuery {
54    /// `1.0` (the default) or `v0.9.1`.
55    #[serde(default)]
56    pub version: Option<String>,
57}
58
59/// `GET /surface/genui/sessions/{session}/forms` answer (spec 3.3 §7.4 rule 5).
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
61#[serde(rename_all = "camelCase")]
62pub struct FormsResponse {
63    /// The session.
64    pub session_id: String,
65    /// Each form sent, its latest send per version.
66    pub forms: Vec<FormState>,
67}
68
69#[cfg(feature = "genui")]
70mod routes {
71    use axum::extract::{Path, Query, State};
72    use axum::response::{IntoResponse, Response};
73    use axum::routing::get;
74    use axum::{Json, Router};
75
76    use super::{CatalogDocuments, CatalogsQuery, FormsResponse, paths};
77    use crate::engine::SurfaceEngine;
78    use crate::genui::GenuiWiring;
79    use crate::model::{DecidedAnswer, ThreadItem};
80    use crate::origin::SurfaceKind;
81    use crate::web::{Context, SurfaceQuery, Unauthenticated, caller, failed, unauthenticated};
82
83    /// The agent-drawn UI routes, relative to `/api` (spec 3.3 §6.1 `genui`): mount them with
84    /// `ServerBuilder::add_api_routes` beside [`crate::web::router`].
85    ///
86    /// # Example
87    ///
88    /// ```rust,no_run
89    /// use std::sync::Arc;
90    /// use adk_surface::{LocalSource, SurfaceEngine};
91    ///
92    /// # fn example(source: LocalSource, builder: adk_server::ServerBuilder) {
93    /// let engine = SurfaceEngine::builder(Arc::new(source)).build();
94    /// let builder = builder
95    ///     .add_api_routes(adk_surface::web::router(engine.clone()))
96    ///     .add_api_routes(adk_surface::web::genui::router(engine));
97    /// # let _ = builder;
98    /// # }
99    /// ```
100    pub fn router(engine: SurfaceEngine) -> Router {
101        router_wired(engine, GenuiWiring::default())
102    }
103
104    /// [`router`] for a host that wired `wiring` beside it: the capabilities route claims
105    /// AG-UI and MCP Apps only where they are wired (spec 3.3 §6.1 `genui`).
106    ///
107    /// # Example
108    ///
109    /// ```rust,no_run
110    /// use std::sync::Arc;
111    /// use adk_surface::genui::{GenuiAgUi, GenuiWiring};
112    /// use adk_surface::{LocalSource, SurfaceEngine};
113    ///
114    /// # fn example(source: LocalSource, builder: adk_server::ServerBuilder) {
115    /// let engine = SurfaceEngine::builder(Arc::new(source)).build();
116    /// let wiring = GenuiWiring { ag_ui: true, mcp_apps: false };
117    /// let builder = builder
118    ///     .with_ag_ui_extension(Arc::new(GenuiAgUi::new()))
119    ///     .add_api_routes(adk_surface::web::genui::router_wired(engine, wiring));
120    /// # let _ = builder;
121    /// # }
122    /// ```
123    pub fn router_wired(engine: SurfaceEngine, wiring: GenuiWiring) -> Router {
124        Router::new()
125            .route(
126                paths::CAPABILITIES,
127                get(move |State(engine): State<SurfaceEngine>, context: Context| {
128                    capabilities(engine, context, wiring)
129                }),
130            )
131            .route(paths::FORMS, get(forms))
132            .route(paths::CATALOGS, get(catalogs))
133            .with_state(engine)
134    }
135
136    async fn catalogs(
137        State(engine): State<SurfaceEngine>,
138        context: Context,
139        Query(query): Query<CatalogsQuery>,
140    ) -> Response {
141        if caller(context, SurfaceKind::Web, None).is_err() {
142            return unauthenticated();
143        }
144        let version = match query.version.as_deref() {
145            None => crate::genui::A2uiVersion::CURRENT,
146            Some(named) => match crate::genui::A2uiVersion::of_wire(named) {
147                Some(version) => version,
148                None => {
149                    return failed(crate::error::SurfaceError::Invalid(format!(
150                        "version '{named}' is not an A2UI version this home writes: use 1.0 or v0.9.1"
151                    )));
152                }
153            },
154        };
155        Json(CatalogDocuments {
156            version: version.wire().to_string(),
157            catalogs: engine
158                .catalogs()
159                .iter()
160                .map(|catalog| catalog.document_for(version))
161                .collect(),
162        })
163        .into_response()
164    }
165
166    async fn capabilities(
167        engine: SurfaceEngine,
168        context: Context,
169        wiring: GenuiWiring,
170    ) -> Response {
171        if caller(context, SurfaceKind::Web, None).is_err() {
172            return unauthenticated();
173        }
174        Json(crate::genui::capabilities_with(wiring, engine.catalogs())).into_response()
175    }
176
177    async fn forms(
178        State(engine): State<SurfaceEngine>,
179        context: Context,
180        Path(session): Path<String>,
181        Query(query): Query<SurfaceQuery>,
182    ) -> Response {
183        let caller = match caller(context, query.surface.unwrap_or(SurfaceKind::Web), None) {
184            Ok(caller) => caller,
185            Err(Unauthenticated) => return unauthenticated(),
186        };
187        let entries = match engine.thread(&caller, &session).await {
188            Ok(entries) => entries,
189            Err(error) => return failed(error),
190        };
191        // How each sent form's decision ended, read once per decision.
192        let mut answers: Vec<(String, Option<DecidedAnswer>)> = Vec::new();
193        for item in entries.iter().flat_map(|entry| &entry.items) {
194            if let ThreadItem::DrawnSent { sent } = item
195                && let Some(id) = &sent.decision_id
196                && !answers.iter().any(|(known, _)| known == id)
197            {
198                let answer = engine
199                    .decision(&caller, id)
200                    .await
201                    .ok()
202                    .and_then(|card| card.decided)
203                    .map(|decided| decided.answer);
204                answers.push((id.clone(), answer));
205            }
206        }
207        let forms = crate::genui::form_states(&entries, |id| {
208            answers.iter().find(|(known, _)| known == id).and_then(|(_, answer)| *answer)
209        });
210        Json(FormsResponse { session_id: session, forms }).into_response()
211    }
212}
213
214#[cfg(feature = "genui")]
215pub use routes::{router, router_wired};
216
217#[cfg(feature = "genui-apps")]
218mod apps {
219    use std::sync::{Arc, Mutex};
220    use std::time::{Duration, Instant};
221
222    use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditTrail};
223    use axum::body::Body;
224    use axum::extract::{Path, Query, Request, State};
225    use axum::http::{HeaderMap, header};
226    use axum::middleware::{self, Next};
227    use axum::response::{IntoResponse, Response};
228    use axum::routing::{get, post};
229    use axum::{Json, Router};
230
231    use super::{AppMessageRequest, AppRequest, paths};
232    use crate::engine::{CommandOutcome, SurfaceEngine};
233    use crate::error::SurfaceError;
234    use crate::genui::{McpAppsHost, SURFACE_AUDIT_APP_ORIGIN_REFUSED};
235    use crate::origin::SurfaceKind;
236    use crate::web::{Context, SurfaceQuery, Unauthenticated, caller, failed, unauthenticated};
237
238    /// The engine and the host an app route needs.
239    #[derive(Clone)]
240    struct Apps {
241        engine: SurfaceEngine,
242        host: McpAppsHost,
243    }
244
245    /// The MCP Apps routes, relative to `/api` (spec 3.3 §6.1 `genui-apps`): mount them with
246    /// `ServerBuilder::add_api_routes` beside [`crate::web::router`], serve
247    /// [`McpAppsHost::sandbox_router`] on the apps origin, and wrap the server's router in
248    /// [`refuse_apps_origin`].
249    ///
250    /// # Example
251    ///
252    /// ```rust,no_run
253    /// use std::sync::Arc;
254    /// use adk_surface::genui::McpAppsHost;
255    /// use adk_surface::{LocalSource, SurfaceEngine};
256    ///
257    /// # fn example(source: LocalSource, manager: Arc<adk_tool::mcp::McpServerManager>, builder: adk_server::ServerBuilder) {
258    /// let engine = SurfaceEngine::builder(Arc::new(source)).build();
259    /// let host = McpAppsHost::builder().servers(manager).apps_origin("http://127.0.0.1:41234").build();
260    /// let builder = builder
261    ///     .add_api_routes(adk_surface::web::router(engine.clone()))
262    ///     .add_api_routes(adk_surface::web::genui::apps_router(engine, host));
263    /// # let _ = builder;
264    /// # }
265    /// ```
266    pub fn apps_router(engine: SurfaceEngine, host: McpAppsHost) -> Router {
267        Router::new()
268            .route(paths::APP, get(open))
269            .route(paths::APP_REQUESTS, post(request))
270            .route(paths::APP_MESSAGE, post(message))
271            .with_state(Apps { engine, host })
272    }
273
274    /// Refuses every request `router` serves whose `Origin` is `apps_origin`, or the opaque
275    /// `null` a sandboxed frame sends, with `403 surface.not_here` (spec 3.3 §6.1
276    /// `genui-apps`): an app's frame never acts on the home, whatever the server's
277    /// `SecurityConfig` admits. Wrap the whole server's router, not only the surface's.
278    ///
279    /// # Example
280    ///
281    /// ```rust
282    /// let app = adk_surface::web::genui::refuse_apps_origin(axum::Router::new(), "http://127.0.0.1:41234");
283    /// # let _ = app;
284    /// ```
285    pub fn refuse_apps_origin(router: Router, apps_origin: &str) -> Router {
286        refuse(router, apps_origin, None)
287    }
288
289    /// [`refuse_apps_origin`], recording the refusals on `trail` as
290    /// `surface.app.origin_refused`: at most one record a minute, with the number refused
291    /// since the last, so a page that keeps trying cannot fill the trail (spec 3.3 §6.1
292    /// `genui-apps`, scenario 11).
293    ///
294    /// # Example
295    ///
296    /// ```rust
297    /// use std::sync::Arc;
298    /// use adk_core::audit_log::{AuditTrail, InMemoryAuditRecorder};
299    ///
300    /// let trail = AuditTrail::new(Arc::new(InMemoryAuditRecorder::new()));
301    /// let app = adk_surface::web::genui::refuse_apps_origin_recorded(
302    ///     axum::Router::new(),
303    ///     "http://127.0.0.1:41234",
304    ///     trail,
305    /// );
306    /// # let _ = app;
307    /// ```
308    pub fn refuse_apps_origin_recorded(
309        router: Router,
310        apps_origin: &str,
311        trail: AuditTrail,
312    ) -> Router {
313        refuse(router, apps_origin, Some(trail))
314    }
315
316    /// How often a refusal from the apps origin is recorded at most.
317    const RECORD_EVERY: Duration = Duration::from_secs(60);
318
319    /// Refusals since the last record, and when that was.
320    #[derive(Default)]
321    struct Refusals {
322        last: Option<Instant>,
323        since: u64,
324    }
325
326    /// Whether `origin` is a server's own origin under `apps_origin`
327    /// (`McpAppsHostBuilder::origin_per_server`): the same scheme and port, a subdomain of its
328    /// host.
329    fn under(origin: &str, apps_origin: &str) -> bool {
330        let (Some((scheme, rest)), Some((apps_scheme, apps_rest))) =
331            (origin.split_once("://"), apps_origin.split_once("://"))
332        else {
333            return false;
334        };
335        scheme == apps_scheme && rest.ends_with(&format!(".{apps_rest}"))
336    }
337
338    fn refuse(router: Router, apps_origin: &str, trail: Option<AuditTrail>) -> Router {
339        let apps_origin = apps_origin.trim_end_matches('/').to_ascii_lowercase();
340        let refusals = Arc::new(Mutex::new(Refusals::default()));
341        router.layer(middleware::from_fn(move |request: Request<Body>, next: Next| {
342            let apps_origin = apps_origin.clone();
343            let trail = trail.clone();
344            let refusals = Arc::clone(&refusals);
345            async move {
346                let from_apps = request
347                    .headers()
348                    .get_all(header::ORIGIN)
349                    .iter()
350                    .filter_map(|origin| origin.to_str().ok())
351                    .map(|origin| origin.trim_end_matches('/').to_ascii_lowercase())
352                    .any(|origin| {
353                        origin == apps_origin || origin == "null" || under(&origin, &apps_origin)
354                    });
355                if from_apps {
356                    tracing::warn!(
357                        http.path = %request.uri().path(),
358                        "refused a request from an app's frame"
359                    );
360                    let due = {
361                        let mut refusals =
362                            refusals.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
363                        refusals.since += 1;
364                        let due = refusals.last.is_none_or(|last| last.elapsed() >= RECORD_EVERY);
365                        due.then(|| {
366                            refusals.last = Some(Instant::now());
367                            std::mem::take(&mut refusals.since)
368                        })
369                    };
370                    if let (Some(trail), Some(refused)) = (trail, due) {
371                        let origin = request
372                            .headers()
373                            .get(header::ORIGIN)
374                            .and_then(|origin| origin.to_str().ok())
375                            .unwrap_or_default()
376                            .chars()
377                            .take(200)
378                            .collect::<String>();
379                        let draft = AuditRecordDraft::new(
380                            AuditRecordKind::Other("surface".to_string()),
381                            SURFACE_AUDIT_APP_ORIGIN_REFUSED,
382                        )
383                        .actor(AuditActor::default())
384                        .ext("method", serde_json::json!(request.method().as_str()))
385                        .ext("path", serde_json::json!(request.uri().path()))
386                        .ext("origin", serde_json::json!(origin))
387                        .ext("refused", serde_json::json!(refused));
388                        if let Err(error) = trail.record(draft).await {
389                            tracing::warn!(error = %error, "a refusal from the apps origin was not recorded");
390                        }
391                    }
392                    return failed(SurfaceError::NotHere(
393                        "an app's frame never acts on this home".to_string(),
394                    ));
395                }
396                next.run(request).await
397            }
398        }))
399    }
400
401    async fn open(
402        State(apps): State<Apps>,
403        context: Context,
404        headers: HeaderMap,
405        Path((session, call)): Path<(String, String)>,
406        Query(query): Query<SurfaceQuery>,
407    ) -> Response {
408        let caller = match caller(context, query.surface.unwrap_or(SurfaceKind::Web), None) {
409            Ok(caller) => caller,
410            Err(Unauthenticated) => return unauthenticated(),
411        };
412        // The page that asked frames the app: its own origin, whatever address it was opened at.
413        let page_host = headers.get(header::HOST).and_then(|host| host.to_str().ok());
414        match apps.host.open(&apps.engine, &caller, &session, &call, page_host).await {
415            Ok(open) => Json(open).into_response(),
416            Err(error) => failed(error),
417        }
418    }
419
420    async fn request(
421        State(apps): State<Apps>,
422        context: Context,
423        Path((session, call)): Path<(String, String)>,
424        Json(body): Json<AppRequest>,
425    ) -> Response {
426        // Only the web home frames apps, so only it relays their requests.
427        let caller = match caller(context, SurfaceKind::Web, None) {
428            Ok(caller) if caller.surface == SurfaceKind::Web => caller,
429            Ok(_) => return failed(SurfaceError::NotHere("apps run in the web home".into())),
430            Err(Unauthenticated) => return unauthenticated(),
431        };
432        match apps.host.request(&apps.engine, &caller, &session, &call, body).await {
433            Ok(answer) => Json(answer).into_response(),
434            Err(error) => failed(error),
435        }
436    }
437
438    async fn message(
439        State(apps): State<Apps>,
440        context: Context,
441        Path((session, call)): Path<(String, String)>,
442        Json(body): Json<AppMessageRequest>,
443    ) -> Response {
444        let caller = match caller(context, SurfaceKind::Web, None) {
445            Ok(caller) if caller.surface == SurfaceKind::Web => caller,
446            Ok(_) => return failed(SurfaceError::NotHere("apps run in the web home".into())),
447            Err(Unauthenticated) => return unauthenticated(),
448        };
449        match apps.host.send_message(&apps.engine, &caller, &session, &call, &body.message).await {
450            Ok(outcome) => Json::<CommandOutcome>(outcome).into_response(),
451            Err(error) => failed(error),
452        }
453    }
454}
455
456#[cfg(feature = "genui-apps")]
457pub use apps::{apps_router, refuse_apps_origin, refuse_apps_origin_recorded};