Skip to content

Commit 85fde8c

Browse files
authored
feat(core): rework form when conditions (#35115)
1 parent c167bde commit 85fde8c

8 files changed

Lines changed: 716 additions & 92 deletions

File tree

‎packages/client/src/promise/generated/types.ts‎

Lines changed: 275 additions & 55 deletions
Large diffs are not rendered by default.

‎packages/core/src/form.ts‎

Lines changed: 60 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ export type Info = typeof Info.Type
1616
export const Field = Form.Field
1717
export type Field = Form.Field
1818

19+
export const When = Form.When
20+
export type When = Form.When
21+
1922
export const State = Form.State
2023
export type State = typeof State.Type
2124

@@ -56,6 +59,10 @@ export class InvalidAnswerError extends Schema.TaggedErrorClass<InvalidAnswerErr
5659
message: Schema.String,
5760
}) {}
5861

62+
export class InvalidFormError extends Schema.TaggedErrorClass<InvalidFormError>()("Form.InvalidFormError", {
63+
message: Schema.String,
64+
}) {}
65+
5966
export type CreateInput =
6067
| (Omit<Form.FormInfo, "id"> & { readonly id?: ID })
6168
| (Omit<Form.UrlInfo, "id"> & { readonly id?: ID })
@@ -70,8 +77,8 @@ export interface ListInput {
7077
}
7178

