~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
464 lines · 33.8 KB Raw History
// The MCP tools and CLI commands themselves, against the lexicons, and the
// admin's reads' tools and commands, against spec/COMMANDS.md, "The admin's
// reads", and against `_logs` and `_stats` over XRPC (spec/COMMANDS.md);
// the account's OAuth and passkey routes' tools and commands, against
// spec/COMMANDS.md, "The account's OAuth sessions" and "The account's
// passkeys" (checks/oauth-account.mjs and checks/passkeys.mjs call them);
// and `pds xrpc`, against the routes and forwarding over XRPC
// and for what it refuses (spec/COMMANDS.md, "Any call"). The calls through
// them are lib/via.mjs's.

import { rmSync } from 'node:fs'
import { isDeepStrictEqual } from 'node:util'
import { cand } from '../lib/processes.mjs'
import { adminRead, statsBetween, statsCounts, statsForm } from '../lib/admin.mjs'
import { sent, settled } from '../lib/observe.mjs'
import { ownHost, takeRequests } from '../lib/services.mjs'
import { accounts, didOf, tokenOf } from '../lib/state.mjs'
import { count, differ } from '../lib/report.mjs'
import { ACCOUNT_ARGS, ADMIN_READS, METHODS, MCP_LEGACY, MCP_VERSION, OAUTH_ROUTES, PASSKEY_ROUTES, hintsOf, mcpPost, mcpRpc, mcpShape, runCli, scratchFile, viaAdminCommand, viaAdminTool, viaXrpc } from '../lib/via.mjs'
import { xrpcHttp } from '../lib/xrpc.mjs'

/// What a lexicon type is as JSON Schema (spec/COMMANDS.md, "Arguments"):
/// the `type` expected, or undefined for none.
function schemaType(t) {
  if (['string', 'integer', 'boolean', 'array'].includes(t)) return t
  if (['object', 'ref', 'union'].includes(t)) return 'object'
  return undefined
}

