프로세스를 가로질러 요청 따라가기

읽는 데 약 37분, 8절에 7개 예제이(가) 있음.

2026.11.2판 예제 통과 2026년 11월 23 80개 예제 중 80개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.2판을 번역한 것이다. 원문 읽기

Labs

직접 해 보며 이 장을 배운다

모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. 약 30초 안에 열린다.

모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. Labs가 실행을 대신한다: 월 40시간.

Lab에서 열기, 새 탭에서

이용 시간을 확인하는 중…

Lab을 찾는 중…

자신의 컴퓨터에서, 무료로: 이 책의 노트북 내려받기, 코드와 데이터를 포함해 GitHub에서 받을 수 있다.

이 장을 마치면 다른 팀의 서버가 기록하는 스팬이 그 스팬을 일으킨 메시지의 트레이스에 합류하게 만들 수 있고, 합류했는지 확인할 수 있으며, 합류하지 못한 스팬을 찾아낼 수 있다. 문제는 요청 하나에서 시작한다. 200개의 메시지를 기록한 기준 1일째의 메시지 16297은 연락처에 대해 묻는다. 그래서 라우터는 이 메시지를 messages 경로로 보내고, 이 경로는 find_contact를 호출한다. 이 도구는 연락처 팀의 MCP 서버에서 실행된다. 이 서버는 어시스턴트가 시작하여 stdio로 통신하는 별도의 프로세스이며, 자체 스팬을 기록한다. 이 스팬들이 메시지의 트레이스 ID를 갖지 않고 자신을 요청한 호출을 가리키지 않는 한, 트레이스는 도구 단계에서 끊기고 어느 메시지를 위한 조회였는지 알려 주는 것은 아무것도 없다.

이 조회는 Replay and the virtual clock의 가상 시계를 사용하여, 기록에 쓴 4 vCPU Intel Xeon 2.10 GHz 머신에서 재생한다. 따라서 이 장에서는 서버의 스팬이 메시지의 트레이스에 합류하게 만들고, 합류하지 못한 스팬을 찾아내는 집계를 구성한다.

contacts 서버는 별도의 프로세스이다

어시스턴트는 find_contact을(를) 직접 실행하지 않는다. 서버는 contacts 팀이 소유하며, 2.3.0 버전의 mcp 패키지가 서버를 하위 프로세스로 시작하고 표준 입출력으로 요청을 보낸다. 명세는 이 전송 방식을 stdio라고 부른다. 서버는 독립된 프로세스이므로 서버의 스팬은 어시스턴트의 메모리에 들어오지 않는다. 서버는 스팬을 자체 JSON-lines 파일에 쓰고, 어시스턴트는 프로세스가 종료된 뒤에 그 파일을 읽는다. MCP SDK는 보내는 요청마다 스팬을 만들며, 이 스팬은 Trace calls with OpenTelemetry에서 자세히 다룬다. 조인이 서버의 스팬을 메시지에 묶어 준다. 헤더를 잃은 요청은 서버의 작업을 파일에 남기지만, 그 작업을 일으킨 질문과의 연결은 남지 않는다.

사례의 다른 도구에는 이 문제가 없다. 캘린더, 알람, 목록 도구는 어시스턴트 자신의 프로세스 안에서 실행되므로 스팬이 같은 메모리에서 만들어지고, One message, one trace에서 본 일반적인 부모 링크로 트레이스에 합류한다.

이 장은 contacts 서버의 수명을 세션이 아니라 실행(run)이라고 부른다. Model Context Protocol 명세의 2026-07-28 개정판은 stdio 프로세스와 같은 열린 연결이 대화나 세션이 아니며, 서버가 그렇게 취급해서는 안 된다고 말한다. 리플레이는 실행마다 프로세스를 하나 시작하고 이를 contacts startup 스팬 안에 둔다. 그 실행이 응답하는 모든 메시지는 이 프로세스를 재사용하므로, 한 번의 실행에는 프로세스 하나와 스팬 파일 하나가 있고 파일은 실행이 끝난 뒤에 읽는다. 실행마다 자기 프로세스를 시작하므로 한 실행에서 다음 실행으로 넘어가는 것은 없다. 이것은 MCP 명세의 무상태성 절이 권장하는 대로 리플레이가 내린 선택이다. 실제 운영에서 클라이언트는 프로세스의 수명을 하나의 작업, 스레드, 대화에 묶어서는 안 된다. propagate-into-the-tool이(가) 두 번의 호출로 하듯이, 실행마다 프로세스를 하나 시작하고 메시지 사이에서 재사용한다. 실행보다 오래 사는 서버는 종료 시점에 읽을 수 없으므로 flush나 리시버가 필요하며, 이는 The book's receiver가 제공한다.

녹화에는 이 절이 다루는 실패가 담겨 있다. 기준일 1은 트레이서 프로바이더가 없는 클라이언트로 녹화되었으므로 클라이언트는 컨텍스트를 보내지 않았다. 예제는 그 녹화를 읽는다.

