:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): add typed-confirm two-tool paradigm for destructive tools (#62622)
Yasend9daea94f382
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex fa83271eb493..c76eb1a58ffb 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3883,6 +3883,9 @@ importers:ioredis:specifier: ^4.28.5version: 4.28.5+ jose:+ specifier: ^6.2.3+ version: 6.2.3lucide-react:specifier: ^0.577.0version: 0.577.0([email protected])@@ -16964,6 +16967,9 @@ packages:resolution: {integrity: sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ==}+ resolution: {integrity: sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==}+resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}engines: {node: '>=10'}@@ -28198,7 +28204,7 @@ snapshots:express: 5.2.1express-rate-limit: 8.5.2([email protected])hono: 4.12.18- jose: 6.1.3+ jose: 6.2.3json-schema-typed: 8.0.2pkce-challenge: 5.0.0raw-body: 3.0.1@@ -40202,6 +40208,8 @@ snapshots:+ [email protected]: {}+diff --git a/services/mcp/.env.example b/services/mcp/.env.examplenew file mode 100644index 000000000000..e45a55b555a3--- /dev/null+++ b/services/mcp/.env.example@@ -0,0 +1,18 @@+# Local-dev environment for the MCP Hono server.+# Copy to .env and fill in the real values. .env is gitignored.+#+# In production (k8s), these go in via the charts repo's Kubernetes+# secret manifest for the MCP deployment, not via this file.++# HMAC-SHA256 signing secret for the typed-confirm `confirmed_action`+# paradigm — bound to user identity, tool purpose, TTL, and a single-use+# nonce inside every `<tool>-prepare` token.+#+# - Minimum 32 bytes. Anything shorter is rejected at boot.+# - Missing or short → the paradigm is disabled (no boot crash);+# non-`confirmed_action` tools keep working, `-prepare`/`-execute`+# calls fail at request time, the `mcp_confirmed_action_runtime_installed`+# gauge reports 0.+# - For local dev only, any 32-byte string is fine. For production,+# generate with: `openssl rand -hex 32`.+MCP_SIGNED_STATE_KEY=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaadiff --git a/services/mcp/package.json b/services/mcp/package.jsonindex 90d5d46f4b4f..e0194f8342ad 100644--- a/services/mcp/package.json+++ b/services/mcp/package.json@@ -53,6 +53,7 @@"fflate": "^0.8.2","hono": "^4.12.18","ioredis": "^4.28.5",+ "jose": "^6.2.3","lucide-react": "^0.577.0","posthog-js-lite": "4.2.2","posthog-node": "^5.25.0",diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.tsindex 567882a9a2f7..67ccd0127a8d 100644--- a/services/mcp/scripts/generate-tools.ts+++ b/services/mcp/scripts/generate-tools.ts@@ -1023,6 +1023,33 @@ function generateToolCode(composition.bodyFieldNames.length > 0 || hasQuery || composition.pathParamNames.length > 0 || enrichUsesParamsconst unusedParamsComment = paramsUsed ? '' : '// eslint-disable-next-line no-unused-vars\n'+ // When `confirmed_action` is declared, emit TWO factories instead of+ // one — `<name>-prepare` and `<name>-execute`. The prepare tool signs+ // the validated args into a hash; the execute tool verifies the hash,+ // requires the literal "confirm" arg, and then runs the original+ // handler body with the verified args. See `src/tools/confirmed-action-runtime.ts`.+ if (config.confirmed_action) {+ const wrapped = buildConfirmedActionFactories({+ toolName,+ config,+ schemaName,+ schemaDecl,+ originalHandlerBody: handlerBody,+ resultType,+ })+ return {+ code: wrapped.code,+ orvalImports: composition.orvalImports,+ toolInputsImports: composition.toolInputsImports,+ castHelperImports: composition.castHelperImports,+ schemaRefBlocks: composition.schemaRefBlocks,+ responseType,+ needsWithPostHogUrl,+ hasEnrichment,+ responseFilterImport: responseFilter.helperImport,+ }+ }+const toolBody = `{name: '${toolName}',schema: ${schemaName},@@ -1051,6 +1078,103 @@ const ${factoryName} = (): ToolBase<typeof ${schemaName}, ${resultType}> => ${fa}}+/**+ * Emit prepare + execute factories for a tool that declares `confirmed_action`.+ * Returns the combined `code` block — the two factories plus the extended+ * schema used by `-execute`. The base schema is emitted exactly as the+ * non-confirmed path does it, so the prepare variant reuses it directly.+ */+function buildConfirmedActionFactories(args: {+ toolName: string+ config: ToolConfig+ schemaName: string+ schemaDecl: string+ originalHandlerBody: string+ resultType: string+}): { code: string } {+ const { toolName, config, schemaName, schemaDecl, originalHandlerBody, resultType } = args+ const baseFactory = toCamelCase(toolName)+ const prepareName = `${toolName}-prepare`+ const executeName = `${toolName}-execute`+ const prepareFactory = `${baseFactory}Prepare`+ const executeFactory = `${baseFactory}Execute`+ const executeSchemaName = `${schemaName}Execute`+ const actionLabel = config.confirmed_action?.action_label ?? config.title ?? toolName+ const messageTemplate = config.confirmed_action?.message ?? `Confirm ${actionLabel}?`++ // Execute schema = base schema extended with the two framework fields.+ // `confirmation` is z.string() not z.literal('confirm') on purpose: the+ // runtime checks the value and refuses with a structured tool-call+ // result + metric counter. A literal would raise a generic zod parse+ // error before our guard runs, losing the metric and the+ // user-targetted refusal text.+ const executeSchemaDecl = `const ${executeSchemaName} = ${schemaName}.extend({+ confirmation_hash: z.string().describe('The confirmation_hash returned by the matching -prepare tool. Pass it back verbatim.'),+ confirmation: z.string().describe('The literal string "confirm", typed by the user in chat. Required to proceed.'),+})`++ // Prepare handler: validate args via the base schema (already happens+ // before our handler runs) and call into the runtime. Args are signed+ // verbatim — bound to user identity + purpose.+ const prepareHandler = ` const __runtime = getConfirmedActionRuntime()+ return await prepareConfirmedAction(context, {+ args: params,+ purpose: ${JSON.stringify(toolName)},+ actionLabel: ${JSON.stringify(actionLabel)},+ messageTemplate: ${JSON.stringify(messageTemplate)},+ codec: __runtime.codec,+ })+`++ // Execute handler: guard, then re-run the original handler body with+ // the verified args. `params` is reassigned to the verified payload so+ // the rest of the original code path (which reads from `params.*`)+ // works unchanged. The cast pins the type so TS knows the original+ // shape survives.+ const executeHandler = ` const __runtime = getConfirmedActionRuntime()+ const __guard = await executeConfirmedAction(context, {+ incomingArgs: params,+ purpose: ${JSON.stringify(toolName)},+ codec: __runtime.codec,+ ledger: __runtime.ledger,+ })+ if (!__guard.ok) {+ return __guard.result as never+ }+ // Replace, do NOT merge: only signed fields are authorized. Any+ // base-schema field the model slipped into the execute call+ // (e.g. an unsigned 'name' alongside the signed 'enforce_2fa')+ // would otherwise survive into the downstream API body.+ // eslint-disable-next-line no-param-reassign+ params = { ...__guard.verifiedArgs } as typeof params+${originalHandlerBody}`++ const prepareBody = `{+ name: '${prepareName}',+ schema: ${schemaName},+ handler: async (context: Context, params: z.infer<typeof ${schemaName}>) => {+${prepareHandler} },+}`++ const executeBody = `{+ name: '${executeName}',+ schema: ${executeSchemaName},+ handler: async (context: Context, params: z.infer<typeof ${executeSchemaName}>) => {+${executeHandler} },+}`++ const code = `+${schemaDecl}++${executeSchemaDecl}++const ${prepareFactory} = (): ToolBase<typeof ${schemaName}, PrepareConfirmedActionResult> => (${prepareBody})++const ${executeFactory} = (): ToolBase<typeof ${executeSchemaName}, ${resultType}> => (${executeBody})+`+ return { code }+}+function generateCustomSchemaToolCode(toolName: string,config: ToolConfig,@@ -1356,7 +1480,19 @@ function generateCategoryFile(.join('\n')}- const restMapEntries = enabledTools.map(([name]) => ` '${name}': ${toCamelCase(name)},`).join('\n')+ const restMapEntries = enabledTools+ .flatMap(([name, config]) => {+ if (config.confirmed_action) {+ return [+ ` '${name}-prepare': ${toCamelCase(name)}Prepare,`,+ ` '${name}-execute': ${toCamelCase(name)}Execute,`,+ ]+ }+ return [` '${name}': ${toCamelCase(name)},`]+ })+ .join('\n')++ const hasConfirmedAction = enabledTools.some(([, c]) => c.confirmed_action)const mapEntries = [restMapEntries, wrapperMapEntries].filter(Boolean).join('\n')const orvalImportLine =@@ -1403,13 +1539,17 @@ function generateCategoryFile(const wrapperImportLine =enabledWrappers.length > 0 ? `import { createQueryWrapper } from '@/tools/query-wrapper-factory'\n` : ''+ const confirmedActionImportLine = hasConfirmedAction+ ? `import { getConfirmedActionRuntime } from '@/tools/confirmed-action-registry'\nimport { executeConfirmedAction, prepareConfirmedAction, type PrepareConfirmedActionResult } from '@/tools/confirmed-action-runtime'\n`+ : ''+const schemaRefCode = allSchemaRefBlocks.length > 0 ? '\n' + allSchemaRefBlocks.join('\n\n') + '\n' : ''const code = `// AUTO-GENERATED from ${fileName} + OpenAPI — do not editimport { z } from 'zod'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'-${toolUtilsImportLine ? `${toolUtilsImportLine}` : ''}${schemasImportLine}${withUiAppImportLine}${toolInputsImportLine}${castHelpersImportLine}${wrapperImportLine}${orvalImportLine}${schemaRefCode}${toolCodes.join('')}${wrapperSchemasCode}+${toolUtilsImportLine ? `${toolUtilsImportLine}` : ''}${schemasImportLine}${withUiAppImportLine}${toolInputsImportLine}${castHelpersImportLine}${wrapperImportLine}${confirmedActionImportLine}${orvalImportLine}${schemaRefCode}${toolCodes.join('')}${wrapperSchemasCode}export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {${mapEntries}}@@ -1455,26 +1595,93 @@ function generateDefinitionsJson(for (const { config: category, enabledTools, enabledWrappers, yamlDir } of categories) {for (const [name, toolConfig, resolved] of enabledTools) {const opDescription = resolved.operation.description?.trim() || resolved.operation.summary?.trim() || ''- definitions[name] = {- description: resolveDescription(toolConfig, yamlDir, opDescription),- category: category.category,- feature: category.feature,- summary: toolConfig.title || opDescription.split('.')[0] || name,- title: toolConfig.title || resolved.operation.summary || name,- required_scopes: toolConfig.scopes,- annotations: {- destructiveHint: toolConfig.annotations.destructive,- idempotentHint: toolConfig.annotations.idempotent,- openWorldHint: true,- readOnlyHint: toolConfig.annotations.readOnly,- },- ...(toolConfig.requires_ai_consent ? { requires_ai_consent: true } : {}),- ...(toolConfig.feature_flag ? { feature_flag: toolConfig.feature_flag } : {}),- ...(toolConfig.feature_flag_behavior- ? { feature_flag_behavior: toolConfig.feature_flag_behavior }- : {}),- ...(toolConfig.feature_flag_variant ? { feature_flag_variant: toolConfig.feature_flag_variant } : {}),- ...(toolConfig.system_prompt_hint ? { system_prompt_hint: toolConfig.system_prompt_hint } : {}),+ const baseDescription = resolveDescription(toolConfig, yamlDir, opDescription)+ const baseTitle = toolConfig.title || resolved.operation.summary || name+ const baseSummary = toolConfig.title || opDescription.split('.')[0] || name++ if (toolConfig.confirmed_action) {+ // Two-tool typed-confirm paradigm: emit `<name>-prepare` and+ // `<name>-execute` entries. Descriptions explicitly guide the+ // model through the prepare → ask user → execute sequence.+ const actionLabel = toolConfig.confirmed_action.action_label ?? baseTitle+ definitions[`${name}-prepare`] = {+ description:+ `Step 1 of 2 for ${actionLabel}. ` ++ `Validates the arguments and returns a signed confirmation_hash plus a message to surface to the user. ` ++ `The user must reply with the literal word "confirm" before you call the matching -execute tool with the hash. ` ++ `Original action: ${baseDescription}`,+ category: category.category,+ feature: category.feature,+ summary: `${baseSummary} (prepare)`,+ title: `${baseTitle} (prepare)`,+ required_scopes: toolConfig.scopes,+ annotations: {+ destructiveHint: false,+ idempotentHint: true,+ openWorldHint: true,+ readOnlyHint: true,+ },+ ...(toolConfig.requires_ai_consent ? { requires_ai_consent: true } : {}),+ ...(toolConfig.feature_flag ? { feature_flag: toolConfig.feature_flag } : {}),+ ...(toolConfig.feature_flag_behavior+ ? { feature_flag_behavior: toolConfig.feature_flag_behavior }+ : {}),+ ...(toolConfig.feature_flag_variant+ ? { feature_flag_variant: toolConfig.feature_flag_variant }+ : {}),+ ...(toolConfig.system_prompt_hint ? { system_prompt_hint: toolConfig.system_prompt_hint } : {}),+ }+ definitions[`${name}-execute`] = {+ description:+ `Step 2 of 2 for ${actionLabel}. ` ++ `Verifies the confirmation_hash from -prepare and the literal "confirm" string typed by the user, then performs the action. ` ++ `ONLY call this after the user has explicitly typed "confirm" in chat. ` ++ `Original action: ${baseDescription}`,+ category: category.category,+ feature: category.feature,+ summary: `${baseSummary} (execute)`,+ title: `${baseTitle} (execute)`,+ required_scopes: toolConfig.scopes,+ annotations: {+ destructiveHint: toolConfig.annotations.destructive,+ idempotentHint: toolConfig.annotations.idempotent,+ openWorldHint: true,+ readOnlyHint: toolConfig.annotations.readOnly,+ },+ ...(toolConfig.requires_ai_consent ? { requires_ai_consent: true } : {}),+ ...(toolConfig.feature_flag ? { feature_flag: toolConfig.feature_flag } : {}),+ ...(toolConfig.feature_flag_behavior+ ? { feature_flag_behavior: toolConfig.feature_flag_behavior }+ : {}),+ ...(toolConfig.feature_flag_variant+ ? { feature_flag_variant: toolConfig.feature_flag_variant }+ : {}),+ ...(toolConfig.system_prompt_hint ? { system_prompt_hint: toolConfig.system_prompt_hint } : {}),+ }+ } else {+ definitions[name] = {+ description: baseDescription,+ category: category.category,+ feature: category.feature,+ summary: baseSummary,+ title: baseTitle,+ required_scopes: toolConfig.scopes,+ annotations: {+ destructiveHint: toolConfig.annotations.destructive,+ idempotentHint: toolConfig.annotations.idempotent,+ openWorldHint: true,+ readOnlyHint: toolConfig.annotations.readOnly,+ },+ ...(toolConfig.requires_ai_consent ? { requires_ai_consent: true } : {}),+ ...(toolConfig.feature_flag ? { feature_flag: toolConfig.feature_flag } : {}),+ ...(toolConfig.feature_flag_behavior+ ? { feature_flag_behavior: toolConfig.feature_flag_behavior }+ : {}),+ ...(toolConfig.feature_flag_variant+ ? { feature_flag_variant: toolConfig.feature_flag_variant }+ : {}),+ ...(toolConfig.system_prompt_hint ? { system_prompt_hint: toolConfig.system_prompt_hint } : {}),+ }}}// Include query wrappers defined in the same category filediff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.tsindex cb515e83a524..4bfab5f24f5f 100644--- a/services/mcp/scripts/yaml-config-schema.ts+++ b/services/mcp/scripts/yaml-config-schema.ts@@ -166,6 +166,43 @@ export const ToolConfigSchema = zmessage: 'response.include and response.exclude are mutually exclusive',}).optional(),+ /**+ * Opt the tool into the typed-confirm two-tool paradigm. Codegen+ * emits TWO tools per YAML entry that declares this block:+ *+ * - `<name>-prepare` — signs the validated args + user identity into+ * a hash and returns a result instructing the model to surface the+ * confirmation prompt to the user.+ * - `<name>-execute` — takes the hash plus the literal string the+ * user typed, validates both (single-use, TTL-bounded), then runs+ * the underlying action with the original args.+ *+ * Use for destructive or security-sensitive actions an LLM should+ * never perform unattended (org-wide settings, key revocation,+ * bulk deletes). The security guarantee is weaker than client-+ * rendered elicitation because the LLM controls the `confirmation`+ * argument — but strictly stronger than a single destructive tool.+ */+ confirmed_action: z+ .object({+ /**+ * Prompt text shown to the user. Supports `{paramName}`+ * placeholders interpolated from the validated tool args+ * at runtime.+ *+ * Example: `"About to enable enforce 2FA on organization {orgId}. Reply 'confirm' to proceed."`+ */+ message: z.string(),+ /**+ * Short human-readable label for the action ("enable 2FA",+ * "delete project"). Surfaced in refusal messages when the+ * confirmation fails so the user sees what was refused.+ * Defaults to the tool's title if omitted.+ */+ action_label: z.string().optional(),+ })+ .strict()+ .optional(),}).strict().refine(@@ -184,6 +221,16 @@ export const ToolConfigSchema = zmessage: '`feature_flag_variant` requires `feature_flag` to be set',path: ['feature_flag_variant'],})+ // confirmed_action emits two factories (`-prepare`, `-execute`) via a+ // codegen path that doesn't currently wrap either with `withUiApp`.+ // Reject the combination at YAML time rather than silently drop the+ // UI app at codegen — if a real consumer wants both, wire `withUiApp`+ // around the execute factory explicitly first.+ .refine((data) => !(data.confirmed_action && data.ui_app), {+ message:+ '`confirmed_action` cannot be combined with `ui_app` yet — the codegen does not wrap the generated -execute factory with withUiApp. Drop one or extend buildConfirmedActionFactories to opt in.',+ path: ['confirmed_action'],+ })export type ToolConfig = z.infer<typeof ToolConfigSchema>diff --git a/services/mcp/src/hono/app.ts b/services/mcp/src/hono/app.tsindex b7b84bba6bc9..8262572f307b 100644--- a/services/mcp/src/hono/app.ts+++ b/services/mcp/src/hono/app.ts@@ -1,5 +1,9 @@import { Hono } from 'hono'+import { loadSigningKeyFromEnv, NonceLedger, SignedStateCodec } from '@/lib/signed-state'+import { setConfirmedActionRuntime } from '@/tools/confirmed-action-registry'++import { confirmedActionRuntimeInstalled } from './metrics'import { httpMetrics, securityHeaders } from './middleware'import { registerPublicRoutes } from './public-routes'import { StreamableMcpHandler } from './streamable-handler'@@ -24,6 +28,32 @@ export function createApp(redis: RedisWithPing): App {const app = new Hono()const lifecycle: Lifecycle = { shuttingDown: false }+ // Install/refresh the process-level typed-confirm runtime singleton.+ // Generated -prepare/-execute handlers call getConfirmedActionRuntime()+ // at request time and throw if it's missing, so do this before any+ // tool dispatch. createApp may be invoked multiple times (e.g. tests+ // creating fresh app instances) — each call overwrites the singleton;+ // that's intentional, the latest installation wins.+ //+ // No MCP_SIGNED_STATE_KEY → skip install. Tools without confirmed_action+ // keep working; -prepare/-execute calls throw at request time with a+ // message pointing at the missing env var. Log loudly so ops sees the+ // misconfig before a real confirmed_action tool lands.+ try {+ setConfirmedActionRuntime({+ codec: new SignedStateCodec(loadSigningKeyFromEnv()),+ ledger: new NonceLedger(redis),+ })+ confirmedActionRuntimeInstalled.set(1)+ } catch (err) {+ setConfirmedActionRuntime(undefined)+ confirmedActionRuntimeInstalled.set(0)+ console.error(+ `[mcp] CRITICAL: confirmed-action paradigm disabled — ${(err as Error).message}. ` ++ `Any -prepare/-execute tool call will fail until this is fixed.`+ )+ }+app.use('*', securityHeaders)app.use('*', httpMetrics)diff --git a/services/mcp/src/hono/metrics.ts b/services/mcp/src/hono/metrics.tsindex 06bd615043aa..c06955983a11 100644--- a/services/mcp/src/hono/metrics.ts+++ b/services/mcp/src/hono/metrics.ts@@ -93,6 +93,42 @@ export const contextMillRevalidationsTotal = new Counter({labelNames: ['source', 'status', 'result'] as const,})+// Typed-confirm two-tool paradigm (`confirmed_action`):+//+// - `prepares_total`/`executes_total` count outcomes of each phase. Watch+// the prepare→execute conversion ratio per tool to detect tools the LLM+// prepares but never executes (user declines or model loses track) and+// tools the LLM executes repeatedly (replay attempts).+// - `refusals_total` breaks down execute refusals by reason so we can tune+// TTL, signing-key rotation, and tool descriptions against real failure+// modes instead of guessing.+export const confirmedActionPreparesTotal = new Counter({+ name: 'mcp_confirmed_action_prepares_total',+ help: 'Outcomes of -prepare tool calls under the typed-confirm paradigm.',+ labelNames: ['tool', 'status'] as const,+})++export const confirmedActionExecutesTotal = new Counter({+ name: 'mcp_confirmed_action_executes_total',+ help: 'Outcomes of -execute tool calls under the typed-confirm paradigm.',+ labelNames: ['tool', 'status'] as const,+})++export const confirmedActionRefusalsTotal = new Counter({+ name: 'mcp_confirmed_action_refusals_total',+ help: 'Reasons -execute calls were refused (wrong word, bad signature, expired, replay, mismatch).',+ labelNames: ['tool', 'reason'] as const,+})++// 1 if the codec + nonce ledger were installed at boot, 0 otherwise. A+// single boot-time console.error is easy to lose; this lets ops alert+// directly on `mcp_confirmed_action_runtime_installed == 0` regardless+// of whether anyone has tried a -prepare/-execute call yet.+export const confirmedActionRuntimeInstalled = new Gauge({+ name: 'mcp_confirmed_action_runtime_installed',+ help: 'Whether the typed-confirm runtime was installed successfully at boot (1 = yes, 0 = misconfigured / MCP_SIGNED_STATE_KEY missing).',+})+export const contextMillRevalidationDurationSeconds = new Histogram({name: 'mcp_context_mill_revalidation_duration_seconds',help: 'Context-mill resource revalidation duration.',diff --git a/services/mcp/src/lib/signed-state/codec.ts b/services/mcp/src/lib/signed-state/codec.tsnew file mode 100644index 000000000000..87dbd83da4dc--- /dev/null+++ b/services/mcp/src/lib/signed-state/codec.ts@@ -0,0 +1,187 @@+/**+ * Signed-state token codec — a thin wrapper around `jose` that stamps an+ * HMAC-SHA256 JWT-compact-format token (`header.payload.signature`)+ * binding a `(user, purpose, payload)` triple plus expiry + nonce. Used+ * by the typed-confirm two-tool paradigm to carry confirmation state+ * through the LLM between a `prepare-X` and `execute-X` call.+ *+ * Claims:+ * - `sub` — user identity (mapped to JWT `sub`); binds the token to the authenticated principal+ * - `purpose` — what the token is for, e.g. tool name (mapped to JWT `aud`); guards cross-purpose replay+ * - `nonce` — 128 random bits (mapped to JWT `jti`); the key for the single-use ledger+ * - `iat/exp` — unix seconds; expiry caps the replay window+ * - `payload` — caller-supplied opaque data, kept as a custom claim+ *+ * The token header is `{alg: 'HS256', typ: 'MCP-SIGNED-STATE'}` — `jose`+ * validates both at decode time so a token signed for a different purpose+ * or a different system (`typ`) can't be coerced into ours.+ *+ * One key: `MCP_SIGNED_STATE_KEY`. No encryption — confidentiality of+ * `payload` is the caller's responsibility.+ */++import { jwtVerify, SignJWT } from 'jose'+import { JOSEError, JWSSignatureVerificationFailed, JWTClaimValidationFailed, JWTExpired } from 'jose/errors'+import { randomBytes } from 'node:crypto'++import { DEFAULT_STATE_TTL_SECONDS, SIGNING_KEY_ENV_VAR, SIGNING_KEY_MIN_BYTES } from './constants'+import {+ SignedStateError,+ SignedStateExpired,+ SignedStateMalformed,+ SignedStatePurposeMismatch,+ SignedStateSignatureInvalid,+ SignedStateUserMismatch,+} from './errors'++const JWT_TYP = 'MCP-SIGNED-STATE'++export interface SignedStateClaims {+ sub: string+ purpose: string+ iat: number+ exp: number+ nonce: string+ payload: unknown+}++export interface SignedStateCodecOptions {+ /** TTL applied at encode time; default `DEFAULT_STATE_TTL_SECONDS`. */+ ttlSeconds?: number+ /** Override `Date.now()` for tests. */+ now?: () => number+ /** Override the entropy source for tests. */+ randomNonce?: () => string+}++export class SignedStateCodec {+ private readonly key: Uint8Array+ private readonly ttlSeconds: number+ private readonly now: () => number+ private readonly randomNonce: () => string++ constructor(key: Buffer | Uint8Array, options: SignedStateCodecOptions = {}) {+ this.key = key instanceof Uint8Array ? key : new Uint8Array(key)+ this.ttlSeconds = options.ttlSeconds ?? DEFAULT_STATE_TTL_SECONDS+ this.now = options.now ?? (() => Date.now())+ this.randomNonce = options.randomNonce ?? (() => randomBytes(16).toString('hex'))+ }++ /** Encode a fresh signed-state token bound to `(sub, purpose, payload)`. */+ async encode(input: {+ sub: string+ purpose: string+ payload: unknown+ }): Promise<{ token: string; claims: SignedStateClaims }> {+ const iat = Math.floor(this.now() / 1000)+ const exp = iat + this.ttlSeconds+ const nonce = this.randomNonce()+ const token = await new SignJWT({ payload: input.payload })+ .setProtectedHeader({ alg: 'HS256', typ: JWT_TYP })+ .setSubject(input.sub)+ .setAudience(input.purpose)+ .setIssuedAt(iat)+ .setExpirationTime(exp)+ .setJti(nonce)+ .sign(this.key)+ return {+ token,+ claims: { sub: input.sub, purpose: input.purpose, iat, exp, nonce, payload: input.payload },+ }+ }++ /**+ * Decode + verify an inbound token against the currently authenticated+ * (user, purpose). Throws `SignedStateError` subclasses for any+ * failure; the caller maps these to the appropriate response shape.+ */+ async decode(token: string, expectedSub: string, expectedPurpose: string): Promise<SignedStateClaims> {+ try {+ const { payload } = await jwtVerify(token, this.key, {+ algorithms: ['HS256'],+ typ: JWT_TYP,+ subject: expectedSub,+ audience: expectedPurpose,+ clockTolerance: 0,+ currentDate: new Date(this.now()),+ })+ // jose has already validated sub/aud/exp/typ; the cast is safe.+ return {+ sub: payload.sub as string,+ purpose: payload.aud as string,+ iat: payload.iat as number,+ exp: payload.exp as number,+ nonce: payload.jti as string,+ payload: (payload as { payload: unknown }).payload,+ }+ } catch (err) {+ throw mapJoseError(err)+ }+ }++ /**+ * Seconds until `claims.exp` according to the codec's clock —+ * guaranteed to be at least 1. Used by callers (e.g. the typed-confirm+ * nonce ledger) that need to size a TTL off the same time source the+ * codec used to stamp the token; reading the wall clock here would+ * skew under test injections or clock drift between the signer and+ * the consumer.+ */+ secondsUntilExpiry(claims: SignedStateClaims): number {+ const nowSeconds = Math.floor(this.now() / 1000)+ return Math.max(1, claims.exp - nowSeconds)+ }+}++/**+ * Load the signing key from the environment. Throws unconditionally if+ * the key is missing or under `SIGNING_KEY_MIN_BYTES`. No NODE_ENV gate+ * and no dev fallback — a deterministic placeholder would be publicly+ * known via this source file, so a leaked key would let any+ * authenticated user (or prompt-injected model) forge tokens for any+ * other user. Callers that want to boot without the paradigm available+ * should catch and continue (see `createApp` for the canonical pattern).+ */+export function loadSigningKeyFromEnv(env: NodeJS.ProcessEnv = process.env): Buffer {+ const raw = env[SIGNING_KEY_ENV_VAR] ?? ''+ const key = Buffer.from(raw, 'utf8')+ if (key.length < SIGNING_KEY_MIN_BYTES) {+ throw new Error(`${SIGNING_KEY_ENV_VAR} must be set to at least ${SIGNING_KEY_MIN_BYTES} bytes`)+ }+ return key+}++/**+ * Map jose's exception hierarchy onto our typed `SignedStateError`+ * subclasses. The runtime catches by class to drive metric labels and+ * user-facing refusal messages, so we want a stable, semantic mapping+ * rather than leaking jose's internal types upward.+ *+ * The `JWTClaimValidationFailed.claim` field tells us which standard+ * claim mismatched; we map `sub` and `aud` to our user/purpose flavors.+ * Anything else (malformed token, bad header) collapses to `Malformed`.+ */+function mapJoseError(err: unknown): SignedStateError {+ const message = err instanceof Error ? err.message : String(err)+ if (err instanceof JWTExpired) {+ return new SignedStateExpired(message)+ }+ if (err instanceof JWTClaimValidationFailed) {+ if (err.claim === 'sub') {+ return new SignedStateUserMismatch(message)+ }+ if (err.claim === 'aud') {+ return new SignedStatePurposeMismatch(message)+ }+ return new SignedStateMalformed(message)+ }+ if (err instanceof JWSSignatureVerificationFailed) {+ return new SignedStateSignatureInvalid(message)+ }+ if (err instanceof JOSEError) {+ return new SignedStateMalformed(message)+ }+ // Non-jose error: shouldn't happen in normal flow; surface as malformed+ // rather than swallowing or re-throwing an unknown type upward.+ return new SignedStateMalformed(message)+}diff --git a/services/mcp/src/lib/signed-state/constants.ts b/services/mcp/src/lib/signed-state/constants.tsnew file mode 100644index 000000000000..80babfa216ce--- /dev/null+++ b/services/mcp/src/lib/signed-state/constants.ts@@ -0,0 +1,24 @@+/**+ * Hard-coded constants for the signed-state codec.+ *+ * None of these are env-configurable on purpose. They define the security+ * envelope that callers (today: the typed-confirm two-tool paradigm) rely+ * on. Tuning them is a deliberate code change, not a deployment knob.+ */++/**+ * Default TTL on a signed state token, in seconds. 5 minutes is long enough+ * for a model to surface the prepare result to the user and for the user to+ * reply with "confirm", short enough to bound the window a leaked or guessed+ * token is usable.+ */+export const DEFAULT_STATE_TTL_SECONDS = 300++/** Minimum acceptable length of the signing key, in bytes (HMAC-SHA256 output size). */+export const SIGNING_KEY_MIN_BYTES = 32++/** Redis key prefix for the single-use nonce ledger. */+export const NONCE_KEY_PREFIX = 'mcp:signed-state:nonce'++/** Env var name. */+export const SIGNING_KEY_ENV_VAR = 'MCP_SIGNED_STATE_KEY'diff --git a/services/mcp/src/lib/signed-state/errors.ts b/services/mcp/src/lib/signed-state/errors.tsnew file mode 100644index 000000000000..ea1185cd3274--- /dev/null+++ b/services/mcp/src/lib/signed-state/errors.ts@@ -0,0 +1,32 @@+/**+ * Typed errors for signed-state decode failures. Callers (e.g. the+ * confirmed-action runtime) catch by class and map to user-facing messages.+ */++export abstract class SignedStateError extends Error {+ /** Short label suitable for metric/log fields. */+ abstract readonly kind: string+ constructor(message: string) {+ super(message)+ this.name = this.constructor.name+ }+}++export class SignedStateMalformed extends SignedStateError {+ readonly kind = 'malformed'+}+export class SignedStateSignatureInvalid extends SignedStateError {+ readonly kind = 'bad_signature'+}+export class SignedStateExpired extends SignedStateError {+ readonly kind = 'expired'+}+export class SignedStateUserMismatch extends SignedStateError {+ readonly kind = 'user_mismatch'+}+export class SignedStatePurposeMismatch extends SignedStateError {+ readonly kind = 'purpose_mismatch'+}+export class SignedStateAlreadyConsumed extends SignedStateError {+ readonly kind = 'already_consumed'+}diff --git a/services/mcp/src/lib/signed-state/index.ts b/services/mcp/src/lib/signed-state/index.tsnew file mode 100644index 000000000000..793b6d45ab91--- /dev/null+++ b/services/mcp/src/lib/signed-state/index.ts@@ -0,0 +1,22 @@+/**+ * Public surface of the signed-state module.+ *+ * Import from `@/lib/signed-state` rather than reaching into individual+ * files — these exports are the supported API; everything else is an+ * implementation detail.+ */++export { DEFAULT_STATE_TTL_SECONDS, SIGNING_KEY_ENV_VAR } from './constants'+export {+ SignedStateAlreadyConsumed,+ SignedStateError,+ SignedStateExpired,+ SignedStateMalformed,+ SignedStatePurposeMismatch,+ SignedStateSignatureInvalid,+ SignedStateUserMismatch,+} from './errors'+export { loadSigningKeyFromEnv, SignedStateCodec } from './codec'+export type { SignedStateClaims, SignedStateCodecOptions } from './codec'+export { NonceLedger } from './nonce-ledger'+export type { NonceLedgerRedis } from './nonce-ledger'diff --git a/services/mcp/src/lib/signed-state/nonce-ledger.ts b/services/mcp/src/lib/signed-state/nonce-ledger.tsnew file mode 100644index 000000000000..0bcdf5e105db--- /dev/null+++ b/services/mcp/src/lib/signed-state/nonce-ledger.ts@@ -0,0 +1,44 @@+/**+ * Single-use nonce ledger for signed-state tokens.+ *+ * Each successful `consume()` writes the nonce to Redis with `SET NX EX` and+ * the token's remaining TTL. A second consume of the same nonce within that+ * window finds the key already set and rejects.+ *+ * Why a ledger and not just TTL: TTL alone bounds the window but a model+ * could call the destructive execute twice in quick succession (or be+ * prompted to retry on a transient error). Single-use closes that footgun+ * cheaply (one `SET NX` per execute, key auto-expires).+ */++import { NONCE_KEY_PREFIX } from './constants'+import { SignedStateAlreadyConsumed } from './errors'++/**+ * Minimal Redis surface — just what the ledger needs. Both `ioredis` (prod)+ * and the in-memory test stubs satisfy this.+ */+export interface NonceLedgerRedis {+ set(key: string, value: string, ...args: (string | number)[]): Promise<string | null>+}++export class NonceLedger {+ constructor(private readonly redis: NonceLedgerRedis) {}++ /**+ * Mark the nonce consumed. Throws `SignedStateAlreadyConsumed` if it was+ * already consumed within the (remaining) TTL window.+ *+ * `ttlSeconds` is the remaining lifetime of the token: setting the+ * ledger entry to that means abandoned nonces self-clean exactly when+ * the token they protect can no longer be replayed.+ */+ async consume(nonce: string, ttlSeconds: number): Promise<void> {+ const key = `${NONCE_KEY_PREFIX}:${nonce}`+ const safeTtl = Math.max(1, Math.ceil(ttlSeconds))+ const result = await this.redis.set(key, '1', 'EX', safeTtl, 'NX')+ if (result === null) {+ throw new SignedStateAlreadyConsumed(`Nonce ${nonce} has already been consumed within its TTL window`)+ }+ }+}diff --git a/services/mcp/src/tools/confirmed-action-registry.ts b/services/mcp/src/tools/confirmed-action-registry.tsnew file mode 100644index 000000000000..223b33a97ebe--- /dev/null+++ b/services/mcp/src/tools/confirmed-action-registry.ts@@ -0,0 +1,36 @@+/**+ * Process-level singleton holding the `SignedStateCodec` and `NonceLedger`+ * that generated `confirmed_action` handlers call into.+ *+ * The Hono entrypoint installs these at boot via `setConfirmedActionRuntime`.+ * Generated code calls `getConfirmedActionRuntime()` from every prepare/execute+ * handler. Tests can install a custom codec + ledger via `setConfirmedActionRuntime`+ * before exercising the generated code.+ *+ * Pattern matches how UI apps + tool catalogs are wired today — globals+ * installed once, read by many.+ */++import type { NonceLedger, SignedStateCodec } from '@/lib/signed-state'++export interface ConfirmedActionRuntime {+ codec: SignedStateCodec+ ledger: NonceLedger+}++let installed: ConfirmedActionRuntime | undefined++export function setConfirmedActionRuntime(runtime: ConfirmedActionRuntime | undefined): void {+ installed = runtime+}++export function getConfirmedActionRuntime(): ConfirmedActionRuntime {+ if (!installed) {+ throw new Error(+ 'ConfirmedActionRuntime not installed. The confirmed_action paradigm is disabled on this server — ' ++ 'set MCP_SIGNED_STATE_KEY to at least 32 bytes and restart. ' ++ '(In tests, call setConfirmedActionRuntime({codec, ledger}) before exercising prepare/execute handlers.)'+ )+ }+ return installed+}diff --git a/services/mcp/src/tools/confirmed-action-runtime.ts b/services/mcp/src/tools/confirmed-action-runtime.tsnew file mode 100644index 000000000000..acba5bd70645--- /dev/null+++ b/services/mcp/src/tools/confirmed-action-runtime.ts@@ -0,0 +1,246 @@+/**+ * Runtime for the typed-confirm two-tool paradigm.+ *+ * For destructive or security-sensitive tools, codegen emits TWO tools per+ * YAML entry: `<name>-prepare` and `<name>-execute`. The model calls them in+ * sequence; the user is expected to type the literal word "confirm" in+ * chat between the two calls.+ *+ * Why two tools and not elicitation:+ *+ * - Works on every MCP client today (no protocol-level elicitation+ * dependency).+ * - Stateless: the signed hash carries the action context through the+ * model — any server instance can serve `execute`.+ * - The security model is weaker than client-rendered elicitation+ * (the LLM controls the `confirmation` argument), but strictly+ * stronger than a single destructive tool. Honest tradeoff documented+ * in the spec.+ *+ * What each helper does:+ *+ * - `prepareConfirmedAction()` — runs at the top of the `-prepare` tool+ * handler. Signs the validated args + user identity into a hash and+ * returns a result the model surfaces to the user.+ * - `executeConfirmedAction()` — runs at the top of the `-execute` tool+ * handler. Verifies the hash, the literal "confirm" string, and the+ * single-use nonce ledger. Returns the validated payload (the original+ * args) for the rest of the handler to act on, or a `ToolErrorResult`+ * to short-circuit the call.+ *+ * Failure UX note: the nonce is consumed before the underlying handler+ * runs. If the downstream API call then fails, the user must run+ * prepare + confirm again — that's intentional. A failed call may have+ * partially succeeded server-side, and silently allowing a retry under+ * the same confirmation could perform the action a second time when the+ * user thought it had been canceled.+ */++import {+ confirmedActionExecutesTotal,+ confirmedActionPreparesTotal,+ confirmedActionRefusalsTotal,+} from '@/hono/metrics'+import { NonceLedger, SignedStateAlreadyConsumed, SignedStateCodec, SignedStateError } from '@/lib/signed-state'++import type { Context } from './types'++/** The literal word the user must type to confirm. Fixed by design. */+export const CONFIRMATION_WORD = 'confirm'++/**+ * Marker arg names the codegen injects into `-execute` tool schemas.+ * Exported so tests and codegen reference one source of truth.+ */+export const CONFIRMATION_HASH_ARG = 'confirmation_hash'+export const CONFIRMATION_WORD_ARG = 'confirmation'++export interface PrepareConfirmedActionOptions<P extends Record<string, unknown>> {+ /** The validated tool args. Signed into the hash so they can't be tampered with between prepare and execute. */+ args: P+ /**+ * Stable identifier for the logical action — typically the underlying+ * tool name (NOT the `-prepare`/`-execute` suffix). Bound into the hash+ * so a hash issued for action A can't be used to authorize action B.+ */+ purpose: string+ /** Human-readable label surfaced to the user. */+ actionLabel: string+ /** Prompt template shown to the user. Supports `{paramName}` interpolation from `args`. */+ messageTemplate: string+ /** Codec — instantiated once at startup, reused across requests. */+ codec: SignedStateCodec+}++export interface PrepareConfirmedActionResult {+ confirmation_hash: string+ confirmation_word: typeof CONFIRMATION_WORD+ action: string+ message: string+ /** Hint for the model. Surfaces as text on the tool result. */+ next_steps: string+}++/**+ * Run at the top of a `-prepare` tool's handler. Signs the args into a+ * hash and returns the payload the model relays to the user.+ */+export async function prepareConfirmedAction<P extends Record<string, unknown>>(+ context: Context,+ options: PrepareConfirmedActionOptions<P>+): Promise<PrepareConfirmedActionResult> {+ const sub = await context.getDistinctId()+ const { token } = await options.codec.encode({+ sub,+ purpose: options.purpose,+ payload: options.args,+ })+ confirmedActionPreparesTotal.inc({ tool: options.purpose, status: 'ok' })+ return {+ confirmation_hash: token,+ confirmation_word: CONFIRMATION_WORD,+ action: options.actionLabel,+ message: interpolate(options.messageTemplate, options.args),+ next_steps:+ `Surface the message above to the user. Wait for them to reply with the literal word "${CONFIRMATION_WORD}". ` ++ `Then call the matching \`-execute\` tool with \`${CONFIRMATION_HASH_ARG}\` set to the confirmation_hash from this result, ` ++ `\`${CONFIRMATION_WORD_ARG}\` set to the user's literal reply, and the same arguments you used here. ` ++ `If the user does not reply with "${CONFIRMATION_WORD}", do not call the execute tool.`,+ }+}++export interface ExecuteConfirmedActionOptions<P extends Record<string, unknown>> {+ /** The full incoming args object — includes `confirmation_hash`, `confirmation`, and the original tool args. */+ incomingArgs: P & { [CONFIRMATION_HASH_ARG]: string; [CONFIRMATION_WORD_ARG]: string }+ /** Same `purpose` value used at prepare time. */+ purpose: string+ /** Codec + ledger; both single instances reused across requests. */+ codec: SignedStateCodec+ ledger: NonceLedger+}++export type ExecuteConfirmedActionOutcome<P> = { ok: true; verifiedArgs: P } | { ok: false; result: ToolErrorResult }++interface ToolErrorResult {+ content: Array<{ type: 'text'; text: string }>+ isError: true+}++/**+ * Run at the top of an `-execute` tool's handler. Verifies the hash, the+ * confirmation string, and burns the nonce. Returns the validated args+ * (without the framework fields) on success, or a `ToolErrorResult` to+ * short-circuit.+ */+export async function executeConfirmedAction<P extends Record<string, unknown>>(+ context: Context,+ options: ExecuteConfirmedActionOptions<P>+): Promise<ExecuteConfirmedActionOutcome<P>> {+ const sub = await context.getDistinctId()++ const hash = options.incomingArgs[CONFIRMATION_HASH_ARG]+ const word = options.incomingArgs[CONFIRMATION_WORD_ARG]++ if (typeof word !== 'string' || word !== CONFIRMATION_WORD) {+ return refuse(+ options.purpose,+ 'wrong_word',+ `${options.purpose} was not executed — the \`${CONFIRMATION_WORD_ARG}\` argument must be the literal string "${CONFIRMATION_WORD}", typed by the user. The user did not confirm.`+ )+ }++ let claims+ try {+ claims = await options.codec.decode(hash, sub, options.purpose)+ } catch (err) {+ if (err instanceof SignedStateError) {+ return refuse(options.purpose, err.kind, `${options.purpose} was not executed — ${reasonFor(err)}.`)+ }+ throw err+ }++ // Single-use enforcement. Bind the ledger TTL to the token's remaining+ // life so abandoned nonces self-clean exactly when the token they+ // protect can no longer be replayed. The remaining TTL comes from the+ // codec's clock, not the wall clock — clock drift between the signer+ // and the consumer could otherwise shrink the ledger TTL enough to+ // re-allow replay.+ try {+ await options.ledger.consume(claims.nonce, options.codec.secondsUntilExpiry(claims))+ } catch (err) {+ if (err instanceof SignedStateAlreadyConsumed) {+ return refuse(+ options.purpose,+ 'replay',+ `${options.purpose} was not executed — this confirmation has already been used. Start a new prepare-then-execute cycle if you need to perform the action again.`+ )+ }+ throw err+ }++ // The payload was signed at prepare time; treat it as untrusted JSON+ // and shape-check before returning. The caller already knows the+ // expected shape via its tool schema.+ const verified = claims.payload+ if (verified === null || typeof verified !== 'object' || Array.isArray(verified)) {+ return refuse(+ options.purpose,+ 'malformed_payload',+ `${options.purpose} was not executed — confirmation payload is malformed.`+ )+ }++ confirmedActionExecutesTotal.inc({ tool: options.purpose, status: 'ok' })+ return { ok: true, verifiedArgs: verified as P }+}++function refuse(purpose: string, reason: string, message: string): { ok: false; result: ToolErrorResult } {+ confirmedActionExecutesTotal.inc({ tool: purpose, status: 'refused' })+ confirmedActionRefusalsTotal.inc({ tool: purpose, reason })+ return {+ ok: false,+ result: {+ content: [{ type: 'text', text: message }],+ isError: true,+ },+ }+}++/**+ * Replace `{paramName}` placeholders in `template` with `args[paramName]`.+ * Missing keys stay as the literal `{name}` so authors notice during smoke+ * tests rather than silently shipping `"Delete organization ?"` to a user.+ * Non-scalar values (objects, arrays) are left as the literal `{name}` too+ * — these are user-facing confirmation prompts; rendering "[object Object]"+ * silently is worse than the author seeing the placeholder leak through.+ */+function interpolate(template: string, args: Record<string, unknown>): string {+ return template.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (full, key: string) => {+ if (!(key in args)) {+ return full+ }+ const value = args[key]+ const t = typeof value+ if (t === 'string' || t === 'number' || t === 'boolean') {+ return String(value)+ }+ return full+ })+}++function reasonFor(err: SignedStateError): string {+ switch (err.kind) {+ case 'expired':+ return 'the confirmation expired; please run the prepare step again'+ case 'user_mismatch':+ return 'the confirmation was issued for a different user'+ case 'purpose_mismatch':+ return 'the confirmation was issued for a different action'+ case 'bad_signature':+ return 'the confirmation signature is invalid'+ case 'malformed':+ return 'the confirmation token is malformed'+ default:+ return 'the confirmation token was rejected'+ }+}diff --git a/services/mcp/tests/hono/app-routes.test.ts b/services/mcp/tests/hono/app-routes.test.tsindex 803961c331ed..033c5d54098e 100644--- a/services/mcp/tests/hono/app-routes.test.ts+++ b/services/mcp/tests/hono/app-routes.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'import type { Mock } from 'vitest'import { createApp } from '@/hono/app'@@ -6,6 +6,14 @@ import type { RedisLike } from '@/hono/cache/RedisCache'import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'+// Tests that go through createApp need a signing key — the typed-confirm+// runtime install throws without one. We stub a fixed value rather than+// depend on the surrounding environment.+const TEST_SIGNING_KEY = 'a'.repeat(32)+beforeAll(() => {+ process.env.MCP_SIGNED_STATE_KEY = TEST_SIGNING_KEY+})+interface MockRedis extends RedisLike {ping: Mock<() => Promise<string>>_store: Map<string, string>@@ -397,4 +405,61 @@ describe('Hono App Routes', () => {expect(res2.status).toBe(200)})})++ describe('confirmed-action runtime', () => {+ afterEach(() => {+ // Restore the signing key after the "missing key" test below+ // unsets it, so following tests don't bleed into each other.+ process.env.MCP_SIGNED_STATE_KEY = TEST_SIGNING_KEY+ })++ it('installs the runtime so generated -prepare/-execute handlers can resolve it', async () => {+ // createApp wires setConfirmedActionRuntime at boot. Without+ // that wiring, getConfirmedActionRuntime() throws — so the+ // mere fact that we can resolve a non-undefined runtime after+ // createApp ran proves the boot path is in place.+ createApp(mockRedis)+ const { getConfirmedActionRuntime } = await import('@/tools/confirmed-action-registry')+ const runtime = getConfirmedActionRuntime()+ expect(runtime.codec).toBeInstanceOf(Object)+ expect(runtime.ledger).toBeInstanceOf(Object)+ })++ it('overwrites the singleton on each createApp call (latest wins)', async () => {+ // app.ts deliberately re-installs the runtime on every+ // createApp. Lock that behavior down so a future "guard+ // against re-install" change doesn't silently make the second+ // app instance share the first app's Redis-bound ledger.+ const { getConfirmedActionRuntime } = await import('@/tools/confirmed-action-registry')+ const redis1 = createMockRedis()+ createApp(redis1)+ const first = getConfirmedActionRuntime()+ const redis2 = createMockRedis()+ createApp(redis2)+ const second = getConfirmedActionRuntime()+ expect(second).not.toBe(first)+ expect(second.ledger).not.toBe(first.ledger)+ })++ it('boots without a signing key — confirmed_action paradigm is disabled but the app still serves', async () => {+ // Option B: missing key disables the paradigm but does NOT+ // crash the app. Other tools keep working; only confirmed_action+ // tools fail at request time. Assert: app responds normally+ // AND getConfirmedActionRuntime() throws with a message that+ // points at the env var.+ delete process.env.MCP_SIGNED_STATE_KEY+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)+ try {+ const { app } = createApp(mockRedis)+ const res = await app.request('/healthz')+ expect(res.status).toBe(200)+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('confirmed-action paradigm disabled'))++ const { getConfirmedActionRuntime } = await import('@/tools/confirmed-action-registry')+ expect(() => getConfirmedActionRuntime()).toThrow(/MCP_SIGNED_STATE_KEY/)+ } finally {+ errorSpy.mockRestore()+ }+ })+ })})diff --git a/services/mcp/tests/unit/confirmed-action-runtime.test.ts b/services/mcp/tests/unit/confirmed-action-runtime.test.tsnew file mode 100644index 000000000000..c262801cb5f4--- /dev/null+++ b/services/mcp/tests/unit/confirmed-action-runtime.test.ts@@ -0,0 +1,351 @@+import { beforeEach, describe, expect, it } from 'vitest'++import {+ confirmedActionExecutesTotal,+ confirmedActionPreparesTotal,+ confirmedActionRefusalsTotal,+} from '@/hono/metrics'+import { NonceLedger, SignedStateCodec } from '@/lib/signed-state'+import {+ CONFIRMATION_HASH_ARG,+ CONFIRMATION_WORD,+ CONFIRMATION_WORD_ARG,+ executeConfirmedAction,+ prepareConfirmedAction,+} from '@/tools/confirmed-action-runtime'+import type { Context } from '@/tools/types'++function makeContext(distinctId: string = 'did-1'): Context {+ const stub = null as unknown as never+ return {+ api: stub,+ cache: stub,+ env: stub,+ stateManager: stub,+ sessionManager: stub,+ getDistinctId: () => Promise.resolve(distinctId),+ trackEvent: () => Promise.resolve(),+ } as Context+}++function makeCodec(): SignedStateCodec {+ return new SignedStateCodec(Buffer.alloc(32, 0x42), {+ now: () => 1_700_000_000_000,+ randomNonce: () => 'nonce-fixed',+ ttlSeconds: 300,+ })+}++function makeLedger(): { ledger: NonceLedger; consumed: Set<string> } {+ const consumed = new Set<string>()+ const ledger = new NonceLedger({+ set: async (key, _value, ..._args) => {+ const args = _args.map((a) => (typeof a === 'string' ? a.toUpperCase() : a))+ const nx = args.includes('NX')+ if (nx && consumed.has(key)) {+ return null+ }+ consumed.add(key)+ return 'OK'+ },+ })+ return { ledger, consumed }+}++describe('prepareConfirmedAction', () => {+ it('returns the canonical payload shape with a signed token', async () => {+ const codec = makeCodec()+ const result = await prepareConfirmedAction(makeContext('did-1'), {+ args: { orgId: 'acme' },+ purpose: 'organization-enforce-2fa-update',+ actionLabel: 'enforce 2FA',+ messageTemplate: 'About to enable enforce 2FA on organization {orgId}.',+ codec,+ })+ expect(result.confirmation_word).toBe(CONFIRMATION_WORD)+ expect(result.action).toBe('enforce 2FA')+ expect(result.message).toBe('About to enable enforce 2FA on organization acme.')+ expect(result.confirmation_hash.split('.')).toHaveLength(3)+ expect(result.next_steps).toContain('"confirm"')+ })++ it('leaves unknown placeholders literal so authors notice missing keys', async () => {+ const codec = makeCodec()+ const result = await prepareConfirmedAction(makeContext(), {+ args: {},+ purpose: 'p',+ actionLabel: 'a',+ messageTemplate: 'Delete {missing}',+ codec,+ })+ expect(result.message).toBe('Delete {missing}')+ })++ it('leaves non-scalar placeholders literal (no "[object Object]" in user prompts)', async () => {+ const codec = makeCodec()+ const result = await prepareConfirmedAction(makeContext(), {+ args: { filters: { team: 1 }, tags: ['a', 'b'] },+ purpose: 'p',+ actionLabel: 'a',+ messageTemplate: 'Apply {filters} for {tags}',+ codec,+ })+ expect(result.message).toBe('Apply {filters} for {tags}')+ })+})++describe('executeConfirmedAction', () => {+ function setup(): { codec: SignedStateCodec; ledger: NonceLedger; consumed: Set<string> } {+ const codec = makeCodec()+ const { ledger, consumed } = makeLedger()+ return { codec, ledger, consumed }+ }++ async function mintToken(+ codec: SignedStateCodec,+ distinctId: string,+ purpose: string,+ payload: unknown+ ): Promise<string> {+ const ctx = makeContext(distinctId)+ const result = await prepareConfirmedAction(ctx, {+ args: payload as Record<string, unknown>,+ purpose,+ actionLabel: 'x',+ messageTemplate: 'msg',+ codec,+ })+ return result.confirmation_hash+ }++ it('verifies a fresh token and returns verifiedArgs', async () => {+ const { codec, ledger } = setup()+ const hash = await mintToken(codec, 'did-1', 'enforce-2fa', { orgId: 'acme' })+ const outcome = await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: {+ [CONFIRMATION_HASH_ARG]: hash,+ [CONFIRMATION_WORD_ARG]: 'confirm',+ orgId: 'acme',+ },+ purpose: 'enforce-2fa',+ codec,+ ledger,+ })+ expect(outcome.ok).toBe(true)+ if (outcome.ok) {+ expect(outcome.verifiedArgs).toEqual({ orgId: 'acme' })+ }+ })++ it('refuses if the literal confirmation word is wrong', async () => {+ const { codec, ledger } = setup()+ const hash = await mintToken(codec, 'did-1', 'p', {})+ const outcome = await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'yes' },+ purpose: 'p',+ codec,+ ledger,+ })+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) {+ expect(outcome.result.content[0]!.text).toContain('confirm')+ }+ })++ it('refuses on user mismatch', async () => {+ const { codec, ledger } = setup()+ const hash = await mintToken(codec, 'did-victim', 'p', {})+ const outcome = await executeConfirmedAction(makeContext('did-attacker'), {+ incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm' },+ purpose: 'p',+ codec,+ ledger,+ })+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) {+ expect(outcome.result.content[0]!.text).toContain('different user')+ }+ })++ it('refuses on purpose mismatch', async () => {+ const { codec, ledger } = setup()+ const hash = await mintToken(codec, 'did-1', 'tool-A', {})+ const outcome = await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm' },+ purpose: 'tool-B',+ codec,+ ledger,+ })+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) {+ expect(outcome.result.content[0]!.text).toContain('different action')+ }+ })++ it('refuses on replay of the same hash', async () => {+ const { codec, ledger } = setup()+ const hash = await mintToken(codec, 'did-1', 'p', { orgId: 'x' })+ const first = await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm', orgId: 'x' },+ purpose: 'p',+ codec,+ ledger,+ })+ expect(first.ok).toBe(true)+ const second = await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm', orgId: 'x' },+ purpose: 'p',+ codec,+ ledger,+ })+ expect(second.ok).toBe(false)+ if (!second.ok) {+ expect(second.result.content[0]!.text).toContain('already been used')+ }+ })++ it('refuses on tampered signature', async () => {+ const { codec, ledger } = setup()+ const hash = await mintToken(codec, 'did-1', 'p', {})+ const segs = hash.split('.')+ const tampered = `${segs[0]}.${segs[1]}.${segs[2]!.slice(0, -1)}A`+ const outcome = await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: { [CONFIRMATION_HASH_ARG]: tampered, [CONFIRMATION_WORD_ARG]: 'confirm' },+ purpose: 'p',+ codec,+ ledger,+ })+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) {+ expect(outcome.result.content[0]!.text).toContain('signature is invalid')+ }+ })++ it('sources the ledger TTL from the codec clock, not the wall clock', async () => {+ // Pin the codec's clock 100s before exp. If the runtime ever+ // sources the TTL from the wall clock instead, the codec's fake+ // clock and real Date.now() will diverge by ~years and the+ // observed TTL will collapse to 1 — re-allowing replay against+ // a real Redis.+ const codec = makeCodec() // ttlSeconds: 300, clock pinned 100s before exp+ let observedTtl: number | undefined+ const ledger = new NonceLedger({+ set: async (_key, _value, ..._args) => {+ // arg order from NonceLedger.consume: ('EX', ttl, 'NX')+ observedTtl = _args[1] as number+ return 'OK'+ },+ })+ const hash = await mintToken(codec, 'did-1', 'tool-A', { x: 1 })+ const outcome = await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm', x: 1 },+ purpose: 'tool-A',+ codec,+ ledger,+ })+ expect(outcome.ok).toBe(true)+ expect(observedTtl).toBe(300)+ })+})++describe('confirmed-action metrics', () => {+ beforeEach(() => {+ // Counter values accumulate across tests in this process — reset to+ // make assertions order-independent.+ confirmedActionPreparesTotal.reset()+ confirmedActionExecutesTotal.reset()+ confirmedActionRefusalsTotal.reset()+ })++ function makeLedger(): NonceLedger {+ const consumed = new Set<string>()+ return new NonceLedger({+ set: async (key, _v, ..._args) => {+ if (consumed.has(key)) {+ return null+ }+ consumed.add(key)+ return 'OK'+ },+ })+ }++ async function metricValue(+ counter:+ | typeof confirmedActionPreparesTotal+ | typeof confirmedActionExecutesTotal+ | typeof confirmedActionRefusalsTotal,+ labels: Record<string, string>+ ): Promise<number> {+ const json = await counter.get()+ return (+ json.values.find((v) =>+ Object.entries(labels).every(([k, val]) => (v.labels as Record<string, string>)[k] === val)+ )?.value ?? 0+ )+ }++ it('increments prepares_total on a successful prepare', async () => {+ const codec = makeCodec()+ await prepareConfirmedAction(makeContext('did-1'), {+ args: {},+ purpose: 'tool-A',+ actionLabel: 'A',+ messageTemplate: 'msg',+ codec,+ })+ expect(await metricValue(confirmedActionPreparesTotal, { tool: 'tool-A', status: 'ok' })).toBe(1)+ })++ it('increments executes_total ok on a successful execute', async () => {+ const codec = makeCodec()+ const ledger = makeLedger()+ const prep = await prepareConfirmedAction(makeContext('did-1'), {+ args: { id: 'x' },+ purpose: 'tool-B',+ actionLabel: 'B',+ messageTemplate: 'msg',+ codec,+ })+ await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: {+ [CONFIRMATION_HASH_ARG]: prep.confirmation_hash,+ [CONFIRMATION_WORD_ARG]: 'confirm',+ id: 'x',+ },+ purpose: 'tool-B',+ codec,+ ledger,+ })+ expect(await metricValue(confirmedActionExecutesTotal, { tool: 'tool-B', status: 'ok' })).toBe(1)+ })++ it('increments refusals_total with the right reason label per failure mode', async () => {+ const codec = makeCodec()+ const ledger = makeLedger()+ const prep = await prepareConfirmedAction(makeContext('did-1'), {+ args: {},+ purpose: 'tool-C',+ actionLabel: 'C',+ messageTemplate: 'msg',+ codec,+ })+ // wrong word+ await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: { [CONFIRMATION_HASH_ARG]: prep.confirmation_hash, [CONFIRMATION_WORD_ARG]: 'yes' },+ purpose: 'tool-C',+ codec,+ ledger,+ })+ // user mismatch+ await executeConfirmedAction(makeContext('did-attacker'), {+ incomingArgs: { [CONFIRMATION_HASH_ARG]: prep.confirmation_hash, [CONFIRMATION_WORD_ARG]: 'confirm' },+ purpose: 'tool-C',+ codec,+ ledger,+ })+ expect(await metricValue(confirmedActionRefusalsTotal, { tool: 'tool-C', reason: 'wrong_word' })).toBe(1)+ expect(await metricValue(confirmedActionRefusalsTotal, { tool: 'tool-C', reason: 'user_mismatch' })).toBe(1)+ expect(await metricValue(confirmedActionExecutesTotal, { tool: 'tool-C', status: 'refused' })).toBe(2)+ })+})diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.tsindex d29246ef16bb..3cebccde72ff 100644--- a/services/mcp/tests/unit/generate-tools.test.ts+++ b/services/mcp/tests/unit/generate-tools.test.ts@@ -1522,3 +1522,186 @@ describe('path parameter encoding', () => {expect(result.code).not.toMatch(/\$\{id\}[^)]/)})})++// ------------------------------------------------------------------+// confirmed_action — schema validation+// ------------------------------------------------------------------++describe('ToolConfigSchema confirmed_action', () => {+ const base = {+ operation: 'organizations_partial_update',+ enabled: true,+ } as const++ it('accepts a minimal confirmed_action block', () => {+ const result = ToolConfigSchema.safeParse({+ ...base,+ confirmed_action: { message: 'Confirm action on {orgId}?' },+ })+ expect(result.success).toBe(true)+ })++ it('accepts an action_label override', () => {+ const result = ToolConfigSchema.safeParse({+ ...base,+ confirmed_action: { message: 'Confirm', action_label: 'enforce 2FA' },+ })+ expect(result.success).toBe(true)+ })++ it('rejects missing message', () => {+ const result = ToolConfigSchema.safeParse({+ ...base,+ confirmed_action: { action_label: 'foo' },+ })+ expect(result.success).toBe(false)+ })++ it('rejects confirmed_action combined with ui_app (silent UI-app drop)', () => {+ const result = ToolConfigSchema.safeParse({+ ...base,+ ui_app: 'org-2fa',+ confirmed_action: { message: 'x' },+ })+ expect(result.success).toBe(false)+ if (!result.success) {+ expect(result.error.issues[0]!.message).toContain('ui_app')+ }+ })++ it('rejects unknown keys inside the confirmed_action object', () => {+ const result = ToolConfigSchema.safeParse({+ ...base,+ confirmed_action: { message: 'x', bogus: true },+ })+ expect(result.success).toBe(false)+ })+})++// ------------------------------------------------------------------+// generateToolCode — confirmed_action codegen+// ------------------------------------------------------------------++describe('generateToolCode with confirmed_action', () => {+ function makeConfirmedConfig(): ToolConfig {+ return {+ operation: 'organizations_partial_update',+ enabled: true,+ title: 'Enforce 2FA',+ confirmed_action: {+ message: 'About to enable enforce 2FA on organization {id}.',+ action_label: 'enforce 2FA',+ },+ }+ }++ function makePatchResolved(): ResolvedOperation {+ return {+ method: 'PATCH',+ path: '/api/organizations/{id}/',+ operation: { operationId: 'organizations_partial_update', parameters: [] },+ }+ }++ it('emits TWO factories (prepare and execute), not the base factory', () => {+ const result = generateToolCode(+ 'organization-enforce-2fa-update',+ makeConfirmedConfig(),+ makePatchResolved(),+ defaultCategory,+ makeSpec(),+ new Set<string>(),+ stubGetQuerySchema+ )+ expect(result.code).toContain('organizationEnforce2faUpdatePrepare')+ expect(result.code).toContain('organizationEnforce2faUpdateExecute')+ // No base factory of the original name should be emitted.+ expect(result.code).not.toMatch(/const organizationEnforce2faUpdate\s*=/)+ })++ it('extends the base schema for the execute variant with confirmation fields', () => {+ const result = generateToolCode(+ 'organization-enforce-2fa-update',+ makeConfirmedConfig(),+ makePatchResolved(),+ defaultCategory,+ makeSpec(),+ new Set<string>(),+ stubGetQuerySchema+ )+ expect(result.code).toContain('OrganizationEnforce2faUpdateSchemaExecute')+ expect(result.code).toContain('.extend({')+ expect(result.code).toContain('confirmation_hash')+ expect(result.code).toContain('confirmation:')+ })++ it('wires prepare into prepareConfirmedAction with the messageTemplate', () => {+ const result = generateToolCode(+ 'organization-enforce-2fa-update',+ makeConfirmedConfig(),+ makePatchResolved(),+ defaultCategory,+ makeSpec(),+ new Set<string>(),+ stubGetQuerySchema+ )+ expect(result.code).toContain('await prepareConfirmedAction')+ expect(result.code).toContain('purpose: "organization-enforce-2fa-update"')+ expect(result.code).toContain('actionLabel: "enforce 2FA"')+ expect(result.code).toContain('messageTemplate: "About to enable enforce 2FA on organization {id}."')+ })++ it('wires execute into executeConfirmedAction and falls through to the original API call', () => {+ const result = generateToolCode(+ 'organization-enforce-2fa-update',+ makeConfirmedConfig(),+ makePatchResolved(),+ defaultCategory,+ makeSpec(),+ new Set<string>(),+ stubGetQuerySchema+ )+ expect(result.code).toContain('await executeConfirmedAction')+ expect(result.code).toContain('if (!__guard.ok)')+ // After the guard, the handler runs the original API request.+ expect(result.code).toContain('await context.api.request')+ expect(result.code).toContain("method: 'PATCH'")+ })++ it('REPLACES params with verifiedArgs (never merges) so unsigned extras cannot survive', () => {+ // The generated handler must not preserve incoming params alongside+ // verifiedArgs — only the signed payload is authorized. A merge+ // would let the model slip an unsigned base-schema field (e.g. an+ // extra 'name') into the downstream API body without it ever being+ // shown to the user at prepare time.+ const result = generateToolCode(+ 'organization-enforce-2fa-update',+ makeConfirmedConfig(),+ makePatchResolved(),+ defaultCategory,+ makeSpec(),+ new Set<string>(),+ stubGetQuerySchema+ )+ expect(result.code).toContain('params = { ...__guard.verifiedArgs }')+ expect(result.code).not.toMatch(/params\s*=\s*\{\s*\.\.\.params\s*,\s*\.\.\.__guard\.verifiedArgs/)+ })++ it('uses the tool title as the fallback action_label when none is set', () => {+ const config: ToolConfig = {+ ...makeConfirmedConfig(),+ title: 'Enforce 2FA',+ confirmed_action: { message: 'msg' },+ }+ const result = generateToolCode(+ 'organization-enforce-2fa-update',+ config,+ makePatchResolved(),+ defaultCategory,+ makeSpec(),+ new Set<string>(),+ stubGetQuerySchema+ )+ expect(result.code).toContain('actionLabel: "Enforce 2FA"')+ })+})diff --git a/services/mcp/tests/unit/signed-state.test.ts b/services/mcp/tests/unit/signed-state.test.tsnew file mode 100644index 000000000000..cbe6d9309b26--- /dev/null+++ b/services/mcp/tests/unit/signed-state.test.ts@@ -0,0 +1,177 @@+import { describe, expect, it, vi } from 'vitest'++import {+ loadSigningKeyFromEnv,+ NonceLedger,+ SignedStateAlreadyConsumed,+ SignedStateCodec,+ SignedStateExpired,+ SignedStateMalformed,+ SignedStatePurposeMismatch,+ SignedStateSignatureInvalid,+ SignedStateUserMismatch,+} from '@/lib/signed-state'++function makeCodec(now = 1_700_000_000_000): {+ codec: SignedStateCodec+ advance: (ms: number) => void+} {+ let clock = now+ const codec = new SignedStateCodec(Buffer.alloc(32, 0x42), {+ now: () => clock,+ randomNonce: () => 'fixed-nonce',+ ttlSeconds: 300,+ })+ return { codec, advance: (ms) => (clock += ms) }+}++describe('SignedStateCodec', () => {+ it('round-trips claims through encode + decode', async () => {+ const { codec } = makeCodec()+ const { token, claims } = await codec.encode({ sub: 'u1', purpose: 'p1', payload: { x: 7 } })+ expect(claims.exp).toBe(claims.iat + 300)+ const decoded = await codec.decode(token, 'u1', 'p1')+ expect(decoded.payload).toEqual({ x: 7 })+ expect(decoded.nonce).toBe('fixed-nonce')+ })++ it('rejects a token whose signature was tampered with', async () => {+ const { codec } = makeCodec()+ const { token } = await codec.encode({ sub: 'u1', purpose: 'p1', payload: null })+ const segs = token.split('.')+ const sig = segs[2]!+ const tampered = `${segs[0]}.${segs[1]}.${sig.slice(0, -1)}${sig.endsWith('A') ? 'B' : 'A'}`+ await expect(codec.decode(tampered, 'u1', 'p1')).rejects.toBeInstanceOf(SignedStateSignatureInvalid)+ })++ it('rejects a token after exp has passed', async () => {+ const { codec, advance } = makeCodec()+ const { token } = await codec.encode({ sub: 'u1', purpose: 'p1', payload: null })+ advance(301 * 1000)+ await expect(codec.decode(token, 'u1', 'p1')).rejects.toBeInstanceOf(SignedStateExpired)+ })++ it('rejects a token replayed under a different sub', async () => {+ const { codec } = makeCodec()+ const { token } = await codec.encode({ sub: 'u1', purpose: 'p1', payload: null })+ await expect(codec.decode(token, 'attacker', 'p1')).rejects.toBeInstanceOf(SignedStateUserMismatch)+ })++ it('rejects a token replayed for a different purpose', async () => {+ const { codec } = makeCodec()+ const { token } = await codec.encode({ sub: 'u1', purpose: 'p1', payload: null })+ await expect(codec.decode(token, 'u1', 'p2')).rejects.toBeInstanceOf(SignedStatePurposeMismatch)+ })++ it('rejects malformed tokens (wrong segment count)', async () => {+ const { codec } = makeCodec()+ await expect(codec.decode('only.two', 'u', 'p')).rejects.toBeInstanceOf(SignedStateMalformed)+ })++ it('rejects a token signed with a different key', async () => {+ const a = new SignedStateCodec(Buffer.alloc(32, 0x11), { now: () => 1_700_000_000_000 })+ const b = new SignedStateCodec(Buffer.alloc(32, 0x22), { now: () => 1_700_000_000_000 })+ const { token } = await a.encode({ sub: 'u1', purpose: 'p1', payload: null })+ await expect(b.decode(token, 'u1', 'p1')).rejects.toBeInstanceOf(SignedStateSignatureInvalid)+ })++ it('secondsUntilExpiry sources the clock from the codec, not the wall clock', async () => {+ // Inject a clock 100s before exp; assert the runtime gets 100,+ // independent of what Date.now() reads in real wall time. This+ // is what protects the nonce ledger from clock-skew shrinkage.+ const { codec } = makeCodec()+ const { claims } = await codec.encode({ sub: 'u', purpose: 'p', payload: null })+ expect(codec.secondsUntilExpiry(claims)).toBe(300)+ })++ it('secondsUntilExpiry tracks the injected clock as it advances', async () => {+ const { codec, advance } = makeCodec()+ const { claims } = await codec.encode({ sub: 'u', purpose: 'p', payload: null })+ advance(200 * 1000)+ expect(codec.secondsUntilExpiry(claims)).toBe(100)+ })++ it('secondsUntilExpiry clamps to 1 once the token has lapsed', async () => {+ const { codec, advance } = makeCodec()+ const { claims } = await codec.encode({ sub: 'u', purpose: 'p', payload: null })+ advance(1_000 * 1000) // far past exp+ expect(codec.secondsUntilExpiry(claims)).toBe(1)+ })++ it('rejects a token whose protected header typ is wrong (cross-system replay)', async () => {+ // jose pins the typ header on verify — this protects against+ // someone feeding us a token signed for a different MCP feature+ // that happens to share the same key.+ const key = Buffer.alloc(32, 0x42)+ const { SignJWT } = await import('jose')+ const foreignToken = await new SignJWT({})+ .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })+ .setSubject('u1')+ .setAudience('p1')+ .setIssuedAt(1_700_000_000)+ .setExpirationTime(1_700_000_300)+ .setJti('n')+ .sign(new Uint8Array(key))+ const codec = new SignedStateCodec(key, { now: () => 1_700_000_000_000 })+ await expect(codec.decode(foreignToken, 'u1', 'p1')).rejects.toBeInstanceOf(SignedStateMalformed)+ })+})++describe('loadSigningKeyFromEnv', () => {+ it('throws when the key is missing, regardless of NODE_ENV', () => {+ expect(() => loadSigningKeyFromEnv({})).toThrow(/must be set/)+ expect(() => loadSigningKeyFromEnv({ NODE_ENV: 'development' })).toThrow(/must be set/)+ expect(() => loadSigningKeyFromEnv({ NODE_ENV: 'production' })).toThrow(/must be set/)+ expect(() => loadSigningKeyFromEnv({ NODE_ENV: 'staging' })).toThrow(/must be set/)+ })++ it('throws when the key is shorter than 32 bytes', () => {+ expect(() => loadSigningKeyFromEnv({ MCP_SIGNED_STATE_KEY: 'short' })).toThrow(/must be set/)+ expect(() => loadSigningKeyFromEnv({ MCP_SIGNED_STATE_KEY: 'a'.repeat(31) })).toThrow(/must be set/)+ })++ it('returns the configured key when long enough', () => {+ const longKey = 'a'.repeat(32)+ const key = loadSigningKeyFromEnv({ MCP_SIGNED_STATE_KEY: longKey })+ expect(key.toString()).toBe(longKey)+ })+})++describe('NonceLedger', () => {+ function makeRedis(): { redis: { set: ReturnType<typeof vi.fn> }; store: Map<string, string> } {+ const store = new Map<string, string>()+ const redis = {+ set: vi.fn(async (key: string, value: string, ..._args: (string | number)[]) => {+ const argv = _args.map((a) => (typeof a === 'string' ? a.toUpperCase() : a))+ const nx = argv.includes('NX')+ if (nx && store.has(key)) {+ return null+ }+ store.set(key, value)+ return 'OK'+ }),+ }+ return { redis, store }+ }++ it('consumes a fresh nonce successfully', async () => {+ const { redis } = makeRedis()+ const ledger = new NonceLedger(redis)+ await expect(ledger.consume('nonce-1', 300)).resolves.toBeUndefined()+ })++ it('rejects a second consume of the same nonce', async () => {+ const { redis } = makeRedis()+ const ledger = new NonceLedger(redis)+ await ledger.consume('nonce-1', 300)+ await expect(ledger.consume('nonce-1', 300)).rejects.toBeInstanceOf(SignedStateAlreadyConsumed)+ })++ it('uses NX + EX so abandoned nonces self-clean', async () => {+ const { redis } = makeRedis()+ const ledger = new NonceLedger(redis)+ await ledger.consume('nonce-1', 300)+ const args = redis.set.mock.calls[0]!+ expect(args).toEqual(['mcp:signed-state:nonce:nonce-1', '1', 'EX', 300, 'NX'])+ })+})