Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(mcp): support OpenID Connect so connectors can restrict access by email domain (#15604)

Hazem Adelbf9e7db5b242
diff --git a/brain/knowledge/ai-intelligence/mcp-server.md b/brain/knowledge/ai-intelligence/mcp-server.md
index b172c1959d9..e130b21e783 100644
--- a/brain/knowledge/ai-intelligence/mcp-server.md
+++ b/brain/knowledge/ai-intelligence/mcp-server.md
@@ -66,6 +66,10 @@ Exposes an Activepieces project as an MCP server so AI clients (Claude Desktop,
- `x-ap-conversation-id` header (EE chat) rebinds the server to a conversation's project, but only when scoping matches the token — it can never widen the grant.
- **The platform server's selected project is keyed per OAuth client, and it has to be.** `/mcp/platform` registers `ap_set_project_context`, and every non-platform-level tool re-reads that selection from Redis on *every* call, because the transport is stateless (`sessionIdGenerator: undefined` — a fresh `McpServer` per POST) and there is no session to hold it in. The key is `mcp-project-selection:client:{platformId}:{userId}:{clientId}`, with `clientId` read off the access token: it was `…:user:{platformId}:{userId}` until GIT-1831, and two clients on the same platform-wide grant (Claude Code and LibreChat, both pointed at `/mcp/platform`) stomped each other's project — surfacing as intermittent "Flow not found" for a flow that exists and reads fine over REST. Two consequences of using `clientId`: a client's selection resets when it re-runs DCR sign-in (see the DCR gotcha above — `clientId` is per registration), and two instances of the *same* registration still share one selection. Nothing available on a stateless request can separate those. `ProjectSelectionScope` also used to carry a `{ conversationId }` variant — PR #13356 (`fbfbcd7578`) removed its only caller in favour of the conversation's own Postgres `projectId`, and when that resolves the server is built project-scoped so the selection layer is never touched; internal chat never writes this key at all (`ap_set_project_context` is in `CHAT_HIDDEN_TOOL_NAMES`). Do not reintroduce a conversation scope for external clients: they never send `x-ap-conversation-id`.
- **The platform server's selected project is live mutable state, so resolve it once per call and thread it.** `mcpProjectSelection.get` is an uncached Redis read, its scope is per OAuth client rather than per session (see the gotcha above), and the transport is stateless (`sessionIdGenerator: undefined`, a fresh server per POST) — so two concurrent requests from the same client share one key, and `ap_set_project_context` can flip it mid-call. Anything downstream of a tool call that re-reads the key instead of reusing what `execute` resolved will disagree with it: `ap_run_action` runs a real engine flow run, so the window is seconds wide, and a deferred read after the response lands in whatever project was selected *by then*. This bites attribution hardest — a row or file written from a second read names a project the action never touched, silently and plausibly.
+- **`openid` alone releases the email, and that is deliberate.** `buildClaims` treats `openid` or `email` as granting the email claim, where OIDC strictly wants `email` for it. ChatGPT's enterprise domain restriction is the whole reason the layer exists and it must not fail on a client that requests only `openid`. Nothing else narrows scopes either — `/authorize` stores `scope.split(' ')` verbatim, so a client self-granting `openid email` gets only the consenting user's own address, which the MCP grant it just approved already dominates.
+- **No `id_token` comes back from a refresh, on purpose.** OIDC makes it optional there, and `refreshAccessToken` has no `nonce` to echo — returning one would hand the RP a nonce-less assertion for a flow that required a nonce. Clients that need fresh claims call `/userinfo`, which is also the only path that re-reads the email after it changes.
+- **`email_verified` is `user_identity.verified`, and that flag means different things per signup path.** Cloud's passwordless path creates the identity `verified: false` and only flips it after the OTP is entered, and Google/SAML/SCIM are attested by the IdP — all genuine. But `authenticationService.signUp` (the CE/EE password path) creates the identity `verified: true` outright, with no mailbox confirmation, so on a self-host with `AP_ALLOW_OPEN_SIGN_UP=true` anyone can register any address and have us assert `email_verified: true` for it. `assertDomainIsAllowed` is not a backstop there: it returns early on Community and on any platform without `ssoEnabled`. Two consequences — a relying party doing enterprise domain restriction is trusting our signup path, not a mailbox check; and a platform whose users never verified will fail such a check outright. Fixing this properly means not auto-verifying on the password path, which needs SMTP that a CE install may not have.
+- **One bearer gate gets it right for both surfaces.** `mcpOAuthTokenService.authenticate` (verify + revocation-list check, 503 on a revocation-store outage, never fail-open) backs both `POST /mcp` and `/userinfo`. Adding a token check to only one of them is the bug this consolidation exists to prevent, and `/userinfo` is the laxer copy's blast radius because it returns PII.
- External MCP-server validation for the agent piece lives under `agents/`, NOT here (it's a probe, not the AP-as-server feature).
- **Every registered tool must declare all three safety hints** — `readOnlyHint`, `destructiveHint`, `openWorldHint`. `McpToolDefinition.annotations` is optional and `buildToolConfig` passes it straight through, so an omitted hint is silent: MCP clients fall back to protocol defaults, but a ChatGPT Apps submission treats any missing hint as a blocker. The two dynamic paths are the easiest to miss because they build their tool config inline instead of from an `McpToolDefinition` — `registerFlowTools` (one tool per enabled MCP-trigger flow) and `registerPlaceholderTools` (the no-project-selected state, which is what a fresh external reviewer meets first). Placeholders annotate per list — locked names get the read-only triple, controllable names get `destructive: true, openWorld: true` — so a stand-in never advertises itself as safer than the tool it represents.
- **`openWorldHint` means the tool can change state in a third-party system**, not that it makes an outbound call. Anything that executes real connector steps needs it: `ap_test_flow`, `ap_test_step`, `ap_retry_run`, `ap_run_action`, and every dynamic flow tool. A read that only calls a connected account to populate dropdowns (`ap_get_piece_props`, `ap_resolve_property_options`, `ap_resolve_property_chain`) does not. `ap_retry_run` originally declared `false` here and was wrong — a retry re-runs the published flow and can resend the same Slack message or repeat an outbound write.
diff --git a/brain/knowledge/decisions/000038-one-openid-configuration-serves-both-workload-federation-and-mcp-user-sign-in.md b/brain/knowledge/decisions/000038-one-openid-configuration-serves-both-workload-federation-and-mcp-user-sign-in.md
new file mode 100644
index 00000000000..c3f9fb9eb9a
--- /dev/null
+++ b/brain/knowledge/decisions/000038-one-openid-configuration-serves-both-workload-federation-and-mcp-user-sign-in.md
@@ -0,0 +1,54 @@
+---
+icon: 🪪
+status: accepted
+---
+
+# One OpenID Connect discovery document serves both workload federation and MCP user sign-in
+
+## Decision
+
+`/.well-known/openid-configuration` describes **both** OIDC purposes at once: the workload-identity
+federation provider (engine-minted RS256 tokens that pieces present to AWS/GCP) and the MCP
+authorization server's user-facing OIDC layer (`openid`/`email`/`profile`, `userinfo_endpoint`,
+`id_token`). Its `issuer` — and the `iss` of every MCP `id_token` — is request-derived via
+`domainHelper.getPublicUrlFromRequest`, matching `/.well-known/oauth-authorization-server`. The
+workload token keeps `iss = FRONTEND_URL`, because the engine mints it over an internal call with no
+public request context.
+
+## Context
+
+OpenAI rejected the Activepieces ChatGPT connector for enterprise domain restrictions, which require
+an OIDC discovery document, a `userinfo` endpoint returning a verified email, and the `openid`/`email`
+scopes. A relying party looks for that document at `<issuer>/.well-known/openid-configuration`, and
+the issuer MCP clients discover from `oauth-protected-resource` is the origin root — where the
+workload-federation document already lived. There is one issuer per origin, so the two cannot both
+own that URL.
+
+## Why
+
+Giving MCP its own path-scoped issuer (`<host>/mcp`) is the cleaner separation and was rejected: it
+changes the issuer every already-connected client (Claude, Cursor, ChatGPT) discovered against, for a
+conflict that is only cosmetic — AWS IAM and GCP workload-identity pools read `issuer` and `jwks_uri`
+and nothing else from the document, so the added MCP fields are inert to them. `response_types_supported`
+moved from `['id_token']` to `['code']`, which is simply accurate: the authorization endpoint only
+supports the code flow, and workload federation has no authorization endpoint at all.
+
+Request-deriving the issuer was the reverse trade. Keeping `FRONTEND_URL` would have left an
+`iss` mismatch on custom domains — an EE feature, and exactly the enterprise deployments the
+ChatGPT connector targets — so every conformant RP would reject the `id_token` there. No working
+federation setup regresses: AWS requires the document's `issuer` to equal the URL the customer
+registered, so a functioning setup is always fetched at the `FRONTEND_URL` host, where the
+request-derived value is identical.
+
+## Consequences
+
+- The MCP triple stays internally consistent on every host: `oauth-protected-resource` →
+ `openid-configuration` → `id_token.iss`. Pinned by a custom-domain test in `mcp-oauth-oidc.test.ts`.
+- Workload federation reached at a host other than `FRONTEND_URL` now returns that host as `issuer`
+ while its tokens still say `FRONTEND_URL`. That configuration was already non-functional, but it
+ now fails at token exchange rather than at provider setup.
+- Both token families share one RSA key and `kid`. Safe today because their claim sets are disjoint
+ and non-forgeable — the workload token's `sub` is server-fixed `platform:<id>:project:<id>` (never
+ a user id) and it carries no `email`, so it can never satisfy a domain check; the `id_token`'s `aud`
+ is a random server-generated `client_id` no customer would register with AWS. Separate keys only
+ pay off alongside separate issuers, so that follow-up travels with a path-scoped issuer, not alone.
diff --git a/bun.lock b/bun.lock
index c6f90fcc698..951b4d452a9 100644
--- a/bun.lock
+++ b/bun.lock
@@ -164,7 +164,7 @@
},
"packages/core/shared": {
"name": "@activepieces/shared",
- "version": "0.173.0",
+ "version": "0.174.0",
"dependencies": {
"@activepieces/core-execution": "workspace:*",
"@activepieces/core-formula": "workspace:*",
diff --git a/packages/core/shared/package.json b/packages/core/shared/package.json
index 7d780eccb1c..bebf2a30040 100644
--- a/packages/core/shared/package.json
+++ b/packages/core/shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/shared",
- "version": "0.173.0",
+ "version": "0.174.0",
"type": "commonjs",
"sideEffects": false,
"main": "./dist/src/index.js",
diff --git a/packages/core/shared/src/lib/automation/mcp/mcp-oauth.ts b/packages/core/shared/src/lib/automation/mcp/mcp-oauth.ts
index d379296e4c9..61134de66e1 100644
--- a/packages/core/shared/src/lib/automation/mcp/mcp-oauth.ts
+++ b/packages/core/shared/src/lib/automation/mcp/mcp-oauth.ts
@@ -48,6 +48,7 @@ export const McpOAuthAuthorizationCode = z.object({
codeChallengeMethod: z.string(),
scopes: z.array(z.string()).nullable(),
state: z.string().nullable(),
+ nonce: z.string().nullable(),
expiresAt: z.string(),
used: z.boolean(),
})
diff --git a/packages/server/api/src/app/core/security/oidc/oidc-discovery.controller.ts b/packages/server/api/src/app/core/security/oidc/oidc-discovery.controller.ts
index cfa62365eeb..bee08784a2a 100644
--- a/packages/server/api/src/app/core/security/oidc/oidc-discovery.controller.ts
+++ b/packages/server/api/src/app/core/security/oidc/oidc-discovery.controller.ts
@@ -1,32 +1,31 @@
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
-import { system } from '../../../helper/system/system'
-import { AppSystemProp } from '../../../helper/system/system-props'
+import { domainHelper } from '../../../helper/domain-helper'
+import { authorizationServerMetadata } from '../../../mcp/oauth/metadata/mcp-oauth-metadata'
import { securityAccess } from '../authorization/fastify-security'
import { oidcKeyManager } from './oidc-key-manager'
export const oidcDiscoveryController: FastifyPluginAsyncZod = async (app) => {
- const issuer = system.getOrThrow(AppSystemProp.FRONTEND_URL).replace(/\/$/, '')
- app.get('/.well-known/openid-configuration', {
- config: { security: securityAccess.public() },
- schema: { hide: true },
- }, async (_req, reply) => {
+ app.get('/.well-known/openid-configuration', PublicDiscoveryRequest, async (req, reply) => {
+ const issuer = domainHelper.getPublicUrlFromRequest({ req })
return reply.status(200).header('Access-Control-Allow-Origin', '*').send({
- issuer,
+ ...authorizationServerMetadata({ issuer }),
jwks_uri: `${issuer}/.well-known/jwks.json`,
- response_types_supported: ['id_token'],
id_token_signing_alg_values_supported: ['RS256'],
subject_types_supported: ['public'],
+ claims_supported: ['sub', 'iss', 'aud', 'exp', 'iat', 'email', 'email_verified', 'name', 'given_name', 'family_name'],
})
})
- app.get('/.well-known/jwks.json', {
- config: { security: securityAccess.public() },
- schema: { hide: true },
- }, async (_req, reply) => {
+ app.get('/.well-known/jwks.json', PublicDiscoveryRequest, async (_req, reply) => {
const jwk = await oidcKeyManager.getPublicKeyJwk()
return reply.status(200).header('Access-Control-Allow-Origin', '*').send({
keys: [jwk],
})
})
}
+
+const PublicDiscoveryRequest = {
+ config: { security: securityAccess.public() },
+ schema: { hide: true },
+}
diff --git a/packages/server/api/src/app/core/security/oidc/oidc-key-manager.ts b/packages/server/api/src/app/core/security/oidc/oidc-key-manager.ts
index 523aabe8b10..5471d88434e 100644
--- a/packages/server/api/src/app/core/security/oidc/oidc-key-manager.ts
+++ b/packages/server/api/src/app/core/security/oidc/oidc-key-manager.ts
@@ -4,6 +4,7 @@ import { ActivepiecesError, ErrorCode, isNil } from '@activepieces/core-utils'
import { Mutex } from 'async-mutex'
import { FlagEntity } from '../../../flags/flag.entity'
import { EncryptedObject, encryptUtils } from '../../../helper/encryption'
+import { JwtSignAlgorithm, jwtUtils } from '../../../helper/jwt-utils'
import { repoFactory } from '../../db/repo-factory'
const flagRepo = repoFactory(FlagEntity)
@@ -39,6 +40,20 @@ export const oidcKeyManager = {
async getKid(): Promise<string> {
return (await oidcKeyManager.getPublicKeyJwk()).kid
},
+ async sign({ payload, expiresInSeconds, issuer }: SignParams): Promise<string> {
+ const [privateKey, kid] = await Promise.all([
+ oidcKeyManager.getPrivateKeyPem(),
+ oidcKeyManager.getKid(),
+ ])
+ return jwtUtils.sign({
+ payload,
+ key: privateKey,
+ expiresInSeconds,
+ algorithm: JwtSignAlgorithm.RS256,
+ keyId: kid,
+ issuer,
+ })
+ },
}
async function getOrGenerateStoredPrivateKey(): Promise<string> {
@@ -84,4 +99,10 @@ function computeKidFromJwk(jwk: JsonWebKey): string {
return createHash('sha256').update(thumbprintData).digest('base64url')
}
+type SignParams = {
+ payload: Record<string, unknown>
+ expiresInSeconds: number
+ issuer: string
+}
+
type OidcJwk = JsonWebKey & { use: string, alg: string, kid: string }
diff --git a/packages/server/api/src/app/core/security/oidc/oidc-token.controller.ts b/packages/server/api/src/app/core/security/oidc/oidc-token.controller.ts
index 60e3e4a8239..9c01584e7ea 100644
--- a/packages/server/api/src/app/core/security/oidc/oidc-token.controller.ts
+++ b/packages/server/api/src/app/core/security/oidc/oidc-token.controller.ts
@@ -1,30 +1,20 @@
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { z } from 'zod'
-import { JwtSignAlgorithm, jwtUtils } from '../../../helper/jwt-utils'
-import { system } from '../../../helper/system/system'
-import { AppSystemProp } from '../../../helper/system/system-props'
+import { domainHelper } from '../../../helper/domain-helper'
import { securityAccess } from '../authorization/fastify-security'
import { oidcKeyManager } from './oidc-key-manager'
export const oidcTokenController: FastifyPluginAsyncZod = async (app) => {
- const issuer = system.getOrThrow(AppSystemProp.FRONTEND_URL).replace(/\/$/, '')
app.post('/oidc-token', CreateOidcTokenRequestOptions, async (request, reply) => {
const { projectId, platform } = request.principal
const { audience, expiresInSeconds } = request.body
- const [privateKey, kid] = await Promise.all([
- oidcKeyManager.getPrivateKeyPem(),
- oidcKeyManager.getKid(),
- ])
- const token = await jwtUtils.sign({
+ const token = await oidcKeyManager.sign({
payload: {
sub: `platform:${platform.id}:project:${projectId}`,
aud: audience,
},
- key: privateKey,
expiresInSeconds,
- algorithm: JwtSignAlgorithm.RS256,
- keyId: kid,
- issuer,
+ issuer: domainHelper.getConfiguredPublicUrl(),
})
void reply.header('Cache-Control', 'no-store')
void reply.header('Pragma', 'no-cache')
diff --git a/packages/server/api/src/app/database/migration/postgres/1851000000000-AddMcpOAuthCodeNonce.ts b/packages/server/api/src/app/database/migration/postgres/1851000000000-AddMcpOAuthCodeNonce.ts
new file mode 100644
index 00000000000..b1852a7a73b
--- /dev/null
+++ b/packages/server/api/src/app/database/migration/postgres/1851000000000-AddMcpOAuthCodeNonce.ts
@@ -0,0 +1,22 @@
+import { QueryRunner } from 'typeorm'
+import { Migration } from '../../migration'
+
+export class AddMcpOAuthCodeNonce1851000000000 implements Migration {
+ name = 'AddMcpOAuthCodeNonce1851000000000'
+ breaking = false
+ release = '0.92.1'
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`
+ ALTER TABLE "mcp_oauth_authorization_code"
+ ADD COLUMN IF NOT EXISTS "nonce" character varying(512)
+ `)
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`
+ ALTER TABLE "mcp_oauth_authorization_code"
+ DROP COLUMN IF EXISTS "nonce"
+ `)
+ }
+}
diff --git a/packages/server/api/src/app/database/postgres-connection.ts b/packages/server/api/src/app/database/postgres-connection.ts
index a0e7e16f5b4..063b86280d7 100644
--- a/packages/server/api/src/app/database/postgres-connection.ts
+++ b/packages/server/api/src/app/database/postgres-connection.ts
@@ -439,6 +439,7 @@ import { AddAgentConversationFlowRunId1843000000000 } from './migration/postgres
import { AddMcpActivity1844000000000 } from './migration/postgres/1844000000000-AddMcpActivity'
import { NullOrphanFolderReferences1846000000000 } from './migration/postgres/1846000000000-NullOrphanFolderReferences'
import { AddAgentConversationAiCredits1850000000000 } from './migration/postgres/1850000000000-AddAgentConversationAiCredits'
+import { AddMcpOAuthCodeNonce1851000000000 } from './migration/postgres/1851000000000-AddMcpOAuthCodeNonce'
const getSslConfig = (): boolean | TlsOptions => {
const useSsl = system.get(AppSystemProp.POSTGRES_USE_SSL)
@@ -893,6 +894,7 @@ export const getMigrations = (): (new () => Migration)[] => {
AddMcpActivity1844000000000,
NullOrphanFolderReferences1846000000000,
AddAgentConversationAiCredits1850000000000,
+ AddMcpOAuthCodeNonce1851000000000,
]
return migrations
}
diff --git a/packages/server/api/src/app/helper/domain-helper.ts b/packages/server/api/src/app/helper/domain-helper.ts
index 159f47bba40..1055321f835 100644
--- a/packages/server/api/src/app/helper/domain-helper.ts
+++ b/packages/server/api/src/app/helper/domain-helper.ts
@@ -8,6 +8,9 @@ export const domainHelper = {
async getPublicUrl({ path }: PublicUrlParams): Promise<string> {
return networkUtils.combineUrl(system.getOrThrow(AppSystemProp.FRONTEND_URL), path ?? '')
},
+ getConfiguredPublicUrl(): string {
+ return cleanTrailingSlash(system.getOrThrow(AppSystemProp.FRONTEND_URL))
+ },
getPublicUrlFromRequest({ req, path }: PublicUrlFromRequestParams): string {
const requestBase = networkUtils.getRequestBaseUrl(req)
const baseWithPrefix = networkUtils.combineUrl(requestBase, getConfiguredBasePath())
diff --git a/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-approve.controller.ts b/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-approve.controller.ts
index c5649631bf9..8e9d553c940 100644
--- a/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-approve.controller.ts
+++ b/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-approve.controller.ts
@@ -60,6 +60,7 @@ export const mcpOAuthApproveController: FastifyPluginAsyncZod = async (app) => {
codeChallengeMethod: authRequest.codeChallengeMethod,
scopes: authRequest.scopes,
state: authRequest.state ?? undefined,
+ nonce: authRequest.nonce,
})
const redirectUrl = new URL(authRequest.redirectUri)
@@ -91,6 +92,7 @@ type AuthRequestPayload = {
codeChallenge: string
codeChallengeMethod: string
state: string | null
+ nonce: string | null
scopes: string[]
resource: string | null
type: 'mcp_auth_request'
diff --git a/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-authorize.controller.ts b/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-authorize.controller.ts
index 9cc86252382..49a8af23033 100644
--- a/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-authorize.controller.ts
+++ b/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-authorize.controller.ts
@@ -5,6 +5,7 @@ import { securityAccess } from '../../../core/security/authorization/fastify-sec
import { domainHelper } from '../../../helper/domain-helper'
import { JwtAudience, jwtUtils } from '../../../helper/jwt-utils'
import { mcpOAuthClientService } from '../client/mcp-oauth-client.service'
+import { DEFAULT_MCP_OAUTH_SCOPES } from '../mcp-oauth-scopes'
import { mcpOAuthValidation } from '../mcp-oauth-validation'
const AUTH_REQUEST_TTL_10_MINUTES_SECONDS = 10 * 60
@@ -12,7 +13,7 @@ const AUTH_REQUEST_TTL_10_MINUTES_SECONDS = 10 * 60
export const mcpOAuthAuthorizeController: FastifyPluginAsyncZod = async (app) => {
app.get('/authorize', AuthorizeRequest, async (req, reply) => {
- const { client_id, redirect_uri, response_type, code_challenge, code_challenge_method, state, scope, resource } = req.query
+ const { client_id, redirect_uri, response_type, code_challenge, code_challenge_method, state, scope, resource, nonce } = req.query
if (response_type !== 'code') {
return reply.status(400).send({ error: 'unsupported_response_type' })
@@ -40,7 +41,8 @@ export const mcpOAuthAuthorizeController: FastifyPluginAsyncZod = async (app) =>
codeChallenge: code_challenge,
codeChallengeMethod: code_challenge_method,
state: state ?? null,
- scopes: scope ? scope.split(' ') : ['mcp'],
+ nonce: nonce ?? null,
+ scopes: scope ? scope.split(' ') : DEFAULT_MCP_OAUTH_SCOPES,
resource: resource ?? null,
type: 'mcp_auth_request',
},
@@ -67,6 +69,7 @@ const AuthorizeRequest = {
code_challenge: mcpOAuthValidation.storableText(256).refine((value) => value.length >= 43, { message: 'code_challenge is too short' }),
code_challenge_method: z.string().max(8).default('S256'),
state: mcpOAuthValidation.storableText(2048).optional(),
+ nonce: mcpOAuthValidation.storableText(512).optional(),
scope: mcpOAuthValidation.storableText(512).optional(),
resource: mcpOAuthValidation.storableText(2048).optional(),
}),
diff --git a/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-code.entity.ts b/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-code.entity.ts
index 8022a22903f..53c4cd424bb 100644
--- a/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-code.entity.ts
+++ b/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-code.entity.ts
@@ -48,6 +48,11 @@ export const McpOAuthAuthorizationCodeEntity = new EntitySchema<McpOAuthAuthoriz
length: 2048,
nullable: true,
},
+ nonce: {
+ type: String,
+ length: 512,
+ nullable: true,
+ },
expiresAt: {
type: 'timestamp with time zone',
nullable: false,
diff --git a/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-code.service.ts b/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-code.service.ts
index d3664fd236e..b64e8d902bc 100644
--- a/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-code.service.ts
+++ b/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-code.service.ts
@@ -29,6 +29,7 @@ export const mcpOAuthCodeService = {
codeChallengeMethod: params.codeChallengeMethod,
scopes: params.scopes ?? [],
state: params.state ?? null,
+ nonce: params.nonce ?? null,
expiresAt: new Date(Date.now() + CODE_TTL_10_MINUTES_MS).toISOString(),
used: false,
created: new Date().toISOString(),
@@ -73,4 +74,5 @@ type CreateCodeParams = {
codeChallengeMethod: string
scopes?: string[]
state?: string
+ nonce?: string | null
}
diff --git a/packages/server/api/src/app/mcp/oauth/mcp-oauth-scopes.ts b/packages/server/api/src/app/mcp/oauth/mcp-oauth-scopes.ts
new file mode 100644
index 00000000000..99d8c00f3a7
--- /dev/null
+++ b/packages/server/api/src/app/mcp/oauth/mcp-oauth-scopes.ts
@@ -0,0 +1,4 @@
+const MCP_SCOPE = 'mcp'
+
+export const DEFAULT_MCP_OAUTH_SCOPES = [MCP_SCOPE]
+export const MCP_OAUTH_SUPPORTED_SCOPES = [MCP_SCOPE, 'openid', 'email', 'profile']
diff --git a/packages/server/api/src/app/mcp/oauth/mcp-oauth.controller.ts b/packages/server/api/src/app/mcp/oauth/mcp-oauth.controller.ts
index 43499d9d80a..590b3ff54ce 100644
--- a/packages/server/api/src/app/mcp/oauth/mcp-oauth.controller.ts
+++ b/packages/server/api/src/app/mcp/oauth/mcp-oauth.controller.ts
@@ -12,7 +12,6 @@ import { domainHelper } from '../../helper/domain-helper'
import { rejectedPromiseHandler } from '../../helper/promise-handler'
import { telemetry, telemetryDedupe } from '../../helper/telemetry.utils'
import { mcpServerService } from '../mcp-service'
-import { mcpOAuthRevocationList } from './token/mcp-oauth-revocation-list'
import { mcpOAuthTokenService } from './token/mcp-oauth-token.service'
export const mcpOAuthHttpController: FastifyPluginAsyncZod = async (app) => {
@@ -123,22 +122,11 @@ function revocationCheckUnavailable(reply: FastifyReply): FastifyReply {
}
async function resolveIdentity({ token, scope, log }: { token: string, scope: McpServerType, log: FastifyBaseLogger }): Promise<IdentityResult> {
- const { data: payload, error } = await tryCatch(() => mcpOAuthTokenService.verifyAccessToken(token))
- if (error) {
- log.debug({ error }, 'OAuth token verification failed')
- return { status: 'invalid' }
- }
- const { grantId } = payload
- if (!isNil(grantId)) {
- const { data: revoked, error: revocationError } = await tryCatch(() => mcpOAuthRevocationList.isRevoked({ grantId }))
- if (revocationError) {
- log.error({ error: revocationError }, 'Could not read the MCP OAuth revocation list')
- return { status: 'unavailable' }
- }
- if (revoked) {
- return { status: 'invalid' }
- }
+ const authenticated = await mcpOAuthTokenService.authenticate({ token, log })
+ if (authenticated.status !== 'ok') {
+ return { status: authenticated.status }
}
+ const { payload } = authenticated
const { projectId } = payload
const clientKey = payload.clientKey ?? null
const isPlatformToken = isNil(projectId)
diff --git a/packages/server/api/src/app/mcp/oauth/mcp-oauth.module.ts b/packages/server/api/src/app/mcp/oauth/mcp-oauth.module.ts
index a2a14b2fa90..75cffae2abf 100644
--- a/packages/server/api/src/app/mcp/oauth/mcp-oauth.module.ts
+++ b/packages/server/api/src/app/mcp/oauth/mcp-oauth.module.ts
@@ -2,6 +2,7 @@ import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { mcpOAuthRegisterController } from './client/mcp-oauth-register.controller'
import { mcpOAuthAuthorizeController } from './code/mcp-oauth-authorize.controller'
import { mcpOAuthMetadataController } from './metadata/mcp-oauth-metadata.controller'
+import { mcpOAuthUserInfoController } from './oidc/mcp-oauth-userinfo.controller'
import { mcpOAuthRevokeController } from './token/mcp-oauth-revoke.controller'
import { mcpOAuthTokenController } from './token/mcp-oauth-token.controller'
@@ -11,4 +12,5 @@ export const mcpOAuthRootModule: FastifyPluginAsyncZod = async (app) => {
await app.register(mcpOAuthAuthorizeController)
await app.register(mcpOAuthTokenController)
await app.register(mcpOAuthRevokeController)
+ await app.register(mcpOAuthUserInfoController)
}
diff --git a/packages/server/api/src/app/mcp/oauth/metadata/mcp-oauth-metadata.controller.ts b/packages/server/api/src/app/mcp/oauth/metadata/mcp-oauth-metadata.controller.ts
index 9135b0bcb88..8b8d02ed3f3 100644
--- a/packages/server/api/src/app/mcp/oauth/metadata/mcp-oauth-metadata.controller.ts
+++ b/packages/server/api/src/app/mcp/oauth/metadata/mcp-oauth-metadata.controller.ts
@@ -1,43 +1,30 @@
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { securityAccess } from '../../../core/security/authorization/fastify-security'
import { domainHelper } from '../../../helper/domain-helper'
+import { MCP_OAUTH_SUPPORTED_SCOPES } from '../mcp-oauth-scopes'
+import { authorizationServerMetadata } from './mcp-oauth-metadata'
export const mcpOAuthMetadataController: FastifyPluginAsyncZod = async (app) => {
app.get('/.well-known/oauth-authorization-server', PublicMetadataRequest, async (req, reply) => {
const issuer = domainHelper.getPublicUrlFromRequest({ req })
- return reply.status(200).header('Access-Control-Allow-Origin', '*').send({
- issuer,
- authorization_endpoint: `${issuer}/authorize`,
- token_endpoint: `${issuer}/token`,
- registration_endpoint: `${issuer}/register`,
- revocation_endpoint: `${issuer}/revoke`,
- response_types_supported: ['code'],
- grant_types_supported: ['authorization_code', 'refresh_token'],
- code_challenge_methods_supported: ['S256'],
- token_endpoint_auth_methods_supported: ['client_secret_post', 'client_secret_basic', 'none'],
- revocation_endpoint_auth_methods_supported: ['client_secret_post', 'client_secret_basic', 'none'],
- scopes_supported: ['mcp'],
- })
- })
-
- app.get('/.well-known/oauth-protected-resource/mcp', PublicMetadataRequest, async (req, reply) => {
- const issuer = domainHelper.getPublicUrlFromRequest({ req })
- return reply.status(200).header('Access-Control-Allow-Origin', '*').send({
- resource: `${issuer}/mcp`,
- authorization_servers: [issuer],
- })
+ return reply.status(200).header('Access-Control-Allow-Origin', '*').send(authorizationServerMetadata({ issuer }))
})
- app.get('/.well-known/oauth-protected-resource/mcp/platform', PublicMetadataRequest, async (req, reply) => {
- const issuer = domainHelper.getPublicUrlFromRequest({ req })
- return reply.status(200).header('Access-Control-Allow-Origin', '*').send({
- resource: `${issuer}/mcp/platform`,
- authorization_servers: [issuer],
+ for (const resourcePath of RESOURCE_PATHS) {
+ app.get(`/.well-known/oauth-protected-resource/${resourcePath}`, PublicMetadataRequest, async (req, reply) => {
+ const issuer = domainHelper.getPublicUrlFromRequest({ req })
+ return reply.status(200).header('Access-Control-Allow-Origin', '*').send({
+ resource: `${issuer}/${resourcePath}`,
+ authorization_servers: [issuer],
+ scopes_supported: MCP_OAUTH_SUPPORTED_SCOPES,
+ })
})
- })
+ }
}
+const RESOURCE_PATHS = ['mcp', 'mcp/platform']
+
const PublicMetadataRequest = {
config: { security: securityAccess.public() },
schema: { hide: true },
diff --git a/packages/server/api/src/app/mcp/oauth/metadata/mcp-oauth-metadata.ts b/packages/server/api/src/app/mcp/oauth/metadata/mcp-oauth-metadata.ts
new file mode 100644
index 00000000000..892a9aabc0a
--- /dev/null
+++ b/packages/server/api/src/app/mcp/oauth/metadata/mcp-oauth-metadata.ts
@@ -0,0 +1,35 @@
+import { MCP_OAUTH_SUPPORTED_SCOPES } from '../mcp-oauth-scopes'
+
+export function authorizationServerMetadata({ issuer }: { issuer: string }): AuthorizationServerMetadata {
+ return {
+ issuer,
+ authorization_endpoint: `${issuer}/authorize`,
+ token_endpoint: `${issuer}/token`,
+ userinfo_endpoint: `${issuer}/userinfo`,
+ registration_endpoint: `${issuer}/register`,
+ revocation_endpoint: `${issuer}/revoke`,
+ response_types_supported: ['code'],
+ grant_types_supported: ['authorization_code', 'refresh_token'],
+ code_challenge_methods_supported: ['S256'],
+ token_endpoint_auth_methods_supported: CLIENT_AUTH_METHODS,
+ revocation_endpoint_auth_methods_supported: CLIENT_AUTH_METHODS,
+ scopes_supported: MCP_OAUTH_SUPPORTED_SCOPES,
+ }
+}
+
+const CLIENT_AUTH_METHODS = ['client_secret_post', 'client_secret_basic', 'none']
+
+export type AuthorizationServerMetadata = {
+ issuer: string
+ authorization_endpoint: string
+ token_endpoint: string
+ userinfo_endpoint: string
+ registration_endpoint: string
+ revocation_endpoint: string
+ response_types_supported: string[]
+ grant_types_supported: string[]
+ code_challenge_methods_supported: string[]
+ token_endpoint_auth_methods_supported: string[]
+ revocation_endpoint_auth_methods_supported: string[]
+ scopes_supported: string[]
+}
diff --git a/packages/server/api/src/app/mcp/oauth/oidc/mcp-oauth-oidc.service.ts b/packages/server/api/src/app/mcp/oauth/oidc/mcp-oauth-oidc.service.ts
new file mode 100644
index 00000000000..74426a6d9f9
--- /dev/null
+++ b/packages/server/api/src/app/mcp/oauth/oidc/mcp-oauth-oidc.service.ts
@@ -0,0 +1,76 @@
+import { isNil, spreadIfDefined } from '@activepieces/core-utils'
+import { repoFactory } from '../../../core/db/repo-factory'
+import { oidcKeyManager } from '../../../core/security/oidc/oidc-key-manager'
+import { UserEntity } from '../../../user/user-entity'
+import { MCP_OAUTH_ID_TOKEN_TTL_SECONDS } from '../token/mcp-oauth-token-lifetimes'
+
+const userRepo = repoFactory(UserEntity)
+
+async function getUserInfo({ userId, platformId, scopes }: UserInfoParams): Promise<OidcClaims | null> {
+ const grantsEmail = scopes.includes('email') || scopes.includes('openid')
+ const grantsProfile = scopes.includes('profile')
+ if (!grantsEmail && !grantsProfile) {
+ return { sub: userId }
+ }
+ const user = await userRepo().findOne({
+ where: { id: userId, platformId },
+ relations: { identity: true },
+ select: { id: true, identity: { email: true, verified: true, firstName: true, lastName: true } },
+ })
+ if (isNil(user)) {
+ return null
+ }
+ const { identity } = user
+ return {
+ sub: userId,
+ ...spreadIfDefined('email', grantsEmail ? identity.email : undefined),
+ ...spreadIfDefined('email_verified', grantsEmail ? identity.verified : undefined),
+ ...spreadIfDefined('name', grantsProfile ? `${identity.firstName} ${identity.lastName}`.trim() : undefined),
+ ...spreadIfDefined('given_name', grantsProfile ? identity.firstName : undefined),
+ ...spreadIfDefined('family_name', grantsProfile ? identity.lastName : undefined),
+ }
+}
+
+export const mcpOAuthOidcService = {
+ getUserInfo,
+
+ async issueIdToken({ userId, platformId, clientId, scopes, nonce, issuer }: IssueIdTokenParams): Promise<string | undefined> {
+ if (!scopes.includes('openid')) {
+ return undefined
+ }
+ const claims = await getUserInfo({ userId, platformId, scopes })
+ if (isNil(claims)) {
+ return undefined
+ }
+ return oidcKeyManager.sign({
+ payload: {
+ ...claims,
+ aud: clientId,
+ ...spreadIfDefined('nonce', nonce ?? undefined),
+ },
+ expiresInSeconds: MCP_OAUTH_ID_TOKEN_TTL_SECONDS,
+ issuer,
+ })
+ },
+}
+
+type UserInfoParams = {
+ userId: string
+ platformId: string
+ scopes: string[]
+}
+
+type IssueIdTokenParams = UserInfoParams & {
+ clientId: string
+ nonce: string | null
+ issuer: string
+}
+
+type OidcClaims = {
+ sub: string
+ email?: string
+ email_verified?: boolean
+ name?: string
+ given_name?: string
+ family_name?: string
+}
diff --git a/packages/server/api/src/app/mcp/oauth/oidc/mcp-oauth-userinfo.controller.ts b/packages/server/api/src/app/mcp/oauth/oidc/mcp-oauth-userinfo.controller.ts
new file mode 100644
index 00000000000..043a9a11adf
--- /dev/null
+++ b/packages/server/api/src/app/mcp/oauth/oidc/mcp-oauth-userinfo.controller.ts
@@ -0,0 +1,52 @@
+import { isNil } from '@activepieces/core-utils'
+import { FastifyReply, FastifyRequest } from 'fastify'
+import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
+import { securityAccess } from '../../../core/security/authorization/fastify-security'
+import { mcpOAuthTokenService } from '../token/mcp-oauth-token.service'
+import { mcpOAuthOidcService } from './mcp-oauth-oidc.service'
+
+export const mcpOAuthUserInfoController: FastifyPluginAsyncZod = async (app) => {
+ app.get('/userinfo', UserInfoRequest, handleUserInfo)
+ app.post('/userinfo', UserInfoRequest, handleUserInfo)
+}
+
+async function handleUserInfo(req: FastifyRequest, reply: FastifyReply): Promise<FastifyReply> {
+ void reply.header('Cache-Control', 'no-store').header('Access-Control-Allow-Origin', '*')
+
+ const [type, token] = req.headers.authorization?.split(' ') ?? []
+ if (type !== 'Bearer' || isNil(token)) {
+ return reply.status(401).header('WWW-Authenticate', 'Bearer').send({
+ error: 'invalid_request',
+ message: 'Authorization: Bearer <token> required',
+ })
+ }
+
+ const authenticated = await mcpOAuthTokenService.authenticate({ token, log: req.log })
+ if (authenticated.status === 'unavailable') {
+ return reply.status(503).header('Retry-After', '1').send({
+ error: 'temporarily_unavailable',
+ message: 'Could not verify the access token right now, retry shortly.',
+ })
+ }
+
+ const claims = authenticated.status === 'ok'
+ ? await mcpOAuthOidcService.getUserInfo({
+ userId: authenticated.payload.sub,
+ platformId: authenticated.payload.platformId,
+ scopes: authenticated.payload.scopes ?? [],
+ })
+ : null
+
+ if (isNil(claims)) {
+ return reply.status(401).header('WWW-Authenticate', 'Bearer error="invalid_token"').send({
+ error: 'invalid_token',
+ message: 'Invalid or expired access token',
+ })
+ }
+ return reply.status(200).send(claims)
+}
+
+const UserInfoRequest = {
+ config: { security: securityAccess.public() },
+ schema: { hide: true },
+}
diff --git a/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token-lifetimes.ts b/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token-lifetimes.ts
index 5a5291b28d1..9fe49c5b716 100644
--- a/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token-lifetimes.ts
+++ b/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token-lifetimes.ts
@@ -2,4 +2,5 @@ const CLOCK_SKEW_BUFFER_SECONDS = 60
export const MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS = 15 * 60
export const MCP_OAUTH_REFRESH_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000
+export const MCP_OAUTH_ID_TOKEN_TTL_SECONDS = 60 * 60
export const MCP_OAUTH_REVOKED_GRANT_TTL_SECONDS = MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS + CLOCK_SKEW_BUFFER_SECONDS
diff --git a/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token.controller.ts b/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token.controller.ts
index b231bc84786..f605c54e232 100644
--- a/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token.controller.ts
+++ b/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token.controller.ts
@@ -1,12 +1,15 @@
-import { isNil } from '@activepieces/core-utils'
+import { isNil, spreadIfDefined } from '@activepieces/core-utils'
import { McpOAuthClient } from '@activepieces/shared'
import { FastifyReply } from 'fastify'
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { z } from 'zod'
import { securityAccess } from '../../../core/security/authorization/fastify-security'
+import { domainHelper } from '../../../helper/domain-helper'
import { mcpOAuthClientAuth } from '../client/mcp-oauth-client-auth'
import { mcpOAuthCodeService } from '../code/mcp-oauth-code.service'
+import { DEFAULT_MCP_OAUTH_SCOPES } from '../mcp-oauth-scopes'
import { mcpOAuthValidation } from '../mcp-oauth-validation'
+import { mcpOAuthOidcService } from '../oidc/mcp-oauth-oidc.service'
import { mcpOAuthTokenService, OAuthTokenError } from './mcp-oauth-token.service'
export const mcpOAuthTokenController: FastifyPluginAsyncZod = async (app) => {
@@ -18,7 +21,7 @@ export const mcpOAuthTokenController: FastifyPluginAsyncZod = async (app) => {
try {
if (grant_type === 'authorization_code') {
- return await handleAuthorizationCode({ authorizationHeader, body: req.body, reply })
+ return await handleAuthorizationCode({ authorizationHeader, body: req.body, reply, issuer: domainHelper.getPublicUrlFromRequest({ req }) })
}
if (grant_type === 'refresh_token') {
return await handleRefreshToken({ authorizationHeader, body: req.body, reply })
@@ -55,7 +58,7 @@ async function authenticateClient({ authorizationHeader, body, reply }: HandlerP
return result.client
}
-async function handleAuthorizationCode({ authorizationHeader, body, reply }: HandlerParams): Promise<void> {
+async function handleAuthorizationCode({ authorizationHeader, body, reply, issuer }: AuthorizationCodeParams): Promise<void> {
const { code, code_verifier, redirect_uri } = body
if (!code || !code_verifier || !redirect_uri) {
await reply.status(400).send({ error: 'invalid_request', error_description: 'Missing code, code_verifier, or redirect_uri' })
@@ -71,6 +74,7 @@ async function handleAuthorizationCode({ authorizationHeader, body, reply }: Han
return
}
+ const scopes = authCode.scopes ?? DEFAULT_MCP_OAUTH_SCOPES
const tokens = await mcpOAuthTokenService.exchangeCode({
redirectUris: client.redirectUris,
codeVerifier: code_verifier,
@@ -80,10 +84,18 @@ async function handleAuthorizationCode({ authorizationHeader, body, reply }: Han
userId: authCode.userId,
projectId: authCode.projectId,
platformId: authCode.platformId,
- scopes: authCode.scopes ?? ['mcp'],
+ scopes,
+ })
+ const idToken = await mcpOAuthOidcService.issueIdToken({
+ userId: authCode.userId,
+ platformId: authCode.platformId,
+ clientId: client.clientId,
+ scopes,
+ nonce: authCode.nonce,
+ issuer,
})
- await reply.status(200).send(tokens)
+ await reply.status(200).send({ ...tokens, ...spreadIfDefined('id_token', idToken) })
}
async function handleRefreshToken({ authorizationHeader, body, reply }: HandlerParams): Promise<void> {
@@ -111,6 +123,10 @@ type HandlerParams = {
reply: FastifyReply
}
+type AuthorizationCodeParams = HandlerParams & {
+ issuer: string
+}
+
const tokenRequestSchema = z.object({
grant_type: z.string().max(64),
code: z.string().max(128).optional(),
diff --git a/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token.service.ts b/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token.service.ts
index 647c35c5820..ce6d94b3174 100644
--- a/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token.service.ts
+++ b/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token.service.ts
@@ -1,7 +1,8 @@
import { randomBytes } from 'crypto'
-import { ActivepiecesError, apId, ErrorCode, isNil, sanitizeObjectForPostgresql, SeekPage, spreadIfDefined, unique } from '@activepieces/core-utils'
+import { ActivepiecesError, apId, ErrorCode, isNil, sanitizeObjectForPostgresql, SeekPage, spreadIfDefined, tryCatch, unique } from '@activepieces/core-utils'
import { cryptoUtils } from '@activepieces/server-utils'
import { McpOAuthClientKey, McpOAuthGrant, McpOAuthToken } from '@activepieces/shared'
+import { FastifyBaseLogger } from 'fastify'
import { In, ObjectLiteral, SelectQueryBuilder } from 'typeorm'
import { repoFactory } from '../../../core/db/repo-factory'
import { JwtAudience, jwtUtils } from '../../../helper/jwt-utils'
@@ -10,6 +11,7 @@ import { paginationHelper } from '../../../helper/pagination/pagination-utils'
import { mcpListingUtils } from '../../mcp-listing-utils'
import { mcpOAuthClientIdentity } from '../client/mcp-oauth-client-identity'
import { McpOAuthClientEntity } from '../client/mcp-oauth-client.entity'
+import { DEFAULT_MCP_OAUTH_SCOPES } from '../mcp-oauth-scopes'
import { mcpOAuthPkce } from '../mcp-oauth.pkce'
import { mcpOAuthRevocationList } from './mcp-oauth-revocation-list'
import { MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS, MCP_OAUTH_REFRESH_TOKEN_TTL_MS } from './mcp-oauth-token-lifetimes'
@@ -129,6 +131,26 @@ export const mcpOAuthTokenService = {
}
},
+ async authenticate({ token, log }: AuthenticateParams): Promise<AuthenticateResult> {
+ const { data: payload, error } = await tryCatch(() => mcpOAuthTokenService.verifyAccessToken(token))
+ if (error || isNil(payload)) {
+ log.debug({ error }, 'MCP OAuth token verification failed')
+ return { status: 'invalid' }
+ }
+ const { grantId } = payload
+ if (!isNil(grantId)) {
+ const { data: revoked, error: revocationError } = await tryCatch(() => mcpOAuthRevocationList.isRevoked({ grantId }))
+ if (revocationError) {
+ log.error({ error: revocationError }, 'Could not read the MCP OAuth revocation list')
+ return { status: 'unavailable' }
+ }
+ if (revoked) {
+ return { status: 'invalid' }
+ }
+ }
+ return { status: 'ok', payload }
+ },
+
async verifyAccessToken(token: string): Promise<McpOAuthAccessTokenPayload> {
const key = await jwtUtils.getJwtSecret()
const payload = await jwtUtils.decodeAndVerify<McpOAuthAccessTokenPayload>({
@@ -208,7 +230,7 @@ export const mcpOAuthTokenService = {
},
async issueInternalAccessToken({ userId, platformId, projectId }: { userId: string, platformId: string, projectId: string | null }): Promise<string> {
- return issueAccessToken({ userId, platformId, projectId, clientId: INTERNAL_CHAT_CLIENT_ID, grantId: null, clientKey: null, scopes: ['mcp'] })
+ return issueAccessToken({ userId, platformId, projectId, clientId: INTERNAL_CHAT_CLIENT_ID, grantId: null, clientKey: null, scopes: DEFAULT_MCP_OAUTH_SCOPES })
},
}
@@ -301,6 +323,16 @@ type TokenResponse = {
refresh_token?: string
}
+type AuthenticateParams = {
+ token: string
+ log: FastifyBaseLogger
+}
+
+type AuthenticateResult =
+ | { status: 'ok', payload: McpOAuthAccessTokenPayload }
+ | { status: 'invalid' }
+ | { status: 'unavailable' }
+
export const INTERNAL_CHAT_CLIENT_ID = 'internal-chat'
export type McpOAuthAccessTokenPayload = {
diff --git a/packages/server/api/test/integration/ce/mcp/mcp-oauth-oidc.test.ts b/packages/server/api/test/integration/ce/mcp/mcp-oauth-oidc.test.ts
new file mode 100644
index 00000000000..4aa87463ecb
--- /dev/null
+++ b/packages/server/api/test/integration/ce/mcp/mcp-oauth-oidc.test.ts
@@ -0,0 +1,246 @@
+import { createPublicKey, JsonWebKey } from 'node:crypto'
+import { DefaultProjectRole } from '@activepieces/shared'
+import { FastifyInstance } from 'fastify'
+import jwtLibrary from 'jsonwebtoken'
+import { beforeAll, describe, expect, it } from 'vitest'
+import { databaseConnection } from '../../../../src/app/database/database-connection'
+import { MCP_OAUTH_REDIRECT_URI, mcpOAuthTestHelpers } from '../../../helpers/mcp-oauth'
+import { createMemberContext, createTestContext, TestContext } from '../../../helpers/test-context'
+import { setupTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance
+let ctx: TestContext
+
+async function discoveredIssuer(headers?: Record<string, string>): Promise<string> {
+ const res = await app.inject({ method: 'GET', url: '/.well-known/openid-configuration', headers })
+ return res.json().issuer
+}
+
+async function completeFlow({ scope, nonce, headers, ctx: flowCtx = ctx }: { scope: string, nonce?: string, headers?: Record<string, string>, ctx?: TestContext }): Promise<TokenResponse> {
+ const client = await mcpOAuthTestHelpers.registerClient({ app, tokenEndpointAuthMethod: 'none' })
+ const { verifier, challenge } = mcpOAuthTestHelpers.generatePkce()
+
+ const query: Record<string, string> = {
+ client_id: client.client_id,
+ redirect_uri: MCP_OAUTH_REDIRECT_URI,
+ response_type: 'code',
+ code_challenge: challenge,
+ code_challenge_method: 'S256',
+ scope,
+ }
+ if (nonce !== undefined) {
+ query.nonce = nonce
+ }
+
+ const consent = await app.inject({ method: 'GET', url: '/authorize?' + new URLSearchParams(query).toString(), headers })
+ expect(consent.statusCode).toBe(302)
+
+ const authRequestId = new URL(String(consent.headers.location), MCP_OAUTH_REDIRECT_URI).searchParams.get('authRequestId')
+ const approved = await flowCtx.post('/v1/mcp-oauth/approve', { authRequestId, projectId: flowCtx.project.id })
+ expect(approved.statusCode).toBe(200)
+
+ const code = new URL(approved.json().redirectUrl).searchParams.get('code')
+ const token = await app.inject({
+ method: 'POST',
+ url: '/token',
+ headers,
+ payload: {
+ grant_type: 'authorization_code',
+ code,
+ code_verifier: verifier,
+ redirect_uri: MCP_OAUTH_REDIRECT_URI,
+ client_id: client.client_id,
+ },
+ })
+ expect(token.statusCode).toBe(200)
+
+ const issued: Omit<TokenResponse, 'clientId'> = token.json()
+ return { ...issued, clientId: client.client_id }
+}
+
+async function verifyIdToken(idToken: string | undefined): Promise<Record<string, unknown>> {
+ if (idToken === undefined) {
+ throw new Error('expected the token response to carry an id_token')
+ }
+ const jwks = await app.inject({ method: 'GET', url: '/.well-known/jwks.json' })
+ expect(jwks.statusCode).toBe(200)
+ const [jwk] = jwks.json().keys as JsonWebKey[]
+ const publicKey = createPublicKey({ key: jwk, format: 'jwk' })
+ return jwtLibrary.verify(idToken, publicKey, { algorithms: ['RS256'] }) as Record<string, unknown>
+}
+
+describe('MCP OAuth OpenID Connect', () => {
+ beforeAll(async () => {
+ app = await setupTestEnvironment({ fresh: true })
+ ctx = await createTestContext(app)
+ })
+
+ it('publishes an OIDC discovery document advertising openid and email', async () => {
+ const res = await app.inject({ method: 'GET', url: '/.well-known/openid-configuration' })
+
+ expect(res.statusCode).toBe(200)
+ const body = res.json()
+ const issuer = body.issuer
+ expect(body.userinfo_endpoint).toBe(`${issuer}/userinfo`)
+ expect(body.scopes_supported).toEqual(expect.arrayContaining(['openid', 'email']))
+ expect(body.claims_supported).toEqual(expect.arrayContaining(['email', 'email_verified']))
+ })
+
+ it('advertises the openid and email scopes on the authorization server metadata', async () => {
+ const res = await app.inject({ method: 'GET', url: '/.well-known/oauth-authorization-server' })
+
+ expect(res.statusCode).toBe(200)
+ expect(res.json().scopes_supported).toEqual(expect.arrayContaining(['mcp', 'openid', 'email']))
+ })
+
+ it('returns a verifiable id_token carrying the verified email and the request nonce', async () => {
+ const nonce = 'n-0S6_WzA2Mj'
+ const tokens = await completeFlow({ scope: 'openid email profile mcp', nonce })
+
+ expect(tokens.id_token).toEqual(expect.any(String))
+
+ const claims = await verifyIdToken(tokens.id_token)
+ expect(claims.iss).toBe(await discoveredIssuer())
+ expect(claims.aud).toBe(tokens.clientId)
+ expect(claims.sub).toBe(ctx.user.id)
+ expect(claims.email).toBe(ctx.userIdentity.email)
+ expect(claims.email_verified).toBe(ctx.userIdentity.verified)
+ expect(claims.nonce).toBe(nonce)
+ expect(claims.name).toBe(`${ctx.userIdentity.firstName} ${ctx.userIdentity.lastName}`)
+ })
+
+ it('issues an id_token whose iss matches the issuer the client discovered on a custom domain', async () => {
+ const headers = { 'x-forwarded-host': 'mcp.customer.example', 'x-forwarded-proto': 'https' }
+
+ const resourceMetadata = await app.inject({
+ method: 'GET',
+ url: '/.well-known/oauth-protected-resource/mcp/platform',
+ headers,
+ })
+ const [authorizationServer] = resourceMetadata.json().authorization_servers
+ expect(authorizationServer).toBe('https://mcp.customer.example')
+ expect(await discoveredIssuer(headers)).toBe(authorizationServer)
+
+ const tokens = await completeFlow({ scope: 'openid email', headers })
+
+ const claims = await verifyIdToken(tokens.id_token)
+ expect(claims.iss).toBe(authorizationServer)
+ expect(claims.email).toBe(ctx.userIdentity.email)
+ })
+
+ it('returns the verified email from the userinfo endpoint', async () => {
+ const tokens = await completeFlow({ scope: 'openid email mcp' })
+
+ const res = await app.inject({
+ method: 'GET',
+ url: '/userinfo',
+ headers: { authorization: `Bearer ${tokens.access_token}` },
+ })
+
+ expect(res.statusCode).toBe(200)
+ expect(res.json()).toEqual({
+ sub: ctx.user.id,
+ email: ctx.userIdentity.email,
+ email_verified: ctx.userIdentity.verified,
+ })
+ })
+
+ it('keeps serving the verified email from userinfo after a refresh', async () => {
+ const tokens = await completeFlow({ scope: 'openid email mcp' })
+
+ const refreshed = await app.inject({
+ method: 'POST',
+ url: '/token',
+ payload: {
+ grant_type: 'refresh_token',
+ refresh_token: tokens.refresh_token,
+ client_id: tokens.clientId,
+ },
+ })
+ expect(refreshed.statusCode).toBe(200)
+
+ const res = await app.inject({
+ method: 'GET',
+ url: '/userinfo',
+ headers: { authorization: `Bearer ${refreshed.json().access_token}` },
+ })
+
+ expect(res.statusCode).toBe(200)
+ expect(res.json().email).toBe(ctx.userIdentity.email)
+ expect(res.json().email_verified).toBe(ctx.userIdentity.verified)
+ })
+
+ it('withholds the email and the id_token when openid was not granted', async () => {
+ const tokens = await completeFlow({ scope: 'mcp' })
+ expect(tokens.id_token).toBeUndefined()
+
+ const res = await app.inject({
+ method: 'GET',
+ url: '/userinfo',
+ headers: { authorization: `Bearer ${tokens.access_token}` },
+ })
+
+ expect(res.statusCode).toBe(200)
+ expect(res.json()).toEqual({ sub: ctx.user.id })
+ })
+
+ it('rejects userinfo once the user behind the token is gone', async () => {
+ const gone = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.ADMIN })
+ const tokens = await completeFlow({ scope: 'openid email', ctx: gone })
+ await databaseConnection().getRepository('user').delete({ id: gone.user.id })
+
+ const res = await app.inject({
+ method: 'GET',
+ url: '/userinfo',
+ headers: { authorization: `Bearer ${tokens.access_token}` },
+ })
+
+ expect(res.statusCode).toBe(401)
+ })
+
+ it('rejects userinfo without a bearer token', async () => {
+ const res = await app.inject({ method: 'GET', url: '/userinfo' })
+
+ expect(res.statusCode).toBe(401)
+ expect(res.headers['www-authenticate']).toBe('Bearer')
+ })
+
+ it('rejects userinfo with a forged token', async () => {
+ const forged = jwtLibrary.sign({ sub: ctx.user.id, type: 'mcp_oauth' }, 'not-the-server-secret')
+
+ const res = await app.inject({
+ method: 'GET',
+ url: '/userinfo',
+ headers: { authorization: `Bearer ${forged}` },
+ })
+
+ expect(res.statusCode).toBe(401)
+ expect(res.headers['www-authenticate']).toBe('Bearer error="invalid_token"')
+ })
+
+ it('rejects userinfo after the grant is revoked', async () => {
+ const tokens = await completeFlow({ scope: 'openid email mcp' })
+
+ const revoked = await app.inject({
+ method: 'POST',
+ url: '/revoke',
+ payload: { token: tokens.refresh_token, client_id: tokens.clientId },
+ })
+ expect(revoked.statusCode).toBe(200)
+
+ const res = await app.inject({
+ method: 'GET',
+ url: '/userinfo',
+ headers: { authorization: `Bearer ${tokens.access_token}` },
+ })
+
+ expect(res.statusCode).toBe(401)
+ })
+})
+
+type TokenResponse = {
+ clientId: string
+ access_token: string
+ refresh_token: string
+ id_token?: string
+}
diff --git a/packages/server/api/test/integration/ce/oidc/oidc-discovery.test.ts b/packages/server/api/test/integration/ce/oidc/oidc-discovery.test.ts
index ebed23bd054..5bdddecf4dc 100644
--- a/packages/server/api/test/integration/ce/oidc/oidc-discovery.test.ts
+++ b/packages/server/api/test/integration/ce/oidc/oidc-discovery.test.ts
@@ -25,7 +25,7 @@ describe('OIDC Discovery', () => {
const body = response.json()
expect(body.issuer).toBeDefined()
expect(body.jwks_uri).toBe(`${body.issuer}/.well-known/jwks.json`)
- expect(body.response_types_supported).toEqual(['id_token'])
+ expect(body.response_types_supported).toEqual(['code'])
expect(body.id_token_signing_alg_values_supported).toEqual(['RS256'])
expect(body.subject_types_supported).toEqual(['public'])
})
diff --git a/packages/server/api/test/integration/ce/oidc/oidc-token.test.ts b/packages/server/api/test/integration/ce/oidc/oidc-token.test.ts
index 0ccf7b27ec2..463e6ef3ed4 100644
--- a/packages/server/api/test/integration/ce/oidc/oidc-token.test.ts
+++ b/packages/server/api/test/integration/ce/oidc/oidc-token.test.ts
@@ -131,6 +131,23 @@ describe('OIDC Token Endpoint', () => {
expect(decoded.payload.sub).toContain(projectId)
})
+ it('carries no identity claim, so it can never pass as a user id_token signed by the same key', async () => {
+ const response = await app!.inject({
+ method: 'POST',
+ url: '/api/v1/worker/oidc-token',
+ headers: { authorization: `Bearer ${engineToken}` },
+ body: { audience: 'some-mcp-client-id' },
+ })
+
+ const { token } = response.json()
+ const decoded = jwtUtils.decode<Record<string, unknown>>({ jwt: token })
+
+ expect(decoded.payload.email).toBeUndefined()
+ expect(decoded.payload.email_verified).toBeUndefined()
+ expect(decoded.payload.nonce).toBeUndefined()
+ expect(Object.keys(decoded.payload).sort()).toEqual(['aud', 'exp', 'iat', 'iss', 'sub'])
+ })
+
it('should use RS256 as the signing algorithm', async () => {
const response = await app!.inject({
method: 'POST',
diff --git a/packages/web/vite.config.mts b/packages/web/vite.config.mts
index 6a667022daf..8e66be6a83d 100644
--- a/packages/web/vite.config.mts
+++ b/packages/web/vite.config.mts
@@ -83,6 +83,14 @@ export default defineConfig(({ command, mode }) => {
'X-Forwarded-Host': 'localhost:4200',
},
},
+ '/userinfo': {
+ target: 'http://127.0.0.1:3000',
+ secure: false,
+ changeOrigin: true,
+ headers: {
+ 'X-Forwarded-Host': 'localhost:4200',
+ },
+ },
},
port: 4200,
host: '0.0.0.0',