プロセスをまたいでリクエストを追跡する
読了まで約42 分。8 節に7 例を収録。
Labs
この章を実際に手を動かして学ぶ
すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。約 30 秒で開く。
すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。Labs が実行環境を用意する: 月40 時間。
自分のマシンで、無料: 書籍のノートブックをダウンロード、そのコードとデータを GitHub から取得する。
書籍のバージョンでコードを実行する
この章を終えると、他チームのサーバーが書き出したスパンを、それを引き起こしたメッセージのトレースに参加させ、参加できているかを確認し、参加できていないスパンを見つけられるようになる。問題は1つのリクエストから始まる。ベースライン1日目、記録された200件のメッセージのうち16297番のメッセージは、ある連絡先について尋ねている。そのためルーターはこのメッセージをmessagesルートへ送り、このルートがfind_contactを呼び出す。このツールは連絡先チームのMCPサーバー上で動く。MCPサーバーは別のプロセスであり、アシスタントが起動して stdio 経由で通信し、サーバーは自身のスパンを書き出す。これらのスパンがメッセージのトレースIDを持たず、自分を要求した呼び出しも示さない限り、トレースはツールのステップで途切れ、その検索がどのメッセージのためのものかは何にも示されない。
この検索は、Replay and the virtual clockで扱った仮想クロックを使い、記録に用いたマシン、すなわち2.10 GHzの4 vCPU Intel Xeon上で再生する。そこで本章では、サーバーのスパンをメッセージのトレースに参加させ、参加していないスパンを見つけるための集計を作る。
contacts サーバーは別のプロセスである
アシスタントは find_contact を自分では実行しない。サーバーは contacts チームが所有しており、2.3.0 の mcp パッケージがそれをサブプロセスとして起動し、標準入出力を介してリクエストを送る。この転送方式を仕様は stdio と呼んでいる。サーバーは独立したプロセスであるため、そのスパンがアシスタントのメモリに入ることはない。サーバーはスパンを自身の JSON-lines ファイルに書き出し、アシスタントはプロセスの終了後にそのファイルを読む。MCP SDK は送信するリクエストごとにスパンを作る。それらのスパンについては OpenTelemetry で呼び出しをトレースする で詳しく扱う。結合(join)が、サーバーのスパンをメッセージに結び付ける。ヘッダーを失ったリクエストは、サーバーの処理をファイルの中に残すが、それを引き起こした質問への結び付きは残らない。
このケースの他のツールには、この問題はない。カレンダー、アラーム、リストの各ツールはアシスタント自身のプロセス内で動くため、そのスパンは同じメモリ内で作られ、1 つのメッセージ、1 つのトレース で示した通常の親リンクによってトレースに加わる。
この章では、contacts サーバーの存続期間をセッションではなく実行(run)と呼ぶ。Model Context Protocol 仕様の 2026-07-28 版 は、stdio プロセスのような開いた接続は会話でもセッションでもなく、サーバーはそれらとして扱ってはならないと述べている。リプレイは実行ごとに 1 つのプロセスを contacts startup スパンの中で起動し、その実行が応答するすべてのメッセージがそのプロセスを再利用する。したがって 1 回の実行にはプロセスが 1 つ、スパンファイルが 1 つあり、ファイルは実行の終了後に読まれる。各実行が自分のプロセスを起動するため、ある実行から次の実行へ引き継がれるものはない。これは MCP 仕様のステートレス性の節が勧めるとおり、リプレイが選んだ方法である。本番環境では、クライアントはプロセスの存続期間を 1 つのタスク、スレッド、会話に結び付けるべきではない。propagate-into-the-tool が 2 回の呼び出しで行っているように、実行ごとに 1 つのプロセスを起動し、メッセージをまたいで再利用する。実行より長く生き続けるサーバーは、終了時に読むことができないため、フラッシュかレシーバーが必要になる。その手段は 本書のレシーバー が提供する。
記録には、この節が扱う失敗が表れている。ベースライン 1 日目は、トレーサープロバイダーを持たないクライアントで記録されたため、クライアントはコンテキストを送らなかった。この例はその記録を読む。
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
ファイルには tools/call find_contact スパンが 3 件あり、そのうち親を持つものは 0 件である。検索自体のスパンは、サーバーのファイル内では呼び出しの下に残っている。しかし親のない呼び出しは切り離されたルートであり(定義は スレッドの境界でコンテキストが失われる にある)、メッセージに結び付くものは何もない。
実践ルール: サーバープロセスごとに専用のトレーサープロバイダーとエクスポーターを持たせ、スパンファイルはプロセスの終了後にのみ読むこと。サーバーは SimpleSpanProcessor を使う。これは各スパンが終了した時点でそれをエクスポーターに渡すため、終了後に読むファイルにはサーバーが作ったすべてのスパンが入っている。BatchSpanProcessor はフラッシュかシャットダウンが行われるまでスパンをキューに保持するため、それを使う場合、ファイルが完全になるのはそのどちらかの後である。
MCP SDK は traceparent を _meta に書き込む
サーバーのスパンがトレースに加わるには、リクエストがトレースの識別情報を運ぶ必要がある。MCP は、そのために各リクエストに引数と並んで _meta オブジェクトを持たせている。識別情報を保持するフィールドは、2021年11月23日付の勧告である W3C Trace Context で定義されている。その traceparent ヘッダーは、バージョン、トレース ID、親スパン ID、フラグの四つのフィールドをハイフンでつないだものである。トレース ID は 16 進数 32 桁、親 ID は 16 桁であり、どちらも全桁が 0 の値は無効である。フラグはサンプリングの判定を運び、11章の親ベースのサンプリングでこれを用いる。
コンテキスト伝播は、スパンの識別情報とバゲージからなるコンテキストを次のプロセスへ運ぶ。traceparent は、そのうちスパンの部分、すなわちトレース ID、親のスパン ID、トレースフラグを表す W3C のフィールドである。トレースフラグのうち定義されているのはサンプリングフラグだけである。スパンのコンテキストにはトレース状態など、ほかにも含まれるものがあるが、サーバーが自分のスパンを正しい親の下に付けるのに必要なのは、この三つである。
最初に試すこととして、ヘッダーを自分で書き、サーバーがそれをどう扱うかを確かめる。以下では、一つ目の呼び出しに、このアシスタントが作っていないトレースを指すヘッダーを持たせ、二つ目の呼び出しでサーバーに存在しないツールを要求する。
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 contextを基にする。1章「スパンを手作業で作る」より
traceを基にする。1章「1メッセージにつき1トレース」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
最初に出力される行は、コードが呼び出しの meta に別の traceparent を書き込んだにもかかわらず、サーバーのスパンがアプリのトレースに加わることを示している。これを説明する選択肢を選べ。
仕組み
OpenTelemetry のトレーサープロバイダーを設定している場合、_meta のヘッダーは、リクエストがクライアントを出る前に置き換えられる。サーバーのスパンは引き続きアシスタントのトレースに加わり、コードが書いたヘッダーは残らない。これは出力の2行目が示すとおりである。3行目は、このサーバーが未知のツールにどう答えるかを示している。isError を設定したエラー結果であり、クライアントはこれを応答として返す。仕様はこれとは別の応答を求めており、これについてはタイムアウトは返されるのではなく送出されるで扱う。yes の行は assert に基づいているため、サーバーのスパンが代わりにヘッダーのトレースに加わった場合は、この例は停止する。
仕様の 2026-07-28 版は、トレースコンテキスト用に _meta の三つのキー traceparent、tracestate、baggage を予約し、その値に W3C の形式を求めている。この予約の元になった提案 SEP-414 は、この版より前に出された。GenAI 規約の MCP のページは、インストルメンテーションが設定済みのプロパゲーターを通じて注入し、三つのキーを接頭辞なしで書くべきだとしている。このページは先の 2025-11-25 版にリンクしており、二つのページは異なる版を挙げている。ここでは後の版に従う。
実践ルール: OpenTelemetry のトレーサープロバイダーを設定している場合は、MCP SDK に traceparent を書かせ、traceparent、tracestate、baggage を手作業で _meta に入れてはならない。SDK は手書きの traceparent を置き換えるが、手書きの tracestate や baggage は SDK が書いたものと並んで残るため、サーバーは SDK が作っていない値を読むことになる。ヘッダーを自分で書くのは、SDK なしで動くコードの中だけにする。その場合、サーバーはそれを書かれたとおりに読む。
サーバーのスパンがトレースに加わる
MCP SDK が書き込んだヘッダーにより、The MCP SDK writes traceparent into _meta で示したとおり、サーバーのスパンは正しい親の下に置かれる。ライブサーバーを使ってメッセージ 16297 を再生すると、アシスタントのツールスパンからサーバー自身の検索処理までの親リンクが確認できる。
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
サーバーのスパンをクライアントのスパンに向ける
+10 件の検証span contextを基にする。1章「スパンを手作業で作る」より
span kindを基にする。2章「スパンの種別はプロセスに従う」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
41行目は、サーバーのスパンをアシスタントのツールスパンと照合しているため、この例はそこで AssertionError を出して止まる。41行目を修正し、サーバーの呼び出しが実際にぶら下がっているスパンを照合するようにせよ。
仕組み
この連鎖は 4 つのスパンと 3 つのリンクから成る。アシスタントの execute_tool find_contact スパンは MCP send tools/call find_contact の親である。後者は、SDK が送信するリクエストのために CLIENT スパンとして作るものである。そのクライアントスパンは、サーバー側の SERVER スパンである tools/call find_contact の親であり、サーバーの contacts.lookup はその子である。4 つのスパンはすべて同じトレース ID を共有する。アシスタントはこのメッセージのトレースのスパンを 8 個保持し、サーバーは同じトレースにさらに 3 個を書き込む。
クライアントスパンは、アシスタントが書かない唯一のスパンである。その名前 MCP send tools/call find_contact は、GenAI 規約の MCP のページがスパンに対して示すパターン {mcp.method.name} {target} に従っていない。第 3 章がパッケージの出力する名前をそのまま保つのと同じく、ここでも MCP SDK の名前を保つ。スパンの名前は、それを作ったコードと一致しているべきだからである。
図は同じトレースを木として描いている。点はアシスタントのスパン、四角はサーバーのスパンであり、一方のプロセスから他方へ渡る親リンクには破線を引いてある。サーバーの時計はサーバー独自のものであり、この章の時刻はサーバーのスパンから得たものを一切含まない。そのため、配置は時間ではなく深さでスパンの位置を決める。図と出力が示すのは構造と親リンクだけである。
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 つあり、出力された個数も一致している。2 である。1 つは、サーバーの tools/call find_contact で、その親は検索のためのクライアントスパンである。もう 1 つは、サーバーの tools/list で、その親は、SDK がサーバーのツール一覧を求めて送るリクエストのクライアントスパンである。MCP SDK は、まだ一覧にないツールから最初に成功した応答を受け取った後でサーバーのツールを一覧する。これは、応答をそのツールの出力スキーマと照合できるようにするためである(src/mcp/client/session.py、call_tool、validate_tool_result、mcp 2.3.0 の場合)。このメッセージでは検索が成功したので、2 つ目のリンクがある。
実践ルール: プロセスをまたぐ呼び出しのあとは、各サーバースパンが呼び出し側のトレースのクライアントスパンを親として挙げていることを確認し、またぐリンクの数を数える。またぐはずの呼び出しでリンク数が 0 であれば、ヘッダーがサーバーに届いていないことを意味する。そのため、サーバーを調べる前にリクエストを調べる。
この部分はまだ翻訳されていないため、英語で表示している。
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章「スパンを手作業で作る」より
traceを基にする。1章「1メッセージにつき1トレース」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
38行目は、素の retrieve 関数をプールに渡している。そのため、その関数が作るスパンはツールのスパンに加わらず、新しいトレースを開始する。38行目を修正し、carry() で包んだワーカーのスパンがツールのスパンに加わるようにせよ。
仕組み
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
呼び出しが運ぶキーをバゲッジから読み取る
+10 件の検証What goes in baggage、4章よりもう一度読む
span contextを基にする。1章「スパンを手作業で作る」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
20行目はキャリアからキーを読み取っているが、キャリアが保持するのはbaggageのエントリ1つだけであるため、21行目のassertは失敗する。呼び出しが運ぶバゲッジからキーを取得するように修正せよ。
仕組み
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 を用いる。これは、障害発生日のある時間帯にわたって、連絡先サーバーの応答を遅くするものである。この注入は、影響を受けるスパンの中で注入であると示されており、例の最初の出力行がその名前を示す。
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 回目の試行は、最初の試行の 2.5 s 後に始まり、同じくタイムアウトする。ツールのステップは、合計 4.5 s で断念する。
各試行はそれぞれ独立した execute_tool スパンであり、本書ではそれぞれを独立した操作として数える。したがって、失敗した試行は ERROR となり、error.type には、呼び出し側が受け取ったクラスである MCPError を設定する。その内側で SDK が捕捉した TimeoutError は設定しない。コードは ambrewick.mcp.error_code に記録し、rpc.status_code には記録しない。規約はこの属性を、JSON-RPC レスポンスのエラーコードと定義しており、ローカルのタイムアウトにはレスポンスがないからである。再試行によって、最初の試行が成功に変わることはない。規約のエラー記録のページは、再試行されたエラーはスパンに残さないとしている。しかしこの規則が対象とするのは、再試行で成功する操作であり、ここでは各試行が失敗した 1 つの操作である。別の読み方をすると最初の試行のタイムアウトが隠れてしまうが、第8章では、メッセージが遭遇した失敗を数えるためにそのタイムアウトが必要になる。
実践ルール: 呼び出しの各試行を、それぞれ独自のステータスとエラー型を持つ独立したスパンとして記録する。以前の試行も失敗している呼び出しを、1 つのエラースパンで代表させてはならない。エラー型は呼び出し側が受け取る例外から読み取り、コードはクライアントが送出するエラーから読み取る。
本番環境で何が問題になるか
本章で扱う障害は、エラーを一切発生させない。SDK が置き換える手書きのヘッダーは黙って通過し、親を持たないサーバースパンも、ほかのスパンと同じようにエクスポートされる。これらを見つけるクエリは三つあり、いずれも両方のプロセスのスパンが一か所に集まっていることを前提とする。その場所は第5章で用意する。一つ目は、プロセス間リンク、すなわち一方のプロセスからもう一方のプロセスへまたがる親リンクを数えるクエリである。二つ目は、切り離されたルートを数えるクエリである。対象は、どちらのプロセスにあるかを問わず、エージェントスパン invoke_agent ambrewick-assistant 以外のルートスパンであり、traceparent なしで到着したサーバースパンもこれに含まれる。三つ目は、孤立スパン、つまり親 ID が保存済みのどのスパンも指していないスパンを数えるクエリである。これらのクエリがなければ、プロセス内では何も失敗しないので、件数だけが唯一の兆候となる。
本番では、ほかにも二つの問題が起こる。独自のスレッドプールで処理を実行するライブラリは、コンテキストをコピーするように書かれていない限り、コンテキストを失う。チームの carry() は、自分たちが所有していないプールには届かない。そのため、メッセージに属しているように見えるスパンが、独自のトレースを開始することがある。バゲージは、リクエストが行く先すべてに、つまり呼び出しが到達するあらゆるプロセスに渡る。したがって、あるプロセスでは無害だった値が、次のプロセスでは漏えいになりうる。ヘルパーが検査するのは、本書が送信するものだけである。上流から届くバゲージは検査されずに通過する。これが What goes in baggage で述べた限界である。
これでトレースの二つの半分は二か所に分かれて存在する。アシスタントのスパンはそのメモリ内に、サーバーのスパンはそのファイル内にある。これらを一つにまとめるのが The book's receiver であり、第5章で扱う。
実践ルール: ツールやワーカーのコードを変更したあとと、リリースのたびに、プロセス間リンクの件数、切り離されたルートの件数、孤立スパンの件数を確認する。いずれかに変化があれば、誰かがその理由を説明するまでは、結合が壊れたものとして扱う。
本章で下した判断
以下の各判断は、我々が誤っている可能性のある判断である。そのため、それぞれに理由と、それを検証する例を示す。
- tracer provider が設定されているときは、MCP SDK に
traceparentを書かせ、手書きのトレースキーは_metaに入れない。サーバーが読むヘッダーは SDK が書いたものであり、コード内の二つ目の写しはサーバーに届かないからである。手書きのヘッダーを置き換えた場合について、propagate-into-the-toolがこれを検証する。 - 各サーバープロセスを一つの実行として扱い、プロセスが終了した後でそのスパンファイルを読む。実行は一つの単位として始まり、終わる。そして、ファイルにすべてのスパンが揃うのは、プロセスが書き込みを終えた後だけである。
server-span-joinsが結合を検証し、server-span-without-contextが結合されていない場合の記録を示す。 - スパンを作るすべてのスレッド、プール、asyncio タスクにコンテキストを引き継ぐ。そのために
carry()とnew_task()を使う。切り離されたルートは何のエラーも出さないため、受け渡しのたびにコンテキストを引き継ぐ必要がある。orphan-span-demoがこれを検証する。この例では、通常のスレッドのスパンと executor のスパンが切り離されたルートになる。 - baggage にはリリースとプロンプトのバージョンだけを入れ、それ以外のキーと、定められた形式に合わない値はすべて拒否する。baggage は呼び出しが到達するすべてのプロセスに伝わり、仕様もそこに載せる内容について注意を促している。
baggage-keysがこれを検証する。この例では、ユーザー識別子は、未知のキーの下でも許可されたキーの下でも拒否される。 - ツール呼び出しの各試行を、それぞれ独立したスパンとして記録する。また、-32001 は MCP のコードではなく SDK のコードとして扱う。第8章ではメッセージが遭遇した失敗を数えるが、最初の試行のタイムアウトはその一つである。そのため、呼び出し全体を一つのスパンにすると、それが隠れてしまう。
contacts-timeout-liveは両方の試行を ERROR スパンとして示す。
この版における本章
第2026.11.2版2026年11月23日時点で例が通過この章の7 例件のうち7件が合格
英語版の書籍(版2026.11.2)から翻訳した。