跳到主要内容
chapter-18 第五部分 · 开放扩展 · 实现笔记

18 · 手写 MCP Client:传输、版本与进程

里程碑 → legacy stdio 握手、分页、调用和三段关闭全部跑通

第 17 章沿着“行为文本”这条线扩展了模型。另一条线是让 runtime 接入外部工具。

直接装 MCP SDK,只要几行代码。但那样会把最值得亲眼看看的部分一起藏起来:

  • 子进程的 stdout 上到底流过什么。
  • 请求和响应怎么一一对上。
  • 协议版本在什么时候确定。
  • 为什么工具出错不等于协议出错。

MCP 不是 function calling 的替代品。两者管的是不同的事:

  • function calling(在 Anthropic API 里叫 tool use)规定的是:模型怎样从 host 已经声明的工具里挑一个,并提交参数。
  • MCP 规定的是:host 怎样从外部 server 发现有哪些能力、协商协议、发起调用。

这里的 host 指运行 agent、对接模型的那个程序。第 19 章会把 MCP server 返回的工具定义,转换成普通的 Anthropic tools 项。模型仍然沿着原来的 tool-use loop 使用它们。

所以可以这样理解 MCP 在“工具供给”这一侧的价值:

  • 没有统一协议时,M 个 host 对 N 个能力提供方,要各写一套适配,一共 M×N 套。
  • 有了统一协议,两边各实现一次标准接口,一共 M+N 套。

这只是帮助理解的模型。MCP 还包括 Resources 和 Prompts,本书只实现 Tools。

本章暂时不改 agent。我们先写一个只支持 legacy stdio Tools 的 MCP client,外加一个独立的 probe(探测脚本)。它按顺序做这几件事:

  1. 启动 server。
  2. 完成 initialize。
  3. 取完 tools/list。
  4. 调用 tools/call。
  5. 最后把进程收掉。

第 19 章才把 SDK 版的远程工具并进 Tool Map。

能力边界与控制流

spawn(command, args, stdio=pipe)
  stderr ───────────────→ 诊断输出
  stdout 每一行 JSON ──→ parse → 按 response.id 找 pending request
  stdin  一行 JSON  ←── request / notification

initialize(2025-11-25)
  → server 选择 2025-11-25 或 2025-06-18
  → notifications/initialized
  → tools/list(cursor?) 直到 nextCursor 缺失
  → tools/call
  → close stdin → SIGTERM → SIGKILL

本章只承诺下面这些:

  • 只做 stdio transport(通过子进程的标准输入输出通信)。不做 Streamable HTTP、SSE 或 OAuth。
  • 只做 legacy 的 2025-11-25 / 2025-06-18 两个版本。不实现 2026-07-28 的 server/discover,也不实现逐请求的 _meta envelope。
  • 只做 Tools 的 list 和 call。不做 Resources、Prompts、Roots、Sampling 或 Logging。
  • 一个 client 对应一个子进程。不做重连、健康检查、热更新或工具下架。
  • 远程工具还没进入 agent。所以不讨论命名、权限、上下文成本和启动失败时的降级。
  • 默认只把 PATH、HOME、临时目录这些启动必需的变量传给 server。API key 等父进程的环境变量不会被悄悄带过去。额外的变量,必须在这个 server 的配置里明确写出来。

这不是“实现完整的 MCP”。它是一个 vertical slice(从头到尾打通一条最窄的路径),用来讲清 wire protocol(线上实际传输的消息格式)和进程责任。

为什么现在只手写 legacy

MCP 的协议版本分成两个时代:

  • 2024-10-07 到 2025-11-25 属于同一个 legacy era。连接以 initialize 开始,之后发送 notifications/initialized。
  • 2026-07-28 开始是 modern era。先用 server/discover 判断对方有什么能力,之后每次请求都带上协议版本和 client capabilities。

官方 SDK v2 才同时处理这两套行为。

本章用最新的 legacy 版本 2025-11-25 发起协商,同时接受 spike(早期探路实验)实际用过的 2025-06-18。

教学目标是把一条真实的握手跑通。手写 client 里不去复制 SDK 那套 dual-era 探测(同时兼容两个时代)。最终的 runtime 在下一章切到 SDK v2:默认走 legacy,显式设成 auto 时才去探测 modern server。