server-span-without-context.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 통과
"""Read baseline day 1's recorded contacts-server spans for message 16297. The recorder's client sent no context, so theserver's lookup span has no parent and starts a trace of its own: a detached root. The prose's two counts rest on theprinted lines, and the assert backs the parent count."""from lib.dayrun import DATAimport jsonrows = [json.loads(line) for line in (DATA / "baseline-day-1" / "contacts-spans.jsonl").read_text(encoding="utf-8").splitlines()]lookups = [r for r in rows if r["name"] == "tools/call find_contact"]with_parent = [r for r in lookups if r["parent_span_id"] is not None]lookup = next(r for r in rows if r["name"] == "contacts.lookup")call = lookups[0]assert with_parent == [] and lookup["parent_span_id"] == call["span_id"] and lookup["trace_id"] == call["trace_id"]print("tools/call find_contact spans in the contacts server:", len(lookups))print("of them with a parent:", len(with_parent))print("contacts.lookup under it, in its trace: yes")
출력python server-span-without-context.py
tools/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 스팬이 있으며, 그중 0개가 부모를 가진다. 조회 자체의 스팬은 여전히 서버 파일에서 해당 호출 아래에 있다. 그러나 부모가 없는 호출은 분리된 루트이므로(컨텍스트는 스레드 경계에서 유실된다에서 정의했다), 메시지와 그 호출을 이어 주는 것이 없다.

작업 규칙: 각 서버 프로세스에 자체 트레이서 프로바이더와 익스포터를 주고, 프로세스가 종료된 뒤에만 스팬 파일을 읽는다. 서버는 SimpleSpanProcessor를 사용하며, 이 프로세서는 스팬이 끝날 때 각 스팬을 익스포터에 넘기므로 종료 후에 읽은 파일에는 서버가 만든 모든 스팬이 들어 있다. BatchSpanProcessor는 flush나 shutdown이 일어날 때까지 스팬을 큐에 보관하므로, 이를 사용하면 둘 중 하나가 일어난 뒤에야 파일이 완전해진다.

MCP SDK는 traceparent를 _meta에 기록한다

서버 스팬이 트레이스에 합류하려면 요청이 트레이스의 식별 정보를 담고 있어야 하며, MCP는 이를 위해 각 요청에 인자와 별도로 _meta 객체를 둔다. 식별 정보를 담는 필드는 2021년 11월 23일에 권고안이 된 W3C Trace Context가 정의한다. traceparent 헤더는 하이픈으로 이어진 네 개의 필드, 즉 버전, 트레이스 ID, 부모 스팬 ID, 플래그로 이루어진다. 트레이스 ID는 16진수 32자리이고 부모 ID는 16자리이며, 둘 중 어느 쪽이든 모두 0인 값은 유효하지 않다. 플래그에는 샘플링 결정이 담기는데, 11장은 이를 부모 기반 샘플링에서 사용한다.

컨텍스트 전파는 스팬의 식별 정보와 baggage로 이루어진 컨텍스트를 다음 프로세스로 전달한다. traceparent는 그중 스팬에 해당하는 부분, 곧 트레이스 ID, 부모의 스팬 ID, 트레이스 플래그를 위한 W3C 필드이며, 트레이스 플래그 중 정의된 것은 샘플링 플래그뿐이다. 스팬의 컨텍스트에는 트레이스 상태 등 더 많은 내용이 있지만, 서버가 자기 스팬을 올바른 부모 아래에 붙이는 데 필요한 것은 이 세 가지다.

가장 먼저 해 볼 일은 헤더를 직접 작성하고 서버가 그것을 어떻게 처리하는지 보는 것이다. 아래에서 한 호출은 이 어시스턴트가 만든 적 없는 트레이스를 가리키는 헤더를 담고, 다른 호출은 서버에 없는 도구를 요청한다.

