Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 31 additions & 9 deletions app/src/mcp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2272,7 +2272,10 @@ fn service() -> Service {
/// `/mcp`, any method: who the request acts for goes into its extensions, with the Laravel context, and rmcp's
/// service answers it.
pub async fn handle(principal: Result<Principal, laravel::Error>, request: axum::extract::Request) -> Response {
let Ok(principal) = principal else { return unauthorized() };
let Ok(principal) = principal else {
let sent = request.headers().contains_key(axum::http::header::AUTHORIZATION);
return unauthorized(sent);
};
let mut request = request;
request.extensions_mut().insert(principal);
context::carry(&mut request);
Expand All @@ -2282,13 +2285,32 @@ pub async fn handle(principal: Result<Principal, laravel::Error>, request: axum:
}
}

/// No token, or one we don't know.
fn unauthorized() -> Response {
(
axum::http::StatusCode::UNAUTHORIZED,
[(axum::http::header::WWW_AUTHENTICATE, "Bearer".to_string())],
/// No token (`sent` false), or one we don't know. The challenge names the protected resource's metadata (RFC 9728
/// section 5.1), which is how an MCP client finds the OAuth server to sign in with: the MCP spec requires it. As
/// today's server sent it: through oauth-provider's `challenge`, scope `mcp`, and `invalid_token` for a token we
/// don't know. (3 Dec 2026: app/ answered a bare `Bearer`, and clients couldn't find the sign-in.)
fn unauthorized(sent: bool) -> Response {
use oauth_provider::Refusal;
let refusal = if sent { Refusal::Invalid("The token is unknown or revoked.".into()) } else { Refusal::Missing };
let message = if sent {
"The token is unknown or revoked. Connect again, or send a live token.".to_string()
} else {
"Connect with OAuth (your MCP client opens VisualCI's sign-in), or send a personal (vcu_...) or project \
(vci_...) token as Authorization: Bearer <token>.",
)
.into_response()
(vci_...) token as Authorization: Bearer <token>."
.to_string()
};
let challenge = oauth_provider::provider::challenge(&resource(), &["mcp".to_string()], &refusal);
(axum::http::StatusCode::UNAUTHORIZED, [(axum::http::header::WWW_AUTHENTICATE, challenge)], message).into_response()
}

/// The MCP server as an OAuth protected resource, as its metadata names it: `<VISUALCI_MCP_URL>/mcp`, or on one host
/// (no host URLs) `<APP_URL>/mcp`.
fn resource() -> String {
let config = laravel::config();
let base = config
.get::<crate::http::hosts::HostUrls>()
.and_then(|h| h.mcp.clone())
.filter(|u| !u.trim().is_empty())
.unwrap_or_else(|| config.app.url.clone());
format!("{}/mcp", base.trim().trim_end_matches('/'))
}
65 changes: 64 additions & 1 deletion app/tests/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,70 @@ async fn rejects_requests_without_a_valid_token(app: Application) -> laravel::Re
.header("accept", "application/json, text/event-stream")
.json(json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }))
.await
.assert_status(401);
.assert_status(401)
.assert_header_contains("www-authenticate", "error=\"invalid_token\"");
Ok(())
}

/// The auth-params of a `Bearer` challenge (RFC 6750 section 3, RFC 9110 section 11.6.1): `key="value"` pairs after
/// the scheme, separated by commas, as an MCP client reads them.
fn bearer_params(header: &str) -> std::collections::HashMap<String, String> {
let rest = header.strip_prefix("Bearer ").unwrap_or_else(|| panic!("not a Bearer challenge: {header}"));
let mut params = std::collections::HashMap::new();
let mut rest = rest.trim();
while let Some((key, after)) = rest.split_once('=') {
let after = after.trim_start();
let (value, tail) = match after.strip_prefix('"') {
Some(quoted) => {
let end = quoted.find('"').unwrap_or_else(|| panic!("unterminated value in {header}"));
(&quoted[..end], &quoted[end + 1..])
}
None => after.split_once(',').map_or((after, ""), |(v, t)| (v, t)),
};
params.insert(key.trim().to_string(), value.to_string());
rest = tail.trim_start().trim_start_matches(',').trim_start();
}
params
}

/// An MCP client's connect flow, as Claude Code follows it (the MCP spec's authorization section, 2025-06-18): the
/// 401's challenge names the resource's metadata; that names the authorization server; whose metadata offers dynamic
/// registration and PKCE with S256. (3 Dec 2026: app/ answered a bare `Bearer`, so clients found no sign-in.)
#[laravel::test]
async fn an_mcp_client_finds_the_sign_in_from_the_401(app: Application) -> laravel::Result<()> {
let refused = app
.post("/mcp")
.header("accept", "application/json, text/event-stream")
.json(json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": { "name": "claude-code", "version": "2" } } }))
.await;
refused.assert_status(401);
let header =
refused.headers().get("www-authenticate").and_then(|v| v.to_str().ok()).unwrap_or_default().to_string();
let params = bearer_params(&header);
assert_eq!(params.get("scope").map(String::as_str), Some("mcp"), "{header}");
assert!(!params.contains_key("error"), "no token is not an error: {header}");
let metadata_url = url::Url::parse(params.get("resource_metadata").expect("resource_metadata")).expect("a URL");
assert_eq!(metadata_url.path(), "/.well-known/oauth-protected-resource/mcp");

let resource = app.get(metadata_url.path()).await;
resource.assert_ok();
let resource: serde_json::Value = resource.json();
assert!(resource["resource"].as_str().is_some_and(|r| r.ends_with("/mcp")), "{resource}");
let issuer =
url::Url::parse(resource["authorization_servers"][0].as_str().expect("an authorization server")).unwrap();

let server =
app.get(format!("{}/.well-known/oauth-authorization-server", issuer.path().trim_end_matches('/'))).await;
server.assert_ok();
let server: serde_json::Value = server.json();
for key in ["authorization_endpoint", "token_endpoint", "registration_endpoint"] {
assert!(server[key].is_string(), "the authorization server's metadata has no {key}: {server}");
}
assert!(
server["code_challenge_methods_supported"].as_array().is_some_and(|m| m.iter().any(|x| x == "S256")),
"no PKCE S256: {server}"
);
Ok(())
}

Expand Down
Loading