/// What a tool is, beside its era's shape: its name, title, description,
/// schema and annotations, the same in every era.
const toolOf = (t) => ({ name: t.name, title: t.title, 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: 'monolith-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, titles, 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: 'monolith-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 admin's reads' tools as spec/COMMANDS.md, "The admin's reads", gives
/// them, in `tools`: after every lexicon's tool, and before the account's
/// OAuth and passkey routes' tools, `admin_logs` then `admin_stats`; each
/// with the title and description that page gives, exactly the arguments it
/// lists, typed and bounded as it says, none required, and `readOnlyHint:
/// true`.
async function checkAdminTools(tools, request) {
  const end = tools.length - OAUTH_ROUTES.length - PASSKEY_ROUTES.length
  const last = tools.slice(end - ADMIN_READS.length, end).map((t) => t.name)
  if (!isDeepStrictEqual(last, ADMIN_READS.map((a) => a.tool))) await differ('MCP tools/list', request, `${ADMIN_READS.map((a) => a.tool).join(' then ')} after every lexicon's tool, before the account's OAuth routes' tools`, tools.slice(-12).map((t) => t.name), 'spec/COMMANDS.md, "The admin\'s reads"')
  for (const a of ADMIN_READS) {
    const t = tools.find((x) => x.name === a.tool)
    const s = t.inputSchema ?? {}
    const props = s.properties ?? {}
    const fail = (why, got) => differ(`tool ${a.tool}`, { route: a.route }, why, got, 'spec/COMMANDS.md, "The admin\'s reads"')
    if (t.description !== a.description) await fail(`the description spec/COMMANDS.md gives: ${a.description}`, t.description)
    if (t.title !== a.title) await fail(`the title ${a.title}`, t.title ?? null)
    if (s.type !== 'object' || !isDeepStrictEqual(Object.keys(props).sort(), Object.keys(a.props).sort())) await fail(`an object schema with the properties ${Object.keys(a.props).join(', ') || 'none'}`, s)
    if ((s.required ?? []).length) await fail('no argument required', s.required)
    for (const [k, want] of Object.entries(a.props)) {
      for (const c of ['type', 'enum', 'minimum', 'maximum', 'maxLength']) if (!isDeepStrictEqual(props[k]?.[c], want[c])) await fail(`${k} with ${c} ${JSON.stringify(want[c]) ?? 'none'}`, props[k])
    }
    if (t.annotations?.readOnlyHint !== true) await fail('readOnlyHint: true', t.annotations ?? null)
  }
}

/// The account's own routes' tools, `routes`, as `spec` (a section of
/// spec/COMMANDS.md) gives them, in `tools`: in that section's order, with
/// `after` tools after them; each with the title and description it gives,
/// exactly the arguments it lists, each a `string`, bounded as it says, and
/// required; and its hints. The OAuth routes' tools come after the admin's
/// reads, and the passkey routes' last ("The account's OAuth sessions",
/// "The account's passkeys").
async function checkRouteTools(tools, request, routes, after, spec) {
  const at = tools.slice(tools.length - after - routes.length, tools.length - after).map((t) => t.name)
  if (!isDeepStrictEqual(at, routes.map((r) => r.tool))) await differ('MCP tools/list', request, `${routes.map((r) => r.tool).join(', ')} in that order, ${after ? `then ${after} tools more` : 'last'}`, tools.slice(-12).map((t) => t.name), spec)
  for (const r of routes) {
    const t = tools.find((x) => x.name === r.tool)
    if (!t) continue
    const s = t.inputSchema ?? {}
    const props = s.properties ?? {}
    const fail = (why, got) => differ(`tool ${r.tool}`, { route: r.route }, why, got, spec)
    if (t.title !== r.title) await fail(`the title ${r.title}`, t.title ?? null)
    if (t.description !== r.description) await fail(`the description spec/COMMANDS.md gives: ${r.description}`, t.description)
    if (s.type !== 'object' || !isDeepStrictEqual(Object.keys(props).sort(), Object.keys(r.props).sort())) await fail(`an object schema with the properties ${Object.keys(r.props).join(', ') || 'none'}`, s)
    if (!isDeepStrictEqual([...(s.required ?? [])].sort(), [...r.required].sort())) await fail(`required ${r.required.join(', ') || 'none'}`, s.required ?? [])
    for (const [k, want] of Object.entries(r.props)) {
      for (const c of ['type', 'minLength', 'maxLength']) if (!isDeepStrictEqual(props[k]?.[c], want[c])) await fail(`${k} with ${c} ${JSON.stringify(want[c]) ?? 'none'}`, props[k])
    }
    for (const [h, v] of Object.entries(r.hints)) if (t.annotations?.[h] !== v) await fail(`${h}: ${v}`, t.annotations ?? null)
  }
}

/// `admin_logs` and `admin_stats` in every era, `pds admin logs` and `pds
/// admin stats`, and `pds xrpc query _logs` and `_stats`, with the admin's
/// auth, an account's token and none, answering as `_logs` and `_stats` do
/// over XRPC, turned back as "Answers" says: the same status and error, and
/// the same lines of `_logs` read by what does not change between the
/// reads; each `_stats` answer of the same form, start and version, every
/// number between those of a read over XRPC before and after
/// (spec/COMMANDS.md, "The admin's reads", "Auth", "Answers", "Any call").
async function checkAdminCalls(own) {
  const spec = 'spec/COMMANDS.md, "The admin\'s reads"'
  const password = Buffer.from(cand.admin.replace(/^Basic /, ''), 'base64').toString('utf8').replace(/^[^:]*:/, '')
  await settled()
  const last = sent.filter((r) => r.traceId && r.status > 0 && r.ended !== null).at(-1)
  const [logs, stats] = ADMIN_READS
  // Reads whose lines no read between changes: the last start, and the
  // line of the request the harness sent last, by its trace and by every
  // other argument too.
  const logArgs = [{ msg: 'start', limit: 1 }, { trace: last.traceId }, { trace: last.traceId, msg: 'request', method: last.route, level: 'debug', minMs: 0, limit: 500 }]
  const ways = [
    ...[MCP_VERSION, ...MCP_LEGACY].map((era) => [`tool, ${era}`, (read, args, auth) => viaAdminTool(read, args, auth.header, era)]),
    ['command', (read, args, auth) => viaAdminCommand(read, args, auth.cli)],
    ['pds xrpc', (read, args, auth) => viaXrpc(read.route, { params: args, ...auth.cli })],
  ]
  const named = (way, read) => (way === 'command' ? `pds admin ${read.command}` : way === 'pds xrpc' ? `pds xrpc query ${read.route}` : `tool ${read.tool}`)
  const auths = [
    ['the admin\'s', { header: cand.admin, cli: { adminPassword: password } }],
    ['an account\'s token', { header: `Bearer ${own}`, cli: { token: own } }],
    ['none', { header: undefined, cli: {} }],
  ]
  const overXrpc = async (route, args, auth) => {
    const r = await adminRead(route, { params: Object.fromEntries(Object.entries(args).map(([k, v]) => [k, String(v)])), headers: auth.header ? { authorization: auth.header } : {} })
    return { status: r.status, body: r.body }
  }
  const shape = (a) => (a.status === 200 ? { status: 200, body: a.body } : { status: a.status, error: a.body?.error ?? null })
  for (const [who, auth] of auths) {
    for (const args of logArgs) {
      const want = shape(await overXrpc(logs.route, args, auth))
      for (const [way, call] of ways) {
        const got = shape(await call(logs, args, auth))
        if (!isDeepStrictEqual(got, want)) await differ(named(way, logs), { auth: who, args, way }, want, got, spec)
      }
    }
    const lo = await overXrpc(stats.route, {}, auth)
    const answers = []
    for (const [way, call] of ways) answers.push([way, await call(stats, {}, auth)])
    const hi = await overXrpc(stats.route, {}, auth)
    for (const [way, got] of answers) {
      const at = [named(way, stats), { auth: who, way }]
      if (lo.status !== 200 || hi.status !== 200 || got.status !== 200) {
        if (!isDeepStrictEqual(shape(got), shape(lo)) || !isDeepStrictEqual(shape(hi), shape(lo))) await differ(...at, shape(lo), shape(got), spec)
        continue
      }
      const form = statsForm(got.body) ?? statsForm(lo.body) ?? statsForm(hi.body)
      if (form) await differ(...at, form, got.body, spec)
      if (got.body.version !== lo.body.version || got.body.started !== lo.body.started) await differ(...at, { version: lo.body.version, started: lo.body.started }, { version: got.body.version, started: got.body.started }, spec)
      const off = statsBetween(statsCounts(lo.body), statsCounts(got.body), statsCounts(hi.body))
      if (off) await differ(...at, `each number between those of _stats read over XRPC before and after: ${off.field} from ${off.lo} to ${off.hi}`, off.mid, spec)
    }
  }
  count('the admin\'s reads as tools and commands and through pds xrpc', true)
}

/// The JSON of a request a service got, or its text.
const bodyOf = (b) => {
  const text = b?.length ? b.toString('utf8') : ''
  try {
    return text ? JSON.parse(text) : null
  } catch {
    return text
  }
}

/// `pds xrpc` (spec/COMMANDS.md, "One binary", "Any call"): listed by `pds
/// --help`, and `pds xrpc --help` exiting 0 and saying its kinds; with an
/// account's password token and none, `_oauthSessions` and `_oauthDevices`
/// answering as their routes do over XRPC; a method the server forwards
/// (spec/PROXY.md, "Which requests are forwarded") answering, and
/// forwarded, as over XRPC; a body as `-` with a `Content-Type:` header,
/// importRepo's, answered as over XRPC; and each usage error exiting 2,
/// with what was wrong on standard error and no request reaching a host of
/// the harness's own that `PDS_URL` names, where calls well formed do
/// reach it, as they say.
async function checkXrpc(own) {
  const spec = 'spec/COMMANDS.md, "Any call"'
  const shape = (a) => (a.status === 200 ? { status: 200, body: a.body } : { status: a.status, error: a.body?.error ?? null })
  const top = await runCli(['--help'])
  if (top.code !== 0 || !/^[ \t]*(pds )?xrpc(\s|$)/m.test(top.stdout.toString())) await differ('pds --help', {}, 'exit 0, listing xrpc', { code: top.code, stdout: top.stdout.toString().slice(0, 800) }, 'spec/COMMANDS.md, "One binary"')
  const help = await runCli(['xrpc', '--help'])
  const helpText = help.stdout.toString()
  if (help.code !== 0 || !/query/.test(helpText) || !/procedure/.test(helpText)) await differ('pds xrpc --help', {}, 'exit 0, saying its kinds, query and procedure', { code: help.code, stdout: helpText.slice(0, 800), stderr: help.stderr.slice(0, 300) }, spec)

  // The server's own routes, with the auth each takes.
  for (const route of ['_oauthSessions', '_oauthDevices', '_passkeyList']) {
    for (const [who, token] of [['the account\'s password session', own], ['none', undefined]]) {
      const want = shape(await adminRead(route, { headers: token ? { authorization: `Bearer ${token}` } : {} }))
      const got = shape(await viaXrpc(route, { token }))
      if (!isDeepStrictEqual(got, want)) await differ(`pds xrpc query ${route}`, { auth: who }, want, got, spec)
    }
  }

  // Methods the server forwards to the AppView, a query and a procedure:
  // the same answer, and the same request forwarded.
  const did = didOf(cand, accounts[0])
  const forwards = [
    ['app.bsky.feed.getPosts', { params: { uris: [`at://${did}/app.bsky.feed.post/a`, `at://${did}/app.bsky.feed.post/b`] } }],
    ['app.bsky.graph.muteActor', { body: { actor: did } }],
  ]
  const forwardedOf = (rs) => rs.map((r) => ({ service: r.service, method: r.method, path: r.path, body: bodyOf(r.body) }))
  for (const [nsid, request] of forwards) {
    takeRequests()
    const a = shape(await xrpcHttp(cand, nsid, { ...request, token: own }))
    const aSent = forwardedOf(takeRequests())
    const b = shape(await viaXrpc(nsid, { ...request, token: own }))
    const bSent = forwardedOf(takeRequests())
    if (!isDeepStrictEqual(b, a) || !isDeepStrictEqual(bSent, aSent)) await differ(`pds xrpc ${nsid}`, request, { answer: a, forwarded: aSent }, { answer: b, forwarded: bSent }, `${spec}: a method the server forwards, as XRPC does`)
  }

  // A body not JSON, as `-` with its Content-Type.
  const IMPORT = 'com.atproto.repo.importRepo'
  const car = Buffer.from('not a CAR file')
  const overXrpc = await fetch(`${cand.url}/xrpc/${IMPORT}`, { method: 'POST', headers: { authorization: `Bearer ${own}`, 'content-type': 'application/vnd.ipld.car' }, body: car })
  const want = { status: overXrpc.status, error: overXrpc.status === 200 ? null : (bodyOf(Buffer.from(await overXrpc.arrayBuffer()))?.error ?? null) }
  const got = await viaXrpc(IMPORT, { bytes: car, contentType: 'application/vnd.ipld.car', token: own })
  if (!isDeepStrictEqual({ status: got.status, error: got.status === 200 ? null : (got.body?.error ?? null) }, want)) await differ(`pds xrpc procedure ${IMPORT} Content-Type:application/vnd.ipld.car -`, { stdin: 'not a CAR file' }, want, { status: got.status, error: got.body?.error ?? null }, spec)

  // Usage errors, against a host of the harness's own that counts every
  // request: none may reach it. Calls well formed, beside them, do.
  const host = await ownHost()
  const url = `http://127.0.0.1:${host.port}`
  const N = 'com.example.harness.call'
  const obj = scratchFile('{"a":1}')
  const list = scratchFile('[1]')
  const text = scratchFile('"a"')
  const broken = scratchFile('{"a":')
  const missing = `${obj}.gone`
  const usage = [
    ['a kind of another form', ['fetch', N]],
    ['a kind of another form', ['queries', N]],
    ['a name of another form', ['query', 'not an nsid']],
    ['a name of another form', ['query', 'com.example']],
    ['a name of another form', ['query', '_logs2']],
    ['an argument of no form', ['query', N, 'limit']],
    ['nothing before its separator', ['query', N, '==1']],
    ['nothing before its separator', ['procedure', N, '=a']],
    ['nothing before its separator', ['procedure', N, ':=1']],
    ['nothing before its separator', ['query', N, ':a']],
    ['JSON that does not parse', ['procedure', N, 'k:={']],
    ['a body property given to a query', ['query', N, 'k=v']],
    ['a body property given to a query', ['get', N, 'k:=1']],
    ['- given to a query', ['query', N, '-']],
    ['- beside body properties', ['procedure', N, 'k=v', '-']],
    ['- beside body properties', ['post', N, '-', 'k:=1']],
    ['an @path that cannot be read', ['procedure', N, `@${missing}`]],
    ['an @path that is not a JSON object', ['procedure', N, `@${list}`]],
    ['an @path that is not a JSON object', ['procedure', N, `@${text}`]],
    ['an @path that is not a JSON object', ['procedure', N, `@${broken}`]],
  ]
  for (const [what, args] of usage) {
    const before = host.requests.length
    const r = await runCli(['xrpc', ...args], { url, stdin: '{}' })
    const reached = host.requests.slice(before)
    if (r.code !== 2 || !r.stderr.trim() || reached.length) await differ(`pds ${['xrpc', ...args].join(' ')}`, { what }, 'a usage error: exit 2, what was wrong on standard error, and no request made', { code: r.code, stderr: r.stderr.slice(0, 300), requests: reached }, spec)
  }
  const wellFormed = [
    [['GET', N, 'a==1', 'X-Harness:1', 'a==2'], { method: 'GET', path: `/xrpc/${N}?a=1&a=2` }],
    [['Procedure', N, `@${obj}`, 'k=v', 'n:=2'], { method: 'POST', path: `/xrpc/${N}` }],
    [['post', N, 'Content-Type:text/plain', '-'], { method: 'POST', path: `/xrpc/${N}` }],
  ]
  for (const [args, want] of wellFormed) {
    const before = host.requests.length
    const r = await runCli(['xrpc', ...args], { url, stdin: 'hi' })
    const reached = host.requests.slice(before)
    if (r.code !== 0 || !isDeepStrictEqual(reached, [want])) await differ(`pds ${['xrpc', ...args].join(' ')}`, {}, { code: 0, requests: [want] }, { code: r.code, stderr: r.stderr.slice(0, 300), requests: reached }, spec)
  }
  for (const f of [obj, list, text, broken]) rmSync(f, { force: true })
  await host.close()
  count('pds xrpc: routes, forwarding, bodies and usage', true)
}

/// The tools and commands, as spec/COMMANDS.md derives them from the
/// lexicons and gives the admin's reads' and the account's OAuth and passkey
/// routes': `server/discover`, the tool list and each tool's title, schema
/// and hints, the legacy era, the CLI's help at each level, and usage
/// errors for what it does not take (spec/COMMANDS.md, "One binary",
/// "Names", "Which methods", "The admin's reads", "The account's OAuth
/// sessions", "The account's passkeys", "Arguments", "Hints", "Answers");
/// every tool listed with a token or without, the admin's reads called with
/// the admin's auth, a token and none (spec/COMMANDS.md, "Auth"); and `pds
/// xrpc` (spec/COMMANDS.md, "Any call").
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)
  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)
  // The spaces' methods among them, by their lexicons: each with a JSON
  // answer or none a tool, its hints as "Hints" gives them
  // (spec/SPACES-REPO.md, "Commands"; spec/SPACES-EXPORT.md, "Commands";
  // spec/SPACES-CREDENTIALS.md, "As tools and commands";
  // spec/SPACES-POLICIES.md, "Commands"; spec/SPACES-SYNC.md, "Commands").
  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()
    // And the admin's reads' tools and the account's OAuth and passkey
    // routes' (spec/COMMANDS.md, "The admin's reads", "The account's OAuth
    // sessions", "The account's passkeys").
    const all = [...want.map((m) => m.tool), ...ADMIN_READS.map((a) => a.tool), ...OAUTH_ROUTES.map((r) => r.tool), ...PASSKEY_ROUTES.map((r) => r.tool)].sort()
    if (!isDeepStrictEqual(names, all)) await differ('MCP tools/list', { token: token ? 'the account\'s' : 'none' }, all, names, 'a tool for every method with a JSON answer or none, admin_logs and admin_stats, the four oauth_ tools and the three passkey_ tools')
    await checkAdminTools(tools, { token: token ? 'the account\'s' : 'none' })
    await checkRouteTools(tools, { token: token ? 'the account\'s' : 'none' }, OAUTH_ROUTES, PASSKEY_ROUTES.length, 'spec/COMMANDS.md, "The account\'s OAuth sessions"')
    await checkRouteTools(tools, { token: token ? 'the account\'s' : 'none' }, PASSKEY_ROUTES, 0, 'spec/COMMANDS.md, "The account\'s passkeys"')
    for (const m of want) {
      const t = tools.find((t) => t.name === m.tool)
      const s = t.inputSchema ?? {}
      const props = s.properties ?? {}
      const fail = (why, got) => differ(`tool ${m.tool}`, { method: m.nsid }, why, got)
      if (t.description !== m.description) await fail(`the lexicon's description: ${m.description}`, t.description)
      if (t.title !== m.title) await fail(`the title ${m.title} (spec/COMMANDS.md, "Names")`, t.title ?? null)
      if (s.type !== 'object' || !isDeepStrictEqual(Object.keys(props).sort(), Object.keys(m.props).sort())) await fail(`an object schema with the lexicon's properties: ${Object.keys(m.props).sort()}`, s)
      const required = m.required.filter((k) => !ACCOUNT_ARGS.includes(k)).sort()
      if (!isDeepStrictEqual([...(s.required ?? [])].sort(), required)) await fail(`required ${required}`, s.required ?? [])
      for (const [k, lexProp] of Object.entries(m.props)) {
        const type = schemaType(lexProp.type)
        const want = m.nullable.includes(k) ? [type, 'null'] : type
        if (!isDeepStrictEqual(props[k]?.type, want)) await fail(`${k} of type ${JSON.stringify(want) ?? 'any'}, as its lexicon type ${lexProp.type}${m.nullable.includes(k) ? ', nullable' : ''}`, props[k])
        // An array's lexicon `maxLength` is its JSON Schema `maxItems`.
        const constraints = lexProp.type === 'array' ? [['maxLength', 'maxItems']] : ['minimum', 'maximum', 'maxLength', 'enum'].map((c) => [c, c])
        for (const [c, as] of constraints) if (lexProp[c] !== undefined && !isDeepStrictEqual(props[k]?.[as], lexProp[c])) await fail(`${k} with ${as} ${JSON.stringify(lexProp[c])}`, props[k])
      }
      // By what each method does, not by whether it is a query
      // (spec/COMMANDS.md, "Hints").
      for (const [h, v] of Object.entries(hintsOf(m))) if (t.annotations?.[h] !== v) await fail(`${h}: ${v} (spec/COMMANDS.md, "Hints")`, t.annotations ?? null)
    }
  }
  const unknown = await mcpRpc('tools/call', { name: 'no_such_tool', arguments: {} }, own, 'CallToolResult')
  if (unknown.message?.error?.code !== -32602) await differ('MCP tools/call', { name: 'no_such_tool' }, 'the protocol error -32602', unknown.message ?? unknown)
  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'])
  for (const g of new Set(cli.map((m) => m.group))) {
    if (top.code !== 0 || !top.stdout.toString().includes(g)) await differ('pds --help', {}, `exit 0, listing the group ${g}`, { code: top.code, stdout: top.stdout.toString().slice(0, 500) })
    const h = await runCli([g, '--help'])
    for (const m of cli.filter((m) => m.group === g)) {
      if (h.code !== 0 || !h.stdout.toString().includes(m.command)) await differ(`pds ${g} --help`, {}, `exit 0, listing ${m.command}`, { code: h.code, stdout: h.stdout.toString().slice(0, 500) })
      const c = await runCli([g, m.command, '--help'])
      for (const p of Object.keys(m.props)) if (c.code !== 0 || !c.stdout.toString().includes(m.flag(p))) await differ(`pds ${g} ${m.command} --help`, {}, `exit 0, listing ${m.flag(p)}`, { code: c.code, stdout: c.stdout.toString().slice(0, 500) })
      const bad = await runCli([g, m.command, '--no-such-flag', 'x'])
      if (bad.code !== 2) await differ(`pds ${g} ${m.command} --no-such-flag x`, {}, 'a usage error: exit 2', { code: bad.code, stdout: bad.stdout.toString().slice(0, 300) })
    }
    const none = await runCli([g, 'no-such-command'])
    if (none.code !== 2) await differ(`pds ${g} no-such-command`, {}, 'a usage error: exit 2', { code: none.code })
  }
  // The admin's reads' commands, in the group `admin`, `logs` then `stats`
  // after the commands of com.atproto.admin's methods (spec/COMMANDS.md,
  // "The admin's reads").
  const adminHelp = await runCli(['admin', '--help'])
  const helpText = adminHelp.stdout.toString()
  const listedAt = (command) => helpText.search(new RegExp(`^\\s*${command}(\\s|$)`, 'm'))
  const order = [...cli.filter((m) => m.group === 'admin').map((m) => m.command), ...ADMIN_READS.map((a) => a.command)]
  const at = order.map(listedAt)
  const after = Math.max(...at.slice(0, -ADMIN_READS.length), -1)
  const admins = at.slice(-ADMIN_READS.length)
  if (adminHelp.code !== 0 || admins.some((p) => p === -1) || !(admins[0] > after) || admins.some((p, i) => i && p <= admins[i - 1])) await differ('pds admin --help', {}, `exit 0, listing ${ADMIN_READS.map((a) => a.command).join(' then ')} after the commands of com.atproto.admin's methods`, { code: adminHelp.code, stdout: helpText.slice(0, 800) }, 'spec/COMMANDS.md, "The admin\'s reads"')
  for (const a of ADMIN_READS) {
    const c = await runCli(['admin', a.command, '--help'])
    if (c.code !== 0) await differ(`pds admin ${a.command} --help`, {}, 'exit 0', { code: c.code, stderr: c.stderr.slice(0, 300) }, 'spec/COMMANDS.md, "The admin\'s reads"')
    for (const p of Object.keys(a.props)) if (!c.stdout.toString().includes(a.flag(p))) await differ(`pds admin ${a.command} --help`, {}, `listing ${a.flag(p)}`, c.stdout.toString().slice(0, 500), 'spec/COMMANDS.md, "The admin\'s reads"')
    const bad = await runCli(['admin', a.command, '--no-such-flag', 'x'])
    if (bad.code !== 2) await differ(`pds admin ${a.command} --no-such-flag x`, {}, 'a usage error: exit 2', { code: bad.code, stdout: bad.stdout.toString().slice(0, 300) })
  }
  // The account's OAuth routes' commands: the group `oauth`, listed after
  // every lexicon's group; then its passkey routes', the group `passkey`,
  // after `oauth`, last. Each exactly its commands in its section's order,
  // each with its description and exactly its flags, those of its required
  // arguments required (spec/COMMANDS.md, "The account's OAuth sessions",
  // "The account's passkeys", "Arguments").
  const collapse = (s) => s.replace(/\s+/g, ' ')
  const topText = top.stdout.toString()
  const groupAt = (g) => topText.search(new RegExp(`^[ \\t]*${g}(\\s|$)`, 'm'))
  const groups = [...new Set(cli.map((m) => m.group))]
  const ownGroups = [
    ['oauth', OAUTH_ROUTES, 'spec/COMMANDS.md, "The account\'s OAuth sessions"'],
    ['passkey', PASSKEY_ROUTES, 'spec/COMMANDS.md, "The account\'s passkeys"'],
  ]
  for (const [i, [group, routes, spec]] of ownGroups.entries()) {
    const earlier = ownGroups.slice(0, i).map(([g]) => g)
    if (groupAt(group) === -1 || [...groups, ...earlier].some((g) => groupAt(g) > groupAt(group))) await differ('pds --help', {}, `listing the group ${group} after every lexicon's group${earlier.length ? ` and ${earlier.join(', ')}` : ''}`, { code: top.code, stdout: topText.slice(-800) }, spec)
    const help = await runCli([group, '--help'])
    const text = help.stdout.toString()
    const listed = [...text.matchAll(/^[ \t]+([a-z][a-z0-9-]*)(?=[ \t]|$)/gm)].map((m) => m[1])
    const unsaid = routes.filter((r) => !collapse(text).includes(r.description)).map((r) => r.command)
    if (help.code !== 0 || !isDeepStrictEqual(listed, routes.map((r) => r.command)) || unsaid.length) await differ(`pds ${group} --help`, {}, { code: 0, commands: routes.map((r) => r.command), each: 'with its description' }, { code: help.code, commands: listed, withoutTheirDescription: unsaid, stdout: text.slice(0, 800) }, spec)
    for (const r of routes) {
      const c = await runCli([group, r.command, '--help'])
      const said = c.stdout.toString()
      const flags = [...new Set(said.match(/--[a-z][a-z0-9-]*/g) ?? [])].filter((f) => f !== '--help').sort()
      const wantFlags = Object.keys(r.props).map(r.flag).sort()
      if (c.code !== 0 || !isDeepStrictEqual(flags, wantFlags) || !collapse(said).includes(r.description)) await differ(`pds ${group} ${r.command} --help`, {}, { code: 0, flags: wantFlags, description: r.description }, { code: c.code, flags, stdout: said.slice(0, 800) }, spec)
      const bad = await runCli([group, r.command, '--no-such-flag', 'x'])
      if (bad.code !== 2) await differ(`pds ${group} ${r.command} --no-such-flag x`, {}, 'a usage error: exit 2', { code: bad.code, stdout: bad.stdout.toString().slice(0, 300) }, spec)
      if (r.required.length) {
        const missing = await runCli([group, r.command])
        if (missing.code !== 2) await differ(`pds ${group} ${r.command}`, {}, `a usage error, ${r.required.map(r.flag).join(', ')} missing: exit 2`, { code: missing.code, stdout: missing.stdout.toString().slice(0, 300) }, spec)
      }
    }
    const noCommand = await runCli([group, 'no-such-command'])
    if (noCommand.code !== 2) await differ(`pds ${group} no-such-command`, {}, 'a usage error: exit 2', { code: noCommand.code }, spec)
  }
  count('command help and usage', true)
  await checkAdminCalls(own)
  await checkXrpc(own)
}