propagate-into-the-tool.py Python 3.13.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 통과
"""Write a traceparent into one call to the contacts server, then ask for a tool the server does not have. The prose's claimthat the SDK replaces the header rests on the second printed line, and its claim about the unknown tool on the third."""from lib.clock import VirtualClockfrom lib.contacts_server import SPANS_ENVfrom lib.genai import SCHEMA_URLfrom lib.ids import SequentialIdsfrom lib.tracing import make_providerimport asyncio, json, sys, tempfilefrom pathlib import Pathfrom mcp import Client, StdioServerParametersfrom opentelemetry import tracefrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterHAND_WRITTEN = "00-" + "ab" * 16 + "-" + "cd" * 8 + "-01"  # a traceparent this app never madeCALLS = [("find_contact", {"user_id": "U0161", "name": "jake"}, {"traceparent": HAND_WRITTEN}), ("no_such_tool", {}, None)]clock, exporter = VirtualClock("2026-12-08"), InMemorySpanExporter()provider = make_provider("ambrewick-assistant", "1.0.0", "propagate-example", clock, SequentialIds(), exporter, SCHEMA_URL)trace.set_tracer_provider(provider)  # the SDK injects its header only when a provider is configuredasync def make_calls(params):    """Make each call inside its own tool span, which is current while the call waits for its reply."""    replies = []    async with Client(params) as client:        for number, (name, arguments, meta) in enumerate(CALLS):            app = provider.get_tracer("ambrewick.assistant").start_span(f"execute_tool {name}", start_time=clock.at(number))            with trace.use_span(app, end_on_exit=False):  # ended below, with a virtual end time                replies.append((app, await client.call_tool(name, arguments, meta=meta)))            app.end(end_time=clock.at(number + 1))    return replieswith tempfile.TemporaryDirectory() as folder:    spans_file = Path(folder) / "spans.jsonl"  # the server's spans; read once the server has exited    params = StdioServerParameters(command=sys.executable, args=["-m", "lib.contacts_server"],                                   cwd=str(Path(__file__).resolve().parent), env={SPANS_ENV: str(spans_file)})    replies = asyncio.run(make_calls(params))    server = [json.loads(line) for line in spans_file.read_text(encoding="utf-8").splitlines()](app, _), (_, unknown) = repliesclient = next(s for s in exporter.get_finished_spans()  # the SDK's client span, child of the tool span              if s.name.startswith("MCP send tools/call") and s.parent and s.parent.span_id == app.context.span_id)span = next(r for r in server if r["parent_span_id"] == format(client.context.span_id, "016x"))assert span["trace_id"] == format(app.context.trace_id, "032x") != "ab" * 16  # joined the app's trace, not the header'sassert unknown.is_error and unknown.content[0].text == "Unknown tool: no_such_tool"print("find_contact, hand-written traceparent: server span joins the app's trace: yes")print("find_contact, hand-written traceparent kept: no")print("no_such_tool, reply is an error result: yes")
출력python propagate-into-the-tool.py
find_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
연습문제 4.1

서버가 앱의 트레이스에 합류하는 이유 설명하기

+10 증명

코드가 호출의 meta에 다른 traceparent를 직접 써 넣었는데도, 출력된 첫 번째 줄은 서버의 스팬이 앱의 트레이스에 합류한다고 알려 준다. 이를 설명하는 해설을 고른다.

서버가 앱의 트레이스에 합류하는 이유 설명하기: 올바른 설명을 고른다
Python 3.13.16에서 실행된다

OpenTelemetry 트레이서 프로바이더가 설정되어 있으면 _meta의 헤더는 요청이 클라이언트를 떠나기 전에 교체된다. 서버의 스팬은 여전히 어시스턴트의 트레이스에 합류하고, 코드가 작성한 헤더는 남지 않는다. 출력된 두 번째 줄이 이를 보여 준다. 세 번째 줄은 이 서버가 알 수 없는 도구에 응답하는 방식을 보여 준다. 서버는 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 없이 실행되는 코드에서만 헤더를 직접 작성하며, 그 경우 서버는 작성된 그대로 읽는다.

서버 스팬이 트레이스에 합류한다

The MCP SDK writes traceparent into _meta에서 보았듯이, MCP SDK가 헤더를 기록하면 서버의 스팬은 올바른 부모 아래에 놓인다. 메시지 16297을 실제 서버와 함께 재생하면, 어시스턴트의 도구 스팬에서 서버 자체의 조회까지 이어지는 부모 링크를 볼 수 있다.

server-span-joins.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 통과
"""Replay baseline day 1's message 16297 with the real contacts server over stdio, and check that the server's span joinsthe assistant's trace under the SDK's client span. The prose's counts rest on the two count lines; the server's clock isits own, so only counts are printed."""from lib.assistant import RELEASES, Assistantfrom lib.bm25 import Retrieverfrom lib.case import load_articles, load_messages, load_tool_durationsfrom lib.clock import VirtualClockfrom lib.genai import SCHEMA_URLfrom lib.ids import SequentialIdsfrom lib.replay import Replayfrom lib.tools import LiveContacts, Toolsfrom lib.tracing import make_providerimport json, tempfilefrom pathlib import Pathfrom opentelemetry import tracefrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterDAY, RELEASE = "2026-12-08", RELEASES["r0"]  # baseline day 1, and the release its recording was made withexporter = InMemorySpanExporter()provider = make_provider("ambrewick-assistant", RELEASE.service_version, "baseline-day-1-replay", VirtualClock(DAY),                         SequentialIds(), exporter, SCHEMA_URL)trace.set_tracer_provider(provider)  # the SDK makes its client span with the global provider, so it must be this onemessage = next(m for m in load_messages(DAY) if m.message_id == "16297")clock = VirtualClock(DAY, start_ns=message.arrival_ns)  # the message's clock starts at its arrivalwith tempfile.TemporaryDirectory() as folder:    spans_file = Path(folder) / "contacts-spans.jsonl"  # the server writes here; it is read once the server has exited    contacts = LiveContacts(clock, spans_file)    outcome = Assistant(Replay(Path(__file__).resolve().parent / "data" / "recorded" / "baseline-day-1"), Retriever(load_articles(), RELEASE.top_k),                        Tools(load_tool_durations(), contacts), clock, provider.get_tracer("ambrewick.assistant"), RELEASE).handle(message)    contacts.close()    server = [json.loads(line) for line in spans_file.read_text(encoding="utf-8").splitlines()]mine = exporter.get_finished_spans()app = next(s for s in mine if s.name == "execute_tool find_contact")client = next(s for s in mine if s.name == "MCP send tools/call find_contact")call = next(r for r in server if r["name"] == "tools/call find_contact")lookup = next(r for r in server if r["name"] == "contacts.lookup")trace_id = format(app.context.trace_id, "032x")assert client.parent.span_id == app.context.span_id and call["trace_id"] == trace_id  # tool span, client span, same traceassert call["parent_span_id"] == format(client.context.span_id, "016x")  # the server's span is under the client spanassert lookup["parent_span_id"] == call["span_id"] and lookup["trace_id"] == trace_id  # and its lookup under thatprint("route chosen:", outcome.route)print("spans in the message's trace, assistant:", sum(s.context.trace_id == app.context.trace_id for s in mine))print("spans in the message's trace, contacts server:", sum(r["trace_id"] == trace_id for r in server))print("contacts server span under the SDK's client span, in the same trace: yes")
출력python server-span-joins.py
route 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
연습문제 4.2

