Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Let any tool declare that each call needs approval (#2561)

Regan Bell19c9fe334c95
diff --git a/docs/mcp-connectors.md b/docs/mcp-connectors.md
index 54959f144..0db7e180f 100644
--- a/docs/mcp-connectors.md
+++ b/docs/mcp-connectors.md
@@ -1,7 +1,14 @@
# MCP connector credentials
-Administrators register HTTP MCP servers through `PUT /v1/admin/mcp-servers/:id`.
-Registration controls the outbound destination and the tools available to agents.
+Administrators register HTTP MCP servers through `PUT /v1/admin/mcp-servers/:id`
+from an admin session (`/admin/api/mcp-servers/:id` behind the portal); agent tokens
+are refused, so an agent cannot change which tools it may call or which calls need
+approval. Registration controls the outbound destination and the tools available to agents.
+
+`approval` decides which calls pause for a person's approval, bound to the exact
+arguments and good for one call: `annotations` (the default; tools annotated
+`destructiveHint: true` and not `readOnlyHint: true`), `all`, or `none`. An update
+that omits `approval` keeps the current policy.
`credentialScope` selects the identity used for `tools/call`:
diff --git a/plugins/admin/src/index.ts b/plugins/admin/src/index.ts
index 36559b91e..2b6f22888 100644
--- a/plugins/admin/src/index.ts
+++ b/plugins/admin/src/index.ts
@@ -312,6 +312,7 @@ const WRITES = new Map<string, string[]>([
["model-providers", ["PUT", "DELETE"]],
["model-registry", ["POST", "PUT", "DELETE"]],
["custom-providers", ["PUT", "DELETE"]],
+ ["mcp-servers", ["PUT", "DELETE"]],
]);
const READS = [
@@ -339,6 +340,7 @@ const READS = [
"model-providers",
"model-registry",
"custom-providers",
+ "mcp-servers",
"principal-links",
];
diff --git a/src/api/routes/admin.ts b/src/api/routes/admin.ts
index acd4fed02..96465c256 100644
--- a/src/api/routes/admin.ts
+++ b/src/api/routes/admin.ts
@@ -77,6 +77,8 @@ const timed =
const GRANTS = "admin grant changes (promote/revoke) are portal-only — the agent cannot manage who governs the org";
const IMPERSONATE = "impersonating a user is portal-only — the agent cannot act as another person";
+const MCP_SERVERS =
+ "registering or changing an MCP server is portal-only — the agent cannot change which tools it can call or which calls need approval";
const LINKS = "identity links are portal-only — the agent cannot decide which sign-ins belong to one person";
const routes: Route<ApiCtx>[] = [
@@ -92,7 +94,13 @@ const routes: Route<ApiCtx>[] = [
{ method: "GET", path: "/v1/admin/model-providers", auth: "either", handle: getModelProviders },
{ method: "PUT", path: "/v1/admin/model-providers/:provider", auth: "either", handle: putModelProvider },
{ method: "GET", path: "/v1/admin/mcp-servers", auth: "either", handle: getMcpServers },
- { method: "PUT", path: "/v1/admin/mcp-servers/:id", auth: "either", handle: putMcpServer },
+ {
+ method: "PUT",
+ path: "/v1/admin/mcp-servers/:id",
+ auth: "either",
+ admin: { agent: { portalOnly: MCP_SERVERS } },
+ handle: putMcpServer,
+ },
{ method: "DELETE", path: "/v1/admin/mcp-servers/:id", auth: "either", handle: deleteMcpServer },
{ method: "DELETE", path: "/v1/admin/model-providers/:provider", auth: "either", handle: deleteModelProvider },
{ method: "POST", path: "/v1/admin/model-registry/lookup", auth: "either", handle: lookupRegistryModel },
diff --git a/src/api/routes/admin/mcp-servers.ts b/src/api/routes/admin/mcp-servers.ts
index 752abad7d..526042473 100644
--- a/src/api/routes/admin/mcp-servers.ts
+++ b/src/api/routes/admin/mcp-servers.ts
@@ -4,7 +4,12 @@
// HTTP destination every scope's agents can call, so it is governed like a
// model-provider credential, not like a personal connector.
-import { isValidMcpServerId, type McpServer, type McpServerAuthMode } from "../../../mcp/mcp-server-store.ts";
+import {
+ isValidMcpServerId,
+ type McpApprovalPolicy,
+ type McpServer,
+ type McpServerAuthMode,
+} from "../../../mcp/mcp-server-store.ts";
import { isAccountType, PROVIDERS } from "../../../connectors/oauth.ts";
import { discoverOAuth, httpsUrl, parseScopes, type DiscoveredOAuth } from "../../../mcp/oauth-discovery.ts";
import { sendJson } from "../../http.ts";
@@ -12,6 +17,7 @@ import type { ApiCtx } from "../route.ts";
import { audit, authorizeAdmin, orgScope } from "../shared.ts";
const AUTH_MODES: McpServerAuthMode[] = ["none", "bearer", "client-credentials", "oauth-user"];
+const APPROVAL_POLICIES: McpApprovalPolicy[] = ["annotations", "all", "none"];
async function actor(ctx: ApiCtx) {
const scope = orgScope(ctx.deps);
@@ -39,11 +45,12 @@ export async function getMcpServers(ctx: ApiCtx): Promise<void> {
const servers = await ctx.deps.mcpServers.list();
return sendJson(ctx.res, 200, {
servers: servers.map(redact),
- tools: ctx.deps.mcpToolService?.toolDefs().map(({ name, serverId, description, readOnly }) => ({
+ tools: ctx.deps.mcpToolService?.toolDefs().map(({ name, serverId, description, readOnly, needsApproval }) => ({
name,
serverId,
description,
readOnly,
+ needsApproval,
})),
});
}
@@ -80,6 +87,13 @@ export async function putMcpServer(ctx: ApiCtx): Promise<void> {
if (!AUTH_MODES.includes(auth)) {
return sendJson(ctx.res, 400, { error: "bad_request", message: `auth must be one of ${AUTH_MODES.join(", ")}` });
}
+ const approval = b.approval ?? (await ctx.deps.mcpServers.get(id))?.approval ?? "annotations";
+ if (!APPROVAL_POLICIES.includes(approval)) {
+ return sendJson(ctx.res, 400, {
+ error: "bad_request",
+ message: `approval must be one of ${APPROVAL_POLICIES.join(", ")}`,
+ });
+ }
const existing = await ctx.deps.mcpServers.get(id);
const oauthUser = auth === "oauth-user";
if (oauthUser && PROVIDERS[id]) {
@@ -166,6 +180,7 @@ export async function putMcpServer(ctx: ApiCtx): Promise<void> {
clientSecret: typeof b.clientSecret === "string" && b.clientSecret ? b.clientSecret : existing?.clientSecret,
}
: {}),
+ ...(approval === "annotations" ? {} : { approval }),
readOnly: b.readOnly !== false,
enabled: b.enabled !== false,
updatedAt: Date.now(),
diff --git a/src/api/slack-core-client.ts b/src/api/slack-core-client.ts
index ef39a81c8..559b87e52 100644
--- a/src/api/slack-core-client.ts
+++ b/src/api/slack-core-client.ts
@@ -59,6 +59,7 @@ interface SlackRunHooks {
interface StoredApprovalView extends Omit<PendingApproval, "reason"> {
createdAt?: number;
reason?: string;
+ sessionId?: string;
request?: Record<string, unknown>;
}
@@ -413,6 +414,7 @@ export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClien
requestId: record.requestId,
...(record.createdAt !== undefined ? { createdAt: record.createdAt } : {}),
command: record.command,
+ sessionId: record.sessionId,
...(record.reason !== undefined ? { reason: record.reason } : {}),
...(record.purpose !== undefined ? { purpose: record.purpose } : {}),
...(record.summary !== undefined ? { summary: record.summary } : {}),
diff --git a/src/core/approval-id.ts b/src/core/approval-id.ts
index e8ce766ce..a76158c0b 100644
--- a/src/core/approval-id.ts
+++ b/src/core/approval-id.ts
@@ -1,9 +1,14 @@
+import { canonicalJson } from "../../cli/src/canonical-json.ts";
import { hashId } from "../util/crypto.ts";
-export function commandApprovalId(sessionId: string, command: string): string {
- return hashId([sessionId, command]);
+export function commandApprovalId(sessionId: string, command: string, approvalKey?: string): string {
+ return hashId(approvalKey ? [sessionId, command, approvalKey] : [sessionId, command]);
}
export function inputApprovalId(sessionId: string, request: unknown): string {
return hashId([sessionId, "security-screen", JSON.stringify(request ?? null)]);
}
+
+export function toolCallApprovalKey(tool: string, params: unknown): string {
+ return `tool-call:${hashId([tool, canonicalJson(params ?? null)], 64)}`;
+}
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 04afa229d..efb52f9ab 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -157,7 +157,7 @@ import {
} from "../harness/replay.ts";
import { errMessage, reportFailure, swallow, swallowAs } from "../util/errors.ts";
import { isObj } from "../util/objects.ts";
-import { absoluteAppLinks, jsonbSafeStringify } from "../util/text.ts";
+import { absoluteAppLinks, headSlice, jsonbSafeStringify } from "../util/text.ts";
import {
isModelBudget,
isNonRetryable,
@@ -208,7 +208,6 @@ import { createTurnSandboxes } from "./orchestrator/sandboxes.ts";
import type { EgressPolicy } from "../types.ts";
import { isOpenScopeMember } from "../resolution/sharing-access.ts";
import { createSurfaceToolDeps, type SpineState } from "./orchestrator/surface-tools.ts";
-import { GATED_TOOL_APPROVALS } from "../harness/agent-tools.ts";
import { createAttachStaging } from "./orchestrator/attach-tool.ts";
import { reconcileMessageRevisions, revisionAnchorAt } from "./message-revisions.ts";
@@ -2043,6 +2042,17 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
}),
);
await mirrorRunActivity(decisionEntry);
+ if (p.kind !== "input" && !p.screenedOutput)
+ await withManagedRosterVersion(() =>
+ deps.sessions.append(lease, {
+ type: "user",
+ payload: {
+ hidden: true,
+ text: `The requesting human denied this pending operation, so it did not run: ${headSlice(p.summary ?? p.command, 2_000)}\nDo not retry it unless they ask again.`,
+ },
+ scopeLabel: scopeId as ScopeId,
+ }),
+ );
await pending.delete(input.approval.requestId);
deps.auditLog.record({
at: Date.now(),
@@ -2064,13 +2074,10 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
const quarantineRelease =
p.approvalKey?.startsWith("security-screen-release:") === true ||
p.approvalKey?.startsWith("quarantine:") === true;
- const recordDisallowsScope =
- scope !== "once" &&
- (quarantineRelease ||
- (p.grantModes?.[scope] === false && p.approvalKey?.startsWith("sandbox:") === true));
+ const recordDisallowsScope = scope !== "once" && (quarantineRelease || p.grantModes?.[scope] === false);
if (scope !== "once" && (!resolution.approvalGrantModes[scope] || recordDisallowsScope)) {
let reason = `the "${scope}" approval option is disabled by an admin here — approve once or deny`;
- if (recordDisallowsScope) {
+ if (recordDisallowsScope && resolution.approvalGrantModes[scope]) {
reason = quarantineRelease
? `quarantined content can only be released once — approve once or deny`
: `this approval does not allow the "${scope}" option — approve once or deny`;
@@ -3613,10 +3620,10 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
},
}
: {}),
- toolApprovalGate:
- securityPolicy.toolApprovals === "all"
- ? authorizeToolCall
- : (tool: string) => !GATED_TOOL_APPROVALS[tool] || authorizeToolCall(tool),
+ toolApprovalGate: (tool: string, callKey?: string) => {
+ if (callKey) return consumeApproval(callKey);
+ return securityPolicy.toolApprovals !== "all" || authorizeToolCall(tool);
+ },
systemPrompt,
history: continuation?.history ?? history,
tools,
@@ -3909,6 +3916,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
pa.screenedOutput
? `${command}:${hashId([pa.screenedOutput.tool, pa.screenedOutput.text, pa.screenedOutput.sourceScopeId ?? scopeId], 64)}`
: command,
+ pa.approvalKey,
);
const summary = pa.summary ?? (await approvalSummary(scopeId, command, pa.reason, pa.purpose));
prepared.push({
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index 36a08a770..1b262ea7e 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -1,3 +1,5 @@
+import { toolCallApprovalKey } from "../core/approval-id.ts";
+import { canonicalJson } from "../../cli/src/canonical-json.ts";
import { adminOperations } from "../tools/admin.ts";
import { parkIfOverCap } from "../sessions/tool-output.ts";
import { handbackStop } from "../runs/run-store.ts";
@@ -17,7 +19,7 @@ import type { GapWork } from "../sessions/session-store.ts";
import { NeedsApproval, CommandDenied } from "../tools/primitives.ts";
import type { McpToolDescriptor } from "../mcp/mcp-tool-service.ts";
import { splitToScope } from "../api/artifact-share.ts";
-import { errMessage, swallowAs } from "../util/errors.ts";
+import { errMessage, reportFailure, swallowAs } from "../util/errors.ts";
import { MemoryFactsMissing } from "../memory/facts.ts";
import { MemoryDisclosureDenied } from "../memory/disclosure.ts";
import { computerVerdict } from "../sandbox/sandbox.ts";
@@ -136,7 +138,7 @@ export interface ToolContextRef {
/** The agent's recent work for the governor, newest last. */
goalRecentWork?: () => string;
screenToolResult?: (input: ToolResultScreenInput) => Promise<ToolResultScreen>;
- toolApprovalGate?: (tool: string) => boolean;
+ toolApprovalGate?: (tool: string, callKey?: string) => boolean;
}
function text(s: string) {
@@ -4231,8 +4233,8 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
const mcpDefs = opts?.mcpTools ?? [];
const mcpTools = mcpDefs
.filter((d) => !opts?.readOnly || d.readOnly)
- .map((d) =>
- defineTool({
+ .map((d) => ({
+ ...defineTool({
name: d.name,
label: d.name,
description:
@@ -4262,7 +4264,8 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
}
},
}),
- );
+ needsApproval: d.needsApproval === true,
+ }));
const clientTools = [...(opts?.clientTools ?? [])]
.sort((a, b) => (a.name < b.name ? -1 : 1))
@@ -4400,12 +4403,16 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
read: skill,
...(controlTools ? { share: sharingTool("skill"), move: sharingTool("skill", true) } : {}),
}),
- resourceTool("files", {
- read,
- write,
- ...(controlTools ? { share: sharingTool("file") } : {}),
- ...(ref.current?.installSharedCanvas ? { install_canvas: installCanvas } : {}),
- }),
+ {
+ ...resourceTool("files", {
+ read,
+ write,
+ ...(controlTools ? { share: sharingTool("file") } : {}),
+ ...(ref.current?.installSharedCanvas ? { install_canvas: installCanvas } : {}),
+ }),
+ needsApproval: (params: unknown) => isObj(params) && params.action === "install_canvas",
+ approvalReason: "install an always-on canvas someone shared with you; its code runs in your QM web UI",
+ },
resourceTool("apps", {
publish,
...(controlTools ? { share: sharingTool("deploy"), move: sharingTool("deploy", true) } : {}),
@@ -4573,19 +4580,27 @@ function withRetrySafety(tool: ToolDefinition, marks: Map<string, RetryMark>): T
}
const TOOL_APPROVAL_EXEMPT = new Set(["finish_silently"]);
-export const GATED_TOOL_APPROVALS: Record<
- string,
- { reason: string; summary: (params: Record<string, unknown>) => string }
-> = {
- "files:install_canvas": {
- reason: "install an always-on canvas someone shared with you; its code runs in your QM web UI",
- summary: (params) => `file ${String(params.id)}`,
- },
-};
const STRICT_TOOL_APPROVAL_REASON = "strict posture: this tool call requires human approval";
+const DECLARED_TOOL_APPROVAL_REASON = "this tool asks for approval before each call";
+const APPROVAL_ARGS_MAX_CHARS = 16_000;
+
+interface ToolApprovalDeclaration {
+ needsApproval?: boolean | ((params: unknown) => boolean | Promise<boolean>);
+ approvalReason?: string;
+}
+
+async function declaredApprovalReason(tool: ToolApprovalDeclaration, params: unknown): Promise<string | undefined> {
+ const needed =
+ typeof tool.needsApproval === "function" ? await tool.needsApproval(params) : tool.needsApproval === true;
+ return needed ? (tool.approvalReason ?? DECLARED_TOOL_APPROVAL_REASON) : undefined;
+}
+
+function approvalCallText(label: string, params: unknown): string {
+ return `${label} ${redactCommand(redactSecrets(canonicalJson(params ?? {})))}`;
+}
function withToolApprovalGate(
- tool: ToolDefinition,
+ tool: ToolDefinition & ToolApprovalDeclaration,
ref: ToolContextRef,
rec: {
recordCall: (callId: string, payload: Record<string, unknown>) => Promise<void>;
@@ -4615,21 +4630,60 @@ function withToolApprovalGate(
? `${tool.name}:${resourceAction ?? "invalid"}`
: tool.name;
const commandLabel = resourceAction ? `${tool.name} ${resourceAction}` : tool.name;
- if (gate && !gate(approvalIdentity)) {
- const gated = GATED_TOOL_APPROVALS[approvalIdentity];
- const reason = gated?.reason ?? STRICT_TOOL_APPROVAL_REASON;
- let summary: string | undefined;
- if (gated && isObj(params)) summary = gated.summary(params);
- else if (params !== undefined) summary = redactCommand(redactSecrets(JSON.stringify(params)));
- ref.pendingApprovals?.push({
- command: commandLabel,
- reason,
- kind: "approval",
- approvalKey: `tool:${approvalIdentity}`,
- ...(gated ? { grantModes: { session: false, always: false } } : {}),
- ...(summary === undefined ? {} : { summary }),
- ...(isObj(params) && typeof params.purpose === "string" ? { purpose: params.purpose } : {}),
- });
+ let declaredReason: string | undefined;
+ try {
+ declaredReason = await declaredApprovalReason(tool, params);
+ } catch (error) {
+ reportFailure("tool approval: needsApproval check", error, tool.name);
+ await rec.recordCall(callId, { tool: tool.name, blocked: "approval_check_failed", error: errMessage(error) });
+ return rec.recordResult(
+ callId,
+ { tool: tool.name, blocked: "approval_check_failed" },
+ {
+ content: [
+ {
+ type: "text" as const,
+ text: `[error] could not check whether this call needs approval: ${errMessage(error)}`,
+ },
+ ],
+ details: {},
+ },
+ true,
+ );
+ }
+ const callKey = declaredReason ? toolCallApprovalKey(approvalIdentity, params) : undefined;
+ if (callKey && canonicalJson(params ?? {}).length > APPROVAL_ARGS_MAX_CHARS) {
+ const reason = `the arguments are too long to show on an approval card (over ${APPROVAL_ARGS_MAX_CHARS} characters); split the work into smaller calls`;
+ await rec.recordCall(callId, { tool: tool.name, blocked: "approval_args_too_long" });
+ return rec.recordResult(
+ callId,
+ { tool: tool.name, blocked: "approval_args_too_long" },
+ { content: [{ type: "text" as const, text: `[blocked] ${reason}` }], details: {} },
+ true,
+ );
+ }
+ if (callKey ? !gate?.(approvalIdentity, callKey) : gate && !gate(approvalIdentity)) {
+ const reason = declaredReason ?? STRICT_TOOL_APPROVAL_REASON;
+ ref.pendingApprovals?.push(
+ callKey
+ ? {
+ command: approvalCallText(commandLabel, params),
+ reason,
+ kind: "approval",
+ approvalKey: callKey,
+ summary: commandLabel,
+ grantModes: { session: false, always: false },
+ ...(isObj(params) && typeof params.purpose === "string" ? { purpose: params.purpose } : {}),
+ }
+ : {
+ command: commandLabel,
+ reason,
+ kind: "approval",
+ approvalKey: `tool:${approvalIdentity}`,
+ ...(params === undefined ? {} : { summary: redactCommand(redactSecrets(JSON.stringify(params))) }),
+ ...(isObj(params) && typeof params.purpose === "string" ? { purpose: params.purpose } : {}),
+ },
+ );
ref.pausedOnApproval = true;
await rec.recordCall(callId, {
tool: tool.name,
diff --git a/src/harness/harness.ts b/src/harness/harness.ts
index 3bede7f67..38d7ba954 100644
--- a/src/harness/harness.ts
+++ b/src/harness/harness.ts
@@ -133,7 +133,7 @@ export interface HarnessTurnInput {
tools: ToolContext;
mcpTools?: McpToolDescriptor[];
commandCredentialHandles?: readonly string[];
- toolApprovalGate?(tool: string): boolean;
+ toolApprovalGate?(tool: string, callKey?: string): boolean;
emit(entry: NewEntry): Promise<SessionEntry>;
resumeToolCall?: ResumableToolCall;
scopeLabel: ScopeId;
diff --git a/src/mcp/mcp-client.ts b/src/mcp/mcp-client.ts
index 03fe45f67..3f0f9ad2c 100644
--- a/src/mcp/mcp-client.ts
+++ b/src/mcp/mcp-client.ts
@@ -18,6 +18,7 @@ interface McpRemoteTool {
name: string;
description: string;
inputSchema: Record<string, unknown>;
+ annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean };
}
export type McpAuth =
@@ -70,7 +71,12 @@ export function createMcpClient(opts: { url: string; auth: McpAuth }): McpClient
do {
const page = await client.listTools(cursor === undefined ? undefined : { cursor });
for (const t of page.tools)
- tools.push({ name: t.name, description: t.description ?? "", inputSchema: t.inputSchema });
+ tools.push({
+ name: t.name,
+ description: t.description ?? "",
+ inputSchema: t.inputSchema,
+ ...(t.annotations ? { annotations: t.annotations } : {}),
+ });
cursor = page.nextCursor;
} while (cursor && tools.length < MAX_TOOLS);
return tools.slice(0, MAX_TOOLS);
diff --git a/src/mcp/mcp-server-store.ts b/src/mcp/mcp-server-store.ts
index c3b6e56aa..cc4ebe089 100644
--- a/src/mcp/mcp-server-store.ts
+++ b/src/mcp/mcp-server-store.ts
@@ -9,6 +9,8 @@ import type { DurableMap } from "../persistence/durable-map.ts";
export type McpServerAuthMode = "none" | "bearer" | "client-credentials" | "oauth-user";
+export type McpApprovalPolicy = "annotations" | "all" | "none";
+
export interface McpServer {
id: string;
name: string;
@@ -23,7 +25,13 @@ export interface McpServer {
oauthAuthorizeUrl?: string;
oauthTokenUrl?: string;
oauthScopes?: string[];
- tools?: Array<{ name: string; description: string; inputSchema: Record<string, unknown> }>;
+ tools?: Array<{
+ name: string;
+ description: string;
+ inputSchema: Record<string, unknown>;
+ annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean };
+ }>;
+ approval?: McpApprovalPolicy;
readOnly: boolean;
enabled: boolean;
updatedAt: number;
diff --git a/src/mcp/mcp-tool-service.ts b/src/mcp/mcp-tool-service.ts
index 4b97e289c..7eda3c4ce 100644
--- a/src/mcp/mcp-tool-service.ts
+++ b/src/mcp/mcp-tool-service.ts
@@ -28,6 +28,15 @@ function modelInputSchema(schema: Record<string, unknown>): Record<string, unkno
return { ...schema, properties: kept };
}
+function mcpToolNeedsApproval(
+ server: Pick<McpServer, "approval">,
+ annotations: { readOnlyHint?: boolean; destructiveHint?: boolean } | undefined,
+): boolean {
+ const policy = server.approval ?? "annotations";
+ if (policy !== "annotations") return policy === "all";
+ return annotations?.destructiveHint === true && annotations.readOnlyHint !== true;
+}
+
export function mcpPublicOAuthClients(servers: McpServer[]): PublicOAuthClient[] {
return servers.flatMap((s) =>
s.enabled && s.auth === "oauth-user" && s.clientId && s.oauthAuthorizeUrl && s.oauthTokenUrl && s.credentialHost
@@ -55,6 +64,7 @@ export interface McpToolDescriptor {
description: string;
inputSchema: Record<string, unknown>;
readOnly: boolean;
+ needsApproval: boolean;
signIn?: true;
}
@@ -146,7 +156,7 @@ export function createMcpToolService(opts: {
const nextPerUser = new Map<string, McpServer>();
for (const server of servers) {
try {
- let tools: Array<{ name: string; description: string; inputSchema: Record<string, unknown> }>;
+ let tools: NonNullable<McpServer["tools"]>;
if (server.auth === "oauth-user") {
nextPerUser.set(server.id, server);
next.push({
@@ -157,6 +167,7 @@ export function createMcpToolService(opts: {
description: `Connect your own ${server.name} account and load its tools. Call this before anything else on ${server.name}.`,
inputSchema: { type: "object", properties: {} },
readOnly: true,
+ needsApproval: false,
});
tools = server.tools ?? [];
if (!tools.length) continue;
@@ -169,6 +180,7 @@ export function createMcpToolService(opts: {
description: tool.description || `${tool.name} on ${server.name}`,
inputSchema: modelInputSchema(tool.inputSchema),
readOnly: server.readOnly,
+ needsApproval: mcpToolNeedsApproval(server, tool.annotations),
});
}
record("list", server.id, `ok tools=${tools.length}`);
diff --git a/src/slack/approval-cards.ts b/src/slack/approval-cards.ts
index d7ae0cf7d..feac57454 100644
--- a/src/slack/approval-cards.ts
+++ b/src/slack/approval-cards.ts
@@ -1,4 +1,5 @@
import { clip, inlineCode } from "./util.ts";
+import { slackSectionBlocks } from "./mrkdwn.ts";
import { parseDeliveryTarget } from "./delivery.ts";
export const APPROVAL_ACTION_IDS = ["hilo_allow_once", "hilo_allow_session", "hilo_allow_always", "hilo_deny"] as const;
@@ -12,6 +13,7 @@ export interface PendingApproval {
summary?: string;
kind?: "approval" | "input";
grantModes?: { session: boolean; always: boolean };
+ originUrl?: string;
}
export interface SlackApprovalMessage {
@@ -20,6 +22,8 @@ export interface SlackApprovalMessage {
}
const APPROVAL_BLOCK_PREFIX = "hilo_approval:";
+const INLINE_COMMAND_MAX = 1_800;
+const COMMAND_SECTIONS_MAX = 6;
function button(
text: string,
@@ -66,19 +70,33 @@ export function approvalMessage(approvals: readonly PendingApproval[]): SlackApp
];
if (p.summary) lines.push(clip(p.summary, 400));
if (p.purpose) lines.push(`*Why:* ${clip(p.purpose, 400)}`);
- if (p.kind !== "input") lines.push(`*Command:* ${inlineCode(p.command)}`);
+ const longCommand = p.kind !== "input" && p.command.length > INLINE_COMMAND_MAX;
+ const sections = longCommand ? slackSectionBlocks(p.command, { code: true }) : [];
+ const shown = sections.length <= COMMAND_SECTIONS_MAX;
+ if (longCommand)
+ lines.push(
+ shown
+ ? "*Command:*"
+ : `*Command:* too long to show in Slack. Open ${p.originUrl && /^https?:\/\//.test(p.originUrl) ? `<${p.originUrl.replaceAll("|", "%7C").replaceAll(">", "%3E")}|this conversation in QM>` : "this conversation in QM"} on the web to review and approve it.`,
+ );
+ else if (p.kind !== "input") lines.push(`*Command:* ${inlineCode(p.command)}`);
lines.push(`*Flagged as:* ${clip(p.reason, 200)}`);
blocks.push({
type: "section",
text: { type: "mrkdwn", text: clip(lines.join("\n"), 2900) },
});
+ if (longCommand && shown) blocks.push(...sections);
blocks.push({
type: "actions",
block_id: `${APPROVAL_BLOCK_PREFIX}${p.requestId || "unknown"}`.slice(0, 255),
elements: [
- button("Allow once", "hilo_allow_once", p.requestId, "primary"),
- ...(p.grantModes?.session === false ? [] : [button("Allow session", "hilo_allow_session", p.requestId)]),
- ...(p.grantModes?.always === false ? [] : [button("Allow always", "hilo_allow_always", p.requestId)]),
+ ...(longCommand && !shown
+ ? []
+ : [
+ button("Allow once", "hilo_allow_once", p.requestId, "primary"),
+ ...(p.grantModes?.session === false ? [] : [button("Allow session", "hilo_allow_session", p.requestId)]),
+ ...(p.grantModes?.always === false ? [] : [button("Allow always", "hilo_allow_always", p.requestId)]),
+ ]),
button("Deny", "hilo_deny", p.requestId, "danger"),
],
});
diff --git a/src/slack/deliveries.ts b/src/slack/deliveries.ts
index 9a0cd8ff4..84207e197 100644
--- a/src/slack/deliveries.ts
+++ b/src/slack/deliveries.ts
@@ -420,7 +420,17 @@ export function createDeliveryPoller(deps: {
let card: { text: string; blocks: Array<Record<string, unknown>> } | null = null;
if (d.destination.deploymentAccess) card = deployAccessMessage(d.destination.deploymentAccess, d.text);
if (commandApproval)
- card = approvalMessage([{ ...commandApproval, reason: commandApproval.reason ?? "Approval required" }]);
+ card = approvalMessage([
+ {
+ ...commandApproval,
+ reason: commandApproval.reason ?? "Approval required",
+ ...(deps.webUiPublicUrl && commandApproval.sessionId
+ ? {
+ originUrl: `${deps.webUiPublicUrl.trim().replace(/\/+$/, "")}/s/${encodeURIComponent(commandApproval.sessionId)}`,
+ }
+ : {}),
+ },
+ ]);
let text = card?.text ?? toSlackMrkdwn(stripReactionDirectives(d.text));
if (!text.trim() && !d.attachments?.length) return undefined;
const channel = await openConversationFor(client, [d.destination.target]);
diff --git a/src/slack/mrkdwn.ts b/src/slack/mrkdwn.ts
index afba0000a..e130a14ca 100644
--- a/src/slack/mrkdwn.ts
+++ b/src/slack/mrkdwn.ts
@@ -1,4 +1,5 @@
-import { safeChunks } from "./safe-cut.ts";
+import { xmlEscape } from "../util/message-tag.ts";
+import { safeChunks, safeCutIndex } from "./safe-cut.ts";
export function decodeSlackEntities(text: string): string {
return text.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
}
@@ -243,6 +244,16 @@ function reformatTables(text: string, keep: (s: string) => string): string {
return out.join("\n");
}
-export function slackSectionBlocks(text: string): Array<Record<string, unknown>> {
- return safeChunks(text, 2_900).map((chunk) => ({ type: "section", text: { type: "mrkdwn", text: chunk } }));
+export function slackSectionBlocks(text: string, opts?: { code?: boolean }): Array<Record<string, unknown>> {
+ if (!opts?.code)
+ return safeChunks(text, 2_900).map((chunk) => ({ type: "section", text: { type: "mrkdwn", text: chunk } }));
+ const blocks: Array<Record<string, unknown>> = [];
+ let rest = text.replace(/`/g, "'");
+ while (rest) {
+ let cut = rest.length > 2_800 ? safeCutIndex(rest, 2_800) : rest.length;
+ while (xmlEscape(rest.slice(0, cut)).length > 2_990) cut = safeCutIndex(rest, Math.floor(cut * 0.8));
+ blocks.push({ type: "section", text: { type: "mrkdwn", text: `\`\`\`${xmlEscape(rest.slice(0, cut))}\`\`\`` } });
+ rest = rest.slice(cut);
+ }
+ return blocks;
}
diff --git a/test/admin-agent-capability.test.ts b/test/admin-agent-capability.test.ts
index a633b8aa8..f45c860ee 100644
--- a/test/admin-agent-capability.test.ts
+++ b/test/admin-agent-capability.test.ts
@@ -398,6 +398,21 @@ test("grant management refuses agent tokens outright — promote/revoke stays in
}
});
+test("MCP server registration refuses agent tokens — the agent cannot change which calls need approval", async () => {
+ const s = start();
+ try {
+ const res = await fetch(`${s.base}/v1/admin/mcp-servers/crm`, {
+ method: "PUT",
+ headers: { "x-agent-capability": await capFor("admin-alice"), "content-type": "application/json" },
+ body: JSON.stringify({ url: "https://tools.example.com/mcp", approval: "none", validate: false }),
+ });
+ assert.equal(res.status, 403);
+ assert.match(((await res.json()) as any).message, /portal-only/);
+ } finally {
+ await s.close();
+ }
+});
+
test("impersonation refuses agent tokens outright — acting as another user stays in the portal", async () => {
const s = start();
try {
diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.ts
index d31625161..23953c900 100644
--- a/test/agent-tools.test.ts
+++ b/test/agent-tools.test.ts
@@ -3,12 +3,7 @@ import { createGoalRecord } from "../src/harness/goal.ts";
import assert from "node:assert/strict";
import { Check } from "typebox/value";
import { fromJSONSchema, z, type ZodObject } from "zod";
-import {
- createAgentTools,
- GATED_TOOL_APPROVALS,
- pauseStampAfterToolCall,
- type ToolContextRef,
-} from "../src/harness/agent-tools.ts";
+import { createAgentTools, pauseStampAfterToolCall, type ToolContextRef } from "../src/harness/agent-tools.ts";
import { resumeStrategy } from "../src/core/turn-resume.ts";
import { reconstructMessagesFromHistory } from "../src/harness/replay.ts";
import { createMemoryRunSignalStore, waitForClientResult } from "../src/runs/run-signal-store.ts";
@@ -3518,6 +3513,7 @@ test("resource catalog exposes one home per operation and leaves MCP tools intac
description: "Search",
inputSchema: { type: "object", properties: {} },
readOnly: true,
+ needsApproval: false,
},
],
},
@@ -4409,7 +4405,7 @@ test("client screenshots reach the model as images and remain subject to output
test("installing a shared sidebar always waits for the person's approval", async () => {
const installed: string[] = [];
- let approved = false;
+ const approved = new Set<string>();
const ref: ToolContextRef = {
current: {
...fakeToolContext(),
@@ -4420,26 +4416,105 @@ test("installing a shared sidebar always waits for the person's approval", async
},
pendingApprovals: [],
scopeLabel: "personal:U1",
- toolApprovalGate: (tool) => !GATED_TOOL_APPROVALS[tool] || approved,
+ toolApprovalGate: (_tool, callKey) => !callKey || approved.has(callKey),
};
const files = createAgentTools(ref).find((t) => t.name === "files")!;
await call(files, { action: "install_canvas", id: "f1" });
assert.deepEqual(installed, []);
const card = ref.pendingApprovals?.[0];
- assert.equal(card?.summary, "file f1");
assert.deepEqual(
- [card?.approvalKey, card?.reason, card?.grantModes],
+ [card?.command, card?.summary, card?.reason, card?.grantModes],
[
- "tool:files:install_canvas",
- GATED_TOOL_APPROVALS["files:install_canvas"]!.reason,
+ 'files install_canvas {"action":"install_canvas","id":"f1"}',
+ "files install_canvas",
+ "install an always-on canvas someone shared with you; its code runs in your QM web UI",
{ session: false, always: false },
],
);
- approved = true;
+ approved.add(card!.approvalKey!);
ref.pausedOnApproval = false;
+ await call(files, { action: "install_canvas", id: "f2" });
+ assert.deepEqual(installed, [], "the approval covers only the approved arguments");
assert.match(textOut(await call(files, { action: "install_canvas", id: "f1" })), /Installed/);
assert.deepEqual(installed, ["f1"]);
ref.current = fakeToolContext();
const plain = createAgentTools(ref).find((t) => t.name === "files")!;
assert.doesNotMatch(JSON.stringify(plain.parameters), /install_canvas/);
});
+
+test("an MCP tool that needs approval is not called until its exact arguments are approved", async () => {
+ const calls: Array<Record<string, unknown>> = [];
+ const approved = new Set<string>();
+ const ref: ToolContextRef = {
+ current: {
+ ...fakeToolContext(),
+ callMcpTool: async (_name, args) => {
+ calls.push(args);
+ return "deleted";
+ },
+ },
+ pendingApprovals: [],
+ scopeLabel: "personal:U1",
+ toolApprovalGate: (_tool, callKey) => !callKey || approved.has(callKey),
+ };
+ const descriptor = {
+ serverId: "example",
+ description: "Example",
+ inputSchema: { type: "object", properties: {} },
+ readOnly: false,
+ };
+ const tools = createAgentTools(ref, {
+ mcpTools: [
+ { ...descriptor, name: "example_delete", remoteName: "delete", needsApproval: true },
+ { ...descriptor, name: "example_get", remoteName: "get", needsApproval: false },
+ ],
+ });
+ const del = tools.find((t) => t.name === "example_delete")!;
+ const get = tools.find((t) => t.name === "example_get")!;
+ assert.match(textOut(await call(get, { id: 1 })), /deleted/);
+ assert.match(textOut(await call(del, { id: 1 })), /blocked: needs human approval/);
+ assert.deepEqual(calls, [{ id: 1 }]);
+ const card = ref.pendingApprovals!.at(-1)!;
+ assert.equal(card.command, 'example_delete {"id":1}');
+ approved.add(card.approvalKey!);
+ ref.pausedOnApproval = false;
+ await call(del, { id: 2 });
+ assert.deepEqual(calls, [{ id: 1 }]);
+ await call(del, { id: 1 });
+ assert.deepEqual(calls, [{ id: 1 }, { id: 1 }]);
+ const cards = ref.pendingApprovals!.length;
+ assert.match(textOut(await call(del, { id: 3, note: "x".repeat(20_000) })), /too long to show on an approval card/);
+ assert.equal(
+ ref.pendingApprovals!.length,
+ cards,
+ "an argument set the card cannot show is never offered for approval",
+ );
+});
+
+test("a tool that needs approval fails closed without an approval gate", async () => {
+ let called = false;
+ const ref: ToolContextRef = {
+ current: {
+ ...fakeToolContext(),
+ callMcpTool: async () => {
+ called = true;
+ return "";
+ },
+ },
+ };
+ const [tool] = createAgentTools(ref, {
+ mcpTools: [
+ {
+ name: "example_delete",
+ serverId: "example",
+ remoteName: "delete",
+ description: "Delete",
+ inputSchema: { type: "object", properties: {} },
+ readOnly: false,
+ needsApproval: true,
+ },
+ ],
+ }).filter((t) => t.name === "example_delete");
+ assert.match(textOut(await call(tool!, {})), /blocked: needs human approval/);
+ assert.equal(called, false);
+});
diff --git a/test/mcp-admin.test.ts b/test/mcp-admin.test.ts
index ca05e7b71..6682800a7 100644
--- a/test/mcp-admin.test.ts
+++ b/test/mcp-admin.test.ts
@@ -87,6 +87,13 @@ test("MCP admin validates and preserves credential scope, without returning secr
assert.equal((await store.get("crm"))?.credentialScope, "shared");
assert.equal((await store.get("crm"))?.credentialHost, undefined);
assert.equal((await store.get("crm"))?.credentialAccountType, undefined);
+ assert.equal((await put({ approval: "sometimes" })).status, 400);
+ assert.equal((await put({ approval: "all" })).status, 200);
+ assert.equal((await store.get("crm"))?.approval, "all");
+ assert.equal((await put({})).status, 200);
+ assert.equal((await store.get("crm"))?.approval, "all", "an update that omits the policy keeps it");
+ assert.equal((await put({ approval: "annotations" })).status, 200);
+ assert.equal((await store.get("crm"))?.approval, undefined);
});
test("production wiring never uses operator fallback tokens for per-user MCP calls", async (t) => {
diff --git a/test/mcp-connectors.test.ts b/test/mcp-connectors.test.ts
index c92cb79fc..b71a4de49 100644
--- a/test/mcp-connectors.test.ts
+++ b/test/mcp-connectors.test.ts
@@ -154,6 +154,27 @@ test("tool service exposes namespaced tools and calls through", async (t) => {
service.close();
});
+test("destructive annotations mark MCP tools for approval unless the server overrides the policy", async (t) => {
+ const mcp = await startMcpTestServer(t, {
+ tools: [
+ { name: "read", inputSchema: { type: "object" }, annotations: { readOnlyHint: true, destructiveHint: true } },
+ { name: "drop", inputSchema: { type: "object" }, annotations: { destructiveHint: true } },
+ { name: "plain", inputSchema: { type: "object" } },
+ ],
+ });
+ const store = createMcpServerStore(createMemoryMap<McpServer>());
+ const service = createMcpToolService({ servers: store, refreshIntervalMs: 3600_000 });
+ const approvals = async (partial: Partial<McpServer>) => {
+ await store.put(server({ url: mcp.url, ...partial }));
+ await service.refresh();
+ return Object.fromEntries(service.toolDefs().map((d) => [d.remoteName, d.needsApproval]));
+ };
+ assert.deepEqual(await approvals({}), { read: false, drop: true, plain: false });
+ assert.deepEqual(await approvals({ approval: "all" }), { read: true, drop: true, plain: true });
+ assert.deepEqual(await approvals({ approval: "none" }), { read: false, drop: false, plain: false });
+ service.close();
+});
+
test("disabled server's tools disappear and calls fail", async (t) => {
const mcp = await startMcpTestServer(t);
const store = createMcpServerStore(createMemoryMap<McpServer>());
diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.ts
index 4d9b19182..863a5bed7 100644
--- a/test/orchestrator.test.ts
+++ b/test/orchestrator.test.ts
@@ -2763,6 +2763,42 @@ test("disabling a grant mode suspends existing grants until it is re-enabled", a
assert.equal(restored.status, "ok", "re-enabling the mode restores the grant without re-approval");
});
+test("a tool that declares approval runs once for the exact approved arguments", async () => {
+ const { app, sessions } = freshApp();
+ const call = '!declared {"to":"[email protected]","body":"hi"}';
+ const first = await app.turn(dm(call));
+ assert.equal(first.status, "pending_approval");
+ const pending = first.pendingApprovals![0]!;
+ assert.match(pending.approvalKey ?? "", /^tool-call:[0-9a-f]{64}$/);
+
+ const always = await app.turn(
+ dm(call, { approval: { requestId: pending.requestId, approved: true, scope: "always" } }),
+ );
+ assert.equal(always.status, "pending_approval", "a per-call approval offers no standing grant");
+
+ const approved = await app.turn(dm(call, { approval: { requestId: pending.requestId, approved: true } }));
+ assert.equal(approved.status, "ok");
+ assert.equal(approved.reply, 'sent {"to":"[email protected]","body":"hi"}');
+
+ const again = await app.turn(dm(call));
+ assert.equal(again.status, "pending_approval", "the approval was consumed by the one call");
+ const changed = await app.turn(dm('!declared {"body":"hi","to":"[email protected]"}'));
+ assert.equal(changed.status, "pending_approval", "different arguments need their own approval");
+
+ const denied = await app.turn(
+ dm(call, { approval: { requestId: again.pendingApprovals![0]!.requestId, approved: false } }),
+ );
+ assert.equal(denied.status, "refused");
+ const notes = (await sessions.getEntries(denied.sessionId!)).filter(
+ (e) => e.type === "user" && (e.payload as { hidden?: boolean }).hidden,
+ );
+ assert.ok(
+ notes.some((e) =>
+ /denied this pending operation, so it did not run: example_send/.test((e.payload as { text: string }).text),
+ ),
+ );
+});
+
test("Strict posture gates tool actions behind HiLO and honors a session grant", async () => {
const built = freshApp();
await built.config.setSecurityPosture(scopeId("org", "default-org"), "strict");
diff --git a/test/slack-approval-cards.test.ts b/test/slack-approval-cards.test.ts
index 05e480393..c17d6c580 100644
--- a/test/slack-approval-cards.test.ts
+++ b/test/slack-approval-cards.test.ts
@@ -65,7 +65,9 @@ test("approvalMessage clamps a huge purpose so the section block stays under Sla
const section = msg.blocks.find((b) => b.type === "section") as any;
const text: string = section.text.text;
assert.ok(text.length <= 3000, `section text is ${text.length} chars`);
- assert.match(text, /\*Command:\* `x/);
+ assert.match(text, /\*Command:\* too long to show in Slack/);
+ assert.ok(msg.blocks.length <= 10);
+ assert.ok(msg.blocks.every((b) => b.type !== "section" || (b.text as { text: string }).text.length <= 3000));
});
test("approvalMessage leads with the agent's purpose when present", () => {
@@ -256,3 +258,46 @@ test("a quarantine-release card offers only Allow once and Deny, with the screen
assert.match(rendered, /instruction in untrusted data/);
assert.match(rendered, /Blocked content preview/);
});
+
+test("a long command is shown in full across code blocks instead of being cut", () => {
+ const command = `example_send {"body":"${"a".repeat(6_000)}","to":"<[email protected]>"}`;
+ const msg = approvalMessage([{ requestId: "req-1", command, reason: "needs approval" }]);
+ const shown = msg.blocks
+ .filter((b) => b.type === "section")
+ .slice(1)
+ .map((b) => (b.text as { text: string }).text.replace(/```/g, "").replace(/\n/g, ""))
+ .join("");
+ assert.equal(shown, command.replace(/</g, "&lt;").replace(/>/g, "&gt;"));
+ assert.ok(msg.blocks.every((b) => b.type !== "section" || (b.text as { text: string }).text.length <= 3000));
+ const actions = msg.blocks.at(-1)!;
+ assert.deepEqual(
+ (actions.elements as Array<{ action_id: string }>).map((e) => e.action_id),
+ ["hilo_allow_once", "hilo_allow_session", "hilo_allow_always", "hilo_deny"],
+ );
+});
+
+test("markup-heavy commands that fit are split so every escaped piece stays within Slack's limit", () => {
+ const command = `example_send {"body":"${"Tom & Jerry <b>'hi'</b> ".repeat(110)}","to":"[email protected]"}`;
+ const msg = approvalMessage([{ requestId: "req-1", command, reason: "needs approval" }]);
+ const sections = msg.blocks.filter((b) => b.type === "section").slice(1);
+ assert.ok(sections.every((b) => (b.text as { text: string }).text.length <= 3000));
+ const shown = sections.map((b) => (b.text as { text: string }).text.slice(3, -3)).join("");
+ assert.equal(shown, command.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"));
+ assert.ok(JSON.stringify(msg.blocks).includes("hilo_allow_once"));
+});
+
+test("a command too long to show in Slack can only be denied there", () => {
+ const command = `example_send {"a":"${"&".repeat(15_000)}","to":"[email protected]"}`;
+ const msg = approvalMessage([{ requestId: "req-1", command, reason: "needs approval" }]);
+ assert.ok(!JSON.stringify(msg.blocks).includes("hilo_allow_once"));
+ assert.ok(JSON.stringify(msg.blocks).includes("hilo_deny"));
+ assert.match(
+ JSON.stringify(msg.blocks),
+ /too long to show in Slack\. Open this conversation in QM on the web to review and approve it/,
+ );
+ assert.ok(!JSON.stringify(msg.blocks).includes("[email protected]"));
+ const linked = approvalMessage([
+ { requestId: "req-2", command, reason: "needs approval", originUrl: "https://qm.example.com/s/abc" },
+ ]);
+ assert.match(JSON.stringify(linked.blocks), /<https:\/\/qm\.example\.com\/s\/abc\|this conversation in QM>/);
+});
diff --git a/test/slack-deliveries.test.ts b/test/slack-deliveries.test.ts
index e02383cc1..97440913e 100644
--- a/test/slack-deliveries.test.ts
+++ b/test/slack-deliveries.test.ts
@@ -325,6 +325,26 @@ test("delegated approvals recover native buttons from durable records", async ()
assert.deepEqual(second.acknowledgements, ["D1"]);
});
+test("an approval too long for Slack links its Deny-only card to the conversation on the web", async () => {
+ const approval = {
+ requestId: "A1",
+ sessionId: "S 1",
+ command: `example_send {"a":"${"&".repeat(15_000)}","to":"[email protected]"}`,
+ reason: "this tool asks for approval before each call",
+ request: { actor: { externalId: "U1" } },
+ };
+ const out = await deliver(
+ { type: "principal", target: "U1", commandApprovalId: "A1" },
+ undefined,
+ "https://qm.example.com/",
+ "Approval needed",
+ { approval },
+ );
+ const rendered = JSON.stringify(out.posts[0]!.blocks);
+ assert.match(rendered, /<https:\/\/qm\.example\.com\/s\/S%201\|this conversation in QM>/);
+ assert.doesNotMatch(rendered, /hilo_allow_once|attacker@example\.com/);
+});
+
for (const approval of [null, { requestId: "A1", command: "publish", request: { actor: { externalId: "U2" } } }]) {
test(`delegated approvals discard ${approval ? "mismatched" : "expired"} records`, async () => {
const out = await deliver(
diff --git a/test/support/mock-harness.ts b/test/support/mock-harness.ts
index e334339c6..3b72a1daa 100644
--- a/test/support/mock-harness.ts
+++ b/test/support/mock-harness.ts
@@ -9,6 +9,7 @@ import {
} from "../../src/harness/harness.ts";
import { NonRetryableTurnError, ProviderTurnError, TitleRejected } from "../../src/core/turn-error.ts";
import { NeedsApproval } from "../../src/tools/primitives.ts";
+import { toolCallApprovalKey } from "../../src/core/approval-id.ts";
import { deterministicCompactSummary, estimateHistoryTokens } from "../../src/harness/context-compaction.ts";
import { countTokens } from "../../src/util/tokens.ts";
import { recordStoppedTurn } from "../../src/harness/harness-shared.ts";
@@ -181,6 +182,8 @@ export function createMockHarness(): Harness {
kind?: "approval";
matched?: string;
approvalKey?: string;
+ grantModes?: { session: boolean; always: boolean };
+ summary?: string;
}> = [];
let pausedOnApproval = false;
const gateTool = (tool: string): boolean => {
@@ -560,6 +563,23 @@ export function createMockHarness(): Harness {
}
usedTool = true;
reply = `ran ${ran}`;
+ } else if (command0.startsWith("!declared ")) {
+ const args = JSON.parse(command0.slice("!declared ".length)) as Record<string, unknown>;
+ const callKey = toolCallApprovalKey("example_send", args);
+ usedTool = true;
+ if (turn.toolApprovalGate?.("example_send", callKey)) reply = `sent ${JSON.stringify(args)}`;
+ else {
+ collected.push({
+ command: `example_send ${JSON.stringify(args)}`,
+ reason: "this tool asks for approval before each call",
+ kind: "approval",
+ approvalKey: callKey,
+ summary: "example_send",
+ grantModes: { session: false, always: false },
+ });
+ pausedOnApproval = true;
+ reply = "";
+ }
} else if (command0.startsWith("!read ") && gateTool("read")) {
usedTool = true;
reply = "";