diff --git a/examples/servers/typescript/everything-server.ts b/examples/servers/typescript/everything-server.ts index c76c1f56..85859270 100644 --- a/examples/servers/typescript/everything-server.ts +++ b/examples/servers/typescript/everything-server.ts @@ -36,7 +36,7 @@ import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-sc import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import cors from 'cors'; -import { randomUUID, createHmac } from 'crypto'; +import { randomUUID, createHmac, createHash } from 'crypto'; // Server state const resourceSubscriptions = new Set(); @@ -1216,6 +1216,55 @@ function notifyListenStreams( } } +// SEP-2127 Server Card at the reserved location, /server-card. +// Registered before the global CORS middleware: the card has its own CORS rules +// (ext-server-card discovery.md § CORS Requirements), and its values mirror what +// server/discover reports, so the card does not contradict the live server. +const SERVER_CARD_MEDIA_TYPE = 'application/mcp-server-card+json'; +function serverCardBody(req: { + protocol: string; + get(name: string): string | undefined; +}): string { + const origin = `${req.protocol}://${req.get('host')}`; + return JSON.stringify({ + $schema: + 'https://static.modelcontextprotocol.io/schemas/v1/server-card.schema.json', + name: 'io.modelcontextprotocol/everything-server', + version: '1.0.0', + description: 'MCP conformance everything-server', + remotes: [ + { + type: 'streamable-http', + url: `${origin}/mcp`, + supportedProtocolVersions: ['2026-07-28'] + } + ] + }); +} +app.options('/mcp/server-card', (_req, res) => { + res.set({ + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET', + 'Access-Control-Allow-Headers': 'Content-Type, If-None-Match' + }); + res.sendStatus(204); +}); +app.get('/mcp/server-card', (req, res) => { + const body = serverCardBody(req); + const etag = `"${createHash('sha256').update(body).digest('hex').slice(0, 32)}"`; + res.set({ + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Expose-Headers': 'ETag', + 'Cache-Control': 'public, max-age=3600', + ETag: etag + }); + if (req.get('if-none-match') === etag) { + res.status(304).end(); + return; + } + res.type(SERVER_CARD_MEDIA_TYPE).send(body); +}); + // Configure CORS to expose Mcp-Session-Id header for browser-based clients app.use( cors({ diff --git a/examples/servers/typescript/sep-2127-server-card-fixture.ts b/examples/servers/typescript/sep-2127-server-card-fixture.ts new file mode 100644 index 00000000..dbc10cea --- /dev/null +++ b/examples/servers/typescript/sep-2127-server-card-fixture.ts @@ -0,0 +1,148 @@ +#!/usr/bin/env node + +/** + * Fixture for the SEP-2127 Server Card scenario (sep-2127-server-card). + * Five MCP endpoints, each answering server/discover, each with a different card: + * + * - /good/mcp — a correct card, served correctly, that agrees with + * server/discover on every field the scenario compares. + * - /html/mcp — the card location answers 200 with an HTML page, no + * CORS and no Cache-Control (a catch-all page, not a card). + * Express still adds an ETag and answers If-None-Match. + * - /contradict/mcp — a valid card with the required CORS headers that + * contradicts server/discover: transport, protocol + * versions, version, reverse-DNS name, title, description. + * - /none/mcp — no card (404): the optional feature is not offered. + * - /auth/mcp — 401 at the card location: also not a hosted card. + * + * Run: PORT=3000 npx tsx sep-2127-server-card-fixture.ts + */ + +import express from 'express'; + +const app = express(); +app.use(express.json()); + +const SERVER_INFO = { + good: { + name: 'com.example/good-server', + version: '1.0.0', + title: 'Good Server', + description: 'A card that agrees with its server' + }, + html: { name: 'sep-2127-html', version: '1.0.0' }, + contradict: { + name: 'com.example/live-server', + version: '2.0.0', + title: 'Live Server', + description: 'What the server says about itself' + }, + none: { name: 'sep-2127-none', version: '1.0.0' } +} as const; + +for (const [prefix, serverInfo] of Object.entries(SERVER_INFO)) { + app.post(`/${prefix}/mcp`, (req, res) => { + const id = req.body?.id ?? null; + if (req.body?.method !== 'server/discover') { + res.status(404).json({ + jsonrpc: '2.0', + id, + error: { code: -32601, message: 'Method not found' } + }); + return; + } + res.json({ + jsonrpc: '2.0', + id, + result: { + supportedVersions: ['2026-07-28'], + capabilities: {}, + resultType: 'complete', + ttlMs: 0, + cacheScope: 'public', + _meta: { 'io.modelcontextprotocol/serverInfo': serverInfo } + } + }); + }); +} + +/** Serve a card at //mcp/server-card with the CORS and caching headers the spec asks for. */ +function serveCard(prefix: string, card: (origin: string) => object) { + const path = `/${prefix}/mcp/server-card`; + const etag = `"sep-2127-${prefix}"`; + app.options(path, (_req, res) => { + res.set({ + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET', + 'Access-Control-Allow-Headers': 'Content-Type, If-None-Match' + }); + res.sendStatus(204); + }); + app.get(path, (req, res) => { + res.set({ + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Expose-Headers': 'ETag', + 'Cache-Control': 'public, max-age=3600', + ETag: etag + }); + if (req.get('if-none-match') === etag) { + res.status(304).end(); + return; + } + const origin = `${req.protocol}://${req.get('host')}`; + res + .type('application/mcp-server-card+json') + .send(JSON.stringify(card(origin))); + }); +} + +const SCHEMA = + 'https://static.modelcontextprotocol.io/schemas/v1/server-card.schema.json'; + +// A card that agrees with server/discover. +serveCard('good', (origin) => ({ + $schema: SCHEMA, + ...SERVER_INFO.good, + remotes: [ + { + type: 'streamable-http', + url: `${origin}/good/mcp`, + supportedProtocolVersions: ['2026-07-28'] + } + ] +})); + +// A well-formed card, served correctly, that contradicts the live server. +serveCard('contradict', (origin) => ({ + $schema: SCHEMA, + name: 'com.example/card-says-otherwise', + version: '1.0.0', + title: 'Card Title', + description: 'A card that contradicts its server', + remotes: [ + { + type: 'sse', + url: `${origin}/contradict/mcp`, + supportedProtocolVersions: ['2025-03-26', '2026-07-28'] + } + ] +})); + +// A catch-all web page at the card location: no card, no CORS, no Cache-Control. +app.get('/html/mcp/server-card', (_req, res) => { + res + .type('text/html') + .send('Not a card

Welcome