서버 스팬이 클라이언트 스팬을 가리키게 하기

+10 증명

41행은 서버의 스팬을 어시스턴트의 도구 스팬과 비교하므로, 예제는 그 지점에서 AssertionError를 내며 멈춘다. 서버의 호출이 실제로 매달려 있는 스팬을 검사하도록 41행을 고친다.

lookup = next(r for r in server if r["name"] == "contacts.lookup")trace_id = format(app.context.trace_id, "032x")assert client.parent.span_id == app.context.span_id and call["trace_id"] == trace_id  # tool span, client span, same traceassert lookup["parent_span_id"] == call["span_id"] and lookup["trace_id"] == trace_id  # and its lookup under thatprint("route chosen:", outcome.route)
Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3에서 실행된다

이 체인에는 스팬 네 개와 링크 세 개가 있다. 어시스턴트의 execute_tool find_contact 스팬은 MCP send tools/call find_contact의 부모이며, 이 스팬은 SDK가 자신이 보내는 요청에 대해 CLIENT 스팬으로 만든다. 그 클라이언트 스팬은 서버의 SERVER 스팬인 tools/call find_contact의 부모이고, 서버의 contacts.lookup는 그 스팬의 자식이다. 네 스팬은 모두 하나의 트레이스 ID를 공유한다. 어시스턴트는 메시지의 트레이스에서 스팬 8개를 갖고 있고, 서버는 같은 트레이스에 3개를 더 기록한다.

클라이언트 스팬은 어시스턴트가 기록하지 않는 스팬이다. 이 스팬의 이름 MCP send tools/call find_contact는 GenAI 규약의 MCP 페이지가 스팬에 대해 제시하는 패턴 {mcp.method.name} {target}를 따르지 않는다. 3장에서 패키지가 내보내는 이름을 그대로 유지했듯이, 여기서도 MCP SDK의 이름을 유지한다. 스팬의 이름은 그 스팬을 만든 코드와 일치해야 하기 때문이다.

그림은 같은 트레이스를 트리로 그린다. 점은 어시스턴트의 스팬이고 사각형은 서버의 스팬이며, 점선은 한 프로세스에서 다른 프로세스로 넘어가는 각 부모 링크를 나타낸다. 배치는 각 스팬을 시간이 아니라 깊이에 따라 놓는다. 서버의 시계는 서버 자체의 것이고 이 장의 어떤 시간도 서버 스팬에서 오지 않기 때문이다. 그림과 출력은 구조와 부모 링크만 담는다.