MCP 2025-11-25 lifecycle定义了本章的握手;SDK v2 protocol versions解释了两种 era 和三种 negotiation mode(协商方式)。

initialize 同时协商版本与能力

legacy 握手不只是互相报个版本号。过程是这样的:

  1. client 发出自己支持的 protocolVersion、clientInfo 和 capabilities。
  2. server 选一个双方都能用的版本,返回 serverInfo 和它提供的 capabilities。

这里的 capabilities: {} 表示:这个最小 client 不向 server 提供 Roots、Sampling 这类反向能力。另一边,server 必须声明 tools,本章才会接着调用 tools/list。

一句话说:版本决定“用哪套语法说话”,capabilities 决定“这条连接上允许说什么”。

stdout 是协议,stderr 才是日志

stdio server 的 stdout 不是普通的终端输出,而是 JSON-RPC 消息的传输通道。启动横幅、debug 日志、报错堆栈,只要混进 stdout,就会被 client 当成协议消息去解析。

stderr 不参与协议,可以转给用户看,用来诊断。

每条 JSON-RPC 消息必须正好占一行,中间不能有换行。这里没有 TCP 那种长度前缀,也没有 HTTP header 或 SSE event。我们只对 readline 交出的完整一行做 JSON.parse。

第三方进程的最小权限

stdio server 是配置文件里指定、由 agent 启动的第三方可执行文件。所以它也是一道供应链边界:你在运行别人写的程序。

defaultMcpEnvironment() 只继承启动必需的 PATH、HOME、临时目录等变量。模型 API key 和父进程的其他 secret,必须按 server 一个个明确传进去。

这是环境变量这一层的最小权限,不是 sandbox。server 仍然可能以当前操作系统用户的身份读文件、访问网络。要限制这些,需要额外的进程隔离机制。

两层错误不能压成一句 throw

tools/call 有两种失败:

  • server 正常处理了请求,但工具本身执行失败:JSON-RPC response 仍是 result,其中 isError: true;模型应看到并有机会修正。
  • 请求本身失败:response 带 JSON-RPC error,例如 method 不存在、参数协议非法或 server 内部异常;client promise reject,并保留 code 与 data。

本章的 probe 会把这两种情况打印成不同的结果。第 19 章把它适配成 ToolResult 时,也必须保留“错误从哪一层来”的区别。

完整代码增量

新建 src/mcp-protocol.ts。它不 import agent、Tool 或 Anthropic SDK:

import {
  spawn,
  type ChildProcessWithoutNullStreams,
} from 'node:child_process'
import { createInterface } from 'node:readline'

const CLIENT_PROTOCOL_VERSION = '2025-11-25'
const SUPPORTED_PROTOCOL_VERSIONS = new Set([
  '2025-11-25',
  '2025-06-18',
])
const DEFAULT_REQUEST_TIMEOUT_MS = 15_000
const MAX_LIST_PAGES = 64
const CLOSE_STDIN_GRACE_MS = 500
const CLOSE_TERM_GRACE_MS = 1_000
const CLOSE_KILL_GRACE_MS = 500
const SAFE_ENV_KEYS = [
  'PATH',
  'HOME',
  'USER',
  'LOGNAME',
  'SHELL',
  'TMPDIR',
  'TEMP',
  'TMP',
  'SystemRoot',
  'WINDIR',
  'ComSpec',
  'PATHEXT',
] as const

type JsonRpcId = number

type JsonRpcResponse = {
  jsonrpc: '2.0'
  id: JsonRpcId
  result?: unknown
  error?: {
    code: number
    message: string
    data?: unknown
  }
}

export type LegacyMcpConfig = {
  command: string
  args?: string[]
  cwd?: string
  env?: NodeJS.ProcessEnv
  requestTimeoutMs?: number
  onStderr?(text: string): void
  onWarning?(text: string): void
}

export type McpToolDefinition = {
  name: string
  description?: string
  inputSchema: Record<string, unknown>
}

export type McpContentBlock = Record<string, unknown> & {
  type: string
}

export type McpToolResult = {
  content: McpContentBlock[]
  isError?: boolean
  structuredContent?: Record<string, unknown>
}

