Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(ai): mcp (#2443)

Eric Hayes490cd618f35e
diff --git a/infra/stacks/fusionauth-instance/index.ts b/infra/stacks/fusionauth-instance/index.ts
index d1d62b609a..9d64800a52 100644
--- a/infra/stacks/fusionauth-instance/index.ts
+++ b/infra/stacks/fusionauth-instance/index.ts
@@ -262,10 +262,14 @@ const macroApplication = new FusionAuthApplication(
proofKeyForCodeExchangePolicy: 'NotRequired',
scopeHandlingPolicy: 'Compatibility',
unknownScopePolicy: 'Remove',
- authorizedUrlValidationPolicy: 'ExactMatch',
+ authorizedUrlValidationPolicy:
+ stack === 'local' || stack === 'dev' ? 'AllowWildcards' : 'ExactMatch',
authorizedRedirectUrls: [
`${AUTHENTICATION_SERVICE_DOMAIN}/oauth/redirect`,
`https://mcp-server${stack === 'prod' ? '' : `-${stack}`}.macro.com/oauth/callback`,
+ ...(stack === 'local' || stack === 'dev'
+ ? ['http://localhost:8085/*', 'http://localhost:8085/oauth/*']
+ : []),
],
authorizedOriginUrls: ALLOWED_ORIGINS(),
logoutBehavior: 'AllApplications',
diff --git a/infra/stacks/mcp-server/index.ts b/infra/stacks/mcp-server/index.ts
index 078db6d901..af876f4525 100644
--- a/infra/stacks/mcp-server/index.ts
+++ b/infra/stacks/mcp-server/index.ts
@@ -60,6 +60,12 @@ const googleClientSecretArn: pulumi.Output<string> = aws.secretsmanager
.getSecretVersionOutput({ secretId: GOOGLE_CLIENT_SECRET })
.apply((secret) => secret.arn);
+const MACRO_CACHE = aws.secretsmanager
+ .getSecretVersionOutput({
+ secretId: config.require(`macro_cache_secret_key`),
+ })
+ .apply((secret) => secret.secretString);
+
const INTERNAL_AUTH_KEY = aws.secretsmanager
.getSecretVersionOutput({
secretId: config.require('internal_auth_key'),
@@ -281,6 +287,10 @@ const mcpServer = new McpServer(`mcp-server-${stack}`, {
name: 'GOOGLE_CLIENT_SECRET_KEY',
value: GOOGLE_CLIENT_SECRET,
},
+ {
+ name: 'REDIS_URL',
+ value: pulumi.interpolate`redis://${MACRO_CACHE}`,
+ },
{
name: 'MACRO_API_TOKEN_ISSUER',
value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenIssuer}`,
diff --git a/infra/stacks/mcp-server/mcp-server.ts b/infra/stacks/mcp-server/mcp-server.ts
index f5fbd82498..3f9fc733a7 100644
--- a/infra/stacks/mcp-server/mcp-server.ts
+++ b/infra/stacks/mcp-server/mcp-server.ts
@@ -87,7 +87,7 @@ export class McpServer extends pulumi.ComponentResource {
dockerfile: 'Dockerfile',
platform,
buildArgs: {
- SERVICE_NAME: 'mcp_server',
+ SERVICE_NAME: 'mcp_service',
},
tags: this.tags,
},
@@ -303,15 +303,6 @@ export class McpServer extends pulumi.ComponentResource {
},
{ parent: this }
);
-
- // NOTE: DatadogServiceEntity requires DD_API_KEY/DD_APP_KEY env vars.
- // Uncomment once deploying via CI where those secrets are available.
- // new DatadogServiceEntity('mcp-server', {
- // serviceName: 'mcp-server',
- // owner: 'ehayes',
- // githubUrl: 'https://github.com/macro-inc/macro-api',
- // githubPath: 'cloud-storage/document-cognition-service/src/bin/mcp_server.rs',
- // });
}
initializeSecurityGroups({
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 3acab2eff5..f3bd2fb91b 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2979,14 +2979,12 @@ dependencies = [
"aws-sdk-secretsmanager",
"aws-sdk-sqs",
"axum",
- "base64 0.22.1",
"chat",
"chrono",
"comms",
"comms_service_client",
"connection_gateway",
"cookie",
- "dashmap",
"document_cognition_service_client",
"document_storage_service_client",
"documents",
@@ -2995,7 +2993,6 @@ dependencies = [
"email_service_client",
"entity_access",
"frecency",
- "fusionauth",
"futures",
"http 1.3.1",
"http-body-util",
@@ -3029,7 +3026,6 @@ dependencies = [
"redis",
"regex",
"reqwest",
- "rmcp",
"roles_and_permissions",
"schemars",
"scribe",
@@ -3037,7 +3033,6 @@ dependencies = [
"secretsmanager_client",
"serde",
"serde_json",
- "sha2",
"soup",
"sqlx",
"sqs_client",
@@ -3054,7 +3049,6 @@ dependencies = [
"tracing",
"unfurl_service",
"url",
- "urlencoding",
"utoipa",
"utoipa-swagger-ui",
"uuid",
@@ -6325,6 +6319,73 @@ dependencies = [
"rayon",
]
+[[package]]
+name = "mcp_auth_proxy"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "axum",
+ "base64 0.22.1",
+ "fusionauth",
+ "macro_auth",
+ "macro_user_id",
+ "redis",
+ "serde",
+ "serde_json",
+ "sha2",
+ "thiserror 2.0.17",
+ "tower 0.5.2",
+ "tracing",
+ "url",
+ "urlencoding",
+ "uuid",
+]
+
+[[package]]
+name = "mcp_service"
+version = "0.1.0"
+dependencies = [
+ "ai_tools",
+ "ai_toolset",
+ "anyhow",
+ "aws-sdk-secretsmanager",
+ "aws-sdk-sqs",
+ "axum",
+ "comms",
+ "document_storage_service_client",
+ "documents",
+ "email",
+ "email_service_client",
+ "entity_access",
+ "frecency",
+ "fusionauth",
+ "http 1.3.1",
+ "lexical_client",
+ "macro_auth",
+ "macro_aws_config",
+ "macro_entrypoint",
+ "macro_env",
+ "macro_env_var",
+ "macro_middleware",
+ "macro_user_id",
+ "mcp_auth_proxy",
+ "properties",
+ "readonly_pool",
+ "redis",
+ "rmcp",
+ "scribe",
+ "search_service_client",
+ "secretsmanager_client",
+ "serde_json",
+ "soup",
+ "sqlx",
+ "sqs_client",
+ "static_file_service_client",
+ "sync_service_client",
+ "tokio",
+ "tracing",
+]
+
[[package]]
name = "md-5"
version = "0.10.6"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 23c7130dd1..7bc9421811 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -72,6 +72,8 @@ members = [
"macro_sha_count_client",
"macro_share_permissions",
"macro_uuid",
+ "mcp_auth_proxy",
+ "mcp_service",
"memory",
"mention_utils",
"model",
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index 7ea789fe1b..654f0f81fc 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -21,10 +21,6 @@ path = "src/openapi.rs"
name = "document_cognition_service_models"
path = "src/models_bin.rs"
-[[bin]]
-name = "mcp_server"
-path = "src/bin/mcp_server.rs"
-
[features]
local = []
local_auth = ["macro_middleware/local_auth"]
@@ -47,14 +43,12 @@ aws-sdk-dynamodb = { workspace = true }
aws-sdk-s3 = { workspace = true }
aws-sdk-sqs = { workspace = true }
axum = { workspace = true, features = ["tower-log", "ws"] }
-base64 = { workspace = true }
chat = { path = "../chat" }
chrono = { workspace = true }
comms = { path = "../comms", features = ["outbound"] }
comms_service_client = { path = "../comms_service_client" }
connection_gateway = { path = "../connection_gateway" }
cookie = { workspace = true }
-dashmap = { workspace = true }
document_cognition_service_client = { path = "../document_cognition_service_client" }
document_storage_service_client = { path = "../document_storage_service_client" }
documents = { path = "../documents", features = ["ai_tools"] }
@@ -63,7 +57,6 @@ entity_access = { path = "../entity_access" }
email = { path = "../email", features = ["outbound"] }
email_service_client = { path = "../email_service_client" }
frecency = { path = "../frecency", features = ["outbound", "postgres"] }
-fusionauth = { path = "../fusionauth" }
futures = { workspace = true }
http = { workspace = true }
http-body-util = { workspace = true }
@@ -98,7 +91,6 @@ models_permissions = { path = "../models_permissions" }
regex = { workspace = true }
reqwest.workspace = true
roles_and_permissions = { path = "../roles_and_permissions", default-features = false }
-rmcp = { version = "1.2.0", features = ["transport-streamable-http-server"] }
schemars = { workspace = true }
scribe = { path = "../scribe", features = [
"channel",
@@ -111,7 +103,6 @@ search_service_client = { path = "../search_service_client" }
secretsmanager_client = { path = "../secretsmanager_client" }
serde = { workspace = true }
serde_json = { workspace = true }
-sha2 = { workspace = true }
readonly_pool = { path = "../readonly_pool" }
soup = { path = "../soup", features = ["outbound"] }
sqlx = { workspace = true }
@@ -143,7 +134,6 @@ unfurl_service = { path = "../unfurl_service" }
utoipa = { workspace = true, features = ["axum_extras", "chrono"] }
utoipa-swagger-ui = { workspace = true, features = ["axum"] }
url = { workspace = true }
-urlencoding = { workspace = true }
uuid = { workspace = true }
[dev-dependencies]
diff --git a/rust/cloud-storage/document_cognition_service/src/lib.rs b/rust/cloud-storage/document_cognition_service/src/lib.rs
deleted file mode 100644
index 39633b9812..0000000000
--- a/rust/cloud-storage/document_cognition_service/src/lib.rs
+++ /dev/null
@@ -1,2 +0,0 @@
-/// OAuth 2.1 proxy for the MCP server.
-pub mod mcp_oauth;
diff --git a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/handlers.rs b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/handlers.rs
deleted file mode 100644
index c66b94ca78..0000000000
--- a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/handlers.rs
+++ /dev/null
@@ -1,323 +0,0 @@
-use axum::{
- extract::{Query, State},
- response::{IntoResponse, Json, Redirect, Response},
-};
-use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
-use serde::{Deserialize, Serialize};
-use sha2::{Digest, Sha256};
-use std::time::{Duration, Instant};
-
-use super::state::OAuthState;
-
-// ── 1. Discovery ────────────────────────────────────────────────────────
-
-/// `GET /.well-known/oauth-authorization-server`
-pub async fn metadata(State(state): State<OAuthState>) -> Json<serde_json::Value> {
- tracing::debug!("oauth-authorization-server metadata requested");
- let base = &state.mcp_public_url;
- Json(serde_json::json!({
- "issuer": base,
- "authorization_endpoint": format!("{base}/authorize"),
- "token_endpoint": format!("{base}/token"),
- "registration_endpoint": format!("{base}/register"),
- "response_types_supported": ["code"],
- "grant_types_supported": ["authorization_code"],
- "code_challenge_methods_supported": ["S256"],
- }))
-}
-
-// ── 1b. Dynamic Client Registration (RFC 7591) ─────────────────────────
-
-/// `POST /register` — accepts a dynamic client registration request and returns
-/// a new client_id. Since we proxy all auth through FusionAuth and use PKCE,
-/// we don't need real client credentials — we just mint a unique client_id.
-pub async fn register(axum::Json(body): axum::Json<serde_json::Value>) -> Response {
- let client_id = uuid::Uuid::new_v4().to_string();
- let client_name = body
- .get("client_name")
- .and_then(|v| v.as_str())
- .unwrap_or("mcp-client");
-
- tracing::info!(%client_id, %client_name, "dynamic client registration");
-
- Json(serde_json::json!({
- "client_id": client_id,
- "client_name": client_name,
- "redirect_uris": body.get("redirect_uris").cloned().unwrap_or(serde_json::json!([])),
- "grant_types": ["authorization_code"],
- "response_types": ["code"],
- "token_endpoint_auth_method": "none",
- }))
- .into_response()
-}
-
-// ── 2. Authorize ────────────────────────────────────────────────────────
-
-#[derive(Deserialize)]
-pub struct AuthorizeParams {
- response_type: String,
- #[allow(dead_code)]
- client_id: String,
- redirect_uri: String,
- state: String,
- code_challenge: String,
- code_challenge_method: String,
- #[serde(default)]
- #[allow(dead_code)]
- scope: Option<String>,
-}
-
-/// Returns `true` if the redirect URI is acceptable.
-///
-/// We allow loopback addresses (with any port) and `http://localhost` variants,
-/// which covers MCP clients like Claude Desktop that spin up a local callback
-/// server. All other origins are rejected to prevent open-redirect attacks.
-fn is_allowed_redirect_uri(uri: &str) -> bool {
- let Ok(parsed) = url::Url::parse(uri) else {
- return false;
- };
-
- matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))
-}
-
-/// `GET /authorize` — validates params, stores the pending flow, then redirects
-/// to FusionAuth's `/oauth2/authorize` endpoint with the Google IDP hint. After
-/// the user logs in, FusionAuth redirects back to our `/oauth/callback` with an
-/// authorization code.
-pub async fn authorize(
- State(oauth): State<OAuthState>,
- Query(params): Query<AuthorizeParams>,
-) -> Response {
- if params.response_type != "code" {
- return (
- axum::http::StatusCode::BAD_REQUEST,
- "unsupported response_type",
- )
- .into_response();
- }
- if params.code_challenge_method != "S256" {
- return (
- axum::http::StatusCode::BAD_REQUEST,
- "unsupported code_challenge_method",
- )
- .into_response();
- }
- if !is_allowed_redirect_uri(&params.redirect_uri) {
- return (
- axum::http::StatusCode::BAD_REQUEST,
- "redirect_uri must be a loopback address",
- )
- .into_response();
- }
-
- // Generate a session ID to correlate the callback.
- let session_id = uuid::Uuid::new_v4().to_string();
- tracing::info!(%session_id, "starting OAuth authorize flow");
-
- oauth.pending.insert(
- session_id.clone(),
- super::state::PendingAuthFlow {
- code_challenge: params.code_challenge,
- client_state: params.state,
- client_redirect_uri: params.redirect_uri,
- expires_at: Instant::now() + Duration::from_secs(600),
- },
- );
-
- // Build the FusionAuth authorize URL with the Google IDP hint.
- // The session_id is threaded through FusionAuth's `state` parameter so we
- // can correlate the callback.
- let fusionauth_url = match oauth.fusionauth_client.construct_oauth2_authorize_url(
- &oauth.google_idp_id,
- None,
- Some(session_id),
- ) {
- Ok(url) => url,
- Err(e) => {
- tracing::error!(error=?e, "failed to construct FusionAuth authorize URL");
- return (
- axum::http::StatusCode::INTERNAL_SERVER_ERROR,
- "failed to construct authorize URL",
- )
- .into_response();
- }
- };
-
- Redirect::temporary(&fusionauth_url).into_response()
-}
-
-// ── 3. OAuth callback (FusionAuth → us via redirect) ─────────────────────
-
-#[derive(Deserialize)]
-pub struct CallbackParams {
- /// Authorization code from FusionAuth.
- code: String,
- /// Our session ID, threaded through FusionAuth's `state` parameter.
- state: Option<String>,
-}
-
-/// `GET /oauth/callback` — FusionAuth redirects here after the user logs in
-/// via Google. The `code` query param is a FusionAuth authorization code that
-/// we exchange for a JWT by calling FusionAuth's `POST /oauth2/token` endpoint.
-pub async fn oauth_callback(
- State(oauth): State<OAuthState>,
- Query(params): Query<CallbackParams>,
-) -> Response {
- // FusionAuth passes state back as a JSON string (since construct_oauth2_authorize_url
- // serializes it with serde_json). Strip the surrounding quotes.
- let session_id = match &params.state {
- Some(s) => s.trim_matches('"').to_string(),
- None => {
- tracing::warn!("no state parameter in FusionAuth callback");
- return (
- axum::http::StatusCode::BAD_REQUEST,
- "missing state parameter",
- )
- .into_response();
- }
- };
- tracing::info!(%session_id, pending_count = oauth.pending.len(), "oauth callback received");
-
- // Look up the pending flow.
- let pending = match oauth.pending.remove(&session_id) {
- Some((_, p)) => p,
- None => {
- tracing::warn!(%session_id, "no pending flow found for session");
- return (
- axum::http::StatusCode::BAD_REQUEST,
- "unknown or expired session",
- )
- .into_response();
- }
- };
-
- // Exchange the FusionAuth authorization code for a JWT via FusionAuth's
- // POST /oauth2/token endpoint.
- let (access_token, _refresh_token) = match oauth
- .fusionauth_client
- .complete_authorization_code_grant(&params.code)
- .await
- {
- Ok(tokens) => tokens,
- Err(e) => {
- tracing::error!(error=?e, "FusionAuth authorization code grant failed");
- return (
- axum::http::StatusCode::BAD_GATEWAY,
- "authorization code exchange failed",
- )
- .into_response();
- }
- };
-
- // Issue our own authorization code, storing the validated JWT.
- let our_code = uuid::Uuid::new_v4().to_string();
- oauth.codes.insert(
- our_code.clone(),
- super::state::IssuedCode {
- access_token,
- code_challenge: pending.code_challenge,
- redirect_uri: pending.client_redirect_uri.clone(),
- expires_at: Instant::now() + Duration::from_secs(300),
- },
- );
-
- // Redirect back to the client (Claude) with our code and the original state.
- let redirect_url = format!(
- "{}?code={}&state={}",
- pending.client_redirect_uri,
- urlencoding::encode(&our_code),
- urlencoding::encode(&pending.client_state),
- );
-
- Redirect::temporary(&redirect_url).into_response()
-}
-
-// ── 4. Token exchange ───────────────────────────────────────────────────
-
-#[derive(Deserialize)]
-pub struct TokenParams {
- grant_type: String,
- code: String,
- #[serde(default)]
- code_verifier: Option<String>,
- #[serde(default)]
- redirect_uri: Option<String>,
- #[serde(default)]
- #[allow(dead_code)]
- client_id: Option<String>,
-}
-
-#[derive(Serialize)]
-struct TokenResponse {
- access_token: String,
- token_type: &'static str,
-}
-
-/// `POST /token` — client exchanges our authorization code for an access token.
-pub async fn token(
- State(oauth): State<OAuthState>,
- axum::Form(params): axum::Form<TokenParams>,
-) -> Response {
- if params.grant_type != "authorization_code" {
- return (
- axum::http::StatusCode::BAD_REQUEST,
- "unsupported grant_type",
- )
- .into_response();
- }
-
- let issued = match oauth.codes.remove(&params.code) {
- Some((_, c)) => c,
- None => {
- return (
- axum::http::StatusCode::BAD_REQUEST,
- "invalid or expired code",
- )
- .into_response();
- }
- };
-
- if issued.expires_at < Instant::now() {
- return (axum::http::StatusCode::BAD_REQUEST, "code expired").into_response();
- }
-
- // OAuth 2.1 §4.1.3: if redirect_uri was in the authorization request,
- // it must match exactly in the token request.
- match &params.redirect_uri {
- Some(uri) if *uri != issued.redirect_uri => {
- return (axum::http::StatusCode::BAD_REQUEST, "redirect_uri mismatch").into_response();
- }
- None => {
- return (axum::http::StatusCode::BAD_REQUEST, "redirect_uri required").into_response();
- }
- _ => {}
- }
-
- // Validate PKCE: BASE64URL(SHA256(code_verifier)) must equal code_challenge.
- match params.code_verifier {
- Some(verifier) => {
- let digest = Sha256::digest(verifier.as_bytes());
- let computed = URL_SAFE_NO_PAD.encode(digest);
- if computed != issued.code_challenge {
- return (
- axum::http::StatusCode::BAD_REQUEST,
- "PKCE verification failed",
- )
- .into_response();
- }
- }
- None => {
- return (
- axum::http::StatusCode::BAD_REQUEST,
- "code_verifier required",
- )
- .into_response();
- }
- }
-
- Json(TokenResponse {
- access_token: issued.access_token,
- token_type: "Bearer",
- })
- .into_response()
-}
diff --git a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/middleware.rs b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/middleware.rs
deleted file mode 100644
index 6c599deddf..0000000000
--- a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/middleware.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-use axum::{
- body::Body,
- http::{Request, StatusCode},
- response::IntoResponse,
-};
-use macro_auth::middleware::decode_jwt::{JwtToken, JwtValidationArgs, handler};
-
-/// Validated user identity extracted from the Bearer token.
-#[derive(Clone, Debug)]
-pub struct McpUserIdentity {
- /// The macro user id (e.g. `macro|[email protected]`).
- pub user_id: String,
- /// The raw JWT string (some downstream code still needs it).
- pub jwt: String,
-}
-
-/// Axum middleware that validates the `Authorization: Bearer <token>` header
-/// and inserts an [`McpUserIdentity`] into request extensions.
-pub async fn validate_bearer(
- axum::extract::State(jwt_args): axum::extract::State<JwtValidationArgs>,
- mut request: Request<Body>,
- next: axum::middleware::Next,
-) -> axum::response::Response {
- let token = request
- .headers()
- .get(axum::http::header::AUTHORIZATION)
- .and_then(|v| v.to_str().ok())
- .and_then(|v| v.strip_prefix("Bearer "))
- .map(|s| s.to_owned());
-
- let Some(token) = token else {
- return StatusCode::UNAUTHORIZED.into_response();
- };
-
- let jwt_token = match handler(&jwt_args, &token) {
- Ok(t) => t,
- Err(e) => {
- tracing::warn!(error=?e, "MCP bearer token validation failed");
- return StatusCode::UNAUTHORIZED.into_response();
- }
- };
-
- let user_id = match &jwt_token {
- JwtToken::MacroAccessToken(t) => t.macro_user_id.clone(),
- JwtToken::MacroApiToken(t) => t.macro_user_id.clone(),
- };
-
- request.extensions_mut().insert(McpUserIdentity {
- user_id,
- jwt: token,
- });
-
- next.run(request).await
-}
diff --git a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/mod.rs b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/mod.rs
deleted file mode 100644
index f6b9fa2f06..0000000000
--- a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/mod.rs
+++ /dev/null
@@ -1,55 +0,0 @@
-//! OAuth 2.1 proxy for the MCP server.
-//!
-//! Exposes OAuth endpoints that Claude talks to, proxying the actual
-//! authentication to FusionAuth behind the scenes.
-
-pub mod handlers;
-pub mod middleware;
-pub mod state;
-pub mod tool_service;
-
-use axum::{Router, middleware as axum_mw, routing};
-use macro_auth::middleware::decode_jwt::JwtValidationArgs;
-use state::OAuthState;
-
-/// Health check handler for ALB.
-async fn health() -> &'static str {
- "ok"
-}
-
-/// Build the complete router for the MCP server: OAuth routes (unauthenticated)
-/// merged with the `/mcp` route (Bearer-authenticated).
-pub fn mcp_router<S>(oauth_state: OAuthState, jwt_args: JwtValidationArgs, mcp_service: S) -> Router
-where
- S: tower::Service<axum::http::Request<axum::body::Body>, Error = std::convert::Infallible>
- + Clone
- + Send
- + Sync
- + 'static,
- S::Response: axum::response::IntoResponse,
- S::Future: Send + 'static,
-{
- // OAuth routes — no auth required.
- let oauth_routes = Router::new()
- .route("/health", routing::get(health))
- .route(
- "/.well-known/oauth-authorization-server",
- routing::get(handlers::metadata),
- )
- .route("/authorize", routing::get(handlers::authorize))
- .route("/register", routing::post(handlers::register))
- .route("/oauth/callback", routing::get(handlers::oauth_callback))
- .route("/token", routing::post(handlers::token))
- .with_state(oauth_state);
-
- // MCP route — protected by Bearer token middleware.
- let mcp_route =
- Router::new()
- .nest_service("/mcp", mcp_service)
- .layer(axum_mw::from_fn_with_state(
- jwt_args,
- middleware::validate_bearer,
- ));
-
- oauth_routes.merge(mcp_route)
-}
diff --git a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/state.rs b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/state.rs
deleted file mode 100644
index 5ad92b68b2..0000000000
--- a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/state.rs
+++ /dev/null
@@ -1,60 +0,0 @@
-use dashmap::DashMap;
-use macro_auth::middleware::decode_jwt::JwtValidationArgs;
-use std::sync::Arc;
-use std::time::Instant;
-
-/// A pending OAuth authorization flow initiated by the client.
-#[derive(Clone)]
-pub struct PendingAuthFlow {
- /// PKCE S256 code challenge from the client.
- pub code_challenge: String,
- /// The client's original `state` parameter.
- pub client_state: String,
- /// Where to redirect back to the client with the authorization code.
- pub client_redirect_uri: String,
- /// When this flow expires (TTL ~10 min).
- pub expires_at: Instant,
-}
-
-/// An authorization code we issued, backed by a validated JWT.
-#[derive(Clone)]
-pub struct IssuedCode {
- /// The access token (JWT) obtained from FusionAuth.
- pub access_token: String,
- /// The original PKCE code challenge, for verification at token exchange.
- pub code_challenge: String,
- /// The `redirect_uri` used in the authorization request, for validation at
- /// token exchange per OAuth 2.1 §4.1.3.
- pub redirect_uri: String,
- /// When this code expires (TTL ~5 min).
- pub expires_at: Instant,
-}
-
-/// Shared state for the OAuth proxy.
-///
-/// The DashMaps are wrapped in `Arc` so that axum's state cloning shares the
-/// same underlying maps across all handlers.
-#[derive(Clone)]
-pub struct OAuthState {
- /// Pending authorization flows, keyed by session ID.
- pub pending: Arc<DashMap<String, PendingAuthFlow>>,
- /// Issued authorization codes, keyed by the code string.
- pub codes: Arc<DashMap<String, IssuedCode>>,
- /// JWT validation args (shared with the `/mcp` Bearer middleware).
- pub jwt_args: JwtValidationArgs,
- /// FusionAuth client for OAuth2 authorization code grant.
- pub fusionauth_client: Arc<fusionauth::FusionAuthClient>,
- /// The Google identity provider ID in FusionAuth, used as `idp_hint`.
- pub google_idp_id: String,
- /// Externally-reachable URL of this MCP server (e.g. `http://localhost:8090`).
- pub mcp_public_url: String,
-}
-
-impl OAuthState {
- /// Remove expired entries from both maps.
- pub fn cleanup_expired(&self) {
- let now = Instant::now();
- self.pending.retain(|_, v| v.expires_at > now);
- self.codes.retain(|_, v| v.expires_at > now);
- }
-}
diff --git a/rust/cloud-storage/fusionauth/src/oauth/mod.rs b/rust/cloud-storage/fusionauth/src/oauth/mod.rs
index a1f0699429..74450fd07c 100644
--- a/rust/cloud-storage/fusionauth/src/oauth/mod.rs
+++ b/rust/cloud-storage/fusionauth/src/oauth/mod.rs
@@ -1,3 +1,4 @@
+use serde::Serialize;
use std::borrow::Cow;
use crate::{
@@ -5,6 +6,19 @@ use crate::{
error::{FusionAuthClientError, GenericErrorResponse},
};
+#[derive(serde::Serialize, Debug)]
+#[serde(rename_all = "snake_case")]
+struct RefreshTokenGrantCompleteRequest<'a> {
+ /// The client id
+ pub client_id: Cow<'a, str>,
+ /// The client secret
+ pub client_secret: Cow<'a, str>,
+ /// The refresh token
+ pub refresh_token: Cow<'a, str>,
+ /// The grant type (should always be refresh_token)
+ pub grant_type: Cow<'a, str>,
+}
+
#[derive(serde::Serialize, serde::Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
struct AuthorizationCodeGrantCompleteRequest<'a> {
@@ -38,7 +52,7 @@ struct AuthorizationCodeGrantCompleteResponse<'a> {
async fn complete(
client: &UnauthedClient,
base_url: &str,
- request: AuthorizationCodeGrantCompleteRequest<'_>,
+ request: impl Serialize,
) -> Result<(String, String)> {
let body = serde_urlencoded::to_string(&request).map_err(|e| {
FusionAuthClientError::Generic(GenericErrorResponse {
@@ -112,4 +126,23 @@ impl FusionAuthClient {
)
.await
}
+
+ /// complete the OAuth2 Refresh token grant flow.
+ #[tracing::instrument(skip(self), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]
+ pub async fn complete_refresh_token_grant(
+ &self,
+ refresh_token: &str,
+ ) -> Result<(String, String)> {
+ complete(
+ &self.unauth_client,
+ &self.fusion_auth_base_url,
+ RefreshTokenGrantCompleteRequest {
+ client_id: Cow::Borrowed(&self.client_id),
+ client_secret: Cow::Borrowed(&self.client_secret),
+ refresh_token: Cow::Borrowed(refresh_token),
+ grant_type: Cow::Borrowed("refresh_token"),
+ },
+ )
+ .await
+ }
}
diff --git a/rust/cloud-storage/mcp_auth_proxy/Cargo.toml b/rust/cloud-storage/mcp_auth_proxy/Cargo.toml
new file mode 100644
index 0000000000..5220dba4f9
--- /dev/null
+++ b/rust/cloud-storage/mcp_auth_proxy/Cargo.toml
@@ -0,0 +1,34 @@
+[package]
+edition = "2024"
+name = "mcp_auth_proxy"
+publish = false
+readme = "README.md"
+version = "0.1.0"
+
+[features]
+default = ["inbound", "outbound"]
+inbound = [
+ "dep:axum",
+ "dep:macro_auth",
+ "dep:macro_user_id",
+ "dep:tower",
+]
+outbound = ["dep:fusionauth"]
+
+[dependencies]
+anyhow = { workspace = true }
+axum = { workspace = true, features = ["tower-log"], optional = true }
+base64 = { workspace = true }
+fusionauth = { path = "../fusionauth", optional = true }
+macro_auth = { path = "../macro_auth", optional = true }
+macro_user_id = { path = "../macro_user_id", optional = true }
+redis = { workspace = true, features = ["aio", "tokio-comp"] }
+serde = { workspace = true }
+serde_json = { workspace = true }
+sha2 = { workspace = true }
+thiserror = { workspace = true }
+tower = { workspace = true, features = ["util"], optional = true }
+tracing = { workspace = true }
+url = { workspace = true }
+urlencoding = { workspace = true }
+uuid = { workspace = true }
diff --git a/rust/cloud-storage/mcp_auth_proxy/README.md b/rust/cloud-storage/mcp_auth_proxy/README.md
new file mode 100644
index 0000000000..75df9fc2d9
--- /dev/null
+++ b/rust/cloud-storage/mcp_auth_proxy/README.md
@@ -0,0 +1,6 @@
+The `mcp_service` acts as proxy to the auth server.
+
+I believe this is needed because FusionAuth doesn't support DCR
+
+(Official Docs)[https://modelcontextprotocol.io/docs/tutorials/security/authorization]
+(Useful fusionauth article)[https://fusionauth.io/articles/ai/mcp-connecting-software-ai]
diff --git a/rust/cloud-storage/mcp_auth_proxy/src/domain.rs b/rust/cloud-storage/mcp_auth_proxy/src/domain.rs
new file mode 100644
index 0000000000..2540aa7a65
--- /dev/null
+++ b/rust/cloud-storage/mcp_auth_proxy/src/domain.rs
@@ -0,0 +1,8 @@
+//! Domain logic for the MCP OAuth broker.
+
+/// Domain models for broker-managed OAuth state and request payloads.
+pub mod models;
+/// Domain port traits for upstream OAuth providers.
+pub mod ports;
+/// Domain service for the MCP OAuth broker.
+pub mod service;
diff --git a/rust/cloud-storage/mcp_auth_proxy/src/domain/models.rs b/rust/cloud-storage/mcp_auth_proxy/src/domain/models.rs
new file mode 100644
index 0000000000..bcbeef45a2
--- /dev/null
+++ b/rust/cloud-storage/mcp_auth_proxy/src/domain/models.rs
@@ -0,0 +1,176 @@
+use serde::{Deserialize, Serialize};
+use std::fmt;
+
+/// Upstream OAuth access token.
+#[derive(Clone, Deserialize, Eq, Hash, PartialEq, Serialize)]
+#[serde(transparent)]
+pub struct AccessToken(String);
+
+impl AccessToken {
+ /// Returns the token as a string slice.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl AsRef<str> for AccessToken {
+ fn as_ref(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl From<String> for AccessToken {
+ fn from(value: String) -> Self {
+ Self(value)
+ }
+}
+
+impl From<&str> for AccessToken {
+ fn from(value: &str) -> Self {
+ Self(value.to_owned())
+ }
+}
+
+impl From<AccessToken> for String {
+ fn from(value: AccessToken) -> Self {
+ value.0
+ }
+}
+
+impl fmt::Debug for AccessToken {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("AccessToken([REDACTED])")
+ }
+}
+
+/// Upstream OAuth refresh token.
+#[derive(Clone, Deserialize, Eq, Hash, PartialEq, Serialize)]
+#[serde(transparent)]
+pub struct RefreshToken(String);
+
+impl RefreshToken {
+ /// Returns the token as a string slice.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl AsRef<str> for RefreshToken {
+ fn as_ref(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl From<String> for RefreshToken {
+ fn from(value: String) -> Self {
+ Self(value)
+ }
+}
+
+impl From<&str> for RefreshToken {
+ fn from(value: &str) -> Self {
+ Self(value.to_owned())
+ }
+}
+
+impl From<RefreshToken> for String {
+ fn from(value: RefreshToken) -> Self {
+ value.0
+ }
+}
+
+impl fmt::Debug for RefreshToken {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("RefreshToken([REDACTED])")
+ }
+}
+
+/// A pending OAuth authorization flow initiated by the client.
+#[derive(Clone)]
+pub struct PendingAuthorization {
+ /// PKCE S256 code challenge from the client.
+ pub code_challenge: String,
+ /// The client's original `state` parameter.
+ pub client_state: String,
+ /// Where to redirect back to the client with the authorization code.
+ pub client_redirect_uri: String,
+}
+
+/// An authorization code issued by this broker and backed by an upstream token.
+#[derive(Clone)]
+pub struct IssuedAuthorizationCode {
+ /// The access token obtained from the upstream provider.
+ pub access_token: AccessToken,
+ /// The refresh token obtained from the upstream provider.
+ pub refresh_token: RefreshToken,
+ /// The original PKCE code challenge, for verification at token exchange.
+ pub code_challenge: String,
+ /// The redirect URI from the authorization request, used for exact-match
+ /// validation during token exchange.
+ pub redirect_uri: String,
+}
+
+/// OAuth authorize request from the MCP client.
+#[derive(Deserialize)]
+pub struct AuthorizeRequest {
+ /// Expected to be `code`.
+ pub response_type: String,
+ /// Dynamically registered client id.
+ #[allow(dead_code)]
+ pub client_id: String,
+ /// Loopback callback URI owned by the MCP client.
+ pub redirect_uri: String,
+ /// Opaque state from the client.
+ pub state: String,
+ /// PKCE code challenge.
+ pub code_challenge: String,
+ /// Expected to be `S256`.
+ pub code_challenge_method: String,
+ /// Optional requested scopes.
+ #[serde(default)]
+ #[allow(dead_code)]
+ pub scope: Option<String>,
+}
+
+/// OAuth callback request from the upstream auth server.
+#[derive(Deserialize)]
+pub struct CallbackRequest {
+ /// Authorization code from the upstream auth server.
+ pub code: String,
+ /// Broker session ID threaded through the upstream `state`.
+ pub state: Option<String>,
+}
+
+/// OAuth token request from the MCP client.
+#[derive(Deserialize)]
+pub struct TokenRequest {
+ /// Supported values are `authorization_code` and `refresh_token`.
+ pub grant_type: String,
+ /// Authorization code issued by this broker.
+ #[serde(default)]
+ pub code: Option<String>,
+ /// PKCE verifier.
+ #[serde(default)]
+ pub code_verifier: Option<String>,
+ /// Refresh token returned by a prior token exchange.
+ #[serde(default)]
+ pub refresh_token: Option<RefreshToken>,
+ /// Redirect URI from the original authorization request.
+ #[serde(default)]
+ pub redirect_uri: Option<String>,
+ /// Optional client id.
+ #[serde(default)]
+ #[allow(dead_code)]
+ pub client_id: Option<String>,
+}
+
+/// OAuth token response returned to the MCP client.
+#[derive(Serialize)]
+pub struct TokenResponse {
+ /// Bearer access token.
+ pub access_token: AccessToken,
+ /// Refresh token for subsequent token refresh.
+ pub refresh_token: RefreshToken,
+ /// OAuth token type.
+ pub token_type: &'static str,
+}
diff --git a/rust/cloud-storage/mcp_auth_proxy/src/domain/ports.rs b/rust/cloud-storage/mcp_auth_proxy/src/domain/ports.rs
new file mode 100644
index 0000000000..240d133e68
--- /dev/null
+++ b/rust/cloud-storage/mcp_auth_proxy/src/domain/ports.rs
@@ -0,0 +1,21 @@
+//! Domain ports for upstream OAuth providers.
+
+use std::{future::Future, pin::Pin};
+
+use super::models::{AccessToken, RefreshToken};
+
+/// Boxed future returning an access/refresh token pair.
+pub type TokenPairFuture<'a> =
+ Pin<Box<dyn Future<Output = anyhow::Result<(AccessToken, RefreshToken)>> + Send + 'a>>;
+
+/// Upstream OAuth provider used by the broker.
+pub trait OAuthProvider: Send + Sync {
+ /// Builds the upstream authorize URL for a broker session.
+ fn construct_authorize_url(&self, state: &str) -> anyhow::Result<String>;
+
+ /// Exchanges an upstream authorization code for tokens.
+ fn exchange_authorization_code<'a>(&'a self, code: &'a str) -> TokenPairFuture<'a>;
+
+ /// Refreshes an upstream access token using the refresh token grant.
+ fn refresh_access_token<'a>(&'a self, refresh_token: &'a RefreshToken) -> TokenPairFuture<'a>;
+}
diff --git a/rust/cloud-storage/mcp_auth_proxy/src/domain/service.rs b/rust/cloud-storage/mcp_auth_proxy/src/domain/service.rs
new file mode 100644
index 0000000000..0bb08eca02
--- /dev/null
+++ b/rust/cloud-storage/mcp_auth_proxy/src/domain/service.rs
@@ -0,0 +1,410 @@
+//! Service implementation for the MCP OAuth broker.
+
+use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
+use sha2::{Digest, Sha256};
+use std::{future::Future, sync::Arc, time::Duration};
+
+use super::{
+ models::{
+ AuthorizeRequest, CallbackRequest, IssuedAuthorizationCode, PendingAuthorization,
+ TokenRequest, TokenResponse,
+ },
+ ports::OAuthProvider,
+};
+
+pub(crate) const PENDING_AUTH_TTL: Duration = Duration::from_secs(10 * 60);
+pub(crate) const AUTHORIZATION_CODE_TTL: Duration = Duration::from_secs(5 * 60);
+
+/// Domain interface for the MCP OAuth broker.
+pub trait McpAuthProxyService: Clone + Send + Sync + 'static {
+ /// Returns OAuth authorization server discovery metadata.
+ fn authorization_server_metadata(&self) -> serde_json::Value;
+ /// Returns protected-resource metadata for MCP clients.
+ fn protected_resource_metadata(&self) -> serde_json::Value;
+ /// Registers a public MCP client dynamically.
+ fn register_client(&self, body: serde_json::Value) -> serde_json::Value;
+ /// Starts an OAuth authorization flow and returns the upstream authorize URL.
+ fn start_authorization(
+ &self,
+ params: AuthorizeRequest,
+ ) -> impl Future<Output = Result<String, StartAuthorizationError>> + Send;
+ /// Completes the upstream callback and returns the loopback redirect URL.
+ fn complete_callback(
+ &self,
+ params: CallbackRequest,
+ ) -> impl Future<Output = Result<String, CompleteCallbackError>> + Send;
+ /// Exchanges a broker-issued code or refresh token for bearer credentials.
+ fn exchange_token(
+ &self,
+ params: TokenRequest,
+ ) -> impl Future<Output = Result<TokenResponse, TokenExchangeError>> + Send;
+ /// Removes expired broker state when required by the backing store.
+ fn cleanup_expired(&self) -> impl Future<Output = anyhow::Result<()>> + Send;
+}
+
+/// Storage for short-lived in-flight OAuth handshake state.
+pub trait InflightAuthStore: Send + Sync {
+ /// Inserts a pending authorization flow keyed by broker session ID.
+ fn insert_pending(
+ &self,
+ session_id: &str,
+ pending: PendingAuthorization,
+ ) -> impl Future<Output = anyhow::Result<()>> + Send;
+
+ /// Removes and returns a pending authorization flow, if present.
+ fn take_pending(
+ &self,
+ session_id: &str,
+ ) -> impl Future<Output = anyhow::Result<Option<PendingAuthorization>>> + Send;
+
+ /// Inserts a broker-issued authorization code.
+ fn insert_issued(
+ &self,
+ code: &str,
+ issued: IssuedAuthorizationCode,
+ ) -> impl Future<Output = anyhow::Result<()>> + Send;
+
+ /// Removes and returns a broker-issued authorization code, if present.
+ fn take_issued(
+ &self,
+ code: &str,
+ ) -> impl Future<Output = anyhow::Result<Option<IssuedAuthorizationCode>>> + Send;
+
+ /// Removes expired entries when the backing store requires manual cleanup.
+ fn cleanup_expired(&self) -> impl Future<Output = anyhow::Result<()>> + Send;
+}
+
+/// Domain service backing the MCP OAuth broker.
+pub struct McpAuthProxyServiceImpl<I> {
+ inflight_auth: Arc<I>,
+ oauth_provider: Arc<dyn OAuthProvider>,
+ public_url: String,
+}
+
+impl<I> Clone for McpAuthProxyServiceImpl<I> {
+ fn clone(&self) -> Self {
+ Self {
+ inflight_auth: Arc::clone(&self.inflight_auth),
+ oauth_provider: Arc::clone(&self.oauth_provider),
+ public_url: self.public_url.clone(),
+ }
+ }
+}
+
+impl<I> McpAuthProxyServiceImpl<I>
+where
+ I: InflightAuthStore + 'static,
+{
+ /// Creates a new auth proxy service backed by an upstream OAuth provider.
+ pub fn new(
+ public_url: String,
+ inflight_auth: Arc<I>,
+ oauth_provider: Arc<dyn OAuthProvider>,
+ ) -> Self {
+ Self {
+ inflight_auth,
+ oauth_provider,
+ public_url,
+ }
+ }
+
+ async fn refresh_token_exchange(
+ &self,
+ params: TokenRequest,
+ ) -> Result<TokenResponse, TokenExchangeError> {
+ let refresh_token = params
+ .refresh_token
+ .ok_or(TokenExchangeError::RefreshTokenRequired)?;
+
+ let (access_token, new_refresh_token) = self
+ .oauth_provider
+ .refresh_access_token(&refresh_token)
+ .await
+ .map_err(TokenExchangeError::RefreshFailed)?;
+
+ Ok(TokenResponse {
+ access_token,
+ refresh_token: new_refresh_token,
+ token_type: "Bearer",
+ })
+ }
+
+ async fn exchange_authorization_code_token(
+ &self,
+ params: TokenRequest,
+ ) -> Result<TokenResponse, TokenExchangeError> {
+ let issued = self
+ .inflight_auth
+ .take_issued(
+ params
+ .code
+ .as_deref()
+ .ok_or(TokenExchangeError::CodeRequired)?,
+ )
+ .await
+ .map_err(TokenExchangeError::InflightStore)?
+ .ok_or(TokenExchangeError::InvalidOrExpiredCode)?;
+
+ match &params.redirect_uri {
+ Some(uri) if *uri != issued.redirect_uri => {
+ return Err(TokenExchangeError::RedirectUriMismatch);
+ }
+ None => return Err(TokenExchangeError::RedirectUriRequired),
+ _ => {}
+ }
+
+ match params.code_verifier {
+ Some(verifier) => {
+ let digest = Sha256::digest(verifier.as_bytes());
+ let computed = URL_SAFE_NO_PAD.encode(digest);
+ if computed != issued.code_challenge {
+ return Err(TokenExchangeError::PkceVerificationFailed);
+ }
+ }
+ None => return Err(TokenExchangeError::CodeVerifierRequired),
+ }
+
+ Ok(TokenResponse {
+ access_token: issued.access_token,
+ refresh_token: issued.refresh_token,
+ token_type: "Bearer",
+ })
+ }
+}
+
+impl<I> McpAuthProxyService for McpAuthProxyServiceImpl<I>
+where
+ I: InflightAuthStore + 'static,
+{
+ /// Authorization server discovery metadata.
+ fn authorization_server_metadata(&self) -> serde_json::Value {
+ tracing::debug!("oauth-authorization-server metadata requested");
+ let base = &self.public_url;
+ serde_json::json!({
+ "issuer": base,
+ "authorization_endpoint": format!("{base}/authorize"),
+ "token_endpoint": format!("{base}/token"),
+ "registration_endpoint": format!("{base}/register"),
+ "response_types_supported": ["code"],
+ "grant_types_supported": ["authorization_code", "refresh_token"],
+ "code_challenge_methods_supported": ["S256"],
+ })
+ }
+
+ /// Protected resource metadata for MCP clients.
+ fn protected_resource_metadata(&self) -> serde_json::Value {
+ tracing::debug!("oauth-protected-resource metadata requested");
+ let base = &self.public_url;
+ serde_json::json!({
+ "authorization_server": base,
+ "authorization_servers": [base],
+ })
+ }
+
+ /// Handles dynamic client registration for public MCP clients.
+ fn register_client(&self, body: serde_json::Value) -> serde_json::Value {
+ let client_id = uuid::Uuid::new_v4().to_string();
+ let client_name = body
+ .get("client_name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("mcp-client");
+
+ tracing::info!(%client_id, %client_name, "dynamic client registration");
+
+ serde_json::json!({
+ "client_id": client_id,
+ "client_name": client_name,
+ "redirect_uris": body.get("redirect_uris").cloned().unwrap_or(serde_json::json!([])),
+ "grant_types": ["authorization_code", "refresh_token"],
+ "response_types": ["code"],
+ "token_endpoint_auth_method": "none",
+ })
+ }
+
+ /// Starts an OAuth authorization flow and returns the upstream authorize URL.
+ fn start_authorization(
+ &self,
+ params: AuthorizeRequest,
+ ) -> impl Future<Output = Result<String, StartAuthorizationError>> + Send {
+ let service = self.clone();
+ async move {
+ if params.response_type != "code" {
+ return Err(StartAuthorizationError::UnsupportedResponseType);
+ }
+ if params.code_challenge_method != "S256" {
+ return Err(StartAuthorizationError::UnsupportedCodeChallengeMethod);
+ }
+ if !is_allowed_redirect_uri(&params.redirect_uri) {
+ return Err(StartAuthorizationError::InvalidRedirectUri);
+ }
+
+ let session_id = uuid::Uuid::new_v4().to_string();
+ tracing::info!(%session_id, "starting OAuth authorize flow");
+
+ service
+ .inflight_auth
+ .insert_pending(
+ &session_id,
+ PendingAuthorization {
+ code_challenge: params.code_challenge,
+ client_state: params.state,
+ client_redirect_uri: params.redirect_uri,
+ },
+ )
+ .await
+ .map_err(StartAuthorizationError::InflightStore)?;
+
+ service
+ .oauth_provider
+ .construct_authorize_url(&session_id)
+ .map_err(StartAuthorizationError::ConstructAuthorizeUrl)
+ }
+ }
+
+ /// Completes the upstream OAuth callback and returns the redirect URL for
+ /// the MCP client loopback callback.
+ async fn complete_callback(
+ &self,
+ params: CallbackRequest,
+ ) -> Result<String, CompleteCallbackError> {
+ let session_id = params
+ .state
+ .as_deref()
+ .map(|state| state.trim_matches('"').to_string())
+ .ok_or(CompleteCallbackError::MissingState)?;
+
+ tracing::info!(%session_id, "oauth callback received");
+
+ let pending = self
+ .inflight_auth
+ .take_pending(&session_id)
+ .await
+ .map_err(CompleteCallbackError::InflightStore)?
+ .ok_or(CompleteCallbackError::UnknownOrExpiredSession)?;
+
+ let (access_token, refresh_token) = self
+ .oauth_provider
+ .exchange_authorization_code(&params.code)
+ .await
+ .map_err(CompleteCallbackError::AuthorizationCodeExchangeFailed)?;
+
+ let issued_code = uuid::Uuid::new_v4().to_string();
+ self.inflight_auth
+ .insert_issued(
+ &issued_code,
+ IssuedAuthorizationCode {
+ access_token,
+ refresh_token,
+ code_challenge: pending.code_challenge,
+ redirect_uri: pending.client_redirect_uri.clone(),
+ },
+ )
+ .await
+ .map_err(CompleteCallbackError::InflightStore)?;
+
+ Ok(format!(
+ "{}?code={}&state={}",
+ pending.client_redirect_uri,
+ urlencoding::encode(&issued_code),
+ urlencoding::encode(&pending.client_state),
+ ))
+ }
+
+ /// Exchanges a broker-issued authorization code for an upstream bearer
+ /// token after verifying redirect URI and PKCE.
+ async fn exchange_token(
+ &self,
+ params: TokenRequest,
+ ) -> Result<TokenResponse, TokenExchangeError> {
+ match params.grant_type.as_str() {
+ "authorization_code" => self.exchange_authorization_code_token(params).await,
+ "refresh_token" => self.refresh_token_exchange(params).await,
+ _ => Err(TokenExchangeError::UnsupportedGrantType),
+ }
+ }
+
+ /// Removes expired pending sessions and broker-issued codes.
+ async fn cleanup_expired(&self) -> anyhow::Result<()> {
+ self.inflight_auth.cleanup_expired().await
+ }
+}
+
+fn is_allowed_redirect_uri(uri: &str) -> bool {
+ let Ok(parsed) = url::Url::parse(uri) else {
+ return false;
+ };
+
+ matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))
+}
+
+/// Errors returned when starting authorization.
+#[derive(Debug, thiserror::Error)]
+pub enum StartAuthorizationError {
+ /// Only authorization code flows are supported.
+ #[error("unsupported response_type")]
+ UnsupportedResponseType,
+ /// Only S256 PKCE is supported.
+ #[error("unsupported code_challenge_method")]
+ UnsupportedCodeChallengeMethod,
+ /// Only loopback redirect URIs are allowed.
+ #[error("redirect_uri must be a loopback address")]
+ InvalidRedirectUri,
+ /// Inflight auth state could not be persisted.
+ #[error("failed to persist inflight auth state")]
+ InflightStore(anyhow::Error),
+ /// Upstream authorize URL construction failed.
+ #[error("failed to construct authorize URL")]
+ ConstructAuthorizeUrl(anyhow::Error),
+}
+
+/// Errors returned when handling the upstream callback.
+#[derive(Debug, thiserror::Error)]
+pub enum CompleteCallbackError {
+ /// Upstream callback omitted state.
+ #[error("missing state parameter")]
+ MissingState,
+ /// Pending broker session was missing or expired.
+ #[error("unknown or expired session")]
+ UnknownOrExpiredSession,
+ /// Inflight auth state could not be loaded or updated.
+ #[error("failed to access inflight auth state")]
+ InflightStore(anyhow::Error),
+ /// Upstream code exchange failed.
+ #[error("authorization code exchange failed")]
+ AuthorizationCodeExchangeFailed(anyhow::Error),
+}
+
+/// Errors returned when exchanging a broker-issued code for a bearer token.
+#[derive(Debug, thiserror::Error)]
+pub enum TokenExchangeError {
+ /// Only authorization code exchanges are supported.
+ #[error("unsupported grant_type")]
+ UnsupportedGrantType,
+ /// Authorization code is required for authorization_code grants.
+ #[error("code required")]
+ CodeRequired,
+ /// Broker-issued code was missing or already used.
+ #[error("invalid or expired code")]
+ InvalidOrExpiredCode,
+ /// Redirect URI did not match the authorization request.
+ #[error("redirect_uri mismatch")]
+ RedirectUriMismatch,
+ /// Redirect URI must be provided for token exchange.
+ #[error("redirect_uri required")]
+ RedirectUriRequired,
+ /// PKCE verifier was missing.
+ #[error("code_verifier required")]
+ CodeVerifierRequired,
+ /// PKCE verification failed.
+ #[error("PKCE verification failed")]
+ PkceVerificationFailed,
+ /// Refresh token is required for refresh_token grants.
+ #[error("refresh_token required")]
+ RefreshTokenRequired,
+ /// Inflight auth state could not be loaded or updated.
+ #[error("failed to access inflight auth state")]
+ InflightStore(anyhow::Error),
+ /// Upstream refresh failed.
+ #[error("refresh token exchange failed")]
+ RefreshFailed(anyhow::Error),
+}
diff --git a/rust/cloud-storage/mcp_auth_proxy/src/inbound.rs b/rust/cloud-storage/mcp_auth_proxy/src/inbound.rs
new file mode 100644
index 0000000000..f76c2e5f6b
--- /dev/null
+++ b/rust/cloud-storage/mcp_auth_proxy/src/inbound.rs
@@ -0,0 +1,6 @@
+//! Inbound adapters for the MCP OAuth broker.
+
+/// Axum router for the MCP OAuth broker.
+pub mod axum_router;
+/// Bearer token middleware for the protected MCP endpoint.
+pub mod middleware;
diff --git a/rust/cloud-storage/mcp_auth_proxy/src/inbound/axum_router.rs b/rust/cloud-storage/mcp_auth_proxy/src/inbound/axum_router.rs
new file mode 100644
index 0000000000..da86f0bb13
--- /dev/null
+++ b/rust/cloud-storage/mcp_auth_proxy/src/inbound/axum_router.rs
@@ -0,0 +1,239 @@
+//! Axum router for the MCP OAuth broker.
+
+use axum::{
+ Router,
+ extract::{Query, State},
+ middleware as axum_mw,
+ response::{IntoResponse, Json, Redirect, Response},
+ routing,
+};
+use macro_auth::middleware::decode_jwt::JwtValidationArgs;
+
+use crate::domain::{
+ models::{AuthorizeRequest, CallbackRequest, TokenRequest},
+ service::{
+ CompleteCallbackError, InflightAuthStore, McpAuthProxyService, McpAuthProxyServiceImpl,
+ StartAuthorizationError, TokenExchangeError,
+ },
+};
+
+/// Health check handler for ALB.
+async fn health() -> &'static str {
+ "ok"
+}
+
+async fn authorization_server_metadata<I: InflightAuthStore + 'static>(
+ State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,
+) -> Json<serde_json::Value> {
+ Json(auth_proxy.authorization_server_metadata())
+}
+
+async fn protected_resource_metadata<I: InflightAuthStore + 'static>(
+ State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,
+) -> Json<serde_json::Value> {
+ Json(auth_proxy.protected_resource_metadata())
+}
+
+async fn register<I: InflightAuthStore + 'static>(
+ State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,
+ axum::Json(body): axum::Json<serde_json::Value>,
+) -> Json<serde_json::Value> {
+ Json(auth_proxy.register_client(body))
+}
+
+async fn authorize<I: InflightAuthStore + 'static>(
+ State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,
+ Query(params): Query<AuthorizeRequest>,
+) -> Response {
+ match auth_proxy.start_authorization(params).await {
+ Ok(url) => Redirect::temporary(&url).into_response(),
+ Err(StartAuthorizationError::UnsupportedResponseType) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "unsupported response_type",
+ )
+ .into_response(),
+ Err(StartAuthorizationError::UnsupportedCodeChallengeMethod) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "unsupported code_challenge_method",
+ )
+ .into_response(),
+ Err(StartAuthorizationError::InvalidRedirectUri) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "redirect_uri must be a loopback address",
+ )
+ .into_response(),
+ Err(StartAuthorizationError::InflightStore(error)) => {
+ tracing::error!(error=?error, "failed to persist inflight auth state");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to persist inflight auth state",
+ )
+ .into_response()
+ }
+ Err(StartAuthorizationError::ConstructAuthorizeUrl(error)) => {
+ tracing::error!(error=?error, "failed to construct upstream authorize URL");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to construct authorize URL",
+ )
+ .into_response()
+ }
+ }
+}
+
+async fn oauth_callback<I: InflightAuthStore + 'static>(
+ State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,
+ Query(params): Query<CallbackRequest>,
+) -> Response {
+ match auth_proxy.complete_callback(params).await {
+ Ok(url) => Redirect::temporary(&url).into_response(),
+ Err(CompleteCallbackError::MissingState) => {
+ tracing::warn!("no state parameter in upstream OAuth callback");
+ (
+ axum::http::StatusCode::BAD_REQUEST,
+ "missing state parameter",
+ )
+ .into_response()
+ }
+ Err(CompleteCallbackError::UnknownOrExpiredSession) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "unknown or expired session",
+ )
+ .into_response(),
+ Err(CompleteCallbackError::InflightStore(error)) => {
+ tracing::error!(error=?error, "failed to access inflight auth state");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to access inflight auth state",
+ )
+ .into_response()
+ }
+ Err(CompleteCallbackError::AuthorizationCodeExchangeFailed(error)) => {
+ tracing::error!(error=?error, "upstream authorization code grant failed");
+ (
+ axum::http::StatusCode::BAD_GATEWAY,
+ "authorization code exchange failed",
+ )
+ .into_response()
+ }
+ }
+}
+
+async fn token<I: InflightAuthStore + 'static>(
+ State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,
+ axum::Form(params): axum::Form<TokenRequest>,
+) -> Response {
+ match auth_proxy.exchange_token(params).await {
+ Ok(response) => Json(response).into_response(),
+ Err(TokenExchangeError::UnsupportedGrantType) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "unsupported grant_type",
+ )
+ .into_response(),
+ Err(TokenExchangeError::CodeRequired) => {
+ (axum::http::StatusCode::BAD_REQUEST, "code required").into_response()
+ }
+ Err(TokenExchangeError::InvalidOrExpiredCode) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "invalid or expired code",
+ )
+ .into_response(),
+ Err(TokenExchangeError::RedirectUriMismatch) => {
+ (axum::http::StatusCode::BAD_REQUEST, "redirect_uri mismatch").into_response()
+ }
+ Err(TokenExchangeError::RedirectUriRequired) => {
+ (axum::http::StatusCode::BAD_REQUEST, "redirect_uri required").into_response()
+ }
+ Err(TokenExchangeError::CodeVerifierRequired) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "code_verifier required",
+ )
+ .into_response(),
+ Err(TokenExchangeError::PkceVerificationFailed) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "PKCE verification failed",
+ )
+ .into_response(),
+ Err(TokenExchangeError::RefreshTokenRequired) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "refresh_token required",
+ )
+ .into_response(),
+ Err(TokenExchangeError::InflightStore(error)) => {
+ tracing::error!(error=?error, "failed to access inflight auth state");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to access inflight auth state",
+ )
+ .into_response()
+ }
+ Err(TokenExchangeError::RefreshFailed(error)) => {
+ tracing::error!(error=?error, "upstream refresh token exchange failed");
+ (
+ axum::http::StatusCode::BAD_GATEWAY,
+ "refresh token exchange failed",
+ )
+ .into_response()
+ }
+ }
+}
+
+/// Builds the complete MCP router: unauthenticated OAuth broker routes plus
+/// the Bearer-protected `/mcp` service route.
+pub fn mcp_router<I, S>(
+ auth_proxy: McpAuthProxyServiceImpl<I>,
+ jwt_args: JwtValidationArgs,
+ mcp_service: S,
+) -> Router
+where
+ I: InflightAuthStore + Clone + Send + Sync + 'static,
+ S: tower::Service<axum::http::Request<axum::body::Body>, Error = std::convert::Infallible>
+ + Clone
+ + Send
+ + Sync
+ + 'static,
+ S::Response: axum::response::IntoResponse,
+ S::Future: Send + 'static,
+{
+ let oauth_routes = Router::new()
+ .route("/health", routing::get(health))
+ .route(
+ "/.well-known/oauth-protected-resource",
+ routing::get(protected_resource_metadata),
+ )
+ .route(
+ "/.well-known/oauth-protected-resource/mcp",
+ routing::get(protected_resource_metadata),
+ )
+ .route(
+ "/mcp/.well-known/oauth-protected-resource",
+ routing::get(protected_resource_metadata),
+ )
+ .route(
+ "/.well-known/oauth-authorization-server",
+ routing::get(authorization_server_metadata),
+ )
+ .route(
+ "/.well-known/oauth-authorization-server/mcp",
+ routing::get(authorization_server_metadata),
+ )
+ .route(
+ "/mcp/.well-known/oauth-authorization-server",
+ routing::get(authorization_server_metadata),
+ )
+ .route("/authorize", routing::get(authorize))
+ .route("/register", routing::post(register))
+ .route("/oauth/callback", routing::get(oauth_callback))
+ .route("/token", routing::post(token))
+ .with_state(auth_proxy);
+
+ let mcp_route =
+ Router::new()
+ .nest_service("/mcp", mcp_service)
+ .layer(axum_mw::from_fn_with_state(
+ jwt_args,
+ super::middleware::validate_bearer,
+ ));
+
+ oauth_routes.merge(mcp_route)
+}
diff --git a/rust/cloud-storage/mcp_auth_proxy/src/inbound/middleware.rs b/rust/cloud-storage/mcp_auth_proxy/src/inbound/middleware.rs
new file mode 100644
index 0000000000..deea0fafed
--- /dev/null
+++ b/rust/cloud-storage/mcp_auth_proxy/src/inbound/middleware.rs
@@ -0,0 +1,109 @@
+//! Bearer token middleware for the protected MCP endpoint.
+
+use axum::{
+ body::Body,
+ http::{
+ Request, Response, StatusCode, Uri,
+ header::{HeaderValue, WWW_AUTHENTICATE},
+ },
+};
+use macro_auth::middleware::decode_jwt::{JwtToken, JwtValidationArgs, handler};
+use macro_user_id::user_id::MacroUserIdStr;
+
+const RESOURCE_METADATA_PATH: &str = "/.well-known/oauth-protected-resource/mcp";
+
+fn absolute_resource_metadata_url(request: &Request<Body>) -> String {
+ let scheme = request
+ .headers()
+ .get("x-forwarded-proto")
+ .and_then(|value| value.to_str().ok())
+ .unwrap_or("http");
+ let authority = request
+ .headers()
+ .get(axum::http::header::HOST)
+ .and_then(|value| value.to_str().ok())
+ .or_else(|| {
+ request
+ .uri()
+ .authority()
+ .map(|authority| authority.as_str())
+ })
+ .unwrap_or("localhost");
+
+ let mut uri = Uri::builder()
+ .scheme(scheme)
+ .authority(authority)
+ .path_and_query(RESOURCE_METADATA_PATH)
+ .build()
+ .expect("valid resource metadata uri")
+ .to_string();
+
+ if !uri.starts_with("http://") && !uri.starts_with("https://") {
+ uri = format!("{scheme}://{authority}{RESOURCE_METADATA_PATH}");
+ }
+
+ uri
+}
+
+fn unauthorized_response(request: &Request<Body>, error: Option<&str>) -> Response<Body> {
+ let resource_metadata = absolute_resource_metadata_url(request);
+ let challenge = match error {
+ Some(error) => {
+ format!(r#"Bearer error="{error}", resource_metadata="{resource_metadata}""#)
+ }
+ None => format!(r#"Bearer resource_metadata="{resource_metadata}""#),
+ };
+
+ let mut response = Response::new(Body::empty());
+ *response.status_mut() = StatusCode::UNAUTHORIZED;
+ response.headers_mut().insert(
+ WWW_AUTHENTICATE,
+ HeaderValue::from_str(&challenge).expect("valid WWW-Authenticate header"),
+ );
+ response
+}
+
+/// Validates `Authorization: Bearer <token>` and stores the authenticated
+/// [`MacroUserIdStr`] in the request extensions.
+pub async fn validate_bearer(
+ axum::extract::State(jwt_args): axum::extract::State<JwtValidationArgs>,
+ mut request: Request<Body>,
+ next: axum::middleware::Next,
+) -> axum::response::Response {
+ let token = request
+ .headers()
+ .get(axum::http::header::AUTHORIZATION)
+ .and_then(|value| value.to_str().ok())
+ .and_then(|value| value.strip_prefix("Bearer "))
+ .map(str::to_owned);
+
+ let Some(token) = token else {
+ tracing::debug!("MCP request missing bearer token");
+ return unauthorized_response(&request, None);
+ };
+
+ let jwt_token = match handler(&jwt_args, &token) {
+ Ok(token) => token,
+ Err(error) => {
+ tracing::warn!(error=?error, "MCP bearer token validation failed");
+ return unauthorized_response(&request, Some("invalid_token"));
+ }
+ };
+
+ let user_id = match jwt_token {
+ JwtToken::MacroAccessToken(token) => token.macro_user_id.clone(),
+ JwtToken::MacroApiToken(token) => token.macro_user_id.clone(),
+ };
+
+ let user_id = match MacroUserIdStr::try_from(user_id) {
+ Ok(user_id) => user_id,
+ Err(error) => {
+ tracing::warn!(error=?error, "MCP bearer token contained invalid macro user id");
+ return unauthorized_response(&request, Some("invalid_token"));
+ }
+ };
+
+ request.extensions_mut().insert(user_id);
+
+ next.run(request).await
+}
diff --git a/rust/cloud-storage/mcp_auth_proxy/src/lib.rs b/rust/cloud-storage/mcp_auth_proxy/src/lib.rs
new file mode 100644
index 0000000000..01a4e5e2c9
--- /dev/null
+++ b/rust/cloud-storage/mcp_auth_proxy/src/lib.rs
@@ -0,0 +1,27 @@
+//! `mcp_auth_proxy` is the MCP-facing OAuth broker used by the `mcp_service` binary.
+//!
+//! It sits between an MCP client and the upstream OAuth provider so the MCP
+//! server can expose the metadata and loopback-public-client behavior Claude
+//! expects while still returning upstream FusionAuth bearer tokens.
+//!
+//! High-level flow:
+//! 1. expose protected-resource and authorization-server discovery metadata
+//! 2. accept dynamic registration for public loopback clients
+//! 3. redirect the user to the upstream provider from `/authorize`
+//! 4. exchange the upstream callback code at `/oauth/callback`
+//! 5. issue a short-lived broker code for the MCP client loopback callback
+//! 6. exchange that code at `/token` after redirect URI and PKCE validation
+//! 7. support refresh-token exchanges against the upstream provider
+//!
+//! Module layout:
+//! - `domain`: auth proxy state, models, ports, and service logic
+//! - `inbound`: axum router and HTTP middleware
+//! - `outbound`: adapters for upstream OAuth providers
+
+#![deny(missing_docs)]
+
+pub mod domain;
+#[cfg(feature = "inbound")]
+pub mod inbound;
+#[cfg(feature = "outbound")]
+pub mod outbound;
diff --git a/rust/cloud-storage/mcp_auth_proxy/src/outbound.rs b/rust/cloud-storage/mcp_auth_proxy/src/outbound.rs
new file mode 100644
index 0000000000..5be5d37057
--- /dev/null
+++ b/rust/cloud-storage/mcp_auth_proxy/src/outbound.rs
@@ -0,0 +1,6 @@
+//! Outbound adapters for the MCP OAuth broker.
+
+/// FusionAuth-backed upstream OAuth provider.
+pub mod fusionauth;
+/// Redis-backed in-flight OAuth state store.
+pub mod redis;
diff --git a/rust/cloud-storage/mcp_auth_proxy/src/outbound/fusionauth.rs b/rust/cloud-storage/mcp_auth_proxy/src/outbound/fusionauth.rs
new file mode 100644
index 0000000000..0c2d5c1d29
--- /dev/null
+++ b/rust/cloud-storage/mcp_auth_proxy/src/outbound/fusionauth.rs
@@ -0,0 +1,77 @@
+//! FusionAuth adapter for the MCP OAuth broker.
+
+use anyhow::Context;
+use std::sync::Arc;
+use tracing::Instrument;
+
+use crate::domain::{
+ models::RefreshToken,
+ ports::{OAuthProvider, TokenPairFuture},
+};
+
+/// FusionAuth-backed OAuth provider for the MCP auth proxy.
+#[derive(Clone)]
+pub struct FusionAuthOAuthProvider {
+ client: Arc<fusionauth::FusionAuthClient>,
+ google_idp_id: String,
+}
+
+impl FusionAuthOAuthProvider {
+ /// Creates a provider and resolves the Google identity provider ID.
+ #[tracing::instrument(skip(client), err)]
+ pub async fn new(client: fusionauth::FusionAuthClient) -> anyhow::Result<Self> {
+ let google_idp_id = client
+ .get_identity_provider_id_by_name("google_gmail")
+ .await
+ .context("failed to look up Google Gmail identity provider in FusionAuth")?;
+ tracing::debug!(%google_idp_id, "resolved Google IDP ID from FusionAuth");
+
+ Ok(Self {
+ client: Arc::new(client),
+ google_idp_id,
+ })
+ }
+}
+
+impl OAuthProvider for FusionAuthOAuthProvider {
+ #[tracing::instrument(skip(self), err)]
+ fn construct_authorize_url(&self, state: &str) -> anyhow::Result<String> {
+ self.client.construct_oauth2_authorize_url(
+ &self.google_idp_id,
+ None,
+ Some(state.to_owned()),
+ )
+ }
+
+ fn exchange_authorization_code<'a>(&'a self, code: &'a str) -> TokenPairFuture<'a> {
+ let span = tracing::debug_span!("FusionAuthOAuthProvider::exchange_authorization_code");
+ Box::pin(
+ async move {
+ let (access_token, refresh_token) = self
+ .client
+ .complete_authorization_code_grant(code)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ Ok((access_token.into(), refresh_token.into()))
+ }
+ .instrument(span),
+ )
+ }
+
+ fn refresh_access_token<'a>(&'a self, refresh_token: &'a RefreshToken) -> TokenPairFuture<'a> {
+ let span = tracing::debug_span!("FusionAuthOAuthProvider::refresh_access_token");
+ Box::pin(
+ async move {
+ let (access_token, refresh_token) = self
+ .client
+ .complete_refresh_token_grant(refresh_token.as_str())
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ Ok((access_token.into(), refresh_token.into()))
+ }
+ .instrument(span),
+ )
+ }
+}
diff --git a/rust/cloud-storage/mcp_auth_proxy/src/outbound/redis.rs b/rust/cloud-storage/mcp_auth_proxy/src/outbound/redis.rs
new file mode 100644
index 0000000000..8c8e47b952
--- /dev/null
+++ b/rust/cloud-storage/mcp_auth_proxy/src/outbound/redis.rs
@@ -0,0 +1,203 @@
+//! Redis-backed storage for short-lived OAuth handshake state.
+
+use anyhow::Context;
+use redis::AsyncCommands;
+use std::future::Future;
+
+use crate::domain::{
+ models::{IssuedAuthorizationCode, PendingAuthorization},
+ service::{AUTHORIZATION_CODE_TTL, InflightAuthStore, PENDING_AUTH_TTL},
+};
+
+const PENDING_KEY_PREFIX: &str = "mcp_auth_proxy:pending:";
+const ISSUED_KEY_PREFIX: &str = "mcp_auth_proxy:issued:";
+
+/// Redis-backed implementation of the in-flight OAuth state store.
+#[derive(Clone)]
+pub struct RedisInflightAuth {
+ client: redis::Client,
+}
+
+impl RedisInflightAuth {
+ /// Creates a new Redis-backed in-flight OAuth state store.
+ pub fn new(client: redis::Client) -> Self {
+ Self { client }
+ }
+
+ fn pending_key(session_id: &str) -> String {
+ format!("{PENDING_KEY_PREFIX}{session_id}")
+ }
+
+ fn issued_key(code: &str) -> String {
+ format!("{ISSUED_KEY_PREFIX}{code}")
+ }
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+struct StoredPendingAuthorization {
+ code_challenge: String,
+ client_state: String,
+ client_redirect_uri: String,
+}
+
+impl From<PendingAuthorization> for StoredPendingAuthorization {
+ fn from(value: PendingAuthorization) -> Self {
+ Self {
+ code_challenge: value.code_challenge,
+ client_state: value.client_state,
+ client_redirect_uri: value.client_redirect_uri,
+ }
+ }
+}
+
+impl From<StoredPendingAuthorization> for PendingAuthorization {
+ fn from(value: StoredPendingAuthorization) -> Self {
+ Self {
+ code_challenge: value.code_challenge,
+ client_state: value.client_state,
+ client_redirect_uri: value.client_redirect_uri,
+ }
+ }
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+struct StoredIssuedAuthorizationCode {
+ access_token: crate::domain::models::AccessToken,
+ refresh_token: crate::domain::models::RefreshToken,
+ code_challenge: String,
+ redirect_uri: String,
+}
+
+impl From<IssuedAuthorizationCode> for StoredIssuedAuthorizationCode {
+ fn from(value: IssuedAuthorizationCode) -> Self {
+ Self {
+ access_token: value.access_token,
+ refresh_token: value.refresh_token,
+ code_challenge: value.code_challenge,
+ redirect_uri: value.redirect_uri,
+ }
+ }
+}
+
+impl From<StoredIssuedAuthorizationCode> for IssuedAuthorizationCode {
+ fn from(value: StoredIssuedAuthorizationCode) -> Self {
+ Self {
+ access_token: value.access_token,
+ refresh_token: value.refresh_token,
+ code_challenge: value.code_challenge,
+ redirect_uri: value.redirect_uri,
+ }
+ }
+}
+
+#[allow(clippy::manual_async_fn)]
+impl InflightAuthStore for RedisInflightAuth {
+ fn insert_pending(
+ &self,
+ session_id: &str,
+ pending: PendingAuthorization,
+ ) -> impl Future<Output = anyhow::Result<()>> + Send {
+ let client = self.client.clone();
+ let key = Self::pending_key(session_id);
+ async move {
+ let value = serde_json::to_string(&StoredPendingAuthorization::from(pending))
+ .context("failed to serialize pending authorization")?;
+ let mut conn = client
+ .get_multiplexed_async_connection()
+ .await
+ .context("unable to connect to redis")?;
+ conn.set_ex::<String, String, ()>(key.clone(), value, PENDING_AUTH_TTL.as_secs())
+ .await
+ .with_context(|| {
+ format!("failed to persist pending authorization for key {key}")
+ })?;
+ Ok(())
+ }
+ }
+
+ fn take_pending(
+ &self,
+ session_id: &str,
+ ) -> impl Future<Output = anyhow::Result<Option<PendingAuthorization>>> + Send {
+ let client = self.client.clone();
+ let key = Self::pending_key(session_id);
+ async move {
+ let mut conn = client
+ .get_multiplexed_async_connection()
+ .await
+ .context("unable to connect to redis")?;
+ let value: Option<String> = redis::cmd("GETDEL")
+ .arg(&key)
+ .query_async(&mut conn)
+ .await
+ .with_context(|| format!("failed to fetch pending authorization for key {key}"))?;
+ value
+ .map(|json| {
+ serde_json::from_str::<StoredPendingAuthorization>(&json)
+ .map(PendingAuthorization::from)
+ .context("failed to deserialize pending authorization")
+ })
+ .transpose()
+ }
+ }
+
+ fn insert_issued(
+ &self,
+ code: &str,
+ issued: IssuedAuthorizationCode,
+ ) -> impl Future<Output = anyhow::Result<()>> + Send {
+ let client = self.client.clone();
+ let key = Self::issued_key(code);
+ async move {
+ let value = serde_json::to_string(&StoredIssuedAuthorizationCode::from(issued))
+ .context("failed to serialize issued authorization code")?;
+ let mut conn = client
+ .get_multiplexed_async_connection()
+ .await
+ .context("unable to connect to redis")?;
+ conn.set_ex::<String, String, ()>(key.clone(), value, AUTHORIZATION_CODE_TTL.as_secs())
+ .await
+ .with_context(|| {
+ format!("failed to persist issued authorization code for key {key}")
+ })?;
+ Ok(())
+ }
+ }
+
+ fn take_issued(
+ &self,
+ code: &str,
+ ) -> impl Future<Output = anyhow::Result<Option<IssuedAuthorizationCode>>> + Send {
+ let client = self.client.clone();
+ let key = Self::issued_key(code);
+ async move {
+ let mut conn = client
+ .get_multiplexed_async_connection()
+ .await
+ .context("unable to connect to redis")?;
+ let value: Option<String> = redis::cmd("GETDEL")
+ .arg(&key)
+ .query_async(&mut conn)
+ .await
+ .with_context(|| {
+ format!("failed to fetch issued authorization code for key {key}")
+ })?;
+ value
+ .map(|json| {
+ serde_json::from_str::<StoredIssuedAuthorizationCode>(&json)
+ .map(IssuedAuthorizationCode::from)
+ .context("failed to deserialize issued authorization code")
+ })
+ .transpose()
+ }
+ }
+
+ fn cleanup_expired(&self) -> impl Future<Output = anyhow::Result<()>> + Send {
+ async {
+ // Redis enforces expiry via the TTL set with `SETEX` on every pending
+ // session and issued code. There is no separate in-process map to
+ // sweep, so cleanup is intentionally a no-op for this backend.
+ Ok(())
+ }
+ }
+}
diff --git a/rust/cloud-storage/mcp_service/Cargo.toml b/rust/cloud-storage/mcp_service/Cargo.toml
new file mode 100644
index 0000000000..f062c6470b
--- /dev/null
+++ b/rust/cloud-storage/mcp_service/Cargo.toml
@@ -0,0 +1,63 @@
+[package]
+default-run = "mcp_service"
+edition = "2024"
+name = "mcp_service"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+ai_tools = { path = "../ai_tools" }
+ai_toolset = { path = "../ai_toolset" }
+anyhow = { workspace = true }
+aws-sdk-secretsmanager = { workspace = true }
+aws-sdk-sqs = { workspace = true }
+axum = { workspace = true, features = ["tower-log"] }
+comms = { path = "../comms", features = ["outbound"] }
+document_storage_service_client = { path = "../document_storage_service_client" }
+documents = { path = "../documents", features = ["ai_tools"] }
+email = { path = "../email", features = ["outbound"] }
+email_service_client = { path = "../email_service_client" }
+entity_access = { path = "../entity_access" }
+frecency = { path = "../frecency", features = ["outbound", "postgres"] }
+fusionauth = { path = "../fusionauth" }
+http = { workspace = true }
+lexical_client = { path = "../lexical_client" }
+mcp_auth_proxy = { path = "../mcp_auth_proxy" }
+macro_auth = { path = "../macro_auth" }
+macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
+macro_entrypoint = { path = "../macro_entrypoint" }
+macro_env = { path = "../macro_env" }
+macro_env_var = { path = "../macro_env_var" }
+macro_middleware = { path = "../macro_middleware", default-features = false, features = [
+ "auth",
+ "cloud_storage",
+ "user_permissions",
+] }
+macro_user_id = { path = "../macro_user_id" }
+properties = { path = "../properties", features = ["ai_tools"] }
+readonly_pool = { path = "../readonly_pool" }
+redis = { workspace = true, features = ["aio", "tokio-comp"] }
+rmcp = { version = "1.2.0", features = ["transport-streamable-http-server"] }
+scribe = { path = "../scribe", features = [
+ "channel",
+ "dcs",
+ "document",
+ "email",
+ "static_file",
+] }
+search_service_client = { path = "../search_service_client" }
+secretsmanager_client = { path = "../secretsmanager_client" }
+serde_json = { workspace = true }
+soup = { path = "../soup", features = ["outbound"] }
+sqlx = { workspace = true }
+sqs_client = { path = "../sqs_client", default-features = false, features = [
+ "chat",
+ "document_text_extractor",
+ "email",
+ "gmail",
+ "search",
+] }
+static_file_service_client = { path = "../static_file_service_client" }
+sync_service_client = { path = "../sync_service_client" }
+tokio = { workspace = true }
+tracing = { workspace = true }
diff --git a/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs b/rust/cloud-storage/mcp_service/src/context.rs
similarity index 60%
rename from rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs
rename to rust/cloud-storage/mcp_service/src/context.rs
index 04a039fc7e..f6c6ddf80e 100644
--- a/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -1,8 +1,4 @@
-//! MCP server binary that serves the DCS AI toolset over HTTP.
-//!
-//! This binary spins up a Streamable HTTP MCP server exposing the same
-//! tools that are available in the DCS chat/stream API, with OAuth 2.1
-//! authentication backed by FusionAuth.
+use std::sync::Arc;
use ai_tools::{
NoOpConnectionService, NoOpNotificationService, NoOpTaskProperties, ToolServiceContext,
@@ -11,10 +7,6 @@ use anyhow::Context;
use comms::domain::service::ChannelServiceImpl;
use comms::outbound::postgres::comms_repo::PgCommsRepo;
use comms::outbound::postgres::user_repo::PgUserRepo;
-use dashmap::DashMap;
-use document_cognition_service::mcp_oauth::{
- mcp_router, state::OAuthState, tool_service::AuthenticatedToolService,
-};
use document_storage_service_client::DocumentStorageServiceClient;
use documents::{
domain::{models::CloudFrontConfig, service::DocumentServiceImpl},
@@ -29,23 +21,22 @@ use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccess
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::outbound::postgres::FrecencyPgStorage;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
-use macro_entrypoint::MacroEntrypoint;
use macro_env_var::env_var;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
-use rmcp::transport::streamable_http_server::{
- StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
+use mcp_auth_proxy::{
+ domain::service::McpAuthProxyServiceImpl,
+ outbound::{fusionauth::FusionAuthOAuthProvider, redis::RedisInflightAuth},
};
use scribe::{ScribeClient, document::DocumentClient};
use search_service_client::SearchServiceClient;
-use secretsmanager_client::SecretManager;
+use secretsmanager_client::LocalOrRemoteSecret;
use soup::domain::service::SoupImpl;
use soup::outbound::pg_soup_repo::PgSoupRepo;
-use sqlx::postgres::PgPoolOptions;
-use std::sync::Arc;
+use sqlx::{PgPool, postgres::PgPoolOptions};
use sync_service_client::SyncServiceClient;
env_var!(
- struct McpEnvVars {
+ pub struct McpEnvVars {
DatabaseUrl,
EmailScheduledQueue,
DocumentStorageServiceUrl,
@@ -64,34 +55,23 @@ env_var!(
FusionauthClientId,
FusionauthTenantId,
FusionauthApiKeySecretKey,
+ FusionauthClientSecretKey,
GoogleClientId,
GoogleClientSecretKey,
+ RedisUrl,
}
);
-fn is_local() -> bool {
- matches!(
- macro_env::Environment::new_or_prod(),
- macro_env::Environment::Local
- )
+#[derive(Clone)]
+pub struct McpContext {
+ pub jwt_args: JwtValidationArgs,
+ pub tool_context: ToolServiceContext,
+ pub auth_proxy: McpAuthProxyServiceImpl<RedisInflightAuth>,
}
-#[tokio::main]
-#[tracing::instrument(err)]
-async fn main() -> anyhow::Result<()> {
- MacroEntrypoint::default().init();
-
+pub async fn build_context() -> anyhow::Result<McpContext> {
let env_vars = McpEnvVars::new().context("failed to load environment variables")?;
- // FusionAuth client secret uses a different env var name in local vs deployed
- let fusionauth_client_secret_env = if is_local() {
- std::env::var("FUSIONAUTH_CLIENT_SECRET")
- .context("FUSIONAUTH_CLIENT_SECRET must be provided")?
- } else {
- std::env::var("FUSIONAUTH_CLIENT_SECRET_KEY")
- .context("FUSIONAUTH_CLIENT_SECRET_KEY must be provided")?
- };
-
let db = PgPoolOptions::new()
.min_connections(3)
.max_connections(10)
@@ -111,7 +91,6 @@ async fn main() -> anyhow::Result<()> {
aws_sdk_secretsmanager::Client::new(&aws_config),
);
- // JWT validation args (reads JWT_SECRET_KEY, AUDIENCE, ISSUER, etc. from env)
let jwt_args = JwtValidationArgs::new_with_secret_manager(macro_env, &secretsmanager_client)
.await
.context("failed to initialize JWT validation args")?;
@@ -120,23 +99,47 @@ async fn main() -> anyhow::Result<()> {
InternalApiSecretKey::new().context("failed to create internal auth key")?,
);
+ let sync_service_auth_key = LocalOrRemoteSecret::new_from_secret_manager(
+ env_vars.sync_service_auth_key.as_ref().to_owned(),
+ &secretsmanager_client,
+ )
+ .await
+ .context("failed to load sync service auth key")?;
+
+ let tool_context = build_tool_context(
+ &env_vars,
+ &db,
+ &secretsmanager_client,
+ sqs_client,
+ internal_auth_key.as_ref().to_string(),
+ sync_service_auth_key.as_ref().to_owned(),
+ )
+ .await?;
+
+ let auth_proxy = build_auth_proxy(&env_vars, &secretsmanager_client).await?;
+
+ Ok(McpContext {
+ jwt_args,
+ tool_context,
+ auth_proxy,
+ })
+}
+
+async fn build_tool_context(
+ env_vars: &McpEnvVars,
+ db: &PgPool,
+ secretsmanager_client: &secretsmanager_client::SecretsManager,
+ sqs_client: sqs_client::SQS,
+ internal_auth_key: String,
+ sync_service_auth_key: String,
+) -> anyhow::Result<ToolServiceContext> {
let dss_url: String = env_vars.document_storage_service_url.as_ref().to_owned();
+ let sync_service_url: String = env_vars.sync_service_url.as_ref().to_owned();
let document_storage_client =
- DocumentStorageServiceClient::new(internal_auth_key.as_ref().to_string(), dss_url.clone());
-
- let sync_service_auth_key = if is_local() {
- env_vars.sync_service_auth_key.as_ref().to_owned()
- } else {
- secretsmanager_client
- .get_secret_value(&env_vars.sync_service_auth_key)
- .await
- .context("failed to get sync service auth key from secrets manager")?
- .to_string()
- };
+ DocumentStorageServiceClient::new(internal_auth_key.clone(), dss_url.clone());
- let search_service_client =
- SearchServiceClient::new(internal_auth_key.as_ref().to_string(), dss_url);
+ let search_service_client = SearchServiceClient::new(internal_auth_key.clone(), dss_url);
let lexical_client = Arc::new(lexical_client::LexicalClient::new(
sync_service_auth_key.clone(),
@@ -144,17 +147,16 @@ async fn main() -> anyhow::Result<()> {
));
let email_service_client = Arc::new(EmailServiceClient::new(
- internal_auth_key.as_ref().to_string(),
+ internal_auth_key.clone(),
env_vars.email_service_url.as_ref().to_owned(),
));
let static_file_service_client =
Arc::new(static_file_service_client::StaticFileServiceClient::new(
- internal_auth_key.as_ref().to_string(),
+ internal_auth_key,
env_vars.static_file_service_url.as_ref().to_owned(),
));
- // Build soup service
let frecency_storage = FrecencyPgStorage::new(db.clone());
let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
let email_service = EmailServiceImpl::new(
@@ -176,7 +178,6 @@ async fn main() -> anyhow::Result<()> {
channels_service,
));
- // Build document tool context
let s3_client = macro_aws_config::s3_client().await;
let s3_upload_adapter = S3UploadUrlAdapter::new(
s3_client,
@@ -184,20 +185,15 @@ async fn main() -> anyhow::Result<()> {
env_vars.docx_document_upload_bucket.as_ref(),
);
let document_repo = PgDocumentRepo::new(db.clone());
- let cloudfront_private_key = if is_local() {
+ let cloudfront_private_key = LocalOrRemoteSecret::new_from_secret_manager(
env_vars
.document_storage_service_cloudfront_signer_private_key_secret_name
.as_ref()
- .to_owned()
- } else {
- secretsmanager_client
- .get_secret_value(
- &env_vars.document_storage_service_cloudfront_signer_private_key_secret_name,
- )
- .await
- .context("failed to get CloudFront signer private key from secrets manager")?
- .to_string()
- };
+ .to_owned(),
+ secretsmanager_client,
+ )
+ .await
+ .context("failed to load CloudFront signer private key")?;
let cloudfront_config = CloudFrontConfig {
distribution_url: env_vars
.document_storage_service_cloudfront_distribution_url
@@ -207,11 +203,10 @@ async fn main() -> anyhow::Result<()> {
.document_storage_service_cloudfront_signer_public_key_id
.as_ref()
.to_owned(),
- signer_private_key: cloudfront_private_key,
+ signer_private_key: cloudfront_private_key.as_ref().to_owned(),
presigned_url_expiry_seconds: 3600,
browser_cache_expiry_seconds: 86400,
};
- let sync_service_url: String = env_vars.sync_service_url.as_ref().to_owned();
let sync_service_client =
SyncServiceClient::new(sync_service_auth_key.clone(), sync_service_url.clone());
let document_service = DocumentServiceImpl::new(
@@ -222,34 +217,32 @@ async fn main() -> anyhow::Result<()> {
NoOpTaskProperties,
NoOpConnectionService,
);
- let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
- db.clone(),
- )));
+ let entity_access_service = EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone()));
let lexical_client_for_tools = (*lexical_client).clone();
let document_tool_context = DocumentToolContext::new(
document_service,
- (*entity_access_service).clone(),
+ entity_access_service,
lexical_client_for_tools,
);
- // Build properties tool context
let properties_service = properties::PropertiesServiceImpl::new(
properties::PropertiesPgRepo::new(db.clone()),
Some(properties::PermissionServiceImpl::new(
db.clone(),
- entity_access_service.clone(),
+ Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ db.clone(),
+ ))),
)),
Some(NoOpNotificationService),
);
let properties_tool_context =
properties::inbound::toolset::PropertiesToolContext::new(properties_service);
- // Build email tool context
let email_tool_context = email::inbound::toolset::EmailToolContext::new(
Arc::new(EmailServiceImpl::new(
EmailPgRepo::new(db.clone()),
FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
- sqs_client.clone(),
+ sqs_client,
0,
)),
Arc::new(email::domain::ports::NoOpGmailTokenProvider),
@@ -258,7 +251,6 @@ async fn main() -> anyhow::Result<()> {
))),
);
- // Build the ToolServiceContext
let tool_context = ToolServiceContext {
email_service_client: Arc::new(EmailServiceClientExternal::new(
email_service_client.url().to_owned(),
@@ -291,105 +283,57 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized tool context");
- // Create the MCP service with authenticated tool handler
- let mcp_service = StreamableHttpService::new(
- move || {
- let tools = ai_tools::all_tools();
- Ok(AuthenticatedToolService::new(
- tools.toolset,
- tool_context.clone(),
- ))
- },
- Arc::new(LocalSessionManager::default()),
- StreamableHttpServerConfig::default(),
- );
+ Ok(tool_context)
+}
- // Build FusionAuth client for the MCP OAuth flow.
- // The oauth_redirect_uri points to the MCP server's own callback endpoint.
+async fn build_auth_proxy(
+ env_vars: &McpEnvVars,
+ secretsmanager_client: &secretsmanager_client::SecretsManager,
+) -> anyhow::Result<McpAuthProxyServiceImpl<RedisInflightAuth>> {
let mcp_public_url: String = env_vars.mcp_public_url.as_ref().to_owned();
let mcp_oauth_redirect_uri = format!("{mcp_public_url}/oauth/callback");
- let fusionauth_api_key = if is_local() {
- env_vars.fusionauth_api_key_secret_key.as_ref().to_owned()
- } else {
- secretsmanager_client
- .get_secret_value(&env_vars.fusionauth_api_key_secret_key)
- .await
- .context("failed to get FusionAuth API key")?
- .to_string()
- };
+ let fusionauth_api_key = LocalOrRemoteSecret::new_from_secret_manager(
+ env_vars.fusionauth_api_key_secret_key.as_ref().to_owned(),
+ secretsmanager_client,
+ )
+ .await
+ .context("failed to load FusionAuth API key")?;
- let fusionauth_client_secret = if is_local() {
- fusionauth_client_secret_env
- } else {
- secretsmanager_client
- .get_secret_value(&fusionauth_client_secret_env)
- .await
- .context("failed to get FusionAuth client secret")?
- .to_string()
- };
+ let fusionauth_client_secret = LocalOrRemoteSecret::new_from_secret_manager(
+ env_vars.fusionauth_client_secret_key.as_ref().to_owned(),
+ secretsmanager_client,
+ )
+ .await
+ .context("failed to load FusionAuth client secret")?;
- let google_client_secret = if is_local() {
- env_vars.google_client_secret_key.as_ref().to_owned()
- } else {
- secretsmanager_client
- .get_secret_value(&env_vars.google_client_secret_key)
- .await
- .context("failed to get Google client secret")?
- .to_string()
- };
+ let google_client_secret = LocalOrRemoteSecret::new_from_secret_manager(
+ env_vars.google_client_secret_key.as_ref().to_owned(),
+ secretsmanager_client,
+ )
+ .await
+ .context("failed to load Google client secret")?;
let fusionauth_client = fusionauth::FusionAuthClient::new(
env_vars.fusionauth_tenant_id.as_ref().to_owned(),
- fusionauth_api_key,
+ fusionauth_api_key.as_ref().to_owned(),
env_vars.fusionauth_client_id.as_ref().to_owned(),
- fusionauth_client_secret,
+ fusionauth_client_secret.as_ref().to_owned(),
env_vars.fusionauth_base_url.as_ref().to_owned(),
mcp_oauth_redirect_uri,
env_vars.google_client_id.as_ref().to_owned(),
- google_client_secret,
+ google_client_secret.as_ref().to_owned(),
);
- // Resolve the Google IDP ID at startup so we don't need it as an env var.
- let google_idp_id = fusionauth_client
- .get_identity_provider_id_by_name("google")
- .await
- .context("failed to look up Google identity provider in FusionAuth")?;
- tracing::info!(%google_idp_id, "resolved Google IDP ID from FusionAuth");
-
- // Build OAuth state
- let oauth_state = OAuthState {
- pending: Arc::new(DashMap::new()),
- codes: Arc::new(DashMap::new()),
- jwt_args: jwt_args.clone(),
- fusionauth_client: Arc::new(fusionauth_client),
- google_idp_id,
- mcp_public_url: mcp_public_url.clone(),
- };
-
- // Spawn background cleanup for expired OAuth entries
- let cleanup_state = oauth_state.clone();
- tokio::spawn(async move {
- let mut interval = tokio::time::interval(std::time::Duration::from_secs(60));
- loop {
- interval.tick().await;
- cleanup_state.cleanup_expired();
- }
- });
-
- let app = mcp_router(oauth_state, jwt_args, mcp_service);
-
- let port = std::env::var("PORT").unwrap_or_else(|_| "8090".to_string());
- let addr = format!("0.0.0.0:{port}");
- let listener = tokio::net::TcpListener::bind(&addr)
+ let auth_provider = FusionAuthOAuthProvider::new(fusionauth_client)
.await
- .context("failed to bind MCP server")?;
-
- tracing::info!("MCP server listening on http://{addr}/mcp");
-
- axum::serve(listener, app)
- .await
- .context("MCP server error")?;
-
- Ok(())
+ .context("failed to initialize MCP auth provider")?;
+ let redis_client = redis::Client::open(env_vars.redis_url.as_ref().to_owned())
+ .context("failed to initialize redis client for MCP auth proxy")?;
+
+ Ok(McpAuthProxyServiceImpl::new(
+ mcp_public_url,
+ Arc::new(RedisInflightAuth::new(redis_client)),
+ Arc::new(auth_provider),
+ ))
}
diff --git a/rust/cloud-storage/mcp_service/src/main.rs b/rust/cloud-storage/mcp_service/src/main.rs
new file mode 100644
index 0000000000..4b5f437f1b
--- /dev/null
+++ b/rust/cloud-storage/mcp_service/src/main.rs
@@ -0,0 +1,74 @@
+//! MCP server binary that serves the DCS AI toolset over HTTP.
+//!
+//! This binary spins up a Streamable HTTP MCP server exposing the same
+//! tools that are available in the DCS chat/stream API, with OAuth 2.1
+//! authentication backed by FusionAuth.
+
+mod context;
+mod tool_service;
+use anyhow::Context;
+use context::build_context;
+use macro_entrypoint::MacroEntrypoint;
+use mcp_auth_proxy::domain::service::McpAuthProxyService;
+use mcp_auth_proxy::inbound::axum_router::mcp_router;
+use rmcp::transport::streamable_http_server::{
+ StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
+};
+use std::sync::Arc;
+use tokio::time::Duration;
+use tool_service::AuthenticatedToolService;
+
+const AUTH_PROXY_CLEANUP_INTERVAL: Duration = Duration::from_secs(60);
+
+#[tokio::main]
+#[tracing::instrument(err)]
+async fn main() -> anyhow::Result<()> {
+ MacroEntrypoint::default().init();
+
+ let context = build_context().await?;
+
+ // Create the MCP service with authenticated tool handler
+ let mcp_service = StreamableHttpService::new(
+ move || {
+ let tools = ai_tools::all_tools();
+ Ok(AuthenticatedToolService::new(
+ tools.toolset,
+ context.tool_context.clone(),
+ ))
+ },
+ Arc::new(LocalSessionManager::default()),
+ StreamableHttpServerConfig {
+ stateful_mode: false,
+ json_response: true,
+ ..Default::default()
+ },
+ );
+
+ // Spawn background cleanup for expired OAuth entries
+ let cleanup_state = context.auth_proxy.clone();
+ tokio::spawn(async move {
+ let mut interval = tokio::time::interval(AUTH_PROXY_CLEANUP_INTERVAL);
+ loop {
+ interval.tick().await;
+ if let Err(error) = cleanup_state.cleanup_expired().await {
+ tracing::error!(error=?error, "auth proxy cleanup task failed");
+ }
+ }
+ });
+
+ let app = mcp_router(context.auth_proxy, context.jwt_args, mcp_service);
+
+ let port = std::env::var("PORT").unwrap_or_else(|_| "8090".to_string());
+ let addr = format!("0.0.0.0:{port}");
+ let listener = tokio::net::TcpListener::bind(&addr)
+ .await
+ .context("failed to bind MCP server")?;
+
+ tracing::info!("MCP server listening on http://{addr}/mcp");
+
+ axum::serve(listener, app)
+ .await
+ .context("MCP server error")?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rs b/rust/cloud-storage/mcp_service/src/tool_service.rs
similarity index 74%
rename from rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rs
rename to rust/cloud-storage/mcp_service/src/tool_service.rs
index fe4cf575af..fe36ce008d 100644
--- a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rs
+++ b/rust/cloud-storage/mcp_service/src/tool_service.rs
@@ -8,8 +8,6 @@ use rmcp::{
};
use std::sync::Arc;
-use super::middleware::McpUserIdentity;
-
/// MCP server handler that extracts authenticated user identity from HTTP
/// request parts injected by rmcp's `StreamableHttpService`.
pub struct AuthenticatedToolService<Context> {
@@ -18,7 +16,7 @@ pub struct AuthenticatedToolService<Context> {
}
impl<Context> AuthenticatedToolService<Context> {
- /// Create a new authenticated tool service.
+ /// Creates a new authenticated tool service.
pub fn new(toolset: Arc<AsyncToolSet<Context>>, context: Context) -> Self {
Self { toolset, context }
}
@@ -58,11 +56,11 @@ where
.toolset
.tools
.iter()
- .map(|(k, v)| {
+ .map(|(key, value)| {
Tool::new(
- k.to_owned(),
- v.description.to_owned(),
- Arc::new(v.input_schema.clone()),
+ key.to_owned(),
+ value.description.to_owned(),
+ Arc::new(value.input_schema.clone()),
)
})
.collect::<Vec<_>>();
@@ -78,18 +76,14 @@ where
request: rmcp::model::CallToolRequestParams,
context: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
- // Extract user identity from HTTP parts injected by rmcp.
- let identity = context
+ let user_id = context
.extensions
.get::<http::request::Parts>()
- .and_then(|parts| parts.extensions.get::<McpUserIdentity>().cloned())
+ .and_then(|parts| parts.extensions.get::<MacroUserIdStr<'static>>().cloned())
.ok_or_else(|| {
rmcp::ErrorData::internal_error("missing user identity — is auth configured?", None)
})?;
- let user_id = MacroUserIdStr::try_from(identity.user_id.clone())
- .map_err(|e| rmcp::ErrorData::internal_error(format!("invalid user id: {e}"), None))?;
-
let request_context = RequestContext { user_id };
let arguments = request
@@ -106,19 +100,19 @@ where
&arguments,
)
.await
- .map_err(|e| match e {
- ai_toolset::ToolSetError::Deserialization(e) => {
- rmcp::ErrorData::parse_error(e.to_string(), None)
+ .map_err(|error| match error {
+ ai_toolset::ToolSetError::Deserialization(error) => {
+ rmcp::ErrorData::parse_error(error.to_string(), None)
}
- ai_toolset::ToolSetError::NotFound(s) => {
- rmcp::ErrorData::resource_not_found(s, None)
+ ai_toolset::ToolSetError::NotFound(message) => {
+ rmcp::ErrorData::resource_not_found(message, None)
}
})?;
match result {
- Ok(good) => Ok(rmcp::model::CallToolResult::structured(good)),
- Err(bad) => Ok(rmcp::model::CallToolResult::error(vec![Content::text(
- bad.description,
+ Ok(value) => Ok(rmcp::model::CallToolResult::structured(value)),
+ Err(error) => Ok(rmcp::model::CallToolResult::error(vec![Content::text(
+ error.description,
)])),
}
}