src/vs/platform/agentHost/node/claude/claudeElicitation.ts

316 LOC · 303 covered · 13 uncovered · 69 ranges · 394 concepts · 29 introducers · 213 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 > /*--------------------------------------------------------------------------------------------- claudeElicitation.ts ×7
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import type { ElicitationRequest, ElicitationResult } from '@anthropic-ai/claude-agent-sdk';
7 > import type { PrimitiveSchemaDefinition } from '@modelcontextprotocol/sdk/types.js';
8 > import { isObject, isString } from '../../../../base/common/types.js';
9 > import { vArray, vNumber, vObj, vOptionalProp, vString, vUnknown, type ValidatorType } from '../../../../base/common/validation.js';
10 > import { ChatInputAnswerState, ChatInputAnswerValueKind, ChatInputQuestionKind, ChatInputResponseKind, type ChatInputAnswer, type ChatInputOption, type ChatInputQuestion, type ChatInputRequest } from '../../common/state/sessionState.js';
11 >
12 > /**
13 > * Pure projections between the Claude SDK's MCP elicitation request/response
14 > * and the agentHost workbench protocol.
15 > *
16 > * When an MCP server calls `elicit/create`, the SDK invokes
17 > * `Options.onElicitation` with an {@link ElicitationRequest}. The agent surfaces
18 > * it as structured user input (a {@link ChatInputRequest}, the same channel
19 > * `AskUserQuestion` uses — NOT the permission gate) and translates the user's
20 > * answer back into the SDK's {@link ElicitationResult}. This module owns those
21 > * projections so they can be unit-tested without standing up an agent.
22 > *
23 > * Unlike the Codex provider — whose `requestedSchema` is a strongly-typed
24 > * generated schema — the Claude SDK delivers `requestedSchema` as an untyped
25 > * `Record<string, unknown>`. Each field is runtime-validated with the base-layer
26 > * {@link vObj} validator ({@link vElicitationField}), which drops malformed
27 > * fields instead of mis-projecting or throwing. The field type is *derived* from
28 > * that validator (not hand-rolled) and cross-checked against the MCP SDK's
29 > * authoritative {@link PrimitiveSchemaDefinition} by
30 > * {@link _assertElicitationFieldCoversSchema} (which catches an incompatible
31 > * reshape of a covered field, though not a purely additive new variant). The
32 > * base-layer validator is used rather than the SDK's own zod schema because this
33 > * module is loaded by the unit-test renderer, where a runtime
34 > * `@modelcontextprotocol/sdk` import does not resolve (all SDK runtime access
35 > * goes through `IClaudeAgentSdkService`).
36 > */
37 >
38 > /** Value the SDK accepts back for a single elicited field. */
39 > type ElicitationFieldValue = NonNullable<ElicitationResult['content']>[string];
40 >
41 > /** A `{ const, title? }` option, shared by `oneOf` and array `items.anyOf`. */
42 > const vTitledOption = vObj({ const: vString(), title: vOptionalProp(vString()) });
43 >
44 > /**
45 > * Lenient runtime validator for a single elicitation schema field. Structure is
46 > * validated (a present `enum` must be a string array, `minimum` a number, …) so
47 > * a malformed field is dropped rather than mis-projected; value-level
48 > * constraints (e.g. `format`, `type`) stay permissive so real-world schema
49 > * variation still renders. {@link IElicitationField} is derived from this, and
50 > * {@link _assertElicitationFieldCoversSchema} pins it to the MCP SDK's
51 > * {@link PrimitiveSchemaDefinition}.
52 > */
53 > const vElicitationField = vObj({
54 > type: vOptionalProp(vString()),
55 > title: vOptionalProp(vString()),
56 > description: vOptionalProp(vString()),
57 > format: vOptionalProp(vString()),
58 > default: vOptionalProp(vUnknown()),
59 > minimum: vOptionalProp(vNumber()),
60 > maximum: vOptionalProp(vNumber()),
61 > minLength: vOptionalProp(vNumber()),
62 > maxLength: vOptionalProp(vNumber()),
63 > minItems: vOptionalProp(vNumber()),
64 > maxItems: vOptionalProp(vNumber()),
65 > enum: vOptionalProp(vArray(vString())),
66 > enumNames: vOptionalProp(vArray(vString())),
67 > oneOf: vOptionalProp(vArray(vTitledOption)),
68 > items: vOptionalProp(vObj({
69 > enum: vOptionalProp(vArray(vString())),
70 > anyOf: vOptionalProp(vArray(vTitledOption)),
71 > })),
72 > });
73 >
74 > type IElicitationField = ValidatorType<typeof vElicitationField>;
75 >
76 > /**
77 > * Compile-time guard: every member of the MCP SDK's authoritative
78 > * {@link PrimitiveSchemaDefinition} union must be assignable to
79 > * {@link IElicitationField}. This catches an *incompatible reshape* of a field
80 > * we already project (e.g. the SDK retyping `enum` from `string[]` to
81 > * `number[]`) by failing to compile. It does NOT catch purely additive changes
82 > * — a brand-new union member or keyword stays structurally assignable to this
83 > * all-optional view and would be silently ignored by the projection until a
84 > * human notices the new shape. It is type-only: never called, erased at runtime.
85 > */
86 function _assertElicitationFieldCoversSchema(field: PrimitiveSchemaDefinition): IElicitationField {
87 return field;
88 }
90 > /**
91 > * Reshaped, validated view of the `form`-mode `requestedSchema`: the schema's
92 > * `properties` record flattened into ordered `[name, field]` tuples, plus its
93 > * `required` list as a set for O(1) per-field lookup during projection.
94 > */
95 > interface IParsedElicitationSchema {
96 > readonly fields: ReadonlyArray<readonly [string, IElicitationField]>;
97 > readonly required: ReadonlySet<string>;
98 > }
99 >
100 > /**
101 > * Narrow the untyped `requestedSchema` into an ordered list of runtime-validated
102 > * fields plus the required set. Fields that fail {@link vElicitationField}
103 > * validation are dropped. Returns `undefined` when the schema is absent or has no
104 > * usable `properties` object, so the caller can fall back to a message-only
105 > * request.
106 > */
107 > function parseElicitationSchema(schema: unknown): IParsedElicitationSchema | undefined { claudeElicitation.ts ×3
108 > if (!isObject(schema)) {
109 > return undefined; validation.ts ×1
110 > }
111 > const properties = (schema as { properties?: unknown }).properties; claudeElicitation.ts ×3
112 > if (!isObject(properties)) {
113 > return undefined; claudeElicitation.ts ×1
114 > }
115 > const rawRequired = (schema as { required?: unknown }).required; claudeElicitation.ts ×2
116 > const required = new Set<string>(Array.isArray(rawRequired) ? rawRequired.filter(isString) : []); claudeElicitation.ts ×3
117 > const fields: Array<readonly [string, IElicitationField]> = [];
118 > for (const [name, field] of Object.entries(properties)) {
119 > const { content, error } = vElicitationField.validate(field); claudeElicitation.ts ×2
120 > if (!error) {
121 > fields.push([name, content]); claudeElicitation.ts ×1
122 > }
124 > return { fields, required }; claudeElicitation.ts ×2
125 > }
127 > /**
128 > * Build the workbench {@link ChatInputRequest} for an MCP elicitation.
129 > *
130 > * - `url` mode surfaces the URL via {@link ChatInputRequest.url} with no
131 > * questions, driving the renderer's "open URL" affordance.
132 > * - `form` mode projects each field of the requested JSON schema into a
133 > * {@link ChatInputQuestion}. A missing/malformed schema falls back to a
134 > * message-only request so the user can still accept or decline.
135 > */
136 > export function buildElicitationRequest(requestId: string, request: ElicitationRequest): ChatInputRequest {
137 > if (request.mode === 'url') { claudeElicitation.ts ×2
138 > const result: ChatInputRequest = { id: requestId, message: request.message }; claudeElicitation.ts ×2
139 > if (request.url) {
140 > result.url = request.url; claudeElicitation.ts ×1
141 > }
142 > return result; claudeElicitation.ts ×2
143 > }
144 > const schema = parseElicitationSchema(request.requestedSchema); claudeElicitation.ts ×1
145 > if (!schema || schema.fields.length === 0) { claudeElicitation.ts ×2
146 > return { id: requestId, message: request.message }; claudeElicitation.ts ×1
147 > }
148 > const questions = schema.fields.map(([name, field]) => elicitationFieldToQuestion(name, field, schema.required.has(name))); claudeElicitation.ts ×7
149 > return { id: requestId, message: request.message, questions };
150 > }
152 > /**
153 > * Build the SDK {@link ElicitationResult} from the client's answers. A declined
154 > * request maps to `decline`, a cancelled/closed request to `cancel`, and an
155 > * accepted request to `accept` with a `content` object keyed by field name
156 > * (omitting skipped/missing answers). `url`-mode acceptances carry no content.
157 > */
158 > export function elicitationResultFromAnswers(
159 > request: ElicitationRequest, claudeElicitation.ts ×2
160 > response: ChatInputResponseKind,
161 > answers: Record<string, ChatInputAnswer> | undefined,
162 > ): ElicitationResult {
163 > if (response === ChatInputResponseKind.Decline) {
164 > return { action: 'decline' }; claudeElicitation.ts ×1
165 > }
166 > if (response !== ChatInputResponseKind.Accept) { claudeElicitation.ts ×1
167 > return { action: 'cancel' }; claudeElicitation.ts ×1
168 > }
169 > const schema = request.mode === 'url' ? undefined : parseElicitationSchema(request.requestedSchema); claudeElicitation.ts ×2
170 > if (!schema) {
171 > return { action: 'accept' }; claudeElicitation.ts ×1
172 > }
173 > // Field names come from an untrusted schema and may be `__proto__` or another claudeElicitation.ts ×7
174 > // inherited key, so read answers with `Object.hasOwn` and materialize the
175 > // content via `Object.fromEntries` (define semantics) so such a name lands as
176 > // an own data property instead of mutating the prototype or being dropped.
177 > const entries: [string, ElicitationFieldValue][] = [];
178 > for (const [name, field] of schema.fields) {
179 > const answer = answers && Object.hasOwn(answers, name) ? answers[name] : undefined;
180 > const value = elicitationAnswerToValue(field, answer);
181 > if (value !== undefined) {
182 > entries.push([name, value]); claudeElicitation.ts ×3
183 > }
185 > return { action: 'accept', content: Object.fromEntries(entries) };
186 > }
188 > /** Cancel result used when there is no session to route the elicitation to. */
189 > export function cancelledElicitationResult(): ElicitationResult {
190 > return { action: 'cancel' }; claudeElicitation.ts ×1
191 > }
193 > /**
194 > * Project a single narrowed schema field into a {@link ChatInputQuestion}. The
195 > * schema's property key becomes the stable question id (the key the answer map
196 > * is later read back by). Unknown/missing types fall back to a plain text field.
197 > */
198 > function elicitationFieldToQuestion(id: string, field: IElicitationField, required: boolean): ChatInputQuestion { claudeElicitation.ts ×7
199 > const base = { id, title: field.title ?? id, message: field.description ?? field.title ?? id, required };
200 >
201 > switch (field.type) {
202 > case 'boolean':
203 > return { ...base, kind: ChatInputQuestionKind.Boolean, defaultValue: typeof field.default === 'boolean' ? field.default : undefined }; claudeElicitation.ts ×3
204 > case 'number': claudeElicitation.ts ×7
205 > case 'integer':
206 > return { claudeElicitation.ts ×4
207 > ...base,
208 > kind: field.type === 'integer' ? ChatInputQuestionKind.Integer : ChatInputQuestionKind.Number,
209 > min: field.minimum,
210 > max: field.maximum,
211 > defaultValue: typeof field.default === 'number' ? field.default : undefined,
212 > };
213 > case 'array': claudeElicitation.ts ×7
214 > return { claudeElicitation.ts ×4
215 > ...base,
216 > kind: ChatInputQuestionKind.MultiSelect,
217 > // MCP enum arrays are strict — only the declared options are valid —
218 > // but the workbench defaults an omitted `allowFreeformInput` to true.
219 > allowFreeformInput: false,
220 > options: field.items?.anyOf
221 > ? field.items.anyOf.map((o): ChatInputOption => ({ id: o.const, label: o.title || o.const })) claudeElicitation.ts ×1
222 > : (field.items?.enum ?? []).map((v): ChatInputOption => ({ id: v, label: v })), claudeElicitation.ts ×3
223 > min: field.minItems, claudeElicitation.ts ×4
224 > max: field.maxItems,
225 > };
226 > case 'string': claudeElicitation.ts ×7
227 > default:
228 > // Titled single-select (`oneOf`), enum/legacy single-select (`enum`,
229 > // optionally `enumNames`), or a plain text field. MCP enums are strict,
230 > // so free-form input is disabled for the select variants.
231 > if (field.oneOf) {
232 > return { claudeElicitation.ts ×3
233 > ...base,
234 > kind: ChatInputQuestionKind.SingleSelect,
235 > allowFreeformInput: false,
236 > options: field.oneOf.map((o): ChatInputOption => ({ id: o.const, label: o.title || o.const })),
237 > };
238 > }
239 > if (field.enum) { claudeElicitation.ts ×7
240 > const names = field.enumNames; claudeElicitation.ts ×4
241 > return {
242 > ...base,
243 > kind: ChatInputQuestionKind.SingleSelect,
244 > allowFreeformInput: false,
245 > options: field.enum.map((v, i): ChatInputOption => ({ id: v, label: names?.[i] || v })),
246 > };
247 > }
248 > return { claudeElicitation.ts ×7
249 > ...base,
250 > kind: ChatInputQuestionKind.Text,
251 > format: field.format,
252 > min: field.minLength,
253 > max: field.maxLength,
254 > defaultValue: typeof field.default === 'string' ? field.default : undefined,
255 > };
256 > }
257 > }
259 > /**
260 > * Project a single {@link ChatInputAnswer} back into the raw value the SDK
261 > * expects for the given field, coercing to the field's declared type. This is
262 > * schema-aware because the workbench renders number/integer/boolean questions as
263 > * text inputs (no dedicated widget) and returns them as {@link ChatInputAnswer}
264 > * text values, so `"3"` / `"false"` must be coerced back to `3` / `false` to
265 > * satisfy the requested schema. Skipped/missing/uncoercible answers return
266 > * `undefined` so the caller omits them from the content object.
267 > */
268 > function elicitationAnswerToValue(field: IElicitationField, answer: ChatInputAnswer | undefined): ElicitationFieldValue | undefined { claudeElicitation.ts ×7
269 > if (!answer || answer.state === ChatInputAnswerState.Skipped) {
270 > return undefined; claudeElicitation.ts ×1
271 > }
272 > const { value } = answer; claudeElicitation.ts ×3
273 > switch (field.type) {
274 > case 'boolean':
275 > if (value.kind === ChatInputAnswerValueKind.Boolean) { claudeElicitation.ts ×5
276 > return value.value; claudeElicitation.ts ×3
277 > }
278 > if (value.kind === ChatInputAnswerValueKind.Text) { claudeElicitation.ts ×3
279 > if (value.value === 'true') { return true; }
280 > if (value.value === 'false') { return false; }
281 > }
282 return undefined;
283 > case 'number': claudeElicitation.ts ×7
284 > case 'integer': {
285 > const n = value.kind === ChatInputAnswerValueKind.Number claudeElicitation.ts ×5
286 > ? value.value claudeElicitation.ts ×3
287 > : value.kind === ChatInputAnswerValueKind.Text && value.value.trim() !== '' claudeElicitation.ts ×3
288 > ? Number(value.value)
289 : undefined;
290 > if (n === undefined || !Number.isFinite(n)) { claudeElicitation.ts ×5
291 > return undefined; claudeElicitation.ts ×3
292 > }
293 > return field.type === 'integer' ? Math.trunc(n) : n; claudeElicitation.ts ×5
294 > }
295 > case 'array': claudeElicitation.ts ×7
296 > if (value.kind === ChatInputAnswerValueKind.SelectedMany) { claudeElicitation.ts ×3
297 > return [...value.value, ...(value.freeformValues ?? [])];
298 > }
299 if (value.kind === ChatInputAnswerValueKind.Selected) {
300 return value.value ? [value.value, ...(value.freeformValues ?? [])] : [...(value.freeformValues ?? [])];
301 }
302 if (value.kind === ChatInputAnswerValueKind.Text) {
303 return value.value ? [value.value] : [];
304 }
305 return undefined;
306 > case 'string': claudeElicitation.ts ×7
307 > default:
308 > if (value.kind === ChatInputAnswerValueKind.Text) { claudeElicitation.ts ×3
309 > return value.value; claudeElicitation.ts ×1
310 > }
311 > if (value.kind === ChatInputAnswerValueKind.Selected) { claudeElicitation.ts ×5
312 > return value.value;
313 > }
314 return undefined;
316 > }