type PendingRequest = {
  resolve(value: unknown): void
  reject(error: Error): void
  timer: NodeJS.Timeout
  removeAbort(): void
}

function isRecord(
  value: unknown,
): value is Record<string, unknown> {
  return value !== null &&
    typeof value === 'object' &&
    !Array.isArray(value)
}

function errorMessage(error: unknown): string {
  return error instanceof Error ? error.message : String(error)
}

export function defaultMcpEnvironment(
  source: NodeJS.ProcessEnv = process.env,
): NodeJS.ProcessEnv {
  const result: NodeJS.ProcessEnv = {}
  for (const key of SAFE_ENV_KEYS) {
    const value = source[key]
    if (value !== undefined) result[key] = value
  }
  return result
}

function parseTool(value: unknown): McpToolDefinition {
  if (
    !isRecord(value) ||
    typeof value.name !== 'string' ||
    value.name === '' ||
    !isRecord(value.inputSchema) ||
    (
      value.description !== undefined &&
      typeof value.description !== 'string'
    )
  ) throw new Error('Invalid MCP tool definition')

  return {
    name: value.name,
    ...(value.description === undefined
      ? {}
      : { description: value.description }),
    inputSchema: value.inputSchema,
  }
}

function parseToolResult(value: unknown): McpToolResult {
  if (!isRecord(value) || !Array.isArray(value.content)) {
    throw new Error('Invalid tools/call result')
  }
  const content = value.content.map((block) => {
    if (!isRecord(block) || typeof block.type !== 'string') {
      throw new Error('Invalid MCP content block')
    }
    return block as McpContentBlock
  })
  if (
    value.isError !== undefined &&
    typeof value.isError !== 'boolean'
  ) throw new Error('Invalid MCP isError field')
  if (
    value.structuredContent !== undefined &&
    !isRecord(value.structuredContent)
  ) throw new Error('Invalid MCP structuredContent field')

  return {
    content,
    ...(value.isError === undefined
      ? {}
      : { isError: value.isError }),
    ...(value.structuredContent === undefined
      ? {}
      : { structuredContent: value.structuredContent }),
  }
}

export class McpProtocolError extends Error {
  constructor(
    readonly code: number,
    message: string,
    readonly data?: unknown,
  ) {
    super(`MCP protocol error ${code}: ${message}`)
    this.name = 'McpProtocolError'
  }
}

export class LegacyMcpClient {
  readonly child: ChildProcessWithoutNullStreams
  private readonly pending = new Map<JsonRpcId, PendingRequest>()
  private nextId = 1
  private state: 'starting' | 'connected' | 'closing' | 'closed' =
    'starting'
  private closePromise: Promise<void> | undefined

  constructor(private readonly config: LegacyMcpConfig) {
    this.child = spawn(config.command, config.args ?? [], {
      cwd: config.cwd,
      // 默认不把 API keys 等整个父进程环境交给第三方 server。
      // config.env 是用户显式添加的 server 专用值。
      env: {
        ...defaultMcpEnvironment(),
        ...(config.env ?? {}),
      },
      stdio: ['pipe', 'pipe', 'pipe'],
      detached: process.platform !== 'win32',
    })

    const lines = createInterface({ input: this.child.stdout })
    lines.on('line', (line) => this.handleLine(line))
    this.child.stdin.on('error', (error) => {
      if (this.state !== 'closing' && this.state !== 'closed') {
        this.protocolFailure(error)
      }
    })
    this.child.stderr.setEncoding('utf8')
    this.child.stderr.on('data', (chunk: string) => {
      this.config.onStderr?.(chunk)
    })
    this.child.once('error', (error) => {
      this.protocolFailure(error)
    })
    this.child.once('close', (code, signal) => {
      if (this.state !== 'closing' && this.state !== 'closed') {
        this.rejectPending(new Error(
          `MCP server exited unexpectedly ` +
          `(code=${String(code)}, signal=${String(signal)})`,
        ))
      } else {
        this.rejectPending(
          new Error('MCP server exited while requests were pending'),
        )
      }
      this.state = 'closed'
    })
  }

