diff --git a/.gitignore b/.gitignore index 2fdd7d0a..2b6bcd5b 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ dist/ .idea/ .claude/settings.local.json .sdk-under-test/ +.sync-schema-tmp/ diff --git a/.prettierignore b/.prettierignore index 43399fcc..dee83ed4 100644 --- a/.prettierignore +++ b/.prettierignore @@ -3,3 +3,8 @@ # repo's `prettier --check .` would reformat the file and fight the generator's # output (and the refresh workflow's `git diff` check). src/seps/traceability.json + +# Vendored verbatim from modelcontextprotocol/schema/{version}/schema.ts via +# `npm run sync-schema`. Keep byte-identical with upstream so the SOURCE pin +# is meaningful and re-syncing produces a clean diff. +src/spec-types/*.ts diff --git a/examples/servers/typescript/everything-server.ts b/examples/servers/typescript/everything-server.ts index 1d9dcc96..ef0028fd 100644 --- a/examples/servers/typescript/everything-server.ts +++ b/examples/servers/typescript/everything-server.ts @@ -21,6 +21,9 @@ import { import { createMcpExpressApp } from '@modelcontextprotocol/sdk/server/express.js'; import { ElicitResultSchema, + ResultSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, ListToolsRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, @@ -30,6 +33,8 @@ import { } from '@modelcontextprotocol/sdk/types.js'; import { z } from 'zod'; import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import cors from 'cors'; import { randomUUID, createHmac } from 'crypto'; @@ -72,6 +77,49 @@ function getMrtInputText(inputResponse: unknown, field: string): string { const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {}; const servers: { [sessionId: string]: McpServer } = {}; +// In-memory client connected to a fully-registered McpServer. Used by the +// stateless POST handler to serve carry-forward methods (tools/call, +// resources/*, prompts/get, completion/complete) without duplicating the +// registrations. The SDK doesn't yet support a stateless server natively, +// so this bridges via the in-memory transport after a one-time initialize. +// +// A fresh server+client pair is built per request so concurrent requests +// can't observe each other's notifications. +type DispatchClient = { + client: Client; + drainNotifications: () => unknown[]; + close: () => Promise; +}; +async function getStatelessDispatchClient(): Promise { + const [clientT, serverT] = InMemoryTransport.createLinkedPair(); + const server = createMcpServer(); + await server.connect(serverT); + const client = new Client( + { name: 'stateless-dispatch', version: '1.0.0' }, + { capabilities: { sampling: {}, elicitation: {} } } + ); + await client.connect(clientT); + + // Buffer notifications so the stateless handler can flush them to the SSE + // response after the request completes. The SDK pre-registers a handler for + // notifications/progress so a fallback alone would miss it. + const buffer: unknown[] = []; + const collect = async (n: unknown) => + void buffer.push({ jsonrpc: '2.0', ...(n as object) }); + client.setNotificationHandler(ProgressNotificationSchema, collect); + client.setNotificationHandler(LoggingMessageNotificationSchema, collect); + client.fallbackNotificationHandler = collect; + + return { + client, + drainNotifications: () => buffer.splice(0, buffer.length), + close: async () => { + await client.close(); + await server.close(); + } + }; +} + // In-memory event store for SEP-1699 resumability const eventStoreData = new Map< string, @@ -1304,11 +1352,19 @@ app.post('/mcp', async (req, res) => { } if (method === 'tools/list') { + const dispatch = await getStatelessDispatchClient(); + const fromServer = (await dispatch.client.request( + { method: 'tools/list', params: {} }, + ResultSchema as any + )) as { tools: any[]; [k: string]: unknown }; + await dispatch.close(); return res.json({ jsonrpc: '2.0', id, result: { + ...fromServer, tools: [ + ...fromServer.tools, { name: 'test_missing_capability', description: 'Test tool requiring sampling', @@ -1378,11 +1434,19 @@ app.post('/mcp', async (req, res) => { // Mock fallbacks to answer prompts capability matches safely if (method === 'prompts/list') { + const dispatch = await getStatelessDispatchClient(); + const fromServer = (await dispatch.client.request( + { method: 'prompts/list', params: {} }, + ResultSchema as any + )) as { prompts: any[]; [k: string]: unknown }; + await dispatch.close(); return res.json({ jsonrpc: '2.0', id, result: { + ...fromServer, prompts: [ + ...fromServer.prompts, { name: 'test_input_required_result_prompt', description: 'MRTR: prompt that requires elicitation input' @@ -1994,6 +2058,68 @@ app.post('/mcp', async (req, res) => { } } + // Carry-forward methods that fell through the MRTR-specific handlers above + // (tools/call for non-MRTR tools, resources/*, prompts/get for non-MRTR + // prompts, completion/complete) are dispatched to the same McpServer the + // stateful path uses, via an in-memory client. This avoids duplicating the + // tool/resource/prompt registrations for the stateless path. + // + // tools/call is served as text/event-stream so progress and logging + // notifications from the underlying tool reach the conformance client. + if (method === 'tools/call') { + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache' + }); + const write = (msg: unknown) => + res.write(`event: message\ndata: ${JSON.stringify(msg)}\n\n`); + const dispatch = await getStatelessDispatchClient(); + try { + const result = await dispatch.client.request( + { method, params }, + ResultSchema as any + ); + for (const n of dispatch.drainNotifications()) write(n); + write({ jsonrpc: '2.0', id, result }); + } catch (e: any) { + for (const n of dispatch.drainNotifications()) write(n); + write({ + jsonrpc: '2.0', + id, + error: { code: e.code ?? -32603, message: e.message, data: e.data } + }); + } finally { + await dispatch.close(); + } + return res.end(); + } + if ( + [ + 'resources/list', + 'resources/read', + 'resources/templates/list', + 'prompts/get', + 'completion/complete' + ].includes(method) + ) { + const dispatch = await getStatelessDispatchClient(); + try { + const result = await dispatch.client.request( + { method, params }, + ResultSchema as any + ); + return res.json({ jsonrpc: '2.0', id, result }); + } catch (e: any) { + return res.json({ + jsonrpc: '2.0', + id, + error: { code: e.code ?? -32603, message: e.message, data: e.data } + }); + } finally { + await dispatch.close(); + } + } + // Removed Methods per SEP-2575 (Changed status from 200 to 400/404 per Transport Spec) if ( [ diff --git a/package.json b/package.json index fe13329e..3bb20cd2 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "lint:fix_check": "npm run lint:fix && git diff --exit-code --quiet", "tier-check": "node dist/index.js tier-check", "traceability": "tsx src/index.ts traceability", + "sync-schema": "tsx scripts/sync-schema.ts", "check": "npm run typecheck && npm run lint", "typecheck": "tsgo --noEmit", "prepack": "npm run build", diff --git a/scripts/sync-schema.ts b/scripts/sync-schema.ts new file mode 100644 index 00000000..5aa9e7f7 --- /dev/null +++ b/scripts/sync-schema.ts @@ -0,0 +1,52 @@ +#!/usr/bin/env -S npx tsx +/** + * Vendor schema/{version}/schema.ts from the modelcontextprotocol spec repo + * into src/spec-types/{version}.ts at a pinned SHA. + * + * Usage: npm run sync-schema -- + */ +import { execFileSync } from 'node:child_process'; +import { mkdirSync, writeFileSync, rmSync, copyFileSync } from 'node:fs'; +import { join } from 'node:path'; + +const VERSIONS = ['2025-03-26', '2025-06-18', '2025-11-25', 'draft'] as const; +const SPEC_REPO = + 'https://github.com/modelcontextprotocol/modelcontextprotocol.git'; +const OUT_DIR = join(process.cwd(), 'src', 'spec-types'); + +const ref = process.argv[2]; +if (!ref) { + console.error('Usage: npm run sync-schema -- '); + process.exit(1); +} + +const tmp = join(process.cwd(), '.sync-schema-tmp'); +rmSync(tmp, { recursive: true, force: true }); +mkdirSync(tmp, { recursive: true }); +mkdirSync(OUT_DIR, { recursive: true }); + +const git = (args: string[]) => + execFileSync('git', args, { cwd: tmp, encoding: 'utf8' }); + +try { + console.log(`Fetching ${SPEC_REPO} @ ${ref} ...`); + git(['init', '-q']); + git(['remote', 'add', 'origin', SPEC_REPO]); + git(['fetch', '-q', '--depth', '1', 'origin', ref]); + git(['checkout', '-q', 'FETCH_HEAD']); + const sha = git(['rev-parse', 'HEAD']).trim(); + + for (const v of VERSIONS) { + copyFileSync(join(tmp, 'schema', v, 'schema.ts'), join(OUT_DIR, `${v}.ts`)); + console.log(` ${v} -> src/spec-types/${v}.ts`); + } + + writeFileSync( + join(OUT_DIR, 'SOURCE'), + `modelcontextprotocol@${sha}\n`, + 'utf8' + ); + console.log(`Pinned: modelcontextprotocol@${sha}`); +} finally { + rmSync(tmp, { recursive: true, force: true }); +} diff --git a/src/connection/connection.test.ts b/src/connection/connection.test.ts new file mode 100644 index 00000000..27b77648 --- /dev/null +++ b/src/connection/connection.test.ts @@ -0,0 +1,125 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { connectFor } from './select'; +import { connectStateful } from './stateful'; +import { connectStateless } from './stateless'; +import { JsonRpcError } from './index'; + +describe('connectFor', () => { + it('returns stateful for dated 2025-x versions', () => { + expect(connectFor('2025-03-26')).toBe(connectStateful); + expect(connectFor('2025-06-18')).toBe(connectStateful); + expect(connectFor('2025-11-25')).toBe(connectStateful); + }); + it('returns stateless for the draft version', () => { + expect(connectFor('DRAFT-2026-v1')).toBe(connectStateless); + }); +}); + +describe('connectStateless', () => { + const mockFetch = vi.fn(); + vi.stubGlobal('fetch', mockFetch); + afterEach(() => mockFetch.mockReset()); + + function jsonResponse(body: unknown, status = 200) { + return new Response(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' } + }); + } + + function sseResponse(events: string[]) { + return new Response(events.join(''), { + status: 200, + headers: { 'content-type': 'text/event-stream' } + }); + } + + it('injects required _meta keys and MCP-Protocol-Version header', async () => { + mockFetch.mockResolvedValue( + jsonResponse({ jsonrpc: '2.0', id: 1, result: { ok: true } }) + ); + const conn = await connectStateless('http://test/mcp'); + await conn.request('tools/list'); + + const [, init] = mockFetch.mock.calls[0]; + expect(init.headers['MCP-Protocol-Version']).toBe('DRAFT-2026-v1'); + const sent = JSON.parse(init.body); + expect(sent.params._meta['io.modelcontextprotocol/protocolVersion']).toBe( + 'DRAFT-2026-v1' + ); + expect( + sent.params._meta['io.modelcontextprotocol/clientInfo'] + ).toBeDefined(); + expect( + sent.params._meta['io.modelcontextprotocol/clientCapabilities'] + ).toBeDefined(); + }); + + it('throws JsonRpcError on JSON-RPC error responses', async () => { + mockFetch.mockResolvedValue( + jsonResponse({ + jsonrpc: '2.0', + id: 1, + error: { code: -32601, message: 'Method not found' } + }) + ); + const conn = await connectStateless('http://test/mcp'); + await expect(conn.request('nope')).rejects.toSatisfy( + (e) => e instanceof JsonRpcError && e.code === -32601 + ); + }); + + it('throws on non-2xx JSON without a JSON-RPC error envelope', async () => { + mockFetch.mockResolvedValue( + jsonResponse({ detail: 'gateway rejected' }, 502) + ); + const conn = await connectStateless('http://test/mcp'); + await expect(conn.request('tools/list')).rejects.toThrow(/HTTP 502/); + }); + + it('throws a useful error for non-JSON non-SSE responses', async () => { + mockFetch.mockResolvedValue( + new Response('500', { + status: 500, + headers: { 'content-type': 'text/html' } + }) + ); + const conn = await connectStateless('http://test/mcp'); + await expect(conn.request('tools/list')).rejects.toThrow(/HTTP 500/); + }); + + it('parses SSE: collects notifications and returns final result (LF)', async () => { + mockFetch.mockResolvedValue( + sseResponse([ + 'event: message\ndata: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progress":1}}\n\n', + 'event: message\ndata: {"jsonrpc":"2.0","id":1,"result":{"done":true}}\n\n' + ]) + ); + const conn = await connectStateless('http://test/mcp'); + const result = await conn.request<{ done: boolean }>('tools/call', {}); + expect(result.done).toBe(true); + expect(conn.notifications).toHaveLength(1); + expect(conn.notifications[0].method).toBe('notifications/progress'); + }); + + it('parses SSE with CRLF line endings', async () => { + mockFetch.mockResolvedValue( + sseResponse([ + 'event: message\r\ndata: {"jsonrpc":"2.0","id":1,"result":{"ok":true}}\r\n\r\n' + ]) + ); + const conn = await connectStateless('http://test/mcp'); + const result = await conn.request<{ ok: boolean }>('tools/call', {}); + expect(result.ok).toBe(true); + }); + + it('rejects server-to-client requests on the SSE stream', async () => { + mockFetch.mockResolvedValue( + sseResponse([ + 'event: message\ndata: {"jsonrpc":"2.0","id":99,"method":"elicitation/create","params":{}}\n\n' + ]) + ); + const conn = await connectStateless('http://test/mcp'); + await expect(conn.request('tools/call', {})).rejects.toThrow(/MRTR/); + }); +}); diff --git a/src/connection/index.ts b/src/connection/index.ts new file mode 100644 index 00000000..2c4afdba --- /dev/null +++ b/src/connection/index.ts @@ -0,0 +1,67 @@ +/** + * Version-aware connection abstraction for server-conformance scenarios. + * + * A `Connection` knows how to send JSON-RPC requests to the server-under-test + * using the lifecycle appropriate for the spec version being tested: + * + * - 2025-x: stateful (initialize handshake, Mcp-Session-Id header) + * - 2026-x: stateless (no handshake, per-request _meta + MCP-Protocol-Version) + * + * Scenarios call `ctx.connect()` and then `conn.request(method, params)`; the + * runner picks the implementation based on `--spec-version`. Scenario code is + * the same regardless of which lifecycle is in use. + */ + +import type { SpecVersion } from '../types'; +import type { JSONRPCNotification } from '../spec-types/2025-11-25'; + +export interface Connection { + /** + * Send a JSON-RPC request and return its result. + * Throws `JsonRpcError` on JSON-RPC error responses. + */ + request( + method: string, + params?: Record + ): Promise; + + /** + * All notifications received over this connection's lifetime, in arrival + * order. For the stateful impl this includes notifications from the + * standalone GET stream; for stateless it's only those on POST-response + * streams. + */ + readonly notifications: JSONRPCNotification[]; + + close(): Promise; +} + +/** + * Per-run context handed to `ClientScenario.run()`. The runner constructs this + * from the resolved `--spec-version` and server URL. + */ +export interface RunContext { + serverUrl: string; + specVersion: SpecVersion; + /** + * Open a version-appropriate connection to the server-under-test. + * Scenarios that test the connection mechanics themselves (initialize, + * GET-SSE, DNS rebinding) bypass this and use raw fetch. + */ + connect(): Promise; +} + +export class JsonRpcError extends Error { + constructor( + public readonly code: number, + message: string, + public readonly data?: unknown + ) { + super(message); + this.name = 'JsonRpcError'; + } +} + +export { connectStateful } from './stateful'; +export { connectStateless } from './stateless'; +export { connectFor } from './select'; diff --git a/src/scenarios/server/client-helper.ts b/src/connection/sdk-client.ts similarity index 100% rename from src/scenarios/server/client-helper.ts rename to src/connection/sdk-client.ts diff --git a/src/connection/select.ts b/src/connection/select.ts new file mode 100644 index 00000000..a08ec954 --- /dev/null +++ b/src/connection/select.ts @@ -0,0 +1,23 @@ +import type { SpecVersion } from '../types'; +import type { Connection } from './index'; +import { connectStateful } from './stateful'; +import { connectStateless } from './stateless'; + +/** + * Spec versions that use the stateful lifecycle (initialize handshake, + * Mcp-Session-Id). Anything not in this list uses the stateless lifecycle. + */ +const STATEFUL_VERSIONS: ReadonlySet = new Set([ + '2024-11-05', + '2025-03-26', + '2025-06-18', + '2025-11-25' +]); + +export function connectFor( + specVersion: SpecVersion +): (serverUrl: string) => Promise { + return STATEFUL_VERSIONS.has(specVersion) + ? connectStateful + : connectStateless; +} diff --git a/src/connection/stateful.ts b/src/connection/stateful.ts new file mode 100644 index 00000000..5c391832 --- /dev/null +++ b/src/connection/stateful.ts @@ -0,0 +1,59 @@ +/** + * Stateful connection: 2025-x lifecycle (initialize handshake, session id). + * + * Backed by the SDK's `Client` so we don't reimplement the handshake, session + * header, or SSE response parsing. The SDK is the driver here, not the + * system-under-test; its own correctness is covered by the client-conformance + * scenarios. + */ + +import { + ResultSchema, + McpError, + ProgressNotificationSchema, + LoggingMessageNotificationSchema +} from '@modelcontextprotocol/sdk/types.js'; +import { connectToServer } from './sdk-client'; +import type { JSONRPCNotification } from '../spec-types/2025-11-25'; +import { JsonRpcError, type Connection } from './index'; + +export async function connectStateful(serverUrl: string): Promise { + const { client, close } = await connectToServer(serverUrl); + + const notifications: JSONRPCNotification[] = []; + const collect = (n: unknown) => { + notifications.push(n as JSONRPCNotification); + }; + // The SDK pre-registers a handler for notifications/progress (to drive the + // onprogress callback feature), so it never reaches the fallback. Register + // explicit collectors for the schemas the SDK claims, then a fallback for + // everything else. + client.setNotificationHandler(ProgressNotificationSchema, async (n) => + collect(n) + ); + client.setNotificationHandler(LoggingMessageNotificationSchema, async (n) => + collect(n) + ); + client.fallbackNotificationHandler = async (n) => collect(n); + + return { + notifications, + + async request( + method: string, + params: Record = {} + ): Promise { + try { + return (await client.request({ method, params }, ResultSchema)) as R; + } catch (e) { + // Normalize so scenarios always see JsonRpcError regardless of impl. + if (e instanceof McpError) { + throw new JsonRpcError(e.code, e.message, e.data); + } + throw e; + } + }, + + close + }; +} diff --git a/src/connection/stateless.ts b/src/connection/stateless.ts new file mode 100644 index 00000000..3b1d7d0b --- /dev/null +++ b/src/connection/stateless.ts @@ -0,0 +1,137 @@ +/** + * Stateless connection: 2026-x lifecycle (SEP-2575). + * + * No handshake. Every request carries `_meta` with protocolVersion, clientInfo, + * and clientCapabilities, plus the `MCP-Protocol-Version` header. Implemented + * with raw fetch so the conformance suite can test draft spec versions before + * the SDK supports them. + */ + +import { DRAFT_PROTOCOL_VERSION } from '../types'; +import type { JSONRPCNotification } from '../spec-types/2025-11-25'; +import { JsonRpcError, type Connection } from './index'; + +const CLIENT_INFO = { name: 'conformance-test-client', version: '1.0.0' }; +const CLIENT_CAPABILITIES = { + sampling: {}, + elicitation: {}, + roots: { listChanged: true } +}; + +export async function connectStateless(serverUrl: string): Promise { + const notifications: JSONRPCNotification[] = []; + let nextId = 1; + + async function request( + method: string, + params: Record = {} + ): Promise { + const id = nextId++; + const _meta = { + 'io.modelcontextprotocol/protocolVersion': DRAFT_PROTOCOL_VERSION, + 'io.modelcontextprotocol/clientInfo': CLIENT_INFO, + 'io.modelcontextprotocol/clientCapabilities': CLIENT_CAPABILITIES, + ...(params._meta as Record | undefined) + }; + + const response = await fetch(serverUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + 'MCP-Protocol-Version': DRAFT_PROTOCOL_VERSION + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id, + method, + params: { ...params, _meta } + }) + }); + + const contentType = response.headers.get('content-type') ?? ''; + if ( + !contentType.includes('json') && + !contentType.includes('text/event-stream') + ) { + throw new Error( + `HTTP ${response.status} ${response.statusText}: ` + + `expected JSON or SSE response, got '${contentType || '(none)'}'` + ); + } + const message = contentType.includes('text/event-stream') + ? await readFinalSseMessage(response, id, notifications) + : await response.json(); + + if (message.error) { + throw new JsonRpcError( + message.error.code, + message.error.message, + message.error.data + ); + } + if (!response.ok) { + // Non-2xx without a JSON-RPC error envelope (e.g. gateway or framework + // error body). Surface the HTTP status rather than returning undefined. + throw new Error( + `HTTP ${response.status} ${response.statusText}: ` + + JSON.stringify(message) + ); + } + return message.result as R; + } + + return { + notifications, + request, + close: async () => {} + }; +} + +/** + * Consume an SSE response stream, pushing notifications into `sink` and + * returning the final response message matching `id`. Server-to-client + * requests on this stream are a spec violation under the stateless lifecycle + * and are surfaced as a thrown error. + */ +async function readFinalSseMessage( + response: Response, + id: number, + sink: JSONRPCNotification[] +): Promise<{ result?: unknown; error?: { code: number; message: string } }> { + const reader = response.body!.getReader(); + const decoder = new TextDecoder(); + let buf = ''; + + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + buf += decoder.decode(value, { stream: true }); + + let m: RegExpMatchArray | null; + while ((m = buf.match(/\r?\n\r?\n/))) { + const sep = m.index!; + const event = buf.slice(0, sep); + buf = buf.slice(sep + m[0].length); + const data = event + .split(/\r?\n/) + .filter((l) => l.startsWith('data:')) + .map((l) => l.slice(5).trimStart()) + .join(''); + if (!data) continue; + const msg = JSON.parse(data); + if ('method' in msg && !('id' in msg)) { + sink.push(msg); + } else if ('method' in msg && 'id' in msg) { + throw new JsonRpcError( + -32600, + `Server sent request '${msg.method}' on response stream; stateless lifecycle forbids this (use MRTR)` + ); + } else if (msg.id === id) { + reader.cancel().catch(() => {}); + return msg; + } + } + } + throw new Error('SSE stream ended without a response for id ' + id); +} diff --git a/src/connection/testing.ts b/src/connection/testing.ts new file mode 100644 index 00000000..92468f68 --- /dev/null +++ b/src/connection/testing.ts @@ -0,0 +1,19 @@ +import { LATEST_SPEC_VERSION, type SpecVersion } from '../types'; +import { connectFor } from './select'; +import type { RunContext } from './index'; + +/** + * Build a RunContext for unit tests that drive a scenario directly. + * Defaults to the latest dated spec version (stateful lifecycle) so existing + * tests keep their pre-RunContext behaviour. + */ +export function testContext( + serverUrl: string, + specVersion: SpecVersion = LATEST_SPEC_VERSION +): RunContext { + return { + serverUrl, + specVersion, + connect: () => connectFor(specVersion)(serverUrl) + }; +} diff --git a/src/index.ts b/src/index.ts index a3019f0a..8754a0b1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -343,7 +343,8 @@ program const result = await runServerConformanceTest( validated.url, validated.scenario, - outputDir + outputDir, + specVersionFilter ); const { failed } = printServerResults( @@ -405,7 +406,8 @@ program const result = await runServerConformanceTest( validated.url, scenarioName, - outputDir + outputDir, + specVersionFilter ); allResults.push({ scenario: scenarioName, checks: result.checks }); } catch (error) { diff --git a/src/runner/server.ts b/src/runner/server.ts index a7d84491..b01e9b78 100644 --- a/src/runner/server.ts +++ b/src/runner/server.ts @@ -1,7 +1,8 @@ import { promises as fs } from 'fs'; import path from 'path'; -import { ConformanceCheck } from '../types'; +import { ConformanceCheck, SpecVersion, LATEST_SPEC_VERSION } from '../types'; import { getClientScenario } from '../scenarios'; +import { connectFor, type RunContext } from '../connection'; import { createResultDir, formatPrettyChecks } from './utils'; /** @@ -20,7 +21,8 @@ function formatMarkdown(text: string): string { export async function runServerConformanceTest( serverUrl: string, scenarioName: string, - outputDir?: string + outputDir?: string, + specVersion: SpecVersion = LATEST_SPEC_VERSION ): Promise<{ checks: ConformanceCheck[]; resultDir?: string; @@ -40,7 +42,12 @@ export async function runServerConformanceTest( `Running client scenario '${scenarioName}' against server: ${serverUrl}` ); - const checks = await scenario.run(serverUrl); + const ctx: RunContext = { + serverUrl, + specVersion, + connect: () => connectFor(specVersion)(serverUrl) + }; + const checks = await scenario.run(ctx); if (resultDir) { await fs.writeFile( diff --git a/src/scenarios/index.ts b/src/scenarios/index.ts index 9b54e819..f2819337 100644 --- a/src/scenarios/index.ts +++ b/src/scenarios/index.ts @@ -221,15 +221,16 @@ export const clientScenarios = new Map( ); // All client scenarios for authorization server -const allClientScenariosListForAuthorizationServer: ClientScenario[] = [ - // Authorization server scenarios - new AuthorizationServerMetadataEndpointScenario() -]; +const allClientScenariosListForAuthorizationServer: ClientScenarioForAuthorizationServer[] = + [ + // Authorization server scenarios + new AuthorizationServerMetadataEndpointScenario() + ]; // Client scenarios map for authorization server - built from list export const clientScenariosForAuthorizationServer = new Map< string, - ClientScenario + ClientScenarioForAuthorizationServer >( allClientScenariosListForAuthorizationServer.map((scenario) => [ scenario.name, diff --git a/src/scenarios/server/all-scenarios.test.ts b/src/scenarios/server/all-scenarios.test.ts index 9f2d014e..9fb2e41b 100644 --- a/src/scenarios/server/all-scenarios.test.ts +++ b/src/scenarios/server/all-scenarios.test.ts @@ -1,3 +1,4 @@ +import { testContext } from '../../connection/testing'; import { spawn, ChildProcess } from 'child_process'; import { createServer } from 'net'; import { getClientScenario, listActiveClientScenarios } from '../index'; @@ -128,7 +129,7 @@ describe('Server Scenarios', () => { throw new Error(`Scenario ${scenarioName} not found`); } - const checks = await scenario.run(serverUrl); + const checks = await scenario.run(testContext(serverUrl)); // Verify checks were returned expect(checks.length).toBeGreaterThan(0); diff --git a/src/scenarios/server/caching.ts b/src/scenarios/server/caching.ts index 5c580023..fc3152bb 100644 --- a/src/scenarios/server/caching.ts +++ b/src/scenarios/server/caching.ts @@ -10,14 +10,15 @@ import { ConformanceCheck, DRAFT_PROTOCOL_VERSION } from '../../types'; -import { connectToServer } from './client-helper'; -import { - ListToolsResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema -} from '@modelcontextprotocol/sdk/types.js'; +import type { RunContext } from '../../connection'; +import type { + CacheableResult, + ListToolsResult, + ListPromptsResult, + ListResourcesResult, + ListResourceTemplatesResult, + ReadResourceResult +} from '../../spec-types/draft'; const SPEC_REFS = [ { @@ -37,12 +38,12 @@ interface CachingFields { hasCacheScope: boolean; } -function extractCachingFields(result: Record): CachingFields { +function extractCachingFields(result: Partial): CachingFields { const hasTtlMs = 'ttlMs' in result; const hasCacheScope = 'cacheScope' in result; return { - ttlMs: hasTtlMs ? result.ttlMs : undefined, - cacheScope: hasCacheScope ? result.cacheScope : undefined, + ttlMs: result.ttlMs, + cacheScope: result.cacheScope, hasTtlMs, hasCacheScope }; @@ -94,22 +95,17 @@ Servers MUST include \`ttlMs\` (integer >= 0) and \`cacheScope\` ("public" or "p - \`resources/templates/list\` - \`resources/read\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; const allFields: Array<{ endpoint: string; fields: CachingFields }> = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); // 1. tools/list try { - const toolsResult = await connection.client.request( - { method: 'tools/list', params: {} }, - ListToolsResultSchema - ); - const fields = extractCachingFields( - toolsResult as Record - ); + const toolsResult = await conn.request('tools/list'); + const fields = extractCachingFields(toolsResult); allFields.push({ endpoint: 'tools/list', fields }); checks.push( buildPresenceCheck( @@ -134,13 +130,9 @@ Servers MUST include \`ttlMs\` (integer >= 0) and \`cacheScope\` ("public" or "p // 2. prompts/list try { - const promptsResult = await connection.client.request( - { method: 'prompts/list', params: {} }, - ListPromptsResultSchema - ); - const fields = extractCachingFields( - promptsResult as Record - ); + const promptsResult = + await conn.request('prompts/list'); + const fields = extractCachingFields(promptsResult); allFields.push({ endpoint: 'prompts/list', fields }); checks.push( buildPresenceCheck( @@ -166,13 +158,9 @@ Servers MUST include \`ttlMs\` (integer >= 0) and \`cacheScope\` ("public" or "p // 3. resources/list let firstResourceUri: string | undefined; try { - const resourcesResult = await connection.client.request( - { method: 'resources/list', params: {} }, - ListResourcesResultSchema - ); - const fields = extractCachingFields( - resourcesResult as Record - ); + const resourcesResult = + await conn.request('resources/list'); + const fields = extractCachingFields(resourcesResult); allFields.push({ endpoint: 'resources/list', fields }); checks.push( buildPresenceCheck( @@ -201,13 +189,10 @@ Servers MUST include \`ttlMs\` (integer >= 0) and \`cacheScope\` ("public" or "p // 4. resources/templates/list try { - const templatesResult = await connection.client.request( - { method: 'resources/templates/list', params: {} }, - ListResourceTemplatesResultSchema - ); - const fields = extractCachingFields( - templatesResult as Record + const templatesResult = await conn.request( + 'resources/templates/list' ); + const fields = extractCachingFields(templatesResult); allFields.push({ endpoint: 'resources/templates/list', fields }); checks.push( buildPresenceCheck( @@ -233,16 +218,11 @@ Servers MUST include \`ttlMs\` (integer >= 0) and \`cacheScope\` ("public" or "p // 5. resources/read — use first resource from resources/list if (firstResourceUri) { try { - const readResult = await connection.client.request( - { - method: 'resources/read', - params: { uri: firstResourceUri } - }, - ReadResourceResultSchema - ); - const fields = extractCachingFields( - readResult as Record + const readResult = await conn.request( + 'resources/read', + { uri: firstResourceUri } ); + const fields = extractCachingFields(readResult); allFields.push({ endpoint: 'resources/read', fields }); checks.push( buildPresenceCheck( @@ -337,7 +317,7 @@ Servers MUST include \`ttlMs\` (integer >= 0) and \`cacheScope\` ("public" or "p } }); - await connection.close(); + await conn.close(); } catch (error) { // Connection-level failure — push a single failure check checks.push({ diff --git a/src/scenarios/server/dns-rebinding.ts b/src/scenarios/server/dns-rebinding.ts index 67c98d96..046d706b 100644 --- a/src/scenarios/server/dns-rebinding.ts +++ b/src/scenarios/server/dns-rebinding.ts @@ -5,7 +5,12 @@ * to prevent DNS rebinding attacks. See GHSA-w48q-cv73-mx4w for details. */ -import { ClientScenario, ConformanceCheck } from '../../types'; +import { + ClientScenario, + ConformanceCheck, + DRAFT_PROTOCOL_VERSION +} from '../../types'; +import type { RunContext } from '../../connection'; import { request } from 'undici'; const SPEC_REFERENCES = [ @@ -42,13 +47,50 @@ function getHostFromUrl(serverUrl: string): string { } /** - * Send an MCP initialize request with custom Host and Origin headers. + * Build a request body that any server for the given spec version should + * accept without prior setup (initialize for the stateful lifecycle, + * server/discover with _meta for the stateless lifecycle). + */ +function probeBody(specVersion: string): unknown { + const clientInfo = { + name: 'conformance-dns-rebinding-test', + version: '1.0.0' + }; + if (specVersion === DRAFT_PROTOCOL_VERSION) { + return { + jsonrpc: '2.0', + id: 1, + method: 'server/discover', + params: { + _meta: { + 'io.modelcontextprotocol/protocolVersion': specVersion, + 'io.modelcontextprotocol/clientInfo': clientInfo, + 'io.modelcontextprotocol/clientCapabilities': {} + } + } + }; + } + return { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: specVersion, + capabilities: {}, + clientInfo + } + }; +} + +/** + * Send an MCP request with custom Host and Origin headers. * Both headers are set to the same value so that servers checking either * Host or Origin will properly detect the rebinding attempt. */ async function sendRequestWithHostAndOrigin( serverUrl: string, - hostOrOrigin: string + hostOrOrigin: string, + specVersion: string ): Promise<{ statusCode: number; body: unknown }> { const response = await request(serverUrl, { method: 'POST', @@ -56,18 +98,10 @@ async function sendRequestWithHostAndOrigin( 'Content-Type': 'application/json', Host: hostOrOrigin, Origin: `http://${hostOrOrigin}`, - Accept: 'application/json, text/event-stream' + Accept: 'application/json, text/event-stream', + 'MCP-Protocol-Version': specVersion }, - body: JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: '2025-11-25', - capabilities: {}, - clientInfo: { name: 'conformance-dns-rebinding-test', version: '1.0.0' } - } - }) + body: JSON.stringify(probeBody(specVersion)) }); let body: unknown; @@ -109,7 +143,8 @@ website tricks a user's browser into making requests to the local server. See: https://github.com/modelcontextprotocol/typescript-sdk/security/advisories/GHSA-w48q-cv73-mx4w`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl, specVersion } = ctx; const checks: ConformanceCheck[] = []; const timestamp = new Date().toISOString(); @@ -160,7 +195,8 @@ See: https://github.com/modelcontextprotocol/typescript-sdk/security/advisories/ try { const response = await sendRequestWithHostAndOrigin( serverUrl, - attackerHost + attackerHost, + specVersion ); const isRejected = response.statusCode >= 400 && response.statusCode < 500; @@ -200,7 +236,11 @@ See: https://github.com/modelcontextprotocol/typescript-sdk/security/advisories/ // Check 2: Valid localhost Host/Origin headers should be accepted (2xx response) try { - const response = await sendRequestWithHostAndOrigin(serverUrl, validHost); + const response = await sendRequestWithHostAndOrigin( + serverUrl, + validHost, + specVersion + ); const isAccepted = response.statusCode >= 200 && response.statusCode < 300; diff --git a/src/scenarios/server/elicitation-defaults.ts b/src/scenarios/server/elicitation-defaults.ts index 61381c0f..f515cd78 100644 --- a/src/scenarios/server/elicitation-defaults.ts +++ b/src/scenarios/server/elicitation-defaults.ts @@ -2,13 +2,21 @@ * SEP-1034: Elicitation default values test scenarios for MCP servers */ -import { ClientScenario, ConformanceCheck } from '../../types'; -import { connectToServer } from './client-helper'; +import { + ClientScenario, + ConformanceCheck, + DRAFT_PROTOCOL_VERSION +} from '../../types'; +import type { RunContext } from '../../connection'; +import { connectToServer } from '../../connection/sdk-client'; import { ElicitRequestSchema } from '@modelcontextprotocol/sdk/types.js'; export class ElicitationDefaultsScenario implements ClientScenario { name = 'elicitation-sep1034-defaults'; - readonly source = { introducedIn: '2025-11-25' } as const; + readonly source = { + introducedIn: '2025-11-25', + removedIn: DRAFT_PROTOCOL_VERSION + } as const; description = `Test elicitation with default values for all primitive types (SEP-1034). **Server Implementation Requirements:** @@ -33,7 +41,8 @@ Implement a tool named \`test_elicitation_sep1034_defaults\` (no arguments) that } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { diff --git a/src/scenarios/server/elicitation-enums.ts b/src/scenarios/server/elicitation-enums.ts index 3a96451d..8b154753 100644 --- a/src/scenarios/server/elicitation-enums.ts +++ b/src/scenarios/server/elicitation-enums.ts @@ -2,13 +2,21 @@ * SEP-1330: Elicitation enum schema improvements test scenarios for MCP servers */ -import { ClientScenario, ConformanceCheck } from '../../types'; -import { connectToServer } from './client-helper'; +import { + ClientScenario, + ConformanceCheck, + DRAFT_PROTOCOL_VERSION +} from '../../types'; +import type { RunContext } from '../../connection'; +import { connectToServer } from '../../connection/sdk-client'; import { ElicitRequestSchema } from '@modelcontextprotocol/sdk/types.js'; export class ElicitationEnumsScenario implements ClientScenario { name = 'elicitation-sep1330-enums'; - readonly source = { introducedIn: '2025-11-25' } as const; + readonly source = { + introducedIn: '2025-11-25', + removedIn: DRAFT_PROTOCOL_VERSION + } as const; description = `Test elicitation with enum schema improvements (SEP-1330). **Server Implementation Requirements:** @@ -34,7 +42,8 @@ Implement a tool named \`test_elicitation_sep1330_enums\` (no arguments) that re } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { diff --git a/src/scenarios/server/http-standard-headers.ts b/src/scenarios/server/http-standard-headers.ts index 528b958d..61371475 100644 --- a/src/scenarios/server/http-standard-headers.ts +++ b/src/scenarios/server/http-standard-headers.ts @@ -20,7 +20,8 @@ import { ConformanceCheck, DRAFT_PROTOCOL_VERSION } from '../../types'; -import { connectToServer } from './client-helper'; +import type { RunContext } from '../../connection'; +import type { ListToolsResult } from '../../spec-types/draft'; const SPEC_REFERENCE = { id: 'SEP-2243-Server-Validation', @@ -262,15 +263,16 @@ export class HttpHeaderValidationScenario implements ClientScenario { - Server MUST return HTTP 400 Bad Request for validation failures - Server MUST return JSON-RPC error with code -32001 (HeaderMismatch)`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; let sessionId: string | null = null; try { - // Establish a session via normal SDK initialization - const connection = await connectToServer(serverUrl); - const toolsResult = await connection.client.listTools(); - await connection.close(); + // Discover tools via the version-appropriate connection + const conn = await ctx.connect(); + const toolsResult = await conn.request('tools/list'); + await conn.close(); // Get a fresh session for raw requests const initResponse = await sendRawRequest( @@ -563,14 +565,15 @@ export class HttpCustomHeaderServerValidationScenario implements ClientScenario - Server MUST treat values without =?base64?...?= wrapper as literal - Server MUST reject requests where custom header is omitted but value is in body`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; let sessionId: string | null = null; try { - const connection = await connectToServer(serverUrl); - const toolsResult = await connection.client.listTools(); - await connection.close(); + const conn = await ctx.connect(); + const toolsResult = await conn.request('tools/list'); + await conn.close(); // Find a tool with x-mcp-header annotations const xMcpTool = toolsResult.tools?.find((tool) => { diff --git a/src/scenarios/server/input-required-result.ts b/src/scenarios/server/input-required-result.ts index f471f582..566b1823 100644 --- a/src/scenarios/server/input-required-result.ts +++ b/src/scenarios/server/input-required-result.ts @@ -12,6 +12,7 @@ import { DRAFT_PROTOCOL_VERSION, SpecVersion } from '../../types'; +import type { RunContext } from '../../connection'; import { sendRpc, isInputRequiredResult, @@ -65,7 +66,8 @@ Implement a tool named \`test_input_required_result_elicitation\` (no arguments } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -210,7 +212,8 @@ Implement a tool named \`test_input_required_result_sampling\` (no arguments req **Behavior (Round 2):** When called with \`inputResponses\` containing the key \`"capital_question"\`, return a complete result with the sampling response text.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -345,7 +348,8 @@ Implement a tool named \`test_input_required_result_list_roots\` (no arguments r **Behavior (Round 2):** When called with \`inputResponses\` containing the key \`"client_roots"\` (a ListRootsResult with a \`roots\` array), return a complete result that references the provided roots.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -488,7 +492,8 @@ Implement a tool named \`test_input_required_result_request_state\` (no argument **Behavior (Round 2):** When called with \`inputResponses\` AND the echoed \`requestState\`, validate the state and return a complete result. The text content MUST include the word "state-ok" to confirm the server received and validated the requestState.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -630,7 +635,8 @@ Implement a tool named \`test_input_required_result_multiple_inputs\` (no argume **Behavior (Round 2):** When called with \`inputResponses\` containing ALL keys and the echoed \`requestState\`, return a complete result.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -815,7 +821,8 @@ Implement a tool named \`test_input_required_result_multi_round\` (no arguments **Behavior (Round 3):** When called with \`inputResponses\` for step2 + updated requestState, return a complete result.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -955,7 +962,8 @@ Use the same tool as A1: \`test_input_required_result_elicitation\`. **Behavior:** When the client retries with \`inputResponses\` that are missing required keys or contain wrong keys, the server SHOULD respond with a new \`InputRequiredResult\` re-requesting the missing information (NOT a JSON-RPC error).`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -1049,7 +1057,8 @@ Implement a prompt named \`test_input_required_result_prompt\` that requires eli **Behavior (Round 2):** When called with \`inputResponses\`, return a complete \`GetPromptResult\`.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -1152,7 +1161,8 @@ Uses the same tool as A1: \`test_input_required_result_elicitation\`. This scenario verifies that the resultType field is explicitly present in the response (not just inferred).`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -1216,7 +1226,8 @@ export class InputRequiredResultUnsupportedMethodsScenario implements ClientScen Servers MUST NOT send InputRequiredResult responses on any client requests other than the supported ones (prompts/get, resources/read, tools/call, tasks/result).`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; const errors: string[] = []; @@ -1281,7 +1292,8 @@ integrity-protected requestState (e.g. HMAC-signed). **Behavior (Round 2 - tampered):** When called with a modified/tampered requestState, return a JSON-RPC error (code -32602 or similar) indicating integrity check failure.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -1393,7 +1405,8 @@ Implement a tool named \`test_input_required_result_capabilities\` (no arguments Only include inputRequests for methods the client supports. For example, if the client declares \`sampling: {}\` but NOT \`elicitation\`, only include \`sampling/createMessage\` inputRequests.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -1475,7 +1488,8 @@ Uses the same tool as A1: \`test_input_required_result_elicitation\`. This scenario sends correct inputResponses PLUS extra unrecognized keys. The server SHOULD ignore the extra keys and complete normally.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -1548,7 +1562,8 @@ Uses the same tool as A1: \`test_input_required_result_elicitation\`. This scenario sends completely invalid inputResponses structures. The server SHOULD validate them and return a JSON-RPC error or a new InputRequiredResult.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { diff --git a/src/scenarios/server/json-schema-2020-12.ts b/src/scenarios/server/json-schema-2020-12.ts index b5693f73..23c4e22b 100644 --- a/src/scenarios/server/json-schema-2020-12.ts +++ b/src/scenarios/server/json-schema-2020-12.ts @@ -17,7 +17,8 @@ import { ConformanceCheck, DRAFT_PROTOCOL_VERSION } from '../../types.js'; -import { connectToServer } from './client-helper.js'; +import type { RunContext } from '../../connection'; +import type { ListToolsResult } from '../../spec-types/2025-11-25'; const EXPECTED_TOOL_NAME = 'json_schema_2020_12_tool'; const EXPECTED_SCHEMA_DIALECT = 'https://json-schema.org/draft/2020-12/schema'; @@ -27,19 +28,19 @@ const EXPECTED_SCHEMA_DIALECT = 'https://json-schema.org/draft/2020-12/schema'; * * Preserving the broader JSON Schema 2020-12 vocabulary is good behavior at * any protocol version, so a server that preserves the keywords gets SUCCESS - * regardless of what it negotiated. Stripping them is only a conformance - * FAILURE once the server claims a protocol version that includes SEP-2106 - * (the draft); a server that only negotiated an earlier dated version is not - * yet subject to the requirement, so the check is SKIPPED rather than failed. + * regardless. Stripping them is only a conformance FAILURE when the run + * targets a protocol version that includes SEP-2106 (the draft); when + * targeting an earlier dated version the requirement does not apply, so the + * check is SKIPPED rather than failed. */ export function sep2106KeywordCheckStatus( preserved: boolean, - negotiatedProtocolVersion: string | undefined + targetProtocolVersion: string ): CheckStatus { if (preserved) { return 'SUCCESS'; } - return negotiatedProtocolVersion === DRAFT_PROTOCOL_VERSION + return targetProtocolVersion === DRAFT_PROTOCOL_VERSION ? 'FAILURE' : 'SKIPPED'; } @@ -93,7 +94,7 @@ Implement tool \`${EXPECTED_TOOL_NAME}\` with inputSchema containing JSON Schema **Verification**: The test verifies that \`$schema\`, \`$defs\`, and \`additionalProperties\` are preserved (SEP-1613), and that the composition (\`allOf\`/\`anyOf\`), conditional (\`if\`/\`then\`/\`else\`), and \`$anchor\` keywords are preserved (SEP-2106), in the tool listing response.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; const specReferences = [ { @@ -109,13 +110,11 @@ Implement tool \`${EXPECTED_TOOL_NAME}\` with inputSchema containing JSON Schema ]; try { - const connection = await connectToServer(serverUrl); - // Negotiated wire protocolVersion from the initialize handshake; used to - // soft-gate the SEP-2106 checks below. - const negotiatedVersion = ( - connection.client.transport as { protocolVersion?: string } | undefined - )?.protocolVersion; - const result = await connection.client.listTools(); + const conn = await ctx.connect(); + // Spec version this run is targeting; used to soft-gate the SEP-2106 + // checks below. + const targetVersion = ctx.specVersion; + const result = await conn.request('tools/list'); // Find the test tool const tool = result.tools?.find((t) => t.name === EXPECTED_TOOL_NAME); @@ -138,7 +137,7 @@ Implement tool \`${EXPECTED_TOOL_NAME}\` with inputSchema containing JSON Schema }); if (!tool) { - await connection.close(); + await conn.close(); return checks; } @@ -222,11 +221,11 @@ Implement tool \`${EXPECTED_TOOL_NAME}\` with inputSchema containing JSON Schema // SEP-2106: the full JSON Schema 2020-12 vocabulary is permitted in // inputSchema and must survive tools/list rather than being stripped to - // properties/required. These checks are soft-gated on the negotiated - // protocol version (see sep2106KeywordCheckStatus): stripping the - // keywords is only a FAILURE for servers that negotiated the draft - // protocol version, and SKIPPED otherwise. - const skippedSuffix = ` (server negotiated protocol version ${negotiatedVersion ?? 'unknown'}; SEP-2106 applies from ${DRAFT_PROTOCOL_VERSION})`; + // properties/required. These checks are soft-gated on the protocol + // version this run targets (see sep2106KeywordCheckStatus): stripping + // the keywords is only a FAILURE when targeting the draft version, and + // SKIPPED otherwise. + const skippedSuffix = ` (run targets protocol version ${targetVersion}; SEP-2106 applies from ${DRAFT_PROTOCOL_VERSION})`; // Check 5: composition keywords (allOf / anyOf) preserved const allOf = inputSchema['allOf']; @@ -242,7 +241,7 @@ Implement tool \`${EXPECTED_TOOL_NAME}\` with inputSchema containing JSON Schema const compositionPreserved = hasAllOf && hasNestedAnyOf; const compositionStatus = sep2106KeywordCheckStatus( compositionPreserved, - negotiatedVersion + targetVersion ); checks.push({ @@ -262,7 +261,7 @@ Implement tool \`${EXPECTED_TOOL_NAME}\` with inputSchema containing JSON Schema details: { hasAllOf, hasNestedAnyOf, - negotiatedProtocolVersion: negotiatedVersion + targetProtocolVersion: targetVersion } }); @@ -273,7 +272,7 @@ Implement tool \`${EXPECTED_TOOL_NAME}\` with inputSchema containing JSON Schema const conditionalPreserved = hasIf && hasThen && hasElse; const conditionalStatus = sep2106KeywordCheckStatus( conditionalPreserved, - negotiatedVersion + targetVersion ); checks.push({ @@ -292,7 +291,7 @@ Implement tool \`${EXPECTED_TOOL_NAME}\` with inputSchema containing JSON Schema hasIf, hasThen, hasElse, - negotiatedProtocolVersion: negotiatedVersion + targetProtocolVersion: targetVersion } }); @@ -301,10 +300,7 @@ Implement tool \`${EXPECTED_TOOL_NAME}\` with inputSchema containing JSON Schema | Record | undefined; const hasAnchor = !!addressDef && '$anchor' in addressDef; - const anchorStatus = sep2106KeywordCheckStatus( - hasAnchor, - negotiatedVersion - ); + const anchorStatus = sep2106KeywordCheckStatus(hasAnchor, targetVersion); checks.push({ id: 'sep-2106-anchor-keyword-preserved', @@ -324,7 +320,7 @@ Implement tool \`${EXPECTED_TOOL_NAME}\` with inputSchema containing JSON Schema } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'json-schema-2020-12-error', diff --git a/src/scenarios/server/lifecycle.test.ts b/src/scenarios/server/lifecycle.test.ts index 15ee6d80..d787fe82 100644 --- a/src/scenarios/server/lifecycle.test.ts +++ b/src/scenarios/server/lifecycle.test.ts @@ -1,7 +1,8 @@ +import { testContext } from '../../connection/testing'; import { ServerInitializeScenario } from './lifecycle'; -import { connectToServer } from './client-helper'; +import { connectToServer } from '../../connection/sdk-client'; -vi.mock('./client-helper', () => ({ +vi.mock('../../connection/sdk-client', () => ({ connectToServer: vi.fn() })); @@ -26,7 +27,9 @@ describe('ServerInitializeScenario', () => { it('returns INFO when the server does not provide an MCP-Session-Id header', async () => { fetchMock.mockResolvedValue(new Response(null)); - const checks = await new ServerInitializeScenario().run(serverUrl); + const checks = await new ServerInitializeScenario().run( + testContext(serverUrl) + ); expect(connectToServer).toHaveBeenCalledWith(serverUrl); expect(closeMock).toHaveBeenCalled(); @@ -59,7 +62,9 @@ describe('ServerInitializeScenario', () => { }) ); - const checks = await new ServerInitializeScenario().run(serverUrl); + const checks = await new ServerInitializeScenario().run( + testContext(serverUrl) + ); expect(checks[1]).toMatchObject({ id: 'server-session-id-visible-ascii', @@ -79,7 +84,9 @@ describe('ServerInitializeScenario', () => { }) ); - const checks = await new ServerInitializeScenario().run(serverUrl); + const checks = await new ServerInitializeScenario().run( + testContext(serverUrl) + ); expect(checks[1]).toMatchObject({ id: 'server-session-id-visible-ascii', diff --git a/src/scenarios/server/lifecycle.ts b/src/scenarios/server/lifecycle.ts index bb55869e..61fac0b4 100644 --- a/src/scenarios/server/lifecycle.ts +++ b/src/scenarios/server/lifecycle.ts @@ -2,8 +2,13 @@ * Lifecycle test scenarios for MCP servers */ -import { ClientScenario, ConformanceCheck } from '../../types'; -import { connectToServer } from './client-helper'; +import { + ClientScenario, + ConformanceCheck, + DRAFT_PROTOCOL_VERSION +} from '../../types'; +import type { RunContext } from '../../connection'; +import { connectToServer } from '../../connection/sdk-client'; const VISIBLE_ASCII_REGEX = /^[\x21-\x7E]+$/; @@ -16,7 +21,10 @@ const SESSION_SPEC_REFERENCES = [ export class ServerInitializeScenario implements ClientScenario { name = 'server-initialize'; - readonly source = { introducedIn: '2025-06-18' } as const; + readonly source = { + introducedIn: '2025-06-18', + removedIn: DRAFT_PROTOCOL_VERSION + } as const; description = `Test basic server initialization handshake. **Server Implementation Requirements:** @@ -32,7 +40,8 @@ export class ServerInitializeScenario implements ClientScenario { This test verifies the server can complete the two-phase initialization handshake successfully, and validates session ID format if one is assigned.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { diff --git a/src/scenarios/server/negative-mrtr.test.ts b/src/scenarios/server/negative-mrtr.test.ts index e12dbe14..57ca0593 100644 --- a/src/scenarios/server/negative-mrtr.test.ts +++ b/src/scenarios/server/negative-mrtr.test.ts @@ -1,3 +1,4 @@ +import { testContext } from '../../connection/testing'; /** * SEP-2322 MRTR negative tests. * @@ -92,7 +93,7 @@ describe('SEP-2322 MRTR negative tests', () => { it('emits FAILURE for sep-2322-result-type-included against server that omits resultType', async () => { const scenario = new InputRequiredResultResultTypeScenario(); - const checks = await scenario.run(SERVER_URL); + const checks = await scenario.run(testContext(SERVER_URL)); const resultTypeCheck = checks.find( (c) => c.id === 'sep-2322-result-type-included' @@ -103,7 +104,7 @@ describe('SEP-2322 MRTR negative tests', () => { it('emits FAILURE for sep-2322-not-on-unsupported-requests against server returning InputRequiredResult on tools/list', async () => { const scenario = new InputRequiredResultUnsupportedMethodsScenario(); - const checks = await scenario.run(SERVER_URL); + const checks = await scenario.run(testContext(SERVER_URL)); const unsupportedCheck = checks.find( (c) => c.id === 'sep-2322-not-on-unsupported-requests' @@ -114,7 +115,7 @@ describe('SEP-2322 MRTR negative tests', () => { it('emits FAILURE for sep-2322-reject-tampered-state against server that accepts tampered state', async () => { const scenario = new InputRequiredResultTamperedStateScenario(); - const checks = await scenario.run(SERVER_URL); + const checks = await scenario.run(testContext(SERVER_URL)); const tamperedCheck = checks.find( (c) => c.id === 'sep-2322-reject-tampered-state' diff --git a/src/scenarios/server/negative.test.ts b/src/scenarios/server/negative.test.ts index d602d643..c18d8695 100644 --- a/src/scenarios/server/negative.test.ts +++ b/src/scenarios/server/negative.test.ts @@ -1,3 +1,4 @@ +import { testContext } from '../../connection/testing'; import { spawn, ChildProcess } from 'child_process'; import path from 'path'; import { DNSRebindingProtectionScenario } from './dns-rebinding'; @@ -74,7 +75,9 @@ describe('Server scenario negative tests', () => { it('emits FAILURE against a server without rebinding protection', async () => { const scenario = new DNSRebindingProtectionScenario(); - const checks = await scenario.run(`http://localhost:${PORT}/mcp`); + const checks = await scenario.run( + testContext(`http://localhost:${PORT}/mcp`) + ); const rebindingCheck = checks.find( (c) => c.id === 'localhost-host-rebinding-rejected' @@ -103,7 +106,9 @@ describe('Server scenario negative tests', () => { it('emits FAILURE for no-empty-contents and WARNING for error-code against a server returning empty contents', async () => { const scenario = new ResourcesNotFoundErrorScenario(); - const checks = await scenario.run(`http://localhost:${PORT}/mcp`); + const checks = await scenario.run( + testContext(`http://localhost:${PORT}/mcp`) + ); const noEmpty = checks.find((c) => c.id === 'sep-2164-no-empty-contents'); expect(noEmpty?.status).toBe('FAILURE'); @@ -133,7 +138,9 @@ describe('Server scenario negative tests', () => { it('emits FAILURE for presence checks against a server without caching hints', async () => { const scenario = new CachingScenario(); - const checks = await scenario.run(`http://localhost:${PORT}/mcp`); + const checks = await scenario.run( + testContext(`http://localhost:${PORT}/mcp`) + ); // Should have at least 7 checks (5 presence + 2 aggregate) expect(checks.length).toBeGreaterThanOrEqual(7); @@ -174,7 +181,9 @@ describe('Server scenario negative tests', () => { it('flags SEP-2106 keyword-preservation checks against a server that strips the 2020-12 vocabulary', async () => { const scenario = new JsonSchema2020_12Scenario(); - const checks = await scenario.run(`http://localhost:${PORT}/mcp`); + const checks = await scenario.run( + testContext(`http://localhost:${PORT}/mcp`) + ); // The tool is still advertised, so it must be found... const found = checks.find( @@ -182,10 +191,9 @@ describe('Server scenario negative tests', () => { ); expect(found?.status).toBe('SUCCESS'); - // ...but the stripped 2020-12 keywords must be flagged. The stripped - // server negotiates 2025-11-25 (the published SDK does not advertise the - // draft protocol version), so the soft version gate reports SKIPPED - // rather than FAILURE — see sep2106KeywordCheckStatus. + // ...but the stripped 2020-12 keywords must be flagged. testContext() + // defaults to LATEST_SPEC_VERSION (2025-11-25), so the soft version gate + // reports SKIPPED rather than FAILURE; see sep2106KeywordCheckStatus. const composition = checks.find( (c) => c.id === 'sep-2106-composition-keywords-preserved' ); @@ -204,24 +212,22 @@ describe('Server scenario negative tests', () => { }); describe('sep2106KeywordCheckStatus (soft version gate)', () => { - it('passes preserved keywords at any negotiated version', () => { + it('passes preserved keywords at any target version', () => { expect(sep2106KeywordCheckStatus(true, DRAFT_PROTOCOL_VERSION)).toBe( 'SUCCESS' ); expect(sep2106KeywordCheckStatus(true, LATEST_SPEC_VERSION)).toBe( 'SUCCESS' ); - expect(sep2106KeywordCheckStatus(true, undefined)).toBe('SUCCESS'); }); - it('fails stripped keywords only when the server negotiated the draft version', () => { + it('fails stripped keywords only when targeting the draft version', () => { expect(sep2106KeywordCheckStatus(false, DRAFT_PROTOCOL_VERSION)).toBe( 'FAILURE' ); expect(sep2106KeywordCheckStatus(false, LATEST_SPEC_VERSION)).toBe( 'SKIPPED' ); - expect(sep2106KeywordCheckStatus(false, undefined)).toBe('SKIPPED'); }); }); }); diff --git a/src/scenarios/server/prompts.ts b/src/scenarios/server/prompts.ts index 2f65723f..c5a5f380 100644 --- a/src/scenarios/server/prompts.ts +++ b/src/scenarios/server/prompts.ts @@ -3,7 +3,11 @@ */ import { ClientScenario, ConformanceCheck } from '../../types'; -import { connectToServer } from './client-helper'; +import type { RunContext } from '../../connection'; +import type { + ListPromptsResult, + GetPromptResult +} from '../../spec-types/2025-06-18'; export class PromptsListScenario implements ClientScenario { name = 'prompts-list'; @@ -21,13 +25,13 @@ export class PromptsListScenario implements ClientScenario { - \`description\` (string) - \`arguments\` (array, optional) - list of required arguments`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.listPrompts(); + const result = await conn.request('prompts/list'); // Validate response structure const errors: string[] = []; @@ -64,7 +68,7 @@ export class PromptsListScenario implements ClientScenario { } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'prompts-list', @@ -109,13 +113,13 @@ Implement a prompt named \`test_simple_prompt\` with no arguments that returns: } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.getPrompt({ + const result = await conn.request('prompts/get', { name: 'test_simple_prompt' }); @@ -149,7 +153,7 @@ Implement a prompt named \`test_simple_prompt\` with no arguments that returns: } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'prompts-get-simple', @@ -198,13 +202,13 @@ Returns (with args \`{arg1: "hello", arg2: "world"}\`): } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.getPrompt({ + const result = await conn.request('prompts/get', { name: 'test_prompt_with_arguments', arguments: { arg1: 'testValue1', @@ -245,7 +249,7 @@ Returns (with args \`{arg1: "hello", arg2: "world"}\`): } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'prompts-get-with-args', @@ -304,13 +308,13 @@ Returns: } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.getPrompt({ + const result = await conn.request('prompts/get', { name: 'test_prompt_with_embedded_resource', arguments: { resourceUri: 'test://example-resource' @@ -351,7 +355,7 @@ Returns: } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'prompts-get-embedded-resource', @@ -404,13 +408,13 @@ Implement a prompt named \`test_prompt_with_image\` with no arguments that retur } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.getPrompt({ + const result = await conn.request('prompts/get', { name: 'test_prompt_with_image' }); @@ -448,7 +452,7 @@ Implement a prompt named \`test_prompt_with_image\` with no arguments that retur } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'prompts-get-with-image', diff --git a/src/scenarios/server/resources.ts b/src/scenarios/server/resources.ts index be332d49..b34d9220 100644 --- a/src/scenarios/server/resources.ts +++ b/src/scenarios/server/resources.ts @@ -7,12 +7,14 @@ import { ConformanceCheck, DRAFT_PROTOCOL_VERSION } from '../../types'; -import { connectToServer } from './client-helper'; -import { +import { JsonRpcError, type RunContext } from '../../connection'; +import type { + ListResourcesResult, + ReadResourceResult, TextResourceContents, BlobResourceContents, - McpError -} from '@modelcontextprotocol/sdk/types.js'; + EmptyResult +} from '../../spec-types/2025-06-18'; export class ResourcesListScenario implements ClientScenario { name = 'resources-list'; @@ -31,13 +33,13 @@ export class ResourcesListScenario implements ClientScenario { - \`description\` (string) - \`mimeType\` (string, optional)`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.listResources(); + const result = await conn.request('resources/list'); // Validate response structure const errors: string[] = []; @@ -73,7 +75,7 @@ export class ResourcesListScenario implements ClientScenario { } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'resources-list', @@ -116,13 +118,13 @@ Implement resource \`test://static-text\` that returns: } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.readResource({ + const result = await conn.request('resources/read', { uri: 'test://static-text' }); @@ -160,7 +162,7 @@ Implement resource \`test://static-text\` that returns: } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'resources-read-text', @@ -203,13 +205,13 @@ Implement resource \`test://static-binary\` that returns: } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.readResource({ + const result = await conn.request('resources/read', { uri: 'test://static-binary' }); @@ -245,7 +247,7 @@ Implement resource \`test://static-binary\` that returns: } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'resources-read-binary', @@ -292,13 +294,13 @@ Returns (for \`uri: "test://template/123/data"\`): } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.readResource({ + const result = await conn.request('resources/read', { uri: 'test://template/123/data' }); @@ -347,7 +349,7 @@ Returns (for \`uri: "test://template/123/data"\`): } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'resources-templates-read', @@ -371,7 +373,10 @@ Returns (for \`uri: "test://template/123/data"\`): export class ResourcesSubscribeScenario implements ClientScenario { name = 'resources-subscribe'; - readonly source = { introducedIn: '2025-06-18' } as const; + readonly source = { + introducedIn: '2025-06-18', + removedIn: DRAFT_PROTOCOL_VERSION + } as const; description = `Test subscribing to resource updates. **Server Implementation Requirements:** @@ -394,13 +399,13 @@ Example request: } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - await connection.client.subscribeResource({ + await conn.request('resources/subscribe', { uri: 'test://watched-resource' }); @@ -418,7 +423,7 @@ Example request: ] }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'resources-subscribe', @@ -473,7 +478,7 @@ Example error response: This scenario does not require the server to register any specific resource — it tests behavior when reading a URI the server does not recognize.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; const nonexistentUri = 'test://nonexistent-resource-for-conformance-testing'; @@ -484,9 +489,9 @@ This scenario does not require the server to register any specific resource — } ]; - let connection; + let conn; try { - connection = await connectToServer(serverUrl); + conn = await ctx.connect(); } catch (error) { checks.push({ id: 'sep-2164-error-code', @@ -504,7 +509,9 @@ This scenario does not require the server to register any specific resource — let caughtError: unknown; let result: { contents: unknown[] } | undefined; try { - result = await connection.client.readResource({ uri: nonexistentUri }); + result = await conn.request('resources/read', { + uri: nonexistentUri + }); } catch (error) { caughtError = error; } @@ -531,12 +538,13 @@ This scenario does not require the server to register any specific resource — }); // Check 2: SHOULD return JSON-RPC error with code -32602 - const errorCode = - caughtError instanceof McpError ? caughtError.code : undefined; + const rpcError = + caughtError instanceof JsonRpcError ? caughtError : undefined; + const errorCode = rpcError?.code; let errorCodeMessage: string | undefined; if (result !== undefined) { errorCodeMessage = `Server returned a result instead of an error (contents length: ${result.contents?.length ?? 'undefined'}). Servers SHOULD return a JSON-RPC error for non-existent resources.`; - } else if (!(caughtError instanceof McpError)) { + } else if (rpcError === undefined) { errorCodeMessage = `Expected a JSON-RPC error, got: ${caughtError instanceof Error ? caughtError.message : String(caughtError)}`; } else if (errorCode !== -32602) { errorCodeMessage = @@ -563,10 +571,7 @@ This scenario does not require the server to register any specific resource — }); // Check 3: SHOULD include uri in error data field - const errorData = - caughtError instanceof McpError - ? (caughtError.data as { uri?: string } | undefined) - : undefined; + const errorData = rpcError?.data as { uri?: string } | undefined; const dataUriMatches = errorData?.uri === nonexistentUri; checks.push({ @@ -575,14 +580,14 @@ This scenario does not require the server to register any specific resource — description: 'Server includes the requested URI in the error data field (SHOULD)', status: - caughtError instanceof McpError + rpcError !== undefined ? dataUriMatches ? 'SUCCESS' : 'WARNING' : 'FAILURE', timestamp: new Date().toISOString(), errorMessage: - caughtError instanceof McpError + rpcError !== undefined ? dataUriMatches ? undefined : `Error data.uri is ${JSON.stringify(errorData?.uri)}, expected "${nonexistentUri}". This is a SHOULD requirement.` @@ -594,14 +599,17 @@ This scenario does not require the server to register any specific resource — } }); - await connection.close(); + await conn.close(); return checks; } } export class ResourcesUnsubscribeScenario implements ClientScenario { name = 'resources-unsubscribe'; - readonly source = { introducedIn: '2025-06-18' } as const; + readonly source = { + introducedIn: '2025-06-18', + removedIn: DRAFT_PROTOCOL_VERSION + } as const; description = `Test unsubscribing from resource. **Server Implementation Requirements:** @@ -614,19 +622,19 @@ export class ResourcesUnsubscribeScenario implements ClientScenario { - Stop sending update notifications for that URI - Return empty object \`{}\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); // First subscribe - await connection.client.subscribeResource({ + await conn.request('resources/subscribe', { uri: 'test://watched-resource' }); // Then unsubscribe - await connection.client.unsubscribeResource({ + await conn.request('resources/unsubscribe', { uri: 'test://watched-resource' }); @@ -644,7 +652,7 @@ export class ResourcesUnsubscribeScenario implements ClientScenario { ] }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'resources-unsubscribe', diff --git a/src/scenarios/server/sse-multiple-streams.ts b/src/scenarios/server/sse-multiple-streams.ts index 7090f81c..1259348c 100644 --- a/src/scenarios/server/sse-multiple-streams.ts +++ b/src/scenarios/server/sse-multiple-streams.ts @@ -9,7 +9,12 @@ * Multiple concurrent streams are achieved via POST requests, each getting their own stream. */ -import { ClientScenario, ConformanceCheck } from '../../types.js'; +import { + ClientScenario, + ConformanceCheck, + DRAFT_PROTOCOL_VERSION +} from '../../types.js'; +import type { RunContext } from '../../connection'; import { EventSourceParserStream } from 'eventsource-parser/stream'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; @@ -20,55 +25,90 @@ export class ServerSSEMultipleStreamsScenario implements ClientScenario { description = 'Test server supports multiple concurrent POST SSE streams (SEP-1699)'; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl, specVersion } = ctx; const checks: ConformanceCheck[] = []; + // Concurrent POSTs (each answered with JSON or its own SSE stream) are + // core transport behavior in every spec version. Only the request + // scaffolding differs: the stateful lifecycle needs a session id from an + // initialize handshake, the stateless lifecycle carries _meta + the + // MCP-Protocol-Version header on each request instead. + const stateless = specVersion === DRAFT_PROTOCOL_VERSION; + let sessionId: string | undefined; let client: Client | undefined; let transport: StreamableHTTPClientTransport | undefined; try { - // Step 1: Initialize session with the server - client = new Client( - { - name: 'conformance-test-client', - version: '1.0.0' - }, - { - capabilities: { - sampling: {}, - elicitation: {} + if (!stateless) { + // Step 1 (stateful): Initialize session with the server + client = new Client( + { + name: 'conformance-test-client', + version: '1.0.0' + }, + { + capabilities: { + sampling: {}, + elicitation: {} + } } - } - ); + ); - transport = new StreamableHTTPClientTransport(new URL(serverUrl)); - await client.connect(transport); + transport = new StreamableHTTPClientTransport(new URL(serverUrl)); + await client.connect(transport); - // Extract session ID from transport - sessionId = (transport as unknown as { sessionId?: string }).sessionId; + // Extract session ID from transport + sessionId = (transport as unknown as { sessionId?: string }).sessionId; - if (!sessionId) { - checks.push({ - id: 'server-sse-multiple-streams-session', - name: 'ServerSSEMultipleStreamsSession', - description: 'Server provides session ID for multiple streams test', - status: 'WARNING', - timestamp: new Date().toISOString(), - specReferences: [ - { - id: 'SEP-1699', - url: 'https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699' + if (!sessionId) { + checks.push({ + id: 'server-sse-multiple-streams-session', + name: 'ServerSSEMultipleStreamsSession', + description: 'Server provides session ID for multiple streams test', + status: 'WARNING', + timestamp: new Date().toISOString(), + specReferences: [ + { + id: 'SEP-1699', + url: 'https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699' + } + ], + details: { + message: + 'Server did not provide session ID - multiple streams test may not work correctly' } - ], - details: { - message: - 'Server did not provide session ID - multiple streams test may not work correctly' - } - }); - return checks; + }); + return checks; + } } + const requestHeaders: Record = stateless + ? { + 'Content-Type': 'application/json', + Accept: 'text/event-stream, application/json', + 'MCP-Protocol-Version': DRAFT_PROTOCOL_VERSION + } + : { + 'Content-Type': 'application/json', + Accept: 'text/event-stream, application/json', + 'mcp-session-id': sessionId!, + 'mcp-protocol-version': '2025-03-26' + }; + const requestParams = stateless + ? { + _meta: { + 'io.modelcontextprotocol/protocolVersion': DRAFT_PROTOCOL_VERSION, + 'io.modelcontextprotocol/clientInfo': { + name: 'conformance-test-client', + version: '1.0.0' + }, + 'io.modelcontextprotocol/clientCapabilities': {} + } + } + : {}; + // Step 2: Open multiple POST SSE streams concurrently // Each POST request gets its own stream with unique streamId // Spec says: "The client MAY remain connected to multiple SSE streams simultaneously" @@ -80,17 +120,12 @@ export class ServerSSEMultipleStreamsScenario implements ClientScenario { for (let i = 0; i < numStreams; i++) { const promise = fetch(serverUrl, { method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'text/event-stream, application/json', - 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-03-26' - }, + headers: requestHeaders, body: JSON.stringify({ jsonrpc: '2.0', id: 1000 + i, // Different request IDs for each stream method: 'tools/list', - params: {} + params: requestParams }) }); postPromises.push(promise); diff --git a/src/scenarios/server/sse-polling.ts b/src/scenarios/server/sse-polling.ts index 79e59864..0f52f406 100644 --- a/src/scenarios/server/sse-polling.ts +++ b/src/scenarios/server/sse-polling.ts @@ -8,7 +8,12 @@ * - Replaying events when client reconnects with Last-Event-ID */ -import { ClientScenario, ConformanceCheck } from '../../types.js'; +import { + ClientScenario, + ConformanceCheck, + DRAFT_PROTOCOL_VERSION +} from '../../types.js'; +import type { RunContext } from '../../connection'; import { EventSourceParserStream } from 'eventsource-parser/stream'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; @@ -67,11 +72,15 @@ function createLoggingFetch(checks: ConformanceCheck[]) { export class ServerSSEPollingScenario implements ClientScenario { name = 'server-sse-polling'; - readonly source = { introducedIn: '2025-11-25' } as const; + readonly source = { + introducedIn: '2025-11-25', + removedIn: DRAFT_PROTOCOL_VERSION + } as const; description = 'Test server SSE polling via test_reconnection tool that closes stream mid-call (SEP-1699)'; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; let sessionId: string | undefined; diff --git a/src/scenarios/server/stateless.test.ts b/src/scenarios/server/stateless.test.ts index 99b376a9..0870af9a 100644 --- a/src/scenarios/server/stateless.test.ts +++ b/src/scenarios/server/stateless.test.ts @@ -1,3 +1,4 @@ +import { testContext } from '../../connection/testing'; import { ServerStatelessScenario } from './stateless'; import { describe, test, expect } from 'vitest'; import { ConformanceCheck } from '../../types'; @@ -110,7 +111,7 @@ describe('Stateless Server Scenario Negative Tests', () => { }); const scenario = new ServerStatelessScenario(); - const checks = await scenario.run(mockUrl); + const checks = await scenario.run(testContext(mockUrl)); // The test scenario should flag this server as a FAILURE for skipping meta validation const missingMetaCheck = findCheck( @@ -153,7 +154,7 @@ describe('Stateless Server Scenario Negative Tests', () => { }); const scenario = new ServerStatelessScenario(); - const checks = await scenario.run(mockUrl); + const checks = await scenario.run(testContext(mockUrl)); const pingRouteCheck = findCheck( checks, @@ -189,7 +190,7 @@ describe('Stateless Server Scenario Negative Tests', () => { }); const scenario = new ServerStatelessScenario(); - const checks = await scenario.run(mockUrl); + const checks = await scenario.run(testContext(mockUrl)); const negotiationMatchCheck = findCheck( checks, @@ -216,7 +217,7 @@ describe('Stateless Server Scenario Negative Tests', () => { }); const scenario = new ServerStatelessScenario(); - const checks = await scenario.run(mockUrl); + const checks = await scenario.run(testContext(mockUrl)); const ackCheck = findCheck( checks, @@ -250,7 +251,7 @@ describe('Stateless Server Scenario Negative Tests', () => { }); const scenario = new ServerStatelessScenario(); - const checks = await scenario.run(mockUrl); + const checks = await scenario.run(testContext(mockUrl)); const independentRequestCheck = findCheck( checks, @@ -280,7 +281,7 @@ describe('Stateless Server Scenario Negative Tests', () => { }); const scenario = new ServerStatelessScenario(); - const checks = await scenario.run(mockUrl); + const checks = await scenario.run(testContext(mockUrl)); const logWithoutLevelCheck = findCheck( checks, @@ -321,7 +322,7 @@ describe('Stateless Server Scenario Negative Tests', () => { }); const scenario = new ServerStatelessScenario(); - const checks = await scenario.run(mockUrl); + const checks = await scenario.run(testContext(mockUrl)); const filterCheck = findCheck( checks, @@ -393,7 +394,7 @@ describe('Stateless Server Scenario Negative Tests', () => { }); const scenario = new ServerStatelessScenario(); - const checks = await scenario.run(mockUrl); + const checks = await scenario.run(testContext(mockUrl)); const promptsCheck = findCheck( checks, diff --git a/src/scenarios/server/stateless.ts b/src/scenarios/server/stateless.ts index def16e48..2648969c 100644 --- a/src/scenarios/server/stateless.ts +++ b/src/scenarios/server/stateless.ts @@ -7,6 +7,7 @@ import { ConformanceCheck, DRAFT_PROTOCOL_VERSION } from '../../types'; +import type { RunContext } from '../../connection'; const SPEC_REF = [ { @@ -47,7 +48,8 @@ export class ServerStatelessScenario implements ClientScenario { 7. **Dynamic List Mutations (2 Checks)** - Evaluates that list-changed capable servers notify active listen streams with \`promptsListChanged: true\` or \`toolsListChanged: true\` upon live configuration or capability modifications. `; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; const timestamp = new Date().toISOString(); diff --git a/src/scenarios/server/tools.ts b/src/scenarios/server/tools.ts index 2fb4717a..7fb43ce2 100644 --- a/src/scenarios/server/tools.ts +++ b/src/scenarios/server/tools.ts @@ -2,13 +2,23 @@ * Tools test scenarios for MCP servers */ -import { ClientScenario, ConformanceCheck } from '../../types'; -import { connectToServer, NotificationCollector } from './client-helper'; import { - CallToolResultSchema, + ClientScenario, + ConformanceCheck, + DRAFT_PROTOCOL_VERSION +} from '../../types'; +import type { RunContext } from '../../connection'; +import type { + ListToolsResult, + CallToolResult +} from '../../spec-types/2025-06-18'; +import { + connectToServer, + NotificationCollector +} from '../../connection/sdk-client'; +import { CreateMessageRequestSchema, - ElicitRequestSchema, - Progress + ElicitRequestSchema } from '@modelcontextprotocol/sdk/types.js'; const TOOL_NAME_PATTERN = /^[A-Za-z0-9_./-]+$/; @@ -104,13 +114,13 @@ export class ToolsListScenario implements ClientScenario { - \`description\` (string) - \`inputSchema\` (valid JSON Schema object)`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.listTools(); + const result = await conn.request('tools/list'); // Validate response structure const errors: string[] = []; @@ -153,7 +163,7 @@ export class ToolsListScenario implements ClientScenario { // names MUST be 1-64 chars matching ^[A-Za-z0-9_./-]+$ checks.push(buildToolsNameFormatCheck(result.tools)); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'tools-list', @@ -195,13 +205,13 @@ Implement tool \`test_simple_text\` with no arguments that returns: } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.callTool({ + const result = await conn.request('tools/call', { name: 'test_simple_text' /* omit arguments as it is not required in the schema */ }); @@ -238,7 +248,7 @@ Implement tool \`test_simple_text\` with no arguments that returns: } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'tools-call-simple-text', @@ -283,13 +293,13 @@ Implement tool \`test_image_content\` with no arguments that returns: **Implementation Note**: Use a minimal test image (e.g., 1x1 red pixel PNG)`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.callTool({ + const result = await conn.request('tools/call', { name: 'test_image_content', arguments: {} }); @@ -326,7 +336,7 @@ Implement tool \`test_image_content\` with no arguments that returns: } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'tools-call-image', @@ -381,13 +391,13 @@ Implement tool \`test_multiple_content_types\` with no arguments that returns: } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.callTool({ + const result = await conn.request('tools/call', { name: 'test_multiple_content_types', arguments: {} }); @@ -427,7 +437,7 @@ Implement tool \`test_multiple_content_types\` with no arguments that returns: } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'tools-call-mixed-content', @@ -451,7 +461,10 @@ Implement tool \`test_multiple_content_types\` with no arguments that returns: export class ToolsCallWithLoggingScenario implements ClientScenario { name = 'tools-call-with-logging'; - readonly source = { introducedIn: '2025-06-18' } as const; + readonly source = { + introducedIn: '2025-06-18', + removedIn: DRAFT_PROTOCOL_VERSION + } as const; description = `Test tool that sends log messages during execution. **Server Implementation Requirements:** @@ -467,7 +480,8 @@ Implement tool \`test_tool_with_logging\` with no arguments. **Implementation Note**: The delays are important to test that clients can receive multiple log notifications during tool execution`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -563,13 +577,13 @@ Implement tool \`test_error_handling\` with no arguments. } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result: any = await connection.client.callTool({ + const result: any = await conn.request('tools/call', { name: 'test_error_handling', arguments: {} }); @@ -601,7 +615,7 @@ Implement tool \`test_error_handling\` with no arguments. } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'tools-call-error', @@ -656,31 +670,22 @@ If no progress token provided, just execute with delays. } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); - const progressUpdates: Array = []; - // TODO: investigate why await connection.client.callTool didn't work for progress. - const result = await connection.client.request( - { - method: 'tools/call', - params: { - name: 'test_tool_with_progress', - arguments: {}, - _meta: { - progressToken: 'progress-test-1' - } - } - }, - CallToolResultSchema, - { - onprogress: (progress) => { - progressUpdates.push(progress); - } + const conn = await ctx.connect(); + const result = await conn.request('tools/call', { + name: 'test_tool_with_progress', + arguments: {}, + _meta: { + progressToken: 'progress-test-1' } - ); + }); + + const progressUpdates = conn.notifications + .filter((n) => n.method === 'notifications/progress') + .map((n) => n.params as { progress: number; total?: number }); const errors: string[] = []; if (progressUpdates.length === 0) { @@ -716,12 +721,12 @@ If no progress token provided, just execute with delays. ], details: { progressCount: progressUpdates.length, - progressNotifications: progressUpdates.map((n: Progress) => n), + progressNotifications: progressUpdates, result } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'tools-call-with-progress', @@ -745,7 +750,10 @@ If no progress token provided, just execute with delays. export class ToolsCallSamplingScenario implements ClientScenario { name = 'tools-call-sampling'; - readonly source = { introducedIn: '2025-06-18' } as const; + readonly source = { + introducedIn: '2025-06-18', + removedIn: DRAFT_PROTOCOL_VERSION + } as const; description = `Test tool that requests LLM sampling from client. **Server Implementation Requirements:** @@ -790,7 +798,8 @@ Implement tool \`test_sampling\` with argument: **Implementation Note**: If the client doesn't support sampling (no \`sampling\` capability), return an error.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -873,7 +882,10 @@ Implement tool \`test_sampling\` with argument: export class ToolsCallElicitationScenario implements ClientScenario { name = 'tools-call-elicitation'; - readonly source = { introducedIn: '2025-06-18' } as const; + readonly source = { + introducedIn: '2025-06-18', + removedIn: DRAFT_PROTOCOL_VERSION + } as const; description = `Test tool that requests user input (elicitation) from client. **Server Implementation Requirements:** @@ -923,7 +935,8 @@ Implement tool \`test_elicitation\` with argument: **Implementation Note**: If the client doesn't support elicitation (no \`elicitation\` capability), return an error.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { + const { serverUrl } = ctx; const checks: ConformanceCheck[] = []; try { @@ -1025,13 +1038,13 @@ Implement tool \`test_audio_content\` with no arguments that returns: **Implementation Note**: Use a minimal test audio file`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.callTool({ + const result = await conn.request('tools/call', { name: 'test_audio_content', arguments: {} }); @@ -1075,7 +1088,7 @@ Implement tool \`test_audio_content\` with no arguments that returns: } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'tools-call-audio', @@ -1121,13 +1134,13 @@ Implement tool \`test_embedded_resource\` with no arguments that returns: } \`\`\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); - const result = await connection.client.callTool({ + const result = await conn.request('tools/call', { name: 'test_embedded_resource', arguments: {} }); @@ -1174,7 +1187,7 @@ Implement tool \`test_embedded_resource\` with no arguments that returns: } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'tools-call-embedded-resource', diff --git a/src/scenarios/server/utils.ts b/src/scenarios/server/utils.ts index 54b6d949..b2297158 100644 --- a/src/scenarios/server/utils.ts +++ b/src/scenarios/server/utils.ts @@ -2,12 +2,20 @@ * Utilities test scenarios for MCP servers */ -import { ClientScenario, ConformanceCheck } from '../../types'; -import { connectToServer } from './client-helper'; +import { + ClientScenario, + ConformanceCheck, + DRAFT_PROTOCOL_VERSION +} from '../../types'; +import type { RunContext } from '../../connection'; +import type { CompleteResult, EmptyResult } from '../../spec-types/2025-06-18'; export class LoggingSetLevelScenario implements ClientScenario { name = 'logging-set-level'; - readonly source = { introducedIn: '2025-06-18' } as const; + readonly source = { + introducedIn: '2025-06-18', + removedIn: DRAFT_PROTOCOL_VERSION + } as const; description = `Test setting logging level. **Server Implementation Requirements:** @@ -29,14 +37,16 @@ export class LoggingSetLevelScenario implements ClientScenario { - \`alert\` - \`emergency\``; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); // Send logging/setLevel request - const result = await connection.client.setLoggingLevel('info'); + const result = await conn.request('logging/setLevel', { + level: 'info' + }); // Validate response (should return empty object {}) const errors: string[] = []; @@ -62,7 +72,7 @@ export class LoggingSetLevelScenario implements ClientScenario { } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'logging-set-level', @@ -86,7 +96,10 @@ export class LoggingSetLevelScenario implements ClientScenario { export class PingScenario implements ClientScenario { name = 'ping'; - readonly source = { introducedIn: '2025-06-18' } as const; + readonly source = { + introducedIn: '2025-06-18', + removedIn: DRAFT_PROTOCOL_VERSION + } as const; description = `Test ping utility for connection health check. **Server Implementation Requirements:** @@ -119,14 +132,14 @@ export class PingScenario implements ClientScenario { **Implementation Note**: The ping utility allows either party to verify that their counterpart is still responsive and the connection is alive.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); // Send ping request - const result = await connection.client.ping(); + const result = await conn.request('ping'); // Validate response (should return empty object {}) const errors: string[] = []; @@ -152,7 +165,7 @@ export class PingScenario implements ClientScenario { } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'ping', @@ -220,14 +233,14 @@ export class CompletionCompleteScenario implements ClientScenario { **Implementation Note**: For conformance testing, completion support can be minimal or return empty arrays. The capability just needs to be declared and the endpoint must respond correctly.`; - async run(serverUrl: string): Promise { + async run(ctx: RunContext): Promise { const checks: ConformanceCheck[] = []; try { - const connection = await connectToServer(serverUrl); + const conn = await ctx.connect(); // Send completion/complete request - const result = await connection.client.complete({ + const result = await conn.request('completion/complete', { ref: { type: 'ref/prompt', name: 'test_prompt_with_arguments' @@ -267,7 +280,7 @@ export class CompletionCompleteScenario implements ClientScenario { } }); - await connection.close(); + await conn.close(); } catch (error) { checks.push({ id: 'completion-complete', diff --git a/src/spec-types/2025-03-26.ts b/src/spec-types/2025-03-26.ts new file mode 100644 index 00000000..a4b3a9d9 --- /dev/null +++ b/src/spec-types/2025-03-26.ts @@ -0,0 +1,1260 @@ +/* JSON-RPC types */ + +/** + * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. + */ +export type JSONRPCMessage = + | JSONRPCRequest + | JSONRPCNotification + | JSONRPCBatchRequest + | JSONRPCResponse + | JSONRPCError + | JSONRPCBatchResponse; + +/** + * A JSON-RPC batch request, as described in https://www.jsonrpc.org/specification#batch. + */ +export type JSONRPCBatchRequest = (JSONRPCRequest | JSONRPCNotification)[]; + +/** + * A JSON-RPC batch response, as described in https://www.jsonrpc.org/specification#batch. + */ +export type JSONRPCBatchResponse = (JSONRPCResponse | JSONRPCError)[]; + +export const LATEST_PROTOCOL_VERSION = "2025-03-26"; +export const JSONRPC_VERSION = "2.0"; + +/** + * A progress token, used to associate progress notifications with the original request. + */ +export type ProgressToken = string | number; + +/** + * An opaque token used to represent a cursor for pagination. + */ +export type Cursor = string; + +export interface Request { + method: string; + params?: { + _meta?: { + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken?: ProgressToken; + }; + [key: string]: unknown; + }; +} + +export interface Notification { + method: string; + params?: { + /** + * This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications. + */ + _meta?: { [key: string]: unknown }; + [key: string]: unknown; + }; +} + +export interface Result { + /** + * This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses. + */ + _meta?: { [key: string]: unknown }; + [key: string]: unknown; +} + +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +export type RequestId = string | number; + +/** + * A request that expects a response. + */ +export interface JSONRPCRequest extends Request { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; +} + +/** + * A notification which does not expect a response. + */ +export interface JSONRPCNotification extends Notification { + jsonrpc: typeof JSONRPC_VERSION; +} + +/** + * A successful (non-error) response to a request. + */ +export interface JSONRPCResponse { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + result: Result; +} + +// Standard JSON-RPC error codes +export const PARSE_ERROR = -32700; +export const INVALID_REQUEST = -32600; +export const METHOD_NOT_FOUND = -32601; +export const INVALID_PARAMS = -32602; +export const INTERNAL_ERROR = -32603; + +/** + * A response to a request that indicates an error occurred. + */ +export interface JSONRPCError { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + error: { + /** + * The error type that occurred. + */ + code: number; + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string; + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data?: unknown; + }; +} + +/* Empty result */ +/** + * A response that indicates success but carries no data. + */ +export type EmptyResult = Result; + +/* Cancellation */ +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + */ +export interface CancelledNotification extends Notification { + method: "notifications/cancelled"; + params: { + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestId; + + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason?: string; + }; +} + +/* Initialization */ +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ +export interface InitializeRequest extends Request { + method: "initialize"; + params: { + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string; + capabilities: ClientCapabilities; + clientInfo: Implementation; + }; +} + +/** + * After receiving an initialize request from the client, the server sends this response. + */ +export interface InitializeResult extends Result { + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string; + capabilities: ServerCapabilities; + serverInfo: Implementation; + + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions?: string; +} + +/** + * This notification is sent from the client to the server after initialization has finished. + */ +export interface InitializedNotification extends Notification { + method: "notifications/initialized"; +} + +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ +export interface ClientCapabilities { + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental?: { [key: string]: object }; + /** + * Present if the client supports listing roots. + */ + roots?: { + /** + * Whether the client supports notifications for changes to the roots list. + */ + listChanged?: boolean; + }; + /** + * Present if the client supports sampling from an LLM. + */ + sampling?: object; +} + +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ +export interface ServerCapabilities { + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental?: { [key: string]: object }; + /** + * Present if the server supports sending log messages to the client. + */ + logging?: object; + /** + * Present if the server supports argument autocompletion suggestions. + */ + completions?: object; + /** + * Present if the server offers any prompt templates. + */ + prompts?: { + /** + * Whether this server supports notifications for changes to the prompt list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any resources to read. + */ + resources?: { + /** + * Whether this server supports subscribing to resource updates. + */ + subscribe?: boolean; + /** + * Whether this server supports notifications for changes to the resource list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any tools to call. + */ + tools?: { + /** + * Whether this server supports notifications for changes to the tool list. + */ + listChanged?: boolean; + }; +} + +/** + * Describes the name and version of an MCP implementation. + */ +export interface Implementation { + name: string; + version: string; +} + +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ +export interface PingRequest extends Request { + method: "ping"; +} + +/* Progress notifications */ +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + */ +export interface ProgressNotification extends Notification { + method: "notifications/progress"; + params: { + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressToken; + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + * + * @TJS-type number + */ + progress: number; + /** + * Total number of items to process (or total progress required), if known. + * + * @TJS-type number + */ + total?: number; + /** + * An optional message describing the current progress. + */ + message?: string; + }; +} + +/* Pagination */ +export interface PaginatedRequest extends Request { + params?: { + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor?: Cursor; + }; +} + +export interface PaginatedResult extends Result { + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor?: Cursor; +} + +/* Resources */ +/** + * Sent from the client to request a list of resources the server has. + */ +export interface ListResourcesRequest extends PaginatedRequest { + method: "resources/list"; +} + +/** + * The server's response to a resources/list request from the client. + */ +export interface ListResourcesResult extends PaginatedResult { + resources: Resource[]; +} + +/** + * Sent from the client to request a list of resource templates the server has. + */ +export interface ListResourceTemplatesRequest extends PaginatedRequest { + method: "resources/templates/list"; +} + +/** + * The server's response to a resources/templates/list request from the client. + */ +export interface ListResourceTemplatesResult extends PaginatedResult { + resourceTemplates: ResourceTemplate[]; +} + +/** + * Sent from the client to the server, to read a specific resource URI. + */ +export interface ReadResourceRequest extends Request { + method: "resources/read"; + params: { + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; + }; +} + +/** + * The server's response to a resources/read request from the client. + */ +export interface ReadResourceResult extends Result { + contents: (TextResourceContents | BlobResourceContents)[]; +} + +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ +export interface ResourceListChangedNotification extends Notification { + method: "notifications/resources/list_changed"; +} + +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + */ +export interface SubscribeRequest extends Request { + method: "resources/subscribe"; + params: { + /** + * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; + }; +} + +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + */ +export interface UnsubscribeRequest extends Request { + method: "resources/unsubscribe"; + params: { + /** + * The URI of the resource to unsubscribe from. + * + * @format uri + */ + uri: string; + }; +} + +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + */ +export interface ResourceUpdatedNotification extends Notification { + method: "notifications/resources/updated"; + params: { + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + * + * @format uri + */ + uri: string; + }; +} + +/** + * A known resource that the server is capable of reading. + */ +export interface Resource { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + + /** + * A human-readable name for this resource. + * + * This can be used by clients to populate UI elements. + */ + name: string; + + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size?: number; +} + +/** + * A template description for resources available on the server. + */ +export interface ResourceTemplate { + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + * + * @format uri-template + */ + uriTemplate: string; + + /** + * A human-readable name for the type of resource this template refers to. + * + * This can be used by clients to populate UI elements. + */ + name: string; + + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; +} + +/** + * The contents of a specific resource or sub-resource. + */ +export interface ResourceContents { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; +} + +export interface TextResourceContents extends ResourceContents { + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string; +} + +export interface BlobResourceContents extends ResourceContents { + /** + * A base64-encoded string representing the binary data of the item. + * + * @format byte + */ + blob: string; +} + +/* Prompts */ +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ +export interface ListPromptsRequest extends PaginatedRequest { + method: "prompts/list"; +} + +/** + * The server's response to a prompts/list request from the client. + */ +export interface ListPromptsResult extends PaginatedResult { + prompts: Prompt[]; +} + +/** + * Used by the client to get a prompt provided by the server. + */ +export interface GetPromptRequest extends Request { + method: "prompts/get"; + params: { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * Arguments to use for templating the prompt. + */ + arguments?: { [key: string]: string }; + }; +} + +/** + * The server's response to a prompts/get request from the client. + */ +export interface GetPromptResult extends Result { + /** + * An optional description for the prompt. + */ + description?: string; + messages: PromptMessage[]; +} + +/** + * A prompt or prompt template that the server offers. + */ +export interface Prompt { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * An optional description of what this prompt provides + */ + description?: string; + /** + * A list of arguments to use for templating the prompt. + */ + arguments?: PromptArgument[]; +} + +/** + * Describes an argument that a prompt can accept. + */ +export interface PromptArgument { + /** + * The name of the argument. + */ + name: string; + /** + * A human-readable description of the argument. + */ + description?: string; + /** + * Whether this argument must be provided. + */ + required?: boolean; +} + +/** + * The sender or recipient of messages and data in a conversation. + */ +export type Role = "user" | "assistant"; + +/** + * Describes a message returned as part of a prompt. + * + * This is similar to `SamplingMessage`, but also supports the embedding of + * resources from the MCP server. + */ +export interface PromptMessage { + role: Role; + content: TextContent | ImageContent | AudioContent | EmbeddedResource; +} + +/** + * The contents of a resource, embedded into a prompt or tool call result. + * + * It is up to the client how best to render embedded resources for the benefit + * of the LLM and/or the user. + */ +export interface EmbeddedResource { + type: "resource"; + resource: TextResourceContents | BlobResourceContents; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; +} + +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export interface PromptListChangedNotification extends Notification { + method: "notifications/prompts/list_changed"; +} + +/* Tools */ +/** + * Sent from the client to request a list of tools the server has. + */ +export interface ListToolsRequest extends PaginatedRequest { + method: "tools/list"; +} + +/** + * The server's response to a tools/list request from the client. + */ +export interface ListToolsResult extends PaginatedResult { + tools: Tool[]; +} + +/** + * The server's response to a tool call. + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ +export interface CallToolResult extends Result { + content: (TextContent | ImageContent | AudioContent | EmbeddedResource)[]; + + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + */ + isError?: boolean; +} + +/** + * Used by the client to invoke a tool provided by the server. + */ +export interface CallToolRequest extends Request { + method: "tools/call"; + params: { + name: string; + arguments?: { [key: string]: unknown }; + }; +} + +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export interface ToolListChangedNotification extends Notification { + method: "notifications/tools/list_changed"; +} + +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + */ +export interface ToolAnnotations { + /** + * A human-readable title for the tool. + */ + title?: string; + + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint?: boolean; + + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint?: boolean; + + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint?: boolean; + + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint?: boolean; +} + +/** + * Definition for a tool the client can call. + */ +export interface Tool { + /** + * The name of the tool. + */ + name: string; + + /** + * A human-readable description of the tool. + * + * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * A JSON Schema object defining the expected parameters for the tool. + */ + inputSchema: { + type: "object"; + properties?: { [key: string]: object }; + required?: string[]; + }; + + /** + * Optional additional tool information. + */ + annotations?: ToolAnnotations; +} + +/* Logging */ +/** + * A request from the client to the server, to enable or adjust logging. + */ +export interface SetLevelRequest extends Request { + method: "logging/setLevel"; + params: { + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/message. + */ + level: LoggingLevel; + }; +} + +/** + * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + */ +export interface LoggingMessageNotification extends Notification { + method: "notifications/message"; + params: { + /** + * The severity of this log message. + */ + level: LoggingLevel; + /** + * An optional name of the logger issuing this message. + */ + logger?: string; + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown; + }; +} + +/** + * The severity of a log message. + * + * These map to syslog message severities, as specified in RFC-5424: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + */ +export type LoggingLevel = + | "debug" + | "info" + | "notice" + | "warning" + | "error" + | "critical" + | "alert" + | "emergency"; + +/* Sampling */ +/** + * 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. + */ +export interface CreateMessageRequest extends Request { + method: "sampling/createMessage"; + params: { + messages: SamplingMessage[]; + /** + * The server's preferences for which model to select. The client MAY ignore these preferences. + */ + modelPreferences?: ModelPreferences; + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt?: string; + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request. + */ + includeContext?: "none" | "thisServer" | "allServers"; + /** + * @TJS-type number + */ + temperature?: number; + /** + * The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested. + */ + maxTokens: number; + stopSequences?: string[]; + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata?: object; + }; +} + +/** + * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. + */ +export interface CreateMessageResult extends Result, SamplingMessage { + /** + * The name of the model that generated the message. + */ + model: string; + /** + * The reason why sampling stopped, if known. + */ + stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string; +} + +/** + * Describes a message issued to or received from an LLM API. + */ +export interface SamplingMessage { + role: Role; + content: TextContent | ImageContent | AudioContent; +} + +/** + * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed + */ +export interface Annotations { + /** + * Describes who the intended customer of this object or data is. + * + * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). + */ + audience?: Role[]; + + /** + * Describes how important this data is for operating the server. + * + * A value of 1 means "most important," and indicates that the data is + * effectively required, while 0 means "least important," and indicates that + * the data is entirely optional. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + priority?: number; +} + +/** + * Text provided to or from an LLM. + */ +export interface TextContent { + type: "text"; + + /** + * The text content of the message. + */ + text: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; +} + +/** + * An image provided to or from an LLM. + */ +export interface ImageContent { + type: "image"; + + /** + * The base64-encoded image data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; +} + +/** + * Audio provided to or from an LLM. + */ +export interface AudioContent { + type: "audio"; + + /** + * The base64-encoded audio data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; +} + +/** + * The server's preferences for model selection, requested of the client during sampling. + * + * Because LLMs can vary along multiple dimensions, choosing the "best" model is + * rarely straightforward. Different models excel in different areas—some are + * faster but less capable, others are more capable but more expensive, and so + * on. This interface allows servers to express their priorities across multiple + * dimensions to help clients make an appropriate selection for their use case. + * + * These preferences are always advisory. The client MAY ignore them. It is also + * up to the client to decide how to interpret these preferences and how to + * balance them against other considerations. + */ +export interface ModelPreferences { + /** + * Optional hints to use for model selection. + * + * If multiple hints are specified, the client MUST evaluate them in order + * (such that the first match is taken). + * + * The client SHOULD prioritize these hints over the numeric priorities, but + * MAY still use the priorities to select from ambiguous matches. + */ + hints?: ModelHint[]; + + /** + * How much to prioritize cost when selecting a model. A value of 0 means cost + * is not important, while a value of 1 means cost is the most important + * factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + costPriority?: number; + + /** + * How much to prioritize sampling speed (latency) when selecting a model. A + * value of 0 means speed is not important, while a value of 1 means speed is + * the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + speedPriority?: number; + + /** + * How much to prioritize intelligence and capabilities when selecting a + * model. A value of 0 means intelligence is not important, while a value of 1 + * means intelligence is the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + intelligencePriority?: number; +} + +/** + * Hints to use for model selection. + * + * Keys not declared here are currently left unspecified by the spec and are up + * to the client to interpret. + */ +export interface ModelHint { + /** + * A hint for a model name. + * + * The client SHOULD treat this as a substring of a model name; for example: + * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` + * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. + * - `claude` should match any Claude model + * + * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: + * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` + */ + name?: string; +} + +/* Autocomplete */ +/** + * A request from the client to the server, to ask for completion options. + */ +export interface CompleteRequest extends Request { + method: "completion/complete"; + params: { + ref: PromptReference | ResourceReference; + /** + * The argument's information + */ + argument: { + /** + * The name of the argument + */ + name: string; + /** + * The value of the argument to use for completion matching. + */ + value: string; + }; + }; +} + +/** + * The server's response to a completion/complete request + */ +export interface CompleteResult extends Result { + completion: { + /** + * An array of completion values. Must not exceed 100 items. + */ + values: string[]; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total?: number; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore?: boolean; + }; +} + +/** + * A reference to a resource or resource template definition. + */ +export interface ResourceReference { + type: "ref/resource"; + /** + * The URI or URI template of the resource. + * + * @format uri-template + */ + uri: string; +} + +/** + * Identifies a prompt. + */ +export interface PromptReference { + type: "ref/prompt"; + /** + * The name of the prompt or prompt template + */ + name: string; +} + +/* Roots */ +/** + * Sent from the server to request a list of root URIs from the client. Roots allow + * servers to ask for specific directories or files to operate on. A common example + * for roots is providing a set of repositories or directories a server should operate + * on. + * + * This request is typically used when the server needs to understand the file system + * structure or access specific locations that the client has permission to read from. + */ +export interface ListRootsRequest extends Request { + method: "roots/list"; +} + +/** + * The client's response to a roots/list request from the server. + * This result contains an array of Root objects, each representing a root directory + * or file that the server can operate on. + */ +export interface ListRootsResult extends Result { + roots: Root[]; +} + +/** + * Represents a root directory or file that the server can operate on. + */ +export interface Root { + /** + * The URI identifying the root. This *must* start with file:// for now. + * This restriction may be relaxed in future versions of the protocol to allow + * other URI schemes. + * + * @format uri + */ + uri: string; + /** + * An optional name for the root. This can be used to provide a human-readable + * identifier for the root, which may be useful for display purposes or for + * referencing the root in other parts of the application. + */ + name?: string; +} + +/** + * A notification from the client to the server, informing it that the list of roots has changed. + * This notification should be sent whenever the client adds, removes, or modifies any root. + * The server should then request an updated list of roots using the ListRootsRequest. + */ +export interface RootsListChangedNotification extends Notification { + method: "notifications/roots/list_changed"; +} + +/* Client messages */ +export type ClientRequest = + | PingRequest + | InitializeRequest + | CompleteRequest + | SetLevelRequest + | GetPromptRequest + | ListPromptsRequest + | ListResourcesRequest + | ListResourceTemplatesRequest + | ReadResourceRequest + | SubscribeRequest + | UnsubscribeRequest + | CallToolRequest + | ListToolsRequest; + +export type ClientNotification = + | CancelledNotification + | ProgressNotification + | InitializedNotification + | RootsListChangedNotification; + +export type ClientResult = EmptyResult | CreateMessageResult | ListRootsResult; + +/* Server messages */ +export type ServerRequest = + | PingRequest + | CreateMessageRequest + | ListRootsRequest; + +export type ServerNotification = + | CancelledNotification + | ProgressNotification + | LoggingMessageNotification + | ResourceUpdatedNotification + | ResourceListChangedNotification + | ToolListChangedNotification + | PromptListChangedNotification; + +export type ServerResult = + | EmptyResult + | InitializeResult + | CompleteResult + | GetPromptResult + | ListPromptsResult + | ListResourceTemplatesResult + | ListResourcesResult + | ReadResourceResult + | CallToolResult + | ListToolsResult; diff --git a/src/spec-types/2025-06-18.ts b/src/spec-types/2025-06-18.ts new file mode 100644 index 00000000..8778ec07 --- /dev/null +++ b/src/spec-types/2025-06-18.ts @@ -0,0 +1,1623 @@ +/* JSON-RPC types */ + +/** + * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. + * + * @category JSON-RPC + */ +export type JSONRPCMessage = + | JSONRPCRequest + | JSONRPCNotification + | JSONRPCResponse + | JSONRPCError; + +/** @internal */ +export const LATEST_PROTOCOL_VERSION = "2025-06-18"; +/** @internal */ +export const JSONRPC_VERSION = "2.0"; + +/** + * A progress token, used to associate progress notifications with the original request. + * + * @category Common Types + */ +export type ProgressToken = string | number; + +/** + * An opaque token used to represent a cursor for pagination. + * + * @category Common Types + */ +export type Cursor = string; + +/** @internal */ +export interface Request { + method: string; + params?: { + /** + * See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken?: ProgressToken; + [key: string]: unknown; + }; + [key: string]: unknown; + }; +} + +/** @internal */ +export interface Notification { + method: string; + params?: { + /** + * See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; + [key: string]: unknown; + }; +} + +/** + * @category Common Types + */ +export interface Result { + /** + * See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; + [key: string]: unknown; +} + +/** + * A uniquely identifying ID for a request in JSON-RPC. + * + * @category Common Types + */ +export type RequestId = string | number; + +/** + * A request that expects a response. + * + * @category JSON-RPC + */ +export interface JSONRPCRequest extends Request { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; +} + +/** + * A notification which does not expect a response. + * + * @category JSON-RPC + */ +export interface JSONRPCNotification extends Notification { + jsonrpc: typeof JSONRPC_VERSION; +} + +/** + * A successful (non-error) response to a request. + * + * @category JSON-RPC + */ +export interface JSONRPCResponse { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + result: Result; +} + +// Standard JSON-RPC error codes +export const PARSE_ERROR = -32700; +export const INVALID_REQUEST = -32600; +export const METHOD_NOT_FOUND = -32601; +export const INVALID_PARAMS = -32602; +export const INTERNAL_ERROR = -32603; + +/** + * A response to a request that indicates an error occurred. + * + * @category JSON-RPC + */ +export interface JSONRPCError { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + error: { + /** + * The error type that occurred. + */ + code: number; + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string; + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data?: unknown; + }; +} + +/* Empty result */ +/** + * A response that indicates success but carries no data. + * + * @category Common Types + */ +export type EmptyResult = Result; + +/* Cancellation */ +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotification extends Notification { + method: "notifications/cancelled"; + params: { + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestId; + + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason?: string; + }; +} + +/* Initialization */ +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + * + * @category `initialize` + */ +export interface InitializeRequest extends Request { + method: "initialize"; + params: { + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string; + capabilities: ClientCapabilities; + clientInfo: Implementation; + }; +} + +/** + * After receiving an initialize request from the client, the server sends this response. + * + * @category `initialize` + */ +export interface InitializeResult extends Result { + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string; + capabilities: ServerCapabilities; + serverInfo: Implementation; + + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions?: string; +} + +/** + * This notification is sent from the client to the server after initialization has finished. + * + * @category `notifications/initialized` + */ +export interface InitializedNotification extends Notification { + method: "notifications/initialized"; +} + +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + * + * @category `initialize` + */ +export interface ClientCapabilities { + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental?: { [key: string]: object }; + /** + * Present if the client supports listing roots. + */ + roots?: { + /** + * Whether the client supports notifications for changes to the roots list. + */ + listChanged?: boolean; + }; + /** + * Present if the client supports sampling from an LLM. + */ + sampling?: object; + /** + * Present if the client supports elicitation from the server. + */ + elicitation?: object; +} + +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + * + * @category `initialize` + */ +export interface ServerCapabilities { + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental?: { [key: string]: object }; + /** + * Present if the server supports sending log messages to the client. + */ + logging?: object; + /** + * Present if the server supports argument autocompletion suggestions. + */ + completions?: object; + /** + * Present if the server offers any prompt templates. + */ + prompts?: { + /** + * Whether this server supports notifications for changes to the prompt list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any resources to read. + */ + resources?: { + /** + * Whether this server supports subscribing to resource updates. + */ + subscribe?: boolean; + /** + * Whether this server supports notifications for changes to the resource list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any tools to call. + */ + tools?: { + /** + * Whether this server supports notifications for changes to the tool list. + */ + listChanged?: boolean; + }; +} + +/** + * Base interface for metadata with name (identifier) and title (display name) properties. + * + * @internal + */ +export interface BaseMetadata { + /** + * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). + */ + name: string; + + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title?: string; +} + +/** + * Describes the name and version of an MCP implementation, with an optional title for UI representation. + * + * @category `initialize` + */ +export interface Implementation extends BaseMetadata { + version: string; +} + +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + * + * @category `ping` + */ +export interface PingRequest extends Request { + method: "ping"; +} + +/* Progress notifications */ +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category `notifications/progress` + */ +export interface ProgressNotification extends Notification { + method: "notifications/progress"; + params: { + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressToken; + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + * + * @TJS-type number + */ + progress: number; + /** + * Total number of items to process (or total progress required), if known. + * + * @TJS-type number + */ + total?: number; + /** + * An optional message describing the current progress. + */ + message?: string; + }; +} + +/* Pagination */ +/** @internal */ +export interface PaginatedRequest extends Request { + params?: { + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor?: Cursor; + }; +} + +/** @internal */ +export interface PaginatedResult extends Result { + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor?: Cursor; +} + +/* Resources */ +/** + * Sent from the client to request a list of resources the server has. + * + * @category `resources/list` + */ +export interface ListResourcesRequest extends PaginatedRequest { + method: "resources/list"; +} + +/** + * The server's response to a resources/list request from the client. + * + * @category `resources/list` + */ +export interface ListResourcesResult extends PaginatedResult { + resources: Resource[]; +} + +/** + * Sent from the client to request a list of resource templates the server has. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesRequest extends PaginatedRequest { + method: "resources/templates/list"; +} + +/** + * The server's response to a resources/templates/list request from the client. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesResult extends PaginatedResult { + resourceTemplates: ResourceTemplate[]; +} + +/** + * Sent from the client to the server, to read a specific resource URI. + * + * @category `resources/read` + */ +export interface ReadResourceRequest extends Request { + method: "resources/read"; + params: { + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; + }; +} + +/** + * The server's response to a resources/read request from the client. + * + * @category `resources/read` + */ +export interface ReadResourceResult extends Result { + contents: (TextResourceContents | BlobResourceContents)[]; +} + +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/resources/list_changed` + */ +export interface ResourceListChangedNotification extends Notification { + method: "notifications/resources/list_changed"; +} + +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + * + * @category `resources/subscribe` + */ +export interface SubscribeRequest extends Request { + method: "resources/subscribe"; + params: { + /** + * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; + }; +} + +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + * + * @category `resources/unsubscribe` + */ +export interface UnsubscribeRequest extends Request { + method: "resources/unsubscribe"; + params: { + /** + * The URI of the resource to unsubscribe from. + * + * @format uri + */ + uri: string; + }; +} + +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotification extends Notification { + method: "notifications/resources/updated"; + params: { + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + * + * @format uri + */ + uri: string; + }; +} + +/** + * A known resource that the server is capable of reading. + * + * @category `resources/list` + */ +export interface Resource extends BaseMetadata { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size?: number; + + /** + * See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * A template description for resources available on the server. + * + * @category `resources/templates/list` + */ +export interface ResourceTemplate extends BaseMetadata { + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + * + * @format uri-template + */ + uriTemplate: string; + + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * The contents of a specific resource or sub-resource. + * + * @internal + */ +export interface ResourceContents { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + /** + * See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * @category Content + */ +export interface TextResourceContents extends ResourceContents { + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string; +} + +/** + * @category Content + */ +export interface BlobResourceContents extends ResourceContents { + /** + * A base64-encoded string representing the binary data of the item. + * + * @format byte + */ + blob: string; +} + +/* Prompts */ +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + * + * @category `prompts/list` + */ +export interface ListPromptsRequest extends PaginatedRequest { + method: "prompts/list"; +} + +/** + * The server's response to a prompts/list request from the client. + * + * @category `prompts/list` + */ +export interface ListPromptsResult extends PaginatedResult { + prompts: Prompt[]; +} + +/** + * Used by the client to get a prompt provided by the server. + * + * @category `prompts/get` + */ +export interface GetPromptRequest extends Request { + method: "prompts/get"; + params: { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * Arguments to use for templating the prompt. + */ + arguments?: { [key: string]: string }; + }; +} + +/** + * The server's response to a prompts/get request from the client. + * + * @category `prompts/get` + */ +export interface GetPromptResult extends Result { + /** + * An optional description for the prompt. + */ + description?: string; + messages: PromptMessage[]; +} + +/** + * A prompt or prompt template that the server offers. + * + * @category `prompts/list` + */ +export interface Prompt extends BaseMetadata { + /** + * An optional description of what this prompt provides + */ + description?: string; + /** + * A list of arguments to use for templating the prompt. + */ + arguments?: PromptArgument[]; + + /** + * See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * Describes an argument that a prompt can accept. + * + * @category `prompts/list` + */ +export interface PromptArgument extends BaseMetadata { + /** + * A human-readable description of the argument. + */ + description?: string; + /** + * Whether this argument must be provided. + */ + required?: boolean; +} + +/** + * The sender or recipient of messages and data in a conversation. + * + * @category Common Types + */ +export type Role = "user" | "assistant"; + +/** + * Describes a message returned as part of a prompt. + * + * This is similar to `SamplingMessage`, but also supports the embedding of + * resources from the MCP server. + * + * @category `prompts/get` + */ +export interface PromptMessage { + role: Role; + content: ContentBlock; +} + +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + * + * @category Content + */ +export interface ResourceLink extends Resource { + type: "resource_link"; +} + +/** + * The contents of a resource, embedded into a prompt or tool call result. + * + * It is up to the client how best to render embedded resources for the benefit + * of the LLM and/or the user. + * + * @category Content + */ +export interface EmbeddedResource { + type: "resource"; + resource: TextResourceContents | BlobResourceContents; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/prompts/list_changed` + */ +export interface PromptListChangedNotification extends Notification { + method: "notifications/prompts/list_changed"; +} + +/* Tools */ +/** + * Sent from the client to request a list of tools the server has. + * + * @category `tools/list` + */ +export interface ListToolsRequest extends PaginatedRequest { + method: "tools/list"; +} + +/** + * The server's response to a tools/list request from the client. + * + * @category `tools/list` + */ +export interface ListToolsResult extends PaginatedResult { + tools: Tool[]; +} + +/** + * The server's response to a tool call. + * + * @category `tools/call` + */ +export interface CallToolResult extends Result { + /** + * A list of content objects that represent the unstructured result of the tool call. + */ + content: ContentBlock[]; + + /** + * An optional JSON object that represents the structured result of the tool call. + */ + structuredContent?: { [key: string]: unknown }; + + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError?: boolean; +} + +/** + * Used by the client to invoke a tool provided by the server. + * + * @category `tools/call` + */ +export interface CallToolRequest extends Request { + method: "tools/call"; + params: { + name: string; + arguments?: { [key: string]: unknown }; + }; +} + +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/tools/list_changed` + */ +export interface ToolListChangedNotification extends Notification { + method: "notifications/tools/list_changed"; +} + +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + * + * @category `tools/list` + */ +export interface ToolAnnotations { + /** + * A human-readable title for the tool. + */ + title?: string; + + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint?: boolean; + + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint?: boolean; + + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint?: boolean; + + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint?: boolean; +} + +/** + * Definition for a tool the client can call. + * + * @category `tools/list` + */ +export interface Tool extends BaseMetadata { + /** + * A human-readable description of the tool. + * + * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * A JSON Schema object defining the expected parameters for the tool. + */ + inputSchema: { + type: "object"; + properties?: { [key: string]: object }; + required?: string[]; + }; + + /** + * An optional JSON Schema object defining the structure of the tool's output returned in + * the structuredContent field of a CallToolResult. + */ + outputSchema?: { + type: "object"; + properties?: { [key: string]: object }; + required?: string[]; + }; + + /** + * Optional additional tool information. + * + * Display name precedence order is: title, annotations.title, then name. + */ + annotations?: ToolAnnotations; + + /** + * See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/* Logging */ +/** + * A request from the client to the server, to enable or adjust logging. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequest extends Request { + method: "logging/setLevel"; + params: { + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/message. + */ + level: LoggingLevel; + }; +} + +/** + * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotification extends Notification { + method: "notifications/message"; + params: { + /** + * The severity of this log message. + */ + level: LoggingLevel; + /** + * An optional name of the logger issuing this message. + */ + logger?: string; + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown; + }; +} + +/** + * The severity of a log message. + * + * These map to syslog message severities, as specified in RFC-5424: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + * + * @category Common Types + */ +export type LoggingLevel = + | "debug" + | "info" + | "notice" + | "warning" + | "error" + | "critical" + | "alert" + | "emergency"; + +/* Sampling */ +/** + * 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. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequest extends Request { + method: "sampling/createMessage"; + params: { + messages: SamplingMessage[]; + /** + * The server's preferences for which model to select. The client MAY ignore these preferences. + */ + modelPreferences?: ModelPreferences; + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt?: string; + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request. + */ + includeContext?: "none" | "thisServer" | "allServers"; + /** + * @TJS-type number + */ + temperature?: number; + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number; + stopSequences?: string[]; + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata?: object; + }; +} + +/** + * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageResult extends Result, SamplingMessage { + /** + * The name of the model that generated the message. + */ + model: string; + /** + * The reason why sampling stopped, if known. + */ + stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string; +} + +/** + * Describes a message issued to or received from an LLM API. + * + * @category `sampling/createMessage` + */ +export interface SamplingMessage { + role: Role; + content: TextContent | ImageContent | AudioContent; +} + +/** + * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed + * + * @category Common Types + */ +export interface Annotations { + /** + * Describes who the intended customer of this object or data is. + * + * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). + */ + audience?: Role[]; + + /** + * Describes how important this data is for operating the server. + * + * A value of 1 means "most important," and indicates that the data is + * effectively required, while 0 means "least important," and indicates that + * the data is entirely optional. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + priority?: number; + + /** + * The moment the resource was last modified, as an ISO 8601 formatted string. + * + * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). + * + * Examples: last activity timestamp in an open file, timestamp when the resource + * was attached, etc. + */ + lastModified?: string; +} + +/** + * @category Content + */ +export type ContentBlock = + | TextContent + | ImageContent + | AudioContent + | ResourceLink + | EmbeddedResource; + +/** + * Text provided to or from an LLM. + * + * @category Content + */ +export interface TextContent { + type: "text"; + + /** + * The text content of the message. + */ + text: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * An image provided to or from an LLM. + * + * @category Content + */ +export interface ImageContent { + type: "image"; + + /** + * The base64-encoded image data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * Audio provided to or from an LLM. + * + * @category Content + */ +export interface AudioContent { + type: "audio"; + + /** + * The base64-encoded audio data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * The server's preferences for model selection, requested of the client during sampling. + * + * Because LLMs can vary along multiple dimensions, choosing the "best" model is + * rarely straightforward. Different models excel in different areas—some are + * faster but less capable, others are more capable but more expensive, and so + * on. This interface allows servers to express their priorities across multiple + * dimensions to help clients make an appropriate selection for their use case. + * + * These preferences are always advisory. The client MAY ignore them. It is also + * up to the client to decide how to interpret these preferences and how to + * balance them against other considerations. + * + * @category `sampling/createMessage` + */ +export interface ModelPreferences { + /** + * Optional hints to use for model selection. + * + * If multiple hints are specified, the client MUST evaluate them in order + * (such that the first match is taken). + * + * The client SHOULD prioritize these hints over the numeric priorities, but + * MAY still use the priorities to select from ambiguous matches. + */ + hints?: ModelHint[]; + + /** + * How much to prioritize cost when selecting a model. A value of 0 means cost + * is not important, while a value of 1 means cost is the most important + * factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + costPriority?: number; + + /** + * How much to prioritize sampling speed (latency) when selecting a model. A + * value of 0 means speed is not important, while a value of 1 means speed is + * the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + speedPriority?: number; + + /** + * How much to prioritize intelligence and capabilities when selecting a + * model. A value of 0 means intelligence is not important, while a value of 1 + * means intelligence is the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + intelligencePriority?: number; +} + +/** + * Hints to use for model selection. + * + * Keys not declared here are currently left unspecified by the spec and are up + * to the client to interpret. + * + * @category `sampling/createMessage` + */ +export interface ModelHint { + /** + * A hint for a model name. + * + * The client SHOULD treat this as a substring of a model name; for example: + * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` + * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. + * - `claude` should match any Claude model + * + * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: + * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` + */ + name?: string; +} + +/* Autocomplete */ +/** + * A request from the client to the server, to ask for completion options. + * + * @category `completion/complete` + */ +export interface CompleteRequest extends Request { + method: "completion/complete"; + params: { + ref: PromptReference | ResourceTemplateReference; + /** + * The argument's information + */ + argument: { + /** + * The name of the argument + */ + name: string; + /** + * The value of the argument to use for completion matching. + */ + value: string; + }; + + /** + * Additional, optional context for completions + */ + context?: { + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments?: { [key: string]: string }; + }; + }; +} + +/** + * The server's response to a completion/complete request + * + * @category `completion/complete` + */ +export interface CompleteResult extends Result { + completion: { + /** + * An array of completion values. Must not exceed 100 items. + */ + values: string[]; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total?: number; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore?: boolean; + }; +} + +/** + * A reference to a resource or resource template definition. + * + * @category `completion/complete` + */ +export interface ResourceTemplateReference { + type: "ref/resource"; + /** + * The URI or URI template of the resource. + * + * @format uri-template + */ + uri: string; +} + +/** + * Identifies a prompt. + * + * @category `completion/complete` + */ +export interface PromptReference extends BaseMetadata { + type: "ref/prompt"; +} + +/* Roots */ +/** + * Sent from the server to request a list of root URIs from the client. Roots allow + * servers to ask for specific directories or files to operate on. A common example + * for roots is providing a set of repositories or directories a server should operate + * on. + * + * This request is typically used when the server needs to understand the file system + * structure or access specific locations that the client has permission to read from. + * + * @category `roots/list` + */ +export interface ListRootsRequest extends Request { + method: "roots/list"; +} + +/** + * The client's response to a roots/list request from the server. + * This result contains an array of Root objects, each representing a root directory + * or file that the server can operate on. + * + * @category `roots/list` + */ +export interface ListRootsResult extends Result { + roots: Root[]; +} + +/** + * Represents a root directory or file that the server can operate on. + * + * @category `roots/list` + */ +export interface Root { + /** + * The URI identifying the root. This *must* start with file:// for now. + * This restriction may be relaxed in future versions of the protocol to allow + * other URI schemes. + * + * @format uri + */ + uri: string; + /** + * An optional name for the root. This can be used to provide a human-readable + * identifier for the root, which may be useful for display purposes or for + * referencing the root in other parts of the application. + */ + name?: string; + + /** + * See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * A notification from the client to the server, informing it that the list of roots has changed. + * This notification should be sent whenever the client adds, removes, or modifies any root. + * The server should then request an updated list of roots using the ListRootsRequest. + * + * @category `notifications/roots/list_changed` + */ +export interface RootsListChangedNotification extends Notification { + method: "notifications/roots/list_changed"; +} + +/** + * A request from the server to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequest extends Request { + method: "elicitation/create"; + params: { + /** + * The message to present to the user. + */ + message: string; + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: { + type: "object"; + properties: { + [key: string]: PrimitiveSchemaDefinition; + }; + required?: string[]; + }; + }; +} + +/** + * Restricted schema definitions that only allow primitive types + * without nested objects or arrays. + * + * @category `elicitation/create` + */ +export type PrimitiveSchemaDefinition = + | StringSchema + | NumberSchema + | BooleanSchema + | EnumSchema; + +/** + * @category `elicitation/create` + */ +export interface StringSchema { + type: "string"; + title?: string; + description?: string; + minLength?: number; + maxLength?: number; + format?: "email" | "uri" | "date" | "date-time"; +} + +/** + * @category `elicitation/create` + */ +export interface NumberSchema { + type: "number" | "integer"; + title?: string; + description?: string; + minimum?: number; + maximum?: number; +} + +/** + * @category `elicitation/create` + */ +export interface BooleanSchema { + type: "boolean"; + title?: string; + description?: string; + default?: boolean; +} + +/** + * @category `elicitation/create` + */ +export interface EnumSchema { + type: "string"; + title?: string; + description?: string; + enum: string[]; + enumNames?: string[]; // Display names for enum values +} + +/** + * The client's response to an elicitation request. + * + * @category `elicitation/create` + */ +export interface ElicitResult extends Result { + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly declined the action + * - "cancel": User dismissed without making an explicit choice + */ + action: "accept" | "decline" | "cancel"; + + /** + * The submitted form data, only present when action is "accept". + * Contains values matching the requested schema. + */ + content?: { [key: string]: string | number | boolean }; +} + +/* Client messages */ +/** @internal */ +export type ClientRequest = + | PingRequest + | InitializeRequest + | CompleteRequest + | SetLevelRequest + | GetPromptRequest + | ListPromptsRequest + | ListResourcesRequest + | ListResourceTemplatesRequest + | ReadResourceRequest + | SubscribeRequest + | UnsubscribeRequest + | CallToolRequest + | ListToolsRequest; + +/** @internal */ +export type ClientNotification = + | CancelledNotification + | ProgressNotification + | InitializedNotification + | RootsListChangedNotification; + +/** @internal */ +export type ClientResult = + | EmptyResult + | CreateMessageResult + | ListRootsResult + | ElicitResult; + +/* Server messages */ +/** @internal */ +export type ServerRequest = + | PingRequest + | CreateMessageRequest + | ListRootsRequest + | ElicitRequest; + +/** @internal */ +export type ServerNotification = + | CancelledNotification + | ProgressNotification + | LoggingMessageNotification + | ResourceUpdatedNotification + | ResourceListChangedNotification + | ToolListChangedNotification + | PromptListChangedNotification; + +/** @internal */ +export type ServerResult = + | EmptyResult + | InitializeResult + | CompleteResult + | GetPromptResult + | ListPromptsResult + | ListResourceTemplatesResult + | ListResourcesResult + | ReadResourceResult + | CallToolResult + | ListToolsResult; diff --git a/src/spec-types/2025-11-25.ts b/src/spec-types/2025-11-25.ts new file mode 100644 index 00000000..332c3f0e --- /dev/null +++ b/src/spec-types/2025-11-25.ts @@ -0,0 +1,2587 @@ +/* JSON-RPC types */ + +/** + * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. + * + * @category JSON-RPC + */ +export type JSONRPCMessage = + | JSONRPCRequest + | JSONRPCNotification + | JSONRPCResponse; + +/** @internal */ +export const LATEST_PROTOCOL_VERSION = "2025-11-25"; +/** @internal */ +export const JSONRPC_VERSION = "2.0"; + +/** + * A progress token, used to associate progress notifications with the original request. + * + * @category Common Types + */ +export type ProgressToken = string | number; + +/** + * An opaque token used to represent a cursor for pagination. + * + * @category Common Types + */ +export type Cursor = string; + +/** + * Common params for any task-augmented request. + * + * @internal + */ +export interface TaskAugmentedRequestParams extends RequestParams { + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a CreateTaskResult immediately, and the actual result can be + * retrieved later via tasks/result. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task?: TaskMetadata; +} +/** + * Common params for any request. + * + * @internal + */ +export interface RequestParams { + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken?: ProgressToken; + [key: string]: unknown; + }; +} + +/** @internal */ +export interface Request { + method: string; + // Allow unofficial extensions of `Request.params` without impacting `RequestParams`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + params?: { [key: string]: any }; +} + +/** @internal */ +export interface NotificationParams { + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** @internal */ +export interface Notification { + method: string; + // Allow unofficial extensions of `Notification.params` without impacting `NotificationParams`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + params?: { [key: string]: any }; +} + +/** + * @category Common Types + */ +export interface Result { + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; + [key: string]: unknown; +} + +/** + * @category Common Types + */ +export interface Error { + /** + * The error type that occurred. + */ + code: number; + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string; + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data?: unknown; +} + +/** + * A uniquely identifying ID for a request in JSON-RPC. + * + * @category Common Types + */ +export type RequestId = string | number; + +/** + * A request that expects a response. + * + * @category JSON-RPC + */ +export interface JSONRPCRequest extends Request { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; +} + +/** + * A notification which does not expect a response. + * + * @category JSON-RPC + */ +export interface JSONRPCNotification extends Notification { + jsonrpc: typeof JSONRPC_VERSION; +} + +/** + * A successful (non-error) response to a request. + * + * @category JSON-RPC + */ +export interface JSONRPCResultResponse { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + result: Result; +} + +/** + * A response to a request that indicates an error occurred. + * + * @category JSON-RPC + */ +export interface JSONRPCErrorResponse { + jsonrpc: typeof JSONRPC_VERSION; + id?: RequestId; + error: Error; +} + +/** + * A response to a request, containing either the result or error. + * + * @category JSON-RPC + */ +export type JSONRPCResponse = JSONRPCResultResponse | JSONRPCErrorResponse; + +// Standard JSON-RPC error codes +export const PARSE_ERROR = -32700; +export const INVALID_REQUEST = -32600; +export const METHOD_NOT_FOUND = -32601; +export const INVALID_PARAMS = -32602; +export const INTERNAL_ERROR = -32603; + +// Implementation-specific JSON-RPC error codes [-32000, -32099] +/** @internal */ +export const URL_ELICITATION_REQUIRED = -32042; + +/** + * An error response that indicates that the server requires the client to provide additional information via an elicitation request. + * + * @internal + */ +export interface URLElicitationRequiredError extends Omit< + JSONRPCErrorResponse, + "error" +> { + error: Error & { + code: typeof URL_ELICITATION_REQUIRED; + data: { + elicitations: ElicitRequestURLParams[]; + [key: string]: unknown; + }; + }; +} + +/* Empty result */ +/** + * A response that indicates success but carries no data. + * + * @category Common Types + */ +export type EmptyResult = Result; + +/* Cancellation */ +/** + * Parameters for a `notifications/cancelled` notification. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotificationParams extends NotificationParams { + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + * This MUST be provided for cancelling non-task requests. + * This MUST NOT be used for cancelling tasks (use the `tasks/cancel` request instead). + */ + requestId?: RequestId; + + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason?: string; +} + +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + * + * For task cancellation, use the `tasks/cancel` request instead of this notification. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotification extends JSONRPCNotification { + method: "notifications/cancelled"; + params: CancelledNotificationParams; +} + +/* Initialization */ +/** + * Parameters for an `initialize` request. + * + * @category `initialize` + */ +export interface InitializeRequestParams extends RequestParams { + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string; + capabilities: ClientCapabilities; + clientInfo: Implementation; +} + +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + * + * @category `initialize` + */ +export interface InitializeRequest extends JSONRPCRequest { + method: "initialize"; + params: InitializeRequestParams; +} + +/** + * After receiving an initialize request from the client, the server sends this response. + * + * @category `initialize` + */ +export interface InitializeResult extends Result { + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string; + capabilities: ServerCapabilities; + serverInfo: Implementation; + + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions?: string; +} + +/** + * This notification is sent from the client to the server after initialization has finished. + * + * @category `notifications/initialized` + */ +export interface InitializedNotification extends JSONRPCNotification { + method: "notifications/initialized"; + params?: NotificationParams; +} + +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + * + * @category `initialize` + */ +export interface ClientCapabilities { + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental?: { [key: string]: object }; + /** + * Present if the client supports listing roots. + */ + roots?: { + /** + * Whether the client supports notifications for changes to the roots list. + */ + listChanged?: boolean; + }; + /** + * Present if the client supports sampling from an LLM. + */ + sampling?: { + /** + * Whether the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context?: object; + /** + * Whether the client supports tool use via tools and toolChoice parameters. + */ + tools?: object; + }; + /** + * Present if the client supports elicitation from the server. + */ + elicitation?: { form?: object; url?: object }; + + /** + * Present if the client supports task-augmented requests. + */ + tasks?: { + /** + * Whether this client supports tasks/list. + */ + list?: object; + /** + * Whether this client supports tasks/cancel. + */ + cancel?: object; + /** + * Specifies which request types can be augmented with tasks. + */ + requests?: { + /** + * Task support for sampling-related requests. + */ + sampling?: { + /** + * Whether the client supports task-augmented sampling/createMessage requests. + */ + createMessage?: object; + }; + /** + * Task support for elicitation-related requests. + */ + elicitation?: { + /** + * Whether the client supports task-augmented elicitation/create requests. + */ + create?: object; + }; + }; + }; +} + +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + * + * @category `initialize` + */ +export interface ServerCapabilities { + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental?: { [key: string]: object }; + /** + * Present if the server supports sending log messages to the client. + */ + logging?: object; + /** + * Present if the server supports argument autocompletion suggestions. + */ + completions?: object; + /** + * Present if the server offers any prompt templates. + */ + prompts?: { + /** + * Whether this server supports notifications for changes to the prompt list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any resources to read. + */ + resources?: { + /** + * Whether this server supports subscribing to resource updates. + */ + subscribe?: boolean; + /** + * Whether this server supports notifications for changes to the resource list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any tools to call. + */ + tools?: { + /** + * Whether this server supports notifications for changes to the tool list. + */ + listChanged?: boolean; + }; + /** + * Present if the server supports task-augmented requests. + */ + tasks?: { + /** + * Whether this server supports tasks/list. + */ + list?: object; + /** + * Whether this server supports tasks/cancel. + */ + cancel?: object; + /** + * Specifies which request types can be augmented with tasks. + */ + requests?: { + /** + * Task support for tool-related requests. + */ + tools?: { + /** + * Whether the server supports task-augmented tools/call requests. + */ + call?: object; + }; + }; + }; +} + +/** + * An optionally-sized icon that can be displayed in a user interface. + * + * @category Common Types + */ +export interface Icon { + /** + * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a + * `data:` URI with Base64-encoded image data. + * + * Consumers SHOULD takes steps to ensure URLs serving icons are from the + * same domain as the client/server or a trusted domain. + * + * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain + * executable JavaScript. + * + * @format uri + */ + src: string; + + /** + * Optional MIME type override if the source MIME type is missing or generic. + * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. + */ + mimeType?: string; + + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes?: string[]; + + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme?: "light" | "dark"; +} + +/** + * Base interface to add `icons` property. + * + * @internal + */ +export interface Icons { + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons?: Icon[]; +} + +/** + * Base interface for metadata with name (identifier) and title (display name) properties. + * + * @internal + */ +export interface BaseMetadata { + /** + * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). + */ + name: string; + + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title?: string; +} + +/** + * Describes the MCP implementation. + * + * @category `initialize` + */ +export interface Implementation extends BaseMetadata, Icons { + version: string; + + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description?: string; + + /** + * An optional URL of the website for this implementation. + * + * @format uri + */ + websiteUrl?: string; +} + +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + * + * @category `ping` + */ +export interface PingRequest extends JSONRPCRequest { + method: "ping"; + params?: RequestParams; +} + +/* Progress notifications */ + +/** + * Parameters for a `notifications/progress` notification. + * + * @category `notifications/progress` + */ +export interface ProgressNotificationParams extends NotificationParams { + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressToken; + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + * + * @TJS-type number + */ + progress: number; + /** + * Total number of items to process (or total progress required), if known. + * + * @TJS-type number + */ + total?: number; + /** + * An optional message describing the current progress. + */ + message?: string; +} + +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category `notifications/progress` + */ +export interface ProgressNotification extends JSONRPCNotification { + method: "notifications/progress"; + params: ProgressNotificationParams; +} + +/* Pagination */ +/** + * Common parameters for paginated requests. + * + * @internal + */ +export interface PaginatedRequestParams extends RequestParams { + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor?: Cursor; +} + +/** @internal */ +export interface PaginatedRequest extends JSONRPCRequest { + params?: PaginatedRequestParams; +} + +/** @internal */ +export interface PaginatedResult extends Result { + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor?: Cursor; +} + +/* Resources */ +/** + * Sent from the client to request a list of resources the server has. + * + * @category `resources/list` + */ +export interface ListResourcesRequest extends PaginatedRequest { + method: "resources/list"; +} + +/** + * The server's response to a resources/list request from the client. + * + * @category `resources/list` + */ +export interface ListResourcesResult extends PaginatedResult { + resources: Resource[]; +} + +/** + * Sent from the client to request a list of resource templates the server has. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesRequest extends PaginatedRequest { + method: "resources/templates/list"; +} + +/** + * The server's response to a resources/templates/list request from the client. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesResult extends PaginatedResult { + resourceTemplates: ResourceTemplate[]; +} + +/** + * Common parameters when working with resources. + * + * @internal + */ +export interface ResourceRequestParams extends RequestParams { + /** + * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; +} + +/** + * Parameters for a `resources/read` request. + * + * @category `resources/read` + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface ReadResourceRequestParams extends ResourceRequestParams {} + +/** + * Sent from the client to the server, to read a specific resource URI. + * + * @category `resources/read` + */ +export interface ReadResourceRequest extends JSONRPCRequest { + method: "resources/read"; + params: ReadResourceRequestParams; +} + +/** + * The server's response to a resources/read request from the client. + * + * @category `resources/read` + */ +export interface ReadResourceResult extends Result { + contents: (TextResourceContents | BlobResourceContents)[]; +} + +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/resources/list_changed` + */ +export interface ResourceListChangedNotification extends JSONRPCNotification { + method: "notifications/resources/list_changed"; + params?: NotificationParams; +} + +/** + * Parameters for a `resources/subscribe` request. + * + * @category `resources/subscribe` + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface SubscribeRequestParams extends ResourceRequestParams {} + +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + * + * @category `resources/subscribe` + */ +export interface SubscribeRequest extends JSONRPCRequest { + method: "resources/subscribe"; + params: SubscribeRequestParams; +} + +/** + * Parameters for a `resources/unsubscribe` request. + * + * @category `resources/unsubscribe` + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface UnsubscribeRequestParams extends ResourceRequestParams {} + +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + * + * @category `resources/unsubscribe` + */ +export interface UnsubscribeRequest extends JSONRPCRequest { + method: "resources/unsubscribe"; + params: UnsubscribeRequestParams; +} + +/** + * Parameters for a `notifications/resources/updated` notification. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotificationParams extends NotificationParams { + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + * + * @format uri + */ + uri: string; +} + +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotification extends JSONRPCNotification { + method: "notifications/resources/updated"; + params: ResourceUpdatedNotificationParams; +} + +/** + * A known resource that the server is capable of reading. + * + * @category `resources/list` + */ +export interface Resource extends BaseMetadata, Icons { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size?: number; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * A template description for resources available on the server. + * + * @category `resources/templates/list` + */ +export interface ResourceTemplate extends BaseMetadata, Icons { + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + * + * @format uri-template + */ + uriTemplate: string; + + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * The contents of a specific resource or sub-resource. + * + * @internal + */ +export interface ResourceContents { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * @category Content + */ +export interface TextResourceContents extends ResourceContents { + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string; +} + +/** + * @category Content + */ +export interface BlobResourceContents extends ResourceContents { + /** + * A base64-encoded string representing the binary data of the item. + * + * @format byte + */ + blob: string; +} + +/* Prompts */ +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + * + * @category `prompts/list` + */ +export interface ListPromptsRequest extends PaginatedRequest { + method: "prompts/list"; +} + +/** + * The server's response to a prompts/list request from the client. + * + * @category `prompts/list` + */ +export interface ListPromptsResult extends PaginatedResult { + prompts: Prompt[]; +} + +/** + * Parameters for a `prompts/get` request. + * + * @category `prompts/get` + */ +export interface GetPromptRequestParams extends RequestParams { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * Arguments to use for templating the prompt. + */ + arguments?: { [key: string]: string }; +} + +/** + * Used by the client to get a prompt provided by the server. + * + * @category `prompts/get` + */ +export interface GetPromptRequest extends JSONRPCRequest { + method: "prompts/get"; + params: GetPromptRequestParams; +} + +/** + * The server's response to a prompts/get request from the client. + * + * @category `prompts/get` + */ +export interface GetPromptResult extends Result { + /** + * An optional description for the prompt. + */ + description?: string; + messages: PromptMessage[]; +} + +/** + * A prompt or prompt template that the server offers. + * + * @category `prompts/list` + */ +export interface Prompt extends BaseMetadata, Icons { + /** + * An optional description of what this prompt provides + */ + description?: string; + + /** + * A list of arguments to use for templating the prompt. + */ + arguments?: PromptArgument[]; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * Describes an argument that a prompt can accept. + * + * @category `prompts/list` + */ +export interface PromptArgument extends BaseMetadata { + /** + * A human-readable description of the argument. + */ + description?: string; + /** + * Whether this argument must be provided. + */ + required?: boolean; +} + +/** + * The sender or recipient of messages and data in a conversation. + * + * @category Common Types + */ +export type Role = "user" | "assistant"; + +/** + * Describes a message returned as part of a prompt. + * + * This is similar to `SamplingMessage`, but also supports the embedding of + * resources from the MCP server. + * + * @category `prompts/get` + */ +export interface PromptMessage { + role: Role; + content: ContentBlock; +} + +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + * + * @category Content + */ +export interface ResourceLink extends Resource { + type: "resource_link"; +} + +/** + * The contents of a resource, embedded into a prompt or tool call result. + * + * It is up to the client how best to render embedded resources for the benefit + * of the LLM and/or the user. + * + * @category Content + */ +export interface EmbeddedResource { + type: "resource"; + resource: TextResourceContents | BlobResourceContents; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/prompts/list_changed` + */ +export interface PromptListChangedNotification extends JSONRPCNotification { + method: "notifications/prompts/list_changed"; + params?: NotificationParams; +} + +/* Tools */ +/** + * Sent from the client to request a list of tools the server has. + * + * @category `tools/list` + */ +export interface ListToolsRequest extends PaginatedRequest { + method: "tools/list"; +} + +/** + * The server's response to a tools/list request from the client. + * + * @category `tools/list` + */ +export interface ListToolsResult extends PaginatedResult { + tools: Tool[]; +} + +/** + * The server's response to a tool call. + * + * @category `tools/call` + */ +export interface CallToolResult extends Result { + /** + * A list of content objects that represent the unstructured result of the tool call. + */ + content: ContentBlock[]; + + /** + * An optional JSON object that represents the structured result of the tool call. + */ + structuredContent?: { [key: string]: unknown }; + + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError?: boolean; +} + +/** + * Parameters for a `tools/call` request. + * + * @category `tools/call` + */ +export interface CallToolRequestParams extends TaskAugmentedRequestParams { + /** + * The name of the tool. + */ + name: string; + /** + * Arguments to use for the tool call. + */ + arguments?: { [key: string]: unknown }; +} + +/** + * Used by the client to invoke a tool provided by the server. + * + * @category `tools/call` + */ +export interface CallToolRequest extends JSONRPCRequest { + method: "tools/call"; + params: CallToolRequestParams; +} + +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/tools/list_changed` + */ +export interface ToolListChangedNotification extends JSONRPCNotification { + method: "notifications/tools/list_changed"; + params?: NotificationParams; +} + +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + * + * @category `tools/list` + */ +export interface ToolAnnotations { + /** + * A human-readable title for the tool. + */ + title?: string; + + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint?: boolean; + + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint?: boolean; + + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint?: boolean; + + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint?: boolean; +} + +/** + * Execution-related properties for a tool. + * + * @category `tools/list` + */ +export interface ToolExecution { + /** + * Indicates whether this tool supports task-augmented execution. + * This allows clients to handle long-running operations through polling + * the task system. + * + * - "forbidden": Tool does not support task-augmented execution (default when absent) + * - "optional": Tool may support task-augmented execution + * - "required": Tool requires task-augmented execution + * + * Default: "forbidden" + */ + taskSupport?: "forbidden" | "optional" | "required"; +} + +/** + * Definition for a tool the client can call. + * + * @category `tools/list` + */ +export interface Tool extends BaseMetadata, Icons { + /** + * A human-readable description of the tool. + * + * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * A JSON Schema object defining the expected parameters for the tool. + */ + inputSchema: { + $schema?: string; + type: "object"; + properties?: { [key: string]: object }; + required?: string[]; + }; + + /** + * Execution-related properties for this tool. + */ + execution?: ToolExecution; + + /** + * An optional JSON Schema object defining the structure of the tool's output returned in + * the structuredContent field of a CallToolResult. + * + * Defaults to JSON Schema 2020-12 when no explicit $schema is provided. + * Currently restricted to type: "object" at the root level. + */ + outputSchema?: { + $schema?: string; + type: "object"; + properties?: { [key: string]: object }; + required?: string[]; + }; + + /** + * Optional additional tool information. + * + * Display name precedence order is: title, annotations.title, then name. + */ + annotations?: ToolAnnotations; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/* Tasks */ + +/** + * The status of a task. + * + * @category `tasks` + */ +export type TaskStatus = + | "working" // The request is currently being processed + | "input_required" // The task is waiting for input (e.g., elicitation or sampling) + | "completed" // The request completed successfully and results are available + | "failed" // The associated request did not complete successfully. For tool calls specifically, this includes cases where the tool call result has `isError` set to true. + | "cancelled"; // The request was cancelled before completion + +/** + * Metadata for augmenting a request with task execution. + * Include this in the `task` field of the request parameters. + * + * @category `tasks` + */ +export interface TaskMetadata { + /** + * Requested duration in milliseconds to retain task from creation. + */ + ttl?: number; +} + +/** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * + * @category `tasks` + */ +export interface RelatedTaskMetadata { + /** + * The task identifier this message is associated with. + */ + taskId: string; +} + +/** + * Data associated with a task. + * + * @category `tasks` + */ +export interface Task { + /** + * The task identifier. + */ + taskId: string; + + /** + * Current task state. + */ + status: TaskStatus; + + /** + * Optional human-readable message describing the current task state. + * This can provide context for any status, including: + * - Reasons for "cancelled" status + * - Summaries for "completed" status + * - Diagnostic information for "failed" status (e.g., error details, what went wrong) + */ + statusMessage?: string; + + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: string; + + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: string; + + /** + * Actual retention duration from creation in milliseconds, null for unlimited. + * @nullable + */ + ttl: number | null; + + /** + * Suggested polling interval in milliseconds. + */ + pollInterval?: number; +} + +/** + * A response to a task-augmented request. + * + * @category `tasks` + */ +export interface CreateTaskResult extends Result { + task: Task; +} + +/** + * A request to retrieve the state of a task. + * + * @category `tasks/get` + */ +export interface GetTaskRequest extends JSONRPCRequest { + method: "tasks/get"; + params: { + /** + * The task identifier to query. + */ + taskId: string; + }; +} + +/** + * The response to a tasks/get request. + * + * @category `tasks/get` + */ +export type GetTaskResult = Result & Task; + +/** + * A request to retrieve the result of a completed task. + * + * @category `tasks/result` + */ +export interface GetTaskPayloadRequest extends JSONRPCRequest { + method: "tasks/result"; + params: { + /** + * The task identifier to retrieve results for. + */ + taskId: string; + }; +} + +/** + * The response to a tasks/result request. + * The structure matches the result type of the original request. + * For example, a tools/call task would return the CallToolResult structure. + * + * @category `tasks/result` + */ +export interface GetTaskPayloadResult extends Result { + [key: string]: unknown; +} + +/** + * A request to cancel a task. + * + * @category `tasks/cancel` + */ +export interface CancelTaskRequest extends JSONRPCRequest { + method: "tasks/cancel"; + params: { + /** + * The task identifier to cancel. + */ + taskId: string; + }; +} + +/** + * The response to a tasks/cancel request. + * + * @category `tasks/cancel` + */ +export type CancelTaskResult = Result & Task; + +/** + * A request to retrieve a list of tasks. + * + * @category `tasks/list` + */ +export interface ListTasksRequest extends PaginatedRequest { + method: "tasks/list"; +} + +/** + * The response to a tasks/list request. + * + * @category `tasks/list` + */ +export interface ListTasksResult extends PaginatedResult { + tasks: Task[]; +} + +/** + * Parameters for a `notifications/tasks/status` notification. + * + * @category `notifications/tasks/status` + */ +export type TaskStatusNotificationParams = NotificationParams & Task; + +/** + * An optional notification from the receiver to the requestor, informing them that a task's status has changed. Receivers are not required to send these notifications. + * + * @category `notifications/tasks/status` + */ +export interface TaskStatusNotification extends JSONRPCNotification { + method: "notifications/tasks/status"; + params: TaskStatusNotificationParams; +} + +/* Logging */ + +/** + * Parameters for a `logging/setLevel` request. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequestParams extends RequestParams { + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/message. + */ + level: LoggingLevel; +} + +/** + * A request from the client to the server, to enable or adjust logging. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequest extends JSONRPCRequest { + method: "logging/setLevel"; + params: SetLevelRequestParams; +} + +/** + * Parameters for a `notifications/message` notification. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotificationParams extends NotificationParams { + /** + * The severity of this log message. + */ + level: LoggingLevel; + /** + * An optional name of the logger issuing this message. + */ + logger?: string; + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown; +} + +/** + * JSONRPCNotification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotification extends JSONRPCNotification { + method: "notifications/message"; + params: LoggingMessageNotificationParams; +} + +/** + * The severity of a log message. + * + * These map to syslog message severities, as specified in RFC-5424: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + * + * @category Common Types + */ +export type LoggingLevel = + | "debug" + | "info" + | "notice" + | "warning" + | "error" + | "critical" + | "alert" + | "emergency"; + +/* Sampling */ +/** + * Parameters for a `sampling/createMessage` request. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequestParams extends TaskAugmentedRequestParams { + messages: SamplingMessage[]; + /** + * The server's preferences for which model to select. The client MAY ignore these preferences. + */ + modelPreferences?: ModelPreferences; + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt?: string; + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext?: "none" | "thisServer" | "allServers"; + /** + * @TJS-type number + */ + temperature?: number; + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number; + stopSequences?: string[]; + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata?: object; + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools?: Tool[]; + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice?: ToolChoice; +} + +/** + * Controls tool selection behavior for sampling requests. + * + * @category `sampling/createMessage` + */ +export interface ToolChoice { + /** + * Controls the tool use ability of the model: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode?: "auto" | "required" | "none"; +} + +/** + * 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. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequest extends JSONRPCRequest { + method: "sampling/createMessage"; + params: CreateMessageRequestParams; +} + +/** + * The client's response to a sampling/createMessage request from the server. + * The client should inform the user before returning the sampled message, to allow them + * to inspect the response (human in the loop) and decide whether to allow the server to see it. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageResult extends Result, SamplingMessage { + /** + * The name of the model that generated the message. + */ + model: string; + + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason?: "endTurn" | "stopSequence" | "maxTokens" | "toolUse" | string; +} + +/** + * Describes a message issued to or received from an LLM API. + * + * @category `sampling/createMessage` + */ +export interface SamplingMessage { + role: Role; + content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * @category `sampling/createMessage` + */ +export type SamplingMessageContentBlock = + | TextContent + | ImageContent + | AudioContent + | ToolUseContent + | ToolResultContent; + +/** + * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed + * + * @category Common Types + */ +export interface Annotations { + /** + * Describes who the intended audience of this object or data is. + * + * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). + */ + audience?: Role[]; + + /** + * Describes how important this data is for operating the server. + * + * A value of 1 means "most important," and indicates that the data is + * effectively required, while 0 means "least important," and indicates that + * the data is entirely optional. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + priority?: number; + + /** + * The moment the resource was last modified, as an ISO 8601 formatted string. + * + * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). + * + * Examples: last activity timestamp in an open file, timestamp when the resource + * was attached, etc. + */ + lastModified?: string; +} + +/** + * @category Content + */ +export type ContentBlock = + | TextContent + | ImageContent + | AudioContent + | ResourceLink + | EmbeddedResource; + +/** + * Text provided to or from an LLM. + * + * @category Content + */ +export interface TextContent { + type: "text"; + + /** + * The text content of the message. + */ + text: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * An image provided to or from an LLM. + * + * @category Content + */ +export interface ImageContent { + type: "image"; + + /** + * The base64-encoded image data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * Audio provided to or from an LLM. + * + * @category Content + */ +export interface AudioContent { + type: "audio"; + + /** + * The base64-encoded audio data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * A request from the assistant to call a tool. + * + * @category `sampling/createMessage` + */ +export interface ToolUseContent { + type: "tool_use"; + + /** + * A unique identifier for this tool use. + * + * This ID is used to match tool results to their corresponding tool uses. + */ + id: string; + + /** + * The name of the tool to call. + */ + name: string; + + /** + * The arguments to pass to the tool, conforming to the tool's input schema. + */ + input: { [key: string]: unknown }; + + /** + * Optional metadata about the tool use. Clients SHOULD preserve this field when + * including tool uses in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * The result of a tool use, provided by the user back to the assistant. + * + * @category `sampling/createMessage` + */ +export interface ToolResultContent { + type: "tool_result"; + + /** + * The ID of the tool use this result corresponds to. + * + * This MUST match the ID from a previous ToolUseContent. + */ + toolUseId: string; + + /** + * The unstructured result content of the tool use. + * + * This has the same format as CallToolResult.content and can include text, images, + * audio, resource links, and embedded resources. + */ + content: ContentBlock[]; + + /** + * An optional structured result object. + * + * If the tool defined an outputSchema, this SHOULD conform to that schema. + */ + structuredContent?: { [key: string]: unknown }; + + /** + * Whether the tool use resulted in an error. + * + * If true, the content typically describes the error that occurred. + * Default: false + */ + isError?: boolean; + + /** + * Optional metadata about the tool result. Clients SHOULD preserve this field when + * including tool results in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * The server's preferences for model selection, requested of the client during sampling. + * + * Because LLMs can vary along multiple dimensions, choosing the "best" model is + * rarely straightforward. Different models excel in different areas—some are + * faster but less capable, others are more capable but more expensive, and so + * on. This interface allows servers to express their priorities across multiple + * dimensions to help clients make an appropriate selection for their use case. + * + * These preferences are always advisory. The client MAY ignore them. It is also + * up to the client to decide how to interpret these preferences and how to + * balance them against other considerations. + * + * @category `sampling/createMessage` + */ +export interface ModelPreferences { + /** + * Optional hints to use for model selection. + * + * If multiple hints are specified, the client MUST evaluate them in order + * (such that the first match is taken). + * + * The client SHOULD prioritize these hints over the numeric priorities, but + * MAY still use the priorities to select from ambiguous matches. + */ + hints?: ModelHint[]; + + /** + * How much to prioritize cost when selecting a model. A value of 0 means cost + * is not important, while a value of 1 means cost is the most important + * factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + costPriority?: number; + + /** + * How much to prioritize sampling speed (latency) when selecting a model. A + * value of 0 means speed is not important, while a value of 1 means speed is + * the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + speedPriority?: number; + + /** + * How much to prioritize intelligence and capabilities when selecting a + * model. A value of 0 means intelligence is not important, while a value of 1 + * means intelligence is the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + intelligencePriority?: number; +} + +/** + * Hints to use for model selection. + * + * Keys not declared here are currently left unspecified by the spec and are up + * to the client to interpret. + * + * @category `sampling/createMessage` + */ +export interface ModelHint { + /** + * A hint for a model name. + * + * The client SHOULD treat this as a substring of a model name; for example: + * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` + * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. + * - `claude` should match any Claude model + * + * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: + * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` + */ + name?: string; +} + +/* Autocomplete */ +/** + * Parameters for a `completion/complete` request. + * + * @category `completion/complete` + */ +export interface CompleteRequestParams extends RequestParams { + ref: PromptReference | ResourceTemplateReference; + /** + * The argument's information + */ + argument: { + /** + * The name of the argument + */ + name: string; + /** + * The value of the argument to use for completion matching. + */ + value: string; + }; + + /** + * Additional, optional context for completions + */ + context?: { + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments?: { [key: string]: string }; + }; +} + +/** + * A request from the client to the server, to ask for completion options. + * + * @category `completion/complete` + */ +export interface CompleteRequest extends JSONRPCRequest { + method: "completion/complete"; + params: CompleteRequestParams; +} + +/** + * The server's response to a completion/complete request + * + * @category `completion/complete` + */ +export interface CompleteResult extends Result { + completion: { + /** + * An array of completion values. Must not exceed 100 items. + */ + values: string[]; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total?: number; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore?: boolean; + }; +} + +/** + * A reference to a resource or resource template definition. + * + * @category `completion/complete` + */ +export interface ResourceTemplateReference { + type: "ref/resource"; + /** + * The URI or URI template of the resource. + * + * @format uri-template + */ + uri: string; +} + +/** + * Identifies a prompt. + * + * @category `completion/complete` + */ +export interface PromptReference extends BaseMetadata { + type: "ref/prompt"; +} + +/* Roots */ +/** + * Sent from the server to request a list of root URIs from the client. Roots allow + * servers to ask for specific directories or files to operate on. A common example + * for roots is providing a set of repositories or directories a server should operate + * on. + * + * This request is typically used when the server needs to understand the file system + * structure or access specific locations that the client has permission to read from. + * + * @category `roots/list` + */ +export interface ListRootsRequest extends JSONRPCRequest { + method: "roots/list"; + params?: RequestParams; +} + +/** + * The client's response to a roots/list request from the server. + * This result contains an array of Root objects, each representing a root directory + * or file that the server can operate on. + * + * @category `roots/list` + */ +export interface ListRootsResult extends Result { + roots: Root[]; +} + +/** + * Represents a root directory or file that the server can operate on. + * + * @category `roots/list` + */ +export interface Root { + /** + * The URI identifying the root. This *must* start with file:// for now. + * This restriction may be relaxed in future versions of the protocol to allow + * other URI schemes. + * + * @format uri + */ + uri: string; + /** + * An optional name for the root. This can be used to provide a human-readable + * identifier for the root, which may be useful for display purposes or for + * referencing the root in other parts of the application. + */ + name?: string; + + /** + * See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * A notification from the client to the server, informing it that the list of roots has changed. + * This notification should be sent whenever the client adds, removes, or modifies any root. + * The server should then request an updated list of roots using the ListRootsRequest. + * + * @category `notifications/roots/list_changed` + */ +export interface RootsListChangedNotification extends JSONRPCNotification { + method: "notifications/roots/list_changed"; + params?: NotificationParams; +} + +/** + * The parameters for a request to elicit non-sensitive information from the user via a form in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestFormParams extends TaskAugmentedRequestParams { + /** + * The elicitation mode. + */ + mode?: "form"; + + /** + * The message to present to the user describing what information is being requested. + */ + message: string; + + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: { + $schema?: string; + type: "object"; + properties: { + [key: string]: PrimitiveSchemaDefinition; + }; + required?: string[]; + }; +} + +/** + * The parameters for a request to elicit information from the user via a URL in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestURLParams extends TaskAugmentedRequestParams { + /** + * The elicitation mode. + */ + mode: "url"; + + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string; + + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string; + + /** + * The URL that the user should navigate to. + * + * @format uri + */ + url: string; +} + +/** + * The parameters for a request to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export type ElicitRequestParams = + | ElicitRequestFormParams + | ElicitRequestURLParams; + +/** + * A request from the server to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequest extends JSONRPCRequest { + method: "elicitation/create"; + params: ElicitRequestParams; +} + +/** + * Restricted schema definitions that only allow primitive types + * without nested objects or arrays. + * + * @category `elicitation/create` + */ +export type PrimitiveSchemaDefinition = + | StringSchema + | NumberSchema + | BooleanSchema + | EnumSchema; + +/** + * @category `elicitation/create` + */ +export interface StringSchema { + type: "string"; + title?: string; + description?: string; + minLength?: number; + maxLength?: number; + format?: "email" | "uri" | "date" | "date-time"; + default?: string; +} + +/** + * @category `elicitation/create` + */ +export interface NumberSchema { + type: "number" | "integer"; + title?: string; + description?: string; + minimum?: number; + maximum?: number; + default?: number; +} + +/** + * @category `elicitation/create` + */ +export interface BooleanSchema { + type: "boolean"; + title?: string; + description?: string; + default?: boolean; +} + +/** + * Schema for single-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum values to choose from. + */ + enum: string[]; + /** + * Optional default value. + */ + default?: string; +} + +/** + * Schema for single-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum options with values and display labels. + */ + oneOf: Array<{ + /** + * The enum value. + */ + const: string; + /** + * Display label for this option. + */ + title: string; + }>; + /** + * Optional default value. + */ + default?: string; +} + +/** + * @category `elicitation/create` + */ +// Combined single selection enumeration +export type SingleSelectEnumSchema = + | UntitledSingleSelectEnumSchema + | TitledSingleSelectEnumSchema; + +/** + * Schema for multiple-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for the array items. + */ + items: { + type: "string"; + /** + * Array of enum values to choose from. + */ + enum: string[]; + }; + /** + * Optional default value. + */ + default?: string[]; +} + +/** + * Schema for multiple-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for array items with enum options and display labels. + */ + items: { + /** + * Array of enum options with values and display labels. + */ + anyOf: Array<{ + /** + * The constant enum value. + */ + const: string; + /** + * Display title for this option. + */ + title: string; + }>; + }; + /** + * Optional default value. + */ + default?: string[]; +} + +/** + * @category `elicitation/create` + */ +// Combined multiple selection enumeration +export type MultiSelectEnumSchema = + | UntitledMultiSelectEnumSchema + | TitledMultiSelectEnumSchema; + +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + * + * @category `elicitation/create` + */ +export interface LegacyTitledEnumSchema { + type: "string"; + title?: string; + description?: string; + enum: string[]; + /** + * (Legacy) Display names for enum values. + * Non-standard according to JSON schema 2020-12. + */ + enumNames?: string[]; + default?: string; +} + +/** + * @category `elicitation/create` + */ +// Union type for all enum schemas +export type EnumSchema = + | SingleSelectEnumSchema + | MultiSelectEnumSchema + | LegacyTitledEnumSchema; + +/** + * The client's response to an elicitation request. + * + * @category `elicitation/create` + */ +export interface ElicitResult extends Result { + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: "accept" | "decline" | "cancel"; + + /** + * The submitted form data, only present when action is "accept" and mode was "form". + * Contains values matching the requested schema. + * Omitted for out-of-band mode responses. + */ + content?: { [key: string]: string | number | boolean | string[] }; +} + +/** + * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request. + * + * @category `notifications/elicitation/complete` + */ +export interface ElicitationCompleteNotification extends JSONRPCNotification { + method: "notifications/elicitation/complete"; + params: { + /** + * The ID of the elicitation that completed. + */ + elicitationId: string; + }; +} + +/* Client messages */ +/** @internal */ +export type ClientRequest = + | PingRequest + | InitializeRequest + | CompleteRequest + | SetLevelRequest + | GetPromptRequest + | ListPromptsRequest + | ListResourcesRequest + | ListResourceTemplatesRequest + | ReadResourceRequest + | SubscribeRequest + | UnsubscribeRequest + | CallToolRequest + | ListToolsRequest + | GetTaskRequest + | GetTaskPayloadRequest + | ListTasksRequest + | CancelTaskRequest; + +/** @internal */ +export type ClientNotification = + | CancelledNotification + | ProgressNotification + | InitializedNotification + | RootsListChangedNotification + | TaskStatusNotification; + +/** @internal */ +export type ClientResult = + | EmptyResult + | CreateMessageResult + | ListRootsResult + | ElicitResult + | GetTaskResult + | GetTaskPayloadResult + | ListTasksResult + | CancelTaskResult; + +/* Server messages */ +/** @internal */ +export type ServerRequest = + | PingRequest + | CreateMessageRequest + | ListRootsRequest + | ElicitRequest + | GetTaskRequest + | GetTaskPayloadRequest + | ListTasksRequest + | CancelTaskRequest; + +/** @internal */ +export type ServerNotification = + | CancelledNotification + | ProgressNotification + | LoggingMessageNotification + | ResourceUpdatedNotification + | ResourceListChangedNotification + | ToolListChangedNotification + | PromptListChangedNotification + | ElicitationCompleteNotification + | TaskStatusNotification; + +/** @internal */ +export type ServerResult = + | EmptyResult + | InitializeResult + | CompleteResult + | GetPromptResult + | ListPromptsResult + | ListResourceTemplatesResult + | ListResourcesResult + | ReadResourceResult + | CallToolResult + | ListToolsResult + | GetTaskResult + | GetTaskPayloadResult + | ListTasksResult + | CancelTaskResult; diff --git a/src/spec-types/README.md b/src/spec-types/README.md new file mode 100644 index 00000000..77580c0d --- /dev/null +++ b/src/spec-types/README.md @@ -0,0 +1,29 @@ +# spec-types + +Vendored copies of `schema/{version}/schema.ts` from the +[modelcontextprotocol](https://github.com/modelcontextprotocol/modelcontextprotocol) +spec repository. + +These are the canonical TypeScript types for each protocol version. The +conformance suite imports types from here rather than from +`@modelcontextprotocol/sdk` so that it can test draft spec versions before any +SDK has implemented them. + +**Do not edit these files by hand.** To refresh: + +```sh +npm run sync-schema -- +``` + +The `SOURCE` file records the spec commit the current copies came from. + +## Import rule + +A scenario imports the schema matching its `source.introducedIn`: + +```ts +import type { ListToolsResult } from '../../spec-types/2025-06-18'; +``` + +`Connection` implementations import the version whose lifecycle they implement +(stateful → `2025-11-25`, stateless → `draft`). diff --git a/src/spec-types/SOURCE b/src/spec-types/SOURCE new file mode 100644 index 00000000..201d6005 --- /dev/null +++ b/src/spec-types/SOURCE @@ -0,0 +1 @@ +modelcontextprotocol@33c3724972e6a87a8ad153e3f8a0d4714b0b9536 diff --git a/src/spec-types/draft.ts b/src/spec-types/draft.ts new file mode 100644 index 00000000..3d7cd427 --- /dev/null +++ b/src/spec-types/draft.ts @@ -0,0 +1,2983 @@ +/* JSON types */ + +/** + * @category Common Types + */ +export type JSONValue = + | string + | number + | boolean + | null + | JSONObject + | JSONArray; + +/** + * @category Common Types + */ +export type JSONObject = { [key: string]: JSONValue }; + +/** + * @category Common Types + */ +export type JSONArray = JSONValue[]; + +/* JSON-RPC types */ + +/** + * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. + * + * @category JSON-RPC + */ +export type JSONRPCMessage = + | JSONRPCRequest + | JSONRPCNotification + | JSONRPCResponse; + +/** @internal */ +export const LATEST_PROTOCOL_VERSION = "DRAFT-2026-v1"; +/** @internal */ +export const JSONRPC_VERSION = "2.0"; + +/** + * Represents the contents of a `_meta` field, which clients and servers use to attach additional metadata to their interactions. + * + * Certain key names are reserved by MCP for protocol-level metadata; implementations MUST NOT make assumptions about values at these keys. Additionally, specific schema definitions may reserve particular names for purpose-specific metadata, as declared in those definitions. + * + * Valid keys have two segments: + * + * **Prefix:** + * - Optional — if specified, MUST be a series of _labels_ separated by dots (`.`), followed by a slash (`/`). + * - Labels MUST start with a letter and end with a letter or digit. Interior characters may be letters, digits, or hyphens (`-`). + * - Implementations SHOULD use reverse DNS notation (e.g., `com.example/` rather than `example.com/`). + * - Any prefix where the second label is `modelcontextprotocol` or `mcp` is **reserved** for MCP use. For example: `io.modelcontextprotocol/`, `dev.mcp/`, `org.modelcontextprotocol.api/`, and `com.mcp.tools/` are all reserved. However, `com.example.mcp/` is NOT reserved, as the second label is `example`. + * + * **Name:** + * - Unless empty, MUST start and end with an alphanumeric character (`[a-z0-9A-Z]`). + * - Interior characters may be alphanumeric, hyphens (`-`), underscores (`_`), or dots (`.`). + * + * @see [General fields: `_meta`](/specification/draft/basic/index#meta) for more details. + * @category Common Types + */ +export type MetaObject = Record; + +/** + * Extends {@link MetaObject} with additional request-specific fields. All key naming rules from `MetaObject` apply. + * + * @see {@link MetaObject} for key naming rules and reserved prefixes. + * @see [General fields: `_meta`](/specification/draft/basic/index#meta) for more details. + * @category Common Types + */ +export interface RequestMetaObject extends MetaObject { + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by {@link ProgressNotification | notifications/progress}). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken?: ProgressToken; + /** + * The MCP Protocol Version being used for this request. Required. + * + * For the HTTP transport, this value MUST match the `MCP-Protocol-Version` + * header; otherwise the server MUST return a `400 Bad Request`. If the + * server does not support the requested version, it MUST return an + * {@link UnsupportedProtocolVersionError}. + */ + "io.modelcontextprotocol/protocolVersion": string; + /** + * Identifies the client software making the request. Required. + * + * The {@link Implementation} schema requires `name` and `version`; other + * fields are optional. + */ + "io.modelcontextprotocol/clientInfo": Implementation; + /** + * The client's capabilities for this specific request. Required. + * + * Capabilities are declared per-request rather than once at initialization; + * an empty object means the client supports no optional capabilities. + * Servers MUST NOT infer capabilities from prior requests. + */ + "io.modelcontextprotocol/clientCapabilities": ClientCapabilities; + /** + * The desired log level for this request. Optional. + * + * If absent, the server MUST NOT send any {@link LoggingMessageNotification | notifications/message} + * notifications for this request. The client opts in to log messages by + * explicitly setting a level. Replaces the former `logging/setLevel` RPC. + */ + "io.modelcontextprotocol/logLevel"?: LoggingLevel; +} + +/** + * A progress token, used to associate progress notifications with the original request. + * + * @category Common Types + */ +export type ProgressToken = string | number; + +/** + * An opaque token used to represent a cursor for pagination. + * + * @category Common Types + */ +export type Cursor = string; + +/** + * Common params for any request. + * + * @category Common Types + */ +export interface RequestParams { + _meta: RequestMetaObject; +} + +/** @internal */ +export interface Request { + method: string; + // Allow unofficial extensions of `Request.params` without impacting `RequestParams`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + params?: { [key: string]: any }; +} + +/** + * Common params for any notification. + * + * @category Common Types + */ +export interface NotificationParams { + _meta?: MetaObject; +} + +/** @internal */ +export interface Notification { + method: string; + // Allow unofficial extensions of `Notification.params` without impacting `NotificationParams`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + params?: { [key: string]: any }; +} + +/** + * Indicates the type of a {@link Result} object, allowing the client to + * determine how to parse the response. + * + * complete - the request completed successfully and the result contains the final content. + * input_required - the request requires additional input and the result contains an {@link InputRequiredResult} object with instructions for the client to provide additional input before retrying the original request. + * @category Common Types + */ +export type ResultType = "complete" | "input_required"; + +/** + * Common result fields. + * + * @category Common Types + */ +export interface Result { + _meta?: MetaObject; + /** + * Indicates the type of the result, which allows the client to determine + * how to parse the result object. + * + * Servers implementing this protocol version MUST include this field. + * For backward compatibility, when a client receives a result from a + * server implementing an earlier protocol version (which does not include + * `resultType`), the client MUST treat the absent field as `"complete"`. + */ + resultType: ResultType; + [key: string]: unknown; +} + +/** + * @category Errors + */ +export interface Error { + /** + * The error type that occurred. + */ + code: number; + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string; + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data?: unknown; +} + +/** + * A uniquely identifying ID for a request in JSON-RPC. + * + * @category Common Types + */ +export type RequestId = string | number; + +/** + * A request that expects a response. + * + * @category JSON-RPC + */ +export interface JSONRPCRequest extends Request { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; +} + +/** + * A notification which does not expect a response. + * + * @category JSON-RPC + */ +export interface JSONRPCNotification extends Notification { + jsonrpc: typeof JSONRPC_VERSION; +} + +/** + * A successful (non-error) response to a request. + * + * @category JSON-RPC + */ +export interface JSONRPCResultResponse { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + result: Result; +} + +/** + * A response to a request that indicates an error occurred. + * + * @category JSON-RPC + */ +export interface JSONRPCErrorResponse { + jsonrpc: typeof JSONRPC_VERSION; + id?: RequestId; + error: Error; +} + +/** + * A response to a request, containing either the result or error. + * + * @category JSON-RPC + */ +export type JSONRPCResponse = JSONRPCResultResponse | JSONRPCErrorResponse; + +// Standard JSON-RPC error codes +export const PARSE_ERROR = -32700; +export const INVALID_REQUEST = -32600; +export const METHOD_NOT_FOUND = -32601; +export const INVALID_PARAMS = -32602; +export const INTERNAL_ERROR = -32603; + +/** + * A JSON-RPC error indicating that invalid JSON was received by the server. This error is returned when the server cannot parse the JSON text of a message. + * + * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object} + * + * @example Invalid JSON + * {@includeCode ./examples/ParseError/invalid-json.json} + * + * @category Errors + */ +export interface ParseError extends Error { + code: typeof PARSE_ERROR; +} + +/** + * A JSON-RPC error indicating that the request is not a valid request object. This error is returned when the message structure does not conform to the JSON-RPC 2.0 specification requirements for a request (e.g., missing required fields like `jsonrpc` or `method`, or using invalid types for these fields). + * + * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object} + * + * @category Errors + */ +export interface InvalidRequestError extends Error { + code: typeof INVALID_REQUEST; +} + +/** + * A JSON-RPC error indicating that the requested method does not exist or is not available. + * + * In MCP, this error is returned when a request is made for a method that requires a capability that has not been declared. This can occur in either direction: + * + * - A server returning this error when the client requests a capability it doesn't support (e.g., requesting completions when the `completions` capability was not advertised) + * - A client returning this error when the server requests a capability it doesn't support (e.g., requesting roots when the client did not declare the `roots` capability) + * + * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object} + * + * @example Roots not supported + * {@includeCode ./examples/MethodNotFoundError/roots-not-supported.json} + * + * @category Errors + */ +export interface MethodNotFoundError extends Error { + code: typeof METHOD_NOT_FOUND; +} + +/** + * A JSON-RPC error indicating that the method parameters are invalid or malformed. + * + * In MCP, this error is returned in various contexts when request parameters fail validation: + * + * - **Tools**: Unknown tool name or invalid tool arguments + * - **Prompts**: Unknown prompt name or missing required arguments + * - **Pagination**: Invalid or expired cursor values + * - **Logging**: Invalid log level + * - **Elicitation**: Server requests an elicitation mode not declared in client capabilities + * - **Sampling**: Missing tool result or tool results mixed with other content + * + * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object} + * + * @example Unknown tool + * {@includeCode ./examples/InvalidParamsError/unknown-tool.json} + * + * @example Invalid tool arguments + * {@includeCode ./examples/InvalidParamsError/invalid-tool-arguments.json} + * + * @example Unknown prompt + * {@includeCode ./examples/InvalidParamsError/unknown-prompt.json} + * + * @example Invalid cursor + * {@includeCode ./examples/InvalidParamsError/invalid-cursor.json} + * + * @category Errors + */ +export interface InvalidParamsError extends Error { + code: typeof INVALID_PARAMS; +} + +/** + * A JSON-RPC error indicating that an internal error occurred on the receiver. This error is returned when the receiver encounters an unexpected condition that prevents it from fulfilling the request. + * + * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object} + * + * @example Unexpected error + * {@includeCode ./examples/InternalError/unexpected-error.json} + * + * @category Errors + */ +export interface InternalError extends Error { + code: typeof INTERNAL_ERROR; +} + +/** + * Error code returned when a server requires a client capability that was + * not declared in the request's `clientCapabilities`. + * + * @category Errors + */ +export const MISSING_REQUIRED_CLIENT_CAPABILITY = -32003; + +/** + * Error code returned when the request's protocol version is not supported + * by the server. + * + * @category Errors + */ +export const UNSUPPORTED_PROTOCOL_VERSION = -32004; + +/** + * Returned when the request's protocol version is unknown to the server or + * unsupported (e.g., a known experimental or draft version the server has + * chosen not to implement). For HTTP, the response status code MUST be + * `400 Bad Request`. + * + * @example Unsupported protocol version + * {@includeCode ./examples/UnsupportedProtocolVersionError/unsupported-version.json} + * + * @category Errors + */ +export interface UnsupportedProtocolVersionError extends Omit< + JSONRPCErrorResponse, + "error" +> { + error: Error & { + code: typeof UNSUPPORTED_PROTOCOL_VERSION; + data: { + /** + * Protocol versions the server supports. The client should choose a + * mutually supported version from this list and retry. + */ + supported: string[]; + /** + * The protocol version that was requested by the client. + */ + requested: string; + }; + }; +} + +/** + * Returned when processing a request requires a capability the client did not + * declare in `clientCapabilities`. For HTTP, the response status code MUST be + * `400 Bad Request`. + * + * @example Missing elicitation capability + * {@includeCode ./examples/MissingRequiredClientCapabilityError/missing-elicitation-capability.json} + * + * @category Errors + */ +export interface MissingRequiredClientCapabilityError extends Omit< + JSONRPCErrorResponse, + "error" +> { + error: Error & { + code: typeof MISSING_REQUIRED_CLIENT_CAPABILITY; + data: { + /** + * The capabilities the server requires from the client to process this request. + */ + requiredCapabilities: ClientCapabilities; + }; + }; +} + +/* Empty result */ +/** + * A result that indicates success but carries no data. + * + * @category Common Types + */ +export type EmptyResult = Result; + +/** @internal */ +export type InputRequest = + | CreateMessageRequest + | ListRootsRequest + | ElicitRequest; + +/** @internal */ +export type InputResponse = + | CreateMessageResult + | ListRootsResult + | ElicitResult; + +/** + * A map of server-initiated requests that the client must fulfill. + * Keys are server-assigned identifiers; values are the request objects. + * + * @example Elicitation and sampling input requests + * {@includeCode ./examples/InputRequests/elicitation-and-sampling-input-requests.json} + * + * @category Multi Round-Trip + */ +export interface InputRequests { + [key: string]: InputRequest; +} + +/** + * A map of client responses to server-initiated requests. + * Keys correspond to the keys in the {@link InputRequests} map; + * values are the client's result for each request. + * + * @example Elicitation and sampling input responses + * {@includeCode ./examples/InputResponses/elicitation-and-sampling-input-responses.json} + * + * @category Multi Round-Trip + */ +export interface InputResponses { + [key: string]: InputResponse; +} + +/** + * An InputRequiredResult sent by the server to indicate that additional input is needed + * before the request can be completed. + * + * At least one of `inputRequests` or `requestState` MUST be present. + * @example InputRequiredResult with elicitation and sampling input requests and request state + * {@includeCode ./examples/InputRequiredResult/input-required-result-with-elicitation-and-sampling-and-request-state.json} + * + * @example InputRequiredResult with request state only (load shedding) + * {@includeCode ./examples/InputRequiredResult/input-required-result-with-request-state-only.json} + * + * @category Multi Round-Trip + */ +export interface InputRequiredResult extends Result { + /* Requests issued by the server that must be complete before the + * client can retry the original request. + */ + inputRequests?: InputRequests; + /* Request state to be passed back to the server when the client + * retries the original request. + * Note: The client must treat this as an opaque blob; it must not + * interpret it in any way. + */ + requestState?: string; +} + +/* Request parameter type that includes input responses and request state. + * These parameters may be included in any client-initiated request. + */ +export interface InputResponseRequestParams extends RequestParams { + /* New field to carry the responses for the server's requests from the + * InputRequiredResult message. For each key in the response's inputRequests + * field, the same key must appear here with the associated response. + */ + inputResponses?: InputResponses; + /* Request state passed back to the server from the client. + */ + requestState?: string; +} + +/* Cancellation */ +/** + * Parameters for a `notifications/cancelled` notification. + * + * @example User-requested cancellation + * {@includeCode ./examples/CancelledNotificationParams/user-requested-cancellation.json} + * + * @category `notifications/cancelled` + */ +export interface CancelledNotificationParams extends NotificationParams { + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId?: RequestId; + + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason?: string; +} + +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * @example User-requested cancellation + * {@includeCode ./examples/CancelledNotification/user-requested-cancellation.json} + * + * @category `notifications/cancelled` + */ +export interface CancelledNotification extends JSONRPCNotification { + method: "notifications/cancelled"; + params: CancelledNotificationParams; +} + +/* Discovery */ +/** + * A request from the client asking the server to advertise its supported + * protocol versions, capabilities, and other metadata. Servers **MUST** + * implement `server/discover`. Clients **MAY** call it but are not required + * to — version negotiation can also happen inline via per-request `_meta`. + * + * @example Discover request + * {@includeCode ./examples/DiscoverRequest/server-discover-request.json} + * + * @category `server/discover` + */ +export interface DiscoverRequest extends JSONRPCRequest { + method: "server/discover"; + params: RequestParams; +} + +/** + * The result returned by the server for a {@link DiscoverRequest | server/discover} request. + * + * @example Server capabilities discovery + * {@includeCode ./examples/DiscoverResult/server-capabilities-discovery.json} + * + * @category `server/discover` + */ +export interface DiscoverResult extends Result { + /** + * MCP Protocol Versions this server supports. The client should choose a + * version from this list for use in subsequent requests. + */ + supportedVersions: string[]; + /** + * The capabilities of the server. + */ + capabilities: ServerCapabilities; + /** + * Information about the server software implementation. + */ + serverInfo: Implementation; + /** + * Natural-language guidance describing the server and its features. + * + * This can be used by clients to improve an LLM's understanding of + * available tools (e.g., by including it in a system prompt). It should + * focus on information that helps the model use the server effectively + * and should not duplicate information already in tool descriptions. + */ + instructions?: string; +} + +/** + * A successful response from the server for a {@link DiscoverRequest | server/discover} request. + * + * @example Discover result response + * {@includeCode ./examples/DiscoverResultResponse/discover-result-response.json} + * + * @category `server/discover` + */ +export interface DiscoverResultResponse extends JSONRPCResultResponse { + result: DiscoverResult; +} + +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + * + * @category `server/discover` + */ +export interface ClientCapabilities { + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental?: { [key: string]: JSONObject }; + /** + * Present if the client supports listing roots. + * + * @example Roots — minimum baseline support + * {@includeCode ./examples/ClientCapabilities/roots-minimum-baseline-support.json} + */ + // eslint-disable-next-line @typescript-eslint/no-empty-object-type + roots?: {}; + /** + * Present if the client supports sampling from an LLM. + * + * @example Sampling — minimum baseline support + * {@includeCode ./examples/ClientCapabilities/sampling-minimum-baseline-support.json} + * + * @example Sampling — tool use support + * {@includeCode ./examples/ClientCapabilities/sampling-tool-use-support.json} + * + * @example Sampling — context inclusion support (soft-deprecated) + * {@includeCode ./examples/ClientCapabilities/sampling-context-inclusion-support-soft-deprecated.json} + */ + sampling?: { + /** + * Whether the client supports context inclusion via `includeContext` parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context?: JSONObject; + /** + * Whether the client supports tool use via `tools` and `toolChoice` parameters. + */ + tools?: JSONObject; + }; + /** + * Present if the client supports elicitation from the server. + * + * @example Elicitation — form and URL mode support + * {@includeCode ./examples/ClientCapabilities/elicitation-form-and-url-mode-support.json} + * + * @example Elicitation — form mode only (implicit) + * {@includeCode ./examples/ClientCapabilities/elicitation-form-only-implicit.json} + */ + elicitation?: { + form?: JSONObject; + url?: JSONObject; + }; + + /** + * Optional MCP extensions that the client supports. Keys are extension identifiers + * (e.g., "io.modelcontextprotocol/oauth-client-credentials"), and values are + * per-extension settings objects. An empty object indicates support with no settings. + * + * @example Extensions — UI extension with MIME type support + * {@includeCode ./examples/ClientCapabilities/extensions-ui-mime-types.json} + */ + extensions?: { [key: string]: JSONObject }; +} + +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + * + * @category `server/discover` + */ +export interface ServerCapabilities { + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental?: { [key: string]: JSONObject }; + /** + * Present if the server supports sending log messages to the client. + * + * @example Logging — minimum baseline support + * {@includeCode ./examples/ServerCapabilities/logging-minimum-baseline-support.json} + */ + logging?: JSONObject; + /** + * Present if the server supports argument autocompletion suggestions. + * + * @example Completions — minimum baseline support + * {@includeCode ./examples/ServerCapabilities/completions-minimum-baseline-support.json} + */ + completions?: JSONObject; + /** + * Present if the server offers any prompt templates. + * + * @example Prompts — minimum baseline support + * {@includeCode ./examples/ServerCapabilities/prompts-minimum-baseline-support.json} + * + * @example Prompts — list changed notifications + * {@includeCode ./examples/ServerCapabilities/prompts-list-changed-notifications.json} + */ + prompts?: { + /** + * Whether this server supports notifications for changes to the prompt list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any resources to read. + * + * @example Resources — minimum baseline support + * {@includeCode ./examples/ServerCapabilities/resources-minimum-baseline-support.json} + * + * @example Resources — subscription to individual resource updates (only) + * {@includeCode ./examples/ServerCapabilities/resources-subscription-to-individual-resource-updates-only.json} + * + * @example Resources — list changed notifications (only) + * {@includeCode ./examples/ServerCapabilities/resources-list-changed-notifications-only.json} + * + * @example Resources — all notifications + * {@includeCode ./examples/ServerCapabilities/resources-all-notifications.json} + */ + resources?: { + /** + * Whether this server supports subscribing to resource updates. + */ + subscribe?: boolean; + /** + * Whether this server supports notifications for changes to the resource list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any tools to call. + * + * @example Tools — minimum baseline support + * {@includeCode ./examples/ServerCapabilities/tools-minimum-baseline-support.json} + * + * @example Tools — list changed notifications + * {@includeCode ./examples/ServerCapabilities/tools-list-changed-notifications.json} + */ + tools?: { + /** + * Whether this server supports notifications for changes to the tool list. + */ + listChanged?: boolean; + }; + /** + * Optional MCP extensions that the server supports. Keys are extension identifiers + * (e.g., "io.modelcontextprotocol/apps"), and values are per-extension settings + * objects. An empty object indicates support with no settings. + * + * @example Extensions — UI extension support + * {@includeCode ./examples/ServerCapabilities/extensions-ui.json} + */ + extensions?: { [key: string]: JSONObject }; +} + +/** + * An optionally-sized icon that can be displayed in a user interface. + * + * @category Common Types + */ +export interface Icon { + /** + * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a + * `data:` URI with Base64-encoded image data. + * + * Consumers SHOULD take steps to ensure URLs serving icons are from the + * same domain as the client/server or a trusted domain. + * + * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain + * executable JavaScript. + * + * @format uri + */ + src: string; + + /** + * Optional MIME type override if the source MIME type is missing or generic. + * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. + */ + mimeType?: string; + + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes?: string[]; + + /** + * Optional specifier for the theme this icon is designed for. `"light"` indicates + * the icon is designed to be used with a light background, and `"dark"` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme?: "light" | "dark"; +} + +/** + * Base interface to add `icons` property. + * + * @internal + */ +export interface Icons { + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons?: Icon[]; +} + +/** + * Base interface for metadata with name (identifier) and title (display name) properties. + * + * @internal + */ +export interface BaseMetadata { + /** + * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). + */ + name: string; + + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for {@link Tool}, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title?: string; +} + +/** + * Describes the MCP implementation. + * + * @category `server/discover` + */ +export interface Implementation extends BaseMetadata, Icons { + /** + * The version of this implementation. + */ + version: string; + + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description?: string; + + /** + * An optional URL of the website for this implementation. + * + * @format uri + */ + websiteUrl?: string; +} + +/* Progress notifications */ + +/** + * Parameters for a {@link ProgressNotification | notifications/progress} notification. + * + * @example Progress message + * {@includeCode ./examples/ProgressNotificationParams/progress-message.json} + * + * @category `notifications/progress` + */ +export interface ProgressNotificationParams extends NotificationParams { + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressToken; + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + * + * @TJS-type number + */ + progress: number; + /** + * Total number of items to process (or total progress required), if known. + * + * @TJS-type number + */ + total?: number; + /** + * An optional message describing the current progress. + */ + message?: string; +} + +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @example Progress message + * {@includeCode ./examples/ProgressNotification/progress-message.json} + * + * @category `notifications/progress` + */ +export interface ProgressNotification extends JSONRPCNotification { + method: "notifications/progress"; + params: ProgressNotificationParams; +} + +/* Pagination */ +/** + * Common params for paginated requests. + * + * @example List request with cursor + * {@includeCode ./examples/PaginatedRequestParams/list-with-cursor.json} + * + * @category Common Types + */ +export interface PaginatedRequestParams extends RequestParams { + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor?: Cursor; +} + +/** @internal */ +export interface PaginatedRequest extends JSONRPCRequest { + params: PaginatedRequestParams; +} + +/** @internal */ +export interface PaginatedResult extends Result { + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor?: Cursor; +} + +/** + * A result that supports a time-to-live (TTL) hint for client-side caching. + * + * @internal + */ +export interface CacheableResult extends Result { + /** + * A hint from the server indicating how long (in milliseconds) the + * client MAY cache this response before re-fetching. Semantics are + * analogous to HTTP Cache-Control max-age. + * + * - If 0, The response SHOULD be considered immediately stale, + * The client MAY re-fetch every time the result is needed. + * - If positive, the client SHOULD consider the result fresh for this many + * milliseconds after receiving the response. + * + * @minimum 0 + */ + ttlMs: number; + + /** + * Indicates the intended scope of the cached response, analogous to HTTP + * `Cache-Control: public` vs `Cache-Control: private`. + * + * - `"public"`: Any client or intermediary (e.g., shared gateway, proxy) + * MAY cache the response and serve it to any user. + * - `"private"`: Only the requesting user's client MAY cache the response. + * Shared caches (e.g., multi-tenant gateways) MUST NOT serve a cached + * copy to a different user. + * + */ + cacheScope: "public" | "private"; +} + +/* Resources */ +/** + * Sent from the client to request a list of resources the server has. + * + * @example List resources request + * {@includeCode ./examples/ListResourcesRequest/list-resources-request.json} + * + * @category `resources/list` + */ +export interface ListResourcesRequest extends PaginatedRequest { + method: "resources/list"; +} + +/** + * The result returned by the server for a {@link ListResourcesRequest | resources/list} request. + * + * @example Resources list with cursor and TTL + * {@includeCode ./examples/ListResourcesResult/resources-list-with-cursor-and-ttl.json} + * + * @category `resources/list` + */ +export interface ListResourcesResult extends PaginatedResult, CacheableResult { + resources: Resource[]; +} + +/** + * A successful response from the server for a {@link ListResourcesRequest | resources/list} request. + * + * @example List resources result response + * {@includeCode ./examples/ListResourcesResultResponse/list-resources-result-response.json} + * + * @category `resources/list` + */ +export interface ListResourcesResultResponse extends JSONRPCResultResponse { + result: ListResourcesResult; +} + +/** + * Sent from the client to request a list of resource templates the server has. + * + * @example List resource templates request + * {@includeCode ./examples/ListResourceTemplatesRequest/list-resource-templates-request.json} + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesRequest extends PaginatedRequest { + method: "resources/templates/list"; +} + +/** + * The result returned by the server for a {@link ListResourceTemplatesRequest | resources/templates/list} request. + * + * @example Resource templates list with cursor and TTL + * {@includeCode ./examples/ListResourceTemplatesResult/resource-templates-list-with-cursor-and-ttl.json} + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesResult + extends PaginatedResult, CacheableResult { + resourceTemplates: ResourceTemplate[]; +} + +/** + * A successful response from the server for a {@link ListResourceTemplatesRequest | resources/templates/list} request. + * + * @example List resource templates result response + * {@includeCode ./examples/ListResourceTemplatesResultResponse/list-resource-templates-result-response.json} + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesResultResponse extends JSONRPCResultResponse { + result: ListResourceTemplatesResult; +} + +/** + * Common params for resource-related requests. + * + * @internal + */ +export interface ResourceRequestParams extends RequestParams { + /** + * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; +} + +/** + * Parameters for a `resources/read` request. + * + * @category `resources/read` + */ +export interface ReadResourceRequestParams + extends ResourceRequestParams, InputResponseRequestParams {} + +/** + * Sent from the client to the server, to read a specific resource URI. + * + * @example Read resource request + * {@includeCode ./examples/ReadResourceRequest/read-resource-request.json} + * + * @category `resources/read` + */ +export interface ReadResourceRequest extends JSONRPCRequest { + method: "resources/read"; + params: ReadResourceRequestParams; +} + +/** + * The result returned by the server for a {@link ReadResourceRequest | resources/read} request. + * + * @example File resource contents + * {@includeCode ./examples/ReadResourceResult/file-resource-contents.json} + * + * @category `resources/read` + */ +export interface ReadResourceResult extends CacheableResult { + contents: (TextResourceContents | BlobResourceContents)[]; +} + +/** + * A successful response from the server for a {@link ReadResourceRequest | resources/read} request. + * + * @example Read resource result response + * {@includeCode ./examples/ReadResourceResultResponse/read-resource-result-response.json} + * + * @example Read resource result response with TTL + * {@includeCode ./examples/ReadResourceResultResponse/read-resource-result-response-with-ttl.json} + * + * @category `resources/read` + */ +export interface ReadResourceResultResponse extends JSONRPCResultResponse { + result: ReadResourceResult | InputRequiredResult; +} + +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + * + * @example Resources list changed + * {@includeCode ./examples/ResourceListChangedNotification/resources-list-changed.json} + * + * @category `notifications/resources/list_changed` + */ +export interface ResourceListChangedNotification extends JSONRPCNotification { + method: "notifications/resources/list_changed"; + params?: NotificationParams; +} + +/** + * The set of notification types a client may opt in to on a + * {@link SubscriptionsListenRequest | subscriptions/listen} request. + * + * Each notification type is **opt-in**; the server **MUST NOT** send + * notification types the client has not explicitly requested here. + * + * @category `subscriptions/listen` + */ +export interface SubscriptionFilter { + /** + * If true, receive {@link ToolListChangedNotification | notifications/tools/list_changed}. + */ + toolsListChanged?: boolean; + /** + * If true, receive {@link PromptListChangedNotification | notifications/prompts/list_changed}. + */ + promptsListChanged?: boolean; + /** + * If true, receive {@link ResourceListChangedNotification | notifications/resources/list_changed}. + */ + resourcesListChanged?: boolean; + /** + * Subscribe to {@link ResourceUpdatedNotification | notifications/resources/updated} for these resource URIs. + * Replaces the former `resources/subscribe` RPC. + */ + resourceSubscriptions?: string[]; +} + +/** + * Parameters for a {@link SubscriptionsListenRequest | subscriptions/listen} request. + * + * @category `subscriptions/listen` + */ +export interface SubscriptionsListenRequestParams extends RequestParams { + /** + * The notifications the client opts in to on this stream. The server + * **MUST NOT** send notification types the client has not explicitly + * requested. + */ + notifications: SubscriptionFilter; +} + +/** + * Sent from the client to open a long-lived channel for receiving notifications + * outside the context of a specific request. Replaces the previous HTTP GET + * endpoint and ensures consistent behavior between HTTP and STDIO. + * + * @example Listen for tools and resource list changes + * {@includeCode ./examples/SubscriptionsListenRequest/listen-for-list-changes.json} + * + * @category `subscriptions/listen` + */ +export interface SubscriptionsListenRequest extends JSONRPCRequest { + method: "subscriptions/listen"; + params: SubscriptionsListenRequestParams; +} + +/** + * Parameters for a {@link SubscriptionsAcknowledgedNotification | notifications/subscriptions/acknowledged} notification. + * + * @category `notifications/subscriptions/acknowledged` + */ +export interface SubscriptionsAcknowledgedNotificationParams extends NotificationParams { + /** + * The subset of requested notification types the server agreed to honor. + * Only includes notification types the server actually supports; if the + * client requested an unsupported type (e.g., `promptsListChanged` when + * the server has no prompts), it is omitted from this set. + */ + notifications: SubscriptionFilter; +} + +/** + * Sent by the server as the first message on a + * {@link SubscriptionsListenRequest | subscriptions/listen} stream to acknowledge + * that the subscription has been established and to report which notification + * types it agreed to honor. + * + * @example Listen acknowledged + * {@includeCode ./examples/SubscriptionsAcknowledgedNotification/listen-acknowledged.json} + * + * @category `notifications/subscriptions/acknowledged` + */ +export interface SubscriptionsAcknowledgedNotification extends JSONRPCNotification { + method: "notifications/subscriptions/acknowledged"; + params: SubscriptionsAcknowledgedNotificationParams; +} + +/** + * Parameters for a `notifications/resources/updated` notification. + * + * @example File resource updated + * {@includeCode ./examples/ResourceUpdatedNotificationParams/file-resource-updated.json} + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotificationParams extends NotificationParams { + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + * + * @format uri + */ + uri: string; +} + +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This is only sent for resources the client opted in to via the `resourceSubscriptions` field of a {@link SubscriptionsListenRequest | subscriptions/listen} request. + * + * @example File resource updated notification + * {@includeCode ./examples/ResourceUpdatedNotification/file-resource-updated-notification.json} + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotification extends JSONRPCNotification { + method: "notifications/resources/updated"; + params: ResourceUpdatedNotificationParams; +} + +/** + * A known resource that the server is capable of reading. + * + * @example File resource with annotations + * {@includeCode ./examples/Resource/file-resource-with-annotations.json} + * + * @category `resources/list` + */ +export interface Resource extends BaseMetadata, Icons { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size?: number; + + _meta?: MetaObject; +} + +/** + * A template description for resources available on the server. + * + * @category `resources/templates/list` + */ +export interface ResourceTemplate extends BaseMetadata, Icons { + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + * + * @format uri-template + */ + uriTemplate: string; + + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + _meta?: MetaObject; +} + +/** + * The contents of a specific resource or sub-resource. + * + * @internal + */ +export interface ResourceContents { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + _meta?: MetaObject; +} + +/** + * @example Text file contents + * {@includeCode ./examples/TextResourceContents/text-file-contents.json} + * + * @category Content + */ +export interface TextResourceContents extends ResourceContents { + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string; +} + +/** + * @example Image file contents + * {@includeCode ./examples/BlobResourceContents/image-file-contents.json} + * + * @category Content + */ +export interface BlobResourceContents extends ResourceContents { + /** + * A base64-encoded string representing the binary data of the item. + * + * @format byte + */ + blob: string; +} + +/* Prompts */ +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + * + * @example List prompts request + * {@includeCode ./examples/ListPromptsRequest/list-prompts-request.json} + * + * @category `prompts/list` + */ +export interface ListPromptsRequest extends PaginatedRequest { + method: "prompts/list"; +} + +/** + * The result returned by the server for a {@link ListPromptsRequest | prompts/list} request. + * + * @example Prompts list with cursor and TTL + * {@includeCode ./examples/ListPromptsResult/prompts-list-with-cursor-and-ttl.json} + * + * @category `prompts/list` + */ +export interface ListPromptsResult extends PaginatedResult, CacheableResult { + prompts: Prompt[]; +} + +/** + * A successful response from the server for a {@link ListPromptsRequest | prompts/list} request. + * + * @example List prompts result response + * {@includeCode ./examples/ListPromptsResultResponse/list-prompts-result-response.json} + * + * @category `prompts/list` + */ +export interface ListPromptsResultResponse extends JSONRPCResultResponse { + result: ListPromptsResult; +} + +/** + * Parameters for a `prompts/get` request. + * + * @example Get code review prompt + * {@includeCode ./examples/GetPromptRequestParams/get-code-review-prompt.json} + * + * @category `prompts/get` + */ +export interface GetPromptRequestParams extends InputResponseRequestParams { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * Arguments to use for templating the prompt. + */ + arguments?: { [key: string]: string }; +} + +/** + * Used by the client to get a prompt provided by the server. + * + * @example Get prompt request + * {@includeCode ./examples/GetPromptRequest/get-prompt-request.json} + * + * @category `prompts/get` + */ +export interface GetPromptRequest extends JSONRPCRequest { + method: "prompts/get"; + params: GetPromptRequestParams; +} + +/** + * The result returned by the server for a {@link GetPromptRequest | prompts/get} request. + * + * @example Code review prompt + * {@includeCode ./examples/GetPromptResult/code-review-prompt.json} + * + * @category `prompts/get` + */ +export interface GetPromptResult extends Result { + /** + * An optional description for the prompt. + */ + description?: string; + messages: PromptMessage[]; +} + +/** + * A successful response from the server for a {@link GetPromptRequest | prompts/get} request. + * + * @example Get prompt result response + * {@includeCode ./examples/GetPromptResultResponse/get-prompt-result-response.json} + * + * @category `prompts/get` + */ +export interface GetPromptResultResponse extends JSONRPCResultResponse { + result: GetPromptResult | InputRequiredResult; +} + +/** + * A prompt or prompt template that the server offers. + * + * @category `prompts/list` + */ +export interface Prompt extends BaseMetadata, Icons { + /** + * An optional description of what this prompt provides + */ + description?: string; + + /** + * A list of arguments to use for templating the prompt. + */ + arguments?: PromptArgument[]; + + _meta?: MetaObject; +} + +/** + * Describes an argument that a prompt can accept. + * + * @category `prompts/list` + */ +export interface PromptArgument extends BaseMetadata { + /** + * A human-readable description of the argument. + */ + description?: string; + /** + * Whether this argument must be provided. + */ + required?: boolean; +} + +/** + * The sender or recipient of messages and data in a conversation. + * + * @category Common Types + */ +export type Role = "user" | "assistant"; + +/** + * Describes a message returned as part of a prompt. + * + * This is similar to {@link SamplingMessage}, but also supports the embedding of + * resources from the MCP server. + * + * @category `prompts/get` + */ +export interface PromptMessage { + role: Role; + content: ContentBlock; +} + +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of {@link ListResourcesRequest | resources/list} requests. + * + * @example File resource link + * {@includeCode ./examples/ResourceLink/file-resource-link.json} + * + * @category Content + */ +export interface ResourceLink extends Resource { + type: "resource_link"; +} + +/** + * The contents of a resource, embedded into a prompt or tool call result. + * + * It is up to the client how best to render embedded resources for the benefit + * of the LLM and/or the user. + * + * @example Embedded file resource with annotations + * {@includeCode ./examples/EmbeddedResource/embedded-file-resource-with-annotations.json} + * + * @category Content + */ +export interface EmbeddedResource { + type: "resource"; + resource: TextResourceContents | BlobResourceContents; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + _meta?: MetaObject; +} +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @example Prompts list changed + * {@includeCode ./examples/PromptListChangedNotification/prompts-list-changed.json} + * + * @category `notifications/prompts/list_changed` + */ +export interface PromptListChangedNotification extends JSONRPCNotification { + method: "notifications/prompts/list_changed"; + params?: NotificationParams; +} + +/* Tools */ +/** + * Sent from the client to request a list of tools the server has. + * + * @example List tools request + * {@includeCode ./examples/ListToolsRequest/list-tools-request.json} + * + * @category `tools/list` + */ +export interface ListToolsRequest extends PaginatedRequest { + method: "tools/list"; +} + +/** + * The result returned by the server for a {@link ListToolsRequest | tools/list} request. + * + * @example Tools list with cursor and TTL + * {@includeCode ./examples/ListToolsResult/tools-list-with-cursor-and-ttl.json} + * + * @category `tools/list` + */ +export interface ListToolsResult extends PaginatedResult, CacheableResult { + tools: Tool[]; +} + +/** + * A successful response from the server for a {@link ListToolsRequest | tools/list} request. + * + * @example List tools result response + * {@includeCode ./examples/ListToolsResultResponse/list-tools-result-response.json} + * + * @category `tools/list` + */ +export interface ListToolsResultResponse extends JSONRPCResultResponse { + result: ListToolsResult; +} + +/** + * The result returned by the server for a {@link CallToolRequest | tools/call} request. + * + * @example Result with unstructured text + * {@includeCode ./examples/CallToolResult/result-with-unstructured-text.json} + * + * @example Result with structured content + * {@includeCode ./examples/CallToolResult/result-with-structured-content.json} + * + * @example Invalid tool input error + * {@includeCode ./examples/CallToolResult/invalid-tool-input-error.json} + * + * @category `tools/call` + */ +export interface CallToolResult extends Result { + /** + * A list of content objects that represent the unstructured result of the tool call. + */ + content: ContentBlock[]; + + /** + * An optional JSON value that represents the structured result of the tool call. + * + * This can be any JSON value (object, array, string, number, boolean, or null) + * that conforms to the tool's outputSchema if one is defined. + */ + structuredContent?: unknown; + + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError?: boolean; +} + +/** + * A successful response from the server for a {@link CallToolRequest | tools/call} request. + * + * @example Call tool result response + * {@includeCode ./examples/CallToolResultResponse/call-tool-result-response.json} + * + * @category `tools/call` + */ +export interface CallToolResultResponse extends JSONRPCResultResponse { + result: CallToolResult | InputRequiredResult; +} + +/** + * Parameters for a `tools/call` request. + * + * @example `get_weather` tool call params + * {@includeCode ./examples/CallToolRequestParams/get-weather-tool-call-params.json} + * + * @example Tool call params with progress token + * {@includeCode ./examples/CallToolRequestParams/tool-call-params-with-progress-token.json} + * + * @category `tools/call` + */ +export interface CallToolRequestParams extends InputResponseRequestParams { + /** + * The name of the tool. + */ + name: string; + /** + * Arguments to use for the tool call. + */ + arguments?: { [key: string]: unknown }; +} + +/** + * Used by the client to invoke a tool provided by the server. + * + * @example Call tool request + * {@includeCode ./examples/CallToolRequest/call-tool-request.json} + * + * @category `tools/call` + */ +export interface CallToolRequest extends JSONRPCRequest { + method: "tools/call"; + params: CallToolRequestParams; +} + +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @example Tools list changed + * {@includeCode ./examples/ToolListChangedNotification/tools-list-changed.json} + * + * @category `notifications/tools/list_changed` + */ +export interface ToolListChangedNotification extends JSONRPCNotification { + method: "notifications/tools/list_changed"; + params?: NotificationParams; +} + +/** + * Additional properties describing a {@link Tool} to clients. + * + * NOTE: all properties in `ToolAnnotations` are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on `ToolAnnotations` + * received from untrusted servers. + * + * @category `tools/list` + */ +export interface ToolAnnotations { + /** + * A human-readable title for the tool. + */ + title?: string; + + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint?: boolean; + + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint?: boolean; + + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint?: boolean; + + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint?: boolean; +} + +/** + * Definition for a tool the client can call. + * + * @example With default 2020-12 input schema + * {@includeCode ./examples/Tool/with-default-2020-12-input-schema.json} + * + * @example With explicit draft-07 input schema + * {@includeCode ./examples/Tool/with-explicit-draft-07-input-schema.json} + * + * @example With no parameters + * {@includeCode ./examples/Tool/with-no-parameters.json} + * + * @example With output schema for structured content + * {@includeCode ./examples/Tool/with-output-schema-for-structured-content.json} + * + * @category `tools/list` + */ +export interface Tool extends BaseMetadata, Icons { + /** + * A human-readable description of the tool. + * + * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * A JSON Schema object defining the expected parameters for the tool. + * + * Tool arguments are always JSON objects, so `type: "object"` is required at the root. + * Beyond that, any JSON Schema 2020-12 keyword may appear alongside `type` — including + * composition keywords (`oneOf`, `anyOf`, `allOf`, `not`), conditional keywords + * (`if`/`then`/`else`), reference keywords (`$ref`, `$defs`, `$anchor`), and any other + * standard validation or annotation keywords. + * + * Defaults to JSON Schema 2020-12 when no explicit `$schema` is provided. + */ + inputSchema: { $schema?: string; type: "object"; [key: string]: unknown }; + + /** + * An optional JSON Schema object defining the structure of the tool's output returned in + * the structuredContent field of a {@link CallToolResult}. This can be any valid JSON Schema 2020-12. + * + * Defaults to JSON Schema 2020-12 when no explicit `$schema` is provided. + */ + outputSchema?: { $schema?: string; [key: string]: unknown }; + + /** + * Optional additional tool information. + * + * Display name precedence order is: `title`, `annotations.title`, then `name`. + */ + annotations?: ToolAnnotations; + + _meta?: MetaObject; +} + +/* Logging */ + +/** + * Parameters for a `notifications/message` notification. + * + * @example Log database connection failed + * {@includeCode ./examples/LoggingMessageNotificationParams/log-database-connection-failed.json} + * + * @category `notifications/message` + */ +export interface LoggingMessageNotificationParams extends NotificationParams { + /** + * The severity of this log message. + */ + level: LoggingLevel; + /** + * An optional name of the logger issuing this message. + */ + logger?: string; + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown; +} + +/** + * JSONRPCNotification of a log message passed from server to client. The client opts in by setting `"io.modelcontextprotocol/logLevel"` in a request's `_meta`. + * + * @example Log database connection failed + * {@includeCode ./examples/LoggingMessageNotification/log-database-connection-failed.json} + * + * @category `notifications/message` + */ +export interface LoggingMessageNotification extends JSONRPCNotification { + method: "notifications/message"; + params: LoggingMessageNotificationParams; +} + +/** + * The severity of a log message. + * + * These map to syslog message severities, as specified in RFC-5424: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + * + * @category Common Types + */ +export type LoggingLevel = + | "debug" + | "info" + | "notice" + | "warning" + | "error" + | "critical" + | "alert" + | "emergency"; + +/* Sampling */ +/** + * Parameters for a `sampling/createMessage` request. + * + * @example Basic request + * {@includeCode ./examples/CreateMessageRequestParams/basic-request.json} + * + * @example Request with tools + * {@includeCode ./examples/CreateMessageRequestParams/request-with-tools.json} + * + * @example Follow-up request with tool results + * {@includeCode ./examples/CreateMessageRequestParams/follow-up-with-tool-results.json} + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequestParams { + messages: SamplingMessage[]; + /** + * The server's preferences for which model to select. The client MAY ignore these preferences. + */ + modelPreferences?: ModelPreferences; + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt?: string; + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is `"none"`. Values `"thisServer"` and `"allServers"` are soft-deprecated. Servers SHOULD only use these values if the client + * declares {@link ClientCapabilities.sampling.context}. These values may be removed in future spec releases. + */ + includeContext?: "none" | "thisServer" | "allServers"; + /** + * @TJS-type number + */ + temperature?: number; + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number; + stopSequences?: string[]; + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata?: JSONObject; + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but {@link ClientCapabilities.sampling.tools} is not declared. + */ + tools?: Tool[]; + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but {@link ClientCapabilities.sampling.tools} is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice?: ToolChoice; +} + +/** + * Controls tool selection behavior for sampling requests. + * + * @category `sampling/createMessage` + */ +export interface ToolChoice { + /** + * Controls the tool use ability of the model: + * - `"auto"`: Model decides whether to use tools (default) + * - `"required"`: Model MUST use at least one tool before completing + * - `"none"`: Model MUST NOT use any tools + */ + mode?: "auto" | "required" | "none"; +} + +/** + * 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. + * + * @example Sampling request + * {@includeCode ./examples/CreateMessageRequest/sampling-request.json} + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequest { + method: "sampling/createMessage"; + params: CreateMessageRequestParams; +} + +/** + * The result returned by the client for a {@link CreateMessageRequest | sampling/createMessage} request. + * The client should inform the user before returning the sampled message, to allow them + * to inspect the response (human in the loop) and decide whether to allow the server to see it. + * + * @example Text response + * {@includeCode ./examples/CreateMessageResult/text-response.json} + * + * @example Tool use response + * {@includeCode ./examples/CreateMessageResult/tool-use-response.json} + * + * @example Final response after tool use + * {@includeCode ./examples/CreateMessageResult/final-response.json} + * + * @category `sampling/createMessage` + */ +export interface CreateMessageResult extends SamplingMessage { + /** + * The name of the model that generated the message. + */ + model: string; + + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - `"endTurn"`: Natural end of the assistant's turn + * - `"stopSequence"`: A stop sequence was encountered + * - `"maxTokens"`: Maximum token limit was reached + * - `"toolUse"`: The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason?: "endTurn" | "stopSequence" | "maxTokens" | "toolUse" | string; +} + +/** + * Describes a message issued to or received from an LLM API. + * + * @example Single content block + * {@includeCode ./examples/SamplingMessage/single-content-block.json} + * + * @example Multiple content blocks + * {@includeCode ./examples/SamplingMessage/multiple-content-blocks.json} + * + * @category `sampling/createMessage` + */ +export interface SamplingMessage { + role: Role; + content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; + _meta?: MetaObject; +} + +/** + * @category `sampling/createMessage` + */ +export type SamplingMessageContentBlock = + | TextContent + | ImageContent + | AudioContent + | ToolUseContent + | ToolResultContent; + +/** + * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed + * + * @category Common Types + */ +export interface Annotations { + /** + * Describes who the intended audience of this object or data is. + * + * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). + */ + audience?: Role[]; + + /** + * Describes how important this data is for operating the server. + * + * A value of 1 means "most important," and indicates that the data is + * effectively required, while 0 means "least important," and indicates that + * the data is entirely optional. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + priority?: number; + + /** + * The moment the resource was last modified, as an ISO 8601 formatted string. + * + * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). + * + * Examples: last activity timestamp in an open file, timestamp when the resource + * was attached, etc. + */ + lastModified?: string; +} + +/** + * @category Content + */ +export type ContentBlock = + | TextContent + | ImageContent + | AudioContent + | ResourceLink + | EmbeddedResource; + +/** + * Text provided to or from an LLM. + * + * @example Text content + * {@includeCode ./examples/TextContent/text-content.json} + * + * @category Content + */ +export interface TextContent { + type: "text"; + + /** + * The text content of the message. + */ + text: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + _meta?: MetaObject; +} + +/** + * An image provided to or from an LLM. + * + * @example `image/png` content with annotations + * {@includeCode ./examples/ImageContent/image-png-content-with-annotations.json} + * + * @category Content + */ +export interface ImageContent { + type: "image"; + + /** + * The base64-encoded image data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + _meta?: MetaObject; +} + +/** + * Audio provided to or from an LLM. + * + * @example `audio/wav` content + * {@includeCode ./examples/AudioContent/audio-wav-content.json} + * + * @category Content + */ +export interface AudioContent { + type: "audio"; + + /** + * The base64-encoded audio data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + _meta?: MetaObject; +} + +/** + * A request from the assistant to call a tool. + * + * @example `get_weather` tool use + * {@includeCode ./examples/ToolUseContent/get-weather-tool-use.json} + * + * @category `sampling/createMessage` + */ +export interface ToolUseContent { + type: "tool_use"; + + /** + * A unique identifier for this tool use. + * + * This ID is used to match tool results to their corresponding tool uses. + */ + id: string; + + /** + * The name of the tool to call. + */ + name: string; + + /** + * The arguments to pass to the tool, conforming to the tool's input schema. + */ + input: { [key: string]: unknown }; + + /** + * Optional metadata about the tool use. Clients SHOULD preserve this field when + * including tool uses in subsequent sampling requests to enable caching optimizations. + */ + _meta?: MetaObject; +} + +/** + * The result of a tool use, provided by the user back to the assistant. + * + * @example `get_weather` tool result + * {@includeCode ./examples/ToolResultContent/get-weather-tool-result.json} + * + * @category `sampling/createMessage` + */ +export interface ToolResultContent { + type: "tool_result"; + + /** + * The ID of the tool use this result corresponds to. + * + * This MUST match the ID from a previous {@link ToolUseContent}. + */ + toolUseId: string; + + /** + * The unstructured result content of the tool use. + * + * This has the same format as {@link CallToolResult.content} and can include text, images, + * audio, resource links, and embedded resources. + */ + content: ContentBlock[]; + + /** + * An optional structured result value. + * + * This can be any JSON value (object, array, string, number, boolean, or null). + * If the tool defined an {@link Tool.outputSchema}, this SHOULD conform to that schema. + */ + structuredContent?: unknown; + + /** + * Whether the tool use resulted in an error. + * + * If true, the content typically describes the error that occurred. + * Default: false + */ + isError?: boolean; + + /** + * Optional metadata about the tool result. Clients SHOULD preserve this field when + * including tool results in subsequent sampling requests to enable caching optimizations. + */ + _meta?: MetaObject; +} + +/** + * The server's preferences for model selection, requested of the client during sampling. + * + * Because LLMs can vary along multiple dimensions, choosing the "best" model is + * rarely straightforward. Different models excel in different areas—some are + * faster but less capable, others are more capable but more expensive, and so + * on. This interface allows servers to express their priorities across multiple + * dimensions to help clients make an appropriate selection for their use case. + * + * These preferences are always advisory. The client MAY ignore them. It is also + * up to the client to decide how to interpret these preferences and how to + * balance them against other considerations. + * + * @example With hints and priorities + * {@includeCode ./examples/ModelPreferences/with-hints-and-priorities.json} + * + * @category `sampling/createMessage` + */ +export interface ModelPreferences { + /** + * Optional hints to use for model selection. + * + * If multiple hints are specified, the client MUST evaluate them in order + * (such that the first match is taken). + * + * The client SHOULD prioritize these hints over the numeric priorities, but + * MAY still use the priorities to select from ambiguous matches. + */ + hints?: ModelHint[]; + + /** + * How much to prioritize cost when selecting a model. A value of 0 means cost + * is not important, while a value of 1 means cost is the most important + * factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + costPriority?: number; + + /** + * How much to prioritize sampling speed (latency) when selecting a model. A + * value of 0 means speed is not important, while a value of 1 means speed is + * the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + speedPriority?: number; + + /** + * How much to prioritize intelligence and capabilities when selecting a + * model. A value of 0 means intelligence is not important, while a value of 1 + * means intelligence is the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + intelligencePriority?: number; +} + +/** + * Hints to use for model selection. + * + * Keys not declared here are currently left unspecified by the spec and are up + * to the client to interpret. + * + * @category `sampling/createMessage` + */ +export interface ModelHint { + /** + * A hint for a model name. + * + * The client SHOULD treat this as a substring of a model name; for example: + * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` + * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. + * - `claude` should match any Claude model + * + * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: + * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` + */ + name?: string; +} + +/* Autocomplete */ +/** + * Parameters for a `completion/complete` request. + * + * @category `completion/complete` + * + * @example Prompt argument completion + * {@includeCode ./examples/CompleteRequestParams/prompt-argument-completion.json} + * + * @example Prompt argument completion with context + * {@includeCode ./examples/CompleteRequestParams/prompt-argument-completion-with-context.json} + */ +export interface CompleteRequestParams extends RequestParams { + ref: PromptReference | ResourceTemplateReference; + /** + * The argument's information + */ + argument: { + /** + * The name of the argument + */ + name: string; + /** + * The value of the argument to use for completion matching. + */ + value: string; + }; + + /** + * Additional, optional context for completions + */ + context?: { + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments?: { [key: string]: string }; + }; +} + +/** + * A request from the client to the server, to ask for completion options. + * + * @example Completion request + * {@includeCode ./examples/CompleteRequest/completion-request.json} + * + * @category `completion/complete` + */ +export interface CompleteRequest extends JSONRPCRequest { + method: "completion/complete"; + params: CompleteRequestParams; +} + +/** + * The result returned by the server for a {@link CompleteRequest | completion/complete} request. + * + * @category `completion/complete` + * + * @example Single completion value + * {@includeCode ./examples/CompleteResult/single-completion-value.json} + * + * @example Multiple completion values with more available + * {@includeCode ./examples/CompleteResult/multiple-completion-values-with-more-available.json} + */ +export interface CompleteResult extends Result { + completion: { + /** + * An array of completion values. Must not exceed 100 items. + * + * @maxItems 100 + */ + values: string[]; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total?: number; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore?: boolean; + }; +} + +/** + * A successful response from the server for a {@link CompleteRequest | completion/complete} request. + * + * @example Completion result response + * {@includeCode ./examples/CompleteResultResponse/completion-result-response.json} + * + * @category `completion/complete` + */ +export interface CompleteResultResponse extends JSONRPCResultResponse { + result: CompleteResult; +} + +/** + * A reference to a resource or resource template definition. + * + * @category `completion/complete` + */ +export interface ResourceTemplateReference { + type: "ref/resource"; + /** + * The URI or URI template of the resource. + * + * @format uri-template + */ + uri: string; +} + +/** + * Identifies a prompt. + * + * @category `completion/complete` + */ +export interface PromptReference extends BaseMetadata { + type: "ref/prompt"; +} + +/* Roots */ +/** + * Sent from the server to request a list of root URIs from the client. Roots allow + * servers to ask for specific directories or files to operate on. A common example + * for roots is providing a set of repositories or directories a server should operate + * on. + * + * This request is typically used when the server needs to understand the file system + * structure or access specific locations that the client has permission to read from. + * + * @example List roots request + * {@includeCode ./examples/ListRootsRequest/list-roots-request.json} + * + * @category `roots/list` + */ +export interface ListRootsRequest { + method: "roots/list"; + params?: RequestParams; +} + +/** + * The result returned by the client for a {@link ListRootsRequest | roots/list} request. + * This result contains an array of {@link Root} objects, each representing a root directory + * or file that the server can operate on. + * + * @example Single root directory + * {@includeCode ./examples/ListRootsResult/single-root-directory.json} + * + * @example Multiple root directories + * {@includeCode ./examples/ListRootsResult/multiple-root-directories.json} + * + * @category `roots/list` + */ +export interface ListRootsResult { + roots: Root[]; +} + +/** + * Represents a root directory or file that the server can operate on. + * + * @example Project directory root + * {@includeCode ./examples/Root/project-directory.json} + * + * @category `roots/list` + */ +export interface Root { + /** + * The URI identifying the root. This *must* start with `file://` for now. + * This restriction may be relaxed in future versions of the protocol to allow + * other URI schemes. + * + * @format uri + */ + uri: string; + /** + * An optional name for the root. This can be used to provide a human-readable + * identifier for the root, which may be useful for display purposes or for + * referencing the root in other parts of the application. + */ + name?: string; + + _meta?: MetaObject; +} + +/** + * The parameters for a request to elicit non-sensitive information from the user via a form in the client. + * + * @example Elicit single field + * {@includeCode ./examples/ElicitRequestFormParams/elicit-single-field.json} + * + * @example Elicit multiple fields + * {@includeCode ./examples/ElicitRequestFormParams/elicit-multiple-fields.json} + * + * @category `elicitation/create` + */ +export interface ElicitRequestFormParams { + /** + * The elicitation mode. + */ + mode?: "form"; + + /** + * The message to present to the user describing what information is being requested. + */ + message: string; + + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: { + $schema?: string; + type: "object"; + properties: { + [key: string]: PrimitiveSchemaDefinition; + }; + required?: string[]; + }; +} + +/** + * The parameters for a request to elicit information from the user via a URL in the client. + * + * @example Elicit sensitive data + * {@includeCode ./examples/ElicitRequestURLParams/elicit-sensitive-data.json} + * + * @category `elicitation/create` + */ +export interface ElicitRequestURLParams { + /** + * The elicitation mode. + */ + mode: "url"; + + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string; + + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string; + + /** + * The URL that the user should navigate to. + * + * @format uri + */ + url: string; +} + +/** + * The parameters for a request to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export type ElicitRequestParams = + | ElicitRequestFormParams + | ElicitRequestURLParams; + +/** + * A request from the server to elicit additional information from the user via the client. + * + * @example Elicitation request + * {@includeCode ./examples/ElicitRequest/elicitation-request.json} + * + * @category `elicitation/create` + */ +export interface ElicitRequest { + method: "elicitation/create"; + params: ElicitRequestParams; +} + +/** + * Restricted schema definitions that only allow primitive types + * without nested objects or arrays. + * + * @category `elicitation/create` + */ +export type PrimitiveSchemaDefinition = + | StringSchema + | NumberSchema + | BooleanSchema + | EnumSchema; + +/** + * @example Email input schema + * {@includeCode ./examples/StringSchema/email-input-schema.json} + * + * @category `elicitation/create` + */ +export interface StringSchema { + type: "string"; + title?: string; + description?: string; + minLength?: number; + maxLength?: number; + format?: "email" | "uri" | "date" | "date-time"; + default?: string; +} + +/** + * @example Number input schema + * {@includeCode ./examples/NumberSchema/number-input-schema.json} + * + * @category `elicitation/create` + */ +export interface NumberSchema { + type: "number" | "integer"; + title?: string; + description?: string; + minimum?: number; + maximum?: number; + default?: number; +} + +/** + * @example Boolean input schema + * {@includeCode ./examples/BooleanSchema/boolean-input-schema.json} + * + * @category `elicitation/create` + */ +export interface BooleanSchema { + type: "boolean"; + title?: string; + description?: string; + default?: boolean; +} + +/** + * Schema for single-selection enumeration without display titles for options. + * + * @example Color select schema + * {@includeCode ./examples/UntitledSingleSelectEnumSchema/color-select-schema.json} + * + * @category `elicitation/create` + */ +export interface UntitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum values to choose from. + */ + enum: string[]; + /** + * Optional default value. + */ + default?: string; +} + +/** + * Schema for single-selection enumeration with display titles for each option. + * + * @example Titled color select schema + * {@includeCode ./examples/TitledSingleSelectEnumSchema/titled-color-select-schema.json} + * + * @category `elicitation/create` + */ +export interface TitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum options with values and display labels. + */ + oneOf: Array<{ + /** + * The enum value. + */ + const: string; + /** + * Display label for this option. + */ + title: string; + }>; + /** + * Optional default value. + */ + default?: string; +} + +/** + * @category `elicitation/create` + */ +// Combined single selection enumeration +export type SingleSelectEnumSchema = + | UntitledSingleSelectEnumSchema + | TitledSingleSelectEnumSchema; + +/** + * Schema for multiple-selection enumeration without display titles for options. + * + * @example Color multi-select schema + * {@includeCode ./examples/UntitledMultiSelectEnumSchema/color-multi-select-schema.json} + * + * @category `elicitation/create` + */ +export interface UntitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for the array items. + */ + items: { + type: "string"; + /** + * Array of enum values to choose from. + */ + enum: string[]; + }; + /** + * Optional default value. + */ + default?: string[]; +} + +/** + * Schema for multiple-selection enumeration with display titles for each option. + * + * @example Titled color multi-select schema + * {@includeCode ./examples/TitledMultiSelectEnumSchema/titled-color-multi-select-schema.json} + * + * @category `elicitation/create` + */ +export interface TitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for array items with enum options and display labels. + */ + items: { + /** + * Array of enum options with values and display labels. + */ + anyOf: Array<{ + /** + * The constant enum value. + */ + const: string; + /** + * Display title for this option. + */ + title: string; + }>; + }; + /** + * Optional default value. + */ + default?: string[]; +} + +/** + * @category `elicitation/create` + */ +// Combined multiple selection enumeration +export type MultiSelectEnumSchema = + | UntitledMultiSelectEnumSchema + | TitledMultiSelectEnumSchema; + +/** + * Use {@link TitledSingleSelectEnumSchema} instead. + * This interface will be removed in a future version. + * + * @category `elicitation/create` + */ +export interface LegacyTitledEnumSchema { + type: "string"; + title?: string; + description?: string; + enum: string[]; + /** + * (Legacy) Display names for enum values. + * Non-standard according to JSON schema 2020-12. + */ + enumNames?: string[]; + default?: string; +} + +/** + * @category `elicitation/create` + */ +// Union type for all enum schemas +export type EnumSchema = + | SingleSelectEnumSchema + | MultiSelectEnumSchema + | LegacyTitledEnumSchema; + +/** + * The result returned by the client for an {@link ElicitRequest| elicitation/create} request. + * + * @example Input single field + * {@includeCode ./examples/ElicitResult/input-single-field.json} + * + * @example Input multiple fields + * {@includeCode ./examples/ElicitResult/input-multiple-fields.json} + * + * @example Accept URL mode (no content) + * {@includeCode ./examples/ElicitResult/accept-url-mode-no-content.json} + * + * @category `elicitation/create` + */ +export interface ElicitResult { + /** + * The user action in response to the elicitation. + * - `"accept"`: User submitted the form/confirmed the action + * - `"decline"`: User explicitly declined the action + * - `"cancel"`: User dismissed without making an explicit choice + */ + action: "accept" | "decline" | "cancel"; + + /** + * The submitted form data, only present when action is `"accept"` and mode was `"form"`. + * Contains values matching the requested schema. + * Omitted for out-of-band mode responses. + */ + content?: { [key: string]: string | number | boolean | string[] }; +} + +/** + * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request. + * + * @example Elicitation complete + * {@includeCode ./examples/ElicitationCompleteNotification/elicitation-complete.json} + * + * @category `notifications/elicitation/complete` + */ +export interface ElicitationCompleteNotification extends JSONRPCNotification { + method: "notifications/elicitation/complete"; + params: { + /** + * The ID of the elicitation that completed. + */ + elicitationId: string; + }; +} + +/* Client messages */ +/** @internal */ +export type ClientRequest = + | DiscoverRequest + | CompleteRequest + | GetPromptRequest + | ListPromptsRequest + | ListResourcesRequest + | ListResourceTemplatesRequest + | ReadResourceRequest + | SubscriptionsListenRequest + | CallToolRequest + | ListToolsRequest; + +/** @internal */ +export type ClientNotification = CancelledNotification | ProgressNotification; + +/** @internal */ +export type ClientResult = EmptyResult; + +/* Server messages */ + +/** @internal */ +export type ServerNotification = + | CancelledNotification + | ProgressNotification + | LoggingMessageNotification + | ResourceUpdatedNotification + | ResourceListChangedNotification + | ToolListChangedNotification + | PromptListChangedNotification + | ElicitationCompleteNotification + | SubscriptionsAcknowledgedNotification; + +/** @internal */ +export type ServerResult = + | EmptyResult + | DiscoverResult + | CompleteResult + | GetPromptResult + | ListPromptsResult + | ListResourceTemplatesResult + | ListResourcesResult + | ReadResourceResult + | CallToolResult + | ListToolsResult + | InputRequiredResult; diff --git a/src/types.ts b/src/types.ts index 8052eb1e..6c6376e5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,5 @@ +import type { RunContext } from './connection'; + export type CheckStatus = | 'SUCCESS' | 'FAILURE' @@ -109,7 +111,7 @@ export interface ClientScenario { name: string; description: string; source: ScenarioSource; - run(serverUrl: string): Promise; + run(ctx: RunContext): Promise; } export interface ClientScenarioForAuthorizationServer {