figure-cross-process-tree.py Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 통과
"""Draw baseline day 1's message 16297 as one trace across the assistant and the contacts server, replayed with the liveserver. The parent-links line rests on the printed count: two server spans have an SDK client span in the assistant astheir parent. Spans sit by depth, not time, since the server's clock is its own, so the figure shows structure only."""from lib.dayrun import run_day_tracedfrom lib.figures import ACCENT, INK, MUTED, new_figure, savetraced = run_day_traced("2026-12-08", ["16297"])  # baseline day 1, with the live contacts server# One row per span of the trace, from both processes. Span IDs link the rows and are never printed.rows = [dict(r, process="assistant") for r in traced.spans] + [dict(r, process="contacts server") for r in traced.server]trace_id = next(r["trace_id"] for r in rows if r["name"] == "execute_tool find_contact")rows = [dict(r, id=r["span_id"], parent=r["parent_span_id"]) for r in rows if r["trace_id"] == trace_id]by_id = {r["id"]: r for r in rows}order = []  # depth-first: a span sits just below its parent, and its depth is its indent in the figuredef walk(row, depth):    row.update(y=len(order), x=depth)    order.append(row)    for child in (r for r in rows if r["parent"] == row["id"]):        walk(child, depth + 1)for root in (r for r in rows if r["parent"] not in by_id):    walk(root, 0)fig, ax = new_figure(height=3.6, sharex=False)for row in order:    parent = by_id.get(row["parent"])    if parent:  # an elbow from the parent's row down, then across; dashed where the link crosses the boundary        cross = parent["process"] != row["process"]        ax.plot([parent["x"], parent["x"], row["x"]], [parent["y"], row["y"], row["y"]], linewidth=1.2, zorder=1,                color=ACCENT if cross else MUTED, linestyle="--" if cross else "-")    server_row = row["process"] == "contacts server"  # squares for the server, dots for the assistant: shape, not colour alone    ax.scatter(row["x"], row["y"], s=30, zorder=3, marker="s" if server_row else "o", color=ACCENT if server_row else INK)    ax.text(row["x"] + 0.14, row["y"], f"{row['name']} ({row['process']})", va="center", fontsize=8, color=INK)ax.invert_yaxis()ax.set_xlim(-0.3, 6.4)ax.axis("off")cross = [r for r in rows if r["parent"] in by_id and by_id[r["parent"]]["process"] != r["process"]]print("spans in the message's trace, assistant:", sum(r["process"] == "assistant" for r in rows))print("spans in the message's trace, contacts server:", sum(r["process"] == "contacts server" for r in rows))print("parent links across the boundary:", len(cross))for r in cross:  # the SDK's client span is the parent; the server's span is the child    print(f"{r['name']} in the contacts server, parent in the assistant:", by_id[r["parent"]]["name"])assert sorted(r["name"] for r in cross) == ["tools/call find_contact", "tools/list"]  # the two links, and no othersave(fig, "cross-process-tree")
출력python figure-cross-process-tree.py
spans 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
invoke_agent ambrewick-assistant (assistant)chat qwen3-4b-instruct-2507 (assistant)retrieval (assistant)chat qwen3-4b-instruct-2507 (assistant)execute_tool find_contact (assistant)MCP send tools/call find_contact (assistant)tools/call find_contact (contacts server)contacts.lookup (contacts server)MCP send tools/list (assistant)tools/list (contacts server)chat qwen3-4b-instruct-2507 (assistant)
그림 4.1 메시지 16297의 스팬을 깊이별로 나타낸 하나의 트레이스. 점선 링크는 두 프로세스 사이를 가로지른다

그림 4.1에는 점선 링크가 두 개 있으며, 출력된 개수도 이와 일치한다. 2. 하나는 서버의 tools/call find_contact로, 부모가 조회에 대한 클라이언트 스팬이다. 다른 하나는 서버의 tools/list로, 부모가 SDK가 서버의 도구 목록을 얻으려고 보내는 요청에 대한 클라이언트 스팬이다. MCP SDK는 아직 목록을 가져오지 않은 도구로부터 처음 성공 응답을 받은 뒤에 서버의 도구 목록을 요청하며, 이는 응답을 그 도구의 출력 스키마와 대조해 검사하기 위해서다(src/mcp/client/session.py, call_tool, validate_tool_result, mcp 2.3.0 기준). 이 메시지의 조회는 성공했으므로 두 번째 링크가 있다.

작업 규칙: 프로세스를 가로지르는 호출 뒤에는 각 서버 스팬이 호출자의 트레이스에 있는 클라이언트 스팬을 부모로 지목하는지 확인하고, 가로지르는 링크의 수를 센다. 가로지를 것으로 예상한 호출에서 링크 수가 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.

orphan-span-demo.py Python 3.13.16 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 통과
"""Make one span on each of four workers started inside one tool span, and show which ones find its context: a plain poolthread, the same thread with carry(), an asyncio task, and the loop's executor. The prose's counts of detached roots reston the asserts, which compare each span's parent with the tool span."""from lib.clock import VirtualClockfrom lib.context import carry, new_taskfrom lib.genai import SCHEMA_URLfrom lib.ids import SequentialIdsfrom lib.tracing import make_provider, spanfrom opentelemetry import traceimport asynciofrom concurrent.futures import ThreadPoolExecutorfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterclock, exporter = VirtualClock("2026-12-08"), InMemorySpanExporter()provider = make_provider("ambrewick-assistant", "1.0.0", "orphan-example", clock, SequentialIds(), exporter, SCHEMA_URL)tracer = provider.get_tracer("ambrewick.assistant")def retrieve(name):    """The worker's work: one span, made on whichever thread runs this. Its times are fixed, as every span's are."""    span(tracer, f"retrieve {name}", clock.at(1), clock.at(2))  # no parent given: the span takes the current oneasync def from_task():    retrieve("task")  # runs in its own task, which asyncio gave a copy of the tool span's contextasync def main():    """Runs as a task inside the tool span, starts a second task, and hands one worker to the loop's executor."""    await new_task(from_task())    await asyncio.get_running_loop().run_in_executor(None, retrieve, "executor")  # copies no contextapp = tracer.start_span("execute_tool retrieve", start_time=clock.at(0))with trace.use_span(app, end_on_exit=False):  # current while the workers run, so their spans can find it    with ThreadPoolExecutor(max_workers=1) as pool:        pool.submit(retrieve, "plain").result()  # the pool's thread starts with an empty context        pool.submit(carry(retrieve), "carried").result()  # carry() runs the work in a copy of this context    asyncio.run(main())app.end(end_time=clock.at(3))spans = {s.name: s for s in exporter.get_finished_spans()}joined = {name: spans[name].parent is not None and spans[name].parent.span_id == app.context.span_id for name in spans}assert joined == {"retrieve plain": False, "retrieve carried": True, "retrieve task": True, "retrieve executor": False,                  "execute_tool retrieve": False}assert all(spans[n].context.trace_id != app.context.trace_id for n in ["retrieve plain", "retrieve executor"])  # own tracesprint("retrieve on a plain thread, joins the tool span: no")print("retrieve on a thread with carry(), joins the tool span: yes")print("retrieve in an asyncio task, joins the tool span: yes")print("retrieve through run_in_executor, joins the tool span: no")print("detached roots without the helper:", sum(not joined[n] for n in ["retrieve plain", "retrieve executor"]))print("detached roots with the helper:", sum(not joined[n] for n in ["retrieve carried"]))print("detached root's trace differs from the tool span's: yes")
출력python orphan-span-demo.py
retrieve 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
연습문제 4.3