  async initialize(signal: AbortSignal): Promise<string> {
    const result = await this.request(
      'initialize',
      {
        protocolVersion: CLIENT_PROTOCOL_VERSION,
        capabilities: {},
        clientInfo: {
          name: 'byoaa-handwritten-client',
          version: '0.1.0',
        },
      },
      signal,
      false,
    )

    if (
      !isRecord(result) ||
      typeof result.protocolVersion !== 'string'
    ) throw new Error('Invalid initialize result')
    if (!SUPPORTED_PROTOCOL_VERSIONS.has(result.protocolVersion)) {
      throw new Error(
        `Server selected unsupported protocol version: ` +
        result.protocolVersion,
      )
    }
    if (
      !isRecord(result.capabilities) ||
      !isRecord(result.capabilities.tools)
    ) {
      throw new Error('MCP server does not declare Tools capability')
    }
    if (
      !isRecord(result.serverInfo) ||
      typeof result.serverInfo.name !== 'string' ||
      typeof result.serverInfo.version !== 'string'
    ) throw new Error('Invalid MCP serverInfo')

    await this.notify('notifications/initialized')
    this.state = 'connected'
    return result.protocolVersion
  }

  async listTools(signal: AbortSignal): Promise<McpToolDefinition[]> {
    this.assertConnected()
    const tools: McpToolDefinition[] = []
    const seenCursors = new Set<string>()
    let cursor: string | undefined
    let pages = 0

    while (true) {
      if (pages >= MAX_LIST_PAGES) {
        throw new Error(
          `MCP tools/list exceeded ${MAX_LIST_PAGES} pages`,
        )
      }
      pages += 1
      const result = await this.request(
        'tools/list',
        cursor === undefined ? {} : { cursor },
        signal,
      )
      if (!isRecord(result) || !Array.isArray(result.tools)) {
        throw new Error('Invalid tools/list result')
      }
      tools.push(...result.tools.map(parseTool))

      const nextCursor = result.nextCursor
      if (nextCursor === undefined) break
      if (typeof nextCursor !== 'string') {
        throw new Error('Invalid tools/list nextCursor')
      }
      if (seenCursors.has(nextCursor)) {
        throw new Error(
          `MCP tools/list repeated cursor: ${JSON.stringify(nextCursor)}`,
        )
      }
      seenCursors.add(nextCursor)
      cursor = nextCursor
    }

    return tools
  }

  async callTool(
    name: string,
    args: Record<string, unknown>,
    signal: AbortSignal,
  ): Promise<McpToolResult> {
    this.assertConnected()
    return parseToolResult(await this.request(
      'tools/call',
      { name, arguments: args },
      signal,
    ))
  }

  async close(): Promise<void> {
    this.closePromise ??= this.closeInner()
    return await this.closePromise
  }

  private assertConnected(): void {
    if (this.state !== 'connected') {
      throw new Error(`MCP client is not connected (${this.state})`)
    }
  }

  private async request(
    method: string,
    params: Record<string, unknown>,
    signal: AbortSignal,
    sendCancellation = true,
  ): Promise<unknown> {
    signal.throwIfAborted()
    if (this.state === 'closing' || this.state === 'closed') {
      throw new Error('MCP client is closed')
    }

    const id = this.nextId++
    const timeoutMs = this.config.requestTimeoutMs ??
      DEFAULT_REQUEST_TIMEOUT_MS

    return await new Promise<unknown>((resolve, reject) => {
      const onAbort = () => {
        if (sendCancellation) {
          void this.notify('notifications/cancelled', {
            requestId: id,
            reason: 'client aborted request',
          }).catch(() => {})
        }
        this.settle(id, signal.reason instanceof Error
          ? signal.reason
          : new Error('MCP request aborted'))
      }
      signal.addEventListener('abort', onAbort, { once: true })

      const timer = setTimeout(() => {
        if (sendCancellation) {
          void this.notify('notifications/cancelled', {
            requestId: id,
            reason: `client timeout after ${timeoutMs}ms`,
          }).catch(() => {})
        }
        this.settle(
          id,
          new Error(`MCP request timed out after ${timeoutMs}ms: ${method}`),
        )
      }, timeoutMs)

      this.pending.set(id, {
        resolve,
        reject,
        timer,
        removeAbort: () => {
          signal.removeEventListener('abort', onAbort)
        },
      })

      void this.writeMessage({
        jsonrpc: '2.0', id, method, params,
      }).catch((error) => {
        this.settle(id, error instanceof Error
          ? error
          : new Error(String(error)))
      })
    })
  }

