mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-29 08:06:46 +00:00
fix: serve new MCP OAuth sign-ins the session toolset on /api/mcp/gateway
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
6939454edb
commit
f6f0aa0f97
@@ -577,13 +577,14 @@ pub async fn run_server(
|
||||
add_www_authenticate_header, add_www_authenticate_header_gateway,
|
||||
extract_workspace_from_token, reject_token_query_param,
|
||||
};
|
||||
let (mcp_router, session_router, mcp_cancellation_token) = setup_mcp_server(
|
||||
db.clone(),
|
||||
user_db,
|
||||
_base_internal_url.clone(),
|
||||
auth_cache.clone(),
|
||||
)
|
||||
.await?;
|
||||
let (mcp_router, gateway_router, session_router, mcp_cancellation_token) =
|
||||
setup_mcp_server(
|
||||
db.clone(),
|
||||
user_db,
|
||||
_base_internal_url.clone(),
|
||||
auth_cache.clone(),
|
||||
)
|
||||
.await?;
|
||||
// Workspace-scoped MCP router
|
||||
let workspaced_mcp_router = mcp_router
|
||||
.clone()
|
||||
@@ -592,7 +593,7 @@ pub async fn run_server(
|
||||
.layer(axum::middleware::from_fn(add_www_authenticate_header))
|
||||
.layer(axum::middleware::from_fn(extract_and_store_workspace_id));
|
||||
// Gateway MCP router — resolves workspace from token
|
||||
let gateway_mcp_router = mcp_router
|
||||
let gateway_mcp_router = gateway_router
|
||||
.route_layer(from_extractor::<ApiAuthed>())
|
||||
.layer(axum::middleware::from_fn(extract_workspace_from_token))
|
||||
.layer(axum::middleware::from_fn(reject_token_query_param))
|
||||
|
||||
@@ -35,6 +35,7 @@ use std::sync::Arc;
|
||||
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,
|
||||
@@ -503,6 +504,19 @@ fn scoped_to_selection(scopes: &[String]) -> bool {
|
||||
mcp.clone().next().is_some() && !mcp.any(|scope| scope == "mcp:all")
|
||||
}
|
||||
|
||||
/// Set on a request whose token `/api/mcp/gateway` serves the session's toolset rather than
|
||||
/// the tools server: an `mcp:all` grant marked `mcp:session`, or narrowed by `mcp:read_only` /
|
||||
/// `mcp:read_run`, which leave the tools server only `list_workspaces` there.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct McpSessionGrant;
|
||||
|
||||
fn serves_session_on_gateway(scopes: &[String]) -> bool {
|
||||
scopes.iter().any(|scope| scope == "mcp:all")
|
||||
&& scopes
|
||||
.iter()
|
||||
.any(|scope| [SESSION_SCOPE, "mcp:read_only", "mcp:read_run"].contains(&scope.as_str()))
|
||||
}
|
||||
|
||||
/// The path of a workspace-less MCP URL, when it is not the tools server's
|
||||
/// `/api/mcp/gateway`: each URL is its own OAuth protected resource.
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -519,6 +533,16 @@ pub async fn extract_and_store_workspace_id(
|
||||
next.run(request).await
|
||||
}
|
||||
|
||||
/// RFC 9728 challenge pointing at the endpoint's protected resource metadata. `scope` is what
|
||||
/// a client requests: without it, Claude requests every scope the metadata lists, read-only
|
||||
/// included, and the consent page would then default to read-only access.
|
||||
fn www_authenticate_value(base_url: &str, endpoint: &str) -> String {
|
||||
format!(
|
||||
"Bearer resource_metadata=\"{base_url}/.well-known/oauth-protected-resource{endpoint}\", \
|
||||
scope=\"mcp:all\""
|
||||
)
|
||||
}
|
||||
|
||||
/// Middleware that adds WWW-Authenticate header to 401 responses
|
||||
/// This helps MCP clients discover the OAuth authorization server (RFC 9728)
|
||||
pub async fn add_www_authenticate_header(
|
||||
@@ -545,11 +569,8 @@ pub async fn add_www_authenticate_header(
|
||||
if response.status() == StatusCode::UNAUTHORIZED {
|
||||
let base_url = BASE_URL.load();
|
||||
|
||||
// RFC 9728: The resource parameter contains the protected resource URL.
|
||||
// Clients derive the metadata URL by inserting /.well-known/oauth-protected-resource
|
||||
// after the host, e.g., http://host/.well-known/oauth-protected-resource/api/mcp/w/test/mcp
|
||||
let resource_url = format!("{}/api/mcp/w/{}/mcp", base_url, workspace_id);
|
||||
let www_authenticate = format!("Bearer resource=\"{}\"", resource_url);
|
||||
let www_authenticate =
|
||||
www_authenticate_value(&base_url, &format!("/api/mcp/w/{}/mcp", workspace_id));
|
||||
|
||||
// Reconstruct response with the new header
|
||||
let (mut parts, body) = response.into_parts();
|
||||
@@ -626,9 +647,13 @@ pub async fn extract_workspace_from_token(
|
||||
.await
|
||||
{
|
||||
Ok(Some(row)) => {
|
||||
if scoped_to_selection(row.scopes.as_deref().unwrap_or_default()) {
|
||||
let scopes = row.scopes.as_deref().unwrap_or_default();
|
||||
if scoped_to_selection(scopes) {
|
||||
request.extensions_mut().insert(McpSelection);
|
||||
}
|
||||
if serves_session_on_gateway(scopes) {
|
||||
request.extensions_mut().insert(McpSessionGrant);
|
||||
}
|
||||
match row.workspace_id {
|
||||
Some(workspace_id) => {
|
||||
request
|
||||
@@ -678,8 +703,7 @@ pub async fn add_www_authenticate_header_gateway(
|
||||
|
||||
if response.status() == StatusCode::UNAUTHORIZED {
|
||||
let base_url = BASE_URL.load();
|
||||
let resource_url = format!("{}{}", base_url, endpoint);
|
||||
let www_authenticate = format!("Bearer resource=\"{}\"", resource_url);
|
||||
let www_authenticate = www_authenticate_value(&base_url, endpoint);
|
||||
|
||||
let (mut parts, body) = response.into_parts();
|
||||
parts.headers.insert(
|
||||
@@ -700,7 +724,7 @@ pub async fn setup_mcp_server(
|
||||
user_db: UserDB,
|
||||
base_internal_url: String,
|
||||
auth_cache: Arc<AuthCache>,
|
||||
) -> anyhow::Result<(Router, Router, CancellationToken)> {
|
||||
) -> anyhow::Result<(Router, Router, Router, CancellationToken)> {
|
||||
let cancellation_token = CancellationToken::new();
|
||||
let session_manager = Arc::new(LocalSessionManager::default());
|
||||
|
||||
@@ -736,6 +760,29 @@ pub async fn setup_mcp_server(
|
||||
StreamableHttpService::new(move || Ok(runner.clone()), session_manager, service_config);
|
||||
|
||||
let router = Router::new().route_service("/", service.clone());
|
||||
// `/api/mcp/gateway` keeps the tools server for every token it served before the
|
||||
// session's toolset existed, and answers a `McpSessionGrant` with that toolset.
|
||||
let gateway_router = Router::new().route(
|
||||
"/",
|
||||
axum::routing::any({
|
||||
let (service, session_service) = (service.clone(), session_service.clone());
|
||||
move |request: Request<axum::body::Body>| {
|
||||
let (service, session_service) = (service.clone(), session_service.clone());
|
||||
async move {
|
||||
use tower::ServiceExt;
|
||||
let response = if request.extensions().get::<McpSessionGrant>().is_some() {
|
||||
session_service.oneshot(request).await
|
||||
} else {
|
||||
service.oneshot(request).await
|
||||
};
|
||||
match response {
|
||||
Ok(response) => response.into_response(),
|
||||
Err(never) => match never {},
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
// `/api/mcp` serves both servers: a token scoped to a selection of scripts, flows and
|
||||
// endpoints gets the tools server, any other the session's toolset. At `/mcp` itself,
|
||||
// beside the `/mcp/...` routes, so it is merged rather than nested.
|
||||
@@ -758,7 +805,7 @@ pub async fn setup_mcp_server(
|
||||
}
|
||||
}),
|
||||
);
|
||||
Ok((router, session_router, cancellation_token))
|
||||
Ok((router, gateway_router, session_router, cancellation_token))
|
||||
}
|
||||
|
||||
/// HTTP handler to list MCP tools as JSON
|
||||
@@ -810,7 +857,7 @@ pub fn toolset_service() -> Router {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::scoped_to_selection;
|
||||
use super::{scoped_to_selection, serves_session_on_gateway};
|
||||
|
||||
#[test]
|
||||
fn only_a_token_without_mcp_all_is_a_selection() {
|
||||
@@ -829,4 +876,17 @@ mod tests {
|
||||
assert!(!selection(&[]));
|
||||
assert!(!selection(&["variables:read"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gateway_keeps_the_tools_server_for_unmarked_tokens() {
|
||||
let session = |scopes: &[&str]| {
|
||||
serves_session_on_gateway(&scopes.iter().map(|s| s.to_string()).collect::<Vec<_>>())
|
||||
};
|
||||
assert!(session(&["mcp:all", "mcp:session"]));
|
||||
assert!(session(&["mcp:all", "mcp:read_only"]));
|
||||
assert!(session(&["mcp:all", "mcp:read_run", "mcp:workspaces:a,b"]));
|
||||
assert!(!session(&["mcp:all"]));
|
||||
assert!(!session(&["mcp:favorites", "mcp:session"]));
|
||||
assert!(!session(&["mcp:all:f/x/*", "mcp:read_only"]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ use windmill_common::{
|
||||
|
||||
use crate::db::ApiAuthed;
|
||||
use windmill_api_auth::forbid_elevated_job_token;
|
||||
use windmill_mcp::parse_mcp_scopes;
|
||||
use windmill_mcp::{common::SESSION_SCOPE, parse_mcp_scopes};
|
||||
|
||||
/// Token expiration for MCP OAuth tokens (1 week in seconds)
|
||||
const MCP_OAUTH_TOKEN_EXPIRATION_SECS: u64 = 7 * 24 * 60 * 60;
|
||||
@@ -1063,6 +1063,10 @@ pub async fn gateway_oauth_approve(
|
||||
Json(form): Json<GatewayApprovalForm>,
|
||||
) -> Result<Json<ApprovalResponse>> {
|
||||
let mut scope = form.scope;
|
||||
let granted = scope.split_whitespace().collect::<Vec<_>>();
|
||||
if granted.contains(&"mcp:all") && !granted.contains(&SESSION_SCOPE) {
|
||||
scope.push_str(&format!(" {SESSION_SCOPE}"));
|
||||
}
|
||||
let mut workspace_ids = form.workspace_ids;
|
||||
if workspace_ids.is_empty() {
|
||||
workspace_ids.extend(form.workspace_id);
|
||||
|
||||
@@ -9,7 +9,7 @@ pub mod transform;
|
||||
pub mod types;
|
||||
|
||||
pub use schema::convert_schema_to_schema_type;
|
||||
pub use scope::{is_resource_allowed, parse_mcp_scopes, McpScopeConfig};
|
||||
pub use scope::{is_resource_allowed, parse_mcp_scopes, McpScopeConfig, SESSION_SCOPE};
|
||||
pub use transform::{
|
||||
apply_key_transformation, extract_hub_version_id_from_hashed, extract_path_prefix_from_hashed,
|
||||
parse_tool_prefix, reverse_transform, reverse_transform_key, transform_hub_path,
|
||||
|
||||
@@ -161,6 +161,11 @@ fn pattern_covers(caller: &str, requested: &str) -> bool {
|
||||
/// URL, which an older selection, carrying none of the newer scopes, still does.
|
||||
pub const RUNNABLES_AS_TOOLS_SCOPE: &str = "mcp:runnables_as_tools";
|
||||
|
||||
/// Added server-side to an `mcp:all` OAuth grant so `/api/mcp/gateway` serves it the AI
|
||||
/// session's toolset. Grants nothing: an `mcp:all` token without it predates the session
|
||||
/// toolset there, and must keep the tools server's endpoint tools.
|
||||
pub const SESSION_SCOPE: &str = "mcp:session";
|
||||
|
||||
/// Parse MCP scopes from token scope strings
|
||||
pub fn parse_mcp_scopes(scopes: &[String]) -> Result<McpScopeConfig, String> {
|
||||
let mut config = McpScopeConfig::default();
|
||||
@@ -233,6 +238,10 @@ pub fn parse_mcp_scopes(scopes: &[String]) -> Result<McpScopeConfig, String> {
|
||||
continue;
|
||||
}
|
||||
|
||||
if scope == SESSION_SCOPE {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(ids) = scope.strip_prefix("mcp:workspaces:") {
|
||||
config
|
||||
.workspaces
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
/** Marks a selection, so the per-workspace URLs add no API endpoint tools to it. */
|
||||
export const RUNNABLES_AS_TOOLS = 'mcp:runnables_as_tools'
|
||||
|
||||
/** Added by the server to an `mcp:all` sign-in so `/api/mcp/gateway` serves it the AI
|
||||
* session's tools. Grants nothing, so it is never shown. */
|
||||
export const MCP_SESSION = 'mcp:session'
|
||||
|
||||
const ACCESS_SCOPES: Record<Exclude<McpAccess, 'selected'>, string[]> = {
|
||||
read: ['mcp:all', 'mcp:read_only'],
|
||||
read_run: ['mcp:all', 'mcp:read_run'],
|
||||
@@ -13,7 +17,7 @@
|
||||
/** The access a token's MCP scopes give: `mcp:all` and how it is narrowed, or else a
|
||||
* selection of scripts, flows and endpoints. */
|
||||
export function mcpAccessOf(scopes: string[]): McpAccess {
|
||||
scopes = scopes.filter((s) => s !== RUNNABLES_AS_TOOLS)
|
||||
scopes = scopes.filter((s) => s !== RUNNABLES_AS_TOOLS && s !== MCP_SESSION)
|
||||
if (!scopes.includes('mcp:all')) return scopes.length > 0 ? 'selected' : 'full'
|
||||
if (scopes.includes('mcp:read_only')) return 'read'
|
||||
if (scopes.includes('mcp:read_run')) return 'read_run'
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import Modal from '../common/modal/Modal.svelte'
|
||||
import TextInput from '../text_input/TextInput.svelte'
|
||||
import ScopesPicker from './ScopesPicker.svelte'
|
||||
import McpAccessPicker, { mcpAccessOf } from '../mcp/McpAccessPicker.svelte'
|
||||
import McpAccessPicker, { MCP_SESSION, mcpAccessOf } from '../mcp/McpAccessPicker.svelte'
|
||||
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
|
||||
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
@@ -50,10 +50,12 @@
|
||||
// user has used the picker; until then the token keeps exactly the scopes it had.
|
||||
let mcpTouched = $state(false)
|
||||
// Carried over as is, the picker knowing nothing of them: dropping the workspace list
|
||||
// would widen the token to every workspace.
|
||||
// would widen the token to every workspace, dropping `mcp:session` would move a sign-in
|
||||
// on `/api/mcp/gateway` back to the endpoint tools.
|
||||
const isWorkspaceList = (s: string) => s.startsWith('mcp:workspaces:')
|
||||
const keptAside = (s: string) =>
|
||||
isWorkspaceList(s) || (mcpAccessOf(mcpScopes) !== 'selected' && s.startsWith('mcp:hub:'))
|
||||
isWorkspaceList(s) ||
|
||||
(mcpAccessOf(mcpScopes) !== 'selected' && (s.startsWith('mcp:hub:') || s === MCP_SESSION))
|
||||
const scopesToSave = $derived(
|
||||
isMcp
|
||||
? mcpTouched
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
import Badge from '../common/badge/Badge.svelte'
|
||||
import Alert from '../common/alert/Alert.svelte'
|
||||
import { Pen, Trash } from 'lucide-svelte'
|
||||
import { MCP_SESSION } from '../mcp/McpAccessPicker.svelte'
|
||||
|
||||
// --- Props ---
|
||||
interface Props {
|
||||
@@ -114,6 +115,10 @@
|
||||
listTokens()
|
||||
}
|
||||
|
||||
function shownScopes(scopes: string[] | null | undefined): string {
|
||||
return (scopes ?? []).filter((s) => s !== MCP_SESSION).join(', ')
|
||||
}
|
||||
|
||||
function handleEditClick(
|
||||
tokenPrefix: string,
|
||||
tokenLabel: string | undefined,
|
||||
@@ -199,13 +204,13 @@
|
||||
</td>
|
||||
<td
|
||||
class="min-w-0 max-w-48 truncate text-xs text-secondary"
|
||||
title={scopes?.join(', ') ?? ''}
|
||||
title={shownScopes(scopes)}
|
||||
>
|
||||
<div class="flex items-center gap-1.5 truncate">
|
||||
{#if read_only}
|
||||
<Badge color="blue" small>Read-only</Badge>
|
||||
{/if}
|
||||
<span class="truncate">{scopes?.join(', ') ?? ''}</span>
|
||||
<span class="truncate">{shownScopes(scopes)}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="w-24 text-center">
|
||||
|
||||
Reference in New Issue
Block a user