diff --git a/docs/self-host/hybrid.md b/docs/self-host/hybrid.md index 1a6e587ca..ec9299e3f 100644 --- a/docs/self-host/hybrid.md +++ b/docs/self-host/hybrid.md @@ -163,7 +163,7 @@ The Setup checks show the link as `hybrid_jira` (in Settings, Setup and the inst | Jira (Forge app) | yes | install CoderHelm's Jira app and enter your install id as the team id, or link a hosted team's site ([Jira through CoderHelm](#jira-through-coderhelm)) | | Notion, Confluence, Google Drive | yes | one-click sign-in through CoderHelm; tokens brokered | | Slack and Teams notifications | not needed | your install posts to the incoming webhook you paste | -| Figma, Linear, Sentry, Sanity and other sign-in apps | not needed | your install registers itself with each provider | +| Figma, Linear, Sentry, Sanity and other sign-in apps | not needed | your install registers itself with each provider; Figma signs in only apps it approved, so Figma uses your own Figma app or a key | | Slack and Teams commands | no | there is no shared Slack or Teams app: each team uses its own app's signing secret, as today | | Sign in with GitHub | yes | CoderHelm's app carries the trip to GitHub; your install checks the account with GitHub and applies its own rules ([Sign in with GitHub through CoderHelm](#sign-in-with-github-through-coderhelm)) | | Sign in with Google | no | a self-hosted install has no Google sign-in, through CoderHelm or its own ([Sign-in and people](./sign-in.md#no-google-sign-in)) | diff --git a/docs/self-host/integrations.md b/docs/self-host/integrations.md index bb607d659..e0107349e 100644 --- a/docs/self-host/integrations.md +++ b/docs/self-host/integrations.md @@ -100,6 +100,8 @@ New Relic, Confluence, OpenSearch, REST APIs, SQL databases, CloudWatch metrics - **What you need**\ Nothing. Servers that support OAuth dynamic client registration register your install by themselves the first time someone signs in. The redirect URI is your install's `https://coderhelm.example.com/settings/integrations/mcp-callback/`, and the add flow shows it for servers that need an app registered by hand. +- **Figma**\ + Figma's MCP server signs in only apps Figma approved, so CoderHelm runs Figma's tools with your own Figma app (or a personal access token). Create the app at https://www.figma.com/developers/apps under your Figma team or organization, add the redirect URI above, give it the `current_user:read` and `file_content:read` scopes, and publish it as a private app (no review from Figma; people in that team or organization can sign in). Paste its client id and secret in Settings, Integrations, Figma, Use my own Figma app, then select Connect. - **With hybrid**\ No change: MCP sign-ins always go to your install directly. diff --git a/services/common/src/hybrid/integrations.rs b/services/common/src/hybrid/integrations.rs index 59a5fd952..158117115 100644 --- a/services/common/src/hybrid/integrations.rs +++ b/services/common/src/hybrid/integrations.rs @@ -92,7 +92,7 @@ pub const CATALOG: &[Entry] = &[ id: "mcp_apps", name: "Figma, Linear, Sentry, Sanity and other sign-in apps", mode: Mode::Direct, - through_coderhelm: "Nothing: your install registers itself with each provider's sign-in server and keeps its own tokens.", + through_coderhelm: "Nothing: your install registers itself with each provider's sign-in server and keeps its own tokens. Figma signs in only apps it approved, so Figma uses your own Figma app or a key.", stays_with_you: "Everything.", reason: "", }, diff --git a/services/common/src/knowledge/sources/oauth.rs b/services/common/src/knowledge/sources/oauth.rs index 2b0124c00..7b0c8cf76 100644 --- a/services/common/src/knowledge/sources/oauth.rs +++ b/services/common/src/knowledge/sources/oauth.rs @@ -303,6 +303,7 @@ pub fn connection_record( .map(|(k, v)| (k.to_string(), v.to_string())) .collect(), token_body_json: p.json_body, + refresh_endpoint: String::new(), }); s } @@ -346,6 +347,7 @@ pub fn brokered_connection_record( legacy: false, extra_authorize: vec![], token_body_json: false, + refresh_endpoint: String::new(), }); s } diff --git a/services/common/src/mcp_catalog.rs b/services/common/src/mcp_catalog.rs index 9b75245fc..2dc1b2dbb 100644 --- a/services/common/src/mcp_catalog.rs +++ b/services/common/src/mcp_catalog.rs @@ -66,8 +66,10 @@ pub const CATALOG: &[McpServerDef] = &[ recommended_permissions: "Read-only file access", npx_package: "figma-developer-mcp", // No remote sign-in: Figma's MCP server registers only clients Figma - // approved (dynamic registration answers 403) and takes no client - // metadata documents, so a key is the way in. + // approved (dynamic registration answers 403, and its `mcp:connect` + // scope is refused to any other app) and takes no client metadata + // documents. The package reads Figma's REST API, which takes a key or + // a token from the team's own Figma OAuth app ([`own_app`]). remote_url: "", remote_key: false, key_unavailable: "", @@ -562,6 +564,59 @@ pub fn key_help(id: &str) -> Option { )) } +/// A team's own OAuth app with a vendor whose package reads the vendor's +/// API with an OAuth token as well as a key. The team registers the app with +/// the vendor and pastes its client id and secret; a sign-in then gives the +/// package a token in place of a key, renewed before it expires. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +pub struct OwnApp { + /// Where people approve the app. + pub authorize: &'static str, + /// Where a code is exchanged for tokens. + pub token: &'static str, + /// Where a refresh token is exchanged, when the vendor uses a separate + /// address for it. Empty means [`OwnApp::token`]. + pub refresh: &'static str, + /// Exactly what the package (and the connection check) calls. + pub scopes: &'static [&'static str], + /// The environment variable the package reads the token from. + #[serde(skip)] + pub env_var: &'static str, + /// Asked with the token after a sign-in to confirm it works. + #[serde(skip)] + pub check: &'static str, + /// Where the team creates the app. + pub console: &'static str, + /// The vendor's guide to creating one. + pub guide: &'static str, +} + +/// The own-app sign-in for a catalog server, when its package takes an +/// OAuth token. +pub fn own_app(id: &str) -> Option { + match id { + // Figma's REST API takes tokens from any OAuth app, and a private + // app needs no review from Figma for people on the team or + // organization that owns it. The token endpoint wants the client in + // an HTTP Basic header; refreshing has its own address and never + // rotates the refresh token. The package calls GET /v1/files, + // /v1/files/:key/nodes, /v1/images and /v1/files/:key/images (all + // file_content:read); the check calls GET /v1/me (current_user:read). + // `figma_own_app_asks_for_what_the_package_calls` pins this list. + "figma" => Some(OwnApp { + authorize: "https://www.figma.com/oauth", + token: "https://api.figma.com/v1/oauth/token", + refresh: "https://api.figma.com/v1/oauth/refresh", + scopes: &["current_user:read", "file_content:read"], + env_var: "FIGMA_OAUTH_TOKEN", + check: "https://api.figma.com/v1/me", + console: "https://www.figma.com/developers/apps", + guide: "https://developers.figma.com/docs/rest-api/oauth-apps/", + }), + _ => None, + } +} + /// The catalog's server ids, in catalog order. pub fn ids() -> impl Iterator { CATALOG.iter().map(|p| p.id) @@ -617,6 +672,36 @@ mod tests { assert_eq!(find("nope").map(|p| p.id), None); } + #[test] + fn an_own_app_is_only_for_a_package_that_reads_its_token() { + for p in CATALOG { + let Some(app) = own_app(p.id) else { continue }; + // The token goes to the package, so there must be one. + assert!(!p.npx_package.is_empty(), "{}", p.id); + assert!( + !app.env_var.is_empty() && !app.scopes.is_empty(), + "{}", + p.id + ); + for u in [app.authorize, app.token, app.check, app.console] { + assert!(u.starts_with("https://"), "{}: {u}", p.id); + } + assert!(app.refresh.is_empty() || app.refresh.starts_with("https://")); + } + assert!(own_app("sentry").is_none()); + } + + #[test] + fn figma_own_app_asks_for_what_the_package_calls() { + let app = own_app("figma").unwrap(); + assert_eq!(app.scopes, &["current_user:read", "file_content:read"]); + // figma-developer-mcp sends FIGMA_OAUTH_TOKEN as a bearer token + // (and FIGMA_API_KEY as X-Figma-Token). + assert_eq!(app.env_var, "FIGMA_OAUTH_TOKEN"); + assert_eq!(find("figma").unwrap().npx_package, "figma-developer-mcp"); + assert_eq!(app.refresh, "https://api.figma.com/v1/oauth/refresh"); + } + #[test] fn the_proxy_allowlist_is_exactly_the_catalogs_packages() { // Every package the catalog runs is allowed, and nothing else is: a diff --git a/services/common/src/mcp_remote/mod.rs b/services/common/src/mcp_remote/mod.rs index d220d4b1b..7dc34e1d3 100644 --- a/services/common/src/mcp_remote/mod.rs +++ b/services/common/src/mcp_remote/mod.rs @@ -16,14 +16,18 @@ //! - [`tools`]: the allow list and its second-admin approval. //! - [`store`]: the records, sealed where they hold secrets. //! - [`runtime`]: everything above put together for the gateway and worker. +//! - [`own_app`]: a team's own OAuth app for a catalog package that reads +//! the vendor's API with a token (Figma), signed in to the same way. //! //! A token Coderhelm gets for a server is sent to that server only, and is -//! never handed to a model or passed through to anything else. +//! never handed to a model or passed through to anything else. An own-app +//! token goes only to the vendor's API, through the vendor's package. pub mod client; pub mod discovery; pub mod http; pub mod oauth; +pub mod own_app; pub mod runtime; pub mod store; pub mod tools; diff --git a/services/common/src/mcp_remote/own_app.rs b/services/common/src/mcp_remote/own_app.rs new file mode 100644 index 000000000..8acd2f582 --- /dev/null +++ b/services/common/src/mcp_remote/own_app.rs @@ -0,0 +1,515 @@ +//! A team's own OAuth app for a catalog server whose package reads the +//! vendor's API with an OAuth token as well as a key (Figma). +//! +//! Some vendors' remote MCP servers sign in only apps the vendor approved, +//! while their REST API takes a token from any OAuth app the team registers +//! itself. For those, the team pastes its app's client id and secret, an +//! admin signs in once, and the catalog package gets that token in place of +//! a key ([`token_env`]), renewed before it expires. +//! +//! The sign-in is a [`ServerRecord`] like any other (PKCE, a one-time +//! `state`, sealed tokens, early refresh, "needs reconnect" when the grant +//! is gone), whose `catalog_id` is `app:` and which has no tools: it is +//! never listed or used as an MCP server ([`super::store::is_token_only`]). +//! The token goes only to the vendor's API, through the vendor's package, +//! exactly where a key for it would go. + +use super::http::HttpRequest; +use super::oauth::ClientAuth; +use super::runtime::{ConnError, Runtime}; +use super::store::{AuthKind, OAuthSettings, Owner, ServerRecord, Sharing, Status}; +use crate::mcp_catalog::OwnApp; + +/// The prefix of an own-app sign-in's `catalog_id`. +const PREFIX: &str = "app:"; + +/// The id of the record holding a catalog server's own-app sign-in. +pub fn connection_id(catalog_id: &str) -> String { + format!("app-{catalog_id}") +} + +/// The `catalog_id` of that record. +pub fn tag(catalog_id: &str) -> String { + format!("{PREFIX}{catalog_id}") +} + +/// Is this record a catalog server's own-app sign-in? +pub fn is_app_connection(catalog_id: &str) -> bool { + catalog_id.starts_with(PREFIX) +} + +/// The catalog server an own-app record signs in for. +pub fn catalog_of(tag: &str) -> Option<&str> { + tag.strip_prefix(PREFIX).filter(|id| !id.is_empty()) +} + +/// The record for a team's own app with `app`, its secret already sealed +/// for this record. The team owns the connection: agents run on schedules +/// and webhooks, not in anyone's session. +pub fn record( + catalog_id: &str, + name: &str, + app: &OwnApp, + client_id: &str, + sealed_secret: &str, +) -> ServerRecord { + let issuer = origin(app.authorize); + let mut s = ServerRecord::new(&connection_id(catalog_id), name, &issuer); + s.catalog_id = tag(catalog_id); + s.auth = AuthKind::OAuth; + s.sharing = Sharing::Shared; + s.oauth = Some(OAuthSettings { + issuer, + authorization_endpoint: app.authorize.into(), + token_endpoint: app.token.into(), + refresh_endpoint: app.refresh.into(), + token_auth_methods: vec![ClientAuth::ClientSecretBasic.as_str().into()], + scopes: app.scopes.iter().map(|s| s.to_string()).collect(), + client_id: client_id.into(), + client_auth: ClientAuth::ClientSecretBasic, + client_secret_sealed: sealed_secret.into(), + registration: super::oauth::Registration::Manual.as_str().into(), + ..Default::default() + }); + s +} + +fn origin(u: &str) -> String { + url::Url::parse(u) + .map(|p| p.origin().ascii_serialization()) + .unwrap_or_else(|_| u.to_string()) +} + +/// Why an own app wasn't saved. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SaveError { + /// Not a catalog server with an own-app sign-in. + NoOwnApp, + /// Something the person pasted isn't usable; the message says what. + Invalid(&'static str), + Internal(String), +} + +/// Saves (or replaces) the team's own app for `catalog_id`. A different +/// client id ends the old sign-in (its tokens belong to the other app); the +/// same client id with a new secret keeps it. +pub async fn save( + rt: &Runtime, + catalog_id: &str, + client_id: &str, + client_secret: &str, + by: &str, + at: &str, +) -> Result { + let app = crate::mcp_catalog::own_app(catalog_id).ok_or(SaveError::NoOwnApp)?; + let def = crate::mcp_catalog::find(catalog_id).ok_or(SaveError::NoOwnApp)?; + let (client_id, client_secret) = (client_id.trim(), client_secret.trim()); + if client_id.is_empty() { + return Err(SaveError::Invalid("Paste the app's client id.")); + } + if client_id.len() > 512 || client_secret.len() > 1024 { + return Err(SaveError::Invalid("That client id or secret is too long.")); + } + let id = connection_id(catalog_id); + let old = rt + .store + .get_server(&rt.team, &id) + .await + .map_err(SaveError::Internal)?; + let old_oauth = old.as_ref().and_then(|o| o.oauth.clone()); + let sealed = match (client_secret.is_empty(), &old_oauth) { + // Same app, secret left blank: keep the saved one. + (true, Some(o)) if o.client_id == client_id && !o.client_secret_sealed.is_empty() => { + o.client_secret_sealed.clone() + } + (true, _) => return Err(SaveError::Invalid("Paste the app's client secret.")), + (false, _) => rt + .seal_client_secret(&id, client_secret) + .await + .map_err(SaveError::Internal)?, + }; + let mut rec = record(catalog_id, def.name, &app, client_id, &sealed); + rec.added_by = by.to_ascii_lowercase(); + rec.added_at = at.to_string(); + rec.status = Status::NotConnected; + if let Some(old) = &old { + let same_app = old_oauth.as_ref().is_some_and(|o| o.client_id == client_id); + if same_app { + rec.status = old.status; + rec.status_reason = old.status_reason.clone(); + } else if let Err(e) = rt.disconnect(old, &Owner::Team).await { + return Err(SaveError::Internal(e)); + } + rec.added_by = old.added_by.clone(); + rec.added_at = old.added_at.clone(); + rec.custom_prompt = old.custom_prompt.clone(); + } + rt.store + .put_server(&rt.team, &rec) + .await + .map_err(SaveError::Internal)?; + Ok(rec) +} + +/// The team's own-app record for `catalog_id`, when one is saved. +pub async fn load(rt: &Runtime, catalog_id: &str) -> Result, String> { + if crate::mcp_catalog::own_app(catalog_id).is_none() { + return Ok(None); + } + Ok(rt + .store + .get_server(&rt.team, &connection_id(catalog_id)) + .await? + .filter(|s| s.catalog_id == tag(catalog_id))) +} + +/// Is the team signed in with its own app for `catalog_id` right now? +pub async fn connected(rt: &Runtime, catalog_id: &str) -> bool { + let Ok(Some(s)) = load(rt, catalog_id).await else { + return false; + }; + matches!( + rt.store.get_token(&rt.team, &s.id, &Owner::Team).await, + Ok(Some(t)) if t.status == Status::Connected + ) +} + +/// The environment variable and token the catalog package for `catalog_id` +/// runs with when the team signed in with its own app: `Ok(None)` when it +/// hasn't (the package uses the saved key, if any). The token is renewed +/// first when it is about to expire. +pub async fn token_env( + rt: &Runtime, + catalog_id: &str, +) -> Result, ConnError> { + let Some(app) = crate::mcp_catalog::own_app(catalog_id) else { + return Ok(None); + }; + let Some(s) = load(rt, catalog_id).await.map_err(ConnError::Temporary)? else { + return Ok(None); + }; + match rt.auth_header(&s, &Owner::Team, false).await { + Ok(Some(h)) => Ok(Some((app.env_var, bearer_value(&h.1).to_string()))), + Ok(None) | Err(ConnError::NotConnected) => Ok(None), + Err(e) => Err(e), + } +} + +fn bearer_value(header: &str) -> &str { + header.strip_prefix("Bearer ").unwrap_or(header) +} + +/// Asks the vendor's API who the token belongs to, right after a sign-in, +/// and records the answer on the connection: a token the API refuses is +/// marked so the card says so instead of agents finding out. +pub async fn check(rt: &Runtime, s: &ServerRecord) -> Result<(), String> { + let catalog_id = catalog_of(&s.catalog_id).ok_or("This isn't an own-app sign-in.")?; + let app = + crate::mcp_catalog::own_app(catalog_id).ok_or("This server has no own-app sign-in.")?; + let header = rt + .auth_header(s, &Owner::Team, false) + .await + .map_err(|e| e.to_string())? + .ok_or("Not signed in.")?; + let resp = rt + .http + .send(HttpRequest::get(app.check).header(&header.0, &header.1)) + .await + .map_err(|e| format!("Couldn't reach {}: {e}", origin(app.check)))?; + if (200..300).contains(&resp.status) { + rt.mark(s, &Owner::Team, Status::Connected, "", &[]).await; + return Ok(()); + } + let why = match resp.status { + 401 | 403 => format!( + "{} refused the new sign-in (HTTP {}). Check the app's scopes and that it is published for your team, then connect again.", + s.name, resp.status + ), + n => format!("{} answered HTTP {n} when the sign-in was checked. Try again.", s.name), + }; + let status = if matches!(resp.status, 401 | 403) { + Status::NeedsReconnect + } else { + Status::Failed + }; + rt.mark(s, &Owner::Team, status, &why, &[]).await; + Err(why) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::mcp_remote::http::fake::{json as fjson, Fake}; + use crate::mcp_remote::http::Method; + use crate::mcp_remote::runtime::testing::{sign_in, FakeKms}; + use crate::mcp_remote::store::fake::MemStore; + use serde_json::json; + use std::sync::Arc; + + const REDIRECT: &str = "https://coderhelm.example.com/settings/integrations/mcp-callback/"; + + fn rt_with(http: Arc, now: i64) -> Runtime { + Runtime { + store: Arc::new(MemStore::default()), + cipher: Arc::new(FakeKms), + http, + team: "TEAM#a".into(), + clock: Arc::new(move || now), + } + } + + fn query(url: &str) -> std::collections::HashMap { + url::Url::parse(url) + .unwrap() + .query_pairs() + .into_owned() + .collect() + } + + #[tokio::test] + async fn figma_signs_in_with_the_teams_own_app() { + let http = Arc::new(Fake::default()); + let rt = rt_with(http.clone(), 1_000_000); + let mut s = save( + &rt, + "figma", + " client-1 ", + "secret-1", + "Ada@Example.com", + "t0", + ) + .await + .unwrap(); + assert_eq!(s.id, "app-figma"); + assert_eq!(s.catalog_id, "app:figma"); + assert_eq!(s.added_by, "ada@example.com"); + // Never an MCP server: not listed, never usable by agents. + assert!(rt.store.list_servers(&rt.team).await.unwrap().is_empty()); + assert!(rt + .store + .get_server(&rt.team, "app-figma") + .await + .unwrap() + .is_some()); + + let url = rt + .start_sign_in( + &mut s, + &Owner::Team, + "sub-1", + "ada@example.com", + REDIRECT, + Some("https://coderhelm.example.com/integrations/mcp-client.json"), + ) + .await + .unwrap(); + assert!(url.starts_with("https://www.figma.com/oauth?"), "{url}"); + let q = query(&url); + assert_eq!(q["client_id"], "client-1"); + assert_eq!(q["redirect_uri"], REDIRECT); + assert_eq!(q["scope"], "current_user:read file_content:read"); + assert_eq!(q["response_type"], "code"); + assert_eq!(q["code_challenge_method"], "S256"); + assert!(!q.contains_key("resource")); + + http.on( + Method::Post, + "https://api.figma.com/v1/oauth/token", + fjson(200, json!({"user_id_string": "1", "access_token": "at-1", "token_type": "bearer", "expires_in": 7_776_000, "refresh_token": "rt-1"})), + ); + rt.finish_sign_in( + &q["state"], + Some("code-1"), + None, + None, + "sub-1", + "ada@example.com", + ) + .await + .unwrap(); + let sent = http.sent_to("https://api.figma.com/v1/oauth/token"); + assert_eq!(sent.len(), 1); + // Figma wants the client in a Basic header, never in the body. + let basic = sent[0].header_value("Authorization").unwrap(); + assert!(basic.starts_with("Basic "), "{basic}"); + let body = sent[0].body_text(); + assert!(body.contains("grant_type=authorization_code") && body.contains("code=code-1")); + assert!(!body.contains("client_secret")); + + assert!(connected(&rt, "figma").await); + assert_eq!( + token_env(&rt, "figma").await.unwrap(), + Some(("FIGMA_OAUTH_TOKEN", "at-1".to_string())) + ); + } + + #[tokio::test] + async fn an_expiring_token_is_renewed_at_figmas_refresh_address() { + let http = Arc::new(Fake::default()); + let rt = rt_with(http.clone(), 2_000_000); + save( + &rt, + "figma", + "client-1", + "secret-1", + "ada@example.com", + "t0", + ) + .await + .unwrap(); + sign_in( + &rt, + "app-figma", + &Owner::Team, + "at-old", + Some("rt-1"), + Some(2_000_010), + "ada@example.com", + ) + .await; + http.on( + Method::Post, + "https://api.figma.com/v1/oauth/refresh", + fjson( + 200, + json!({"access_token": "at-new", "token_type": "bearer", "expires_in": 7_776_000}), + ), + ); + let got = token_env(&rt, "figma").await.unwrap(); + assert_eq!(got, Some(("FIGMA_OAUTH_TOKEN", "at-new".to_string()))); + let sent = http.sent_to("https://api.figma.com/v1/oauth/refresh"); + assert_eq!(sent.len(), 1); + assert!(sent[0] + .header_value("Authorization") + .unwrap() + .starts_with("Basic ")); + assert!(sent[0].body_text().contains("refresh_token=rt-1")); + assert!(http + .sent_to("https://api.figma.com/v1/oauth/token") + .is_empty()); + // Figma doesn't rotate refresh tokens: the old one is kept for next time. + http.on( + Method::Post, + "https://api.figma.com/v1/oauth/refresh", + fjson(200, json!({"access_token": "at-3", "expires_in": 1})), + ); + let s = load(&rt, "figma").await.unwrap().unwrap(); + rt.auth_header(&s, &Owner::Team, true).await.unwrap(); + let sent = http.sent_to("https://api.figma.com/v1/oauth/refresh"); + assert!(sent[1].body_text().contains("refresh_token=rt-1")); + } + + #[tokio::test] + async fn without_a_sign_in_the_package_keeps_its_key() { + let rt = rt_with(Arc::new(Fake::default()), 1); + assert_eq!(token_env(&rt, "figma").await.unwrap(), None); + save(&rt, "figma", "client-1", "secret-1", "a@example.com", "t0") + .await + .unwrap(); + assert_eq!(token_env(&rt, "figma").await.unwrap(), None); + assert!(!connected(&rt, "figma").await); + // A server without an own app never has one. + assert_eq!(token_env(&rt, "sentry").await.unwrap(), None); + assert_eq!( + save(&rt, "sentry", "c", "s", "a@example.com", "t0") + .await + .unwrap_err(), + SaveError::NoOwnApp + ); + } + + #[tokio::test] + async fn another_app_ends_the_old_sign_in_and_a_new_secret_keeps_it() { + let rt = rt_with(Arc::new(Fake::default()), 1); + assert_eq!( + save(&rt, "figma", "client-1", "", "a@example.com", "t0") + .await + .unwrap_err(), + SaveError::Invalid("Paste the app's client secret.") + ); + save(&rt, "figma", "client-1", "secret-1", "a@example.com", "t0") + .await + .unwrap(); + sign_in( + &rt, + "app-figma", + &Owner::Team, + "at", + Some("rt"), + None, + "a@example.com", + ) + .await; + rt.store + .set_status(&rt.team, "app-figma", Status::Connected, "") + .await + .unwrap(); + // Same app, secret left blank: the saved secret and sign-in stay. + let s = save(&rt, "figma", "client-1", "", "b@example.com", "t1") + .await + .unwrap(); + assert_eq!(s.status, Status::Connected); + assert_eq!(s.added_by, "a@example.com"); + assert!(connected(&rt, "figma").await); + // Another app: the old tokens are gone. + let s = save(&rt, "figma", "client-2", "secret-2", "b@example.com", "t2") + .await + .unwrap(); + assert_eq!(s.status, Status::NotConnected); + assert!(!connected(&rt, "figma").await); + assert_eq!(s.oauth.unwrap().client_id, "client-2"); + } + + #[tokio::test] + async fn the_check_marks_a_refused_token() { + let http = Arc::new(Fake::default()); + let rt = rt_with(http.clone(), 1); + let s = save(&rt, "figma", "client-1", "secret-1", "a@example.com", "t0") + .await + .unwrap(); + sign_in( + &rt, + "app-figma", + &Owner::Team, + "at", + None, + None, + "a@example.com", + ) + .await; + http.on( + Method::Get, + "https://api.figma.com/v1/me", + fjson(200, json!({"id": "1"})), + ); + check(&rt, &s).await.unwrap(); + assert_eq!( + http.sent_to("https://api.figma.com/v1/me")[0].header_value("Authorization"), + Some("Bearer at") + ); + + let http = Arc::new(Fake::default()); + let rt = rt_with(http.clone(), 1); + let s = save(&rt, "figma", "client-1", "secret-1", "a@example.com", "t0") + .await + .unwrap(); + sign_in( + &rt, + "app-figma", + &Owner::Team, + "at", + None, + None, + "a@example.com", + ) + .await; + http.on( + Method::Get, + "https://api.figma.com/v1/me", + fjson(403, json!({"status": 403, "err": "Invalid scope"})), + ); + let e = check(&rt, &s).await.unwrap_err(); + assert!(e.contains("published for your team"), "{e}"); + assert!(!connected(&rt, "figma").await); + } +} diff --git a/services/common/src/mcp_remote/runtime.rs b/services/common/src/mcp_remote/runtime.rs index 37876ef4b..6f5e5c83e 100644 --- a/services/common/src/mcp_remote/runtime.rs +++ b/services/common/src/mcp_remote/runtime.rs @@ -387,8 +387,12 @@ impl Runtime { .as_ref() .ok_or_else(|| ConnError::Failed("No sign-in settings.".into()))?; let client = self.client(s).await.map_err(ConnError::Failed)?; - let mut req = - oauth::refresh_request(&o.token_endpoint, &client, &refresh_token, &o.resource); + let endpoint = if o.refresh_endpoint.is_empty() { + &o.token_endpoint + } else { + &o.refresh_endpoint + }; + let mut req = oauth::refresh_request(endpoint, &client, &refresh_token, &o.resource); if o.token_body_json { req = oauth::as_json_body(req); } diff --git a/services/common/src/mcp_remote/store.rs b/services/common/src/mcp_remote/store.rs index c60943a56..a6903f0aa 100644 --- a/services/common/src/mcp_remote/store.rs +++ b/services/common/src/mcp_remote/store.rs @@ -162,6 +162,9 @@ pub struct OAuthSettings { pub extra_authorize: Vec<(String, String)>, /// The token endpoint takes JSON instead of a form (Notion, Atlassian). pub token_body_json: bool, + /// Where a refresh token is exchanged, when the provider uses its own + /// address for that (Figma). Empty means the token endpoint. + pub refresh_endpoint: String, } impl OAuthSettings { @@ -216,6 +219,7 @@ impl OAuthSettings { "legacy": self.legacy, "extra_authorize": self.extra_authorize, "token_body_json": self.token_body_json, + "refresh_endpoint": self.refresh_endpoint, }) } @@ -250,6 +254,7 @@ impl OAuthSettings { extra_authorize: serde_json::from_value(v["extra_authorize"].clone()) .unwrap_or_default(), token_body_json: v["token_body_json"].as_bool().unwrap_or(false), + refresh_endpoint: st("refresh_endpoint"), } } } @@ -321,6 +326,14 @@ fn num(v: i64) -> AttributeValue { AttributeValue::N(v.to_string()) } +/// A record that only holds a sign-in for something else to use (a +/// knowledge source's sync, a catalog package run with the team's own app), +/// never an MCP server of its own. +pub fn is_token_only(catalog_id: &str) -> bool { + crate::knowledge::sources::oauth::is_source_connection(catalog_id) + || super::own_app::is_app_connection(catalog_id) +} + fn set_json(v: &BTreeSet) -> String { serde_json::to_string(v).unwrap_or_else(|_| "[]".into()) } @@ -860,9 +873,10 @@ impl Store for DynamoStore { .await? .iter() .filter_map(ServerRecord::from_item) - // A knowledge source's sign-in is kept here too, but it is never - // an MCP server (`knowledge::sources::oauth`). - .filter(|s| !crate::knowledge::sources::oauth::is_source_connection(&s.catalog_id)) + // A knowledge source's sign-in and a catalog server's own-app + // sign-in are kept here too, but neither is an MCP server + // (`knowledge::sources::oauth`, `mcp_remote::own_app`). + .filter(|s| !is_token_only(&s.catalog_id)) .collect()) } @@ -1152,7 +1166,7 @@ pub mod fake { .prefix(team, SERVER_PREFIX) .iter() .filter_map(ServerRecord::from_item) - .filter(|s| !crate::knowledge::sources::oauth::is_source_connection(&s.catalog_id)) + .filter(|s| !is_token_only(&s.catalog_id)) .collect()) } async fn put_server(&self, team: &str, s: &ServerRecord) -> Result<(), String> { diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index d8ca7e3dd..fea043c49 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -1065,6 +1065,10 @@ async fn main() -> Result<(), Error> { "/mcp-servers/:id/connection", delete(routes::mcp_servers::disconnect), ) + .route( + "/mcp-servers/apps/:catalog_id", + put(routes::mcp_servers::save_own_app), + ) .route( "/mcp-servers/:id/client", put(routes::mcp_servers::set_client), diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index b0542a94e..79223c4d8 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -554,6 +554,7 @@ pub const CAPABILITIES: &[Capability] = &[ "mcp_servers::create", "mcp_servers::remove", "mcp_servers::set_client", + "mcp_servers::save_own_app", "mcp_servers::set_key", "mcp_servers::set_tools", "mcp_servers::approve", diff --git a/services/gateway/src/routes/integrations.rs b/services/gateway/src/routes/integrations.rs index 6474038b4..40fe76383 100644 --- a/services/gateway/src/routes/integrations.rs +++ b/services/gateway/src/routes/integrations.rs @@ -126,6 +126,32 @@ pub fn plugin_state( } } +/// A catalog server with the team's own app saved (`own_app` is its card +/// JSON): connected through it, it needs signing in again, or (not signed +/// in yet) the key's state stands, saying a sign-in is waiting. +pub fn own_app_state(own_app: &Value, key: &CardState) -> CardState { + let reason = own_app["status_reason"].as_str().unwrap_or("").to_string(); + match own_app["status"].as_str().unwrap_or("") { + "connected" => cs("connected", "Signed in with your own app.", "manage"), + "needs_reconnect" => cs( + "needs_reconnect", + if reason.is_empty() { + "Your own app's sign-in has to be renewed.".to_string() + } else { + reason + }, + "reconnect", + ), + "failed" => cs("error", reason, "check_again"), + _ if key.status == "connected" => key.clone(), + _ => cs( + "not_connected", + "Your own app is saved. Connect it to sign in.", + "connect", + ), + } +} + /// A remote MCP server, as seen by one person: their own connection on a /// personal server, the team's otherwise. pub fn remote_state( @@ -673,7 +699,29 @@ pub async fn list( Some(r) => r.tools_listed_at.clone(), None => tested_at, }; + // Signed in with the team's own app: that sign-in is what agents + // use (the key stays as a fallback), so its state is the card's. + let own = match common::mcp_remote::own_app::load(&rt, &id).await { + Ok(o) => o, + Err(e) => { + warn!(error = %e, plugin = %id, "Could not read own app"); + None + } + }; + let own_json = match &own { + Some(o) => Some(super::mcp_servers::own_app_json(&rt, o, &state.config.stage).await), + None => None, + }; + let st = match own_json.as_ref().map(|o| own_app_state(o, &st)) { + Some(s) => s, + None => st, + }; + // Where the team's own app sends people back, for its setup steps. + let own_redirect = common::mcp_catalog::own_app(&id) + .map(|_| super::mcp_servers::redirect_uri(&state.config.stage)); let detail = json!({ + "own_app": own_json, + "own_app_redirect_uri": own_redirect, "remote": remote.map(|r| r.public_json(my_tokens.get(&r.id), can_edit)), "plugin": p, "enabled": enabled.unwrap_or(false), @@ -901,6 +949,24 @@ pub async fn set_aws_abilities( #[cfg(test)] mod tests { use super::*; + + #[test] + fn an_own_app_sign_in_is_the_cards_state() { + let key_off = plugin_state(None, false, None, "", false); + let key_on = plugin_state(Some(true), true, Some(true), "", true); + let own = |status: &str, reason: &str| json!({ "status": status, "status_reason": reason }); + let st = own_app_state(&own("connected", ""), &key_off); + assert_eq!((st.status, st.action), ("connected", "manage")); + let st = own_app_state(&own("needs_reconnect", "Figma refused it."), &key_on); + assert_eq!( + (st.status, st.reason.as_str()), + ("needs_reconnect", "Figma refused it.") + ); + // Saved but not signed in: a working key still stands. + assert_eq!(own_app_state(&own("not_connected", ""), &key_on), key_on); + let st = own_app_state(&own("not_connected", ""), &key_off); + assert_eq!((st.status, st.action), ("not_connected", "connect")); + } use common::live::identity::RoleCheck; fn account() -> AwsAccount { diff --git a/services/gateway/src/routes/mcp_servers.rs b/services/gateway/src/routes/mcp_servers.rs index 6610c562b..30000c280 100644 --- a/services/gateway/src/routes/mcp_servers.rs +++ b/services/gateway/src/routes/mcp_servers.rs @@ -27,7 +27,7 @@ use axum::{ use common::mcp_remote::http::check_url; use common::mcp_remote::runtime::{detect, Detected, Runtime}; use common::mcp_remote::store::{AuthKind, OAuthSettings, Owner, ServerRecord, Sharing, Status}; -use common::mcp_remote::{oauth, tools}; +use common::mcp_remote::{oauth, own_app, tools}; use serde_json::{json, Value}; use tracing::{error, info, warn}; @@ -537,6 +537,68 @@ pub async fn set_client( )) } +/// PUT /api/mcp-servers/apps/:catalog_id { client_id, client_secret? } — the +/// team's own OAuth app for a catalog server whose package takes a token +/// (Figma). Connecting it is then `POST /api/mcp-servers/app-/connect`, +/// and removing it `DELETE /api/mcp-servers/app-`. A blank secret keeps +/// the saved one for the same client id; another client id ends the old +/// sign-in. +pub async fn save_own_app( + State(state): State>, + Extension(claims): Extension, + Path(catalog_id): Path, + Json(body): Json, +) -> Reply { + claims.require_role(3).map_err(forbidden)?; + let rt = runtime(&state, &claims.team_id); + let s = own_app::save( + &rt, + &catalog_id, + body["client_id"].as_str().unwrap_or(""), + body["client_secret"].as_str().unwrap_or(""), + &claims.email, + &chrono::Utc::now().to_rfc3339(), + ) + .await + .map_err(|e| match e { + own_app::SaveError::NoOwnApp => fail( + StatusCode::NOT_FOUND, + "This server can't use your own app. Use a key instead.", + ), + own_app::SaveError::Invalid(m) => fail(StatusCode::BAD_REQUEST, m), + own_app::SaveError::Internal(e) => internal("save own app", e), + })?; + info!(team = %rt.team, server = %s.id, by = %claims.email, "Own app saved"); + Ok(Json( + json!({ "own_app": own_app_json(&rt, &s, &state.config.stage).await }), + )) +} + +/// A team's own app for a catalog server, for its card: never the secret. +pub async fn own_app_json(rt: &Runtime, s: &ServerRecord, stage: &str) -> Value { + let token = rt + .store + .get_token(&rt.team, &s.id, &Owner::Team) + .await + .ok() + .flatten(); + let (status, reason) = match &token { + Some(t) => (t.status, t.status_reason.clone()), + None => (Status::NotConnected, String::new()), + }; + let o = s.oauth.as_ref(); + json!({ + "id": s.id, + "client_id": o.map(|o| o.client_id.as_str()).unwrap_or(""), + "has_secret": o.is_some_and(|o| !o.client_secret_sealed.is_empty()), + "status": status.as_str(), + "status_reason": reason, + "connected_by": token.as_ref().map(|t| t.connected_by.as_str()).unwrap_or(""), + "connected_at": token.as_ref().map(|t| t.connected_at.as_str()).unwrap_or(""), + "redirect_uri": redirect_uri(stage), + }) +} + /// PUT /api/mcp-servers/:id/key { header_name?, header_value } — replace a /// static key (checked against the server before it is saved). pub async fn set_key( @@ -664,6 +726,18 @@ pub async fn oauth_callback( ) .await .map_err(|e| fail(StatusCode::BAD_REQUEST, &e))?; + // A catalog server's own-app sign-in has no tools either: its package + // gets the token. Check the token with the vendor's API now, so a wrong + // scope or an unpublished app shows on the card instead of in a run. + if let Some(catalog) = own_app::catalog_of(&s.catalog_id) { + let checked = own_app::check(&rt, &s).await; + info!(team = %rt.team, server = %s.id, ok = checked.is_ok(), "Own app signed in"); + return Ok(Json(json!({ + "server": { "id": s.id, "name": s.name, "catalog_id": catalog }, + "tools_error": checked.err(), + "own_app": true, + }))); + } // List the tools now so the picker has them. A failure here leaves the // connection saved; the status says why. // A knowledge source's sign-in has no tools to list. diff --git a/services/gateway/src/routes/plans.rs b/services/gateway/src/routes/plans.rs index 7c32b1c56..b0b9041bf 100644 --- a/services/gateway/src/routes/plans.rs +++ b/services/gateway/src/routes/plans.rs @@ -3849,9 +3849,29 @@ fn mcp_table(state: &AppState) -> &str { } /// Load enabled plugins for the team, returning (server_id, has_credentials, custom_prompt). +/// A catalog server the team signed in to with its own app counts as +/// switched on with credentials. pub(crate) async fn load_enabled_plugins( state: &AppState, team_id: &str, +) -> Vec<(String, bool, Option)> { + let mut out = load_switched_on_plugins(state, team_id).await; + let rt = super::mcp_servers::runtime(state, team_id); + for id in common::mcp_catalog::ids() { + if !common::mcp_remote::own_app::connected(&rt, id).await { + continue; + } + match out.iter_mut().find(|(p, _, _)| p == id) { + Some(p) => p.1 = true, + None => out.push((id.to_string(), true, None)), + } + } + out +} + +async fn load_switched_on_plugins( + state: &AppState, + team_id: &str, ) -> Vec<(String, bool, Option)> { state .dynamo @@ -3940,19 +3960,10 @@ pub(crate) async fn invoke_mcp_tool( // Find catalog entry for this server let entry = common::mcp_catalog::find(server_id) .ok_or_else(|| format!("Unknown MCP server: {server_id}"))?; - let (npx_package, env_mapping) = (entry.npx_package, entry.env_mapping); + let npx_package = entry.npx_package; - // Open the saved values for this call only. - let creds = super::plugins::load_credentials(state, team_id, server_id).await?; - - // Map credential fields to env vars - let mut env_vars = serde_json::Map::new(); - for (cred_key, env_var) in env_mapping { - if let Some(val) = creds.get(*cred_key) { - env_vars.insert(env_var.to_string(), json!(val)); - } - } - drop(creds); + // The team's own-app token or its saved key, opened for this call only. + let env_vars = super::plugins::package_env(state, team_id, entry).await?; // Build proxy Lambda payload let payload = json!({ diff --git a/services/gateway/src/routes/plugins.rs b/services/gateway/src/routes/plugins.rs index b195fe85e..d2441590b 100644 --- a/services/gateway/src/routes/plugins.rs +++ b/services/gateway/src/routes/plugins.rs @@ -72,14 +72,49 @@ pub(crate) fn mcp_table(state: &AppState) -> &str { } } -/// The catalog as the Integrations page shows it. +/// The catalog as the Integrations page shows it. A server whose package +/// also takes a token from the team's own OAuth app says where to create +/// one and the scopes to give it (`own_app`). pub(crate) fn catalog_json() -> Vec { CATALOG .iter() - .filter_map(|p| serde_json::to_value(p).ok()) + .filter_map(|p| { + let mut v = serde_json::to_value(p).ok()?; + if let Some(app) = common::mcp_catalog::own_app(p.id) { + v["own_app"] = serde_json::to_value(app).ok()?; + } + Some(v) + }) .collect() } +/// The environment a catalog package runs with for a team: the token from +/// the team's own app when it signed in with one, else its saved key. Opened +/// for this call only. +pub(crate) async fn package_env( + state: &AppState, + team_id: &str, + def: &common::mcp_catalog::McpServerDef, +) -> Result, String> { + let mut env = serde_json::Map::new(); + let rt = super::mcp_servers::runtime(state, team_id); + match common::mcp_remote::own_app::token_env(&rt, def.id).await { + Ok(Some((var, token))) => { + env.insert(var.to_string(), json!(token)); + return Ok(env); + } + Ok(None) => {} + Err(e) => return Err(format!("{}'s sign-in: {e}", def.name)), + } + let creds = load_credentials(state, team_id, def.id).await?; + for (cred_key, env_var) in def.env_mapping { + if let Some(val) = creds.get(*cred_key) { + env.insert(env_var.to_string(), json!(val)); + } + } + Ok(env) +} + fn cipher(state: &AppState) -> Kms<'_> { Kms { client: &state.kms, diff --git a/services/worker/src/agent/mcp.rs b/services/worker/src/agent/mcp.rs index 0225ad505..b5e528858 100644 --- a/services/worker/src/agent/mcp.rs +++ b/services/worker/src/agent/mcp.rs @@ -44,6 +44,20 @@ pub struct McpPlugin { /// Set for a remote server (Streamable HTTP, OAuth or a key): calls go /// to it directly instead of through the proxy Lambda. pub remote: Option, + /// Set when the team signed in to this catalog server with its own + /// OAuth app: the package runs with that token (renewed when due) + /// instead of the saved key. + pub own_app: Option, +} + +/// The team's runtime for its own-app sign-in to a catalog server. +#[derive(Clone)] +pub struct OwnAppBinding(pub Runtime); + +impl std::fmt::Debug for OwnAppBinding { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("OwnAppBinding").finish_non_exhaustive() + } } /// A remote MCP server, bound to the connection this run uses. @@ -108,6 +122,7 @@ pub async fn load_remote_plugins( stored: common::mcp_credentials::Stored::None, kms: kms.clone(), custom_prompt: Some(server.custom_prompt.clone()).filter(|p| !p.trim().is_empty()), + own_app: None, remote: Some(RemoteBinding { rt: rt.clone(), server, @@ -346,6 +361,16 @@ pub async fn call_tool( async fn build_env_vars( plugin: &McpPlugin, ) -> Result> { + if let Some(rt) = &plugin.own_app { + match common::mcp_remote::own_app::token_env(&rt.0, &plugin.server_id).await { + Ok(Some((var, token))) => { + return Ok(json!({ var: token })); + } + // Disconnected since the run started: the saved key, if any. + Ok(None) => {} + Err(e) => return Err(format!("{} sign-in: {e}", plugin.server_id).into()), + } + } let kms = common::mcp_credentials::Kms { client: &plugin.kms, key_id: "", @@ -364,8 +389,61 @@ async fn build_env_vars( } /// Load enabled MCP plugins with credentials for a team from DynamoDB. -/// Returns plugins that are enabled AND have credentials stored. +/// Returns plugins that are enabled AND have credentials stored, and the +/// catalog servers the team signed in to with its own OAuth app (whose +/// token takes the place of a key; `key_id` seals a renewed token). pub async fn load_team_plugins( + dynamo: &aws_sdk_dynamodb::Client, + kms: &aws_sdk_kms::Client, + settings_table: &str, + key_id: &str, + team_id: &str, +) -> Vec { + let mut plugins = load_keyed_plugins(dynamo, kms, settings_table, team_id).await; + let rt = Runtime::aws(dynamo.clone(), settings_table, kms.clone(), key_id, team_id); + for id in common::mcp_catalog::ids() { + if !common::mcp_remote::own_app::connected(&rt, id).await { + continue; + } + let Some(def) = common::mcp_catalog::find(id) else { + continue; + }; + with_own_app(&mut plugins, def, &rt, kms, team_id); + } + plugins +} + +/// Marks `def`'s plugin as run with the team's own app, adding it when no +/// key switched it on. +fn with_own_app( + plugins: &mut Vec, + def: &common::mcp_catalog::McpServerDef, + rt: &Runtime, + kms: &aws_sdk_kms::Client, + team_id: &str, +) { + if let Some(p) = plugins.iter_mut().find(|p| p.server_id == def.id) { + p.own_app = Some(OwnAppBinding(rt.clone())); + return; + } + plugins.push(McpPlugin { + server_id: def.id.to_string(), + npx_package: def.npx_package.to_string(), + env_mapping: Vec::new(), + team_id: team_id.to_string(), + stored: common::mcp_credentials::Stored::None, + kms: kms.clone(), + custom_prompt: None, + remote: None, + own_app: Some(OwnAppBinding(rt.clone())), + }); + info!( + server_id = def.id, + "Catalog server runs with the team's own app" + ); +} + +async fn load_keyed_plugins( dynamo: &aws_sdk_dynamodb::Client, kms: &aws_sdk_kms::Client, settings_table: &str, @@ -456,6 +534,7 @@ pub async fn load_team_plugins( kms: kms.clone(), custom_prompt, remote: None, + own_app: None, }); } @@ -481,9 +560,44 @@ mod tests { kms: aws_sdk_kms::Client::from_conf(conf), custom_prompt: None, remote: None, + own_app: None, } } + fn runtime() -> Runtime { + let conf = aws_sdk_dynamodb::Config::builder() + .behavior_version(aws_sdk_dynamodb::config::BehaviorVersion::latest()) + .region(aws_sdk_dynamodb::config::Region::new("us-east-1")) + .build(); + let kms = local("x").kms; + Runtime::aws( + aws_sdk_dynamodb::Client::from_conf(conf), + "t", + kms, + "k", + "TEAM#a", + ) + } + + #[test] + fn an_own_app_sign_in_runs_the_package_without_a_key() { + let rt = runtime(); + let kms = local("x").kms; + let figma = common::mcp_catalog::find("figma").unwrap(); + // Switched on with a key: the same plugin now uses the sign-in. + let mut plugins = vec![local("figma"), local("sentry")]; + with_own_app(&mut plugins, figma, &rt, &kms, "TEAM#a"); + assert_eq!(plugins.len(), 2); + assert!(plugins[0].own_app.is_some() && plugins[1].own_app.is_none()); + // No key at all: the plugin is added, running the catalog package. + let mut plugins = vec![local("sentry")]; + with_own_app(&mut plugins, figma, &rt, &kms, "TEAM#a"); + let p = plugins.iter().find(|p| p.server_id == "figma").unwrap(); + assert_eq!(p.npx_package, "figma-developer-mcp"); + assert!(p.own_app.is_some() && p.remote.is_none()); + assert!(matches!(p.stored, common::mcp_credentials::Stored::None)); + } + #[test] fn a_remote_connection_replaces_the_same_servers_key() { let mut remote = local("linear"); diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index cefdc3718..32e5b5e92 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -458,7 +458,14 @@ pub async fn run( &state.config.mcp_configs_table_name }; let mcp_plugins = mcp::merge_plugins( - mcp::load_team_plugins(&state.dynamo, &state.kms, mcp_table, &msg.team_id).await, + mcp::load_team_plugins( + &state.dynamo, + &state.kms, + mcp_table, + &state.config.secrets_key_id, + &msg.team_id, + ) + .await, mcp::load_remote_plugins( &state.dynamo, &state.kms, diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index a0b71d265..85fa89c8e 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -2104,7 +2104,14 @@ async fn run_passes( &state.config.mcp_configs_table_name }; let mcp_plugins = mcp::merge_plugins( - mcp::load_team_plugins(&state.dynamo, &state.kms, mcp_table, &msg.team_id).await, + mcp::load_team_plugins( + &state.dynamo, + &state.kms, + mcp_table, + &state.config.secrets_key_id, + &msg.team_id, + ) + .await, mcp::load_remote_plugins( &state.dynamo, &state.kms, diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 0f58a5d2a..76e4d35ae 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -418,7 +418,14 @@ Then the ```fix_location.json block described above."#, &state.config.mcp_configs_table_name }; let mcp_plugins = mcp::merge_plugins( - mcp::load_team_plugins(&state.dynamo, &state.kms, mcp_table, &msg.team_id).await, + mcp::load_team_plugins( + &state.dynamo, + &state.kms, + mcp_table, + &state.config.secrets_key_id, + &msg.team_id, + ) + .await, mcp::load_remote_plugins( &state.dynamo, &state.kms, diff --git a/services/worker/src/passes/plugins.rs b/services/worker/src/passes/plugins.rs index 9516c7dec..937c13541 100644 --- a/services/worker/src/passes/plugins.rs +++ b/services/worker/src/passes/plugins.rs @@ -393,11 +393,17 @@ impl CatalogConnections<'_> { } else { &self.state.config.mcp_configs_table_name }; - crate::agent::mcp::load_team_plugins(&self.state.dynamo, &self.state.kms, table, team) - .await - .into_iter() - .find(|p| p.server_id == server) - .ok_or_else(|| format!("{server} isn't connected on the Connections page.")) + crate::agent::mcp::load_team_plugins( + &self.state.dynamo, + &self.state.kms, + table, + &self.state.config.secrets_key_id, + team, + ) + .await + .into_iter() + .find(|p| p.server_id == server) + .ok_or_else(|| format!("{server} isn't connected on the Connections page.")) } }