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
feat(mcp): point the MCP page at the platform server, and fold Pieces into Tools (#15652)
Othman Abu Ajamiehdcedf7f249ca
diff --git a/brain/knowledge/ai-intelligence/mcp-server.md b/brain/knowledge/ai-intelligence/mcp-server.mdindex a80908f6611..b275858e7ff 100644--- a/brain/knowledge/ai-intelligence/mcp-server.md+++ b/brain/knowledge/ai-intelligence/mcp-server.md@@ -52,6 +52,8 @@ Exposes an Activepieces project as an MCP server so AI clients (Claude Desktop,- **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 MCP page has no Pieces tab: pieces are the second segment of Tools.** Built-in and Pieces share one project picker, because both answer "what can a connected client call in this project". The segment rides the URL as `?segment=`, and the old `/mcp-server/pieces` address is its own route, `LegacyPiecesRedirect`, that keeps `?project=`. Flows-as-tools and the project `/mcp` URL live only in the embedded MCP settings dialog.+- **The Tools tab edits the selected project's `disabledTools`, not the session project's.** It posts to `POST /v1/projects/:projectId/mcp-server` with the picker's project, so the role that matters is the role there: `McpTools` reads `WRITE_MCP` through `useAuthorization(projectId)` and disables every checkbox without it. `platformDisabledTools` comes back beside the project list, and `McpTools` shows those tools as off, locked and badged, here and in the embedded dialog. `useMcpNav` drops a `?project=` that is not an `ApId`, because `..` survives `encodeURIComponent` and the browser would resolve the path to the platform server's own row.- **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 exact@@ -121,7 +123,7 @@ Entry point: `mcpServerModule`, the Fastify plugin in `mcp/mcp-module.ts` regist- `packages/server/api/src/app/mcp/oauth/` — OAuth 2.0 PKCE flow: metadata, authorize, token, revoke- `packages/core/shared/src/lib/automation/mcp/` — McpServer schema, McpToolDefinition, MCP OAuth types- `packages/web/src/app/components/project-settings/mcp-server/` — settings panel: credentials, flows-as-tools, tool toggles-- `packages/web/src/app/routes/mcp-server/` — the Connect, Pieces and Grants tabs+- `packages/web/src/app/routes/mcp-server/` — the Connect, Tools, Connections and Activity tabs; Tools holds the Built-in / Pieces segments- `packages/web/src/app/routes/mcp-authorize/` — standalone OAuth consent page and its permission item- `packages/web/src/app/routes/embed/` — the `embedded-mcp-*` dialogs for managed-auth consent and settings- `packages/ee/embed-sdk/src/index.ts` — embed SDK public methods `authorizeMcp()`, `mcpSettings()`, `generateMcpToken()`diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex 052e85772f6..dcf7ceb2ce5 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -662,7 +662,6 @@"Save Changes": "Save Changes","Tools": "Tools","Internal Tools": "Internal Tools",- "Control which built-in Activepieces tools are available to agents via this MCP server.": "Control which built-in Activepieces tools are available to agents via this MCP server.","Your Flows": "Your Flows","Flows with the MCP Trigger are exposed as tools on this server.": "Flows with the MCP Trigger are exposed as tools on this server.","Server URL": "Server URL",@@ -673,6 +672,7 @@"On": "On","Off": "Off","Required by other tools — always enabled": "Required by other tools — always enabled",+ "You can see these tools, but your role cannot change them.": "You can see these tools, but your role cannot change them.","Select all in {{category}}": "Select all in {{category}}","always enabled": "always enabled","{firstName} {lastName} role has become {roleName}": "{firstName} {lastName} role has become {roleName}",@@ -1552,7 +1552,7 @@"Change the settings for your platform.": "Change the settings for your platform.","Platform MCP Server": "Platform MCP Server","Configure the platform-wide MCP server used by the AI Chat assistant and external MCP clients.": "Configure the platform-wide MCP server used by the AI Chat assistant and external MCP clients.",- "Control which built-in tools are available to the AI Chat and external agents via the platform MCP server.": "Control which built-in tools are available to the AI Chat and external agents via the platform MCP server.",+ "Switching a tool off here switches it off everywhere on this platform: the AI Chat, external agents, and every project MCP server.": "Switching a tool off here switches it off everywhere on this platform: the AI Chat, external agents, and every project MCP server.","Customize Selector": "Customize Selector","Custom tabs must have a name": "Custom tabs must have a name","Sections must have a name": "Sections must have a name",@@ -2786,8 +2786,6 @@"Waiting for first call": "Waiting for first call","Where do you want to use it?": "Where do you want to use it?","Your AI gets all of this": "Your AI gets all of this",- "{count} pieces, plus every flow you’ve built — ready to run.": "{count} pieces, plus every flow you’ve built — ready to run.",- "Every piece you can use, plus every flow you’ve built.": "Every piece you can use, plus every flow you’ve built.","Your AI stops guessing and starts doing — sending the Slack message, updating the CRM, running the flow. Paste it into any client that speaks MCP.": "Your AI stops guessing and starts doing — sending the Slack message, updating the CRM, running the flow. Paste it into any client that speaks MCP.","desktop and web, needs a public HTTPS URL": "desktop and web, needs a public HTTPS URL","one command, nothing to edit": "one command, nothing to edit",@@ -2810,11 +2808,8 @@"revokeSelectedCount": "{count, plural, =1 {Revoke 1} other {Revoke #}}","revokedGrants": "{count, plural, =1 {1 connection} other {# connections}}","{name} · you": "{name} · you",- "Every piece a connected client can reach, and every action inside it.": "Every piece a connected client can reach, and every action inside it.",- "This page is a mirror — a platform admin decides what is on the list.": "This page is a mirror — a platform admin decides what is on the list.","Nothing below can run right now": "Nothing below can run right now","Running piece actions is switched off for this project. Clients can still see the list, but every call fails.": "Running piece actions is switched off for this project. Clients can still see the list, but every call fails.",- "Turn it on in project settings": "Turn it on in project settings","Search pieces and actions...": "Search pieces and actions...","No piece or action matches your search.": "No piece or action matches your search.","No pieces are reachable in this project.": "No pieces are reachable in this project.",@@ -3132,5 +3127,18 @@"Forward every audit event we emit to a webhook, then handle it in a flow.": "Forward every audit event we emit to a webhook, then handle it in a flow.","Not included in your plan": "Not included in your plan","Included in the {tier} plan": "Included in the {tier} plan",- "Opened a paid admin page": "Opened a paid admin page"+ "Opened a paid admin page": "Opened a paid admin page",+ "You are not allowed to change the tools of this project.": "You are not allowed to change the tools of this project.",+ "The tools could not be saved. Try again.": "The tools could not be saved. Try again.",+ "Built-in": "Built-in",+ "Turn on Run action": "Turn on Run action",+ "Everything a connected client can call in this project.": "Everything a connected client can call in this project.",+ "Built-in tools are switched on and off here. Pieces are controlled in piece sets.": "Built-in tools are switched on and off here. Pieces are controlled in piece sets.",+ "Off for the whole platform": "Off for the whole platform",+ "A platform admin switched this off for the whole platform, so no client can call it here or on the platform MCP server.": "A platform admin switched this off for the whole platform, so no client can call it here or on the platform MCP server.",+ "A platform admin switched Run action off for the whole platform. Clients can still see the list, but every call fails.": "A platform admin switched Run action off for the whole platform. Clients can still see the list, but every call fails.",+ "tools": "tools",+ "Control which built-in tools are available to agents via this MCP server.": "Control which built-in tools are available to agents via this MCP server.",+ "Every piece you can use, in every project MCP reaches.": "Every piece you can use, in every project MCP reaches.",+ "{count} pieces, ready to run in every project MCP reaches.": "{count} pieces, ready to run in every project MCP reaches."}diff --git a/packages/web/src/app/components/primary-rail/index.tsx b/packages/web/src/app/components/primary-rail/index.tsxindex af304f5739f..24d69aeca87 100644--- a/packages/web/src/app/components/primary-rail/index.tsx+++ b/packages/web/src/app/components/primary-rail/index.tsx@@ -1,4 +1,3 @@-import { Permission } from '@activepieces/core-utils';import {ApEdition,ApFlagId,@@ -63,10 +62,7 @@ import {railIsCollapsed,useRailCollapsed,} from '@/features/workspace/lib/rail-collapsed';-import {- useAuthorization,- useIsPlatformAdmin,-} from '@/hooks/authorization-hooks';+import { useIsPlatformAdmin } from '@/hooks/authorization-hooks';import { flagsHooks } from '@/hooks/flags-hooks';import { platformHooks } from '@/hooks/platform-hooks';import { userHooks } from '@/hooks/user-hooks';@@ -77,6 +73,7 @@ import { AccountSettingsDialog } from '../account-settings';import { recordAccess } from '../global-search/access-history';import { useGlobalSearch } from '../global-search/global-search-context';import { HelpAndFeedback } from '../help-and-feedback';+import { mcpHooks } from '../project-settings/mcp-server/utils/mcp-hooks';export function PrimaryRail() {const { embedState } = useEmbedding();@@ -87,9 +84,10 @@ export function PrimaryRail() {const [openedOn, setOpenedOn] = useState<string | null>(null);const collapsed = railIsCollapsed({ preference, pathname, openedOn });const showAgents = useAgentsNavVisible();- const { checkAccess } = useAuthorization();+ const isRailHidden = embedState.isEmbedded || embedState.hideSideNav;+ const { reachesMcp } = mcpHooks.useMcpReach({ enabled: !isRailHidden });- if (embedState.isEmbedded || embedState.hideSideNav) {+ if (isRailHidden) {return null;}@@ -138,7 +136,7 @@ export function PrimaryRail() {}/>)}- {checkAccess(Permission.READ_MCP) && (+ {reachesMcp && (<RailNavButtoncollapsed={collapsed}to="/mcp-server"diff --git a/packages/web/src/app/components/project-settings/index.tsx b/packages/web/src/app/components/project-settings/index.tsxindex 43cbcf7c6f7..08c4d7d9cc1 100644--- a/packages/web/src/app/components/project-settings/index.tsx+++ b/packages/web/src/app/components/project-settings/index.tsx@@ -6,7 +6,6 @@ import { useState, useEffect, useRef } from 'react';import { useForm } from 'react-hook-form';import { toast } from 'sonner';-import { McpSvg } from '@/assets/img/custom/mcp';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Dialog, DialogContent } from '@/components/ui/dialog';@@ -26,17 +25,10 @@ import { ProjectAvatar } from '../project-avatar';import { AlertsSettings } from './alerts';import { EnvironmentSettings } from './environment';import { GeneralSettings, FormValues } from './general';-import { McpServerSettings } from './mcp-server';import { MembersSettings } from './members';import { PiecesSettings } from './pieces';-type TabId =- | 'general'- | 'members'- | 'alerts'- | 'pieces'- | 'environment'- | 'mcp';+type TabId = 'general' | 'members' | 'alerts' | 'pieces' | 'environment';interface ProjectSettingsDialogProps {open: boolean;@@ -143,12 +135,6 @@ export function ProjectSettingsDialog({icon: <Bell className="w-4 h-4" />,disabled: !checkAccess(Permission.READ_ALERT) || !showAlerts,},- {- id: 'mcp' as TabId,- label: t('MCP Server'),- icon: <McpSvg className="w-4 h-4" />,- disabled: false,- },{id: 'pieces' as TabId,label: t('Pieces'),@@ -175,8 +161,6 @@ export function ProjectSettingsDialog({return <PiecesSettings />;case 'environment':return <EnvironmentSettings />;- case 'mcp':- return <McpServerSettings />;default:return null;}diff --git a/packages/web/src/app/components/project-settings/mcp-server/index.tsx b/packages/web/src/app/components/project-settings/mcp-server/index.tsxindex b13eee61914..eec3054a3bb 100644--- a/packages/web/src/app/components/project-settings/mcp-server/index.tsx+++ b/packages/web/src/app/components/project-settings/mcp-server/index.tsx@@ -49,11 +49,12 @@ export const McpServerSettings = () => {</h3><p className="text-sm text-muted-foreground mb-3">{t(- 'Control which built-in Activepieces tools are available to agents via this MCP server.',+ 'Control which built-in tools are available to agents via this MCP server.',)}</p><McpToolsdisabledTools={mcpServer.disabledTools}+ platformDisabledTools={mcpServer.platformDisabledTools}isPending={isUpdating}onUpdateDisabledTools={(tools) =>updateMcpServer({ disabledTools: tools })diff --git a/packages/web/src/app/components/project-settings/mcp-server/mcp-credentials.tsx b/packages/web/src/app/components/project-settings/mcp-server/mcp-credentials.tsxindex 03643b60a68..80d1f1138fb 100644--- a/packages/web/src/app/components/project-settings/mcp-server/mcp-credentials.tsx+++ b/packages/web/src/app/components/project-settings/mcp-server/mcp-credentials.tsx@@ -1,3 +1,4 @@+import { McpServerType } from '@activepieces/shared';import { t } from 'i18next';import { useMcpServerUrl } from '@/app/routes/mcp-server/mcp-server-url';@@ -5,7 +6,7 @@ import { CopyButton } from '@/components/custom/clipboard/copy-button';import { CollapsibleJson } from '@/components/custom/collapsible-json';export function McpCredentials() {- const { serverUrl } = useMcpServerUrl();+ const { serverUrl } = useMcpServerUrl({ serverType: McpServerType.PROJECT });const jsonConfiguration = {mcpServers: {diff --git a/packages/web/src/app/components/project-settings/mcp-server/mcp-tools.tsx b/packages/web/src/app/components/project-settings/mcp-server/mcp-tools.tsxindex e36a2db33bb..5999d78b4f6 100644--- a/packages/web/src/app/components/project-settings/mcp-server/mcp-tools.tsx+++ b/packages/web/src/app/components/project-settings/mcp-server/mcp-tools.tsx@@ -1,3 +1,4 @@+import { Permission } from '@activepieces/core-utils';import { ApFlagId } from '@activepieces/shared';import { t } from 'i18next';import { Lock } from 'lucide-react';@@ -10,28 +11,28 @@ import {AccordionItem,AccordionTrigger,} from '@/components/ui/accordion';+import { Badge } from '@/components/ui/badge';import { Checkbox } from '@/components/ui/checkbox';import {Tooltip,TooltipContent,TooltipTrigger,} from '@/components/ui/tooltip';+import { useAuthorization } from '@/hooks/authorization-hooks';import { flagsHooks } from '@/hooks/flags-hooks';import { cn } from '@/lib/utils';import { getToolCategories } from './utils/mcp-tools-metadata';-type McpToolsProps = {- disabledTools: string[] | null;- isPending: boolean;- onUpdateDisabledTools: (tools: string[]) => void;-};-export function McpTools({disabledTools: externalDisabledTools,+ platformDisabledTools = [],+ projectId,isPending,onUpdateDisabledTools,}: McpToolsProps) {+ const { checkAccess } = useAuthorization(projectId);+ const canWrite = checkAccess(Permission.WRITE_MCP);const { data: toolSearchEnabled } = flagsHooks.useFlag<boolean>(ApFlagId.TOOL_SEARCH_ENABLED,);@@ -53,6 +54,9 @@ export function McpTools({}, 300);const toggleTool = (name: string, checked: boolean) => {+ if (!canWrite) {+ return;+ }const next = checked? disabledTools.filter((n) => n !== name): [...disabledTools, name];@@ -61,6 +65,9 @@ export function McpTools({};const toggleCategory = (toolNames: string[], checked: boolean) => {+ if (!canWrite) {+ return;+ }const next = checked? disabledTools.filter((n) => !toolNames.includes(n)): [@@ -72,101 +79,143 @@ export function McpTools({};return (- <Accordion type="multiple" className="space-y-2">- {toolCategories.map((category) => {- const toolNames = category.tools.map((tool) => tool.name);- const enabledInCategory = category.locked- ? toolNames- : toolNames.filter((n) => !disabledTools.includes(n));- const allChecked = enabledInCategory.length === toolNames.length;- const someChecked =- enabledInCategory.length > 0 &&- enabledInCategory.length < toolNames.length;+ <div className="flex flex-col gap-2">+ {!canWrite && (+ <p className="text-xs text-muted-foreground">+ {t('You can see these tools, but your role cannot change them.')}+ </p>+ )}+ <Accordion type="multiple" className="space-y-2">+ {toolCategories.map((category) => {+ const toolNames = category.tools.map((tool) => tool.name);+ const isPlatformOff = (name: string) =>+ !category.locked && platformDisabledTools.includes(name);+ const editableNames = toolNames.filter((n) => !isPlatformOff(n));+ const enabledInCategory = category.locked+ ? toolNames+ : editableNames.filter((n) => !disabledTools.includes(n));+ const allChecked =+ editableNames.length > 0 &&+ enabledInCategory.length === editableNames.length;+ const someChecked =+ enabledInCategory.length > 0 &&+ enabledInCategory.length < editableNames.length;- return (- <AccordionItem key={category.label} value={category.label}>- <AccordionTrigger className="bg-muted/40 hover:no-underline">- <div className="flex items-center gap-3">- {category.locked ? (- <Tooltip>- <TooltipTrigger asChild>- <Lock className="h-4 w-4 text-muted-foreground shrink-0" />- </TooltipTrigger>- <TooltipContent>- {t('Required by other tools — always enabled')}- </TooltipContent>- </Tooltip>- ) : (- <Checkbox- checked={- allChecked ? true : someChecked ? 'indeterminate' : false- }- onCheckedChange={(v) =>- toggleCategory(toolNames, v === true)- }- onClick={(e) => e.stopPropagation()}- aria-label={t('Select all in {{category}}', {- category: category.label,- })}- />- )}- <span className="text-sm font-semibold">- {t(category.label)}- </span>- {category.locked && (- <span className="text-xs text-muted-foreground ml-1">- ({t('always enabled')})+ return (+ <AccordionItem key={category.label} value={category.label}>+ <AccordionTrigger className="bg-muted/40 hover:no-underline">+ <div className="flex items-center gap-3">+ {category.locked ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Lock className="h-4 w-4 text-muted-foreground shrink-0" />+ </TooltipTrigger>+ <TooltipContent>+ {t('Required by other tools — always enabled')}+ </TooltipContent>+ </Tooltip>+ ) : (+ <Checkbox+ checked={+ allChecked+ ? true+ : someChecked+ ? 'indeterminate'+ : false+ }+ disabled={!canWrite || editableNames.length === 0}+ onCheckedChange={(v) =>+ toggleCategory(editableNames, v === true)+ }+ onClick={(e) => e.stopPropagation()}+ aria-label={t('Select all in {{category}}', {+ category: category.label,+ })}+ />+ )}+ <span className="text-sm font-semibold">+ {t(category.label)}</span>- )}- <span className="text-xs text-muted-foreground">- {enabledInCategory.length}/{toolNames.length}- </span>- </div>- </AccordionTrigger>- <AccordionContent className="p-0 pl-6">- <div className="divide-y">- {category.tools.map((tool) => {- const isChecked =- category.locked || !disabledTools.includes(tool.name);- return (- <div- key={tool.name}- className="flex items-start gap-3 px-4 py-3"- >- {category.locked ? (- <div className="h-4 w-4 shrink-0 mt-0.5" />- ) : (- <Checkbox- id={tool.name}- checked={isChecked}- onCheckedChange={(v) =>- toggleTool(tool.name, v === true)- }- className="mt-0.5"- />- )}- <label- htmlFor={category.locked ? undefined : tool.name}- className={cn(- 'flex flex-col gap-0.5',- !category.locked && 'cursor-pointer',- )}+ {category.locked && (+ <span className="text-xs text-muted-foreground ml-1">+ ({t('always enabled')})+ </span>+ )}+ <span className="text-xs text-muted-foreground">+ {enabledInCategory.length}/{toolNames.length}+ </span>+ </div>+ </AccordionTrigger>+ <AccordionContent className="p-0 pl-6">+ <div className="divide-y">+ {category.tools.map((tool) => {+ const platformOff = isPlatformOff(tool.name);+ const isChecked =+ !platformOff &&+ (category.locked || !disabledTools.includes(tool.name));+ const isEditable =+ !category.locked && !platformOff && canWrite;+ return (+ <div+ key={tool.name}+ className="flex items-start gap-3 px-4 py-3">- <span className="text-sm font-mono font-medium">- {tool.name}- </span>- <span className="text-xs text-muted-foreground">- {tool.description}- </span>- </label>- </div>- );- })}- </div>- </AccordionContent>- </AccordionItem>- );- })}- </Accordion>+ {category.locked ? (+ <div className="h-4 w-4 shrink-0 mt-0.5" />+ ) : (+ <Checkbox+ id={tool.name}+ checked={isChecked}+ disabled={platformOff || !canWrite}+ onCheckedChange={(v) =>+ toggleTool(tool.name, v === true)+ }+ className="mt-0.5"+ />+ )}+ <label+ htmlFor={isEditable ? tool.name : undefined}+ className={cn(+ 'flex flex-col gap-0.5',+ isEditable && 'cursor-pointer',+ platformOff && 'opacity-60',+ )}+ >+ <span className="flex items-center gap-2">+ <span className="text-sm font-mono font-medium">+ {tool.name}+ </span>+ {platformOff && (+ <Badge variant="outline" className="font-normal">+ {t('Off for the whole platform')}+ </Badge>+ )}+ </span>+ <span className="text-xs text-muted-foreground">+ {platformOff+ ? t(+ 'A platform admin switched this off for the whole platform, so no client can call it here or on the platform MCP server.',+ )+ : tool.description}+ </span>+ </label>+ </div>+ );+ })}+ </div>+ </AccordionContent>+ </AccordionItem>+ );+ })}+ </Accordion>+ </div>);}++type McpToolsProps = {+ disabledTools: string[] | null;+ platformDisabledTools?: string[];+ projectId?: string;+ isPending: boolean;+ onUpdateDisabledTools: (tools: string[]) => void;+};diff --git a/packages/web/src/app/components/project-settings/mcp-server/utils/mcp-api.ts b/packages/web/src/app/components/project-settings/mcp-server/utils/mcp-api.tsindex 859b21363a5..659456b8bd1 100644--- a/packages/web/src/app/components/project-settings/mcp-server/utils/mcp-api.ts+++ b/packages/web/src/app/components/project-settings/mcp-server/utils/mcp-api.ts@@ -1,30 +1,35 @@import {- PopulatedMcpServer,+ McpReachResponse,+ ProjectMcpServerResponse,UpdateMcpServerRequest,} from '@activepieces/shared';import { api } from '@/lib/api';export const mcpApi = {- async get(projectId: string): Promise<PopulatedMcpServer> {- return await api.get<PopulatedMcpServer>(- `/v1/projects/${projectId}/mcp-server`,+ async reach(): Promise<McpReachResponse> {+ return await api.get<McpReachResponse>('/v1/mcp-server/reach');+ },++ async get(projectId: string): Promise<ProjectMcpServerResponse> {+ return await api.get<ProjectMcpServerResponse>(+ `/v1/projects/${encodeURIComponent(projectId)}/mcp-server`,);},async update(projectId: string,request: UpdateMcpServerRequest,- ): Promise<PopulatedMcpServer> {- return await api.post<PopulatedMcpServer>(- `/v1/projects/${projectId}/mcp-server`,+ ): Promise<ProjectMcpServerResponse> {+ return await api.post<ProjectMcpServerResponse>(+ `/v1/projects/${encodeURIComponent(projectId)}/mcp-server`,request,);},- async rotateToken(projectId: string): Promise<PopulatedMcpServer> {- return await api.post<PopulatedMcpServer>(- `/v1/projects/${projectId}/mcp-server/rotate`,+ async rotateToken(projectId: string): Promise<ProjectMcpServerResponse> {+ return await api.post<ProjectMcpServerResponse>(+ `/v1/projects/${encodeURIComponent(projectId)}/mcp-server/rotate`,);},};diff --git a/packages/web/src/app/components/project-settings/mcp-server/utils/mcp-hooks.ts b/packages/web/src/app/components/project-settings/mcp-server/utils/mcp-hooks.tsindex a8f200c3a30..56ca5f84096 100644--- a/packages/web/src/app/components/project-settings/mcp-server/utils/mcp-hooks.ts+++ b/packages/web/src/app/components/project-settings/mcp-server/utils/mcp-hooks.ts@@ -1,10 +1,36 @@+import { ErrorCode, isNil } from '@activepieces/core-utils';import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';+import { t } from 'i18next';+import { toast } from 'sonner';++import { isProjectAccessError } from '@/app/routes/mcp-server/project-access';+import { api } from '@/lib/api';import { mcpApi } from './mcp-api';export const MCP_SERVER_QUERY_KEY = ['mcp-server'];+const MCP_REACH_QUERY_KEY = ['mcp-reach'];+export const mcpHooks = {+ useMcpReach(options: { enabled?: boolean } = {}): McpReach {+ const enabled = options.enabled ?? true;+ const { data, error, isLoading } = useQuery({+ queryKey: MCP_REACH_QUERY_KEY,+ queryFn: () => mcpApi.reach(),+ retry: false,+ enabled,+ });++ const projectIds = data?.projectIds ?? null;+ return {+ projectIds,+ isResolved: enabled && !isLoading,+ reachesMcp:+ !isReachRefused(error) && (isNil(projectIds) || projectIds.length > 0),+ };+ },+useMcpServer(projectId: string, options: { enabled?: boolean } = {}) {return useQuery({queryKey: [...MCP_SERVER_QUERY_KEY, projectId],@@ -23,6 +49,13 @@ export const mcpHooks = {onSuccess: (data) => {queryClient.setQueryData([...MCP_SERVER_QUERY_KEY, projectId], data);},+ onError: (error: Error) => {+ toast.error(+ isProjectAccessError(error)+ ? t('You are not allowed to change the tools of this project.')+ : t('The tools could not be saved. Try again.'),+ );+ },});},@@ -37,3 +70,16 @@ export const mcpHooks = {});},};++function isReachRefused(error: Error | null): boolean {+ return (+ api.isApError(error, ErrorCode.AUTHORIZATION) ||+ api.isApError(error, ErrorCode.PERMISSION_DENIED)+ );+}++type McpReach = {+ projectIds: string[] | null;+ isResolved: boolean;+ reachesMcp: boolean;+};diff --git a/packages/web/src/app/routes/mcp-server/index.tsx b/packages/web/src/app/routes/mcp-server/index.tsxindex 828d22361fe..1668af1e091 100644--- a/packages/web/src/app/routes/mcp-server/index.tsx+++ b/packages/web/src/app/routes/mcp-server/index.tsx@@ -1,5 +1,7 @@+import { McpServerType } from '@activepieces/shared';import { t } from 'i18next';+import { mcpHooks } from '@/app/components/project-settings/mcp-server/utils/mcp-hooks';import { PageHeader } from '@/components/custom/page-header';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import { piecesHooks } from '@/features/pieces/hooks/pieces-hooks';@@ -10,11 +12,14 @@ import { GrantsTab } from './grants/grants-tab';import { useMcpNav } from './mcp-nav';import { useMcpServerUrl } from './mcp-server-url';import { PageBand } from './page-band';-import { PiecesTab } from './pieces/pieces-tab';+import { ToolsTab } from './tools/tools-tab';export default function McpServerPage() {- const { serverUrl, isReachableFromInternet } = useMcpServerUrl();+ const { serverUrl, isReachableFromInternet } = useMcpServerUrl({+ serverType: McpServerType.PLATFORM,+ });const nav = useMcpNav();+ const { projectIds: reachableProjectIds } = mcpHooks.useMcpReach();piecesHooks.usePrefetchPieces({ skipProjectFilter: true });return (@@ -27,8 +32,8 @@ export default function McpServerPage() {<TabsTrigger variant="outline" value="connect">{t('Connect')}</TabsTrigger>- <TabsTrigger variant="outline" value="pieces">- {t('Pieces')}+ <TabsTrigger variant="outline" value="tools">+ {t('Tools')}</TabsTrigger><TabsTrigger variant="outline" value="connections">{t('Connections')}@@ -41,10 +46,13 @@ export default function McpServerPage() {</PageBand></div><div className="w-full">- {nav.tab === 'pieces' ? (- <PiecesTab+ {nav.tab === 'tools' ? (+ <ToolsTabprojectId={nav.projectId}+ reachableProjectIds={reachableProjectIds}+ segment={nav.segment}onSelectProject={nav.selectProject}+ onSelectSegment={nav.selectSegment}/>) : nav.tab === 'connections' ? (<GrantsTab />diff --git a/packages/web/src/app/routes/mcp-server/legacy-pieces-redirect.tsx b/packages/web/src/app/routes/mcp-server/legacy-pieces-redirect.tsxnew file mode 100644index 00000000000..77354e07a08--- /dev/null+++ b/packages/web/src/app/routes/mcp-server/legacy-pieces-redirect.tsx@@ -0,0 +1,14 @@+import { Navigate, useSearchParams } from 'react-router-dom';++import { buildToolsParams } from './mcp-nav';++export function LegacyPiecesRedirect() {+ const [params] = useSearchParams();+ const search = new URLSearchParams(+ buildToolsParams({+ projectId: params.get('project'),+ segment: 'pieces',+ }),+ ).toString();+ return <Navigate to={`/mcp-server/tools?${search}`} replace />;+}diff --git a/packages/web/src/app/routes/mcp-server/mcp-nav.ts b/packages/web/src/app/routes/mcp-server/mcp-nav.tsindex 698bcbc7d70..6d7c16c4061 100644--- a/packages/web/src/app/routes/mcp-server/mcp-nav.ts+++ b/packages/web/src/app/routes/mcp-server/mcp-nav.ts@@ -1,38 +1,76 @@+import { ApId } from '@activepieces/core-utils';import { useNavigate, useParams, useSearchParams } from 'react-router-dom';import { authenticationSession } from '@/lib/authentication-session';-function toTab(value: string | undefined): McpTab {- return value === 'connections' || value === 'pieces' || value === 'activity'- ? value- : 'connect';-}-export function useMcpNav(): McpNav {const { tab } = useParams();const navigate = useNavigate();const [params, setParams] = useSearchParams();const clientKey = params.get('client');+ const projectParam = toProjectId(params.get('project'));+ const segment = toSegment(params.get('segment'));return {clientKey,+ segment,tab: toTab(tab),view: clientKey ? 'client' : params.has('browse') ? 'browse' : 'landing',- projectId: params.get('project') ?? authenticationSession.getProjectId(),+ projectId: projectParam ?? authenticationSession.getProjectId(),showLanding: () => setParams({}),showBrowse: () => setParams({ browse: '1' }),showClient: (key: string) => setParams({ client: key }),showTab: (value: string) => navigate(`/mcp-server/${toTab(value)}`),- selectProject: (projectId: string) => setParams({ project: projectId }),+ selectSegment: (value: string) =>+ setParams(+ buildToolsParams({+ projectId: projectParam,+ segment: toSegment(value),+ }),+ ),+ selectProject: (projectId: string) =>+ setParams(buildToolsParams({ projectId, segment })),};}-export type McpTab = 'connect' | 'pieces' | 'connections' | 'activity';+export function buildToolsParams({+ projectId,+ segment,+}: {+ projectId: string | null;+ segment: McpToolSegment;+}): Record<string, string> {+ return {+ ...(projectId === null ? {} : { project: projectId }),+ ...(segment === DEFAULT_SEGMENT ? {} : { segment }),+ };+}++function toTab(value: string | undefined): McpTab {+ return value === 'connections' || value === 'tools' || value === 'activity'+ ? value+ : 'connect';+}++function toSegment(value: string | null): McpToolSegment {+ return value === 'pieces' ? value : DEFAULT_SEGMENT;+}++function toProjectId(value: string | null): string | null {+ return ApId.safeParse(value).success ? value : null;+}++const DEFAULT_SEGMENT: McpToolSegment = 'built-in';++export type McpTab = 'connect' | 'tools' | 'connections' | 'activity';++export type McpToolSegment = 'built-in' | 'pieces';export type McpView = 'landing' | 'browse' | 'client';export type McpNav = {tab: McpTab;+ segment: McpToolSegment;view: McpView;clientKey: string | null;projectId: string | null;@@ -40,5 +78,6 @@ export type McpNav = {showBrowse: () => void;showClient: (key: string) => void;showTab: (value: string) => void;+ selectSegment: (value: string) => void;selectProject: (projectId: string) => void;};diff --git a/packages/web/src/app/routes/mcp-server/mcp-reach-guard.tsx b/packages/web/src/app/routes/mcp-server/mcp-reach-guard.tsxnew file mode 100644index 00000000000..1c5d7c31a9d--- /dev/null+++ b/packages/web/src/app/routes/mcp-server/mcp-reach-guard.tsx@@ -0,0 +1,16 @@+import { ReactNode } from 'react';+import { Navigate } from 'react-router-dom';++import { mcpHooks } from '@/app/components/project-settings/mcp-server/utils/mcp-hooks';++export function McpReachGuard({ children }: { children: ReactNode }) {+ const { isResolved, reachesMcp } = mcpHooks.useMcpReach();++ if (!isResolved) {+ return null;+ }+ if (!reachesMcp) {+ return <Navigate to="/404" replace />;+ }+ return children;+}diff --git a/packages/web/src/app/routes/mcp-server/mcp-server-url.ts b/packages/web/src/app/routes/mcp-server/mcp-server-url.tsindex 57fed97c62c..cd4786de223 100644--- a/packages/web/src/app/routes/mcp-server/mcp-server-url.ts+++ b/packages/web/src/app/routes/mcp-server/mcp-server-url.ts@@ -1,16 +1,21 @@-import { ApFlagId } from '@activepieces/shared';+import { ApFlagId, McpServerType } from '@activepieces/shared';import { flagsHooks } from '@/hooks/flags-hooks';import { formatUtils } from '@/lib/format-utils';-export function useMcpServerUrl(): {+export function useMcpServerUrl({+ serverType,+}: {+ serverType: McpServerType;+}): {serverUrl: string;isReachableFromInternet: boolean;} {const { data: publicUrl } = flagsHooks.useFlag<string>(ApFlagId.PUBLIC_URL);const base = (publicUrl ?? '').replace(/\/$/, '');+ const path = serverType === McpServerType.PLATFORM ? '/mcp/platform' : '/mcp';return {- serverUrl: `${base}/mcp`,+ serverUrl: `${base}${path}`,isReachableFromInternet: formatUtils.urlIsPubliclyReachable(base),};}diff --git a/packages/web/src/app/routes/mcp-server/pieces-showcase.tsx b/packages/web/src/app/routes/mcp-server/pieces-showcase.tsxindex 44ea96e842d..809aea9e0ae 100644--- a/packages/web/src/app/routes/mcp-server/pieces-showcase.tsx+++ b/packages/web/src/app/routes/mcp-server/pieces-showcase.tsx@@ -29,9 +29,9 @@ export function PiecesShowcase() {</h2><p className="max-w-[560px] text-sm text-muted-foreground">{isLoading- ? t('Every piece you can use, plus every flow you’ve built.')+ ? t('Every piece you can use, in every project MCP reaches.'): t(- '{count} pieces, plus every flow you’ve built — ready to run.',+ '{count} pieces, ready to run in every project MCP reaches.',{ count: tiles.length },)}</p>diff --git a/packages/web/src/app/routes/mcp-server/pieces/pieces-tab.tsx b/packages/web/src/app/routes/mcp-server/pieces/pieces-panel.tsxsimilarity index 63%rename from packages/web/src/app/routes/mcp-server/pieces/pieces-tab.tsxrename to packages/web/src/app/routes/mcp-server/pieces/pieces-panel.tsxindex 5f39df65e2b..1a116874ca8 100644--- a/packages/web/src/app/routes/mcp-server/pieces/pieces-tab.tsx+++ b/packages/web/src/app/routes/mcp-server/pieces/pieces-panel.tsx@@ -1,4 +1,3 @@-import { ErrorCode } from '@activepieces/core-utils';import { isNil, SuggestionType } from '@activepieces/shared';import { t } from 'i18next';import { ExternalLink, Info, TriangleAlert } from 'lucide-react';@@ -6,10 +5,7 @@ import { useMemo, useState } from 'react';import { Link } from 'react-router-dom';import { useDebounce } from 'use-debounce';-import { ProjectSettingsDialog } from '@/app/components/project-settings';-import { mcpHooks } from '@/app/components/project-settings/mcp-server/utils/mcp-hooks';import { LockedAlert } from '@/components/custom/locked-alert';-import { SearchInput } from '@/components/custom/search-input';import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';import { Button } from '@/components/ui/button';import { Skeleton } from '@/components/ui/skeleton';@@ -20,23 +16,27 @@ import { piecesHooks } from '@/features/pieces/hooks/pieces-hooks';import { projectCollectionUtils } from '@/features/projects';import { useIsPlatformAdmin } from '@/hooks/authorization-hooks';import { platformHooks } from '@/hooks/platform-hooks';-import { api } from '@/lib/api';-import { authenticationSession } from '@/lib/authentication-session';-import { PageBand } from '../page-band';+import {+ isProjectAccessError,+ ProjectAccessDeniedAlert,+} from '../project-access';import { PieceRow } from './piece-row';import { piecesUtils } from './pieces-utils';-import { ProjectPicker } from './project-picker';-const RUN_ACTION_TOOL_NAME = 'ap_run_action';const COLLAPSED_ROW_LIMIT = 6;const COLLAPSED_ROW_HEIGHT = 50;const PIECE_SETS_LIST_ROUTE = '/platform/pieces/piece-sets';const SEARCH_DEBOUNCE_MS = 300;-export function PiecesTab({ projectId, onSelectProject }: PiecesTabProps) {- const [searchQuery, setSearchQuery] = useState('');+export function PiecesPanel({+ projectId,+ searchQuery,+ isRunActionDisabled,+ isRunActionDisabledByPlatform,+ onShowBuiltIn,+}: PiecesPanelProps) {const [debouncedSearchQuery] = useDebounce(searchQuery.trim(),SEARCH_DEBOUNCE_MS,@@ -51,8 +51,6 @@ export function PiecesTab({ projectId, onSelectProject }: PiecesTabProps) {enabled: !isNil(projectId),keepPreviousResults: true,});- const { data: mcpServer } = mcpHooks.useMcpServer(projectId ?? '');-const rows = useMemo(() =>piecesUtils.toReachablePieces({@@ -68,37 +66,15 @@ export function PiecesTab({ projectId, onSelectProject }: PiecesTabProps) {const hiddenCount = rows.length - visibleRows.length;return (- <PageBand className="flex flex-col gap-6 py-8">- <div className="flex flex-col gap-1.5">- <h2 className="text-xl font-bold leading-7 tracking-tight">- {t(- 'Every piece a connected client can reach, and every action inside it.',- )}- </h2>- <p className="text-sm text-muted-foreground">- {t(- 'This page is a mirror — a platform admin decides what is on the list.',- )}- </p>- </div>-+ <div className="flex flex-col gap-4"><PieceSetBanner projectId={projectId} />- {projectId !== null &&- mcpServer?.disabledTools?.includes(RUN_ACTION_TOOL_NAME) && (- <RunActionDisabledAlert projectId={projectId} />- )}-- <div className="flex flex-wrap items-center gap-3">- <ProjectPicker projectId={projectId} onSelect={onSelectProject} />- <div className="w-full max-w-[420px]">- <SearchInput- value={searchQuery}- onChange={setSearchQuery}- placeholder={t('Search pieces and actions...')}- />- </div>- </div>+ {(isRunActionDisabled || isRunActionDisabledByPlatform) && (+ <RunActionDisabledAlert+ isDisabledByPlatform={isRunActionDisabledByPlatform}+ onShowBuiltIn={onShowBuiltIn}+ />+ )}{isLoading ? (<div className="flex flex-col gap-2">@@ -138,7 +114,7 @@ export function PiecesTab({ projectId, onSelectProject }: PiecesTabProps) {)}</div>)}- </PageBand>+ </div>);}@@ -147,17 +123,7 @@ function PiecesUnavailableAlert({onRetry,}: PiecesUnavailableAlertProps) {if (isProjectAccessError(error)) {- return (- <Alert variant="destructive">- <TriangleAlert />- <AlertTitle>{t('You cannot see this project')}</AlertTitle>- <AlertDescription>- {t(- 'Pick another project above, or ask a platform admin for access to this one.',- )}- </AlertDescription>- </Alert>- );+ return <ProjectAccessDeniedAlert />;}return (@@ -181,37 +147,37 @@ function PiecesUnavailableAlert({);}-function RunActionDisabledAlert({ projectId }: { projectId: string }) {- const [settingsOpen, setSettingsOpen] = useState(false);- const isCurrentProject = authenticationSession.getProjectId() === projectId;-+function RunActionDisabledAlert({+ isDisabledByPlatform,+ onShowBuiltIn,+}: {+ isDisabledByPlatform: boolean;+ onShowBuiltIn: () => void;+}) {return (- <>- <Alert variant="warning">- <TriangleAlert />- <AlertTitle>{t('Nothing below can run right now')}</AlertTitle>- <AlertDescription>- {t(- 'Running piece actions is switched off for this project. Clients can still see the list, but every call fails.',- )}- </AlertDescription>- {isCurrentProject && (- <Button- variant="outline"- size="sm"- className="col-start-2 mt-3 w-fit"- onClick={() => setSettingsOpen(true)}- >- {t('Turn it on in project settings')}- </Button>- )}- </Alert>- <ProjectSettingsDialog- open={settingsOpen}- onClose={() => setSettingsOpen(false)}- initialTab="mcp"- />- </>+ <Alert variant="warning">+ <TriangleAlert />+ <AlertTitle>{t('Nothing below can run right now')}</AlertTitle>+ <AlertDescription>+ {isDisabledByPlatform+ ? t(+ 'A platform admin switched Run action off for the whole platform. Clients can still see the list, but every call fails.',+ )+ : t(+ 'Running piece actions is switched off for this project. Clients can still see the list, but every call fails.',+ )}+ </AlertDescription>+ {!isDisabledByPlatform && (+ <Button+ variant="outline"+ size="sm"+ className="col-start-2 mt-3 w-fit"+ onClick={onShowBuiltIn}+ >+ {t('Turn on Run action')}+ </Button>+ )}+ </Alert>);}@@ -273,20 +239,15 @@ function PieceSetBanner({ projectId }: { projectId: string | null }) {);}-function isProjectAccessError(error: Error | null): boolean {- return (- api.isApError(error, ErrorCode.AUTHORIZATION) ||- api.isApError(error, ErrorCode.PERMISSION_DENIED) ||- api.isApError(error, ErrorCode.ENTITY_NOT_FOUND)- );-}-type PiecesUnavailableAlertProps = {error: Error | null;onRetry: () => void;};-type PiecesTabProps = {+type PiecesPanelProps = {projectId: string | null;- onSelectProject: (projectId: string) => void;+ searchQuery: string;+ isRunActionDisabled: boolean;+ isRunActionDisabledByPlatform: boolean;+ onShowBuiltIn: () => void;};diff --git a/packages/web/src/app/routes/mcp-server/pieces/pieces-utils.ts b/packages/web/src/app/routes/mcp-server/pieces/pieces-utils.tsindex d8af6487c38..df44cd6465f 100644--- a/packages/web/src/app/routes/mcp-server/pieces/pieces-utils.ts+++ b/packages/web/src/app/routes/mcp-server/pieces/pieces-utils.ts@@ -64,16 +64,26 @@ function toReachablePieces({pieces: PieceMetadataModelSummary[];isSearching: boolean;}): ReachablePiece[] {- const piecesWithActions = pieces.filter(- (piece) => (piece.suggestedActions ?? []).length > 0,- );+ const piecesWithActions = pieces.filter(hasSuggestedActions);const orderedPieces = isSearching? piecesWithActions: orderPopularFirst(piecesWithActions);return orderedPieces.map((piece) => toReachablePiece({ piece, isSearching }));}-export const piecesUtils = { toReachablePieces };+function countReachablePieces({+ pieces,+}: {+ pieces: PieceMetadataModelSummary[];+}): number {+ return pieces.filter(hasSuggestedActions).length;+}++function hasSuggestedActions(piece: PieceMetadataModelSummary): boolean {+ return (piece.suggestedActions ?? []).length > 0;+}++export const piecesUtils = { toReachablePieces, countReachablePieces };export type ActionGroup = {classification: ActionClassification;diff --git a/packages/web/src/app/routes/mcp-server/project-access.tsx b/packages/web/src/app/routes/mcp-server/project-access.tsxnew file mode 100644index 00000000000..3d55b81338b--- /dev/null+++ b/packages/web/src/app/routes/mcp-server/project-access.tsx@@ -0,0 +1,28 @@+import { ErrorCode } from '@activepieces/core-utils';+import { t } from 'i18next';+import { TriangleAlert } from 'lucide-react';++import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';+import { api } from '@/lib/api';++export function isProjectAccessError(error: Error | null): boolean {+ return (+ api.isApError(error, ErrorCode.AUTHORIZATION) ||+ api.isApError(error, ErrorCode.PERMISSION_DENIED) ||+ api.isApError(error, ErrorCode.ENTITY_NOT_FOUND)+ );+}++export function ProjectAccessDeniedAlert() {+ return (+ <Alert variant="destructive">+ <TriangleAlert />+ <AlertTitle>{t('You cannot see this project')}</AlertTitle>+ <AlertDescription>+ {t(+ 'Pick another project above, or ask a platform admin for access to this one.',+ )}+ </AlertDescription>+ </Alert>+ );+}diff --git a/packages/web/src/app/routes/mcp-server/pieces/project-picker.tsx b/packages/web/src/app/routes/mcp-server/project-picker.tsxsimilarity index 84%rename from packages/web/src/app/routes/mcp-server/pieces/project-picker.tsxrename to packages/web/src/app/routes/mcp-server/project-picker.tsxindex 02055d3ea58..8ef79082311 100644--- a/packages/web/src/app/routes/mcp-server/pieces/project-picker.tsx+++ b/packages/web/src/app/routes/mcp-server/project-picker.tsx@@ -1,3 +1,4 @@+import { isNil } from '@activepieces/shared';import { t } from 'i18next';import { Check, ChevronDown } from 'lucide-react';@@ -17,11 +18,19 @@ import { cn } from '@/lib/utils';type ProjectPickerProps = {projectId: string | null;+ allowedProjectIds?: string[] | null;onSelect: (projectId: string) => void;};-export function ProjectPicker({ projectId, onSelect }: ProjectPickerProps) {- const { data: projects = [] } = projectCollectionUtils.useAll();+export function ProjectPicker({+ projectId,+ allowedProjectIds,+ onSelect,+}: ProjectPickerProps) {+ const { data: allProjects = [] } = projectCollectionUtils.useAll();+ const projects = isNil(allowedProjectIds)+ ? allProjects+ : allProjects.filter((project) => allowedProjectIds.includes(project.id));const selectedProject = projects.find((project) => project.id === projectId);return (diff --git a/packages/web/src/app/routes/mcp-server/tools/project-selection.ts b/packages/web/src/app/routes/mcp-server/tools/project-selection.tsnew file mode 100644index 00000000000..2b42f97ac7d--- /dev/null+++ b/packages/web/src/app/routes/mcp-server/tools/project-selection.ts@@ -0,0 +1,19 @@+import { isNil } from '@activepieces/shared';++function resolveSelected({+ projectId,+ reachableProjectIds,+}: {+ projectId: string | null;+ reachableProjectIds: string[] | null;+}): string | null {+ if (isNil(reachableProjectIds) || reachableProjectIds.length === 0) {+ return projectId;+ }+ if (!isNil(projectId) && reachableProjectIds.includes(projectId)) {+ return projectId;+ }+ return reachableProjectIds[0];+}++export const reachableProjectUtils = { resolveSelected };diff --git a/packages/web/src/app/routes/mcp-server/tools/tools-tab.tsx b/packages/web/src/app/routes/mcp-server/tools/tools-tab.tsxnew file mode 100644index 00000000000..9aa43c500bb--- /dev/null+++ b/packages/web/src/app/routes/mcp-server/tools/tools-tab.tsx@@ -0,0 +1,183 @@+import { ApFlagId, isNil, SuggestionType } from '@activepieces/shared';+import { t } from 'i18next';+import { useMemo, useState } from 'react';++import { McpTools } from '@/app/components/project-settings/mcp-server/mcp-tools';+import { mcpHooks } from '@/app/components/project-settings/mcp-server/utils/mcp-hooks';+import { getToolCategories } from '@/app/components/project-settings/mcp-server/utils/mcp-tools-metadata';+import { DataFetchErrorState } from '@/components/custom/data-fetch-error-state';+import { SearchInput } from '@/components/custom/search-input';+import { Skeleton } from '@/components/ui/skeleton';+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';+import { piecesHooks } from '@/features/pieces/hooks/pieces-hooks';+import { flagsHooks } from '@/hooks/flags-hooks';++import { McpToolSegment } from '../mcp-nav';+import { PageBand } from '../page-band';+import { PiecesPanel } from '../pieces/pieces-panel';+import { piecesUtils } from '../pieces/pieces-utils';+import {+ isProjectAccessError,+ ProjectAccessDeniedAlert,+} from '../project-access';+import { ProjectPicker } from '../project-picker';++import { reachableProjectUtils } from './project-selection';++const RUN_ACTION_TOOL_NAME = 'ap_run_action';+const SKELETON_ROW_COUNT = 5;++export function ToolsTab({+ projectId,+ reachableProjectIds,+ segment,+ onSelectProject,+ onSelectSegment,+}: ToolsTabProps) {+ const [searchQuery, setSearchQuery] = useState('');+ const selectedProjectId = reachableProjectUtils.resolveSelected({+ projectId,+ reachableProjectIds,+ });+ const {+ data: mcpServer,+ isLoading,+ isError,+ error,+ refetch,+ } = mcpHooks.useMcpServer(selectedProjectId ?? '');+ const { mutate: updateMcpServer, isPending } = mcpHooks.useUpdateMcpServer(+ selectedProjectId ?? '',+ );+ const { data: toolSearchEnabled } = flagsHooks.useFlag<boolean>(+ ApFlagId.TOOL_SEARCH_ENABLED,+ );+ const { pieces } = piecesHooks.usePieces({+ projectId: selectedProjectId ?? undefined,+ suggestionType: SuggestionType.ACTION,+ enabled: !isNil(selectedProjectId),+ });++ const builtInCount = useMemo(+ () =>+ getToolCategories({+ toolSearchEnabled: toolSearchEnabled ?? false,+ }).reduce((total, category) => total + category.tools.length, 0),+ [toolSearchEnabled],+ );+ const pieceCount = useMemo(+ () => (isNil(pieces) ? null : piecesUtils.countReachablePieces({ pieces })),+ [pieces],+ );++ const selectSegment = (value: string) => {+ setSearchQuery('');+ onSelectSegment(value);+ };++ const updateDisabledTools = (disabledTools: string[]) =>+ updateMcpServer({ disabledTools });++ return (+ <PageBand className="flex flex-col gap-6 py-8">+ <div className="flex flex-col gap-1.5">+ <h2 className="text-xl font-bold leading-7 tracking-tight">+ {t('Everything a connected client can call in this project.')}+ </h2>+ <p className="text-sm text-muted-foreground">+ {t(+ 'Built-in tools are switched on and off here. Pieces are controlled in piece sets.',+ )}+ </p>+ </div>++ <div className="flex flex-wrap items-center gap-3">+ <ProjectPicker+ projectId={selectedProjectId}+ allowedProjectIds={reachableProjectIds}+ onSelect={onSelectProject}+ />+ <Tabs value={segment} onValueChange={selectSegment}>+ <TabsList>+ <TabsTrigger value="built-in">+ {t('Built-in')}+ <SegmentCount count={builtInCount} />+ </TabsTrigger>+ <TabsTrigger value="pieces">+ {t('Pieces')}+ <SegmentCount count={pieceCount} />+ </TabsTrigger>+ </TabsList>+ </Tabs>+ {segment === 'pieces' && (+ <div className="w-full max-w-[360px]">+ <SearchInput+ value={searchQuery}+ onChange={setSearchQuery}+ placeholder={t('Search pieces and actions...')}+ />+ </div>+ )}+ </div>++ {isLoading ? (+ <div className="flex flex-col gap-2">+ {Array.from({ length: SKELETON_ROW_COUNT }).map((_, index) => (+ <Skeleton key={index} className="h-12 w-full" />+ ))}+ </div>+ ) : isError ? (+ <ToolsUnavailableAlert error={error} onRetry={refetch} />+ ) : isNil(mcpServer) ? null : segment === 'pieces' ? (+ <PiecesPanel+ projectId={selectedProjectId}+ searchQuery={searchQuery}+ isRunActionDisabled={(mcpServer.disabledTools ?? []).includes(+ RUN_ACTION_TOOL_NAME,+ )}+ isRunActionDisabledByPlatform={mcpServer.platformDisabledTools.includes(+ RUN_ACTION_TOOL_NAME,+ )}+ onShowBuiltIn={() => selectSegment('built-in')}+ />+ ) : (+ <McpTools+ key={selectedProjectId}+ disabledTools={mcpServer.disabledTools}+ platformDisabledTools={mcpServer.platformDisabledTools}+ projectId={selectedProjectId ?? undefined}+ isPending={isPending}+ onUpdateDisabledTools={updateDisabledTools}+ />+ )}+ </PageBand>+ );+}++function SegmentCount({ count }: { count: number | null }) {+ if (isNil(count)) {+ return null;+ }+ return <span className="ml-1.5 text-xs text-muted-foreground">{count}</span>;+}++function ToolsUnavailableAlert({ error, onRetry }: ToolsUnavailableAlertProps) {+ if (isProjectAccessError(error)) {+ return <ProjectAccessDeniedAlert />;+ }++ return <DataFetchErrorState entity={t('tools')} onRetry={onRetry} />;+}++type ToolsUnavailableAlertProps = {+ error: Error | null;+ onRetry: () => void;+};++type ToolsTabProps = {+ projectId: string | null;+ reachableProjectIds: string[] | null;+ segment: McpToolSegment;+ onSelectProject: (projectId: string) => void;+ onSelectSegment: (segment: string) => void;+};diff --git a/packages/web/src/app/routes/platform/setup/mcp/index.tsx b/packages/web/src/app/routes/platform/setup/mcp/index.tsxindex 3de1c5e27b8..e27863fc0ec 100644--- a/packages/web/src/app/routes/platform/setup/mcp/index.tsx+++ b/packages/web/src/app/routes/platform/setup/mcp/index.tsx@@ -110,7 +110,7 @@ export default function PlatformMcpPage({ section }: PlatformMcpPageProps) {</h3><p className="text-sm text-muted-foreground mb-3">{t(- 'Control which built-in tools are available to the AI Chat and external agents via the platform MCP server.',+ 'Switching a tool off here switches it off everywhere on this platform: the AI Chat, external agents, and every project MCP server.',)}</p><McpToolsdiff --git a/packages/web/src/app/routes/project-routes.tsx b/packages/web/src/app/routes/project-routes.tsxindex 54f3d12ec0f..391a9d71ceb 100644--- a/packages/web/src/app/routes/project-routes.tsx+++ b/packages/web/src/app/routes/project-routes.tsx@@ -18,6 +18,8 @@ import { ProjectRouterWrapper } from '../guards/project-route-wrapper';import { ApprovalsPage } from './approvals';import { AutomationsPage } from './automations';+import { LegacyPiecesRedirect } from './mcp-server/legacy-pieces-redirect';+import { McpReachGuard } from './mcp-server/mcp-reach-guard';const AgentEditorPage = lazyWithRetry(() => import('./agents/id').then((m) => ({ default: m.AgentEditorPage })),@@ -287,17 +289,21 @@ export const projectRoutes = [</ProjectDashboardLayout>),},+ {+ path: '/mcp-server/pieces',+ element: <LegacyPiecesRedirect />,+ },{path: '/mcp-server/:tab?',element: (<ProjectDashboardLayout>- <RoutePermissionGuard requiredPermissions={[Permission.READ_MCP]}>+ <McpReachGuard><PageTitle title="MCP Server"><SuspenseWrapper><McpServerPage /></SuspenseWrapper></PageTitle>- </RoutePermissionGuard>+ </McpReachGuard></ProjectDashboardLayout>),},diff --git a/packages/web/test/app/components/project-settings/mcp-server/mcp-tools.test.tsx b/packages/web/test/app/components/project-settings/mcp-server/mcp-tools.test.tsxnew file mode 100644index 00000000000..195def22767--- /dev/null+++ b/packages/web/test/app/components/project-settings/mcp-server/mcp-tools.test.tsx@@ -0,0 +1,315 @@+/**+ * @vitest-environment jsdom+ */+/* eslint-disable @typescript-eslint/no-explicit-any */+/* eslint-disable testing-library/no-unnecessary-act */+/* eslint-disable jest-dom/prefer-to-have-text-content -- @testing-library/jest-dom is not a dependency of packages/web */+import { Permission } from '@activepieces/core-utils';+import * as React from 'react';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const authorization = vi.hoisted(() => {+ const grantedPermissions: string[] = [];+ return { grantedPermissions, useAuthorization: vi.fn() };+});++vi.mock('i18next', () => ({ t: (key: string) => key }));++vi.mock('@/hooks/authorization-hooks', () => ({+ useAuthorization: (projectId?: string) => {+ authorization.useAuthorization(projectId);+ return {+ checkAccess: (permission: string) =>+ authorization.grantedPermissions.includes(permission),+ };+ },+}));++vi.mock('@/hooks/flags-hooks', () => ({+ flagsHooks: { useFlag: () => ({ data: false }) },+}));++vi.mock('use-debounce', () => ({+ useDebouncedCallback: (fn: (...args: any[]) => void) => fn,+}));++vi.mock('@/components/ui/accordion', () => ({+ Accordion: ({ children }: any) => <div>{children}</div>,+ AccordionItem: ({ children }: any) => <div>{children}</div>,+ AccordionTrigger: ({ children }: any) => <div>{children}</div>,+ AccordionContent: ({ children }: any) => <div>{children}</div>,+}));++vi.mock('@/components/ui/tooltip', () => ({+ Tooltip: ({ children }: any) => <div>{children}</div>,+ TooltipTrigger: ({ children }: any) => <div>{children}</div>,+ TooltipContent: ({ children }: any) => <div>{children}</div>,+}));++vi.mock('@/components/ui/badge', () => ({+ Badge: ({ children }: any) => <span data-badge="true">{children}</span>,+}));++vi.mock('@/components/ui/checkbox', () => ({+ Checkbox: ({ id, checked, disabled, onCheckedChange }: any) => (+ <input+ type="checkbox"+ data-tool={id ?? 'category'}+ data-state={checked === 'indeterminate' ? 'indeterminate' : undefined}+ checked={checked === true}+ disabled={disabled === true}+ onChange={(event) => onCheckedChange?.(event.target.checked)}+ readOnly+ />+ ),+}));++const { McpTools } = await import(+ '@/app/components/project-settings/mcp-server/mcp-tools'+);++declare global {+ // eslint-disable-next-line no-var+ var IS_REACT_ACT_ENVIRONMENT: boolean;+}++globalThis.IS_REACT_ACT_ENVIRONMENT = true;++const PROJECT_ID = 'project-1';+const PLATFORM_OFF_TOOL = 'ap_delete_flow';+const PROJECT_OFF_TOOL = 'ap_create_flow';+const LOCKED_TOOL = 'ap_list_flows';+const FLOW_MANAGEMENT_TOOLS = [+ 'ap_create_flow',+ 'ap_duplicate_flow',+ 'ap_rename_flow',+ 'ap_change_flow_status',+ 'ap_delete_flow',+ 'ap_lock_and_publish',+];+const READ_ONLY_NOTE =+ 'You can see these tools, but your role cannot change them.';++let container: HTMLDivElement;+let root: Root;++function render({+ canWrite = true,+ ...props+}: Partial<Parameters<typeof McpTools>[0]> & { canWrite?: boolean } = {}) {+ authorization.grantedPermissions = canWrite+ ? [Permission.READ_MCP, Permission.WRITE_MCP]+ : [Permission.READ_MCP];+ act(() => {+ root.render(+ <McpTools+ disabledTools={[]}+ projectId={PROJECT_ID}+ isPending={false}+ onUpdateDisabledTools={() => undefined}+ {...props}+ />,+ );+ });+}++function checkboxes(): HTMLInputElement[] {+ return Array.from(container.querySelectorAll('input[type="checkbox"]'));+}++function checkboxFor(toolName: string): HTMLInputElement | null {+ return container.querySelector(`input[data-tool="${toolName}"]`);+}++function flowManagementCheckbox(): HTMLInputElement {+ const element = container.querySelector<HTMLInputElement>(+ 'input[data-tool="category"]',+ );+ if (!element) {+ throw new Error('no category checkbox');+ }+ return element;+}++function flowManagementCount(): string | undefined {+ const label = Array.from(container.querySelectorAll('span')).find(+ (span) => span.textContent === 'Flow Management',+ );+ return label?.nextElementSibling?.textContent ?? undefined;+}++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ authorization.useAuthorization.mockClear();+});++describe('McpTools write gate', () => {+ it('checks write access against the project it edits', () => {+ render();++ expect(authorization.useAuthorization).toHaveBeenCalledWith(PROJECT_ID);+ });++ it('leaves every checkbox editable when the role can write', () => {+ render();++ expect(checkboxes().length).toBeGreaterThan(0);+ expect(checkboxes().every((box) => box.disabled)).toBe(false);+ });++ it('disables every checkbox when the role cannot write', () => {+ render({ canWrite: false });++ expect(checkboxes().length).toBeGreaterThan(0);+ expect(checkboxes().every((box) => box.disabled)).toBe(true);+ });++ it('does not save when a read-only role toggles a tool', () => {+ const onUpdateDisabledTools = vi.fn();+ render({ canWrite: false, onUpdateDisabledTools });++ act(() => {+ checkboxFor(PROJECT_OFF_TOOL)!.click();+ });++ expect(onUpdateDisabledTools).not.toHaveBeenCalled();+ expect(checkboxFor(PROJECT_OFF_TOOL)!.checked).toBe(true);+ });++ it('saves when a writing role toggles a tool', () => {+ const onUpdateDisabledTools = vi.fn();+ render({ onUpdateDisabledTools });++ act(() => {+ checkboxFor(PROJECT_OFF_TOOL)!.click();+ });++ expect(onUpdateDisabledTools).toHaveBeenCalledWith([PROJECT_OFF_TOOL]);+ });++ it('tells a read-only role why the tools cannot change', () => {+ render({ canWrite: false });++ expect(container.textContent).toContain(READ_ONLY_NOTE);+ });++ it('stays silent about the role when it can write', () => {+ render();++ expect(container.textContent).not.toContain(READ_ONLY_NOTE);+ });+});++describe('McpTools, when the platform switched a tool off', () => {+ it('shows the tool as off and refuses to let anyone turn it on', () => {+ render({ platformDisabledTools: [PLATFORM_OFF_TOOL] });++ const checkbox = checkboxFor(PLATFORM_OFF_TOOL);+ expect(checkbox).not.toBeNull();+ expect(checkbox!.checked).toBe(false);+ expect(checkbox!.disabled).toBe(true);+ });++ it('says who switched it off, so nobody hunts for the project switch', () => {+ render({ platformDisabledTools: [PLATFORM_OFF_TOOL] });++ expect(container.textContent).toContain('Off for the whole platform');+ });++ it('leaves every other tool editable', () => {+ render({ platformDisabledTools: [PLATFORM_OFF_TOOL] });++ const checkbox = checkboxFor(PROJECT_OFF_TOOL);+ expect(checkbox!.disabled).toBe(false);+ expect(checkbox!.checked).toBe(true);+ });++ it('keeps a project-switched-off tool editable, so it can be turned back on', () => {+ render({ disabledTools: [PROJECT_OFF_TOOL] });++ const checkbox = checkboxFor(PROJECT_OFF_TOOL);+ expect(checkbox!.checked).toBe(false);+ expect(checkbox!.disabled).toBe(false);+ });++ it('never switches a locked tool off, whatever the platform list says', () => {+ render({ platformDisabledTools: [LOCKED_TOOL] });++ expect(checkboxFor(LOCKED_TOOL)).toBeNull();+ expect(container.textContent).toContain(LOCKED_TOOL);+ });++ it('shows the category as on when every tool the project controls is on, and counts every tool', () => {+ render({ platformDisabledTools: [PLATFORM_OFF_TOOL] });++ const category = flowManagementCheckbox();+ expect(category.checked).toBe(true);+ expect(category.getAttribute('data-state')).toBeNull();+ expect(flowManagementCount()).toBe(+ `${FLOW_MANAGEMENT_TOOLS.length - 1}/${FLOW_MANAGEMENT_TOOLS.length}`,+ );+ });++ it('switches the editable tools off from a checked category', () => {+ const saved: string[][] = [];+ render({+ platformDisabledTools: [PLATFORM_OFF_TOOL],+ onUpdateDisabledTools: (tools: string[]) => saved.push(tools),+ });++ act(() => {+ flowManagementCheckbox().click();+ });++ expect(saved).toHaveLength(1);+ expect([...saved[0]].sort()).toEqual(+ FLOW_MANAGEMENT_TOOLS.filter((name) => name !== PLATFORM_OFF_TOOL).sort(),+ );+ });++ it('switches the editable tools on from a partly-on category', () => {+ const saved: string[][] = [];+ render({+ disabledTools: [PROJECT_OFF_TOOL],+ platformDisabledTools: [PLATFORM_OFF_TOOL],+ onUpdateDisabledTools: (tools: string[]) => saved.push(tools),+ });++ expect(flowManagementCheckbox().getAttribute('data-state')).toBe(+ 'indeterminate',+ );+ act(() => {+ flowManagementCheckbox().click();+ });++ expect(saved).toEqual([[]]);+ });++ it('locks the category when the platform switched all of its tools off', () => {+ render({ platformDisabledTools: FLOW_MANAGEMENT_TOOLS });++ expect(flowManagementCheckbox().disabled).toBe(true);+ expect(flowManagementCount()).toBe(`0/${FLOW_MANAGEMENT_TOOLS.length}`);+ });++ it('does not write the platform tool into the project list when a category is turned on', () => {+ const saved: string[][] = [];+ render({+ disabledTools: [PLATFORM_OFF_TOOL, PROJECT_OFF_TOOL],+ platformDisabledTools: [PLATFORM_OFF_TOOL],+ onUpdateDisabledTools: (tools: string[]) => saved.push(tools),+ });++ act(() => {+ flowManagementCheckbox().click();+ });++ expect(saved).toHaveLength(1);+ expect(saved[0]).toContain(PLATFORM_OFF_TOOL);+ expect(saved[0]).not.toContain(PROJECT_OFF_TOOL);+ });+});diff --git a/packages/web/test/app/routes/mcp-server/legacy-pieces-redirect.test.tsx b/packages/web/test/app/routes/mcp-server/legacy-pieces-redirect.test.tsxnew file mode 100644index 00000000000..e8faad32aea--- /dev/null+++ b/packages/web/test/app/routes/mcp-server/legacy-pieces-redirect.test.tsx@@ -0,0 +1,53 @@+/**+ * @vitest-environment jsdom+ */+/* eslint-disable testing-library/no-unnecessary-act */+import * as React from 'react';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';+import { describe, expect, it } from 'vitest';++import { LegacyPiecesRedirect } from '@/app/routes/mcp-server/legacy-pieces-redirect';++declare global {+ // eslint-disable-next-line no-var+ var IS_REACT_ACT_ENVIRONMENT: boolean;+}++globalThis.IS_REACT_ACT_ENVIRONMENT = true;++function landingFor(url: string): string {+ const seen: string[] = [];+ function Probe() {+ const location = useLocation();+ seen.push(`${location.pathname}${location.search}`);+ return null;+ }+ const root = createRoot(document.createElement('div'));+ act(() => {+ root.render(+ <MemoryRouter initialEntries={[url]}>+ <Routes>+ <Route path="/mcp-server/pieces" element={<LegacyPiecesRedirect />} />+ <Route path="/mcp-server/:tab" element={<Probe />} />+ </Routes>+ </MemoryRouter>,+ );+ });+ return seen[seen.length - 1];+}++describe('LegacyPiecesRedirect', () => {+ it('sends the old Pieces tab to the Pieces segment of Tools, keeping the project', () => {+ expect(landingFor('/mcp-server/pieces?project=project-1')).toBe(+ '/mcp-server/tools?project=project-1&segment=pieces',+ );+ });++ it('opens the Pieces segment without a project when none was given', () => {+ expect(landingFor('/mcp-server/pieces')).toBe(+ '/mcp-server/tools?segment=pieces',+ );+ });+});diff --git a/packages/web/test/app/routes/mcp-server/mcp-nav.test.tsx b/packages/web/test/app/routes/mcp-server/mcp-nav.test.tsxnew file mode 100644index 00000000000..186bfea811e--- /dev/null+++ b/packages/web/test/app/routes/mcp-server/mcp-nav.test.tsx@@ -0,0 +1,62 @@+/**+ * @vitest-environment jsdom+ */+/* eslint-disable testing-library/no-unnecessary-act */+import * as React from 'react';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { MemoryRouter, Route, Routes } from 'react-router-dom';+import { describe, expect, it, vi } from 'vitest';++const SESSION_PROJECT_ID = 'sessionProject0000001';+const OTHER_PROJECT_ID = 'otherProject000000001';++vi.mock('@/lib/authentication-session', () => ({+ authenticationSession: { getProjectId: () => SESSION_PROJECT_ID },+}));++const { useMcpNav } = await import('@/app/routes/mcp-server/mcp-nav');++declare global {+ // eslint-disable-next-line no-var+ var IS_REACT_ACT_ENVIRONMENT: boolean;+}++globalThis.IS_REACT_ACT_ENVIRONMENT = true;++function projectIdFor(url: string): string | null {+ const seen: Array<string | null> = [];+ function Probe() {+ seen.push(useMcpNav().projectId);+ return null;+ }+ const root = createRoot(document.createElement('div'));+ act(() => {+ root.render(+ <MemoryRouter initialEntries={[url]}>+ <Routes>+ <Route path="/mcp-server/:tab" element={<Probe />} />+ </Routes>+ </MemoryRouter>,+ );+ });+ return seen[seen.length - 1];+}++describe('useMcpNav project', () => {+ it('takes the project from the address', () => {+ expect(projectIdFor(`/mcp-server/tools?project=${OTHER_PROJECT_ID}`)).toBe(+ OTHER_PROJECT_ID,+ );+ });++ it('falls back to the session project when the address names none', () => {+ expect(projectIdFor('/mcp-server/tools')).toBe(SESSION_PROJECT_ID);+ });++ it('ignores a value that is not a project id, so a crafted link cannot reach another path', () => {+ expect(projectIdFor('/mcp-server/tools?project=..')).toBe(+ SESSION_PROJECT_ID,+ );+ });+});diff --git a/packages/web/test/app/routes/mcp-server/mcp-reach-guard.test.tsx b/packages/web/test/app/routes/mcp-server/mcp-reach-guard.test.tsxnew file mode 100644index 00000000000..6fb477d5e08--- /dev/null+++ b/packages/web/test/app/routes/mcp-server/mcp-reach-guard.test.tsx@@ -0,0 +1,96 @@+/**+ * @vitest-environment jsdom+ */+/* eslint-disable testing-library/no-unnecessary-act */+/* eslint-disable jest-dom/prefer-to-have-text-content -- @testing-library/jest-dom is not a dependency of packages/web */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import * as React from 'react';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { MemoryRouter, Route, Routes } from 'react-router-dom';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const reach = vi.hoisted(() => vi.fn());+const refusedCode = vi.hoisted(() => ({ value: null as string | null }));++vi.mock('i18next', () => ({ t: (key: string) => key }));+vi.mock('sonner', () => ({ toast: { error: () => undefined } }));+vi.mock('@/lib/api', () => ({+ api: {+ isApError: (_error: unknown, code: string) => refusedCode.value === code,+ },+}));+vi.mock('@/app/components/project-settings/mcp-server/utils/mcp-api', () => ({+ mcpApi: { reach },+}));++const { McpReachGuard } = await import(+ '@/app/routes/mcp-server/mcp-reach-guard'+);++declare global {+ // eslint-disable-next-line no-var+ var IS_REACT_ACT_ENVIRONMENT: boolean;+}++globalThis.IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;++async function renderGuard() {+ const queryClient = new QueryClient();+ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <MemoryRouter initialEntries={['/mcp-server']}>+ <Routes>+ <Route+ path="/mcp-server"+ element={<McpReachGuard>mcp page</McpReachGuard>}+ />+ <Route path="/404" element={<>not found</>} />+ </Routes>+ </MemoryRouter>+ </QueryClientProvider>,+ );+ });+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ });+}++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ reach.mockReset();+ refusedCode.value = null;+});++describe('McpReachGuard', () => {+ it('opens the page when reach fails, so a broken endpoint never locks anyone out', async () => {+ reach.mockRejectedValue(new Error('boom'));+ await renderGuard();+ expect(container.textContent).toBe('mcp page');+ });++ it('sends a user the server refuses, such as an embedded user, to 404', async () => {+ refusedCode.value = 'AUTHORIZATION';+ reach.mockRejectedValue(new Error('forbidden'));+ await renderGuard();+ expect(container.textContent).toBe('not found');+ });++ it('sends a user who reaches no project to 404', async () => {+ reach.mockResolvedValue({ projectIds: [] });+ await renderGuard();+ expect(container.textContent).toBe('not found');+ });++ it('opens the page when the user reaches a project', async () => {+ reach.mockResolvedValue({ projectIds: ['project-1'] });+ await renderGuard();+ expect(container.textContent).toBe('mcp page');+ });+});diff --git a/packages/web/test/app/routes/mcp-server/project-picker.test.tsx b/packages/web/test/app/routes/mcp-server/project-picker.test.tsxnew file mode 100644index 00000000000..aae96ac76c0--- /dev/null+++ b/packages/web/test/app/routes/mcp-server/project-picker.test.tsx@@ -0,0 +1,70 @@+/**+ * @vitest-environment jsdom+ */+/* eslint-disable testing-library/no-unnecessary-act */+import * as React from 'react';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { describe, expect, it, vi } from 'vitest';++type WithChildren = { children?: React.ReactNode };++vi.mock('i18next', () => ({ t: (key: string) => key }));+vi.mock('@/components/ui/dropdown-menu', () => ({+ DropdownMenu: ({ children }: WithChildren) => <div>{children}</div>,+ DropdownMenuTrigger: ({ children }: WithChildren) => <div>{children}</div>,+ DropdownMenuContent: ({ children }: WithChildren) => <div>{children}</div>,+ DropdownMenuItem: ({ children }: WithChildren) => (+ <div data-project-item="true">{children}</div>+ ),+}));+vi.mock('@/features/projects', () => ({+ ApProjectDisplay: ({ title }: { title: string }) => <span>{title}</span>,+ getProjectName: ({ displayName }: { displayName: string }) => displayName,+ projectCollectionUtils: {+ useAll: () => ({+ data: [+ { id: 'reachable', displayName: 'Reachable' },+ { id: 'unreachable', displayName: 'Unreachable' },+ ],+ }),+ },+}));++const { ProjectPicker } = await import(+ '@/app/routes/mcp-server/project-picker'+);++declare global {+ // eslint-disable-next-line no-var+ var IS_REACT_ACT_ENVIRONMENT: boolean;+}++globalThis.IS_REACT_ACT_ENVIRONMENT = true;++function offeredProjects(allowedProjectIds: string[] | null): Array<string | null> {+ const container = document.createElement('div');+ const root = createRoot(container);+ act(() => {+ root.render(+ <ProjectPicker+ projectId="reachable"+ allowedProjectIds={allowedProjectIds}+ onSelect={() => undefined}+ />,+ );+ });+ return Array.from(+ container.querySelectorAll('[data-project-item="true"]'),+ ).map((item) => item.textContent);+}++describe('ProjectPicker', () => {+ it('offers only the projects MCP reaches', () => {+ expect(offeredProjects(['reachable'])).toEqual(['Reachable']);+ });++ it('offers every project when MCP reaches all of them', () => {+ expect(offeredProjects(null)).toEqual(['Reachable', 'Unreachable']);+ });+});diff --git a/packages/web/test/app/routes/mcp-server/tools/project-selection.test.ts b/packages/web/test/app/routes/mcp-server/tools/project-selection.test.tsnew file mode 100644index 00000000000..415ce22f567--- /dev/null+++ b/packages/web/test/app/routes/mcp-server/tools/project-selection.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';++import { reachableProjectUtils } from '@/app/routes/mcp-server/tools/project-selection';++const SESSION_PROJECT = 'session-project';+const REACHABLE = 'reachable-project';++describe('reachableProjectUtils.resolveSelected', () => {+ it('keeps the session project when MCP reaches it', () => {+ const selected = reachableProjectUtils.resolveSelected({+ projectId: SESSION_PROJECT,+ reachableProjectIds: [SESSION_PROJECT, REACHABLE],+ });++ expect(selected).toBe(SESSION_PROJECT);+ });++ it('falls to a reachable project rather than opening on a denial', () => {+ const selected = reachableProjectUtils.resolveSelected({+ projectId: SESSION_PROJECT,+ reachableProjectIds: [REACHABLE],+ });++ expect(selected).toBe(REACHABLE);+ });++ it('picks a project when the URL names none', () => {+ const selected = reachableProjectUtils.resolveSelected({+ projectId: null,+ reachableProjectIds: [REACHABLE],+ });++ expect(selected).toBe(REACHABLE);+ });++ it('leaves the session project alone while reach is unknown, so the page still loads', () => {+ const selected = reachableProjectUtils.resolveSelected({+ projectId: SESSION_PROJECT,+ reachableProjectIds: null,+ });++ expect(selected).toBe(SESSION_PROJECT);+ });++ it('leaves the session project alone when reach is empty, and lets the server refuse', () => {+ const selected = reachableProjectUtils.resolveSelected({+ projectId: SESSION_PROJECT,+ reachableProjectIds: [],+ });++ expect(selected).toBe(SESSION_PROJECT);+ });+});diff --git a/packages/web/test/app/routes/mcp-server/tools/tools-tab.test.tsx b/packages/web/test/app/routes/mcp-server/tools/tools-tab.test.tsxnew file mode 100644index 00000000000..9796e2ccf1f--- /dev/null+++ b/packages/web/test/app/routes/mcp-server/tools/tools-tab.test.tsx@@ -0,0 +1,119 @@+/**+ * @vitest-environment jsdom+ */+/* eslint-disable testing-library/no-unnecessary-act */+import * as React from 'react';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { describe, expect, it, vi } from 'vitest';++type WithChildren = { children?: React.ReactNode };++const server = vi.hoisted(() => {+ const state: { disabledTools: string[]; platformDisabledTools: string[] } = {+ disabledTools: [],+ platformDisabledTools: [],+ };+ return state;+});++vi.mock('i18next', () => ({ t: (key: string) => key }));+vi.mock('@/app/components/project-settings/mcp-server/utils/mcp-hooks', () => ({+ mcpHooks: {+ useMcpServer: () => ({+ data: server,+ isLoading: false,+ isError: false,+ error: null,+ refetch: () => undefined,+ }),+ useUpdateMcpServer: () => ({ mutate: () => undefined, isPending: false }),+ },+}));+vi.mock('@/app/components/project-settings/mcp-server/mcp-tools', () => ({+ McpTools: () => null,+}));+vi.mock('@/hooks/flags-hooks', () => ({+ flagsHooks: { useFlag: () => ({ data: false }) },+}));+vi.mock('@/features/pieces/hooks/pieces-hooks', () => ({+ piecesHooks: { usePieces: () => ({ pieces: undefined }) },+}));+vi.mock('@/app/routes/mcp-server/page-band', () => ({+ PageBand: ({ children }: WithChildren) => <div>{children}</div>,+}));+vi.mock('@/app/routes/mcp-server/project-picker', () => ({+ ProjectPicker: () => null,+}));+vi.mock('@/app/routes/mcp-server/pieces/pieces-panel', () => ({+ PiecesPanel: ({+ isRunActionDisabled,+ isRunActionDisabledByPlatform,+ }: {+ isRunActionDisabled: boolean;+ isRunActionDisabledByPlatform: boolean;+ }) => (+ <div+ data-run-action-off={String(isRunActionDisabled)}+ data-run-action-off-by-platform={String(isRunActionDisabledByPlatform)}+ />+ ),+}));++const { ToolsTab } = await import('@/app/routes/mcp-server/tools/tools-tab');++declare global {+ // eslint-disable-next-line no-var+ var IS_REACT_ACT_ENVIRONMENT: boolean;+}++globalThis.IS_REACT_ACT_ENVIRONMENT = true;++const RUN_ACTION = 'ap_run_action';++function piecesPanelFor({+ disabledTools,+ platformDisabledTools,+}: {+ disabledTools: string[];+ platformDisabledTools: string[];+}): Element | null {+ server.disabledTools = disabledTools;+ server.platformDisabledTools = platformDisabledTools;+ const container = document.createElement('div');+ const root = createRoot(container);+ act(() => {+ root.render(+ <ToolsTab+ projectId="project-1"+ reachableProjectIds={null}+ segment="pieces"+ onSelectProject={() => undefined}+ onSelectSegment={() => undefined}+ />,+ );+ });+ return container.querySelector('[data-run-action-off]');+}++describe('ToolsTab, Run action on the Pieces segment', () => {+ it('blames the platform only when the platform switched Run action off', () => {+ const panel = piecesPanelFor({+ disabledTools: [RUN_ACTION],+ platformDisabledTools: [],+ });+ expect(panel?.getAttribute('data-run-action-off')).toBe('true');+ expect(panel?.getAttribute('data-run-action-off-by-platform')).toBe(+ 'false',+ );+ });++ it('says the platform switched Run action off', () => {+ const panel = piecesPanelFor({+ disabledTools: [],+ platformDisabledTools: [RUN_ACTION],+ });+ expect(panel?.getAttribute('data-run-action-off')).toBe('false');+ expect(panel?.getAttribute('data-run-action-off-by-platform')).toBe('true');+ });+});