mcp-elicitation
Elicitation: MCP SDK v2 user-input rounds, prompt completion, progress, or cancellation.
- License 许可
- MIT
- 最近更新
- 2026-11-15
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- mcp-elicitation
- metadata
- { "category": "technique" }
- description
- Elicitation: MCP SDK v2 user-input rounds, prompt completion, progress, or cancellation.
- user-invocable
- false
03 SKILL.md 正文
MCP Elicitation
Implement mid-call interaction with @modelcontextprotocol/server v2. Reference: https://ts.sdk.modelcontextprotocol.io/v2/
Era gotcha. Modern (2026) handlers return stateless, multi-round inputRequired(...) descriptors; 2025 handlers await blocking elicitInput(). elicitInput() throws on modern connections. With its default legacyShim: true, SDK deliver modern inputRequired(...) returns to 2025 clients by issuing elicitation/create, sampling/createMessage, and roots/list; not enable elicitInput() for modern clients. Progress (notify) and cancellation (signal) work both eras.
Steps
-
Register owned clients before calls: Advertise elicitation capabilities, bound auto-fulfillment with
inputRequired.maxRounds, handleelicitation/createat construction. Client default 10 rounds; past it client rejects withSdkError(INPUT_REQUIRED_ROUNDS_EXCEEDED).const client = new Client( { name: 'client', version: '1.0' }, { capabilities: { elicitation: { form: {} } }, inputRequired: { maxRounds: 10 }, }, ); client.setRequestHandler('elicitation/create', async (req) => { if (req.params.mode === 'url') return { action: 'decline' }; // mode is omitted on older form requests const content = await renderAndValidateJsonSchemaForm( req.params.message, req.params.requestedSchema, ); return content === undefined ? { action: 'decline' } : { action: 'accept', content }; });Host-implemented
renderAndValidateJsonSchemaForm()(not SDK export) renders requested schema, resolves only validated content;undefinedmeans user declined. Add URL capability + owned URL handler only when client can complete that flow.Done: Every owned client serving interaction advertises only supported modes, has bounded handler, returns content validated against requested schema.
-
Make modern tool calls replay-safe: Each answer restarts tool from beginning. Read
ctx.mcpReq.inputResponsesbefore returninginputRequired; useacceptedContent(..., key, schema)for accepted content,inputResponse(...)to exit clean ondeclineorcancel.server.registerTool( 'deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => { const state = inputResponse(ctx.mcpReq.inputResponses, 'confirm'); if (state?.kind === 'elicit' && state.action !== 'accept') { return { content: [{ type: 'text', text: 'Deploy cancelled' }] }; } const confirmed = acceptedContent( ctx.mcpReq.inputResponses, 'confirm', z.object({ confirm: z.boolean() }), )?.confirm; if (confirmed) return { content: [{ type: 'text', text: 'Deployed' }] }; return inputRequired({ inputRequests: { confirm: inputRequired.elicit({ message: 'Deploy?', requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } } }, }), }, }); }, );Use
inputRequired.elicit()for form fields,inputRequired.elicitUrl()for redirects like OAuth. Migrate embedded sampling and roots flows off deprecatedinputRequired.createMessage()andinputRequired.listRoots().Done: Every modern interaction reads prior responses, returns each accepted path once, terminates every decline/cancel path.
-
Carry sequential state in signed
requestState: Return opaque, HMAC-signed state value, read viactx.mcpReq.requestState<State>(). Client round-trips value byte-for-byte — keep secrets out, reject tampered/expired values with-32602 Invalid or expired requestState.const codec = createRequestStateCodec<{ step: string }>({ key: crypto.getRandomValues(new Uint8Array(32)), ttlSeconds: 600, }); const app = new McpServer( { name: 'app', version: '1.0' }, { requestState: { verify: codec.verify } }, ); // Inside a tool handler registered on `app`: return inputRequired({ inputRequests: { scope: inputRequired.elicit({/* … */}) }, requestState: await codec.mint({ step: 'confirmed' }), });Done: Every multi-round flow stores state in verified codec, rejects invalid state before business logic, exposes no secret in payload.
-
Report long work, honor cancellation: Emit strictly increasing
notifications/progressvalues for oneprogressToken. Passctx.mcpReq.signalto DB/HTTP work; checksignal.abortedinside recursive work and loop conditions.async ({ files }, ctx) => { const tok = ctx.mcpReq._meta?.progressToken; for (let i = 0; i < files.length; i++) { if (tok) await ctx.mcpReq.notify({ method: 'notifications/progress', params: { progressToken: tok, progress: i + 1, total: files.length }, }); } return { content: [{ type: 'text', text: 'Done' }] }; };Done: Each long-running path propagates abort signal, checks it during repeated work, emits monotonic progress when caller supplied token.
-
Complete prompt arguments at schema: Wrap prompt
argsSchemafields withcompletable(...). Define resource-template completion in template'scompletemap instead.import { completable } from '@modelcontextprotocol/server'; server.registerPrompt( 'review', { argsSchema: z.object({ lang: completable(z.string(), (val) => ['ts', 'js', 'py'].filter((lang) => lang.startsWith(val)), ), }), }, ({ lang }) => ({ messages: [{ role: 'user', content: { type: 'text', text: `Review ${lang}` } }], }), );Done: Every prompt argument needing completion uses
completable(...), every resource-template variable uses its template completion map. -
Serve confirmed 2025 connections through legacy branch: Require client's
elicitationcapability, use form mode for standard data, URL mode for external redirects, return from handler ondecline/cancel. Keep credentials, API keys out of forms.requestedSchemadefaults JSON Schema 2020-12; declare$schemawhen porting draft-07.ElicitResult.contentin form mode is submitted form fields as object (e.g.{ rating: 5, comment: '…' }) validated againstrequestedSchema— return schema-shaped object.const result = await ctx.mcpReq.elicitInput({ mode: 'form', message: 'Rate topic', requestedSchema: { type: 'object', properties: { rating: { type: 'number' } }, required: ['rating'], }, }); if (result.action === 'accept') { return { content: [{ type: 'text', text: `Recorded: ${JSON.stringify(result.content)}` }] }; }Done: Each legacy-only flow has confirmed 2025 connection, supported client capability, declared schema dialect when needed, valid result content, terminating non-accept path.
-
Retire 2025-only facilities: Replace
ctx.mcpReq.requestSamplingwith server direct-LLM-provider call only after recording provider, data-handling/retention policy, consent path, cost owner; stays functional for 2025 connections but throws for modern ones. Replace deprecatedctx.mcpReq.log(level, data)with stderr or OpenTelemetry.Done: Each direct LLM replacement has recorded provider, privacy/consent, cost decision; new interaction paths use neither sampling nor MCP logging; every retained legacy call isolated to confirmed 2025 branch.
04 同仓库更多 Skills
unslop
Use when writing or editing prose a person will read, or when text sounds AI-generated.
show-me
Use when asked to show, diagram, or walk through how code fits together or what a change does, or before explaining a multi-file flow in prose.
pr
Use when writing or updating a pull request description, or before running `gh pr create`.
commit
Use when writing a commit message, or before running `git commit`.
write-specs
Spec a feature's observable behavior. Use when asked for requirements, when a request says what the system should do but not how, or to capture what a built system already guarantees. Not for how to build it (write-plan).
write-skills
Write, fix, or audit a skill's frontmatter, trigger description, and body. Use when a skill is asked for, never fires, or fires at the wrong moment. Not for a hook (write-hooks) or the plugin manifest and catalog.