풀 스레드에 컨텍스트 복사본을 넘겨라

+10 증명

38행은 retrieve 함수를 그대로 풀에 넘기므로, 이 함수가 만드는 스팬은 도구 스팬에 합류하지 못하고 새 트레이스를 시작한다. 38행을 고쳐서 carry()로 감싼 작업자의 스팬이 도구 스팬에 합류하도록 하라.

with trace.use_span(app, end_on_exit=False):  # current while the workers run, so their spans can find it    with ThreadPoolExecutor(max_workers=1) as pool:        pool.submit(retrieve, "plain").result()  # the pool's thread starts with an empty context    asyncio.run(main())app.end(end_time=clock.at(3))
Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3에서 실행된다

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.

baggage-keys.py Python 3.13.16 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 통과
"""Put the release and the prompt version in baggage, and carry them as an MCP call would: the global propagator writes the`baggage` entry that the SDK sends in `_meta`. A user identifier is refused under an unknown key and under an allowed one.The prose rests on the last two printed lines, which the asserts back."""from lib.context import ALLOWED_BAGGAGE_KEYS, baggage_contextfrom opentelemetry import baggage, propagatedef refused(values):    """True when baggage_context refuses these values."""    try:        baggage_context(values)    except ValueError:        return True    return Falsectx = baggage_context({"ambrewick.release": "1.0.0", "ambrewick.prompt.version": "p1"})carrier = {}propagate.inject(carrier, context=ctx)  # the same global propagator the SDK uses for `_meta`carried = sorted(baggage.get_all(ctx))assert carried == sorted(ALLOWED_BAGGAGE_KEYS)  # nothing else is carriedassert carrier["baggage"] == "ambrewick.prompt.version=p1,ambrewick.release=1.0.0"assert refused({"ambrewick.user.id": "U0161"})  # a key that is not allowedassert refused({"ambrewick.release": "U0161"})  # a user identifier under an allowed key, which is not in its formprint("allowed baggage keys:", ", ".join(sorted(ALLOWED_BAGGAGE_KEYS)))print("baggage keys carried on a call:", ", ".join(carried))print("baggage entry sent in _meta:", carrier["baggage"])print("user identifier refused: yes")print("user identifier under an allowed key refused: yes")
출력python baggage-keys.py
allowed 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
연습문제 4.4

호출이 운반하는 키를 baggage에서 읽기

+10 증명

20번째 줄은 baggage 항목을 하나만 담고 있는 캐리어에서 키를 읽으므로 21번째 줄의 assert가 실패한다. 호출이 운반하는 baggage에서 키를 가져오도록 고쳐라.

ctx = baggage_context({"ambrewick.release": "1.0.0", "ambrewick.prompt.version": "p1"})carrier = {}propagate.inject(carrier, context=ctx)  # the same global propagator the SDK uses for `_meta`assert carried == sorted(ALLOWED_BAGGAGE_KEYS)  # nothing else is carriedassert carrier["baggage"] == "ambrewick.prompt.version=p1,ambrewick.release=1.0.0"assert refused({"ambrewick.user.id": "U0161"})  # a key that is not allowed
Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3에서 실행된다

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.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

A timeout is raised, not returned

The lookup can fail in more than one way, and the failures arrive differently at the caller. A tool that the server does not have comes back as an error result from this server. A conforming server built by another team fails differently: the specification's tools page makes an unknown tool a protocol error, a JSON-RPC error with code -32602, which the client raises as MCPError. A read timeout does not come back from any server at all. The SDK raises it as an MCPError, with the code -32001.

The specification assigns no code to errors that are purely local to an implementation, such as a request timeout raised inside an SDK. So -32001 is not an MCP code. The client made it itself, and no server sent it. The specification puts -32001 in its legacy range, -32000 to -32019, where new implementations should not use codes and receivers must not assume a meaning, and it asks that a local error never be mistaken for a peer's. mcp raises the timeout as the same MCPError class it uses for a server's errors, so a query over ambrewick.mcp.error_code must not count -32001 as the server's error. We call -32001 the SDK's code for a read timeout, and chapter 8 reads these timeouts across the incident day under the same name.