'); +}); + +// An auth challenge at the card location: not a hosted card, so the checks skip. +app.get('/auth/mcp/server-card', (_req, res) => { + res.status(401).set('WWW-Authenticate', 'Bearer').end(); +}); + +const PORT = parseInt(process.env.PORT || '3000', 10); +app.listen(PORT, () => { + console.log( + `SEP-2127 server card fixture running on http://localhost:${PORT}` + ); +}); diff --git a/src/scenarios/index.ts b/src/scenarios/index.ts index ff377f54..300d7365 100644 --- a/src/scenarios/index.ts +++ b/src/scenarios/index.ts @@ -63,6 +63,7 @@ import { import { SkillsDirectoryReadScenario } from './server/skills/directory'; import { SkillsEnumerationScenario } from './server/skills/enumeration'; import { SkillsManifestScenario } from './server/skills/manifest'; +import { ServerCardScenario } from './server/server-card'; import { PromptsListScenario, @@ -166,7 +167,12 @@ const pendingClientScenariosList: ClientScenario[] = [ // `npm start -- server --scenario sep-2640-skills-* --url `. new SkillsDirectoryReadScenario(), new SkillsEnumerationScenario(), - new SkillsManifestScenario() + new SkillsManifestScenario(), + + // SEP-2127 Server Card extension. Pending so a default run does not grade an + // optional extension; targeted runs use + // `npm start -- server --scenario sep-2127-server-card --url `. + new ServerCardScenario() ]; // All client scenarios @@ -224,6 +230,10 @@ const allClientScenariosList: ClientScenario[] = [ new SkillsEnumerationScenario(), new SkillsManifestScenario(), + // Server Card extension (SEP-2127). Hosting a card is optional (MAY): the + // checks SKIP unless /server-card answers 2xx. + new ServerCardScenario(), + // Prompts scenarios new PromptsListScenario(), new PromptsGetSimpleScenario(), diff --git a/src/scenarios/server/negative.test.ts b/src/scenarios/server/negative.test.ts index 746cf9ce..1737ec56 100644 --- a/src/scenarios/server/negative.test.ts +++ b/src/scenarios/server/negative.test.ts @@ -6,6 +6,7 @@ import path from 'path'; import { DNSRebindingProtectionScenario } from './dns-rebinding'; import { ResourcesNotFoundErrorScenario } from './resources'; import { CachingScenario } from './caching'; +import { ServerCardScenario } from './server-card'; import { ToolsListScenario } from './tools'; import { JsonSchema2020_12Scenario, @@ -519,4 +520,112 @@ describe('Server scenario negative tests', () => { ); }); }); + + describe('sep-2127-server-card', () => { + let serverProcess: ChildProcess | null = null; + const PORT = 3010; + const base = `http://localhost:${PORT}`; + const statusOf = (checks: { id: string; status: string }[], id: string) => + checks.find((c) => c.id === id)?.status; + const run = (url: string) => + new ServerCardScenario().run(testContext(url, DRAFT_PROTOCOL_VERSION)); + + beforeAll(async () => { + serverProcess = await startServer( + path.join( + process.cwd(), + 'examples/servers/typescript/sep-2127-server-card-fixture.ts' + ), + PORT + ); + }, 35000); + + afterAll(async () => { + await stopServer(serverProcess); + }); + + it('passes every check against a correct card that agrees with server/discover', async () => { + const checks = await run(`${base}/good/mcp`); + expect(checks.length).toBe(17); + for (const c of checks) + expect([c.id, c.status]).toEqual([c.id, 'SUCCESS']); + expect(takeWireViolations().violations).toEqual([]); + }, 15000); + + it('passes every check with a trailing slash on the server URL', async () => { + const checks = await run(`${base}/good/mcp/`); + expect(checks.length).toBe(17); + for (const c of checks) + expect([c.id, c.status]).toEqual([c.id, 'SUCCESS']); + takeWireViolations(); + }, 15000); + + it('fails an HTML page at the card location instead of skipping it', async () => { + const checks = await run(`${base}/html/mcp`); + expect(statusOf(checks, 'sep-2127-card-schema-valid')).toBe('FAILURE'); + expect(statusOf(checks, 'sep-2127-card-media-type')).toBe('WARNING'); + for (const id of [ + 'sep-2127-cors-allow-origin', + 'sep-2127-cors-expose-headers', + 'sep-2127-cors-preflight', + 'sep-2127-cors-allow-methods', + 'sep-2127-cors-allow-headers' + ]) { + expect(statusOf(checks, id)).toBe('FAILURE'); + } + expect(statusOf(checks, 'sep-2127-cache-control')).toBe('WARNING'); + expect(checks.some((c) => c.status === 'SKIPPED')).toBe(false); + takeWireViolations(); + }, 15000); + + it('warns on every field where the card contradicts server/discover', async () => { + const checks = await run(`${base}/contradict/mcp`); + for (const id of [ + 'sep-2127-card-schema-valid', + 'sep-2127-cors-allow-origin', + 'sep-2127-cors-preflight', + 'sep-2127-cors-allow-methods', + 'sep-2127-cors-allow-headers', + 'sep-2127-if-none-match' + ]) { + expect(statusOf(checks, id)).toBe('SUCCESS'); + } + for (const id of [ + 'sep-2127-consistent-transport', + 'sep-2127-consistent-protocol-version', + 'sep-2127-consistent-version', + 'sep-2127-consistent-name', + 'sep-2127-consistent-title', + 'sep-2127-consistent-description' + ]) { + expect(statusOf(checks, id)).toBe('WARNING'); + } + // The fixture's server/discover is wire-valid: only the card is wrong. + expect(takeWireViolations().violations).toEqual([]); + }, 15000); + + it('skips every check when no card is hosted (404 or 401)', async () => { + for (const p of ['none', 'auth']) { + const checks = await run(`${base}/${p}/mcp`); + expect(checks.length).toBe(17); + expect(checks.every((c) => c.status === 'SKIPPED')).toBe(true); + } + }, 15000); + + it('fails, rather than throws, when nothing answers', async () => { + // A port the OS just handed out and we closed: nothing listens on it. + // `localhost` makes undici try ::1 and 127.0.0.1, whose AggregateError + // has an empty message; the check must still name the cause. + const probe = createServer(); + await new Promise((r) => probe.listen(0, r)); + const freePort = (probe.address() as AddressInfo).port; + await new Promise((r) => probe.close(() => r())); + + const checks = await run(`http://localhost:${freePort}/mcp`); + expect(checks.length).toBe(17); + const schema = checks.find((c) => c.id === 'sep-2127-card-schema-valid'); + expect(schema?.status).toBe('FAILURE'); + expect(schema?.errorMessage).toMatch(/failed: \S/); + }, 15000); + }); }); diff --git a/src/scenarios/server/server-card/SOURCE b/src/scenarios/server/server-card/SOURCE new file mode 100644 index 00000000..b02d83e0 --- /dev/null +++ b/src/scenarios/server/server-card/SOURCE @@ -0,0 +1 @@ +modelcontextprotocol/ext-server-card@28db12c9b4a379489d46e49bf1bd4a991f05c9b7 schema.json diff --git a/src/scenarios/server/server-card/index.ts b/src/scenarios/server/server-card/index.ts new file mode 100644 index 00000000..1bc05be6 --- /dev/null +++ b/src/scenarios/server/server-card/index.ts @@ -0,0 +1,699 @@ +/** + * SEP-2127 MCP Server Cards — hosted card scenario. + * + * SEP-2127 is an Extensions Track SEP: its normative text lives in + * modelcontextprotocol/ext-server-card (docs/discovery.md, README, schema.json), + * not under docs/specification/draft/. The SEP says implementers "should follow + * the current, versioned extension specification rather than this historical + * snapshot", so this scenario is pinned to ext-server-card@28db12c9 (the current + * v1 schema, which adds Remote.extensionsInfo, ext-server-card#55). + * + * Hosting a card is a MAY ("MCP Servers MAY host their Server Card at + * `GET /server-card`"). Only a 2xx there counts as hosting + * a card, and the checks run against it: a 200 HTML page fails + * sep-2127-card-schema-valid instead of skipping. Any other status (404, 405, a + * redirect, an auth challenge) means the optional feature is not offered, so + * every check is SKIPPED. No answer at all fails sep-2127-card-schema-valid. + * + * Plain HTTP (GET with and without If-None-Match, and a CORS preflight) goes + * through undici beside the MCP connection, as dns-rebinding.ts does. The + * consistency checks compare the card with `server/discover`. + */ + +import { request } from 'undici'; +import { Ajv2020 } from 'ajv/dist/2020.js'; +import { default as addFormats } from 'ajv-formats'; +import type { + ClientScenario, + ConformanceCheck, + SpecReference +} from '../../../types'; +import type { RunContext } from '../../../connection'; +import { untestableCheck } from '../../untestable'; +import serverCardSchema from './server-card.schema.json'; + +const SERVER_CARD_MEDIA_TYPE = 'application/mcp-server-card+json'; +/** Any browser origin the server does not know; CORS for cards must allow it. */ +const PROBE_ORIGIN = 'https://conformance-client.example'; + +const PIN = '28db12c9b4a379489d46e49bf1bd4a991f05c9b7'; +const DISCOVERY = `https://github.com/modelcontextprotocol/ext-server-card/blob/${PIN}/docs/discovery.md`; +const REF_SEP: SpecReference = { + id: 'SEP-2127', + url: 'https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2127' +}; +const REF_LOCATION: SpecReference = { + id: 'Server-Card-Hosted-Location', + url: `${DISCOVERY}#hosted-server-card-location` +}; +const REF_SCHEMA: SpecReference = { + id: 'Server-Card-Schema-v1', + url: `https://github.com/modelcontextprotocol/ext-server-card/blob/${PIN}/schema.json` +}; +const REF_CORS: SpecReference = { + id: 'Server-Card-CORS', + url: `${DISCOVERY}#cors-requirements` +}; +const REF_CACHING: SpecReference = { + id: 'Server-Card-Caching', + url: `${DISCOVERY}#caching` +}; +const REF_CONSISTENCY: SpecReference = { + id: 'Server-Card-Consistency', + url: `${DISCOVERY}#consistency-with-runtime-behavior` +}; + +/** SemVer 2.0.0 (semver.org, "Is there a suggested regular expression"). */ +const SEMVER = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; +/** A reverse-DNS server name, `namespace/name`. */ +const REVERSE_DNS_NAME = /^[a-zA-Z0-9.-]+\/[a-zA-Z0-9._-]+$/; + +type Json = Record; +const isObject = (v: unknown): v is Json => + typeof v === 'object' && v !== null && !Array.isArray(v); + +/** `/server-card`: the path gains one segment; query and fragment are dropped. */ +function serverCardUrl(serverUrl: string): string { + const u = new URL(serverUrl); + u.pathname = `${u.pathname.replace(/\/+$/, '')}/server-card`; + u.search = ''; + u.hash = ''; + return u.href; +} + +/** Two endpoint URLs name the same endpoint: same origin, path (ignoring a trailing slash) and query. */ +function sameEndpoint(a: unknown, b: string): boolean { + if (typeof a !== 'string') return false; + try { + const norm = (v: string) => { + const u = new URL(v); + return `${u.origin}${u.pathname.replace(/\/+$/, '')}${u.search}`; + }; + return norm(a) === norm(b); + } catch { + return false; + } +} + +/** + * A readable cause for a failed request. undici's connection errors can carry an + * empty message (an AggregateError over the IPv6 and IPv4 attempts), so fall + * back to the error code and the inner errors. + */ +function errorText(e: unknown): string { + if (!(e instanceof Error)) return String(e); + const code = (e as { code?: unknown }).code; + const errors = (e as { errors?: unknown }).errors; + const inner = Array.isArray(errors) + ? errors.map((x) => (x instanceof Error ? x.message : String(x))) + : []; + const parts = [ + e.message, + typeof code === 'string' ? code : '', + inner.length ? `(${inner.join('; ')})` : '' + ].filter(Boolean); + return parts.length ? parts.join(' ') : e.name; +} + +function header( + headers: Record, + name: string +): string | undefined { + const v = headers[name.toLowerCase()]; + return Array.isArray(v) ? v.join(', ') : v; +} + +/** Comma-separated header tokens, lower-cased. */ +function tokens(value: string | undefined): string[] { + return (value ?? '') + .split(',') + .map((t) => t.trim().toLowerCase()) + .filter(Boolean); +} + +function check( + id: string, + name: string, + description: string, + ok: boolean, + severity: 'FAILURE' | 'WARNING', + specReferences: SpecReference[], + errorMessage: string, + details?: Json +): ConformanceCheck { + return { + id, + name, + description, + status: ok ? 'SUCCESS' : severity, + timestamp: new Date().toISOString(), + specReferences, + ...(ok ? {} : { errorMessage }), + ...(details ? { details } : {}) + }; +} + +function skipped( + id: string, + name: string, + description: string, + reason: string, + specReferences: SpecReference[] +): ConformanceCheck { + return { + id, + name, + description, + status: 'SKIPPED', + timestamp: new Date().toISOString(), + specReferences, + details: { reason } + }; +} + +/** Every check this scenario emits: [id, name, description, severity, refs]. */ +const CHECKS = [ + [ + 'sep-2127-card-schema-valid', + 'ServerCardSchemaValid', + 'The hosted Server Card is a JSON object that validates against the v1 Server Card schema', + 'FAILURE', + [REF_SCHEMA, REF_SEP] + ], + [ + 'sep-2127-version-semver', + 'ServerCardVersionSemver', + "The card's version follows semantic versioning", + 'WARNING', + [REF_SCHEMA] + ], + [ + 'sep-2127-card-media-type', + 'ServerCardMediaType', + `The card is served as ${SERVER_CARD_MEDIA_TYPE} when that type is requested`, + 'WARNING', + [REF_LOCATION] + ], + [ + 'sep-2127-cors-allow-origin', + 'ServerCardCorsAllowOrigin', + 'The card response carries Access-Control-Allow-Origin: *', + 'FAILURE', + [REF_CORS] + ], + [ + 'sep-2127-cors-expose-headers', + 'ServerCardCorsExposeHeaders', + 'The card response exposes ETag (Access-Control-Expose-Headers)', + 'FAILURE', + [REF_CORS] + ], + [ + 'sep-2127-cors-preflight', + 'ServerCardCorsPreflight', + 'A CORS preflight for the card succeeds with Access-Control-Allow-Origin (* or the request origin)', + 'FAILURE', + [REF_CORS] + ], + [ + 'sep-2127-cors-allow-methods', + 'ServerCardCorsAllowMethods', + 'The preflight response allows GET (Access-Control-Allow-Methods)', + 'FAILURE', + [REF_CORS] + ], + [ + 'sep-2127-cors-allow-headers', + 'ServerCardCorsAllowHeaders', + 'The preflight response allows Content-Type and If-None-Match (Access-Control-Allow-Headers)', + 'FAILURE', + [REF_CORS] + ], + [ + 'sep-2127-cache-control', + 'ServerCardCacheControl', + 'The card response carries a Cache-Control header', + 'WARNING', + [REF_CACHING] + ], + [ + 'sep-2127-etag', + 'ServerCardETag', + 'The card response carries an ETag', + 'WARNING', + [REF_CACHING] + ], + [ + 'sep-2127-if-none-match', + 'ServerCardIfNoneMatch', + 'A request with If-None-Match set to that ETag gets 304 Not Modified', + 'WARNING', + [REF_CACHING] + ], + [ + 'sep-2127-consistent-transport', + 'ServerCardConsistentTransport', + "The card's remote for this endpoint declares streamable-http", + 'WARNING', + [REF_CONSISTENCY] + ], + [ + 'sep-2127-consistent-protocol-version', + 'ServerCardConsistentProtocolVersion', + "The card's supportedProtocolVersions do not contradict server/discover's supportedVersions", + 'WARNING', + [REF_CONSISTENCY] + ], + [ + 'sep-2127-consistent-version', + 'ServerCardConsistentVersion', + "The card's version does not contradict serverInfo.version", + 'WARNING', + [REF_CONSISTENCY] + ], + [ + 'sep-2127-consistent-name', + 'ServerCardConsistentName', + "The card's name does not contradict a reverse-DNS serverInfo.name", + 'WARNING', + [REF_CONSISTENCY] + ], + [ + 'sep-2127-consistent-title', + 'ServerCardConsistentTitle', + "The card's title does not contradict serverInfo.title", + 'WARNING', + [REF_CONSISTENCY] + ], + [ + 'sep-2127-consistent-description', + 'ServerCardConsistentDescription', + "The card's description does not contradict the server's description", + 'WARNING', + [REF_CONSISTENCY] + ] +] as const satisfies ReadonlyArray< + readonly [string, string, string, 'FAILURE' | 'WARNING', SpecReference[]] +>; + +type CheckId = (typeof CHECKS)[number][0]; +const META = Object.fromEntries( + CHECKS.map(([id, name, description, severity, refs]) => [ + id, + { name, description, severity, refs } + ]) +) as unknown as Record< + CheckId, + { + name: string; + description: string; + severity: 'FAILURE' | 'WARNING'; + refs: SpecReference[]; + } +>; + +let validateCard: + | (((card: unknown) => boolean) & { errors?: unknown }) + | undefined; +function cardValidator() { + if (!validateCard) { + const ajv = new Ajv2020({ allErrors: true, strict: false }); + addFormats(ajv); + ajv.addSchema(serverCardSchema, 'server-card-v1'); + validateCard = ajv.getSchema( + 'server-card-v1#/$defs/ServerCard' + ) as typeof validateCard; + } + return validateCard!; +} + +export class ServerCardScenario implements ClientScenario { + name = 'sep-2127-server-card'; + readonly source = { + extensionId: 'io.modelcontextprotocol/server-card' + } as const; + description = `SEP-2127 MCP Server Cards: the card a server hosts at its reserved location, and whether it agrees with the live server. + +**Optional feature:** servers MAY host a Server Card at \`GET /server-card\`. Only a 2xx response there is treated as a hosted card; any other status means the server does not offer one, and every check is SKIPPED. + +**Server Implementation Requirements (for servers that host a card), from ext-server-card@28db12c9:** +- MUST: the card validates against the v1 Server Card schema (\`$schema\`, \`name\`, \`version\`, \`description\`) +- MUST: CORS for browser clients — \`Access-Control-Allow-Origin: *\` and \`Access-Control-Expose-Headers: ETag\` on the card response; a preflight that succeeds and allows \`GET\` and the \`Content-Type\` and \`If-None-Match\` headers +- SHOULD: served as \`${SERVER_CARD_MEDIA_TYPE}\`; \`version\` is semver; a \`Cache-Control\` header; an \`ETag\`, and \`304 Not Modified\` for a matching \`If-None-Match\` +- SHOULD NOT: the card contradicts the live server (\`server/discover\`): the transport of the remote for this endpoint, \`supportedProtocolVersions\`, and \`serverInfo\` \`version\`, \`name\` (when reverse-DNS), \`title\` and \`description\``; + + async run(ctx: RunContext): Promise { + const checks: ConformanceCheck[] = []; + const add = ( + id: CheckId, + ok: boolean, + errorMessage: string, + details?: Json + ) => { + const m = META[id]; + checks.push( + check( + id, + m.name, + m.description, + ok, + m.severity, + m.refs, + errorMessage, + details + ) + ); + }; + const skip = (id: CheckId, reason: string) => { + const m = META[id]; + checks.push(skipped(id, m.name, m.description, reason, m.refs)); + }; + const untestable = (id: CheckId, reason: string) => { + const m = META[id]; + checks.push( + untestableCheck(id, m.name, m.description, reason, m.refs, m.severity) + ); + }; + + const cardUrl = serverCardUrl(ctx.serverUrl); + + // === The card, requested the way the spec asks clients to request it === + let res: Awaited>; + let bodyText: string; + try { + res = await request(cardUrl, { + method: 'GET', + headers: { accept: SERVER_CARD_MEDIA_TYPE, origin: PROBE_ORIGIN } + }); + bodyText = await res.body.text(); + } catch (e) { + // The server did not answer at all, so whether it hosts a card is unknown. + add( + 'sep-2127-card-schema-valid', + false, + `GET ${cardUrl} failed: ${errorText(e)}` + ); + for (const [id] of CHECKS.slice(1)) + untestable(id, `GET ${cardUrl} failed: ${errorText(e)}`); + return checks; + } + + // Hosting a card is optional (MAY). Only a 2xx is a hosted card; anything + // else (404, 405, a redirect, an auth challenge) means no card is offered. + if (res.statusCode < 200 || res.statusCode >= 300) { + const reason = `No Server Card at ${cardUrl} (HTTP ${res.statusCode}); hosting a card is optional (MAY), so the checks do not apply.`; + for (const [id] of CHECKS) skip(id, reason); + return checks; + } + + // --- sep-2127-card-schema-valid (MUST) --- + let card: Json | undefined; + let parseError: string | undefined; + try { + const parsed: unknown = JSON.parse(bodyText); + if (isObject(parsed)) card = parsed; + else parseError = 'the body is JSON but not an object'; + } catch { + parseError = `the body is not JSON (HTTP ${res.statusCode}, content-type ${header(res.headers, 'content-type') ?? 'none'})`; + } + if (!card) { + add( + 'sep-2127-card-schema-valid', + false, + `No valid Server Card at ${cardUrl}: ${parseError}`, + { statusCode: res.statusCode } + ); + } else { + const validate = cardValidator(); + const ok = validate(card); + add( + 'sep-2127-card-schema-valid', + ok, + 'The card does not validate against the v1 Server Card schema', + ok ? undefined : { errors: validate.errors } + ); + } + + // --- sep-2127-version-semver (SHOULD) --- + if (!card || typeof card.version !== 'string') { + untestable( + 'sep-2127-version-semver', + 'the card has no version string to check' + ); + } else { + add( + 'sep-2127-version-semver', + SEMVER.test(card.version), + `version ${JSON.stringify(card.version)} is not semantic versioning` + ); + } + + // --- sep-2127-card-media-type (SHOULD) --- + const contentType = (header(res.headers, 'content-type') ?? '') + .split(';')[0] + .trim() + .toLowerCase(); + add( + 'sep-2127-card-media-type', + contentType === SERVER_CARD_MEDIA_TYPE, + `Served as ${JSON.stringify(contentType || 'no content-type')}, not ${SERVER_CARD_MEDIA_TYPE}` + ); + + // --- sep-2127-cors-allow-origin (MUST), sep-2127-cors-expose-headers (MUST): on the card response --- + const acao = header(res.headers, 'access-control-allow-origin'); + add( + 'sep-2127-cors-allow-origin', + acao?.trim() === '*', + `Access-Control-Allow-Origin is ${JSON.stringify(acao ?? null)}, not "*"` + ); + const expose = tokens(header(res.headers, 'access-control-expose-headers')); + add( + 'sep-2127-cors-expose-headers', + expose.includes('etag') || expose.includes('*'), + `Access-Control-Expose-Headers ${JSON.stringify(expose.join(', ') || null)} does not include ETag` + ); + + // --- Preflight: a browser sending If-None-Match always preflights (it is not a CORS-safelisted header) --- + let pre: Awaited> | undefined; + let preError: string | undefined; + try { + pre = await request(cardUrl, { + method: 'OPTIONS', + headers: { + origin: PROBE_ORIGIN, + 'access-control-request-method': 'GET', + 'access-control-request-headers': 'content-type, if-none-match' + } + }); + await pre.body.dump(); + } catch (e) { + preError = `OPTIONS ${cardUrl} failed: ${errorText(e)}`; + } + if (!pre) { + untestable('sep-2127-cors-preflight', preError!); + untestable('sep-2127-cors-allow-methods', preError!); + untestable('sep-2127-cors-allow-headers', preError!); + } else { + const preOrigin = header( + pre.headers, + 'access-control-allow-origin' + )?.trim(); + const preOk = + pre.statusCode >= 200 && + pre.statusCode < 300 && + (preOrigin === '*' || preOrigin === PROBE_ORIGIN); + add( + 'sep-2127-cors-preflight', + preOk, + `Preflight answered HTTP ${pre.statusCode} with Access-Control-Allow-Origin ${JSON.stringify(preOrigin ?? null)}` + ); + const methods = tokens( + header(pre.headers, 'access-control-allow-methods') + ); + add( + 'sep-2127-cors-allow-methods', + methods.includes('get') || methods.includes('*'), + `Preflight Access-Control-Allow-Methods ${JSON.stringify(methods.join(', ') || null)} does not include GET` + ); + const allowHeaders = tokens( + header(pre.headers, 'access-control-allow-headers') + ); + const missing = ['content-type', 'if-none-match'].filter( + (h) => !allowHeaders.includes(h) && !allowHeaders.includes('*') + ); + add( + 'sep-2127-cors-allow-headers', + missing.length === 0, + `Preflight Access-Control-Allow-Headers ${JSON.stringify(allowHeaders.join(', ') || null)} does not include ${missing.join(' and ')}` + ); + } + + // --- sep-2127-cache-control, sep-2127-etag, sep-2127-if-none-match (SHOULD) --- + const cacheControl = header(res.headers, 'cache-control') ?? ''; + add( + 'sep-2127-cache-control', + cacheControl.trim() !== '', + 'The card response has no Cache-Control header' + ); + const etag = header(res.headers, 'etag'); + add('sep-2127-etag', Boolean(etag), 'The card response has no ETag'); + if (!etag) { + untestable( + 'sep-2127-if-none-match', + 'the card response has no ETag to revalidate' + ); + } else { + try { + const again = await request(cardUrl, { + method: 'GET', + headers: { accept: SERVER_CARD_MEDIA_TYPE, 'if-none-match': etag } + }); + await again.body.dump(); + add( + 'sep-2127-if-none-match', + again.statusCode === 304, + `If-None-Match ${etag} answered HTTP ${again.statusCode}, not 304` + ); + } catch (e) { + untestable( + 'sep-2127-if-none-match', + `the revalidation GET failed: ${errorText(e)}` + ); + } + } + + // === Consistency with runtime behavior: the card vs server/discover === + const consistency: CheckId[] = [ + 'sep-2127-consistent-transport', + 'sep-2127-consistent-protocol-version', + 'sep-2127-consistent-version', + 'sep-2127-consistent-name', + 'sep-2127-consistent-title', + 'sep-2127-consistent-description' + ]; + if (!card) { + for (const id of consistency) + untestable(id, 'there is no card object to compare with the server'); + return checks; + } + + let discovered: Json; + try { + const conn = await ctx.connect(); + try { + discovered = await conn.discover(); + } finally { + await conn.close(); + } + } catch (e) { + const reason = `server/discover failed: ${errorText(e)}`; + for (const id of consistency) untestable(id, reason); + return checks; + } + const meta = isObject(discovered._meta) ? discovered._meta : {}; + const serverInfo: Json = isObject( + meta['io.modelcontextprotocol/serverInfo'] + ) + ? meta['io.modelcontextprotocol/serverInfo'] + : isObject(discovered.serverInfo) + ? discovered.serverInfo + : {}; + const supportedVersions = Array.isArray(discovered.supportedVersions) + ? discovered.supportedVersions.filter( + (v): v is string => typeof v === 'string' + ) + : undefined; + + // --- sep-2127-consistent-transport --- + // The first remotes[] entry for this URL is compared; a card listing two + // transports at one URL is judged on the first. + const remote = Array.isArray(card.remotes) + ? card.remotes + .filter(isObject) + .find((r) => sameEndpoint(r.url, ctx.serverUrl)) + : undefined; + if (!remote) { + skip( + 'sep-2127-consistent-transport', + `The card declares no remote for ${ctx.serverUrl}` + ); + } else { + add( + 'sep-2127-consistent-transport', + remote.type === 'streamable-http', + `The card's remote for this endpoint says type ${JSON.stringify(remote.type)}; it answered server/discover over Streamable HTTP` + ); + } + + // --- sep-2127-consistent-protocol-version --- + const listed = + remote && Array.isArray(remote.supportedProtocolVersions) + ? remote.supportedProtocolVersions.filter( + (v): v is string => typeof v === 'string' + ) + : undefined; + if (!listed) { + skip( + 'sep-2127-consistent-protocol-version', + "The card's remote for this endpoint lists no supportedProtocolVersions" + ); + } else if (!supportedVersions) { + untestable( + 'sep-2127-consistent-protocol-version', + 'server/discover returned no supportedVersions' + ); + } else { + const extra = listed.filter((v) => !supportedVersions.includes(v)); + add( + 'sep-2127-consistent-protocol-version', + extra.length === 0, + `The card lists ${extra.join(', ')}, which server/discover does not (server: ${supportedVersions.join(', ')})`, + { card: listed, server: supportedVersions } + ); + } + + // --- sep-2127-consistent-version / -title / -description --- + const compare = ( + id: CheckId, + field: 'version' | 'title' | 'description' + ) => { + const mine = card![field]; + const theirs = serverInfo[field]; + if (typeof mine !== 'string' || typeof theirs !== 'string') { + skip( + id, + `The card or serverInfo sets no ${field}, so there is nothing to contradict` + ); + } else { + add( + id, + mine === theirs, + `The card's ${field} ${JSON.stringify(mine)} contradicts serverInfo.${field} ${JSON.stringify(theirs)}` + ); + } + }; + compare('sep-2127-consistent-version', 'version'); + + // --- sep-2127-consistent-name: only a reverse-DNS serverInfo.name can contradict the card's --- + if ( + typeof serverInfo.name !== 'string' || + !REVERSE_DNS_NAME.test(serverInfo.name) + ) { + skip( + 'sep-2127-consistent-name', + 'serverInfo.name is not reverse-DNS, so it cannot contradict the card name' + ); + } else { + add( + 'sep-2127-consistent-name', + serverInfo.name === card.name, + `The card's name ${JSON.stringify(card.name)} contradicts serverInfo.name ${JSON.stringify(serverInfo.name)}` + ); + } + compare('sep-2127-consistent-title', 'title'); + compare('sep-2127-consistent-description', 'description'); + + return checks; + } +} diff --git a/src/scenarios/server/server-card/server-card.schema.json b/src/scenarios/server/server-card/server-card.schema.json new file mode 100644 index 00000000..7da60a1e --- /dev/null +++ b/src/scenarios/server/server-card/server-card.schema.json @@ -0,0 +1,295 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$defs": { + "Icon": { + "description": "An optionally-sized icon that can be displayed in a user interface.", + "properties": { + "mimeType": { + "description": "Optional MIME type override if the source MIME type is missing or generic.\nFor example: `\"image/png\"`, `\"image/jpeg\"`, or `\"image/svg+xml\"`.", + "type": "string" + }, + "sizes": { + "description": "Optional array of strings that specify sizes at which the icon can be used.\nEach string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n\nIf not provided, the client should assume that the icon can be used at any size.", + "items": { + "type": "string" + }, + "type": "array" + }, + "src": { + "description": "A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a\n`data:` URI with Base64-encoded image data.\n\nConsumers SHOULD take steps to ensure URLs serving icons are from the\nsame domain as the client/server or a trusted domain.\n\nConsumers SHOULD take appropriate precautions when consuming SVGs as they can contain\nexecutable JavaScript.", + "format": "uri", + "type": "string" + }, + "theme": { + "description": "Optional specifier for the theme this icon is designed for. `\"light\"` indicates\nthe icon is designed to be used with a light background, and `\"dark\"` indicates\nthe icon is designed to be used with a dark background.\n\nIf not provided, the client should assume the icon can be used with any theme.", + "enum": ["dark", "light"], + "type": "string" + } + }, + "required": ["src"], + "type": "object" + }, + "Input": { + "description": "A user-supplied or pre-set input value, used for {@link Remote} URL\nvariables and header values.", + "properties": { + "choices": { + "description": "Allowed values for the input. If provided, the user must select one.", + "items": { + "type": "string" + }, + "type": "array" + }, + "default": { + "description": "Default value for the input. SHOULD be a valid value for the input.", + "type": "string" + }, + "description": { + "description": "Human-readable explanation of the input. Clients can use this to provide\ncontext to the user.", + "type": "string" + }, + "format": { + "description": "Specifies the input format. `\"filepath\"` should be interpreted as a file\non the user's filesystem. When the input is converted to a string,\nbooleans should be represented by `\"true\"`/`\"false\"`, and numbers by\ndecimal values.", + "enum": ["boolean", "filepath", "number", "string"], + "type": "string" + }, + "isRequired": { + "description": "Whether the input must be supplied for the connection to succeed.", + "type": "boolean" + }, + "isSecret": { + "description": "Whether the input is a secret value (e.g., password, token). If true,\nclients should handle the value securely.", + "type": "boolean" + }, + "placeholder": { + "description": "Placeholder displayed during configuration to provide examples or\nguidance about the expected form of the input.", + "type": "string" + }, + "value": { + "description": "Pre-set value for the input. If set, the value should not be configurable\nby end users. Identifiers wrapped in `{curly_braces}` will be replaced\nwith the corresponding entries from the input's `variables` map (if any).", + "type": "string" + } + }, + "type": "object" + }, + "JSONArray": { + "items": { + "$ref": "#/$defs/JSONValue" + }, + "type": "array" + }, + "JSONObject": { + "additionalProperties": { + "$ref": "#/$defs/JSONValue" + }, + "type": "object" + }, + "JSONValue": { + "anyOf": [ + { + "$ref": "#/$defs/JSONObject" + }, + { + "items": { + "$ref": "#/$defs/JSONValue" + }, + "type": "array" + }, + { + "type": ["string", "integer", "boolean"] + } + ] + }, + "KeyValueInput": { + "description": "A named {@link Input} — used for HTTP headers — whose `value` may reference\nvariables for substitution.", + "properties": { + "choices": { + "description": "Allowed values for the input. If provided, the user must select one.", + "items": { + "type": "string" + }, + "type": "array" + }, + "default": { + "description": "Default value for the input. SHOULD be a valid value for the input.", + "type": "string" + }, + "description": { + "description": "Human-readable explanation of the input. Clients can use this to provide\ncontext to the user.", + "type": "string" + }, + "format": { + "description": "Specifies the input format. `\"filepath\"` should be interpreted as a file\non the user's filesystem. When the input is converted to a string,\nbooleans should be represented by `\"true\"`/`\"false\"`, and numbers by\ndecimal values.", + "enum": ["boolean", "filepath", "number", "string"], + "type": "string" + }, + "isRequired": { + "description": "Whether the input must be supplied for the connection to succeed.", + "type": "boolean" + }, + "isSecret": { + "description": "Whether the input is a secret value (e.g., password, token). If true,\nclients should handle the value securely.", + "type": "boolean" + }, + "name": { + "description": "Name of the header.", + "type": "string" + }, + "placeholder": { + "description": "Placeholder displayed during configuration to provide examples or\nguidance about the expected form of the input.", + "type": "string" + }, + "value": { + "description": "Pre-set value for the input. If set, the value should not be configurable\nby end users. Identifiers wrapped in `{curly_braces}` will be replaced\nwith the corresponding entries from the input's `variables` map (if any).", + "type": "string" + }, + "variables": { + "additionalProperties": { + "$ref": "#/$defs/Input" + }, + "description": "Variables referenced by `{curly_braces}` identifiers in `value`. The map\nkey is the variable name; the value defines the variable's properties.", + "type": "object" + } + }, + "required": ["name"], + "type": "object" + }, + "MetaObject": { + "additionalProperties": {}, + "description": "Represents the contents of a `_meta` field, which clients and servers use to attach additional metadata to their interactions.\n\nCertain 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.\n\nValid keys have two segments:\n\n**Prefix:**\n- Optional — if specified, MUST be a series of _labels_ separated by dots (`.`), followed by a slash (`/`).\n- Labels MUST start with a letter and end with a letter or digit. Interior characters may be letters, digits, or hyphens (`-`).\n- Any prefix consisting of zero or more labels, followed by `modelcontextprotocol` or `mcp`, followed by any label, is **reserved** for MCP use. For example: `modelcontextprotocol.io/`, `mcp.dev/`, `api.modelcontextprotocol.org/`, and `tools.mcp.com/` are all reserved.\n\n**Name:**\n- Unless empty, MUST start and end with an alphanumeric character (`[a-z0-9A-Z]`).\n- Interior characters may be alphanumeric, hyphens (`-`), underscores (`_`), or dots (`.`).", + "type": "object" + }, + "Remote": { + "description": "Metadata for connecting to a remote (HTTP-based) MCP server endpoint.", + "properties": { + "extensionsInfo": { + "additionalProperties": { + "$ref": "#/$defs/JSONObject" + }, + "description": "Optional server-level information about MCP extensions for this remote\nendpoint. Keys are extension identifiers (e.g.,\n`\"io.modelcontextprotocol/events\"`), and values are objects whose contents\nare defined by the respective extension — typically information a client\nneeds before connecting, such as keys for verifying webhook signatures.\n\nThe presence or absence of an entry does not indicate whether the server\nsupports that extension, and an entry need not match the server's\n`capabilities.extensions`. Extension support is negotiated at runtime via\n`server/discover` and may vary per user.\n\nKeys MUST follow the {@link MetaObject`_meta` key naming rules}, with a\nmandatory prefix.", + "type": "object" + }, + "headers": { + "description": "HTTP headers required or accepted when connecting to this remote\nendpoint. Each header is described as a {@link KeyValueInput} so that\nclients can prompt users for required values, mark secrets, surface\ndefaults, and constrain to a list of choices.", + "items": { + "$ref": "#/$defs/KeyValueInput" + }, + "type": "array" + }, + "supportedProtocolVersions": { + "description": "MCP protocol versions actively supported by this remote endpoint. Allows\nclients to select a compatible protocol version before connecting.", + "items": { + "type": "string" + }, + "type": "array" + }, + "type": { + "description": "The transport type for this remote endpoint.", + "enum": ["sse", "streamable-http"], + "type": "string" + }, + "url": { + "description": "URL template for the remote endpoint. Must start with `http://`,\n`https://`, or a `{template-variable}`. Variables in `{curly_braces}`\nare substituted from the {@link Remote.variables} map before the\nclient connects.", + "pattern": "^(https?://[^\\s]+|\\{[a-zA-Z_][a-zA-Z0-9_]*\\}[^\\s]*)$", + "type": "string" + }, + "variables": { + "additionalProperties": { + "$ref": "#/$defs/Input" + }, + "description": "Configuration variables that can be referenced as `{curly_braces}`\nplaceholders in `url` (and inside header values via\n{@link KeyValueInput.variables}). The map key is the variable\nname; the value defines the variable's properties (e.g., human-readable\ndescription, default, whether it is required or secret).", + "type": "object" + } + }, + "required": ["type", "url"], + "type": "object" + }, + "Repository": { + "description": "Repository metadata for the MCP server source code. Enables users and\nsecurity experts to inspect the code, improving transparency.", + "properties": { + "id": { + "description": "Repository identifier from the hosting service (e.g., GitHub repo ID).\nOwned and determined by the source forge. Should remain stable across\nrepository renames and may be used to detect repository resurrection\nattacks — if a repository is deleted and recreated, the ID should change.", + "type": "string" + }, + "source": { + "description": "Repository hosting service identifier (e.g., `\"github\"`). Used by registries\nto determine validation and API access methods.", + "type": "string" + }, + "subfolder": { + "description": "Optional relative path from repository root to the server location within a\nmonorepo or nested package structure. Must be a clean relative path.", + "type": "string" + }, + "url": { + "description": "Repository URL for browsing source code. Should support both web browsing\nand `git clone` operations.", + "format": "uri", + "type": "string" + } + }, + "required": ["source", "url"], + "type": "object" + }, + "ServerCard": { + "description": "A static metadata document describing a remote MCP server, suitable for\npre-connection discovery. A Server Card may be hosted at any unreserved URI;\nMCP reserves `GET /server-card` as the recommended\nlocation. Clients learn a card's URL from an [AI Catalog](https://github.com/Agent-Card/ai-catalog)\nrather than guessing it.\n\nServer Cards describe only what is needed to discover and connect to a remote server:\nidentity, transport, and protocol versions.\n\nThey do not enumerate primitives (tools, resources, prompts) — those remain\nsubject to runtime listing via the protocol's standard list operations.\n\nThe fields a Server Card does declare (identity, transport, protocol\nversions) are advisory, not authoritative: they should be consistent with\nthe server's `server/discover` response, and clients must not treat them as\nauthoritative for security decisions. See \"Consistency with Runtime\nBehavior\" in docs/discovery.md for the normative requirement.", + "properties": { + "$schema": { + "description": "The Server Card JSON Schema URI that this document conforms to. Required.\n\nMust be the `/v1/` Server Card schema URL under\n`static.modelcontextprotocol.io/schemas/` (i.e.,\n`https://static.modelcontextprotocol.io/schemas/v1/server-card.schema.json`).\nSchema URLs are versioned by the `vN` segment rather than by date; a\nbreaking revision of the Server Card shape publishes a new `vN` family.", + "format": "uri", + "pattern": "^https://static\\.modelcontextprotocol\\.io/schemas/v1/server-card\\.schema\\.json$", + "type": "string" + }, + "_meta": { + "$ref": "#/$defs/MetaObject", + "description": "Extension metadata using reverse-DNS namespacing for vendor-specific data.\n\nFollows the protocol's standard `_meta` definition." + }, + "description": { + "description": "Clear human-readable explanation of server functionality. Should focus on\ncapabilities, not implementation details.", + "maxLength": 100, + "minLength": 1, + "type": "string" + }, + "icons": { + "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following\nMIME types: `image/png` and `image/jpeg` (safe, universal compatibility).\nClients SHOULD also support: `image/svg+xml` (scalable but requires security\nprecautions) and `image/webp` (modern, efficient format).", + "items": { + "$ref": "#/$defs/Icon" + }, + "type": "array" + }, + "name": { + "description": "Server name in reverse-DNS format. Must contain exactly one forward slash\nseparating namespace from server name.", + "maxLength": 200, + "minLength": 3, + "pattern": "^[a-zA-Z0-9.-]+/[a-zA-Z0-9._-]+$", + "type": "string" + }, + "remotes": { + "description": "Metadata helpful for making HTTP-based connections to this MCP server.", + "items": { + "$ref": "#/$defs/Remote" + }, + "type": "array" + }, + "repository": { + "$ref": "#/$defs/Repository", + "description": "Optional repository metadata for the MCP server source code.\nRecommended for transparency and security inspection." + }, + "title": { + "description": "Optional human-readable title or display name for the MCP server.\nMCP subregistries or clients MAY choose to use this for display purposes.", + "maxLength": 100, + "minLength": 1, + "type": "string" + }, + "version": { + "description": "Version string for this server. SHOULD follow semantic versioning\n(e.g., '1.0.2', '2.1.0-alpha'). Equivalent of `Implementation.version`\nin the MCP specification. Non-semantic versions are allowed but may not\nsort predictably. Version ranges are rejected (e.g., '^1.2.3', '~1.2.3',\n'>=1.2.3', '1.x', '1.*').", + "maxLength": 255, + "type": "string" + }, + "websiteUrl": { + "description": "Optional URL to the server's homepage, documentation, or project website.\nProvides a central link for users to learn more about the server.\nParticularly useful when the server has custom installation instructions\nor setup requirements.", + "format": "uri", + "type": "string" + } + }, + "required": ["$schema", "description", "name", "version"], + "type": "object" + } + } +} diff --git a/src/seps/sep-2127.yaml b/src/seps/sep-2127.yaml new file mode 100644 index 00000000..5aa6d481 --- /dev/null +++ b/src/seps/sep-2127.yaml @@ -0,0 +1,121 @@ +# spec_source: modelcontextprotocol/ext-server-card@28db12c9 docs/discovery.md, schema.json, README.md +# extracted: 2026-11-25 +# +# SEP-2127 is an Extensions Track SEP. It charters the Server Card extension +# and keeps the normative wire format in ext-server-card, not inline. The SEP +# pins snapshot 526201bb for its review and says implementers "should follow +# the current, versioned extension specification rather than this historical +# snapshot". These rows quote 28db12c9, the current main, whose v1 schema adds +# Remote.extensionsInfo (ext-server-card#55). Every sentence quoted below +# also appears, word for word, at 526201bb, except the last three not-tested +# client rows: two added by #55 (extensionsInfo), one reworded since. +# +# Quotes are verbatim. Where several checks rest on one sentence (CORS, +# consistency), each row quotes the whole sentence and a comment names the +# part that check observes. +# +# Scope: the card a server hosts at its reserved location. Hosting is a MAY, so +# only a 2xx there is graded; any other status skips every check. AI Catalog discovery +# (/.well-known/ai-catalog.json) is out of scope: it belongs to the AI Catalog +# specification, not to this extension. +sep: 2127 +spec_url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md +requirements: + # === The card === + # The sentence introduces a code block holding the URL template + # https://static.modelcontextprotocol.io/schemas/v1/.schema.json + # (server-card for a Server Card). Observed by validating the card against the + # vendored v1 schema (schema.json `$defs/ServerCard`), which requires `$schema`, + # `name`, `version` and `description`; the schema is the requirement. + - check: sep-2127-card-schema-valid + text: 'The `$schema` field on every document MUST be a URL of the form:' + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/README.md#schema-url-conventions + # schema.json, `ServerCard.version` description. + - check: sep-2127-version-semver + text: 'Version string for this server. SHOULD follow semantic versioning' + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/schema.json + - check: sep-2127-card-media-type + text: 'MCP Servers SHOULD respect the `application/mcp-server-card+json` media type wherever they choose to host it.' + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#hosted-server-card-location + + # === CORS Requirements === + # Access-Control-Allow-Origin: * on the GET response. + - check: sep-2127-cors-allow-origin + text: 'Hosted Server Card endpoints MUST include appropriate CORS headers to allow browser-based clients:' + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#cors-requirements + # Access-Control-Expose-Headers: ETag on the GET response. + - check: sep-2127-cors-expose-headers + text: 'Hosted Server Card endpoints MUST include appropriate CORS headers to allow browser-based clients:' + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#cors-requirements + # A preflight (OPTIONS) for the card succeeds; the header lines below only work if it does. + - check: sep-2127-cors-preflight + text: 'Hosted Server Card endpoints MUST include appropriate CORS headers to allow browser-based clients:' + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#cors-requirements + # Access-Control-Allow-Methods: GET on the preflight response. + - check: sep-2127-cors-allow-methods + text: 'Hosted Server Card endpoints MUST include appropriate CORS headers to allow browser-based clients:' + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#cors-requirements + # Access-Control-Allow-Headers: Content-Type, If-None-Match on the preflight response. + - check: sep-2127-cors-allow-headers + text: 'Hosted Server Card endpoints MUST include appropriate CORS headers to allow browser-based clients:' + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#cors-requirements + + # === Caching === + # A Cache-Control header is present. The `public, max-age=3600` the spec shows in a code block under this SHOULD is not graded. + - check: sep-2127-cache-control + text: 'Server Card hosts SHOULD include caching headers to reduce unnecessary requests:' + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#caching + - check: sep-2127-etag + text: 'Hosts SHOULD also return an `ETag` response header.' + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#caching + - check: sep-2127-if-none-match + text: 'Hosts SHOULD honor `If-None-Match` and return `304 Not Modified` when the selected representation has not changed.' + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#caching + + # === Consistency with Runtime Behavior === + # The transport of the remotes[] entry for the tested endpoint. + - check: sep-2127-consistent-transport + text: "A Server Card SHOULD accurately reflect the server's runtime behavior: the values a client observes once connected — the `serverInfo` (`name`, `version`) and `supportedVersions` from [`server/discover`](https://modelcontextprotocol.io/specification/draft/server/discover), the transport served at each `remotes[]` endpoint, and descriptive fields (`title`, `description`, `icons`) — SHOULD NOT contradict the equivalent values declared in the Server Card." + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#consistency-with-runtime-behavior + # supportedProtocolVersions of that remote vs server/discover supportedVersions. + - check: sep-2127-consistent-protocol-version + text: "A Server Card SHOULD accurately reflect the server's runtime behavior: the values a client observes once connected — the `serverInfo` (`name`, `version`) and `supportedVersions` from [`server/discover`](https://modelcontextprotocol.io/specification/draft/server/discover), the transport served at each `remotes[]` endpoint, and descriptive fields (`title`, `description`, `icons`) — SHOULD NOT contradict the equivalent values declared in the Server Card." + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#consistency-with-runtime-behavior + # serverInfo.version. + - check: sep-2127-consistent-version + text: "A Server Card SHOULD accurately reflect the server's runtime behavior: the values a client observes once connected — the `serverInfo` (`name`, `version`) and `supportedVersions` from [`server/discover`](https://modelcontextprotocol.io/specification/draft/server/discover), the transport served at each `remotes[]` endpoint, and descriptive fields (`title`, `description`, `icons`) — SHOULD NOT contradict the equivalent values declared in the Server Card." + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#consistency-with-runtime-behavior + # serverInfo.name, compared only when it is reverse-DNS: a short name cannot contradict the card name. + - check: sep-2127-consistent-name + text: "A Server Card SHOULD accurately reflect the server's runtime behavior: the values a client observes once connected — the `serverInfo` (`name`, `version`) and `supportedVersions` from [`server/discover`](https://modelcontextprotocol.io/specification/draft/server/discover), the transport served at each `remotes[]` endpoint, and descriptive fields (`title`, `description`, `icons`) — SHOULD NOT contradict the equivalent values declared in the Server Card." + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#consistency-with-runtime-behavior + # title. + - check: sep-2127-consistent-title + text: "A Server Card SHOULD accurately reflect the server's runtime behavior: the values a client observes once connected — the `serverInfo` (`name`, `version`) and `supportedVersions` from [`server/discover`](https://modelcontextprotocol.io/specification/draft/server/discover), the transport served at each `remotes[]` endpoint, and descriptive fields (`title`, `description`, `icons`) — SHOULD NOT contradict the equivalent values declared in the Server Card." + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#consistency-with-runtime-behavior + # description. + - check: sep-2127-consistent-description + text: "A Server Card SHOULD accurately reflect the server's runtime behavior: the values a client observes once connected — the `serverInfo` (`name`, `version`) and `supportedVersions` from [`server/discover`](https://modelcontextprotocol.io/specification/draft/server/discover), the transport served at each `remotes[]` endpoint, and descriptive fields (`title`, `description`, `icons`) — SHOULD NOT contradict the equivalent values declared in the Server Card." + url: https://github.com/modelcontextprotocol/ext-server-card/blob/28db12c9b4a379489d46e49bf1bd4a991f05c9b7/docs/discovery.md#consistency-with-runtime-behavior + + # === Not tested === + - text: 'MCP Servers MAY host their Server Card at `GET /server-card`, which we reserve for this purpose, though any unreserved URI (on any domain) is valid.' + excluded: 'Optional (MAY). Not a check of its own: only a 2xx at that location is graded as a hosted card, and any other status skips every check.' + - text: 'After a client identifies a Server Card URL from an AI Catalog, it SHOULD request that URL expressing the `application/mcp-server-card+json` media type.' + excluded: 'A client requirement. This scenario tests servers; the harness sends that Accept header itself.' + - text: 'Hosted Server Cards MUST be served over HTTPS (TLS 1.2 or later) in production. HTTP MAY be used for local development only.' + excluded: 'Conformance runs against local HTTP servers, where HTTP is allowed; production deployment is not observable from the harness.' + - text: 'MCP Servers SHOULD implement rate limiting on their Server Card endpoint to prevent abuse.' + excluded: 'No crisp threshold to test against; probing for it would mean flooding the server under test.' + - text: 'AI Catalogs and Server Cards used for public discovery are publicly accessible by design. They MUST NOT include sensitive information such as:' + excluded: 'Whether a value is sensitive is a judgement about the deployment, not observable on the wire.' + - text: "A Server Card SHOULD accurately reflect the server's runtime behavior: the values a client observes once connected — the `serverInfo` (`name`, `version`) and `supportedVersions` from [`server/discover`](https://modelcontextprotocol.io/specification/draft/server/discover), the transport served at each `remotes[]` endpoint, and descriptive fields (`title`, `description`, `icons`) — SHOULD NOT contradict the equivalent values declared in the Server Card." + excluded: 'The `icons` part only. Icon arrays can differ in order, size and theme without contradicting each other, so there is no crisp comparison; the other fields are checked above.' + - text: 'MCP Clients SHOULD respect `Cache-Control` headers, use returned `ETag` validators as described in [Caching](#caching), and avoid unnecessary polling.' + excluded: 'A client requirement; this scenario tests servers.' + - text: "A remote's `extensionsInfo` map carries server-level information defined by each extension; it is not a declaration of extension support. Clients MUST NOT infer from the presence or absence of an entry whether the server supports that extension" + excluded: 'A client requirement; this scenario tests servers.' + - text: 'Clients MUST NOT rely on such information from a Server Card hosted on another origin or embedded inline in a catalog entry.' + excluded: 'A client requirement; this scenario tests servers.' + - text: 'Clients MUST NOT treat Server Card contents as authoritative for security or access-control decisions for which the live connection is the source of truth.' + excluded: 'A client requirement; this scenario tests servers.' diff --git a/src/types.ts b/src/types.ts index ebe75a27..f098621e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -103,7 +103,9 @@ export const EXTENSION_IDS = [ 'io.modelcontextprotocol/auth/dpop', 'io.modelcontextprotocol/auth/wif', 'io.modelcontextprotocol/tasks', - 'io.modelcontextprotocol/skills' + 'io.modelcontextprotocol/skills', + // SEP-2127 Server Cards (Extension Identifier in the SEP header). + 'io.modelcontextprotocol/server-card' ] as const; export type ExtensionId = (typeof EXTENSION_IDS)[number];