chadtmiller.com/monolith
An atproto PDS
0
0
MCP: legacy clients too, 2025-11-25 and 2025-06-18, beside 2026-07-28
crates/pds-server/src/mcp.rs+165−34
| @@ -1,7 +1,11 @@ | ||
//! The MCP endpoint, `POST /mcp`: Streamable HTTP for protocol version | ||
//! 2026-07-28, stateless, serving `server/discover`, `tools/list` and | ||
//! `tools/call`. Each method with a JSON answer, or none, is a tool (`spec/COMMANDS.md`), | ||
//! called through the same handling as XRPC. | ||
//! The MCP endpoint, `POST /mcp`: Streamable HTTP, dual-era | ||
//! (`spec/COMMANDS.md`, "The MCP endpoint"). A request with `_meta`'s | ||
//! protocol version is served statelessly as 2026-07-28, with | ||
//! `server/discover`, `tools/list` and `tools/call`; an `initialize`, and the | ||
//! requests after it that name a legacy version in `MCP-Protocol-Version`, | ||
//! as 2025-11-25 or 2025-06-18, statelessly too, with no session. Each | ||
//! method with a JSON answer, or none, is a tool, called through the same | ||
//! handling as XRPC. | ||
| ||
use crate::sessions::Bearer; | ||
use crate::{Auth, Call, Resp, Shared, answer, authorization, limits}; | ||
| @@ -14,8 +18,15 @@ use pds_lexicon::{Kind, Method as Lexicon}; | ||
use serde_json::{Map, Value as Json, json}; | ||
use std::sync::OnceLock; | ||
| ||
/// The one protocol version served. | ||
/// The modern protocol version. | ||
const VERSION: &str = "2026-07-28"; | ||
/// The legacy versions, opened by `initialize`: the first is answered to a | ||
/// client asking for one not served. | ||
const LEGACY: [&str; 2] = ["2025-11-25", "2025-06-18"]; | ||
/// Every version served, as `server/discover` and `UnsupportedProtocolVersionError` name them. | ||
const SUPPORTED: [&str; 3] = [VERSION, LEGACY[0], LEGACY[1]]; | ||
/// What the server says of itself, to a client of either era. | ||
const INSTRUCTIONS: &str = "An atproto PDS holding any number of accounts. Each tool is an XRPC method of the server, with its arguments and answer; a `repo` or `did` left out, with a token, is the token's account's DID."; | ||
| ||
const PARSE_ERROR: i64 = -32700; | ||
const INVALID_REQUEST: i64 = -32600; | ||
| @@ -251,18 +262,129 @@ fn mismatch(name: &str, header: &str, body: &str) -> RpcError { | ||
) | ||
} | ||
| ||
/// Check a request's headers and `_meta`, then answer it with its result. | ||
/// Answer a request in the era it opens: an `initialize`, or a legacy | ||
/// `MCP-Protocol-Version` with no `_meta` version, is legacy; anything else | ||
/// is held to the modern rules. | ||
async fn request( | ||
st: &Shared, | ||
headers: &HeaderMap, | ||
method: &str, | ||
params: Option<&Json>, | ||
client: String, | ||
) -> Result<Json, RpcError> { | ||
if method == "initialize" { | ||
return initialize(params); | ||
} | ||
let meta_version = params | ||
.and_then(|p| p.get("_meta")) | ||
.and_then(|m| m.get("io.modelcontextprotocol/protocolVersion")); | ||
let header = headers | ||
.get("mcp-protocol-version") | ||
.and_then(|v| v.to_str().ok()); | ||
if meta_version.is_none() && header.is_some_and(|v| LEGACY.contains(&v)) { | ||
return legacy(st, headers, method, params, client).await; | ||
} | ||
modern(st, headers, method, params, client).await | ||
} | ||
| ||
/// The legacy handshake (`mcp/legacy/2025-11-25/basic/lifecycle.md`): the | ||
/// version asked for if served, else the latest legacy one; no session. | ||
fn initialize(params: Option<&Json>) -> Result<Json, RpcError> { | ||
let Some(asked) = params | ||
.and_then(|p| p.get("protocolVersion")) | ||
.and_then(Json::as_str) | ||
else { | ||
return Err(rpc_err( | ||
StatusCode::OK, | ||
INVALID_PARAMS, | ||
"params.protocolVersion is required", | ||
)); | ||
}; | ||
let version = LEGACY | ||
.iter() | ||
.find(|v| **v == asked) | ||
.copied() | ||
.unwrap_or(LEGACY[0]); | ||
Ok(json!({ | ||
"protocolVersion": version, | ||
"capabilities": { "tools": {} }, | ||
"serverInfo": server_info(), | ||
"instructions": INSTRUCTIONS, | ||
})) | ||
} | ||
| ||
/// A request after `initialize`, in a legacy revision's shape: `ping`, | ||
/// `tools/list` and `tools/call`, the same tools and answers as the modern | ||
/// era's, without its fields; anything else not found. Errors are HTTP 200. | ||
async fn legacy( | ||
st: &Shared, | ||
headers: &HeaderMap, | ||
method: &str, | ||
params: Option<&Json>, | ||
client: String, | ||
) -> Result<Json, RpcError> { | ||
let params = match params { | ||
None | Some(Json::Null) => &Map::new(), | ||
Some(Json::Object(p)) => p, | ||
Some(_) => { | ||
return Err(rpc_err( | ||
StatusCode::OK, | ||
INVALID_PARAMS, | ||
"params must be an object", | ||
)); | ||
} | ||
}; | ||
match method { | ||
"ping" => Ok(json!({})), | ||
"tools/list" => match params.get("cursor") { | ||
Some(c) if !c.is_null() => { | ||
Err(rpc_err(StatusCode::OK, INVALID_PARAMS, "Invalid cursor")) | ||
} | ||
_ => Ok(json!({ "tools": tools() })), | ||
}, | ||
"tools/call" => { | ||
let Some(name) = params.get("name").and_then(Json::as_str) else { | ||
return Err(rpc_err( | ||
StatusCode::OK, | ||
INVALID_PARAMS, | ||
"params.name must be a tool's name", | ||
)); | ||
}; | ||
let (content, is_error) = call_tool( | ||
st, | ||
name, | ||
params.get("arguments"), | ||
authorization(headers), | ||
client, | ||
) | ||
.await?; | ||
Ok(json!({ | ||
"content": [{ "type": "text", "text": content.to_string() }], | ||
"structuredContent": content, | ||
"isError": is_error, | ||
})) | ||
} | ||
_ => Err(rpc_err( | ||
StatusCode::OK, | ||
METHOD_NOT_FOUND, | ||
format!("Method not found: {method}"), | ||
)), | ||
} | ||
} | ||
| ||
/// Check a modern request's headers and `_meta`, then answer it with its result. | ||
async fn modern( | ||
st: &Shared, | ||
headers: &HeaderMap, | ||
method: &str, | ||
params: Option<&Json>, | ||
client: String, | ||
) -> Result<Json, RpcError> { | ||
let version = required_header(headers, "mcp-protocol-version").map_err(|mut e| { | ||
e.message = format!( | ||
"{}; this server supports protocol version {VERSION}", | ||
e.message | ||
"{}; this server supports protocol versions {}", | ||
e.message, | ||
SUPPORTED.join(", ") | ||
); | ||
e | ||
})?; | ||
| @@ -271,7 +393,7 @@ async fn request( | ||
status: StatusCode::BAD_REQUEST, | ||
code: UNSUPPORTED_PROTOCOL_VERSION, | ||
message: "Unsupported protocol version".into(), | ||
data: Some(json!({ "supported": [VERSION], "requested": version })), | ||
data: Some(json!({ "supported": SUPPORTED, "requested": version })), | ||
}); | ||
} | ||
let header_method = required_header(headers, "mcp-method")?; | ||
| @@ -339,36 +461,49 @@ async fn request( | ||
if header_name != name { | ||
return Err(mismatch("Mcp-Name", &header_name, name)); | ||
} | ||
call_tool( | ||
let (content, is_error) = call_tool( | ||
st, | ||
name, | ||
params.get("arguments"), | ||
authorization(headers), | ||
client, | ||
) | ||
.await | ||
.await?; | ||
Ok(json!({ | ||
"resultType": "complete", | ||
"content": [{ "type": "text", "text": content.to_string() }], | ||
"structuredContent": content, | ||
"isError": is_error, | ||
"_meta": server_meta(), | ||
})) | ||
} | ||
} | ||
} | ||
| ||
/// The server's name and version, as either era names it. | ||
fn server_info() -> Json { | ||
json!({ "name": "pds", "version": env!("CARGO_PKG_VERSION") }) | ||
} | ||
| ||
fn server_meta() -> Json { | ||
json!({ "io.modelcontextprotocol/serverInfo": { "name": "pds", "version": env!("CARGO_PKG_VERSION") } }) | ||
json!({ "io.modelcontextprotocol/serverInfo": server_info() }) | ||
} | ||
| ||
fn discover() -> Json { | ||
json!({ | ||
"resultType": "complete", | ||
"supportedVersions": [VERSION], | ||
"supportedVersions": SUPPORTED, | ||
"capabilities": { "tools": {} }, | ||
"instructions": "An atproto PDS holding any number of accounts. Each tool is an XRPC method of the server, with its arguments and answer; a `repo` or `did` left out, with a token, is the token's account's DID.", | ||
"instructions": INSTRUCTIONS, | ||
"_meta": server_meta(), | ||
"ttlMs": 0, | ||
"cacheScope": "public", | ||
}) | ||
} | ||
| ||
fn list_tools() -> Json { | ||
let tools: Vec<Json> = pds_lexicon::methods() | ||
/// Every tool, the same in either era. | ||
fn tools() -> Vec<Json> { | ||
pds_lexicon::methods() | ||
.iter() | ||
.filter_map(|m| { | ||
let name = m.tool()?; | ||
| @@ -381,8 +516,11 @@ fn list_tools() -> Json { | ||
} | ||
Some(tool) | ||
}) | ||
.collect(); | ||
json!({ "resultType": "complete", "tools": tools, "_meta": server_meta(), "ttlMs": 0, "cacheScope": "public" }) | ||
.collect() | ||
} | ||
| ||
fn list_tools() -> Json { | ||
json!({ "resultType": "complete", "tools": tools(), "_meta": server_meta(), "ttlMs": 0, "cacheScope": "public" }) | ||
} | ||
| ||
/// A query parameter's text, as XRPC takes it. | ||
| @@ -394,14 +532,15 @@ fn param_text(v: &Json) -> String { | ||
} | ||
| ||
/// Call a tool's method, with its arguments as the query's parameters or the | ||
/// procedure's input, and the request's `Authorization` header, from `client`. | ||
/// procedure's input, and the request's `Authorization` header, from `client`: | ||
/// its answer, and whether it is an error the method answered. | ||
async fn call_tool( | ||
st: &Shared, | ||
name: &str, | ||
arguments: Option<&Json>, | ||
authorization: Option<String>, | ||
client: String, | ||
) -> Result<Json, RpcError> { | ||
) -> Result<(Json, bool), RpcError> { | ||
let bearer = Bearer::of(authorization.as_deref()); | ||
let Some(m): Option<&'static Lexicon> = pds_lexicon::by_tool(name) else { | ||
return Err(rpc_err( | ||
| @@ -499,13 +638,7 @@ async fn call_tool( | ||
), | ||
Err(e) => (json!({ "error": e.name, "message": e.message }), true), | ||
}; | ||
Ok(json!({ | ||
"resultType": "complete", | ||
"content": [{ "type": "text", "text": content.to_string() }], | ||
"structuredContent": content, | ||
"isError": is_error, | ||
"_meta": server_meta(), | ||
})) | ||
Ok((content, is_error)) | ||
} | ||
| ||
#[cfg(test)] | ||
| @@ -559,18 +692,16 @@ mod tests { | ||
} | ||
} | ||
}; | ||
let refused = tool("server_delete_session", Some(json!({ "x": 1 }))).await; | ||
let (refused, is_error) = tool("server_delete_session", Some(json!({ "x": 1 }))).await; | ||
assert_eq!( | ||
(&refused["isError"], &refused["structuredContent"]["error"]), | ||
(&json!(true), &json!("InvalidRequest")) | ||
(is_error, &refused["error"]), | ||
(true, &json!("InvalidRequest")) | ||
); | ||
for args in [None, Some(json!({}))] { | ||
let r = tool("server_delete_session", args).await; | ||
assert_eq!( | ||
(&r["isError"], &r["structuredContent"]), | ||
(&json!(false), &json!({})) | ||
tool("server_delete_session", args).await, | ||
(json!({}), false) | ||
); | ||
assert_eq!(r["content"], json!([{ "type": "text", "text": "{}" }])); | ||
} | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
harness/checks/commands.mjs+69−3
| @@ -5,7 +5,7 @@ import { isDeepStrictEqual } from 'node:util' | ||
import { cand } from '../lib/processes.mjs' | ||
import { accounts, tokenOf } from '../lib/state.mjs' | ||
import { count, differ } from '../lib/report.mjs' | ||
import { ACCOUNT_ARGS, METHODS, MCP_VERSION, mcpRpc, runCli } from '../lib/via.mjs' | ||
import { ACCOUNT_ARGS, METHODS, MCP_LEGACY, MCP_VERSION, mcpPost, mcpRpc, mcpShape, runCli } from '../lib/via.mjs' | ||
| ||
/// What a lexicon type is as JSON Schema, by spec/COMMANDS.md: the `type` | ||
/// expected, or undefined for none. | ||
| @@ -15,19 +15,83 @@ function schemaType(t) { | ||
return undefined | ||
} | ||
| ||
/// What a tool is, beside its era's shape: its name, description, schema | ||
/// and annotations, the same in every era. | ||
const toolOf = (t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema, annotations: t.annotations }) | ||
| ||
/// The legacy era, `era` (spec/COMMANDS.md, "The MCP endpoint"): `initialize` | ||
/// with and without the version header, answering that revision with the | ||
/// tools capability, the server's identity and instructions as | ||
/// `server/discover` gives them, and no session; the notification after it; | ||
/// `ping`; the tools as in the modern era; and what it refuses. | ||
async function checkLegacy(era, own, discovered, modernTools) { | ||
const fail = (what, request, want, got) => differ(`MCP ${what} (${era})`, request, want, got) | ||
const serverInfo = discovered._meta?.['io.modelcontextprotocol/serverInfo'] | ||
for (const header of [true, false]) { | ||
const request = { protocolVersion: era, capabilities: {}, clientInfo: { name: 'spec-pds-harness', version: '0' } } | ||
const r = await mcpPost({ jsonrpc: '2.0', id: 1, method: 'initialize', params: request }, header ? { 'mcp-protocol-version': era } : {}) | ||
const m = r.messages?.[0] | ||
const at = { ...request, header: header ? era : 'none' } | ||
if (r.http !== 200 || !m?.result) await fail('initialize', at, 'an InitializeResult, HTTP 200', r.failed ?? { http: r.http, message: m }) | ||
const check = mcpShape(era, 'InitializeResult') | ||
if (!check(m.result)) await fail('initialize', at, `a result valid against the ${era} schema`, check.errors.slice(0, 5)) | ||
const want = { protocolVersion: era, tools: true, serverInfo, instructions: discovered.instructions, session: null } | ||
const got = { protocolVersion: m.result.protocolVersion, tools: !!m.result.capabilities?.tools, serverInfo: m.result.serverInfo, instructions: m.result.instructions, session: r.headers.get('mcp-session-id') } | ||
if (!isDeepStrictEqual(got, want)) await fail('initialize', at, want, got) | ||
} | ||
const note = await mcpPost({ jsonrpc: '2.0', method: 'notifications/initialized' }, { 'mcp-protocol-version': era }) | ||
if (note.http !== 202 || note.messages?.length) await fail('notifications/initialized', {}, '202 Accepted, no body', note.failed ?? { http: note.http, messages: note.messages }) | ||
const ping = await mcpRpc('ping', {}, undefined, 'EmptyResult', era) | ||
if (!isDeepStrictEqual(ping.message?.result, {})) await fail('ping', {}, {}, ping.message ?? ping) | ||
const list = await mcpRpc('tools/list', {}, own, 'ListToolsResult', era) | ||
if (list.failed || list.message.error) await fail('tools/list', {}, 'a ListToolsResult', list) | ||
const tools = list.message.result.tools.map(toolOf) | ||
if (!isDeepStrictEqual(tools, modernTools.map(toolOf))) await fail('tools/list', {}, 'the modern era\'s tools, names, descriptions, schemas and annotations', tools.filter((t, i) => !isDeepStrictEqual(t, toolOf(modernTools[i] ?? {}))).slice(0, 3)) | ||
const unknown = await mcpRpc('tools/call', { name: 'no_such_tool', arguments: {} }, own, 'CallToolResult', era) | ||
if (unknown.message?.error?.code !== -32602) await fail('tools/call', { name: 'no_such_tool' }, 'the protocol error -32602', unknown.message ?? unknown) | ||
const discover = await mcpPost({ jsonrpc: '2.0', id: 1, method: 'server/discover', params: {} }, { 'mcp-protocol-version': era }) | ||
if (discover.messages?.[0]?.error?.code !== -32601) await fail('server/discover', {}, 'the protocol error -32601: no such method in this era', discover.messages?.[0] ?? discover) | ||
count(`MCP legacy ${era}`, true) | ||
} | ||
| ||
/// What both eras refuse: a request naming no version, one naming a | ||
/// revision the server does not serve, an `initialize` asking for one, and | ||
/// `GET` and `DELETE`. | ||
async function checkMcpRefusals(versions) { | ||
const none = await mcpPost({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }, {}) | ||
if (none.http !== 400 || none.messages?.[0]?.error?.code !== -32020) await differ('MCP tools/list', { version: 'none, in a header or _meta' }, 'HTTP 400 and -32020', none.failed ?? { http: none.http, message: none.messages?.[0] }) | ||
const old = await mcpPost({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }, { 'mcp-protocol-version': '2025-03-26' }) | ||
const e = old.messages?.[0]?.error | ||
if (old.http !== 400 || e?.code !== -32022 || !isDeepStrictEqual(e?.data?.supported, versions)) await differ('MCP tools/list', { 'MCP-Protocol-Version': '2025-03-26' }, { http: 400, code: -32022, supported: versions }, old.failed ?? { http: old.http, error: e }) | ||
for (const asked of ['2025-03-26', '1999-01-01']) { | ||
const r = await mcpPost({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: asked, capabilities: {}, clientInfo: { name: 'spec-pds-harness', version: '0' } } }, {}) | ||
if (r.messages?.[0]?.result?.protocolVersion !== MCP_LEGACY[0]) await differ('MCP initialize', { protocolVersion: asked }, `protocolVersion ${MCP_LEGACY[0]}, the latest legacy revision`, r.messages?.[0] ?? r) | ||
} | ||
for (const method of ['GET', 'DELETE']) { | ||
const res = await fetch(`${cand.url}/mcp`, { method, headers: { accept: 'text/event-stream' } }) | ||
await res.arrayBuffer() | ||
if (res.status !== 405) await differ(`MCP ${method} /mcp`, {}, '405 Method Not Allowed', res.status) | ||
} | ||
count('MCP refusals', true) | ||
} | ||
| ||
/// The tools and commands, as spec/COMMANDS.md derives them from the | ||
/// lexicons: `server/discover`, the tool list and each tool's schema, the | ||
/// CLI's help at each level, and usage errors for what it does not take. | ||
/// legacy era, the CLI's help at each level, and usage errors for what it | ||
/// does not take. | ||
export async function checkCommands() { | ||
const own = tokenOf(cand, accounts[0]) | ||
const d = await mcpRpc('server/discover', {}, undefined, 'DiscoverResult') | ||
if (d.failed || d.message.error) await differ('MCP server/discover', {}, 'a DiscoverResult', d) | ||
if (!d.message.result.supportedVersions?.includes(MCP_VERSION) || !d.message.result.capabilities?.tools) await differ('MCP server/discover', {}, `supportedVersions with ${MCP_VERSION}, and the tools capability`, d.message.result) | ||
const versions = [MCP_VERSION, ...MCP_LEGACY] | ||
if (!isDeepStrictEqual(d.message.result.supportedVersions, versions) || !d.message.result.capabilities?.tools) await differ('MCP server/discover', {}, `supportedVersions ${versions}, and the tools capability`, d.message.result) | ||
const want = Object.values(METHODS).filter((m) => m.tool) | ||
let modernTools | ||
for (const token of [undefined, own]) { | ||
const r = await mcpRpc('tools/list', {}, token, 'ListToolsResult') | ||
if (r.failed || r.message.error) await differ('MCP tools/list', { token: token ? 'the account\'s' : 'none' }, 'a ListToolsResult', r) | ||
const tools = r.message.result.tools | ||
modernTools = tools | ||
const names = tools.map((t) => t.name).sort() | ||
if (!isDeepStrictEqual(names, want.map((m) => m.tool).sort())) await differ('MCP tools/list', { token: token ? 'the account\'s' : 'none' }, want.map((m) => m.tool).sort(), names, 'a tool for every method with a JSON answer or none') | ||
for (const m of want) { | ||
| @@ -57,6 +121,8 @@ export async function checkCommands() { | ||
const malformed = await mcpRpc('tools/call', { name: METHODS['com.atproto.repo.getRecord'].tool, arguments: 'not an object' }, own, 'CallToolResult') | ||
if (malformed.message?.error?.code !== -32602) await differ('MCP tools/call', { arguments: 'not an object' }, 'the protocol error -32602', malformed.message ?? malformed) | ||
count('tool list and schemas', true) | ||
for (const era of MCP_LEGACY) await checkLegacy(era, own, d.message.result, modernTools) | ||
await checkMcpRefusals(versions) | ||
| ||
const cli = Object.values(METHODS).filter((m) => m.command) | ||
const top = await runCli(['--help']) | ||
harness/lib/via.mjs+62−39
| @@ -6,8 +6,9 @@ import { readFileSync, readdirSync, statSync } from 'node:fs' | ||
import { join } from 'node:path' | ||
import { isDeepStrictEqual } from 'node:util' | ||
import Ajv2020 from 'ajv/dist/2020.js' | ||
import Ajv07 from 'ajv' | ||
import { command } from './args.mjs' | ||
import { chance } from './random.mjs' | ||
import { chance, pick } from './random.mjs' | ||
import { cand } from './processes.mjs' | ||
import { count, differ } from './report.mjs' | ||
import { accountWithToken, didOf } from './state.mjs' | ||
| @@ -61,58 +62,76 @@ export const METHODS = (() => { | ||
export const ACCOUNT_ARGS = ['repo', 'did'] | ||
| ||
export const MCP_VERSION = '2026-07-28' | ||
const ajv = new Ajv2020({ strict: false, validateFormats: false, allErrors: true }) | ||
ajv.addSchema(JSON.parse(readFileSync(new URL('../../spec/mcp/schema.json', import.meta.url), 'utf8')), 'mcp') | ||
const mcpShape = (name) => ajv.getSchema(`mcp#/$defs/${name}`) | ||
/// The legacy revisions the endpoint serves beside the modern one, each with | ||
/// an `initialize` handshake (spec/COMMANDS.md, "The MCP endpoint"). | ||
export const MCP_LEGACY = ['2025-11-25', '2025-06-18'] | ||
/// Each revision's schema, by version: `2025-06-18`'s is JSON Schema | ||
/// draft-07, under `definitions`; the others are 2020-12, under `$defs`. | ||
const SCHEMAS = (() => { | ||
const load = (p) => JSON.parse(readFileSync(new URL(`../../spec/mcp/${p}`, import.meta.url), 'utf8')) | ||
const modern = new Ajv2020({ strict: false, validateFormats: false, allErrors: true }) | ||
modern.addSchema(load('schema.json'), MCP_VERSION) | ||
modern.addSchema(load('legacy/2025-11-25/schema.json'), '2025-11-25') | ||
const draft07 = new Ajv07({ strict: false, validateFormats: false, allErrors: true }) | ||
draft07.addSchema(load('legacy/2025-06-18/schema.json'), '2025-06-18') | ||
return { [MCP_VERSION]: [modern, '$defs'], '2025-11-25': [modern, '$defs'], '2025-06-18': [draft07, 'definitions'] } | ||
})() | ||
/// A definition of revision `era`'s schema, by name. | ||
export const mcpShape = (era, name) => { | ||
const [ajv, defs] = SCHEMAS[era] | ||
return ajv.getSchema(`${era}#/${defs}/${name}`) | ||
} | ||
let mcpId = 0 | ||
| ||
/// One JSON-RPC request to the server's MCP endpoint. Every message it | ||
/// answers must be valid against MCP's schema, as `shape` names it. | ||
export async function mcpRpc(method, params, token, shape) { | ||
const id = ++mcpId | ||
const body = { | ||
jsonrpc: '2.0', | ||
id, | ||
method, | ||
params: { | ||
...params, | ||
_meta: { | ||
'io.modelcontextprotocol/protocolVersion': MCP_VERSION, | ||
'io.modelcontextprotocol/clientCapabilities': {}, | ||
'io.modelcontextprotocol/clientInfo': { name: 'spec-pds-harness', version: '0' }, | ||
}, | ||
}, | ||
} | ||
const headers = { | ||
'content-type': 'application/json', | ||
accept: 'application/json, text/event-stream', | ||
'mcp-protocol-version': MCP_VERSION, | ||
'mcp-method': method, | ||
} | ||
if (params.name !== undefined) headers['mcp-name'] = params.name | ||
if (token) headers.authorization = `Bearer ${token}` | ||
/// A POST to the server's MCP endpoint with `headers` and `body` as they are; | ||
/// answers its status, headers, and the JSON-RPC messages in its body. | ||
export async function mcpPost(body, headers) { | ||
let res, text | ||
try { | ||
res = await fetch(`${cand.url}/mcp`, { method: 'POST', headers, body: JSON.stringify(body) }) | ||
res = await fetch(`${cand.url}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...headers }, body: JSON.stringify(body) }) | ||
text = await res.text() | ||
} catch (err) { | ||
return { http: 0, failed: err.message } | ||
} | ||
let messages | ||
if (!text) return { http: res.status, headers: res.headers, messages: [] } | ||
try { | ||
messages = (res.headers.get('content-type') ?? '').startsWith('text/event-stream') | ||
const messages = (res.headers.get('content-type') ?? '').startsWith('text/event-stream') | ||
? text.split(/\r?\n\r?\n/).map((ev) => ev.split(/\r?\n/).filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trimStart()).join('\n')).filter(Boolean).map((d) => JSON.parse(d)) | ||
: [JSON.parse(text)] | ||
return { http: res.status, headers: res.headers, messages } | ||
} catch { | ||
return { http: res.status, failed: `an answer that is not JSON-RPC: ${text.slice(0, 200)}` } | ||
} | ||
const message = messages.find((m) => m.id === id) | ||
if (!message) return { http: res.status, failed: `no answer with id ${id}: ${text.slice(0, 200)}` } | ||
for (const m of messages) { | ||
const check = mcpShape(m === message && m.result ? shape : m.error ? 'JSONRPCErrorResponse' : 'JSONRPCMessage') | ||
if (!check(m === message && m.result ? m.result : m)) await differ(`MCP ${method}`, params, `a message valid against mcp/schema.json (${m === message && m.result ? shape : 'JSONRPCMessage'})`, { message: m, errors: check.errors.slice(0, 5) }) | ||
} | ||
| ||
/// One JSON-RPC request to the server's MCP endpoint, in `era`: the modern | ||
/// revision, with its `_meta` and headers, or a legacy one, named in the | ||
/// `MCP-Protocol-Version` header alone, as a client does after `initialize`. | ||
/// Every message it answers must be valid against its era's schema, as | ||
/// `shape` names it. | ||
export async function mcpRpc(method, params, token, shape, era = MCP_VERSION) { | ||
const id = ++mcpId | ||
const modern = era === MCP_VERSION | ||
const meta = { | ||
'io.modelcontextprotocol/protocolVersion': MCP_VERSION, | ||
'io.modelcontextprotocol/clientCapabilities': {}, | ||
'io.modelcontextprotocol/clientInfo': { name: 'spec-pds-harness', version: '0' }, | ||
} | ||
const body = { jsonrpc: '2.0', id, method, params: modern ? { ...params, _meta: meta } : params } | ||
const headers = { 'mcp-protocol-version': era } | ||
if (modern) headers['mcp-method'] = method | ||
if (modern && params.name !== undefined) headers['mcp-name'] = params.name | ||
if (token) headers.authorization = `Bearer ${token}` | ||
const r = await mcpPost(body, headers) | ||
if (r.failed) return r | ||
const message = r.messages.find((m) => m.id === id) | ||
if (!message) return { http: r.http, failed: `no answer with id ${id}: ${JSON.stringify(r.messages).slice(0, 200)}` } | ||
for (const m of r.messages) { | ||
const name = m === message && m.result ? shape : 'JSONRPCMessage' | ||
const check = mcpShape(era, name) | ||
if (!check(m === message && m.result ? m.result : m)) await differ(`MCP ${method}${modern ? '' : ` (${era})`}`, params, `a message valid against the ${era} schema (${name})`, { message: m, errors: check.errors.slice(0, 5) }) | ||
} | ||
return { http: res.status, message } | ||
return { http: r.http, headers: r.headers, message } | ||
} | ||
| ||
/// XRPC error names and their statuses, to set a tool's error, which has no | ||
| @@ -143,7 +162,9 @@ export async function viaTool(nsid, { params, body, token, raw }) { | ||
if (!m?.tool || raw) return null | ||
const args = argsOf(m, params, body, token) | ||
count(`via tool ${m.tool}`, true) | ||
const r = await mcpRpc('tools/call', { name: m.tool, arguments: args }, token, 'CallToolResult') | ||
// Either era, at random: modern, or one of the legacy revisions. | ||
const era = chance(0.5) ? MCP_VERSION : pick(MCP_LEGACY) | ||
const r = await mcpRpc('tools/call', { name: m.tool, arguments: args }, token, 'CallToolResult', era) | ||
if (r.failed) return { status: 0, body: { error: r.failed } } | ||
if (r.message.error) return { status: 0, body: { error: `JSON-RPC ${r.message.error.code}` } } | ||
const result = r.message.result | ||
| @@ -171,7 +192,9 @@ const PDS = command[0] | ||
export function runCli(argv, { token, stdin } = {}) { | ||
return new Promise((ok) => { | ||
const env = { ...process.env, PDS_URL: cand.url } | ||
// The CLI's credentials are the call's alone, never the shell's. | ||
delete env.PDS_TOKEN | ||
delete env.PDS_ADMIN_PASSWORD | ||
if (token) env.PDS_TOKEN = token | ||
const p = spawn(PDS, argv, { env, stdio: ['pipe', 'pipe', 'pipe'] }) | ||
const out = [] | ||
harness/conformance.mjs+11−5
| @@ -1,6 +1,8 @@ | ||
// Starts a server and runs MCP's conformance suite against its `/mcp` | ||
// endpoint, anonymously, for the scenarios that need none of the suite's own | ||
// test tools. `conformance.yaml` names the checks within them that do. | ||
// test tools: the modern revision's, and the legacy ones of 2025-11-25, | ||
// which the endpoint serves beside it (spec/COMMANDS.md, "The MCP | ||
// endpoint"). `conformance.yaml` names the checks within them that do. | ||
// | ||
// node conformance.mjs -- <pds> serve | ||
| ||
| @@ -12,7 +14,11 @@ import { join } from 'node:path' | ||
import { TestPlc } from '@atproto/dev-env' | ||
import { serverEnv } from './lib/env.mjs' | ||
| ||
const SCENARIOS = ['server-stateless', 'tools-list', 'caching', 'dns-rebinding-protection', 'http-header-validation'] | ||
/// Each scenario, with the revision whose requirements it is run against. | ||
const SCENARIOS = [ | ||
...['server-stateless', 'tools-list', 'caching', 'dns-rebinding-protection', 'http-header-validation'].map((s) => [s, '2026-07-28']), | ||
...['server-initialize', 'server-session-lifecycle', 'ping', 'tools-list', 'dns-rebinding-protection'].map((s) => [s, '2025-11-25']), | ||
] | ||
| ||
const dash = process.argv.indexOf('--') | ||
if (dash === -1 || dash === process.argv.length - 1) { | ||
| @@ -54,14 +60,14 @@ for (;;) { | ||
} | ||
| ||
let failed = [] | ||
for (const scenario of SCENARIOS) { | ||
for (const [scenario, version] of SCENARIOS) { | ||
const run = spawn( | ||
'npx', | ||
['conformance', 'server', '--url', `${url}/mcp`, '--scenario', scenario, '--spec-version', '2026-07-28', '--expected-failures', new URL('conformance.yaml', import.meta.url).pathname], | ||
['conformance', 'server', '--url', `${url}/mcp`, '--scenario', scenario, '--spec-version', version, '--expected-failures', new URL('conformance.yaml', import.meta.url).pathname], | ||
{ stdio: 'inherit', cwd: new URL('.', import.meta.url).pathname }, | ||
) | ||
const code = await new Promise((ok) => run.on('exit', ok)) | ||
if (code !== 0) failed.push(scenario) | ||
if (code !== 0) failed.push(`${scenario} (${version})`) | ||
} | ||
server.kill() | ||
await plc.close() | ||
harness/conformance.yaml+5−0
| @@ -8,6 +8,11 @@ server: | ||
- server-stateless:sep-2575-missing-capability-http-400 | ||
- server-stateless:sep-2575-http-server-no-independent-requests-on-stream | ||
- server-stateless:sep-2575-server-no-log-without-loglevel | ||
# This one holds a server that does not implement `initialize`, which | ||
# 2026-07-28 removed, to 404 and -32601 for it. The server implements it, | ||
# for legacy clients, as a dual-era server may (spec/COMMANDS.md, "The | ||
# MCP endpoint"); the legacy scenarios of 2025-11-25 check its answer. | ||
- server-stateless:sep-2575-http-server-method-not-found-404-initialize | ||
# These call prompts/list, resources/list and resources/templates/list | ||
# whatever capabilities a server declares. The server declares only | ||
# tools, so it answers them -32601, as the spec says it must. | ||
spec/mcp/legacy/2025-06-18/basic/utilities/ping.mdnew+66−0
| @@ -0,0 +1,66 @@ | ||
--- | ||
title: Ping | ||
--- | ||
| ||
<div id="enable-section-numbers" /> | ||
| ||
The Model Context Protocol includes an optional ping mechanism that allows either party | ||
to verify that their counterpart is still responsive and the connection is alive. | ||
| ||
## Overview | ||
| ||
The ping functionality is implemented through a simple request/response pattern. Either | ||
the client or server can initiate a ping by sending a `ping` request. | ||
| ||
## Message Format | ||
| ||
A ping request is a standard JSON-RPC request with no parameters: | ||
| ||
```json | ||
{ | ||
"jsonrpc": "2.0", | ||
"id": "123", | ||
"method": "ping" | ||
} | ||
``` | ||
| ||
## Behavior Requirements | ||
| ||
1. The receiver **MUST** respond promptly with an empty response: | ||
| ||
```json | ||
{ | ||
"jsonrpc": "2.0", | ||
"id": "123", | ||
"result": {} | ||
} | ||
``` | ||
| ||
2. If no response is received within a reasonable timeout period, the sender **MAY**: | ||
- Consider the connection stale | ||
- Terminate the connection | ||
- Attempt reconnection procedures | ||
| ||
## Usage Patterns | ||
| ||
```mermaid | ||
sequenceDiagram | ||
participant Sender | ||
participant Receiver | ||
| ||
Sender->>Receiver: ping request | ||
Receiver->>Sender: empty response | ||
``` | ||
| ||
## Implementation Considerations | ||
| ||
- Implementations **SHOULD** periodically issue pings to detect connection health | ||
- The frequency of pings **SHOULD** be configurable | ||
- Timeouts **SHOULD** be appropriate for the network environment | ||
- Excessive pinging **SHOULD** be avoided to reduce network overhead | ||
| ||
## Error Handling | ||
| ||
- Timeouts **SHOULD** be treated as connection failures | ||
- Multiple failed pings **MAY** trigger connection reset | ||
- Implementations **SHOULD** log ping failures for diagnostics | ||
spec/mcp/legacy/2025-06-18/basic/index.mdnew+147−0
| @@ -0,0 +1,147 @@ | ||
--- | ||
title: Overview | ||
--- | ||
| ||
<div id="enable-section-numbers" /> | ||
| ||
The Model Context Protocol consists of several key components that work together: | ||
| ||
- **Base Protocol**: Core JSON-RPC message types | ||
- **Lifecycle Management**: Connection initialization, capability negotiation, and | ||
session control | ||
- **Authorization**: Authentication and authorization framework for HTTP-based transports | ||
- **Server Features**: Resources, prompts, and tools exposed by servers | ||
- **Client Features**: Sampling and root directory lists provided by clients | ||
- **Utilities**: Cross-cutting concerns like logging and argument completion | ||
| ||
All implementations **MUST** support the base protocol and lifecycle management | ||
components. Other components **MAY** be implemented based on the specific needs of the | ||
application. | ||
| ||
These protocol layers establish clear separation of concerns while enabling rich | ||
interactions between clients and servers. The modular design allows implementations to | ||
support exactly the features they need. | ||
| ||
## Messages | ||
| ||
All messages between MCP clients and servers **MUST** follow the | ||
[JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines | ||
these types of messages: | ||
| ||
### Requests | ||
| ||
Requests are sent from the client to the server or vice versa, to initiate an operation. | ||
| ||
```typescript | ||
{ | ||
jsonrpc: "2.0"; | ||
id: string | number; | ||
method: string; | ||
params?: { | ||
[key: string]: unknown; | ||
}; | ||
} | ||
``` | ||
| ||
- Requests **MUST** include a string or integer ID. | ||
- Unlike base JSON-RPC, the ID **MUST NOT** be `null`. | ||
- The request ID **MUST NOT** have been previously used by the requestor within the same | ||
session. | ||
| ||
### Responses | ||
| ||
Responses are sent in reply to requests, containing the result or error of the operation. | ||
| ||
```typescript | ||
{ | ||
jsonrpc: "2.0"; | ||
id: string | number; | ||
result?: { | ||
[key: string]: unknown; | ||
} | ||
error?: { | ||
code: number; | ||
message: string; | ||
data?: unknown; | ||
} | ||
} | ||
``` | ||
| ||
- Responses **MUST** include the same ID as the request they correspond to. | ||
- **Responses** are further sub-categorized as either **successful results** or | ||
**errors**. Either a `result` or an `error` **MUST** be set. A response **MUST NOT** | ||
set both. | ||
- Results **MAY** follow any JSON object structure, while errors **MUST** include an | ||
error code and message at minimum. | ||
- Error codes **MUST** be integers. | ||
| ||
### Notifications | ||
| ||
Notifications are sent from the client to the server or vice versa, as a one-way message. | ||
The receiver **MUST NOT** send a response. | ||
| ||
```typescript | ||
{ | ||
jsonrpc: "2.0"; | ||
method: string; | ||
params?: { | ||
[key: string]: unknown; | ||
}; | ||
} | ||
``` | ||
| ||
- Notifications **MUST NOT** include an ID. | ||
| ||
## Auth | ||
| ||
MCP provides an [Authorization](/specification/2025-06-18/basic/authorization) framework for use with HTTP. | ||
Implementations using an HTTP-based transport **SHOULD** conform to this specification, | ||
whereas implementations using STDIO transport **SHOULD NOT** follow this specification, | ||
and instead retrieve credentials from the environment. | ||
| ||
Additionally, clients and servers **MAY** negotiate their own custom authentication and | ||
authorization strategies. | ||
| ||
For further discussions and contributions to the evolution of MCP’s auth mechanisms, join | ||
us in | ||
[GitHub Discussions](https://github.com/modelcontextprotocol/specification/discussions) | ||
to help shape the future of the protocol! | ||
| ||
## Schema | ||
| ||
The full specification of the protocol is defined as a | ||
[TypeScript schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/2025-06-18/schema.ts). | ||
This is the source of truth for all protocol messages and structures. | ||
| ||
There is also a | ||
[JSON Schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/2025-06-18/schema.json), | ||
which is automatically generated from the TypeScript source of truth, for use with | ||
various automated tooling. | ||
| ||
### General fields | ||
| ||
#### `_meta` | ||
| ||
The `_meta` property/parameter is reserved by MCP to allow clients and servers | ||
to attach additional metadata to their interactions. | ||
| ||
Certain key names are reserved by MCP for protocol-level metadata, as specified below; | ||
implementations MUST NOT make assumptions about values at these keys. | ||
| ||
Additionally, definitions in the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/2025-06-18/schema.ts) | ||
may reserve particular names for purpose-specific metadata, as declared in those definitions. | ||
| ||
**Key name format:** valid `_meta` key names have two segments: an optional **prefix**, and a **name**. | ||
| ||
**Prefix:** | ||
| ||
- 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 can be letters, digits, or hyphens (`-`). | ||
- Any prefix beginning with zero or more valid labels, followed by `modelcontextprotocol` or `mcp`, followed by any valid label, | ||
is **reserved** for MCP use. | ||
- For example: `modelcontextprotocol.io/`, `mcp.dev/`, `api.modelcontextprotocol.org/`, and `tools.mcp.com/` are all reserved. | ||
| ||
**Name:** | ||
| ||
- Unless empty, MUST begin and end with an alphanumeric character (`[a-z0-9A-Z]`). | ||
- MAY contain hyphens (`-`), underscores (`_`), dots (`.`), and alphanumerics in between. | ||
spec/mcp/legacy/2025-06-18/basic/lifecycle.mdnew+244−0
| @@ -0,0 +1,244 @@ | ||
--- | ||
title: Lifecycle | ||
--- | ||
| ||
<div id="enable-section-numbers" /> | ||
| ||
The Model Context Protocol (MCP) defines a rigorous lifecycle for client-server | ||
connections that ensures proper capability negotiation and state management. | ||
| ||
1. **Initialization**: Capability negotiation and protocol version agreement | ||
2. **Operation**: Normal protocol communication | ||
3. **Shutdown**: Graceful termination of the connection | ||
| ||
```mermaid | ||
sequenceDiagram | ||
participant Client | ||
participant Server | ||
| ||
Note over Client,Server: Initialization Phase | ||
activate Client | ||
Client->>+Server: initialize request | ||
Server-->>Client: initialize response | ||
Client--)Server: initialized notification | ||
| ||
Note over Client,Server: Operation Phase | ||
rect rgb(200, 220, 250) | ||
note over Client,Server: Normal protocol operations | ||
end | ||
| ||
Note over Client,Server: Shutdown | ||
Client--)-Server: Disconnect | ||
deactivate Server | ||
Note over Client,Server: Connection closed | ||
``` | ||
| ||
## Lifecycle Phases | ||
| ||
### Initialization | ||
| ||
The initialization phase **MUST** be the first interaction between client and server. | ||
During this phase, the client and server: | ||
| ||
- Establish protocol version compatibility | ||
- Exchange and negotiate capabilities | ||
- Share implementation details | ||
| ||
The client **MUST** initiate this phase by sending an `initialize` request containing: | ||
| ||
- Protocol version supported | ||
- Client capabilities | ||
- Client implementation information | ||
| ||
```json | ||
{ | ||
"jsonrpc": "2.0", | ||
"id": 1, | ||
"method": "initialize", | ||
"params": { | ||
"protocolVersion": "2025-06-18", | ||
"capabilities": { | ||
"roots": { | ||
"listChanged": true | ||
}, | ||
"sampling": {}, | ||
"elicitation": {} | ||
}, | ||
"clientInfo": { | ||
"name": "ExampleClient", | ||
"title": "Example Client Display Name", | ||
"version": "1.0.0" | ||
} | ||
} | ||
} | ||
``` | ||
| ||
The server **MUST** respond with its own capabilities and information: | ||
| ||
```json | ||
{ | ||
"jsonrpc": "2.0", | ||
"id": 1, | ||
"result": { | ||
"protocolVersion": "2025-06-18", | ||
"capabilities": { | ||
"logging": {}, | ||
"prompts": { | ||
"listChanged": true | ||
}, | ||
"resources": { | ||
"subscribe": true, | ||
"listChanged": true | ||
}, | ||
"tools": { | ||
"listChanged": true | ||
} | ||
}, | ||
"serverInfo": { | ||
"name": "ExampleServer", | ||
"title": "Example Server Display Name", | ||
"version": "1.0.0" | ||
}, | ||
"instructions": "Optional instructions for the client" | ||
} | ||
} | ||
``` | ||
| ||
After successful initialization, the client **MUST** send an `initialized` notification | ||
to indicate it is ready to begin normal operations: | ||
| ||
```json | ||
{ | ||
"jsonrpc": "2.0", | ||
"method": "notifications/initialized" | ||
} | ||
``` | ||
| ||
- The client **SHOULD NOT** send requests other than | ||
[pings](/specification/2025-06-18/basic/utilities/ping) before the server has responded to the | ||
`initialize` request. | ||
- The server **SHOULD NOT** send requests other than | ||
[pings](/specification/2025-06-18/basic/utilities/ping) and | ||
[logging](/specification/2025-06-18/server/utilities/logging) before receiving the `initialized` | ||
notification. | ||
| ||
#### Version Negotiation | ||
| ||
In the `initialize` request, the client **MUST** send a protocol version it supports. | ||
This **SHOULD** be the _latest_ version supported by the client. | ||
| ||
If the server supports the requested protocol version, it **MUST** respond with the same | ||
version. Otherwise, the server **MUST** respond with another protocol version it | ||
supports. This **SHOULD** be the _latest_ version supported by the server. | ||
| ||
If the client does not support the version in the server's response, it **SHOULD** | ||
disconnect. | ||
| ||
<Note> | ||
If using HTTP, the client **MUST** include the `MCP-Protocol-Version: | ||
<protocol-version>` HTTP header on all subsequent requests to the MCP | ||
server. | ||
For details, see [the Protocol Version Header section in Transports](/specification/2025-06-18/basic/transports#protocol-version-header). | ||
</Note> | ||
| ||
#### Capability Negotiation | ||
| ||
Client and server capabilities establish which optional protocol features will be | ||
available during the session. | ||
| ||
Key capabilities include: | ||
| ||
| Category | Capability | Description | | ||
| -------- | -------------- | ----------------------------------------------------------------------------------------- | | ||
| Client | `roots` | Ability to provide filesystem [roots](/specification/2025-06-18/client/roots) | | ||
| Client | `sampling` | Support for LLM [sampling](/specification/2025-06-18/client/sampling) requests | | ||
| Client | `elicitation` | Support for server [elicitation](/specification/2025-06-18/client/elicitation) requests | | ||
| Client | `experimental` | Describes support for non-standard experimental features | | ||
| Server | `prompts` | Offers [prompt templates](/specification/2025-06-18/server/prompts) | | ||
| Server | `resources` | Provides readable [resources](/specification/2025-06-18/server/resources) | | ||
| Server | `tools` | Exposes callable [tools](/specification/2025-06-18/server/tools) | | ||
| Server | `logging` | Emits structured [log messages](/specification/2025-06-18/server/utilities/logging) | | ||
| Server | `completions` | Supports argument [autocompletion](/specification/2025-06-18/server/utilities/completion) | | ||
| Server | `experimental` | Describes support for non-standard experimental features | | ||
| ||
Capability objects can describe sub-capabilities like: | ||
| ||
- `listChanged`: Support for list change notifications (for prompts, resources, and | ||
tools) | ||
- `subscribe`: Support for subscribing to individual items' changes (resources only) | ||
| ||
### Operation | ||
| ||
During the operation phase, the client and server exchange messages according to the | ||
negotiated capabilities. | ||
| ||
Both parties **MUST**: | ||
| ||
- Respect the negotiated protocol version | ||
- Only use capabilities that were successfully negotiated | ||
| ||
### Shutdown | ||
| ||
During the shutdown phase, one side (usually the client) cleanly terminates the protocol | ||
connection. No specific shutdown messages are defined—instead, the underlying transport | ||
mechanism should be used to signal connection termination: | ||
| ||
#### stdio | ||
| ||
For the stdio [transport](/specification/2025-06-18/basic/transports), the client **SHOULD** initiate | ||
shutdown by: | ||
| ||
1. First, closing the input stream to the child process (the server) | ||
2. Waiting for the server to exit, or sending `SIGTERM` if the server does not exit | ||
within a reasonable time | ||
3. Sending `SIGKILL` if the server does not exit within a reasonable time after `SIGTERM` | ||
| ||
The server **MAY** initiate shutdown by closing its output stream to the client and | ||
exiting. | ||
| ||
#### HTTP | ||
| ||
For HTTP [transports](/specification/2025-06-18/basic/transports), shutdown is indicated by closing the | ||
associated HTTP connection(s). | ||
| ||
## Timeouts | ||
| ||
Implementations **SHOULD** establish timeouts for all sent requests, to prevent hung | ||
connections and resource exhaustion. When the request has not received a success or error | ||
response within the timeout period, the sender **SHOULD** issue a [cancellation | ||
notification](/specification/2025-06-18/basic/utilities/cancellation) for that request and stop waiting for | ||
a response. | ||
| ||
SDKs and other middleware **SHOULD** allow these timeouts to be configured on a | ||
per-request basis. | ||
| ||
Implementations **MAY** choose to reset the timeout clock when receiving a [progress | ||
notification](/specification/2025-06-18/basic/utilities/progress) corresponding to the request, as this | ||
implies that work is actually happening. However, implementations **SHOULD** always | ||
enforce a maximum timeout, regardless of progress notifications, to limit the impact of a | ||
misbehaving client or server. | ||
| ||
## Error Handling | ||
| ||
Implementations **SHOULD** be prepared to handle these error cases: | ||
| ||
- Protocol version mismatch | ||
- Failure to negotiate required capabilities | ||
- Request [timeouts](#timeouts) | ||
| ||
Example initialization error: | ||
| ||
```json | ||
{ | ||
"jsonrpc": "2.0", | ||
"id": 1, | ||
"error": { | ||
"code": -32602, | ||
"message": "Unsupported protocol version", | ||
"data": { | ||
"supported": ["2024-11-05"], | ||
"requested": "1.0.0" | ||
} | ||
} | ||
} | ||
``` | ||
spec/mcp/legacy/2025-06-18/basic/transports.mdnew+297−0
| @@ -0,0 +1,297 @@ | ||
--- | ||
title: Transports | ||
--- | ||
| ||
<div id="enable-section-numbers" /> | ||
| ||
MCP uses JSON-RPC to encode messages. JSON-RPC messages **MUST** be UTF-8 encoded. | ||
| ||
The protocol currently defines two standard transport mechanisms for client-server | ||
communication: | ||
| ||
1. [stdio](#stdio), communication over standard in and standard out | ||
2. [Streamable HTTP](#streamable-http) | ||
| ||
Clients **SHOULD** support stdio whenever possible. | ||
| ||
It is also possible for clients and servers to implement | ||
[custom transports](#custom-transports) in a pluggable fashion. | ||
| ||
## stdio | ||
| ||
In the **stdio** transport: | ||
| ||
- The client launches the MCP server as a subprocess. | ||
- The server reads JSON-RPC messages from its standard input (`stdin`) and sends messages | ||
to its standard output (`stdout`). | ||
- Messages are individual JSON-RPC requests, notifications, or responses. | ||
- Messages are delimited by newlines, and **MUST NOT** contain embedded newlines. | ||
- The server **MAY** write UTF-8 strings to its standard error (`stderr`) for logging | ||
purposes. Clients **MAY** capture, forward, or ignore this logging. | ||
- The server **MUST NOT** write anything to its `stdout` that is not a valid MCP message. | ||
- The client **MUST NOT** write anything to the server's `stdin` that is not a valid MCP | ||
message. | ||
| ||
```mermaid | ||
sequenceDiagram | ||
participant Client | ||
participant Server Process | ||
| ||
Client->>+Server Process: Launch subprocess | ||
loop Message Exchange | ||
Client->>Server Process: Write to stdin | ||
Server Process->>Client: Write to stdout | ||
Server Process--)Client: Optional logs on stderr | ||
end | ||
Client->>Server Process: Close stdin, terminate subprocess | ||
deactivate Server Process | ||
``` | ||
| ||
## Streamable HTTP | ||
| ||
<Info> | ||
| ||
This replaces the [HTTP+SSE | ||
transport](/specification/2024-11-05/basic/transports#http-with-sse) from | ||
protocol version 2024-11-05. See the [backwards compatibility](#backwards-compatibility) | ||
guide below. | ||
| ||
</Info> | ||
| ||
In the **Streamable HTTP** transport, the server operates as an independent process that | ||
can handle multiple client connections. This transport uses HTTP POST and GET requests. | ||
Server can optionally make use of | ||
[Server-Sent Events](https://en.wikipedia.org/wiki/Server-sent_events) (SSE) to stream | ||
multiple server messages. This permits basic MCP servers, as well as more feature-rich | ||
servers supporting streaming and server-to-client notifications and requests. | ||
| ||
The server **MUST** provide a single HTTP endpoint path (hereafter referred to as the | ||
**MCP endpoint**) that supports both POST and GET methods. For example, this could be a | ||
URL like `https://example.com/mcp`. | ||
| ||
#### Security Warning | ||
| ||
When implementing Streamable HTTP transport: | ||
| ||
1. Servers **MUST** validate the `Origin` header on all incoming connections to prevent DNS rebinding attacks | ||
2. When running locally, servers **SHOULD** bind only to localhost (127.0.0.1) rather than all network interfaces (0.0.0.0) | ||
3. Servers **SHOULD** implement proper authentication for all connections | ||
| ||
Without these protections, attackers could use DNS rebinding to interact with local MCP servers from remote websites. | ||
| ||
### Sending Messages to the Server | ||
| ||
Every JSON-RPC message sent from the client **MUST** be a new HTTP POST request to the | ||
MCP endpoint. | ||
| ||
1. The client **MUST** use HTTP POST to send JSON-RPC messages to the MCP endpoint. | ||
2. The client **MUST** include an `Accept` header, listing both `application/json` and | ||
`text/event-stream` as supported content types. | ||
3. The body of the POST request **MUST** be a single JSON-RPC _request_, _notification_, or _response_. | ||
4. If the input is a JSON-RPC _response_ or _notification_: | ||
- If the server accepts the input, the server **MUST** return HTTP status code 202 | ||
Accepted with no body. | ||
- If the server cannot accept the input, it **MUST** return an HTTP error status code | ||
(e.g., 400 Bad Request). The HTTP response body **MAY** comprise a JSON-RPC _error | ||
response_ that has no `id`. | ||
5. If the input is a JSON-RPC _request_, the server **MUST** either | ||
return `Content-Type: text/event-stream`, to initiate an SSE stream, or | ||
`Content-Type: application/json`, to return one JSON object. The client **MUST** | ||
support both these cases. | ||
6. If the server initiates an SSE stream: | ||
- The SSE stream **SHOULD** eventually include JSON-RPC _response_ for the | ||
JSON-RPC _request_ sent in the POST body. | ||
- The server **MAY** send JSON-RPC _requests_ and _notifications_ before sending the | ||
JSON-RPC _response_. These messages **SHOULD** relate to the originating client | ||
_request_. | ||
- The server **SHOULD NOT** close the SSE stream before sending the JSON-RPC _response_ | ||
for the received JSON-RPC _request_, unless the [session](#session-management) | ||
expires. | ||
- After the JSON-RPC _response_ has been sent, the server **SHOULD** close the SSE | ||
stream. | ||
- Disconnection **MAY** occur at any time (e.g., due to network conditions). | ||
Therefore: | ||
- Disconnection **SHOULD NOT** be interpreted as the client cancelling its request. | ||
- To cancel, the client **SHOULD** explicitly send an MCP `CancelledNotification`. | ||
- To avoid message loss due to disconnection, the server **MAY** make the stream | ||
[resumable](#resumability-and-redelivery). | ||
| ||
### Listening for Messages from the Server | ||
| ||
1. The client **MAY** issue an HTTP GET to the MCP endpoint. This can be used to open an | ||
SSE stream, allowing the server to communicate to the client, without the client first | ||
sending data via HTTP POST. | ||
2. The client **MUST** include an `Accept` header, listing `text/event-stream` as a | ||
supported content type. | ||
3. The server **MUST** either return `Content-Type: text/event-stream` in response to | ||
this HTTP GET, or else return HTTP 405 Method Not Allowed, indicating that the server | ||
does not offer an SSE stream at this endpoint. | ||
4. If the server initiates an SSE stream: | ||
- The server **MAY** send JSON-RPC _requests_ and _notifications_ on the stream. | ||
- These messages **SHOULD** be unrelated to any concurrently-running JSON-RPC | ||
_request_ from the client. | ||
- The server **MUST NOT** send a JSON-RPC _response_ on the stream **unless** | ||
[resuming](#resumability-and-redelivery) a stream associated with a previous client | ||
request. | ||
- The server **MAY** close the SSE stream at any time. | ||
- The client **MAY** close the SSE stream at any time. | ||
| ||
### Multiple Connections | ||
| ||
1. The client **MAY** remain connected to multiple SSE streams simultaneously. | ||
2. The server **MUST** send each of its JSON-RPC messages on only one of the connected | ||
streams; that is, it **MUST NOT** broadcast the same message across multiple streams. | ||
- The risk of message loss **MAY** be mitigated by making the stream | ||
[resumable](#resumability-and-redelivery). | ||
| ||
### Resumability and Redelivery | ||
| ||
To support resuming broken connections, and redelivering messages that might otherwise be | ||
lost: | ||
| ||
1. Servers **MAY** attach an `id` field to their SSE events, as described in the | ||
[SSE standard](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation). | ||
- If present, the ID **MUST** be globally unique across all streams within that | ||
[session](#session-management)—or all streams with that specific client, if session | ||
management is not in use. | ||
2. If the client wishes to resume after a broken connection, it **SHOULD** issue an HTTP | ||
GET to the MCP endpoint, and include the | ||
[`Last-Event-ID`](https://html.spec.whatwg.org/multipage/server-sent-events.html#the-last-event-id-header) | ||
header to indicate the last event ID it received. | ||
- The server **MAY** use this header to replay messages that would have been sent | ||
after the last event ID, _on the stream that was disconnected_, and to resume the | ||
stream from that point. | ||
- The server **MUST NOT** replay messages that would have been delivered on a | ||
different stream. | ||
| ||
In other words, these event IDs should be assigned by servers on a _per-stream_ basis, to | ||
act as a cursor within that particular stream. | ||
| ||
### Session Management | ||
| ||
An MCP "session" consists of logically related interactions between a client and a | ||
server, beginning with the [initialization phase](/specification/2025-06-18/basic/lifecycle). To support | ||
servers which want to establish stateful sessions: | ||
| ||
1. A server using the Streamable HTTP transport **MAY** assign a session ID at | ||
initialization time, by including it in an `Mcp-Session-Id` header on the HTTP | ||
response containing the `InitializeResult`. | ||
- The session ID **SHOULD** be globally unique and cryptographically secure (e.g., a | ||
securely generated UUID, a JWT, or a cryptographic hash). | ||
- The session ID **MUST** only contain visible ASCII characters (ranging from 0x21 to | ||
0x7E). | ||
2. If an `Mcp-Session-Id` is returned by the server during initialization, clients using | ||
the Streamable HTTP transport **MUST** include it in the `Mcp-Session-Id` header on | ||
all of their subsequent HTTP requests. | ||
- Servers that require a session ID **SHOULD** respond to requests without an | ||
`Mcp-Session-Id` header (other than initialization) with HTTP 400 Bad Request. | ||
3. The server **MAY** terminate the session at any time, after which it **MUST** respond | ||
to requests containing that session ID with HTTP 404 Not Found. | ||
4. When a client receives HTTP 404 in response to a request containing an | ||
`Mcp-Session-Id`, it **MUST** start a new session by sending a new `InitializeRequest` | ||
without a session ID attached. | ||
5. Clients that no longer need a particular session (e.g., because the user is leaving | ||
the client application) **SHOULD** send an HTTP DELETE to the MCP endpoint with the | ||
`Mcp-Session-Id` header, to explicitly terminate the session. | ||
- The server **MAY** respond to this request with HTTP 405 Method Not Allowed, | ||
indicating that the server does not allow clients to terminate sessions. | ||
| ||
### Sequence Diagram | ||
| ||
```mermaid | ||
sequenceDiagram | ||
participant Client | ||
participant Server | ||
| ||
note over Client, Server: initialization | ||
| ||
Client->>+Server: POST InitializeRequest | ||
Server->>-Client: InitializeResponse<br>Mcp-Session-Id: 1868a90c... | ||
| ||
Client->>+Server: POST InitializedNotification<br>Mcp-Session-Id: 1868a90c... | ||
Server->>-Client: 202 Accepted | ||
| ||
note over Client, Server: client requests | ||
Client->>+Server: POST ... request ...<br>Mcp-Session-Id: 1868a90c... | ||
| ||
alt single HTTP response | ||
Server->>Client: ... response ... | ||
else server opens SSE stream | ||
loop while connection remains open | ||
Server-)Client: ... SSE messages from server ... | ||
end | ||
Server-)Client: SSE event: ... response ... | ||
end | ||
deactivate Server | ||
| ||
note over Client, Server: client notifications/responses | ||
Client->>+Server: POST ... notification/response ...<br>Mcp-Session-Id: 1868a90c... | ||
Server->>-Client: 202 Accepted | ||
| ||
note over Client, Server: server requests | ||
Client->>+Server: GET<br>Mcp-Session-Id: 1868a90c... | ||
loop while connection remains open | ||
Server-)Client: ... SSE messages from server ... | ||
end | ||
deactivate Server | ||
| ||
``` | ||
| ||
### Protocol Version Header | ||
| ||
If using HTTP, the client **MUST** include the `MCP-Protocol-Version: | ||
<protocol-version>` HTTP header on all subsequent requests to the MCP | ||
server, allowing the MCP server to respond based on the MCP protocol version. | ||
| ||
For example: `MCP-Protocol-Version: 2025-06-18` | ||
| ||
The protocol version sent by the client **SHOULD** be the one [negotiated during | ||
initialization](/specification/2025-06-18/basic/lifecycle#version-negotiation). | ||
| ||
For backwards compatibility, if the server does _not_ receive an `MCP-Protocol-Version` | ||
header, and has no other way to identify the version - for example, by relying on the | ||
protocol version negotiated during initialization - the server **SHOULD** assume protocol | ||
version `2025-03-26`. | ||
| ||
If the server receives a request with an invalid or unsupported | ||
`MCP-Protocol-Version`, it **MUST** respond with `400 Bad Request`. | ||
| ||
### Backwards Compatibility | ||
| ||
Clients and servers can maintain backwards compatibility with the deprecated [HTTP+SSE | ||
transport](/specification/2024-11-05/basic/transports#http-with-sse) (from | ||
protocol version 2024-11-05) as follows: | ||
| ||
**Servers** wanting to support older clients should: | ||
| ||
- Continue to host both the SSE and POST endpoints of the old transport, alongside the | ||
new "MCP endpoint" defined for the Streamable HTTP transport. | ||
- It is also possible to combine the old POST endpoint and the new MCP endpoint, but | ||
this may introduce unneeded complexity. | ||
| ||
**Clients** wanting to support older servers should: | ||
| ||
1. Accept an MCP server URL from the user, which may point to either a server using the | ||
old transport or the new transport. | ||
2. Attempt to POST an `InitializeRequest` to the server URL, with an `Accept` header as | ||
defined above: | ||
- If it succeeds, the client can assume this is a server supporting the new Streamable | ||
HTTP transport. | ||
- If it fails with an HTTP 4xx status code (e.g., 405 Method Not Allowed or 404 Not | ||
Found): | ||
- Issue a GET request to the server URL, expecting that this will open an SSE stream | ||
and return an `endpoint` event as the first event. | ||
- When the `endpoint` event arrives, the client can assume this is a server running | ||
the old HTTP+SSE transport, and should use that transport for all subsequent | ||
communication. | ||
| ||
## Custom Transports | ||
| ||
Clients and servers **MAY** implement additional custom transport mechanisms to suit | ||
their specific needs. The protocol is transport-agnostic and can be implemented over any | ||
communication channel that supports bidirectional message exchange. | ||
| ||
Implementers who choose to support custom transports **MUST** ensure they preserve the | ||
JSON-RPC message format and lifecycle requirements defined by MCP. Custom transports | ||
**SHOULD** document their specific connection establishment and message exchange patterns | ||
to aid interoperability. | ||
spec/mcp/legacy/2025-06-18/server/tools.mdnew+443−0
443 lines changed: not loaded until asked for.
spec/mcp/legacy/2025-06-18/changelog.mdnew+45−0
| @@ -0,0 +1,45 @@ | ||
--- | ||
title: Key Changes | ||
--- | ||
| ||
<div id="enable-section-numbers" /> | ||
| ||
This document lists changes made to the Model Context Protocol (MCP) specification since | ||
the previous revision, [2025-03-26](/specification/2025-03-26). | ||
| ||
## Major changes | ||
| ||
1. Remove support for JSON-RPC **[batching](https://www.jsonrpc.org/specification#batch)** | ||
(PR [#416](https://github.com/modelcontextprotocol/specification/pull/416)) | ||
2. Add support for [structured tool output](/specification/2025-06-18/server/tools#structured-content) | ||
(PR [#371](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/371)) | ||
3. Classify MCP servers as [OAuth Resource Servers](/specification/2025-06-18/basic/authorization#authorization-server-discovery), | ||
adding protected resource metadata to discover the corresponding Authorization server. | ||
(PR [#338](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/338)) | ||
4. Require MCP clients to implement Resource Indicators as described in [RFC 8707](https://www.rfc-editor.org/rfc/rfc8707.html) to prevent | ||
malicious servers from obtaining access tokens. | ||
(PR [#734](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/734)) | ||
5. Clarify [security considerations](/specification/2025-06-18/basic/authorization#security-considerations) and best practices | ||
in the authorization spec and in a new [security best practices page](/specification/2025-06-18/basic/security_best_practices). | ||
6. Add support for **[elicitation](/specification/2025-06-18/client/elicitation)**, enabling servers to request additional | ||
information from users during interactions. | ||
(PR [#382](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/382)) | ||
7. Add support for **[resource links](/specification/2025-06-18/server/tools#resource-links)** in | ||
tool call results. (PR [#603](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/603)) | ||
8. Require [negotiated protocol version to be specified](/specification/2025-06-18/basic/transports#protocol-version-header) | ||
via `MCP-Protocol-Version` header in subsequent requests when using HTTP (PR [#548](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/548)). | ||
9. Change **SHOULD** to **MUST** in [Lifecycle Operation](/specification/2025-06-18/basic/lifecycle#operation) | ||
| ||
## Other schema changes | ||
| ||
1. Add `_meta` field to additional interface types (PR [#710](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/710)), | ||
and specify [proper usage](/specification/2025-06-18/basic#meta). | ||
2. Add `context` field to `CompletionRequest`, providing for completion requests to include | ||
previously-resolved variables (PR [#598](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/598)). | ||
3. Add `title` field for human-friendly display names, so that `name` can be used as a programmatic | ||
identifier (PR [#663](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/663)) | ||
| ||
## Full changelog | ||
| ||
For a complete list of all changes that have been made since the last protocol revision, | ||
[see GitHub](https://github.com/modelcontextprotocol/specification/compare/2025-03-26...2025-06-18). | ||
spec/mcp/legacy/2025-06-18/schema.jsonnew+2517−0
A large diff, not shown.
spec/mcp/legacy/2025-11-25/basic/utilities/ping.mdnew+66−0
spec/mcp/legacy/2025-11-25/basic/index.mdnew+267−0
spec/mcp/legacy/2025-11-25/basic/lifecycle.mdnew+286−0
spec/mcp/legacy/2025-11-25/basic/transports.mdnew+320−0
spec/mcp/legacy/2025-11-25/server/tools.mdnew+524−0
524 lines changed: not loaded until asked for.
spec/mcp/legacy/2025-11-25/changelog.mdnew+49−0
spec/mcp/legacy/2025-11-25/schema.jsonnew+4058−0
A large diff, not shown.