elicitation example

This commit is contained in:
ihrpr 2025-05-20 15:10:40 +01:00 • committed by Basil Hosmer
commit 04cbbfbb0d
No known key found for this signature in database

View file

@ -8,6 +8,9 @@ import {
ClientCapabilities,
CreateMessageRequest,
CreateMessageResultSchema,
ElicitRequest,
ElicitResult,
ElicitResultSchema,
EmptyResultSchema,
Implementation,
InitializedNotificationSchema,
@ -18,6 +21,8 @@ import {
ListRootsRequest,
ListRootsResultSchema,
LoggingMessageNotification,
McpError,
ErrorCode,
Notification,
Request,
ResourceUpdatedNotification,
@ -28,6 +33,7 @@ import {
ServerResult,
SUPPORTED_PROTOCOL_VERSIONS,
} from "../types.js";
import { Ajv } from "ajv";
export type ServerOptions = ProtocolOptions & {
/**
@ -129,6 +135,14 @@ export class Server<
}
break;
case "elicitation/create":
if (!this._clientCapabilities?.elicitation) {
throw new Error(
`Client does not support elicitation (required for ${method})`,
);
}
break;
case "roots/list":
if (!this._clientCapabilities?.roots) {
throw new Error(
@ -294,6 +308,44 @@ export class Server<
);
}
async elicitInput(
params: ElicitRequest["params"],
options?: RequestOptions,
): Promise<ElicitResult> {
const result = await this.request(
{ method: "elicitation/create", params },
ElicitResultSchema,
options,
);
// Validate the response content against the requested schema if action is "accept"
if (result.action === "accept" && result.content) {
try {
const ajv = new Ajv({ strict: false, validateFormats: true });
const validate = ajv.compile(params.requestedSchema);
const isValid = validate(result.content);
if (!isValid) {
throw new McpError(
ErrorCode.InvalidParams,
`Elicitation response content does not match requested schema: ${ajv.errorsText(validate.errors)}`,
);
}
} catch (error) {
if (error instanceof McpError) {
throw error;
}
throw new McpError(
ErrorCode.InternalError,
`Error validating elicitation response: ${error}`,
);
}
}
return result;
}
async listRoots(
params?: ListRootsRequest["params"],
options?: RequestOptions,