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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(mcp): revoking a grant cuts the client off now, not in 15 minutes (#15181)
Othman Abu Ajamiehb38695dd3488
diff --git a/brain/knowledge/ai-intelligence/mcp-server.md b/brain/knowledge/ai-intelligence/mcp-server.mdindex 61e11119eba..b172c1959d9 100644--- a/brain/knowledge/ai-intelligence/mcp-server.md+++ b/brain/knowledge/ai-intelligence/mcp-server.md@@ -10,6 +10,7 @@ Exposes an Activepieces project as an MCP server so AI clients (Claude Desktop,**Grant** — one row of `mcp_oauth_token`: this user's live authorisation for one registered client. The unit the connect page lists and revokes, named `McpOAuthGrant` and served from `/v1/mcp-oauth/grants`.**Client** — one `mcp_oauth_client` registration row. Not a stable identity: Claude Code and Codex re-run DCR per sign-in, so one client-as-a-product yields many rows, and one user re-authenticating yields many grants. _Avoid_: using "client" for the thing being revoked.+**Revocation List** — the Redis keys (`mcp_oauth:revoked_grant:<grantId>`) naming grants revoked while their access tokens are still unexpired, read on every `POST /mcp`. TTL outlives the access token, so it empties itself. _Avoid_: "blacklist", "denylist"**Connection** — belongs to piece auth (`AppConnection`), never to MCP. _Avoid_: "MCP connection" in code; the tab label "Connections" and the `/mcp-server/connections` URL are deliberate copy, not the domain term — the code under `app/routes/mcp-server/grants/` says grant.**Activity** — one `mcp_activity` row: one recorded `ap_run_action` call by a connected client. Never a flow run, and never one row per flow edit. _Avoid_: "run" (means `flow_run`; the retired V1 table was `mcp_run`).**Activity feed** — the list surface over those rows and the `/v1/mcp-activity` endpoint behind it. Cursor-paginated, newest first, no count. _Avoid_: "activity log" and "audit log" — a row is written off the response path and is lost to a crash mid-write, which is acceptable for a feed and is not evidence.@@ -31,7 +32,7 @@ Exposes an Activepieces project as an MCP server so AI clients (Claude Desktop,### How it works- Main protocol endpoint: `POST /mcp` at the domain root, plus `POST /mcp/platform` (StreamableHTTP), both registered in `server.ts`. Config lives under the project API (`GET/POST` on the project MCP server route).-- Auth is **OAuth-only**: `resolveIdentity` accepts an `Authorization: Bearer` value only if `mcpOAuthTokenService.verifyAccessToken` verifies it as a signed JWT with audience `JwtAudience.MCP_OAUTH_ACCESS`. There is no static-token authenticator and no `?token=` query path.+- Auth is **OAuth-only**: `resolveIdentity` accepts an `Authorization: Bearer` value only if `mcpOAuthTokenService.verifyAccessToken` verifies it as a signed JWT with audience `JwtAudience.MCP_OAUTH_ACCESS`, *and* the Revocation List does not name its grant. It returns three outcomes — `ok`, `invalid` (`401`), and `unavailable` (`503`, the list could not be read). There is no static-token authenticator and no `?token=` query path.- AI pieces consume MCP tools over three transports: `SIMPLE_HTTP`, `STREAMABLE_HTTP`, `SSE`.- Embed SDK adds `authorizeMcp()` (in-embed OAuth consent), `mcpSettings()`, and `generateMcpToken()` (mints `{ mcpServerUrl, mcpToken }` with no OAuth flow, backed by `POST /v1/projects/:projectId/mcp-server/token` — a short-lived 15-min project-scoped token).@@ -44,6 +45,7 @@ Exposes an Activepieces project as an MCP server so AI clients (Claude Desktop,heuristic later does **not** relabel existing grants (they age out in 30 days, and an active client relabels onits next refresh, which backfills a NULL key), and `NULL` is not a third state — it means "signed in before thecolumn existed" and reads as `unknown` everywhere, including the `?clientKeys=unknown` filter.+- **Revocation only reaches a live access token through the `grantId` claim, and a token without one is trusted.** `revoked = true` is read by the refresh flow, never by `POST /mcp`, so the Revocation List is what actually cuts a connected client off — see [000033](../decisions/000033-a-revoked-mcp-grant-is-blocked-by-a-redis-revocation-list.md). It is keyed on `grantId` (the `mcp_oauth_token` row id) because `clientId` is a DCR registration shared across users, so revoking by it would kill strangers' tokens. Two populations carry no claim and therefore skip the check entirely: tokens minted before the claim shipped (they age out in 15 minutes, and `refreshAccessToken` stamps the claim) and `issueInternalAccessToken` tokens for EE chat, which have no grant row at all. Anything that mints an MCP access token without a grant row inherits that exemption silently. Platform teardown is a third gap by design — it `DELETE`s the rows instead of revoking them, so no keys are written.- **Claude Code and Codex re-run Dynamic Client Registration on *every* sign-in**, registering the exactephemeral loopback port they are about to bind (`http://localhost:<port>/callback`,`http://127.0.0.1:<port>/callback/<callback_id>`). So the exact-string `validateRedirectUri` works anddiff --git a/brain/knowledge/decisions/000033-a-revoked-mcp-grant-is-blocked-by-a-redis-revocation-list.md b/brain/knowledge/decisions/000033-a-revoked-mcp-grant-is-blocked-by-a-redis-revocation-list.mdnew file mode 100644index 00000000000..39e46282633--- /dev/null+++ b/brain/knowledge/decisions/000033-a-revoked-mcp-grant-is-blocked-by-a-redis-revocation-list.md@@ -0,0 +1,30 @@+---+status: accepted+---++# A revoked MCP grant is blocked by a Redis revocation list, not by waiting out the token++## Decision+Revoking an MCP OAuth grant writes `mcp_oauth:revoked_grant:<grantId>` to Redis with a TTL of the access-token lifetime plus a minute, and every `POST /mcp` reads that key before serving. The access token carries the grant's row id as a `grantId` claim so there is something to read it by. Both revocation paths write it — `revokeGrants` behind the Reach tab, and the RFC 7009 `/revoke` a client calls on disconnect. A token with no `grantId` claim skips the check.++## Context+`revokeGrants` set `revoked = true` and stopped there. That kills the refresh flow, which reads the column — but `resolveIdentity` only verified the JWT signature and never consulted the row, so an already-issued access token kept calling tools for up to fifteen more minutes. The Reach tab reported the grant revoked the moment the request returned. The API was asserting something it had not made true.++## Why++**The token had nothing to key a revocation on.** The payload was `{ sub, projectId, platformId, clientId, scopes }` — no `jti`, no row id. `clientId` was the tempting shortcut and is wrong: a DCR registration is shared by every user who signed in through that client, so revoking one person's Claude grant would have killed strangers' live tokens. Tracking issued `jti`s per grant would have meant a Redis write on every token issue to enable a rare read. Stamping the grant's own id is one claim, no extra state, and it names exactly the thing the UI revokes.++**Checking the row in Postgres instead was the real alternative.** It is always correct, needs no TTL and no cache semantics, and the request path already runs several queries — one more indexed PK lookup would not have been the bottleneck. Redis won on it being the cheaper of two cheap things on a path that has no reason to grow a query, and on the list being self-emptying: a revoked grant stops costing anything the moment its tokens could no longer be alive.++**Failing open on a Redis error would have silently reinstated the bug.** The check fails closed, but answers `503` rather than `401`. A `WWW-Authenticate: error="invalid_token"` tells an MCP client its credentials are bad and several will drop the refresh token and push the user back through consent — a full re-authorisation over a 200ms hiccup. `503` makes them retry. Redis is already load-bearing for the API, so the availability coupling this adds is not new.++**Postgres is written first, and a Redis failure fails the request.** The reverse order would leave a grant that looks revoked for fifteen minutes and then quietly works again. Swallowing the Redis error would return `204` while the token still functions, which is the exact lie being removed. Retrying is safe: the row is already revoked and the refresh token already dead, so a retry only re-writes the keys.++**The TTL is derived, not typed.** `MCP_OAUTH_REVOKED_GRANT_TTL_SECONDS = MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS + 60`, both in `mcp-oauth-token-lifetimes.ts`, so tuning the token lifetime cannot leave the list covering less than the tail of it. The extra minute absorbs clock skew: a token signed on a node running behind Redis outlives an exact-lifetime key by the skew, and that gap would be silent.++## Consequences+- **Redis is now load-bearing for MCP authentication.** An MCP request whose token carries a `grantId` cannot be served while the revocation list is unreadable — it gets `503`. Before this, a Redis outage left `POST /mcp` working.+- **A claim-less token is trusted.** Tokens minted before this shipped, and internal chat tokens from `issueInternalAccessToken` which have no grant row, skip the check. The first population self-heals within fifteen minutes of deploy — `refreshAccessToken` stamps the claim, so even 30-day refresh tokens are covered — and the second is by design. The cost is a fifteen-minute window after deploy where a revoke behaves as it did before.+- **Platform teardown still leaves a residual window.** `platform-teardown-jobs` bulk-`DELETE`s `mcp_oauth_token` rows rather than revoking them, so no keys are written and tokens stay valid until they expire. Deliberate: the platform's data is being erased anyway, and covering it would mean either enumerating every id or a second platform-scoped key that turns the hot-path `GET` into an `MGET`.+- **`distributedStore` gained `putBatch(pairs, ttl)`**, a pipelined `SETEX`, so a bulk revoke of up to 100 grants is one round trip. `putBooleanBatch` already existed but takes no TTL.+- **A pipelined write has to inspect its own results, or fail-closed is a fiction.** ioredis resolves `multi().exec()` with a `[error, result]` tuple per command instead of rejecting, so a single `SETEX` refused by Redis — `OOM`, a replica in read-only mode — used to leave `putBatch` reporting success. Both revoke endpoints would then have returned `204` with the row marked revoked and the key missing, which is the precise failure this whole decision exists to prevent, arriving silently. `exec()` also resolves `null` when the transaction is discarded, which is likewise not success. Both batch helpers now throw on either. Anything else added to this file that pipelines commands needs the same treatment.diff --git a/packages/server/api/src/app/database/redis/distributed-store-factory.ts b/packages/server/api/src/app/database/redis/distributed-store-factory.tsindex 029d185067f..640f3fffd34 100644--- a/packages/server/api/src/app/database/redis/distributed-store-factory.ts+++ b/packages/server/api/src/app/database/redis/distributed-store-factory.ts@@ -13,6 +13,19 @@ export const distributedStoreFactory = (getRedisClient: () => Promise<Redis>) =>}},+ async putBatch(keyValuePairs: Array<{ key: string, value: unknown }>, ttlInSeconds: number): Promise<void> {+ if (keyValuePairs.length === 0) return++ const redisClient = await getRedisClient()+ const multi = redisClient.multi()++ for (const { key, value } of keyValuePairs) {+ multi.setex(key, ttlInSeconds, JSON.stringify(value))+ }++ assertEveryCommandApplied(await multi.exec())+ },+async get<T>(key: string): Promise<T | null> {const redisClient = await getRedisClient()const value = await redisClient.get(key)@@ -66,7 +79,7 @@ export const distributedStoreFactory = (getRedisClient: () => Promise<Redis>) =>multi.set(key, value ? '1' : '0')}- await multi.exec()+ assertEveryCommandApplied(await multi.exec())},async hgetJson<T extends Record<string, unknown>>(key: string): Promise<T | null> {@@ -125,4 +138,16 @@ export const distributedStoreFactory = (getRedisClient: () => Promise<Redis>) =>},})+function assertEveryCommandApplied(results: RedisTransactionResults): void {+ if (isNil(results)) {+ throw new Error('Redis transaction was discarded, no command was applied')+ }+ const failed = results.find(([error]) => !isNil(error))+ if (!isNil(failed)) {+ throw failed[0]+ }+}++type RedisTransactionResults = [error: Error | null, result: unknown][] | null+export type DistributedStore = ReturnType<typeof distributedStoreFactory>diff --git a/packages/server/api/src/app/database/redis/keys.ts b/packages/server/api/src/app/database/redis/keys.tsindex f72d5d7960b..a539d3843e7 100644--- a/packages/server/api/src/app/database/redis/keys.ts+++ b/packages/server/api/src/app/database/redis/keys.ts@@ -19,6 +19,7 @@ export const getProjectConcurrencyPoolKey = (projectId: ProjectId): string => `pexport const getConcurrencyPoolLimitKey = (poolId: string): string => `concurrency-pool:limit:${poolId}` // gets limit value for the poolexport const getConcurrencyPoolSetKey = (poolId: string): string => `active_jobs_set:pool:${poolId}`export const getConcurrencyPoolParkedKey = (poolId: string): string => `parked_jobs_set:pool:${poolId}`+export const getMcpOAuthRevokedGrantKey = (grantId: string): string => `mcp_oauth:revoked_grant:${grantId}`export const BILLING_ENFORCED_TTL_SECONDS = 24 * 60 * 60export const PLATFORM_PLAN_NAME_TTL_SECONDS = 24 * 60 * 60diff --git a/packages/server/api/src/app/mcp/oauth/mcp-oauth.controller.ts b/packages/server/api/src/app/mcp/oauth/mcp-oauth.controller.tsindex 0fab21d7248..43499d9d80a 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,6 +12,7 @@ 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) => {@@ -56,11 +57,15 @@ function registerMcpEndpoint(app: Parameters<FastifyPluginAsyncZod>[0], scope: Mreturn unauthorized({ req, reply, scope, message: 'Authorization: Bearer <token> required' })}- const identity = await resolveIdentity({ token, scope, log: req.log })- if (isNil(identity)) {+ const result = await resolveIdentity({ token, scope, log: req.log })+ if (result.status === 'unavailable') {+ return revocationCheckUnavailable(reply)+ }+ if (result.status === 'invalid') {return unauthorized({ req, reply, scope, message: 'Invalid or expired access token', invalidToken: true })}+ const { identity } = resultconst { mcp, userId, platformId } = await resolveMcpAndUser({ identity, log: req.log })if (isNil(mcp)) {return unauthorized({ req, reply, scope, message: 'Invalid project or token.', invalidToken: true })@@ -110,22 +115,40 @@ function unauthorized({ req, reply, scope, message, invalidToken }: {})}-async function resolveIdentity({ token, scope, log }: { token: string, scope: McpServerType, log: FastifyBaseLogger }): Promise<ResolvedIdentity | null> {+function revocationCheckUnavailable(reply: FastifyReply): FastifyReply {+ return reply.status(503).header('Retry-After', '1').send({+ error: 'temporarily_unavailable',+ message: 'Could not verify the access token right now, retry shortly.',+ })+}++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 null+ 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 { projectId } = payloadconst clientKey = payload.clientKey ?? nullconst isPlatformToken = isNil(projectId)if (isPlatformToken && scope === McpServerType.PLATFORM) {- return { type: McpServerType.PLATFORM, platformId: payload.platformId, userId: payload.sub, clientKey, clientId: payload.clientId }+ return { status: 'ok', identity: { type: McpServerType.PLATFORM, platformId: payload.platformId, userId: payload.sub, clientKey, clientId: payload.clientId } }}if (!isPlatformToken && scope === McpServerType.PROJECT) {- return { type: McpServerType.PROJECT, projectId, platformId: payload.platformId, userId: payload.sub, clientKey, clientId: payload.clientId }+ return { status: 'ok', identity: { type: McpServerType.PROJECT, projectId, platformId: payload.platformId, userId: payload.sub, clientKey, clientId: payload.clientId } }}- return null+ return { status: 'invalid' }}async function resolveMcpAndUser({ identity, log }: { identity: ResolvedIdentity, log: FastifyBaseLogger }): Promise<{ mcp: PopulatedMcpServer | null, userId?: string, platformId?: string }> {@@ -171,6 +194,11 @@ type ResolvedIdentity =| { type: McpServerType.PROJECT, projectId: string, platformId: string, userId: string, clientKey: McpOAuthClientKey | null, clientId: string }| { type: McpServerType.PLATFORM, platformId: string, userId: string, clientKey: McpOAuthClientKey | null, clientId: string }+type IdentityResult =+ | { status: 'ok', identity: ResolvedIdentity }+ | { status: 'invalid' }+ | { status: 'unavailable' }+const chatConversationRepo = repoFactory(AgentConversationEntity)async function resolveConversationProjectId({ conversationId, identity, log }: {diff --git a/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-revocation-list.ts b/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-revocation-list.tsnew file mode 100644index 00000000000..a6454646fac--- /dev/null+++ b/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-revocation-list.ts@@ -0,0 +1,23 @@+import { getMcpOAuthRevokedGrantKey } from '../../../database/redis/keys'+import { distributedStore } from '../../../database/redis-connections'+import { MCP_OAUTH_REVOKED_GRANT_TTL_SECONDS } from './mcp-oauth-token-lifetimes'++export const mcpOAuthRevocationList = {+ async revoke({ grantIds }: RevokeParams): Promise<void> {+ const entries = grantIds.map((grantId) => ({ key: getMcpOAuthRevokedGrantKey(grantId), value: true }))+ await distributedStore.putBatch(entries, MCP_OAUTH_REVOKED_GRANT_TTL_SECONDS)+ },++ async isRevoked({ grantId }: IsRevokedParams): Promise<boolean> {+ const revoked = await distributedStore.get<boolean>(getMcpOAuthRevokedGrantKey(grantId))+ return revoked === true+ },+}++type RevokeParams = {+ grantIds: string[]+}++type IsRevokedParams = {+ grantId: string+}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.tsnew file mode 100644index 00000000000..5a5291b28d1--- /dev/null+++ b/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token-lifetimes.ts@@ -0,0 +1,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_REVOKED_GRANT_TTL_SECONDS = MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS + CLOCK_SKEW_BUFFER_SECONDSdiff --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.tsindex 6686b7e9d16..59611008665 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@@ -11,13 +11,13 @@ import { mcpListingUtils } from '../../mcp-listing-utils'import { mcpOAuthClientIdentity } from '../client/mcp-oauth-client-identity'import { McpOAuthClientEntity } from '../client/mcp-oauth-client.entity'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'import { McpOAuthTokenEntity } from './mcp-oauth-token.entity'const repo = repoFactory(McpOAuthTokenEntity)const clientRepo = repoFactory(McpOAuthClientEntity)-const ACCESS_TOKEN_TTL_15_MINUTES_SECONDS = 15 * 60-const REFRESH_TOKEN_TTL_30_DAYS_MS = 30 * 24 * 60 * 60 * 1000const INTERNAL_CHAT_CLIENT_ID = 'internal-chat'const DEFAULT_GRANT_PAGE_SIZE = 20const TOKEN_ALIAS = 'mcp_oauth_token'@@ -39,12 +39,13 @@ async function issueAccessToken(params: IssueAccessTokenParams): Promise<string>projectId: params.projectId,platformId: params.platformId,clientId: params.clientId,+ ...spreadIfDefined('grantId', params.grantId ?? undefined),clientKey: params.clientKey,scopes: params.scopes,type: 'mcp_oauth',},key,- expiresInSeconds: ACCESS_TOKEN_TTL_15_MINUTES_SECONDS,+ expiresInSeconds: MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS,audience: JwtAudience.MCP_OAUTH_ACCESS,})}@@ -69,7 +70,7 @@ export const mcpOAuthTokenService = {projectId: params.projectId,platformId: params.platformId,scopes: params.scopes,- expiresAt: new Date(Date.now() + REFRESH_TOKEN_TTL_30_DAYS_MS).toISOString(),+ expiresAt: new Date(Date.now() + MCP_OAUTH_REFRESH_TOKEN_TTL_MS).toISOString(),revoked: false,lastUsedAt: null,created: new Date().toISOString(),@@ -82,6 +83,7 @@ export const mcpOAuthTokenService = {projectId: params.projectId,platformId: params.platformId,clientId: params.clientId,+ grantId: tokenRecord.id,clientKey,scopes: params.scopes,})@@ -89,7 +91,7 @@ export const mcpOAuthTokenService = {return {access_token: accessToken,token_type: 'Bearer',- expires_in: ACCESS_TOKEN_TTL_15_MINUTES_SECONDS,+ expires_in: MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS,refresh_token: rawRefreshToken,}},@@ -115,6 +117,7 @@ export const mcpOAuthTokenService = {projectId: record.projectId,platformId: record.platformId,clientId: record.clientId,+ grantId: record.id,clientKey,scopes: record.scopes ?? [],})@@ -122,7 +125,7 @@ export const mcpOAuthTokenService = {return {access_token: accessToken,token_type: 'Bearer',- expires_in: ACCESS_TOKEN_TTL_15_MINUTES_SECONDS,+ expires_in: MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS,refresh_token: params.refreshToken,}},@@ -141,7 +144,12 @@ export const mcpOAuthTokenService = {},async revokeRefreshToken({ refreshToken, clientId }: RevokeRefreshTokenParams): Promise<void> {- await repo().update({ refreshToken: hashRefreshToken(refreshToken), clientId }, { revoked: true })+ const record = await repo().findOneBy({ refreshToken: hashRefreshToken(refreshToken), clientId })+ if (isNil(record)) {+ return+ }+ await repo().update({ id: record.id }, { revoked: true })+ await mcpOAuthRevocationList.revoke({ grantIds: [record.id] })},async listGrants({ platformId, userId, projectIds, memberIds, clientKeys, cursor, limit }: ListGrantsParams): Promise<SeekPage<McpOAuthGrant>> {@@ -195,11 +203,13 @@ export const mcpOAuthTokenService = {params: { message: 'One or more grants do not exist or are not yours to revoke' },})}- await repo().update({ id: In(matched.map((token) => token.id)) }, { revoked: true })+ const grantIds = matched.map((token) => token.id)+ await repo().update({ id: In(grantIds) }, { revoked: true })+ await mcpOAuthRevocationList.revoke({ grantIds })},async issueInternalAccessToken({ userId, platformId, projectId }: { userId: string, platformId: string, projectId: string | null }): Promise<string> {- return issueAccessToken({ userId, platformId, projectId, clientId: INTERNAL_CHAT_CLIENT_ID, clientKey: null, scopes: ['mcp'] })+ return issueAccessToken({ userId, platformId, projectId, clientId: INTERNAL_CHAT_CLIENT_ID, grantId: null, clientKey: null, scopes: ['mcp'] })},}@@ -236,6 +246,7 @@ type IssueAccessTokenParams = {projectId: string | nullplatformId: stringclientId: string+ grantId: string | nullclientKey: McpOAuthClientKey | nullscopes: string[]}@@ -296,6 +307,7 @@ export type McpOAuthAccessTokenPayload = {projectId: string | nullplatformId: stringclientId: string+ grantId?: stringclientKey: McpOAuthClientKey | nullscopes: string[]type: 'mcp_oauth'diff --git a/packages/server/api/test/integration/ce/mcp/mcp-oauth-revocation.test.ts b/packages/server/api/test/integration/ce/mcp/mcp-oauth-revocation.test.tsnew file mode 100644index 00000000000..4b9a5df5836--- /dev/null+++ b/packages/server/api/test/integration/ce/mcp/mcp-oauth-revocation.test.ts@@ -0,0 +1,158 @@+import { createHash, randomBytes } from 'crypto'+import { DefaultProjectRole, McpOAuthToken } from '@activepieces/shared'+import { FastifyInstance, LightMyRequestResponse } from 'fastify'+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { mcpOAuthClientService } from '../../../../src/app/mcp/oauth/client/mcp-oauth-client.service'+import { mcpOAuthRevocationList } from '../../../../src/app/mcp/oauth/token/mcp-oauth-revocation-list'+import { mcpOAuthTokenService } from '../../../../src/app/mcp/oauth/token/mcp-oauth-token.service'+import { db } from '../../../helpers/db'+import { createMemberContext, createTestContext, TestContext } from '../../../helpers/test-context'+import { setupTestEnvironment } from '../../../helpers/test-setup'++let app: FastifyInstance+let ctx: TestContext++const CLAUDE_REDIRECT = 'https://claude.ai/api/mcp/auth_callback'++const INITIALIZE_REQUEST = {+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2024-11-05',+ capabilities: {},+ clientInfo: { name: 'revocation-test', version: '1.0.0' },+ },+}++async function connectClient({ userId, projectId, platformId }: { userId: string, projectId: string | null, platformId: string }): Promise<Connection> {+ const codeVerifier = randomBytes(32).toString('base64url')+ const codeChallenge = createHash('sha256').update(codeVerifier).digest().toString('base64url')+ const { client_id: clientId } = await mcpOAuthClientService.register({+ redirectUris: [CLAUDE_REDIRECT],+ tokenEndpointAuthMethod: 'none',+ })+ const tokens = await mcpOAuthTokenService.exchangeCode({+ redirectUris: [CLAUDE_REDIRECT],+ codeVerifier,+ codeChallenge,+ codeChallengeMethod: 'S256',+ clientId,+ userId,+ projectId,+ platformId,+ scopes: ['mcp'],+ })+ const grant = await db.findOneBy<McpOAuthToken>('mcp_oauth_token', { clientId })+ if (grant === null) {+ throw new Error('expected exchangeCode to persist a grant')+ }+ if (tokens.refresh_token === undefined) {+ throw new Error('expected exchangeCode to return a refresh token')+ }+ return { grantId: grant.id, clientId, accessToken: tokens.access_token, refreshToken: tokens.refresh_token }+}++function callMcp(accessToken: string): Promise<LightMyRequestResponse> {+ return app.inject({+ method: 'POST',+ url: '/mcp',+ headers: {+ authorization: `Bearer ${accessToken}`,+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json',+ },+ payload: INITIALIZE_REQUEST,+ })+}++describe('MCP OAuth revocation list', () => {+ beforeAll(async () => {+ app = await setupTestEnvironment({ fresh: true })+ })++ beforeEach(async () => {+ ctx = await createTestContext(app)+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('rejects the already-issued access token as soon as the grant is revoked', async () => {+ const connection = await connectClient({ userId: ctx.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })+ expect((await callMcp(connection.accessToken)).statusCode).not.toBe(401)++ const revoked = await ctx.post('/v1/mcp-oauth/grants/revoke', { ids: [connection.grantId] })+ expect(revoked.statusCode).toBe(204)++ const afterRevoke = await callMcp(connection.accessToken)+ expect(afterRevoke.statusCode).toBe(401)+ expect(afterRevoke.headers['www-authenticate']).toContain('error="invalid_token"')+ })++ it('leaves another members live token alone when one grant is revoked', async () => {+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.ADMIN })+ const mine = await connectClient({ userId: ctx.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })+ const theirs = await connectClient({ userId: member.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })++ await ctx.post('/v1/mcp-oauth/grants/revoke', { ids: [mine.grantId] })++ expect((await callMcp(mine.accessToken)).statusCode).toBe(401)+ expect((await callMcp(theirs.accessToken)).statusCode).not.toBe(401)+ })++ it('leaves an internal chat token working, since it carries no grant', async () => {+ const connection = await connectClient({ userId: ctx.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })+ const internalToken = await mcpOAuthTokenService.issueInternalAccessToken({+ userId: ctx.user.id,+ platformId: ctx.platform.id,+ projectId: ctx.project.id,+ })++ await ctx.post('/v1/mcp-oauth/grants/revoke', { ids: [connection.grantId] })++ expect((await callMcp(internalToken)).statusCode).not.toBe(401)+ })++ it('rejects the access token when the client disconnects through /revoke', async () => {+ const connection = await connectClient({ userId: ctx.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })++ const revoked = await app.inject({+ method: 'POST',+ url: '/revoke',+ payload: { token: connection.refreshToken, client_id: connection.clientId, token_type_hint: 'refresh_token' },+ })+ expect(revoked.statusCode).toBe(200)++ expect((await callMcp(connection.accessToken)).statusCode).toBe(401)+ })++ it('refuses to report a revoke as done when the revocation list write fails', async () => {+ const connection = await connectClient({ userId: ctx.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })+ vi.spyOn(mcpOAuthRevocationList, 'revoke').mockRejectedValue(new Error('OOM command not allowed'))++ const response = await ctx.post('/v1/mcp-oauth/grants/revoke', { ids: [connection.grantId] })++ expect(response.statusCode).not.toBe(204)+ expect(response.statusCode).toBeGreaterThanOrEqual(500)+ })++ it('answers 503 rather than 401 when the revocation list cannot be read', async () => {+ const connection = await connectClient({ userId: ctx.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })+ vi.spyOn(mcpOAuthRevocationList, 'isRevoked').mockRejectedValue(new Error('redis is unreachable'))++ const response = await callMcp(connection.accessToken)++ expect(response.statusCode).toBe(503)+ expect(response.headers['retry-after']).toBe('1')+ expect(response.headers['www-authenticate']).toBeUndefined()+ })+})++type Connection = {+ grantId: string+ clientId: string+ accessToken: string+ refreshToken: string+}diff --git a/packages/server/api/test/unit/app/database/redis/distributed-store-batch.test.ts b/packages/server/api/test/unit/app/database/redis/distributed-store-batch.test.tsnew file mode 100644index 00000000000..43517a43839--- /dev/null+++ b/packages/server/api/test/unit/app/database/redis/distributed-store-batch.test.ts@@ -0,0 +1,48 @@+import Redis from 'ioredis'+import { describe, expect, it, vi } from 'vitest'+import { distributedStoreFactory } from '../../../../../src/app/database/redis/distributed-store-factory'++type ExecResult = [error: Error | null, result: unknown][] | null++function storeWithExecResult(execResult: ExecResult): { store: ReturnType<typeof distributedStoreFactory>, setex: ReturnType<typeof vi.fn> } {+ const setex = vi.fn()+ const client = {+ multi: () => ({ setex, set: vi.fn(), exec: () => Promise.resolve(execResult) }),+ } as unknown as Redis+ return { store: distributedStoreFactory(() => Promise.resolve(client)), setex }+}++const TWO_ENTRIES = [+ { key: 'mcp_oauth:revoked_grant:one', value: true },+ { key: 'mcp_oauth:revoked_grant:two', value: true },+]++describe('distributedStore.putBatch', () => {+ it('resolves when every queued command applied', async () => {+ const { store, setex } = storeWithExecResult([[null, 'OK'], [null, 'OK']])++ await expect(store.putBatch(TWO_ENTRIES, 960)).resolves.toBeUndefined()+ expect(setex).toHaveBeenCalledTimes(2)+ expect(setex).toHaveBeenCalledWith('mcp_oauth:revoked_grant:one', 960, 'true')+ })++ it('throws when one command inside the transaction failed', async () => {+ const oom = new Error('OOM command not allowed when used memory > maxmemory')+ const { store } = storeWithExecResult([[null, 'OK'], [oom, null]])++ await expect(store.putBatch(TWO_ENTRIES, 960)).rejects.toThrow(oom)+ })++ it('throws when the transaction was discarded entirely', async () => {+ const { store } = storeWithExecResult(null)++ await expect(store.putBatch(TWO_ENTRIES, 960)).rejects.toThrow('Redis transaction was discarded')+ })++ it('never opens a transaction for an empty batch', async () => {+ const { store, setex } = storeWithExecResult(null)++ await expect(store.putBatch([], 960)).resolves.toBeUndefined()+ expect(setex).not.toHaveBeenCalled()+ })+})diff --git a/packages/server/api/test/unit/app/mcp/oauth/token/mcp-oauth-revocation-list.test.ts b/packages/server/api/test/unit/app/mcp/oauth/token/mcp-oauth-revocation-list.test.tsnew file mode 100644index 00000000000..e0d45de5761--- /dev/null+++ b/packages/server/api/test/unit/app/mcp/oauth/token/mcp-oauth-revocation-list.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from 'vitest'+import { getMcpOAuthRevokedGrantKey } from '../../../../../../src/app/database/redis/keys'+import { MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS, MCP_OAUTH_REVOKED_GRANT_TTL_SECONDS } from '../../../../../../src/app/mcp/oauth/token/mcp-oauth-token-lifetimes'++describe('MCP OAuth revocation list', () => {+ it('namespaces a revoked grant under its own id', () => {+ expect(getMcpOAuthRevokedGrantKey('9SzBEyRXJP')).toBe('mcp_oauth:revoked_grant:9SzBEyRXJP')+ })++ it('outlives every access token the grant could have issued', () => {+ expect(MCP_OAUTH_REVOKED_GRANT_TTL_SECONDS).toBeGreaterThan(MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS)+ expect(MCP_OAUTH_REVOKED_GRANT_TTL_SECONDS).toBe(MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS + 60)+ })+})diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex 78694778902..b8f1ea8adc1 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -2658,7 +2658,7 @@"All projects": "All projects","MCP client": "MCP client","Revoke access": "Revoke access",- "Access ends within 15 minutes.": "Access ends within 15 minutes.",+ "Access ended. The client will ask to sign in again.": "Access ended. The client will ask to sign in again.","Could not revoke access. Try again.": "Could not revoke access. Try again.","Add the connector": "Add the connector","Add the server": "Add the server",@@ -2722,7 +2722,7 @@"{client} docs": "{client} docs","Or edit {path}": "Or edit {path}","{client} opens your browser on the first tool call. Approve the project.": "{client} opens your browser on the first tool call. Approve the project.",- "Revoking {entityName}. Access ends within 15 minutes. The client will ask to sign in again.": "Revoking {entityName}. Access ends within 15 minutes. The client will ask to sign in again.",+ "Revoking {entityName}. Access ends immediately. The client will ask to sign in again.": "Revoking {entityName}. Access ends immediately. The client will ask to sign in again.","Active today": "Active today","Clear a filter to see more.": "Clear a filter to see more.","How connecting works": "How connecting works",diff --git a/packages/web/src/app/routes/mcp-server/grants/grants-columns.tsx b/packages/web/src/app/routes/mcp-server/grants/grants-columns.tsxindex de7c547bb6b..150e874e19c 100644--- a/packages/web/src/app/routes/mcp-server/grants/grants-columns.tsx+++ b/packages/web/src/app/routes/mcp-server/grants/grants-columns.tsx@@ -143,7 +143,7 @@ export function buildGrantsColumns({<ConfirmationDeleteDialogtitle={t('Revoke access')}message={t(- 'Revoking {entityName}. Access ends within 15 minutes. The client will ask to sign in again.',+ 'Revoking {entityName}. Access ends immediately. The client will ask to sign in again.',{ entityName: clientLabel },)}entityName={clientLabel}diff --git a/packages/web/src/app/routes/mcp-server/grants/grants-tab.tsx b/packages/web/src/app/routes/mcp-server/grants/grants-tab.tsxindex 80524483f97..6cdeaa91215 100644--- a/packages/web/src/app/routes/mcp-server/grants/grants-tab.tsx+++ b/packages/web/src/app/routes/mcp-server/grants/grants-tab.tsx@@ -122,7 +122,7 @@ export function GrantsTab() {<ConfirmationDeleteDialogtitle={t('Revoke access')}message={t(- 'Revoking {entityName}. Access ends within 15 minutes. The client will ask to sign in again.',+ 'Revoking {entityName}. Access ends immediately. The client will ask to sign in again.',{ entityName: t('revokedGrants', { count: rows.length }) },)}entityName={t('revokedGrants', { count: rows.length })}diff --git a/packages/web/src/app/routes/mcp-server/mcp-grants-hooks.ts b/packages/web/src/app/routes/mcp-server/mcp-grants-hooks.tsindex ef71664a571..4b0add767b3 100644--- a/packages/web/src/app/routes/mcp-server/mcp-grants-hooks.ts+++ b/packages/web/src/app/routes/mcp-server/mcp-grants-hooks.ts@@ -28,7 +28,7 @@ export const mcpGrantsMutations = {return useMutation({mutationFn: (ids: string[]) => mcpGrantsApi.revoke({ ids }),onSuccess: () => {- toast.success(t('Access ends within 15 minutes.'));+ toast.success(t('Access ended. The client will ask to sign in again.'));queryClient.invalidateQueries({ queryKey: GRANTS_QUERY_KEY });},onError: () => {