This section uses an injected incident, inc-contacts-timeout, which makes the contacts server answer too slowly for a window of the incident day. The injection is labelled as one in the spans it touches, and the example's first printed line names it.

contacts-timeout-live.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 통과
"""Replay incident-day message 16297 with the live contacts server, inside the injected timeout window. Each attempt offind_contact is its own execute_tool span. The first raises MCPError with code -32001, the SDK's code for a read timeout,which the MCP spec does not assign: that span ends ERROR, with error.type MCPError and an exception event. The retry starts2.5 s later, times out too, and the tool step gives up."""from lib.dayrun import run_day_tracedfrom lib.tools import TIMEOUT_CODEtraced = run_day_traced("2026-12-09", ["16297"])  # the incident day, with the live server inside its windowoutcome = traced.runs[0].outcomeattempts = sorted((r for r in traced.spans if r["name"] == "execute_tool find_contact"),                  key=lambda r: r["attributes"]["ambrewick.attempt"])injected = [r for r in traced.server if r["name"] == "tools/call find_contact" and "ambrewick.incident.id" in r["attributes"]]first, second = attemptsassert len(attempts) == 2 and outcome.source == "model"  # the retry times out too, and the answer comes from the modelassert all(a["status"] == "ERROR" and a["attributes"]["error.type"] == "MCPError" for a in attempts)assert first["attributes"]["ambrewick.mcp.error_code"] == TIMEOUT_CODEassert len(injected) == 2 and all(r["attributes"]["ambrewick.incident.injected"] is True for r in injected)print("injected incident, ID:", injected[0]["attributes"]["ambrewick.incident.id"])print("attempts of find_contact:", len(attempts))print("attempt 1, status and error.type:", first["status"], first["attributes"]["error.type"])print("attempt 1, error code:", first["attributes"]["ambrewick.mcp.error_code"])print("attempt 1, exception event:", first["events"][0]["attributes"]["exception.type"].rsplit(".", 1)[-1])print("attempt 1, time:", f"{(first['end_ns'] - first['start_ns']) / 1e9:.1f} s")  # the 2.0 s timeoutprint("attempt 2 starts after attempt 1:", f"{(second['start_ns'] - first['start_ns']) / 1e9:.1f} s")  # 2.0 s + 0.5 sprint("tool step, time:", f"{(second['end_ns'] - first['start_ns']) / 1e9:.1f} s")
출력python contacts-timeout-live.py
injected 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
연습문제 4.5

호출자가 받는 오류 유형 확인하기

+10 증명

15행은 각 시도의 오류 유형을 SDK가 클라이언트 내부에서 잡은 예외와 비교한다. 이를 호출자가 받는 예외와 비교하도록 바꾼다.

injected = [r for r in traced.server if r["name"] == "tools/call find_contact" and "ambrewick.incident.id" in r["attributes"]]first, second = attemptsassert len(attempts) == 2 and outcome.source == "model"  # the retry times out too, and the answer comes from the modelassert first["attributes"]["ambrewick.mcp.error_code"] == TIMEOUT_CODEassert len(injected) == 2 and all(r["attributes"]["ambrewick.incident.injected"] is True for r in injected)print("injected incident, ID:", injected[0]["attributes"]["ambrewick.incident.id"])
Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3에서 실행된다

Message 16297 on the incident day runs with the live server inside the injected window. The first attempt times out, and the printed lines show its status, its error type and its code, which is -32001. The attempt takes 2.0 s on the virtual clock, which is the timeout the client is configured with. The second attempt starts 2.5 s after the first, also times out, and the tool step gives up after 4.5 s in all.

Each attempt is its own execute_tool span, and we count each one as its own operation. A failed attempt is therefore ERROR, with error.type set to the class the caller received, MCPError, not the inner TimeoutError that the SDK caught underneath it. The code goes on ambrewick.mcp.error_code, not on rpc.status_code: the conventions define that attribute as the error code from the JSON-RPC response, and a local timeout has no response. The retry does not turn the first attempt into a success. The conventions' recording-errors page says that retried errors stay off the span, but that rule covers an operation that succeeds on retry, and here each attempt is one operation that failed. The alternative reading would hide the first attempt's timeout, and chapter 8 needs that timeout to count the failures a message met.

Working rule: Record each attempt of a call as its own span, with its own status and error type, and never let one error span stand for a call whose earlier attempts also failed. Read the error type from the exception the caller receives, and read the code from the error the client raises.

운영 환경에서 잘못되는 것

이 장에서 다루는 실패는 오류를 일으키지 않는다. SDK가 대체하는 직접 작성한 헤더는 조용히 통과하고, 부모가 없는 서버 스팬도 다른 스팬과 똑같이 내보내진다. 쿼리 세 개로 이런 실패를 찾을 수 있으며, 각 쿼리에는 두 프로세스의 스팬이 한곳에 모여 있어야 한다. 그런 곳은 5장에서 마련한다. 첫 번째 쿼리는 프로세스 간 연결, 즉 한 프로세스에서 다른 프로세스로 넘어가는 부모 연결의 수를 센다. 두 번째 쿼리는 분리된 루트의 수를 센다. 분리된 루트란 어느 프로세스에 있든 에이전트 스팬 invoke_agent ambrewick-assistant이 아닌 루트 스팬을 말하며, traceparent 없이 도착한 서버 스팬도 여기에 해당한다. 마지막 쿼리는 고아 스팬의 수를 센다. 고아 스팬은 부모 ID가 저장된 어떤 스팬도 가리키지 않는 스팬이다. 이 쿼리가 없으면 프로세스 안에서는 아무것도 실패하지 않으므로, 이 개수가 유일한 신호다.

