Open History to see the last commit
1import type { AuthInfo } from '@modelcontextprotocol/server'
2
3/**
4 * One question for the user.
5 * `message` is the text the user sees.
6 */
7export type ToolInputRequest = {
8 message: string
9}
10
11/**
12 * The prompt for `ctx.context.sample`.
13 * `messages` is the list the model reads.
14 * Each item has `role` and `content`.
15 */
16export type SampleRequest = {
17 messages: ReadonlyArray<{
18 role: string
19 content: string
20 }>
21}
22
23type WaitForInput<TAnswer> = (request: ToolInputRequest) => Promise<TAnswer>
24
25type SampleModel<TSample> = (request: SampleRequest) => Promise<TSample>
26
27/** The error a tool gets when the user declines or cancels an input request. */
28export const inputDeclinedMessage = 'The user did not accept the input request.'
29
30/**
31 * Callbacks for one tool call.
32 *
33 * Era `2025` needs `waitForInput` and `clientSample`.
34 * Era `2026` uses `sample` for the model result.
35 * On a protocol 2026 retry, `inputAnswer` is the answer.
36 * `inputDeclined` is true when the user declined or cancelled the request.
37 */
38export type ServerToolContextOptions<TAnswer, TSample> =
39 | {
40 era: '2025'
41 waitForInput: WaitForInput<TAnswer>
42 clientSample: SampleModel<TSample>
43 sample?: SampleModel<TSample>
44 authInfo?: AuthInfo
45 }
46 | {
47 era: '2026'
48 inputAnswer?: TAnswer
49 inputDeclined?: boolean
50 sample?: SampleModel<TSample>
51 authInfo?: AuthInfo
52 }
53
54/**
55 * The tool stopped because it needs user input.
56 *
57 * `resultType` is `input_required`.
58 * `request` is the object passed to `ctx.context.requestInput`.
59 * Catch this error, then run the tool again with `inputAnswer`.
60 * `ctx.context.requestInput` then returns that answer.
61 *
62 * @param request - The input request from the tool
63 *
64 * @example
65 * try {
66 * await tool(ctx)
67 * } catch (error) {
68 * if (error instanceof ToolInputRequiredError) {
69 * error.request
70 * }
71 * }
72 */
73export class ToolInputRequiredError extends Error {
74 readonly resultType = 'input_required' as const
75
76 constructor(public readonly request: ToolInputRequest) {
77 super(
78 'The tool stopped because it needs input. ' +
79 'Run the tool again with inputAnswer.',
80 )
81 this.name = 'ToolInputRequiredError'
82 }
83}
84
85/**
86 * The runtime context that `createMCPServer` gives a tool on `ctx.context`.
87 *
88 * Pass it as the context type of `.server()`, so `ctx.context.requestInput`
89 * and `ctx.context.sample` type-check.
90 *
91 * @example
92 * ```ts
93 * const askCity = toolDefinition({
94 * name: 'ask_city',
95 * description: 'Ask which city to use',
96 * inputSchema: z.object({}),
97 * }).server<MCPToolContext>(async (_args, ctx) => {
98 * const city = await ctx.context.requestInput({ message: 'Which city?' })
99 * return { city }
100 * })
101 * ```
102 */
103export type MCPToolContext<
104 TContext extends Record<string, unknown> = Record<never, never>,
105> = ReturnType<typeof createServerToolContext> & TContext
106
107/**
108 * Builds the context for one tool call.
109 *
110 * On era `2025`, `requestInput` waits on `waitForInput`.
111 * The same tool call then continues with that answer.
112 * If `inputAnswer` is absent on era `2026`, `requestInput` throws
113 * {@link ToolInputRequiredError}.
114 * If you pass `inputAnswer`, the tool runs again.
115 * Then `requestInput` returns that answer.
116 * If you pass `inputDeclined`, `requestInput` throws an Error instead.
117 * Code before `requestInput` runs on both calls.
118 *
119 * On era `2025`, `sample` calls `clientSample`.
120 * It does not call the `sample` adapter.
121 * On era `2026`, `sample` calls the `sample` adapter.
122 * It does not call `clientSample`.
123 * If `sample` is absent on era `2026`, `ctx.sample` throws an Error.
124 * The error message contains `sample`.
125 *
126 * @param options - The protocol era and the callbacks for that era
127 *
128 * @example
129 * const ctx = createServerToolContext({
130 * era: '2025',
131 * waitForInput: async () => 'Paris',
132 * clientSample: async () => 'A short draft',
133 * })
134 * await ctx.requestInput({ message: 'Which city?' })
135 */
136export function createServerToolContext<TAnswer = unknown, TSample = unknown>(
137 options: ServerToolContextOptions<TAnswer, TSample>,
138) {
139 let asked = false
140 return {
141 /**
142 * The verified token of the caller, from the server `auth` option.
143 * `undefined` when the server has no `auth`, or for
144 * `createMCPClient({ server })`.
145 */
146 authInfo: options.authInfo,
147
148 /**
149 * Asks the user for a value.
150 *
151 * On era `2025`, this waits on `waitForInput` and returns that answer.
152 * If `inputAnswer` is absent on era `2026`, this throws
153 * {@link ToolInputRequiredError}.
154 * If `inputAnswer` is present, this returns that answer.
155 * If the user declined or cancelled, this throws an Error.
156 * On era `2026`, a second call in the same tool call throws an Error.
157 *
158 * @param request - The question for the user
159 */
160 async requestInput(request: ToolInputRequest) {
161 if (options.era === '2025') {
162 return options.waitForInput(request)
163 }
164
165 // The retry carries one answer. A second question would get that same
166 // answer back, so stop the call instead.
167 if (asked) {
168 throw new Error(
169 'ctx.context.requestInput can ask only one question per tool call ' +
170 'on protocol 2026. Split the questions into separate tools.',
171 )
172 }
173 asked = true
174
175 if (options.inputDeclined === true) {
176 throw new Error(inputDeclinedMessage)
177 }
178
179 // No answer yet: this call ends as input required.
180 if (options.inputAnswer === undefined) {
181 throw new ToolInputRequiredError(request)
182 }
183
184 return options.inputAnswer
185 },
186
187 /**
188 * Asks for a model result.
189 *
190 * On era `2025`, this calls `clientSample`.
191 * On era `2026`, this calls the `sample` adapter.
192 * If that adapter is absent, this throws an Error.
193 * The message contains `sample`.
194 *
195 * @param request - The prompt for the model
196 */
197 async sample(request: SampleRequest) {
198 if (options.era === '2025') {
199 return options.clientSample(request)
200 }
201
202 if (options.sample === undefined) {
203 throw new Error(
204 'ctx.context.sample needs the sample adapter on protocol 2026. ' +
205 'Pass sample to createServerToolContext.',
206 )
207 }
208
209 return options.sample(request)
210 },
211 }
212}