7279
export interface Interface {
73-
readonly create: (input: CreateInput) => Effect.Effect<Info, AlreadyExistsError>
74-
readonly ask: (input: CreateInput) => Effect.Effect<State, AlreadyExistsError>
80+
readonly create: (input: CreateInput) => Effect.Effect<Info, AlreadyExistsError | InvalidFormError>
81+
readonly ask: (input: CreateInput) => Effect.Effect<State, AlreadyExistsError | InvalidFormError>
7582
readonly get: (id: ID) => Effect.Effect<Info, NotFoundError>
7683
readonly list: (input?: ListInput) => Effect.Effect<ReadonlyArray<Info>>
7784
readonly state: (id: ID) => Effect.Effect<State, NotFoundError>
@@ -113,6 +120,10 @@ export const layer = Layer.effect(
113120
const id = input.id ?? ID.create()
114121
const existing = yield* Cache.getSuccess(forms, id)
115122
if (Option.isSome(existing)) return yield* new AlreadyExistsError({ id })
123+
if (input.mode === "form") {
124+
const invalid = validateFields(input.fields)
125+
if (invalid) return yield* new InvalidFormError({ message: invalid })
126+
}
116127
const base = {
117128
id,
118129
sessionID: input.sessionID,
@@ -218,20 +229,63 @@ function validateAnswer(form: Info, answer: Answer) {
218229
}
219230
for (const field of form.fields) {
220231
const value = answer[field.key]
232+
const active = isActive(field, answer)
221233
if (value === undefined) {
222-
if (field.required && isActive(field, answer)) return `Missing required form field: ${field.key}`
234+
if (field.required && active) return `Missing required form field: ${field.key}`
223235
continue
224236
}
237+
if (!active) return `Form field is not active: ${field.key}`
225238
const invalid = validateField(field, value)
226239
if (invalid) return invalid
227240
}
228241
}
229242

230243
function isActive(field: Form.Field, answer: Answer) {
231244
if (!field.when) return true
232-
const value = answer[field.when.key]
233-
if (field.when.op === "eq") return value === field.when.value
234-
return value !== field.when.value
245+
return field.when.every((when) => matches(when, answer[when.key]))
246+
}
247+
248+
// An unanswered referenced field makes the condition false for both ops. Combined with inactive
249+
// fields being unanswerable, this cascades: hiding a field falsifies every condition referencing it.
250+
function matches(when: Form.When, value: Form.Value | undefined) {
251+
if (value === undefined) return false
252+
const hit = Array.isArray(value) ? value.some((item) => item === when.value) : value === when.value
253+
return when.op === "eq" ? hit : !hit
254+
}
255+
256+
// Create-time validation of `when` references: each condition must point at an earlier field,
257+
// carry a value matching that field's type, and use a declared option when the field's options
258+
// are closed. Rejecting these at creation surfaces authoring mistakes to the caller instead of
259+
// silently never matching.
260+
function validateFields(fields: ReadonlyArray<Form.Field>) {
261+
const earlier = new Map<string, Form.Field>()
262+
for (const field of fields) {
263+
if (earlier.has(field.key)) return `Duplicate form field key: ${field.key}`
264+
for (const when of field.when ?? []) {
265+
const target = earlier.get(when.key)
266+
if (!target) return `Form field condition must reference an earlier field: ${field.key} -> ${when.key}`
267+
const invalid = validateWhen(when, target)
268+
if (invalid) return `${invalid}: ${field.key} -> ${when.key}`
269+
}
270+
earlier.set(field.key, field)
271+
}
272+
}
273+
274+
function validateWhen(when: Form.When, target: Form.Field) {
275+
if (target.type === "boolean") {
276+
if (typeof when.value !== "boolean") return "Form field condition value must be a boolean"
277+
return
278+
}
279+
if (target.type === "number" || target.type === "integer") {
280+
if (typeof when.value !== "number") return "Form field condition value must be a number"
281+
return
282+
}
283+
// string and multiselect targets both compare against string values
284+
if (typeof when.value !== "string") return "Form field condition value must be a string"
285+
const closed = target.type === "multiselect" ? !target.custom : target.options !== undefined && !target.custom
286+
if (closed && !target.options?.some((option) => option.value === when.value)) {
287+
return "Form field condition value must be one of the field's options"
288+
}
235289
}
236290

237291
function validateField(field: Form.Field, value: Form.Value): string | undefined {

‎packages/core/src/mcp/client.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,13 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/
99
import { UnauthorizedError, type OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"
1010
import {
1111
CallToolResultSchema,
12+
ElicitationCompleteNotificationSchema,
13+
ElicitRequestSchema,
1214
GetPromptResultSchema,
15+
type ElicitRequestFormParams,
16+
type ElicitRequestParams,
17+
type ElicitRequestURLParams,
18+
type ElicitResult,
1319
ListPromptsResultSchema,
1420
ListRootsRequestSchema,
1521
ListToolsResultSchema,
@@ -82,6 +88,22 @@ export interface CallToolResult {
8288
readonly content: ReadonlyArray<CallToolContent>
8389
}
8490

91+
export type ElicitationFormParams = ElicitRequestFormParams
92+
export type ElicitationParams = ElicitRequestParams
93+
export type ElicitationResult = ElicitResult
94+
95+
export interface ElicitationHandler {
96+
readonly create: (input: {
97+
readonly server: string
98+
readonly params: ElicitationParams
99+
readonly signal: AbortSignal
100+
}) => Effect.Effect<ElicitationResult, Error>
101+
readonly complete: (input: {
102+
readonly server: string
103+
readonly elicitationID: ElicitRequestURLParams["elicitationId"]
104+
}) => Effect.Effect<void>
105+
}
106+
85107
export interface LogMessage {
86108
readonly level: LoggingMessageNotification["params"]["level"]
87109
readonly logger?: LoggingMessageNotification["params"]["logger"]
@@ -123,6 +145,7 @@ export const connect = Effect.fnUntraced(function* (
123145
// Only consumed by the remote transport; stdio servers have no auth concept. A provider with no
124146
// stored token (and a no-op redirect) surfaces an UnauthorizedError, which we map to needs_auth.
125147
authProvider?: OAuthClientProvider,
148+
elicitation?: ElicitationHandler,
126149
) {
127150
const transport: Transport = yield* Effect.gen(function* () {
128151
if (config.type === "local") {
@@ -149,6 +172,7 @@ export const connect = Effect.fnUntraced(function* (
149172
{ name: "opencode", version: InstallationVersion },
150173
{
151174
capabilities: {
175+
...(elicitation ? { elicitation: { form: { applyDefaults: true }, url: {} } } : {}),
152176
// https://github.com/anomalyco/opencode/issues/2308
153177
roots: {},
154178
},
@@ -157,6 +181,14 @@ export const connect = Effect.fnUntraced(function* (
157181
client.setRequestHandler(ListRootsRequestSchema, () =>
158182
Promise.resolve({ roots: [{ uri: pathToFileURL(directory).href }] }),
159183
)
184+
if (elicitation) {
185+
client.setRequestHandler(ElicitRequestSchema, (request, extra) =>
186+
Effect.runPromise(elicitation.create({ server, params: request.params, signal: extra.signal })),
187+
)
188+
client.setNotificationHandler(ElicitationCompleteNotificationSchema, (notification) =>
189+
Effect.runPromise(elicitation.complete({ server, elicitationID: notification.params.elicitationId })),
190+
)
191+
}
160192

161193
const exit = yield* Effect.tryPromise({
162194
try: (signal) => client.connect(transport, { timeout: config.timeout?.startup ?? DEFAULT_STARTUP_TIMEOUT, signal }),

‎packages/core/src/mcp/index.ts‎

Lines changed: 144 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@ import { Config } from "../config"
1010
import { ConfigMCP } from "../config/mcp"
1111
import { Credential } from "../credential"
1212
import { EventV2 } from "../event"
13+
import { Form } from "../form"
1314
import { Integration } from "../integration"
1415
import { IntegrationConnection } from "../integration/connection"
1516
import { Location } from "../location"
17+
import { waitForAbort } from "../process"
1618
import { MCPClient } from "./client"
1719
import { MCPOAuth } from "./oauth"
1820

@@ -145,6 +147,10 @@ type ServerEntry = {
145147
integrationID?: Integration.ID
146148
}
147149

150+
// MCP elicitations are Location-scoped, not Session-scoped: the server cannot attribute them to a
151+
// persisted session row, so their forms are owned by this opaque sentinel session identifier.
152+
const GLOBAL_ELICITATION_SESSION_ID = "global"
153+
148154
export interface Interface {
149155
readonly servers: () => Effect.Effect<ServerInfo[]>
150156
readonly tools: () => Effect.Effect<Tool[]>
@@ -175,6 +181,7 @@ export const layer = Layer.effect(
175181
const config = yield* Config.Service
176182
const location = yield* Location.Service
177183
const events = yield* EventV2.Service
184+
const forms = yield* Form.Service
178185
const integration = yield* Integration.Service
179186
const credentials = yield* Credential.Service
180187
const root = yield* Scope.make()
@@ -189,6 +196,7 @@ export const layer = Layer.effect(
189196
)
190197
// Later config files win for duplicate server names; per-server timeout overrides globals.
191198
const runtime = new Map<ServerName, ServerEntry>()
199+
const urlElicitations = new Map<string, Form.ID>()
192200
for (const entry of documents) {
193201
for (const [name, server] of Object.entries(entry.info.mcp?.servers ?? {})) {
194202
runtime.set(ServerName.make(name), {
@@ -308,6 +316,76 @@ export const layer = Layer.effect(
308316
})
309317
})
310318

319+
const elicitation = {
320+
create: (input: {
321+
readonly server: string
322+
readonly params: MCPClient.ElicitationParams
323+
readonly signal: AbortSignal
324+
}) =>
325+
Effect.gen(function* () {
326+
if (input.params.mode === "url") {
327+
const formID = Form.ID.create()
328+
const key = input.server + "\u0000" + input.params.elicitationId
329+
urlElicitations.set(key, formID)
330+
return yield* forms
331+
.ask({
332+
id: formID,
333+
sessionID: GLOBAL_ELICITATION_SESSION_ID,
334+
title: `${input.server} is requesting input`,
335+
metadata: {
336+
kind: "mcp-elicitation",
337+
server: input.server,
338+
elicitationID: input.params.elicitationId,
339+
message: input.params.message,
340+
},
341+
mode: "url",
342+
url: input.params.url,
343+
})
344+
.pipe(
345+
Effect.raceFirst(waitForAbort(input.signal)),
346+
Effect.ensuring(Effect.sync(() => urlElicitations.delete(key))),
347+
Effect.map(
348+
(state): MCPClient.ElicitationResult => ({
349+
action: state.status === "answered" ? "accept" : "cancel",
350+
}),
351+
),
352+
)
353+
}
354+
const params = input.params
355+
return yield* forms
356+
.ask({
357+
sessionID: GLOBAL_ELICITATION_SESSION_ID,
358+
title: `${input.server} is requesting input`,
359+
metadata: { kind: "mcp-elicitation", server: input.server, message: params.message },
360+
mode: "form",
361+
fields: Object.entries(params.requestedSchema.properties).map(([key, property]) =>
362+
toElicitationField(key, property, params.requestedSchema.required?.includes(key) === true),
363+
),
364+
})
365+
.pipe(
366+
Effect.raceFirst(waitForAbort(input.signal)),
367+
Effect.map((state): MCPClient.ElicitationResult => {
368+
if (state.status !== "answered") return { action: "cancel" }
369+
return {
370+
action: "accept",
371+
content: Object.fromEntries(
372+
Object.entries(state.answer).map(
373+
([key, value]): [string, NonNullable<MCPClient.ElicitationResult["content"]>[string]] =>
374+
typeof value === "object" ? [key, Array.from(value)] : [key, value],
375+
),
376+
),
377+
}
378+
}),
379+
)
380+
}),
381+
complete: (input: { readonly server: string; readonly elicitationID: string }) =>
382+
Effect.gen(function* () {
383+
const formID = urlElicitations.get(input.server + "\u0000" + input.elicitationID)
384+
if (!formID) return
385+
yield* forms.reply({ id: formID, answer: {} }).pipe(Effect.ignore)
386+
}),
387+
} satisfies MCPClient.ElicitationHandler
388+
311389
const toTool = (server: ServerName, def: MCPClient.ToolDefinition) =>
312390
new Tool({ server, name: def.name, description: def.description, inputSchema: def.inputSchema })
313391

@@ -396,7 +474,7 @@ export const layer = Layer.effect(
396474
const authProvider = yield* connectProvider(entry)
397475
// List tools as part of connect so a failure here marks the server failed rather than
398476
// leaving it connected with a silently empty tool list and no path to recover.
399-
const result = yield* MCPClient.connect(name, entry.config, location.directory, authProvider).pipe(
477+
const result = yield* MCPClient.connect(name, entry.config, location.directory, authProvider, elicitation).pipe(
400478
Effect.flatMap((connection) => connection.tools().pipe(Effect.map((tools) => ({ connection, tools })))),
401479
Scope.provide(scope),
402480
Effect.exit,
@@ -561,5 +639,69 @@ export const layer = Layer.effect(
561639
export const node = makeLocationNode({
562640
service: Service,
563641
layer,
564-
deps: [Config.node, Location.node, EventV2.node, Integration.node, Credential.node],
642+
deps: [Config.node, Location.node, EventV2.node, Form.node, Integration.node, Credential.node],
565643
})
644+
645+
// Schema `optional` strips undefined-valued properties on encode, so fields can assign
646+
// optional properties directly instead of conditionally spreading them.
647+
function toElicitationField(key: string, property: ElicitationProperty, required: boolean): Form.Field {
648+
// Some servers emit machine titles like "string with format email"; prefer description/key over those.
649+
const machineTitle = /^(boolean|string|number|integer|array|object)(\s+with\b.*|\s+in\b.*)?$/i
650+
const title =
651+
property.title && !machineTitle.test(property.title.trim()) ? property.title : (property.description ?? key)
652+
const base = {
653+
key,
654+
title,
655+
description: property.description === title ? undefined : property.description,
656+
required: required || undefined,
657+
}
658+
switch (property.type) {
659+
case "boolean":
660+
return { ...base, type: "boolean", default: property.default }
661+
case "number":
662+
case "integer":
663+
return {
664+
...base,
665+
type: property.type,
666+
minimum: property.minimum,
667+
maximum: property.maximum,
668+
default: property.default,
669+
}
670+
case "array":
671+
return {
672+
...base,
673+
type: "multiselect",
674+
options:
675+
"anyOf" in property.items
676+
? property.items.anyOf.map((option) => ({ value: option.const, label: option.title }))
677+
: property.items.enum.map((value) => ({ value, label: value })),
678+
custom: false,
679+
minItems: property.minItems,
680+
maxItems: property.maxItems,
681+
default: property.default,
682+
}
683+
case "string": {
684+
const options =
685+
"oneOf" in property
686+
? property.oneOf.map((option) => ({ value: option.const, label: option.title }))
687+
: "enum" in property
688+
? property.enum.map((value, index) => ({
689+
value,
690+
label: ("enumNames" in property ? property.enumNames?.[index] : undefined) ?? value,
691+
}))
692+
: undefined
693+
return {
694+
...base,
695+
type: "string",
696+
format: "format" in property ? property.format : undefined,
697+
minLength: "minLength" in property ? property.minLength : undefined,
698+
maxLength: "maxLength" in property ? property.maxLength : undefined,
699+
default: property.default,
700+
options,
701+
custom: options ? false : undefined,
702+
}
703+
}
704+
}
705+
}
706+
707+
type ElicitationProperty = MCPClient.ElicitationFormParams["requestedSchema"]["properties"][string]

0 commit comments

Comments
 (0)