/** * @file mcp-test-client.ts * @description Main MCP Test Client implementation for E2E testing */ import { MCP_20260728_META, PROTOCOL_2026_07_28, type DiscoverResult, type InputRequests, type InputRequiredResult, type InputResponses, type LoggingLevel, type SubscriptionFilter, } from '@frontmcp/protocol'; import { EventRequestError, EventsClient, type EventsClientTransport } from '@frontmcp/sdk'; import { trimSlashes } from '@frontmcp/utils'; import { DefaultInterceptorChain, mockResponse, type InterceptorChain, type MockDefinition, type MockHandle, type RequestInterceptor, type ResponseInterceptor, } from '../interceptor'; import { errorMessage, isInterceptedError } from '../transport/error-utils'; import { isStatelessRequest } from '../transport/mcp-20260728'; import { SseTransport } from '../transport/sse.transport'; import { StreamableHttpTransport } from '../transport/streamable-http.transport'; import type { JsonRpcRequest, McpTransport } from '../transport/transport.interface'; import { McpTestClientBuilder } from './mcp-test-client.builder'; import type { AuthState, CallToolResult, ElicitationCreateRequest, ElicitationHandler, ElicitResponse, GetPromptResult, InitializeResult, JSONRPCResponse, ListPromptsResult, ListResourcesResult, ListResourceTemplatesResult, ListToolsResult, LogEntry, McpErrorInfo, McpResponse, McpTestClientConfig, NotificationEntry, ProgressUpdate, Prompt, PromptResultWrapper, ReadResourceResult, RequestTrace, Resource, ResourceContentWrapper, ResourceTemplate, SessionInfo, TestClientCapabilities, TestTransportType, Tool, ToolCallOptions, ToolResultWrapper, } from './mcp-test-client.types'; // ═══════════════════════════════════════════════════════════════════ // CONSTANTS // ═══════════════════════════════════════════════════════════════════ const DEFAULT_TIMEOUT = 30000; const DEFAULT_PROTOCOL_VERSION = '2025-06-18'; const DEFAULT_MCP_LOG_LEVEL: LoggingLevel = 'debug'; /** Most `input_required` answers one call gives before it fails, so a server that never settles can't hang a spec. */ const MAX_INPUT_ROUNDS = 10; const LIST_CHANGED_SUBSCRIPTIONS: SubscriptionFilter = { toolsListChanged: true, promptsListChanged: true, resourcesListChanged: true, }; const DEFAULT_CLIENT_INFO = { name: '@frontmcp/testing', version: '0.4.0', }; /** * Most pages one `list()` call follows. A server whose cursor never runs out * fails the spec with a clear error instead of hanging it. */ const MAX_LIST_PAGES = 1000; // ═══════════════════════════════════════════════════════════════════ // MAIN CLIENT CLASS // ═══════════════════════════════════════════════════════════════════ /** The server answered `initialize` with 401/403 — an auth decision, not a server that is still starting. */ function isAuthFailure(error: McpErrorInfo | undefined): boolean { return typeof error?.message === 'string' && /^HTTP (401|403)\b/.test(error.message); } /** Message plus the server's response text, so `toThrow('expired')` can match the reason. */ function describeInitializeError(error: McpErrorInfo | undefined): string { const message = error?.message ?? 'Unknown error'; const data = error?.data; const detail = typeof data === 'string' ? data.trim() : ''; return detail ? `${message} - ${detail.slice(0, 500)}` : message; } /** What `initialize` would have told a 2025 client, from a 2026-07-28 `server/discover` result. */ function initializeResultFrom(discovered: DiscoverResult): InitializeResult { const serverInfo = discovered._meta?.[MCP_20260728_META.serverInfo] ?? { name: '', version: '' }; return { protocolVersion: PROTOCOL_2026_07_28, capabilities: discovered.capabilities, serverInfo, ...(discovered.instructions !== undefined && { instructions: discovered.instructions }), }; } function isInputRequired(result: unknown): result is InputRequiredResult { return (result as { resultType?: unknown } | undefined)?.resultType === 'input_required'; } /** * Pull `entryPaths` out of a 404 body the server produced. * * The web-fetch host answers an unmatched path with * `{"error":"Not Found","entryPaths":["/mcp"]}`, and the transport passes that * body through as the JSON-RPC error's `data`. It arrives as a string, so parse * defensively — any other body simply yields `undefined` (issue #543). */ function extractEntryPaths(data: unknown): string[] | undefined { let payload: unknown = data; if (typeof payload === 'string') { try { payload = JSON.parse(payload); } catch { return undefined; } } if (!payload || typeof payload !== 'object') return undefined; const paths = (payload as { entryPaths?: unknown }).entryPaths; if (!Array.isArray(paths)) return undefined; const strings = paths.filter((p): p is string => typeof p === 'string'); return strings.length > 0 ? strings : undefined; } export class McpTestClient { // Platform, capabilities, and queryParams are optional - only set when needed private readonly config: Required< Omit > & Pick; /** Protocol 2026-07-28: the resources `resources.subscribe()` listens to. */ private readonly resourceSubscriptions = new Set(); /** Protocol 2026-07-28: whether the tools were listed since connecting, which mirrors `x-mcp-header` arguments. */ private toolsListed = false; private transport: McpTransport | null = null; private initResult: InitializeResult | null = null; private requestIdCounter = 0; private _lastRequestId: string | number = 0; private _sessionId: string | undefined; /** #543 — discovery is attempted at most once per connect. */ private triedDiscoveredEntryPath = false; private _sessionInfo: SessionInfo | null = null; private _authState: AuthState = { isAnonymous: true, scopes: [] }; // Logging and tracing private _logs: LogEntry[] = []; private _traces: RequestTrace[] = []; private _notifications: NotificationEntry[] = []; private _progressUpdates: ProgressUpdate[] = []; private collectingProgress = false; private progressTokenCounter = 0; // Interceptor chain private _interceptors: InterceptorChain; // Elicitation handler for server→client elicit requests private _elicitationHandler?: ElicitationHandler; private eventsClient?: EventsClient; // ═══════════════════════════════════════════════════════════════════ // CONSTRUCTOR & FACTORY // ═══════════════════════════════════════════════════════════════════ constructor(config: McpTestClientConfig) { if (config.protocolVersion === PROTOCOL_2026_07_28 && config.transport === 'sse') { throw new Error( `Protocol version ${PROTOCOL_2026_07_28} has no HTTP+SSE transport: use 'streamable-http', ` + `or a protocol version before it with 'sse'.`, ); } this.config = { baseUrl: config.baseUrl, entryPath: config.entryPath, transport: config.transport ?? 'streamable-http', auth: config.auth ?? {}, publicMode: config.publicMode ?? false, timeout: config.timeout ?? DEFAULT_TIMEOUT, debug: config.debug ?? false, protocolVersion: config.protocolVersion ?? DEFAULT_PROTOCOL_VERSION, mcpLogLevel: config.mcpLogLevel ?? DEFAULT_MCP_LOG_LEVEL, clientInfo: config.clientInfo ?? DEFAULT_CLIENT_INFO, platform: config.platform, capabilities: config.capabilities, queryParams: config.queryParams, events: config.events, }; // If a token is provided, user is authenticated (even in public mode) // Public mode just means anonymous access is allowed, not that tokens are ignored if (config.auth?.token) { this._authState = { isAnonymous: false, token: config.auth.token, scopes: this.parseScopesFromToken(config.auth.token), user: this.parseUserFromToken(config.auth.token), }; } // Otherwise, user is anonymous (default _authState is already { isAnonymous: true, scopes: [] }) // Initialize interceptor chain this._interceptors = new DefaultInterceptorChain(); } /** * Create a new McpTestClientBuilder for fluent configuration */ static create(config: McpTestClientConfig): McpTestClientBuilder { return new McpTestClientBuilder(config); } // ═══════════════════════════════════════════════════════════════════ // CONNECTION & LIFECYCLE // ═══════════════════════════════════════════════════════════════════ /** * Connect to the MCP server and perform initialization */ async connect(): Promise { this.log('debug', `Connecting to ${this.config.baseUrl}...`); // Discovery is once per CONNECT, not once per client: a reconnect may face a // server that now serves a different path. this.triedDiscoveredEntryPath = false; this.initResult = null; this.toolsListed = false; // Create transport based on config this.transport = this.createTransport(); // Connect transport await this.transport.connect(); // Retry initialization to handle brief window where server is up but routes not ready const maxRetries = 3; const retryDelayMs = 500; let lastError: string | undefined; let reportedEntryPaths: string[] | undefined; let attemptsMade = 0; for (let attempt = 1; attempt <= maxRetries; attempt++) { attemptsMade = attempt; const initResponse = this.isStateless ? await this.discoverServer() : await this.initialize(); if (initResponse.success && initResponse.data) { this.initResult = initResponse.data; break; } lastError = describeInitializeError(initResponse.error); reportedEntryPaths = extractEntryPaths(initResponse.error?.data) ?? reportedEntryPaths; // Issue #543 — a server with a non-default `http.entryPath` answers the // root with `{"error":"Not Found","entryPaths":["/mcp"]}`. Retrying at the // path it names turns a whole-suite failure into a connection, and is // strictly better than surfacing a bare HTTP 404 from client internals. if (reportedEntryPaths?.length === 1 && !this.triedDiscoveredEntryPath) { this.triedDiscoveredEntryPath = true; const discovered = reportedEntryPaths[0]; this.log('info', `Server serves MCP at ${discovered}; reconnecting there (configured: ${this.mcpPathLabel()})`); this.config.entryPath = discovered; await this.transport.close(); this.transport = this.createTransport(); await this.transport.connect(); continue; } // 401/403 are answers, not a server that is still starting: retrying only delays the failure if (isAuthFailure(initResponse.error)) break; if (attempt < maxRetries) { this.log('debug', `MCP init attempt ${attempt} failed (${lastError}), retrying in ${retryDelayMs}ms...`); await new Promise((resolve) => setTimeout(resolve, retryDelayMs)); } } if (!this.initResult) { const served = reportedEntryPaths?.length ? ` The server reports it serves MCP at ${reportedEntryPaths.join(', ')}; ` + `set \`entryPath\` in test.use() (or \`http.entryPath\` on the server) to match.` : ''; throw new Error( `Failed to initialize MCP connection to ${this.config.baseUrl}${this.mcpPathLabel()} ` + `after ${attemptsMade} attempt${attemptsMade === 1 ? '' : 's'}: ${lastError}.${served}`, ); } this._sessionId = this.transport.getSessionId(); this._sessionInfo = { id: this._sessionId ?? `session-${Date.now()}`, createdAt: new Date(), lastActivityAt: new Date(), requestCount: 1, }; if (this.isStateless) { await this.listen(); } else { // Send initialized notification per MCP protocol // This notification MUST be sent after receiving initialize response // before the client can make any other requests await this.transport.notify({ jsonrpc: '2.0', method: 'notifications/initialized', }); await this.transport.openNotificationStream?.(this.initResult.protocolVersion); await this.setServerLogLevel(); } this.log('info', `Connected to ${this.initResult.serverInfo?.name ?? 'MCP Server'}`); return this.initResult; } /** * Disconnect from the MCP server */ async disconnect(): Promise { await this.eventsClient?.close(); if (this.transport) { await this.transport.close(); this.transport = null; } this.initResult = null; this.log('info', 'Disconnected from MCP server'); } /** * Reconnect to the server, optionally with an existing session ID */ async reconnect(options?: { sessionId?: string }): Promise { await this.disconnect(); if (options?.sessionId && this.transport) { // Set session ID before reconnecting this._sessionId = options.sessionId; } await this.connect(); } /** * Check if the client is currently connected */ isConnected(): boolean { return this.transport?.isConnected() ?? false; } // ═══════════════════════════════════════════════════════════════════ // SESSION & AUTH PROPERTIES // ═══════════════════════════════════════════════════════════════════ get sessionId(): string { return this._sessionId ?? ''; } get session(): SessionInfo & { expire: () => Promise } { const info = this._sessionInfo ?? { id: '', createdAt: new Date(), lastActivityAt: new Date(), requestCount: 0, }; return { ...info, expire: async () => { // Force session expiration for testing this._sessionId = undefined; this._sessionInfo = null; }, }; } get auth(): AuthState { return this._authState; } /** * Authenticate with a token. * * When connected, this opens a NEW session with the token (the previous session was created * for the previous identity) and rejects if the server refuses it — for example because the * token is expired or badly signed. On rejection the client keeps its previous identity and * session. The token is kept in the client config, so `reconnect()` keeps using it. */ async authenticate(token: string): Promise { if (typeof token !== 'string' || token.trim() === '') { throw new Error('authenticate() requires a non-empty token'); } const previousAuthState = this._authState; const previousConfigAuth = this.config.auth; this.config.auth = { ...previousConfigAuth, token }; this._authState = { isAnonymous: false, token, scopes: this.parseScopesFromToken(token), user: this.parseUserFromToken(token), }; const previousTransport = this.transport; if (!previousTransport) { this.log('debug', 'Authentication updated (not connected yet)'); return; } const previousInit = this.initResult; const previousSessionId = this._sessionId; const previousSessionInfo = this._sessionInfo; try { await this.connect(); } catch (err) { await this.transport?.close().catch(() => undefined); this.transport = previousTransport; this.initResult = previousInit; this._sessionId = previousSessionId; this._sessionInfo = previousSessionInfo; this.config.auth = previousConfigAuth; this._authState = previousAuthState; throw err; } await previousTransport.close().catch(() => undefined); this.log('debug', 'Authentication updated'); } // ═══════════════════════════════════════════════════════════════════ // SERVER INFO & CAPABILITIES // ═══════════════════════════════════════════════════════════════════ get serverInfo(): { name: string; version: string; title?: string } { return { name: this.initResult?.serverInfo?.name ?? '', version: this.initResult?.serverInfo?.version ?? '', }; } get protocolVersion(): string { return this.initResult?.protocolVersion ?? ''; } get instructions(): string { return this.initResult?.instructions ?? ''; } get capabilities(): InitializeResult['capabilities'] { return this.initResult?.capabilities ?? {}; } /** * Check if server has a specific capability */ hasCapability(name: 'tools' | 'resources' | 'prompts' | 'logging' | 'sampling'): boolean { return !!this.capabilities[name]; } /** * Send `server/discover` and return what the server answers: its supported versions, capabilities, * instructions and `_meta` (with its server info). Sent as a 2026-07-28 request whatever revision * this client speaks, since the method exists only there. Throws with the server's error. */ async discover(): Promise { const response = await this.request('server/discover', {}); if (!response.success || !response.data) throw new Error(`server/discover failed: ${response.error?.message}`); return response.data; } // ═══════════════════════════════════════════════════════════════════ // TOOLS API // ═══════════════════════════════════════════════════════════════════ readonly tools = { /** * List all available tools */ list: async (): Promise => { const tools = await this.listAllPages( 'tools/list', 'tools', (cursor) => this.listTools(cursor), (page) => page.tools, ); this.toolsListed = true; return tools; }, /** * Call a tool by name with arguments */ call: async ( name: string, args?: Record, options: ToolCallOptions = {}, ): Promise => { await this.learnToolSchemas(); const response = await this.callTool(name, args, this.progressTokenFor(options)); return this.wrapToolResult(response); }, }; // ═══════════════════════════════════════════════════════════════════ // RESOURCES API // ═══════════════════════════════════════════════════════════════════ readonly resources = { /** * List all static resources */ list: async (): Promise => this.listAllPages( 'resources/list', 'resources', (cursor) => this.listResources(cursor), (page) => page.resources, ), /** * List all resource templates */ listTemplates: async (): Promise => this.listAllPages( 'resources/templates/list', 'resource templates', (cursor) => this.listResourceTemplates(cursor), (page) => page.resourceTemplates, ), /** * Read a resource by URI */ read: async (uri: string): Promise => { const response = await this.readResource(uri); return this.wrapResourceContent(response); }, /** * Subscribe to a resource: the server then sends `notifications/resources/updated` when it changes. * Throws with the server's error when it refuses the subscription. On 2026-07-28, which has no * `resources/subscribe`, the client listens again (`subscriptions/listen`) with the URI added, and * throws when the server doesn't acknowledge it. */ subscribe: async (uri: string): Promise => { if (this.isStateless) return this.listenToResource(uri); const response = await this.request('resources/subscribe', { uri }); if (!response.success) throw new Error(`Failed to subscribe to ${uri}: ${response.error?.message}`); }, /** * Unsubscribe from a resource's changes. */ unsubscribe: async (uri: string): Promise => { if (this.isStateless) { this.resourceSubscriptions.delete(uri); await this.listen(); return; } const response = await this.request('resources/unsubscribe', { uri }); if (!response.success) throw new Error(`Failed to unsubscribe from ${uri}: ${response.error?.message}`); }, }; // ═══════════════════════════════════════════════════════════════════ // PROMPTS API // ═══════════════════════════════════════════════════════════════════ readonly prompts = { /** * List all available prompts */ list: async (): Promise => this.listAllPages( 'prompts/list', 'prompts', (cursor) => this.listPrompts(cursor), (page) => page.prompts, ), /** * Get a prompt with arguments */ get: async (name: string, args?: Record): Promise => { const response = await this.getPrompt(name, args); return this.wrapPromptResult(response); }, }; // ═══════════════════════════════════════════════════════════════════ // EVENTS (MCP Events, SEP-3415) // ═══════════════════════════════════════════════════════════════════ /** * `events.list()` lists the event types; `events.subscribe(name, args)` subscribes to one and yields its * occurrences: by webhook when `withEvents({ webhook })` configured a receiver, else by push over Streamable HTTP, * else by poll. */ get events(): EventsClient { this.eventsClient ??= new EventsClient(this.eventsTransport(), this.config.events); return this.eventsClient; } /** The events client's way to the server: this client's requests, and `events/stream` over Streamable HTTP. */ private eventsTransport(): EventsClientTransport { const transport: EventsClientTransport = { request: async (method, params) => { const response = await this.request(method, params); if (!response.success) { const { code, message, data } = response.error as McpErrorInfo; throw new EventRequestError(method, code, message, data); } return response.data; }, }; if (this.config.transport === 'streamable-http') { transport.openStream = (params, onNotification, signal) => this.openEventStream(params, onNotification, signal); } return transport; } /** Hold an `events/stream` open; over a session, cancel it with `notifications/cancelled` when it is aborted. */ private async openEventStream( params: Record, onNotification: (notification: { method: string; params?: Record }) => void, signal: AbortSignal, ): Promise { const transport = this.getConnectedTransport(); const id = ++this.requestIdCounter; const message = { jsonrpc: '2.0' as const, id, method: 'events/stream', params }; const response = await transport.streamRequest?.(message, onNotification, signal); if (response?.error) { throw new EventRequestError('events/stream', response.error.code, response.error.message, response.error.data); } if (signal.aborted && !isStatelessRequest(this.config.protocolVersion, 'events/stream')) { await transport .notify({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: id } }) .catch(() => undefined); } } // ═══════════════════════════════════════════════════════════════════ // RAW PROTOCOL ACCESS // ═══════════════════════════════════════════════════════════════════ readonly raw = { /** * Send any JSON-RPC request */ request: async (message: { jsonrpc: '2.0'; id: string | number; method: string; params?: Record; }): Promise => { const transport = this.getConnectedTransport(); const start = Date.now(); const response = await transport.request(message); this.traceRequest(message.method, message.params, message.id, response, Date.now() - start); return response; }, /** * Send a notification (no response expected) */ notify: async (message: { jsonrpc: '2.0'; method: string; params?: Record }): Promise => { const transport = this.getConnectedTransport(); await transport.notify(message); }, /** * Send raw string data (for error testing) */ sendRaw: async (data: string): Promise => { const transport = this.getConnectedTransport(); return transport.sendRaw(data); }, }; get lastRequestId(): string | number { return this._lastRequestId; } // ═══════════════════════════════════════════════════════════════════ // TRANSPORT INFO // ═══════════════════════════════════════════════════════════════════ /** * Get transport information and utilities */ get transport_info(): { type: TestTransportType; isConnected: () => boolean; messageEndpoint: string | undefined; connectionCount: number; reconnectCount: number; lastRequestHeaders: Record; simulateDisconnect: () => Promise; waitForReconnect: (timeoutMs: number) => Promise; } { return { type: this.config.transport, isConnected: () => this.transport?.isConnected() ?? false, messageEndpoint: this.transport?.getMessageEndpoint?.(), connectionCount: this.transport?.getConnectionCount?.() ?? 0, reconnectCount: this.transport?.getReconnectCount?.() ?? 0, lastRequestHeaders: this.transport?.getLastRequestHeaders?.() ?? {}, simulateDisconnect: async () => { await this.transport?.simulateDisconnect?.(); }, waitForReconnect: async (timeoutMs: number) => { await this.transport?.waitForReconnect?.(timeoutMs); }, }; } // Alias for transport info get transport_() { return this.transport_info; } // ═══════════════════════════════════════════════════════════════════ // NOTIFICATIONS // ═══════════════════════════════════════════════════════════════════ readonly notifications = { /** * Start collecting server notifications */ collect: (): NotificationCollector => { return new NotificationCollector(this._notifications); }, /** * Collect progress notifications specifically */ collectProgress: (): ProgressCollector => { this.collectingProgress = true; return new ProgressCollector(this._progressUpdates); }, /** * Send a notification to the server */ send: async (method: string, params?: Record): Promise => { await this.raw.notify({ jsonrpc: '2.0', method, params }); }, }; // ═══════════════════════════════════════════════════════════════════ // ELICITATION // ═══════════════════════════════════════════════════════════════════ /** * Register a handler for elicitation requests from the server. * * When a tool calls `this.elicit()` during execution, the server sends an * `elicitation/create` request to the client. This handler is called to * provide the response that would normally come from user interaction. * * @param handler - Function that receives the elicitation request and returns a response * * @example * ```typescript * // Simple acceptance * mcp.onElicitation(async () => ({ * action: 'accept', * content: { confirmed: true } * })); * * // Conditional response based on request * mcp.onElicitation(async (request) => { * if (request.message.includes('delete')) { * return { action: 'decline' }; * } * return { action: 'accept', content: { approved: true } }; * }); * * // Multi-step wizard * let step = 0; * mcp.onElicitation(async () => { * step++; * if (step === 1) return { action: 'accept', content: { name: 'Alice' } }; * return { action: 'accept', content: { color: 'blue' } }; * }); * ``` */ onElicitation(handler: ElicitationHandler): void { this._elicitationHandler = handler; // Pass handler to transport if already connected if (this.transport?.setElicitationHandler) { this.transport.setElicitationHandler(handler); } this.log('debug', 'Elicitation handler registered'); } /** * Clear the elicitation handler. * * After calling this, elicitation requests from the server will not be * handled automatically. This can be used to test timeout scenarios. */ clearElicitationHandler(): void { this._elicitationHandler = undefined; if (this.transport?.setElicitationHandler) { this.transport.setElicitationHandler(undefined); } this.log('debug', 'Elicitation handler cleared'); } // ═══════════════════════════════════════════════════════════════════ // LOGGING & DEBUGGING // ═══════════════════════════════════════════════════════════════════ readonly logs = { all: (): LogEntry[] => [...this._logs], filter: (level: 'debug' | 'info' | 'warn' | 'error'): LogEntry[] => this._logs.filter((l) => l.level === level), search: (text: string): LogEntry[] => this._logs.filter((l) => l.message.includes(text)), last: (): LogEntry | undefined => this._logs[this._logs.length - 1], clear: (): void => { this._logs = []; }, }; readonly trace = { all: (): RequestTrace[] => [...this._traces], last: (): RequestTrace | undefined => this._traces[this._traces.length - 1], clear: (): void => { this._traces = []; }, }; // ═══════════════════════════════════════════════════════════════════ // MOCKING & INTERCEPTION // ═══════════════════════════════════════════════════════════════════ /** * API for mocking MCP requests * * @example * ```typescript * // Mock a specific tool call * const handle = mcp.mock.tool('my-tool', { result: 'mocked!' }); * * // Mock with params matching * mcp.mock.add({ * method: 'tools/call', * params: { name: 'my-tool' }, * response: mockResponse.toolResult([{ type: 'text', text: 'mocked' }]), * }); * * // Clear all mocks after test * mcp.mock.clear(); * ``` */ readonly mock = { /** * Add a mock definition */ add: (mock: MockDefinition): MockHandle => { return this._interceptors.mocks.add(mock); }, /** * Mock a tools/call request for a specific tool */ tool: (name: string, result: unknown, options?: { times?: number; delay?: number }): MockHandle => { return this._interceptors.mocks.add({ method: 'tools/call', params: { name }, response: mockResponse.toolResult([ { type: 'text', text: typeof result === 'string' ? result : JSON.stringify(result) }, ]), times: options?.times, delay: options?.delay, }); }, /** * Mock a tools/call request to return an error */ toolError: (name: string, code: number, message: string, options?: { times?: number }): MockHandle => { return this._interceptors.mocks.add({ method: 'tools/call', params: { name }, response: mockResponse.error(code, message), times: options?.times, }); }, /** * Mock a resources/read request */ resource: ( uri: string, content: string | { text?: string; blob?: string; mimeType?: string }, options?: { times?: number; delay?: number }, ): MockHandle => { const contentObj = typeof content === 'string' ? { uri, text: content } : { uri, ...content }; return this._interceptors.mocks.add({ method: 'resources/read', params: { uri }, response: mockResponse.resourceRead([contentObj]), times: options?.times, delay: options?.delay, }); }, /** * Mock a resources/read request to return an error */ resourceError: (uri: string, options?: { times?: number }): MockHandle => { return this._interceptors.mocks.add({ method: 'resources/read', params: { uri }, response: mockResponse.errors.resourceNotFound(uri), times: options?.times, }); }, /** * Mock the tools/list response */ toolsList: ( tools: Array<{ name: string; description?: string; inputSchema?: Record }>, options?: { times?: number }, ): MockHandle => { return this._interceptors.mocks.add({ method: 'tools/list', response: mockResponse.toolsList(tools), times: options?.times, }); }, /** * Mock the resources/list response */ resourcesList: ( resources: Array<{ uri: string; name?: string; description?: string; mimeType?: string }>, options?: { times?: number }, ): MockHandle => { return this._interceptors.mocks.add({ method: 'resources/list', response: mockResponse.resourcesList(resources), times: options?.times, }); }, /** * Clear all mocks */ clear: (): void => { this._interceptors.mocks.clear(); }, /** * Get all active mocks */ all: (): MockDefinition[] => { return this._interceptors.mocks.getAll(); }, }; /** * API for intercepting requests and responses * * @example * ```typescript * // Log all requests * const remove = mcp.intercept.request((ctx) => { * console.log('Request:', ctx.request.method); * return { action: 'passthrough' }; * }); * * // Modify requests * mcp.intercept.request((ctx) => { * if (ctx.request.method === 'tools/call') { * return { * action: 'modify', * request: { ...ctx.request, params: { ...ctx.request.params, extra: true } }, * }; * } * return { action: 'passthrough' }; * }); * * // Add latency to all requests * mcp.intercept.delay(100); * * // Clean up * remove(); * mcp.intercept.clear(); * ``` */ readonly intercept = { /** * Add a request interceptor * @returns Function to remove the interceptor */ request: (interceptor: RequestInterceptor): (() => void) => { return (this._interceptors as DefaultInterceptorChain).addRequestInterceptor(interceptor); }, /** * Add a response interceptor * @returns Function to remove the interceptor */ response: (interceptor: ResponseInterceptor): (() => void) => { return (this._interceptors as DefaultInterceptorChain).addResponseInterceptor(interceptor); }, /** * Add latency to all requests * @returns Function to remove the interceptor */ delay: (ms: number): (() => void) => { return (this._interceptors as DefaultInterceptorChain).addRequestInterceptor(async () => { await new Promise((r) => setTimeout(r, ms)); return { action: 'passthrough' }; }); }, /** * Fail requests matching a method * @returns Function to remove the interceptor */ failMethod: (method: string, error?: string): (() => void) => { return (this._interceptors as DefaultInterceptorChain).addRequestInterceptor((ctx) => { if (ctx.request.method === method) { return { action: 'error', error: new Error(error ?? `Intercepted: ${method}`) }; } return { action: 'passthrough' }; }); }, /** * Clear all interceptors (but not mocks) */ clear: (): void => { (this._interceptors as DefaultInterceptorChain).request = []; (this._interceptors as DefaultInterceptorChain).response = []; }, /** * Clear everything (interceptors and mocks) */ clearAll: (): void => { (this._interceptors as DefaultInterceptorChain).clear(); }, }; // ═══════════════════════════════════════════════════════════════════ // TIMEOUT // ═══════════════════════════════════════════════════════════════════ setTimeout(ms: number): void { this.config.timeout = ms; if (this.transport) { this.transport.setTimeout(ms); } } // ═══════════════════════════════════════════════════════════════════ // PRIVATE: MCP OPERATIONS // ═══════════════════════════════════════════════════════════════════ private get isStateless(): boolean { return this.config.protocolVersion === PROTOCOL_2026_07_28; } private get clientCapabilities(): TestClientCapabilities { // Default includes elicitation.form for testing elicitation workflows // Note: MCP SDK expects form to be an object, not boolean return this.config.capabilities ?? { sampling: {}, elicitation: { form: {} } }; } private async initialize(): Promise> { return this.request('initialize', { protocolVersion: this.config.protocolVersion, capabilities: this.clientCapabilities, clientInfo: this.config.clientInfo, }); } /** Protocol 2026-07-28 has no `initialize`: `server/discover` tells the client what the server offers. */ private async discoverServer(): Promise> { const response = await this.request('server/discover', {}); const data = response.data && initializeResultFrom(response.data); return { ...response, data }; } /** Ask for the server's log messages at `mcpLogLevel`, when the server has the logging capability. */ private async setServerLogLevel(): Promise { const level = this.config.mcpLogLevel; if (level === false || !this.hasCapability('logging')) return; const response = await this.request('logging/setLevel', { level }); if (!response.success) this.log('warn', `logging/setLevel ${level} failed: ${response.error?.message}`); } /** Protocol 2026-07-28: open the `subscriptions/listen` stream for list changes and the subscribed resources. */ private async listen(): Promise { const resourceSubscriptions = [...this.resourceSubscriptions]; const acknowledged = await this.transport?.listen?.(++this.requestIdCounter, { ...LIST_CHANGED_SUBSCRIPTIONS, ...(resourceSubscriptions.length > 0 && { resourceSubscriptions }), }); if (!acknowledged) this.log('warn', 'The server opened no subscriptions/listen stream'); return acknowledged; } private async listenToResource(uri: string): Promise { this.resourceSubscriptions.add(uri); const acknowledged = await this.listen(); if (acknowledged?.resourceSubscriptions?.includes(uri)) return; this.resourceSubscriptions.delete(uri); throw new Error(`Failed to subscribe to ${uri}: the server did not acknowledge it in subscriptions/listen`); } /** Protocol 2026-07-28 mirrors `x-mcp-header` arguments into headers, so the tools' schemas are listed once. */ private async learnToolSchemas(): Promise { if (!this.isStateless || this.toolsListed) return; this.toolsListed = true; await this.tools.list().catch((error: unknown) => { this.log('warn', `Listing the tools before the first call failed: ${errorMessage(error)}`); }); } private async listTools(cursor?: string): Promise> { return this.request('tools/list', cursor ? { cursor } : {}); } /** * Follow `nextCursor` until the server stops returning one, concatenating the * pages. A server that hands back a cursor it already returned, or never stops * paging, fails the call rather than looping. */ private async listAllPages( method: string, label: string, fetchPage: (cursor?: string) => Promise>, itemsOf: (page: TPage) => TItem[] | undefined, ): Promise { const items: TItem[] = []; const seenCursors = new Set(); let cursor: string | undefined; for (let page = 0; page < MAX_LIST_PAGES; page++) { const response = await fetchPage(cursor); if (!response.success || !response.data) { throw new Error(`Failed to list ${label}: ${response.error?.message}`); } items.push(...(itemsOf(response.data) ?? [])); const next = response.data.nextCursor; if (!next) return items; if (seenCursors.has(next)) { throw new Error(`Failed to list ${label}: ${method} returned the cursor "${next}" twice`); } seenCursors.add(next); cursor = next; } throw new Error(`Failed to list ${label}: ${method} did not finish within ${MAX_LIST_PAGES} pages`); } private async callTool( name: string, args?: Record, progressToken?: string | number, ): Promise> { return this.request('tools/call', { name, arguments: args ?? {}, ...(progressToken !== undefined && { _meta: { progressToken } }), }); } private progressTokenFor(options: ToolCallOptions): string | number | undefined { if (options.progressToken !== undefined) return options.progressToken; return this.collectingProgress ? `progress-${++this.progressTokenCounter}` : undefined; } private readonly recordNotification = (notification: JsonRpcRequest): void => { const timestamp = new Date(); this._notifications.push({ method: notification.method, params: notification.params, timestamp }); if (notification.method !== 'notifications/progress') return; const { progress, total, progressToken, message } = notification.params ?? {}; this._progressUpdates.push({ progress: Number(progress), total: typeof total === 'number' ? total : undefined, message: typeof message === 'string' ? message : undefined, progressToken: typeof progressToken === 'string' || typeof progressToken === 'number' ? progressToken : undefined, timestamp, }); }; private async listResources(cursor?: string): Promise> { return this.request('resources/list', cursor ? { cursor } : {}); } private async listResourceTemplates(cursor?: string): Promise> { return this.request('resources/templates/list', cursor ? { cursor } : {}); } private async readResource(uri: string): Promise> { return this.request('resources/read', { uri }); } private async listPrompts(cursor?: string): Promise> { return this.request('prompts/list', cursor ? { cursor } : {}); } private async getPrompt(name: string, args?: Record): Promise> { return this.request('prompts/get', { name, arguments: args ?? {}, }); } // ═══════════════════════════════════════════════════════════════════ // PRIVATE: TRANSPORT & REQUEST HELPERS // ═══════════════════════════════════════════════════════════════════ /** The MCP path this client is currently pointed at, for log and error text. */ private mcpPathLabel(): string { const entry = trimSlashes(this.config.entryPath); return entry ? `/${entry}` : '/'; } private createTransport(): McpTransport { // Build URL with query params if provided using URL API for proper handling let baseUrl = this.config.baseUrl; if (this.config.queryParams && Object.keys(this.config.queryParams).length > 0) { const url = new URL(baseUrl); Object.entries(this.config.queryParams).forEach(([key, value]) => { url.searchParams.set(key, String(value)); }); baseUrl = url.toString(); } switch (this.config.transport) { case 'streamable-http': return new StreamableHttpTransport({ baseUrl, entryPath: this.config.entryPath, timeout: this.config.timeout, auth: this.config.auth, publicMode: this.config.publicMode, debug: this.config.debug, interceptors: this._interceptors, clientInfo: this.config.clientInfo, elicitationHandler: this._elicitationHandler, notificationHandler: this.recordNotification, protocolVersion: this.config.protocolVersion, capabilities: this.clientCapabilities, logLevel: this.config.mcpLogLevel || undefined, }); case 'sse': return new SseTransport({ baseUrl, entryPath: this.config.entryPath, timeout: this.config.timeout, auth: this.config.auth, publicMode: this.config.publicMode, debug: this.config.debug, interceptors: this._interceptors, clientInfo: this.config.clientInfo, elicitationHandler: this._elicitationHandler, notificationHandler: this.recordNotification, }); default: throw new Error(`Unknown transport type: ${this.config.transport}`); } } /** * Send a request, and answer each `input_required` result (protocol 2026-07-28) by sending the * request again with the answers and the server's `requestState`, until the server settles. */ private async request(method: string, params: Record): Promise> { let response = await this.send(method, params); for (let round = 1; response.success && isInputRequired(response.data); round++) { const { inputRequests, requestState } = response.data; const inputResponses = round > MAX_INPUT_ROUNDS ? `the server asked for input more than ${MAX_INPUT_ROUNDS} times` : await this.answerInputRequests(inputRequests); if (typeof inputResponses === 'string') { return { ...response, success: false, data: undefined, error: { code: -32603, message: `${method}: ${inputResponses}` }, }; } const retried = await this.send(method, { ...params, inputResponses, ...(requestState !== undefined && { requestState }), }); response = { ...retried, durationMs: response.durationMs + retried.durationMs }; } return response; } /** The answers to an `input_required` result's requests, or why the client can't give them. */ private async answerInputRequests(inputRequests: InputRequests = {}): Promise { const answers: InputResponses = {}; for (const [key, inputRequest] of Object.entries(inputRequests)) { if (inputRequest.method !== 'elicitation/create') { return `the server asked for ${inputRequest.method}, which McpTestClient doesn't answer`; } answers[key] = { ...(await this.answerElicitation(inputRequest.params ?? {})) }; } return answers; } /** As over a session: the handler's answer, `decline` without a handler, and `cancel` when it throws. */ private async answerElicitation(params: Record): Promise { if (!this._elicitationHandler) return { action: 'decline' }; try { return await this._elicitationHandler({ mode: 'form', ...params } as ElicitationCreateRequest); } catch (error) { this.log('warn', `The elicitation handler threw: ${errorMessage(error)}`); return { action: 'cancel' }; } } private async send(method: string, params: Record): Promise> { const transport = this.getConnectedTransport(); const id = ++this.requestIdCounter; this._lastRequestId = id; const start = Date.now(); try { const response = await transport.request({ jsonrpc: '2.0', id, method, params, }); const durationMs = Date.now() - start; this.updateSessionActivity(); if ('error' in response && response.error) { const error = response.error as McpErrorInfo; this.traceRequest(method, params, id, response, durationMs); return { success: false, error, durationMs, requestId: id, }; } this.traceRequest(method, params, id, response, durationMs); return { success: true, data: response.result as T, durationMs, requestId: id, }; } catch (err) { // An error injected through mcp.intercept (failMethod / failWhen) must reject the call if (isInterceptedError(err)) throw err; const durationMs = Date.now() - start; const error: McpErrorInfo = { code: -32603, message: errorMessage(err), }; return { success: false, error, durationMs, requestId: id, }; } } /** * Get the transport, throwing if not connected. */ private getConnectedTransport(): McpTransport { if (!this.transport || !this.transport.isConnected()) { throw new Error('Not connected to MCP server. Call connect() first.'); } return this.transport; } private updateSessionActivity(): void { if (this._sessionInfo) { this._sessionInfo.lastActivityAt = new Date(); this._sessionInfo.requestCount++; } } // ═══════════════════════════════════════════════════════════════════ // PRIVATE: RESULT WRAPPERS // ═══════════════════════════════════════════════════════════════════ private wrapToolResult(response: McpResponse): ToolResultWrapper { const raw = response.data ?? { content: [] }; const isError = !response.success || raw.isError === true; // Check for Tool UI response - has UI metadata in _meta // All platforms use ui/* namespace per MCP Apps specification const meta = raw._meta as Record | undefined; const hasUI = meta?.['ui/html'] !== undefined || meta?.['ui/component'] !== undefined; const structuredContent = (raw as Record)['structuredContent']; return { raw, isSuccess: !isError, isError, error: response.error, durationMs: response.durationMs, json(): T { // For Tool UI responses, return structuredContent (the typed output) if (hasUI && structuredContent !== undefined) { return structuredContent as T; } // For regular responses, parse text content as JSON const textContent = raw.content?.find((c) => c.type === 'text'); if (textContent && 'text' in textContent) { return JSON.parse(textContent.text) as T; } throw new Error('No text content to parse as JSON'); }, text(): string | undefined { const textContent = raw.content?.find((c) => c.type === 'text'); if (textContent && 'text' in textContent) { return textContent.text; } return undefined; }, hasTextContent(): boolean { return raw.content?.some((c) => c.type === 'text') ?? false; }, hasImageContent(): boolean { return raw.content?.some((c) => c.type === 'image') ?? false; }, hasResourceContent(): boolean { return raw.content?.some((c) => c.type === 'resource') ?? false; }, hasToolUI(): boolean { return hasUI; }, }; } private wrapResourceContent(response: McpResponse): ResourceContentWrapper { const raw = response.data ?? { contents: [] }; const isError = !response.success; const firstContent = raw.contents?.[0]; return { raw, isSuccess: !isError, isError, error: response.error, durationMs: response.durationMs, json(): T { if (firstContent && 'text' in firstContent) { return JSON.parse(firstContent.text) as T; } throw new Error('No text content to parse as JSON'); }, text(): string | undefined { if (firstContent && 'text' in firstContent) { return firstContent.text; } return undefined; }, mimeType(): string | undefined { return firstContent?.mimeType; }, hasMimeType(type: string): boolean { return firstContent?.mimeType === type; }, }; } private wrapPromptResult(response: McpResponse): PromptResultWrapper { const raw = response.data ?? { messages: [] }; const isError = !response.success; return { raw, isSuccess: !isError, isError, error: response.error, durationMs: response.durationMs, messages: raw.messages ?? [], description: raw.description, }; } // ═══════════════════════════════════════════════════════════════════ // PRIVATE: LOGGING & TRACING // ═══════════════════════════════════════════════════════════════════ private log(level: 'debug' | 'info' | 'warn' | 'error', message: string, data?: unknown): void { const entry: LogEntry = { level, message, timestamp: new Date(), data, }; this._logs.push(entry); if (this.config.debug) { console.log(`[${level.toUpperCase()}] ${message}`, data ?? ''); } } private traceRequest( method: string, params: unknown, id: string | number, response: JSONRPCResponse, durationMs: number, ): void { this._traces.push({ request: { method, params, id }, response: { result: 'result' in response ? response.result : undefined, error: 'error' in response ? (response.error as McpErrorInfo) : undefined, }, durationMs, timestamp: new Date(), }); } // ═══════════════════════════════════════════════════════════════════ // PRIVATE: TOKEN PARSING // ═══════════════════════════════════════════════════════════════════ private parseScopesFromToken(token: string): string[] { try { const payload = this.decodeJwtPayload(token); if (!payload) return []; const scope = payload['scope']; const scopes = payload['scopes']; if (typeof scope === 'string') { return scope.split(' '); } if (Array.isArray(scopes)) { return scopes as string[]; } return []; } catch { return []; } } private parseUserFromToken(token: string): { sub: string; email?: string; name?: string } | undefined { try { const payload = this.decodeJwtPayload(token); const sub = payload?.['sub']; if (!sub || typeof sub !== 'string') return undefined; return { sub, email: payload['email'] as string | undefined, name: payload['name'] as string | undefined, }; } catch { return undefined; } } private decodeJwtPayload(token: string): Record | null { try { const parts = token.split('.'); if (parts.length !== 3) return null; const payload = Buffer.from(parts[1], 'base64url').toString('utf-8'); return JSON.parse(payload); } catch { return null; } } } // ═══════════════════════════════════════════════════════════════════ // NOTIFICATION COLLECTORS // ═══════════════════════════════════════════════════════════════════ class NotificationCollector { constructor(private readonly notifications: NotificationEntry[]) {} get received(): NotificationEntry[] { return [...this.notifications]; } has(method: string): boolean { return this.notifications.some((n) => n.method === method); } async waitFor(method: string, timeoutMs: number): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const found = this.notifications.find((n) => n.method === method); if (found) return found; await new Promise((r) => setTimeout(r, 50)); } throw new Error(`Timeout waiting for notification: ${method}`); } } class ProgressCollector { constructor(private readonly updates: ProgressUpdate[]) {} get all(): ProgressUpdate[] { return [...this.updates]; } async waitForComplete(timeoutMs: number): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const last = this.updates[this.updates.length - 1]; if (last && last.total !== undefined && last.progress >= last.total) { return; } await new Promise((r) => setTimeout(r, 50)); } throw new Error('Timeout waiting for progress to complete'); } }