Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

feat: configure MCP tool approval in Build Agent (#770)

Abhishek Choudhary551b6a890709
diff --git a/.changeset/mcp-approval-destructive-default.md b/.changeset/mcp-approval-destructive-default.md
new file mode 100644
index 000000000..3cd81e7fb
--- /dev/null
+++ b/.changeset/mcp-approval-destructive-default.md
@@ -0,0 +1,7 @@
+---
+"@truefoundry/trueforge-core": patch
+"@truefoundry/trueforge-ui": patch
+"@truefoundry/trueforge": patch
+---
+
+Default MCP tool approval to `@destructive` only. Selecting Other/read-only tools clears approval; selecting destructive tools keeps it on. Migrate mounts still carrying the old `@write`+`@destructive` default.
diff --git a/.changeset/mcp-tool-approval-selection.md b/.changeset/mcp-tool-approval-selection.md
new file mode 100644
index 000000000..86c1b8fde
--- /dev/null
+++ b/.changeset/mcp-tool-approval-selection.md
@@ -0,0 +1,5 @@
+---
+'@truefoundry/trueforge-ui': patch
+---
+
+Let Build Agent pick which MCP tools require human approval, saved as `require_approval_for_tools` on the agent spec, and make unchecked tool checkboxes legible in both tool selectors. The agent Overview tab now expands each attached MCP server into its tools, with read/write/destructive labels and approval state.
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index 099c6d695..314e1d62d 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -2602,10 +2602,9 @@
},
"require_approval_for_tools": {
"default": [
- "@write",
"@destructive"
],
- "description": "Tools that pause for human approval: `@all`, `@write`, `@destructive`, or literal names. Default: `[\"@write\", \"@destructive\"]`.",
+ "description": "Tools that pause for human approval: `@all`, `@write`, `@destructive`, or literal names. Default: `[\"@destructive\"]`.",
"items": {
"$ref": "#/components/schemas/MCPServerApprovalToolSelector"
},
diff --git a/docs/create-agent/overview.mdx b/docs/create-agent/overview.mdx
index 89723ed87..f2d5708c7 100644
--- a/docs/create-agent/overview.mdx
+++ b/docs/create-agent/overview.mdx
@@ -38,10 +38,10 @@ Each option below is part of the agent definition. The **Set in** line on each s
- **Preload** — load a server's full tool definitions upfront, or (default) discover them on demand to keep context lean. See [Deferred Tool Loading](/key-features/deferred-tool-loading). Toggle it on the connector's chip in Build Agent, or via the API.
- **Tool approval** — pause before sensitive tool calls until a human approves. See below.
- **Set in:** UI (attach servers, tool selection, preload toggle) · API (same, plus approval policy)
+ **Set in:** UI + API
</Accordion>
- <Accordion title="Tool approval (API only)" icon="user-shield">
+ <Accordion title="Tool approval" icon="user-shield">
Some tool calls shouldn't run without a human's sign-off. **Tool approval** pauses the agent before such a call, shows the tool name and arguments, and resumes only after the user chooses **Allow** or **Deny** in the chat UI.
By default, the harness decides what to gate from the tool's own **MCP annotation**: if the server marks a tool as **write or destructive** (the default `["@write", "@destructive"]`), the agent pauses for approval before running it. Read-only tools run autonomously.
@@ -50,9 +50,19 @@ Each option below is part of the agent definition. The **Set in** line on each s
<img src="/images/hitl.png" alt="Chat UI pausing on a tool call, showing the request payload with Allow and Deny buttons" />
</Frame>
- You can override which tools require approval — gate a specific list, or every tool — but that is configured **per MCP server via the API only** ([`require_approval_for_tools`](#mcp_servers)).
+ You can override which tools require approval per MCP server. In **Select MCP Tools**, the shield next to an enabled tool toggles approval for it, and the **Destructive Actions** header has an **Approval required** switch that covers all of them; via the API, set [`require_approval_for_tools`](#mcp_servers) to `@all`, `@write`, `@destructive`, or literal tool names.
- **Set in:** API
+ <Frame caption="The shield on an enabled tool row toggles approval; the Selected Tools panel counts how many are gated.">
+ <img src="/images/mcp-tool-approval.png" alt="The Select MCP Tools dialog with a shielded web_search tool and a Selected Tools panel listing tools with approval badges" />
+ </Frame>
+
+ To review what a saved agent ended up with, open its **Overview** tab: **MCP Servers & Tools** lists each attached server with how many of its tools need approval, and expanding one shows every tool with its `read` / `write` / `destructive` label and shield state.
+
+ <Frame caption="The agent Overview tab, with the slack server expanded to show each tool's annotation and shield state.">
+ <img src="/images/agent-overview-mcp-tools.png" alt="The agent Overview tab showing an MCP Servers and Tools panel with per-server approval counts and a tool list labelled read or write" />
+ </Frame>
+
+ **Set in:** UI + API
</Accordion>
<Accordion title="Skills" icon="book">
@@ -143,7 +153,7 @@ Open **Build Agent** from the sidebar. The **Agent Config** panel on the left is
1. **Select a model** from the providers you configured under **Settings → Models**, and set its reasoning effort.
2. Write focused **instructions** — role, audience, and behavior.
-3. **Add MCP servers** — open **Select MCP Tools**, pick the servers the agent should use, and choose which of their tools to enable. Set a server's **preload** toggle on its chip to load its tools upfront.
+3. **Add MCP servers** — open **Select MCP Tools**, pick the servers the agent should use, and choose which of their tools to enable. Use the shield on a tool to require **approval** before it runs — write and destructive tools are gated by default. Set a server's **preload** toggle on its chip to load its tools upfront.
4. **Add skills** if the agent should follow specialized procedures (requires [sandbox](/sandbox) enabled).
5. Open **Runtime Config** to review execution and context behavior — Dynamic sub-agents, Generative UI, Ask user questions, the sandbox, iteration limit, and context compaction (all on by default).
6. Click **Save Agent**, give it a name and description, and save. It then appears under [Agents](/agent-library).
@@ -152,10 +162,10 @@ Open **Build Agent** from the sidebar. The **Agent Config** panel on the left is
<img src="/images/save-agent.png" alt="The Save agent dialog with an agent name and a description field" />
</Frame>
-Available in the UI today: **model**, **instructions**, **MCP servers** (attach, tool selection, preload), **skills**, **sandbox** (on/off and file downloads), **iteration limit**, **context compaction**, and the **Dynamic sub-agents**, **Generative UI**, and **Ask user questions** toggles.
+Available in the UI today: **model**, **instructions**, **MCP servers** (attach, tool selection, tool approval, preload), **skills**, **sandbox** (on/off and file downloads), **iteration limit**, **context compaction**, and the **Dynamic sub-agents**, **Generative UI**, and **Ask user questions** toggles.
<Note>
- A few options are still API only: model parameters (temperature, top_p, and so on), per-tool **approval** policy, response format, and seed messages. See [Create an agent via the API](#create-an-agent-via-the-api).
+ A few options are still API only: model parameters (temperature, top_p, and so on), response format, and seed messages. See [Create an agent via the API](#create-an-agent-via-the-api).
</Note>
## Create an agent via the API
@@ -347,7 +357,7 @@ Optional array. Each entry attaches a [configured MCP server](/mcp-servers) by n
| `enable_tools` | `["@all"]` | API | Tools exposed to the agent: `@all`, `@read-only`, or literal tool names. |
| `disable_tools` | `[]` | API | Tools subtracted from the enabled set. |
| `preload_tools` | `[]` | API | Tools loaded eagerly into context while the rest stay deferred. |
-| `require_approval_for_tools` | `["@write", "@destructive"]` | API | Tools that pause for [human approval](#whats-in-an-agent): `@all`, `@write`, `@destructive`, or literal names. |
+| `require_approval_for_tools` | `["@write", "@destructive"]` | UI + API | Tools that pause for [human approval](#whats-in-an-agent): `@all`, `@write`, `@destructive`, or literal names. |
| `preload` | `false` | UI + API | Load all tool schemas upfront instead of [on demand](/key-features/deferred-tool-loading). |
The `@read-only`, `@write`, and `@destructive` selectors are resolved from the tool annotations published by the MCP server.
diff --git a/docs/images/agent-overview-mcp-tools.png b/docs/images/agent-overview-mcp-tools.png
new file mode 100644
index 000000000..1fd859896
Binary files /dev/null and b/docs/images/agent-overview-mcp-tools.png differ
diff --git a/docs/images/mcp-tool-approval.png b/docs/images/mcp-tool-approval.png
new file mode 100644
index 000000000..0322dd1ba
Binary files /dev/null and b/docs/images/mcp-tool-approval.png differ
diff --git a/docs/openapi.json b/docs/openapi.json
index 099c6d695..314e1d62d 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -2602,10 +2602,9 @@
},
"require_approval_for_tools": {
"default": [
- "@write",
"@destructive"
],
- "description": "Tools that pause for human approval: `@all`, `@write`, `@destructive`, or literal names. Default: `[\"@write\", \"@destructive\"]`.",
+ "description": "Tools that pause for human approval: `@all`, `@write`, `@destructive`, or literal names. Default: `[\"@destructive\"]`.",
"items": {
"$ref": "#/components/schemas/MCPServerApprovalToolSelector"
},
diff --git a/packages/trueforge-core/src/agent-session/schemas/agentSpec.ts b/packages/trueforge-core/src/agent-session/schemas/agentSpec.ts
index 8aaa3c5d0..c5134870b 100644
--- a/packages/trueforge-core/src/agent-session/schemas/agentSpec.ts
+++ b/packages/trueforge-core/src/agent-session/schemas/agentSpec.ts
@@ -92,12 +92,12 @@ const MCPServerRequestSchema = z
.describe(
'Tools loaded eagerly into context while the rest stay deferred. A non-empty list implies `preload: false`.',
),
- // Tools that require human approval before execution. Default: @write + @destructive.
+ // Tools that require human approval before execution. Default: @destructive only.
require_approval_for_tools: z
.array(RequireApprovalToolSelectorSchema)
.default(DEFAULT_REQUIRE_APPROVAL_FOR_TOOLS)
.describe(
- 'Tools that pause for human approval: `@all`, `@write`, `@destructive`, or literal names. Default: `["@write", "@destructive"]`.',
+ 'Tools that pause for human approval: `@all`, `@write`, `@destructive`, or literal names. Default: `["@destructive"]`.',
),
// Whether this server's tools are preloaded into context. Default: false.
// When false, tools are discovered lazily and only `preload_tools` stay eager.
diff --git a/packages/trueforge-core/src/core/mcp/ToolSelectorPolicy.ts b/packages/trueforge-core/src/core/mcp/ToolSelectorPolicy.ts
index de7af5d03..ea1d69310 100644
--- a/packages/trueforge-core/src/core/mcp/ToolSelectorPolicy.ts
+++ b/packages/trueforge-core/src/core/mcp/ToolSelectorPolicy.ts
@@ -107,7 +107,7 @@ export class ToolSelectorPolicy {
/**
* Whether the tool requires human approval. Honors `requireApprovalForTools` exactly: omit /
- * undefined defaults to write+destructive (constructor); an explicit list — including empty —
+ * undefined defaults to `@destructive` (constructor); an explicit list — including empty —
* is exact.
*/
requiresApproval(toolName: string, annotations: ToolAnnotations | undefined): boolean {
diff --git a/packages/trueforge-core/src/core/mcp/toolSelectors.ts b/packages/trueforge-core/src/core/mcp/toolSelectors.ts
index 74e2654b5..d69d0be90 100644
--- a/packages/trueforge-core/src/core/mcp/toolSelectors.ts
+++ b/packages/trueforge-core/src/core/mcp/toolSelectors.ts
@@ -25,7 +25,7 @@ export const REQUIRE_APPROVAL_TOOLS_SELECTOR_TAGS = [TOOL_TAG_ALL, TOOL_TAG_WRIT
export const DEFAULT_ENABLE_TOOLS: string[] = [TOOL_TAG_ALL];
export const DEFAULT_DISABLE_TOOLS: string[] = [];
export const DEFAULT_PRELOAD_TOOLS: string[] = [];
-export const DEFAULT_REQUIRE_APPROVAL_FOR_TOOLS: string[] = [TOOL_TAG_WRITE, TOOL_TAG_DESTRUCTIVE];
+export const DEFAULT_REQUIRE_APPROVAL_FOR_TOOLS: string[] = [TOOL_TAG_DESTRUCTIVE];
function isToolTag(selector: string): selector is ToolTag {
return TOOL_TAGS.includes(selector as ToolTag);
diff --git a/packages/trueforge-sdk/src/api/types/McpServer.ts b/packages/trueforge-sdk/src/api/types/McpServer.ts
index 2b0f8ee06..901e443f3 100644
--- a/packages/trueforge-sdk/src/api/types/McpServer.ts
+++ b/packages/trueforge-sdk/src/api/types/McpServer.ts
@@ -13,6 +13,6 @@ export interface McpServer {
preload?: boolean;
/** Tools loaded eagerly into context while the rest stay deferred. A non-empty list implies `preload: false`. */
preloadTools?: TrueForge.McpServerToolSelector[];
- /** Tools that pause for human approval: `@all`, `@write`, `@destructive`, or literal names. Default: `["@write", "@destructive"]`. */
+ /** Tools that pause for human approval: `@all`, `@write`, `@destructive`, or literal names. Default: `["@destructive"]`. */
requireApprovalForTools?: TrueForge.McpServerApprovalToolSelector[];
}
diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentDetailsPage.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentDetailsPage.tsx
index 93a269108..042222efc 100644
--- a/packages/trueforge-ui/src/atoms/agent-details/AgentDetailsPage.tsx
+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentDetailsPage.tsx
@@ -110,7 +110,7 @@ export function AgentDetailsPage({ agentId }: AgentDetailsPageProps) {
} else if (detail == null) {
content = (
<div
- className="grid min-h-0 gap-3 overflow-auto p-4 md:grid-cols-[minmax(0,1fr)_18rem]"
+ className="grid min-h-0 gap-3 overflow-auto p-4 md:grid-cols-[minmax(0,1fr)_22rem]"
role="status"
aria-label="Loading agent details"
>
diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentOverview.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentOverview.tsx
index d4c2d249a..2016322b6 100644
--- a/packages/trueforge-ui/src/atoms/agent-details/AgentOverview.tsx
+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentOverview.tsx
@@ -4,6 +4,7 @@ import { useState, type ComponentType } from 'react';
import { Icon } from '../../icons/Icon.js';
import { useSlot } from '../../theme/SlotsProvider.js';
import { cn } from '../lib/cn.js';
+import { AgentOverviewMcpServers } from './AgentOverviewMcpServers.js';
import type { AgentOverviewProps } from './types.js';
type InstructionsView = 'markdown' | 'raw';
@@ -27,12 +28,6 @@ function readRecordValue(record: Record<string, unknown> | null, ...keys: string
return undefined;
}
-function hasAllTools(value: object): boolean {
- if (!isRecord(value)) return false;
- const tools = readRecordValue(value, 'enableTools', 'enable_tools');
- return tools === undefined || (Array.isArray(tools) && tools.includes('@all'));
-}
-
function displayModelName(name: string): string {
const slash = name.lastIndexOf('/');
return slash >= 0 ? name.slice(slash + 1) : name;
@@ -45,7 +40,6 @@ export default function AgentOverview({ detail }: AgentOverviewProps) {
const [copied, setCopied] = useState(false);
const spec = detail.agentSpec;
const skills = spec.skills ?? [];
- const connectors = spec.mcpServers ?? [];
const modelParams = isRecord(spec.model.params) ? spec.model.params : null;
const maxTokens = readRecordValue(modelParams, 'maxTokens', 'max_tokens');
const temperature = readRecordValue(modelParams, 'temperature');
@@ -69,7 +63,7 @@ export default function AgentOverview({ detail }: AgentOverviewProps) {
return (
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-auto p-4 md:overflow-hidden">
- <div className="grid min-h-0 flex-1 gap-3 md:grid-cols-[minmax(0,1fr)_18rem] md:overflow-hidden">
+ <div className="grid min-h-0 flex-1 gap-3 md:grid-cols-[minmax(0,1fr)_22rem] md:overflow-hidden">
<section className="flex min-h-64 flex-col rounded-lg border border-border bg-card-bg p-4 text-text-primary">
<div className="mb-3 flex shrink-0 items-center justify-between gap-2">
<h2 className="flex items-center gap-1.5 text-sm font-semibold text-text-primary">
@@ -155,29 +149,7 @@ export default function AgentOverview({ detail }: AgentOverviewProps) {
) : null}
</dl>
</AgentOverviewCard>
- <AgentOverviewCard title="MCP Servers" icon="plug" count={connectors.length}>
- {connectors.length === 0 ? (
- <p className="text-xs text-text-secondary">No connectors attached.</p>
- ) : (
- <ul className="space-y-1.5">
- {connectors.map((connector, index) => (
- <li
- key={`${readName(connector) ?? 'connector'}-${index}`}
- className="rounded-md bg-secondary-bg px-2 py-1.5 text-xs"
- >
- <span className="flex items-center justify-between gap-2">
- <span className="truncate">{readName(connector) ?? `Connector ${index + 1}`}</span>
- {hasAllTools(connector) ? (
- <span className="shrink-0 rounded-full bg-primary-button-bg/10 px-1.5 py-0.5 text-[10px] text-primary-button-bg">
- All tools
- </span>
- ) : null}
- </span>
- </li>
- ))}
- </ul>
- )}
- </AgentOverviewCard>
+ <AgentOverviewMcpServers mcpServers={spec.mcpServers} />
<AgentOverviewCard title="Attached Skills" icon="lightbulb" count={skills.length}>
{skills.length === 0 ? (
diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentOverviewMcpServers.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentOverviewMcpServers.tsx
new file mode 100644
index 000000000..6f1b59558
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentOverviewMcpServers.tsx
@@ -0,0 +1,195 @@
+'use client';
+
+import { useEffect, useMemo, useState } from 'react';
+
+import { Icon } from '../../icons/Icon.js';
+import { useOptionalServer } from '../../server/ServerContext.js';
+import type { McpToolSelection } from '../../server/types.js';
+import { useSlot } from '../../theme/SlotsProvider.js';
+import {
+ approvalSelectorsFromMount,
+ disableSelectorsFromMount,
+ editableMountsFromSpec,
+ enableSelectorsFromMount,
+} from '../draft/agentConfigMounts.js';
+import { namedToolRequiresApproval } from '../draft/mcpToolApprovals.js';
+import { mcpToolKind, type McpToolKind } from '../draft/mcpToolSections.js';
+import { selectedToolNames, TOOL_TAG_ALL } from '../draft/mcpToolSelectors.js';
+import { cn } from '../lib/cn.js';
+import { Tooltip } from '../primitives/Tooltip.js';
+
+const KIND_CLASSES: Record<McpToolKind, string> = {
+ read: 'border-border bg-secondary-bg text-text-secondary',
+ write: 'border-border bg-secondary-bg text-text-primary',
+ destructive: 'border-failure-bg/30 bg-failure-bg/10 text-failure-bg',
+};
+
+/** Read-only tools first and destructive last, mirroring the tool picker's sections. */
+const KIND_ORDER: Record<McpToolKind | 'unknown', number> = {
+ read: 0,
+ write: 1,
+ unknown: 2,
+ destructive: 3,
+};
+
+function toolCountLabel(count: number): string {
+ return count === 1 ? '1 tool' : `${count} tools`;
+}
+
+/** Shown while tags cannot be resolved: the selectors themselves are the best available answer. */
+function toolSelectorLabel(enableSelectors: readonly string[]): string {
+ if (enableSelectors.includes(TOOL_TAG_ALL)) return 'All tools';
+ return enableSelectors.filter(selector => selector.startsWith('@')).join(' ');
+}
+
+function ApprovalCountBadge({ count }: { count: number }) {
+ return (
+ <span
+ className="border-warning-bg/40 bg-warning-bg/10 text-warning-bg inline-flex shrink-0 items-center gap-1 rounded-full border px-1.5 py-0.5 text-[0.625rem] font-medium"
+ aria-label={`${count} ${count === 1 ? 'tool needs' : 'tools need'} approval`}
+ >
+ <Icon name="shield-check" className="size-2.5" />
+ {count}
+ </span>
+ );
+}
+
+function ToolKindPill({ kind }: { kind: McpToolKind }) {
+ return (
+ <span className={cn('shrink-0 rounded-full border px-1.5 py-0.5 text-[0.625rem] font-medium', KIND_CLASSES[kind])}>
+ {kind}
+ </span>
+ );
+}
+
+function ApprovalIndicator({ approvalRequired, toolName }: { approvalRequired: boolean; toolName: string }) {
+ return (
+ <Tooltip
+ content={approvalRequired ? 'Asks for approval before running' : 'Runs without asking for approval'}
+ triggerClassName="shrink-0"
+ >
+ <span
+ role="img"
+ aria-label={`${toolName} ${approvalRequired ? 'requires approval' : 'runs without approval'}`}
+ className={cn(
+ 'flex size-5 items-center justify-center rounded-md border',
+ approvalRequired
+ ? 'border-warning-bg/50 bg-warning-bg/10 text-warning-bg'
+ : 'border-border text-text-secondary',
+ )}
+ >
+ <Icon name={approvalRequired ? 'shield-check' : 'shield'} className="size-3" />
+ </span>
+ </Tooltip>
+ );
+}
+
+/** Attached MCP servers, each expanding into the tools the agent can call. */
+export function AgentOverviewMcpServers({ mcpServers }: { mcpServers: unknown }) {
+ const AgentOverviewCard = useSlot('AgentOverviewCard');
+ const server = useOptionalServer();
+ const getMcpTools = server?.getMcpTools;
+ const mounts = useMemo(() => editableMountsFromSpec(mcpServers), [mcpServers]);
+ const [toolsByServer, setToolsByServer] = useState<Record<string, McpToolSelection[]>>({});
+ const [expandedIds, setExpandedIds] = useState<ReadonlySet<string>>(() => new Set());
+
+ // Tool metadata drives the counts, kinds, and approval state; a failing server just shows less.
+ useEffect(() => {
+ if (getMcpTools === undefined) return;
+ let cancelled = false;
+ for (const mount of mounts) {
+ void getMcpTools({ connectorId: mount.name }).then(
+ tools => {
+ if (!cancelled) setToolsByServer(prev => ({ ...prev, [mount.name]: tools }));
+ },
+ () => {},
+ );
+ }
+ return () => {
+ cancelled = true;
+ };
+ }, [getMcpTools, mounts]);
+
+ if (mounts.length === 0) {
+ return (
+ <AgentOverviewCard title="MCP Servers & Tools" icon="plug" count={0}>
+ <p className="text-text-secondary text-xs">No connectors attached.</p>
+ </AgentOverviewCard>
+ );
+ }
+
+ return (
+ <AgentOverviewCard title="MCP Servers & Tools" icon="plug" count={mounts.length}>
+ <ul className="space-y-1.5">
+ {mounts.map(mount => {
+ const tools = toolsByServer[mount.name] ?? [];
+ const selectors = approvalSelectorsFromMount(mount.value);
+ const enableSelectors = enableSelectorsFromMount(mount.value);
+ const enabled = selectedToolNames({
+ enableSelectors,
+ disableSelectors: disableSelectorsFromMount(mount.value),
+ tools,
+ });
+ const toolNames = enabled.names
+ .map(toolName => {
+ const tool = tools.find(item => item.name === toolName);
+ const kind = tool === undefined ? undefined : mcpToolKind(tool);
+ return {
+ toolName,
+ kind,
+ approvalRequired: namedToolRequiresApproval({ toolName, tools, selectors }),
+ };
+ })
+ .sort((left, right) => KIND_ORDER[left.kind ?? 'unknown'] - KIND_ORDER[right.kind ?? 'unknown']);
+ const approvalCount = toolNames.filter(tool => tool.approvalRequired).length;
+ const expanded = expandedIds.has(mount.id);
+ return (
+ <li key={mount.id} className="overflow-hidden rounded-md border border-border">
+ <button
+ type="button"
+ aria-expanded={expanded}
+ disabled={toolNames.length === 0}
+ className="flex w-full cursor-pointer items-center gap-2 bg-secondary-bg px-2.5 py-2 text-left text-xs hover:bg-ghost-button-hover disabled:cursor-default disabled:hover:bg-secondary-bg"
+ onClick={() =>
+ setExpandedIds(prev => {
+ const next = new Set(prev);
+ if (expanded) next.delete(mount.id);
+ else next.add(mount.id);
+ return next;
+ })
+ }
+ >
+ <Icon
+ name="chevron-down"
+ className={cn(
+ 'size-3 shrink-0 text-text-secondary transition-transform',
+ expanded ? undefined : '-rotate-90',
+ toolNames.length === 0 && 'invisible',
+ )}
+ />
+ <span className="min-w-0 flex-1 truncate font-medium">{mount.name}</span>
+ <span className="shrink-0 text-text-secondary">
+ {enabled.resolved ? toolCountLabel(toolNames.length) : toolSelectorLabel(enableSelectors)}
+ </span>
+ {approvalCount > 0 ? <ApprovalCountBadge count={approvalCount} /> : null}
+ </button>
+ {expanded ? (
+ <ul className="divide-y divide-border border-t border-border">
+ {toolNames.map(({ toolName, kind, approvalRequired }) => (
+ <li key={toolName} className="flex items-center gap-2 px-2.5 py-1.5">
+ <span className="min-w-0 flex-1 truncate font-mono text-[0.6875rem]" title={toolName}>
+ {toolName}
+ </span>
+ {kind ? <ToolKindPill kind={kind} /> : null}
+ <ApprovalIndicator approvalRequired={approvalRequired} toolName={toolName} />
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ </li>
+ );
+ })}
+ </ul>
+ </AgentOverviewCard>
+ );
+}
diff --git a/packages/trueforge-ui/src/atoms/draft/AgentConfigEditors.tsx b/packages/trueforge-ui/src/atoms/draft/AgentConfigEditors.tsx
index 148e36618..7eb1d4e0c 100644
--- a/packages/trueforge-ui/src/atoms/draft/AgentConfigEditors.tsx
+++ b/packages/trueforge-ui/src/atoms/draft/AgentConfigEditors.tsx
@@ -59,9 +59,12 @@ export function AgentConfigEditors({
const [connectorLoading, setConnectorLoading] = useState(false);
const [connectorError, setConnectorError] = useState<string | null>(null);
const [tools, setTools] = useState<McpToolSelection[]>([]);
+ const [toolsByConnector, setToolsByConnector] = useState<Record<string, McpToolSelection[]>>({});
const [toolsLoading, setToolsLoading] = useState(false);
const [toolsError, setToolsError] = useState<string | null>(null);
const [toolsRequestEpoch, setToolsRequestEpoch] = useState(0);
+ // Connector ids whose tool listing is cached or in flight, so mounts are listed once.
+ const requestedToolConnectorsRef = useRef<Set<string>>(new Set());
const mounts = useMemo(() => editableMountsFromSpec(spec.mcpServers), [spec.mcpServers]);
const catalogConnectors = useMemo(
() => connectorsWithSelectedStubs({ connectors, selected: mounts }),
@@ -121,6 +124,9 @@ export function AgentConfigEditors({
setToolsLoading(true);
try {
const nextTools = await loadMcpTools(selectedConnectorId);
+ // Cache by id even when this run was cancelled, so the mark always has tools behind it.
+ requestedToolConnectorsRef.current.add(selectedConnectorId);
+ setToolsByConnector(previous => ({ ...previous, [selectedConnectorId]: nextTools }));
if (!cancelled) setTools(nextTools);
} catch (reason: unknown) {
if (!cancelled) setToolsError(getErrorMessage(reason, 'Failed to load tools.'));
@@ -133,12 +139,48 @@ export function AgentConfigEditors({
};
}, [editor, loadMcpConnector, loadMcpTools, selectedConnectorId, selectedListedAuthenticated, toolsRequestEpoch]);
+ // Selected servers other than the open one need their tools listed too, so the Selected Tools
+ // summary can resolve `@write` / `@destructive` approval selectors against tool annotations.
+ useEffect(() => {
+ if (editor !== 'mcp' || loadMcpTools === undefined) return;
+ const requested = requestedToolConnectorsRef.current;
+ const pending = mounts.flatMap(mount => {
+ const connector = catalogConnectorsRef.current.find(item => item.id === mount.id || item.name === mount.name);
+ if (connector === undefined || connector.authenticated !== true) return [];
+ if (connector.id === selectedConnectorId || requested.has(connector.id)) return [];
+ return [connector.id];
+ });
+ if (pending.length === 0) return;
+ for (const connectorId of pending) requested.add(connectorId);
+ const settled = new Set<string>();
+ void Promise.all(
+ pending.map(async connectorId => {
+ try {
+ const nextTools = await loadMcpTools(connectorId);
+ settled.add(connectorId);
+ setToolsByConnector(previous => ({ ...previous, [connectorId]: nextTools }));
+ } catch {
+ // Approval badges fall back to name-only matching until a later run retries the listing.
+ }
+ }),
+ );
+ return () => {
+ // Listings that produced no tools (still in flight, or failed) lose their mark so a later
+ // run retries them.
+ for (const connectorId of pending) {
+ if (!settled.has(connectorId)) requested.delete(connectorId);
+ }
+ };
+ }, [editor, loadMcpTools, mounts, selectedConnectorId]);
+
const close = () => {
setQuery('');
setActiveConnectorId(null);
setActiveConnector(undefined);
setConnectorError(null);
setTools([]);
+ setToolsByConnector({});
+ requestedToolConnectorsRef.current.clear();
setToolsError(null);
onClose();
};
@@ -201,6 +243,7 @@ export function AgentConfigEditors({
query={query}
activeConnectorId={selectedConnectorId}
tools={tools}
+ toolsByConnector={toolsByConnector}
connectorLoading={
connectorLoading ||
(loadMcpConnector !== undefined && activeConnector?.id !== selectedConnectorId && connectorError === null)
diff --git a/packages/trueforge-ui/src/atoms/draft/AgentMcpEditorContent.tsx b/packages/trueforge-ui/src/atoms/draft/AgentMcpEditorContent.tsx
index dd1bb20c3..da297e7d8 100644
--- a/packages/trueforge-ui/src/atoms/draft/AgentMcpEditorContent.tsx
+++ b/packages/trueforge-ui/src/atoms/draft/AgentMcpEditorContent.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { useMCPAuth } from '../../hooks/useMcpAuth.js';
import { Icon } from '../../icons/Icon.js';
@@ -10,12 +10,38 @@ import { cn } from '../lib/cn.js';
import { auiInputClass } from '../lib/inputClasses.js';
import { Button } from '../primitives/Button.js';
import { CatalogLogo } from '../primitives/CatalogLogo.js';
+import { Checkbox } from '../primitives/Checkbox.js';
import { Spinner } from '../primitives/Spinner.js';
import { Switch } from '../primitives/Switch.js';
import { Tooltip } from '../primitives/Tooltip.js';
-import { editableMountsFromSpec, enabledToolsFromMount, withEnabledTools } from './agentConfigMounts.js';
+import {
+ approvalSelectorsFromMount,
+ editableMountsFromSpec,
+ enabledToolsFromMount,
+ withApprovalSelectors,
+ withEnabledTools,
+ type EditableMount,
+} from './agentConfigMounts.js';
import { connectorsWithSelectedStubs } from './mcpConnectorStubs.js';
-import { MCP_TOOL_SECTION_LABELS, MCP_TOOL_SECTION_ORDER, partitionMcpToolsBySection } from './mcpToolSections.js';
+import {
+ approvalSelectorsAfterEnabling,
+ approvalSelectorsFor,
+ approvedToolNames,
+ DEFAULT_APPROVAL_SELECTORS,
+ namedToolRequiresApproval,
+ sameSelectors,
+} from './mcpToolApprovals.js';
+import {
+ MCP_TOOL_SECTION_ENABLE_ALL_LABELS,
+ MCP_TOOL_SECTION_LABELS,
+ MCP_TOOL_SECTION_ORDER,
+ partitionMcpToolsBySection,
+ type McpToolSectionId,
+} from './mcpToolSections.js';
+import { TOOL_TAG_DESTRUCTIVE, TOOL_TAG_WRITE, toolMatchesSelectors } from './mcpToolSelectors.js';
+
+/** Pre-change harness default; still present on mounts materialized before approval became destructive-only. */
+const LEGACY_APPROVAL_SELECTORS = [TOOL_TAG_WRITE, TOOL_TAG_DESTRUCTIVE] as const;
export type AgentMcpEditorContentProps = {
spec: AgentSpec;
@@ -23,6 +49,8 @@ export type AgentMcpEditorContentProps = {
query: string;
activeConnectorId: string | null;
tools: McpToolSelection[];
+ /** Tools already loaded per connector id, so selected servers can show approval state. */
+ toolsByConnector?: Record<string, McpToolSelection[]>;
connectorLoading: boolean;
connectorError: string | null;
toolsLoading: boolean;
@@ -34,22 +62,6 @@ export type AgentMcpEditorContentProps = {
onChange: (spec: AgentSpec) => void;
};
-function ToolCheckbox({ checked }: { checked: boolean }) {
- return (
- <span
- className={cn(
- 'flex size-4 shrink-0 items-center justify-center rounded border',
- checked
- ? 'border-primary-button-bg bg-primary-button-bg text-primary-button-text'
- : 'border-input-border bg-input-box-bg',
- )}
- aria-hidden
- >
- {checked ? <Icon name="check" className="size-3" /> : null}
- </span>
- );
-}
-
function ConnectorIcon({ connector }: { connector: ConnectorState }) {
const logo = Reflect.get(connector, 'logo');
if (typeof logo === 'string' && logo.trim() !== '') {
@@ -58,15 +70,75 @@ function ConnectorIcon({ connector }: { connector: ConnectorState }) {
return <Icon name="mcp-server" className="text-text-secondary size-4 shrink-0" />;
}
-function selectedToolsHeaderLabel(mcpMounts: ReturnType<typeof editableMountsFromSpec>): string {
- if (mcpMounts.length === 0) return 'Selected Tools (0)';
- const everyAll = mcpMounts.every(mount => enabledToolsFromMount(mount.value) === 'all');
- if (everyAll) return 'Selected Tools (All)';
+function selectedToolsLabel(mcpMounts: readonly EditableMount[]): string {
+ if (mcpMounts.length === 0) return '0';
+ if (mcpMounts.every(mount => enabledToolsFromMount(mount.value) === 'all')) return 'All';
const count = mcpMounts.reduce((total, mount) => {
const enabled = enabledToolsFromMount(mount.value);
return enabled === 'all' ? total : total + enabled.length;
}, 0);
- return `Selected Tools (${count})`;
+ return `${count}`;
+}
+
+function ApprovalBadge() {
+ return (
+ <span className="border-warning-bg/40 bg-warning-bg/10 text-warning-bg inline-flex shrink-0 items-center gap-1 rounded-full border px-1.5 py-0.5 text-[0.625rem] font-medium">
+ <Icon name="shield-check" className="size-2.5" />
+ approval
+ </span>
+ );
+}
+
+function ToolApprovalToggle({
+ approvalRequired,
+ toolName,
+ onToggle,
+}: {
+ approvalRequired: boolean;
+ toolName: string;
+ onToggle: () => void;
+}) {
+ return (
+ <Tooltip
+ side="bottom"
+ dismissOnClick={false}
+ className="w-64 whitespace-normal p-3 text-left shadow-lg"
+ content={
+ <span className="flex flex-col gap-1.5">
+ <span className="flex items-center justify-between gap-3">
+ <span className="font-semibold">Require approval</span>
+ <span className="text-primary-button-bg text-[0.625rem] font-semibold tracking-wide uppercase">
+ {approvalRequired ? 'ON' : 'OFF'}
+ </span>
+ </span>
+ <span className="text-text-secondary text-xs leading-snug">
+ {approvalRequired
+ ? 'This tool will ask for your approval before running — click to auto-run'
+ : 'This tool runs without asking — click to require your approval'}
+ </span>
+ </span>
+ }
+ >
+ <button
+ type="button"
+ aria-pressed={approvalRequired}
+ aria-label={`Require approval for ${toolName}`}
+ className={auiButtonClass({
+ variant: 'secondary',
+ size: 'small',
+ className: cn(
+ 'size-6 px-0 [&_svg]:size-3.5',
+ approvalRequired
+ ? 'border-warning-bg/50 bg-warning-bg/10 text-warning-bg hover:bg-warning-bg/20'
+ : 'text-text-secondary',
+ ),
+ })}
+ onClick={onToggle}
+ >
+ <Icon name={approvalRequired ? 'shield-check' : 'shield'} />
+ </button>
+ </Tooltip>
+ );
}
function ConnectNowButton({ connectorId, onConnected }: { connectorId: string; onConnected: () => void }) {
@@ -93,6 +165,7 @@ export function AgentMcpEditorContent({
query,
activeConnectorId,
tools,
+ toolsByConnector = {},
connectorLoading,
connectorError,
toolsLoading,
@@ -135,10 +208,30 @@ export function AgentMcpEditorContent({
const filteredTools =
normalizedToolQuery === '' ? tools : tools.filter(tool => tool.name.toLowerCase().includes(normalizedToolQuery));
const toolSections = partitionMcpToolsBySection(filteredTools);
- const readOnlyTools = partitionMcpToolsBySection(tools)['read-only'];
- const readOnlyNames = readOnlyTools.map(tool => tool.name);
- const allReadOnlyEnabled =
- readOnlyNames.length > 0 && (enabledTools === 'all' || readOnlyNames.every(name => enabledTools.includes(name)));
+ const allSections = partitionMcpToolsBySection(tools);
+ const approvalSelectors = activeMount
+ ? approvalSelectorsFromMount(activeMount.value)
+ : [...DEFAULT_APPROVAL_SELECTORS];
+ const approvedNames = approvedToolNames({ tools, selectors: approvalSelectors });
+ const knownTools: Record<string, McpToolSelection[]> = {
+ ...toolsByConnector,
+ ...(activeConnectorId !== null && tools.length > 0 ? { [activeConnectorId]: tools } : {}),
+ };
+
+ const toolsForMount = (mount: EditableMount): McpToolSelection[] => {
+ const connectorId = catalogConnectors.find(item => item.id === mount.id || item.name === mount.name)?.id;
+ return knownTools[mount.id] ?? (connectorId === undefined ? undefined : knownTools[connectorId]) ?? [];
+ };
+
+ const approvalCount = mcpMounts.reduce((total, mount) => {
+ const selectors = approvalSelectorsFromMount(mount.value);
+ const mountTools = toolsForMount(mount);
+ const enabled = enabledToolsFromMount(mount.value);
+ if (enabled === 'all') return total + approvedToolNames({ tools: mountTools, selectors }).size;
+ return (
+ total + enabled.filter(toolName => namedToolRequiresApproval({ toolName, tools: mountTools, selectors })).length
+ );
+ }, 0);
const updateMount = (mountId: string, value: object) => {
onChange({
@@ -147,6 +240,33 @@ export function AgentMcpEditorContent({
});
};
+ // Specs saved under the old default still carry `@write`+`@destructive`. Rewrite once tools are
+ // known so Other tools show (and run) without approval unless the user opts in.
+ const migratedLegacyApprovalRef = useRef(new Set<string>());
+ useEffect(() => {
+ if (!activeMount || tools.length === 0) return;
+ if (migratedLegacyApprovalRef.current.has(activeMount.id)) return;
+ const selectors = approvalSelectorsFromMount(activeMount.value);
+ if (!sameSelectors(selectors, LEGACY_APPROVAL_SELECTORS)) {
+ migratedLegacyApprovalRef.current.add(activeMount.id);
+ return;
+ }
+ migratedLegacyApprovalRef.current.add(activeMount.id);
+ const enabled = enabledToolsFromMount(activeMount.value);
+ const names = enabled === 'all' ? tools.map(tool => tool.name) : enabled;
+ onChange({
+ ...spec,
+ mcpServers: mcpMounts.map(item =>
+ item.id === activeMount.id
+ ? withApprovalSelectors(
+ activeMount.value,
+ approvalSelectorsAfterEnabling({ tools, selectors, newlyEnabledNames: names }),
+ )
+ : item.value,
+ ),
+ });
+ }, [activeMount, tools, mcpMounts, onChange, spec]);
+
const removeMount = (mountId: string) => {
onChange({
...spec,
@@ -159,14 +279,43 @@ export function AgentMcpEditorContent({
onSelectConnector(match?.id ?? mount.id);
};
- const setEnabledToolNames = (next: string[]) => {
+ const commitEnabledTools = ({
+ next,
+ newlyEnabledNames,
+ baseValue,
+ }: {
+ next: string[];
+ newlyEnabledNames: readonly string[];
+ baseValue: object;
+ }) => {
+ let value = withEnabledTools(baseValue, next);
+ if (newlyEnabledNames.length > 0 && tools.length > 0) {
+ value = withApprovalSelectors(
+ value,
+ approvalSelectorsAfterEnabling({
+ tools,
+ selectors: approvalSelectorsFromMount(value),
+ newlyEnabledNames,
+ }),
+ );
+ }
+ return value;
+ };
+
+ const setEnabledToolNames = ({
+ next,
+ newlyEnabledNames = [],
+ }: {
+ next: string[];
+ newlyEnabledNames?: readonly string[];
+ }) => {
if (!selectedConnector) return;
if (next.length === 0) {
if (activeMount) removeMount(activeMount.id);
return;
}
if (activeMount) {
- updateMount(activeMount.id, withEnabledTools(activeMount.value, next));
+ updateMount(activeMount.id, commitEnabledTools({ next, newlyEnabledNames, baseValue: activeMount.value }));
return;
}
if (!canAddActiveConnector) return;
@@ -174,7 +323,11 @@ export function AgentMcpEditorContent({
...spec,
mcpServers: [
...(spec.mcpServers ?? []),
- withEnabledTools({ id: selectedConnector.id, name: selectedConnector.name }, next),
+ commitEnabledTools({
+ next,
+ newlyEnabledNames,
+ baseValue: { id: selectedConnector.id, name: selectedConnector.name },
+ }),
],
});
};
@@ -183,38 +336,44 @@ export function AgentMcpEditorContent({
if (!selectedConnector) return;
if (!activeMount) {
if (!canAddActiveConnector) return;
- onChange({
- ...spec,
- mcpServers: [
- ...(spec.mcpServers ?? []),
- withEnabledTools({ id: selectedConnector.id, name: selectedConnector.name }, [toolName]),
- ],
- });
+ setEnabledToolNames({ next: [toolName], newlyEnabledNames: [toolName] });
return;
}
const current = enabledTools === 'all' ? tools.map(tool => tool.name) : enabledTools;
const checked = current.includes(toolName);
const next = checked ? current.filter(name => name !== toolName) : [...current, toolName];
- setEnabledToolNames(next);
+ setEnabledToolNames({ next, newlyEnabledNames: checked ? [] : [toolName] });
};
- const setAllReadOnlyTools = (enabled: boolean) => {
- if (!selectedConnector || readOnlyNames.length === 0) return;
+ const setSectionTools = ({ sectionId, enabled }: { sectionId: McpToolSectionId; enabled: boolean }) => {
+ const sectionNames = allSections[sectionId].map(tool => tool.name);
+ if (!selectedConnector || sectionNames.length === 0) return;
if (enabled) {
if (enabledTools === 'all') return;
- const current = activeMount ? enabledTools : [];
- const merged = [...current];
- for (const name of readOnlyNames) {
- if (!merged.includes(name)) merged.push(name);
+ const merged = activeMount ? [...enabledTools] : [];
+ const newlyEnabledNames: string[] = [];
+ for (const name of sectionNames) {
+ if (!merged.includes(name)) {
+ merged.push(name);
+ newlyEnabledNames.push(name);
+ }
}
- setEnabledToolNames(merged);
+ setEnabledToolNames({ next: merged, newlyEnabledNames });
return;
}
- if (enabledTools === 'all') {
- setEnabledToolNames(tools.map(tool => tool.name).filter(name => !readOnlyNames.includes(name)));
- return;
+ const current = enabledTools === 'all' ? tools.map(tool => tool.name) : enabledTools;
+ setEnabledToolNames({ next: current.filter(name => !sectionNames.includes(name)) });
+ };
+
+ const setToolsApproval = ({ toolNames, required }: { toolNames: readonly string[]; required: boolean }) => {
+ // Selectors are rebuilt from the server's tool list, so never rewrite them before it loads.
+ if (!activeMount || toolNames.length === 0 || tools.length === 0) return;
+ const approved = new Set(approvedNames);
+ for (const name of toolNames) {
+ if (required) approved.add(name);
+ else approved.delete(name);
}
- setEnabledToolNames(enabledTools.filter(name => !readOnlyNames.includes(name)));
+ updateMount(activeMount.id, withApprovalSelectors(activeMount.value, approvalSelectorsFor({ tools, approved })));
};
const connectDuringChat = () => {
@@ -223,7 +382,10 @@ export function AgentMcpEditorContent({
...spec,
mcpServers: [
...(spec.mcpServers ?? []),
- withEnabledTools({ id: selectedConnector.id, name: selectedConnector.name }, 'all'),
+ withApprovalSelectors(
+ withEnabledTools({ id: selectedConnector.id, name: selectedConnector.name }, 'all'),
+ DEFAULT_APPROVAL_SELECTORS,
+ ),
],
});
};
@@ -368,10 +530,21 @@ export function AgentMcpEditorContent({
const onlyOthers =
toolSections['read-only'].length === 0 && toolSections.destructive.length === 0;
const showSectionHeader = sectionId !== 'others' || !onlyOthers;
+ const sectionNames = allSections[sectionId].map(tool => tool.name);
+ const sectionEnabled =
+ sectionNames.length > 0 &&
+ (enabledTools === 'all' || sectionNames.every(name => enabledTools.includes(name)));
+ // Approval only applies to tools the agent can call, so bulk gating follows the enabled set.
+ const sectionEnabledNames =
+ enabledTools === 'all'
+ ? sectionNames
+ : sectionNames.filter(name => enabledTools.includes(name));
+ const sectionApproved =
+ sectionEnabledNames.length > 0 && sectionEnabledNames.every(name => approvedNames.has(name));
return (
<div key={sectionId} className="mb-3">
{showSectionHeader ? (
- <div className="flex items-center justify-between gap-3 px-2 py-2">
+ <div className="flex items-center justify-between gap-2 px-2 py-2">
<p
className={cn(
'min-w-0 truncate text-sm font-semibold',
@@ -380,42 +553,70 @@ export function AgentMcpEditorContent({
>
{MCP_TOOL_SECTION_LABELS[sectionId]}
</p>
- {sectionId === 'read-only' ? (
+ <div className="flex shrink-0 items-center gap-3">
+ {sectionId !== 'destructive' || sectionEnabledNames.length === 0 ? null : (
+ <label className="text-text-secondary flex shrink-0 cursor-pointer items-center gap-2 text-xs">
+ Approval required
+ <Switch
+ checked={sectionApproved}
+ onCheckedChange={required =>
+ setToolsApproval({ toolNames: sectionEnabledNames, required })
+ }
+ aria-label="Require approval for all destructive tools"
+ />
+ </label>
+ )}
<label className="text-text-secondary flex shrink-0 cursor-pointer items-center gap-2 text-xs has-[:disabled]:cursor-not-allowed">
- Enable All Read-only Tools
+ Enable all
<Switch
- checked={allReadOnlyEnabled}
+ checked={sectionEnabled}
disabled={!canAddActiveConnector && activeMount === undefined}
- onCheckedChange={setAllReadOnlyTools}
- aria-label="Enable all read-only tools"
+ onCheckedChange={enabled => setSectionTools({ sectionId, enabled })}
+ aria-label={MCP_TOOL_SECTION_ENABLE_ALL_LABELS[sectionId]}
/>
</label>
- ) : null}
+ </div>
</div>
) : null}
{sectionTools.map(tool => {
const checked = enabledTools === 'all' || enabledTools.includes(tool.name);
+ const approvalRequired = toolMatchesSelectors({ tool, selectors: approvalSelectors });
return (
- <button
+ <div
key={tool.id}
- type="button"
- role="menuitemcheckbox"
- aria-checked={checked}
- aria-label={tool.name}
- disabled={!canAddActiveConnector && activeMount === undefined}
- className="hover:bg-ghost-button-hover flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-left disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"
- onClick={() => toggleTool(tool.name)}
+ className="hover:bg-ghost-button-hover flex w-full items-center gap-1 rounded-md pr-2"
>
- <ToolCheckbox checked={checked} />
- <span className="min-w-0 flex-1">
- <span className="text-text-primary block truncate text-sm font-medium">
- {tool.name}
+ <button
+ type="button"
+ role="menuitemcheckbox"
+ aria-checked={checked}
+ aria-label={tool.name}
+ disabled={!canAddActiveConnector && activeMount === undefined}
+ className="flex min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-left disabled:cursor-not-allowed disabled:opacity-50"
+ onClick={() => toggleTool(tool.name)}
+ >
+ <Checkbox checked={checked} />
+ <span className="min-w-0 flex-1">
+ <span className="text-text-primary block truncate text-sm font-medium">
+ {tool.name}
+ </span>
+ {tool.description ? (
+ <span className="text-text-secondary line-clamp-1 text-xs">
+ {tool.description}
+ </span>
+ ) : null}
</span>
- {tool.description ? (
- <span className="text-text-secondary line-clamp-1 text-xs">{tool.description}</span>
- ) : null}
- </span>
- </button>
+ </button>
+ {checked ? (
+ <ToolApprovalToggle
+ approvalRequired={approvalRequired}
+ toolName={tool.name}
+ onToggle={() =>
+ setToolsApproval({ toolNames: [tool.name], required: !approvalRequired })
+ }
+ />
+ ) : null}
+ </div>
);
})}
</div>
@@ -431,14 +632,21 @@ export function AgentMcpEditorContent({
</div>
<div className="flex max-h-44 min-h-0 min-w-0 flex-col md:max-h-none">
- <div className="shrink-0 border-b border-border p-3 text-sm font-semibold">
- {selectedToolsHeaderLabel(mcpMounts)}
+ <div className="shrink-0 border-b border-border p-3">
+ <p className="text-sm font-semibold">Selected Tools ({selectedToolsLabel(mcpMounts)})</p>
+ {mcpMounts.length ? (
+ <p className="text-text-secondary mt-0.5 text-xs">
+ {selectedToolsLabel(mcpMounts)} selected · {approvalCount} need approval
+ </p>
+ ) : null}
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-2">
{mcpMounts.length ? (
<div className="space-y-1">
{mcpMounts.map(mount => {
const selected = enabledToolsFromMount(mount.value);
+ const mountSelectors = approvalSelectorsFromMount(mount.value);
+ const mountTools = toolsForMount(mount);
return (
<details
key={mount.id}
@@ -499,7 +707,10 @@ export function AgentMcpEditorContent({
onClick={() => openMountConnector(mount)}
>
<Icon name="wrench" className="size-3 shrink-0" />
- ALL TOOLS ENABLED
+ <span className="min-w-0 flex-1 truncate">ALL TOOLS ENABLED</span>
+ {approvedToolNames({ tools: mountTools, selectors: mountSelectors }).size > 0 ? (
+ <ApprovalBadge />
+ ) : null}
</button>
) : selected.length ? (
selected.map(toolName => (
@@ -507,11 +718,14 @@ export function AgentMcpEditorContent({
key={`${mount.id}:${toolName}`}
type="button"
aria-label={`Open ${mount.name} for ${toolName}`}
- className="text-text-primary hover:bg-ghost-button-hover flex w-full cursor-pointer items-center gap-1.5 rounded-md px-2 py-1 pl-7 text-left text-[0.6875rem]"
+ className="text-text-primary hover:bg-ghost-button-hover flex w-full h-7 cursor-pointer items-center gap-1.5 rounded-md px-2 py-1 pl-7 text-left text-[0.6875rem]"
onClick={() => openMountConnector(mount)}
>
<Icon name="wrench" className="text-text-secondary size-3 shrink-0" />
- <span className="min-w-0 truncate">{toolName}</span>
+ <span className="min-w-0 flex-1 truncate">{toolName}</span>
+ {namedToolRequiresApproval({ toolName, tools: mountTools, selectors: mountSelectors }) ? (
+ <ApprovalBadge />
+ ) : null}
</button>
))
) : (
diff --git a/packages/trueforge-ui/src/atoms/draft/AgentResourceConfigModal.tsx b/packages/trueforge-ui/src/atoms/draft/AgentResourceConfigModal.tsx
index d8e0b4da9..687b7b0be 100644
--- a/packages/trueforge-ui/src/atoms/draft/AgentResourceConfigModal.tsx
+++ b/packages/trueforge-ui/src/atoms/draft/AgentResourceConfigModal.tsx
@@ -1,5 +1,6 @@
'use client';
+import { Icon } from '../../icons/Icon.js';
import type { AgentSkill, AgentSpec, ConnectorState, McpToolSelection } from '../../server/types.js';
import { useSlot } from '../../theme/SlotsProvider.js';
import { Button } from '../primitives/Button.js';
@@ -14,6 +15,7 @@ export type AgentResourceConfigModalProps = {
query: string;
activeConnectorId: string | null;
tools: McpToolSelection[];
+ toolsByConnector?: Record<string, McpToolSelection[]>;
connectorLoading: boolean;
connectorError: string | null;
toolsLoading: boolean;
@@ -44,7 +46,11 @@ export function AgentResourceConfigModal({ editor, onClose, ...contentProps }: A
aria-label={selectingMcp ? 'Select MCP Tools' : 'Edit skills'}
footer={
selectingMcp ? (
- <div className="flex justify-end">
+ <div className="flex items-center justify-between gap-3">
+ <p className="text-text-secondary flex min-w-0 items-center gap-1.5 text-xs">
+ <Icon name="shield-check" className="text-warning-bg size-3.5 shrink-0" />
+ <span className="min-w-0">Shielded tools always ask before the agent runs them.</span>
+ </p>
<Button.Primary type="button" onClick={onClose}>
Save
</Button.Primary>
diff --git a/packages/trueforge-ui/src/atoms/draft/AgentResourceEditorContent.tsx b/packages/trueforge-ui/src/atoms/draft/AgentResourceEditorContent.tsx
index 187ee4862..6ba32c323 100644
--- a/packages/trueforge-ui/src/atoms/draft/AgentResourceEditorContent.tsx
+++ b/packages/trueforge-ui/src/atoms/draft/AgentResourceEditorContent.tsx
@@ -12,6 +12,7 @@ export type AgentResourceEditorContentProps = {
query: string;
activeConnectorId: string | null;
tools: McpToolSelection[];
+ toolsByConnector?: Record<string, McpToolSelection[]>;
connectorLoading: boolean;
connectorError: string | null;
toolsLoading: boolean;
@@ -47,6 +48,7 @@ export function AgentResourceEditorContent(props: AgentResourceEditorContentProp
query={props.query}
activeConnectorId={props.activeConnectorId}
tools={props.tools}
+ {...(props.toolsByConnector === undefined ? {} : { toolsByConnector: props.toolsByConnector })}
connectorLoading={props.connectorLoading}
connectorError={props.connectorError}
toolsLoading={props.toolsLoading}
diff --git a/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx b/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx
index 5f2830d20..6fabdf6c3 100644
--- a/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx
+++ b/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx
@@ -17,6 +17,7 @@ import { useIsMobile } from '../lib/useIsMobile.js';
import { BottomSheet } from '../primitives/BottomSheet.js';
import { Button } from '../primitives/Button.js';
import { CatalogLogo } from '../primitives/CatalogLogo.js';
+import { Checkbox } from '../primitives/Checkbox.js';
import { Tooltip } from '../primitives/Tooltip.js';
import { DraftCatalogEmptyState } from './DraftCatalogEmptyState.js';
import { useDraftCatalog } from './DraftCatalogProvider.js';
@@ -58,22 +59,6 @@ const TABS: { id: AttachTab; label: string; icon: string }[] = [
const SPEC_FLUSH_MS = 300;
-function Checkbox({ checked }: { checked: boolean }) {
- return (
- <span
- className={cn(
- 'flex size-4 shrink-0 items-center justify-center rounded border',
- checked
- ? 'border-primary-button-bg bg-primary-button-bg text-primary-button-text'
- : 'border-input-border bg-input-box-bg',
- )}
- aria-hidden
- >
- {checked ? <Icon name="check" className="size-3" /> : null}
- </span>
- );
-}
-
export function CatalogRow({
title,
description,
diff --git a/packages/trueforge-ui/src/atoms/draft/agentConfigMounts.ts b/packages/trueforge-ui/src/atoms/draft/agentConfigMounts.ts
index 556858bcf..6ce2086a5 100644
--- a/packages/trueforge-ui/src/atoms/draft/agentConfigMounts.ts
+++ b/packages/trueforge-ui/src/atoms/draft/agentConfigMounts.ts
@@ -1,3 +1,6 @@
+import { DEFAULT_APPROVAL_SELECTORS, sameSelectors } from './mcpToolApprovals.js';
+import { TOOL_TAG_ALL } from './mcpToolSelectors.js';
+
export type EditableMount = {
id: string;
name: string;
@@ -21,10 +24,25 @@ export function editableMountsFromSpec(value: unknown): EditableMount[] {
export function enabledToolsFromMount(value: object): string[] | 'all' {
const enabled = Reflect.get(value, 'enableTools');
- if (!Array.isArray(enabled) || enabled.includes('@all')) return 'all';
+ if (!Array.isArray(enabled) || enabled.includes(TOOL_TAG_ALL)) return 'all';
return enabled.filter((tool): tool is string => typeof tool === 'string' && !tool.startsWith('@'));
}
+function selectorsFromMount({ value, key }: { value: object; key: string }): string[] | undefined {
+ const selectors = Reflect.get(value, key);
+ if (!Array.isArray(selectors)) return undefined;
+ return selectors.filter((selector): selector is string => typeof selector === 'string');
+}
+
+/** Omitting `enableTools` enables every tool, matching the harness default. */
+export function enableSelectorsFromMount(value: object): string[] {
+ return selectorsFromMount({ value, key: 'enableTools' }) ?? [TOOL_TAG_ALL];
+}
+
+export function disableSelectorsFromMount(value: object): string[] {
+ return selectorsFromMount({ value, key: 'disableTools' }) ?? [];
+}
+
export function withEnabledTools(value: object, enabledTools: string[] | 'all'): object {
return {
...value,
@@ -32,6 +50,22 @@ export function withEnabledTools(value: object, enabledTools: string[] | 'all'):
};
}
+export function approvalSelectorsFromMount(value: object): string[] {
+ const selectors = Reflect.get(value, 'requireApprovalForTools');
+ if (!Array.isArray(selectors)) return [...DEFAULT_APPROVAL_SELECTORS];
+ return selectors.filter((selector): selector is string => typeof selector === 'string');
+}
+
+/** Drops the field when it matches the harness default so untouched mounts stay clean. */
+export function withApprovalSelectors(value: object, selectors: readonly string[]): object {
+ if (sameSelectors(selectors, DEFAULT_APPROVAL_SELECTORS)) {
+ const next = { ...value };
+ Reflect.deleteProperty(next, 'requireApprovalForTools');
+ return next;
+ }
+ return { ...value, requireApprovalForTools: [...selectors] };
+}
+
export function preloadFromMount(value: object): boolean {
return Reflect.get(value, 'preload') === true;
}
diff --git a/packages/trueforge-ui/src/atoms/draft/mcpToolApprovals.ts b/packages/trueforge-ui/src/atoms/draft/mcpToolApprovals.ts
new file mode 100644
index 000000000..b52e8a080
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/draft/mcpToolApprovals.ts
@@ -0,0 +1,103 @@
+import type { McpToolSelection } from '../../server/types.js';
+import { mcpToolSectionId } from './mcpToolSections.js';
+import {
+ TOOL_TAG_ALL,
+ TOOL_TAG_DESTRUCTIVE,
+ TOOL_TAG_WRITE,
+ toolMatchesSelectors,
+ toolMatchesTag,
+} from './mcpToolSelectors.js';
+
+/** Harness default applied when a mount omits `requireApprovalForTools`. */
+export const DEFAULT_APPROVAL_SELECTORS: readonly string[] = [TOOL_TAG_DESTRUCTIVE];
+
+/** Approval on by default only for destructive tools; Other/read-only stay off until toggled. */
+export function defaultApprovalRequiredForTool(tool: McpToolSelection): boolean {
+ return mcpToolSectionId(tool) === 'destructive';
+}
+
+/**
+ * Apply section defaults for tools that were just enabled: destructive → gated, everything else →
+ * auto-run. Rebuilds selectors from the full server tool list so class tags stay coherent.
+ */
+export function approvalSelectorsAfterEnabling({
+ tools,
+ selectors,
+ newlyEnabledNames,
+}: {
+ tools: readonly McpToolSelection[];
+ selectors: readonly string[];
+ newlyEnabledNames: readonly string[];
+}): string[] {
+ if (tools.length === 0 || newlyEnabledNames.length === 0) return [...selectors];
+ const approved = approvedToolNames({ tools, selectors });
+ for (const name of newlyEnabledNames) {
+ const tool = tools.find(item => item.name === name);
+ if (tool === undefined) continue;
+ if (defaultApprovalRequiredForTool(tool)) approved.add(name);
+ else approved.delete(name);
+ }
+ const next = approvalSelectorsFor({ tools, approved });
+ // No destructive tools on this server → keep the omitted harness default instead of writing `[]`,
+ // so later-added destructive tools still pick up `@destructive`.
+ if (next.length === 0 && !tools.some(tool => defaultApprovalRequiredForTool(tool))) {
+ return [...DEFAULT_APPROVAL_SELECTORS];
+ }
+ return next;
+}
+
+/** Approval state for a tool name whose annotations are unknown (tags cannot be resolved). */
+export function namedToolRequiresApproval({
+ toolName,
+ tools,
+ selectors,
+}: {
+ toolName: string;
+ tools: readonly McpToolSelection[];
+ selectors: readonly string[];
+}): boolean {
+ const tool = tools.find(item => item.name === toolName);
+ if (tool !== undefined) return toolMatchesSelectors({ tool, selectors });
+ return selectors.includes(TOOL_TAG_ALL) || selectors.includes(toolName);
+}
+
+export function approvedToolNames({
+ tools,
+ selectors,
+}: {
+ tools: readonly McpToolSelection[];
+ selectors: readonly string[];
+}): Set<string> {
+ return new Set(tools.filter(tool => toolMatchesSelectors({ tool, selectors })).map(tool => tool.name));
+}
+
+/**
+ * Narrowest selector list that gates exactly `approved`. Class tags are kept while every tool of
+ * that class stays gated, so servers that later add write/destructive tools still gate them.
+ * Tags with no matching tools on the server are omitted (vacuous `every` would otherwise keep them).
+ */
+export function approvalSelectorsFor({
+ tools,
+ approved,
+}: {
+ tools: readonly McpToolSelection[];
+ approved: ReadonlySet<string>;
+}): string[] {
+ if (tools.length > 0 && tools.every(tool => approved.has(tool.name))) return [TOOL_TAG_ALL];
+ const selectors = [TOOL_TAG_WRITE, TOOL_TAG_DESTRUCTIVE].filter(tag => {
+ const matching = tools.filter(tool => toolMatchesTag({ tag, tool }));
+ return matching.length > 0 && matching.every(tool => approved.has(tool.name));
+ });
+ for (const tool of tools) {
+ if (!approved.has(tool.name)) continue;
+ if (toolMatchesSelectors({ tool, selectors })) continue;
+ selectors.push(tool.name);
+ }
+ return selectors;
+}
+
+export function sameSelectors(left: readonly string[], right: readonly string[]): boolean {
+ if (left.length !== right.length) return false;
+ const rightSet = new Set(right);
+ return left.every(selector => rightSet.has(selector));
+}
diff --git a/packages/trueforge-ui/src/atoms/draft/mcpToolSections.ts b/packages/trueforge-ui/src/atoms/draft/mcpToolSections.ts
index f91fba49c..9b667b7ef 100644
--- a/packages/trueforge-ui/src/atoms/draft/mcpToolSections.ts
+++ b/packages/trueforge-ui/src/atoms/draft/mcpToolSections.ts
@@ -26,6 +26,17 @@ export function mcpToolSectionId(tool: McpToolSelection): McpToolSectionId {
return 'others';
}
+export type McpToolKind = 'read' | 'write' | 'destructive';
+
+/** Undefined when the server ships no usable hints, so callers can omit the label. */
+export function mcpToolKind(tool: McpToolSelection): McpToolKind | undefined {
+ const annotations = mcpToolAnnotations(tool);
+ if (annotations?.readOnlyHint === true) return 'read';
+ if (annotations?.destructiveHint === true) return 'destructive';
+ if (annotations?.readOnlyHint === false) return 'write';
+ return undefined;
+}
+
export const MCP_TOOL_SECTION_ORDER: readonly McpToolSectionId[] = ['read-only', 'others', 'destructive'];
export const MCP_TOOL_SECTION_LABELS: Record<McpToolSectionId, string> = {
@@ -34,6 +45,12 @@ export const MCP_TOOL_SECTION_LABELS: Record<McpToolSectionId, string> = {
destructive: 'Destructive Actions',
};
+export const MCP_TOOL_SECTION_ENABLE_ALL_LABELS: Record<McpToolSectionId, string> = {
+ 'read-only': 'Enable all read-only tools',
+ others: 'Enable all other tools',
+ destructive: 'Enable all destructive tools',
+};
+
export function partitionMcpToolsBySection(
tools: readonly McpToolSelection[],
): Record<McpToolSectionId, McpToolSelection[]> {
diff --git a/packages/trueforge-ui/src/atoms/draft/mcpToolSelectors.ts b/packages/trueforge-ui/src/atoms/draft/mcpToolSelectors.ts
new file mode 100644
index 000000000..92328472e
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/draft/mcpToolSelectors.ts
@@ -0,0 +1,65 @@
+import type { McpToolSelection } from '../../server/types.js';
+import { mcpToolAnnotations } from './mcpToolSections.js';
+
+export const TOOL_TAG_ALL = '@all';
+export const TOOL_TAG_READ_ONLY = '@read-only';
+export const TOOL_TAG_WRITE = '@write';
+export const TOOL_TAG_DESTRUCTIVE = '@destructive';
+
+/** Harness tag semantics. A tool without annotations matches no tag except `@all`. */
+export function toolMatchesTag({ tag, tool }: { tag: string; tool: McpToolSelection }): boolean {
+ const annotations = mcpToolAnnotations(tool);
+ switch (tag) {
+ case TOOL_TAG_ALL:
+ return true;
+ case TOOL_TAG_READ_ONLY:
+ return annotations?.readOnlyHint === true;
+ case TOOL_TAG_DESTRUCTIVE:
+ return annotations?.destructiveHint === true;
+ case TOOL_TAG_WRITE:
+ return annotations?.readOnlyHint === false && annotations.destructiveHint !== true;
+ default:
+ return false;
+ }
+}
+
+export function toolMatchesSelectors({
+ tool,
+ selectors,
+}: {
+ tool: McpToolSelection;
+ selectors: readonly string[];
+}): boolean {
+ return selectors.some(selector =>
+ selector.startsWith('@') ? toolMatchesTag({ tag: selector, tool }) : selector === tool.name,
+ );
+}
+
+/**
+ * Tools a mount lets the agent call. `resolved` is false when tags cannot be applied because the
+ * server's tool list — and with it the annotations tags match on — is unavailable.
+ */
+export function selectedToolNames({
+ enableSelectors,
+ disableSelectors,
+ tools,
+}: {
+ enableSelectors: readonly string[];
+ disableSelectors: readonly string[];
+ tools: readonly McpToolSelection[];
+}): { names: string[]; resolved: boolean } {
+ if (tools.length === 0) {
+ if ([...enableSelectors, ...disableSelectors].some(selector => selector.startsWith('@'))) {
+ return { names: [], resolved: false };
+ }
+ return { names: enableSelectors.filter(name => !disableSelectors.includes(name)), resolved: true };
+ }
+ const names = tools
+ .filter(
+ tool =>
+ toolMatchesSelectors({ tool, selectors: enableSelectors }) &&
+ !toolMatchesSelectors({ tool, selectors: disableSelectors }),
+ )
+ .map(tool => tool.name);
+ return { names, resolved: true };
+}
diff --git a/packages/trueforge-ui/src/atoms/primitives/Checkbox.tsx b/packages/trueforge-ui/src/atoms/primitives/Checkbox.tsx
new file mode 100644
index 000000000..e4c1a7da0
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/primitives/Checkbox.tsx
@@ -0,0 +1,30 @@
+'use client';
+
+import { Icon } from '../../icons/Icon.js';
+import { cn } from '../lib/cn.js';
+
+export type CheckboxProps = {
+ checked: boolean;
+ className?: string;
+};
+
+/**
+ * Presentational checkbox box. Callers own the interactive element and its checked semantics,
+ * so this stays `aria-hidden`.
+ */
+export function Checkbox({ checked, className }: CheckboxProps) {
+ return (
+ <span
+ className={cn(
+ 'flex size-4 shrink-0 items-center justify-center rounded-sm border transition-colors',
+ checked
+ ? 'border-primary-button-bg bg-primary-button-bg text-primary-button-text'
+ : 'border-text-secondary/60 bg-input-box-bg',
+ className,
+ )}
+ aria-hidden
+ >
+ {checked ? <Icon name="check" className="size-3" /> : null}
+ </span>
+ );
+}
diff --git a/packages/trueforge-ui/src/icons/IconRegistry.tsx b/packages/trueforge-ui/src/icons/IconRegistry.tsx
index 20f3be1a3..0b779ef97 100644
--- a/packages/trueforge-ui/src/icons/IconRegistry.tsx
+++ b/packages/trueforge-ui/src/icons/IconRegistry.tsx
@@ -59,6 +59,8 @@ import {
Save,
Search,
Settings,
+ Shield,
+ ShieldCheck,
SlidersHorizontal,
Sparkle,
SquareArrowOutUpRight,
@@ -160,6 +162,8 @@ const defaults: Record<string, IconEntry> = {
sun: Sun,
moon: Moon,
settings: Settings,
+ shield: Shield,
+ 'shield-check': ShieldCheck,
sliders: SlidersHorizontal,
'log-out': LogOut,
search: Search,
diff --git a/packages/trueforge-ui/test/atoms/AgentOverviewMcpServers.test.tsx b/packages/trueforge-ui/test/atoms/AgentOverviewMcpServers.test.tsx
new file mode 100644
index 000000000..4af208aac
--- /dev/null
+++ b/packages/trueforge-ui/test/atoms/AgentOverviewMcpServers.test.tsx
@@ -0,0 +1,132 @@
+// @vitest-environment jsdom
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import AgentOverview from '@/atoms/agent-details/AgentOverview.js';
+import { ServerProvider } from '@/server/ServerContext.js';
+import type { AgentDetail, McpToolSelection } from '@/server/types.js';
+import { SlotsProvider } from '@/theme/SlotsProvider.js';
+import { createMockAgentUIServer } from '../server/mockServer.js';
+
+function tool(name: string, annotations: { readOnlyHint?: boolean; destructiveHint?: boolean }): McpToolSelection {
+ const row: McpToolSelection = { id: name, name };
+ Reflect.set(row, 'annotations', annotations);
+ return row;
+}
+
+const slackTools = [
+ tool('slack_send_message', { readOnlyHint: false }),
+ tool('slack_update_canvas', { destructiveHint: true }),
+ tool('slack_search_public', { readOnlyHint: true }),
+];
+const webTools = [tool('web_search', { readOnlyHint: true })];
+
+const detail: AgentDetail = {
+ agentId: 'agent-1',
+ name: 'release-notes-writer',
+ agentSpec: {
+ model: { name: 'openai/gpt-5.1' },
+ instructions: 'Write release notes.',
+ mcpServers: [
+ { name: 'slack', requireApprovalForTools: ['@destructive'] },
+ { name: 'parallel-web', enableTools: ['web_search'] },
+ ],
+ },
+};
+
+function renderOverview({
+ getMcpTools,
+ agentDetail = detail,
+}: {
+ getMcpTools?: (request: { connectorId: string }) => Promise<McpToolSelection[]>;
+ agentDetail?: AgentDetail;
+} = {}) {
+ const server = createMockAgentUIServer(getMcpTools === undefined ? {} : { getMcpTools });
+ render(
+ <SlotsProvider>
+ <ServerProvider server={server}>
+ <AgentOverview detail={agentDetail} />
+ </ServerProvider>
+ </SlotsProvider>,
+ );
+}
+
+describe('AgentOverview MCP servers', () => {
+ it('lists each server with its tool count and how many tools need approval', async () => {
+ const getMcpTools = vi.fn(async ({ connectorId }: { connectorId: string }) =>
+ connectorId === 'slack' ? slackTools : webTools,
+ );
+ renderOverview({ getMcpTools });
+
+ expect(await screen.findByText('3 tools')).toBeInTheDocument();
+ expect(screen.getByText('1 tool')).toBeInTheDocument();
+ expect(screen.getByLabelText('1 tool needs approval')).toBeInTheDocument();
+ expect(getMcpTools).toHaveBeenCalledWith({ connectorId: 'slack' });
+ expect(getMcpTools).toHaveBeenCalledWith({ connectorId: 'parallel-web' });
+ });
+
+ it('expands a server into read/write/destructive tools with their approval state', async () => {
+ renderOverview({ getMcpTools: vi.fn(async () => slackTools) });
+
+ const slack = await screen.findByRole('button', { name: /slack/ });
+ expect(slack).toHaveAttribute('aria-expanded', 'false');
+ fireEvent.click(slack);
+
+ expect(slack).toHaveAttribute('aria-expanded', 'true');
+ // Read-only tools sort first and destructive last, as in the tool picker.
+ expect(screen.getAllByRole('listitem').map(item => item.textContent)).toEqual(
+ expect.arrayContaining(['slack_search_publicread', 'slack_send_messagewrite', 'slack_update_canvasdestructive']),
+ );
+ expect(screen.getByLabelText('slack_search_public runs without approval')).toBeInTheDocument();
+ expect(screen.getByLabelText('slack_update_canvas requires approval')).toBeInTheDocument();
+ });
+
+ it('keeps an all-tools server readable when the host cannot list tools', async () => {
+ renderOverview();
+
+ expect(await screen.findByText('All tools')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /slack/ })).toBeDisabled();
+ expect(screen.getByRole('button', { name: /parallel-web/ })).toBeEnabled();
+ });
+
+ it('applies tag-based enableTools and subtracts disableTools', async () => {
+ renderOverview({
+ getMcpTools: vi.fn(async () => slackTools),
+ agentDetail: {
+ ...detail,
+ agentSpec: {
+ ...detail.agentSpec,
+ mcpServers: [
+ { name: 'slack', enableTools: ['@all'], disableTools: ['slack_update_canvas'] },
+ { name: 'parallel-web', enableTools: ['@read-only'] },
+ ],
+ },
+ },
+ });
+
+ expect(await screen.findByText('2 tools')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: /slack/ }));
+ expect(screen.queryByText('slack_update_canvas')).not.toBeInTheDocument();
+ expect(screen.getByText('slack_send_message')).toBeInTheDocument();
+ });
+
+ it('falls back to the selector text when tags cannot be resolved', () => {
+ renderOverview({
+ agentDetail: {
+ ...detail,
+ agentSpec: { ...detail.agentSpec, mcpServers: [{ name: 'slack', enableTools: ['@read-only'] }] },
+ },
+ });
+
+ expect(screen.getByText('@read-only')).toBeInTheDocument();
+ });
+
+ it('counts only the servers it can render', () => {
+ renderOverview({
+ agentDetail: { ...detail, agentSpec: { ...detail.agentSpec, mcpServers: [] } },
+ });
+
+ expect(screen.getByRole('heading', { name: 'MCP Servers & Tools (0)' })).toBeInTheDocument();
+ expect(screen.getByText('No connectors attached.')).toBeInTheDocument();
+ });
+});
diff --git a/packages/trueforge-ui/test/atoms/draft/AgentConfigEditors.test.tsx b/packages/trueforge-ui/test/atoms/draft/AgentConfigEditors.test.tsx
index ee25bc6c5..85bc53aff 100644
--- a/packages/trueforge-ui/test/atoms/draft/AgentConfigEditors.test.tsx
+++ b/packages/trueforge-ui/test/atoms/draft/AgentConfigEditors.test.tsx
@@ -1206,11 +1206,93 @@ describe('AgentConfigEditors', () => {
await waitFor(() => expect(loadMcpTools).toHaveBeenLastCalledWith('github'));
rendered.rerender(renderEditors(slackSpec));
- expect(loadMcpTools).toHaveBeenLastCalledWith('github');
+ expect(screen.getByRole('button', { name: 'GitHub' })).toHaveAttribute('aria-current', 'true');
expect(screen.getAllByRole('menuitemcheckbox', { name: /issues.list/ }).length).toBeGreaterThan(0);
expect(screen.getByLabelText('Slack selected')).toBeInTheDocument();
});
+ it('relists tools for a selected MCP whose background listing was cancelled', async () => {
+ const slackPending = deferred<{ id: string; name: string }[]>();
+ const loadMcpTools = vi.fn(async (connectorId: string) =>
+ connectorId === 'slack' ? slackPending.promise : [{ id: 'issues.list', name: 'issues.list' }],
+ );
+ const renderEditors = () => (
+ <SlotsProvider>
+ <AgentConfigEditors
+ editor="mcp"
+ spec={{
+ model: { name: 'openai/gpt' },
+ mcpServers: [
+ { id: 'github', name: 'GitHub', enableTools: ['@all'] },
+ { id: 'slack', name: 'Slack', enableTools: ['@all'] },
+ ],
+ }}
+ models={[]}
+ connectors={[
+ { id: 'github', name: 'GitHub', authenticated: true },
+ { id: 'slack', name: 'Slack', authenticated: true },
+ ]}
+ skills={[]}
+ loading={false}
+ error={null}
+ loadMcpTools={loadMcpTools}
+ onChange={vi.fn()}
+ onClose={vi.fn()}
+ />
+ </SlotsProvider>
+ );
+ const rendered = render(renderEditors());
+
+ await waitFor(() => expect(loadMcpTools).toHaveBeenCalledWith('slack'));
+ rendered.rerender(renderEditors());
+
+ await waitFor(() => expect(loadMcpTools.mock.calls.filter(([id]) => id === 'slack')).toHaveLength(2));
+ await act(async () => {
+ slackPending.resolve([{ id: 'messages.list', name: 'messages.list' }]);
+ });
+ });
+
+ it('retries a background tool listing that failed', async () => {
+ const loadMcpTools = vi.fn(async (connectorId: string) => {
+ if (connectorId !== 'slack') return [{ id: 'issues.list', name: 'issues.list' }];
+ if (loadMcpTools.mock.calls.filter(([id]) => id === 'slack').length === 1) {
+ throw new Error('Slack is unreachable');
+ }
+ return [{ id: 'messages.list', name: 'messages.list' }];
+ });
+ const renderEditors = () => (
+ <SlotsProvider>
+ <AgentConfigEditors
+ editor="mcp"
+ spec={{
+ model: { name: 'openai/gpt' },
+ mcpServers: [
+ { id: 'github', name: 'GitHub', enableTools: ['@all'] },
+ { id: 'slack', name: 'Slack', enableTools: ['@all'] },
+ ],
+ }}
+ models={[]}
+ connectors={[
+ { id: 'github', name: 'GitHub', authenticated: true },
+ { id: 'slack', name: 'Slack', authenticated: true },
+ ]}
+ skills={[]}
+ loading={false}
+ error={null}
+ loadMcpTools={loadMcpTools}
+ onChange={vi.fn()}
+ onClose={vi.fn()}
+ />
+ </SlotsProvider>
+ );
+ const rendered = render(renderEditors());
+
+ await waitFor(() => expect(loadMcpTools).toHaveBeenCalledWith('slack'));
+ rendered.rerender(renderEditors());
+
+ await waitFor(() => expect(loadMcpTools.mock.calls.filter(([id]) => id === 'slack')).toHaveLength(2));
+ });
+
it('enables sandbox when a skill is added', () => {
const spec: AgentSpec = { model: { name: 'openai/gpt' } };
const onChange = vi.fn();
diff --git a/packages/trueforge-ui/test/atoms/draft/AgentMcpEditorContent.approvals.test.tsx b/packages/trueforge-ui/test/atoms/draft/AgentMcpEditorContent.approvals.test.tsx
new file mode 100644
index 000000000..3ee86a539
--- /dev/null
+++ b/packages/trueforge-ui/test/atoms/draft/AgentMcpEditorContent.approvals.test.tsx
@@ -0,0 +1,311 @@
+// @vitest-environment jsdom
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { AgentMcpEditorContent } from '@/atoms/draft/AgentMcpEditorContent.js';
+import type { AgentSpec, McpToolSelection } from '@/server/types.js';
+import { SlotsProvider } from '@/theme/SlotsProvider.js';
+
+function tool(name: string, annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean }): McpToolSelection {
+ const row: McpToolSelection = { id: name, name, description: name };
+ if (annotations !== undefined) Reflect.set(row, 'annotations', annotations);
+ return row;
+}
+
+const tools = [
+ tool('list_items', { readOnlyHint: true, destructiveHint: false }),
+ tool('rename_item', { readOnlyHint: false, destructiveHint: false }),
+ tool('delete_item', { readOnlyHint: false, destructiveHint: true }),
+];
+
+function renderEditor({
+ spec,
+ onChange,
+ serverTools = tools,
+}: {
+ spec: AgentSpec;
+ onChange: (next: AgentSpec) => void;
+ serverTools?: McpToolSelection[];
+}) {
+ return render(
+ <SlotsProvider>
+ <AgentMcpEditorContent
+ spec={spec}
+ connectors={[{ id: 'linear', name: 'Linear', authenticated: true }]}
+ query=""
+ activeConnectorId="linear"
+ tools={serverTools}
+ connectorLoading={false}
+ connectorError={null}
+ toolsLoading={false}
+ toolsError={null}
+ onQueryChange={vi.fn()}
+ onSelectConnector={vi.fn()}
+ onRetryTools={vi.fn()}
+ onChange={onChange}
+ />
+ </SlotsProvider>,
+ );
+}
+
+const mountedSpec: AgentSpec = {
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['@all'] }],
+};
+
+describe('AgentMcpEditorContent tool approvals', () => {
+ it('marks only destructive tools as approval-gated by default', () => {
+ renderEditor({ spec: mountedSpec, onChange: vi.fn() });
+
+ expect(screen.getByRole('button', { name: 'Require approval for rename_item' })).toHaveAttribute(
+ 'aria-pressed',
+ 'false',
+ );
+ expect(screen.getByRole('button', { name: 'Require approval for delete_item' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ expect(screen.getByRole('button', { name: 'Require approval for list_items' })).toHaveAttribute(
+ 'aria-pressed',
+ 'false',
+ );
+ });
+
+ it('gates a read-only tool the harness would otherwise auto-run', () => {
+ const onChange = vi.fn();
+ renderEditor({
+ spec: {
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['@all'], requireApprovalForTools: [] }],
+ },
+ onChange,
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Require approval for list_items' }));
+
+ expect(onChange).toHaveBeenCalledWith({
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['@all'], requireApprovalForTools: ['list_items'] }],
+ });
+ });
+
+ it('collapses to @all once every tool is gated', () => {
+ const onChange = vi.fn();
+ renderEditor({
+ spec: {
+ model: { name: 'openai/gpt' },
+ mcpServers: [
+ { id: 'linear', name: 'Linear', enableTools: ['@all'], requireApprovalForTools: ['@write', '@destructive'] },
+ ],
+ },
+ onChange,
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Require approval for list_items' }));
+
+ expect(onChange).toHaveBeenCalledWith({
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['@all'], requireApprovalForTools: ['@all'] }],
+ });
+ });
+
+ it('writes an empty list when the last gated tool is set to auto-run', () => {
+ const onChange = vi.fn();
+ renderEditor({ spec: mountedSpec, onChange });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Require approval for delete_item' }));
+
+ expect(onChange).toHaveBeenCalledWith({
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['@all'], requireApprovalForTools: [] }],
+ });
+ });
+
+ it('drops the field when the selection returns to the harness default', () => {
+ const onChange = vi.fn();
+ renderEditor({
+ spec: {
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['@all'], requireApprovalForTools: [] }],
+ },
+ onChange,
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Require approval for delete_item' }));
+
+ expect(onChange).toHaveBeenCalledWith({
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['@all'] }],
+ });
+ });
+
+ it('gates every destructive tool from the section toggle', () => {
+ const onChange = vi.fn();
+ renderEditor({
+ spec: {
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['@all'], requireApprovalForTools: [] }],
+ },
+ onChange,
+ });
+
+ fireEvent.click(screen.getByRole('switch', { name: 'Require approval for all destructive tools' }));
+
+ expect(onChange).toHaveBeenCalledWith({
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['@all'] }],
+ });
+ });
+
+ it('starts the destructive section toggle on and clears approval when switched off', () => {
+ const onChange = vi.fn();
+ renderEditor({ spec: mountedSpec, onChange });
+ const toggle = screen.getByRole('switch', { name: 'Require approval for all destructive tools' });
+
+ expect(toggle).toBeChecked();
+ fireEvent.click(toggle);
+
+ expect(onChange).toHaveBeenCalledWith({
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['@all'], requireApprovalForTools: [] }],
+ });
+ });
+
+ it('offers the section toggle only for destructive tools', () => {
+ renderEditor({ spec: mountedSpec, onChange: vi.fn() });
+
+ expect(screen.getByRole('switch', { name: 'Require approval for all destructive tools' })).toBeInTheDocument();
+ expect(screen.getAllByText('Approval required')).toHaveLength(1);
+ });
+
+ it('hides approval controls for tools that are not enabled', () => {
+ renderEditor({
+ spec: {
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['delete_item'] }],
+ },
+ onChange: vi.fn(),
+ });
+
+ expect(screen.getByRole('button', { name: 'Require approval for delete_item' })).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Require approval for rename_item' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Require approval for list_items' })).not.toBeInTheDocument();
+ });
+
+ it('hides the destructive toggle when no destructive tool is enabled', () => {
+ renderEditor({
+ spec: {
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['rename_item'] }],
+ },
+ onChange: vi.fn(),
+ });
+
+ expect(
+ screen.queryByRole('switch', { name: 'Require approval for all destructive tools' }),
+ ).not.toBeInTheDocument();
+ });
+
+ it('shows no approval controls until the server is added', () => {
+ renderEditor({ spec: { model: { name: 'openai/gpt' } }, onChange: vi.fn() });
+
+ expect(screen.queryByRole('button', { name: /^Require approval for/ })).not.toBeInTheDocument();
+ expect(screen.queryByRole('switch', { name: /^Require approval for/ })).not.toBeInTheDocument();
+ });
+
+ it('gates only the enabled destructive tools', () => {
+ const onChange = vi.fn();
+ renderEditor({
+ spec: {
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['delete_item'], requireApprovalForTools: [] }],
+ },
+ onChange,
+ serverTools: [...tools, tool('purge_items', { readOnlyHint: false, destructiveHint: true })],
+ });
+
+ fireEvent.click(screen.getByRole('switch', { name: 'Require approval for all destructive tools' }));
+
+ expect(onChange).toHaveBeenCalledWith({
+ model: { name: 'openai/gpt' },
+ mcpServers: [
+ { id: 'linear', name: 'Linear', enableTools: ['delete_item'], requireApprovalForTools: ['delete_item'] },
+ ],
+ });
+ });
+
+ it('summarizes how many selected tools need approval', () => {
+ renderEditor({
+ spec: {
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['list_items', 'rename_item', 'delete_item'] }],
+ },
+ onChange: vi.fn(),
+ });
+
+ expect(screen.getByText('Selected Tools (3)')).toBeInTheDocument();
+ expect(screen.getByText('3 selected · 1 need approval')).toBeInTheDocument();
+ expect(screen.getAllByText('approval')).toHaveLength(1);
+ });
+
+ it('enables every tool in a section from its Enable all switch', () => {
+ const onChange = vi.fn();
+ renderEditor({ spec: { model: { name: 'openai/gpt' } }, onChange });
+
+ fireEvent.click(screen.getByRole('switch', { name: 'Enable all destructive tools' }));
+
+ expect(onChange).toHaveBeenCalledWith({
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['delete_item'] }],
+ });
+ });
+
+ it('turns approval off when selecting an Other tool even if the mount still gates @write', () => {
+ const onChange = vi.fn();
+ renderEditor({
+ spec: {
+ model: { name: 'openai/gpt' },
+ mcpServers: [
+ {
+ id: 'linear',
+ name: 'Linear',
+ enableTools: ['list_items'],
+ requireApprovalForTools: ['@write', '@destructive'],
+ },
+ ],
+ },
+ onChange,
+ });
+
+ fireEvent.click(screen.getByRole('menuitemcheckbox', { name: 'rename_item' }));
+
+ expect(onChange).toHaveBeenCalledWith({
+ model: { name: 'openai/gpt' },
+ mcpServers: [
+ {
+ id: 'linear',
+ name: 'Linear',
+ enableTools: ['list_items', 'rename_item'],
+ },
+ ],
+ });
+ });
+
+ it('keeps approval on when selecting a destructive tool', () => {
+ const onChange = vi.fn();
+ renderEditor({
+ spec: {
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['list_items'], requireApprovalForTools: [] }],
+ },
+ onChange,
+ });
+
+ fireEvent.click(screen.getByRole('menuitemcheckbox', { name: 'delete_item' }));
+
+ expect(onChange).toHaveBeenCalledWith({
+ model: { name: 'openai/gpt' },
+ mcpServers: [{ id: 'linear', name: 'Linear', enableTools: ['list_items', 'delete_item'] }],
+ });
+ });
+});
diff --git a/packages/trueforge-ui/test/atoms/draft/mcpToolApprovals.test.ts b/packages/trueforge-ui/test/atoms/draft/mcpToolApprovals.test.ts
new file mode 100644
index 000000000..50431da70
--- /dev/null
+++ b/packages/trueforge-ui/test/atoms/draft/mcpToolApprovals.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from 'vitest';
+
+import { approvalSelectorsFromMount, withApprovalSelectors } from '@/atoms/draft/agentConfigMounts.js';
+import {
+ approvalSelectorsAfterEnabling,
+ approvalSelectorsFor,
+ approvedToolNames,
+ DEFAULT_APPROVAL_SELECTORS,
+ namedToolRequiresApproval,
+} from '@/atoms/draft/mcpToolApprovals.js';
+import type { McpToolSelection } from '@/server/types.js';
+
+function tool(name: string, annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean }): McpToolSelection {
+ const row: McpToolSelection = { id: name, name };
+ if (annotations !== undefined) Reflect.set(row, 'annotations', annotations);
+ return row;
+}
+
+const listItems = tool('list_items', { readOnlyHint: true, destructiveHint: false });
+const renameItem = tool('rename_item', { readOnlyHint: false, destructiveHint: false });
+const deleteItem = tool('delete_item', { readOnlyHint: false, destructiveHint: true });
+const unannotated = tool('run_report');
+const tools = [listItems, renameItem, deleteItem, unannotated];
+
+describe('namedToolRequiresApproval', () => {
+ it('falls back to name and @all matching when annotations are unknown', () => {
+ expect(
+ namedToolRequiresApproval({ toolName: 'delete_item', tools: [], selectors: ['@write', '@destructive'] }),
+ ).toBe(false);
+ expect(namedToolRequiresApproval({ toolName: 'delete_item', tools: [], selectors: ['delete_item'] })).toBe(true);
+ expect(namedToolRequiresApproval({ toolName: 'delete_item', tools, selectors: ['@destructive'] })).toBe(true);
+ });
+});
+
+describe('approvalSelectorsAfterEnabling', () => {
+ it('ungates Other tools and keeps destructive tools gated', () => {
+ expect(
+ approvalSelectorsAfterEnabling({
+ tools,
+ selectors: ['@write', '@destructive'],
+ newlyEnabledNames: ['rename_item', 'delete_item'],
+ }),
+ ).toEqual(['@destructive']);
+ });
+
+ it('keeps the harness default when enabling tools on a server with no destructive class', () => {
+ expect(
+ approvalSelectorsAfterEnabling({
+ tools: [unannotated],
+ selectors: [...DEFAULT_APPROVAL_SELECTORS],
+ newlyEnabledNames: ['run_report'],
+ }),
+ ).toEqual([...DEFAULT_APPROVAL_SELECTORS]);
+ });
+});
+
+describe('approvalSelectorsFor', () => {
+ it('keeps class tags while every tool of the class stays gated', () => {
+ const approved = approvedToolNames({ tools, selectors: [...DEFAULT_APPROVAL_SELECTORS] });
+ approved.add('list_items');
+
+ expect(approvalSelectorsFor({ tools, approved })).toEqual(['@destructive', 'list_items']);
+ });
+
+ it('expands a class tag into names when one of its tools is ungated', () => {
+ const approved = new Set(['rename_item']);
+
+ expect(approvalSelectorsFor({ tools, approved })).toEqual(['@write']);
+ });
+
+ it('drops a tag whose tools are no longer all gated', () => {
+ const moreWrites = [...tools, tool('archive_item', { readOnlyHint: false, destructiveHint: false })];
+ const approved = new Set(['rename_item', 'delete_item']);
+
+ expect(approvalSelectorsFor({ tools: moreWrites, approved })).toEqual(['@destructive', 'rename_item']);
+ });
+
+ it('collapses to @all when every tool is gated', () => {
+ const approved = new Set(tools.map(item => item.name));
+
+ expect(approvalSelectorsFor({ tools, approved })).toEqual(['@all']);
+ });
+
+ it('returns an empty list when nothing is gated', () => {
+ expect(approvalSelectorsFor({ tools, approved: new Set() })).toEqual([]);
+ });
+
+ it('omits class tags when the server has no tools in that class', () => {
+ expect(approvalSelectorsFor({ tools: [unannotated], approved: new Set() })).toEqual([]);
+ expect(approvalSelectorsFor({ tools: [listItems], approved: new Set([listItems.name]) })).toEqual(['@all']);
+ });
+});
+
+describe('mount approval selectors', () => {
+ it('reads the harness default when the mount omits the field', () => {
+ expect(approvalSelectorsFromMount({ name: 'linear' })).toEqual(['@destructive']);
+ expect(approvalSelectorsFromMount({ name: 'linear', requireApprovalForTools: [] })).toEqual([]);
+ });
+
+ it('drops the field again when the selection matches the default', () => {
+ const mount = { name: 'linear', requireApprovalForTools: ['@all'] };
+
+ expect(withApprovalSelectors(mount, ['@destructive'])).toEqual({ name: 'linear' });
+ expect(withApprovalSelectors(mount, [])).toEqual({ name: 'linear', requireApprovalForTools: [] });
+ });
+});
diff --git a/packages/trueforge-ui/test/atoms/draft/mcpToolSelectors.test.ts b/packages/trueforge-ui/test/atoms/draft/mcpToolSelectors.test.ts
new file mode 100644
index 000000000..de0e0967e
--- /dev/null
+++ b/packages/trueforge-ui/test/atoms/draft/mcpToolSelectors.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from 'vitest';
+
+import { disableSelectorsFromMount, enableSelectorsFromMount } from '@/atoms/draft/agentConfigMounts.js';
+import { selectedToolNames, toolMatchesSelectors } from '@/atoms/draft/mcpToolSelectors.js';
+import type { McpToolSelection } from '@/server/types.js';
+
+function tool(name: string, annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean }): McpToolSelection {
+ const row: McpToolSelection = { id: name, name };
+ if (annotations !== undefined) Reflect.set(row, 'annotations', annotations);
+ return row;
+}
+
+const listItems = tool('list_items', { readOnlyHint: true, destructiveHint: false });
+const renameItem = tool('rename_item', { readOnlyHint: false, destructiveHint: false });
+const deleteItem = tool('delete_item', { readOnlyHint: false, destructiveHint: true });
+const unannotated = tool('run_report');
+const tools = [listItems, renameItem, deleteItem, unannotated];
+
+describe('toolMatchesSelectors', () => {
+ it('resolves class tags from tool annotations', () => {
+ const selectors = ['@write', '@destructive'];
+ expect(toolMatchesSelectors({ tool: renameItem, selectors })).toBe(true);
+ expect(toolMatchesSelectors({ tool: deleteItem, selectors })).toBe(true);
+ expect(toolMatchesSelectors({ tool: listItems, selectors })).toBe(false);
+ expect(toolMatchesSelectors({ tool: listItems, selectors: ['@read-only'] })).toBe(true);
+ expect(toolMatchesSelectors({ tool: renameItem, selectors: ['@read-only'] })).toBe(false);
+ });
+
+ it('matches unannotated tools only by name or @all', () => {
+ expect(toolMatchesSelectors({ tool: unannotated, selectors: ['@write', '@destructive'] })).toBe(false);
+ expect(toolMatchesSelectors({ tool: unannotated, selectors: ['run_report'] })).toBe(true);
+ expect(toolMatchesSelectors({ tool: unannotated, selectors: ['@all'] })).toBe(true);
+ });
+
+ it('matches nothing for an empty selector list', () => {
+ expect(toolMatchesSelectors({ tool: deleteItem, selectors: [] })).toBe(false);
+ });
+});
+
+describe('selectedToolNames', () => {
+ it('applies enable tags and subtracts disabled tools', () => {
+ expect(selectedToolNames({ enableSelectors: ['@read-only'], disableSelectors: [], tools })).toEqual({
+ names: ['list_items'],
+ resolved: true,
+ });
+ expect(selectedToolNames({ enableSelectors: ['@all'], disableSelectors: ['@destructive'], tools })).toEqual({
+ names: ['list_items', 'rename_item', 'run_report'],
+ resolved: true,
+ });
+ expect(
+ selectedToolNames({ enableSelectors: ['list_items', 'delete_item'], disableSelectors: ['delete_item'], tools }),
+ ).toEqual({ names: ['list_items'], resolved: true });
+ });
+
+ it('reports tags as unresolved until the tool list is known', () => {
+ expect(selectedToolNames({ enableSelectors: ['@read-only'], disableSelectors: [], tools: [] })).toEqual({
+ names: [],
+ resolved: false,
+ });
+ expect(
+ selectedToolNames({ enableSelectors: ['list_items', 'delete_item'], disableSelectors: [], tools: [] }),
+ ).toEqual({ names: ['list_items', 'delete_item'], resolved: true });
+ });
+});
+
+describe('mount tool selectors', () => {
+ it('treats a missing enableTools as every tool', () => {
+ expect(enableSelectorsFromMount({ name: 'linear' })).toEqual(['@all']);
+ expect(enableSelectorsFromMount({ name: 'linear', enableTools: ['@read-only'] })).toEqual(['@read-only']);
+ expect(enableSelectorsFromMount({ name: 'linear', enableTools: [] })).toEqual([]);
+ expect(disableSelectorsFromMount({ name: 'linear' })).toEqual([]);
+ expect(disableSelectorsFromMount({ name: 'linear', disableTools: ['delete_item'] })).toEqual(['delete_item']);
+ });
+});
diff --git a/python/trueforge_sdk/src/trueforge_sdk/types/mcp_server.py b/python/trueforge_sdk/src/trueforge_sdk/types/mcp_server.py
index 539a3ca52..46d237306 100644
--- a/python/trueforge_sdk/src/trueforge_sdk/types/mcp_server.py
+++ b/python/trueforge_sdk/src/trueforge_sdk/types/mcp_server.py
@@ -39,7 +39,7 @@ class McpServer(UncheckedBaseModel):
default=None
)
"""
- Tools that pause for human approval: `@all`, `@write`, `@destructive`, or literal names. Default: `["@write", "@destructive"]`.
+ Tools that pause for human approval: `@all`, `@write`, `@destructive`, or literal names. Default: `["@destructive"]`.
"""
if IS_PYDANTIC_V2: