From 04cbbfbb0d35d4038ac376effed0544a36985415 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Tue, 20 May 2025 15:10:40 +0100 Subject: [PATCH 01/18] elicitation example --- src/client/index.test.ts | 38 +++ src/client/index.ts | 8 + src/examples/client/simpleStreamableHttp.ts | 211 ++++++++++++- src/examples/server/simpleStreamableHttp.ts | 153 +++++++++- src/server/index.test.ts | 313 ++++++++++++++++++++ src/server/index.ts | 52 ++++ src/shared/protocol.test.ts | 2 + src/types.ts | 116 ++++++++ 8 files changed, 891 insertions(+), 2 deletions(-) diff --git a/src/client/index.test.ts b/src/client/index.test.ts index bbfa80fa..abd0c34e 100644 --- a/src/client/index.test.ts +++ b/src/client/index.test.ts @@ -14,6 +14,7 @@ import { ListToolsRequestSchema, CallToolRequestSchema, CreateMessageRequestSchema, + ElicitRequestSchema, ListRootsRequestSchema, ErrorCode, } from "../types.js"; @@ -597,6 +598,43 @@ test("should only allow setRequestHandler for declared capabilities", () => { }).toThrow("Client does not support roots capability"); }); +test("should allow setRequestHandler for declared elicitation capability", () => { + const client = new Client( + { + name: "test-client", + version: "1.0.0", + }, + { + capabilities: { + elicitation: {}, + }, + }, + ); + + // This should work because elicitation is a declared capability + expect(() => { + client.setRequestHandler(ElicitRequestSchema, () => ({ + action: "accept", + content: { + username: "test-user", + confirmed: true, + }, + })); + }).not.toThrow(); + + // This should throw because sampling is not a declared capability + expect(() => { + client.setRequestHandler(CreateMessageRequestSchema, () => ({ + model: "test-model", + role: "assistant", + content: { + type: "text", + text: "Test response", + }, + })); + }).toThrow("Client does not support sampling capability"); +}); + /*** * Test: Type Checking * Test that custom request/notification/result schemas can be used with the Client class. diff --git a/src/client/index.ts b/src/client/index.ts index 98618a17..53ef8c52 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -303,6 +303,14 @@ export class Client< } break; + case "elicitation/create": + if (!this._capabilities.elicitation) { + throw new Error( + `Client does not support elicitation capability (required for ${method})`, + ); + } + break; + case "roots/list": if (!this._capabilities.roots) { throw new Error( diff --git a/src/examples/client/simpleStreamableHttp.ts b/src/examples/client/simpleStreamableHttp.ts index 0328f0d2..63efdd2f 100644 --- a/src/examples/client/simpleStreamableHttp.ts +++ b/src/examples/client/simpleStreamableHttp.ts @@ -14,7 +14,9 @@ import { ListResourcesResultSchema, LoggingMessageNotificationSchema, ResourceListChangedNotificationSchema, + ElicitRequestSchema, } from '../../types.js'; +import { Ajv } from 'ajv'; // Create readline interface for user input const readline = createInterface({ @@ -54,6 +56,7 @@ function printHelp(): void { console.log(' call-tool [args] - Call a tool with optional JSON arguments'); console.log(' greet [name] - Call the greet tool'); console.log(' multi-greet [name] - Call the multi-greet tool with notifications'); + console.log(' collect-info [type] - Test elicitation with collect-user-info tool (contact/preferences/feedback)'); console.log(' start-notifications [interval] [count] - Start periodic notifications'); console.log(' list-prompts - List available prompts'); console.log(' get-prompt [name] [args] - Get a prompt with optional JSON arguments'); @@ -114,6 +117,10 @@ function commandLoop(): void { await callMultiGreetTool(args[1] || 'MCP User'); break; + case 'collect-info': + await callCollectInfoTool(args[1] || 'contact'); + break; + case 'start-notifications': { const interval = args[1] ? parseInt(args[1], 10) : 2000; const count = args[2] ? parseInt(args[2], 10) : 10; @@ -183,15 +190,212 @@ async function connect(url?: string): Promise { console.log(`Connecting to ${serverUrl}...`); try { - // Create a new client + // Create a new client with elicitation capability client = new Client({ name: 'example-client', version: '1.0.0' + }, { + capabilities: { + elicitation: {}, + }, }); client.onerror = (error) => { console.error('\x1b[31mClient error:', error, '\x1b[0m'); } + // Set up elicitation request handler with proper validation + client.setRequestHandler(ElicitRequestSchema, async (request) => { + console.log('\nšŸ”” Elicitation Request Received:'); + console.log(`Message: ${request.params.message}`); + console.log('Requested Schema:'); + console.log(JSON.stringify(request.params.requestedSchema, null, 2)); + + const schema = request.params.requestedSchema; + const properties = schema.properties; + const required = schema.required || []; + + // Set up AJV validator for the requested schema + const ajv = new Ajv({ strict: false, validateFormats: true }); + const validate = ajv.compile(schema); + + let attempts = 0; + const maxAttempts = 3; + + while (attempts < maxAttempts) { + attempts++; + console.log(`\nPlease provide the following information (attempt ${attempts}/${maxAttempts}):`); + + const content: Record = {}; + let inputCancelled = false; + + // Collect input for each field + for (const [fieldName, fieldSchema] of Object.entries(properties)) { + const field = fieldSchema as { + type?: string; + title?: string; + description?: string; + default?: unknown; + enum?: string[]; + minimum?: number; + maximum?: number; + minLength?: number; + maxLength?: number; + format?: string; + }; + + const isRequired = required.includes(fieldName); + let prompt = `${field.title || fieldName}`; + + // Add helpful information to the prompt + if (field.description) { + prompt += ` (${field.description})`; + } + if (field.enum) { + prompt += ` [options: ${field.enum.join(', ')}]`; + } + if (field.type === 'number' || field.type === 'integer') { + if (field.minimum !== undefined && field.maximum !== undefined) { + prompt += ` [${field.minimum}-${field.maximum}]`; + } else if (field.minimum !== undefined) { + prompt += ` [min: ${field.minimum}]`; + } else if (field.maximum !== undefined) { + prompt += ` [max: ${field.maximum}]`; + } + } + if (field.type === 'string' && field.format) { + prompt += ` [format: ${field.format}]`; + } + if (isRequired) { + prompt += ' *required*'; + } + if (field.default !== undefined) { + prompt += ` [default: ${field.default}]`; + } + + prompt += ': '; + + const answer = await new Promise((resolve) => { + readline.question(prompt, (input) => { + resolve(input.trim()); + }); + }); + + // Check for cancellation + if (answer.toLowerCase() === 'cancel' || answer.toLowerCase() === 'c') { + inputCancelled = true; + break; + } + + // Parse and validate the input + try { + if (answer === '' && field.default !== undefined) { + content[fieldName] = field.default; + } else if (answer === '' && !isRequired) { + // Skip optional empty fields + continue; + } else if (answer === '') { + throw new Error(`${fieldName} is required`); + } else { + // Parse the value based on type + let parsedValue: unknown; + + if (field.type === 'boolean') { + parsedValue = answer.toLowerCase() === 'true' || answer.toLowerCase() === 'yes' || answer === '1'; + } else if (field.type === 'number') { + parsedValue = parseFloat(answer); + if (isNaN(parsedValue as number)) { + throw new Error(`${fieldName} must be a valid number`); + } + } else if (field.type === 'integer') { + parsedValue = parseInt(answer, 10); + if (isNaN(parsedValue as number)) { + throw new Error(`${fieldName} must be a valid integer`); + } + } else if (field.enum) { + if (!field.enum.includes(answer)) { + throw new Error(`${fieldName} must be one of: ${field.enum.join(', ')}`); + } + parsedValue = answer; + } else { + parsedValue = answer; + } + + content[fieldName] = parsedValue; + } + } catch (error) { + console.log(`āŒ Error: ${error}`); + // Continue to next attempt + break; + } + } + + if (inputCancelled) { + return { action: 'cancel' }; + } + + // If we didn't complete all fields due to an error, try again + if (Object.keys(content).length !== Object.keys(properties).filter(name => + required.includes(name) || content[name] !== undefined + ).length) { + if (attempts < maxAttempts) { + console.log('Please try again...'); + continue; + } else { + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + } + } + + // Validate the complete object against the schema + const isValid = validate(content); + + if (!isValid) { + console.log('āŒ Validation errors:'); + validate.errors?.forEach(error => { + console.log(` - ${error.instancePath || 'root'}: ${error.message}`); + }); + + if (attempts < maxAttempts) { + console.log('Please correct the errors and try again...'); + continue; + } else { + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + } + } + + // Show the collected data and ask for confirmation + console.log('\nāœ… Collected data:'); + console.log(JSON.stringify(content, null, 2)); + + const confirmAnswer = await new Promise((resolve) => { + readline.question('\nSubmit this information? (yes/no/cancel): ', (input) => { + resolve(input.trim().toLowerCase()); + }); + }); + + + if (confirmAnswer === 'yes' || confirmAnswer === 'y') { + return { + action: 'accept', + content, + }; + } else if (confirmAnswer === 'cancel' || confirmAnswer === 'c') { + return { action: 'cancel' }; + } else if (confirmAnswer === 'no' || confirmAnswer === 'n') { + if (attempts < maxAttempts) { + console.log('Please re-enter the information...'); + continue; + } else { + return { action: 'decline' }; + } + } + } + + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + }); + transport = new StreamableHTTPClientTransport( new URL(serverUrl), { @@ -362,6 +566,11 @@ async function callMultiGreetTool(name: string): Promise { await callTool('multi-greet', { name }); } +async function callCollectInfoTool(infoType: string): Promise { + console.log(`Testing elicitation with collect-user-info tool (${infoType})...`); + await callTool('collect-user-info', { infoType }); +} + async function startNotifications(interval: number, count: number): Promise { console.log(`Starting notification stream: interval=${interval}ms, count=${count || 'unlimited'}`); await callTool('start-notification-stream', { interval, count }); diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index 6c331192..4ef50446 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -5,7 +5,7 @@ import { McpServer } from '../../server/mcp.js'; import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; import { getOAuthProtectedResourceMetadataUrl, mcpAuthMetadataRouter } from '../../server/auth/router.js'; import { requireBearerAuth } from '../../server/auth/middleware/bearerAuth.js'; -import { CallToolResult, GetPromptResult, isInitializeRequest, ReadResourceResult } from '../../types.js'; +import { CallToolResult, GetPromptResult, isInitializeRequest, PrimitiveSchemaDefinition, ReadResourceResult } from '../../types.js'; import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; import { setupAuthServer } from './demoInMemoryOAuthProvider.js'; import { OAuthMetadata } from 'src/shared/auth.js'; @@ -84,6 +84,157 @@ const getServer = () => { } ); + // Register a tool that demonstrates elicitation (user input collection) + // This creates a closure that captures the server instance + server.tool( + 'collect-user-info', + 'A tool that collects user information through elicitation', + { + infoType: z.enum(['contact', 'preferences', 'feedback']).describe('Type of information to collect'), + }, + async ({ infoType }): Promise => { + let message: string; + let requestedSchema: { + type: 'object'; + properties: Record; + required?: string[]; + }; + + switch (infoType) { + case 'contact': + message = 'Please provide your contact information'; + requestedSchema = { + type: 'object', + properties: { + name: { + type: 'string', + title: 'Full Name', + description: 'Your full name', + }, + email: { + type: 'string', + title: 'Email Address', + description: 'Your email address', + format: 'email', + }, + phone: { + type: 'string', + title: 'Phone Number', + description: 'Your phone number (optional)', + }, + }, + required: ['name', 'email'], + }; + break; + case 'preferences': + message = 'Please set your preferences'; + requestedSchema = { + type: 'object', + properties: { + theme: { + type: 'string', + title: 'Theme', + description: 'Choose your preferred theme', + enum: ['light', 'dark', 'auto'], + enumNames: ['Light', 'Dark', 'Auto'], + }, + notifications: { + type: 'boolean', + title: 'Enable Notifications', + description: 'Would you like to receive notifications?', + default: true, + }, + frequency: { + type: 'string', + title: 'Notification Frequency', + description: 'How often would you like notifications?', + enum: ['daily', 'weekly', 'monthly'], + enumNames: ['Daily', 'Weekly', 'Monthly'], + }, + }, + required: ['theme'], + }; + break; + case 'feedback': + message = 'Please provide your feedback'; + requestedSchema = { + type: 'object', + properties: { + rating: { + type: 'integer', + title: 'Rating', + description: 'Rate your experience (1-5)', + minimum: 1, + maximum: 5, + }, + comments: { + type: 'string', + title: 'Comments', + description: 'Additional comments (optional)', + maxLength: 500, + }, + recommend: { + type: 'boolean', + title: 'Would you recommend this?', + description: 'Would you recommend this to others?', + }, + }, + required: ['rating', 'recommend'], + }; + break; + default: + throw new Error(`Unknown info type: ${infoType}`); + } + + try { + // Use the underlying server instance to elicit input from the client + const result = await server.server.elicitInput({ + message, + requestedSchema, + }); + + if (result.action === 'accept') { + return { + content: [ + { + type: 'text', + text: `Thank you! Collected ${infoType} information: ${JSON.stringify(result.content, null, 2)}`, + }, + ], + }; + } else if (result.action === 'decline') { + return { + content: [ + { + type: 'text', + text: `No information was collected. User declined to provide ${infoType} information.`, + }, + ], + }; + } else { + return { + content: [ + { + type: 'text', + text: `Information collection was cancelled by the user.`, + }, + ], + }; + } + } catch (error) { + return { + content: [ + { + type: 'text', + text: `Error collecting ${infoType} information: ${error}`, + }, + ], + }; + } + } + ); + + // Register a simple prompt server.prompt( 'greeting-template', diff --git a/src/server/index.test.ts b/src/server/index.test.ts index 7c0fbc51..ce54247a 100644 --- a/src/server/index.test.ts +++ b/src/server/index.test.ts @@ -10,6 +10,7 @@ import { LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, CreateMessageRequestSchema, + ElicitRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, @@ -267,6 +268,318 @@ test("should respect client capabilities", async () => { await expect(server.listRoots()).rejects.toThrow(/^Client does not support/); }); +test("should respect client elicitation capabilities", async () => { + const server = new Server( + { + name: "test server", + version: "1.0", + }, + { + capabilities: { + prompts: {}, + resources: {}, + tools: {}, + logging: {}, + }, + enforceStrictCapabilities: true, + }, + ); + + const client = new Client( + { + name: "test client", + version: "1.0", + }, + { + capabilities: { + elicitation: {}, + }, + }, + ); + + client.setRequestHandler(ElicitRequestSchema, (params) => ({ + action: "accept", + content: { + username: params.params.message.includes("username") ? "test-user" : undefined, + confirmed: true, + }, + })); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + server.connect(serverTransport), + ]); + + expect(server.getClientCapabilities()).toEqual({ elicitation: {} }); + + // This should work because elicitation is supported by the client + await expect( + server.elicitInput({ + message: "Please provide your username", + requestedSchema: { + type: "object", + properties: { + username: { + type: "string", + title: "Username", + description: "Your username", + }, + confirmed: { + type: "boolean", + title: "Confirm", + description: "Please confirm", + default: false, + }, + }, + required: ["username"], + }, + }), + ).resolves.toEqual({ + action: "accept", + content: { + username: "test-user", + confirmed: true, + }, + }); + + // This should still throw because sampling is not supported by the client + await expect( + server.createMessage({ + messages: [], + maxTokens: 10, + }), + ).rejects.toThrow(/^Client does not support/); +}); + +test("should validate elicitation response against requested schema", async () => { + const server = new Server( + { + name: "test server", + version: "1.0", + }, + { + capabilities: { + prompts: {}, + resources: {}, + tools: {}, + logging: {}, + }, + enforceStrictCapabilities: true, + }, + ); + + const client = new Client( + { + name: "test client", + version: "1.0", + }, + { + capabilities: { + elicitation: {}, + }, + }, + ); + + // Set up client to return valid response + client.setRequestHandler(ElicitRequestSchema, (request) => ({ + action: "accept", + content: { + name: "John Doe", + email: "john@example.com", + age: 30, + }, + })); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + server.connect(serverTransport), + ]); + + // Test with valid response + await expect( + server.elicitInput({ + message: "Please provide your information", + requestedSchema: { + type: "object", + properties: { + name: { + type: "string", + minLength: 1, + }, + email: { + type: "string", + minLength: 1, + }, + age: { + type: "integer", + minimum: 0, + maximum: 150, + }, + }, + required: ["name", "email"], + }, + }), + ).resolves.toEqual({ + action: "accept", + content: { + name: "John Doe", + email: "john@example.com", + age: 30, + }, + }); +}); + +test("should reject elicitation response with invalid data", async () => { + const server = new Server( + { + name: "test server", + version: "1.0", + }, + { + capabilities: { + prompts: {}, + resources: {}, + tools: {}, + logging: {}, + }, + enforceStrictCapabilities: true, + }, + ); + + const client = new Client( + { + name: "test client", + version: "1.0", + }, + { + capabilities: { + elicitation: {}, + }, + }, + ); + + // Set up client to return invalid response (missing required field, invalid age) + client.setRequestHandler(ElicitRequestSchema, (request) => ({ + action: "accept", + content: { + email: "", // Invalid - too short + age: -5, // Invalid age + }, + })); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + server.connect(serverTransport), + ]); + + // Test with invalid response + await expect( + server.elicitInput({ + message: "Please provide your information", + requestedSchema: { + type: "object", + properties: { + name: { + type: "string", + minLength: 1, + }, + email: { + type: "string", + minLength: 1, + }, + age: { + type: "integer", + minimum: 0, + maximum: 150, + }, + }, + required: ["name", "email"], + }, + }), + ).rejects.toThrow(/does not match requested schema/); +}); + +test("should allow elicitation decline and cancel without validation", async () => { + const server = new Server( + { + name: "test server", + version: "1.0", + }, + { + capabilities: { + prompts: {}, + resources: {}, + tools: {}, + logging: {}, + }, + enforceStrictCapabilities: true, + }, + ); + + const client = new Client( + { + name: "test client", + version: "1.0", + }, + { + capabilities: { + elicitation: {}, + }, + }, + ); + + let requestCount = 0; + client.setRequestHandler(ElicitRequestSchema, (request) => { + requestCount++; + if (requestCount === 1) { + return { action: "decline" }; + } else { + return { action: "cancel" }; + } + }); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + server.connect(serverTransport), + ]); + + const schema = { + type: "object" as const, + properties: { + name: { type: "string" as const }, + }, + required: ["name"], + }; + + // Test decline - should not validate + await expect( + server.elicitInput({ + message: "Please provide your name", + requestedSchema: schema, + }), + ).resolves.toEqual({ + action: "decline", + }); + + // Test cancel - should not validate + await expect( + server.elicitInput({ + message: "Please provide your name", + requestedSchema: schema, + }), + ).resolves.toEqual({ + action: "cancel", + }); +}); + test("should respect server notification capabilities", async () => { const server = new Server( { diff --git a/src/server/index.ts b/src/server/index.ts index 3901099e..6a819db8 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -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 { + 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, diff --git a/src/shared/protocol.test.ts b/src/shared/protocol.test.ts index e0141da1..ac453b17 100644 --- a/src/shared/protocol.test.ts +++ b/src/shared/protocol.test.ts @@ -339,6 +339,7 @@ describe("mergeCapabilities", () => { experimental: { feature: true, }, + elicitation: {}, roots: { newProp: true, }, @@ -347,6 +348,7 @@ describe("mergeCapabilities", () => { const merged = mergeCapabilities(base, additional); expect(merged).toEqual({ sampling: {}, + elicitation: {}, roots: { listChanged: true, newProp: true, diff --git a/src/types.ts b/src/types.ts index ae25848e..e5a544b5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -218,6 +218,10 @@ export const ClientCapabilitiesSchema = z * Present if the client supports sampling from an LLM. */ sampling: z.optional(z.object({}).passthrough()), + /** + * Present if the client supports eliciting user input. + */ + elicitation: z.optional(z.object({}).passthrough()), /** * Present if the client supports listing roots. */ @@ -1088,6 +1092,107 @@ export const CreateMessageResultSchema = ResultSchema.extend({ ]), }); +/* Elicitation */ +/** + * Primitive schema definition for boolean fields. + */ +export const BooleanSchemaSchema = z + .object({ + type: z.literal("boolean"), + title: z.optional(z.string()), + description: z.optional(z.string()), + default: z.optional(z.boolean()), + }) + .passthrough(); + +/** + * Primitive schema definition for string fields. + */ +export const StringSchemaSchema = z + .object({ + type: z.literal("string"), + title: z.optional(z.string()), + description: z.optional(z.string()), + minLength: z.optional(z.number()), + maxLength: z.optional(z.number()), + format: z.optional(z.enum(["email", "uri", "date", "date-time"])), + }) + .passthrough(); + +/** + * Primitive schema definition for number fields. + */ +export const NumberSchemaSchema = z + .object({ + type: z.enum(["number", "integer"]), + title: z.optional(z.string()), + description: z.optional(z.string()), + minimum: z.optional(z.number()), + maximum: z.optional(z.number()), + }) + .passthrough(); + +/** + * Primitive schema definition for enum fields. + */ +export const EnumSchemaSchema = z + .object({ + type: z.literal("string"), + title: z.optional(z.string()), + description: z.optional(z.string()), + enum: z.array(z.string()), + enumNames: z.optional(z.array(z.string())), + }) + .passthrough(); + +/** + * Union of all primitive schema definitions. + */ +export const PrimitiveSchemaDefinitionSchema = z.union([ + BooleanSchemaSchema, + StringSchemaSchema, + NumberSchemaSchema, + EnumSchemaSchema, +]); + +/** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user. + */ +export const ElicitRequestSchema = RequestSchema.extend({ + method: z.literal("elicitation/create"), + params: BaseRequestParamsSchema.extend({ + /** + * The message to present to the user. + */ + message: z.string(), + /** + * The schema for the requested user input. + */ + requestedSchema: z + .object({ + type: z.literal("object"), + properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), + required: z.optional(z.array(z.string())), + }) + .passthrough(), + }), +}); + +/** + * The client's response to an elicitation/create request from the server. + */ +export const ElicitResultSchema = ResultSchema.extend({ + /** + * The user's response action. + */ + action: z.enum(["accept", "decline", "cancel"]), + /** + * The collected user input content (only present if action is "accept"). + */ + content: z.optional(z.record(z.string(), z.unknown())), +}); + /* Autocomplete */ /** * A reference to a resource or resource template definition. @@ -1227,6 +1332,7 @@ export const ClientNotificationSchema = z.union([ export const ClientResultSchema = z.union([ EmptyResultSchema, CreateMessageResultSchema, + ElicitResultSchema, ListRootsResultSchema, ]); @@ -1234,6 +1340,7 @@ export const ClientResultSchema = z.union([ export const ServerRequestSchema = z.union([ PingRequestSchema, CreateMessageRequestSchema, + ElicitRequestSchema, ListRootsRequestSchema, ]); @@ -1376,6 +1483,15 @@ export type SamplingMessage = Infer; export type CreateMessageRequest = Infer; export type CreateMessageResult = Infer; +/* Elicitation */ +export type BooleanSchema = Infer; +export type StringSchema = Infer; +export type NumberSchema = Infer; +export type EnumSchema = Infer; +export type PrimitiveSchemaDefinition = Infer; +export type ElicitRequest = Infer; +export type ElicitResult = Infer; + /* Autocomplete */ export type ResourceReference = Infer; export type PromptReference = Infer; From a89f950222a4d129437f01731766fdb4ca7347b2 Mon Sep 17 00:00:00 2001 From: Basil Hosmer Date: Wed, 21 May 2025 17:12:42 -0400 Subject: [PATCH 02/18] post-rebase fixes --- src/examples/client/simpleStreamableHttp.ts | 6 +++--- src/server/index.ts | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/examples/client/simpleStreamableHttp.ts b/src/examples/client/simpleStreamableHttp.ts index 63efdd2f..4bcaf94c 100644 --- a/src/examples/client/simpleStreamableHttp.ts +++ b/src/examples/client/simpleStreamableHttp.ts @@ -16,7 +16,7 @@ import { ResourceListChangedNotificationSchema, ElicitRequestSchema, } from '../../types.js'; -import { Ajv } from 'ajv'; +import Ajv from "ajv"; // Create readline interface for user input const readline = createInterface({ @@ -215,7 +215,7 @@ async function connect(url?: string): Promise { const required = schema.required || []; // Set up AJV validator for the requested schema - const ajv = new Ajv({ strict: false, validateFormats: true }); + const ajv = new Ajv(); const validate = ajv.compile(schema); let attempts = 0; @@ -352,7 +352,7 @@ async function connect(url?: string): Promise { if (!isValid) { console.log('āŒ Validation errors:'); validate.errors?.forEach(error => { - console.log(` - ${error.instancePath || 'root'}: ${error.message}`); + console.log(` - ${error.dataPath || 'root'}: ${error.message}`); }); if (attempts < maxAttempts) { diff --git a/src/server/index.ts b/src/server/index.ts index 6a819db8..506589d9 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -33,7 +33,8 @@ import { ServerResult, SUPPORTED_PROTOCOL_VERSIONS, } from "../types.js"; -import { Ajv } from "ajv"; +import Ajv from "ajv"; +import type { ValidateFunction } from "ajv"; export type ServerOptions = ProtocolOptions & { /** @@ -321,7 +322,7 @@ export class Server< // 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 ajv = new Ajv(); const validate = ajv.compile(params.requestedSchema); const isValid = validate(result.content); From eea1519994f78750b516f527dc135697a69f8eac Mon Sep 17 00:00:00 2001 From: Basil Hosmer Date: Wed, 21 May 2025 23:42:00 -0400 Subject: [PATCH 03/18] lint --- src/server/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/server/index.ts b/src/server/index.ts index 506589d9..5d482d32 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -34,7 +34,6 @@ import { SUPPORTED_PROTOCOL_VERSIONS, } from "../types.js"; import Ajv from "ajv"; -import type { ValidateFunction } from "ajv"; export type ServerOptions = ProtocolOptions & { /** From 2d61b4b8fc0a63162a4b64aa52793af7e9f27d15 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Tue, 10 Jun 2025 15:52:20 +0100 Subject: [PATCH 04/18] adding README --- README.md | 102 +++++++++++++++++ src/server/mcp.test.ts | 255 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 357 insertions(+) diff --git a/README.md b/README.md index c9e27c27..6c100735 100644 --- a/README.md +++ b/README.md @@ -635,6 +635,108 @@ const transport = new StdioServerTransport(); await server.connect(transport); ``` +### Eliciting User Input + +MCP servers can request additional information from users through the elicitation feature. This is useful for interactive workflows where the server needs user input or confirmation: + +```typescript +// Server-side: Restaurant booking tool that asks for alternatives +server.tool( + "book-restaurant", + { + restaurant: z.string(), + date: z.string(), + partySize: z.number() + }, + async ({ restaurant, date, partySize }) => { + // Check availability + const available = await checkAvailability(restaurant, date, partySize); + + if (!available) { + // Ask user if they want to try alternative dates + const result = await server.server.elicitInput({ + message: `No tables available at ${restaurant} on ${date}. Would you like to check alternative dates?`, + requestedSchema: { + type: "object", + properties: { + checkAlternatives: { + type: "boolean", + title: "Check alternative dates", + description: "Would you like me to check other dates?" + }, + flexibleDates: { + type: "string", + title: "Date flexibility", + description: "How flexible are your dates?", + enum: ["next_day", "same_week", "next_week"], + enumNames: ["Next day", "Same week", "Next week"] + } + }, + required: ["checkAlternatives"] + } + }); + + if (result.action === "accept" && result.content?.checkAlternatives) { + const alternatives = await findAlternatives( + restaurant, + date, + partySize, + result.content.flexibleDates as string + ); + return { + content: [{ + type: "text", + text: `Found these alternatives: ${alternatives.join(", ")}` + }] + }; + } + + return { + content: [{ + type: "text", + text: "No booking made. Original date not available." + }] + }; + } + + // Book the table + await makeBooking(restaurant, date, partySize); + return { + content: [{ + type: "text", + text: `Booked table for ${partySize} at ${restaurant} on ${date}` + }] + }; + } +); + +// Client-side: Handle elicitation requests + + +// This is a placeholder - implement based on your UI framework +async function getInputFromUser(message: string, schema: any): Promise<{ + action: "accept" | "decline" | "cancel"; + data?: Record; +}> { + // This should be implemented depending on the app + throw new Error("getInputFromUser must be implemented for your platform"); +} + +client.setRequestHandler(ElicitRequestSchema, async (request) => { + const userResponse = await getInputFromUser( + request.params.message, + request.params.requestedSchema + ); + + return { + action: userResponse.action, + content: userResponse.action === "accept" ? userResponse.data : undefined + }; +}); +``` + +**Note**: Elicitation requires client support. Clients must declare the `elicitation` capability during initialization. + ### Writing MCP Clients The SDK provides a high-level client interface: diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 0ba1998d..bcf09d52 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -14,6 +14,7 @@ import { LoggingMessageNotificationSchema, Notification, TextContent, + ElicitRequestSchema, } from "../types.js"; import { ResourceTemplate } from "./mcp.js"; import { completable } from "./completable.js"; @@ -3457,4 +3458,258 @@ describe("prompt()", () => { expect(typeof receivedRequestId === 'string' || typeof receivedRequestId === 'number').toBe(true); expect(result.messages[0].content.text).toContain("Received request ID:"); }); + + /** + * Test: Restaurant booking example with elicitation from README + */ + describe("Restaurant booking elicitation example", () => { + // Mock restaurant booking functions + const checkAvailability = jest.fn().mockResolvedValue(false); + const findAlternatives = jest.fn().mockResolvedValue([]); + const makeBooking = jest.fn().mockResolvedValue("BOOKING-123"); + + let mcpServer: McpServer; + let client: Client; + + beforeEach(() => { + // Reset mocks + jest.clearAllMocks(); + + // Create server with restaurant booking tool + mcpServer = new McpServer({ + name: "restaurant-booking-server", + version: "1.0.0", + }); + + // Register the restaurant booking tool from README example + mcpServer.tool( + "book-restaurant", + { + restaurant: z.string(), + date: z.string(), + partySize: z.number() + }, + async ({ restaurant, date, partySize }) => { + // Check availability + const available = await checkAvailability(restaurant, date, partySize); + + if (!available) { + // Ask user if they want to try alternative dates + const result = await mcpServer.server.elicitInput({ + message: `No tables available at ${restaurant} on ${date}. Would you like to check alternative dates?`, + requestedSchema: { + type: "object", + properties: { + checkAlternatives: { + type: "boolean", + title: "Check alternative dates", + description: "Would you like me to check other dates?" + }, + flexibleDates: { + type: "string", + title: "Date flexibility", + description: "How flexible are your dates?", + enum: ["next_day", "same_week", "next_week"], + enumNames: ["Next day", "Same week", "Next week"] + } + }, + required: ["checkAlternatives"] + } + }); + + if (result.action === "accept" && result.content?.checkAlternatives) { + const alternatives = await findAlternatives( + restaurant, + date, + partySize, + result.content.flexibleDates as string + ); + return { + content: [{ + type: "text", + text: `Found these alternatives: ${alternatives.join(", ")}` + }] + }; + } + + return { + content: [{ + type: "text", + text: "No booking made. Original date not available." + }] + }; + } + + // Book the table + await makeBooking(restaurant, date, partySize); + return { + content: [{ + type: "text", + text: `Booked table for ${partySize} at ${restaurant} on ${date}` + }] + }; + } + ); + + // Create client with elicitation capability + client = new Client( + { + name: "test-client", + version: "1.0.0", + }, + { + capabilities: { + elicitation: {}, + }, + } + ); + }); + + test("should successfully book when table is available", async () => { + // Mock availability check to return true + checkAvailability.mockResolvedValue(true); + makeBooking.mockResolvedValue("BOOKING-123"); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + mcpServer.server.connect(serverTransport), + ]); + + // Call the tool + const result = await client.callTool({ + name: "book-restaurant", + arguments: { + restaurant: "ABC Restaurant", + date: "2024-12-25", + partySize: 2 + } + }); + + expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); + expect(makeBooking).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); + expect(result.content).toEqual([{ + type: "text", + text: "Booked table for 2 at ABC Restaurant on 2024-12-25" + }]); + }); + + test("should ask for alternatives when no availability and user accepts", async () => { + // Mock availability check to return false + checkAvailability.mockResolvedValue(false); + findAlternatives.mockResolvedValue(["2024-12-26", "2024-12-27", "2024-12-28"]); + + // Set up client to accept alternative date checking + client.setRequestHandler(ElicitRequestSchema, async (request) => { + expect(request.params.message).toContain("No tables available at ABC Restaurant on 2024-12-25"); + return { + action: "accept", + content: { + checkAlternatives: true, + flexibleDates: "same_week" + } + }; + }); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + mcpServer.server.connect(serverTransport), + ]); + + // Call the tool + const result = await client.callTool({ + name: "book-restaurant", + arguments: { + restaurant: "ABC Restaurant", + date: "2024-12-25", + partySize: 2 + } + }); + + expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); + expect(findAlternatives).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2, "same_week"); + expect(result.content).toEqual([{ + type: "text", + text: "Found these alternatives: 2024-12-26, 2024-12-27, 2024-12-28" + }]); + }); + + test("should handle user declining to check alternatives", async () => { + // Mock availability check to return false + checkAvailability.mockResolvedValue(false); + + // Set up client to decline alternative date checking + client.setRequestHandler(ElicitRequestSchema, async () => { + return { + action: "accept", + content: { + checkAlternatives: false + } + }; + }); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + mcpServer.server.connect(serverTransport), + ]); + + // Call the tool + const result = await client.callTool({ + name: "book-restaurant", + arguments: { + restaurant: "ABC Restaurant", + date: "2024-12-25", + partySize: 2 + } + }); + + expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); + expect(findAlternatives).not.toHaveBeenCalled(); + expect(result.content).toEqual([{ + type: "text", + text: "No booking made. Original date not available." + }]); + }); + + test("should handle user cancelling the elicitation", async () => { + // Mock availability check to return false + checkAvailability.mockResolvedValue(false); + + // Set up client to cancel the elicitation + client.setRequestHandler(ElicitRequestSchema, async () => { + return { + action: "cancel" + }; + }); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + mcpServer.server.connect(serverTransport), + ]); + + // Call the tool + const result = await client.callTool({ + name: "book-restaurant", + arguments: { + restaurant: "ABC Restaurant", + date: "2024-12-25", + partySize: 2 + } + }); + + expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); + expect(findAlternatives).not.toHaveBeenCalled(); + expect(result.content).toEqual([{ + type: "text", + text: "No booking made. Original date not available." + }]); + }); + }); }); From c08871998530d3f5f10e53d52342c645e2a73230 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Tue, 10 Jun 2025 17:26:48 +0100 Subject: [PATCH 05/18] tests --- src/server/mcp.test.ts | 393 +++++++++++++++++++---------------------- 1 file changed, 179 insertions(+), 214 deletions(-) diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index bcf09d52..7cb0c489 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -3458,258 +3458,223 @@ describe("prompt()", () => { expect(typeof receivedRequestId === 'string' || typeof receivedRequestId === 'number').toBe(true); expect(result.messages[0].content.text).toContain("Received request ID:"); }); +}); - /** - * Test: Restaurant booking example with elicitation from README - */ - describe("Restaurant booking elicitation example", () => { - // Mock restaurant booking functions - const checkAvailability = jest.fn().mockResolvedValue(false); - const findAlternatives = jest.fn().mockResolvedValue([]); - const makeBooking = jest.fn().mockResolvedValue("BOOKING-123"); +describe("elicitInput()", () => { - let mcpServer: McpServer; - let client: Client; + const checkAvailability = jest.fn().mockResolvedValue(false); + const findAlternatives = jest.fn().mockResolvedValue([]); + const makeBooking = jest.fn().mockResolvedValue("BOOKING-123"); - beforeEach(() => { - // Reset mocks - jest.clearAllMocks(); - - // Create server with restaurant booking tool - mcpServer = new McpServer({ - name: "restaurant-booking-server", - version: "1.0.0", - }); + let mcpServer: McpServer; + let client: Client; - // Register the restaurant booking tool from README example - mcpServer.tool( - "book-restaurant", - { - restaurant: z.string(), - date: z.string(), - partySize: z.number() - }, - async ({ restaurant, date, partySize }) => { - // Check availability - const available = await checkAvailability(restaurant, date, partySize); - - if (!available) { - // Ask user if they want to try alternative dates - const result = await mcpServer.server.elicitInput({ - message: `No tables available at ${restaurant} on ${date}. Would you like to check alternative dates?`, - requestedSchema: { - type: "object", - properties: { - checkAlternatives: { - type: "boolean", - title: "Check alternative dates", - description: "Would you like me to check other dates?" - }, - flexibleDates: { - type: "string", - title: "Date flexibility", - description: "How flexible are your dates?", - enum: ["next_day", "same_week", "next_week"], - enumNames: ["Next day", "Same week", "Next week"] - } + beforeEach(() => { + jest.clearAllMocks(); + + // Create server with restaurant booking tool + mcpServer = new McpServer({ + name: "restaurant-booking-server", + version: "1.0.0", + }); + + // Register the restaurant booking tool from README example + mcpServer.tool( + "book-restaurant", + { + restaurant: z.string(), + date: z.string(), + partySize: z.number() + }, + async ({ restaurant, date, partySize }) => { + // Check availability + const available = await checkAvailability(restaurant, date, partySize); + + if (!available) { + // Ask user if they want to try alternative dates + const result = await mcpServer.server.elicitInput({ + message: `No tables available at ${restaurant} on ${date}. Would you like to check alternative dates?`, + requestedSchema: { + type: "object", + properties: { + checkAlternatives: { + type: "boolean", + title: "Check alternative dates", + description: "Would you like me to check other dates?" }, - required: ["checkAlternatives"] - } - }); - - if (result.action === "accept" && result.content?.checkAlternatives) { - const alternatives = await findAlternatives( - restaurant, - date, - partySize, - result.content.flexibleDates as string - ); - return { - content: [{ - type: "text", - text: `Found these alternatives: ${alternatives.join(", ")}` - }] - }; + flexibleDates: { + type: "string", + title: "Date flexibility", + description: "How flexible are your dates?", + enum: ["next_day", "same_week", "next_week"], + enumNames: ["Next day", "Same week", "Next week"] + } + }, + required: ["checkAlternatives"] } - + }); + + if (result.action === "accept" && result.content?.checkAlternatives) { + const alternatives = await findAlternatives( + restaurant, + date, + partySize, + result.content.flexibleDates as string + ); return { content: [{ type: "text", - text: "No booking made. Original date not available." + text: `Found these alternatives: ${alternatives.join(", ")}` }] }; } - - // Book the table - await makeBooking(restaurant, date, partySize); + return { content: [{ type: "text", - text: `Booked table for ${partySize} at ${restaurant} on ${date}` + text: "No booking made. Original date not available." }] }; } - ); - // Create client with elicitation capability - client = new Client( - { - name: "test-client", - version: "1.0.0", + await makeBooking(restaurant, date, partySize); + return { + content: [{ + type: "text", + text: `Booked table for ${partySize} at ${restaurant} on ${date}` + }] + }; + } + ); + + // Create client with elicitation capability + client = new Client( + { + name: "test-client", + version: "1.0.0", + }, + { + capabilities: { + elicitation: {}, }, - { - capabilities: { - elicitation: {}, - }, + } + ); + }); + + test("should successfully elicit additional information", async () => { + // Mock availability check to return false + checkAvailability.mockResolvedValue(false); + findAlternatives.mockResolvedValue(["2024-12-26", "2024-12-27", "2024-12-28"]); + + // Set up client to accept alternative date checking + client.setRequestHandler(ElicitRequestSchema, async (request) => { + expect(request.params.message).toContain("No tables available at ABC Restaurant on 2024-12-25"); + return { + action: "accept", + content: { + checkAlternatives: true, + flexibleDates: "same_week" } - ); + }; }); - test("should successfully book when table is available", async () => { - // Mock availability check to return true - checkAvailability.mockResolvedValue(true); - makeBooking.mockResolvedValue("BOOKING-123"); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([ - client.connect(clientTransport), - mcpServer.server.connect(serverTransport), - ]); + await Promise.all([ + client.connect(clientTransport), + mcpServer.server.connect(serverTransport), + ]); - // Call the tool - const result = await client.callTool({ - name: "book-restaurant", - arguments: { - restaurant: "ABC Restaurant", - date: "2024-12-25", - partySize: 2 - } - }); - - expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); - expect(makeBooking).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); - expect(result.content).toEqual([{ - type: "text", - text: "Booked table for 2 at ABC Restaurant on 2024-12-25" - }]); + // Call the tool + const result = await client.callTool({ + name: "book-restaurant", + arguments: { + restaurant: "ABC Restaurant", + date: "2024-12-25", + partySize: 2 + } }); - test("should ask for alternatives when no availability and user accepts", async () => { - // Mock availability check to return false - checkAvailability.mockResolvedValue(false); - findAlternatives.mockResolvedValue(["2024-12-26", "2024-12-27", "2024-12-28"]); + expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); + expect(findAlternatives).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2, "same_week"); + expect(result.content).toEqual([{ + type: "text", + text: "Found these alternatives: 2024-12-26, 2024-12-27, 2024-12-28" + }]); + }); - // Set up client to accept alternative date checking - client.setRequestHandler(ElicitRequestSchema, async (request) => { - expect(request.params.message).toContain("No tables available at ABC Restaurant on 2024-12-25"); - return { - action: "accept", - content: { - checkAlternatives: true, - flexibleDates: "same_week" - } - }; - }); + test("should handle user declining to elicitation request", async () => { + // Mock availability check to return false + checkAvailability.mockResolvedValue(false); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([ - client.connect(clientTransport), - mcpServer.server.connect(serverTransport), - ]); - - // Call the tool - const result = await client.callTool({ - name: "book-restaurant", - arguments: { - restaurant: "ABC Restaurant", - date: "2024-12-25", - partySize: 2 + // Set up client to decline alternative date checking + client.setRequestHandler(ElicitRequestSchema, async () => { + return { + action: "accept", + content: { + checkAlternatives: false } - }); - - expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); - expect(findAlternatives).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2, "same_week"); - expect(result.content).toEqual([{ - type: "text", - text: "Found these alternatives: 2024-12-26, 2024-12-27, 2024-12-28" - }]); + }; }); - test("should handle user declining to check alternatives", async () => { - // Mock availability check to return false - checkAvailability.mockResolvedValue(false); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - // Set up client to decline alternative date checking - client.setRequestHandler(ElicitRequestSchema, async () => { - return { - action: "accept", - content: { - checkAlternatives: false - } - }; - }); + await Promise.all([ + client.connect(clientTransport), + mcpServer.server.connect(serverTransport), + ]); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([ - client.connect(clientTransport), - mcpServer.server.connect(serverTransport), - ]); - - // Call the tool - const result = await client.callTool({ - name: "book-restaurant", - arguments: { - restaurant: "ABC Restaurant", - date: "2024-12-25", - partySize: 2 - } - }); - - expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); - expect(findAlternatives).not.toHaveBeenCalled(); - expect(result.content).toEqual([{ - type: "text", - text: "No booking made. Original date not available." - }]); + // Call the tool + const result = await client.callTool({ + name: "book-restaurant", + arguments: { + restaurant: "ABC Restaurant", + date: "2024-12-25", + partySize: 2 + } }); - test("should handle user cancelling the elicitation", async () => { - // Mock availability check to return false - checkAvailability.mockResolvedValue(false); + expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); + expect(findAlternatives).not.toHaveBeenCalled(); + expect(result.content).toEqual([{ + type: "text", + text: "No booking made. Original date not available." + }]); + }); - // Set up client to cancel the elicitation - client.setRequestHandler(ElicitRequestSchema, async () => { - return { - action: "cancel" - }; - }); + test("should handle user cancelling the elicitation", async () => { + // Mock availability check to return false + checkAvailability.mockResolvedValue(false); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([ - client.connect(clientTransport), - mcpServer.server.connect(serverTransport), - ]); - - // Call the tool - const result = await client.callTool({ - name: "book-restaurant", - arguments: { - restaurant: "ABC Restaurant", - date: "2024-12-25", - partySize: 2 - } - }); - - expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); - expect(findAlternatives).not.toHaveBeenCalled(); - expect(result.content).toEqual([{ - type: "text", - text: "No booking made. Original date not available." - }]); + // Set up client to cancel the elicitation + client.setRequestHandler(ElicitRequestSchema, async () => { + return { + action: "cancel" + }; }); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + mcpServer.server.connect(serverTransport), + ]); + + // Call the tool + const result = await client.callTool({ + name: "book-restaurant", + arguments: { + restaurant: "ABC Restaurant", + date: "2024-12-25", + partySize: 2 + } + }); + + expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); + expect(findAlternatives).not.toHaveBeenCalled(); + expect(result.content).toEqual([{ + type: "text", + text: "No booking made. Original date not available." + }]); }); }); From c90d6c9853ab64cf94c2d3d016f615ae4376fa89 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Mon, 16 Jun 2025 14:11:10 +0100 Subject: [PATCH 06/18] add context with arguments to completable --- src/server/completable.ts | 3 + src/server/mcp.test.ts | 271 +++++++++++++++++++++++++++++++++++--- src/server/mcp.ts | 7 +- src/types.test.ts | 90 ++++++++++++- src/types.ts | 8 ++ 5 files changed, 357 insertions(+), 22 deletions(-) diff --git a/src/server/completable.ts b/src/server/completable.ts index 3b5bc164..652eaf72 100644 --- a/src/server/completable.ts +++ b/src/server/completable.ts @@ -15,6 +15,9 @@ export enum McpZodTypeKind { export type CompleteCallback = ( value: T["_input"], + context?: { + arguments?: Record; + }, ) => T["_input"][] | Promise; export interface CompletableDef diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 36a8f7b8..23600db4 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -3521,12 +3521,12 @@ describe("prompt()", () => { ); expect(result.resources).toHaveLength(2); - + // Resource 1 should have its own metadata expect(result.resources[0].name).toBe("Resource 1"); expect(result.resources[0].description).toBe("Individual resource description"); expect(result.resources[0].mimeType).toBe("text/plain"); - + // Resource 2 should inherit template metadata expect(result.resources[1].name).toBe("Resource 2"); expect(result.resources[1].description).toBe("Template description"); @@ -3592,7 +3592,7 @@ describe("prompt()", () => { ); expect(result.resources).toHaveLength(1); - + // All fields should be from the individual resource, not the template expect(result.resources[0].name).toBe("Overridden Name"); expect(result.resources[0].description).toBe("Overridden description"); @@ -3698,41 +3698,274 @@ describe("Tool title precedence", () => { }); test("getDisplayName unit tests for title precedence", () => { - + // Test 1: Only name expect(getDisplayName({ name: "tool_name" })).toBe("tool_name"); - + // Test 2: Name and title - title wins - expect(getDisplayName({ - name: "tool_name", - title: "Tool Title" + expect(getDisplayName({ + name: "tool_name", + title: "Tool Title" })).toBe("Tool Title"); - + // Test 3: Name and annotations.title - annotations.title wins - expect(getDisplayName({ + expect(getDisplayName({ name: "tool_name", annotations: { title: "Annotations Title" } })).toBe("Annotations Title"); - + // Test 4: All three - title wins (correct precedence) - expect(getDisplayName({ - name: "tool_name", + expect(getDisplayName({ + name: "tool_name", title: "Regular Title", annotations: { title: "Annotations Title" } })).toBe("Regular Title"); - + // Test 5: Empty title should not be used - expect(getDisplayName({ - name: "tool_name", + expect(getDisplayName({ + name: "tool_name", title: "", annotations: { title: "Annotations Title" } })).toBe("Annotations Title"); - + // Test 6: Undefined vs null handling - expect(getDisplayName({ - name: "tool_name", + expect(getDisplayName({ + name: "tool_name", title: undefined, annotations: { title: "Annotations Title" } })).toBe("Annotations Title"); }); + + test("should support resource template completion with resolved context", async () => { + const mcpServer = new McpServer({ + name: "test server", + version: "1.0", + }); + + const client = new Client({ + name: "test client", + version: "1.0", + }); + + mcpServer.resource( + "test", + new ResourceTemplate("github://repos/{owner}/{repo}", { + list: undefined, + complete: { + repo: (value, context) => { + if (context?.arguments?.["owner"] === "org1") { + return ["project1", "project2", "project3"].filter(r => r.startsWith(value)); + } else if (context?.arguments?.["owner"] === "org2") { + return ["repo1", "repo2", "repo3"].filter(r => r.startsWith(value)); + } + return []; + }, + }, + }), + async () => ({ + contents: [ + { + uri: "github://repos/test/test", + text: "Test content", + }, + ], + }), + ); + + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + mcpServer.server.connect(serverTransport), + ]); + + // Test with microsoft owner + const result1 = await client.request( + { + method: "completion/complete", + params: { + ref: { + type: "ref/resource", + uri: "github://repos/{owner}/{repo}", + }, + argument: { + name: "repo", + value: "p", + }, + context: { + arguments: { + owner: "org1", + }, + }, + }, + }, + CompleteResultSchema, + ); + + expect(result1.completion.values).toEqual(["project1", "project2", "project3"]); + expect(result1.completion.total).toBe(3); + + // Test with facebook owner + const result2 = await client.request( + { + method: "completion/complete", + params: { + ref: { + type: "ref/resource", + uri: "github://repos/{owner}/{repo}", + }, + argument: { + name: "repo", + value: "r", + }, + context: { + arguments: { + owner: "org2", + }, + }, + }, + }, + CompleteResultSchema, + ); + + expect(result2.completion.values).toEqual(["repo1", "repo2", "repo3"]); + expect(result2.completion.total).toBe(3); + + // Test with no resolved context + const result3 = await client.request( + { + method: "completion/complete", + params: { + ref: { + type: "ref/resource", + uri: "github://repos/{owner}/{repo}", + }, + argument: { + name: "repo", + value: "t", + }, + }, + }, + CompleteResultSchema, + ); + + expect(result3.completion.values).toEqual([]); + expect(result3.completion.total).toBe(0); + }); + + test("should support prompt argument completion with resolved context", async () => { + const mcpServer = new McpServer({ + name: "test server", + version: "1.0", + }); + + const client = new Client({ + name: "test client", + version: "1.0", + }); + + mcpServer.prompt( + "test-prompt", + { + name: completable(z.string(), (value, context) => { + if (context?.arguments?.["category"] === "developers") { + return ["Alice", "Bob", "Charlie"].filter(n => n.startsWith(value)); + } else if (context?.arguments?.["category"] === "managers") { + return ["David", "Eve", "Frank"].filter(n => n.startsWith(value)); + } + return ["Guest"].filter(n => n.startsWith(value)); + }), + }, + async ({ name }) => ({ + messages: [ + { + role: "assistant", + content: { + type: "text", + text: `Hello ${name}`, + }, + }, + ], + }), + ); + + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + mcpServer.server.connect(serverTransport), + ]); + + // Test with developers category + const result1 = await client.request( + { + method: "completion/complete", + params: { + ref: { + type: "ref/prompt", + name: "test-prompt", + }, + argument: { + name: "name", + value: "A", + }, + context: { + arguments: { + category: "developers", + }, + }, + }, + }, + CompleteResultSchema, + ); + + expect(result1.completion.values).toEqual(["Alice"]); + + // Test with managers category + const result2 = await client.request( + { + method: "completion/complete", + params: { + ref: { + type: "ref/prompt", + name: "test-prompt", + }, + argument: { + name: "name", + value: "D", + }, + context: { + arguments: { + category: "managers", + }, + }, + }, + }, + CompleteResultSchema, + ); + + expect(result2.completion.values).toEqual(["David"]); + + // Test with no resolved context + const result3 = await client.request( + { + method: "completion/complete", + params: { + ref: { + type: "ref/prompt", + name: "test-prompt", + }, + argument: { + name: "name", + value: "G", + }, + }, + }, + CompleteResultSchema, + ); + + expect(result3.completion.values).toEqual(["Guest"]); + }); }); diff --git a/src/server/mcp.ts b/src/server/mcp.ts index ac6cf772..3d9673da 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -293,7 +293,7 @@ export class McpServer { } const def: CompletableDef = field._def; - const suggestions = await def.complete(request.params.argument.value); + const suggestions = await def.complete(request.params.argument.value, request.params.context); return createCompletionResult(suggestions); } @@ -324,7 +324,7 @@ export class McpServer { return EMPTY_COMPLETION_RESULT; } - const suggestions = await completer(request.params.argument.value); + const suggestions = await completer(request.params.argument.value, request.params.context); return createCompletionResult(suggestions); } @@ -1068,6 +1068,9 @@ export class McpServer { */ export type CompleteResourceTemplateCallback = ( value: string, + context?: { + arguments?: Record; + }, ) => string[] | Promise; /** diff --git a/src/types.test.ts b/src/types.test.ts index d163f03d..bc109110 100644 --- a/src/types.test.ts +++ b/src/types.test.ts @@ -4,7 +4,8 @@ import { ResourceLinkSchema, ContentBlockSchema, PromptMessageSchema, - CallToolResultSchema + CallToolResultSchema, + CompleteRequestSchema } from "./types.js"; describe("Types", () => { @@ -223,4 +224,91 @@ describe("Types", () => { } }); }); + + describe("CompleteRequest", () => { + test("should validate a CompleteRequest without resolved field", () => { + const request = { + method: "completion/complete", + params: { + ref: { type: "ref/prompt", name: "greeting" }, + argument: { name: "name", value: "A" } + } + }; + + const result = CompleteRequestSchema.safeParse(request); + expect(result.success).toBe(true); + if (result.success) { + expect(result.data.method).toBe("completion/complete"); + expect(result.data.params.ref.type).toBe("ref/prompt"); + expect(result.data.params.context).toBeUndefined(); + } + }); + + test("should validate a CompleteRequest with resolved field", () => { + const request = { + method: "completion/complete", + params: { + ref: { type: "ref/resource", uri: "github://repos/{owner}/{repo}" }, + argument: { name: "repo", value: "t" }, + context: { + arguments: { + "{owner}": "microsoft" + } + } + } + }; + + const result = CompleteRequestSchema.safeParse(request); + expect(result.success).toBe(true); + if (result.success) { + expect(result.data.params.context?.arguments).toEqual({ + "{owner}": "microsoft" + }); + } + }); + + test("should validate a CompleteRequest with empty resolved field", () => { + const request = { + method: "completion/complete", + params: { + ref: { type: "ref/prompt", name: "test" }, + argument: { name: "arg", value: "" }, + context: { + arguments: {} + } + } + }; + + const result = CompleteRequestSchema.safeParse(request); + expect(result.success).toBe(true); + if (result.success) { + expect(result.data.params.context?.arguments).toEqual({}); + } + }); + + test("should validate a CompleteRequest with multiple resolved variables", () => { + const request = { + method: "completion/complete", + params: { + ref: { type: "ref/resource", uri: "api://v1/{tenant}/{resource}/{id}" }, + argument: { name: "id", value: "123" }, + context: { + arguments: { + "{tenant}": "acme-corp", + "{resource}": "users" + } + } + } + }; + + const result = CompleteRequestSchema.safeParse(request); + expect(result.success).toBe(true); + if (result.success) { + expect(result.data.params.context?.arguments).toEqual({ + "{tenant}": "acme-corp", + "{resource}": "users" + }); + } + }); + }); }); diff --git a/src/types.ts b/src/types.ts index 8e8b7d33..1bc22591 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1169,6 +1169,14 @@ export const CompleteRequestSchema = RequestSchema.extend({ value: z.string(), }) .passthrough(), + context: z.optional( + z.object({ + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments: z.optional(z.record(z.string(), z.string())), + }) + ), }), }); From 42c3967d8b04f2a95550102967f65763719fceb5 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Mon, 16 Jun 2025 14:23:17 +0100 Subject: [PATCH 07/18] add to readme --- README.md | 111 ++++++++++++++++++++++++++++++++++++++++- src/server/mcp.test.ts | 28 +++++++---- 2 files changed, 128 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index ff6c482f..63acfb06 100644 --- a/README.md +++ b/README.md @@ -150,6 +150,33 @@ server.registerResource( }] }) ); + +// Resource with context-aware completion +server.registerResource( + "repository", + new ResourceTemplate("github://repos/{owner}/{repo}", { + list: undefined, + complete: { + // Provide intelligent completions based on previously resolved parameters + repo: (value, context) => { + if (context?.arguments?.["owner"] === "org1") { + return ["project1", "project2", "project3"].filter(r => r.startsWith(value)); + } + return ["default-repo"].filter(r => r.startsWith(value)); + } + } + }), + { + title: "GitHub Repository", + description: "Repository information" + }, + async (uri, { owner, repo }) => ({ + contents: [{ + uri: uri.href, + text: `Repository: ${owner}/${repo}` + }] + }) +); ``` ### Tools @@ -233,12 +260,14 @@ Tools can return `ResourceLink` objects to reference resources without embedding Prompts are reusable templates that help LLMs interact with your server effectively: ```typescript +import { completable } from "@modelcontextprotocol/sdk/server/completable.js"; + server.registerPrompt( "review-code", { title: "Code Review", description: "Review code for best practices and potential issues", - arguments: { code: z.string() } + argsSchema: { code: z.string() } }, ({ code }) => ({ messages: [{ @@ -250,6 +279,35 @@ server.registerPrompt( }] }) ); + +// Prompt with context-aware completion +server.registerPrompt( + "team-greeting", + { + title: "Team Greeting", + description: "Generate a greeting for team members", + argsSchema: { + // Completable arguments can use context for intelligent suggestions + name: completable(z.string(), (value, context) => { + if (context?.arguments?.["department"] === "engineering") { + return ["Alice", "Bob", "Charlie"].filter(n => n.startsWith(value)); + } else if (context?.arguments?.["department"] === "sales") { + return ["David", "Eve", "Frank"].filter(n => n.startsWith(value)); + } + return ["Guest"].filter(n => n.startsWith(value)); + }) + } + }, + ({ name }) => ({ + messages: [{ + role: "assistant", + content: { + type: "text", + text: `Hello ${name}, welcome to the team!` + } + }] + }) +); ``` ### Display Names and Metadata @@ -637,6 +695,57 @@ server.registerTool( ## Advanced Usage +### Context-Aware Completions + +MCP supports intelligent completions that can use previously resolved values as context. This is useful for creating dependent parameter completions where later parameters depend on earlier ones: + +```typescript +import { completable } from "@modelcontextprotocol/sdk/server/completable.js"; + +// For resource templates +server.registerResource( + "database-query", + new ResourceTemplate("db://{database}/{table}/{query}", { + list: undefined, + complete: { + // Table completions depend on the selected database + table: (value, context) => { + const database = context?.arguments?.["database"]; + if (database === "users_db") { + return ["profiles", "sessions", "preferences"].filter(t => t.startsWith(value)); + } else if (database === "products_db") { + return ["items", "categories", "inventory"].filter(t => t.startsWith(value)); + } + return []; + } + } + }), + metadata, + handler +); + +// For prompts with completable arguments +server.registerPrompt( + "api-request", + { + argsSchema: { + endpoint: z.string(), + // Method completions can be context-aware + method: completable(z.string(), (value, context) => { + const endpoint = context?.arguments?.["endpoint"]; + if (endpoint?.includes("/readonly/")) { + return ["GET"].filter(m => m.startsWith(value.toUpperCase())); + } + return ["GET", "POST", "PUT", "DELETE"].filter(m => m.startsWith(value.toUpperCase())); + }) + } + }, + handler +); +``` + +The context object contains an `arguments` field with previously resolved parameter values, allowing you to provide more intelligent and contextual completions. + ### Dynamic Servers If you want to offer an initial set of tools/prompts/resources, but later add additional ones based on user action or external state change, you can add/update/remove them _after_ the Server is connected. This will automatically emit the corresponding `listChanged` notifications: diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 23600db4..685987bf 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -3747,7 +3747,7 @@ describe("Tool title precedence", () => { version: "1.0", }); - mcpServer.resource( + mcpServer.registerResource( "test", new ResourceTemplate("github://repos/{owner}/{repo}", { list: undefined, @@ -3762,6 +3762,10 @@ describe("Tool title precedence", () => { }, }, }), + { + title: "GitHub Repository", + description: "Repository information" + }, async () => ({ contents: [ { @@ -3865,17 +3869,21 @@ describe("Tool title precedence", () => { version: "1.0", }); - mcpServer.prompt( + mcpServer.registerPrompt( "test-prompt", { - name: completable(z.string(), (value, context) => { - if (context?.arguments?.["category"] === "developers") { - return ["Alice", "Bob", "Charlie"].filter(n => n.startsWith(value)); - } else if (context?.arguments?.["category"] === "managers") { - return ["David", "Eve", "Frank"].filter(n => n.startsWith(value)); - } - return ["Guest"].filter(n => n.startsWith(value)); - }), + title: "Team Greeting", + description: "Generate a greeting for team members", + argsSchema: { + name: completable(z.string(), (value, context) => { + if (context?.arguments?.["category"] === "developers") { + return ["Alice", "Bob", "Charlie"].filter(n => n.startsWith(value)); + } else if (context?.arguments?.["category"] === "managers") { + return ["David", "Eve", "Frank"].filter(n => n.startsWith(value)); + } + return ["Guest"].filter(n => n.startsWith(value)); + }), + } }, async ({ name }) => ({ messages: [ From 0e86a6d139e0a3da564101cb751f53d3c3fb00fe Mon Sep 17 00:00:00 2001 From: ihrpr Date: Mon, 16 Jun 2025 14:36:35 +0100 Subject: [PATCH 08/18] improve readme --- README.md | 68 ++++++++---------------------------------- src/server/mcp.test.ts | 51 ++++++++++++++++++++++++------- 2 files changed, 53 insertions(+), 66 deletions(-) diff --git a/README.md b/README.md index 63acfb06..08b711c2 100644 --- a/README.md +++ b/README.md @@ -287,23 +287,30 @@ server.registerPrompt( title: "Team Greeting", description: "Generate a greeting for team members", argsSchema: { - // Completable arguments can use context for intelligent suggestions + department: completable(z.string(), (value) => { + // Department suggestions + return ["engineering", "sales", "marketing", "support"].filter(d => d.startsWith(value)); + }), name: completable(z.string(), (value, context) => { - if (context?.arguments?.["department"] === "engineering") { + // Name suggestions based on selected department + const department = context?.arguments?.["department"]; + if (department === "engineering") { return ["Alice", "Bob", "Charlie"].filter(n => n.startsWith(value)); - } else if (context?.arguments?.["department"] === "sales") { + } else if (department === "sales") { return ["David", "Eve", "Frank"].filter(n => n.startsWith(value)); + } else if (department === "marketing") { + return ["Grace", "Henry", "Iris"].filter(n => n.startsWith(value)); } return ["Guest"].filter(n => n.startsWith(value)); }) } }, - ({ name }) => ({ + ({ department, name }) => ({ messages: [{ role: "assistant", content: { type: "text", - text: `Hello ${name}, welcome to the team!` + text: `Hello ${name}, welcome to the ${department} team!` } }] }) @@ -695,57 +702,6 @@ server.registerTool( ## Advanced Usage -### Context-Aware Completions - -MCP supports intelligent completions that can use previously resolved values as context. This is useful for creating dependent parameter completions where later parameters depend on earlier ones: - -```typescript -import { completable } from "@modelcontextprotocol/sdk/server/completable.js"; - -// For resource templates -server.registerResource( - "database-query", - new ResourceTemplate("db://{database}/{table}/{query}", { - list: undefined, - complete: { - // Table completions depend on the selected database - table: (value, context) => { - const database = context?.arguments?.["database"]; - if (database === "users_db") { - return ["profiles", "sessions", "preferences"].filter(t => t.startsWith(value)); - } else if (database === "products_db") { - return ["items", "categories", "inventory"].filter(t => t.startsWith(value)); - } - return []; - } - } - }), - metadata, - handler -); - -// For prompts with completable arguments -server.registerPrompt( - "api-request", - { - argsSchema: { - endpoint: z.string(), - // Method completions can be context-aware - method: completable(z.string(), (value, context) => { - const endpoint = context?.arguments?.["endpoint"]; - if (endpoint?.includes("/readonly/")) { - return ["GET"].filter(m => m.startsWith(value.toUpperCase())); - } - return ["GET", "POST", "PUT", "DELETE"].filter(m => m.startsWith(value.toUpperCase())); - }) - } - }, - handler -); -``` - -The context object contains an `arguments` field with previously resolved parameter values, allowing you to provide more intelligent and contextual completions. - ### Dynamic Servers If you want to offer an initial set of tools/prompts/resources, but later add additional ones based on user action or external state change, you can add/update/remove them _after_ the Server is connected. This will automatically emit the corresponding `listChanged` notifications: diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 685987bf..15be3d98 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -3875,23 +3875,29 @@ describe("Tool title precedence", () => { title: "Team Greeting", description: "Generate a greeting for team members", argsSchema: { + department: completable(z.string(), (value) => { + return ["engineering", "sales", "marketing", "support"].filter(d => d.startsWith(value)); + }), name: completable(z.string(), (value, context) => { - if (context?.arguments?.["category"] === "developers") { + const department = context?.arguments?.["department"]; + if (department === "engineering") { return ["Alice", "Bob", "Charlie"].filter(n => n.startsWith(value)); - } else if (context?.arguments?.["category"] === "managers") { + } else if (department === "sales") { return ["David", "Eve", "Frank"].filter(n => n.startsWith(value)); + } else if (department === "marketing") { + return ["Grace", "Henry", "Iris"].filter(n => n.startsWith(value)); } return ["Guest"].filter(n => n.startsWith(value)); }), } }, - async ({ name }) => ({ + async ({ department, name }) => ({ messages: [ { role: "assistant", content: { type: "text", - text: `Hello ${name}`, + text: `Hello ${name}, welcome to the ${department} team!`, }, }, ], @@ -3906,7 +3912,7 @@ describe("Tool title precedence", () => { mcpServer.server.connect(serverTransport), ]); - // Test with developers category + // Test with engineering department const result1 = await client.request( { method: "completion/complete", @@ -3921,7 +3927,7 @@ describe("Tool title precedence", () => { }, context: { arguments: { - category: "developers", + department: "engineering", }, }, }, @@ -3931,7 +3937,7 @@ describe("Tool title precedence", () => { expect(result1.completion.values).toEqual(["Alice"]); - // Test with managers category + // Test with sales department const result2 = await client.request( { method: "completion/complete", @@ -3946,7 +3952,7 @@ describe("Tool title precedence", () => { }, context: { arguments: { - category: "managers", + department: "sales", }, }, }, @@ -3956,8 +3962,33 @@ describe("Tool title precedence", () => { expect(result2.completion.values).toEqual(["David"]); - // Test with no resolved context + // Test with marketing department const result3 = await client.request( + { + method: "completion/complete", + params: { + ref: { + type: "ref/prompt", + name: "test-prompt", + }, + argument: { + name: "name", + value: "G", + }, + context: { + arguments: { + department: "marketing", + }, + }, + }, + }, + CompleteResultSchema, + ); + + expect(result3.completion.values).toEqual(["Grace"]); + + // Test with no resolved context + const result4 = await client.request( { method: "completion/complete", params: { @@ -3974,6 +4005,6 @@ describe("Tool title precedence", () => { CompleteResultSchema, ); - expect(result3.completion.values).toEqual(["Guest"]); + expect(result4.completion.values).toEqual(["Guest"]); }); }); From c0c78ad412c36403ec70fae28f767dd0a756eaa5 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Mon, 16 Jun 2025 15:04:23 +0100 Subject: [PATCH 09/18] add how to use Completions to the readme --- README.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/README.md b/README.md index 08b711c2..8d319f67 100644 --- a/README.md +++ b/README.md @@ -317,6 +317,32 @@ server.registerPrompt( ); ``` +### Completions + +MCP supports argument completions to help users fill in prompt arguments and resource template parameters. See the examples above for [resource completions](#resources) and [prompt completions](#prompts). + +#### Client Usage + +```typescript +// Request completions for any argument +const result = await client.complete({ + ref: { + type: "ref/prompt", // or "ref/resource" + name: "example" // or uri: "template://..." + }, + argument: { + name: "argumentName", + value: "partial" // What the user has typed so far + }, + context: { // Optional: Include previously resolved arguments + arguments: { + previousArg: "value" + } + } +}); +console.log(result.completion.values); // ["suggestion1", "suggestion2", ...] +``` + ### Display Names and Metadata All resources, tools, and prompts support an optional `title` field for better UI presentation. The `title` is used as a display name, while `name` remains the unique identifier. @@ -870,6 +896,18 @@ const result = await client.callTool({ arg1: "value" } }); + +// Request completions +const completions = await client.complete({ + ref: { + type: "ref/prompt", + name: "example-prompt" + }, + argument: { + name: "arg1", + value: "partial" + } +}); ``` ### Proxy Authorization Requests Upstream From 4549250a4301ac2f44b60923e38ef2db1f8b7051 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Mon, 16 Jun 2025 15:04:33 +0100 Subject: [PATCH 10/18] readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8d319f67..a73d8a38 100644 --- a/README.md +++ b/README.md @@ -340,7 +340,7 @@ const result = await client.complete({ } } }); -console.log(result.completion.values); // ["suggestion1", "suggestion2", ...] + ``` ### Display Names and Metadata From 5b875aa542337f253d9a31b166f068ed519a724b Mon Sep 17 00:00:00 2001 From: ihrpr Date: Mon, 16 Jun 2025 15:19:21 +0100 Subject: [PATCH 11/18] clean up --- README.md | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/README.md b/README.md index a73d8a38..272eeb12 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ - [Resources](#resources) - [Tools](#tools) - [Prompts](#prompts) + - [Completions](#completions) - [Running Your Server](#running-your-server) - [stdio](#stdio) - [Streamable HTTP](#streamable-http) @@ -897,17 +898,6 @@ const result = await client.callTool({ } }); -// Request completions -const completions = await client.complete({ - ref: { - type: "ref/prompt", - name: "example-prompt" - }, - argument: { - name: "arg1", - value: "partial" - } -}); ``` ### Proxy Authorization Requests Upstream From 3df732545f0f0d38c13181b6db1381e0eafff41d Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Mon, 16 Jun 2025 16:06:13 +0100 Subject: [PATCH 12/18] Add missing _meta fields to match spec requirements MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added optional _meta field to ResourceContentsSchema, PromptSchema, and EmbeddedResourceSchema to align with spec change PR #710. These were the only schemas missing the _meta field that were required by the specification update. šŸ¤– Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- src/types.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/types.ts b/src/types.ts index 1bc22591..1c248d77 100644 --- a/src/types.ts +++ b/src/types.ts @@ -435,6 +435,10 @@ export const ResourceContentsSchema = z * The MIME type of this resource, if known. */ mimeType: z.optional(z.string()), + /** + * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. + */ + _meta: z.optional(z.object({}).passthrough()), }) .passthrough(); @@ -637,6 +641,10 @@ export const PromptSchema = BaseMetadataSchema.extend({ * A list of arguments to use for templating the prompt. */ arguments: z.optional(z.array(PromptArgumentSchema)), + /** + * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. + */ + _meta: z.optional(z.object({}).passthrough()), }); /** @@ -739,6 +747,10 @@ export const EmbeddedResourceSchema = z .object({ type: z.literal("resource"), resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), + /** + * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. + */ + _meta: z.optional(z.object({}).passthrough()), }) .passthrough(); From 4af2d4fe9fbcd983262e248cc18e2102887d8cce Mon Sep 17 00:00:00 2001 From: ihrpr Date: Mon, 16 Jun 2025 19:14:52 +0100 Subject: [PATCH 13/18] separate code block in README --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3ab5a898..9fa07de3 100644 --- a/README.md +++ b/README.md @@ -923,10 +923,11 @@ server.tool( }; } ); +``` -// Client-side: Handle elicitation requests - +Client-side: Handle elicitation requests +```typescript // This is a placeholder - implement based on your UI framework async function getInputFromUser(message: string, schema: any): Promise<{ action: "accept" | "decline" | "cancel"; From 784d94437764dc0f8e46ccebab62337202b31a48 Mon Sep 17 00:00:00 2001 From: Basil Hosmer Date: Mon, 16 Jun 2025 14:52:33 -0400 Subject: [PATCH 14/18] update _meta comments --- src/types.ts | 54 ++++++++++++++++++++++++++++++++-------------------- 1 file changed, 33 insertions(+), 21 deletions(-) diff --git a/src/types.ts b/src/types.ts index 1c248d77..762708f5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -44,8 +44,9 @@ export const RequestSchema = z.object({ const BaseNotificationParamsSchema = z .object({ /** - * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. - */ + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ _meta: z.optional(z.object({}).passthrough()), }) .passthrough(); @@ -58,8 +59,9 @@ export const NotificationSchema = z.object({ export const ResultSchema = z .object({ /** - * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. - */ + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ _meta: z.optional(z.object({}).passthrough()), }) .passthrough(); @@ -436,7 +438,8 @@ export const ResourceContentsSchema = z */ mimeType: z.optional(z.string()), /** - * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. */ _meta: z.optional(z.object({}).passthrough()), }) @@ -478,8 +481,9 @@ export const ResourceSchema = BaseMetadataSchema.extend({ mimeType: z.optional(z.string()), /** - * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. - */ + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ _meta: z.optional(z.object({}).passthrough()), }); @@ -505,8 +509,9 @@ export const ResourceTemplateSchema = BaseMetadataSchema.extend({ mimeType: z.optional(z.string()), /** - * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. - */ + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ _meta: z.optional(z.object({}).passthrough()), }); @@ -642,7 +647,8 @@ export const PromptSchema = BaseMetadataSchema.extend({ */ arguments: z.optional(z.array(PromptArgumentSchema)), /** - * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. */ _meta: z.optional(z.object({}).passthrough()), }); @@ -690,8 +696,9 @@ export const TextContentSchema = z text: z.string(), /** - * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. - */ + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ _meta: z.optional(z.object({}).passthrough()), }) .passthrough(); @@ -712,8 +719,9 @@ export const ImageContentSchema = z mimeType: z.string(), /** - * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. - */ + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ _meta: z.optional(z.object({}).passthrough()), }) .passthrough(); @@ -734,8 +742,9 @@ export const AudioContentSchema = z mimeType: z.string(), /** - * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. - */ + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ _meta: z.optional(z.object({}).passthrough()), }) .passthrough(); @@ -748,7 +757,8 @@ export const EmbeddedResourceSchema = z type: z.literal("resource"), resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), /** - * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. */ _meta: z.optional(z.object({}).passthrough()), }) @@ -895,8 +905,9 @@ export const ToolSchema = BaseMetadataSchema.extend({ annotations: z.optional(ToolAnnotationsSchema), /** - * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. - */ + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ _meta: z.optional(z.object({}).passthrough()), }); @@ -1230,8 +1241,9 @@ export const RootSchema = z name: z.optional(z.string()), /** - * Reserved by MCP for protocol-level metadata; implementations must not make assumptions about its contents. - */ + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ _meta: z.optional(z.object({}).passthrough()), }) .passthrough(); From 8b9aa20b390699ef851863e28c1ef7a52adbe2ec Mon Sep 17 00:00:00 2001 From: Jerome Date: Tue, 17 Jun 2025 10:18:58 +0100 Subject: [PATCH 15/18] Jerome/fix/dev oauth server required scopes change (#629) * updating lock to latest version * Added .git-blame-ignore-revs (fixes gitlens) * Not requiring mcp:tools --- .git-blame-ignore-revs | 0 package-lock.json | 4 ++-- src/examples/server/simpleStreamableHttp.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) create mode 100644 .git-blame-ignore-revs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 00000000..e69de29b diff --git a/package-lock.json b/package-lock.json index 40bad9fe..c676d07f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.11.4", + "version": "1.12.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@modelcontextprotocol/sdk", - "version": "1.11.4", + "version": "1.12.3", "license": "MIT", "dependencies": { "ajv": "^6.12.6", diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index 52c49caf..4f424151 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -477,7 +477,7 @@ if (useOAuth) { authMiddleware = requireBearerAuth({ verifier: tokenVerifier, - requiredScopes: ['mcp:tools'], + requiredScopes: [], resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl), }); } From 4f708a777f5bfd81bd590a4d647b310038beb551 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Tue, 17 Jun 2025 11:38:00 +0100 Subject: [PATCH 16/18] update latest protocol version --- src/client/auth.test.ts | 3 ++- .../stateManagementStreamableHttp.test.ts | 14 +++++++------- src/types.test.ts | 3 ++- src/types.ts | 3 ++- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index 1b9fb071..8f415c17 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -1,3 +1,4 @@ +import { LATEST_PROTOCOL_VERSION } from '../types.js'; import { discoverOAuthMetadata, startAuthorization, @@ -202,7 +203,7 @@ describe("OAuth Authorization", () => { const [url, options] = calls[0]; expect(url.toString()).toBe("https://auth.example.com/.well-known/oauth-authorization-server"); expect(options.headers).toEqual({ - "MCP-Protocol-Version": "2025-03-26" + "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION }); }); diff --git a/src/integration-tests/stateManagementStreamableHttp.test.ts b/src/integration-tests/stateManagementStreamableHttp.test.ts index d12a4f99..4a191134 100644 --- a/src/integration-tests/stateManagementStreamableHttp.test.ts +++ b/src/integration-tests/stateManagementStreamableHttp.test.ts @@ -5,7 +5,7 @@ import { Client } from '../client/index.js'; import { StreamableHTTPClientTransport } from '../client/streamableHttp.js'; import { McpServer } from '../server/mcp.js'; import { StreamableHTTPServerTransport } from '../server/streamableHttp.js'; -import { CallToolResultSchema, ListToolsResultSchema, ListResourcesResultSchema, ListPromptsResultSchema, DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from '../types.js'; +import { CallToolResultSchema, ListToolsResultSchema, ListResourcesResultSchema, ListPromptsResultSchema, LATEST_PROTOCOL_VERSION } from '../types.js'; import { z } from 'zod'; describe('Streamable HTTP Transport Session Management', () => { @@ -145,7 +145,7 @@ describe('Streamable HTTP Transport Session Management', () => { params: {} }, ListToolsResultSchema); - + }); it('should operate without session management', async () => { // Create and connect a client @@ -220,15 +220,15 @@ describe('Streamable HTTP Transport Session Management', () => { }); const transport = new StreamableHTTPClientTransport(baseUrl); - + // Verify protocol version is not set before connecting expect(transport.protocolVersion).toBeUndefined(); - + await client.connect(transport); - + // Verify protocol version is set after connecting - expect(transport.protocolVersion).toBe(DEFAULT_NEGOTIATED_PROTOCOL_VERSION); - + expect(transport.protocolVersion).toBe(LATEST_PROTOCOL_VERSION); + // Clean up await transport.close(); }); diff --git a/src/types.test.ts b/src/types.test.ts index bc109110..0115f2ed 100644 --- a/src/types.test.ts +++ b/src/types.test.ts @@ -12,7 +12,7 @@ describe("Types", () => { test("should have correct latest protocol version", () => { expect(LATEST_PROTOCOL_VERSION).toBeDefined(); - expect(LATEST_PROTOCOL_VERSION).toBe("2025-03-26"); + expect(LATEST_PROTOCOL_VERSION).toBe("2025-06-17"); }); test("should have correct supported protocol versions", () => { expect(SUPPORTED_PROTOCOL_VERSIONS).toBeDefined(); @@ -20,6 +20,7 @@ describe("Types", () => { expect(SUPPORTED_PROTOCOL_VERSIONS).toContain(LATEST_PROTOCOL_VERSION); expect(SUPPORTED_PROTOCOL_VERSIONS).toContain("2024-11-05"); expect(SUPPORTED_PROTOCOL_VERSIONS).toContain("2024-10-07"); + expect(SUPPORTED_PROTOCOL_VERSIONS).toContain("2025-03-26"); }); describe("ResourceLink", () => { diff --git a/src/types.ts b/src/types.ts index 1f7f6fa0..a6f59623 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,9 +1,10 @@ import { z, ZodTypeAny } from "zod"; -export const LATEST_PROTOCOL_VERSION = "2025-03-26"; +export const LATEST_PROTOCOL_VERSION = "2025-06-17"; export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; export const SUPPORTED_PROTOCOL_VERSIONS = [ LATEST_PROTOCOL_VERSION, + "2025-03-26", "2024-11-05", "2024-10-07", ]; From 741a201a3d4bff3e98bb1003b444414f9602100e Mon Sep 17 00:00:00 2001 From: ihrpr Date: Tue, 17 Jun 2025 12:35:29 +0100 Subject: [PATCH 17/18] remove hasCustomTitle --- src/shared/metadataUtils.ts | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/shared/metadataUtils.ts b/src/shared/metadataUtils.ts index 410827a5..0119a669 100644 --- a/src/shared/metadataUtils.ts +++ b/src/shared/metadataUtils.ts @@ -15,7 +15,7 @@ export function getDisplayName(metadata: BaseMetadata): string { if (metadata.title !== undefined && metadata.title !== '') { return metadata.title; } - + // Then check for annotations.title (only present in Tool objects) if ('annotations' in metadata) { const metadataWithAnnotations = metadata as BaseMetadata & { annotations?: { title?: string } }; @@ -23,14 +23,7 @@ export function getDisplayName(metadata: BaseMetadata): string { return metadataWithAnnotations.annotations.title; } } - + // Finally fall back to name return metadata.name; } - -/** - * Checks if an object has a custom title different from its name. - */ -export function hasCustomTitle(metadata: BaseMetadata): boolean { - return metadata.title !== undefined && metadata.title !== metadata.name; -} \ No newline at end of file From 66465abdd91ac7c72c8397358cf4adbf4284fd33 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Tue, 17 Jun 2025 17:29:41 +0100 Subject: [PATCH 18/18] change version --- src/types.test.ts | 2 +- src/types.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/types.test.ts b/src/types.test.ts index 0115f2ed..0aee62a9 100644 --- a/src/types.test.ts +++ b/src/types.test.ts @@ -12,7 +12,7 @@ describe("Types", () => { test("should have correct latest protocol version", () => { expect(LATEST_PROTOCOL_VERSION).toBeDefined(); - expect(LATEST_PROTOCOL_VERSION).toBe("2025-06-17"); + expect(LATEST_PROTOCOL_VERSION).toBe("2025-06-18"); }); test("should have correct supported protocol versions", () => { expect(SUPPORTED_PROTOCOL_VERSIONS).toBeDefined(); diff --git a/src/types.ts b/src/types.ts index a6f59623..e16b313d 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,6 +1,6 @@ import { z, ZodTypeAny } from "zod"; -export const LATEST_PROTOCOL_VERSION = "2025-06-17"; +export const LATEST_PROTOCOL_VERSION = "2025-06-18"; export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; export const SUPPORTED_PROTOCOL_VERSIONS = [ LATEST_PROTOCOL_VERSION,