운영 환경에서는 두 가지 문제가 더 생긴다. 자체 스레드 풀에서 작업을 실행하는 라이브러리는 컨텍스트를 복사하도록 작성되지 않았다면 컨텍스트를 잃는다. 팀의 carry()는 팀이 소유하지 않은 풀에는 닿을 수 없으므로, 메시지에 속하는 것처럼 보이는 스팬이 자체 트레이스를 시작할 수 있다. 배기지는 요청이 가는 곳이면 어디든, 즉 호출이 닿는 모든 프로세스로 전달된다. 따라서 한 프로세스에서는 무해했던 값이 다음 프로세스에서는 유출이 될 수 있다. 헬퍼는 이 책이 보내는 것만 검사한다. 업스트림에서 도착하는 배기지는 검사 없이 통과하며, 이것이 배기지에 들어가는 것에서 설명하는 한계다.

트레이스의 두 절반은 이제 두 곳에 있다. 어시스턴트의 스팬은 어시스턴트의 메모리에, 서버의 스팬은 서버의 파일에 있으며, 5장은 이 책의 수신기에서 이 둘을 합친다.

작업 규칙: 도구 코드나 워커 코드를 변경한 뒤와 모든 릴리스마다 프로세스 간 연결 수, 분리된 루트 수, 고아 스팬 수를 확인한다. 이 중 하나라도 변하면 누군가 그 이유를 설명하기 전까지는 조인이 깨진 것으로 간주한다.

이 장에서 내린 결정

아래의 각 결정은 우리가 틀릴 수도 있는 판단이므로, 각각 그 이유와 이를 검증하는 예제를 함께 제시한다.

  • 트레이서 공급자가 설정되어 있으면 MCP SDK가 traceparent를 쓰도록 맡기고, 직접 작성한 추적 키는 _meta에 넣지 않는다. 서버가 읽는 헤더는 SDK가 쓴 헤더이므로, 코드에 둔 두 번째 사본은 서버에 도달하지 못한다. 직접 작성한 헤더를 대체하는 propagate-into-the-tool가 이를 검증한다.
  • 각 서버 프로세스를 하나의 실행으로 취급하고, 프로세스가 종료된 뒤에 그 스팬 파일을 한 번 읽는다. 실행은 하나의 단위로 시작하고 끝나며, 파일에는 프로세스가 쓰기를 마친 뒤에야 모든 스팬이 담긴다. server-span-joins가 결합을 검증하고, server-span-without-context는 결합이 빠진 기록을 보여 준다.
  • 스팬을 만드는 모든 스레드, 풀, asyncio 태스크로 carry()와 new_task()를 사용해 컨텍스트를 전달한다. 분리된 루트는 아무 오류도 일으키지 않으므로, 작업을 넘겨주는 모든 지점에서 컨텍스트를 전달해야 한다. 일반 스레드의 스팬과 실행기의 스팬이 분리된 루트가 되는 orphan-span-demo가 이를 검증한다.
  • 배기지에는 릴리스와 프롬프트 버전만 넣고, 그 외의 모든 키와 정해진 형식을 벗어난 모든 값은 거부한다. 배기지는 호출이 닿는 모든 프로세스로 전달되며, 명세는 배기지에 실을 수 있는 내용에 대해 경고한다. 알 수 없는 키와 허용된 키 아래의 사용자 식별자가 모두 거부되는 baggage-keys가 이를 검증한다.
  • 도구 호출의 각 시도를 별도의 스팬으로 기록하고, -32001은 MCP 코드가 아니라 SDK의 코드라고 명시한다. 8장은 메시지가 겪은 실패를 세는데, 첫 번째 시도의 타임아웃도 그중 하나이므로 호출 전체를 스팬 하나로 기록하면 이를 가리게 된다. contacts-timeout-live는 두 시도를 모두 ERROR 스팬으로 보여 준다.

이 판의 이 장

2026.11.2판예제 통과 2026년 11월 237 of 7개 예제 in this chapter pass

영어판 2026.11.2판을 번역한 것이다.

Labs 시작

도서는 계속 무료로 읽을 수 있다.

요금 보기

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

12장 중 4장: 프로세스를 가로질러 요청 따라가기

  1. contacts 서버는 별도의 프로세스이다
  2. MCP SDK는 traceparent를 _meta에 기록한다
  3. 서버 스팬이 트레이스에 합류한다
  4. Context is lost at a thread boundary
  5. What goes in baggage
  6. A timeout is raised, not returned
  7. 운영 환경에서 잘못되는 것
  8. 이 장에서 내린 결정

맨 위로 돌아가기전체 장