跨行程追蹤一個請求
閱讀約 49 分鐘,8 節 中共有 7 個範例。
Labs
透過實作學習本章
完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。約 30 秒內開啟。
完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。由 Labs 為你執行:每月 40 小時。
於您自己的電腦,免費: 下載本書的筆記本,連同其程式碼與資料,皆取自 GitHub。
在本書的版本上執行你的程式碼
讀完本章,你能讓另一個團隊的伺服器所寫出的 span 加入引發它的那則訊息的追蹤(trace),確認它已加入,並找出尚未加入的 span。問題從一個請求開始。基準日第 1 天是一個記錄了 200 則訊息的日子,其中第 16297 號訊息詢問某位聯絡人的資料,於是路由器將它送往 messages 路由,由該路由呼叫 find_contact。這個工具執行於聯絡人團隊的 MCP 伺服器上,那是一個獨立的行程,由助理啟動,並透過標準輸入輸出(stdio)與之通訊,而伺服器會寫出它自己的 span。在這些 span 帶有該訊息的追蹤 ID,並指明是哪一次呼叫要求了它們之前,追蹤會在工具這一步中斷,也沒有任何資訊說明這次查詢是為哪一則訊息服務。
這次查詢是在錄製用的機器上重放的,該機器為 4 個 vCPU、時脈 2.10 GHz 的 Intel Xeon,並使用重放與虛擬時鐘一節中的虛擬時鐘。因此,本章要讓伺服器的 span 加入該訊息的追蹤,並建立用來找出未加入者的計數。
聯絡人伺服器是另一個行程
助理本身並不執行 find_contact。伺服器由聯絡人團隊負責維護,位於 2.3.0 的 mcp 套件會將它以子行程啟動,並透過標準輸入與輸出向它傳送請求,規格將這種傳輸方式稱為 stdio。由於伺服器是獨立的行程,它的 span 不會進入助理的記憶體:伺服器會把 span 寫入自己的 JSON-lines 檔案,待行程結束後再由助理讀取。MCP SDK 會為它送出的每個請求建立一個 span,Trace calls with OpenTelemetry 對這些 span 有深入說明。串接(join)的作用,是把伺服器的 span 與訊息連結起來。請求一旦遺失標頭,伺服器的工作就會留在檔案中,卻與引發它的問題失去關聯。
本案例中的其他工具沒有這個問題。行事曆、鬧鐘與清單工具都在助理自己的行程內執行,因此它們的 span 建立於同一份記憶體中,並透過 One message, one trace 所示範的一般父子連結加入追蹤。
本章把聯絡人伺服器的存續期間稱為一次執行(run),而不稱為工作階段(session)。Model Context Protocol 規格的 2026-07-28 修訂版指出,開啟中的連線(例如 stdio 行程)既不是對話,也不是工作階段,伺服器不得將它視為這類事物。重播會為每次執行啟動一個行程,並置於 contacts startup span 之內,該次執行回答的每則訊息都重複使用這個行程,因此一次執行只有一個行程與一個 span 檔案,並在執行結束後讀取。由於每次執行都啟動自己的行程,因此沒有任何狀態會從一次執行延續到下一次。這是重播的選擇,也符合 MCP 規格無狀態一節的建議。在正式環境中,用戶端不應把行程的存續期間綁定在單一任務、執行緒或對話上。每次執行啟動一個行程,並在各則訊息之間重複使用,propagate-into-the-tool 對其兩次呼叫就是這樣做。比一次執行活得更久的伺服器無法在結束時讀取,因此需要排清(flush)機制或接收器,The book's receiver 提供了後者。
錄製資料呈現了本節所談的失敗情形。基準第 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。查詢本身的 span 仍位於伺服器檔案中它所屬的呼叫之下。但沒有父 span 的呼叫是分離的根 span(定義見 情境在執行緒邊界遺失),因此沒有任何東西把它與訊息連結起來。
實用原則: 讓每個伺服器行程擁有自己的 tracer provider 與匯出器,並且只在行程結束後才讀取它的 span 檔案。伺服器使用 SimpleSpanProcessor,它會在 span 結束時立即把 span 交給匯出器,因此行程結束後讀取的檔案包含伺服器產生的每一個 span。BatchSpanProcessor 則會把 span 保留在佇列中,直到排清或關閉為止,因此使用它時,檔案要等到這兩個動作之一完成後才算完整。
MCP SDK 會把 traceparent 寫入 _meta
要讓伺服器端的 span 加入某條追蹤,請求就必須帶有該追蹤的識別資訊。為此,MCP 在每個請求的引數之外,另給一個 _meta 物件。承載這項識別資訊的欄位由 W3C Trace Context 定義,這是 2021 年 11 月 23 日發布的 Recommendation。其 traceparent 標頭有四個以連字號相連的欄位:版本、追蹤 ID、父 span ID 與旗標。追蹤 ID 為 32 位十六進位數字,父 ID 為 16 位;兩者若為全零,皆屬無效。旗標帶有取樣決定,第 11 章在以父 span 為依據的取樣中會用到。
情境傳播(context propagation)會把情境,也就是 span 的識別資訊與任何baggage,帶到下一個行程;traceparent 是 W3C 為 span 部分所定的欄位:追蹤 ID、父 span 的 ID 與追蹤旗標,其中只有取樣旗標有定義。span 的情境還包含更多內容,例如追蹤狀態(trace state),但伺服器要把自己的 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 的各行都以 assert 為依據,因此若伺服器的 span 改為加入標頭所指的追蹤,範例就會停止。
規格的 2026-07-28 修訂版為追蹤情境保留了三個 _meta 鍵:traceparent、tracestate 與 baggage,並要求其值採用 W3C 的格式。這項保留所依據的提案 SEP-414,早於該修訂版。GenAI 慣例的 MCP 頁面指出,檢測(instrumentation)應透過已設定的 propagator 注入,並以不加前綴的方式寫入這三個鍵。該頁面連結的是較早的 2025-11-25 修訂版,因此兩個頁面所指的修訂版不同,我們採用較新的一版。
實用原則: 已設定 OpenTelemetry 的 tracer provider 時,讓 MCP SDK 寫入 traceparent,且絕不要手動把 traceparent、tracestate 或 baggage 放進 _meta。SDK 會取代手寫的 traceparent,但手寫的 tracestate 或 baggage 會與 SDK 所寫的並存,使伺服器讀到不是 SDK 產生的值。只有在不使用 SDK 的程式碼中才自行寫入標頭,而在那種情況下,伺服器會照原樣讀取。
伺服器 span 加入追蹤
如〈MCP SDK 將 traceparent 寫入 _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。該 client span 是伺服器上 tools/call find_contact 的父節點,後者是一個 SERVER span,而伺服器的 contacts.lookup 則是它的子節點。四個 span 共用同一個追蹤 ID。助理持有該訊息追蹤中的 8 個 span,伺服器在同一個追蹤中另外寫入 3 個。
client span 是助理不會自行寫入的那一個。它的名稱 MCP send tools/call find_contact,並不符合 GenAI 慣例中 MCP 頁面為 span 所訂的格式 {mcp.method.name} {target}。我們保留 MCP SDK 的名稱,一如第 3 章保留其套件所發出的名稱,因為 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
此圖以樹狀繪出同一條追蹤。圓點是助理的 span,方塊是伺服器的 span,虛線標示每一條從一個行程跨到另一個行程的父連結。版面依深度而非時間來安排各 span,因為伺服器的時鐘是它自己的,本章中的任何時間都不是取自伺服器 span:圖與輸出只呈現結構與父連結。
圖 4.1 有兩條虛線連結,印出的計數也相符:2。其一是伺服器的 tools/call find_contact,其父節點是該次查詢的 client span。另一個是伺服器的 tools/list,其父節點是 SDK 為取得伺服器工具清單所送出請求的 client span。MCP SDK 會在某個尚未列出的工具首次成功回覆之後,列出伺服器的工具,以便依該工具的輸出綱要檢查回覆(src/mcp/client/session.py、call_tool 與 validate_tool_result,mcp 2.3.0)。這則訊息的查詢成功了,所以才有第二條連結。
**實用原則:**在任何跨行程的呼叫之後,檢查每個伺服器 span 是否都以呼叫端追蹤中的某個 client span 為其父節點,並計算跨越的連結數。若預期會跨行程的呼叫其連結數為零,表示標頭沒有送到伺服器,所以應先檢查請求,再檢查伺服器。
此部分尚未翻譯,因此以英文呈現。
Context is lost at a thread boundary
The join works because the SDK's call runs in the same context as the tool span that made it. Python keeps the current span in a ContextVar, and each thread and each asyncio task has its own value of it. Three common ways of moving work lose that value: threading.Thread(target=...), executor.submit and loop.run_in_executor each start the function with an empty context, so a span made there finds no parent. asyncio.to_thread and asyncio.run_coroutine_threadsafe copy the context, and that is why the book's LiveContacts, which sends each call to the client's thread with run_coroutine_threadsafe, keeps find_contact's span in the message's trace.
A span that starts a trace of its own this way is a detached root: a span whose context was lost, so it starts a new trace and sits outside the message's trace. An orphan is a different failure. An orphan is a span whose parent ID names a span the store does not hold. It keeps the message's trace ID and stays in the message's trace. The two look different in the store. An orphan shows as a gap, a parent with no span behind it. A detached root looks like a healthy one-span trace, so nothing marks what it lost. Spans by hand shows the other way a parent goes missing, when a process crashes partway through a message.
The example makes one span on each of four workers, all started inside one tool span, and shows which of them find its context.
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 則證明來自 Context is lost at a thread boundary,第 4 章再讀一次
建立於 parent span,出自第 1 章「手動建立 span」
建立於 trace,出自第 1 章「一則訊息,一條追蹤」
新版次已改變本練習所涵蓋的內容。版次 2026.11.2 的變更內容
第 38 行把未經包裝的 retrieve 函式直接交給執行緒池,因此它建立的 span 會開啟一條新的追蹤,而不是加入工具 span。請修正第 38 行,讓經 carry() 包裝的工作執行緒所建立的 span 加入工具 span。
為何有效
The plain thread's span is a detached root, and the first printed line says it did not join the tool span. The wrapped thread's span joins, and so does the task's, because asyncio gives a task a copy of the context that was current when the task was made. The executor worker loses the context like the plain thread, so its span is a detached root too. The counts make the cost plain: 2 detached roots without the helper, and 0 with it. The last line states that a detached root's trace differs from the tool span's, which is the test for one: a trace ID other than the one its work belongs to.
The fix is carry(), from the book's shared module lib/context.py, which wraps a function so it runs in a copy of the caller's context. new_task() starts an asyncio task with an explicit copy of the context. asyncio copies it anyway, and the helper makes the copy visible in code. Two standard alternatives exist. opentelemetry-instrumentation-threading patches Thread and ThreadPoolExecutor so they carry the context, and asyncio.to_thread copies it for the work it starts. We recommend carry() in code the team owns, because the copy is visible at the call site and nothing is patched. The instrumentation is for libraries whose own thread pools the team cannot change.
Working rule: Wrap every function that a thread, a thread pool or run_in_executor runs in carry(), and start asyncio tasks with new_task(), so each one starts from a copy of the caller's context. A span that finds no parent raises no error and changes no status, so the context has to be carried at every hand-off.
此部分尚未翻譯,因此以英文呈現。
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 行從載體(carrier)讀取鍵,但載體只含有一筆 baggage 項目,因此第 21 行的 assert 會失敗。請修正程式,讓鍵取自該呼叫所攜帶的 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 一樣被匯出。有三項查詢可以找出這些問題,每一項都需要一個能讓兩個行程的 span 並列的地方,第 5 章會提供這個地方。第一項計算跨行程連結:也就是從一個行程跨到另一個行程的父連結。第二項計算分離的根 span:在任一行程中,除了代理程式 span invoke_agent ambrewick-assistant 以外的根 span,而抵達時沒有 traceparent 的伺服器 span 也算在內。第三項計算孤立 span:其父 ID 指向的 span 並未儲存。若沒有這些查詢,程序中不會有任何環節失敗,因此這些計數是唯一的訊號。
正式環境中還有兩件事會出問題。在自有執行緒池上執行工作的函式庫,除非原本就被寫成會複製情境,否則會遺失情境,而團隊自己的 carry() 也無法作用於不歸自己所有的執行緒池,因此一個看起來屬於某則訊息的 span,可能自行開啟一條追蹤。Baggage 會隨請求前往各處,傳到呼叫所觸及的每個行程,所以一個在某個行程中無害的值,到了下一個行程可能變成洩漏。輔助函式只檢查本書所送出的內容。從上游傳入的 baggage 會不經檢查就通過,這正是 What goes in baggage 所描述的限制。
追蹤的兩半現在位於兩個地方:助理的 span 在它的記憶體中,伺服器的 span 在它的檔案中,而 The book's receiver 就是第 5 章將兩者合併的地方。
實用原則: 在每次更動工具或工作者程式碼之後,以及每次發行時,都要執行跨行程連結計數,以及分離根 span 與孤立 span 的計數。其中任何一項計數有變化,在有人解釋清楚之前,都應視為串接(join)已經斷裂。
本章所做的決定
以下每一項決定都是我們可能判斷錯誤的看法,因此每一項都附上理由,以及用來檢驗它的範例。
- 只要設定了 tracer provider,我們就讓 MCP SDK 寫入
traceparent,並且不在_meta中放入手寫的追蹤鍵。伺服器讀取的標頭就是 SDK 所寫的標頭,因此程式碼中多一份副本,永遠不會送到伺服器。propagate-into-the-tool檢驗這一點,其中手寫的標頭會被取代。 - 我們把每個伺服器行程視為一次執行,並在行程結束後才讀取它的 span 檔案。一次執行是作為一個單位開始與結束,而且要等行程寫完之後,檔案才會包含所有的 span。
server-span-joins檢驗這項串接,server-span-without-context則呈現缺少串接時的記錄。 - 對每個會產生 span 的執行緒、執行緒池與 asyncio 工作,我們都用
carry()和new_task()帶入情境。脫離的根 span 不會引發任何錯誤,所以每一次交接都必須帶入情境。orphan-span-demo檢驗這一點,其中一般執行緒的 span 與 executor 的 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。