|
1 | | -import { AnyZodObject, ZodLiteral, ZodObject, z } from "zod"; |
| 1 | +import { AnyZodObject, ZodLiteral, ZodObject, ZodOptional, z } from "zod"; |
2 | 2 | import { |
| 3 | + BaseRequestParamsSchema, |
3 | 4 | ErrorCode, |
4 | 5 | JSONRPCError, |
5 | 6 | JSONRPCNotification, |
@@ -312,18 +313,42 @@ export class Protocol< |
312 | 313 | /** |
313 | 314 | * Registers a handler to invoke when this protocol object receives a request with the given method. |
314 | 315 | * |
| 316 | + * The handler receives a second callback parameter that can be used to emit progress notifications. |
| 317 | + * |
315 | 318 | * Note that this will replace any previous request handler for the same method. |
316 | 319 | */ |
317 | 320 | setRequestHandler< |
318 | 321 | T extends ZodObject<{ |
319 | 322 | method: ZodLiteral<string>; |
| 323 | + params: ZodOptional<typeof BaseRequestParamsSchema>; |
320 | 324 | }>, |
321 | 325 | >( |
322 | 326 | requestSchema: T, |
323 | | - handler: (request: z.infer<T>) => SendResultT | Promise<SendResultT>, |
| 327 | + handler: ( |
| 328 | + request: z.infer<T>, |
| 329 | + progress: (progress: Progress) => void, |
| 330 | + ) => SendResultT | Promise<SendResultT>, |
324 | 331 | ): void { |
325 | | - this._requestHandlers.set(requestSchema.shape.method.value, (request) => |
326 | | - Promise.resolve(handler(requestSchema.parse(request))), |
| 332 | + this._requestHandlers.set( |
| 333 | + requestSchema.shape.method.value, |
| 334 | + async (request) => { |
| 335 | + const parsedRequest = requestSchema.parse(request); |
| 336 | + const progressToken = parsedRequest.params?._meta?.progressToken; |
| 337 | + const progressHandler = |
| 338 | + progressToken !== undefined |
| 339 | + ? (progress: Progress) => |
| 340 | + // Sending directly on the transport to avoid typing conflicts |
| 341 | + this._transport |
| 342 | + ?.send({ |
| 343 | + jsonrpc: "2.0", |
| 344 | + method: "notifications/progress", |
| 345 | + params: { ...progress, progressToken }, |
| 346 | + }) |
| 347 | + .catch((error: Error) => this._onerror(error)) |
| 348 | + : () => {}; |
| 349 | + |
| 350 | + return handler(parsedRequest, progressHandler); |
| 351 | + }, |
327 | 352 | ); |
328 | 353 | } |
329 | 354 |
|
|
0 commit comments