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

Merge commit from fork

moaaz7a72b09a6a18
diff --git a/brain/knowledge/ai-intelligence/mcp-server.md b/brain/knowledge/ai-intelligence/mcp-server.md
index c8620b6c057..1177862ba5f 100644
--- a/brain/knowledge/ai-intelligence/mcp-server.md
+++ b/brain/knowledge/ai-intelligence/mcp-server.md
@@ -75,7 +75,8 @@ Exposes an Activepieces project as an MCP server so AI clients (Claude Desktop,
- **An `AP_FRONTEND_URL` path prefix is not a deployable shape, so MCP at `example.com/mcp` only works with the UI at the origin root.** The SPA is anchored to the origin root three ways (see [[web-feature-anatomy]]) and the router has no `basename`, so opening `example.com/<prefix>/` makes the app *relocate itself* to the origin root and nothing under the prefix ever routes. Measured 2026-09-09 behind Kong with a real SimpleSAMLphp IdP: with a prefixed `AP_FRONTEND_URL`, `/authorize` sends consent to `<prefix>/mcp-authorize`, SAML sign-in completes, and the user lands on `/projects/…` with the MCP flow silently abandoned and **no code issued**. With the UI at the root, `example.com/mcp` needs **no** `AP_MCP_URL` at all: discovery advertises `resource: example.com/mcp` against root-anchored `.well-known`, and the full round trip (IdP credential form → `/acs` → `/authenticate` → consent → code → token → `tools/list`) completes. The operator only has to forward the root-mounted protocol paths with `strip_path: false`.
- **A dedicated MCP host splits the flow between two parties, and only one of them needs the public internet.** The MCP *client* talks only to `AP_MCP_URL`; the *browser* is sent to `AP_FRONTEND_URL` for consent and sign-in, and the authorization code returns to the client's own `redirect_uri`, never to the MCP host. So an internal-only main host is a supported shape — a VPN user authorizes, and the cloud client then works from anywhere — and the corollary is that nobody outside that boundary can authorize at all. It also means SSO needs no second ACS URL: the browser always signs in on the main host, same origin as the configured ACS, so the `sessionStorage` continuation in [[ee-authentication-sso-rbac]] survives. Bouncing consent to the MCP host instead would break both properties.
- **On a dedicated MCP host, match `/mcp` exactly — a prefix rule also matches `/mcp-authorize`.** Kong's `paths: [/mcp]` (and any prefix-matching proxy rule) routes `/mcp-authorize` to the app too, so the MCP host serves the consent SPA shell — which cannot work there, because the whole point of the separate host is that it exposes no `/api` and no `/assets`. The operator sees a blank or broken consent page instead of a clean 404 telling them their rule is too broad. Route `/mcp` and `/mcp/platform` as exact matches alongside `/.well-known/oauth-*`, `/.well-known/openid-configuration`, `/.well-known/jwks.json`, `/authorize`, `/token`, `/register`, `/revoke`, `/userinfo`.
-- **MCP access tokens are not bound to a host.** They carry `audience: JwtAudience.MCP_OAUTH_ACCESS` and no issuer or host claim, and while the OAuth `resource` parameter is accepted and recorded it is never enforced as an audience; DCR redirect URIs are ephemeral loopback, so they are host-independent too. Serving MCP on two hostnames at once is therefore safe — a client works against whichever URL it discovered — but a token minted on one is equally valid on the other. A separate MCP hostname is a traffic and WAF boundary, never a token boundary; do not describe it to an operator as isolation.
+- **A grant ends when its user or project goes away.** Deactivating, deleting or removing a user from the platform, deleting a project, and removing a project member (also through SCIM) revoke the matching grants through `mcpGrantRevocation`, and every MCP call and refresh re-checks that the user is active and the project exists. Revocation is permanent: a reactivated user signs in again. Deleting a project role cascades its members away without revoking their grants; the per-call role check still denies their tools.
+- **MCP access tokens are not bound to a host.** They carry `audience: JwtAudience.MCP_OAUTH_ACCESS` and no issuer or host claim, and the OAuth `resource` parameter only decides project versus platform at approve, never an audience; DCR redirect URIs are ephemeral loopback, so they are host-independent too. Serving MCP on two hostnames at once is therefore safe — a client works against whichever URL it discovered — but a token minted on one is equally valid on the other. A separate MCP hostname is a traffic and WAF boundary, never a token boundary; do not describe it to an operator as isolation.
- **DCR must issue a client secret when `token_endpoint_auth_method` is omitted.** RFC 7591 §2 says an omitted value defaults to `client_secret_basic`, *not* `none`, and [Microsoft Copilot Studio](https://learn.microsoft.com/en-us/microsoft-365/copilot/extensibility/plugin-authentication-dynamic-client-registration) refuses DCR outright without one ("DCR without a client secret isn't supported yet"). Defaulting an omitted method to `none` looks like it fixes the "public client handed a secret" contradiction, but it resolves it the wrong way: it breaks Copilot and makes `client_secret_basic` support unreachable for every client that omits the field. Resolve it the other way — default to `client_secret_basic` and keep issuing the secret.
- `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`.
diff --git a/packages/server/api/src/app/authentication/lib/access-token-manager.ts b/packages/server/api/src/app/authentication/lib/access-token-manager.ts
index b889e41998f..7b965b95e27 100644
--- a/packages/server/api/src/app/authentication/lib/access-token-manager.ts
+++ b/packages/server/api/src/app/authentication/lib/access-token-manager.ts
@@ -1,5 +1,5 @@
import { ActivepiecesError, apId, ErrorCode, PlatformId, ProjectId } from '@activepieces/core-utils'
-import { ALL_PRINCIPAL_TYPES, EnginePrincipal, Principal, PrincipalType, UserStatus, WorkerPrincipal } from '@activepieces/shared'
+import { ALL_PRINCIPAL_TYPES, EnginePrincipal, Principal, PrincipalType, WorkerPrincipal } from '@activepieces/shared'
import dayjs from 'dayjs'
import { FastifyBaseLogger } from 'fastify'
import { jwtUtils } from '../../helper/jwt-utils'
@@ -107,7 +107,7 @@ async function assertUserSession(log: FastifyBaseLogger, decoded: Principal | Pr
const user = await userService(log).getOneOrFail({ id: decoded.id })
const identity = await userIdentityService(log).getOneOrFail({ id: user.identityId })
const isExpired = (identity.tokenVersion ?? null) !== (decoded.tokenVersion ?? null)
- if (isExpired || user.status === UserStatus.INACTIVE || !identity.verified) {
+ if (isExpired || !userService(log).isActive({ user, identity })) {
throw new ActivepiecesError({
code: ErrorCode.SESSION_EXPIRED,
params: {
diff --git a/packages/server/api/src/app/ee/projects/platform-project-service.ts b/packages/server/api/src/app/ee/projects/platform-project-service.ts
index fd4470fcb13..31d23e4b8c6 100644
--- a/packages/server/api/src/app/ee/projects/platform-project-service.ts
+++ b/packages/server/api/src/app/ee/projects/platform-project-service.ts
@@ -12,6 +12,7 @@ import { paginationHelper } from '../../helper/pagination/pagination-utils'
import { Order } from '../../helper/pagination/paginator'
import { SystemJobName } from '../../helper/system-jobs/common'
import { systemJobsSchedule } from '../../helper/system-jobs/system-job'
+import { mcpGrantRevocation } from '../../mcp/oauth/token/mcp-grant-revocation'
import { platformService } from '../../platform/platform.service'
import { ProjectEntity } from '../../project/project-entity'
import { applyProjectsAccessFilters, projectService } from '../../project/project-service'
@@ -219,6 +220,7 @@ export const platformProjectService = (log: FastifyBaseLogger) => ({
await projectRepo(entityManager).softDelete({ id: personalProject.id, platformId })
})
await scheduleHardDeleteProjectJob({ id: personalProject.id, platformId, log })
+ await mcpGrantRevocation.revokeActiveGrants({ scope: { projectId: personalProject.id, platformId }, log })
},
async markForDeletion({ id, platformId, enforceDefaultGuard = false }: DeleteProjectParams): Promise<void> {
@@ -249,6 +251,7 @@ export const platformProjectService = (log: FastifyBaseLogger) => ({
})
}
await scheduleHardDeleteProjectJob({ id, platformId, log })
+ await mcpGrantRevocation.revokeActiveGrants({ scope: { projectId: id, platformId }, log })
},
})
diff --git a/packages/server/api/src/app/ee/projects/project-members/project-member.service.ts b/packages/server/api/src/app/ee/projects/project-members/project-member.service.ts
index 29c992702b4..70f0cb6ddda 100644
--- a/packages/server/api/src/app/ee/projects/project-members/project-member.service.ts
+++ b/packages/server/api/src/app/ee/projects/project-members/project-member.service.ts
@@ -1,4 +1,4 @@
-import { ActivepiecesError, ApId, apId, chunk, Cursor, ErrorCode, isNil, Permission, PlatformId, ProjectId, ProjectRole, SeekPage, UserId } from '@activepieces/core-utils'
+import { ActivepiecesError, ApId, apId, chunk, Cursor, ErrorCode, isNil, Permission, PlatformId, ProjectId, ProjectRole, SeekPage, tryCatch, UserId } from '@activepieces/core-utils'
import { ApEdition, DefaultProjectRole, PlatformRole, ProjectMember, ProjectMemberId, ProjectMemberWithUser, ProjectType, UserStatus } from '@activepieces/shared'
import dayjs from 'dayjs'
import { FastifyBaseLogger } from 'fastify'
@@ -8,6 +8,7 @@ import { distributedLock } from '../../../database/redis-connections'
import { buildPaginator } from '../../../helper/pagination/build-paginator'
import { paginationHelper } from '../../../helper/pagination/pagination-utils'
import { system } from '../../../helper/system/system'
+import { mcpGrantRevocation } from '../../../mcp/oauth/token/mcp-grant-revocation'
import { projectRepo } from '../../../project/project-repo'
import { projectService } from '../../../project/project-service'
import { UserSchema } from '../../../user/user-entity'
@@ -244,7 +245,7 @@ export const projectMemberService = (log: FastifyBaseLogger) => ({
if (enforceLastProjectGuard) {
await assertMemberKeepsAProject({ member: currentMember, log })
}
- await repo().delete({ projectId, id: memberId })
+ await this.delete(projectId, memberId)
},
})
},
@@ -252,7 +253,15 @@ export const projectMemberService = (log: FastifyBaseLogger) => ({
projectId: ProjectId,
invitationId: ProjectMemberId,
): Promise<void> {
+ const member = await repo().findOneBy({ projectId, id: invitationId })
await repo().delete({ projectId, id: invitationId })
+ if (isNil(member)) {
+ return
+ }
+ const { data: role } = await tryCatch(() => this.getRole({ userId: member.userId, projectId }))
+ if (isNil(role)) {
+ await mcpGrantRevocation.revokeActiveGrants({ scope: { userId: member.userId, projectId, platformId: member.platformId }, log })
+ }
},
async countTotalUsersByProjects(projectIds: ProjectId[]): Promise<Map<ProjectId, number>> {
if (projectIds.length === 0) return new Map()
diff --git a/packages/server/api/src/app/ee/scim/scim-group-service.ts b/packages/server/api/src/app/ee/scim/scim-group-service.ts
index 553902fadb5..ce61427bcf4 100644
--- a/packages/server/api/src/app/ee/scim/scim-group-service.ts
+++ b/packages/server/api/src/app/ee/scim/scim-group-service.ts
@@ -218,6 +218,7 @@ export const scimGroupService = (log: FastifyBaseLogger) => ({
userId,
projectId,
platformId,
+ log,
})
}
}
@@ -304,8 +305,9 @@ async function removeMemberFromProject(params: {
userId: string
projectId: string
platformId: string
+ log: FastifyBaseLogger
}): Promise<void> {
- const { userId, projectId, platformId } = params
+ const { userId, projectId, platformId, log } = params
const member = await projectMemberRepo().findOneBy({
userId,
@@ -314,7 +316,7 @@ async function removeMemberFromProject(params: {
})
if (!isNil(member)) {
- await projectMemberRepo().delete({ id: member.id })
+ await projectMemberService(log).delete(projectId, member.id)
}
}
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 668ccf44a63..0c86e136d5a 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
@@ -31,6 +31,9 @@ export const mcpOAuthApproveController: FastifyPluginAsyncZod = async (app) => {
if (error) {
return reply.status(400).send({ error: 'invalid_request', error_description: 'Invalid or expired authorization request' })
}
+ if (isNil(projectId) !== isPlatformResource(authRequest.resource)) {
+ return reply.status(400).send({ error: 'invalid_request', error_description: 'Project access needs a projectId and platform access must not have one' })
+ }
const code = await mcpOAuthCodeService.create({
clientId: authRequest.clientId,
@@ -83,6 +86,10 @@ async function verifyAuthRequest(authRequestId: string): Promise<AuthRequestPayl
return authRequest
}
+function isPlatformResource(resource: string | null): boolean {
+ return resource?.replace(/\/+$/, '').endsWith('/mcp/platform') ?? false
+}
+
const ApproveRequest = {
config: {
security: securityAccess.publicPlatform([PrincipalType.USER]),
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 60d14fd6ba5..3ce910f52b5 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
@@ -11,6 +11,7 @@ import { CONVERSATION_ID_HEADER } from '../../ee/agent/mcp/agent-mcp'
import { domainHelper } from '../../helper/domain-helper'
import { rejectedPromiseHandler } from '../../helper/promise-handler'
import { telemetry, telemetryDedupe } from '../../helper/telemetry.utils'
+import { projectRepo } from '../../project/project-repo'
import { mcpServerService } from '../mcp-service'
import { INTERNAL_CHAT_CLIENT_ID, mcpOAuthTokenService } from './token/mcp-oauth-token.service'
@@ -157,6 +158,9 @@ async function resolveMcpAndUser({ identity, log }: { identity: ResolvedIdentity
const mcp = await mcpServerService(log).getPopulatedByPlatformId(identity.platformId)
return { mcp, userId: identity.userId, platformId: identity.platformId }
}
+ if (!(await projectRepo().existsBy({ id: identity.projectId, platformId: identity.platformId }))) {
+ return { mcp: null }
+ }
if (telemetryDedupe.onceToday(`mcp-server-connected:project:${identity.projectId}:${identity.userId}`)) {
rejectedPromiseHandler(telemetry(log).trackProject({
projectId: identity.projectId,
diff --git a/packages/server/api/src/app/mcp/oauth/token/mcp-grant-revocation.ts b/packages/server/api/src/app/mcp/oauth/token/mcp-grant-revocation.ts
new file mode 100644
index 00000000000..05878418692
--- /dev/null
+++ b/packages/server/api/src/app/mcp/oauth/token/mcp-grant-revocation.ts
@@ -0,0 +1,49 @@
+import { isNil, tryCatch } from '@activepieces/core-utils'
+import { FastifyBaseLogger } from 'fastify'
+import { In, MoreThan } from 'typeorm'
+import { repoFactory } from '../../../core/db/repo-factory'
+import { transaction } from '../../../core/db/transaction'
+import { McpOAuthAuthorizationCodeEntity } from '../code/mcp-oauth-code.entity'
+import { mcpOAuthRevocationList } from './mcp-oauth-revocation-list'
+import { McpOAuthTokenEntity } from './mcp-oauth-token.entity'
+
+const repo = repoFactory(McpOAuthTokenEntity)
+const codeRepo = repoFactory(McpOAuthAuthorizationCodeEntity)
+
+export const mcpGrantRevocation = {
+ async revokeGrantIds({ grantIds }: RevokeGrantIdsParams): Promise<void> {
+ if (grantIds.length === 0) {
+ return
+ }
+ await repo().update({ id: In(grantIds) }, { revoked: true })
+ await mcpOAuthRevocationList.revoke({ grantIds })
+ },
+ async revokeActiveGrants({ scope, log }: RevokeActiveGrantsParams): Promise<void> {
+ const { error } = await tryCatch(async () => {
+ const grantIds = await transaction(async (entityManager) => {
+ await codeRepo(entityManager).update({ ...scope, used: false, expiresAt: MoreThan(new Date().toISOString()) }, { used: true })
+ const grants = await repo(entityManager).find({ where: { ...scope, revoked: false }, select: { id: true } })
+ const ids = grants.map((grant) => grant.id)
+ if (ids.length > 0) {
+ await repo(entityManager).update({ id: In(ids) }, { revoked: true })
+ }
+ return ids
+ })
+ if (grantIds.length > 0) {
+ await mcpOAuthRevocationList.revoke({ grantIds })
+ }
+ })
+ if (!isNil(error)) {
+ log.error({ error, platform: { id: scope.platformId } }, 'Could not revoke MCP grants')
+ }
+ },
+}
+
+type RevokeGrantIdsParams = {
+ grantIds: string[]
+}
+
+type RevokeActiveGrantsParams = {
+ scope: { platformId: string } & ({ userId: string } | { projectId: string })
+ log: FastifyBaseLogger
+}
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 f605c54e232..50210fba321 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,6 +1,6 @@
import { isNil, spreadIfDefined } from '@activepieces/core-utils'
import { McpOAuthClient } from '@activepieces/shared'
-import { FastifyReply } from 'fastify'
+import { FastifyBaseLogger, FastifyReply } from 'fastify'
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { z } from 'zod'
import { securityAccess } from '../../../core/security/authorization/fastify-security'
@@ -24,7 +24,7 @@ export const mcpOAuthTokenController: FastifyPluginAsyncZod = async (app) => {
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 })
+ return await handleRefreshToken({ authorizationHeader, body: req.body, reply, log: req.log })
}
return await reply.status(400).send({ error: 'unsupported_grant_type' })
}
@@ -98,7 +98,7 @@ async function handleAuthorizationCode({ authorizationHeader, body, reply, issue
await reply.status(200).send({ ...tokens, ...spreadIfDefined('id_token', idToken) })
}
-async function handleRefreshToken({ authorizationHeader, body, reply }: HandlerParams): Promise<void> {
+async function handleRefreshToken({ authorizationHeader, body, reply, log }: RefreshTokenParams): Promise<void> {
const { refresh_token } = body
if (!refresh_token) {
await reply.status(400).send({ error: 'invalid_request', error_description: 'Missing refresh_token' })
@@ -112,6 +112,7 @@ async function handleRefreshToken({ authorizationHeader, body, reply }: HandlerP
redirectUris: client.redirectUris,
refreshToken: refresh_token,
clientId: client.clientId,
+ log,
})
await reply.status(200).send(tokens)
@@ -123,6 +124,10 @@ type HandlerParams = {
reply: FastifyReply
}
+type RefreshTokenParams = HandlerParams & {
+ log: FastifyBaseLogger
+}
+
type AuthorizationCodeParams = HandlerParams & {
issuer: string
}
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 b9843d7d32f..4f5b3366add 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
@@ -8,11 +8,14 @@ import { repoFactory } from '../../../core/db/repo-factory'
import { JwtAudience, jwtUtils } from '../../../helper/jwt-utils'
import { buildPaginator } from '../../../helper/pagination/build-paginator'
import { paginationHelper } from '../../../helper/pagination/pagination-utils'
+import { projectRepo } from '../../../project/project-repo'
+import { userService } from '../../../user/user-service'
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 { mcpGrantRevocation } from './mcp-grant-revocation'
import { mcpOAuthRevocationList } from './mcp-oauth-revocation-list'
import { MCP_CHAT_TURN_ACCESS_TOKEN_TTL_SECONDS, MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS, MCP_OAUTH_REFRESH_TOKEN_TTL_MS } from './mcp-oauth-token-lifetimes'
import { McpOAuthTokenEntity } from './mcp-oauth-token.entity'
@@ -57,6 +60,9 @@ export const mcpOAuthTokenService = {
if (!valid) {
throw new OAuthTokenError('invalid_grant', 'PKCE verification failed')
}
+ if (!isNil(params.projectId) && !(await projectRepo().existsBy({ id: params.projectId, platformId: params.platformId }))) {
+ throw new OAuthTokenError('invalid_grant', 'The project of this authorization code no longer exists')
+ }
const rawRefreshToken = generateRefreshToken()
const hashedRefreshToken = hashRefreshToken(rawRefreshToken)
@@ -107,6 +113,10 @@ export const mcpOAuthTokenService = {
if (record.clientId !== params.clientId) {
throw new OAuthTokenError('invalid_grant', 'Client mismatch')
}
+ const userActive = await userService(params.log).isActiveOnPlatform({ id: record.userId, platformId: record.platformId })
+ if (!userActive || (!isNil(record.projectId) && !(await projectRepo().existsBy({ id: record.projectId, platformId: record.platformId })))) {
+ throw new OAuthTokenError('invalid_grant', 'Invalid or expired refresh token')
+ }
const clientKey = record.clientKey ?? mcpOAuthClientIdentity.detectClientKey({ redirectUris: params.redirectUris })
await repo().update({ id: record.id }, {
@@ -150,6 +160,14 @@ export const mcpOAuthTokenService = {
return { status: 'invalid' }
}
}
+ const { data: userActive, error: userError } = await tryCatch(() => userService(log).isActiveOnPlatform({ id: payload.sub, platformId: payload.platformId }))
+ if (userError) {
+ log.error({ error: userError }, 'Could not check the MCP OAuth token user')
+ return { status: 'unavailable' }
+ }
+ if (!userActive) {
+ return { status: 'invalid' }
+ }
return { status: 'ok', payload }
},
@@ -171,8 +189,7 @@ export const mcpOAuthTokenService = {
if (isNil(record)) {
return
}
- await repo().update({ id: record.id }, { revoked: true })
- await mcpOAuthRevocationList.revoke({ grantIds: [record.id] })
+ await mcpGrantRevocation.revokeGrantIds({ grantIds: [record.id] })
},
async listGrants({ platformId, userId, projectIds, memberIds, clientKeys, cursor, limit }: ListGrantsParams): Promise<SeekPage<McpOAuthGrant>> {
@@ -226,9 +243,7 @@ export const mcpOAuthTokenService = {
params: { message: 'One or more grants do not exist or are not yours to revoke' },
})
}
- const grantIds = matched.map((token) => token.id)
- await repo().update({ id: In(grantIds) }, { revoked: true })
- await mcpOAuthRevocationList.revoke({ grantIds })
+ await mcpGrantRevocation.revokeGrantIds({ grantIds: matched.map((token) => token.id) })
},
async issueInternalAccessToken(params: InternalTokenParams): Promise<string> {
@@ -330,6 +345,7 @@ type RefreshParams = {
redirectUris: string[]
refreshToken: string
clientId: string
+ log: FastifyBaseLogger
}
type TokenResponse = {
diff --git a/packages/server/api/src/app/user/user-service.ts b/packages/server/api/src/app/user/user-service.ts
index c6209344e21..54ae2c4a3d4 100644
--- a/packages/server/api/src/app/user/user-service.ts
+++ b/packages/server/api/src/app/user/user-service.ts
@@ -13,6 +13,7 @@ import { projectMemberRepo } from '../ee/projects/project-role/project-role.serv
import { buildPaginator } from '../helper/pagination/build-paginator'
import { paginationHelper } from '../helper/pagination/pagination-utils'
import { system } from '../helper/system/system'
+import { mcpGrantRevocation } from '../mcp/oauth/token/mcp-grant-revocation'
import { platformService } from '../platform/platform.service'
import { projectService } from '../project/project-service'
import { UserEntity, UserSchema } from './user-entity'
@@ -123,6 +124,9 @@ export const userService = (log: FastifyBaseLogger) => ({
else {
await applyUpdate()
}
+ if (status === UserStatus.INACTIVE) {
+ await mcpGrantRevocation.revokeActiveGrants({ scope: { userId: id, platformId }, log })
+ }
return this.getMetaInformation({ id })
},
@@ -208,6 +212,7 @@ export const userService = (log: FastifyBaseLogger) => ({
})
await deleteIdentityIfOrphaned({ identityId: user.identityId, entityManager })
})
+ await mcpGrantRevocation.revokeActiveGrants({ scope: { userId: id, platformId }, log })
},
async removeFromPlatform({ id, platformId }: DeleteParams): Promise<void> {
await assertNotPlatformOwner({ id, platformId, log })
@@ -231,6 +236,7 @@ export const userService = (log: FastifyBaseLogger) => ({
}, {
lastLoggedInPlatformId: null,
})
+ await mcpGrantRevocation.revokeActiveGrants({ scope: { userId: id, platformId }, log })
},
async getByPlatformRole(id: PlatformId, role: PlatformRole): Promise<UserSchema[]> {
@@ -280,6 +286,20 @@ export const userService = (log: FastifyBaseLogger) => ({
})
},
+ isActive({ user, identity }: IsActiveParams): boolean {
+ return user.status === UserStatus.ACTIVE && identity.verified
+ },
+ async isActiveOnPlatform({ id, platformId }: GetOneByIdAndPlatformIdParams): Promise<boolean> {
+ const user = await userRepo().findOne({
+ where: { id, platformId },
+ relations: { identity: true },
+ select: { id: true, status: true, identity: { id: true, verified: true } },
+ })
+ if (isNil(user)) {
+ return false
+ }
+ return this.isActive({ user, identity: user.identity })
+ },
isUserPrivileged(user: User): boolean {
return user.platformRole === PlatformRole.ADMIN || user.platformRole === PlatformRole.OPERATOR
},
@@ -421,6 +441,11 @@ type GetOrCreateWithProjectParams = {
platformRole?: PlatformRole
}
+type IsActiveParams = {
+ user: Pick<User, 'status'>
+ identity: Pick<UserIdentity, 'verified'>
+}
+
type GetOrCreateWithProjectResult = {
user: User
created: boolean
diff --git a/packages/server/api/test/helpers/mcp-oauth.ts b/packages/server/api/test/helpers/mcp-oauth.ts
index fd3c7922413..de24e638afc 100644
--- a/packages/server/api/test/helpers/mcp-oauth.ts
+++ b/packages/server/api/test/helpers/mcp-oauth.ts
@@ -1,7 +1,11 @@
import { createHash, randomBytes } from 'node:crypto'
-import { apId } from '@activepieces/core-utils'
-import { FastifyInstance } from 'fastify'
+import { spreadIfDefined } from '@activepieces/core-utils'
+import { McpOAuthToken } from '@activepieces/shared'
+import { FastifyInstance, LightMyRequestResponse } from 'fastify'
+import { mcpOAuthClientService } from '../../src/app/mcp/oauth/client/mcp-oauth-client.service'
import { mcpOAuthCodeService } from '../../src/app/mcp/oauth/code/mcp-oauth-code.service'
+import { mcpOAuthTokenService } from '../../src/app/mcp/oauth/token/mcp-oauth-token.service'
+import { db } from './db'
function generatePkce(): PkcePair {
const verifier = randomBytes(32).toString('base64url')
@@ -17,12 +21,12 @@ async function registerClient({ app, tokenEndpointAuthMethod, redirectUris = [MC
return res.json()
}
-async function issueCode({ clientId, codeChallenge, redirectUri = MCP_OAUTH_REDIRECT_URI }: IssueCodeParams): Promise<string> {
+async function issueCode({ clientId, codeChallenge, redirectUri = MCP_OAUTH_REDIRECT_URI, userId, projectId, platformId }: IssueCodeParams): Promise<string> {
return mcpOAuthCodeService.create({
clientId,
- userId: apId(),
- projectId: apId(),
- platformId: apId(),
+ userId,
+ projectId,
+ platformId,
redirectUri,
codeChallenge,
codeChallengeMethod: 'S256',
@@ -30,6 +34,62 @@ async function issueCode({ clientId, codeChallenge, redirectUri = MCP_OAUTH_REDI
})
}
+async function exchangeGrant({ userId, projectId, platformId }: McpGrantee): Promise<ExchangedGrant> {
+ const { client_id: clientId } = await mcpOAuthClientService.register({ redirectUris: [MCP_OAUTH_REDIRECT_URI], tokenEndpointAuthMethod: 'none' })
+ const { verifier, challenge } = generatePkce()
+ const tokens = await mcpOAuthTokenService.exchangeCode({
+ redirectUris: [MCP_OAUTH_REDIRECT_URI],
+ codeVerifier: verifier,
+ codeChallenge: challenge,
+ codeChallengeMethod: 'S256',
+ clientId,
+ userId,
+ projectId,
+ platformId,
+ scopes: ['mcp'],
+ })
+ const grant = await db.findOneBy<McpOAuthToken>('mcp_oauth_token', { clientId })
+ if (grant === null || tokens.refresh_token === undefined) {
+ throw new Error('expected exchangeCode to persist a grant and return a refresh token')
+ }
+ return { grantId: grant.id, clientId, accessToken: tokens.access_token, refreshToken: tokens.refresh_token }
+}
+
+async function authorize({ app, resource, redirectUri = MCP_OAUTH_REDIRECT_URI, redirectUris = [redirectUri] }: AuthorizeParams): Promise<string> {
+ const client = await registerClient({ app, tokenEndpointAuthMethod: 'none', redirectUris })
+ const { challenge } = generatePkce()
+ const res = await app.inject({
+ method: 'GET',
+ url: '/authorize?' + new URLSearchParams({
+ client_id: client.client_id,
+ redirect_uri: redirectUri,
+ response_type: 'code',
+ code_challenge: challenge,
+ code_challenge_method: 'S256',
+ ...spreadIfDefined('resource', resource),
+ }).toString(),
+ })
+ return new URL(String(res.headers.location), redirectUri).searchParams.get('authRequestId') ?? ''
+}
+
+function callMcp({ app, accessToken }: { app: FastifyInstance, 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: {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'mcp-test', version: '1.0.0' } },
+ },
+ })
+}
+
function basicHeader({ clientId, clientSecret }: { clientId: string, clientSecret: string }): string {
return 'Basic ' + Buffer.from(`${clientId}:${clientSecret}`).toString('base64')
}
@@ -38,11 +98,20 @@ export const mcpOAuthTestHelpers = {
generatePkce,
registerClient,
issueCode,
+ exchangeGrant,
+ authorize,
+ callMcp,
basicHeader,
}
export const MCP_OAUTH_REDIRECT_URI = 'https://example.com/oauth/callback'
+export type McpGrantee = {
+ userId: string
+ projectId: string | null
+ platformId: string
+}
+
export type RegisteredClient = {
client_id: string
client_secret?: string
@@ -60,7 +129,21 @@ type RegisterClientParams = {
redirectUris?: string[]
}
-type IssueCodeParams = {
+type ExchangedGrant = {
+ grantId: string
+ clientId: string
+ accessToken: string
+ refreshToken: string
+}
+
+type AuthorizeParams = {
+ app: FastifyInstance
+ resource?: string
+ redirectUri?: string
+ redirectUris?: string[]
+}
+
+type IssueCodeParams = McpGrantee & {
clientId: string
codeChallenge: string
redirectUri?: string
diff --git a/packages/server/api/test/integration/ce/mcp/mcp-oauth-chatgpt-conformance.test.ts b/packages/server/api/test/integration/ce/mcp/mcp-oauth-chatgpt-conformance.test.ts
index bd16850f880..f13ec99d77d 100644
--- a/packages/server/api/test/integration/ce/mcp/mcp-oauth-chatgpt-conformance.test.ts
+++ b/packages/server/api/test/integration/ce/mcp/mcp-oauth-chatgpt-conformance.test.ts
@@ -40,7 +40,6 @@ async function consentThenApprove({ state }: { state: string }): Promise<URL> {
const approved = await ctx.post('/v1/mcp-oauth/approve', {
authRequestId: authRequestIdFrom(String(consent.headers.location)),
- projectId: ctx.project.id,
})
expect(approved.statusCode).toBe(200)
diff --git a/packages/server/api/test/integration/ce/mcp/mcp-oauth-client-auth.test.ts b/packages/server/api/test/integration/ce/mcp/mcp-oauth-client-auth.test.ts
index 5af659d2ab2..f6d1304dc39 100644
--- a/packages/server/api/test/integration/ce/mcp/mcp-oauth-client-auth.test.ts
+++ b/packages/server/api/test/integration/ce/mcp/mcp-oauth-client-auth.test.ts
@@ -2,10 +2,12 @@ import { FastifyInstance } from 'fastify'
import { beforeAll, describe, expect, it } from 'vitest'
import { databaseConnection } from '../../../../src/app/database/database-connection'
import { mcpOAuthClientService } from '../../../../src/app/mcp/oauth/client/mcp-oauth-client.service'
-import { MCP_OAUTH_REDIRECT_URI, mcpOAuthTestHelpers, RegisteredClient } from '../../../helpers/mcp-oauth'
+import { MCP_OAUTH_REDIRECT_URI, McpGrantee, mcpOAuthTestHelpers, RegisteredClient } from '../../../helpers/mcp-oauth'
+import { createTestContext } from '../../../helpers/test-context'
import { setupTestEnvironment } from '../../../helpers/test-setup'
let app: FastifyInstance
+let grantee: McpGrantee
async function registerClient(tokenEndpointAuthMethod?: string): Promise<RegisteredClient> {
return mcpOAuthTestHelpers.registerClient({ app, tokenEndpointAuthMethod })
@@ -17,7 +19,7 @@ async function exchange({ client, headers, body }: {
body?: Record<string, string>
}): Promise<ReturnType<FastifyInstance['inject']>> {
const { verifier, challenge } = mcpOAuthTestHelpers.generatePkce()
- const code = await mcpOAuthTestHelpers.issueCode({ clientId: client.client_id, codeChallenge: challenge })
+ const code = await mcpOAuthTestHelpers.issueCode({ clientId: client.client_id, codeChallenge: challenge, ...grantee })
return app.inject({
method: 'POST',
url: '/token',
@@ -35,6 +37,8 @@ async function exchange({ client, headers, body }: {
describe('MCP OAuth client authentication', () => {
beforeAll(async () => {
app = await setupTestEnvironment({ fresh: true })
+ const ctx = await createTestContext(app)
+ grantee = { userId: ctx.user.id, projectId: ctx.project.id, platformId: ctx.platform.id }
})
describe('dynamic client registration', () => {
@@ -463,7 +467,7 @@ describe('MCP OAuth client authentication', () => {
const owner = await registerClient('none')
const attacker = await registerClient('none')
const { verifier, challenge } = mcpOAuthTestHelpers.generatePkce()
- const code = await mcpOAuthTestHelpers.issueCode({ clientId: owner.client_id, codeChallenge: challenge })
+ const code = await mcpOAuthTestHelpers.issueCode({ clientId: owner.client_id, codeChallenge: challenge, ...grantee })
const issued = await app.inject({
method: 'POST',
url: '/token',
diff --git a/packages/server/api/test/integration/ce/mcp/mcp-oauth-client-profiles.test.ts b/packages/server/api/test/integration/ce/mcp/mcp-oauth-client-profiles.test.ts
index 59867809931..40d80e6aa17 100644
--- a/packages/server/api/test/integration/ce/mcp/mcp-oauth-client-profiles.test.ts
+++ b/packages/server/api/test/integration/ce/mcp/mcp-oauth-client-profiles.test.ts
@@ -2,10 +2,12 @@ import { FastifyInstance } from 'fastify'
import { beforeAll, describe, expect, it } from 'vitest'
import { databaseConnection } from '../../../../src/app/database/database-connection'
import { mcpOAuthClientService } from '../../../../src/app/mcp/oauth/client/mcp-oauth-client.service'
-import { MCP_OAUTH_REDIRECT_URI, mcpOAuthTestHelpers } from '../../../helpers/mcp-oauth'
+import { MCP_OAUTH_REDIRECT_URI, McpGrantee, mcpOAuthTestHelpers } from '../../../helpers/mcp-oauth'
+import { createTestContext } from '../../../helpers/test-context'
import { setupTestEnvironment } from '../../../helpers/test-setup'
let app: FastifyInstance
+let grantee: McpGrantee
async function redeemCode({ clientId, headers, body }: {
clientId: string
@@ -13,7 +15,7 @@ async function redeemCode({ clientId, headers, body }: {
body?: Record<string, string>
}): Promise<{ statusCode: number, json: () => Record<string, string> }> {
const { verifier, challenge } = mcpOAuthTestHelpers.generatePkce()
- const code = await mcpOAuthTestHelpers.issueCode({ clientId, codeChallenge: challenge })
+ const code = await mcpOAuthTestHelpers.issueCode({ clientId, codeChallenge: challenge, ...grantee })
return app.inject({
method: 'POST',
url: '/token',
@@ -44,6 +46,8 @@ function renew({ refreshToken, headers, body }: {
describe('MCP OAuth client profiles', () => {
beforeAll(async () => {
app = await setupTestEnvironment({ fresh: true })
+ const ctx = await createTestContext(app)
+ grantee = { userId: ctx.user.id, projectId: ctx.project.id, platformId: ctx.platform.id }
})
it('a client that omits the auth method and uses the Authorization header connects and renews', async () => {
diff --git a/packages/server/api/test/integration/ce/mcp/mcp-oauth-code.test.ts b/packages/server/api/test/integration/ce/mcp/mcp-oauth-code.test.ts
index f71370dc71d..36357f68d51 100644
--- a/packages/server/api/test/integration/ce/mcp/mcp-oauth-code.test.ts
+++ b/packages/server/api/test/integration/ce/mcp/mcp-oauth-code.test.ts
@@ -2,10 +2,12 @@ import { randomBytes } from 'node:crypto'
import { FastifyInstance } from 'fastify'
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 { MCP_OAUTH_REDIRECT_URI, McpGrantee, mcpOAuthTestHelpers } from '../../../helpers/mcp-oauth'
+import { createTestContext } from '../../../helpers/test-context'
import { setupTestEnvironment } from '../../../helpers/test-setup'
let app: FastifyInstance
+let grantee: McpGrantee
const OTHER_REDIRECT_URI = 'https://example.com/other/callback'
@@ -37,12 +39,14 @@ function redeem({ clientId, code, verifier, redirectUri = MCP_OAUTH_REDIRECT_URI
describe('MCP OAuth authorization code redemption', () => {
beforeAll(async () => {
app = await setupTestEnvironment({ fresh: true })
+ const ctx = await createTestContext(app)
+ grantee = { userId: ctx.user.id, projectId: ctx.project.id, platformId: ctx.platform.id }
})
it('redeems a code exactly once', async () => {
const clientId = await registerPublicClient()
const { verifier, challenge } = mcpOAuthTestHelpers.generatePkce()
- const code = await mcpOAuthTestHelpers.issueCode({ clientId, codeChallenge: challenge })
+ const code = await mcpOAuthTestHelpers.issueCode({ clientId, codeChallenge: challenge, ...grantee })
const first = await redeem({ clientId, code, verifier })
const second = await redeem({ clientId, code, verifier })
@@ -55,7 +59,7 @@ describe('MCP OAuth authorization code redemption', () => {
it('redeems a code exactly once under concurrent redemption', async () => {
const clientId = await registerPublicClient()
const { verifier, challenge } = mcpOAuthTestHelpers.generatePkce()
- const code = await mcpOAuthTestHelpers.issueCode({ clientId, codeChallenge: challenge })
+ const code = await mcpOAuthTestHelpers.issueCode({ clientId, codeChallenge: challenge, ...grantee })
const results = await Promise.all(
Array.from({ length: 4 }, () => redeem({ clientId, code, verifier })),
@@ -68,7 +72,7 @@ describe('MCP OAuth authorization code redemption', () => {
const owner = await registerPublicClient()
const attacker = await registerPublicClient()
const { verifier, challenge } = mcpOAuthTestHelpers.generatePkce()
- const code = await mcpOAuthTestHelpers.issueCode({ clientId: owner, codeChallenge: challenge })
+ const code = await mcpOAuthTestHelpers.issueCode({ clientId: owner, codeChallenge: challenge, ...grantee })
const res = await redeem({ clientId: attacker, code, verifier })
@@ -79,7 +83,7 @@ describe('MCP OAuth authorization code redemption', () => {
it('refuses a code presented with a different redirect_uri', async () => {
const clientId = await registerPublicClient([MCP_OAUTH_REDIRECT_URI, OTHER_REDIRECT_URI])
const { verifier, challenge } = mcpOAuthTestHelpers.generatePkce()
- const code = await mcpOAuthTestHelpers.issueCode({ clientId, codeChallenge: challenge })
+ const code = await mcpOAuthTestHelpers.issueCode({ clientId, codeChallenge: challenge, ...grantee })
const res = await redeem({ clientId, code, verifier, redirectUri: OTHER_REDIRECT_URI })
@@ -90,7 +94,7 @@ describe('MCP OAuth authorization code redemption', () => {
it('refuses an expired code', async () => {
const clientId = await registerPublicClient()
const { verifier, challenge } = mcpOAuthTestHelpers.generatePkce()
- const code = await mcpOAuthTestHelpers.issueCode({ clientId, codeChallenge: challenge })
+ const code = await mcpOAuthTestHelpers.issueCode({ clientId, codeChallenge: challenge, ...grantee })
await databaseConnection().query(
'UPDATE mcp_oauth_authorization_code SET "expiresAt" = NOW() - INTERVAL \'1 hour\' WHERE "code" = $1',
[code],
@@ -105,7 +109,7 @@ describe('MCP OAuth authorization code redemption', () => {
it('refuses a code presented with the wrong PKCE verifier', async () => {
const clientId = await registerPublicClient()
const { challenge } = mcpOAuthTestHelpers.generatePkce()
- const code = await mcpOAuthTestHelpers.issueCode({ clientId, codeChallenge: challenge })
+ const code = await mcpOAuthTestHelpers.issueCode({ clientId, codeChallenge: challenge, ...grantee })
const res = await redeem({ clientId, code, verifier: randomBytes(32).toString('base64url') })
diff --git a/packages/server/api/test/integration/ce/mcp/mcp-oauth-resource.test.ts b/packages/server/api/test/integration/ce/mcp/mcp-oauth-resource.test.ts
new file mode 100644
index 00000000000..9c8c6ba1e36
--- /dev/null
+++ b/packages/server/api/test/integration/ce/mcp/mcp-oauth-resource.test.ts
@@ -0,0 +1,34 @@
+import { FastifyInstance } from 'fastify'
+import { beforeAll, describe, expect, it } from 'vitest'
+import { mcpOAuthTestHelpers } from '../../../helpers/mcp-oauth'
+import { createTestContext, TestContext } from '../../../helpers/test-context'
+import { setupTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance
+let ctx: TestContext
+
+describe('MCP OAuth approve matches the requested resource', () => {
+ beforeAll(async () => {
+ app = await setupTestEnvironment()
+ ctx = await createTestContext(app)
+ })
+
+ it.each([
+ { resource: 'http://localhost:4200/mcp/platform', withProject: false, approved: true },
+ { resource: 'http://localhost:4200/mcp/platform/', withProject: false, approved: true },
+ { resource: 'http://localhost:4200/mcp/platform', withProject: true, approved: false },
+ { resource: 'http://localhost:4200/mcp', withProject: true, approved: true },
+ { resource: 'http://localhost:4200/mcp', withProject: false, approved: false },
+ { resource: undefined, withProject: true, approved: true },
+ { resource: undefined, withProject: false, approved: false },
+ ])('resource $resource with project=$withProject is approved: $approved', async ({ resource, withProject, approved }) => {
+ const authRequestId = await mcpOAuthTestHelpers.authorize({ app, resource })
+
+ const res = await ctx.post('/v1/mcp-oauth/approve', {
+ authRequestId,
+ ...(withProject ? { projectId: ctx.project.id } : {}),
+ })
+
+ expect(res.statusCode).toBe(approved ? 200 : 400)
+ })
+})
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.ts
index 4b9a5df5836..08b76213d68 100644
--- 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.ts
@@ -1,11 +1,12 @@
-import { createHash, randomBytes } from 'crypto'
-import { DefaultProjectRole, McpOAuthToken } from '@activepieces/shared'
-import { FastifyInstance, LightMyRequestResponse } from 'fastify'
+import { DefaultProjectRole, McpOAuthToken, User, UserStatus } from '@activepieces/shared'
+import { FastifyInstance } 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 { mcpOAuthCodeService } from '../../../../src/app/mcp/oauth/code/mcp-oauth-code.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 { mcpOAuthTokenService, OAuthTokenError } from '../../../../src/app/mcp/oauth/token/mcp-oauth-token.service'
+import { userService } from '../../../../src/app/user/user-service'
import { db } from '../../../helpers/db'
+import { MCP_OAUTH_REDIRECT_URI, mcpOAuthTestHelpers } from '../../../helpers/mcp-oauth'
import { createMemberContext, createTestContext, TestContext } from '../../../helpers/test-context'
import { setupTestEnvironment } from '../../../helpers/test-setup'
@@ -14,58 +15,6 @@ 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 })
@@ -80,30 +29,30 @@ describe('MCP OAuth revocation list', () => {
})
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 connection = await mcpOAuthTestHelpers.exchangeGrant({ userId: ctx.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })
+ expect((await mcpOAuthTestHelpers.callMcp({ app, accessToken: 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)
+ const afterRevoke = await mcpOAuthTestHelpers.callMcp({ app, accessToken: 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 })
+ const mine = await mcpOAuthTestHelpers.exchangeGrant({ userId: ctx.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })
+ const theirs = await mcpOAuthTestHelpers.exchangeGrant({ 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)
+ expect((await mcpOAuthTestHelpers.callMcp({ app, accessToken: mine.accessToken })).statusCode).toBe(401)
+ expect((await mcpOAuthTestHelpers.callMcp({ app, accessToken: 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 connection = await mcpOAuthTestHelpers.exchangeGrant({ 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,
@@ -112,11 +61,11 @@ describe('MCP OAuth revocation list', () => {
await ctx.post('/v1/mcp-oauth/grants/revoke', { ids: [connection.grantId] })
- expect((await callMcp(internalToken)).statusCode).not.toBe(401)
+ expect((await mcpOAuthTestHelpers.callMcp({ app, accessToken: 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 connection = await mcpOAuthTestHelpers.exchangeGrant({ userId: ctx.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })
const revoked = await app.inject({
method: 'POST',
@@ -125,11 +74,11 @@ describe('MCP OAuth revocation list', () => {
})
expect(revoked.statusCode).toBe(200)
- expect((await callMcp(connection.accessToken)).statusCode).toBe(401)
+ expect((await mcpOAuthTestHelpers.callMcp({ app, accessToken: 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 })
+ const connection = await mcpOAuthTestHelpers.exchangeGrant({ 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] })
@@ -138,21 +87,60 @@ describe('MCP OAuth revocation list', () => {
expect(response.statusCode).toBeGreaterThanOrEqual(500)
})
+ it.each([
+ { change: 'deactivated', apply: (user: User): Promise<unknown> => db.update('user', user.id, { status: UserStatus.INACTIVE }) },
+ { change: 'removed from the platform', apply: (user: User): Promise<unknown> => db.update('user', user.id, { platformId: null }) },
+ { change: 'left with an unverified email', apply: (user: User): Promise<unknown> => db.update('user_identity', user.identityId, { verified: false }) },
+ ])('rejects the access and refresh tokens once the user is $change', async ({ apply }) => {
+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.ADMIN })
+ const connection = await mcpOAuthTestHelpers.exchangeGrant({ userId: member.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })
+
+ await apply(member.user)
+
+ expect((await mcpOAuthTestHelpers.callMcp({ app, accessToken: connection.accessToken })).statusCode).toBe(401)
+ await expect(mcpOAuthTokenService.refreshAccessToken({
+ redirectUris: [CLAUDE_REDIRECT],
+ refreshToken: connection.refreshToken,
+ clientId: connection.clientId,
+ log: app.log,
+ })).rejects.toBeInstanceOf(OAuthTokenError)
+ })
+
+ it.each([
+ { change: 'deactivated', apply: (userId: string): Promise<unknown> => userService(app.log).update({ id: userId, platformId: ctx.platform.id, status: UserStatus.INACTIVE }) },
+ { change: 'deleted', apply: (userId: string): Promise<unknown> => userService(app.log).delete({ id: userId, platformId: ctx.platform.id }) },
+ { change: 'removed from the platform', apply: (userId: string): Promise<unknown> => userService(app.log).removeFromPlatform({ id: userId, platformId: ctx.platform.id }) },
+ ])('revokes the grants of a user who is $change', async ({ apply }) => {
+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.ADMIN })
+ const connection = await mcpOAuthTestHelpers.exchangeGrant({ userId: member.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })
+
+ await apply(member.user.id)
+
+ expect((await db.findOneBy<McpOAuthToken>('mcp_oauth_token', { id: connection.grantId }))?.revoked).toBe(true)
+ expect(await mcpOAuthRevocationList.isRevoked({ grantId: connection.grantId })).toBe(true)
+ })
+
+ it('keeps the OAuth token and an unused code rejected after a deactivated user is reactivated', async () => {
+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.ADMIN })
+ const grantee = { userId: member.user.id, projectId: ctx.project.id, platformId: ctx.platform.id }
+ const { accessToken } = await mcpOAuthTestHelpers.exchangeGrant(grantee)
+ const code = await mcpOAuthTestHelpers.issueCode({ clientId: 'revocation-test-client', codeChallenge: 'challenge', ...grantee })
+
+ await userService(app.log).update({ id: member.user.id, platformId: ctx.platform.id, status: UserStatus.INACTIVE })
+ await userService(app.log).update({ id: member.user.id, platformId: ctx.platform.id, status: UserStatus.ACTIVE })
+
+ expect((await mcpOAuthTestHelpers.callMcp({ app, accessToken })).statusCode).toBe(401)
+ expect(await mcpOAuthCodeService.consume({ code, clientId: 'revocation-test-client', redirectUri: MCP_OAUTH_REDIRECT_URI })).toBeNull()
+ })
+
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 })
+ const connection = await mcpOAuthTestHelpers.exchangeGrant({ 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)
+ const response = await mcpOAuthTestHelpers.callMcp({ app, accessToken: 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/integration/ce/mcp/mcp-oauth-token.test.ts b/packages/server/api/test/integration/ce/mcp/mcp-oauth-token.test.ts
index 1303cb40472..1ff4368ea12 100644
--- a/packages/server/api/test/integration/ce/mcp/mcp-oauth-token.test.ts
+++ b/packages/server/api/test/integration/ce/mcp/mcp-oauth-token.test.ts
@@ -1,12 +1,12 @@
-import { createHash, randomBytes } from 'crypto'
-import { apId } from '@activepieces/core-utils'
import { FastifyInstance } from 'fastify'
import { beforeAll, describe, expect, it } from 'vitest'
-import { mcpOAuthClientService } from '../../../../src/app/mcp/oauth/client/mcp-oauth-client.service'
import { mcpOAuthTokenService } from '../../../../src/app/mcp/oauth/token/mcp-oauth-token.service'
+import { McpGrantee, mcpOAuthTestHelpers } from '../../../helpers/mcp-oauth'
+import { createTestContext } from '../../../helpers/test-context'
import { setupTestEnvironment } from '../../../helpers/test-setup'
let app: FastifyInstance
+let grantee: McpGrantee
function requireRefreshToken(response: { refresh_token?: string }): string {
if (response.refresh_token === undefined) {
@@ -15,61 +15,40 @@ function requireRefreshToken(response: { refresh_token?: string }): string {
return response.refresh_token
}
-async function exchangeFreshCode(clientId: string): Promise<string> {
- const codeVerifier = randomBytes(32).toString('base64url')
- const codeChallenge = createHash('sha256').update(codeVerifier).digest().toString('base64url')
- const tokens = await mcpOAuthTokenService.exchangeCode({
- redirectUris: [],
- codeVerifier,
- codeChallenge,
- codeChallengeMethod: 'S256',
- clientId,
- userId: apId(),
- projectId: apId(),
- platformId: apId(),
- scopes: ['mcp'],
- })
- return requireRefreshToken(tokens)
-}
-
describe('MCP OAuth token refresh', () => {
beforeAll(async () => {
app = await setupTestEnvironment({ fresh: true })
+ const ctx = await createTestContext(app)
+ grantee = { userId: ctx.user.id, projectId: ctx.project.id, platformId: ctx.platform.id }
})
it('echoes the presented refresh token back so clients cannot lose it', async () => {
- const clientId = apId()
- const refreshToken = await exchangeFreshCode(clientId)
+ const { clientId, refreshToken } = await mcpOAuthTestHelpers.exchangeGrant(grantee)
- const refreshed = await mcpOAuthTokenService.refreshAccessToken({ redirectUris: [], refreshToken, clientId })
+ const refreshed = await mcpOAuthTokenService.refreshAccessToken({ redirectUris: [], refreshToken, clientId, log: app.log })
expect(refreshed.access_token).toBeTypeOf('string')
expect(refreshed.refresh_token).toBe(refreshToken)
})
it('keeps refreshing indefinitely using the token from the previous response', async () => {
- const clientId = apId()
- const first = await exchangeFreshCode(clientId)
+ const { clientId, refreshToken: first } = await mcpOAuthTestHelpers.exchangeGrant(grantee)
- const second = await mcpOAuthTokenService.refreshAccessToken({ redirectUris: [], refreshToken: first, clientId })
- const third = await mcpOAuthTokenService.refreshAccessToken({ redirectUris: [], refreshToken: requireRefreshToken(second), clientId })
+ const second = await mcpOAuthTokenService.refreshAccessToken({ redirectUris: [], refreshToken: first, clientId, log: app.log })
+ const third = await mcpOAuthTokenService.refreshAccessToken({ redirectUris: [], refreshToken: requireRefreshToken(second), clientId, log: app.log })
expect(third.refresh_token).toBe(first)
})
it('returns the refresh token in the /token HTTP response a client persists', async () => {
- const client = await mcpOAuthClientService.register({
- redirectUris: ['https://example.com/callback'],
- tokenEndpointAuthMethod: 'none',
- })
- const refreshToken = await exchangeFreshCode(client.client_id)
+ const { clientId, refreshToken } = await mcpOAuthTestHelpers.exchangeGrant(grantee)
const res = await app.inject({
method: 'POST',
url: '/token',
payload: {
grant_type: 'refresh_token',
- client_id: client.client_id,
+ client_id: clientId,
refresh_token: refreshToken,
},
})
diff --git a/packages/server/api/test/integration/cloud/mcp/mcp-oauth-approve-access.test.ts b/packages/server/api/test/integration/cloud/mcp/mcp-oauth-approve-access.test.ts
index f8d3f48a79e..2c3fddb2325 100644
--- a/packages/server/api/test/integration/cloud/mcp/mcp-oauth-approve-access.test.ts
+++ b/packages/server/api/test/integration/cloud/mcp/mcp-oauth-approve-access.test.ts
@@ -4,7 +4,7 @@ import { FastifyInstance } from 'fastify'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { generateMockToken } from '../../../helpers/auth'
import { db } from '../../../helpers/db'
-import { MCP_OAUTH_REDIRECT_URI, mcpOAuthTestHelpers } from '../../../helpers/mcp-oauth'
+import { mcpOAuthTestHelpers } from '../../../helpers/mcp-oauth'
import { createMockProjectMember, createMockProjectRole, mockBasicUser } from '../../../helpers/mocks'
import { createTestContext, TestContext } from '../../../helpers/test-context'
import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
@@ -12,6 +12,7 @@ import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/
let app: FastifyInstance
const PLATFORM_RESOURCE = 'https://cloud.activepieces.com/mcp/platform'
+const PROJECT_RESOURCE = 'https://cloud.activepieces.com/mcp'
beforeAll(async () => {
app = await setupTestEnvironment()
@@ -21,31 +22,13 @@ afterAll(async () => {
await teardownTestEnvironment()
})
-async function createAuthRequestId(): Promise<string> {
- const client = await mcpOAuthTestHelpers.registerClient({ app, tokenEndpointAuthMethod: 'none' })
- const { challenge } = mcpOAuthTestHelpers.generatePkce()
- const consent = await app.inject({
- method: 'GET',
- url: '/authorize?' + new URLSearchParams({
- client_id: client.client_id,
- redirect_uri: MCP_OAUTH_REDIRECT_URI,
- response_type: 'code',
- code_challenge: challenge,
- code_challenge_method: 'S256',
- scope: 'mcp',
- resource: PLATFORM_RESOURCE,
- }).toString(),
- })
- return new URL(String(consent.headers.location), MCP_OAUTH_REDIRECT_URI).searchParams.get('authRequestId') ?? ''
-}
-
async function approveAs({ token, projectId }: { token: string, projectId?: string }) {
return app.inject({
method: 'POST',
url: '/api/v1/mcp-oauth/approve',
headers: { authorization: `Bearer ${token}` },
payload: {
- authRequestId: await createAuthRequestId(),
+ authRequestId: await mcpOAuthTestHelpers.authorize({ app, resource: projectId ? PROJECT_RESOURCE : PLATFORM_RESOURCE }),
...(projectId ? { projectId } : {}),
},
})
diff --git a/packages/server/api/test/integration/ee/mcp/mcp-oauth-project-delete.test.ts b/packages/server/api/test/integration/ee/mcp/mcp-oauth-project-delete.test.ts
new file mode 100644
index 00000000000..2a580b55187
--- /dev/null
+++ b/packages/server/api/test/integration/ee/mcp/mcp-oauth-project-delete.test.ts
@@ -0,0 +1,139 @@
+import { DefaultProjectRole, McpOAuthToken, PlatformRole } from '@activepieces/shared'
+import { FastifyInstance } from 'fastify'
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+import { platformProjectService } from '../../../../src/app/ee/projects/platform-project-service'
+import { projectMemberService } from '../../../../src/app/ee/projects/project-members/project-member.service'
+import { scimGroupService } from '../../../../src/app/ee/scim/scim-group-service'
+import { mcpOAuthCodeService } from '../../../../src/app/mcp/oauth/code/mcp-oauth-code.service'
+import { mcpGrantRevocation } from '../../../../src/app/mcp/oauth/token/mcp-grant-revocation'
+import { mcpOAuthRevocationList } from '../../../../src/app/mcp/oauth/token/mcp-oauth-revocation-list'
+import { mcpOAuthTokenService, OAuthTokenError } from '../../../../src/app/mcp/oauth/token/mcp-oauth-token.service'
+import { db } from '../../../helpers/db'
+import { MCP_OAUTH_REDIRECT_URI, McpGrantee, mcpOAuthTestHelpers } from '../../../helpers/mcp-oauth'
+import { mockAndSaveBasicSetup } from '../../../helpers/mocks'
+import { createMemberContext, createTestContext, TestContext } from '../../../helpers/test-context'
+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance
+
+beforeAll(async () => {
+ app = await setupTestEnvironment()
+})
+
+afterEach(() => {
+ vi.restoreAllMocks()
+})
+
+afterAll(async () => {
+ await teardownTestEnvironment()
+})
+
+describe('MCP OAuth grants on project delete', () => {
+ it('revokes the project\'s grants and voids its unused codes once it is deleted', async () => {
+ const grantee = await createProjectOwner()
+ const grant = await mcpOAuthTestHelpers.exchangeGrant(grantee)
+ const isCodeUsable = await issueUnusedCode(grantee)
+
+ await platformProjectService(app.log).markForDeletion({ id: grantee.projectId, platformId: grantee.platformId })
+
+ expect((await db.findOneBy<McpOAuthToken>('mcp_oauth_token', { id: grant.grantId }))?.revoked).toBe(true)
+ expect(await mcpOAuthRevocationList.isRevoked({ grantId: grant.grantId })).toBe(true)
+ await expect(refresh(grant)).rejects.toBeInstanceOf(OAuthTokenError)
+ expect(await isCodeUsable()).toBe(false)
+ })
+
+ it('still deletes the project when revoking its grants fails', async () => {
+ const grantee = await createProjectOwner()
+ await mcpOAuthTestHelpers.exchangeGrant(grantee)
+ vi.spyOn(mcpOAuthRevocationList, 'revoke').mockRejectedValue(new Error('redis down'))
+
+ await expect(platformProjectService(app.log).markForDeletion({ id: grantee.projectId, platformId: grantee.platformId })).resolves.toBeUndefined()
+ })
+
+ it('refuses the tokens of a deleted project even when its revocation was not written', async () => {
+ const grantee = await createProjectOwner()
+ const grant = await mcpOAuthTestHelpers.exchangeGrant(grantee)
+ vi.spyOn(mcpGrantRevocation, 'revokeActiveGrants').mockResolvedValue(undefined)
+
+ await platformProjectService(app.log).markForDeletion({ id: grantee.projectId, platformId: grantee.platformId })
+
+ await expect(refresh(grant)).rejects.toBeInstanceOf(OAuthTokenError)
+ expect((await mcpOAuthTestHelpers.callMcp({ app, accessToken: grant.accessToken })).statusCode).toBe(401)
+ })
+
+ it('refuses to issue tokens for a project that was deleted', async () => {
+ const grantee = await createProjectOwner()
+ await platformProjectService(app.log).markForDeletion({ id: grantee.projectId, platformId: grantee.platformId })
+
+ await expect(mcpOAuthTestHelpers.exchangeGrant(grantee)).rejects.toBeInstanceOf(OAuthTokenError)
+ })
+})
+
+describe('MCP OAuth grants on project member removal', () => {
+ it.each([
+ { removal: 'removed from the project', remove: ({ ctx, membershipId }: RemovalParams): Promise<unknown> => projectMemberService(app.log).removeFromProject({ projectId: ctx.project.id, memberId: membershipId, enforceLastProjectGuard: false }) },
+ { removal: 'removed from its SCIM group', remove: ({ ctx, userId }: RemovalParams): Promise<unknown> => scimGroupService(app.log).patch({
+ platformId: ctx.platform.id,
+ projectId: ctx.project.id,
+ request: { schemas: ['urn:ietf:params:scim:api:messages:2.0:PatchOp'], Operations: [{ op: 'remove', path: `members[value eq "${userId}"]` }] },
+ }) },
+ ])('ends a member\'s sign-ins for the project once $removal, and keeps their other sign-ins', async ({ remove }) => {
+ const { ctx, member, membershipId } = await createEditor()
+ const grantee = { userId: member.user.id, projectId: ctx.project.id, platformId: ctx.platform.id }
+ const projectGrant = await mcpOAuthTestHelpers.exchangeGrant(grantee)
+ const platformGrant = await mcpOAuthTestHelpers.exchangeGrant({ ...grantee, projectId: null })
+ const isCodeUsable = await issueUnusedCode(grantee)
+
+ await remove({ ctx, userId: member.user.id, membershipId })
+
+ await expect(refresh(projectGrant)).rejects.toBeInstanceOf(OAuthTokenError)
+ expect(await isCodeUsable()).toBe(false)
+ await expect(refresh(platformGrant)).resolves.toHaveProperty('access_token')
+ })
+
+ it('keeps the sign-in of a platform admin whose membership row is removed, since they keep access', async () => {
+ const { ctx, member, membershipId } = await createEditor()
+ await db.update('user', member.user.id, { platformRole: PlatformRole.ADMIN })
+ const projectGrant = await mcpOAuthTestHelpers.exchangeGrant({ userId: member.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })
+
+ await projectMemberService(app.log).delete(ctx.project.id, membershipId)
+
+ await expect(refresh(projectGrant)).resolves.toHaveProperty('access_token')
+ })
+
+ it('still removes the member when revoking their sign-ins fails', async () => {
+ const { ctx, member, membershipId } = await createEditor()
+ await mcpOAuthTestHelpers.exchangeGrant({ userId: member.user.id, projectId: ctx.project.id, platformId: ctx.platform.id })
+ vi.spyOn(mcpOAuthRevocationList, 'revoke').mockRejectedValue(new Error('redis down'))
+
+ await expect(projectMemberService(app.log).delete(ctx.project.id, membershipId)).resolves.toBeUndefined()
+ })
+})
+
+async function createProjectOwner(): Promise<McpGrantee & { projectId: string }> {
+ const { mockOwner, mockPlatform, mockProject } = await mockAndSaveBasicSetup()
+ return { userId: mockOwner.id, projectId: mockProject.id, platformId: mockPlatform.id }
+}
+
+async function createEditor(): Promise<{ ctx: TestContext, member: TestContext, membershipId: string }> {
+ const ctx = await createTestContext(app)
+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.EDITOR })
+ const membership = await db.findOneByOrFail<{ id: string }>('project_member', { userId: member.user.id, projectId: ctx.project.id })
+ return { ctx, member, membershipId: membership.id }
+}
+
+async function issueUnusedCode(grantee: McpGrantee): Promise<() => Promise<boolean>> {
+ const clientId = 'project-delete-test-client'
+ const code = await mcpOAuthTestHelpers.issueCode({ clientId, codeChallenge: 'challenge', ...grantee })
+ return async () => (await mcpOAuthCodeService.consume({ code, clientId, redirectUri: MCP_OAUTH_REDIRECT_URI })) !== null
+}
+
+function refresh({ clientId, refreshToken }: { clientId: string, refreshToken: string }): ReturnType<typeof mcpOAuthTokenService.refreshAccessToken> {
+ return mcpOAuthTokenService.refreshAccessToken({ redirectUris: [MCP_OAUTH_REDIRECT_URI], refreshToken, clientId, log: app.log })
+}
+
+type RemovalParams = {
+ ctx: TestContext
+ userId: string
+ membershipId: string
+}
diff --git a/packages/web/src/app/routes/mcp-authorize/index.tsx b/packages/web/src/app/routes/mcp-authorize/index.tsx
index 09c7de1d4a8..18c3d49428a 100644
--- a/packages/web/src/app/routes/mcp-authorize/index.tsx
+++ b/packages/web/src/app/routes/mcp-authorize/index.tsx
@@ -322,7 +322,9 @@ function decodeJwtPayload(token: string | null): AuthRequestSummary {
}>(token);
return {
clientName: payload.clientName ?? t('Unknown app'),
- isPlatformScoped: payload.resource?.endsWith('/mcp/platform') ?? false,
+ isPlatformScoped:
+ payload.resource?.replace(/\/+$/, '').endsWith('/mcp/platform') ??
+ false,
expiresAt: payload.exp ?? null,
};
} catch {