  private async notify(
    method: string,
    params?: Record<string, unknown>,
  ): Promise<void> {
    await this.writeMessage({
      jsonrpc: '2.0',
      method,
      ...(params === undefined ? {} : { params }),
    })
  }

  private async writeMessage(
    message: Record<string, unknown>,
  ): Promise<void> {
    const line = JSON.stringify(message) + '\n'
    await new Promise<void>((resolve, reject) => {
      this.child.stdin.write(line, (error) => {
        if (error) reject(error)
        else resolve()
      })
    })
  }

  private handleLine(line: string): void {
    let value: unknown
    try {
      value = JSON.parse(line)
    } catch (error) {
      this.protocolFailure(new Error(
        `Invalid JSON on MCP stdout: ${errorMessage(error)}`,
      ))
      return
    }
    if (!isRecord(value)) {
      this.protocolFailure(new Error('Invalid MCP message'))
      return
    }
    if (value.jsonrpc !== '2.0') {
      this.protocolFailure(new Error('MCP message must use jsonrpc 2.0'))
      return
    }

    // 当前 client 不实现 server→client requests;不能让它的 id
    // 碰巧 settle 一个同号的 outbound request。
    if (typeof value.method === 'string') {
      this.config.onWarning?.(
        `Ignoring unsupported MCP inbound method: ${value.method}`,
      )
      return
    }
    // 未知通知没有 method 也只告警。
    if (!('id' in value)) {
      this.config.onWarning?.(
        'Ignoring MCP message without id',
      )
      return
    }
    if (typeof value.id !== 'number') {
      this.config.onWarning?.('Ignoring MCP response with non-number id')
      return
    }
    const response = value as JsonRpcResponse
    const pending = this.pending.get(response.id)
    if (!pending) {
      this.config.onWarning?.(
        `Ignoring MCP response for unknown id ${response.id}`,
      )
      return
    }

    if (response.error) {
      if (
        !isRecord(response.error) ||
        typeof response.error.code !== 'number' ||
        typeof response.error.message !== 'string'
      ) {
        this.protocolFailure(
          new Error('Invalid MCP JSON-RPC error response'),
        )
        return
      }
      this.settle(response.id, new McpProtocolError(
        response.error.code,
        response.error.message,
        response.error.data,
      ))
    } else if ('result' in response) {
      this.settle(response.id, undefined, response.result)
    } else {
      this.settle(
        response.id,
        new Error('MCP response has neither result nor error'),
      )
    }
  }

  private settle(
    id: JsonRpcId,
    error?: Error,
    value?: unknown,
  ): void {
    const pending = this.pending.get(id)
    if (!pending) return
    this.pending.delete(id)
    clearTimeout(pending.timer)
    pending.removeAbort()
    if (error) pending.reject(error)
    else pending.resolve(value)
  }

  private rejectPending(error: Error): void {
    for (const id of [...this.pending.keys()]) {
      this.settle(id, error)
    }
  }

  private protocolFailure(error: Error): void {
    this.rejectPending(error)
    if (this.state !== 'closing' && this.state !== 'closed') {
      void this.close().catch((closeError) => {
        this.config.onWarning?.(
          `Failed to close broken MCP server: ${errorMessage(closeError)}`,
        )
      })
    }
  }

  private async closeInner(): Promise<void> {
    if (this.state === 'closed') return
    this.state = 'closing'
    this.rejectPending(new Error('MCP client closed'))

    this.child.stdin.end()
    if (await waitForClose(
      this.child,
      CLOSE_STDIN_GRACE_MS,
      () => this.state === 'closed',
    )) return

    signalProcess(this.child, 'SIGTERM')
    if (await waitForClose(
      this.child,
      CLOSE_TERM_GRACE_MS,
      () => this.state === 'closed',
    )) return

    signalProcess(this.child, 'SIGKILL')
    if (!await waitForClose(
      this.child,
      CLOSE_KILL_GRACE_MS,
      () => this.state === 'closed',
    )) {
      throw new Error('MCP server did not exit after SIGKILL')
    }
  }
}

