跨进程跟踪一个请求
阅读约 43分钟,8节中含7个示例。
实验室
通过动手实践学习本章
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。约 30 秒后打开。
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。Labs 为你运行:每月 40小时。
在你自己的机器上,免费: 下载本书的笔记本,附其代码和数据,来源为 GitHub。
在本书所用版本上运行你的代码
读完本章,你将能够让另一个团队的服务器写出的 span 加入引发它的那条消息的 trace,检查它是否已经加入,并找出尚未加入的 span。问题从一个请求开始。基线第 1 天是一个记录下来的日子,共 200 条消息,其中第 16297 号消息询问某个联系人,因此路由器把它送往 messages 路由,该路由调用 find_contact。这个工具运行在联系人团队的 MCP 服务器上,那是一个独立的进程,由助手启动,并通过 stdio 与之通信,服务器会写出它自己的 span。在这些 span 带上该消息的 trace ID,并指明是哪一次调用要求了它们之前,trace 会在工具这一步中断,也没有任何信息说明这次查询服务于哪条消息。
这次查询在录制机器上重放,该机器是一台 4 vCPU、主频 2.10 GHz 的 Intel Xeon,使用的是 重放与虚拟时钟 中的虚拟时钟。因此,本章先让服务器的 span 加入消息的 trace,再建立用于找出未加入者的计数。
联系人服务器是另一个进程
助手本身并不运行 find_contact。服务器由联系人团队维护,2.3.0 版本的 mcp 包把它作为子进程启动,并通过标准输入和输出向它发送请求,规范把这种传输方式称为 stdio。由于服务器是独立的进程,它的 span 不会进入助手的内存:服务器把 span 写入自己的 JSON-lines 文件,待进程退出后,助手再读取该文件。MCP SDK 会为它发出的每个请求生成一个 span,用 OpenTelemetry 追踪调用对这些 span 有深入的讨论。这个关联(join)就是把服务器的 span 与那条消息联系起来的环节。如果请求丢失了请求头,服务器的工作就会留在文件中,与引起它的问题没有任何联系。
案例中的其他工具没有这个问题。日历、闹钟和列表工具都在助手自己的进程内运行,它们的 span 生成于同一块内存,并通过普通的父级链接加入追踪,这一点已在一条消息,一条追踪中说明。
本章把联系人服务器的存续期称为一次运行(run),而不是一次会话(session)。模型上下文协议规范 2026-07-28 修订版指出,处于打开状态的连接(例如 stdio 进程)不是对话,也不是会话,服务器不得将其当作会话来处理。回放为每次运行启动一个进程,置于 contacts startup span 之内,这次运行所回答的每条消息都复用该进程,因此一次运行只有一个进程和一个 span 文件,并在运行结束后读取。由于每次运行都启动自己的进程,所以没有任何内容会从一次运行延续到下一次运行。这是回放的选择,与 MCP 规范中无状态一节的建议一致。在生产环境中,客户端不应把进程的存续期绑定到某个任务、线程或对话上。应当每次运行启动一个进程,并在多条消息之间复用它,正如 propagate-into-the-tool 用它的两次调用所做的那样。比一次运行存活更久的服务器无法在退出时读取,因此需要刷新或接收器,本书的接收器提供了后者。
录制的数据展示了本节所讨论的故障。基线第 1 天是用一个没有 tracer provider 的客户端录制的,因此客户端没有发送上下文。示例读取的就是这份录制。
1"""Read baseline day 1's recorded contacts-server spans for message 16297. The recorder's client sent no context, so the2server's lookup span has no parent and starts a trace of its own: a detached root. The prose's two counts rest on the3printed lines, and the assert backs the parent count."""4from lib.dayrun import DATA5import json67rows = [json.loads(line) for line in (DATA / "baseline-day-1" / "contacts-spans.jsonl").read_text(encoding="utf-8").splitlines()]8lookups = [r for r in rows if r["name"] == "tools/call find_contact"]9with_parent = [r for r in lookups if r["parent_span_id"] is not None]10lookup = next(r for r in rows if r["name"] == "contacts.lookup")11call = lookups[0]12assert with_parent == [] and lookup["parent_span_id"] == call["span_id"] and lookup["trace_id"] == call["trace_id"]13print("tools/call find_contact spans in the contacts server:", len(lookups))14print("of them with a parent:", len(with_parent))15print("contacts.lookup under it, in its trace: yes")
python server-span-without-context.pytools/call find_contact spans in the contacts server: 3
of them with a parent: 0
contacts.lookup under it, in its trace: yes
文件中有 3 个 tools/call find_contact span,其中 0 个有父级。查找本身的 span 仍然位于服务器文件中对应调用之下。但没有父级的调用是游离的根(定义见上下文在线程边界处丢失),因此没有任何东西把它与那条消息联系起来。
工作准则: 为每个服务器进程配置它自己的 tracer provider 和导出器,并且只在进程退出之后读取它的 span 文件。服务器使用 SimpleSpanProcessor,它在 span 结束时就把 span 交给导出器,所以退出后读取的文件包含服务器生成的全部 span。BatchSpanProcessor 会把 span 保留在队列中,直到刷新或关闭,因此使用它时,文件只有在其中一个操作之后才是完整的。
MCP SDK 把 traceparent 写入 _meta
要让服务器端的 span 加入某条追踪,请求就必须携带该追踪的标识。为此,MCP 在每个请求的参数之外另设了一个 _meta 对象。承载这一标识的字段由 W3C Trace Context 定义,该规范是 2021 年 11 月 23 日发布的 W3C 推荐标准。它的 traceparent 头部有四个字段,以连字符相连:版本、追踪 ID、父 span ID 和标志位。追踪 ID 为 32 位十六进制数字,父 ID 为 16 位;两者若为全零,则均无效。标志位携带采样决定,第 11 章在基于父级的采样中会用到它。
上下文传播会把上下文,即 span 的标识和所有baggage,传递给下一个进程;traceparent 是 W3C 为 span 这一部分定义的字段:追踪 ID、父级的 span ID 和追踪标志位,其中采样标志位是目前唯一已定义的标志。span 的上下文还包含更多内容,例如追踪状态,但服务器要把自己的 span 挂到正确的父级之下,只需要这三项。
首先可以试着自己写出这个头部,看服务器如何处理它。下面的第一次调用携带的头部指向一条该助手从未创建的追踪,第二次调用请求的则是服务器没有的工具。
1"""Write a traceparent into one call to the contacts server, then ask for a tool the server does not have. The prose's claim2that the SDK replaces the header rests on the second printed line, and its claim about the unknown tool on the third."""3from lib.clock import VirtualClock4from lib.contacts_server import SPANS_ENV5from lib.genai import SCHEMA_URL6from lib.ids import SequentialIds7from lib.tracing import make_provider8import asyncio, json, sys, tempfile9from pathlib import Path10from mcp import Client, StdioServerParameters11from opentelemetry import trace12from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1314HAND_WRITTEN = "00-" + "ab" * 16 + "-" + "cd" * 8 + "-01" # a traceparent this app never made15CALLS = [("find_contact", {"user_id": "U0161", "name": "jake"}, {"traceparent": HAND_WRITTEN}), ("no_such_tool", {}, None)]16clock, exporter = VirtualClock("2026-12-08"), InMemorySpanExporter()17provider = make_provider("ambrewick-assistant", "1.0.0", "propagate-example", clock, SequentialIds(), exporter, SCHEMA_URL)18trace.set_tracer_provider(provider) # the SDK injects its header only when a provider is configured192021async def make_calls(params):22 """Make each call inside its own tool span, which is current while the call waits for its reply."""23 replies = []24 async with Client(params) as client:25 for number, (name, arguments, meta) in enumerate(CALLS):26 app = provider.get_tracer("ambrewick.assistant").start_span(f"execute_tool {name}", start_time=clock.at(number))27 with trace.use_span(app, end_on_exit=False): # ended below, with a virtual end time28 replies.append((app, await client.call_tool(name, arguments, meta=meta)))29 app.end(end_time=clock.at(number + 1))30 return replies313233with tempfile.TemporaryDirectory() as folder:34 spans_file = Path(folder) / "spans.jsonl" # the server's spans; read once the server has exited35 params = StdioServerParameters(command=sys.executable, args=["-m", "lib.contacts_server"],36 cwd=str(Path(__file__).resolve().parent), env={SPANS_ENV: str(spans_file)})37 replies = asyncio.run(make_calls(params))38 server = [json.loads(line) for line in spans_file.read_text(encoding="utf-8").splitlines()]3940(app, _), (_, unknown) = replies41client = next(s for s in exporter.get_finished_spans() # the SDK's client span, child of the tool span42 if s.name.startswith("MCP send tools/call") and s.parent and s.parent.span_id == app.context.span_id)43span = next(r for r in server if r["parent_span_id"] == format(client.context.span_id, "016x"))44assert span["trace_id"] == format(app.context.trace_id, "032x") != "ab" * 16 # joined the app's trace, not the header's45assert unknown.is_error and unknown.content[0].text == "Unknown tool: no_such_tool"46print("find_contact, hand-written traceparent: server span joins the app's trace: yes")47print("find_contact, hand-written traceparent kept: no")48print("no_such_tool, reply is an error result: yes")
python propagate-into-the-tool.pyfind_contact, hand-written traceparent: server span joins the app's trace: yes
find_contact, hand-written traceparent kept: no
no_such_tool, reply is an error result: yes
解释服务器为何加入应用的追踪
+10 项证明来自MCP SDK 把 traceparent 写入 _meta,第 4 章再读一遍
建立在 parent span 的基础上,参见第1章,“手工构造 span”
建立在 span context 的基础上,参见第1章,“手工构造 span”
建立在 trace 的基础上,参见第1章,“一条消息,一条追踪”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第一行输出表明,服务器的 span 加入了应用的追踪,尽管代码在调用的 meta 中写入的是另一个 traceparent。请选出能够解释这一现象的说明。
原理何在
配置了 OpenTelemetry tracer provider 之后,_meta 中的头部会在请求离开客户端之前被替换。服务器的 span 仍然加入助手的追踪,而代码写入的头部没有保留下来,第二行输出即说明了这一点。第三行显示了这台服务器如何应对未知工具:返回一个设置了 isError 的错误结果,客户端把它当作一次答复交还。规范要求的是另一种答复,见超时是被抛出的,而不是被返回的。输出中的 yes 行依靠断言得出,因此若服务器的 span 加入的是头部所指的追踪,示例就会停止。
规范的 2026-07-28 修订版为追踪上下文保留了三个 _meta 键,即 traceparent、tracestate 和 baggage,并要求它们的值采用 W3C 格式。这一保留背后的提案 SEP-414 早于该修订版。GenAI 约定中的 MCP 页面指出,插桩应通过已配置的传播器注入,并且写入这三个不带前缀的键。该页面链接的是较早的 2025-11-25 修订版,所以两个页面指向的修订版不同,我们遵循较新的一个。
工作准则: 配置了 OpenTelemetry tracer provider 时,让 MCP SDK 写入 traceparent,不要手工把 traceparent、tracestate 或 baggage 放进 _meta。SDK 会替换手工写入的 traceparent,但手工写入的 tracestate 或 baggage 会与 SDK 写入的并存,于是服务器读到的是 SDK 没有生成的值。只有在不使用 SDK 的代码中才自己写这个头部,此时服务器读到的就是所写的内容。
服务器的 span 加入同一条追踪
如 The MCP SDK writes traceparent into _meta 所示,由 MCP SDK 写入请求头后,服务器的 span 会落在正确的父节点之下。用在线服务器重放消息 16297,可以看到从助手的工具 span 一直到服务器自身查找操作的各级父子链接。
1"""Replay baseline day 1's message 16297 with the real contacts server over stdio, and check that the server's span joins2the assistant's trace under the SDK's client span. The prose's counts rest on the two count lines; the server's clock is3its own, so only counts are printed."""4from lib.assistant import RELEASES, Assistant5from lib.bm25 import Retriever6from lib.case import load_articles, load_messages, load_tool_durations7from lib.clock import VirtualClock8from lib.genai import SCHEMA_URL9from lib.ids import SequentialIds10from lib.replay import Replay11from lib.tools import LiveContacts, Tools12from lib.tracing import make_provider13import json, tempfile14from pathlib import Path15from opentelemetry import trace16from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1718DAY, RELEASE = "2026-12-08", RELEASES["r0"] # baseline day 1, and the release its recording was made with19exporter = InMemorySpanExporter()20provider = make_provider("ambrewick-assistant", RELEASE.service_version, "baseline-day-1-replay", VirtualClock(DAY),21 SequentialIds(), exporter, SCHEMA_URL)22trace.set_tracer_provider(provider) # the SDK makes its client span with the global provider, so it must be this one2324message = next(m for m in load_messages(DAY) if m.message_id == "16297")25clock = VirtualClock(DAY, start_ns=message.arrival_ns) # the message's clock starts at its arrival26with tempfile.TemporaryDirectory() as folder:27 spans_file = Path(folder) / "contacts-spans.jsonl" # the server writes here; it is read once the server has exited28 contacts = LiveContacts(clock, spans_file)29 outcome = Assistant(Replay(Path(__file__).resolve().parent / "data" / "recorded" / "baseline-day-1"), Retriever(load_articles(), RELEASE.top_k),30 Tools(load_tool_durations(), contacts), clock, provider.get_tracer("ambrewick.assistant"), RELEASE).handle(message)31 contacts.close()32 server = [json.loads(line) for line in spans_file.read_text(encoding="utf-8").splitlines()]3334mine = exporter.get_finished_spans()35app = next(s for s in mine if s.name == "execute_tool find_contact")36client = next(s for s in mine if s.name == "MCP send tools/call find_contact")37call = next(r for r in server if r["name"] == "tools/call find_contact")38lookup = next(r for r in server if r["name"] == "contacts.lookup")39trace_id = format(app.context.trace_id, "032x")40assert client.parent.span_id == app.context.span_id and call["trace_id"] == trace_id # tool span, client span, same trace41assert call["parent_span_id"] == format(client.context.span_id, "016x") # the server's span is under the client span42assert lookup["parent_span_id"] == call["span_id"] and lookup["trace_id"] == trace_id # and its lookup under that4344print("route chosen:", outcome.route)45print("spans in the message's trace, assistant:", sum(s.context.trace_id == app.context.trace_id for s in mine))46print("spans in the message's trace, contacts server:", sum(r["trace_id"] == trace_id for r in server))47print("contacts server span under the SDK's client span, in the same trace: yes")
python server-span-joins.pyroute chosen: messages
spans in the message's trace, assistant: 8
spans in the message's trace, contacts server: 3
contacts server span under the SDK's client span, in the same trace: yes
让服务器 span 指向客户端 span
+10 项证明来自服务器的 span 加入同一条追踪,第 4 章再读一遍
建立在 span context 的基础上,参见第1章,“手工构造 span”
建立在 span kind 的基础上,参见第2章,“span 的类型取决于进程”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 41 行将服务器的 span 与助手的工具 span 进行比对,因此示例在这里会因 AssertionError 而停止。请修改第 41 行,使其检查服务器的调用实际所挂靠的那个 span。
原理何在
这条链包含四个 span 和三个链接。助手的 execute_tool find_contact span 是 MCP send tools/call find_contact 的父节点,后者由 SDK 为其发出的请求创建,类型为 CLIENT span。该客户端 span 是服务器上 tools/call find_contact 的父节点,后者是一个 SERVER span,而服务器的 contacts.lookup 又是它的子节点。四个 span 共享同一个追踪 ID。助手持有该消息追踪中的 8 个 span,服务器在同一条追踪中另外写入 3 个。
客户端 span 是助手自己不写的那一个。它的名称 MCP send tools/call find_contact 不符合 GenAI 约定中 MCP 页面为 span 给出的模式 {mcp.method.name} {target}。我们保留 MCP SDK 的名称,正如第 3 章保留其软件包所发出的名称一样,因为 span 的名称应当与创建它的代码一致。
该图把同一条追踪画成一棵树。圆点是助手的 span,方块是服务器的 span,虚线标出每个从一个进程跨到另一个进程的父链接。布局按深度而不是按时间来安排各个 span,因为服务器的时钟是它自己的,而且本章中的任何时间都不来自服务器 span:图和输出只包含结构和父链接。
1"""Draw baseline day 1's message 16297 as one trace across the assistant and the contacts server, replayed with the live2server. The parent-links line rests on the printed count: two server spans have an SDK client span in the assistant as3their parent. Spans sit by depth, not time, since the server's clock is its own, so the figure shows structure only."""4from lib.dayrun import run_day_traced5from lib.figures import ACCENT, INK, MUTED, new_figure, save67traced = run_day_traced("2026-12-08", ["16297"]) # baseline day 1, with the live contacts server8# One row per span of the trace, from both processes. Span IDs link the rows and are never printed.9rows = [dict(r, process="assistant") for r in traced.spans] + [dict(r, process="contacts server") for r in traced.server]10trace_id = next(r["trace_id"] for r in rows if r["name"] == "execute_tool find_contact")11rows = [dict(r, id=r["span_id"], parent=r["parent_span_id"]) for r in rows if r["trace_id"] == trace_id]12by_id = {r["id"]: r for r in rows}13order = [] # depth-first: a span sits just below its parent, and its depth is its indent in the figure141516def walk(row, depth):17 row.update(y=len(order), x=depth)18 order.append(row)19 for child in (r for r in rows if r["parent"] == row["id"]):20 walk(child, depth + 1)212223for root in (r for r in rows if r["parent"] not in by_id):24 walk(root, 0)2526fig, ax = new_figure(height=3.6, sharex=False)27for row in order:28 parent = by_id.get(row["parent"])29 if parent: # an elbow from the parent's row down, then across; dashed where the link crosses the boundary30 cross = parent["process"] != row["process"]31 ax.plot([parent["x"], parent["x"], row["x"]], [parent["y"], row["y"], row["y"]], linewidth=1.2, zorder=1,32 color=ACCENT if cross else MUTED, linestyle="--" if cross else "-")33 server_row = row["process"] == "contacts server" # squares for the server, dots for the assistant: shape, not colour alone34 ax.scatter(row["x"], row["y"], s=30, zorder=3, marker="s" if server_row else "o", color=ACCENT if server_row else INK)35 ax.text(row["x"] + 0.14, row["y"], f"{row['name']} ({row['process']})", va="center", fontsize=8, color=INK)36ax.invert_yaxis()37ax.set_xlim(-0.3, 6.4)38ax.axis("off")3940cross = [r for r in rows if r["parent"] in by_id and by_id[r["parent"]]["process"] != r["process"]]41print("spans in the message's trace, assistant:", sum(r["process"] == "assistant" for r in rows))42print("spans in the message's trace, contacts server:", sum(r["process"] == "contacts server" for r in rows))43print("parent links across the boundary:", len(cross))44for r in cross: # the SDK's client span is the parent; the server's span is the child45 print(f"{r['name']} in the contacts server, parent in the assistant:", by_id[r["parent"]]["name"])46assert sorted(r["name"] for r in cross) == ["tools/call find_contact", "tools/list"] # the two links, and no other47save(fig, "cross-process-tree")
python figure-cross-process-tree.pyspans in the message's trace, assistant: 8
spans in the message's trace, contacts server: 3
parent links across the boundary: 2
tools/call find_contact in the contacts server, parent in the assistant: MCP send tools/call find_contact
tools/list in the contacts server, parent in the assistant: MCP send tools/list
figure: figures/cross-process-tree.svg
图 4.1 有两条虚线链接,打印出的计数与此一致:2。其一是服务器的 tools/call find_contact,其父节点是查找操作的客户端 span。另一条是服务器的 tools/list,其父节点是 SDK 为获取服务器工具列表而发出的请求所对应的客户端 span。MCP SDK 会在首次收到某个尚未列出过的工具的成功回复之后,列出服务器的工具,以便对照该工具的输出模式检查返回结果(见 src/mcp/client/session.py、call_tool 和 validate_tool_result,mcp 版本为 2.3.0)。这条消息的查找成功了,所以才有第二条链接。
工作准则: 在任何跨进程的调用之后,检查每个服务器 span 是否都以调用方追踪中的某个客户端 span 作为父节点,并统计跨越的链接数。如果在预期会跨进程的调用上链接数为零,就说明请求头没有到达服务器,因此应先检查请求,再检查服务器。
上下文在线程边界处丢失
这次关联之所以成立,是因为 SDK 的调用与发起该调用的工具 span 运行在同一个上下文中。Python 把当前 span 保存在 ContextVar 中,每个线程和每个 asyncio 任务各有自己的值。有三种常见的转移工作的方式会丢失这个值:threading.Thread(target=...)、executor.submit 和 loop.run_in_executor 都以空上下文启动函数,因此在其中创建的 span 找不到父 span。asyncio.to_thread 和 asyncio.run_coroutine_threadsafe 会复制上下文,所以本书的 LiveContacts 用 run_coroutine_threadsafe 把每次调用发送到客户端所在的线程,才能让 find_contact 的 span 保留在该消息的追踪中。
以这种方式开启自己追踪的 span 是游离根 span:它的上下文已经丢失,因此开启了一条新的追踪,位于该消息的追踪之外。孤儿 span 是另一种故障。孤儿 span 的父 ID 指向存储中并不存在的 span。它保留了该消息的追踪 ID,仍然处在该消息的追踪之内。两者在存储中的表现不同。孤儿 span 表现为一个缺口,即一个父 span 后面没有对应的 span。游离根 span 看起来则像一条正常的单 span 追踪,因此没有任何标记表明它丢失了什么。手动创建 span展示了父 span 缺失的另一种情形,即进程在处理消息的中途崩溃。
该示例在四个工作单元上各创建一个 span,它们都在同一个工具 span 内启动,并显示其中哪些能找到自己的上下文。
1"""Make one span on each of four workers started inside one tool span, and show which ones find its context: a plain pool2thread, the same thread with carry(), an asyncio task, and the loop's executor. The prose's counts of detached roots rest3on the asserts, which compare each span's parent with the tool span."""4from lib.clock import VirtualClock5from lib.context import carry, new_task6from lib.genai import SCHEMA_URL7from lib.ids import SequentialIds8from lib.tracing import make_provider, span9from opentelemetry import trace10import asyncio11from concurrent.futures import ThreadPoolExecutor12from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1314clock, exporter = VirtualClock("2026-12-08"), InMemorySpanExporter()15provider = make_provider("ambrewick-assistant", "1.0.0", "orphan-example", clock, SequentialIds(), exporter, SCHEMA_URL)16tracer = provider.get_tracer("ambrewick.assistant")171819def retrieve(name):20 """The worker's work: one span, made on whichever thread runs this. Its times are fixed, as every span's are."""21 span(tracer, f"retrieve {name}", clock.at(1), clock.at(2)) # no parent given: the span takes the current one222324async def from_task():25 retrieve("task") # runs in its own task, which asyncio gave a copy of the tool span's context262728async def main():29 """Runs as a task inside the tool span, starts a second task, and hands one worker to the loop's executor."""30 await new_task(from_task())31 await asyncio.get_running_loop().run_in_executor(None, retrieve, "executor") # copies no context323334app = tracer.start_span("execute_tool retrieve", start_time=clock.at(0))35with trace.use_span(app, end_on_exit=False): # current while the workers run, so their spans can find it36 with ThreadPoolExecutor(max_workers=1) as pool:37 pool.submit(retrieve, "plain").result() # the pool's thread starts with an empty context38 pool.submit(carry(retrieve), "carried").result() # carry() runs the work in a copy of this context39 asyncio.run(main())40app.end(end_time=clock.at(3))4142spans = {s.name: s for s in exporter.get_finished_spans()}43joined = {name: spans[name].parent is not None and spans[name].parent.span_id == app.context.span_id for name in spans}44assert joined == {"retrieve plain": False, "retrieve carried": True, "retrieve task": True, "retrieve executor": False,45 "execute_tool retrieve": False}46assert all(spans[n].context.trace_id != app.context.trace_id for n in ["retrieve plain", "retrieve executor"]) # own traces47print("retrieve on a plain thread, joins the tool span: no")48print("retrieve on a thread with carry(), joins the tool span: yes")49print("retrieve in an asyncio task, joins the tool span: yes")50print("retrieve through run_in_executor, joins the tool span: no")51print("detached roots without the helper:", sum(not joined[n] for n in ["retrieve plain", "retrieve executor"]))52print("detached roots with the helper:", sum(not joined[n] for n in ["retrieve carried"]))53print("detached root's trace differs from the tool span's: yes")
python orphan-span-demo.pyretrieve on a plain thread, joins the tool span: no
retrieve on a thread with carry(), joins the tool span: yes
retrieve in an asyncio task, joins the tool span: yes
retrieve through run_in_executor, joins the tool span: no
detached roots without the helper: 2
detached roots with the helper: 0
detached root's trace differs from the tool span's: yes
把上下文的副本交给线程池中的线程
+10 项证明来自上下文在线程边界处丢失,第 4 章再读一遍
建立在 parent span 的基础上,参见第1章,“手工构造 span”
建立在 trace 的基础上,参见第1章,“一条消息,一条追踪”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 38 行把未经包装的 retrieve 函数直接交给了线程池,因此它创建的 span 会开启一条新的追踪,而不是加入工具 span。请修改第 38 行,使被携带的工作线程所创建的 span 加入工具 span。
原理何在
普通线程的 span 是游离根 span,输出的第一行表明它没有加入工具 span。包装后的线程的 span 成功加入,任务的 span 也是如此,因为 asyncio 会给任务一份创建该任务时当前上下文的副本。执行器的工作线程与普通线程一样丢失了上下文,因此它的 span 也是游离根 span。计数使代价一目了然:不使用该辅助函数时有 2 个游离根 span,使用时有 0 个。最后一行指出,游离根 span 的追踪与工具 span 的追踪不同,这正是判断游离根 span 的依据:它的追踪 ID 不是其所属工作应有的那一个。
解决办法是 carry(),它来自本书的共享模块 lib/context.py,用于包装函数,使其在调用方上下文的副本中运行。new_task() 以显式的上下文副本启动 asyncio 任务。asyncio 本来就会复制上下文,而该辅助函数让这次复制在代码中清晰可见。另有两种标准的替代方案。opentelemetry-instrumentation-threading 会给 Thread 和 ThreadPoolExecutor 打补丁,使它们携带上下文,而 asyncio.to_thread 会为它启动的工作复制上下文。对于团队自己维护的代码,我们推荐 carry(),因为复制在调用处清晰可见,也不需要打任何补丁。该插桩库适用于团队无法修改其线程池的第三方库。
工作准则: 把线程、线程池或 run_in_executor 运行的每个函数都用 carry() 包装,并用 new_task() 启动 asyncio 任务,使每个任务都从调用方上下文的副本开始。找不到父 span 的 span 不会引发错误,也不会改变状态,因此必须在每一次交接处都传递上下文。
这部分尚未翻译,因此以英文显示。
What goes in baggage
A trace ID and a parent ID say where a span belongs, and a server often needs one more value to label its own spans: which release and which prompt version made the call. Baggage is the mechanism for that. The standard for it is the W3C Baggage specification, a Candidate Recommendation Snapshot of 30 May 2024. It is not yet a Recommendation, and we cite it at that status.
Baggage is a set of key-value pairs that travels with the context into every later process when every process along the way propagates it. The specification warns that baggage may carry sensitive information, advises that no proprietary or confidential information goes in it, and says that its keys and values can be passed on to other systems. Those warnings decide what we put there. Only the release and the prompt version go in, under the keys ambrewick.release and ambrewick.prompt.version. A release has the form MAJOR.MINOR.PATCH in digits, and a prompt version is p followed by digits. Running the example below shows the allowed list, the keys a call carries, and the refusals.
1"""Put the release and the prompt version in baggage, and carry them as an MCP call would: the global propagator writes the2`baggage` entry that the SDK sends in `_meta`. A user identifier is refused under an unknown key and under an allowed one.3The prose rests on the last two printed lines, which the asserts back."""4from lib.context import ALLOWED_BAGGAGE_KEYS, baggage_context5from opentelemetry import baggage, propagate678def refused(values):9 """True when baggage_context refuses these values."""10 try:11 baggage_context(values)12 except ValueError:13 return True14 return False151617ctx = baggage_context({"ambrewick.release": "1.0.0", "ambrewick.prompt.version": "p1"})18carrier = {}19propagate.inject(carrier, context=ctx) # the same global propagator the SDK uses for `_meta`20carried = sorted(baggage.get_all(ctx))21assert carried == sorted(ALLOWED_BAGGAGE_KEYS) # nothing else is carried22assert carrier["baggage"] == "ambrewick.prompt.version=p1,ambrewick.release=1.0.0"23assert refused({"ambrewick.user.id": "U0161"}) # a key that is not allowed24assert refused({"ambrewick.release": "U0161"}) # a user identifier under an allowed key, which is not in its form2526print("allowed baggage keys:", ", ".join(sorted(ALLOWED_BAGGAGE_KEYS)))27print("baggage keys carried on a call:", ", ".join(carried))28print("baggage entry sent in _meta:", carrier["baggage"])29print("user identifier refused: yes")30print("user identifier under an allowed key refused: yes")
python baggage-keys.pyallowed baggage keys: ambrewick.prompt.version, ambrewick.release
baggage keys carried on a call: ambrewick.prompt.version, ambrewick.release
baggage entry sent in _meta: ambrewick.prompt.version=p1,ambrewick.release=1.0.0
user identifier refused: yes
user identifier under an allowed key refused: yes
从 baggage 中读取调用携带的键
+10 项证明来自What goes in baggage,第 4 章再读一遍
建立在 span context 的基础上,参见第1章,“手工构造 span”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 20 行从载体中读取这些键,但载体只包含一个 baggage 条目,所以第 21 行的断言失败。请修改代码,使这些键取自调用所携带的 baggage。
原理何在
Only the two allowed keys leave the process: the propagator writes them into one baggage entry, and the SDK sends that entry in _meta beside traceparent. The helper refuses a key outside the allowed list, and a value outside its key's form, so a user identifier is refused even under an allowed key. The last two lines report those refusals.
baggage_context does not see two cases. It starts from the current context, so baggage that arrived from upstream passes through it unchecked, and a direct call to opentelemetry.baggage.set_baggage skips it altogether. We recommend that code calls baggage_context and never set_baggage directly.
A user identifier does not go into baggage, and we do not put one there in any form. The keyed pseudonym we use for users is in Keyed user pseudonyms, where chapter 12 explains why it is safe to put in a span.
Working rule: Put a value in baggage only when a process downstream needs it to label its own spans, and only under a key on the allowed list. A value that identifies a person stays out, however short or harmless it looks in one message.
超时是被抛出的,而不是被返回的
查找可能以多种方式失败,而这些失败到达调用方的方式各不相同。本服务器没有的工具,会作为错误结果从本服务器返回。由其他团队构建的符合规范的服务器,失败方式则不同:规范的工具页面把未知工具定义为协议错误,即错误码为 -32602 的 JSON-RPC 错误,客户端会将其作为 MCPError 抛出。读取超时则根本不会来自任何服务器。SDK 将其作为 MCPError 抛出,错误码为 -32001。
规范没有为纯属实现本地的错误分配错误码,例如在 SDK 内部抛出的请求超时。因此 -32001 不是 MCP 的错误码。它是客户端自己生成的,没有任何服务器发送过它。规范将 -32001 划入其遗留范围,即 -32000 到 -32019,新的实现不应使用该范围内的错误码,接收方也不得假定其含义,并且规范要求本地错误绝不能被误认为来自对端。mcp 抛出超时时使用的 MCPError 类,与它用于服务器错误的类相同,因此基于 ambrewick.mcp.error_code 的查询不得把 -32001 计为服务器的错误。我们把 -32001 称为 SDK 针对读取超时的错误码,第 8 章会在事故当天的范围内,以同一名称来解读这些超时。
本节使用一个注入的事故 inc-contacts-timeout,它使联系人服务器在事故当天的某个时间窗口内响应过慢。该注入在其涉及的 span 中有明确标注,示例打印的第一行也指明了它。
1"""Replay incident-day message 16297 with the live contacts server, inside the injected timeout window. Each attempt of2find_contact is its own execute_tool span. The first raises MCPError with code -32001, the SDK's code for a read timeout,3which the MCP spec does not assign: that span ends ERROR, with error.type MCPError and an exception event. The retry starts42.5 s later, times out too, and the tool step gives up."""5from lib.dayrun import run_day_traced6from lib.tools import TIMEOUT_CODE78traced = run_day_traced("2026-12-09", ["16297"]) # the incident day, with the live server inside its window9outcome = traced.runs[0].outcome10attempts = sorted((r for r in traced.spans if r["name"] == "execute_tool find_contact"),11 key=lambda r: r["attributes"]["ambrewick.attempt"])12injected = [r for r in traced.server if r["name"] == "tools/call find_contact" and "ambrewick.incident.id" in r["attributes"]]13first, second = attempts14assert len(attempts) == 2 and outcome.source == "model" # the retry times out too, and the answer comes from the model15assert all(a["status"] == "ERROR" and a["attributes"]["error.type"] == "MCPError" for a in attempts)16assert first["attributes"]["ambrewick.mcp.error_code"] == TIMEOUT_CODE17assert len(injected) == 2 and all(r["attributes"]["ambrewick.incident.injected"] is True for r in injected)18print("injected incident, ID:", injected[0]["attributes"]["ambrewick.incident.id"])19print("attempts of find_contact:", len(attempts))20print("attempt 1, status and error.type:", first["status"], first["attributes"]["error.type"])21print("attempt 1, error code:", first["attributes"]["ambrewick.mcp.error_code"])22print("attempt 1, exception event:", first["events"][0]["attributes"]["exception.type"].rsplit(".", 1)[-1])23print("attempt 1, time:", f"{(first['end_ns'] - first['start_ns']) / 1e9:.1f} s") # the 2.0 s timeout24print("attempt 2 starts after attempt 1:", f"{(second['start_ns'] - first['start_ns']) / 1e9:.1f} s") # 2.0 s + 0.5 s25print("tool step, time:", f"{(second['end_ns'] - first['start_ns']) / 1e9:.1f} s")
python contacts-timeout-live.pyinjected incident, ID: inc-contacts-timeout
attempts of find_contact: 2
attempt 1, status and error.type: ERROR MCPError
attempt 1, error code: -32001
attempt 1, exception event: MCPError
attempt 1, time: 2.0 s
attempt 2 starts after attempt 1: 2.5 s
tool step, time: 4.5 s
检查调用方收到的错误类型
+10 项证明来自超时是被抛出的,而不是被返回的,第 4 章再读一遍
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 15 行把每次尝试的错误类型与 SDK 在客户端内部捕获的异常进行比对。请将它改为检查调用方收到的异常。
原理何在
事故当天的第 16297 号消息在注入窗口内与实时服务器一同运行。第一次尝试超时,打印的各行显示了它的状态、错误类型和错误码,其中错误码为 -32001。该次尝试在虚拟时钟上耗时 2.0 s,这正是客户端配置的超时时间。第二次尝试在第一次之后 2.5 s 开始,同样超时,工具步骤在共计 4.5 s 后放弃。
每次尝试都是各自独立的 execute_tool span,我们将每一次都计为一个独立的操作。因此,失败的尝试为 ERROR,其 error.type 设为调用方收到的类 MCPError,而不是 SDK 在其底层捕获的内部 TimeoutError。错误码记录在 ambrewick.mcp.error_code 上,而不是 rpc.status_code 上:约定将该属性定义为来自 JSON-RPC 响应的错误码,而本地超时没有响应。重试不会把第一次尝试变成成功。约定中的错误记录页面指出,重试过的错误不保留在 span 上,但这条规则针对的是重试后成功的操作,而这里每次尝试都是一个失败的操作。另一种读法会隐藏第一次尝试的超时,而第 8 章需要这一超时来统计一条消息遇到的失败次数。
**工作准则:**将一次调用的每次尝试记录为各自独立的 span,并带有各自的状态和错误类型,绝不要让一个错误 span 代表一次早先尝试也已失败的调用。错误类型取自调用方收到的异常,错误码取自客户端抛出的错误。
生产环境中的问题
本章所述的故障不会引发任何错误。SDK 替换掉手写的请求头时,不会有任何提示;没有父级的服务端 span 也会和其他 span 一样被导出。有三种查询可以发现这些问题,每一种都要求两个进程的 span 存放在同一处,第 5 章提供了这样的位置。第一种统计跨进程链接,即从一个进程跨到另一个进程的父级链接。第二种统计游离的根 span,即除智能体 span invoke_agent ambrewick-assistant 之外、出现在任一进程中的根 span,到达时没有携带 traceparent 的服务端 span 也算在内。第三种统计孤儿 span,即父级 ID 指向的 span 并未存储的 span。没有这些查询,进程中不会有任何失败的迹象,因此这些计数是唯一的信号。
生产环境中还有两类问题。在自有线程池上运行任务的库会丢失上下文,除非它们在编写时就会复制上下文;而团队自己的 carry() 无法作用于不归自己所有的线程池,所以一个看起来属于某条消息的 span,可能会另起一条追踪。Baggage 会随请求传到调用所及的每一个进程,所以在一个进程中无害的值,到了下一个进程可能就成为泄露。辅助函数只检查本书自己发出的内容。从上游传来的 baggage 会不经检查地通过,这正是 Baggage 中放什么 所述的局限。
追踪的两半现在位于两处:助手的 span 在它的内存中,服务端的 span 在它的文件中,而 本书的接收端 就是第 5 章把它们合在一起的地方。
工作准则: 在修改工具或工作进程代码之后,以及每次发布时,都要运行跨进程链接计数、游离根 span 计数和孤儿 span 计数。其中任何一项发生变化,在有人给出解释之前,都应视为连接已经断裂。
本章做出的决定
下面每一项决定都是我们可能判断错误的地方,因此每一项都给出理由,以及用来检验它的示例。
- 只要配置了 tracer provider,我们就让 MCP SDK 写入
traceparent,并且不在_meta中放手写的追踪键。服务器读取的请求头就是 SDK 写入的那一个,代码中再写第二份,永远不会到达服务器。propagate-into-the-tool对此做了检验,其中手写的请求头被替换掉。 - 我们把每个服务器进程视为一次运行,并在进程退出之后再读取它的 span 文件。一次运行作为一个整体开始和结束,而只有在进程写完之后,文件才包含全部 span。
server-span-joins检验这一连接,server-span-without-context则展示缺少连接时的记录。 - 我们用
carry()和new_task(),把上下文带入每一个生成 span 的线程、线程池和 asyncio 任务。脱离的根 span 不会引发任何报错,所以每一次交接都必须携带上下文。orphan-span-demo对此做了检验,其中普通线程的 span 和执行器的 span 就是脱离的根。 - 我们在 baggage 中只放发布版本和提示词版本,拒绝其他所有键,也拒绝所有不符合形式的值。Baggage 会传到一次调用所触及的每个进程,规范也对它可能携带的内容提出了警告。
baggage-keys对此做了检验,其中用户标识符在未知键和允许的键下都被拒绝。 - 我们把工具调用的每一次尝试记录为各自独立的 span,并把 -32001 说明为 SDK 的错误码,而不是 MCP 的错误码。第 8 章统计一条消息遇到的失败次数,而第一次尝试的超时就是其中之一,所以整个调用只用一个 span 会把它掩盖。
contacts-timeout-live将两次尝试都显示为 ERROR span。
本章,在本版次中
版次 2026.11.2示例于 2026年11月23日 通过7 of 7个示例 in this chapter pass
译自英文版图书,版次 2026.11.2。