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): the tool switches now bind every MCP server, both ways (#15651)
Othman Abu Ajamiehdb0a2fa8b7d1
diff --git a/brain/knowledge/ai-intelligence/mcp-server.md b/brain/knowledge/ai-intelligence/mcp-server.mdindex 490c1215282..a80908f6611 100644--- a/brain/knowledge/ai-intelligence/mcp-server.md+++ b/brain/knowledge/ai-intelligence/mcp-server.md@@ -49,6 +49,9 @@ Exposes an Activepieces project as an MCP server so AI clients (Claude Desktop,its 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.+- **The platform `disabledTools` list is the outer bound on every MCP server; the project list narrows it.** A project can switch off more than the platform, never switch back on what the platform switched off.+ A platform client picks its project after it connects, so `executeInSelectedProject` checks the selected project's live list at call time: a switched-off tool stays listed, refuses when called, and is not charged.+ `LOCKED_TOOL_NAMES` are exempt from both lists; `isToolEnabled` in `mcp-server-builder.ts` is the one place that rule lives.- **The four `PLATFORM_LEVEL_TOOL_NAMES` never reach `executeInSelectedProject`, so they carry their own permission gate.** `ap_research_pieces`, `ap_search_actions`, `ap_search_triggers` and `ap_get_piece_props` run against `templateMcp` (projectId = platformId) and return early in `registerPlatformTools`, which means the per-project `PermissionChecker` never touches them. Membership is earned by guarding on `mcpUtils.isProjectScoped(mcp)` and passing `undefined` instead of the fake project id — `ap_list_ai_models` was listed here without that guard, so `rowAllowsScope` tested the platform id against an AI provider row's `projectIds`, hiding `selected`-scoped providers from everyone and offering `except`-scoped ones to the very projects they exclude. It routes through the selected project now. Without a gate of their own a member whose `READ_MCP` was revoked everywhere kept calling them on an already-issued token, and kept being charged for it. `withMcpReach` now wraps them with `mcpAccess.hasMcpReach`, the same any-project rule `POST /v1/mcp-oauth/approve` applies at authorization time, and it wraps the `charged` call so a refusal costs nothing. `ap_set_project_context` is wrapped the same way; enforcing the rule from inside its `execute` alone left the denial on the far side of `charged`, so a user with reach nowhere paid a credit per refusal.- **`READ_MCP` gates external MCP clients, not the in-app chat.** The chat reaches its tools through `POST /mcp/platform` like any client, and the controller serves it through the project branch once the conversation resolves a project, so `resolveMcpPermissionChecker` would deny every chat tool to a custom role with MCP set to None. `isInAppChatIdentity` in `mcp-oauth.controller.ts` picks the chat out as a *platform-scoped* token carrying `INTERNAL_CHAT_CLIENT_ID`, and `buildMcpServer` then uses `resolvePermissionChecker` (per-tool checks only, as the chat's own `agent-tools.ts` path does). Both halves are needed: `POST /v1/projects/:id/mcp-server/token` mints the same client id, but always project-scoped, and `resolveIdentity` rejects a scope mismatch, so those embed-SDK tokens keep the gate. Only the project branch relaxes; `registerPlatformTools`, `withMcpReach` and `executeInSelectedProject` stay gated, because the platform branch is the fallback for a conversation with no project or one the user lost access to.- **Claude Code and Codex re-run Dynamic Client Registration on *every* sign-in**, registering the exactdiff --git a/bun.lock b/bun.lockindex 11fdd123d23..77fa96a6b33 100644--- a/bun.lock+++ b/bun.lock@@ -165,7 +165,7 @@},"packages/core/shared": {"name": "@activepieces/shared",- "version": "0.182.0",+ "version": "0.183.0","dependencies": {"@activepieces/core-execution": "workspace:*","@activepieces/core-formula": "workspace:*",diff --git a/packages/core/shared/package.json b/packages/core/shared/package.jsonindex fc4835eb764..21fcd1ea9dd 100644--- a/packages/core/shared/package.json+++ b/packages/core/shared/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/shared",- "version": "0.182.0",+ "version": "0.183.0","type": "commonjs","sideEffects": false,"main": "./dist/src/index.js",diff --git a/packages/core/shared/src/lib/automation/mcp/mcp.ts b/packages/core/shared/src/lib/automation/mcp/mcp.tsindex 2b6ed696e91..fc2cc6403a2 100644--- a/packages/core/shared/src/lib/automation/mcp/mcp.ts+++ b/packages/core/shared/src/lib/automation/mcp/mcp.ts@@ -25,6 +25,11 @@ export const PopulatedMcpServer = McpServer.extend({})export type PopulatedMcpServer = z.infer<typeof PopulatedMcpServer>+export const ProjectMcpServerResponse = PopulatedMcpServer.extend({+ platformDisabledTools: z.array(z.string()),+})+export type ProjectMcpServerResponse = z.infer<typeof ProjectMcpServerResponse>+export const McpReachResponse = z.object({projectIds: z.array(ApId).nullable(),})diff --git a/packages/server/api/src/app/mcp/mcp-server-builder.ts b/packages/server/api/src/app/mcp/mcp-server-builder.tsindex 646764b9b9e..a0ee19cc30c 100644--- a/packages/server/api/src/app/mcp/mcp-server-builder.ts+++ b/packages/server/api/src/app/mcp/mcp-server-builder.ts@@ -10,12 +10,12 @@ import { telemetry } from '../helper/telemetry.utils'import { WebhookFlowVersionToRun, webhookService } from '../webhooks/webhook.service'import { McpActivityContext, withActivityRecording } from './activity/mcp-activity-recorder'import { mcpAccess } from './mcp-access'-import { ALLOW_ALL, PermissionChecker, resolveMcpPermissionChecker, resolvePermissionChecker } from './mcp-permissions'+import { ALLOW_ALL, deny, PermissionChecker, resolveMcpPermissionChecker, resolvePermissionChecker } from './mcp-permissions'import { mcpProjectSelection, ProjectSelectionScope } from './mcp-project-selection'import { mcpToolInput } from './mcp-tool-input'import { McpCallBilling, mcpUsageTracker } from './mcp-usage-tracker'import { activepiecesTools, ALL_CONTROLLABLE_TOOL_NAMES, LOCKED_TOOL_NAMES, PLATFORM_LEVEL_TOOL_NAMES } from './tools'-import { apSetProjectContextTool } from './tools/ap-set-project-context'+import { apSetProjectContextTool, SET_PROJECT_CONTEXT_TOOL_NAME } from './tools/ap-set-project-context'const PLATFORM_LEVEL_TOOL_SET = new Set<string>(PLATFORM_LEVEL_TOOL_NAMES)@@ -38,10 +38,11 @@ const MCP_SERVER_INSTRUCTIONS = `## Activepieces MCP Server- **CODE steps**: export a \`code\` fn; access inputs via \`inputs.key\`.- **Tables**: use field names, not IDs.`-export async function buildMcpServer({ mcp, userId, platformId, clientKey, clientId, isInAppChat, log, resolveProjectMcp }: {+export async function buildMcpServer({ mcp, userId, platformId, platformDisabledTools, clientKey, clientId, isInAppChat, log, resolveProjectMcp }: {mcp: PopulatedMcpServeruserId?: stringplatformId?: string+ platformDisabledTools: string[]clientKey: McpOAuthClientKey | nullclientId: stringisInAppChat: boolean@@ -80,7 +81,7 @@ export async function buildMcpServer({ mcp, userId, platformId, clientKey, clien: ALLOW_ALLconst activityContext: McpActivityContext | null = isNil(platformId) || isNil(userId) ? null : { platformId, projectId, userId, clientKey }registerFlowTools({ server, mcp, projectId, permissionChecker, billing, log })- registerStaticTools({ server, mcp, projectId, userId, permissionChecker, activityContext, billing, log })+ registerStaticTools({ server, mcp, projectId, userId, platformDisabledTools, permissionChecker, activityContext, billing, log })}else if (!isNil(mcp.platformId) && !isNil(userId) && !isNil(resolveProjectMcp)) {registerPlatformTools({ server, mcp, platformId: mcp.platformId, userId, clientKey, selectionScope: { platformId: mcp.platformId, userId, clientId }, resolveProjectMcp, billing, log })@@ -108,9 +109,7 @@ function registerPlatformTools({ server, mcp, platformId, userId, clientKey, selserver.registerTool(contextTool.title, buildToolConfig(contextTool), (args: Record<string, unknown>) => withMcpReach({ execute: charged({ execute: contextTool.execute, toolName: contextTool.title, projectId: null, billing }), toolTitle: contextTool.title, platformId, userId, log })(args))const templateMcp: ProjectScopedMcpServer = { ...mcp, projectId: platformId }- const allTools = activepiecesTools(templateMcp, userId, log)- const disabledToolSet = new Set(mcp.disabledTools ?? [])- const tools = allTools.filter(t => LOCKED_TOOL_NAMES.includes(t.title) || !disabledToolSet.has(t.title))+ const tools = filterEnabledTools({ tools: activepiecesTools(templateMcp, userId, log), disabledTools: mcp.disabledTools })tools.forEach((tool) => {if (PLATFORM_LEVEL_TOOL_SET.has(tool.title)) {@@ -150,13 +149,12 @@ async function executeInSelectedProject({ toolTitle, args, projectId, userId, reconst realTools = activepiecesTools(projectScopedMcp, userId, log)const realTool = realTools.find(t => t.title === toolTitle)if (isNil(realTool)) {- return {- content: [{ type: 'text' as const, text: `Tool "${toolTitle}" is not available for this project.` }],- isError: true,- }+ return deny(`Tool "${toolTitle}" is not available for this project.`)}const execute = permissionChecker.wrapExecute({- execute: charged({ execute: realTool.execute, toolName: realTool.title, projectId, billing }),+ execute: isToolEnabled({ toolTitle: realTool.title, disabledTools: projectMcp.disabledTools })+ ? charged({ execute: realTool.execute, toolName: realTool.title, projectId, billing })+ : async () => toolSwitchedOffResult(realTool.title),permission: realTool.permission,toolTitle: realTool.title,})@@ -179,14 +177,26 @@ function withMcpReach({ execute, toolTitle, platformId, userId, log }: {}}+function filterEnabledTools({ tools, disabledTools }: {+ tools: McpToolDefinition[]+ disabledTools: string[] | null+}): McpToolDefinition[] {+ return tools.filter(tool => isToolEnabled({ toolTitle: tool.title, disabledTools }))+}++function isToolEnabled({ toolTitle, disabledTools }: {+ toolTitle: string+ disabledTools: string[] | null+}): boolean {+ return LOCKED_TOOL_NAMES.includes(toolTitle) || !(disabledTools ?? []).includes(toolTitle)+}++function toolSwitchedOffResult(toolTitle: string): McpToolResult {+ return deny(`Tool "${toolTitle}" is switched off for the selected project by an admin. Do not retry it here. Ask the user to switch it on, or call ${SET_PROJECT_CONTEXT_TOOL_NAME} to select a project where it is on.`)+}+function noProjectSelectedResult(): McpToolResult {- return {- content: [{- type: 'text' as const,- text: 'No project selected. Use ap_set_project_context to select a project first.',- }],- isError: true,- }+ return deny(`No project selected. Use ${SET_PROJECT_CONTEXT_TOOL_NAME} to select a project first.`)}function registerFlowTools({ server, mcp, projectId, permissionChecker, billing, log }: RegisterToolsParams): void {@@ -280,10 +290,11 @@ export async function runFlowAsTool({ flow, properties, payload, returnsResponsereturn { content: [{ type: 'text', text }], ...(isOkay ? {} : { isError: true }) }}-function registerStaticTools({ server, mcp, projectId, userId, permissionChecker, activityContext, billing, log }: RegisterStaticToolsParams): void {- const allTools = activepiecesTools({ ...mcp, projectId }, userId, log)- const disabledToolSet = new Set(mcp.disabledTools ?? [])- const tools = allTools.filter(t => LOCKED_TOOL_NAMES.includes(t.title) || !disabledToolSet.has(t.title))+function registerStaticTools({ server, mcp, projectId, userId, platformDisabledTools, permissionChecker, activityContext, billing, log }: RegisterStaticToolsParams): void {+ const tools = filterEnabledTools({+ tools: activepiecesTools({ ...mcp, projectId }, userId, log),+ disabledTools: [...(mcp.disabledTools ?? []), ...platformDisabledTools],+ })tools.forEach((tool) => {const execute = permissionChecker.wrapExecute({@@ -362,5 +373,6 @@ type RegisterToolsParams = {type RegisterStaticToolsParams = RegisterToolsParams & {userId?: string+ platformDisabledTools: string[]activityContext: McpActivityContext | null}diff --git a/packages/server/api/src/app/mcp/mcp-server-controller.ts b/packages/server/api/src/app/mcp/mcp-server-controller.tsindex dfb13d4b0bc..130847739dc 100644--- a/packages/server/api/src/app/mcp/mcp-server-controller.ts+++ b/packages/server/api/src/app/mcp/mcp-server-controller.ts@@ -1,5 +1,6 @@import { ApId, Permission } from '@activepieces/core-utils'-import { PrincipalType, SERVICE_KEY_SECURITY_OPENAPI, UpdateMcpServerRequest } from '@activepieces/shared'+import { PopulatedMcpServer, PrincipalType, ProjectMcpServerResponse, SERVICE_KEY_SECURITY_OPENAPI, UpdateMcpServerRequest } from '@activepieces/shared'+import { FastifyBaseLogger } from 'fastify'import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'import { StatusCodes } from 'http-status-codes'import { z } from 'zod'@@ -7,26 +8,39 @@ import { ProjectResourceType } from '../core/security/authorization/common'import { securityAccess } from '../core/security/authorization/fastify-security'import { system } from '../helper/system/system'import { AppSystemProp } from '../helper/system/system-props'+import { projectService } from '../project/project-service'import { mcpServerService } from './mcp-service'import { mcpOAuthTokenService } from './oauth/token/mcp-oauth-token.service'export const mcpServerController: FastifyPluginAsyncZod = async (app) => {app.get('/', GetMcpRequest, async (req) => {- return mcpServerService(req.log).getPopulatedByProjectId(req.projectId)+ return withPlatformDisabledTools({+ projectId: req.projectId,+ mcp: await mcpServerService(req.log).getPopulatedByProjectId(req.projectId),+ log: req.log,+ })})app.post('/', UpdateMcpRequest, async (req) => {const { disabledTools } = req.body- return mcpServerService(req.log).update({+ return withPlatformDisabledTools({projectId: req.projectId,- disabledTools,+ mcp: await mcpServerService(req.log).update({+ projectId: req.projectId,+ disabledTools,+ }),+ log: req.log,})})app.post('/rotate', RotateTokenRequest, async (req) => {- return mcpServerService(req.log).rotateToken({+ return withPlatformDisabledTools({projectId: req.projectId,+ mcp: await mcpServerService(req.log).rotateToken({+ projectId: req.projectId,+ }),+ log: req.log,})})@@ -44,6 +58,16 @@ export const mcpServerController: FastifyPluginAsyncZod = async (app) => {})}+async function withPlatformDisabledTools({ projectId, mcp, log }: {+ projectId: string+ mcp: PopulatedMcpServer+ log: FastifyBaseLogger+}): Promise<ProjectMcpServerResponse> {+ const project = await projectService(log).getOneOrThrow(projectId)+ const platformDisabledTools = await mcpServerService(log).listPlatformDisabledTools({ platformId: project.platformId })+ return { ...mcp, platformDisabledTools }+}+export const UpdateMcpRequest = {config: {security: securityAccess.project(@@ -62,6 +86,9 @@ export const UpdateMcpRequest = {projectId: ApId,}),body: UpdateMcpServerRequest,+ response: {+ [StatusCodes.OK]: ProjectMcpServerResponse,+ },},}@@ -82,6 +109,9 @@ const GetMcpRequest = {params: z.object({projectId: ApId,}),+ response: {+ [StatusCodes.OK]: ProjectMcpServerResponse,+ },},}@@ -98,10 +128,13 @@ const RotateTokenRequest = {schema: {tags: ['mcp'],description: 'Rotate the MCP server token',+ params: z.object({+ projectId: ApId,+ }),+ response: {+ [StatusCodes.OK]: ProjectMcpServerResponse,+ },},- params: z.object({- projectId: ApId,- }),}const GenerateMcpTokenResponse = z.object({diff --git a/packages/server/api/src/app/mcp/mcp-service.ts b/packages/server/api/src/app/mcp/mcp-service.tsindex 5df0d966403..64fc183c631 100644--- a/packages/server/api/src/app/mcp/mcp-service.ts+++ b/packages/server/api/src/app/mcp/mcp-service.ts@@ -29,6 +29,11 @@ export const mcpServerService = (log: FastifyBaseLogger) => ({return { ...mcp, flows }},+ listPlatformDisabledTools: async ({ platformId }: { platformId: string }): Promise<string[]> => {+ const platformMcp = await mcpServerRepository().findOneBy({ platformId })+ return platformMcp?.disabledTools ?? []+ },+getPopulatedByPlatformId: async (platformId: string): Promise<PopulatedMcpServer> => {const mcp = await mcpServerService(log).getByPlatformId(platformId)return { ...mcp, flows: [] }@@ -67,6 +72,9 @@ export const mcpServerService = (log: FastifyBaseLogger) => ({mcp,userId,platformId,+ platformDisabledTools: mcp.type === McpServerType.PROJECT && !isNil(platformId)+ ? await mcpServerService(log).listPlatformDisabledTools({ platformId })+ : [],clientKey: clientKey ?? null,clientId,isInAppChat: isInAppChat ?? false,diff --git a/packages/server/api/test/integration/ce/mcp/mcp-platform-project-selection.test.ts b/packages/server/api/test/integration/ce/mcp/mcp-platform-project-selection.test.tsindex b8dbb7f6cc5..0cea0475eba 100644--- a/packages/server/api/test/integration/ce/mcp/mcp-platform-project-selection.test.ts+++ b/packages/server/api/test/integration/ce/mcp/mcp-platform-project-selection.test.ts@@ -1,19 +1,22 @@-import { FlowStatus, FlowVersionState, Project } from '@activepieces/shared'+import { apId, DefaultProjectRole, FlowStatus, FlowVersionState, McpServerType, Project } from '@activepieces/shared'import { FastifyInstance } from 'fastify'import { beforeAll, describe, expect, it } from 'vitest'import { db } from '../../../helpers/db'import { MCP_OAUTH_REDIRECT_URI, mcpOAuthTestHelpers } from '../../../helpers/mcp-oauth'import { createMockFlow, createMockFlowVersion, createMockProject } from '../../../helpers/mocks'-import { createTestContext, TestContext } from '../../../helpers/test-context'+import { createMemberContext, createTestContext, TestContext } from '../../../helpers/test-context'import { setupTestEnvironment } from '../../../helpers/test-setup'let app: FastifyInstancelet ctx: TestContextlet secondProject: Project+let restrictedProject: Projectconst PLATFORM_RESOURCE = 'https://cloud.activepieces.com/mcp/platform'const FLOW_IN_FIRST_PROJECT = 'flow-in-first-project'const FLOW_IN_SECOND_PROJECT = 'flow-in-second-project'+const SWITCHED_OFF_TOOL = 'ap_create_flow'+const LOCKED_TOOL = 'ap_list_flows'async function connectPlatformWideClient(): Promise<string> {const client = await mcpOAuthTestHelpers.registerClient({ app, tokenEndpointAuthMethod: 'none' })@@ -108,6 +111,21 @@ describe('platform MCP project selection', () => {})await db.save('project', secondProject)+ restrictedProject = createMockProject({+ platformId: ctx.platform.id,+ ownerId: ctx.user.id,+ displayName: 'restricted-project',+ })+ await db.save('project', restrictedProject)+ await db.save('mcp_server', {+ id: apId(),+ projectId: restrictedProject.id,+ platformId: null,+ type: McpServerType.PROJECT,+ token: apId(72),+ disabledTools: [SWITCHED_OFF_TOOL, LOCKED_TOOL],+ })+await seedFlow({ projectId: ctx.project.id, displayName: FLOW_IN_FIRST_PROJECT })await seedFlow({ projectId: secondProject.id, displayName: FLOW_IN_SECOND_PROJECT })})@@ -128,6 +146,52 @@ describe('platform MCP project selection', () => {expect(listedBySecond).not.toContain(FLOW_IN_FIRST_PROJECT)})+ it('lets a platform MEMBER authorize platform-wide MCP', async () => {+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.EDITOR })+ 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(),+ })+ const authRequestId = new URL(String(consent.headers.location), MCP_OAUTH_REDIRECT_URI).searchParams.get('authRequestId') ?? ''++ const approved = await member.post('/v1/mcp-oauth/approve', { authRequestId })++ expect(approved.statusCode).toBe(200)+ })++ it('refuses a tool the selected project switched off, and runs it in a project that did not', async () => {+ const client = await connectPlatformWideClient()++ await callTool({ accessToken: client, name: 'ap_set_project_context', args: { projectId: restrictedProject.id } })+ const refused = await callTool({ accessToken: client, name: SWITCHED_OFF_TOOL, args: { flowName: 'blocked-flow' } })++ await callTool({ accessToken: client, name: 'ap_set_project_context', args: { projectId: ctx.project.id } })+ const created = await callTool({ accessToken: client, name: SWITCHED_OFF_TOOL, args: { flowName: 'allowed-flow' } })++ expect(refused).toContain('switched off for the selected project')+ expect(created).toContain('allowed-flow')+ })++ it('keeps a locked tool callable even when the selected project lists it in disabledTools', async () => {+ const client = await connectPlatformWideClient()+ await callTool({ accessToken: client, name: 'ap_set_project_context', args: { projectId: restrictedProject.id } })++ const listed = await callTool({ accessToken: client, name: LOCKED_TOOL })++ expect(listed).not.toContain('switched off')+ })+it('asks a client with no selection of its own to pick a project', async () => {const alreadySelectedClient = await connectPlatformWideClient()await callTool({ accessToken: alreadySelectedClient, name: 'ap_set_project_context', args: { projectId: ctx.project.id } })diff --git a/packages/server/api/test/integration/cloud/mcp/mcp-platform-member-e2e.test.ts b/packages/server/api/test/integration/cloud/mcp/mcp-platform-member-e2e.test.tsnew file mode 100644index 00000000000..07c9a516bf8--- /dev/null+++ b/packages/server/api/test/integration/cloud/mcp/mcp-platform-member-e2e.test.ts@@ -0,0 +1,460 @@+import { apId, Permission, ProjectRole, RoleType } from '@activepieces/core-utils'+import { AgentRunSource, DefaultProjectRole, McpServerType, PlatformRole, PrincipalType, Project } from '@activepieces/shared'+import { FastifyInstance } from 'fastify'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { generateMockToken } from '../../../helpers/auth'+import { db } from '../../../helpers/db'+import { McpClient, mcpClientHelpers } from '../../../helpers/mcp-client'+import { createMockProject, createMockProjectMember, createMockProjectRole, mockBasicUser } from '../../../helpers/mocks'+import { createMemberContext, createTestContext, TestContext } from '../../../helpers/test-context'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++let app: FastifyInstance++const SWITCHED_OFF_TOOL = 'ap_create_flow'+const LOCKED_TOOL = 'ap_list_flows'+const PIECE_CATALOG_TOOL = 'ap_research_pieces'++beforeAll(async () => {+ app = await setupTestEnvironment()+})++afterAll(async () => {+ await teardownTestEnvironment()+})++async function connectAs({ ctx, projectId, conversationId }: { ctx: TestContext, projectId?: string, conversationId?: string }): Promise<McpClient> {+ return mcpClientHelpers.connect({+ app,+ approve: (payload) => ctx.post('/v1/mcp-oauth/approve', payload),+ ...(projectId ? { projectId } : {}),+ ...(conversationId ? { conversationId } : {}),+ })+}++async function switchOffOnPlatform({ ctx, tools }: { ctx: TestContext, tools: string[] }): Promise<void> {+ await db.save('mcp_server', {+ id: apId(),+ projectId: null,+ platformId: ctx.platform.id,+ type: McpServerType.PLATFORM,+ token: apId(72),+ disabledTools: tools,+ })+}++async function createConversation({ ctx }: { ctx: TestContext }): Promise<string> {+ const conversationId = apId()+ await db.save('agent_conversation', {+ id: conversationId,+ created: new Date().toISOString(),+ updated: new Date().toISOString(),+ platformId: ctx.platform.id,+ projectId: ctx.project.id,+ userId: ctx.user.id,+ source: AgentRunSource.AGENT,+ status: 'STREAMING',+ messages: [],+ uiMessages: [],+ })+ return conversationId+}++function call({ mcpClient, name, args }: { mcpClient: McpClient, name: string, args?: Record<string, unknown> }): Promise<string> {+ return mcpClientHelpers.callTool({ app, mcpClient, name, args })+}++function selectProject({ mcpClient, projectId }: { mcpClient: McpClient, projectId: string }): Promise<string> {+ return call({ mcpClient, name: 'ap_set_project_context', args: { projectId } })+}++async function createCustomRoleMember({ ctx, permissions }: { ctx: TestContext, permissions: Permission[] }): Promise<{ member: TestContext, role: ProjectRole }> {+ const role = createMockProjectRole({+ platformId: ctx.platform.id,+ name: `role-${apId()}`,+ permissions,+ type: RoleType.CUSTOM,+ })+ await db.save('project_role', role)+ const member = await createMemberContext(app, ctx, { projectRole: role.name })+ return { member, role }+}++async function createSiblingProject({ ctx, disabledTools }: { ctx: TestContext, disabledTools?: string[] }): Promise<Project> {+ const project = createMockProject({+ platformId: ctx.platform.id,+ ownerId: ctx.user.id,+ displayName: `project-${apId()}`,+ })+ await db.save('project', project)+ if (disabledTools) {+ await db.save('mcp_server', {+ id: apId(),+ projectId: project.id,+ platformId: null,+ type: McpServerType.PROJECT,+ token: apId(72),+ disabledTools,+ })+ }+ return project+}++async function grantMemberAccess({ ctx, member, projectId, permissions }: {+ ctx: TestContext+ member: TestContext+ projectId: string+ permissions: Permission[]+}): Promise<void> {+ const role = createMockProjectRole({+ platformId: ctx.platform.id,+ name: `role-${apId()}`,+ permissions,+ type: RoleType.CUSTOM,+ })+ await db.save('project_role', role)+ await db.save('project_member', createMockProjectMember({+ userId: member.user.id,+ platformId: ctx.platform.id,+ projectId,+ projectRoleId: role.id,+ }))+}++async function createPlatformUser({ ctx, platformRole }: { ctx: TestContext, platformRole: PlatformRole }): Promise<PlatformUser> {+ const { mockUser } = await mockBasicUser({+ user: {+ platformId: ctx.platform.id,+ platformRole,+ },+ })+ const token = await generateMockToken({+ id: mockUser.id,+ type: PrincipalType.USER,+ platform: { id: ctx.platform.id },+ })+ return {+ approve: (payload) => app.inject({+ method: 'POST',+ url: '/api/v1/mcp-oauth/approve',+ headers: { authorization: `Bearer ${token}` },+ payload,+ }),+ }+}++describe('platform MCP end to end, for a member', () => {+ it('lets an EDITOR connect, select their project and run a read tool', async () => {+ const ctx = await createTestContext(app)+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.EDITOR })+ const mcpClient = await connectAs({ ctx: member })++ const selected = await selectProject({ mcpClient, projectId: ctx.project.id })+ const listed = await call({ mcpClient, name: LOCKED_TOOL })++ expect(selected).toContain('Project context set')+ expect(listed).not.toContain('Permission denied')+ })++ it('refuses a VIEWER a write tool while allowing a read tool', async () => {+ const ctx = await createTestContext(app)+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.VIEWER })+ const mcpClient = await connectAs({ ctx: member })+ await selectProject({ mcpClient, projectId: ctx.project.id })++ const created = await call({ mcpClient, name: SWITCHED_OFF_TOOL, args: { flowName: 'viewer-flow' } })+ const listed = await call({ mcpClient, name: LOCKED_TOOL })++ expect(created).toContain('Permission denied')+ expect(created).toContain(Permission.WRITE_FLOW)+ expect(listed).not.toContain('Permission denied')+ })++ it('refuses the next call on a token already issued once READ_MCP is taken away', async () => {+ const ctx = await createTestContext(app)+ const { member, role } = await createCustomRoleMember({ ctx, permissions: [Permission.READ_FLOW, Permission.READ_MCP] })+ const mcpClient = await connectAs({ ctx: member })+ await selectProject({ mcpClient, projectId: ctx.project.id })+ expect(await call({ mcpClient, name: LOCKED_TOOL })).not.toContain('Permission denied')++ await db.update('project_role', role.id, { permissions: [Permission.READ_FLOW] })++ expect(await call({ mcpClient, name: LOCKED_TOOL })).toContain(Permission.READ_MCP)+ })++ it('stops a member selecting a project where their role lacks READ_MCP', async () => {+ const ctx = await createTestContext(app)+ const { member } = await createCustomRoleMember({ ctx, permissions: [Permission.READ_FLOW, Permission.READ_MCP] })+ const otherProject = await createSiblingProject({ ctx })+ await grantMemberAccess({ ctx, member, projectId: otherProject.id, permissions: [Permission.READ_FLOW] })+ const mcpClient = await connectAs({ ctx: member })++ const selected = await selectProject({ mcpClient, projectId: otherProject.id })++ expect(selected).toContain('don\'t have access')+ expect(selected).not.toContain(otherProject.id.concat(')'))+ })++ it('stops a member selecting a project in another platform', async () => {+ const ctx = await createTestContext(app)+ const otherPlatform = await createTestContext(app)+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.EDITOR })+ const mcpClient = await connectAs({ ctx: member })++ const selected = await selectProject({ mcpClient, projectId: otherPlatform.project.id })++ expect(selected).toContain('don\'t have access')+ })++ it('lets a member reach a second project once a role there grants READ_MCP', async () => {+ const ctx = await createTestContext(app)+ const { member } = await createCustomRoleMember({ ctx, permissions: [Permission.READ_FLOW, Permission.READ_MCP] })+ const otherProject = await createSiblingProject({ ctx })+ await grantMemberAccess({ ctx, member, projectId: otherProject.id, permissions: [Permission.READ_FLOW, Permission.READ_MCP] })+ const mcpClient = await connectAs({ ctx: member })++ const selected = await selectProject({ mcpClient, projectId: otherProject.id })+ const listed = await call({ mcpClient, name: LOCKED_TOOL })++ expect(selected).toContain('Project context set')+ expect(listed).not.toContain('Permission denied')+ })+})++describe('platform MCP tools configuration, as an admin', () => {+ it('refuses a tool the selected project switched off, and runs it where it is on', async () => {+ const ctx = await createTestContext(app)+ const restricted = await createSiblingProject({ ctx, disabledTools: [SWITCHED_OFF_TOOL] })+ const mcpClient = await connectAs({ ctx })++ await selectProject({ mcpClient, projectId: restricted.id })+ const refused = await call({ mcpClient, name: SWITCHED_OFF_TOOL, args: { flowName: 'blocked-flow' } })++ await selectProject({ mcpClient, projectId: ctx.project.id })+ const created = await call({ mcpClient, name: SWITCHED_OFF_TOOL, args: { flowName: 'allowed-flow' } })++ expect(refused).toContain('switched off for the selected project')+ expect(created).toContain('allowed-flow')+ })++ it('keeps a switched-off tool in the tool list, because the project is chosen after connecting', async () => {+ const ctx = await createTestContext(app)+ const restricted = await createSiblingProject({ ctx, disabledTools: [SWITCHED_OFF_TOOL] })+ const mcpClient = await connectAs({ ctx })+ await selectProject({ mcpClient, projectId: restricted.id })++ const toolNames = await mcpClientHelpers.listToolNames({ app, mcpClient })++ expect(toolNames).toContain(SWITCHED_OFF_TOOL)+ })++ it('keeps a locked tool callable even when the project lists it in disabledTools', async () => {+ const ctx = await createTestContext(app)+ const restricted = await createSiblingProject({ ctx, disabledTools: [SWITCHED_OFF_TOOL, LOCKED_TOOL] })+ const mcpClient = await connectAs({ ctx })+ await selectProject({ mcpClient, projectId: restricted.id })++ const listed = await call({ mcpClient, name: LOCKED_TOOL })++ expect(listed).not.toContain('switched off')+ })++ it('drops a tool the platform server switched off from the tool list entirely', async () => {+ const ctx = await createTestContext(app)+ await db.save('mcp_server', {+ id: apId(),+ projectId: null,+ platformId: ctx.platform.id,+ type: McpServerType.PLATFORM,+ token: apId(72),+ disabledTools: [SWITCHED_OFF_TOOL],+ })+ const mcpClient = await connectAs({ ctx })+ await selectProject({ mcpClient, projectId: ctx.project.id })++ const toolNames = await mcpClientHelpers.listToolNames({ app, mcpClient })++ expect(toolNames).not.toContain(SWITCHED_OFF_TOOL)+ expect(toolNames).toContain(LOCKED_TOOL)+ })++ it('lands a switch back on at the next call, with no reconnect', async () => {+ const ctx = await createTestContext(app)+ const restricted = await createSiblingProject({ ctx, disabledTools: [SWITCHED_OFF_TOOL] })+ const mcpClient = await connectAs({ ctx })+ await selectProject({ mcpClient, projectId: restricted.id })+ expect(await call({ mcpClient, name: SWITCHED_OFF_TOOL, args: { flowName: 'first-try' } })).toContain('switched off')++ const saved = await ctx.post(`/v1/projects/${restricted.id}/mcp-server`, { disabledTools: [] })+ expect(saved.statusCode).toBe(200)++ expect(await call({ mcpClient, name: SWITCHED_OFF_TOOL, args: { flowName: 'second-try' } })).toContain('second-try')+ })+})++describe('project-scoped MCP end to end', () => {+ it('lets a member authorize their own project and run a read tool', async () => {+ const ctx = await createTestContext(app)+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.EDITOR })++ const mcpClient = await connectAs({ ctx: member, projectId: ctx.project.id })+ const listed = await call({ mcpClient, name: LOCKED_TOOL })++ expect(listed).not.toContain('Permission denied')+ })++ it('refuses every tool on the project server once READ_MCP is taken away', async () => {+ const ctx = await createTestContext(app)+ const { member, role } = await createCustomRoleMember({ ctx, permissions: [Permission.READ_FLOW, Permission.READ_MCP] })+ const mcpClient = await connectAs({ ctx: member, projectId: ctx.project.id })+ expect(await call({ mcpClient, name: LOCKED_TOOL })).not.toContain('Permission denied')++ await db.update('project_role', role.id, { permissions: [Permission.READ_FLOW] })++ expect(await call({ mcpClient, name: LOCKED_TOOL })).toContain(Permission.READ_MCP)+ })++ it('refuses a piece-catalog tool on the project server once READ_MCP is taken away', async () => {+ const ctx = await createTestContext(app)+ const { member, role } = await createCustomRoleMember({ ctx, permissions: [Permission.READ_FLOW, Permission.READ_MCP] })+ const mcpClient = await connectAs({ ctx: member, projectId: ctx.project.id })++ await db.update('project_role', role.id, { permissions: [Permission.READ_FLOW] })++ expect(await call({ mcpClient, name: PIECE_CATALOG_TOOL, args: { query: 'slack' } })).toContain(Permission.READ_MCP)+ })++ it('refuses project selection on the platform server once READ_MCP is taken away', async () => {+ const ctx = await createTestContext(app)+ const { member, role } = await createCustomRoleMember({ ctx, permissions: [Permission.READ_FLOW, Permission.READ_MCP] })+ const mcpClient = await connectAs({ ctx: member })++ await db.update('project_role', role.id, { permissions: [Permission.READ_FLOW] })++ expect(await selectProject({ mcpClient, projectId: ctx.project.id })).toContain(Permission.READ_MCP)+ })++ it('refuses a piece-catalog tool on the platform server once READ_MCP is taken away', async () => {+ const ctx = await createTestContext(app)+ const { member, role } = await createCustomRoleMember({ ctx, permissions: [Permission.READ_FLOW, Permission.READ_MCP] })+ const mcpClient = await connectAs({ ctx: member })+ await selectProject({ mcpClient, projectId: ctx.project.id })++ await db.update('project_role', role.id, { permissions: [Permission.READ_FLOW] })++ expect(await call({ mcpClient, name: PIECE_CATALOG_TOOL, args: { query: 'slack' } })).toContain(Permission.READ_MCP)+ })++ it('drops a tool the platform server switched off, although the project leaves it on', async () => {+ const ctx = await createTestContext(app)+ await switchOffOnPlatform({ ctx, tools: [SWITCHED_OFF_TOOL] })+ const mcpClient = await connectAs({ ctx, projectId: ctx.project.id })++ const toolNames = await mcpClientHelpers.listToolNames({ app, mcpClient })++ expect(toolNames).not.toContain(SWITCHED_OFF_TOOL)+ })++ it('keeps a locked tool callable, whatever the platform list says', async () => {+ const ctx = await createTestContext(app)+ await switchOffOnPlatform({ ctx, tools: [LOCKED_TOOL] })+ const mcpClient = await connectAs({ ctx, projectId: ctx.project.id })++ const toolNames = await mcpClientHelpers.listToolNames({ app, mcpClient })++ expect(toolNames).toContain(LOCKED_TOOL)+ expect(await call({ mcpClient, name: LOCKED_TOOL })).not.toContain('Permission denied')+ })++ it('leaves the other tools alone', async () => {+ const ctx = await createTestContext(app)+ await switchOffOnPlatform({ ctx, tools: [SWITCHED_OFF_TOOL] })+ const mcpClient = await connectAs({ ctx, projectId: ctx.project.id })++ const toolNames = await mcpClientHelpers.listToolNames({ app, mcpClient })++ expect(toolNames).toContain('ap_rename_flow')+ })+})++describe('the AI chat, which resolves its project from the conversation', () => {+ it('honours the platform switch, which the platform setup page has always promised', async () => {+ const ctx = await createTestContext(app)+ await switchOffOnPlatform({ ctx, tools: [SWITCHED_OFF_TOOL] })+ const conversationId = await createConversation({ ctx })+ const mcpClient = await connectAs({ ctx, conversationId })++ const toolNames = await mcpClientHelpers.listToolNames({ app, mcpClient })++ expect(toolNames).not.toContain(SWITCHED_OFF_TOOL)+ expect(toolNames).toContain(LOCKED_TOOL)+ })+})++describe('platform MCP end to end, for a privileged user', () => {+ it('lets a platform admin run a piece-catalog tool on the platform server', async () => {+ const ctx = await createTestContext(app)+ const mcpClient = await connectAs({ ctx })++ const researched = await call({ mcpClient, name: PIECE_CATALOG_TOOL, args: { query: 'slack' } })++ expect(researched).not.toContain('Permission denied')+ })++ it('lets a platform admin select a project and run a read tool', async () => {+ const ctx = await createTestContext(app)+ const mcpClient = await connectAs({ ctx })++ const selected = await selectProject({ mcpClient, projectId: ctx.project.id })+ const listed = await call({ mcpClient, name: LOCKED_TOOL })++ expect(selected).toContain('Project context set')+ expect(listed).not.toContain('Permission denied')+ })++ it('lets an operator who belongs to no project run a piece-catalog tool', async () => {+ const ctx = await createTestContext(app)+ const operator = await createPlatformUser({ ctx, platformRole: PlatformRole.OPERATOR })+ const mcpClient = await mcpClientHelpers.connect({ app, approve: operator.approve })++ const researched = await call({ mcpClient, name: PIECE_CATALOG_TOOL, args: { query: 'slack' } })++ expect(researched).not.toContain('Permission denied')+ })++ it('lets an operator select a project they are no member of, and run a read tool there', async () => {+ const ctx = await createTestContext(app)+ const operator = await createPlatformUser({ ctx, platformRole: PlatformRole.OPERATOR })+ const mcpClient = await mcpClientHelpers.connect({ app, approve: operator.approve })++ const selected = await selectProject({ mcpClient, projectId: ctx.project.id })+ const listed = await call({ mcpClient, name: LOCKED_TOOL })++ expect(selected).toContain('Project context set')+ expect(listed).not.toContain('Permission denied')+ })++ it('stops an operator selecting a project in another platform', async () => {+ const ctx = await createTestContext(app)+ const otherPlatform = await createTestContext(app)+ const operator = await createPlatformUser({ ctx, platformRole: PlatformRole.OPERATOR })+ const mcpClient = await mcpClientHelpers.connect({ app, approve: operator.approve })++ const selected = await selectProject({ mcpClient, projectId: otherPlatform.project.id })++ expect(selected).toContain('don\'t have access')+ })++ it('refuses a member who is privileged nowhere, on the same platform the operator reaches', async () => {+ const ctx = await createTestContext(app)+ const stranger = await createPlatformUser({ ctx, platformRole: PlatformRole.MEMBER })++ const response = await stranger.approve({ authRequestId: 'unused' })++ expect(response.statusCode).toBe(403)+ })+})++type PlatformUser = {+ approve: (payload: { authRequestId: string, projectId?: string }) => ReturnType<FastifyInstance['inject']>+}diff --git a/packages/server/api/test/integration/cloud/mcp/mcp-project-server-response.test.ts b/packages/server/api/test/integration/cloud/mcp/mcp-project-server-response.test.tsnew file mode 100644index 00000000000..117cfbdb0bc--- /dev/null+++ b/packages/server/api/test/integration/cloud/mcp/mcp-project-server-response.test.ts@@ -0,0 +1,138 @@+import { apId, Permission, RoleType } from '@activepieces/core-utils'+import { DefaultProjectRole, McpServerType } from '@activepieces/shared'+import { FastifyInstance } from 'fastify'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { db } from '../../../helpers/db'+import { createMockProjectMember, createMockProjectRole } from '../../../helpers/mocks'+import { createMemberContext, createTestContext, TestContext } from '../../../helpers/test-context'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++let app: FastifyInstance++const PLATFORM_SWITCHED_OFF_TOOL = 'ap_delete_flow'+const PROJECT_SWITCHED_OFF_TOOL = 'ap_create_flow'++beforeAll(async () => {+ app = await setupTestEnvironment()+})++afterAll(async () => {+ await teardownTestEnvironment()+})++async function switchOffOnPlatform({ ctx, tools }: { ctx: TestContext, tools: string[] }): Promise<void> {+ await db.save('mcp_server', {+ id: apId(),+ projectId: null,+ platformId: ctx.platform.id,+ type: McpServerType.PLATFORM,+ token: apId(72),+ disabledTools: tools,+ })+}++describe('GET /v1/projects/:projectId/mcp-server', () => {+ it('reports the platform tools an admin switched off, beside the project ones', async () => {+ const ctx = await createTestContext(app)+ await switchOffOnPlatform({ ctx, tools: [PLATFORM_SWITCHED_OFF_TOOL] })+ await ctx.post(`/v1/projects/${ctx.project.id}/mcp-server`, { disabledTools: [PROJECT_SWITCHED_OFF_TOOL] })++ const response = await ctx.get(`/v1/projects/${ctx.project.id}/mcp-server`)++ expect(response.statusCode).toBe(200)+ expect(response.json().disabledTools).toEqual([PROJECT_SWITCHED_OFF_TOOL])+ expect(response.json().platformDisabledTools).toEqual([PLATFORM_SWITCHED_OFF_TOOL])+ })++ it('reports an empty platform list when the platform switched nothing off', async () => {+ const ctx = await createTestContext(app)++ const response = await ctx.get(`/v1/projects/${ctx.project.id}/mcp-server`)++ expect(response.json().platformDisabledTools).toEqual([])+ })++ it('reads the platform list without creating a platform server row', async () => {+ const ctx = await createTestContext(app)++ const response = await ctx.get(`/v1/projects/${ctx.project.id}/mcp-server`)++ expect(response.statusCode).toBe(200)+ expect(await db.findBy('mcp_server', { platformId: ctx.platform.id })).toEqual([])+ })++ it('keeps the platform list on the save response, so the page does not lose it', async () => {+ const ctx = await createTestContext(app)+ await switchOffOnPlatform({ ctx, tools: [PLATFORM_SWITCHED_OFF_TOOL] })++ const response = await ctx.post(`/v1/projects/${ctx.project.id}/mcp-server`, { disabledTools: [PROJECT_SWITCHED_OFF_TOOL] })++ expect(response.json().platformDisabledTools).toEqual([PLATFORM_SWITCHED_OFF_TOOL])+ })++ it('shows a member the platform list too, on READ_MCP alone', async () => {+ const ctx = await createTestContext(app)+ await switchOffOnPlatform({ ctx, tools: [PLATFORM_SWITCHED_OFF_TOOL] })+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.VIEWER })++ const response = await member.get(`/v1/projects/${ctx.project.id}/mcp-server`)++ expect(response.statusCode).toBe(200)+ expect(response.json().platformDisabledTools).toEqual([PLATFORM_SWITCHED_OFF_TOOL])+ })++ it('refuses a member whose role lacks READ_MCP', async () => {+ const ctx = await createTestContext(app)+ const role = createMockProjectRole({+ platformId: ctx.platform.id,+ name: `role-${apId()}`,+ permissions: [Permission.READ_FLOW],+ type: RoleType.CUSTOM,+ })+ await db.save('project_role', role)+ const member = await createMemberContext(app, ctx, { projectRole: role.name })++ const response = await member.get(`/v1/projects/${ctx.project.id}/mcp-server`)++ expect(response.statusCode).toBe(403)+ })++ it('refuses a VIEWER the save, because it needs WRITE_MCP', async () => {+ const ctx = await createTestContext(app)+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.VIEWER })++ const response = await member.post(`/v1/projects/${ctx.project.id}/mcp-server`, { disabledTools: [PROJECT_SWITCHED_OFF_TOOL] })++ expect(response.statusCode).toBe(403)+ })++ it('reports the list of the platform that owns the project, not of the caller platform', async () => {+ const owner = await createTestContext(app)+ await switchOffOnPlatform({ ctx: owner, tools: [PLATFORM_SWITCHED_OFF_TOOL] })+ const outsider = await createTestContext(app)+ await switchOffOnPlatform({ ctx: outsider, tools: [PROJECT_SWITCHED_OFF_TOOL] })+ const viewerRole = await db.findOneByOrFail<{ id: string }>('project_role', { name: DefaultProjectRole.VIEWER })+ await db.save('project_member', createMockProjectMember({+ userId: outsider.user.id,+ platformId: owner.platform.id,+ projectId: owner.project.id,+ projectRoleId: viewerRole.id,+ }))++ const response = await outsider.get(`/v1/projects/${owner.project.id}/mcp-server`)++ expect(response.statusCode).toBe(200)+ expect(response.json().platformDisabledTools).toEqual([PLATFORM_SWITCHED_OFF_TOOL])+ })++ it('never leaks the platform server token to a project member', async () => {+ const ctx = await createTestContext(app)+ await switchOffOnPlatform({ ctx, tools: [PLATFORM_SWITCHED_OFF_TOOL] })+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.VIEWER })++ const platformMcp = await db.findOneByOrFail<{ token: string }>('mcp_server', { platformId: ctx.platform.id })+ const response = await member.get(`/v1/projects/${ctx.project.id}/mcp-server`)++ expect(response.body).not.toContain(platformMcp.token)+ })+})diff --git a/packages/server/api/test/integration/cloud/mcp/mcp-switched-off-billing.test.ts b/packages/server/api/test/integration/cloud/mcp/mcp-switched-off-billing.test.tsnew file mode 100644index 00000000000..4d843cccfac--- /dev/null+++ b/packages/server/api/test/integration/cloud/mcp/mcp-switched-off-billing.test.ts@@ -0,0 +1,96 @@+import { apId } from '@activepieces/core-utils'+import { McpServerType } from '@activepieces/shared'+import { FastifyInstance } from 'fastify'+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { db } from '../../../helpers/db'+import { McpClient, mcpClientHelpers } from '../../../helpers/mcp-client'+import { createMockProject } from '../../../helpers/mocks'+import { createTestContext, TestContext } from '../../../helpers/test-context'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++const { mockTrackBilling } = vi.hoisted(() => ({+ mockTrackBilling: vi.fn<(params: TrackedBilling) => Promise<void>>(),+}))++vi.mock('../../../../src/app/platform/billing-and-telemetry', () => ({+ trackBillingAndSendTelemetry: mockTrackBilling,+}))++let app: FastifyInstance++const SWITCHED_OFF_TOOL = 'ap_create_flow'++beforeAll(async () => {+ app = await setupTestEnvironment()+})++afterAll(async () => {+ await teardownTestEnvironment()+})++beforeEach(() => {+ mockTrackBilling.mockReset()+ mockTrackBilling.mockResolvedValue(undefined)+})++function connectAs({ ctx }: { ctx: TestContext }): Promise<McpClient> {+ return mcpClientHelpers.connect({+ app,+ approve: (payload) => ctx.post('/v1/mcp-oauth/approve', payload),+ })+}++function call({ mcpClient, name, args }: { mcpClient: McpClient, name: string, args?: Record<string, unknown> }): Promise<string> {+ return mcpClientHelpers.callTool({ app, mcpClient, name, args })+}++function chargedProjectIds({ toolName }: { toolName: string }): (string | null)[] {+ return mockTrackBilling.mock.calls+ .map(([params]) => params.credits.properties)+ .filter((properties) => properties.toolName === toolName)+ .map((properties) => properties.projectId)+}++async function createRestrictedProject({ ctx }: { ctx: TestContext }): Promise<string> {+ const project = createMockProject({+ platformId: ctx.platform.id,+ ownerId: ctx.user.id,+ displayName: `project-${apId()}`,+ })+ await db.save('project', project)+ await db.save('mcp_server', {+ id: apId(),+ projectId: project.id,+ platformId: null,+ type: McpServerType.PROJECT,+ token: apId(72),+ disabledTools: [SWITCHED_OFF_TOOL],+ })+ return project.id+}++describe('a tool the selected project switched off', () => {+ it('is not charged, while the same tool is charged where it is on', async () => {+ const ctx = await createTestContext(app)+ const restrictedProjectId = await createRestrictedProject({ ctx })+ const mcpClient = await connectAs({ ctx })++ await call({ mcpClient, name: 'ap_set_project_context', args: { projectId: restrictedProjectId } })+ const refused = await call({ mcpClient, name: SWITCHED_OFF_TOOL, args: { flowName: 'blocked-flow' } })+ await call({ mcpClient, name: 'ap_set_project_context', args: { projectId: ctx.project.id } })+ await call({ mcpClient, name: SWITCHED_OFF_TOOL, args: { flowName: 'allowed-flow' } })++ await vi.waitFor(() => expect(chargedProjectIds({ toolName: SWITCHED_OFF_TOOL })).toContain(ctx.project.id))+ expect(refused).toContain('switched off')+ expect(chargedProjectIds({ toolName: SWITCHED_OFF_TOOL })).not.toContain(restrictedProjectId)+ })+})++type TrackedBilling = {+ credits: {+ properties: {+ toolName: string+ projectId: string | null+ }+ }+}diff --git a/packages/server/api/test/integration/ee/mcp/mcp-access-ee.test.ts b/packages/server/api/test/integration/ee/mcp/mcp-access-ee.test.tsindex 2d67d3c6aca..1cfb3bb64c8 100644--- a/packages/server/api/test/integration/ee/mcp/mcp-access-ee.test.ts+++ b/packages/server/api/test/integration/ee/mcp/mcp-access-ee.test.ts@@ -1,5 +1,5 @@import { apId, Permission, RoleType } from '@activepieces/core-utils'-import { DefaultProjectRole, PlatformRole, PrincipalType } from '@activepieces/shared'+import { DefaultProjectRole, McpServerType, PlatformRole, PrincipalType } from '@activepieces/shared'import { FastifyInstance } from 'fastify'import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { mcpAccess } from '../../../../src/app/mcp/mcp-access'@@ -7,12 +7,13 @@ import { resolveMcpPermissionChecker } from '../../../../src/app/mcp/mcp-permissimport { generateMockToken } from '../../../helpers/auth'import { db } from '../../../helpers/db'import { McpClient, mcpClientHelpers } from '../../../helpers/mcp-client'-import { createMockProjectRole, mockBasicUser } from '../../../helpers/mocks'+import { createMockProject, createMockProjectRole, mockBasicUser } from '../../../helpers/mocks'import { createMemberContext, createTestContext, TestContext } from '../../../helpers/test-context'import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'let app: FastifyInstance+const SWITCHED_OFF_TOOL = 'ap_create_flow'const LOCKED_TOOL = 'ap_list_flows'const PIECE_CATALOG_TOOL = 'ap_research_pieces'@@ -104,6 +105,46 @@ describe('MCP access on enterprise edition', () => {expect(listed).not.toContain('Permission denied')})+ it('applies the selected project\'s switched-off tools to a platform client', async () => {+ const ctx = await createTestContext(app)+ const restricted = createMockProject({+ platformId: ctx.platform.id,+ ownerId: ctx.user.id,+ displayName: `project-${apId()}`,+ })+ await db.save('project', restricted)+ await db.save('mcp_server', {+ id: apId(),+ projectId: restricted.id,+ platformId: null,+ type: McpServerType.PROJECT,+ token: apId(72),+ disabledTools: [SWITCHED_OFF_TOOL],+ })+ const mcpClient = await connectAs({ ctx })++ await mcpClientHelpers.callTool({ app, mcpClient, name: 'ap_set_project_context', args: { projectId: restricted.id } })+ const refused = await mcpClientHelpers.callTool({ app, mcpClient, name: SWITCHED_OFF_TOOL, args: { flowName: 'blocked-flow' } })++ expect(refused).toContain('switched off for the selected project')+ })++ it('reports the platform switched-off tools on the project MCP server route', async () => {+ const ctx = await createTestContext(app)+ await db.save('mcp_server', {+ id: apId(),+ projectId: null,+ platformId: ctx.platform.id,+ type: McpServerType.PLATFORM,+ token: apId(72),+ disabledTools: [SWITCHED_OFF_TOOL],+ })++ const response = await ctx.get(`/v1/projects/${ctx.project.id}/mcp-server`)++ expect(response.json().platformDisabledTools).toEqual([SWITCHED_OFF_TOOL])+ })+it('lets a platform admin run a piece-catalog tool on the platform server', async () => {const ctx = await createTestContext(app)const mcpClient = await connectAs({ ctx })