function signalProcess(
  child: ChildProcessWithoutNullStreams,
  signal: NodeJS.Signals,
): void {
  if (child.pid === undefined) return
  try {
    if (process.platform === 'win32') child.kill(signal)
    else process.kill(-child.pid, signal)
  } catch (error) {
    const code = isRecord(error) ? error.code : undefined
    if (code !== 'ESRCH') throw error
  }
}

async function waitForClose(
  child: ChildProcessWithoutNullStreams,
  timeoutMs: number,
  isClosed: () => boolean,
): Promise<boolean> {
  if (isClosed()) return true

  return await new Promise<boolean>((resolve) => {
    let settled = false
    const onClose = () => finish(true)
    const timer = setTimeout(() => finish(false), timeoutMs)
    const finish = (exited: boolean) => {
      if (settled) return
      settled = true
      clearTimeout(timer)
      child.removeListener('close', onClose)
      resolve(exited)
    }
    child.once('close', onClose)
    // close 可能在入口检查与注册 listener 之间发生。
    if (isClosed()) finish(true)
  })
}

export async function connectLegacyMcp(
  config: LegacyMcpConfig,
  signal: AbortSignal,
): Promise<{ client: LegacyMcpClient; protocolVersion: string }> {
  const client = new LegacyMcpClient(config)
  try {
    const protocolVersion = await client.initialize(signal)
    return { client, protocolVersion }
  } catch (error) {
    try {
      await client.close()
    } catch (closeError) {
      throw new AggregateError(
        [error, closeError],
        'MCP initialization failed and the server could not be closed',
      )
    }
    throw error
  }
}

这里的 McpToolResult 是远端 JSON-RPC 消息的原始形状。按协议,isError 缺失就等于 false。它不是 agent 内部的 ToolResult。

第 19 章的 adapter 必须把这个可选字段,规范成内部的判别联合:

  • 成功时,明确写上 isError: false。
  • 失败时,同时写上 isError: true 和结构化的 error。

再看分页。cursor 是 server 给的翻页标记,对 client 来说是不透明的字符串。代码对它做了三层防护:

  1. seenCursors 不去解析 cursor 的内容,只检查 server 有没有把同一个值又返回一次。
  2. 另设 64 页的总上限。这是为了防止恶意或出了故障的 server 每次都返回不同的 cursor:每个请求都在 timeout 内完成,但翻页永远不结束。
  3. 循环的结束条件是 nextCursor === undefined,而不是“值为真”。空字符串在协议里仍是合法的 cursor。

close() 是幂等的:调多少次,效果都和调一次一样。它分三段关闭:

  1. 先关闭 stdin,给正常的 server 自己收尾的机会。
  2. 再向整个 POSIX 进程组发 SIGTERM。
  3. 最后发 SIGKILL。

这里等的是 close 事件,而不只是 exit。原因是:直接子进程已经退出、但它的后代进程还占着 stdio 管道时,close 不会发生。这时 client 会继续清理整个进程组。

Windows 没有同样的负 PID 语义(向负 PID 发信号等于发给整个进程组),只能退回到只处理直接子进程。本书“后代进程无残留”的验收只限 macOS / Linux。跨平台的 job object 不在目标范围里。

协议被破坏时,比如收到非法 JSON、错误的 jsonrpc 版本,不能只把内部状态改成 closed。那样随后的 close() 会以为进程已经退出,实际却留下一个 orphan(没人管的孤儿进程)。

正确的处理分三步:

  1. protocolFailure 先把所有等待中的请求 reject 掉。
  2. 再启动同一条真实的三段关闭流程。
  3. 只有子进程的 close 事件,才能把状态标成 closed。

SIGKILL 之后仍然等不到 close 时,close() 必须 reject,不能打印成功。

如果是初始化本身被 abort 或超时,就不发送 cancelled notification。因为这个通知要求连接已经初始化完成。这时直接由 connectLegacyMcp 关闭进程。

新建独立入口 src/mcp-probe.ts。它用来证明 client 自己就能跑,不把半成品塞进 agent:

import { connectLegacyMcp } from './mcp-protocol.js'

const [command, ...args] = process.argv.slice(2)
if (!command) {
  throw new Error(
    'usage: npm run mcp:probe -- <command> [...args]',
  )
}

const controller = new AbortController()
process.once('SIGINT', () => {
  controller.abort(new Error('cancelled by SIGINT'))
})

