use anda_core::{BoxError, Json};
use async_trait::async_trait;
use parking_lot::RwLock;
use rmcp::{
service::ClientInitializeError,
transport::{
AuthError, AuthorizationManager, ClientCredentialsConfig, CredentialStore,
StoredCredentials,
auth::{
AuthorizationCallback, AuthorizationMetadataSource, AuthorizationRequest,
AuthorizationSession, OAuthClientConfig, OAuthState, WWWAuthenticateParams,
},
},
};
use serde::{Deserialize, Serialize};
use std::{
collections::{HashMap, HashSet},
sync::Arc,
time::{Duration, Instant},
};
use super::McpServerConfig;
use super::session::McpTransportConfig;
pub(crate) const CLIENT_CREDENTIALS_RENEW_BUFFER: Duration = Duration::from_secs(120);
pub(crate) fn client_credentials_deadline(now: Instant, ttl: Duration) -> Option<Instant> {
let buffer = CLIENT_CREDENTIALS_RENEW_BUFFER.min(ttl / 2);
now.checked_add(ttl.saturating_sub(buffer))
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "flow", rename_all = "snake_case")]
pub enum McpOAuthConfig {
AuthorizationCode(OAuthAuthorizationCodeConfig),
ClientCredentials(OAuthClientCredentialsConfig),
}
impl McpOAuthConfig {
pub(crate) fn validate(&self) -> Result<(), BoxError> {
match self {
Self::AuthorizationCode(config) => config.validate(),
Self::ClientCredentials(config) => config.validate(),
}
}
}
#[derive(Clone, Default, Deserialize, Serialize)]
pub struct OAuthAuthorizationCodeConfig {
pub redirect_uri: String,
#[serde(default)]
pub scopes: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_secret: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_metadata_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub application_type: Option<String>,
}
impl std::fmt::Debug for OAuthAuthorizationCodeConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OAuthAuthorizationCodeConfig")
.field("redirect_uri", &self.redirect_uri)
.field("scopes", &self.scopes)
.field("client_name", &self.client_name)
.field("client_id", &self.client_id)
.field(
"client_secret",
&self.client_secret.as_ref().map(|_| "[REDACTED]"),
)
.field("client_metadata_url", &self.client_metadata_url)
.field("application_type", &self.application_type)
.finish()
}
}
impl OAuthAuthorizationCodeConfig {
pub fn new(redirect_uri: impl Into<String>) -> Self {
Self {
redirect_uri: redirect_uri.into(),
..Self::default()
}
}
pub(crate) fn validate(&self) -> Result<(), BoxError> {
if self.redirect_uri.trim().is_empty() {
return Err("MCP OAuth authorization_code redirect_uri must not be empty".into());
}
if let Some(secret) = &self.client_secret {
if self
.client_id
.as_deref()
.is_none_or(|id| id.trim().is_empty())
{
return Err("MCP OAuth authorization_code client_secret requires client_id".into());
}
if secret.trim().is_empty() {
return Err("MCP OAuth authorization_code client_secret must not be empty".into());
}
}
if let Some(metadata_url) = &self.client_metadata_url {
let parsed = reqwest::Url::parse(metadata_url).map_err(|err| {
format!("MCP OAuth authorization_code client_metadata_url is invalid: {err}")
})?;
if parsed.scheme() != "https"
|| !parsed.username().is_empty()
|| parsed.password().is_some()
|| parsed.fragment().is_some()
|| parsed.path() == "/"
|| parsed.path().is_empty()
{
return Err(
"MCP OAuth authorization_code client_metadata_url must be an HTTPS URL \
with a non-root path and no user info or fragment"
.into(),
);
}
}
if let Some(application_type) = &self.application_type
&& application_type.trim().is_empty()
{
return Err("MCP OAuth authorization_code application_type must not be empty".into());
}
Ok(())
}
}
#[derive(Clone, Deserialize, Serialize)]
pub struct OAuthClientCredentialsConfig {
pub client_id: String,
pub client_secret: String,
#[serde(default)]
pub scopes: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
}
impl std::fmt::Debug for OAuthClientCredentialsConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OAuthClientCredentialsConfig")
.field("client_id", &self.client_id)
.field("client_secret", &"[REDACTED]")
.field("scopes", &self.scopes)
.field("resource", &self.resource)
.finish()
}
}
impl OAuthClientCredentialsConfig {
pub(crate) fn validate(&self) -> Result<(), BoxError> {
if self.client_id.trim().is_empty() {
return Err("MCP OAuth client_credentials client_id must not be empty".into());
}
if self.client_secret.trim().is_empty() {
return Err("MCP OAuth client_credentials client_secret must not be empty".into());
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct McpOAuthMetadata {
pub scopes_supported: Vec<String>,
pub registration_supported: bool,
pub client_id_metadata_document_supported: bool,
}
#[async_trait]
pub trait McpCredentialStore: Send + Sync {
async fn load(&self, server_id: &str) -> Result<Option<StoredCredentials>, BoxError>;
async fn save(&self, server_id: &str, credentials: StoredCredentials) -> Result<(), BoxError>;
async fn clear(&self, server_id: &str) -> Result<(), BoxError>;
async fn on_refresh_token_rejected(
&self,
_server_id: &str,
_credentials: &StoredCredentials,
) -> Result<(), BoxError> {
Ok(())
}
async fn acquire_refresh_guard(
&self,
_server_id: &str,
) -> Result<Option<rmcp::transport::auth::CredentialRefreshGuard>, BoxError> {
Ok(None)
}
}
#[derive(Debug, Default)]
pub struct InMemoryMcpCredentialStore {
credentials: RwLock<HashMap<String, StoredCredentials>>,
refresh_locks: RwLock<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
}
impl InMemoryMcpCredentialStore {
pub fn new() -> Self {
Self::default()
}
}
#[async_trait]
impl McpCredentialStore for InMemoryMcpCredentialStore {
async fn acquire_refresh_guard(
&self,
server_id: &str,
) -> Result<Option<rmcp::transport::auth::CredentialRefreshGuard>, BoxError> {
let lock = self
.refresh_locks
.write()
.entry(server_id.to_string())
.or_default()
.clone();
Ok(Some(rmcp::transport::auth::CredentialRefreshGuard::new(
lock.lock_owned().await,
)))
}
async fn load(&self, server_id: &str) -> Result<Option<StoredCredentials>, BoxError> {
Ok(self.credentials.read().get(server_id).cloned())
}
async fn save(&self, server_id: &str, credentials: StoredCredentials) -> Result<(), BoxError> {
self.credentials
.write()
.insert(server_id.to_string(), credentials);
Ok(())
}
async fn clear(&self, server_id: &str) -> Result<(), BoxError> {
self.credentials.write().remove(server_id);
Ok(())
}
}
pub(crate) struct ScopedCredentialStore {
pub(crate) server_id: String,
pub(crate) inner: Arc<dyn McpCredentialStore>,
}
#[async_trait]
impl CredentialStore for ScopedCredentialStore {
async fn acquire_refresh_guard(
&self,
) -> Result<Option<rmcp::transport::auth::CredentialRefreshGuard>, AuthError> {
self.inner
.acquire_refresh_guard(&self.server_id)
.await
.map_err(|err| AuthError::CredentialStoreError(err.to_string()))
}
async fn load(&self) -> Result<Option<StoredCredentials>, AuthError> {
self.inner
.load(&self.server_id)
.await
.map_err(|err| AuthError::CredentialStoreError(err.to_string()))
}
async fn save(&self, credentials: StoredCredentials) -> Result<(), AuthError> {
self.inner
.save(&self.server_id, credentials)
.await
.map_err(|err| AuthError::CredentialStoreError(err.to_string()))
}
async fn clear(&self) -> Result<(), AuthError> {
self.inner
.clear(&self.server_id)
.await
.map_err(|err| AuthError::CredentialStoreError(err.to_string()))
}
async fn on_refresh_token_rejected(
&self,
credentials: &StoredCredentials,
) -> Result<(), AuthError> {
self.inner
.on_refresh_token_rejected(&self.server_id, credentials)
.await
.map_err(|err| AuthError::CredentialStoreError(err.to_string()))
}
}
#[derive(Debug, Clone)]
pub struct McpAuthorizationRequired {
pub server_id: String,
}
impl std::fmt::Display for McpAuthorizationRequired {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"MCP server {} requires interactive OAuth authorization; \
call begin_authorization/complete_authorization first",
self.server_id
)
}
}
impl std::error::Error for McpAuthorizationRequired {}
pub(crate) fn is_authorization_error(err: &(dyn std::error::Error + 'static)) -> bool {
use rmcp::transport::streamable_http_client::StreamableHttpError;
if let Some(service_err) = err.downcast_ref::<rmcp::service::ServiceError>() {
if service_err.is_authorization_required() {
return true;
}
if let rmcp::service::ServiceError::TransportSend(transport) = service_err {
return is_authorization_error(transport.error.as_ref());
}
}
if let Some(error) = err.downcast_ref::<ClientInitializeError>() {
if error.is_authorization_required() {
return true;
}
match error {
ClientInitializeError::TransportError { error, .. } => {
return is_authorization_error(error.error.as_ref());
}
ClientInitializeError::LegacyFallbackFailed { fallback, .. } => {
return is_authorization_error(fallback.as_ref());
}
_ => {}
}
}
if let Some(error) = err.downcast_ref::<StreamableHttpError<super::http_client::HttpError>>() {
return matches!(
error,
StreamableHttpError::AuthRequired(_)
| StreamableHttpError::InsufficientScope(_)
| StreamableHttpError::Client(super::http_client::HttpError::Status(401 | 403))
| StreamableHttpError::Auth(
AuthError::AuthorizationRequired | AuthError::TokenRefreshRejected(_)
)
);
}
if err.is::<McpAuthorizationRequired>() {
return true;
}
matches!(
err.downcast_ref::<AuthError>(),
Some(AuthError::AuthorizationRequired | AuthError::TokenRefreshRejected(_))
)
}
pub(crate) fn extract_auth_challenge(err: &(dyn std::error::Error + 'static)) -> Option<String> {
use rmcp::transport::streamable_http_client::{
AuthRequiredError, InsufficientScopeError, StreamableHttpError,
};
if let Some(service_err) = err.downcast_ref::<rmcp::service::ServiceError>() {
if let Some(challenge) = service_err.auth_challenge() {
return Some(challenge.to_string());
}
if let rmcp::service::ServiceError::TransportSend(transport) = service_err {
return extract_auth_challenge(transport.error.as_ref());
}
}
if let Some(init_err) = err.downcast_ref::<ClientInitializeError>() {
if let Some(challenge) = init_err.auth_challenge() {
return Some(challenge.to_string());
}
match init_err {
ClientInitializeError::TransportError { error, .. } => {
return extract_auth_challenge(error.error.as_ref());
}
ClientInitializeError::LegacyFallbackFailed { fallback, .. } => {
return extract_auth_challenge(fallback.as_ref());
}
_ => {}
}
}
if let Some(http_err) = err.downcast_ref::<StreamableHttpError<super::http_client::HttpError>>()
&& let Some(challenge) = http_err.auth_challenge()
{
return Some(challenge.to_string());
}
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(current) = source {
if let Some(auth_required) = current.downcast_ref::<AuthRequiredError>() {
return Some(auth_required.www_authenticate_header.clone());
}
if let Some(insufficient_scope) = current.downcast_ref::<InsufficientScopeError>() {
return Some(insufficient_scope.www_authenticate_header.clone());
}
source = current.source();
}
None
}
pub(crate) fn extract_required_scope(err: &(dyn std::error::Error + 'static)) -> Option<String> {
use rmcp::transport::streamable_http_client::{InsufficientScopeError, StreamableHttpError};
if let Some(rmcp::service::ServiceError::TransportSend(transport)) =
err.downcast_ref::<rmcp::service::ServiceError>()
{
return extract_required_scope(transport.error.as_ref());
}
if let Some(init_err) = err.downcast_ref::<ClientInitializeError>() {
match init_err {
ClientInitializeError::TransportError { error, .. } => {
return extract_required_scope(error.error.as_ref());
}
ClientInitializeError::LegacyFallbackFailed { fallback, .. } => {
return extract_required_scope(fallback.as_ref());
}
_ => {}
}
}
if let Some(StreamableHttpError::InsufficientScope(scope_err)) =
err.downcast_ref::<StreamableHttpError<super::http_client::HttpError>>()
{
return scope_err.required_scope.clone();
}
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(current) = source {
if let Some(scope_err) = current.downcast_ref::<InsufficientScopeError>() {
return scope_err.required_scope.clone();
}
source = current.source();
}
None
}
pub(crate) fn authorization_required_hint(config: &McpServerConfig, err: BoxError) -> BoxError {
if err.is::<McpAuthorizationRequired>() || !is_authorization_error(err.as_ref()) {
return err;
}
let McpTransportConfig::StreamableHttp(http) = &config.transport else {
return err;
};
if !matches!(&http.auth, Some(McpOAuthConfig::AuthorizationCode(_))) {
return err;
}
log::warn!(
"MCP server {}: stored authorization is no longer usable ({err}); interactive \
authorization must run again",
config.id
);
McpAuthorizationRequired {
server_id: config.id.clone(),
}
.into()
}
pub(crate) async fn discover_http_oauth(url: &str) -> Result<Option<McpOAuthMetadata>, BoxError> {
let manager = AuthorizationManager::new(url).await?;
let resolution = manager.resolve_metadata().await?;
if resolution.source == AuthorizationMetadataSource::LegacyEndpointFallback {
return Ok(None);
}
let metadata = resolution.metadata;
let client_id_metadata_document_supported = metadata
.additional_fields
.get("client_id_metadata_document_supported")
.and_then(Json::as_bool)
.unwrap_or(false);
Ok(Some(McpOAuthMetadata {
scopes_supported: metadata.scopes_supported.unwrap_or_default(),
registration_supported: metadata.registration_endpoint.is_some(),
client_id_metadata_document_supported,
}))
}
fn merge_unique_scopes(groups: impl IntoIterator<Item = Vec<String>>) -> Vec<String> {
let mut seen = HashSet::new();
let mut merged = Vec::new();
for group in groups {
for scope in group {
if !scope.is_empty() && seen.insert(scope.clone()) {
merged.push(scope);
}
}
}
merged
}
pub(crate) async fn begin_authorization_manager(
url: &str,
ac: &OAuthAuthorizationCodeConfig,
store: ScopedCredentialStore,
challenge: Option<&str>,
) -> Result<(AuthorizationManager, String), BoxError> {
let prior_scopes = store
.load()
.await?
.map(|stored| stored.granted_scopes)
.unwrap_or_default();
let mut manager = AuthorizationManager::new(url).await?;
manager.set_credential_store(store);
let metadata = manager
.resolve_metadata_from_challenge(challenge)
.await?
.metadata;
manager.set_metadata(metadata);
let mut request = AuthorizationRequest::new(ac.redirect_uri.clone())
.with_client_name(ac.client_name.as_deref().unwrap_or("Anda Engine MCP Host"));
if let Some(client_id) = &ac.client_id {
request = request.with_preregistered_client(client_id.clone());
if let Some(client_secret) = &ac.client_secret {
request = request.with_client_secret(client_secret.clone());
}
}
if let Some(client_metadata_url) = &ac.client_metadata_url {
request = request.with_client_metadata_url(client_metadata_url.clone());
}
if let Some(application_type) = &ac.application_type {
request = request.with_application_type(application_type.clone());
}
let challenge_params = challenge.and_then(|header| {
reqwest::Url::parse(url)
.ok()
.map(|base_url| WWWAuthenticateParams::parse(header, &base_url))
});
let is_step_up = challenge_params
.as_ref()
.is_some_and(WWWAuthenticateParams::is_insufficient_scope);
let challenged_scopes: Vec<String> = challenge_params
.as_ref()
.and_then(|params| params.scope.as_deref())
.map(|scope| scope.split_whitespace().map(str::to_string).collect())
.unwrap_or_default();
if is_step_up {
let merged = merge_unique_scopes([prior_scopes, ac.scopes.clone(), challenged_scopes]);
if !merged.is_empty() {
request = request.with_scopes(merged);
}
} else if !ac.scopes.is_empty() {
request = request.with_scopes(ac.scopes.clone());
} else {
request = request.with_initial_scope_selection();
}
let session = AuthorizationSession::new(manager, request)
.await
.map_err(|(_, err)| BoxError::from(err))?;
Ok((session.auth_manager, session.auth_url))
}
pub(crate) async fn complete_authorization_exchange(
manager: AuthorizationManager,
redirect_url: &str,
) -> Result<(), BoxError> {
let callback = AuthorizationCallback::from_redirect_url(redirect_url)?;
manager
.exchange_code_for_token_with_issuer(
&callback.code,
&callback.csrf_token,
callback.issuer.as_deref(),
)
.await?;
Ok(())
}
pub(crate) async fn authorize_from_store(
server_id: &str,
url: &str,
ac: &OAuthAuthorizationCodeConfig,
store: ScopedCredentialStore,
challenge: Option<&str>,
) -> Result<AuthorizationManager, BoxError> {
let mut manager = AuthorizationManager::new(url).await?;
manager.set_credential_store(store);
if challenge.is_some() {
let resolution = manager.resolve_metadata_from_challenge(challenge).await?;
manager.set_metadata(resolution.metadata);
}
if !manager.initialize_from_store().await? {
return Err(McpAuthorizationRequired {
server_id: server_id.to_string(),
}
.into());
}
if let Some(client_secret) = &ac.client_secret {
let client_id = match &ac.client_id {
Some(client_id) => client_id.clone(),
None => manager.get_credentials().await?.0,
};
let mut cfg = OAuthClientConfig::new(client_id, ac.redirect_uri.clone())
.with_client_secret(client_secret.clone());
if let Some(application_type) = &ac.application_type {
cfg = cfg.with_application_type(application_type.clone());
}
manager.configure_client(cfg)?;
}
Ok(manager)
}
pub(crate) async fn authorize_client_credentials(
url: &str,
config: &OAuthClientCredentialsConfig,
) -> Result<(AuthorizationManager, Option<Instant>), BoxError> {
let mut state = OAuthState::new(url, None).await?;
state
.authenticate_client_credentials(ClientCredentialsConfig::ClientSecret {
client_id: config.client_id.clone(),
client_secret: config.client_secret.clone(),
scopes: config.scopes.clone(),
resource: config.resource.clone(),
})
.await?;
let expires_at = match state.get_credentials().await {
Ok((_, Some(token))) => serde_json::to_value(&token)
.ok()
.and_then(|token| token.get("expires_in").and_then(Json::as_u64))
.and_then(|secs| {
client_credentials_deadline(Instant::now(), Duration::from_secs(secs))
}),
_ => None,
};
let manager = state
.into_authorization_manager()
.ok_or("MCP client_credentials authorization did not complete")?;
Ok((manager, expires_at))
}