use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use greentic_secrets_lib::SecretsManager;
use secrecy::SecretString;
use serde::Deserialize;
use crate::oauth::{ResolvedAuth, RouteAuthSpec, RouteOAuth, TokenProvider};
pub(super) const CATALOG_TTL: Duration = Duration::from_secs(5 * 60);
pub(super) const PROBE_TIMEOUT: Duration = Duration::from_secs(5);
pub(super) const PULL_TIMEOUT: Duration = Duration::from_secs(300);
pub(super) const MAX_CONCURRENT_PROBES: usize = 8;
pub(super) const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(120);
pub(super) const CALL_TIMEOUT_ENV: &str = "GREENTIC_AW_MCP_CALL_TIMEOUT_SECS";
pub(super) fn call_timeout_from(raw: Option<&str>) -> Duration {
raw.and_then(|v| v.trim().parse::<u64>().ok())
.filter(|secs| *secs > 0)
.map(Duration::from_secs)
.unwrap_or(DEFAULT_CALL_TIMEOUT)
}
pub(super) fn call_timeout() -> Duration {
call_timeout_from(std::env::var(CALL_TIMEOUT_ENV).ok().as_deref())
}
pub const MCP_ROLE_AGENTIC_WORKER: &str = "agentic_worker";
pub const MCP_ROLE_FLOW_EDITOR: &str = "flow_editor";
#[derive(Clone, Debug)]
pub struct McpCallerIdentity {
pub tenant_slug: String,
pub user_email: String,
pub team_slug: Option<String>,
}
impl McpCallerIdentity {
pub fn new(tenant_slug: impl Into<String>, user_email: impl Into<String>) -> Self {
Self {
tenant_slug: tenant_slug.into(),
user_email: user_email.into(),
team_slug: None,
}
}
pub fn with_team(mut self, team_slug: impl Into<String>) -> Self {
self.team_slug = Some(team_slug.into());
self
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Transport {
#[default]
Http,
LocalWasm,
}
#[derive(Deserialize)]
pub(super) struct WireRow {
pub(super) id: String,
#[allow(dead_code)]
pub(super) name: String,
#[serde(default)]
pub(super) transport_url: Option<String>,
pub(super) auth_header_name: Option<String>,
pub(super) auth_token: Option<String>,
pub(super) allowed_tools: Option<Vec<String>>,
#[serde(default)]
pub(super) roles: Vec<String>,
#[serde(default)]
pub(super) transport: Transport,
pub(super) component_ref: Option<String>,
pub(super) component_version: Option<String>,
#[serde(default)]
pub(super) component_digest: Option<String>,
#[serde(default)]
pub(super) auth_mode: Option<String>,
#[serde(default)]
pub(super) oauth_endpoint: Option<String>,
#[serde(default)]
pub(super) oauth_scope: Option<String>,
#[serde(default)]
pub(super) oauth_audience: Option<String>,
}
#[derive(Deserialize)]
pub(super) struct WireBody {
pub(super) servers: Vec<WireRow>,
}
pub(super) struct ParsedServer {
pub(super) id: String,
pub(super) transport_url: String,
pub(super) auth_header_name: Option<String>,
pub(super) auth_token: Option<SecretString>,
pub(super) allowed_tools: Option<Vec<String>>,
pub(super) roles: Vec<String>,
pub(super) transport: Transport,
pub(super) component_ref: Option<String>,
pub(super) component_version: Option<String>,
pub(super) component_digest: Option<String>,
pub(super) oauth: Option<RouteOAuth>,
pub(super) auth_error: Option<String>,
}
#[derive(Clone, Debug)]
pub struct McpToolEntry {
pub description: String,
pub parameters: serde_json::Value,
}
#[derive(Clone)]
pub struct McpRoute {
pub(super) server_id: String,
pub(super) transport_url: String,
pub(super) auth_header_name: Option<String>,
pub(super) auth_token: Option<SecretString>,
pub(super) raw_tool_name: String,
pub transport: Transport,
pub component_ref: Option<String>,
pub component_version: Option<String>,
pub component_digest: Option<String>,
pub(super) oauth: Option<RouteOAuth>,
}
impl McpRoute {
#[allow(clippy::too_many_arguments)]
pub fn from_parts(
server_id: &str,
transport_url: &str,
auth_header_name: Option<&str>,
auth_token: Option<&str>,
transport: &str,
component_ref: Option<&str>,
component_version: Option<&str>,
component_digest: Option<&str>,
) -> Self {
Self {
server_id: server_id.to_string(),
transport_url: transport_url.to_string(),
auth_header_name: auth_header_name.map(str::to_string),
auth_token: auth_token.map(SecretString::from),
raw_tool_name: String::new(),
transport: if transport == "local-wasm" {
Transport::LocalWasm
} else {
Transport::Http
},
component_ref: component_ref.map(str::to_string),
component_version: component_version.map(str::to_string),
component_digest: component_digest.map(str::to_string),
oauth: None,
}
}
#[allow(clippy::too_many_arguments)]
pub fn from_pack_parts(
server_id: &str,
transport_url: &str,
auth_header_name: Option<&str>,
secret: Option<&str>,
transport: &str,
component_ref: Option<&str>,
component_version: Option<&str>,
component_digest: Option<&str>,
auth: &RouteAuthSpec<'_>,
token_key: String,
) -> Result<Self, String> {
if transport == "local-wasm" {
return Ok(Self::from_parts(
server_id,
transport_url,
auth_header_name,
None,
transport,
component_ref,
component_version,
component_digest,
));
}
match crate::oauth::resolve_route_auth(auth, secret, token_key, TokenProvider::shared())? {
ResolvedAuth::Static { token } => Ok(Self::from_parts(
server_id,
transport_url,
auth_header_name,
token.as_deref(),
transport,
component_ref,
component_version,
component_digest,
)),
ResolvedAuth::OAuth(oauth) => {
let mut route = Self::from_parts(
server_id,
transport_url,
None,
None,
transport,
component_ref,
component_version,
component_digest,
);
route.oauth = Some(oauth);
Ok(route)
}
}
}
#[must_use]
pub fn with_token_provider(mut self, provider: std::sync::Arc<TokenProvider>) -> Self {
self.oauth = self.oauth.map(|oauth| oauth.with_provider(provider));
self
}
#[must_use]
pub fn with_tool(mut self, raw_tool_name: &str) -> Self {
self.raw_tool_name = raw_tool_name.to_string();
self
}
}
impl std::fmt::Debug for McpRoute {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("McpRoute")
.field("server_id", &self.server_id)
.field("transport_url", &self.transport_url)
.field("auth_header_name", &self.auth_header_name)
.field(
"auth_token",
&self.auth_token.as_ref().map(|_| "[REDACTED]"),
)
.field("oauth", &self.oauth)
.field("raw_tool_name", &self.raw_tool_name)
.field("transport", &self.transport)
.field("component_ref", &self.component_ref)
.field("component_version", &self.component_version)
.field("component_digest", &self.component_digest)
.finish()
}
}
#[derive(Clone, Debug, Default)]
pub struct McpPackRoute {
pub server_id: String,
pub transport: String,
pub transport_url: Option<String>,
pub auth_header_name: Option<String>,
pub auth_team: Option<String>,
pub component_ref: Option<String>,
pub component_version: Option<String>,
pub component_digest: Option<String>,
pub auth_mode: Option<String>,
pub oauth_endpoint: Option<String>,
pub oauth_scope: Option<String>,
pub oauth_audience: Option<String>,
}
impl McpPackRoute {
pub fn auth_spec(&self) -> RouteAuthSpec<'_> {
RouteAuthSpec {
auth_mode: self.auth_mode.as_deref(),
oauth_endpoint: self.oauth_endpoint.as_deref(),
oauth_scope: self.oauth_scope.as_deref(),
oauth_audience: self.oauth_audience.as_deref(),
}
}
}
pub struct McpToolCatalog {
pub(super) tools: HashMap<(String, String), McpToolEntry>,
pub(super) routes: HashMap<(String, String), McpRoute>,
pub(super) server_routes: HashMap<String, McpRoute>,
pub(super) server_errors: HashMap<String, String>,
pub(super) fetched_at: Instant,
pub(super) secrets: Option<Arc<dyn SecretsManager>>,
}
impl McpToolCatalog {
pub(super) fn empty() -> Self {
Self {
tools: HashMap::new(),
routes: HashMap::new(),
server_routes: HashMap::new(),
server_errors: HashMap::new(),
fetched_at: Instant::now(),
secrets: None,
}
}
pub fn tools(&self) -> impl Iterator<Item = (&(String, String), &McpToolEntry)> {
self.tools.iter()
}
pub fn len(&self) -> usize {
self.tools.len()
}
pub fn is_empty(&self) -> bool {
self.tools.is_empty()
}
pub fn tool_entry(&self, server_id: &str, tool: &str) -> Option<&McpToolEntry> {
self.tools.get(&(server_id.to_string(), tool.to_string()))
}
pub fn route(&self, server_id: &str, tool: &str) -> Option<&McpRoute> {
self.routes.get(&(server_id.to_string(), tool.to_string()))
}
pub fn resolve_route(&self, server_id: &str, tool: &str) -> Option<McpRoute> {
if let Some(route) = self.route(server_id, tool) {
return Some(route.clone());
}
self.server_routes
.get(server_id)
.map(|route| route.clone().with_tool(tool))
}
pub fn server_error(&self, server_id: &str) -> Option<&str> {
self.server_errors.get(server_id).map(String::as_str)
}
pub fn secrets(&self) -> Option<Arc<dyn SecretsManager>> {
self.secrets.clone()
}
pub fn from_parts(
tools: HashMap<(String, String), McpToolEntry>,
routes: HashMap<(String, String), McpRoute>,
secrets: Option<Arc<dyn SecretsManager>>,
) -> Self {
Self {
tools,
routes,
server_routes: HashMap::new(),
server_errors: HashMap::new(),
fetched_at: Instant::now(),
secrets,
}
}
#[must_use]
pub fn with_server_routes(
mut self,
server_routes: HashMap<String, McpRoute>,
server_errors: HashMap<String, String>,
) -> Self {
self.server_routes = server_routes;
self.server_errors = server_errors;
self
}
}
#[cfg(test)]
pub(crate) fn route_for_tests(server_id: &str, tool: &str, transport_url: &str) -> McpRoute {
McpRoute::from_parts(
server_id,
transport_url,
None,
None,
"http",
None,
None,
None,
)
.with_tool(tool)
}