const { client, protocolVersion } = await connectLegacyMcp(
  {
    command,
    args,
    onStderr: (text) => process.stderr.write(`[server] ${text}`),
    onWarning: (text) => console.warn(text),
  },
  controller.signal,
)

try {
  console.log(`protocol: ${protocolVersion}`)
  const tools = await client.listTools(controller.signal)
  for (const tool of tools) {
    console.log(`${tool.name} — ${tool.description ?? ''}`)
  }
} finally {
  await client.close()
}

在 agent 实现包的 package.json 里加脚本。网站根目录那个 Astro 的 package.json 不改:

{
  "scripts": {
    "mcp:probe": "tsx src/mcp-probe.ts"
  }
}

probe 目前只做 list,不去猜任何真实 server 的工具参数。真实调用的验收有两种方式:用测试 fixture,或者临时改一次代码、明确指定工具名。第 19 章才提供稳定的配置入口。

自动化测试与故障注入

确定性测试不能依赖 npx 下载,也不能依赖某个第三方 server 有多少个工具。

所以新建一个 fixtures/mcp/legacy-server.mjs,作为测试用的假 server。用环境变量切换它的行为:分页、业务错误、协议错误、挂起不响应、忽略关闭。

import readline from 'node:readline'

const mode = process.env.BYOAA_MCP_MODE ?? 'ok'
const lines = readline.createInterface({ input: process.stdin })

function send(message) {
  process.stdout.write(`${JSON.stringify(message)}\n`)
}

lines.on('line', (line) => {
  const message = JSON.parse(line)
  if (message.method === 'initialize') {
    send({
      jsonrpc: '2.0',
      id: message.id,
      result: {
        protocolVersion:
          process.env.BYOAA_MCP_VERSION ?? '2025-11-25',
        capabilities: { tools: {} },
        serverInfo: { name: 'fixture', version: '1.0.0' },
      },
    })
    return
  }
  if (message.method === 'notifications/initialized') return

  if (message.method === 'tools/list') {
    if (mode === 'hang') return
    const cursor = message.params?.cursor
    if (cursor === undefined) {
      send({
        jsonrpc: '2.0', id: message.id,
        result: {
          tools: [{
            name: 'echo',
            description: 'Echo one string',
            inputSchema: {
              type: 'object',
              properties: { text: { type: 'string' } },
              required: ['text'],
            },
          }],
          nextCursor: 'page-2',
        },
      })
    } else {
      send({
        jsonrpc: '2.0', id: message.id,
        result: {
          tools: [{
            name: 'fail',
            inputSchema: { type: 'object', properties: {} },
          }],
          ...(mode === 'repeat-cursor'
            ? { nextCursor: 'page-2' }
            : {}),
        },
      })
    }
    return
  }

  if (message.method === 'tools/call') {
    if (message.params.name === 'protocol-fail') {
      send({
        jsonrpc: '2.0', id: message.id,
        error: { code: -32601, message: 'Unknown tool' },
      })
    } else if (message.params.name === 'fail') {
      send({
        jsonrpc: '2.0', id: message.id,
        result: {
          content: [{ type: 'text', text: 'fixture failure' }],
          isError: true,
        },
      })
    } else {
      send({
        jsonrpc: '2.0', id: message.id,
        result: {
          content: [{
            type: 'text', text: String(message.params.arguments.text),
          }],
        },
      })
    }
  }
})

if (process.env.BYOAA_MCP_PID_FILE) {
  await import('node:fs/promises').then(({ writeFile }) =>
    writeFile(process.env.BYOAA_MCP_PID_FILE, String(process.pid)),
  )
}

if (mode === 'ignore-stdin') {
  lines.on('close', () => setInterval(() => {}, 1_000))
}

新建 src/mcp-protocol.test.ts。测试用 process.execPath 直接启动本地 fixture,不经过 shell:

import assert from 'node:assert/strict'
import test from 'node:test'
import {
  connectLegacyMcp,
  defaultMcpEnvironment,
  McpProtocolError,
} from './mcp-protocol.js'

const fixture = new URL(
  '../fixtures/mcp/legacy-server.mjs',
  import.meta.url,
).pathname

