From 01ec22a868e71abfa367fc6ffabc42b0946b1337 Mon Sep 17 00:00:00 2001 From: Guilhem Lemouel Date: Fri, 27 Nov 2026 03:02:53 -0800 Subject: [PATCH] fix: offer mcp card tools only to clients that draw cards Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- .../tests/mcp_protocol_versions.rs | 78 +++++++++++++++ backend/windmill-api/src/lib.rs | 8 +- backend/windmill-api/src/mcp/core.rs | 53 +++++++--- backend/windmill-mcp/src/server/mod.rs | 2 +- backend/windmill-mcp/src/server/session.rs | 99 ++++++++++++++++--- 6 files changed, 208 insertions(+), 34 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c1ad3b7310..bd0ac6cd04 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,7 +73,7 @@ Open-source platform for internal tools, workflows, API integrations, background - **Domain vocabulary**: `CONTEXT.md` — the words this codebase uses for its own concepts (step, step setting, trigger step, …). Name things the way it does. - **CLI commands**: when adding/modifying/removing a command, subcommand, option, or description in `cli/src/commands/`, run `python system_prompts/generate.py` to refresh `system_prompts/auto-generated/` and `cli/src/guidance/skills.gen.ts`. The CLI docs the agents use to operate `wmill` are derived from the source — stale generated files give agents the wrong flags. - **AI guidance** (chat prompts and CLI skills): what the AI knows about Windmill itself — how flows, scripts, apps, pipelines and resources work — is written once, in `system_prompts/base/` and `system_prompts/languages/`, and `system_prompts/generate.py` builds both the chat's `$system_prompts` exports and the CLI's skills from it. Add or change such guidance there, never inline in one consumer: a sentence only one side should see goes in a `` / `` block, and a new file reaches both through the `TOPICS` table. The chat prompt builders under `frontend/src/lib/components/copilot/chat/` add only tool plumbing and runtime values, and shared markdown names no chat tool, since it reaches every chat mode. Rerun `generate.py` after editing; `system_prompts/README.md` has the details. -- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/ai_session_tools/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve and by the token forms' Build and run access, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `ai_session_tools/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). The instructions are one template (`EXTERNAL_PROMPT` in `chat/global/core.ts`, with `{{#flag}}` blocks rendered by `promptTemplate.ts`), and the generator exports the flags and variables of each access profile: the token's scope and, for a full token, the caller's role and whether the deploy rules let them deploy. The server only renders it, with the profile the key `prompt_profile` (`ai_session_tools/instructions.rs`) builds, which must match the generator's; its renderer must match `promptTemplate.ts`, which a hash per profile pins. In a workspace with `DisableDirectDeployment` every full token, an admin's included, is held to read-and-run there (`workspace_access` in `mcp/core.rs`), as the chat's session is (`protects` in `chat/global/sessionAccess.ts`), and a member whose role cannot run is held to read-only, with no run tools (`session_ctx_with`, and `capabilitiesForRole` in the chat); the two copies of each rule change together. What a tool *does* is written once, in a Rust handler the chat also calls (`POST /w/{workspace}/ai_session_tools/{name}`, through `chat/global/backendSessionTools.ts`); the browser applies the effects it returns, saving drafts through its own draft store. A new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `ai_session_tools/mod.rs` fails otherwise). Still written twice, so a behaviour change must be mirrored: `deploy_workspace_item` and `diff` (the chat uses the UI's shared deploy and diff code), and the run tools' form side (argument coercion, secrets, plan mode, the outcome text), where the chat resolves and starts the run on the server but owns the form in between; both sides test their argument handling against `ai_session_tools/run_args_cases.json`, so a change there comes with a case. For MCP Apps clients the server adds tools of its own, defined in Rust (`ai_session_tools/views.rs`) rather than generated, and not offered to the chat, which draws its own cards: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v` view (`mcp/card.html`; bump `CARD_URI` in `mcp/session.rs` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. +- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/ai_session_tools/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve and by the token forms' Build and run access, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `ai_session_tools/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). The instructions are one template (`EXTERNAL_PROMPT` in `chat/global/core.ts`, with `{{#flag}}` blocks rendered by `promptTemplate.ts`), and the generator exports the flags and variables of each access profile: the token's scope and, for a full token, the caller's role and whether the deploy rules let them deploy. The server only renders it, with the profile the key `prompt_profile` (`ai_session_tools/instructions.rs`) builds, which must match the generator's; its renderer must match `promptTemplate.ts`, which a hash per profile pins. In a workspace with `DisableDirectDeployment` every full token, an admin's included, is held to read-and-run there (`workspace_access` in `mcp/core.rs`), as the chat's session is (`protects` in `chat/global/sessionAccess.ts`), and a member whose role cannot run is held to read-only, with no run tools (`session_ctx_with`, and `capabilitiesForRole` in the chat); the two copies of each rule change together. What a tool *does* is written once, in a Rust handler the chat also calls (`POST /w/{workspace}/ai_session_tools/{name}`, through `chat/global/backendSessionTools.ts`); the browser applies the effects it returns, saving drafts through its own draft store. A new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `ai_session_tools/mod.rs` fails otherwise). Still written twice, so a behaviour change must be mirrored: `deploy_workspace_item` and `diff` (the chat uses the UI's shared deploy and diff code), and the run tools' form side (argument coercion, secrets, plan mode, the outcome text), where the chat resolves and starts the run on the server but owns the form in between; both sides test their argument handling against `ai_session_tools/run_args_cases.json`, so a change there comes with a case. For MCP Apps clients the server adds tools of its own, defined in Rust (`ai_session_tools/views.rs`) rather than generated, and not offered to the chat, which draws its own cards: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v` view (`mcp/card.html`; bump `CARD_URI` in `mcp/session.rs` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). Only a client that declares the MCP Apps extension (`io.modelcontextprotocol/ui`) is offered the show tools, and Codex (`codex-mcp-client`), whose desktop app draws its cards over connections that declare nothing. A `2026-07-28` client declares it on every request; an older one only in `initialize`, which the sessionless server answers with an `Mcp-Session-Id` (prefix `wm-ui-`) that the client sends back on every request. - **Session recorder**: `frontend/src/lib/components/recording/` is also the recorder `wmill app dev --recording` serves, vendored into the CLI as `cli/src/commands/app/devRecorderBundle.gen.ts`. After changing `rawAppSnapshot.ts` or `rawAppRecording.svelte.ts`, run `bun run gen:dev-recorder` from `cli/` (`cli/test/dev_recorder_bundle_unit.test.ts` fails otherwise). - **Raw-app policy**: `frontend/src/lib/components/raw_apps/rawAppPolicy.ts` also derives the policy the server's raw-app deploy stores, vendored into the bundle job as `backend/windmill-api/src/apps_raw_policy.gen.js`. After changing it or anything it imports, run `bun run gen:app-policy` from `cli/` (`cli/test/app_policy_bundle_unit.test.ts` fails otherwise). It rides in the job rather than being read from the CLI the job runs because the images install `windmill-cli` unpinned, so an image can carry one older than its server. diff --git a/backend/windmill-api-integration-tests/tests/mcp_protocol_versions.rs b/backend/windmill-api-integration-tests/tests/mcp_protocol_versions.rs index e684e3ee14..12d458b379 100644 --- a/backend/windmill-api-integration-tests/tests/mcp_protocol_versions.rs +++ b/backend/windmill-api-integration-tests/tests/mcp_protocol_versions.rs @@ -219,3 +219,81 @@ async fn test_mcp_unsupported_version_lists_supported_ones( Ok(()) } + +/// A legacy client sends its capabilities only in `initialize`, and the endpoint keeps no +/// session: the card tools must still follow them, through the session id it answers with. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_mcp_card_tools_follow_legacy_initialize_capabilities( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + set_jwt_secret().await; + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin, scopes) + VALUES (encode(sha256('MCP_SESSION'::bytea), 'hex'), 'MCP_SES', 'MCP_SESSION', 'test@windmill.dev', 'mcp session', true, ARRAY['mcp:all', 'mcp:session'])", + ) + .execute(&db) + .await?; + let server = ApiServer::start_mcp(db.clone()).await?; + let url = format!( + "http://localhost:{}/api/mcp/w/test-workspace/mcp", + server.addr.port() + ); + let send = |session_id: Option, body: Value| { + let mut req = reqwest::Client::new() + .post(&url) + .header("Authorization", "Bearer MCP_SESSION") + .header("Accept", "application/json, text/event-stream") + .header("MCP-Protocol-Version", "2025-11-25") + .json(&body); + if let Some(id) = session_id { + req = req.header("Mcp-Session-Id", id); + } + async move { + let resp = req.send().await?; + let session_id = resp + .headers() + .get("mcp-session-id") + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + let text = resp.text().await?; + let payload = text + .lines() + .find_map(|l| l.strip_prefix("data: ")) + .unwrap_or(text.trim()); + anyhow::Ok((session_id, serde_json::from_str::(payload)?)) + } + }; + + let cards = json!({ "extensions": { "io.modelcontextprotocol/ui": { + "mimeTypes": ["text/html;profile=mcp-app"] } } }); + for (capabilities, offered) in [(cards, true), (json!({ "elicitation": {} }), false)] { + let (session_id, _) = send( + None, + json!({ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": { + "protocolVersion": "2025-11-25", + "capabilities": capabilities.clone(), + "clientInfo": { "name": "test-client", "version": "0.0.1" }, + } + }), + ) + .await?; + let (_, body) = send( + session_id, + json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/list" }), + ) + .await?; + let tools = body["result"]["tools"] + .as_array() + .ok_or_else(|| anyhow::anyhow!("no tool list: {body}"))?; + assert_eq!( + tools.iter().any(|t| t["name"] == "show_run"), + offered, + "show_run offered to the wrong client ({capabilities})" + ); + } + + Ok(()) +} diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index b1d3f60c76..d361b15dcd 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -489,8 +489,12 @@ pub async fn run_server( .allow_headers(tower_http::cors::AllowHeaders::mirror_request()) // The 401 challenge is how a client discovers where to authorize (RFC 9728), // and it is not a safelisted response header, so without this a browser - // client sees an empty one and has no way to begin the OAuth flow. - .expose_headers([http::header::WWW_AUTHENTICATE]) + // client sees an empty one and has no way to begin the OAuth flow. The session + // id is how a browser host that draws cards keeps being offered the card tools. + .expose_headers([ + http::header::WWW_AUTHENTICATE, + http::HeaderName::from_static("mcp-session-id"), + ]) .allow_origin(Any); let sp_extension = Arc::new(saml_oss::build_sp_extension(&db).await?); diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index 25507b4119..e0db60024d 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -39,8 +39,8 @@ use std::time::Duration; use tokio_util::sync::CancellationToken; use windmill_mcp::common::SESSION_SCOPE; use windmill_mcp::server::{ - LocalSessionManager, McpToken, MultiWorkspaceMcp, NoEndpointTools, Runner, SessionRunner, - StreamableHttpServerConfig, StreamableHttpService, + initialize_draws_cards, LocalSessionManager, McpToken, MultiWorkspaceMcp, NoEndpointTools, + Runner, SessionRunner, StreamableHttpServerConfig, StreamableHttpService, CARD_SESSION_PREFIX, }; use windmill_mcp::WorkspaceId; @@ -856,12 +856,10 @@ pub async fn setup_mcp_server( let session = request.extensions().get::().is_some_and(|a| { serves_session_toolset(a.scopes.as_deref().unwrap_or_default()) }); - let response = if session { - session_service.oneshot(request).await - } else { - service.oneshot(request).await - }; - match response { + if session { + return serve_session(session_service, request).await; + } + match service.oneshot(request).await { Ok(response) => response.into_response(), Err(never) => match never {}, } @@ -878,13 +876,11 @@ pub async fn setup_mcp_server( let (service, session_service) = (service.clone(), session_service.clone()); async move { use tower::ServiceExt; - let response = if request.extensions().get::().is_some() { - request.extensions_mut().insert(NoEndpointTools); - service.oneshot(request).await - } else { - session_service.oneshot(request).await - }; - match response { + if request.extensions().get::().is_none() { + return serve_session(session_service, request).await; + } + request.extensions_mut().insert(NoEndpointTools); + match service.oneshot(request).await { Ok(response) => response.into_response(), Err(never) => match never {}, } @@ -894,6 +890,33 @@ pub async fn setup_mcp_server( Ok((router, session_router, cancellation_token)) } +/// Serves the session's toolset, answering the `initialize` of a client that draws cards +/// with a session id that tells its later requests so. +async fn serve_session( + service: StreamableHttpService, LocalSessionManager>, + request: Request, +) -> Response { + use tower::ServiceExt; + let (parts, body) = request.into_parts(); + let limit = *crate::REQUEST_SIZE_LIMIT.read().await; + let Ok(bytes) = axum::body::to_bytes(body, limit).await else { + return axum::http::StatusCode::PAYLOAD_TOO_LARGE.into_response(); + }; + let draws_cards = parts.method == axum::http::Method::POST && initialize_draws_cards(&bytes); + let request = Request::from_parts(parts, axum::body::Body::from(bytes)); + let mut response = match service.oneshot(request).await { + Ok(response) => response.into_response(), + Err(never) => match never {}, + }; + if draws_cards && response.status().is_success() { + let id = format!("{CARD_SESSION_PREFIX}{}", uuid::Uuid::new_v4().simple()); + if let Ok(value) = id.parse() { + response.headers_mut().insert("mcp-session-id", value); + } + } + response +} + /// HTTP handler to list MCP tools as JSON async fn list_mcp_tools_handler() -> JsonResult> { let endpoint_tools = all_tools(); diff --git a/backend/windmill-mcp/src/server/mod.rs b/backend/windmill-mcp/src/server/mod.rs index 69ce01be4f..79818f3800 100644 --- a/backend/windmill-mcp/src/server/mod.rs +++ b/backend/windmill-mcp/src/server/mod.rs @@ -22,7 +22,7 @@ pub use endpoints::{ list_workspaces_tool, non_empty_body_fields, with_workspace_id_arg, EndpointTool, }; pub use runner::{has_endpoint_path_policy, Runner, MAX_TOOL_RESULT_BYTES}; -pub use session::SessionRunner; +pub use session::{initialize_draws_cards, SessionRunner, CARD_SESSION_PREFIX}; pub use tools::create_tool_from_item; // Re-export rmcp types for convenience diff --git a/backend/windmill-mcp/src/server/session.rs b/backend/windmill-mcp/src/server/session.rs index 7c4a7d68e7..72a48b6122 100644 --- a/backend/windmill-mcp/src/server/session.rs +++ b/backend/windmill-mcp/src/server/session.rs @@ -52,18 +52,58 @@ const GET_WORKSPACE_CONTEXT: &str = "get_workspace_context"; const MCP_APP_MIME_TYPE: &str = "text/html;profile=mcp-app"; const MCP_APPS_EXTENSION: &str = "io.modelcontextprotocol/ui"; -/// A tool that only shows a card does nothing for a client that declares it draws none. -/// Only a request's own capabilities count: a legacy client's are never seen (the -/// transport keeps no session), and it keeps the tools. -fn declines_cards(capabilities: Option<&ClientCapabilities>) -> bool { - capabilities.is_some_and(|caps| { - !caps - .extensions - .as_ref() - .is_some_and(|e| e.contains_key(MCP_APPS_EXTENSION)) +/// The `Mcp-Session-Id` prefix given to a connection whose `initialize` says it draws cards. +/// The transport keeps no session, so the id itself carries what the handshake said: a +/// legacy client sends it back on every request, and a request's own capabilities, which +/// only `2026-07-28` clients send, never reach a legacy one. +pub const CARD_SESSION_PREFIX: &str = "wm-ui-"; + +fn declares_cards(capabilities: &ClientCapabilities) -> bool { + capabilities + .extensions + .as_ref() + .is_some_and(|e| e.contains_key(MCP_APPS_EXTENSION)) +} + +/// Codex's desktop app fetches and draws its cards over connections that declare nothing, +/// and draws a card only for a tool those connections list, so they are indistinguishable +/// from Codex CLI, which draws none. Both keep the card tools until Codex declares MCP Apps +/// on those connections. +const CODEX_CLIENT: &str = "codex-mcp-client"; + +/// Whether a request body is an `initialize` from a client that draws cards. +pub fn initialize_draws_cards(body: &[u8]) -> bool { + #[derive(serde::Deserialize)] + struct Initialize { + method: String, + params: InitializeParams, + } + #[derive(serde::Deserialize)] + #[serde(rename_all = "camelCase")] + struct InitializeParams { + capabilities: ClientCapabilities, + client_info: Option, + } + #[derive(serde::Deserialize)] + struct ClientName { + name: String, + } + serde_json::from_slice::(body).is_ok_and(|i| { + i.method == "initialize" + && (declares_cards(&i.params.capabilities) + || i.params.client_info.is_some_and(|c| c.name == CODEX_CLIENT)) }) } +/// Only a client that draws cards is offered the tools that just show one. +fn draws_cards(capabilities: Option<&ClientCapabilities>, headers: &http::HeaderMap) -> bool { + capabilities.is_some_and(declares_cards) + || headers + .get("mcp-session-id") + .and_then(|v| v.to_str().ok()) + .is_some_and(|id| id.starts_with(CARD_SESSION_PREFIX)) +} + /// The views load nothing from outside their own page and reach Windmill only through /// tools, so they declare no domain; a host reviewing the declared policy holds them to it. fn mcp_app_meta() -> MetaObject { @@ -106,6 +146,7 @@ struct Caller { scope: McpScopeConfig, /// The scheme and host the client reached, for links to Windmill pages. origin: Option, + headers: http::HeaderMap, } /// `x-forwarded-*` first, since a proxy in front rewrites the host the request names. @@ -151,7 +192,7 @@ impl SessionRunner { None, )); } - Ok(Caller { auth, mode, scope, origin: request_origin(&headers) }) + Ok(Caller { auth, mode, scope, origin: request_origin(&headers), headers }) } async fn workspaces(&self, caller: &Caller) -> Result, ErrorData> { @@ -304,7 +345,7 @@ impl ServerHandler for SessionRunner { .into_iter() .map(with_workspace_id_arg), ); - if declines_cards(context.meta.client_capabilities().as_ref()) { + if !draws_cards(context.meta.client_capabilities().as_ref(), &caller.headers) { tools.retain(|tool| { !tool.meta.as_ref().is_some_and(|m| { m.0.get("ui") @@ -424,12 +465,40 @@ mod tests { use super::*; #[test] - fn only_a_client_declaring_no_cards_loses_the_card_tools() { + fn only_a_client_declaring_mcp_apps_gets_the_card_tools() { + let none = http::HeaderMap::new(); let mut caps: ClientCapabilities = serde_json::from_value(serde_json::json!({})).unwrap(); - assert!(declines_cards(Some(&caps))); - assert!(!declines_cards(None)); + assert!(!draws_cards(Some(&caps), &none)); + assert!(!draws_cards(None, &none)); caps.extensions = Some([(MCP_APPS_EXTENSION.to_string(), Default::default())].into()); - assert!(!declines_cards(Some(&caps))); + assert!(draws_cards(Some(&caps), &none)); + + let mut session = http::HeaderMap::new(); + session.insert("mcp-session-id", "wm-ui-abc".parse().unwrap()); + assert!(draws_cards(None, &session)); + session.insert("mcp-session-id", "abc".parse().unwrap()); + assert!(!draws_cards(None, &session)); + } + + #[test] + fn an_initialize_draws_cards_through_its_extensions_or_as_codex() { + let init = |caps: Value, client: &str| { + serde_json::to_vec(&serde_json::json!({ + "jsonrpc": "2.0", "id": 0, "method": "initialize", + "params": { "protocolVersion": "2025-11-25", "capabilities": caps, + "clientInfo": { "name": client, "version": "1" } } + })) + .unwrap() + }; + let ui = serde_json::json!({ "extensions": { MCP_APPS_EXTENSION: { + "mimeTypes": [MCP_APP_MIME_TYPE] } } }); + let none = serde_json::json!({ "elicitation": {} }); + assert!(initialize_draws_cards(&init(ui, "claude-ai"))); + assert!(!initialize_draws_cards(&init(none.clone(), "other"))); + assert!(initialize_draws_cards(&init(none, CODEX_CLIENT))); + assert!(!initialize_draws_cards( + br#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"# + )); } #[test]