Skip to content

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

feat(web): redesign the MCP admin pages around four tool tiers (#15908)

moaaz4c284c5e0cf4
diff --git a/brain/knowledge/ai-intelligence/mcp-server.md b/brain/knowledge/ai-intelligence/mcp-server.md
index c0270a900f6..e4fd6d53f4d 100644
--- a/brain/knowledge/ai-intelligence/mcp-server.md
+++ b/brain/knowledge/ai-intelligence/mcp-server.md
@@ -53,7 +53,7 @@ Exposes an Activepieces project as an MCP server so AI clients (Claude Desktop,
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 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: `McpToolTierList` (with `scope="project"`) reads `WRITE_MCP` through `useAuthorization(projectId)` and shows every switch read-only without it. `platformDisabledTools` comes back beside the project list, and `McpToolTierList` shows those tools as off, locked and badged "Off for the platform", here and in the embedded dialog. On the platform page (`scope="platform"`) there is no project role to check: `/platform/*` is admin-only already. `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
@@ -108,7 +108,9 @@ Exposes an Activepieces project as an MCP server so AI clients (Claude Desktop,
- **A row carries no payload; the input and output go to the `file` table as `MCP_CALL_PAYLOAD`.** That is what V1 got wrong — `mcp_run` had two non-null JSONB columns written synchronously per call. Keeping the fat bytes in a table the list query never reads also buys the retention for free: `MCP_CALL_PAYLOAD` is in `isExecutionDataFileThatExpires`, so it routes to S3 when configured and is swept by the hourly `FILE_CLEANUP_TRIGGER` already running. Row retention rides the same job via `mcpActivityRetention.deleteStale()`, in bounded passes modelled on `agentRetention`.
- **`FileType` is declared twice and the two copies must stay in lockstep** — `core/shared/src/lib/core/file/index.ts` and `core-piece-types/src/lib/execution-contracts.ts`. Adding a member to only one breaks assignability at the seam (`sample-data.service.ts` is the first thing to fail to compile), with an error that points at the *consumer*, not at the enum you edited.
-- **The Activity feed renders on two surfaces from one component, so editing its columns or filters edits a platform admin settings page too.** `ActivityFeed` (`app/routes/mcp-server/activity/`) is consumed by the project MCP page's Activity tab *and* by `/platform/mcp/activity`, a sidebar child of the platform MCP page — a platform admin already sees the whole platform's rows there, because `GET /v1/mcp-activity` is platform-scoped and `resolveUserIdFilter` only narrows a *non*-privileged caller. The platform page is a `CenteredPage`, whose default `max-w-[40rem]` cannot hold a six-column table, so it is widened to the `max-w-[1198px]` band `PageBand` uses on the project page — which also widens its sibling Connection and Tools sections, since all three render through the same `CenteredPage`. The import is `app` → `app`, which the `import/no-restricted-paths` zone allows; had the feed lived in `src/features`, it could not have reached back for `useMcpNav` or `PageBand`.
+- **Built-in tools are grouped into four tiers by what a wrong call costs, and the grouping is a hand-kept list in the web app.** `mcpToolTiers` (`app/components/project-settings/mcp-server/tool-tiers/`) puts the locked Discovery category in View, names the Edit flows and Delete tools in `DRAFT_TOOLS` and `DELETE_TOOLS`, and sends every other tool to Publish and run, so a new tool lands in Publish and run, not Edit flows, and skips the Delete confirmation until someone adds it to `DELETE_TOOLS`. Delete holds the tools that destroy data outright; `ap_manage_fields` is there because it can delete a field and its data, which means turning Delete off also stops clients adding or renaming fields. Turning Delete off does **not** stop every delete: `ap_delete_step` and `ap_delete_branch` edit drafts and stay in Edit flows, and `ap_run_action` stays in Publish and run although it can run any piece action, including a Tables or third-party delete. The tiers are only a view over `disabledTools`: the server still checks tool names one by one.
+
+- **The Activity feed renders on two surfaces from one component, so editing its columns or filters edits a platform admin settings page too.** `ActivityFeed` (`app/routes/mcp-server/activity/`) is consumed by the project MCP page's Activity tab *and* by `/platform/mcp/activity`, a sidebar child of the platform MCP page — a platform admin already sees the whole platform's rows there, because `GET /v1/mcp-activity` is platform-scoped and `resolveUserIdFilter` only narrows a *non*-privileged caller. The platform page is a `CenteredPage`, whose default `max-w-[40rem]` cannot hold a six-column table, so the Activity tab widens it to the `max-w-[1198px]` band `PageBand` uses on the project page; the Tools tab keeps the default width. The import is `app` → `app`, which the `import/no-restricted-paths` zone allows; had the feed lived in `src/features`, it could not have reached back for `useMcpNav` or `PageBand`.
- **Filter options on a platform-scoped feed must be sourced by privilege, or an admin sees rows they cannot filter by.** `projectCollectionUtils.useAll()` is the member-scoped hook: it keeps TEAM projects plus only the *current user's* PERSONAL project, so on a platform-wide feed an admin gets rows from other members' personal projects with no matching entry in the Project dropdown. Use `useAllPlatformProjects()` when `useIsPlatformPrivileged()` — `/v1/projects` already scopes itself by `isUserPrivileged`, so the wider hook returns nothing extra to a member. The columns are unaffected either way: the server sends `projectName` on each row, so only the *filter* goes blind. Same shape as the platform Connections page, which sources its project filter the same way.
diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.json
index b321f2c5d85..28245aa9141 100644
--- a/packages/web/public/locales/en/translation.json
+++ b/packages/web/public/locales/en/translation.json
@@ -675,10 +675,7 @@
"No MCP flows yet. Create a flow with an MCP Trigger to expose it as a tool on this server.": "No MCP flows yet. Create a flow with an MCP Trigger to expose it as a tool on this server.",
"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}",
"Pending Invitation": "Pending Invitation",
"Remove Invitation": "Remove Invitation",
@@ -1556,9 +1553,6 @@
"Your projects, flows, connections, agents and tables are erased on {date}.": "Your projects, flows, connections, agents and tables are erased on {date}.",
"Type {name} to confirm": "Type {name} to confirm",
"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.",
- "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",
@@ -3150,8 +3144,6 @@
"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.",
@@ -3174,5 +3166,36 @@
"Solid": "Solid",
"Text and marks": "Text and marks",
"Button": "Button",
- "Hover": "Hover"
+ "Hover": "Hover",
+ "{enabled} of {total} on": "{enabled} of {total} on",
+ "Always on": "Always on",
+ "View flows, runs, tables, connections and pieces.": "View flows, runs, tables, connections and pieces.",
+ "Edit flows": "Edit flows",
+ "Create, rename and duplicate flows, and edit drafts.": "Create, rename and duplicate flows, and edit drafts.",
+ "Publish and run": "Publish and run",
+ "Permanently delete flows, tables, fields and records.": "Permanently delete flows, tables, fields and records.",
+ "{total, plural, =1 {1 tool} other {# tools}}": "{total, plural, =1 {1 tool} other {# tools}}",
+ "Turn a tool off to stop MCP clients from calling it.": "Turn a tool off to stop MCP clients from calling it.",
+ "Choose which tools MCP clients can use in every project and in AI Chat. Clients act with the signed-in user's permissions.": "Choose which tools MCP clients can use in every project and in AI Chat. Clients act with the signed-in user's permissions.",
+ "Piece actions run by MCP clients, like Claude and Cursor. Other tool calls are not logged.": "Piece actions run by MCP clients, like Claude and Cursor. Other tool calls are not logged.",
+ "No activity yet": "No activity yet",
+ "When an MCP client runs a piece action, it appears here.": "When an MCP client runs a piece action, it appears here.",
+ "MCP Tools": "MCP Tools",
+ "MCP Activity": "MCP Activity",
+ "Turn on Delete tools?": "Turn on Delete tools?",
+ "Turn on": "Turn on",
+ "Delete tools": "Delete tools",
+ "Other tools need these to work.": "Other tools need these to work.",
+ "Always on. Other tools need these to work.": "Always on. Other tools need these to work.",
+ "Turn all off": "Turn all off",
+ "Turn all on": "Turn all on",
+ "Manage roles": "Manage roles",
+ "Off for the platform": "Off for the platform",
+ "A platform admin turned these off for every project.": "A platform admin turned these off for every project.",
+ "Publish, test and run flows and actions, and change tables.": "Publish, test and run flows and actions, and change tables.",
+ "MCP clients will be able to use the delete tools you are turning on, in every project their user can edit, unless the project turned them off. Deleted items cannot be restored.": "MCP clients will be able to use the delete tools you are turning on, in every project their user can edit, unless the project turned them off. Deleted items cannot be restored.",
+ "MCP clients will be able to use the delete tools you are turning on in this project. Deleted items cannot be restored.": "MCP clients will be able to use the delete tools you are turning on in this project. Deleted items cannot be restored.",
+ "{tier}: {status}": "{tier}: {status}",
+ "{tier}, {status}": "{tier}, {status}",
+ "Show full output": "Show full output"
}
diff --git a/packages/web/src/app/components/centered-page.tsx b/packages/web/src/app/components/centered-page.tsx
index fac7b916b5c..804112b2bde 100644
--- a/packages/web/src/app/components/centered-page.tsx
+++ b/packages/web/src/app/components/centered-page.tsx
@@ -13,6 +13,7 @@ export const CenteredPage = ({
footer,
children,
widthClassName = 'max-w-[40rem]',
+ showHeaderSeparator = true,
className,
}: {
title?: string;
@@ -21,12 +22,18 @@ export const CenteredPage = ({
footer?: React.ReactNode;
children: React.ReactNode;
widthClassName?: string;
+ showHeaderSeparator?: boolean;
className?: string;
}) => {
const header =
title === undefined && !description && !actions ? null : (
<>
- <div className="flex items-start justify-between gap-4">
+ <div
+ className={cn(
+ 'flex items-start justify-between gap-4',
+ !showHeaderSeparator && 'mb-6',
+ )}
+ >
<div className="flex flex-col gap-1">
{title !== undefined && (
<h1 className="text-xl font-medium">{title}</h1>
@@ -37,7 +44,7 @@ export const CenteredPage = ({
</div>
{actions && <div className="shrink-0">{actions}</div>}
</div>
- <Separator className="my-4" />
+ {showHeaderSeparator && <Separator className="my-4" />}
</>
);
diff --git a/packages/web/src/app/components/global-search/static-pages.ts b/packages/web/src/app/components/global-search/static-pages.ts
index a0ff86883c7..0f9e8dcac67 100644
--- a/packages/web/src/app/components/global-search/static-pages.ts
+++ b/packages/web/src/app/components/global-search/static-pages.ts
@@ -87,15 +87,8 @@ export const STATIC_PAGES: StaticPage[] = [
},
{
id: 'page-platform-mcp',
- label: 'Platform Admin — MCP Server',
- href: '/platform/mcp',
- icon: ConnectIcon,
- requiresPlatformAdmin: true,
- },
- {
- id: 'page-platform-mcp-tools',
label: 'Platform Admin — MCP Tools',
- href: '/platform/mcp/tools',
+ href: '/platform/mcp',
icon: ConnectIcon,
requiresPlatformAdmin: true,
},
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.tsx
index 185411d2429..6674a00b6bd 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
@@ -6,7 +6,7 @@ import { authenticationSession } from '@/lib/authentication-session';
import { McpCredentials } from './mcp-credentials';
import { McpFlows } from './mcp-flows';
-import { McpTools } from './mcp-tools';
+import { McpToolTierList } from './tool-tiers/mcp-tool-tier-list';
import { mcpHooks } from './utils/mcp-hooks';
export const McpServerSettings = () => {
@@ -14,8 +14,9 @@ export const McpServerSettings = () => {
const { data: mcpServer, isLoading } = mcpHooks.useMcpServer(
currentProjectId!,
);
- const { mutate: updateMcpServer, isPending: isUpdating } =
- mcpHooks.useUpdateMcpServer(currentProjectId!);
+ const { mutate: updateMcpServer } = mcpHooks.useUpdateMcpServer(
+ currentProjectId!,
+ );
if (isLoading) {
return (
@@ -52,12 +53,12 @@ export const McpServerSettings = () => {
'Control which built-in tools are available to agents via this MCP server.',
)}
</p>
- <McpTools
+ <McpToolTierList
disabledTools={mcpServer.disabledTools}
platformDisabledTools={mcpServer.platformDisabledTools}
- isPending={isUpdating}
- onUpdateDisabledTools={(tools) =>
- updateMcpServer({ disabledTools: tools })
+ scope="project"
+ onUpdateDisabledTools={({ tools, onSettled }) =>
+ updateMcpServer({ disabledTools: tools }, { onSettled })
}
/>
</div>
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.tsx
deleted file mode 100644
index d03d8a797f0..00000000000
--- a/packages/web/src/app/components/project-settings/mcp-server/mcp-tools.tsx
+++ /dev/null
@@ -1,221 +0,0 @@
-import { Permission } from '@activepieces/core-utils';
-import { ApFlagId } from '@activepieces/shared';
-import { t } from 'i18next';
-import { Lock } from 'lucide-react';
-import { useEffect, useState } from 'react';
-import { useDebouncedCallback } from 'use-debounce';
-
-import {
- Accordion,
- AccordionContent,
- 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';
-
-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,
- );
- const toolCategories = getToolCategories({
- toolSearchEnabled: toolSearchEnabled ?? false,
- });
- const [disabledTools, setDisabledTools] = useState<string[]>(
- () => externalDisabledTools ?? [],
- );
-
- useEffect(() => {
- if (!isPending) {
- setDisabledTools(externalDisabledTools ?? []);
- }
- }, [externalDisabledTools, isPending]);
-
- const saveDisabledTools = useDebouncedCallback((tools: string[]) => {
- onUpdateDisabledTools(tools);
- }, 300);
-
- const toggleTool = (name: string, checked: boolean) => {
- if (!canWrite) {
- return;
- }
- const next = checked
- ? disabledTools.filter((n) => n !== name)
- : [...disabledTools, name];
- setDisabledTools(next);
- saveDisabledTools(next);
- };
-
- const toggleCategory = (toolNames: string[], checked: boolean) => {
- if (!canWrite) {
- return;
- }
- const next = checked
- ? disabledTools.filter((n) => !toolNames.includes(n))
- : [
- ...disabledTools,
- ...toolNames.filter((n) => !disabledTools.includes(n)),
- ];
- setDisabledTools(next);
- saveDisabledTools(next);
- };
-
- return (
- <div className="flex flex-col gap-2">
- {!canWrite && (
- <p className="text-xs text-gray-11">
- {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-gray-3/40 hover:no-underline">
- <div className="flex items-center gap-3">
- {category.locked ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <Lock className="h-4 w-4 text-gray-11 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>
- {category.locked && (
- <span className="text-xs text-gray-11 ml-1">
- ({t('always enabled')})
- </span>
- )}
- <span className="text-xs text-gray-11">
- {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"
- >
- {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-gray-11">
- {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/tool-tiers/mcp-tool-tier-list.tsx b/packages/web/src/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tier-list.tsx
new file mode 100644
index 00000000000..f3271903f81
--- /dev/null
+++ b/packages/web/src/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tier-list.tsx
@@ -0,0 +1,330 @@
+import { Permission } from '@activepieces/core-utils';
+import { ApFlagId } from '@activepieces/shared';
+import { t } from 'i18next';
+import {
+ ChevronRight,
+ Eye,
+ LucideIcon,
+ Pencil,
+ Play,
+ Trash2,
+} from 'lucide-react';
+import { Fragment, useEffect, useMemo, useState } from 'react';
+import { useDebouncedCallback } from 'use-debounce';
+
+import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import {
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemMedia,
+ ItemSeparator,
+ ItemTitle,
+} from '@/components/ui/item';
+import { Switch } from '@/components/ui/switch';
+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';
+
+import { McpToolTier, McpToolTierGroup, mcpToolTiers } from './mcp-tool-tiers';
+import { McpToolsSheet } from './mcp-tools-sheet';
+
+export function McpToolTierList({
+ disabledTools: savedDisabledTools,
+ platformDisabledTools = NO_TOOLS,
+ scope,
+ projectId,
+ onUpdateDisabledTools,
+}: McpToolTierListProps) {
+ const { checkAccess } = useAuthorization(projectId);
+ const readOnly = scope === 'project' && !checkAccess(Permission.WRITE_MCP);
+ const { data: toolSearchEnabled } = flagsHooks.useFlag<boolean>(
+ ApFlagId.TOOL_SEARCH_ENABLED,
+ );
+ const tiers = useMemo(
+ () =>
+ mcpToolTiers.groupByTier(
+ getToolCategories({ toolSearchEnabled: toolSearchEnabled ?? false }),
+ ),
+ [toolSearchEnabled],
+ );
+ const [pendingDisabledTools, setPendingDisabledTools] = useState<
+ string[] | null
+ >(null);
+ const disabledTools = pendingDisabledTools ?? savedDisabledTools ?? NO_TOOLS;
+ const [openTierId, setOpenTierId] = useState<McpToolTier | null>(null);
+ const [pendingDeleteTools, setPendingDeleteTools] = useState<string[] | null>(
+ null,
+ );
+ const deleteToolNames = useMemo(
+ () =>
+ tiers
+ .filter((tier) => tier.id === 'delete')
+ .flatMap((tier) => tier.tools.map((tool) => tool.name)),
+ [tiers],
+ );
+ const offTools = useMemo(
+ () => [...new Set([...disabledTools, ...platformDisabledTools])],
+ [disabledTools, platformDisabledTools],
+ );
+
+ const save = useDebouncedCallback((tools: string[]) => {
+ onUpdateDisabledTools({
+ tools,
+ onSettled: () =>
+ setPendingDisabledTools((current) =>
+ current === tools ? null : current,
+ ),
+ });
+ }, 300);
+
+ useEffect(() => () => save.flush(), [save]);
+
+ const applyToolsEnabled = ({
+ names,
+ enabled,
+ }: {
+ names: string[];
+ enabled: boolean;
+ }) => {
+ const next = enabled
+ ? disabledTools.filter((name) => !names.includes(name))
+ : [...disabledTools, ...names.filter((n) => !disabledTools.includes(n))];
+ setPendingDisabledTools(next);
+ save(next);
+ };
+
+ const setToolsEnabled = ({
+ names,
+ enabled,
+ }: {
+ names: string[];
+ enabled: boolean;
+ }) => {
+ if (readOnly) {
+ return;
+ }
+ const editable = names.filter(
+ (name) => !platformDisabledTools.includes(name),
+ );
+ const turnsOnDeleteTool =
+ enabled &&
+ editable.some(
+ (name) =>
+ deleteToolNames.includes(name) && disabledTools.includes(name),
+ );
+ if (turnsOnDeleteTool) {
+ setPendingDeleteTools(editable);
+ return;
+ }
+ applyToolsEnabled({ names: editable, enabled });
+ };
+
+ return (
+ <div className="flex flex-col gap-3">
+ {readOnly && (
+ <p className="text-sm text-gray-11">
+ {t('You can see these tools, but your role cannot change them.')}
+ </p>
+ )}
+ <ItemGroup className="rounded-lg border bg-gray-1">
+ {tiers.map((tier, index) => (
+ <Fragment key={tier.id}>
+ {index > 0 && <ItemSeparator />}
+ <TierRow
+ tier={tier}
+ offTools={offTools}
+ platformDisabledTools={platformDisabledTools}
+ readOnly={readOnly}
+ onOpenTools={() => setOpenTierId(tier.id)}
+ onChange={(enabled) =>
+ setToolsEnabled({
+ names: tier.tools.map((tool) => tool.name),
+ enabled,
+ })
+ }
+ />
+ </Fragment>
+ ))}
+ </ItemGroup>
+
+ <McpToolsSheet
+ tier={tiers.find((tier) => tier.id === openTierId) ?? null}
+ onClose={() => setOpenTierId(null)}
+ offTools={offTools}
+ platformDisabledTools={platformDisabledTools}
+ readOnly={readOnly}
+ onToggleTool={({ name, enabled }) =>
+ setToolsEnabled({ names: [name], enabled })
+ }
+ onSetAll={({ names, enabled }) => setToolsEnabled({ names, enabled })}
+ />
+
+ <ConfirmationDeleteDialog
+ open={pendingDeleteTools !== null}
+ onOpenChange={(open) => !open && setPendingDeleteTools(null)}
+ title={t('Turn on Delete tools?')}
+ message={
+ scope === 'platform'
+ ? t(
+ 'MCP clients will be able to use the delete tools you are turning on, in every project their user can edit, unless the project turned them off. Deleted items cannot be restored.',
+ )
+ : t(
+ 'MCP clients will be able to use the delete tools you are turning on in this project. Deleted items cannot be restored.',
+ )
+ }
+ buttonText={t('Turn on')}
+ entityName={t('Delete tools')}
+ mutationFn={async () => {
+ if (pendingDeleteTools !== null) {
+ applyToolsEnabled({ names: pendingDeleteTools, enabled: true });
+ }
+ setPendingDeleteTools(null);
+ }}
+ />
+ </div>
+ );
+}
+
+function TierRow({
+ tier,
+ offTools,
+ platformDisabledTools,
+ readOnly,
+ onOpenTools,
+ onChange,
+}: TierRowProps) {
+ const copy = mcpToolTiers.copyOf(tier.id);
+ const Icon = TIER_ICON[tier.id];
+ const enabled = mcpToolTiers.countEnabled({
+ group: tier,
+ disabledTools: offTools,
+ });
+ const total = tier.tools.length;
+ const editable = tier.tools.filter(
+ (tool) => !platformDisabledTools.includes(tool.name),
+ );
+ const editableOn = editable.filter(
+ (tool) => !offTools.includes(tool.name),
+ ).length;
+ const offForPlatform = !tier.locked && editable.length === 0;
+ const isPartial = editableOn > 0 && editableOn < editable.length;
+ const someOff = enabled > 0 && enabled < total;
+ const countLabel = someOff
+ ? t('{enabled} of {total} on', { enabled, total })
+ : t('{total, plural, =1 {1 tool} other {# tools}}', { total });
+
+ return (
+ <Item>
+ <ItemMedia variant="icon">
+ <Icon className="size-4 text-gray-11" />
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>
+ {copy.label}
+ {tier.locked && (
+ <TitleBadge
+ label={t('Always on')}
+ tooltip={t('Other tools need these to work.')}
+ />
+ )}
+ {offForPlatform && (
+ <TitleBadge
+ label={t('Off for the platform')}
+ tooltip={t(
+ 'A platform admin turned these off for every project.',
+ )}
+ />
+ )}
+ </ItemTitle>
+ <ItemDescription>{copy.description}</ItemDescription>
+ </ItemContent>
+ <ItemActions className="gap-4">
+ <Button
+ variant="ghost"
+ size="sm"
+ className={cn('text-gray-11', someOff && 'text-gray-12')}
+ onClick={onOpenTools}
+ aria-label={t('{tier}: {status}', {
+ tier: copy.label,
+ status: countLabel,
+ })}
+ >
+ {countLabel}
+ <ChevronRight className="size-4" />
+ </Button>
+ <div className="flex w-8 justify-end">
+ {!tier.locked && (
+ <Switch
+ checked={editable.length > 0 && editableOn === editable.length}
+ indeterminate={isPartial}
+ disabled={readOnly || offForPlatform}
+ onCheckedChange={(checked) => onChange(checked === true)}
+ aria-label={
+ isPartial
+ ? t('{tier}, {status}', {
+ tier: copy.label,
+ status: countLabel,
+ })
+ : copy.label
+ }
+ />
+ )}
+ </div>
+ </ItemActions>
+ </Item>
+ );
+}
+
+function TitleBadge({ label, tooltip }: { label: string; tooltip: string }) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="neutral" className="font-normal" tabIndex={0}>
+ {label}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>{tooltip}</TooltipContent>
+ </Tooltip>
+ );
+}
+
+const NO_TOOLS: string[] = [];
+
+const TIER_ICON: Record<McpToolTier, LucideIcon> = {
+ read: Eye,
+ draft: Pencil,
+ live: Play,
+ delete: Trash2,
+};
+
+type McpToolTierListProps = {
+ disabledTools: string[] | null;
+ platformDisabledTools?: string[];
+ scope: 'platform' | 'project';
+ projectId?: string;
+ onUpdateDisabledTools: (params: {
+ tools: string[];
+ onSettled: () => void;
+ }) => void;
+};
+
+type TierRowProps = {
+ tier: McpToolTierGroup;
+ offTools: string[];
+ platformDisabledTools: string[];
+ readOnly: boolean;
+ onOpenTools: () => void;
+ onChange: (enabled: boolean) => void;
+};
diff --git a/packages/web/src/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tiers.ts b/packages/web/src/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tiers.ts
new file mode 100644
index 00000000000..e959c534966
--- /dev/null
+++ b/packages/web/src/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tiers.ts
@@ -0,0 +1,133 @@
+import { t } from 'i18next';
+
+import {
+ ToolCategory,
+ ToolMeta,
+} from '@/app/components/project-settings/mcp-server/utils/mcp-tools-metadata';
+
+const DRAFT_TOOLS = new Set([
+ 'ap_create_flow',
+ 'ap_duplicate_flow',
+ 'ap_rename_flow',
+ 'ap_build_flow',
+ 'ap_update_trigger',
+ 'ap_add_step',
+ 'ap_update_step',
+ 'ap_delete_step',
+ 'ap_add_branch',
+ 'ap_update_branch',
+ 'ap_delete_branch',
+ 'ap_manage_notes',
+]);
+
+const DELETE_TOOLS = new Set([
+ 'ap_delete_flow',
+ 'ap_delete_table',
+ 'ap_delete_records',
+ 'ap_manage_fields',
+]);
+
+function tierOf({
+ name,
+ locked,
+}: {
+ name: string;
+ locked: boolean;
+}): McpToolTier {
+ if (locked) {
+ return 'read';
+ }
+ if (DELETE_TOOLS.has(name)) {
+ return 'delete';
+ }
+ return DRAFT_TOOLS.has(name) ? 'draft' : 'live';
+}
+
+function groupByTier(categories: ToolCategory[]): McpToolTierGroup[] {
+ const buckets: Record<McpToolTier, ToolMeta[]> = {
+ read: [],
+ draft: [],
+ live: [],
+ delete: [],
+ };
+ for (const category of categories) {
+ for (const tool of category.tools) {
+ buckets[
+ tierOf({ name: tool.name, locked: category.locked === true })
+ ].push(tool);
+ }
+ }
+ return TIER_ORDER.map((id) => ({
+ id,
+ locked: id === 'read',
+ tools: buckets[id],
+ })).filter((group) => group.tools.length > 0);
+}
+
+function countEnabled({
+ group,
+ disabledTools,
+}: {
+ group: McpToolTierGroup;
+ disabledTools: string[];
+}): number {
+ if (group.locked) {
+ return group.tools.length;
+ }
+ return group.tools.filter((tool) => !disabledTools.includes(tool.name))
+ .length;
+}
+
+function copyOf(tier: McpToolTier): McpToolTierCopy {
+ switch (tier) {
+ case 'read':
+ return {
+ label: t('View'),
+ description: t('View flows, runs, tables, connections and pieces.'),
+ };
+ case 'draft':
+ return {
+ label: t('Edit flows'),
+ description: t('Create, rename and duplicate flows, and edit drafts.'),
+ };
+ case 'live':
+ return {
+ label: t('Publish and run'),
+ description: t(
+ 'Publish, test and run flows and actions, and change tables.',
+ ),
+ };
+ case 'delete':
+ return {
+ label: t('Delete'),
+ description: t('Permanently delete flows, tables, fields and records.'),
+ };
+ }
+}
+
+function titleOf(toolName: string): string {
+ const words = toolName.replace(/^ap_/, '').split('_').join(' ');
+ return words.charAt(0).toUpperCase() + words.slice(1);
+}
+
+const TIER_ORDER: McpToolTier[] = ['read', 'draft', 'live', 'delete'];
+
+export const mcpToolTiers = {
+ groupByTier,
+ countEnabled,
+ copyOf,
+ titleOf,
+};
+
+export type McpToolTier = 'read' | 'draft' | 'live' | 'delete';
+
+export type McpToolTierGroup = {
+ id: McpToolTier;
+ locked: boolean;
+ tools: ToolMeta[];
+};
+
+type McpToolTierCopy = {
+ label: string;
+ description: string;
+};
diff --git a/packages/web/src/app/components/project-settings/mcp-server/tool-tiers/mcp-tools-sheet.tsx b/packages/web/src/app/components/project-settings/mcp-server/tool-tiers/mcp-tools-sheet.tsx
new file mode 100644
index 00000000000..40f6cc2cac9
--- /dev/null
+++ b/packages/web/src/app/components/project-settings/mcp-server/tool-tiers/mcp-tools-sheet.tsx
@@ -0,0 +1,156 @@
+import { t } from 'i18next';
+import { Fragment } from 'react';
+
+import { TextWithTooltip } from '@/components/custom/text-with-tooltip';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import {
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemSeparator,
+ ItemTitle,
+} from '@/components/ui/item';
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet';
+import { Switch } from '@/components/ui/switch';
+
+import { McpToolTierGroup, mcpToolTiers } from './mcp-tool-tiers';
+
+export function McpToolsSheet({
+ tier,
+ onClose,
+ offTools,
+ platformDisabledTools,
+ readOnly,
+ onToggleTool,
+ onSetAll,
+}: McpToolsSheetProps) {
+ return (
+ <Sheet open={tier !== null} onOpenChange={(open) => !open && onClose()}>
+ <SheetContent className="flex w-full flex-col gap-0 p-0 sm:w-[544px] sm:max-w-[544px]">
+ {tier !== null && (
+ <TierTools
+ tier={tier}
+ offTools={offTools}
+ platformDisabledTools={platformDisabledTools}
+ readOnly={readOnly}
+ onToggleTool={onToggleTool}
+ onSetAll={onSetAll}
+ />
+ )}
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+function TierTools({
+ tier,
+ offTools,
+ platformDisabledTools,
+ readOnly,
+ onToggleTool,
+ onSetAll,
+}: TierToolsProps) {
+ const copy = mcpToolTiers.copyOf(tier.id);
+ const editableNames = tier.tools
+ .map((tool) => tool.name)
+ .filter((name) => !platformDisabledTools.includes(name));
+ const allOn = editableNames.every((name) => !offTools.includes(name));
+ const canSetAll = !tier.locked && !readOnly && editableNames.length > 0;
+ return (
+ <>
+ <SheetHeader className="shrink-0 border-b px-6 py-4 pr-12">
+ <SheetTitle>{copy.label}</SheetTitle>
+ <div className="flex items-center justify-between gap-4">
+ <SheetDescription>
+ {tier.locked
+ ? t('Always on. Other tools need these to work.')
+ : editableNames.length === 0
+ ? t('A platform admin turned these off for every project.')
+ : readOnly
+ ? t('You can see these tools, but your role cannot change them.')
+ : t('Turn a tool off to stop MCP clients from calling it.')}
+ </SheetDescription>
+ {canSetAll && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0"
+ onClick={() =>
+ onSetAll({ names: editableNames, enabled: !allOn })
+ }
+ >
+ {allOn ? t('Turn all off') : t('Turn all on')}
+ </Button>
+ )}
+ </div>
+ </SheetHeader>
+
+ <ItemGroup className="flex-1 overflow-y-auto px-6 py-2">
+ {tier.tools.map((tool, index) => {
+ const offForPlatform = platformDisabledTools.includes(tool.name);
+ return (
+ <Fragment key={tool.name}>
+ {index > 0 && <ItemSeparator />}
+ <Item size="sm" className="px-0">
+ <ItemContent>
+ <ItemTitle className="flex min-w-0 items-baseline gap-2">
+ <span>{mcpToolTiers.titleOf(tool.name)}</span>
+ <TextWithTooltip tooltipMessage={tool.name}>
+ <code className="truncate font-mono text-xs font-normal text-gray-11">
+ {tool.name}
+ </code>
+ </TextWithTooltip>
+ {offForPlatform && (
+ <Badge variant="neutral" className="shrink-0 font-normal">
+ {t('Off for the platform')}
+ </Badge>
+ )}
+ </ItemTitle>
+ <ItemDescription>{tool.description}</ItemDescription>
+ </ItemContent>
+ {!tier.locked && (
+ <ItemActions>
+ <Switch
+ checked={!offTools.includes(tool.name)}
+ disabled={readOnly || offForPlatform}
+ onCheckedChange={(checked) =>
+ onToggleTool({
+ name: tool.name,
+ enabled: checked === true,
+ })
+ }
+ aria-label={mcpToolTiers.titleOf(tool.name)}
+ />
+ </ItemActions>
+ )}
+ </Item>
+ </Fragment>
+ );
+ })}
+ </ItemGroup>
+ </>
+ );
+}
+
+type McpToolsSheetProps = {
+ tier: McpToolTierGroup | null;
+ onClose: () => void;
+ offTools: string[];
+ platformDisabledTools: string[];
+ readOnly: boolean;
+ onToggleTool: (params: { name: string; enabled: boolean }) => void;
+ onSetAll: (params: { names: string[]; enabled: boolean }) => void;
+};
+
+type TierToolsProps = Omit<McpToolsSheetProps, 'tier' | 'onClose'> & {
+ tier: McpToolTierGroup;
+};
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.ts
index 56ca5f84096..59cf86cd1f6 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
@@ -44,6 +44,7 @@ export const mcpHooks = {
const queryClient = useQueryClient();
return useMutation({
+ scope: { id: `mcp-server-tools-${projectId}` },
mutationFn: (input: Parameters<typeof mcpApi.update>[1]) =>
mcpApi.update(projectId, input),
onSuccess: (data) => {
diff --git a/packages/web/src/app/components/sidebar/platform/index.tsx b/packages/web/src/app/components/sidebar/platform/index.tsx
index 785b99a308a..69fc14f4dc6 100644
--- a/packages/web/src/app/components/sidebar/platform/index.tsx
+++ b/packages/web/src/app/components/sidebar/platform/index.tsx
@@ -200,8 +200,7 @@ export function PlatformSidebar() {
label: t('MCP Server'),
icon: McpSvg,
subItems: [
- { to: '/platform/mcp', label: t('Connection'), end: true },
- { to: '/platform/mcp/tools', label: t('Tools') },
+ { to: '/platform/mcp', label: t('Tools'), end: true },
{ to: '/platform/mcp/activity', label: t('Activity') },
],
},
diff --git a/packages/web/src/app/routes/mcp-server/activity/activity-columns.tsx b/packages/web/src/app/routes/mcp-server/activity/activity-columns.tsx
index 5865874d75f..8e65238c3bd 100644
--- a/packages/web/src/app/routes/mcp-server/activity/activity-columns.tsx
+++ b/packages/web/src/app/routes/mcp-server/activity/activity-columns.tsx
@@ -8,7 +8,7 @@ import { DataTableColumnHeader } from '@/components/custom/data-table/data-table
import { StatusIconWithText } from '@/components/custom/status-icon-with-text';
import { TextWithTooltip } from '@/components/custom/text-with-tooltip';
import { Badge } from '@/components/ui/badge';
-import { PieceIconWithPieceName } from '@/features/pieces/components/piece-icon-from-name';
+import { PieceIcon } from '@/features/pieces/components/piece-icon';
import { ClientIcon } from '../client-icon';
import { mcpClientDisplay } from '../mcp-client-display';
@@ -20,6 +20,7 @@ export function buildActivityColumns({
showMember,
resolveActionDisplayName,
resolvePieceDisplayName,
+ resolvePieceLogoUrl,
resolveProjectType,
}: BuildActivityColumnsParams): ActivityColumn[] {
const when: ActivityColumn = {
@@ -29,7 +30,7 @@ export function buildActivityColumns({
<DataTableColumnHeader column={column} title={t('When')} icon={Clock} />
),
cell: ({ row }) => (
- <div className="text-gray-11">
+ <div className="whitespace-nowrap text-gray-11">
{activityUtils.formatWhen(row.original.created)}
</div>
),
@@ -71,7 +72,7 @@ export function buildActivityColumns({
if (!rowMember) {
return <div className="text-gray-11">—</div>;
}
- const name = `${rowMember.firstName} ${rowMember.lastName}`.trim();
+ const name = activityUtils.memberName(rowMember);
return (
<TextWithTooltip tooltipMessage={rowMember.email}>
<div className="truncate text-gray-11">
@@ -99,9 +100,11 @@ export function buildActivityColumns({
return (
<div className="flex min-w-0 items-center gap-2.5">
{row.original.pieceName !== null && (
- <PieceIconWithPieceName
- pieceName={row.original.pieceName}
+ <PieceIcon
+ logoUrl={resolvePieceLogoUrl(row.original)}
+ displayName={resolvePieceDisplayName(row.original)}
showTooltip={false}
+ border
size="sm"
/>
)}
@@ -184,5 +187,6 @@ type BuildActivityColumnsParams = {
showMember: boolean;
resolveActionDisplayName: (row: PopulatedMcpActivity) => string | undefined;
resolvePieceDisplayName: (row: PopulatedMcpActivity) => string | undefined;
+ resolvePieceLogoUrl: (row: PopulatedMcpActivity) => string | undefined;
resolveProjectType: (row: PopulatedMcpActivity) => ProjectType | undefined;
};
diff --git a/packages/web/src/app/routes/mcp-server/activity/activity-detail-sheet.tsx b/packages/web/src/app/routes/mcp-server/activity/activity-detail-sheet.tsx
index 4616d198a2e..149f92a4294 100644
--- a/packages/web/src/app/routes/mcp-server/activity/activity-detail-sheet.tsx
+++ b/packages/web/src/app/routes/mcp-server/activity/activity-detail-sheet.tsx
@@ -1,43 +1,123 @@
import { PopulatedMcpActivity, ProjectType } from '@activepieces/shared';
import { t } from 'i18next';
-import { Check, X } from 'lucide-react';
-import { ReactNode } from 'react';
+import { Check, ChevronDown, ChevronUp, X } from 'lucide-react';
+import React, { ReactNode, useRef } from 'react';
+import { LogoPlate } from '@/components/custom/logo-plate';
import { SimpleJsonViewer } from '@/components/custom/simple-json-viewer';
import { LoadingSpinner } from '@/components/custom/spinner';
import { StatusIconWithText } from '@/components/custom/status-icon-with-text';
+import { UserAvatar } from '@/components/custom/user-avatar';
import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from '@/components/ui/collapsible';
import {
Sheet,
+ SheetClose,
SheetContent,
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet';
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/components/ui/tooltip';
+import { PieceIcon } from '@/features/pieces/components/piece-icon';
import { formatUtils } from '@/lib/format-utils';
+import { cn } from '@/lib/utils';
+import { ClientIcon } from '../client-icon';
import { mcpActivityQueries } from '../mcp-activity-hooks';
import { mcpClientDisplay } from '../mcp-client-display';
-import { activityUtils } from './activity-utils';
+import { activityUtils, ParsedOutput } from './activity-utils';
export function ActivityDetailSheet({
row,
onClose,
actionDisplayName,
pieceDisplayName,
+ pieceLogoUrl,
currentUserId,
projectType,
+ onPrevious,
+ onNext,
}: ActivityDetailSheetProps) {
+ const focusTargetRef = useRef<HTMLDivElement>(null);
+
+ const handleKeyDown = (event: React.KeyboardEvent) => {
+ if (
+ event.target instanceof Element &&
+ event.target.closest('[data-activity-body]') !== null
+ ) {
+ return;
+ }
+ if (event.key === 'ArrowUp' && onPrevious) {
+ event.preventDefault();
+ onPrevious();
+ }
+ if (event.key === 'ArrowDown' && onNext) {
+ event.preventDefault();
+ onNext();
+ }
+ };
+
return (
<Sheet open={row !== null} onOpenChange={(open) => !open && onClose()}>
- <SheetContent className="flex w-[480px] flex-col p-0 sm:max-w-[480px]">
+ <SheetContent
+ hideCloseButton
+ overlayClassName="bg-scrim/40"
+ onKeyDown={handleKeyDown}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ focusTargetRef.current?.focus();
+ }}
+ className="flex w-full flex-col gap-0 p-0 sm:w-[480px] sm:max-w-[480px]"
+ >
{row !== null && (
<ActivityDetail
+ key={row.id}
row={row}
actionDisplayName={actionDisplayName}
pieceDisplayName={pieceDisplayName}
+ pieceLogoUrl={pieceLogoUrl}
currentUserId={currentUserId}
projectType={projectType}
+ controls={
+ <div
+ ref={focusTargetRef}
+ tabIndex={-1}
+ className="flex shrink-0 items-center gap-1 outline-none"
+ >
+ <NavButton
+ label={t('Previous')}
+ shortcut="↑"
+ icon={ChevronUp}
+ onClick={onPrevious}
+ />
+ <NavButton
+ label={t('Next')}
+ shortcut="↓"
+ icon={ChevronDown}
+ onClick={onNext}
+ />
+ <SheetClose asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="text-gray-11"
+ aria-label={t('Close')}
+ >
+ <X className="size-4" />
+ </Button>
+ </SheetClose>
+ </div>
+ }
/>
)}
</SheetContent>
@@ -49,45 +129,71 @@ function ActivityDetail({
row,
actionDisplayName,
pieceDisplayName,
+ pieceLogoUrl,
currentUserId,
projectType,
+ controls,
}: ActivityDetailProps) {
const { action, piece } = activityUtils.formatRan({
row,
actionDisplayName,
pieceDisplayName,
});
- const memberName = row.member
- ? `${row.member.firstName} ${row.member.lastName}`.trim() ||
- row.member.email
- : null;
+ const memberName =
+ row.member === null ? null : activityUtils.memberName(row.member);
return (
<>
- <SheetHeader className="shrink-0 border-b px-6 py-4">
- <SheetTitle className="flex flex-wrap items-center gap-2">
- <span>{action}</span>
- {piece !== null && (
- <span className="font-normal text-gray-11">{piece}</span>
- )}
- </SheetTitle>
- <div className="flex items-center gap-3 pt-1">
- {row.status === 'SUCCEEDED' ? (
- <StatusIconWithText
- icon={Check}
- text={t('Succeeded')}
- variant="success"
+ <SheetHeader className="shrink-0 flex-row items-center gap-3 border-b py-3 pr-3 pl-6">
+ {pieceLogoUrl !== undefined && (
+ <div className="hidden shrink-0 sm:block">
+ <PieceIcon
+ logoUrl={pieceLogoUrl}
+ displayName={pieceDisplayName}
+ size="md"
+ border
+ showTooltip={false}
/>
- ) : (
- <StatusIconWithText icon={X} text={t('Failed')} variant="error" />
- )}
- <span className="text-sm text-gray-11">
- {formatUtils.formatDuration(row.durationMs)}
- </span>
+ </div>
+ )}
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <SheetTitle className="truncate">{action}</SheetTitle>
+ <div className="flex min-w-0 flex-col gap-y-0.5 text-sm text-gray-11 sm:flex-row sm:items-center sm:gap-x-2">
+ {piece !== null && (
+ <span className="flex min-w-0 items-center gap-2">
+ <span className="truncate">{piece}</span>
+ <span aria-hidden className="hidden sm:inline">
+ ·
+ </span>
+ </span>
+ )}
+ <span className="flex shrink-0 items-center gap-2">
+ {row.status === 'SUCCEEDED' ? (
+ <StatusIconWithText
+ icon={Check}
+ text={t('Succeeded')}
+ variant="success"
+ />
+ ) : (
+ <StatusIconWithText
+ icon={X}
+ text={t('Failed')}
+ variant="error"
+ />
+ )}
+ <span aria-hidden>·</span>
+ <span>{formatUtils.formatDuration(row.durationMs, true)}</span>
+ </span>
+ </div>
</div>
+ {controls}
</SheetHeader>
- <div className="flex-1 overflow-y-auto px-6 py-4">
+ <div
+ data-activity-body
+ tabIndex={0}
+ className="flex-1 overflow-y-auto px-6 py-4 outline-none focus-visible:ring-2 focus-visible:ring-accent-8"
+ >
<dl className="flex flex-col gap-3 text-sm">
<DetailRow
label={t('When')}
@@ -95,19 +201,36 @@ function ActivityDetail({
/>
<DetailRow
label={t('Client')}
- value={mcpClientDisplay.label({
- key: row.clientKey,
- clientName: null,
- })}
+ value={
+ <span className="flex items-center gap-2">
+ <ClientIcon
+ icon={mcpClientDisplay.icon(row.clientKey)}
+ className="size-5"
+ />
+ {mcpClientDisplay.label({
+ key: row.clientKey,
+ clientName: null,
+ })}
+ </span>
+ }
/>
<DetailRow
label={t('Member')}
value={
- memberName === null
- ? null
- : row.member?.id === currentUserId
- ? t('{name} · you', { name: memberName })
- : memberName
+ row.member === null || memberName === null ? null : (
+ <span className="flex items-center gap-2">
+ <UserAvatar
+ name={memberName}
+ email={row.member.email}
+ imageUrl={row.member.imageUrl}
+ size={20}
+ disableTooltip
+ />
+ {row.member.id === currentUserId
+ ? t('{name} · you', { name: memberName })
+ : memberName}
+ </span>
+ )
}
/>
<DetailRow
@@ -132,7 +255,12 @@ function ActivityDetail({
/>
<DetailRow
label={t('Account')}
- value={activityUtils.formatAccount(row)}
+ value={
+ <AccountValue
+ pieceLogoUrl={pieceLogoUrl}
+ account={activityUtils.formatAccount(row)}
+ />
+ }
/>
</dl>
@@ -141,14 +269,14 @@ function ActivityDetail({
<div className="mb-1 text-xs font-semibold uppercase tracking-wide text-danger-11">
{t('Error')}
</div>
- <pre className="whitespace-pre-wrap break-words text-xs text-danger-11">
- {row.errorMessage}
- </pre>
+ <p className="whitespace-pre-wrap break-words text-sm text-danger-11">
+ {activityUtils.errorText(row.errorMessage)}
+ </p>
</div>
)}
{row.hasPayload ? (
- <ActivityPayload id={row.id} />
+ <ActivityPayload id={row.id} showOutput={row.status !== 'FAILED'} />
) : (
<p className="mt-5 text-sm text-gray-11">
{t('The input and output were not kept for this call.')}
@@ -159,7 +287,13 @@ function ActivityDetail({
);
}
-function ActivityPayload({ id }: { id: string }) {
+function ActivityPayload({
+ id,
+ showOutput,
+}: {
+ id: string;
+ showOutput: boolean;
+}) {
const { data, isLoading, isError } = mcpActivityQueries.usePayload({ id });
if (isLoading) {
@@ -185,12 +319,55 @@ function ActivityPayload({ id }: { id: string }) {
{t('Too large to keep in full — some of it was dropped.')}
</p>
)}
- <PayloadSection label={t('Input')} data={data.input} />
- <PayloadSection label={t('Output')} data={data.output} />
+ <PayloadSection
+ label={t('Input')}
+ data={activityUtils.actionInput(data.input)}
+ />
+ {showOutput ? (
+ <OutputSection output={activityUtils.parseOutput(data.output)} />
+ ) : (
+ <Collapsible className="flex flex-col gap-2">
+ <CollapsibleTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="w-fit px-0 text-gray-11"
+ >
+ {t('Show full output')}
+ </Button>
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <PayloadValue data={data.output} />
+ </CollapsibleContent>
+ </Collapsible>
+ )}
+ </div>
+ );
+}
+
+function OutputSection({ output }: { output: ParsedOutput }) {
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="text-xs font-semibold uppercase tracking-wide text-gray-11">
+ {t('Output')}
+ </div>
+ {output.summary !== null && <p className="text-sm">{output.summary}</p>}
+ {output.data !== null && <PayloadValue data={output.data} />}
</div>
);
}
+function PayloadValue({ data }: { data: unknown }) {
+ if (typeof data === 'string') {
+ return (
+ <pre className="whitespace-pre-wrap break-words rounded-md border bg-gray-2 p-3 text-xs">
+ {data}
+ </pre>
+ );
+ }
+ return <SimpleJsonViewer data={data} maxHeight={260} fontSize="12px" />;
+}
+
function PayloadSection({ label, data }: { label: string; data: unknown }) {
return (
<div className="flex flex-col gap-2">
@@ -200,12 +377,65 @@ function PayloadSection({ label, data }: { label: string; data: unknown }) {
{data === null || data === undefined ? (
<div className="text-sm text-gray-11">—</div>
) : (
- <SimpleJsonViewer data={data} maxHeight={260} fontSize="12px" />
+ <PayloadValue data={data} />
)}
</div>
);
}
+function AccountValue({
+ pieceLogoUrl,
+ account,
+}: {
+ pieceLogoUrl: string | undefined;
+ account: string | null;
+}) {
+ if (account === null) {
+ return null;
+ }
+ return (
+ <span className="flex items-center gap-2">
+ {pieceLogoUrl !== undefined && (
+ <LogoPlate
+ src={pieceLogoUrl}
+ alt=""
+ border
+ className="size-5"
+ innerClassName="size-[62%]"
+ />
+ )}
+ {account}
+ </span>
+ );
+}
+
+function NavButton({ label, shortcut, icon: Icon, onClick }: NavButtonProps) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className={cn(
+ 'text-gray-11',
+ !onClick && 'cursor-default opacity-50',
+ )}
+ aria-disabled={!onClick}
+ onClick={onClick}
+ aria-label={label}
+ >
+ <Icon className="size-4" />
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ {label} <span className="text-gray-11">{shortcut}</span>
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
function DetailRow({ label, value }: { label: string; value: ReactNode }) {
return (
<div className="flex gap-4">
@@ -220,14 +450,26 @@ type ActivityDetailSheetProps = {
onClose: () => void;
actionDisplayName: string | undefined;
pieceDisplayName: string | undefined;
+ pieceLogoUrl: string | undefined;
currentUserId: string | undefined;
projectType: ProjectType | undefined;
+ onPrevious?: () => void;
+ onNext?: () => void;
+};
+
+type NavButtonProps = {
+ label: string;
+ shortcut: string;
+ icon: React.ComponentType<{ className?: string }>;
+ onClick: (() => void) | undefined;
};
type ActivityDetailProps = {
row: PopulatedMcpActivity;
+ controls: React.ReactNode;
actionDisplayName: string | undefined;
pieceDisplayName: string | undefined;
+ pieceLogoUrl: string | undefined;
currentUserId: string | undefined;
projectType: ProjectType | undefined;
};
diff --git a/packages/web/src/app/routes/mcp-server/activity/activity-feed.tsx b/packages/web/src/app/routes/mcp-server/activity/activity-feed.tsx
index 5978489b0cf..caafe71f0ab 100644
--- a/packages/web/src/app/routes/mcp-server/activity/activity-feed.tsx
+++ b/packages/web/src/app/routes/mcp-server/activity/activity-feed.tsx
@@ -5,7 +5,7 @@ import {
} from '@activepieces/shared';
import { t } from 'i18next';
import { Activity, CircleCheck, FolderOpen, Plug, User } from 'lucide-react';
-import { ReactNode, useMemo, useState } from 'react';
+import { ReactNode, useCallback, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import {
@@ -32,12 +32,17 @@ import { mcpClientDisplay } from '../mcp-client-display';
import { buildActivityColumns } from './activity-columns';
import { ActivityDetailSheet } from './activity-detail-sheet';
+import { ActivitySelection, activityUtils } from './activity-utils';
const DEFAULT_PAGE_SIZE = 10;
-export function ActivityFeed({ emptyStateAction }: ActivityFeedProps) {
- const [searchParams] = useSearchParams();
- const [selected, setSelected] = useState<PopulatedMcpActivity | null>(null);
+export function ActivityFeed({
+ emptyStateAction,
+ emptyStateTitle,
+ emptyStateDescription,
+}: ActivityFeedProps) {
+ const [searchParams, setSearchParams] = useSearchParams();
+ const [selection, setSelection] = useState<ActivitySelection | null>(null);
const { data: currentUser } = userHooks.useCurrentUser();
const isPrivileged = useIsPlatformPrivileged();
const { data: memberProjects = [] } = projectCollectionUtils.useAll();
@@ -71,7 +76,7 @@ export function ActivityFeed({ emptyStateAction }: ActivityFeedProps) {
request.createdAfter !== undefined ||
request.createdBefore !== undefined;
- const { data, isLoading, isError, isPaused, refetch } =
+ const { data, isLoading, isError, isPaused, isPlaceholderData, refetch } =
mcpActivityQueries.useActivity({
request,
});
@@ -81,46 +86,120 @@ export function ActivityFeed({ emptyStateAction }: ActivityFeedProps) {
() => distinctPieceNames(data?.data ?? []),
[data?.data],
);
- const pieceQueries = piecesHooks.useMultiplePieces({ names: pieceNames });
- const piecesByName = useMemo(
- () =>
- new Map(
- pieceQueries
- .map((query) => query.data)
- .filter((piece) => piece !== undefined)
- .map((piece) => [piece.name, piece]),
- ),
- [pieceQueries],
- );
+ const piecesByName = piecesHooks.usePiecesByName({ names: pieceNames });
- const resolvePieceDisplayName = (row: PopulatedMcpActivity) =>
- row.pieceName === null
- ? undefined
- : piecesByName.get(row.pieceName)?.displayName;
+ const resolvePieceDisplayName = useCallback(
+ (row: PopulatedMcpActivity) =>
+ row.pieceName === null
+ ? undefined
+ : piecesByName.get(row.pieceName)?.displayName,
+ [piecesByName],
+ );
const projectTypes = useMemo(
() => new Map(projects.map((project) => [project.id, project.type])),
[projects],
);
- const resolveProjectType = (row: PopulatedMcpActivity) =>
- row.projectId === null ? undefined : projectTypes.get(row.projectId);
+ const resolvePieceLogoUrl = useCallback(
+ (row: PopulatedMcpActivity) =>
+ row.pieceName === null
+ ? undefined
+ : piecesByName.get(row.pieceName)?.logoUrl,
+ [piecesByName],
+ );
+
+ const resolveProjectType = useCallback(
+ (row: PopulatedMcpActivity) =>
+ row.projectId === null ? undefined : projectTypes.get(row.projectId),
+ [projectTypes],
+ );
+
+ const resolveActionDisplayName = useCallback(
+ (row: PopulatedMcpActivity) => {
+ if (row.pieceName === null || row.actionName === null) {
+ return undefined;
+ }
+ return piecesByName.get(row.pieceName)?.actions?.[row.actionName]
+ ?.displayName;
+ },
+ [piecesByName],
+ );
+
+ const rows = data?.data ?? [];
+ const selected = activityUtils.resolveSelection({
+ selection,
+ rows,
+ cursor: request.cursor,
+ isPlaceholderData,
+ });
+ if (
+ selection?.pending !== undefined &&
+ selected !== null &&
+ selected !== selection.row
+ ) {
+ setSelection({ row: selected });
+ }
+ const selectedIndex =
+ selected === null ? -1 : rows.findIndex((row) => row.id === selected.id);
- const resolveActionDisplayName = (row: PopulatedMcpActivity) => {
- if (row.pieceName === null || row.actionName === null) {
- return undefined;
+ const goToPage = ({
+ cursor,
+ edge,
+ }: {
+ cursor: string;
+ edge: 'first' | 'last';
+ }) => {
+ if (selected === null) {
+ return;
}
- return piecesByName.get(row.pieceName)?.actions?.[row.actionName]
- ?.displayName;
+ setSelection({ row: selected, pending: { cursor, edge } });
+ setSearchParams(
+ (prev) => {
+ const next = new URLSearchParams(prev);
+ next.set(CURSOR_QUERY_PARAM, cursor);
+ return next;
+ },
+ { replace: true },
+ );
};
- const columns = buildActivityColumns({
- currentUserId: currentUser?.id,
- showMember: isPrivileged,
- resolveActionDisplayName,
- resolvePieceDisplayName,
- resolveProjectType,
- });
+ const previousPageCursor = data?.previous ?? null;
+ const nextPageCursor = data?.next ?? null;
+ const onPrevious =
+ selectedIndex > 0
+ ? () => setSelection({ row: rows[selectedIndex - 1] })
+ : selectedIndex === 0 && previousPageCursor !== null
+ ? () => goToPage({ cursor: previousPageCursor, edge: 'last' })
+ : undefined;
+ const onNext =
+ selectedIndex >= 0 && selectedIndex < rows.length - 1
+ ? () => setSelection({ row: rows[selectedIndex + 1] })
+ : selectedIndex >= 0 &&
+ selectedIndex === rows.length - 1 &&
+ nextPageCursor !== null
+ ? () => goToPage({ cursor: nextPageCursor, edge: 'first' })
+ : undefined;
+
+ const columns = useMemo(
+ () =>
+ buildActivityColumns({
+ currentUserId: currentUser?.id,
+ showMember: isPrivileged,
+ resolveActionDisplayName,
+ resolvePieceDisplayName,
+ resolvePieceLogoUrl,
+ resolveProjectType,
+ }),
+ [
+ currentUser?.id,
+ isPrivileged,
+ resolveActionDisplayName,
+ resolvePieceDisplayName,
+ resolvePieceLogoUrl,
+ resolveProjectType,
+ ],
+ );
if (
!isLoading &&
@@ -135,11 +214,12 @@ export function ActivityFeed({ emptyStateAction }: ActivityFeedProps) {
<EmptyMedia variant="icon">
<Activity />
</EmptyMedia>
- <EmptyTitle>{t('Nothing has run yet')}</EmptyTitle>
+ <EmptyTitle>{emptyStateTitle ?? t('Nothing has run yet')}</EmptyTitle>
<EmptyDescription>
- {t(
- 'A client can be connected and still never run anything. Check Connections to confirm it signed in.',
- )}
+ {emptyStateDescription ??
+ t(
+ 'A client can be connected and still never run anything. Check Connections to confirm it signed in.',
+ )}
</EmptyDescription>
{emptyStateAction}
</EmptyHeader>
@@ -161,7 +241,10 @@ export function ActivityFeed({ emptyStateAction }: ActivityFeedProps) {
members: isPrivileged ? users?.data ?? [] : [],
})}
bordered={true}
- onRowClick={(row) => setSelected(row)}
+ onRowClick={(row) => setSelection({ row })}
+ getRowClassName={(row) =>
+ row.id === selected?.id ? 'bg-accent-3 hover:bg-accent-4' : ''
+ }
emptyStateTextTitle={t('No runs match these filters')}
emptyStateTextDescription={t('Clear a filter to see more.')}
emptyStateIcon={<Activity className="size-10" />}
@@ -169,7 +252,9 @@ export function ActivityFeed({ emptyStateAction }: ActivityFeedProps) {
<ActivityDetailSheet
row={selected}
- onClose={() => setSelected(null)}
+ onClose={() => setSelection(null)}
+ onPrevious={isPlaceholderData ? undefined : onPrevious}
+ onNext={isPlaceholderData ? undefined : onNext}
currentUserId={currentUser?.id}
actionDisplayName={
selected === null ? undefined : resolveActionDisplayName(selected)
@@ -177,6 +262,9 @@ export function ActivityFeed({ emptyStateAction }: ActivityFeedProps) {
pieceDisplayName={
selected === null ? undefined : resolvePieceDisplayName(selected)
}
+ pieceLogoUrl={
+ selected === null ? undefined : resolvePieceLogoUrl(selected)
+ }
projectType={
selected === null ? undefined : resolveProjectType(selected)
}
@@ -233,7 +321,7 @@ function buildFilters({
accessorKey: 'member',
icon: User,
options: members.map((member) => ({
- label: `${member.firstName} ${member.lastName}`.trim() || member.email,
+ label: activityUtils.memberName(member),
value: member.id,
})),
});
@@ -273,6 +361,8 @@ function buildFilters({
type ActivityFeedProps = {
emptyStateAction?: ReactNode;
+ emptyStateTitle?: string;
+ emptyStateDescription?: string;
};
type BuildFiltersParams = {
diff --git a/packages/web/src/app/routes/mcp-server/activity/activity-utils.ts b/packages/web/src/app/routes/mcp-server/activity/activity-utils.ts
index b26a4049bc5..b2a4bd18f27 100644
--- a/packages/web/src/app/routes/mcp-server/activity/activity-utils.ts
+++ b/packages/web/src/app/routes/mcp-server/activity/activity-utils.ts
@@ -1,3 +1,4 @@
+import { tryCatchSync } from '@activepieces/core-utils';
import { PopulatedMcpActivity } from '@activepieces/shared';
import dayjs from 'dayjs';
import { t } from 'i18next';
@@ -35,7 +36,103 @@ function formatAccount(row: PopulatedMcpActivity): string | null {
return row.connectionDisplayName ?? row.connectionExternalId;
}
-export const activityUtils = { formatWhen, formatRan, formatAccount };
+function parseOutput(output: unknown): ParsedOutput {
+ const text = toolResultText(output);
+ if (text === null) {
+ return { summary: null, data: output ?? null };
+ }
+ const [firstParagraph, ...rest] = text.split(/\n\s*\n/);
+ const remainder = rest.join('\n\n').trim();
+ return {
+ summary: stripStatusMark(firstParagraph.trim()),
+ data: remainder.length === 0 ? null : parseJsonOrText(remainder),
+ };
+}
+
+function actionInput(input: unknown): unknown {
+ if (isRecord(input) && 'pieceName' in input && 'actionName' in input) {
+ return input.input ?? null;
+ }
+ return input ?? null;
+}
+
+function errorText(errorMessage: string): string {
+ return errorMessage
+ .split(/\n\s*\n/)
+ .map((paragraph) => paragraph.trim())
+ .filter(
+ (paragraph) =>
+ paragraph.length > 0 && !paragraph.startsWith('Retry suggestion:'),
+ )
+ .map((paragraph, index) =>
+ index === 0 ? stripStatusMark(paragraph) : paragraph,
+ )
+ .join('\n\n');
+}
+
+function memberName(member: MemberNameParts): string {
+ return `${member.firstName} ${member.lastName}`.trim() || member.email;
+}
+
+function resolveSelection({
+ selection,
+ rows,
+ cursor,
+ isPlaceholderData,
+}: ResolveSelectionParams): PopulatedMcpActivity | null {
+ if (selection === null) {
+ return null;
+ }
+ const { pending } = selection;
+ const landed =
+ pending !== undefined &&
+ pending.cursor === cursor &&
+ !isPlaceholderData &&
+ rows.length > 0;
+ if (!landed) {
+ return selection.row;
+ }
+ return pending.edge === 'first' ? rows[0] : rows[rows.length - 1];
+}
+
+function toolResultText(output: unknown): string | null {
+ if (!Array.isArray(output) || output.length === 0) {
+ return null;
+ }
+ const texts = output.map((part) =>
+ isRecord(part) && part.type === 'text' && typeof part.text === 'string'
+ ? part.text
+ : null,
+ );
+ if (texts.some((text) => text === null)) {
+ return null;
+ }
+ return texts.join('\n\n');
+}
+
+function parseJsonOrText(value: string): unknown {
+ const { data, error } = tryCatchSync<unknown>(() => JSON.parse(value));
+ return error === null ? data : value;
+}
+
+function stripStatusMark(value: string): string {
+ return value.replace(/^(✅|❌|⏳)\s*/u, '');
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+export const activityUtils = {
+ formatWhen,
+ formatRan,
+ formatAccount,
+ parseOutput,
+ actionInput,
+ errorText,
+ memberName,
+ resolveSelection,
+};
export type Ran = {
action: string;
@@ -47,3 +144,26 @@ type FormatRanParams = {
actionDisplayName: string | undefined;
pieceDisplayName: string | undefined;
};
+
+export type ParsedOutput = {
+ summary: string | null;
+ data: unknown;
+};
+
+export type ActivitySelection = {
+ row: PopulatedMcpActivity;
+ pending?: { cursor: string; edge: 'first' | 'last' };
+};
+
+type MemberNameParts = {
+ firstName: string;
+ lastName: string;
+ email: string;
+};
+
+type ResolveSelectionParams = {
+ selection: ActivitySelection | null;
+ rows: PopulatedMcpActivity[];
+ cursor: string | undefined;
+ isPlaceholderData: boolean;
+};
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.tsx
index ef0c68ef399..b5955c7b8fb 100644
--- a/packages/web/src/app/routes/mcp-server/tools/tools-tab.tsx
+++ b/packages/web/src/app/routes/mcp-server/tools/tools-tab.tsx
@@ -2,7 +2,7 @@ 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 { McpToolTierList } from '@/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tier-list';
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';
@@ -46,9 +46,6 @@ export function ToolsTab({
error,
refetch,
} = mcpHooks.useMcpServer(selectedProjectId ?? '');
- const { mutate: updateMcpServer, isPending } = mcpHooks.useUpdateMcpServer(
- selectedProjectId ?? '',
- );
const { data: toolSearchEnabled } = flagsHooks.useFlag<boolean>(
ApFlagId.TOOL_SEARCH_ENABLED,
);
@@ -75,9 +72,6 @@ export function ToolsTab({
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">
@@ -141,19 +135,36 @@ export function ToolsTab({
onShowBuiltIn={() => selectSegment('built-in')}
/>
) : (
- <McpTools
+ <ProjectToolTiers
key={selectedProjectId}
+ projectId={selectedProjectId ?? ''}
disabledTools={mcpServer.disabledTools}
platformDisabledTools={mcpServer.platformDisabledTools}
- projectId={selectedProjectId ?? undefined}
- isPending={isPending}
- onUpdateDisabledTools={updateDisabledTools}
/>
)}
</PageBand>
);
}
+function ProjectToolTiers({
+ projectId,
+ disabledTools,
+ platformDisabledTools,
+}: ProjectToolTiersProps) {
+ const { mutate: updateMcpServer } = mcpHooks.useUpdateMcpServer(projectId);
+ return (
+ <McpToolTierList
+ disabledTools={disabledTools}
+ platformDisabledTools={platformDisabledTools}
+ scope="project"
+ projectId={projectId}
+ onUpdateDisabledTools={({ tools, onSettled }) =>
+ updateMcpServer({ disabledTools: tools }, { onSettled })
+ }
+ />
+ );
+}
+
function SegmentCount({ count }: { count: number | null }) {
if (isNil(count)) {
return null;
@@ -174,6 +185,12 @@ type ToolsUnavailableAlertProps = {
onRetry: () => void;
};
+type ProjectToolTiersProps = {
+ projectId: string;
+ disabledTools: string[] | null;
+ platformDisabledTools: string[];
+};
+
type ToolsTabProps = {
projectId: string | null;
reachableProjectIds: string[] | null;
diff --git a/packages/web/src/app/routes/platform-routes.tsx b/packages/web/src/app/routes/platform-routes.tsx
index e7820e35c32..7dcc2b677a7 100644
--- a/packages/web/src/app/routes/platform-routes.tsx
+++ b/packages/web/src/app/routes/platform-routes.tsx
@@ -184,9 +184,9 @@ export const platformRoutes = [
path: '/platform/mcp',
element: (
<PlatformLayout>
- <PageTitle title="MCP Server">
+ <PageTitle title="MCP Tools">
<SuspenseWrapper>
- <PlatformMcpPage section="connection" />
+ <PlatformMcpPage section="access" />
</SuspenseWrapper>
</PageTitle>
</PlatformLayout>
@@ -194,15 +194,7 @@ export const platformRoutes = [
},
{
path: '/platform/mcp/tools',
- element: (
- <PlatformLayout>
- <PageTitle title="MCP Tools">
- <SuspenseWrapper>
- <PlatformMcpPage section="tools" />
- </SuspenseWrapper>
- </PageTitle>
- </PlatformLayout>
- ),
+ element: <Navigate to="/platform/mcp" replace />,
},
{
path: '/platform/mcp/activity',
diff --git a/packages/web/src/app/routes/platform/setup/mcp/index.tsx b/packages/web/src/app/routes/platform/setup/mcp/index.tsx
index 33d92305696..1c2e51a60bb 100644
--- a/packages/web/src/app/routes/platform/setup/mcp/index.tsx
+++ b/packages/web/src/app/routes/platform/setup/mcp/index.tsx
@@ -1,142 +1,100 @@
-import { ApFlagId } from '@activepieces/shared';
import { t } from 'i18next';
+import { Link } from 'react-router-dom';
import { CenteredPage } from '@/app/components/centered-page';
-import { McpTools } from '@/app/components/project-settings/mcp-server/mcp-tools';
+import { McpToolTierList } from '@/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tier-list';
import { ActivityFeed } from '@/app/routes/mcp-server/activity/activity-feed';
-import { CopyToClipboardInput } from '@/components/custom/clipboard/copy-to-clipboard';
-import { CollapsibleJson } from '@/components/custom/collapsible-json';
import { DataFetchErrorState } from '@/components/custom/data-fetch-error-state';
import { LoadingSpinner } from '@/components/custom/spinner';
-import { flagsHooks } from '@/hooks/flags-hooks';
+import { platformHooks } from '@/hooks/platform-hooks';
import { platformMcpHooks } from './platform-mcp-hooks';
export default function PlatformMcpPage({ section }: PlatformMcpPageProps) {
+ const { platform } = platformHooks.useCurrentPlatform();
+ return (
+ <CenteredPage
+ widthClassName={section === 'activity' ? 'max-w-[1198px]' : undefined}
+ showHeaderSeparator={false}
+ title={section === 'access' ? t('MCP Tools') : t('MCP Activity')}
+ description={
+ section === 'access' ? (
+ <>
+ {t(
+ "Choose which tools MCP clients can use in every project and in AI Chat. Clients act with the signed-in user's permissions.",
+ )}
+ {platform.plan.projectRolesEnabled && (
+ <>
+ {' '}
+ <Link
+ to="/platform/users/roles"
+ className="text-accent-11 underline underline-offset-4"
+ >
+ {t('Manage roles')}
+ </Link>
+ </>
+ )}
+ </>
+ ) : (
+ t(
+ 'Piece actions run by MCP clients, like Claude and Cursor. Other tool calls are not logged.',
+ )
+ )
+ }
+ >
+ <div className="pb-6">
+ {section === 'access' ? <AccessContent /> : <ActivityContent />}
+ </div>
+ </CenteredPage>
+ );
+}
+
+function AccessContent() {
const {
data: mcpServer,
isLoading,
isError,
refetch,
} = platformMcpHooks.usePlatformMcpServer();
- const { mutate: updateTools, isPending: isToolsUpdating } =
- platformMcpHooks.useUpdatePlatformMcpTools();
- const { data: mcpUrl } = flagsHooks.useFlag<string>(ApFlagId.MCP_URL);
+ const { mutate: updateTools } = platformMcpHooks.useUpdatePlatformMcpTools();
if (isLoading) {
return (
- <CenteredPage
- title={t('Platform MCP Server')}
- description={t(
- 'Configure the platform-wide MCP server used by the AI Chat assistant and external MCP clients.',
- )}
- >
- <div className="flex items-center justify-center py-20">
- <LoadingSpinner />
- </div>
- </CenteredPage>
+ <div className="flex items-center justify-center py-20">
+ <LoadingSpinner />
+ </div>
);
}
- if (isError) {
+ if (isError || !mcpServer) {
return (
- <CenteredPage
- title={t('Platform MCP Server')}
- description={t(
- 'Configure the platform-wide MCP server used by the AI Chat assistant and external MCP clients.',
- )}
- >
- <DataFetchErrorState entity={t('the MCP server')} onRetry={refetch} />
- </CenteredPage>
+ <DataFetchErrorState entity={t('the MCP server')} onRetry={refetch} />
);
}
- const serverUrl = `${(mcpUrl ?? '').replace(/\/$/, '')}/mcp/platform`;
-
- const jsonConfiguration = {
- mcpServers: {
- activepieces: {
- url: serverUrl,
- },
- },
- };
+ return (
+ <McpToolTierList
+ disabledTools={mcpServer.disabledTools}
+ scope="platform"
+ onUpdateDisabledTools={({ tools, onSettled }) =>
+ updateTools({ disabledTools: tools }, { onSettled })
+ }
+ />
+ );
+}
+function ActivityContent() {
return (
- <CenteredPage
- widthClassName="max-w-[1198px]"
- title={t('Platform MCP Server')}
- description={t(
- 'Configure the platform-wide MCP server used by the AI Chat assistant and external MCP clients.',
+ <ActivityFeed
+ emptyStateTitle={t('No activity yet')}
+ emptyStateDescription={t(
+ 'When an MCP client runs a piece action, it appears here.',
)}
- >
- <div className="space-y-6">
- {!mcpServer ? null : (
- <>
- {section === 'connection' && (
- <div className="pb-6">
- <div className="space-y-4">
- <div className="flex flex-col gap-1.5">
- <label className="text-sm font-medium">
- {t('Server URL')}
- </label>
- <p className="text-xs text-gray-11">
- {t(
- 'Use this URL to connect from Cursor, Windsurf, Claude Desktop, or any MCP-compatible client. Authentication is handled via OAuth.',
- )}
- </p>
- <CopyToClipboardInput
- textToCopy={serverUrl}
- useInput={true}
- />
- </div>
-
- <CollapsibleJson
- json={jsonConfiguration}
- label={t('JSON Configuration')}
- description={t(
- 'Copy this into your MCP client config (Cursor, Windsurf, Claude Desktop, etc.).',
- )}
- defaultOpen={false}
- />
- </div>
- </div>
- )}
-
- {section === 'tools' && (
- <div className="space-y-6 pb-6">
- <div>
- <h3 className="font-semibold text-base mb-1">
- {t('Internal Tools')}
- </h3>
- <p className="text-sm text-gray-11 mb-3">
- {t(
- 'Switching a tool off here switches it off everywhere on this platform: the AI Chat, external agents, and every project MCP server.',
- )}
- </p>
- <McpTools
- disabledTools={mcpServer.disabledTools}
- isPending={isToolsUpdating}
- onUpdateDisabledTools={(tools) =>
- updateTools({ disabledTools: tools })
- }
- />
- </div>
- </div>
- )}
-
- {section === 'activity' && (
- <div className="flex flex-col gap-2 pb-6">
- <ActivityFeed />
- </div>
- )}
- </>
- )}
- </div>
- </CenteredPage>
+ />
);
}
-type PlatformMcpSection = 'connection' | 'tools' | 'activity';
+type PlatformMcpSection = 'access' | 'activity';
type PlatformMcpPageProps = {
section: PlatformMcpSection;
diff --git a/packages/web/src/app/routes/platform/setup/mcp/platform-mcp-hooks.ts b/packages/web/src/app/routes/platform/setup/mcp/platform-mcp-hooks.ts
index 9cf6a143b49..474cac74c2e 100644
--- a/packages/web/src/app/routes/platform/setup/mcp/platform-mcp-hooks.ts
+++ b/packages/web/src/app/routes/platform/setup/mcp/platform-mcp-hooks.ts
@@ -1,4 +1,6 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { t } from 'i18next';
+import { toast } from 'sonner';
import { platformMcpApi } from './platform-mcp-api';
@@ -16,10 +18,14 @@ export const platformMcpHooks = {
useUpdatePlatformMcpTools() {
const queryClient = useQueryClient();
return useMutation({
+ scope: { id: 'platform-mcp-server-tools' },
mutationFn: platformMcpApi.update,
onSuccess: (data) => {
queryClient.setQueryData(QUERY_KEY, data);
},
+ onError: () => {
+ toast.error(t('The tools could not be saved. Try again.'));
+ },
});
},
};
diff --git a/packages/web/src/components/custom/data-table/index.tsx b/packages/web/src/components/custom/data-table/index.tsx
index c4da63ffff6..f324bcf5d19 100644
--- a/packages/web/src/components/custom/data-table/index.tsx
+++ b/packages/web/src/components/custom/data-table/index.tsx
@@ -213,6 +213,11 @@ export function DataTable<
const [currentCursor, setCurrentCursor] = useState<string | undefined>(
startingCursor,
);
+ const [lastUrlCursor, setLastUrlCursor] = useState(startingCursor);
+ if (startingCursor !== lastUrlCursor) {
+ setLastUrlCursor(startingCursor);
+ setCurrentCursor(startingCursor);
+ }
const [nextPageCursor, setNextPageCursor] = useState<string | undefined>(
page?.next ?? undefined,
);
diff --git a/packages/web/src/components/custom/date-time-picker-range.tsx b/packages/web/src/components/custom/date-time-picker-range.tsx
index fc52dcd8e5e..9e8a938aad7 100644
--- a/packages/web/src/components/custom/date-time-picker-range.tsx
+++ b/packages/web/src/components/custom/date-time-picker-range.tsx
@@ -23,6 +23,7 @@ import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';
export type PresetKey =
+ | 'today'
| '7days'
| '14days'
| '30days'
@@ -63,6 +64,7 @@ const getDayBoundaries = () => {
};
const PRESETS: Record<PresetKey, () => { from: Date; to: Date }> = {
+ today: () => ({ from: startOfDay(new Date()), to: new Date() }),
'7days': () => ({ from: subDays(new Date(), 7), to: new Date() }),
'14days': () => ({ from: subDays(new Date(), 14), to: new Date() }),
'30days': () => ({ from: subDays(new Date(), 30), to: new Date() }),
@@ -75,6 +77,7 @@ const PRESETS: Record<PresetKey, () => { from: Date; to: Date }> = {
const getPresetLabel = (value: string) => {
const labels: Record<string, string> = {
+ today: t('Today'),
'7days': t('Last 7 Days'),
'14days': t('Last 14 Days'),
'30days': t('Last 30 Days'),
@@ -94,10 +97,10 @@ const detectPreset = (
): string | null => {
if (!from || !to) return null;
- const candidates =
+ const candidates: PresetKey[] =
presetType === 'past'
- ? (['7days', '14days', '30days', '90days'] as PresetKey[])
- : (['7', '14', '30', '90'] as PresetKey[]);
+ ? ['today', '7days', '14days', '30days', '90days']
+ : ['7', '14', '30', '90'];
for (const key of candidates) {
const { from: pf, to: pt } = PRESETS[key]();
@@ -262,6 +265,7 @@ export function DateTimePickerWithRange({
<SelectContent>
{presetType === 'past' ? (
<>
+ <SelectItem value="today">{t('Today')}</SelectItem>
<SelectItem value="7days">{t('Last 7 Days')}</SelectItem>
<SelectItem value="14days">{t('Last 14 Days')}</SelectItem>
<SelectItem value="30days">{t('Last 30 Days')}</SelectItem>
diff --git a/packages/web/src/components/ui/sheet.tsx b/packages/web/src/components/ui/sheet.tsx
index e6c067f26d7..fc4cf6a477a 100644
--- a/packages/web/src/components/ui/sheet.tsx
+++ b/packages/web/src/components/ui/sheet.tsx
@@ -49,14 +49,16 @@ function SheetContent({
children,
side = 'right',
hideCloseButton = false,
+ overlayClassName,
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: 'top' | 'right' | 'bottom' | 'left';
hideCloseButton?: boolean;
+ overlayClassName?: string;
}) {
return (
<SheetPortal>
- <SheetOverlay />
+ <SheetOverlay className={overlayClassName} />
<SheetPrimitive.Content
data-slot="sheet-content"
data-side={side}
diff --git a/packages/web/src/components/ui/switch.tsx b/packages/web/src/components/ui/switch.tsx
index 47918e79577..bf0c97954f9 100644
--- a/packages/web/src/components/ui/switch.tsx
+++ b/packages/web/src/components/ui/switch.tsx
@@ -11,6 +11,7 @@ function Switch({
variant = 'default',
size = 'default',
color = 'default',
+ indeterminate = false,
...props
}: SwitchProps) {
const isControlled = props.checked !== undefined;
@@ -32,6 +33,8 @@ function Switch({
COLOR_CLASSES[color],
variant === 'square' ? 'rounded-md' : 'rounded-full',
SIZE_CLASSES[size],
+ indeterminate &&
+ 'justify-center data-[state=unchecked]:border-accent-8 data-[state=unchecked]:bg-accent-5',
className,
)}
onCheckedChange={(checked) =>
@@ -43,6 +46,7 @@ function Switch({
)
}
{...props}
+ data-indeterminate={indeterminate || undefined}
checked={isChecked}
>
<SwitchPrimitive.Thumb
@@ -108,6 +112,7 @@ type SwitchProps = React.ComponentProps<typeof SwitchPrimitive.Root> & {
variant?: 'default' | 'square';
size?: 'default' | 'sm' | 'lg' | 'xl';
color?: 'default' | 'secondary';
+ indeterminate?: boolean;
};
export { Switch };
diff --git a/packages/web/src/features/pieces/hooks/pieces-hooks.ts b/packages/web/src/features/pieces/hooks/pieces-hooks.ts
index bfdbded4d44..c3ce871f3a6 100644
--- a/packages/web/src/features/pieces/hooks/pieces-hooks.ts
+++ b/packages/web/src/features/pieces/hooks/pieces-hooks.ts
@@ -25,6 +25,7 @@ import {
usePrefetchQuery,
useQueries,
useQuery,
+ UseQueryResult,
} from '@tanstack/react-query';
import { t } from 'i18next';
import { useMemo } from 'react';
@@ -153,16 +154,18 @@ export const piecesHooks = {
useMultiplePieces: ({ names }: UseMultiplePiecesProps) => {
const { i18n } = useTranslation();
return useQueries({
- queries: names.map((name) => ({
- queryKey: ['piece', name, undefined, i18n.language],
- queryFn: () =>
- piecesApi.get({
- name,
- version: undefined,
- locale: i18n.language as LocalesEnum,
- }),
- staleTime: Infinity,
- })),
+ queries: names.map((name) =>
+ latestPieceQueryOptions({ name, language: i18n.language }),
+ ),
+ });
+ },
+ usePiecesByName: ({ names }: UseMultiplePiecesProps) => {
+ const { i18n } = useTranslation();
+ return useQueries({
+ queries: names.map((name) =>
+ latestPieceQueryOptions({ name, language: i18n.language }),
+ ),
+ combine: piecesByNameFromResults,
});
},
usePieceSummariesByNames: ({ names }: UseMultiplePiecesProps) => {
@@ -587,6 +590,38 @@ const getExploreTabContent = (
return [popularCategory, hightlightedPiecesCategory];
};
+function latestPieceQueryOptions({
+ name,
+ language,
+}: {
+ name: string;
+ language: string;
+}) {
+ return {
+ queryKey: ['piece', name, undefined, language],
+ queryFn: () =>
+ piecesApi.get({
+ name,
+ version: undefined,
+ locale: Object.values(LocalesEnum).find(
+ (locale) => locale === language,
+ ),
+ }),
+ staleTime: Infinity,
+ };
+}
+
+function piecesByNameFromResults(
+ results: UseQueryResult<PieceMetadataModel>[],
+): Map<string, PieceMetadataModel> {
+ return new Map(
+ results
+ .map((result) => result.data)
+ .filter((piece) => piece !== undefined)
+ .map((piece) => [piece.name, piece]),
+ );
+}
+
function invalidatePieceCaches(queryClient: QueryClient): Promise<void[]> {
const pieceDerivedQueryKeys = [
['pieces'],
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.tsx
deleted file mode 100644
index 195def22767..00000000000
--- a/packages/web/test/app/components/project-settings/mcp-server/mcp-tools.test.tsx
+++ /dev/null
@@ -1,315 +0,0 @@
-/**
- * @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/components/project-settings/mcp-server/tool-tiers/mcp-tool-tier-list.test.tsx b/packages/web/test/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tier-list.test.tsx
new file mode 100644
index 00000000000..89d73a1f51f
--- /dev/null
+++ b/packages/web/test/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tier-list.test.tsx
@@ -0,0 +1,398 @@
+/**
+ * @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 { Permission } from '@activepieces/core-utils';
+import * as React from 'react';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const sheet = vi.hoisted(() => {
+ const state: { latestProps: SheetCallbacks | null } = { latestProps: null };
+ return state;
+});
+
+const debounce = vi.hoisted(() => {
+ const state: { deferred: boolean } = { deferred: false };
+ return state;
+});
+
+const authorization = vi.hoisted(() => {
+ const grantedPermissions: string[] = [];
+ return { grantedPermissions, useAuthorization: vi.fn() };
+});
+
+vi.mock('i18next', () => ({
+ t: (key: string, values?: Record<string, string | number>) =>
+ key.replace(/\{(\w+)\}/g, (match, name: string) =>
+ values && name in values ? String(values[name]) : match,
+ ),
+}));
+
+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', async () => {
+ const { useMemo, useRef } = await import('react');
+ return {
+ useDebouncedCallback: (fn: (tools: string[]) => void) => {
+ const latest = useRef(fn);
+ latest.current = fn;
+ return useMemo(() => {
+ const pending: { args: string[] | null } = { args: null };
+ const debounced = (tools: string[]) => {
+ if (debounce.deferred) {
+ pending.args = tools;
+ return;
+ }
+ latest.current(tools);
+ };
+ return Object.assign(debounced, {
+ flush: () => {
+ if (pending.args !== null) {
+ latest.current(pending.args);
+ pending.args = null;
+ }
+ },
+ });
+ }, []);
+ },
+ };
+});
+
+vi.mock('@/components/ui/tooltip', () => ({
+ Tooltip: ({ children }: ChildrenProps) => <>{children}</>,
+ TooltipTrigger: ({ children }: ChildrenProps) => <>{children}</>,
+ TooltipContent: ({ children }: ChildrenProps) => <span>{children}</span>,
+}));
+
+vi.mock('@/components/ui/switch', () => ({
+ Switch: (props: SwitchMockProps) => (
+ <input
+ type="checkbox"
+ data-switch={props['aria-label']}
+ data-indeterminate={props.indeterminate ? 'true' : undefined}
+ checked={props.checked === true}
+ disabled={props.disabled === true}
+ onChange={(event) => props.onCheckedChange?.(event.target.checked)}
+ />
+ ),
+}));
+
+vi.mock(
+ '@/app/components/project-settings/mcp-server/tool-tiers/mcp-tools-sheet',
+ () => ({
+ McpToolsSheet: (props: SheetCallbacks) => {
+ sheet.latestProps = props;
+ return null;
+ },
+ }),
+);
+
+vi.mock('@/components/custom/delete-dialog', () => ({
+ ConfirmationDeleteDialog: (props: DialogMockProps) =>
+ props.open ? (
+ <div data-dialog="true">
+ <p>{props.message}</p>
+ <button data-confirm="true" onClick={() => props.mutationFn()}>
+ {props.buttonText}
+ </button>
+ </div>
+ ) : null,
+}));
+
+const { McpToolTierList } = await import(
+ '@/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tier-list'
+);
+
+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 DELETE_TOOLS = [
+ 'ap_delete_flow',
+ 'ap_delete_table',
+ 'ap_delete_records',
+ 'ap_manage_fields',
+];
+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<ListProps> & { canWrite?: boolean } = {}) {
+ authorization.grantedPermissions = canWrite
+ ? [Permission.READ_MCP, Permission.WRITE_MCP]
+ : [Permission.READ_MCP];
+ act(() => {
+ root.render(
+ <McpToolTierList
+ disabledTools={[]}
+ scope="project"
+ projectId={PROJECT_ID}
+ onUpdateDisabledTools={() => undefined}
+ {...props}
+ />,
+ );
+ });
+}
+
+function tierSwitch(label: string): HTMLInputElement {
+ const element = container.querySelector<HTMLInputElement>(
+ `input[data-switch^="${label}"]`,
+ );
+ if (!element) {
+ throw new Error(`no switch for ${label}`);
+ }
+ return element;
+}
+
+function toggle(label: string) {
+ act(() => {
+ tierSwitch(label).click();
+ });
+}
+
+function confirm() {
+ act(() => {
+ container.querySelector<HTMLButtonElement>('[data-confirm]')!.click();
+ });
+}
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ authorization.useAuthorization.mockClear();
+ debounce.deferred = false;
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('McpToolTierList write gate', () => {
+ it('checks write access against the project it edits', () => {
+ render();
+
+ expect(authorization.useAuthorization).toHaveBeenCalledWith(PROJECT_ID);
+ });
+
+ it('has no switch for the always-on View tier', () => {
+ render();
+
+ expect(container.querySelector('input[data-switch^="View"]')).toBeNull();
+ expect(container.textContent).toContain('Always on');
+ });
+
+ it('disables every switch and explains why when the role cannot write', () => {
+ render({ canWrite: false });
+
+ const switches = Array.from(
+ container.querySelectorAll<HTMLInputElement>('input[data-switch]'),
+ );
+ expect(switches.length).toBe(3);
+ expect(switches.every((element) => element.disabled)).toBe(true);
+ expect(container.textContent).toContain(READ_ONLY_NOTE);
+ });
+
+ it('does not save when a read-only role toggles a tool from the sheet', () => {
+ const onUpdateDisabledTools = vi.fn();
+ render({ canWrite: false, onUpdateDisabledTools });
+
+ act(() => {
+ sheet.latestProps!.onToggleTool({
+ name: 'ap_create_flow',
+ enabled: false,
+ });
+ sheet.latestProps!.onSetAll({
+ names: ['ap_create_flow'],
+ enabled: false,
+ });
+ });
+
+ expect(onUpdateDisabledTools).not.toHaveBeenCalled();
+ });
+
+ it('lets a platform admin edit whatever their role in the open project', () => {
+ render({ canWrite: false, scope: 'platform' });
+
+ expect(tierSwitch('Edit flows').disabled).toBe(false);
+ expect(container.textContent).not.toContain(READ_ONLY_NOTE);
+ });
+});
+
+describe('McpToolTierList saving', () => {
+ it('turns a whole tier off in one save', () => {
+ const onUpdateDisabledTools = vi.fn();
+ render({ onUpdateDisabledTools });
+
+ toggle('Delete');
+
+ expect(onUpdateDisabledTools).toHaveBeenCalledTimes(1);
+ expect(onUpdateDisabledTools.mock.calls[0][0].tools.sort()).toEqual(
+ [...DELETE_TOOLS].sort(),
+ );
+ });
+
+ it('asks before turning Delete tools on, and saves only once confirmed', () => {
+ const onUpdateDisabledTools = vi.fn();
+ render({ disabledTools: DELETE_TOOLS, onUpdateDisabledTools });
+
+ toggle('Delete');
+
+ expect(onUpdateDisabledTools).not.toHaveBeenCalled();
+ confirm();
+ expect(onUpdateDisabledTools).toHaveBeenCalledTimes(1);
+ expect(onUpdateDisabledTools.mock.calls[0][0].tools).toEqual([]);
+ });
+
+ it('says the Delete confirmation applies to this project on a project page', () => {
+ render({ disabledTools: DELETE_TOOLS });
+
+ toggle('Delete');
+
+ expect(container.querySelector('[data-dialog]')!.textContent).toContain(
+ 'in this project',
+ );
+ });
+
+ it('says the Delete confirmation applies to every project on the platform page', () => {
+ render({ disabledTools: DELETE_TOOLS, scope: 'platform' });
+
+ toggle('Delete');
+
+ expect(container.querySelector('[data-dialog]')!.textContent).toContain(
+ 'in every project',
+ );
+ });
+
+ it('shows the saved value once a save settles, so a failure puts the switch back', () => {
+ render({
+ onUpdateDisabledTools: ({ onSettled }) => onSettled(),
+ });
+
+ toggle('Edit flows');
+
+ expect(tierSwitch('Edit flows').checked).toBe(true);
+ });
+
+ it('keeps a newer change when an older save settles', () => {
+ const settles: (() => void)[] = [];
+ render({
+ onUpdateDisabledTools: ({ onSettled }) => settles.push(onSettled),
+ });
+
+ toggle('Edit flows');
+ toggle('Delete');
+ act(() => settles[0]());
+
+ expect(tierSwitch('Edit flows').checked).toBe(false);
+ expect(tierSwitch('Delete').checked).toBe(false);
+ });
+
+ it('sends a save that was still waiting when the list unmounts', () => {
+ debounce.deferred = true;
+ const onUpdateDisabledTools = vi.fn();
+ render({ onUpdateDisabledTools });
+
+ toggle('Edit flows');
+ expect(onUpdateDisabledTools).not.toHaveBeenCalled();
+ act(() => root.unmount());
+
+ expect(onUpdateDisabledTools).toHaveBeenCalledTimes(1);
+ root = createRoot(container);
+ });
+
+ it('shows the middle state when only some of a tier is on', () => {
+ render({ disabledTools: ['ap_delete_flow'] });
+
+ expect(tierSwitch('Delete').dataset.indeterminate).toBe('true');
+ });
+});
+
+describe('McpToolTierList, when the platform switched tools off', () => {
+ it('locks a tier the platform turned off entirely', () => {
+ render({ platformDisabledTools: DELETE_TOOLS });
+
+ expect(tierSwitch('Delete').disabled).toBe(true);
+ expect(tierSwitch('Delete').checked).toBe(false);
+ expect(container.textContent).toContain('Off for the platform');
+ });
+
+ it('keeps a project-level disable of a platform-off tool when a tier is turned on', () => {
+ const onUpdateDisabledTools = vi.fn();
+ render({
+ disabledTools: ['ap_delete_flow', 'ap_delete_table'],
+ platformDisabledTools: ['ap_delete_flow'],
+ onUpdateDisabledTools,
+ });
+
+ toggle('Delete');
+ confirm();
+
+ expect(onUpdateDisabledTools.mock.calls[0][0].tools).toEqual([
+ 'ap_delete_flow',
+ ]);
+ });
+
+ it('does not copy platform-off tools into the project list when a tier is turned off', () => {
+ const onUpdateDisabledTools = vi.fn();
+ render({
+ platformDisabledTools: ['ap_delete_flow'],
+ onUpdateDisabledTools,
+ });
+
+ toggle('Delete');
+
+ expect(onUpdateDisabledTools.mock.calls[0][0].tools.sort()).toEqual(
+ ['ap_delete_records', 'ap_delete_table', 'ap_manage_fields'].sort(),
+ );
+ });
+});
+
+type ListProps = Parameters<typeof McpToolTierList>[0];
+
+type ChildrenProps = { children: React.ReactNode };
+
+type SheetCallbacks = {
+ onToggleTool: (params: { name: string; enabled: boolean }) => void;
+ onSetAll: (params: { names: string[]; enabled: boolean }) => void;
+};
+
+type SwitchMockProps = {
+ checked?: boolean;
+ indeterminate?: boolean;
+ disabled?: boolean;
+ onCheckedChange?: (checked: boolean) => void;
+ 'aria-label'?: string;
+};
+
+type DialogMockProps = {
+ open: boolean;
+ message: React.ReactNode;
+ buttonText: string;
+ mutationFn: () => Promise<void>;
+};
diff --git a/packages/web/test/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tiers.test.ts b/packages/web/test/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tiers.test.ts
new file mode 100644
index 00000000000..014aef9c422
--- /dev/null
+++ b/packages/web/test/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tiers.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from 'vitest';
+
+import { mcpToolTiers } from '@/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tiers';
+import { getToolCategories } from '@/app/components/project-settings/mcp-server/utils/mcp-tools-metadata';
+
+function namesIn({ tier }: { tier: string }): string[] {
+ const group = mcpToolTiers
+ .groupByTier(getToolCategories({ toolSearchEnabled: true }))
+ .find((g) => g.id === tier);
+ return group?.tools.map((tool) => tool.name) ?? [];
+}
+
+describe('mcpToolTiers.groupByTier', () => {
+ it('puts every tool in exactly one tier', () => {
+ const categories = getToolCategories({ toolSearchEnabled: true });
+ const all = categories.flatMap((c) => c.tools.map((tool) => tool.name));
+ const grouped = mcpToolTiers
+ .groupByTier(categories)
+ .flatMap((g) => g.tools.map((tool) => tool.name));
+ expect(grouped.sort()).toEqual([...all].sort());
+ });
+
+ it('makes the locked category the always-on read tier', () => {
+ const tiers = mcpToolTiers.groupByTier(
+ getToolCategories({ toolSearchEnabled: true }),
+ );
+ expect(tiers[0]).toMatchObject({ id: 'read', locked: true });
+ expect(namesIn({ tier: 'read' })).toContain('ap_list_flows');
+ });
+
+ it('separates destroying things from editing drafts', () => {
+ expect(namesIn({ tier: 'delete' }).sort()).toEqual([
+ 'ap_delete_flow',
+ 'ap_delete_records',
+ 'ap_delete_table',
+ 'ap_manage_fields',
+ ]);
+ expect(namesIn({ tier: 'draft' }).sort()).toEqual(
+ [
+ 'ap_create_flow',
+ 'ap_duplicate_flow',
+ 'ap_rename_flow',
+ 'ap_build_flow',
+ 'ap_update_trigger',
+ 'ap_add_step',
+ 'ap_update_step',
+ 'ap_delete_step',
+ 'ap_add_branch',
+ 'ap_update_branch',
+ 'ap_delete_branch',
+ 'ap_manage_notes',
+ ].sort(),
+ );
+ });
+
+ it('treats testing and table writes as live', () => {
+ const live = namesIn({ tier: 'live' });
+ expect(live).toEqual(
+ expect.arrayContaining([
+ 'ap_test_step',
+ 'ap_insert_records',
+ 'ap_lock_and_publish',
+ ]),
+ );
+ });
+
+ it('puts a tool it does not know in the live tier', () => {
+ const tiers = mcpToolTiers.groupByTier([
+ { label: 'New', tools: [{ name: 'ap_brand_new', description: '' }] },
+ ]);
+ expect(tiers).toEqual([
+ {
+ id: 'live',
+ locked: false,
+ tools: [{ name: 'ap_brand_new', description: '' }],
+ },
+ ]);
+ });
+});
+
+describe('mcpToolTiers.countEnabled', () => {
+ it('counts a locked tier as fully on', () => {
+ const group = {
+ id: 'read' as const,
+ locked: true,
+ tools: [{ name: 'ap_list_flows', description: '' }],
+ };
+ expect(
+ mcpToolTiers.countEnabled({ group, disabledTools: ['ap_list_flows'] }),
+ ).toBe(1);
+ });
+
+ it('subtracts disabled tools from an unlocked tier', () => {
+ const group = {
+ id: 'delete' as const,
+ locked: false,
+ tools: [
+ { name: 'ap_delete_flow', description: '' },
+ { name: 'ap_delete_table', description: '' },
+ ],
+ };
+ expect(
+ mcpToolTiers.countEnabled({ group, disabledTools: ['ap_delete_flow'] }),
+ ).toBe(1);
+ });
+});
+
+describe('mcpToolTiers.titleOf', () => {
+ it('turns a tool name into a sentence-case title', () => {
+ expect(mcpToolTiers.titleOf('ap_change_flow_status')).toBe(
+ 'Change flow status',
+ );
+ expect(mcpToolTiers.titleOf('ap_lock_and_publish')).toBe(
+ 'Lock and publish',
+ );
+ });
+});
diff --git a/packages/web/test/app/components/project-settings/mcp-server/tool-tiers/mcp-tools-sheet.test.tsx b/packages/web/test/app/components/project-settings/mcp-server/tool-tiers/mcp-tools-sheet.test.tsx
new file mode 100644
index 00000000000..91809abd8e8
--- /dev/null
+++ b/packages/web/test/app/components/project-settings/mcp-server/tool-tiers/mcp-tools-sheet.test.tsx
@@ -0,0 +1,194 @@
+/**
+ * @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 * as React from 'react';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('i18next', () => ({ t: (key: string) => key }));
+
+vi.mock('@/components/ui/sheet', () => ({
+ Sheet: ({ open, children }: { open: boolean; children: React.ReactNode }) =>
+ open ? <div>{children}</div> : null,
+ SheetContent: ({ children }: ChildrenProps) => <div>{children}</div>,
+ SheetHeader: ({ children }: ChildrenProps) => <div>{children}</div>,
+ SheetTitle: ({ children }: ChildrenProps) => <h2>{children}</h2>,
+ SheetDescription: ({ children }: ChildrenProps) => (
+ <p data-description="true">{children}</p>
+ ),
+}));
+
+vi.mock('@/components/custom/text-with-tooltip', () => ({
+ TextWithTooltip: ({ children }: ChildrenProps) => <>{children}</>,
+}));
+
+vi.mock('@/components/ui/switch', () => ({
+ Switch: (props: SwitchMockProps) => (
+ <input
+ type="checkbox"
+ data-switch={props['aria-label']}
+ checked={props.checked === true}
+ disabled={props.disabled === true}
+ onChange={(event) => props.onCheckedChange?.(event.target.checked)}
+ />
+ ),
+}));
+
+const { McpToolsSheet } = await import(
+ '@/app/components/project-settings/mcp-server/tool-tiers/mcp-tools-sheet'
+);
+
+declare global {
+ // eslint-disable-next-line no-var
+ var IS_REACT_ACT_ENVIRONMENT: boolean;
+}
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true;
+
+const DELETE_TIER: McpToolTierGroup = {
+ id: 'delete',
+ locked: false,
+ tools: [
+ { name: 'ap_delete_flow', description: 'Delete a flow' },
+ { name: 'ap_delete_table', description: 'Delete a table' },
+ ],
+};
+
+let container: HTMLDivElement;
+let root: Root;
+
+function render(props: Partial<SheetProps> = {}) {
+ act(() => {
+ root.render(
+ <McpToolsSheet
+ tier={DELETE_TIER}
+ onClose={() => undefined}
+ offTools={[]}
+ platformDisabledTools={[]}
+ readOnly={false}
+ onToggleTool={() => undefined}
+ onSetAll={() => undefined}
+ {...props}
+ />,
+ );
+ });
+}
+
+function button(label: string): HTMLButtonElement | null {
+ return (
+ Array.from(container.querySelectorAll('button')).find(
+ (element) => element.textContent === label,
+ ) ?? null
+ );
+}
+
+function description(): string {
+ return container.querySelector('[data-description]')!.textContent ?? '';
+}
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('McpToolsSheet', () => {
+ it('leads each tool with a readable name and keeps the code name beside it', () => {
+ render();
+
+ expect(container.textContent).toContain('Delete flow');
+ expect(container.textContent).toContain('ap_delete_flow');
+ });
+
+ it('turns every tool off when all of them are on', () => {
+ const onSetAll = vi.fn();
+ render({ onSetAll });
+
+ act(() => button('Turn all off')!.click());
+
+ expect(onSetAll).toHaveBeenCalledWith({
+ names: ['ap_delete_flow', 'ap_delete_table'],
+ enabled: false,
+ });
+ });
+
+ it('turns every tool on when any of them is off', () => {
+ const onSetAll = vi.fn();
+ render({ offTools: ['ap_delete_table'], onSetAll });
+
+ act(() => button('Turn all on')!.click());
+
+ expect(onSetAll).toHaveBeenCalledWith({
+ names: ['ap_delete_flow', 'ap_delete_table'],
+ enabled: true,
+ });
+ });
+
+ it('locks a tool the platform turned off and leaves it out of Turn all', () => {
+ const onSetAll = vi.fn();
+ render({
+ offTools: ['ap_delete_flow'],
+ platformDisabledTools: ['ap_delete_flow'],
+ onSetAll,
+ });
+
+ const locked = container.querySelector<HTMLInputElement>(
+ 'input[data-switch="Delete flow"]',
+ )!;
+ expect(locked.disabled).toBe(true);
+ expect(container.textContent).toContain('Off for the platform');
+
+ act(() => button('Turn all off')!.click());
+ expect(onSetAll).toHaveBeenCalledWith({
+ names: ['ap_delete_table'],
+ enabled: false,
+ });
+ });
+
+ it('says why nothing can change when every tool is off for the platform', () => {
+ render({
+ offTools: ['ap_delete_flow', 'ap_delete_table'],
+ platformDisabledTools: ['ap_delete_flow', 'ap_delete_table'],
+ });
+
+ expect(description()).toBe(
+ 'A platform admin turned these off for every project.',
+ );
+ expect(button('Turn all on')).toBeNull();
+ });
+
+ it('explains a read-only role and hides Turn all', () => {
+ render({ readOnly: true });
+
+ expect(description()).toBe(
+ 'You can see these tools, but your role cannot change them.',
+ );
+ expect(button('Turn all off')).toBeNull();
+ expect(
+ Array.from(
+ container.querySelectorAll<HTMLInputElement>('input[data-switch]'),
+ ).every((element) => element.disabled),
+ ).toBe(true);
+ });
+});
+
+type SheetProps = Parameters<typeof McpToolsSheet>[0];
+
+type McpToolTierGroup = NonNullable<SheetProps['tier']>;
+
+type ChildrenProps = { children: React.ReactNode };
+
+type SwitchMockProps = {
+ checked?: boolean;
+ disabled?: boolean;
+ onCheckedChange?: (checked: boolean) => void;
+ 'aria-label'?: string;
+};
diff --git a/packages/web/test/app/routes/mcp-server/activity/activity-utils.test.ts b/packages/web/test/app/routes/mcp-server/activity/activity-utils.test.ts
index 2364429949e..f7f1023ca39 100644
--- a/packages/web/test/app/routes/mcp-server/activity/activity-utils.test.ts
+++ b/packages/web/test/app/routes/mcp-server/activity/activity-utils.test.ts
@@ -127,3 +127,153 @@ describe('activityUtils.formatAccount', () => {
).toBe('hallucinated');
});
});
+
+describe('activityUtils.parseOutput', () => {
+ it('splits the summary line from the JSON result', () => {
+ const output = [
+ {
+ type: 'text',
+ text: '✅ Add Row completed (run r1).\n\n{\n "row": 7\n}',
+ },
+ ];
+
+ expect(activityUtils.parseOutput(output)).toEqual({
+ summary: 'Add Row completed (run r1).',
+ data: { row: 7 },
+ });
+ });
+
+ it('keeps a non-JSON remainder as text', () => {
+ const output = [{ type: 'text', text: '✅ Done.\n\nnot json' }];
+
+ expect(activityUtils.parseOutput(output)).toEqual({
+ summary: 'Done.',
+ data: 'not json',
+ });
+ });
+
+ it('passes through output that is not an MCP text result', () => {
+ const output = { ok: true };
+
+ expect(activityUtils.parseOutput(output)).toEqual({
+ summary: null,
+ data: { ok: true },
+ });
+ });
+});
+
+describe('activityUtils.actionInput', () => {
+ it('returns only the action input from an ap_run_action call', () => {
+ const input = {
+ pieceName: 'slack',
+ actionName: 'send_channel_message',
+ input: { channel: 'C1' },
+ connectionExternalId: 'slack-acme',
+ };
+
+ expect(activityUtils.actionInput(input)).toEqual({ channel: 'C1' });
+ });
+
+ it('returns any other input unchanged', () => {
+ expect(activityUtils.actionInput({ key: 'value' })).toEqual({
+ key: 'value',
+ });
+ });
+});
+
+describe('activityUtils.errorText', () => {
+ it('drops the retry hint meant for the agent and the status mark', () => {
+ const message =
+ '❌ Add Row failed (run r1): 403.\n\nRetry suggestion: check the connection.';
+
+ expect(activityUtils.errorText(message)).toBe(
+ 'Add Row failed (run r1): 403.',
+ );
+ });
+
+ it('keeps every other paragraph', () => {
+ const message = '❌ Failed.\n\nDetails line.';
+
+ expect(activityUtils.errorText(message)).toBe('Failed.\n\nDetails line.');
+ });
+});
+
+describe('activityUtils.memberName', () => {
+ it('joins first and last name', () => {
+ expect(
+ activityUtils.memberName({
+ firstName: 'Lena',
+ lastName: 'Fischer',
+ email: '[email protected]',
+ }),
+ ).toBe('Lena Fischer');
+ });
+
+ it('falls back to the email when there is no name', () => {
+ expect(
+ activityUtils.memberName({
+ firstName: '',
+ lastName: '',
+ email: '[email protected]',
+ }),
+ ).toBe('[email protected]');
+ });
+});
+
+describe('activityUtils.resolveSelection', () => {
+ const rows = [activity({ id: 'first' }), activity({ id: 'last' })];
+
+ it('keeps the selected row while the next page is loading', () => {
+ const previous = activity({ id: 'previous-page-row' });
+
+ expect(
+ activityUtils.resolveSelection({
+ selection: { row: previous, pending: { cursor: 'c2', edge: 'first' } },
+ rows,
+ cursor: 'c2',
+ isPlaceholderData: true,
+ }),
+ ).toBe(previous);
+ });
+
+ it('lands on the first row of the next page', () => {
+ expect(
+ activityUtils.resolveSelection({
+ selection: {
+ row: activity({ id: 'x' }),
+ pending: { cursor: 'c2', edge: 'first' },
+ },
+ rows,
+ cursor: 'c2',
+ isPlaceholderData: false,
+ })?.id,
+ ).toBe('first');
+ });
+
+ it('lands on the last row of the previous page', () => {
+ expect(
+ activityUtils.resolveSelection({
+ selection: {
+ row: activity({ id: 'x' }),
+ pending: { cursor: 'c0', edge: 'last' },
+ },
+ rows,
+ cursor: 'c0',
+ isPlaceholderData: false,
+ })?.id,
+ ).toBe('last');
+ });
+
+ it('ignores a pending move while the URL still points at the old page', () => {
+ const previous = activity({ id: 'x' });
+
+ expect(
+ activityUtils.resolveSelection({
+ selection: { row: previous, pending: { cursor: 'c2', edge: 'first' } },
+ rows,
+ cursor: 'c1',
+ isPlaceholderData: false,
+ }),
+ ).toBe(previous);
+ });
+});
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.tsx
index 9796e2ccf1f..4ede8bff91d 100644
--- 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.tsx
@@ -30,9 +30,14 @@ vi.mock('@/app/components/project-settings/mcp-server/utils/mcp-hooks', () => ({
useUpdateMcpServer: () => ({ mutate: () => undefined, isPending: false }),
},
}));
-vi.mock('@/app/components/project-settings/mcp-server/mcp-tools', () => ({
- McpTools: () => null,
-}));
+vi.mock(
+ '@/app/components/project-settings/mcp-server/tool-tiers/mcp-tool-tier-list',
+ () => ({
+ McpToolTierList: ({ projectId }: { projectId?: string }) => (
+ <div data-tier-list-project={projectId} />
+ ),
+ }),
+);
vi.mock('@/hooks/flags-hooks', () => ({
flagsHooks: { useFlag: () => ({ data: false }) },
}));
@@ -117,3 +122,29 @@ describe('ToolsTab, Run action on the Pieces segment', () => {
expect(panel?.getAttribute('data-run-action-off-by-platform')).toBe('true');
});
});
+
+describe('ToolsTab, Built-in segment', () => {
+ it('gives the tool tiers the selected project, not the session project', () => {
+ server.disabledTools = [];
+ server.platformDisabledTools = [];
+ const container = document.createElement('div');
+ const root = createRoot(container);
+ act(() => {
+ root.render(
+ <ToolsTab
+ projectId="project-1"
+ reachableProjectIds={null}
+ segment="built-in"
+ onSelectProject={() => undefined}
+ onSelectSegment={() => undefined}
+ />,
+ );
+ });
+
+ expect(
+ container
+ .querySelector('[data-tier-list-project]')
+ ?.getAttribute('data-tier-list-project'),
+ ).toBe('project-1');
+ });
+});