function config(mode = 'ok') {
  return {
    command: process.execPath,
    args: [fixture],
    env: { ...process.env, BYOAA_MCP_MODE: mode },
    requestTimeoutMs: 200,
  }
}

test('does not inherit secrets unless config explicitly supplies them', () => {
  const env = defaultMcpEnvironment({
    PATH: '/usr/bin',
    HOME: '/tmp/home',
    ANTHROPIC_API_KEY: 'secret',
  })
  assert.deepEqual(env, {
    PATH: '/usr/bin',
    HOME: '/tmp/home',
  })
})

test('negotiates, paginates and preserves tool errors', async () => {
  const signal = new AbortController().signal
  const { client, protocolVersion } = await connectLegacyMcp(
    config(), signal,
  )
  try {
    assert.equal(protocolVersion, '2025-11-25')
    assert.deepEqual(
      (await client.listTools(signal)).map((tool) => tool.name),
      ['echo', 'fail'],
    )
    const ok = await client.callTool(
      'echo', { text: 'hello' }, signal,
    )
    assert.equal(ok.isError, undefined)
    assert.equal(ok.content[0]?.text, 'hello')

    const toolError = await client.callTool('fail', {}, signal)
    assert.equal(toolError.isError, true)

    await assert.rejects(
      client.callTool('protocol-fail', {}, signal),
      (error) => error instanceof McpProtocolError &&
        error.code === -32601,
    )
  } finally {
    await client.close()
  }
})

test('rejects a repeated pagination cursor', async () => {
  const signal = new AbortController().signal
  const { client } = await connectLegacyMcp(
    config('repeat-cursor'), signal,
  )
  try {
    await assert.rejects(
      client.listTools(signal), /repeated cursor/,
    )
  } finally {
    await client.close()
  }
})

test('times out a silent request and remains closable', async () => {
  const signal = new AbortController().signal
  const { client } = await connectLegacyMcp(
    config('hang'), signal,
  )
  try {
    await assert.rejects(
      client.listTools(signal), /timed out/,
    )
  } finally {
    await client.close()
  }
})

再用表格测试补上这些情况:

  • server 选择 2025-06-18 并声明 Tools:能连上。
  • 缺少 capabilities.tools、serverInfo 不合法、或选了别的版本:先关闭,再拒绝。
  • 错误的 jsonrpc,或 stdout 出现非法 JSON:所有等待中的请求都 reject,PID 随后消失。
  • 未知的 response id 和 notification:只给 warning。
  • 初始化时 abort / 超时:不发送 notifications/cancelled。普通 call 被 abort:会发送。
  • Abort 结束后:等待中的 timer 被移除。
  • 重复调用 close():只执行一轮清理。
  • fake child 在 SIGKILL 之后仍不发 close:close() 必须 reject。
  • server 连续返回 64 个互不重复的 cursor:在请求第 65 页之前,必须以 page limit 错误失败。

三段关闭要用真实 PID 做故障注入:

  1. 用 BYOAA_MCP_MODE=ignore-stdin 和一个临时 PID 文件启动 fixture。
  2. 调用 close() 后,kill -0 <pid> 必须失败。
  3. 再让 fixture 额外 spawn 一个 sleep 60,记录 parent 和 child 两个 PID。在 macOS / Linux 下,两次 kill -0 都必须失败。

这个测试不放进跨平台的默认测试集。

在参考实现的 code/ 目录,用本地 fixture 验证握手和分页:

npm run mcp:probe -- node fixtures/mcp/legacy-server.mjs

输出会显示协商出的 2025-11-25 和两页工具 echo、fail。要验证调用和进程关闭,再运行 npm test 中的 MCP 协议测试。只支持 modern era 的 server 交给下一章的 SDK auto 模式。

已验证的边界

  • stdout 与 stderr 若混用,日志会污染逐行 JSON-RPC。stdout 只 parse 协议,stderr 单独回调;非法 stdout fixture 令连接失败。
  • tools/list 需要翻页且 server 可能重复 cursor。cursor 当不透明字符串;缺失才结束;seenCursors 加 64 页硬上限同时防重复和永远变化的 cursor。

独立客户端已经能列工具、执行调用并关闭进程。下一章用官方 SDK 把远程工具接入现有的工具表、审批和截断路径。