Skip to content

Commit 231026e

Browse files
committed
Make it easy to issue progress notifications from request handlers
Resolves #34.
1 parent 822c451 commit 231026e

File tree

2 files changed

+30
-5
lines changed

2 files changed

+30
-5
lines changed

src/shared/protocol.ts

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import { AnyZodObject, ZodLiteral, ZodObject, z } from "zod";
1+
import { AnyZodObject, ZodLiteral, ZodObject, ZodOptional, z } from "zod";
22
import {
3+
BaseRequestParamsSchema,
34
ErrorCode,
45
JSONRPCError,
56
JSONRPCNotification,
@@ -312,18 +313,42 @@ export class Protocol<
312313
/**
313314
* Registers a handler to invoke when this protocol object receives a request with the given method.
314315
*
316+
* The handler receives a second callback parameter that can be used to emit progress notifications.
317+
*
315318
* Note that this will replace any previous request handler for the same method.
316319
*/
317320
setRequestHandler<
318321
T extends ZodObject<{
319322
method: ZodLiteral<string>;
323+
params: ZodOptional<typeof BaseRequestParamsSchema>;
320324
}>,
321325
>(
322326
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>,
324331
): 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+
},
327352
);
328353
}
329354

src/types.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ export const ProgressTokenSchema = z.union([z.string(), z.number().int()]);
1515
*/
1616
export const CursorSchema = z.string();
1717

18-
const BaseRequestParamsSchema = z
18+
export const BaseRequestParamsSchema = z
1919
.object({
2020
_meta: z.optional(
2121
z

0 commit comments

Comments
 (0)