diff --git a/package.json b/package.json index ef5f5d103..3a741fc84 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "fetch:spec-types": "curl -o spec.types.ts https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/refs/heads/main/schema/draft/schema.ts", "generate:strict-types": "tsx scripts/generateStrictTypes.ts", "check:strict-types": "npm run generate:strict-types && git diff --exit-code src/strictTypes.ts || (echo 'Error: strictTypes.ts is out of date. Run npm run generate:strict-types' && exit 1)", + "test:strict-types": "node scripts/test-strict-types.js", "build": "npm run build:esm && npm run build:cjs", "build:esm": "mkdir -p dist/esm && echo '{\"type\": \"module\"}' > dist/esm/package.json && tsc -p tsconfig.prod.json", "build:esm:w": "npm run build:esm -- -w", @@ -46,7 +47,7 @@ "examples:simple-server:w": "tsx --watch src/examples/server/simpleStreamableHttp.ts --oauth", "prepack": "npm run build:esm && npm run build:cjs", "lint": "eslint src/", - "test": "npm run fetch:spec-types && jest", + "test": "npm run fetch:spec-types && jest && npm run test:strict-types", "start": "npm run server", "server": "tsx watch --clear-screen=false src/cli.ts server", "client": "tsx src/cli.ts client" diff --git a/scripts/generateStrictTypes.ts b/scripts/generateStrictTypes.ts index 6c9ec2097..6bfa29d2e 100755 --- a/scripts/generateStrictTypes.ts +++ b/scripts/generateStrictTypes.ts @@ -11,6 +11,10 @@ const strictTypesPath = join(__dirname, '../src/strictTypes.ts'); let content = readFileSync(typesPath, 'utf-8'); +// Remove the @deprecated comment block +const deprecatedCommentPattern = /\/\*\*\s*\n\s*\*\s*@deprecated[\s\S]*?\*\/\s*\n/; +content = content.replace(deprecatedCommentPattern, ''); + // Add header comment const header = `/** * Types remove unknown @@ -24,37 +28,40 @@ const header = `/** `; -// Replace all .passthrough() with .strip() -content = content.replace(/\.passthrough\(\)/g, '.strip()'); +// Replace all .passthrough() with a temporary marker +content = content.replace(/\.passthrough\(\)/g, '.__TEMP_MARKED_FOR_REMOVAL__()'); // Special handling for experimental and capabilities that should remain open // These are explicitly designed to be extensible const patternsToKeepOpen = [ // Keep experimental fields open as they're meant for extensions - /experimental: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, + /experimental: z\.optional\(z\.object\(\{\}\)\.__TEMP_MARKED_FOR_REMOVAL__\(\)\)/g, // Keep _meta fields open as they're meant for arbitrary metadata - /_meta: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, + /_meta: z\.optional\(z\.object\(\{\}\)\.__TEMP_MARKED_FOR_REMOVAL__\(\)\)/g, // Keep JSON Schema properties open as they can have arbitrary fields - /properties: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, + /properties: z\.optional\(z\.object\(\{\}\)\.__TEMP_MARKED_FOR_REMOVAL__\(\)\)/g, // Keep BaseRequestParamsSchema passthrough for JSON-RPC param compatibility - /const BaseRequestParamsSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.strip\(\)/g, + /const BaseRequestParamsSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.__TEMP_MARKED_FOR_REMOVAL__\(\)/g, // Keep BaseNotificationParamsSchema passthrough for JSON-RPC param compatibility - /const BaseNotificationParamsSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.strip\(\)/g, + /const BaseNotificationParamsSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.__TEMP_MARKED_FOR_REMOVAL__\(\)/g, // Keep RequestMetaSchema passthrough for extensibility - /const RequestMetaSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.strip\(\)/g, + /const RequestMetaSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.__TEMP_MARKED_FOR_REMOVAL__\(\)/g, // Keep structuredContent passthrough for tool-specific output - /structuredContent: z\.object\(\{\}\)\.strip\(\)\.optional\(\)/g, + /structuredContent: z\.object\(\{\}\)\.__TEMP_MARKED_FOR_REMOVAL__\(\)\.optional\(\)/g, // Keep metadata passthrough for provider-specific data in sampling - /metadata: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, + /metadata: z\.optional\(z\.object\(\{\}\)\.__TEMP_MARKED_FOR_REMOVAL__\(\)\)/g, ]; -// Revert strip back to passthrough for these special cases +// Revert marker back to passthrough for these special cases patternsToKeepOpen.forEach(pattern => { content = content.replace(pattern, (match) => - match.replace('.strip()', '.passthrough()') + match.replace('.__TEMP_MARKED_FOR_REMOVAL__()', '.passthrough()') ); }); +// Remove the temporary marker from all remaining locations (these become no modifier) +content = content.replace(/\.__TEMP_MARKED_FOR_REMOVAL__\(\)/g, ''); + // Add a comment explaining the difference const explanation = ` /** @@ -68,7 +75,7 @@ const explanation = ` * - structuredContent: Tool-specific output that can have arbitrary fields * - metadata: Provider-specific metadata in sampling requests * - * All other objects use .strip() to remove unknown properties while + * All other objects use default behavior (no modifier) to remove unknown properties while * maintaining compatibility with extended protocols. */ `; diff --git a/scripts/test-strict-types.js b/scripts/test-strict-types.js new file mode 100644 index 000000000..bad99ee17 --- /dev/null +++ b/scripts/test-strict-types.js @@ -0,0 +1,93 @@ +#!/usr/bin/env node + +import { execSync } from 'child_process'; +import { readFileSync, writeFileSync, existsSync } from 'fs'; +import { join, dirname } from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const rootDir = join(__dirname, '..'); + +const files = [ + 'src/client/index.ts', + 'src/server/index.ts', + 'src/server/mcp.ts' +]; + +console.log('Testing strict types compatibility...'); +console.log('======================================\n'); + +// Backup original files +const backups = {}; +files.forEach(file => { + const fullPath = join(rootDir, file); + if (existsSync(fullPath)) { + backups[file] = readFileSync(fullPath, 'utf8'); + + // Replace imports + const content = backups[file]; + const newContent = content.replace(/from "\.\.\/types\.js"/g, 'from "../strictTypes.js"'); + writeFileSync(fullPath, newContent); + console.log(`✓ Replaced imports in ${file}`); + } +}); + +console.log('\nRunning TypeScript compilation...\n'); + +try { + // Run TypeScript compilation + execSync('npm run build', { cwd: rootDir, stdio: 'pipe' }); + console.log('✓ No type errors found!'); +} catch (error) { + // Extract and format type errors + const output = error.stdout?.toString() || error.stderr?.toString() || ''; + const lines = output.split('\n'); + + const errors = []; + let currentError = null; + + lines.forEach((line, i) => { + if (line.includes('error TS')) { + if (currentError) { + errors.push(currentError); + } + currentError = { + file: line.split('(')[0], + location: line.match(/\((\d+),(\d+)\)/)?.[0] || '', + code: line.match(/error (TS\d+)/)?.[1] || '', + message: line.split(/error TS\d+:/)[1]?.trim() || '', + context: [] + }; + } else if (currentError && line.trim() && !line.startsWith('npm ')) { + currentError.context.push(line); + } + }); + + if (currentError) { + errors.push(currentError); + } + + // Display errors + console.log(`Found ${errors.length} type error(s):\n`); + + errors.forEach((error, index) => { + console.log(`${index + 1}. ${error.file}${error.location}`); + console.log(` Error ${error.code}: ${error.message}`); + if (error.context.length > 0) { + console.log(` Context:`); + error.context.slice(0, 3).forEach(line => { + console.log(` ${line.trim()}`); + }); + } + console.log(''); + }); +} + +// Restore original files +console.log('Restoring original files...'); +Object.entries(backups).forEach(([file, content]) => { + const fullPath = join(rootDir, file); + writeFileSync(fullPath, content); +}); + +console.log('✓ Original files restored.'); \ No newline at end of file diff --git a/scripts/test-strict-types.sh b/scripts/test-strict-types.sh new file mode 100755 index 000000000..c9f2ce320 --- /dev/null +++ b/scripts/test-strict-types.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +# Script to test strict types by replacing imports and running tests + +echo "Testing strict types compatibility..." +echo "======================================" + +# Save original files +cp src/client/index.ts src/client/index.ts.bak +cp src/server/index.ts src/server/index.ts.bak +cp src/server/mcp.ts src/server/mcp.ts.bak + +# Replace imports +sed -i '' 's/from "\.\.\/types\.js"/from "..\/strictTypes.js"/g' src/client/index.ts +sed -i '' 's/from "\.\.\/types\.js"/from "..\/strictTypes.js"/g' src/server/index.ts +sed -i '' 's/from "\.\.\/types\.js"/from "..\/strictTypes.js"/g' src/server/mcp.ts + +echo "Replaced imports in:" +echo " - src/client/index.ts" +echo " - src/server/index.ts" +echo " - src/server/mcp.ts" +echo "" + +# Run TypeScript compilation to get type errors +echo "Running TypeScript compilation..." +echo "" +npm run build 2>&1 | grep -E "(error TS|src/)" | grep -B1 "error TS" || true + +# Restore original files +mv src/client/index.ts.bak src/client/index.ts +mv src/server/index.ts.bak src/server/index.ts +mv src/server/mcp.ts.bak src/server/mcp.ts + +echo "" +echo "Original files restored." \ No newline at end of file diff --git a/src/client/index.test.ts b/src/client/index.test.ts index abd0c34e4..0fe5c29d8 100644 --- a/src/client/index.test.ts +++ b/src/client/index.test.ts @@ -217,11 +217,11 @@ test("should connect new client to old, supported server version", async () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + // Client initialization automatically uses LATEST_PROTOCOL_VERSION in the current SDK const client = new Client( { name: "new client", version: "1.0", - protocolVersion: LATEST_PROTOCOL_VERSION, }, { capabilities: { @@ -287,7 +287,6 @@ test("should negotiate version when client is old, and newer server supports its { name: "old client", version: "1.0", - protocolVersion: OLD_VERSION, }, { capabilities: { @@ -297,6 +296,17 @@ test("should negotiate version when client is old, and newer server supports its }, ); + // Mock the request method to simulate an old client sending OLD_VERSION + const originalRequest = client.request.bind(client); + client.request = jest.fn(async (request, schema, options) => { + // If this is the initialize request, modify the protocol version to simulate old client + if (request.method === "initialize" && request.params) { + request.params.protocolVersion = OLD_VERSION; + } + // Call the original request method with the potentially modified request + return originalRequest(request, schema, options); + }); + await Promise.all([ client.connect(clientTransport), server.connect(serverTransport), @@ -350,11 +360,13 @@ test("should throw when client is old, and server doesn't support its version", const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + // Client uses LATEST_PROTOCOL_VERSION by default, which is sufficient for this test + // The error occurs because the server returns FUTURE_VERSION (unsupported), + // not because of the client's version. Any client version would fail here. const client = new Client( { name: "old client", version: "1.0", - protocolVersion: OLD_VERSION, }, { capabilities: { @@ -880,6 +892,7 @@ describe('outputSchema validation', () => { server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === 'test-tool') { return { + content: [], // Required field for CallToolResult structuredContent: { result: 'success', count: 42 }, }; } @@ -903,7 +916,11 @@ describe('outputSchema validation', () => { // Call the tool - should validate successfully const result = await client.callTool({ name: 'test-tool' }); - expect(result.structuredContent).toEqual({ result: 'success', count: 42 }); + // Type narrowing: check if structuredContent exists before accessing + expect('structuredContent' in result).toBe(true); + if ('structuredContent' in result) { + expect(result.structuredContent).toEqual({ result: 'success', count: 42 }); + } }); /*** @@ -955,6 +972,7 @@ describe('outputSchema validation', () => { if (request.params.name === 'test-tool') { // Return invalid structured content (count is string instead of number) return { + content: [], // Required field for CallToolResult structuredContent: { result: 'success', count: 'not a number' }, }; } @@ -1120,7 +1138,11 @@ describe('outputSchema validation', () => { // Call the tool - should work normally without validation const result = await client.callTool({ name: 'test-tool' }); - expect(result.content).toEqual([{ type: 'text', text: 'Normal response' }]); + // Type narrowing: check if content exists before accessing + expect('content' in result).toBe(true); + if ('content' in result) { + expect(result.content).toEqual([{ type: 'text', text: 'Normal response' }]); + } }); /*** @@ -1184,6 +1206,7 @@ describe('outputSchema validation', () => { server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === 'complex-tool') { return { + content: [], // Required field for CallToolResult structuredContent: { name: 'John Doe', age: 30, @@ -1215,10 +1238,14 @@ describe('outputSchema validation', () => { // Call the tool - should validate successfully const result = await client.callTool({ name: 'complex-tool' }); - expect(result.structuredContent).toBeDefined(); - const structuredContent = result.structuredContent as { name: string; age: number }; - expect(structuredContent.name).toBe('John Doe'); - expect(structuredContent.age).toBe(30); + // Type narrowing: check if structuredContent exists before accessing + expect('structuredContent' in result).toBe(true); + if ('structuredContent' in result) { + expect(result.structuredContent).toBeDefined(); + const structuredContent = result.structuredContent as { name: string; age: number }; + expect(structuredContent.name).toBe('John Doe'); + expect(structuredContent.age).toBe(30); + } }); /*** @@ -1269,6 +1296,7 @@ describe('outputSchema validation', () => { if (request.params.name === 'strict-tool') { // Return structured content with extra property return { + content: [], // Required field for CallToolResult structuredContent: { name: 'John', extraField: 'not allowed', diff --git a/src/client/index.ts b/src/client/index.ts index 3e8d8ec80..10ad35b53 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -42,6 +42,16 @@ import { Tool, ErrorCode, McpError, + EmptyResult, + CompleteResult, + GetPromptResult, + ListPromptsResult, + ListResourcesResult, + ListResourceTemplatesResult, + ReadResourceResult, + CompatibilityCallToolResult, + CallToolResult, + ListToolsResult, } from "../types.js"; import Ajv from "ajv"; import type { ValidateFunction } from "ajv"; @@ -329,11 +339,11 @@ export class Client< } } - async ping(options?: RequestOptions) { + async ping(options?: RequestOptions): Promise { return this.request({ method: "ping" }, EmptyResultSchema, options); } - async complete(params: CompleteRequest["params"], options?: RequestOptions) { + async complete(params: CompleteRequest["params"], options?: RequestOptions): Promise { return this.request( { method: "completion/complete", params }, CompleteResultSchema, @@ -341,7 +351,7 @@ export class Client< ); } - async setLoggingLevel(level: LoggingLevel, options?: RequestOptions) { + async setLoggingLevel(level: LoggingLevel, options?: RequestOptions): Promise { return this.request( { method: "logging/setLevel", params: { level } }, EmptyResultSchema, @@ -352,7 +362,7 @@ export class Client< async getPrompt( params: GetPromptRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "prompts/get", params }, GetPromptResultSchema, @@ -363,7 +373,7 @@ export class Client< async listPrompts( params?: ListPromptsRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "prompts/list", params }, ListPromptsResultSchema, @@ -374,7 +384,7 @@ export class Client< async listResources( params?: ListResourcesRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "resources/list", params }, ListResourcesResultSchema, @@ -385,7 +395,7 @@ export class Client< async listResourceTemplates( params?: ListResourceTemplatesRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "resources/templates/list", params }, ListResourceTemplatesResultSchema, @@ -396,7 +406,7 @@ export class Client< async readResource( params: ReadResourceRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "resources/read", params }, ReadResourceResultSchema, @@ -407,7 +417,7 @@ export class Client< async subscribeResource( params: SubscribeRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "resources/subscribe", params }, EmptyResultSchema, @@ -418,7 +428,7 @@ export class Client< async unsubscribeResource( params: UnsubscribeRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "resources/unsubscribe", params }, EmptyResultSchema, @@ -432,7 +442,8 @@ export class Client< | typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema = CallToolResultSchema, options?: RequestOptions, - ) { + ): Promise { + // Ensure the tool name is provided const result = await this.request( { method: "tools/call", params }, resultSchema, @@ -443,7 +454,11 @@ export class Client< const validator = this.getToolOutputValidator(params.name); if (validator) { // If tool has outputSchema, it MUST return structuredContent (unless it's an error) - if (!result.structuredContent && !result.isError) { + // Use property presence checks for union type compatibility + const hasStructuredContent = 'structuredContent' in result && result.structuredContent !== undefined; + const hasError = 'isError' in result && result.isError; + + if (!hasStructuredContent && !hasError) { throw new McpError( ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content` @@ -451,7 +466,7 @@ export class Client< } // Only validate structured content if present (not when there's an error) - if (result.structuredContent) { + if (hasStructuredContent) { try { // Validate the structured content (which is already an object) against the schema const isValid = validator(result.structuredContent); @@ -500,7 +515,7 @@ export class Client< async listTools( params?: ListToolsRequest["params"], options?: RequestOptions, - ) { + ): Promise { const result = await this.request( { method: "tools/list", params }, ListToolsResultSchema, diff --git a/src/integration-tests/taskResumability.test.ts b/src/integration-tests/taskResumability.test.ts index efd2611f8..fbd39a1ab 100644 --- a/src/integration-tests/taskResumability.test.ts +++ b/src/integration-tests/taskResumability.test.ts @@ -149,15 +149,14 @@ describe('Transport resumability', () => { // This test demonstrates the capability to resume long-running tools // across client disconnection/reconnection it('should resume long-running notifications with lastEventId', async () => { - // Create unique client ID for this test - const clientId = 'test-client-long-running'; + // Create unique client name for this test + const clientName = 'test-client-long-running'; const notifications = []; let lastEventId: string | undefined; // Create first client const client1 = new Client({ - id: clientId, - name: 'test-client', + name: clientName, version: '1.0.0' }); @@ -225,10 +224,9 @@ describe('Transport resumability', () => { await catchPromise; - // Create second client with same client ID + // Create second client with same client name const client2 = new Client({ - id: clientId, - name: 'test-client', + name: clientName, version: '1.0.0' }); diff --git a/src/server/index.test.ts b/src/server/index.test.ts index 46205d726..912f84a15 100644 --- a/src/server/index.test.ts +++ b/src/server/index.test.ts @@ -730,11 +730,6 @@ test("should handle server cancelling a request", async () => { name: "test server", version: "1.0", }, - { - capabilities: { - sampling: {}, - }, - }, ); const client = new Client( @@ -798,11 +793,6 @@ test("should handle request timeout", async () => { name: "test server", version: "1.0", }, - { - capabilities: { - sampling: {}, - }, - }, ); // Set up client that delays responses diff --git a/src/server/index.ts b/src/server/index.ts index 10ae2fadc..8e76aaf77 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -7,10 +7,12 @@ import { import { ClientCapabilities, CreateMessageRequest, + CreateMessageResult, CreateMessageResultSchema, ElicitRequest, ElicitResult, ElicitResultSchema, + EmptyResult, EmptyResultSchema, Implementation, InitializedNotificationSchema, @@ -19,6 +21,7 @@ import { InitializeResult, LATEST_PROTOCOL_VERSION, ListRootsRequest, + ListRootsResult, ListRootsResultSchema, LoggingMessageNotification, McpError, @@ -206,14 +209,6 @@ export class Server< protected assertRequestHandlerCapability(method: string): void { switch (method) { - case "sampling/createMessage": - if (!this._capabilities.sampling) { - throw new Error( - `Server does not support sampling (required for ${method})`, - ); - } - break; - case "logging/setLevel": if (!this._capabilities.logging) { throw new Error( @@ -295,14 +290,14 @@ export class Server< return this._capabilities; } - async ping() { + async ping(): Promise { return this.request({ method: "ping" }, EmptyResultSchema); } async createMessage( params: CreateMessageRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "sampling/createMessage", params }, CreateMessageResultSchema, @@ -351,7 +346,7 @@ export class Server< async listRoots( params?: ListRootsRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "roots/list", params }, ListRootsResultSchema, @@ -359,28 +354,28 @@ export class Server< ); } - async sendLoggingMessage(params: LoggingMessageNotification["params"]) { + async sendLoggingMessage(params: LoggingMessageNotification["params"]): Promise { return this.notification({ method: "notifications/message", params }); } - async sendResourceUpdated(params: ResourceUpdatedNotification["params"]) { + async sendResourceUpdated(params: ResourceUpdatedNotification["params"]): Promise { return this.notification({ method: "notifications/resources/updated", params, }); } - async sendResourceListChanged() { + async sendResourceListChanged(): Promise { return this.notification({ method: "notifications/resources/list_changed", }); } - async sendToolListChanged() { + async sendToolListChanged(): Promise { return this.notification({ method: "notifications/tools/list_changed" }); } - async sendPromptListChanged() { + async sendPromptListChanged(): Promise { return this.notification({ method: "notifications/prompts/list_changed" }); } } diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 10e550df4..16b02a886 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -3626,11 +3626,10 @@ describe("prompt()", () => { }), }), { - name: "Template Name", description: "Template description", mimeType: "application/json", }, - async (uri) => ({ + async (uri: URL) => ({ contents: [ { uri: uri.href, @@ -4210,10 +4209,15 @@ describe("elicitInput()", () => { 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" - }]); + + // Type narrowing for union type + expect('content' in result).toBe(true); + if ('content' in result) { + 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 elicitation request", async () => { @@ -4249,10 +4253,14 @@ describe("elicitInput()", () => { expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); expect(findAlternatives).not.toHaveBeenCalled(); - expect(result.content).toEqual([{ + // Type narrowing for union type + expect('content' in result).toBe(true); + if ('content' in result) { + expect(result.content).toEqual([{ type: "text", text: "No booking made. Original date not available." }]); + } }); test("should handle user cancelling the elicitation", async () => { @@ -4285,9 +4293,13 @@ describe("elicitInput()", () => { expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); expect(findAlternatives).not.toHaveBeenCalled(); - expect(result.content).toEqual([{ + // Type narrowing for union type + expect('content' in result).toBe(true); + if ('content' in result) { + expect(result.content).toEqual([{ type: "text", text: "No booking made. Original date not available." }]); + } }); }); diff --git a/src/server/mcp.ts b/src/server/mcp.ts index 791facef1..69897ac3c 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -313,7 +313,7 @@ export class McpServer { throw new McpError( ErrorCode.InvalidParams, - `Resource template ${request.params.ref.uri} not found`, + `Resource template ${'uri' in request.params.ref ? request.params.ref.uri : 'unknown'} not found`, ); } diff --git a/src/server/title.test.ts b/src/server/title.test.ts index 3f64570b8..3a9352dc4 100644 --- a/src/server/title.test.ts +++ b/src/server/title.test.ts @@ -208,7 +208,13 @@ describe("Title field backwards compatibility", () => { // Test reading the resource const readResult = await client.readResource({ uri: "users://123/profile" }); expect(readResult.contents).toHaveLength(1); - expect(readResult.contents[0].text).toBe("Profile data for user 123"); + + // Type narrowing for union type (text vs blob content) + const content = readResult.contents[0]; + expect('text' in content).toBe(true); + if ('text' in content) { + expect(content.text).toBe("Profile data for user 123"); + } }); it("should support serverInfo with title", async () => { diff --git a/src/strictTypes.ts b/src/strictTypes.ts index b59cfae0e..b13c43229 100644 --- a/src/strictTypes.ts +++ b/src/strictTypes.ts @@ -8,23 +8,6 @@ * @generated by scripts/generateStrictTypes.ts */ -/** - * @deprecated These extensible types with .strip() will be removed in a future version. - * - * For better type safety, use the types from "./strictTypes.js" instead. - * Those types use .strip() which provides compatibility with protocol extensions - * while ensuring type safety by removing unknown fields. - * - * Benefits of strictTypes.js: - * - Type safety: Only known fields are included in the result - * - No runtime errors: Unknown fields are silently stripped, not rejected - * - Protocol compatible: Works with extended servers/clients - * - * Migration guide: - * - Change: import { ToolSchema } from "@modelcontextprotocol/sdk/types.js" - * - To: import { ToolSchema } from "@modelcontextprotocol/sdk/strictTypes.js" - */ - import { z, ZodTypeAny } from "zod"; import { AuthInfo } from "./server/auth/types.js"; @@ -39,7 +22,7 @@ import { AuthInfo } from "./server/auth/types.js"; * - structuredContent: Tool-specific output that can have arbitrary fields * - metadata: Provider-specific metadata in sampling requests * - * All other objects use .strip() to remove unknown properties while + * All other objects use default behavior (no modifier) to remove unknown properties while * maintaining compatibility with extended protocols. */ @@ -108,7 +91,7 @@ export const ResultSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; /** * A uniquely identifying ID for a request in JSON-RPC. @@ -259,7 +242,7 @@ export const BaseMetadataSchema = z */ title: z.optional(z.string()), }) - .strip(); + ; /* Initialization */ /** @@ -281,11 +264,11 @@ export const ClientCapabilitiesSchema = z /** * Present if the client supports sampling from an LLM. */ - sampling: z.optional(z.object({}).strip()), + sampling: z.optional(z.object({})), /** * Present if the client supports eliciting user input. */ - elicitation: z.optional(z.object({}).strip()), + elicitation: z.optional(z.object({})), /** * Present if the client supports listing roots. */ @@ -297,10 +280,10 @@ export const ClientCapabilitiesSchema = z */ listChanged: z.optional(z.boolean()), }) - .strip(), + , ), }) - .strip(); + ; /** * This request is sent from the client to the server when it first connects, asking it to begin initialization. @@ -333,11 +316,11 @@ export const ServerCapabilitiesSchema = z /** * Present if the server supports sending log messages to the client. */ - logging: z.optional(z.object({}).strip()), + logging: z.optional(z.object({})), /** * Present if the server supports sending completions to the client. */ - completions: z.optional(z.object({}).strip()), + completions: z.optional(z.object({})), /** * Present if the server offers any prompt templates. */ @@ -349,7 +332,7 @@ export const ServerCapabilitiesSchema = z */ listChanged: z.optional(z.boolean()), }) - .strip(), + , ), /** * Present if the server offers any resources to read. @@ -367,7 +350,7 @@ export const ServerCapabilitiesSchema = z */ listChanged: z.optional(z.boolean()), }) - .strip(), + , ), /** * Present if the server offers any tools to call. @@ -380,10 +363,10 @@ export const ServerCapabilitiesSchema = z */ listChanged: z.optional(z.boolean()), }) - .strip(), + , ), }) - .strip(); + ; /** * After receiving an initialize request from the client, the server sends this response. @@ -437,7 +420,7 @@ export const ProgressSchema = z */ message: z.optional(z.string()), }) - .strip(); + ; /** * An out-of-band notification used to inform the receiver of a progress update for a long-running request. @@ -491,7 +474,7 @@ export const ResourceContentsSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; export const TextResourceContentsSchema = ResourceContentsSchema.extend({ /** @@ -700,7 +683,7 @@ export const PromptArgumentSchema = z */ required: z.optional(z.boolean()), }) - .strip(); + ; /** * A prompt or prompt template that the server offers. @@ -769,7 +752,7 @@ export const TextContentSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; /** * An image provided to or from an LLM. @@ -792,7 +775,7 @@ export const ImageContentSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; /** * An Audio provided to or from an LLM. @@ -815,7 +798,7 @@ export const AudioContentSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; /** * The contents of a resource, embedded into a prompt or tool call result. @@ -830,7 +813,7 @@ export const EmbeddedResourceSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; /** * A resource that the server is capable of reading, included in a prompt or tool call result. @@ -860,7 +843,7 @@ export const PromptMessageSchema = z role: z.enum(["user", "assistant"]), content: ContentBlockSchema, }) - .strip(); + ; /** * The server's response to a prompts/get request from the client. @@ -935,7 +918,7 @@ export const ToolAnnotationsSchema = z */ openWorldHint: z.optional(z.boolean()), }) - .strip(); + ; /** * Definition for a tool the client can call. @@ -954,7 +937,7 @@ export const ToolSchema = BaseMetadataSchema.extend({ properties: z.optional(z.object({}).passthrough()), required: z.optional(z.array(z.string())), }) - .strip(), + , /** * An optional JSON Schema object defining the structure of the tool's output returned in * the structuredContent field of a CallToolResult. @@ -965,7 +948,7 @@ export const ToolSchema = BaseMetadataSchema.extend({ properties: z.optional(z.object({}).passthrough()), required: z.optional(z.array(z.string())), }) - .strip() + ), /** * Optional additional tool information. @@ -1116,7 +1099,7 @@ export const ModelHintSchema = z */ name: z.string().optional(), }) - .strip(); + ; /** * The server's preferences for model selection, requested of the client during sampling. @@ -1140,7 +1123,7 @@ export const ModelPreferencesSchema = z */ intelligencePriority: z.optional(z.number().min(0).max(1)), }) - .strip(); + ; /** * Describes a message issued to or received from an LLM API. @@ -1150,7 +1133,7 @@ export const SamplingMessageSchema = z role: z.enum(["user", "assistant"]), content: z.union([TextContentSchema, ImageContentSchema, AudioContentSchema]), }) - .strip(); + ; /** * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. @@ -1217,7 +1200,7 @@ export const BooleanSchemaSchema = z description: z.optional(z.string()), default: z.optional(z.boolean()), }) - .strip(); + ; /** * Primitive schema definition for string fields. @@ -1231,7 +1214,7 @@ export const StringSchemaSchema = z maxLength: z.optional(z.number()), format: z.optional(z.enum(["email", "uri", "date", "date-time"])), }) - .strip(); + ; /** * Primitive schema definition for number fields. @@ -1244,7 +1227,7 @@ export const NumberSchemaSchema = z minimum: z.optional(z.number()), maximum: z.optional(z.number()), }) - .strip(); + ; /** * Primitive schema definition for enum fields. @@ -1257,7 +1240,7 @@ export const EnumSchemaSchema = z enum: z.array(z.string()), enumNames: z.optional(z.array(z.string())), }) - .strip(); + ; /** * Union of all primitive schema definitions. @@ -1289,7 +1272,7 @@ export const ElicitRequestSchema = RequestSchema.extend({ properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), required: z.optional(z.array(z.string())), }) - .strip(), + , }), }); @@ -1319,7 +1302,7 @@ export const ResourceTemplateReferenceSchema = z */ uri: z.string(), }) - .strip(); + ; /** * @deprecated Use ResourceTemplateReferenceSchema instead @@ -1337,7 +1320,7 @@ export const PromptReferenceSchema = z */ name: z.string(), }) - .strip(); + ; /** * A request from the client to the server, to ask for completion options. @@ -1360,7 +1343,7 @@ export const CompleteRequestSchema = RequestSchema.extend({ */ value: z.string(), }) - .strip(), + , context: z.optional( z.object({ /** @@ -1391,7 +1374,7 @@ export const CompleteResultSchema = ResultSchema.extend({ */ hasMore: z.optional(z.boolean()), }) - .strip(), + , }); /* Roots */ @@ -1415,7 +1398,7 @@ export const RootSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; /** * Sent from the server to request a list of root URIs from the client.