From a8063f90ab394ca9a967c7e90a02d7d250b25ca6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 03:31:08 +0000 Subject: [PATCH 1/8] wip(mcp): elicit-first confirmation channel for the action tools Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 --- .../src/action-confirmation-elicitation.ts | 166 ++++++++++++++++++ packages/mcp/src/index.ts | 12 ++ packages/mcp/src/mcp-http-tools.ts | 46 ++++- 3 files changed, 216 insertions(+), 8 deletions(-) create mode 100644 packages/mcp/src/action-confirmation-elicitation.ts diff --git a/packages/mcp/src/action-confirmation-elicitation.ts b/packages/mcp/src/action-confirmation-elicitation.ts new file mode 100644 index 00000000000..020c67ae746 --- /dev/null +++ b/packages/mcp/src/action-confirmation-elicitation.ts @@ -0,0 +1,166 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * # Asking the person in their client (step 1 of the amended confirmation contract) + * + * The MCP `run_action` and `resume_run` doors confirm an action whose author + * declared `ai.requiresConfirmation: true` with the person, never with the + * caller's own `confirm` (`AI_ACTION_CONFIRMATION_CAPABILITY`, + * `@objectstack/spec/contracts`). Step 1 of that contract asks the person in + * place: when the client advertised `elicitation` at `initialize` for the + * session the call rides on, and the door can carry a request to it while the + * call is open, the server sends ONE `elicitation/create` request in form mode + * naming the action, the object and the record. This module is that request. + * + * The runtime owns WHEN it is asked (after every admission gate, the subject + * load and its verdict included, and never for an AI service account); this + * door owns HOW: {@link actionConfirmationElicitorFor} answers a function the + * bridge calls with the subject, or `undefined` when this call cannot be + * elicited, and the runtime then hands the call off (step 2) exactly as + * before. + * + * ## Which doors can elicit + * + * Only a server that read the client's `initialize`. The long-lived server + * behind the stdio transport keeps the client's capabilities for the session + * and carries a request to the client while a call is open, so it elicits. The + * Streamable HTTP door (`handleHttpRequest`) builds a fresh server for every + * POST: the server that answers a `tools/call` never saw the client's + * `initialize`, so it holds no capabilities and this function answers + * `undefined` there. Its callers are handed off, as the contract's step 2 + * says a door that cannot elicit does, and are never refused for that alone. + * + * ## The answers + * + * Only the result's `action` is read; any `content` is not (the contract, + * step 3.1), so a client's form payload can neither satisfy nor break it. + * + * - `accept`, `decline`, `cancel`: the client's own answer. + * - `timed_out`: no answer within {@link ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS}. + * The SDK drops the pending request at that moment, so an answer that + * arrives later is never delivered and runs nothing. + * - `cancel` also stands for an error answer to the request, a result the + * door cannot read, the tool call being cancelled while the question is + * open, and a connection that closes before an answer (the contract reads + * each the same way as a dismissal). + */ + +import { z } from 'zod'; +import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { ErrorCode, McpError, type ServerNotification, type ServerRequest } from '@modelcontextprotocol/sdk/types.js'; +import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js'; +import { AI_ACTION_CONFIRMATION_CAPABILITY } from '@objectstack/spec/contracts'; + +/** + * The door's bound on an elicited confirmation: how long the server waits for + * the person's answer before it reads the question as unanswered (`timed_out`, + * the contract's step 4, "within the door's bound, which the implementing door + * names"). Five minutes: long enough for a person to read an action and its + * record and decide, short enough that an abandoned question does not hold a + * tool call open for the rest of a session. A door constant, not an + * authorable key: no metadata author or caller sets it. + */ +export const ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS = 5 * 60_000; + +/** What the person is asked to confirm: the action, the object and the record it runs on. */ +export interface McpActionConfirmationSubject { + /** The declarative action name. */ + actionName: string; + /** The action's label, when its author gave one. */ + actionLabel?: string; + /** The object the action operates on; omitted for object-less actions. */ + objectName?: string; + /** The record the action runs on, when it takes one. */ + recordId?: string; + /** The record's title, when the subject load read one. Never the id restated. */ + recordTitle?: string; +} + +/** The person's answer to an elicited confirmation, as the door read it. */ +export type McpActionConfirmationAnswer = 'accept' | 'decline' | 'cancel' | 'timed_out'; + +/** + * Ask the person, in their client, to confirm one call. Resolves to the + * answer; never rejects (a failure to ask is a `cancel`). + */ +export type McpActionConfirmationElicitor = (subject: McpActionConfirmationSubject) => Promise; + +/** + * What the action tools hand the bridge beside the request: the door's own + * channel for this call, never anything the caller sent. Passed only when the + * call can be elicited; a bridge reads its absence as "hand off". + */ +export interface McpActionCallDoor { + /** Ask the person in their client (step 1); see {@link actionConfirmationElicitorFor}. */ + elicitConfirmation: McpActionConfirmationElicitor; +} + +/** + * The result shape this door reads: `action` and nothing else. Loose on + * purpose, unlike the SDK's own `ElicitResultSchema`, which also parses + * `content` — a client's form payload is not read (step 3.1), so a payload the + * SDK would refuse must not turn a person's `accept` into a failure. + */ +const ElicitedActionSchema = z.looseObject({ action: z.enum(['accept', 'decline', 'cancel']) }); + +/** A confirmation asks for nothing but the answer: an empty form. */ +const EMPTY_FORM = { type: 'object', properties: {} } as const; + +/** `'X' (x)`, or `x` alone when the label is the name or absent. */ +function named(name: string, label: string | undefined): string { + return label && label !== name ? `'${label}' (${name})` : `'${name}'`; +} + +/** + * The question the person reads: the action, the object and the record it + * runs on (its id, and its title when the subject load read one), and what + * each answer does. + */ +export function actionConfirmationQuestion(subject: McpActionConfirmationSubject): string { + const on = subject.objectName ? ` on ${subject.objectName}` : ''; + const record = subject.recordId + ? ` record ${subject.recordTitle !== undefined && subject.recordTitle !== '' ? `'${subject.recordTitle}' (id ${subject.recordId})` : `id ${subject.recordId}`}` + : ''; + return `Your AI assistant asks to run the action ${named(subject.actionName, subject.actionLabel)}${on}${record}. ` + + 'Its author requires your confirmation before it runs. Accept runs it once, as you; decline refuses it. ' + + 'Nothing has run yet.'; +} + +/** + * The elicitor for the tool call `extra` belongs to, or `undefined` when this + * call cannot be elicited: the client did not advertise form-mode + * `elicitation` at `initialize` on this server (an empty `elicitation: {}` + * reads as form mode, MCP 2025-11-25, normalised by the SDK), which is always + * the case on the per-request Streamable HTTP server. + * + * The request rides the tool call (`extra.sendRequest` relates it to the open + * call), is bounded by `timeoutMs`, and is abandoned when the tool call is + * cancelled (`extra.signal`). + */ +export function actionConfirmationElicitorFor( + server: McpServer, + extra: RequestHandlerExtra | undefined, + timeoutMs: number = ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS, +): McpActionConfirmationElicitor | undefined { + const capability = server.server.getClientCapabilities()?.[AI_ACTION_CONFIRMATION_CAPABILITY]; + if (!capability?.form || typeof extra?.sendRequest !== 'function') return undefined; + return async (subject) => { + try { + const result = await extra.sendRequest( + { + method: 'elicitation/create', + params: { mode: 'form', message: actionConfirmationQuestion(subject), requestedSchema: EMPTY_FORM }, + }, + ElicitedActionSchema, + { timeout: timeoutMs, signal: extra.signal }, + ); + return result.action; + } catch (error) { + // Asked first: the SDK rejects an ABORTED request with a + // `RequestTimeout` error too, and the call's signal aborts both when + // the client cancels the tool call and when the connection closes. + if (extra.signal?.aborted) return 'cancel'; + return error instanceof McpError && error.code === ErrorCode.RequestTimeout ? 'timed_out' : 'cancel'; + } + }; +} diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index d73edea572c..9792fdc2348 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -55,6 +55,18 @@ export type { RegisterActionToolsOptions, McpFederationBridge, } from './mcp-http-tools.js'; +// [#33712] Step 1 of the amended confirmation contract: the person asked in their client. +export { + ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS, + actionConfirmationElicitorFor, + actionConfirmationQuestion, +} from './action-confirmation-elicitation.js'; +export type { + McpActionCallDoor, + McpActionConfirmationAnswer, + McpActionConfirmationElicitor, + McpActionConfirmationSubject, +} from './action-confirmation-elicitation.js'; // The portable `SKILL.md` distributable (ADR-0036 Amendment C) — NOT the // `skill` metadata type; that one is projected onto MCP prompts just below. export { diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 0a178bb2360..45388c68eee 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -125,6 +125,7 @@ import { } from './metadata-completeness.js'; // [#30892] The file seam and what `read_file` renders from it. import { READ_FILE_MAX_BYTES, ReadFileExtractionBusyError, renderReadFile, type McpFileBridge } from './file-content.js'; +import { actionConfirmationElicitorFor, type McpActionCallDoor } from './action-confirmation-elicitation.js'; export interface McpObjectSummary { name: string; @@ -435,6 +436,11 @@ export interface McpActionBridge { * the host hands it to the person and resolves to the contract's * `ActionConfirmationPending` (`status: 'pending_confirmation'`), which the * tool relays as its successful result; the request's `confirm` is not read. + * [#33712] When the tool passes `door` (the client advertised + * `elicitation` on a door that can carry a request to it), the host asks + * the person through `door.elicitConfirmation` first, once every admission + * gate has passed: `accept` runs the call, any other answer refuses it, and + * nothing is handed off. Without `door` the call is handed off as above. */ runAction( name: string, @@ -449,6 +455,7 @@ export interface McpActionBridge { recordId?: string; params?: Record; } & AIActionConfirmation, + door?: McpActionCallDoor, ): Promise; /** * [#30771] The capability refusal `runAction` would throw for an action on @@ -475,7 +482,9 @@ export interface McpActionBridge { * pauses on its next screen comes back paused again. Throws on refusal, with * the ADR-0112 `code` / `status` on the thrown value. [#33690] A resume of a * gated action resolves to `ActionConfirmationPending` instead, as - * {@link runAction} does, and the run stays parked. + * {@link runAction} does, and the run stays parked. [#33712] `door` as on + * {@link runAction}: an elicited `accept` resumes the run, any other + * answer refuses it and the run stays parked. * * OPTIONAL, like {@link McpDataBridge.aggregate}. A host that cannot resume * runs omits it, and `resume_run` is then not registered. @@ -483,6 +492,7 @@ export interface McpActionBridge { resumeRun?( runId: string, input: { values?: Record } & AIActionConfirmation, + door?: McpActionCallDoor, ): Promise; } @@ -3379,6 +3389,11 @@ export function registerActionTools( 'Nothing has run then; do not retry, tell the user to approve it. Where the server cannot hand it off, ' + 'the call is refused ACTION_CONFIRMATION_REQUIRED (details.reason "no_confirmation_service"): the user ' + 'performs the action in the app. ' + + // [#33712] Step 1: a client that supports elicitation is asked in place. + 'When your client supports elicitation and this connection can carry it, the user is asked in your ' + + 'client instead: accept runs the action once; decline, dismissing it or no answer in time refuses it ' + + '(ACTION_CONFIRMATION_REQUIRED, details.reason "declined", "cancelled" or "timed_out"); do not retry ' + + 'unless the user asks. ' + // [ADR-0151 D3 rule 3] An AI service account is refused, never handed off. 'Under an AI service account\'s own key (an agent acting for itself, for no person) the call is ' + 'refused whatever it sends and nothing runs: hand the action to a person, or its author declares ' + @@ -3470,7 +3485,7 @@ export function registerActionTools( // is further surfaced via `requiresConfirmation` in list_actions. annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, }, - async (args) => { + async (args, extra) => { const { recordId, params } = args; let { actionName, objectName, namespace } = args; // Read off the constant, so the member's spelling has exactly one @@ -3509,7 +3524,7 @@ export function registerActionTools( return errorResult(systemObjectActionRefusal(actionName, objectName)); } } - const result = await bridge.runAction(actionName, { + const request = { objectName, // [ADR-0150 D5] Forwarded only when given: a call that names no // namespace reaches the bridge exactly as before. @@ -3520,7 +3535,15 @@ export function registerActionTools( // key above are the two halves of one change: dropping either one // restores the strip that made the gate unsatisfiable. [AI_ACTION_CONFIRMATION_MEMBER]: confirm, - }); + }; + // [#33712] Step 1 of the amended confirmation contract: a client that + // advertised `elicitation` on a server that read its `initialize` (the + // stdio door) is asked in place. Otherwise the bridge is called + // exactly as before and hands a gated call off. + const elicitConfirmation = actionConfirmationElicitorFor(server, extra); + const result = elicitConfirmation + ? await bridge.runAction(actionName, request, { elicitConfirmation }) + : await bridge.runAction(actionName, request); return textResult(result); } catch (err) { return landedWriteResultOrError( @@ -3560,7 +3583,9 @@ export function registerActionTools( 'change that: it is handed to the person you act for, who approves or rejects it in the app, and you ' + 'are answered status "pending_confirmation" with a pendingId; the run stays paused until they ' + 'approve. Where the server cannot hand it off, the call is refused ACTION_CONFIRMATION_REQUIRED and ' + - 'the run stays paused. Under an AI service account\'s own key the call is refused ' + + 'the run stays paused. When your client supports elicitation and this connection can carry it, the ' + + 'user is asked in your client instead: accept continues the run; any other answer refuses the call ' + + 'and the run stays paused. Under an AI service account\'s own key the call is refused ' + 'whatever it sends and the run stays paused: hand it to a person. A run that fails answers as ' + 'run_action does: tell the user the reason in the second text block, never the flow and node chain ' + 'in the error message.', @@ -3612,18 +3637,23 @@ export function registerActionTools( // as `run_action`: the client should confirm before calling it. annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, }, - async (args) => { + async (args, extra) => { const { runId, values } = args; const confirm = args[AI_ACTION_CONFIRMATION_MEMBER]; if (!runId || typeof runId !== 'string') { return errorResult('runId is required'); } try { - const result = await resumeRun(runId, { + const request = { values, // Forwarded, never rebuilt without it: see `run_action` above. [AI_ACTION_CONFIRMATION_MEMBER]: confirm, - }); + }; + // [#33712] As `run_action`: asked in place where the client can be. + const elicitConfirmation = actionConfirmationElicitorFor(server, extra); + const result = elicitConfirmation + ? await resumeRun(runId, request, { elicitConfirmation }) + : await resumeRun(runId, request); return textResult(result); } catch (err) { return errorResultFromThrown(err, `resume_run ${runId}`); From 9338516ef066ee5d63e4ea565fabffe824cf79bc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 03:44:27 +0000 Subject: [PATCH 2/8] wip(runtime): ask the person in place when the MCP door can elicit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 --- packages/runtime/src/action-dispatch.ts | 49 +++++++- packages/runtime/src/action-execution.ts | 139 ++++++++++++++++++++++- packages/runtime/src/domains/mcp.ts | 37 +++++- 3 files changed, 215 insertions(+), 10 deletions(-) diff --git a/packages/runtime/src/action-dispatch.ts b/packages/runtime/src/action-dispatch.ts index ee9e4978020..fbfc02ee1fe 100644 --- a/packages/runtime/src/action-dispatch.ts +++ b/packages/runtime/src/action-dispatch.ts @@ -160,7 +160,18 @@ export interface ResolvedActionCall { * hand-off's own members (`ActionConfirmationHandOff`). A door without it * (REST, a host's door) keeps the member gate. */ - confirmationHandOff?: { door: string; namespace?: string }; + confirmationHandOff?: { + door: string; + namespace?: string; + /** + * [#33712] The door's channel to the person's client (step 1 of the + * amended contract), present only when the client can be elicited. The + * person is then asked in place, after the same verdict the hand-off + * asks: `accept` dispatches the call as any admitted call, any other + * answer refuses it, and nothing is handed off. + */ + elicitConfirmation?: actionExec.ActionConfirmationElicitor; + }; /** * [ADR-0106 D1] This door's answer for a name nothing declares, where it * is not the sequence's own undeclared `404` ({@link undeclaredActionRefusal}): @@ -277,7 +288,11 @@ export async function runResolvedAction( ): Promise { const admission = await admitResolvedAction(deps, requestContext, call); if ('refused' in admission) return admission; - if (admission.handOff) return handOffAdmittedAction(deps, requestContext, call, admission); + if (admission.handOff) { + const confirmation = await confirmAdmittedAction(deps, requestContext, call, admission); + // [#33712] Only an elicited `accept` falls through to the dispatch. + if (confirmation !== 'accepted') return confirmation; + } const outcome = await dispatchAdmittedAction(deps, requestContext, call, admission); return { admitted: { actionDef: admission.actionDef, objectName: call.objectName, actionName: call.actionName, recordId: admission.recordId }, @@ -301,13 +316,16 @@ interface Admission { * the host's pending-confirmation service (or the `no_confirmation_service` * refusal). Nothing dispatches, and no invocation row is written: the call * did not run. A verdict refusal is the arm's own, rendered as a refusal. + * [#33712] At a door that holds the person's client (`elicitConfirmation`), + * the person is asked there instead, after the same verdict: `'accepted'` + * sends the caller on to the dispatch, any other answer is the refusal. */ -async function handOffAdmittedAction( +async function confirmAdmittedAction( deps: ActionExecutionDeps, requestContext: HttpProtocolContext, call: ResolvedActionCall, admission: Admission, -): Promise { +): Promise { const { objectName, wiring } = call; const { actionDef, recordId, params, subject } = admission; const subjectRecordId = recordId === undefined || recordId === null || recordId === '' ? undefined : String(recordId); @@ -321,8 +339,29 @@ async function handOffAdmittedAction( return { refused: { message: thrown.message, status: thrown.status, details: { code: thrown.code } } }; } const handOff = call.confirmationHandOff!; + const actionName = typeof actionDef?.name === 'string' && actionDef.name ? actionDef.name : call.actionName; + // [#33712] Step 1: a client that can be elicited is asked in place, after + // the same verdict, and its answer stands: `accept` dispatches, anything + // else refuses. The hand-off below is the step-2 path for every other call. + if (handOff.elicitConfirmation) { + const elicited = await actionExec.elicitActionConfirmation( + handOff.elicitConfirmation, + actionExec.actionConfirmationElicitSubject( + actionDef, actionName, objectName, subjectRecordId, call.declaration?.obj, subject?.record, + ), + ); + if ('accepted' in elicited) return 'accepted'; + const { refused } = elicited; + return { + refused: { + message: refused.message, + status: refused.status, + details: { code: refused.code, ...(refused.details as unknown as Record) }, + }, + }; + } const answer = await actionExec.handOffActionConfirmation(deps, requestContext, wiring.envId, { - actionName: typeof actionDef?.name === 'string' && actionDef.name ? actionDef.name : call.actionName, + actionName, ...(actionExec.isObjectLessActionKey(objectName) ? {} : { objectName }), ...(handOff.namespace !== undefined ? { namespace: handOff.namespace } : {}), ...(subjectRecordId !== undefined ? { recordId: subjectRecordId } : {}), diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index fa5e3071e0d..6c736782324 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -109,6 +109,7 @@ import { reconcileActionRegistrations as reconcileActionRegistrationsPure, resolveActionByPackage, resolveActionHandlerKeys, + resolveRecordTitle, standaloneActionOwnerKey, SummaryRecomputeError, type PackageScopedRefusal, @@ -3258,6 +3259,127 @@ export async function handOffActionConfirmation( }; } +/** + * [#33712] What an MCP door asks the person to confirm (step 1 of the amended + * contract, `AI_ACTION_CONFIRMATION_CAPABILITY`): the action, the object and + * the record it runs on, its id and, when the subject load read one, its + * title. Structurally the `McpActionConfirmationSubject` of `@objectstack/mcp`, + * which this package does not depend on. + */ +export interface ActionConfirmationElicitSubject { + actionName: string; + actionLabel?: string; + objectName?: string; + recordId?: string; + recordTitle?: string; +} + +/** [#33712] The person's answer, as the door read it (`McpActionConfirmationAnswer`). */ +export type ActionConfirmationElicitAnswer = 'accept' | 'decline' | 'cancel' | 'timed_out'; + +/** + * [#33712] The door's channel to the person's client for ONE call + * (`McpActionConfirmationElicitor`). Present only when the client can be + * elicited; its absence means "hand off" (step 2), never a refusal. + */ +export type ActionConfirmationElicitor = (subject: ActionConfirmationElicitSubject) => Promise; + +/** + * [#33712] The subject an elicitation names, built from what the admitted + * sequence already holds: the declaration, the object and the record the + * caller-scope subject load read. The title is the object's own + * (`resolveRecordTitle`: its `nameField`, formula or column), and is left out + * rather than replaced by the id when it does not resolve. + */ +export function actionConfirmationElicitSubject( + action: any, + actionName: string, + objectName: string | undefined, + recordId: string | undefined, + obj: unknown, + record: Record | undefined, +): ActionConfirmationElicitSubject { + const label = typeof action?.label === 'string' && action.label !== '' ? action.label : undefined; + let recordTitle: string | undefined; + if (recordId !== undefined && record && Object.keys(record).length > 0) { + try { + recordTitle = resolveRecordTitle(obj, record); + } catch { + // A title that cannot be composed is left out: the id still names the record. + recordTitle = undefined; + } + } + return { + actionName, + ...(label !== undefined ? { actionLabel: label } : {}), + ...(objectName && !isObjectLessActionKey(objectName) ? { objectName } : {}), + ...(recordId !== undefined ? { recordId } : {}), + ...(recordTitle !== undefined && recordTitle !== '' ? { recordTitle } : {}), + }; +} + +/** + * [#33712] Step 1 of the amended contract: ask the person in their client, and + * read the answer as step 4 does. Asked by a door that holds an elicitor, once + * every admission gate has passed (the subject load and its caller-scope + * verdict included) and never for an AI service account, which the + * confirmation step refuses before it gets here. + * + * - `accept`: `{ accepted: true }`; the caller dispatches the call exactly + * once, as any admitted call. Nothing is stored: the next call is asked again. + * - `decline`: refused `428`, `reason: 'declined'`. + * - `cancel` (a dismissal, an error answer, a dropped connection): refused, + * `reason: 'cancelled'`. + * - `timed_out` (no answer within the door's bound): refused, + * `reason: 'timed_out'`. + * + * An elicitor that throws, or answers anything else, reads as `cancel`: + * nothing runs for want of a readable answer. Nothing is handed off on any of + * these answers: the person was asked, and their answer (or their silence) + * stands. + */ +export async function elicitActionConfirmation( + elicit: ActionConfirmationElicitor, + subject: ActionConfirmationElicitSubject, +): Promise<{ accepted: true } | { refused: ActionConfirmationRefusal }> { + let answer: unknown; + try { + answer = await elicit(subject); + } catch { + answer = 'cancel'; + } + if (answer === 'accept') return { accepted: true }; + const on = confirmationSubjectOn(subject.objectName); + const declared = `Action '${subject.actionName}'${on} declares ai.requiresConfirmation: true, so the person was asked to confirm it in their client`; + if (answer === 'decline') { + return { + refused: confirmationRefusalOf( + subject.actionName, subject.objectName, + `${declared}, and they declined — nothing was run. Do not retry unless they ask again.`, + 'declined', + ), + }; + } + if (answer === 'timed_out') { + return { + refused: confirmationRefusalOf( + subject.actionName, subject.objectName, + `${declared}, and no answer arrived in time — nothing was run, and a later answer runs nothing. ` + + 'Retry only when they are there to answer.', + 'timed_out', + ), + }; + } + return { + refused: confirmationRefusalOf( + subject.actionName, subject.objectName, + `${declared}, and the question was dismissed without an answer — nothing was run. ` + + 'Retry only if they ask again.', + 'cancelled', + ), + }; +} + /** * [#33690] The caller-scope subject verdict, as the dispatch arm that would * run `action` reads it, asked BEFORE a hand-off (the amended contract, step @@ -4814,9 +4936,16 @@ export async function invokeBusinessAction(deps: ActionExecutionDeps, // metadata service's `loadMany('action')` is read, as before. readActions?: () => Promise; callData: (action: string, params: any, dataDriver?: any, scopeId?: string, ec?: ExecutionContext) => Promise; + /** + * [#33712] The MCP door's channel to the person's client for this call + * (step 1 of the amended contract), present only when the client can + * be elicited. A declared-gated call is then asked in place instead of + * handed off; see {@link elicitActionConfirmation}. + */ + elicitConfirmation?: ActionConfirmationElicitor; }, ): Promise { - const { driver, envId, ec, getMeta, readObjects, readActions, callData } = wiring; + const { driver, envId, ec, getMeta, readObjects, readActions, callData, elicitConfirmation } = wiring; const meta: any = await getMeta(); const params = input?.params && typeof input.params === 'object' ? input.params : {}; const recordId = typeof input?.recordId === 'string' && input.recordId.length > 0 ? input.recordId : undefined; @@ -4901,7 +5030,13 @@ export async function invokeBusinessAction(deps: ActionExecutionDeps, // [#33690] This door hands a declared-gated call to the person it runs // as: the caller's `confirm` is not passed on, because it never counts // there (the amended contract, `AI_ACTION_CONFIRMATION_CAPABILITY`). - confirmationHandOff: { door: 'mcp', ...(namespace !== undefined ? { namespace } : {}) }, + // [#33712] With the door's elicitor, the person is asked in their + // client first (step 1); the hand-off is then never taken. + confirmationHandOff: { + door: 'mcp', + ...(namespace !== undefined ? { namespace } : {}), + ...(elicitConfirmation ? { elicitConfirmation } : {}), + }, ql: engine, wiring: { ec, envId, driver, callData, diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index 0be1c84eed3..fefb9e12dc9 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -1373,8 +1373,12 @@ export function buildMcpBridge( // [ADR-0150 D5] `namespace` rides through like `confirm`: the whole // request object is forwarded, never rebuilt without it. input: { objectName?: string; namespace?: string; recordId?: string; params?: Record } & AIActionConfirmation, + // [#33712] The door's channel to the person's client, set by the + // tool only when the client can be elicited (`McpActionCallDoor`). + door?: { elicitConfirmation?: actionExec.ActionConfirmationElicitor }, ) => actionExec.invokeBusinessAction(deps, context, name, input ?? {}, { driver, envId, ec, getMeta, readObjects: readServedObjects, readActions: readServedActions, callData, + ...(typeof door?.elicitConfirmation === 'function' ? { elicitConfirmation: door.elicitConfirmation } : {}), }), // [#15705] `resume_run`: continue the caller's own paused screen run. // Admitted by the same gates as `run_action`; see @@ -1382,8 +1386,10 @@ export function buildMcpBridge( resumeRun: async ( runId: string, input: { values?: Record } & AIActionConfirmation, + door?: { elicitConfirmation?: actionExec.ActionConfirmationElicitor }, ) => resumeActionRun(deps, context, runId, input ?? {}, { driver, envId, ec, getMeta, readObjects: readServedObjects, readActions: readServedActions, callData, + ...(typeof door?.elicitConfirmation === 'function' ? { elicitConfirmation: door.elicitConfirmation } : {}), }), // ── Federation surface (McpFederationBridge, #27745) ─────── // The `external-datasource` service Studio's datasource page reaches @@ -1920,9 +1926,11 @@ export async function resumeActionRun( /** [#25297] As `invokeBusinessAction`'s: the standalone `action` items that admit the run. */ readActions?: () => Promise; callData: (action: string, params: any, dataDriver?: any, scopeId?: string, ec?: any) => Promise; + /** [#33712] As `invokeBusinessAction`'s: the person asked in their client, in place of a hand-off. */ + elicitConfirmation?: actionExec.ActionConfirmationElicitor; }, ): Promise { - const { driver, envId, ec, getMeta, readObjects, readActions, callData } = wiring; + const { driver, envId, ec, getMeta, readObjects, readActions, callData, elicitConfirmation } = wiring; if (typeof runId !== 'string' || runId === '') { throw resumeDoorError(deps, 'runId is required', 400); } @@ -2024,7 +2032,28 @@ export async function resumeActionRun( // [#33690] A gated action's resume is handed to the person, after steps 4 // and 5 so nobody is asked to confirm a resume refused anyway: nothing // resumes, the run stays parked, and no invocation row is written. - if (handOff) { + // + // [#33712] Where the person's client can be elicited, they are asked there + // instead, after the same steps: `accept` resumes the run below, as any + // admitted resume; any other answer refuses the call and the run stays + // parked. Nothing is handed off then. + if (handOff && elicitConfirmation) { + const subject = await refuseUnresumableAdmittedRun(deps, automation, runId, { objectName, recordId, driver, envId, ec, callData }); + const elicited = await actionExec.elicitActionConfirmation( + elicitConfirmation, + actionExec.actionConfirmationElicitSubject( + action, + typeof action?.name === 'string' && action.name ? action.name : String(flowName), + objectName, recordId, objectsByName.get(objectName), subject.record, + ), + ); + if ('refused' in elicited) { + throw resumeDoorError(deps, elicited.refused.message, elicited.refused.status, { + code: elicited.refused.code, + ...elicited.refused.details, + }); + } + } else if (handOff) { await refuseUnresumableAdmittedRun(deps, automation, runId, { objectName, recordId, driver, envId, ec, callData }); const answer = await actionExec.handOffActionConfirmation(deps, context, envId, { actionName: typeof action?.name === 'string' && action.name ? action.name : String(flowName), @@ -2122,7 +2151,7 @@ async function refuseUnresumableAdmittedRun( ec: any; callData: (action: string, params: any, dataDriver?: any, scopeId?: string, ec?: any) => Promise; }, -): Promise { +): Promise { const { objectName, recordId, driver, envId, ec, callData } = admitted; // ── 4. the subject record, read again in the caller's own scope ────────── @@ -2140,6 +2169,8 @@ async function refuseUnresumableAdmittedRun( 409, ); } + // [#33712] The subject as read, so an elicitation can name the record by its title. + return subject; } /** From c9c53093784869807dbc8d561b2aba6e57aaa334 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 03:46:56 +0000 Subject: [PATCH 3/8] test: pin the elicit-first confirmation at the MCP action doors Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 --- ...-action-confirmation-handoff-33690.test.ts | 242 ++++++++++++++++++ .../action-confirmation-handoff-33690.test.ts | 156 ++++++++++- 2 files changed, 397 insertions(+), 1 deletion(-) diff --git a/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts b/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts index 73f58b3664f..43366857792 100644 --- a/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts +++ b/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts @@ -18,11 +18,25 @@ */ import { describe, it, expect } from 'vitest'; +import { PassThrough } from 'node:stream'; +import { z } from 'zod'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { ReadBuffer, serializeMessage } from '@modelcontextprotocol/sdk/shared/stdio.js'; +import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; +import { CallToolResultSchema, ElicitRequestSchema, type JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js'; import { AI_ACTION_CONFIRMATION_MEMBER, type ActionConfirmationPending } from '@objectstack/spec/contracts'; import { MCPServerRuntime } from './mcp-server-runtime.js'; import type { McpDataBridge, McpActionBridge } from './mcp-http-tools.js'; +import { + ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS, + actionConfirmationElicitorFor, + type McpActionCallDoor, +} from './action-confirmation-elicitation.js'; const GATED = 'archive_account'; @@ -132,3 +146,231 @@ describe('[#33690] run_action and resume_run relay a hand-off as the call\'s suc } }); }); + +// --------------------------------------------------------------------------- +// [#33712] Step 1 of the amended contract: the person asked in their client. +// --------------------------------------------------------------------------- + +/** The client half of a stdio pipe: newline-delimited JSON-RPC over two streams, the framing the server reads. */ +class PipeClientTransport implements Transport { + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + private readonly buffer = new ReadBuffer(); + constructor(private readonly toServer: PassThrough, private readonly fromServer: PassThrough) {} + async start(): Promise { + this.fromServer.on('data', (chunk: Buffer) => { + this.buffer.append(chunk); + for (let message = this.buffer.readMessage(); message; message = this.buffer.readMessage()) this.onmessage?.(message); + }); + } + async send(message: JSONRPCMessage): Promise { + this.toServer.write(serializeMessage(message)); + } + async close(): Promise { + this.onclose?.(); + } +} + +type Elicited = { action: 'accept' | 'decline' | 'cancel'; content?: Record } | 'never' | Error; + +/** + * A real SDK client on the long-lived server's stdio transport, advertising + * `elicitation: {}` (form mode) or nothing, and answering each + * `elicitation/create` with `answer`. + */ +async function openStdioClient(server: McpServer, opts: { elicitation: boolean; answer?: Elicited }) { + const toServer = new PassThrough(); + const fromServer = new PassThrough(); + await server.connect(new StdioServerTransport(toServer, fromServer)); + const client = new Client( + { name: 'confirm-test-client', version: '1.0.0' }, + { capabilities: opts.elicitation ? { elicitation: {} } : {} }, + ); + const asked: any[] = []; + if (opts.elicitation) { + client.setRequestHandler(ElicitRequestSchema, async (request) => { + asked.push(request.params); + const answer = opts.answer ?? { action: 'cancel' }; + if (answer === 'never') return new Promise(() => {}); + if (answer instanceof Error) throw answer; + return answer; + }); + } + await client.connect(new PipeClientTransport(toServer, fromServer)); + return { client, asked }; +} + +/** A bridge double for the stdio door: runs the step-1 half the runtime owns, through whatever `door` the tool handed it. */ +function elicitingBridge() { + const calls: Array<{ tool: string; door: McpActionCallDoor | undefined; argCount: number }> = []; + const confirmWith = async (door: McpActionCallDoor | undefined, name: string) => { + if (!door) return pendingOf(1); + const answer = await door.elicitConfirmation({ + actionName: name, actionLabel: 'Archive Account', objectName: 'account', recordId: 'a1', recordTitle: 'Acme', + }); + if (answer === 'accept') return { ok: true, action: name, objectName: 'account', recordId: 'a1', result: { ran: true } }; + const reason = { decline: 'declined', cancel: 'cancelled', timed_out: 'timed_out' }[answer]; + throw Object.assign(new Error(`refused: ${reason}`), { + code: 'ACTION_CONFIRMATION_REQUIRED', status: 428, + details: { actionName: name, objectName: 'account', confirmationMember: AI_ACTION_CONFIRMATION_MEMBER, reason }, + }); + }; + const bridge = { + ...makeBridge('service'), + calls, + async runAction(name: string, _input: any, door?: McpActionCallDoor) { + // eslint-disable-next-line prefer-rest-params + calls.push({ tool: 'run_action', door, argCount: arguments.length }); + return confirmWith(door, name); + }, + async resumeRun(_runId: string, _input: any, door?: McpActionCallDoor) { + // eslint-disable-next-line prefer-rest-params + calls.push({ tool: 'resume_run', door, argCount: arguments.length }); + return confirmWith(door, GATED); + }, + }; + return bridge; +} + +async function stdioCall(opts: { elicitation: boolean; answer?: Elicited }, tool: 'run_action' | 'resume_run' = 'run_action') { + const runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' }); + const bridge = elicitingBridge(); + runtime.bridgeDataTools(bridge); + const { client, asked } = await openStdioClient(runtime.server, opts); + const args = tool === 'run_action' ? { actionName: GATED, recordId: 'a1' } : { runId: 'run_1', values: { reason: 'x' } }; + const result = await client.request({ method: 'tools/call', params: { name: tool, arguments: args } }, CallToolResultSchema); + await client.close(); + return { result: result as any, asked, calls: bridge.calls }; +} + +describe('[#33712] stdio: a client that advertises elicitation is asked in place by run_action and resume_run', () => { + it('accept: one elicitation/create in form mode naming the action, the object and the record; the action runs', async () => { + const { result, asked, calls } = await stdioCall({ elicitation: true, answer: { action: 'accept' } }); + expect(result.isError).toBeFalsy(); + expect(JSON.parse(result.content[0].text)).toMatchObject({ ok: true, action: GATED, result: { ran: true } }); + expect(asked).toHaveLength(1); + expect(asked[0].mode).toBe('form'); + expect(asked[0].requestedSchema).toEqual({ type: 'object', properties: {} }); + for (const named of [`'Archive Account' (${GATED})`, 'account', "'Acme'", 'id a1']) expect(asked[0].message).toContain(named); + expect(calls).toHaveLength(1); + expect(typeof calls[0].door?.elicitConfirmation).toBe('function'); + }); + + it('accept with a form payload the door does not read still runs: only the result\'s action is read', async () => { + const { result } = await stdioCall({ elicitation: true, answer: { action: 'accept', content: { note: 'yes' } } }); + expect(JSON.parse(result.content[0].text)).toMatchObject({ ok: true }); + }); + + for (const [answer, reason] of [ + [{ action: 'decline' } as const, 'declined'], + [{ action: 'cancel' } as const, 'cancelled'], + [new Error('the user closed the dialog'), 'cancelled'], + ] as const) { + const label = answer instanceof Error ? 'an error answer' : answer.action; + it(`${label}: refused 428 ACTION_CONFIRMATION_REQUIRED, reason ${reason}`, async () => { + const { result, asked } = await stdioCall({ elicitation: true, answer }); + expect(asked).toHaveLength(1); + expect(result.isError).toBe(true); + const envelope = JSON.parse(result.content[0].text); + expect({ code: envelope.error.code, status: envelope.error.status }).toEqual({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); + expect(envelope.error.details.reason).toBe(reason); + }); + } + + it('resume_run: accept continues the run, decline refuses it', async () => { + const accepted = await stdioCall({ elicitation: true, answer: { action: 'accept' } }, 'resume_run'); + expect(JSON.parse(accepted.result.content[0].text)).toMatchObject({ ok: true }); + expect(accepted.asked).toHaveLength(1); + const declined = await stdioCall({ elicitation: true, answer: { action: 'decline' } }, 'resume_run'); + expect(JSON.parse(declined.result.content[0].text).error.details.reason).toBe('declined'); + }); + + it('a client WITHOUT the capability is never asked: the bridge is called exactly as before and hands off', async () => { + const { result, calls } = await stdioCall({ elicitation: false }); + expect(result.isError).toBeFalsy(); + expect(JSON.parse(result.content[0].text)).toEqual(pendingOf(1)); + expect(calls).toEqual([{ tool: 'run_action', door: undefined, argCount: 2 }]); + }); +}); + +describe('[#33712] Streamable HTTP: the per-request server never read the client\'s initialize, so its callers are handed off', () => { + const INIT = { + jsonrpc: '2.0', id: 0, method: 'initialize', + params: { protocolVersion: '2025-11-25', capabilities: { elicitation: {} }, clientInfo: { name: 'c', version: '1' } }, + }; + + it('a client that advertised elicitation at initialize: the gated call is handed off, answered in one JSON body', async () => { + const runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' }); + const bridge = elicitingBridge(); + const init = await runtime.handleHttpRequest(mcpRequest(INIT), { bridge, parsedBody: INIT }); + expect(init.status).toBe(200); + const body = toolsCall(1, 'run_action', { actionName: GATED, recordId: 'a1' }); + const req = mcpRequest(body); + req.headers.set('mcp-protocol-version', '2025-11-25'); + const res = await runtime.handleHttpRequest(req, { bridge, parsedBody: body }); + expect(res.headers.get('content-type')).toContain('application/json'); + const json: any = await res.json(); + expect(JSON.parse(json.result.content[0].text)).toEqual(pendingOf(1)); + expect(bridge.calls).toEqual([{ tool: 'run_action', door: undefined, argCount: 2 }]); + }); + + it('CONTROL: a non-gated tool call answers plain JSON, no event stream', async () => { + const runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' }); + const body = toolsCall(1, 'list_actions', {}); + const res = await runtime.handleHttpRequest(mcpRequest(body), { bridge: elicitingBridge(), parsedBody: body }); + expect(res.headers.get('content-type')).toContain('application/json'); + expect(((await res.json()) as any).result.isError).toBeFalsy(); + }); +}); + +describe('[#33712] actionConfirmationElicitorFor: the answers a real client can give, the door\'s bound, and a dropped connection', () => { + async function probe(answer: Elicited, opts: { timeoutMs?: number; drop?: boolean } = {}) { + const server = new McpServer({ name: 'probe', version: '1' }); + let settled!: (a: unknown) => void; + const elicited = new Promise((resolve) => { settled = resolve; }); + server.registerTool('probe', { inputSchema: { x: z.string().optional() } }, async (_args, extra) => { + const elicit = actionConfirmationElicitorFor(server, extra, opts.timeoutMs); + const got = elicit ? await elicit({ actionName: 'a', objectName: 'o', recordId: 'r' }) : 'no-elicitor'; + settled(got); + return { content: [{ type: 'text', text: String(got) }] }; + }); + const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); + await server.connect(serverSide); + const client = new Client({ name: 'c', version: '1' }, { capabilities: { elicitation: {} } }); + client.setRequestHandler(ElicitRequestSchema, async () => { + if (opts.drop) { + setTimeout(() => void client.close(), 10); + return new Promise(() => {}); + } + if (answer === 'never') return new Promise(() => {}); + if (answer instanceof Error) throw answer; + return answer; + }); + await client.connect(clientSide); + void client.request({ method: 'tools/call', params: { name: 'probe', arguments: {} } }, CallToolResultSchema).catch(() => {}); + return elicited; + } + + it('the bound is the door\'s constant: five minutes', () => { + expect(ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS).toBe(300_000); + }); + + it('accept, decline and cancel are read off the result', async () => { + expect(await probe({ action: 'accept' })).toBe('accept'); + expect(await probe({ action: 'decline' })).toBe('decline'); + expect(await probe({ action: 'cancel' })).toBe('cancel'); + }); + + it('no answer within the bound: timed_out', async () => { + expect(await probe('never', { timeoutMs: 50 })).toBe('timed_out'); + }); + + it('a connection that drops before an answer: cancel', async () => { + expect(await probe('never', { drop: true })).toBe('cancel'); + }); + + it('an error answer: cancel', async () => { + expect(await probe(new Error('boom'))).toBe('cancel'); + }); +}); diff --git a/packages/runtime/src/action-confirmation-handoff-33690.test.ts b/packages/runtime/src/action-confirmation-handoff-33690.test.ts index a27e7ef4bc9..22e1dfb25a7 100644 --- a/packages/runtime/src/action-confirmation-handoff-33690.test.ts +++ b/packages/runtime/src/action-confirmation-handoff-33690.test.ts @@ -96,7 +96,8 @@ function makeHarness(opts: { service?: unknown } = {}) { return { success: true, status: 'completed', output: {}, durationMs: 1 }; }), }; - const object = { name: OBJECT, label: 'Lead', fields: { status: { type: 'text' }, name: { type: 'text' } }, actions: [GATED, GATED_FLOW, GATED_UPDATE, PLAIN] }; + // `nameField` names the record's title, which an elicitation carries (#33712). + const object = { name: OBJECT, label: 'Lead', nameField: 'name', fields: { status: { type: 'text' }, name: { type: 'text' } }, actions: [GATED, GATED_FLOW, GATED_UPDATE, PLAIN] }; const ql: any = { executeAction: vi.fn(async () => ({ ran: 'script' })), registry: { getObject: () => object, getItem: () => undefined }, @@ -371,3 +372,156 @@ describe('[#33690] CONTROL: the doors outside the amendment keep the member gate expect(refused?.details).not.toHaveProperty('reason'); }); }); + +/** + * [#33712] Step 1 of the amended contract: where the MCP door holds the + * person's client (`door.elicitConfirmation`, passed by the tool only when the + * client advertised `elicitation`), the person is asked there, after the same + * gates the hand-off asks, and never for an AI service account. `accept` runs + * the call once; `decline`, `cancel` and `timed_out` refuse it with their + * contract reasons; nothing is handed off on any answer. + */ +type ElicitAnswer = 'accept' | 'decline' | 'cancel' | 'timed_out'; +function makeElicitor(...answers: Array) { + const queue = [...answers]; + return vi.fn(async (_subject: Record) => { + const next = queue.shift() ?? 'cancel'; + if (next instanceof Error) throw next; + return next; + }); +} + +describe('[#33712] run_action: a client that can be elicited is asked in place, and its answer stands', () => { + it('accept: the call dispatches exactly once, as any admitted call, and nothing is handed off', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const elicitConfirmation = makeElicitor('accept'); + + const answer = await h.bridgeAs(PERSON).runAction( + GATED.name, { recordId: 'lead_1', params: { note: 'stale' } }, { elicitConfirmation }, + ); + + expect(answer).toMatchObject({ ok: true, action: GATED.name, objectName: OBJECT, recordId: 'lead_1' }); + expect(h.ql.executeAction).toHaveBeenCalledTimes(1); + expect(service.submit).not.toHaveBeenCalled(); + // The question names the action, the object and the record: its id, and + // its title, which the caller-scope subject load read. + expect(elicitConfirmation).toHaveBeenCalledTimes(1); + expect(elicitConfirmation.mock.calls[0][0]).toEqual({ + actionName: GATED.name, actionLabel: GATED.label, objectName: OBJECT, recordId: 'lead_1', recordTitle: 'Ada', + }); + }); + + it('an accept covers that one call: the next call is asked again', async () => { + const h = makeHarness({ service: makeConfirmationService() }); + const elicitConfirmation = makeElicitor('accept', 'decline'); + const bridge = h.bridgeAs(PERSON); + await bridge.runAction(GATED.name, { recordId: 'lead_1' }, { elicitConfirmation }); + const refused = await refusalOf(bridge.runAction(GATED.name, { recordId: 'lead_1' }, { elicitConfirmation })); + expect(refused.details).toMatchObject({ reason: 'declined' }); + expect(elicitConfirmation).toHaveBeenCalledTimes(2); + expect(h.ql.executeAction).toHaveBeenCalledTimes(1); + }); + + for (const [answer, reason] of [ + ['decline', 'declined'], + ['cancel', 'cancelled'], + ['timed_out', 'timed_out'], + ] as const) { + it(`${answer}: refused 428 ACTION_CONFIRMATION_REQUIRED, reason ${reason}; nothing runs and nothing is handed off`, async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const refused = await refusalOf(h.bridgeAs(PERSON).runAction( + GATED.name, { recordId: 'lead_1', [AI_ACTION_CONFIRMATION_MEMBER]: true }, { elicitConfirmation: makeElicitor(answer) }, + )); + expect({ code: refused.code, status: refused.status }).toEqual({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); + expect(refused.details).toEqual({ + actionName: GATED.name, objectName: OBJECT, confirmationMember: AI_ACTION_CONFIRMATION_MEMBER, reason, + }); + expect(h.ql.executeAction).not.toHaveBeenCalled(); + expect(service.submit).not.toHaveBeenCalled(); + }); + } + + it('an elicitor that fails reads as a dismissal: reason cancelled, nothing runs', async () => { + const h = makeHarness({ service: makeConfirmationService() }); + const refused = await refusalOf(h.bridgeAs(PERSON).runAction( + GATED.name, { recordId: 'lead_1' }, { elicitConfirmation: makeElicitor(new Error('connection closed')) }, + )); + expect(refused.details).toMatchObject({ reason: 'cancelled' }); + expect(h.ql.executeAction).not.toHaveBeenCalled(); + }); + + it('[ADR-0151 D3 rule 3] an AI service account is refused before anyone is asked: reason service_account', async () => { + const h = makeHarness({ service: makeConfirmationService() }); + const elicitConfirmation = makeElicitor('accept'); + const refused = await refusalOf(h.bridgeAs(ACCOUNT).runAction(GATED.name, { recordId: 'lead_1' }, { elicitConfirmation })); + expect(refused.details).toMatchObject({ reason: 'service_account' }); + expect(elicitConfirmation).not.toHaveBeenCalled(); + expect(h.ql.executeAction).not.toHaveBeenCalled(); + }); + + it('a record the caller cannot read is refused 404 before anyone is asked', async () => { + const h = makeHarness({ service: makeConfirmationService() }); + const elicitConfirmation = makeElicitor('accept'); + const refused = await refusalOf(h.bridgeAs(PERSON).runAction(GATED.name, { recordId: 'lead_2' }, { elicitConfirmation })); + expect({ code: refused.code, status: refused.status }).toEqual({ code: 'RECORD_NOT_FOUND', status: 404 }); + expect(elicitConfirmation).not.toHaveBeenCalled(); + expect(h.ql.executeAction).not.toHaveBeenCalled(); + }); + + it('CONTROL: an action that declares no confirmation runs at once, and nobody is asked', async () => { + const h = makeHarness({ service: makeConfirmationService() }); + const elicitConfirmation = makeElicitor('decline'); + const answer = await h.bridgeAs(PERSON).runAction(PLAIN.name, { recordId: 'lead_1' }, { elicitConfirmation }); + expect(answer).toMatchObject({ ok: true, action: PLAIN.name }); + expect(elicitConfirmation).not.toHaveBeenCalled(); + }); +}); + +describe('[#33712] resume_run: a client that can be elicited is asked in place for the run\'s action', () => { + async function pausedRun(h: ReturnType): Promise { + const started: any = await h.automation.execute(GATED_FLOW.target, { userId: 'u1', object: OBJECT, record: { id: 'lead_1' } }); + h.automation.execute.mockClear(); + return started.runId; + } + + it('accept: the run resumes with the call\'s values, and nothing is handed off', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const runId = await pausedRun(h); + const elicitConfirmation = makeElicitor('accept'); + + const answer = await h.bridgeAs(PERSON).resumeRun(runId, { values: { reason: 'done' } }, { elicitConfirmation }); + + expect(answer).toMatchObject({ ok: true, action: GATED_FLOW.name, objectName: OBJECT }); + expect(h.automation.resume).toHaveBeenCalledTimes(1); + expect(h.automation.resume.mock.calls[0]).toEqual([runId, { variables: { reason: 'done' } }]); + expect(service.submit).not.toHaveBeenCalled(); + expect(elicitConfirmation.mock.calls[0][0]).toMatchObject({ actionName: GATED_FLOW.name, objectName: OBJECT, recordId: 'lead_1' }); + }); + + it('decline: refused, reason declined, and the run stays paused', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const runId = await pausedRun(h); + const refused = await refusalOf(h.bridgeAs(PERSON).resumeRun( + runId, { values: { reason: 'done' } }, { elicitConfirmation: makeElicitor('decline') }, + )); + expect({ code: refused.code, status: refused.status }).toEqual({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); + expect(refused.details).toMatchObject({ actionName: GATED_FLOW.name, objectName: OBJECT, reason: 'declined' }); + expect(h.automation.resume).not.toHaveBeenCalled(); + expect(h.runs.get(runId)?.status).toBe('paused'); + expect(service.submit).not.toHaveBeenCalled(); + }); + + it('[ADR-0151 D3 rule 3] an AI service account\'s resume is refused before anyone is asked', async () => { + const h = makeHarness({ service: makeConfirmationService() }); + const started: any = await h.automation.execute(GATED_FLOW.target, { userId: 'bot_1', object: OBJECT, record: { id: 'lead_1' } }); + const elicitConfirmation = makeElicitor('accept'); + const refused = await refusalOf(h.bridgeAs(ACCOUNT).resumeRun(started.runId, { values: { reason: 'x' } }, { elicitConfirmation })); + expect(refused.details).toMatchObject({ reason: 'service_account' }); + expect(elicitConfirmation).not.toHaveBeenCalled(); + expect(h.automation.resume).not.toHaveBeenCalled(); + }); +}); From c09b8aa5571d0b11a9165c332b4f7ac7f3c985ee Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 03:51:41 +0000 Subject: [PATCH 4/8] chore: changeset for the elicit-first MCP action confirmation Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 --- .../33712-mcp-elicit-action-confirmation.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 .changeset/33712-mcp-elicit-action-confirmation.md diff --git a/.changeset/33712-mcp-elicit-action-confirmation.md b/.changeset/33712-mcp-elicit-action-confirmation.md new file mode 100644 index 00000000000..43911a0ed8a --- /dev/null +++ b/.changeset/33712-mcp-elicit-action-confirmation.md @@ -0,0 +1,19 @@ +--- +'@objectstack/runtime': minor +'@objectstack/mcp': minor +--- + +feat(runtime,mcp): the MCP `run_action` and `resume_run` tools ask the person in their client when it advertises `elicitation` + +Clause-②: no +Metadata-protocol: semantic (at the MCP door, an author's `ai.requiresConfirmation: true` is confirmed in place for a client that advertises `elicitation`. The dev confirms the level against the diff and, if it holds, adds the PR body's `Skills-docs:` line.) +Skills-docs: follow-up owed — skills/objectstack-ai/SKILL.md (the `run_action` row of the MCP tool table; the same row the hand-off follow-up #34210 rewrites) + +This release implements step 1 of the amended confirmation contract (`AI_ACTION_CONFIRMATION_CAPABILITY`, `@objectstack/spec/contracts`) on the long-lived MCP server, the one behind the stdio transport. + +- When the client advertised `elicitation` at `initialize` (an empty `elicitation: {}` reads as form mode), a call on an action whose author declared `ai.requiresConfirmation: true` is asked in place: after every admission gate, the subject load and the caller-scope subject verdict included, the server sends one `elicitation/create` request in form mode, related to the open tool call, naming the action, the object and the record (its id, and its title when the subject load read one). Only the result's `action` is read. +- `accept` runs the call exactly once, as any admitted call, under the caller's permissions; the next call is asked again. `decline` is refused `428 ACTION_CONFIRMATION_REQUIRED` with `details.reason: 'declined'`. `cancel`, an error answer, a tool call cancelled by the client and a connection that closes first are refused with `reason: 'cancelled'`. No answer within the door's bound, `ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS` (five minutes, exported by `@objectstack/mcp`), is refused with `reason: 'timed_out'`, and a later answer runs nothing. Nothing is handed off on any of these answers. +- `resume_run` is asked the same way for the run's action: `accept` resumes the parked run with the call's values; any other answer refuses the call and the run stays paused. +- An AI service account is refused before anyone is asked, as before (`reason: 'service_account'`). +- Unchanged: a client that does not advertise `elicitation` takes the hand-off (or the `no_confirmation_service` refusal) exactly as before, and is never refused for that alone. The Streamable HTTP door builds a fresh server per request that never read the client's `initialize`, so it cannot elicit, and every caller there is handed off as before; its answers stay plain JSON. +- `McpActionBridge.runAction` and `resumeRun` take an optional third argument, `door: { elicitConfirmation }` (`McpActionCallDoor`), which the tools pass only when the call can be elicited. `@objectstack/mcp` also exports `actionConfirmationElicitorFor`, `actionConfirmationQuestion` and the types `McpActionConfirmationSubject`, `McpActionConfirmationAnswer` and `McpActionConfirmationElicitor`. From 3557594b65debd8755e4e2c90385d781706f5540 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 04:41:18 +0000 Subject: [PATCH 5/8] test: drop two inert lint directives Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 --- packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts b/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts index 43366857792..654ac63236e 100644 --- a/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts +++ b/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts @@ -220,12 +220,10 @@ function elicitingBridge() { ...makeBridge('service'), calls, async runAction(name: string, _input: any, door?: McpActionCallDoor) { - // eslint-disable-next-line prefer-rest-params calls.push({ tool: 'run_action', door, argCount: arguments.length }); return confirmWith(door, name); }, async resumeRun(_runId: string, _input: any, door?: McpActionCallDoor) { - // eslint-disable-next-line prefer-rest-params calls.push({ tool: 'resume_run', door, argCount: arguments.length }); return confirmWith(door, GATED); }, From 86f490318cdb0a84a0ae2175b1c0f69fdf7eb65e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 06:56:53 +0000 Subject: [PATCH 6/8] fix(runtime): an elicited accept dispatches on a read taken after the answer Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 --- packages/runtime/src/action-dispatch.ts | 47 ++++++++++++++++++++---- packages/runtime/src/action-execution.ts | 21 ++++------- packages/runtime/src/domains/mcp.ts | 5 +++ 3 files changed, 53 insertions(+), 20 deletions(-) diff --git a/packages/runtime/src/action-dispatch.ts b/packages/runtime/src/action-dispatch.ts index fbfc02ee1fe..76bb29fe4f1 100644 --- a/packages/runtime/src/action-dispatch.ts +++ b/packages/runtime/src/action-dispatch.ts @@ -286,12 +286,22 @@ export async function runResolvedAction( requestContext: HttpProtocolContext, call: ResolvedActionCall, ): Promise { - const admission = await admitResolvedAction(deps, requestContext, call); + let admission = await admitResolvedAction(deps, requestContext, call); if ('refused' in admission) return admission; if (admission.handOff) { const confirmation = await confirmAdmittedAction(deps, requestContext, call, admission); // [#33712] Only an elicited `accept` falls through to the dispatch. if (confirmation !== 'accepted') return confirmation; + // [#33712] The person answered some time after the admission was read. + // The call dispatches on a read taken AFTER the answer: every gate and + // the subject load again, then the caller-scope verdict on that fresh + // subject, exactly as the question was preceded. A refusal there runs + // nothing; the dispatch never sees the read taken before the question. + const fresh = await admitResolvedAction(deps, requestContext, call); + if ('refused' in fresh) return fresh; + const verdict = await subjectVerdictRefusal(deps, requestContext, call, fresh); + if (verdict) return verdict; + admission = fresh; } const outcome = await dispatchAdmittedAction(deps, requestContext, call, admission); return { @@ -320,24 +330,47 @@ interface Admission { * the person is asked there instead, after the same verdict: `'accepted'` * sends the caller on to the dispatch, any other answer is the refusal. */ -async function confirmAdmittedAction( +/** The admitted record id as the hand-off and the question carry it: absent for a record-less call. */ +function subjectRecordIdOf(recordId: unknown): string | undefined { + return recordId === undefined || recordId === null || recordId === '' ? undefined : String(recordId); +} + +/** + * [#33690] The caller-scope subject verdict on an admission, as the dispatch + * arm would read it, rendered as a refusal; `undefined` when the call may go + * on. [#33712] Asked before the person is asked, and again on the read taken + * after an elicited `accept`. + */ +async function subjectVerdictRefusal( deps: ActionExecutionDeps, requestContext: HttpProtocolContext, call: ResolvedActionCall, admission: Admission, -): Promise { +): Promise<{ refused: ActionRefusal } | undefined> { const { objectName, wiring } = call; - const { actionDef, recordId, params, subject } = admission; - const subjectRecordId = recordId === undefined || recordId === null || recordId === '' ? undefined : String(recordId); try { - await actionExec.refuseDeniedSubjectBeforeHandOff(deps, requestContext, actionDef, { - objectName, recordId: subjectRecordId, subject, ec: wiring.ec, envId: wiring.envId, + await actionExec.refuseDeniedSubjectBeforeHandOff(deps, requestContext, admission.actionDef, { + objectName, recordId: subjectRecordIdOf(admission.recordId), subject: admission.subject, ec: wiring.ec, envId: wiring.envId, }); } catch (error) { const thrown = error as Error & { code?: unknown; status?: unknown }; if (typeof thrown?.status !== 'number' || typeof thrown?.code !== 'string') throw error; return { refused: { message: thrown.message, status: thrown.status, details: { code: thrown.code } } }; } + return undefined; +} + +async function confirmAdmittedAction( + deps: ActionExecutionDeps, + requestContext: HttpProtocolContext, + call: ResolvedActionCall, + admission: Admission, +): Promise { + const { objectName, wiring } = call; + const { actionDef, recordId, params, subject } = admission; + const subjectRecordId = subjectRecordIdOf(recordId); + const verdict = await subjectVerdictRefusal(deps, requestContext, call, admission); + if (verdict) return verdict; const handOff = call.confirmationHandOff!; const actionName = typeof actionDef?.name === 'string' && actionDef.name ? actionDef.name : call.actionName; // [#33712] Step 1: a client that can be elicited is asked in place, after diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index 6c736782324..c4970815025 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -109,7 +109,7 @@ import { reconcileActionRegistrations as reconcileActionRegistrationsPure, resolveActionByPackage, resolveActionHandlerKeys, - resolveRecordTitle, + servedRecordTitle, standaloneActionOwnerKey, SummaryRecomputeError, type PackageScopedRefusal, @@ -3287,9 +3287,10 @@ export type ActionConfirmationElicitor = (subject: ActionConfirmationElicitSubje /** * [#33712] The subject an elicitation names, built from what the admitted * sequence already holds: the declaration, the object and the record the - * caller-scope subject load read. The title is the object's own - * (`resolveRecordTitle`: its `nameField`, formula or column), and is left out - * rather than replaced by the id when it does not resolve. + * caller-scope subject load read. The title is the value that read SERVED + * under the object's title pointer (`servedRecordTitle`), never re-derived + * from the row, and is left out rather than replaced by the id when the read + * served none. The door that phrases the question bounds and neutralises it. */ export function actionConfirmationElicitSubject( action: any, @@ -3300,15 +3301,9 @@ export function actionConfirmationElicitSubject( record: Record | undefined, ): ActionConfirmationElicitSubject { const label = typeof action?.label === 'string' && action.label !== '' ? action.label : undefined; - let recordTitle: string | undefined; - if (recordId !== undefined && record && Object.keys(record).length > 0) { - try { - recordTitle = resolveRecordTitle(obj, record); - } catch { - // A title that cannot be composed is left out: the id still names the record. - recordTitle = undefined; - } - } + const recordTitle = recordId !== undefined && record && Object.keys(record).length > 0 + ? servedRecordTitle(obj, record) + : undefined; return { actionName, ...(label !== undefined ? { actionLabel: label } : {}), diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index fefb9e12dc9..534bcec2d33 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -2053,6 +2053,11 @@ export async function resumeActionRun( ...elicited.refused.details, }); } + // The person answered some time after the gates were read: ask the + // admitting action's gates again before the resume below, which reads + // the subject and the screen again itself (`continueAdmittedRun`). + const regated = resumeAdmissionRefusal(deps, admitted, ec, activationEngine); + if (regated instanceof Error) throw regated; } else if (handOff) { await refuseUnresumableAdmittedRun(deps, automation, runId, { objectName, recordId, driver, envId, ec, callData }); const answer = await actionExec.handOffActionConfirmation(deps, context, envId, { From ee1b4ede2c5adebeccef187a99ec11a515630eb8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:06:07 +0000 Subject: [PATCH 7/8] fix(mcp): the confirmation question carries bounded single-line values, the record id on a line of its own Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 --- .../src/action-confirmation-elicitation.ts | 68 +++++++++++++--- packages/mcp/src/index.ts | 3 + ...-action-confirmation-handoff-33690.test.ts | 78 ++++++++++++++++++- .../action-confirmation-handoff-33690.test.ts | 51 +++++++++++- 4 files changed, 185 insertions(+), 15 deletions(-) diff --git a/packages/mcp/src/action-confirmation-elicitation.ts b/packages/mcp/src/action-confirmation-elicitation.ts index 020c67ae746..729eed6cb05 100644 --- a/packages/mcp/src/action-confirmation-elicitation.ts +++ b/packages/mcp/src/action-confirmation-elicitation.ts @@ -106,24 +106,72 @@ const ElicitedActionSchema = z.looseObject({ action: z.enum(['accept', 'decline' /** A confirmation asks for nothing but the answer: an empty form. */ const EMPTY_FORM = { type: 'object', properties: {} } as const; -/** `'X' (x)`, or `x` alone when the label is the name or absent. */ -function named(name: string, label: string | undefined): string { - return label && label !== name ? `'${label}' (${name})` : `'${name}'`; +/** The longest free text (a label, a record title) the question carries, in characters. */ +export const ACTION_CONFIRMATION_QUESTION_TEXT_MAX = 80; +/** The longest machine name or record id the question carries, in characters. */ +export const ACTION_CONFIRMATION_QUESTION_ID_MAX = 200; + +/** + * Characters that never reach the person's prompt as themselves: C0 and C1 + * controls (line breaks and tabs included), the Unicode line and paragraph + * separators, and the invisible format characters that reorder or hide text + * (bidirectional controls, zero-width characters, the byte-order mark). + */ +const UNSHOWN = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/gu; +/** Markup and quoting characters a client might render or a reader might take as structure. */ +const MARKUP = /[<>`*_[\]{}|#"\\]/gu; + +/** At most `max` characters (code points), with a visible mark when it was cut. */ +function bounded(text: string, max: number): string { + const chars = Array.from(text); + return chars.length <= max ? text : `${chars.slice(0, max - 1).join('')}…`; +} + +/** + * Free text written by an author or stored on a record (an action label, a + * record title), made safe for one labelled line of the question: every + * unshown character becomes a space, markup characters and double quotes are + * dropped, a single quote becomes a typographic apostrophe, runs of spaces collapse, and the result is bounded. `undefined` + * when nothing readable is left. + */ +export function confirmationQuestionText(text: string | undefined): string | undefined { + if (typeof text !== 'string') return undefined; + const plain = text.replace(UNSHOWN, ' ').replace(MARKUP, '').replace(/'/gu, '\u2019').replace(/\s+/gu, ' ').trim(); + return plain === '' ? undefined : bounded(plain, ACTION_CONFIRMATION_QUESTION_TEXT_MAX); +} + +/** + * A machine name or record id for its own labelled line: kept character for + * character so it still names exactly one record, except that an unshown + * character is shown as U+FFFD, and bounded. + */ +function confirmationQuestionId(id: string): string { + return bounded(id.replace(UNSHOWN, '\ufffd'), ACTION_CONFIRMATION_QUESTION_ID_MAX); } /** * The question the person reads: the action, the object and the record it * runs on (its id, and its title when the subject load read one), and what * each answer does. + * + * One fact per labelled line, in a fixed order, the record id BEFORE the + * title: every value is reduced to a single line first (no value can start a + * line of its own), so the id line is always the one this door wrote, and a + * title cannot pose as another record's id or as the end of the question. */ export function actionConfirmationQuestion(subject: McpActionConfirmationSubject): string { - const on = subject.objectName ? ` on ${subject.objectName}` : ''; - const record = subject.recordId - ? ` record ${subject.recordTitle !== undefined && subject.recordTitle !== '' ? `'${subject.recordTitle}' (id ${subject.recordId})` : `id ${subject.recordId}`}` - : ''; - return `Your AI assistant asks to run the action ${named(subject.actionName, subject.actionLabel)}${on}${record}. ` - + 'Its author requires your confirmation before it runs. Accept runs it once, as you; decline refuses it. ' - + 'Nothing has run yet.'; + const name = confirmationQuestionId(subject.actionName); + const label = confirmationQuestionText(subject.actionLabel); + const title = subject.recordId !== undefined ? confirmationQuestionText(subject.recordTitle) : undefined; + const lines = [ + 'Your AI assistant asks to run an action whose author requires your confirmation. Nothing has run yet.', + `Action: ${label && label !== name ? `${label} (${name})` : name}`, + ...(subject.objectName ? [`Object: ${confirmationQuestionId(subject.objectName)}`] : []), + ...(subject.recordId !== undefined ? [`Record id: ${confirmationQuestionId(subject.recordId)}`] : []), + ...(title !== undefined ? [`Record title: ${title}`] : []), + 'Accept runs it once, as you. Decline refuses it.', + ]; + return lines.join('\n'); } /** diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index 9792fdc2348..663bb7c4f48 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -58,8 +58,11 @@ export type { // [#33712] Step 1 of the amended confirmation contract: the person asked in their client. export { ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS, + ACTION_CONFIRMATION_QUESTION_ID_MAX, + ACTION_CONFIRMATION_QUESTION_TEXT_MAX, actionConfirmationElicitorFor, actionConfirmationQuestion, + confirmationQuestionText, } from './action-confirmation-elicitation.js'; export type { McpActionCallDoor, diff --git a/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts b/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts index 654ac63236e..d5578b94d1b 100644 --- a/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts +++ b/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts @@ -34,7 +34,9 @@ import { MCPServerRuntime } from './mcp-server-runtime.js'; import type { McpDataBridge, McpActionBridge } from './mcp-http-tools.js'; import { ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS, + ACTION_CONFIRMATION_QUESTION_TEXT_MAX, actionConfirmationElicitorFor, + actionConfirmationQuestion, type McpActionCallDoor, } from './action-confirmation-elicitation.js'; @@ -250,7 +252,10 @@ describe('[#33712] stdio: a client that advertises elicitation is asked in place expect(asked).toHaveLength(1); expect(asked[0].mode).toBe('form'); expect(asked[0].requestedSchema).toEqual({ type: 'object', properties: {} }); - for (const named of [`'Archive Account' (${GATED})`, 'account', "'Acme'", 'id a1']) expect(asked[0].message).toContain(named); + const lines = String(asked[0].message).split('\n'); + for (const line of [`Action: Archive Account (${GATED})`, 'Object: account', 'Record id: a1', 'Record title: Acme']) { + expect(lines).toContain(line); + } expect(calls).toHaveLength(1); expect(typeof calls[0].door?.elicitConfirmation).toBe('function'); }); @@ -323,7 +328,7 @@ describe('[#33712] Streamable HTTP: the per-request server never read the client }); describe('[#33712] actionConfirmationElicitorFor: the answers a real client can give, the door\'s bound, and a dropped connection', () => { - async function probe(answer: Elicited, opts: { timeoutMs?: number; drop?: boolean } = {}) { + async function probe(answer: Elicited, opts: { timeoutMs?: number; drop?: boolean; lateAcceptMs?: number; cancelCall?: boolean } = {}) { const server = new McpServer({ name: 'probe', version: '1' }); let settled!: (a: unknown) => void; const elicited = new Promise((resolve) => { settled = resolve; }); @@ -336,7 +341,15 @@ describe('[#33712] actionConfirmationElicitorFor: the answers a real client can const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); await server.connect(serverSide); const client = new Client({ name: 'c', version: '1' }, { capabilities: { elicitation: {} } }); + const call = new AbortController(); client.setRequestHandler(ElicitRequestSchema, async () => { + if (opts.cancelCall) { + setTimeout(() => call.abort('the user stopped the tool call'), 10); + return new Promise(() => {}); + } + if (opts.lateAcceptMs !== undefined) { + return new Promise((resolve) => setTimeout(() => resolve({ action: 'accept' }), opts.lateAcceptMs)); + } if (opts.drop) { setTimeout(() => void client.close(), 10); return new Promise(() => {}); @@ -346,7 +359,8 @@ describe('[#33712] actionConfirmationElicitorFor: the answers a real client can return answer; }); await client.connect(clientSide); - void client.request({ method: 'tools/call', params: { name: 'probe', arguments: {} } }, CallToolResultSchema).catch(() => {}); + void client.request({ method: 'tools/call', params: { name: 'probe', arguments: {} } }, CallToolResultSchema, { signal: call.signal }) + .catch(() => {}); return elicited; } @@ -371,4 +385,62 @@ describe('[#33712] actionConfirmationElicitorFor: the answers a real client can it('an error answer: cancel', async () => { expect(await probe(new Error('boom'))).toBe('cancel'); }); + + it('an accept that arrives after the bound is not read: the question already answered timed_out', async () => { + expect(await probe('never', { timeoutMs: 50, lateAcceptMs: 150 })).toBe('timed_out'); + // The late answer lands on no pending request; nothing settles twice. + await new Promise((resolve) => setTimeout(resolve, 200)); + }); + + it('a tool call the client cancels while the question is open: cancel', async () => { + expect(await probe('never', { cancelCall: true })).toBe('cancel'); + }); +}); + +describe('[#33712] actionConfirmationQuestion: the record is named by its id on a line no value can imitate', () => { + const base = { actionName: 'archive_account', objectName: 'account', recordId: 'a1' }; + const UNSHOWN = /[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u2028\u2029\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/u; + + it('a hostile title (a line break, a fake id, quotes, markup, invisible characters, length) is reduced to one bounded line after the id', () => { + const recordTitle = 'Acme"\nRecord id: a9\r\n(id a9) ok `x` \u202eevil\u200b ' + 'z'.repeat(500); + const question = actionConfirmationQuestion({ ...base, actionLabel: 'Archive\n"now"', recordTitle }); + const lines = question.split('\n'); + expect(lines.filter((l) => l.startsWith('Record id:'))).toEqual(['Record id: a1']); + const titleLines = lines.filter((l) => l.startsWith('Record title:')); + expect(titleLines).toHaveLength(1); + expect(lines.indexOf(titleLines[0])).toBeGreaterThan(lines.indexOf('Record id: a1')); + const title = titleLines[0].slice('Record title: '.length); + expect(Array.from(title).length).toBeLessThanOrEqual(ACTION_CONFIRMATION_QUESTION_TEXT_MAX); + expect(title.endsWith('…')).toBe(true); + expect(question).not.toMatch(UNSHOWN); + expect(question).not.toMatch(/["<>`]/u); + expect(lines).toContain('Action: Archive now (archive_account)'); + }); + + it('an id is kept character for character on its own line; an unshown character in it is shown, never a line break', () => { + const question = actionConfirmationQuestion({ ...base, recordId: 'a1\nRecord title: Safe', recordTitle: 'Acme' }); + const lines = question.split('\n'); + expect(lines.filter((l) => l.startsWith('Record id:'))).toEqual(['Record id: a1\ufffdRecord title: Safe']); + expect(lines.filter((l) => l.startsWith('Record title:'))).toEqual(['Record title: Acme']); + }); + + it('a title with nothing readable left is left out; the id still names the record', () => { + const lines = actionConfirmationQuestion({ ...base, recordTitle: '\u200b\n "' }).split('\n'); + expect(lines).toContain('Record id: a1'); + expect(lines.some((l) => l.startsWith('Record title:'))).toBe(false); + }); +}); + +describe('[#33712] Streamable HTTP: initialize batched with a tool call', () => { + it('is refused by the transport before any tool runs', async () => { + const runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' }); + const bridge = elicitingBridge(); + const batch = [ + { jsonrpc: '2.0', id: 0, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: { elicitation: {} }, clientInfo: { name: 'c', version: '1' } } }, + toolsCall(1, 'run_action', { actionName: GATED, recordId: 'a1' }), + ]; + const res = await runtime.handleHttpRequest(mcpRequest(batch), { bridge, parsedBody: batch }); + expect(res.status).toBe(400); + expect(bridge.calls).toEqual([]); + }); }); diff --git a/packages/runtime/src/action-confirmation-handoff-33690.test.ts b/packages/runtime/src/action-confirmation-handoff-33690.test.ts index 22e1dfb25a7..d1ed2bb0476 100644 --- a/packages/runtime/src/action-confirmation-handoff-33690.test.ts +++ b/packages/runtime/src/action-confirmation-handoff-33690.test.ts @@ -29,7 +29,7 @@ import { describe, it, expect, vi } from 'vitest'; import { ACTION_CONFIRMATION_SERVICE, AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts'; import { HttpDispatcher } from './http-dispatcher.js'; -import { actionConfirmationRefusal } from './action-execution.js'; +import { actionConfirmationElicitSubject, actionConfirmationRefusal } from './action-execution.js'; import { dispatchAction } from './action-dispatch.js'; const OBJECT = 'crm_lead'; @@ -140,7 +140,7 @@ function makeHarness(opts: { service?: unknown } = {}) { }; const viaHost = (ec: unknown, action: string, extra: Record = {}) => dispatchAction(kernel, { executionContext: ec as any, environmentId: 'platform', objectName: OBJECT, actionName: action, ...extra } as any); - return { ql, automation, runs, bridgeAs, viaRest, viaHost }; + return { ql, automation, runs, leads, bridgeAs, viaRest, viaHost }; } async function refusalOf(p: Promise): Promise<{ code: unknown; status: unknown; message: string; details?: any }> { @@ -525,3 +525,50 @@ describe('[#33712] resume_run: a client that can be elicited is asked in place f expect(h.automation.resume).not.toHaveBeenCalled(); }); }); + +describe('[#33712] run_action: an elicited accept dispatches on a read taken after the answer', () => { + it('a record the caller can no longer read when they answer is refused, and nothing runs', async () => { + const h = makeHarness({ service: makeConfirmationService() }); + const elicitConfirmation = vi.fn(async () => { + h.leads[0] = { ...h.leads[0], owner: 'u2' }; + return 'accept' as const; + }); + const refused = await refusalOf(h.bridgeAs(PERSON).runAction(GATED.name, { recordId: 'lead_1' }, { elicitConfirmation })); + expect({ code: refused.code, status: refused.status }).toEqual({ code: 'RECORD_NOT_FOUND', status: 404 }); + expect(elicitConfirmation).toHaveBeenCalledTimes(1); + expect(h.ql.executeAction).not.toHaveBeenCalled(); + }); + + it('a record that changed while the question was open reaches the action as it is now', async () => { + const h = makeHarness({ service: makeConfirmationService() }); + const elicitConfirmation = vi.fn(async () => { + h.leads[0] = { ...h.leads[0], name: 'Ada Lovelace' }; + return 'accept' as const; + }); + await h.bridgeAs(PERSON).runAction(GATED.name, { recordId: 'lead_1' }, { elicitConfirmation }); + expect(h.ql.executeAction).toHaveBeenCalledTimes(1); + const actionContext: any = (h.ql.executeAction.mock.calls[0] as any[])[2]; + expect(actionContext.record).toMatchObject({ id: 'lead_1', name: 'Ada Lovelace' }); + }); +}); + +describe('[#33712] the question names the record by the title its read served', () => { + const SCHEMA = { + name: OBJECT, nameField: 'display_title', + fields: { + name: { name: 'name', type: 'text' }, + display_title: { name: 'display_title', type: 'formula', expression: { dialect: 'cel', source: 'record.name + " (lead)"' } }, + }, + }; + + it('the served value under the title pointer, as served', () => { + const subject = actionConfirmationElicitSubject(GATED, GATED.name, OBJECT, 'lead_1', SCHEMA, { id: 'lead_1', name: 'Ada', display_title: 'Served Title' }); + expect(subject.recordTitle).toBe('Served Title'); + }); + + it('a row the read served without its title has none: the title is never re-derived from the row', () => { + const subject = actionConfirmationElicitSubject(GATED, GATED.name, OBJECT, 'lead_1', SCHEMA, { id: 'lead_1', name: 'Ada' }); + expect(subject).not.toHaveProperty('recordTitle'); + expect(subject.recordId).toBe('lead_1'); + }); +}); From 736e6595ffa1038be087b970ca8590d0a2a6776c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:14:16 +0000 Subject: [PATCH 8/8] test: pin the after-answer read, the served title and the bounded question Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 --- .changeset/33712-mcp-elicit-action-confirmation.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.changeset/33712-mcp-elicit-action-confirmation.md b/.changeset/33712-mcp-elicit-action-confirmation.md index 43911a0ed8a..4a89a85f6ba 100644 --- a/.changeset/33712-mcp-elicit-action-confirmation.md +++ b/.changeset/33712-mcp-elicit-action-confirmation.md @@ -6,14 +6,14 @@ feat(runtime,mcp): the MCP `run_action` and `resume_run` tools ask the person in their client when it advertises `elicitation` Clause-②: no -Metadata-protocol: semantic (at the MCP door, an author's `ai.requiresConfirmation: true` is confirmed in place for a client that advertises `elicitation`. The dev confirms the level against the diff and, if it holds, adds the PR body's `Skills-docs:` line.) +Metadata-protocol: semantic (at the stdio MCP door, an author's `ai.requiresConfirmation: true` is confirmed in place for a client that advertises `elicitation`) Skills-docs: follow-up owed — skills/objectstack-ai/SKILL.md (the `run_action` row of the MCP tool table; the same row the hand-off follow-up #34210 rewrites) This release implements step 1 of the amended confirmation contract (`AI_ACTION_CONFIRMATION_CAPABILITY`, `@objectstack/spec/contracts`) on the long-lived MCP server, the one behind the stdio transport. -- When the client advertised `elicitation` at `initialize` (an empty `elicitation: {}` reads as form mode), a call on an action whose author declared `ai.requiresConfirmation: true` is asked in place: after every admission gate, the subject load and the caller-scope subject verdict included, the server sends one `elicitation/create` request in form mode, related to the open tool call, naming the action, the object and the record (its id, and its title when the subject load read one). Only the result's `action` is read. -- `accept` runs the call exactly once, as any admitted call, under the caller's permissions; the next call is asked again. `decline` is refused `428 ACTION_CONFIRMATION_REQUIRED` with `details.reason: 'declined'`. `cancel`, an error answer, a tool call cancelled by the client and a connection that closes first are refused with `reason: 'cancelled'`. No answer within the door's bound, `ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS` (five minutes, exported by `@objectstack/mcp`), is refused with `reason: 'timed_out'`, and a later answer runs nothing. Nothing is handed off on any of these answers. +- When the client advertised `elicitation` at `initialize` (an empty `elicitation: {}` reads as form mode), a call on an action whose author declared `ai.requiresConfirmation: true` is asked in place: after every admission gate, the subject load and the caller-scope subject verdict included, the server sends one `elicitation/create` request in form mode, related to the open tool call, naming the action, the object and the record (its id, and the title the caller-scope read served, bounded to one line). Only the result's `action` is read. +- `accept` runs the call exactly once, as any admitted call, under the caller's permissions, on the gates and the subject read again after the answer; the next call is asked again. `decline` is refused `428 ACTION_CONFIRMATION_REQUIRED` with `details.reason: 'declined'`. `cancel`, an error answer, a tool call cancelled by the client and a connection that closes first are refused with `reason: 'cancelled'`. No answer within the door's bound, `ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS` (five minutes, exported by `@objectstack/mcp`), is refused with `reason: 'timed_out'`, and a later answer runs nothing. Nothing is handed off on any of these answers. - `resume_run` is asked the same way for the run's action: `accept` resumes the parked run with the call's values; any other answer refuses the call and the run stays paused. - An AI service account is refused before anyone is asked, as before (`reason: 'service_account'`). - Unchanged: a client that does not advertise `elicitation` takes the hand-off (or the `no_confirmation_service` refusal) exactly as before, and is never refused for that alone. The Streamable HTTP door builds a fresh server per request that never read the client's `initialize`, so it cannot elicit, and every caller there is handed off as before; its answers stay plain JSON. -- `McpActionBridge.runAction` and `resumeRun` take an optional third argument, `door: { elicitConfirmation }` (`McpActionCallDoor`), which the tools pass only when the call can be elicited. `@objectstack/mcp` also exports `actionConfirmationElicitorFor`, `actionConfirmationQuestion` and the types `McpActionConfirmationSubject`, `McpActionConfirmationAnswer` and `McpActionConfirmationElicitor`. +- `McpActionBridge.runAction` and `resumeRun` take an optional third argument, `door: { elicitConfirmation }` (`McpActionCallDoor`), which the tools pass only when the call can be elicited. `@objectstack/mcp` also exports `actionConfirmationElicitorFor`, `actionConfirmationQuestion`, `confirmationQuestionText`, the bounds `ACTION_CONFIRMATION_QUESTION_TEXT_MAX` and `ACTION_CONFIRMATION_QUESTION_ID_MAX`, and the types `McpActionConfirmationSubject`, `McpActionConfirmationAnswer` and `McpActionConfirmationElicitor`.