mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-28 08:06:16 +00:00
fix: offer mcp card tools only to clients that draw cards
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
9a7ab54746
commit
01ec22a868
@@ -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<Postgres>,
|
||||
) -> 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<String>, 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::<Value>(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(())
|
||||
}
|
||||
|
||||
@@ -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?);
|
||||
|
||||
@@ -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::<ApiAuthed>().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::<McpSelection>().is_some() {
|
||||
request.extensions_mut().insert(NoEndpointTools);
|
||||
service.oneshot(request).await
|
||||
} else {
|
||||
session_service.oneshot(request).await
|
||||
};
|
||||
match response {
|
||||
if request.extensions().get::<McpSelection>().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<SessionRunner<WindmillBackend>, LocalSessionManager>,
|
||||
request: Request<axum::body::Body>,
|
||||
) -> 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<Vec<EndpointTool>> {
|
||||
let endpoint_tools = all_tools();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<ClientName>,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct ClientName {
|
||||
name: String,
|
||||
}
|
||||
serde_json::from_slice::<Initialize>(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<A> {
|
||||
scope: McpScopeConfig,
|
||||
/// The scheme and host the client reached, for links to Windmill pages.
|
||||
origin: Option<String>,
|
||||
headers: http::HeaderMap,
|
||||
}
|
||||
|
||||
/// `x-forwarded-*` first, since a proxy in front rewrites the host the request names.
|
||||
@@ -151,7 +192,7 @@ impl<B: McpBackend> SessionRunner<B> {
|
||||
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<B::Auth>) -> Result<Vec<WorkspaceInfo>, ErrorData> {
|
||||
@@ -304,7 +345,7 @@ impl<B: McpBackend> ServerHandler for SessionRunner<B> {
|
||||
.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]
|
||||
|
||||
Reference in New Issue
Block a user