CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
feat(tracing): Phase 5 — MCP CLIENT spans + traceparent helper (#86)
Chris311018929ddd
diff --git a/cubepi/mcp/_adapter.py b/cubepi/mcp/_adapter.pyindex 367b9d6..b435b23 100644--- a/cubepi/mcp/_adapter.py+++ b/cubepi/mcp/_adapter.py@@ -7,6 +7,7 @@ from typing import Any, Awaitable, Callable, Literalfrom pydantic import BaseModel, Field, create_modelfrom cubepi.agent.types import AgentTool, AgentToolResult+from cubepi.mcp._tracing import mark_span_mcp_error, mcp_client_spanfrom cubepi.providers.base import Content, ImageContent, TextContent@@ -104,12 +105,21 @@ def make_mcp_agent_tool(description: str,input_schema: dict[str, Any],call_remote: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]],+ server_address: str | None = None,+ server_port: int | None = None,+ protocol_version: str | None = None,+ session_id: str | None = None,) -> AgentTool:"""Build a cubepi.AgentTool wrapping an MCP tool call.call_remote is the transport-specific RPC: given (tool_name, args_dict),returns the MCP tools/call response dict normalized to:{"content": [{"type": "text", "text": ...}, ...], "isError": bool}++ The optional ``server_address`` / ``server_port`` / ``protocol_version``+ / ``session_id`` are recorded on the OTel CLIENT span around the+ remote call when ``cubepi[tracing]`` is installed. Loaders pass+ whichever values they have access to from the MCP handshake."""parameters_model = mcp_schema_to_pydantic_model(tool_name=name,@@ -123,16 +133,33 @@ def make_mcp_agent_tool(signal=None,on_update=None,) -> AgentToolResult:- # tool_call_id and on_update are unused by MCP semantics (MCP RPC is- # not incremental), but we accept them for signature compatibility- # with cubepi's agent loop.- del tool_call_id, on_update+ # on_update is unused by MCP semantics (MCP RPC is not+ # incremental). ``tool_call_id`` is forwarded as the parent+ # lookup key so the CLIENT span nests under the cubepi recorder's+ # execute_tool span when tracing is enabled.+ del on_updateargs_dict = (args.model_dump(exclude_none=True)if hasattr(args, "model_dump")else dict(args))- result = await call_remote(name, args_dict)+ async with mcp_client_span(+ method="tools/call",+ tool_name=name,+ session_id=session_id,+ protocol_version=protocol_version,+ server_address=server_address,+ server_port=server_port,+ parent_tool_call_id=tool_call_id,+ ) as span:+ result = await call_remote(name, args_dict)+ # MCP server-reported tool failure (``isError: true``): the+ # JSON-RPC call succeeded but the tool's logic failed. Mark+ # the CLIENT span ERROR so backends count it as a failure,+ # matching the cubepi.tool.is_error treatment for non-MCP+ # tool spans.+ if result.get("isError"):+ mark_span_mcp_error(span, "MCP server returned isError")content_blocks: list[Content] = []for c in result.get("content", []):ctype = c.get("type")diff --git a/cubepi/mcp/_tracing.py b/cubepi/mcp/_tracing.pynew file mode 100644index 0000000..08fa692--- /dev/null+++ b/cubepi/mcp/_tracing.py@@ -0,0 +1,389 @@+"""MCP-side OTel CLIENT span instrumentation.++This module is intentionally local to ``cubepi/mcp`` so the core MCP+adapter has zero hard dependency on ``opentelemetry`` — if the OTel API+is not installed, every public symbol becomes a no-op pass-through. When+``cubepi[tracing]`` is installed, MCP ``tools/call`` invocations+automatically emit CLIENT spans per the OTel GenAI MCP semconv (§14 of+the tracing design spec).++Span emitted per call::++ tools/call <tool_name> [CLIENT]+ mcp.method.name = "tools/call"+ gen_ai.tool.name = <tool_name>+ gen_ai.operation.name = "execute_tool"+ mcp.session.id = <if provided>+ mcp.protocol.version = <if provided>+ server.address = <if provided>+ server.port = <if provided>+ error.type = <on failure>++The W3C ``traceparent`` for downstream-server propagation is exposed+via :func:`current_traceparent`; the HTTP loader injects it into the+session's HTTP headers so an instrumented MCP server can continue the+trace. The MCP Python SDK does not expose the JSON-RPC ``params._meta``+slot directly, so we use HTTP headers as the practical wire location —+W3C trace-context spec §3 permits either.+"""++from __future__ import annotations++import contextvars+from contextlib import asynccontextmanager+from typing import TYPE_CHECKING, Any, AsyncIterator++if TYPE_CHECKING:+ pass+++try:+ from opentelemetry import trace as _otel_trace+ from opentelemetry.trace import SpanKind, Status, StatusCode++ _OTEL_AVAILABLE = True+except ImportError: # pragma: no cover — exercised only without the extra.+ _OTEL_AVAILABLE = False+ _otel_trace = None # type: ignore[assignment]+ SpanKind = None # type: ignore[assignment]+ Status = None # type: ignore[assignment]+ StatusCode = None # type: ignore[assignment]+++# When :class:`cubepi.tracing.Tracer` is attached to an agent it+# pushes its private :class:`TracerProvider` onto this stack. Without+# any registration, ``_otel_trace.get_tracer`` falls back to the OTel+# global default — which is a no-op provider unless the caller also+# did ``set_tracer_provider`` themselves.+#+# Using a stack rather than a single slot lets one Tracer attach to+# multiple agents (each attach pushes a token; each detach pops just+# its own entry) and supports detaches in any order without clearing+# routing for the still-attached agents.+_provider_stack: list[tuple[object, Any]] = []+++def register_provider(provider: Any) -> object:+ """Push ``provider`` onto the routing stack as the preferred source+ for MCP spans. Returns an opaque token that+ :func:`unregister_provider` uses to remove this exact entry.++ Called by :meth:`cubepi.tracing.Tracer.attach`.+ """+ token = object()+ _provider_stack.append((token, provider))+ return token+++def unregister_provider(token: object | None = None) -> None:+ """Remove a previously-registered provider.++ ``token`` is the value returned from :func:`register_provider`.+ When ``None`` (legacy callers) the most recent entry is popped.+ Out-of-order detaches affect only their own registration; siblings+ remain.+ """+ if not _provider_stack:+ return+ if token is None:+ _provider_stack.pop()+ return+ for i, (t, _p) in enumerate(_provider_stack):+ if t is token:+ _provider_stack.pop(i)+ return+++def _get_tracer(scope_name: str) -> Any:+ """Resolve the tracer to use for emitting an MCP span.++ Prefers the most recently-registered provider over OTel's global+ default (which is a no-op unless the user separately called+ ``set_tracer_provider``).+ """+ if _provider_stack:+ return _provider_stack[-1][1].get_tracer(scope_name)+ return _otel_trace.get_tracer(scope_name)+++# When the cubepi Recorder opens an ``execute_tool`` span, it publishes+# ``(span, owning_provider)`` here so an MCP tool call running inside+# the AgentTool body can make its CLIENT span a child of this span+# (rather than starting an orphan root trace — recorder doesn't bother+# installing ``execute_tool`` as the OTel current span; see+# docs/specs/2026-05-18-cubepi-tracing-design.md §9), and route the+# CLIENT span through the parent's owning provider so trace_ids and+# exporter destination stay consistent (codex round-7).+#+# Lookup uses a per-task ``ContextVar`` holding an opaque handle, with+# the actual ``(span, provider)`` payload stored in a module-level+# ``_active_entries`` dict. The dict is the source of truth for+# cleanup; the contextvar is the per-task pointer.+#+# Why both: tool-call ids are provider-local (Faux / OpenAI-style mint+# ``tc1`` / ``call_...`` per conversation), so a global dict keyed by+# ``tool_call_id`` lets concurrent agents overwrite each other (codex+# round-8). ContextVars scope per asyncio task and copy on+# ``create_task``, so each agent run — and each spawned tool task+# within it — sees only its own parent. BUT the cubepi agent loop+# emits ``ToolExecutionStartEvent`` in the parent task and (in+# ``parallel`` tool mode) ``ToolExecutionEndEvent`` from the per-tool+# *child* task it spawns. A ``Token`` produced in the parent task+# cannot be ``reset`` in a child task — ``ContextVar.reset`` raises+# ``ValueError`` (codex round-9). The dict-handle indirection lets+# ``unregister_tool_span`` clean up the payload unconditionally (so+# any later lookup through the stale contextvar returns ``None``),+# while the contextvar reset is best-effort and skipped silently when+# the calling task differs from the registering one.+_active_entries: dict[object, tuple[Any, Any]] = {}+_current_handle: contextvars.ContextVar[object | None] = contextvars.ContextVar(+ "_cubepi_mcp_current_tool_handle", default=None+)+++def register_tool_span(+ tool_call_id: str,+ span: Any,+ provider: Any = None,+) -> tuple[object, contextvars.Token[object | None]]:+ """Publish ``span`` (and its owning ``provider``) as the current+ ``execute_tool`` parent for the calling task.++ Returns a ``(handle, cv_token)`` tuple — pass it to+ :func:`unregister_tool_span` on tool-exec end. The handle is used+ for dict cleanup (safe across tasks); the cv_token is used for+ contextvar reset (best-effort, only valid in the registering+ task).++ ``tool_call_id`` is accepted for API symmetry / future debug attrs+ but is not used as a lookup key — see module-level comment.+ """+ del tool_call_id+ handle = object()+ _active_entries[handle] = (span, provider)+ cv_token = _current_handle.set(handle)+ return (handle, cv_token)+++def unregister_tool_span(+ token: tuple[object, contextvars.Token[object | None]] | None,+) -> None:+ """Clean up a previously-registered entry.++ ``token`` is the value returned from :func:`register_tool_span`,+ or ``None`` (no-op, for callers that defensively unregister when+ the corresponding register failed).++ The dict entry is always removed — this is the safety net for+ cross-task ``unregister`` (parallel tool mode emits+ ``ToolExecutionEndEvent`` from the child task even though+ ``register`` ran in the parent). The contextvar reset is+ attempted but silently skipped if the calling task is not the+ registering task; the next ``register`` in the parent task will+ overwrite the stale handle.+ """+ if token is None:+ return+ handle, cv_token = token+ _active_entries.pop(handle, None)+ try:+ _current_handle.reset(cv_token)+ except (ValueError, LookupError):+ pass+++def _get_tool_span_entry() -> tuple[Any, Any] | None:+ """Return the (span, provider) entry for the current task, or+ ``None`` when no live ``execute_tool`` is in scope.++ A stale contextvar handle (pointing at an already-cleaned-up dict+ entry) returns ``None`` — exactly the same outcome as no parent at+ all, so the MCP CLIENT span starts a new root rather than+ parenting under an already-ended span.+ """+ handle = _current_handle.get()+ if handle is None:+ return None+ return _active_entries.get(handle)+++def _current_span_via_registered() -> Any:+ """Return the current span — preferring the registered provider's+ context. Used by :func:`current_traceparent`.++ The OTel context is process-global and shared across providers, so+ ``get_current_span()`` returns the right answer whether or not we+ use the registered provider. We expose this indirection so tests+ can monkeypatch a single helper.+ """+ return _otel_trace.get_current_span()+++# Public attribute name constants — duplicated from+# cubepi.tracing.schema so this module can be imported without the+# tracing extra installed. Keep in sync.+_MCP_METHOD_NAME = "mcp.method.name"+_MCP_SESSION_ID = "mcp.session.id"+_MCP_PROTOCOL_VERSION = "mcp.protocol.version"+_GEN_AI_TOOL_NAME = "gen_ai.tool.name"+_GEN_AI_OPERATION_NAME = "gen_ai.operation.name"+_SERVER_ADDRESS = "server.address"+_SERVER_PORT = "server.port"+_ERROR_TYPE = "error.type"+_SCOPE_NAME = "cubepi.mcp"+++@asynccontextmanager+async def mcp_client_span(+ *,+ method: str = "tools/call",+ tool_name: str | None = None,+ session_id: str | None = None,+ protocol_version: str | None = None,+ server_address: str | None = None,+ server_port: int | None = None,+ parent_tool_call_id: str | None = None,+) -> AsyncIterator[Any]:+ """Open an OTel CLIENT span around an MCP RPC.++ When the OTel API is not installed (``cubepi[tracing]`` not+ selected) this yields ``None`` and the body runs unwrapped — the+ caller pays no overhead and has no observability impact.+ """+ if not _OTEL_AVAILABLE:+ yield None+ return++ span_name = f"{method} {tool_name}" if tool_name else method+ # Resolve explicit parent + owning provider from the per-task+ # contextvar published by the cubepi recorder on+ # ``_on_tool_exec_start``. If present, the MCP CLIENT span becomes a+ # child of the agent's execute_tool span AND is exported through+ # the parent's owning provider so trace_ids and exporter+ # destination stay consistent across concurrent Tracers (codex+ # round-7 + round-8). When no parent is active, fall back to the+ # registered-provider stack — used by bare ``mcp_client_span``+ # calls outside an agent run.+ #+ # ``parent_tool_call_id`` is accepted for API symmetry / future+ # debug attrs; the lookup is purely contextvar-scoped now.+ del parent_tool_call_id+ entry = _get_tool_span_entry()+ if entry is not None:+ parent_span, parent_provider = entry+ parent_context = _otel_trace.set_span_in_context(parent_span)+ tracer = (+ parent_provider.get_tracer(_SCOPE_NAME)+ if parent_provider is not None+ else _get_tracer(_SCOPE_NAME)+ )+ else:+ parent_context = None+ tracer = _get_tracer(_SCOPE_NAME)+ attrs: dict[str, Any] = {+ _MCP_METHOD_NAME: method,+ _GEN_AI_OPERATION_NAME: "execute_tool",+ }+ if tool_name is not None:+ attrs[_GEN_AI_TOOL_NAME] = tool_name+ if session_id is not None:+ attrs[_MCP_SESSION_ID] = session_id+ if protocol_version is not None:+ attrs[_MCP_PROTOCOL_VERSION] = protocol_version+ if server_address is not None:+ attrs[_SERVER_ADDRESS] = server_address+ if server_port is not None:+ attrs[_SERVER_PORT] = server_port++ span = tracer.start_span(+ span_name,+ kind=SpanKind.CLIENT,+ attributes=attrs,+ context=parent_context,+ )+ try:+ # Disable use_span's default record_exception / set_status_on_exception+ # so we are the single source of the exception event and ERROR+ # status — otherwise OTel would auto-record on context exit AND+ # this ``except`` block would record again, double-counting.+ with _otel_trace.use_span(+ span,+ record_exception=False,+ set_status_on_exception=False,+ ):+ yield span+ except BaseException as exc:+ try:+ error_type = _error_type_for(exc)+ span.set_attribute(_ERROR_TYPE, error_type)+ # Cancellation is a control signal, not a failure — match the+ # convention from the chat / turn / invoke_agent spans: leave+ # Status UNSET and mark cubepi.aborted=true, do NOT record an+ # exception event.+ if error_type == "cubepi.aborted":+ span.set_attribute("cubepi.aborted", True)+ else:+ span.set_status(Status(StatusCode.ERROR, str(exc)[:256]))+ span.record_exception(exc)+ finally:+ span.end()+ raise+ else:+ span.end()+++def mark_span_mcp_error(span: Any, message: str) -> None:+ """Mark an MCP CLIENT span as a protocol-level failure.++ An MCP server can return a normal ``tools/call`` JSON-RPC response+ with ``isError: true`` — the wire call succeeds but the tool+ reports failure. Without this helper the CLIENT span would close+ with UNSET status, hiding the failure in trace dashboards.++ Pass the span yielded by :func:`mcp_client_span` (which may be+ ``None`` when OTel isn't installed); no-op on None.+ """+ if span is None or not _OTEL_AVAILABLE:+ return+ span.set_status(Status(StatusCode.ERROR, message[:256]))+ span.set_attribute(_ERROR_TYPE, "mcp.is_error")+++def current_traceparent() -> str | None:+ """Return a W3C ``traceparent`` string for the current span context,+ or ``None`` when there is no active recording span (or OTel is not+ installed).++ Used by the HTTP loader to inject the header on outgoing MCP+ requests so an instrumented server can continue the trace.+ """+ if not _OTEL_AVAILABLE:+ return None+ span = _otel_trace.get_current_span()+ ctx = span.get_span_context()+ if not getattr(ctx, "is_valid", False):+ return None+ trace_id = ctx.trace_id+ span_id = ctx.span_id+ if not trace_id or not span_id:+ return None+ # W3C trace context §3.2: traceparent = "00-<32hex>-<16hex>-<flags>"+ flags = int(getattr(ctx, "trace_flags", 0))+ return f"00-{trace_id:032x}-{span_id:016x}-{flags:02x}"+++def _error_type_for(exc: BaseException) -> str:+ """Local error.type derivation. Mirrors cubepi.tracing.errors but+ re-implemented here so the MCP module has no hard tracing dep."""+ import asyncio++ if isinstance(exc, asyncio.CancelledError):+ return "cubepi.aborted"+ if isinstance(exc, (asyncio.TimeoutError, TimeoutError)):+ return "timeout"+ if isinstance(exc, ConnectionError):+ return "connection_error"+ cls = type(exc)+ if cls.__module__ in {"builtins", "__main__"}:+ return cls.__qualname__+ return f"{cls.__module__}.{cls.__qualname__}"diff --git a/cubepi/mcp/http_loader.py b/cubepi/mcp/http_loader.pyindex 83de6b7..9ebd647 100644--- a/cubepi/mcp/http_loader.py+++ b/cubepi/mcp/http_loader.py@@ -109,8 +109,21 @@ async def load_mcp_tools_http("""async def _call_remote(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:+ # When an MCP CLIENT span is current (cubepi.mcp._adapter wraps+ # this call in ``mcp_client_span``), propagate the W3C+ # ``traceparent`` header so an instrumented MCP server can+ # continue the trace. The helper returns None when no recording+ # span is active or OTel isn't installed; merge so caller-+ # supplied headers aren't clobbered.+ from cubepi.mcp._tracing import current_traceparent++ call_headers = headers+ tp = current_traceparent()+ if tp is not None:+ call_headers = {**(headers or {}), "traceparent": tp}+async with _open_session(- server_url, headers=headers, timeout=timeout, transport=transport+ server_url, headers=call_headers, timeout=timeout, transport=transport) as session:await asyncio.wait_for(session.initialize(), timeout=timeout)resp = await asyncio.wait_for(@@ -125,12 +138,19 @@ async def load_mcp_tools_http(tools_resp = await asyncio.wait_for(session.list_tools(), timeout=timeout)tool_descs = tools_resp.tools+ # Trace attribute sources for the CLIENT spans emitted per call.+ address, port = _split_address(server_url)+ protocol_version = _extract_protocol_version(init_result)+tools = [make_mcp_agent_tool(name=desc.name,description=desc.description or "",input_schema=desc.inputSchema or {"type": "object", "properties": {}},call_remote=_call_remote,+ server_address=address,+ server_port=port,+ protocol_version=protocol_version,)for desc in tool_descs]@@ -142,6 +162,32 @@ async def load_mcp_tools_http()+def _split_address(server_url: str) -> tuple[str | None, int | None]:+ """Extract ``(host, port)`` from a server URL for the+ ``server.address`` / ``server.port`` span attributes. Returns+ ``(None, None)`` on parse failure.+ """+ try:+ from urllib.parse import urlparse++ parsed = urlparse(server_url)+ return parsed.hostname, parsed.port+ except Exception:+ return None, None+++def _extract_protocol_version(init_result: Any) -> str | None:+ """Read ``protocolVersion`` off the MCP SDK initialize() result.++ The SDK exposes it as ``init_result.protocolVersion``. Defensive+ against future shape changes.+ """+ value = getattr(init_result, "protocolVersion", None)+ if isinstance(value, str):+ return value+ return None++def _serialize_call_tool_response(resp: Any) -> dict[str, Any]:"""Normalize mcp SDK CallToolResult → dict for adapter.diff --git a/cubepi/mcp/stdio_loader.py b/cubepi/mcp/stdio_loader.pyindex 56d72c8..07e9185 100644--- a/cubepi/mcp/stdio_loader.py+++ b/cubepi/mcp/stdio_loader.py@@ -64,12 +64,18 @@ async def load_mcp_tools_stdio(tools_resp = await asyncio.wait_for(session.list_tools(), timeout=timeout)tool_descs = tools_resp.tools+ # stdio has no network address; only protocol version is observable.+ protocol_version = getattr(init_result, "protocolVersion", None)+ if not isinstance(protocol_version, str):+ protocol_version = None+tools = [make_mcp_agent_tool(name=desc.name,description=desc.description or "",input_schema=desc.inputSchema or {"type": "object", "properties": {}},call_remote=_call_remote,+ protocol_version=protocol_version,)for desc in tool_descs]diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.pyindex ddd0598..888148a 100644--- a/cubepi/tracing/recorder.py+++ b/cubepi/tracing/recorder.py@@ -129,6 +129,10 @@ class _RunState:chat_open_ns: int | None = Nonechat_first_chunk_recorded: bool = Falsetool_spans: dict[str, Any] = field(default_factory=dict)+ # contextvars.Token per tool_call_id, returned by+ # ``cubepi.mcp._tracing.register_tool_span``. Passed back on+ # ``unregister_tool_span`` to restore the prior contextvar state.+ tool_span_tokens: dict[str, Any] = field(default_factory=dict)# Caller-supplied extra attrs for this run (set via run_scope, future).extra_attrs: dict[str, Any] = field(default_factory=dict)# Counts for invoke_agent attrs.@@ -208,32 +212,43 @@ class Recorder:provider.subscribe_response(self._on_provider_response))- async def _detach_async() -> None:+ def _sync_detach() -> None:+ """All synchronous cleanup: unsubscribe + sweep leaked+ registrations. Runs eagerly in ``detach()`` so the+ cancellation-leak cleanup is observable on the next line —+ not deferred to a loop tick that may never arrive if the+ caller immediately awaits ``tracer.shutdown()`` or exits+ ``asyncio.run`` (codex round-11).+ """unsub_agent()for d in provider_detachers:try:d()except Exception:pass+ # Final cleanup of any leaked tool-span registrations from+ # a cancelled run — CancelledError bypasses the agent's+ # ``except Exception`` handler so _on_agent_end /+ # _on_tool_exec_end never fire (codex round-10).+ self._sweep_tool_span_tokens(self._run)++ async def _detach_async() -> None:+ _sync_detach()await self._tracer.force_flush()def detach() -> None:- # Synchronous shim. Tests can also call ``detach_async``.- import asyncio-+ # Synchronous part runs immediately in either path so the+ # caller can rely on cleanup having happened by the time+ # ``detach()`` returns.+ _sync_detach()try:+ import asyncio+loop = asyncio.get_running_loop()except RuntimeError:- # No running loop — best-effort sync detach.- unsub_agent()- for d in provider_detachers:- try:- d()- except Exception:- pass- return- # Inside a loop — schedule the async detach.- loop.create_task(_detach_async())+ return # no loop — sync cleanup already done.+ # Inside a loop — schedule the remaining async flush.+ loop.create_task(self._tracer.force_flush())return detach@@ -270,7 +285,45 @@ class Recorder:# invoke_agent# ------------------------------------------------------------------+ def _sweep_tool_span_tokens(self, run: "_RunState | None") -> None:+ """Drain ``run.tool_span_tokens`` through ``unregister_tool_span``.++ The cubepi agent loop emits ``ToolExecutionEndEvent`` for every+ tool that produced a ``ToolExecutionStartEvent`` *only on the+ ``Exception`` path*. ``asyncio.CancelledError`` inherits from+ ``BaseException`` and bypasses that handler, so a run cancelled+ while an MCP tool was in flight leaves the registration alive+ in :mod:`cubepi.mcp._tracing._active_entries`. Repeated aborts+ would leak parent-span/provider pairs for the lifetime of the+ process.++ We sweep on agent_start (next run reuses this Recorder),+ agent_end (normal completion + agent-caught errors), and on+ detach (final safety net for an aborted run that never starts+ again). This is the cleanup path codex round-10 requested.+ """+ if run is None or not run.tool_span_tokens:+ return+ try:+ from cubepi.mcp import _tracing as _mcp_tracing+ except ImportError: # pragma: no cover — mcp module always present+ run.tool_span_tokens.clear()+ return+ for token in list(run.tool_span_tokens.values()):+ try:+ _mcp_tracing.unregister_tool_span(token)+ except Exception:+ pass+ run.tool_span_tokens.clear()+def _on_agent_start(self) -> None:+ # Defensive sweep: if a prior run was cancelled (CancelledError+ # inherits BaseException — cubepi's agent loop doesn't emit+ # ToolExecutionEndEvent in that path), its tool-span registrations+ # could still be live in cubepi.mcp._tracing. Clean before+ # opening the new _RunState.+ self._sweep_tool_span_tokens(self._run)+run_id = str(uuid.uuid4())# Open the root invoke_agent span. Caller-context propagation# (parent_trace_id / parent_span_id from a host service) lands@@ -324,6 +377,10 @@ class Recorder:GEN_AI_OUTPUT_MESSAGES,messages_to_semconv(run.output_messages),)+ # Final sweep for normal-end (and agent-caught error) paths.+ # Cancellation skips this hook entirely — see+ # ``_sweep_tool_span_tokens`` docstring.+ self._sweep_tool_span_tokens(run)run.agent_span.end()self._run = None@@ -439,6 +496,25 @@ class Recorder:attributes=attrs,)run.tool_spans[event.tool_call_id] = span+ # Expose this execute_tool span (and its owning provider) to+ # ``cubepi.mcp._tracing`` via a per-task contextvar so an MCP+ # tool call running inside the AgentTool body inherits the+ # right parent. Per-task scoping avoids the global-dict+ # collision when concurrent agents reuse the same tool_call_id+ # (e.g. Faux/OpenAI-style providers minting ``tc1`` per+ # conversation — codex round-8). The recorder stashes the+ # contextvar reset token on _RunState to undo on exec_end.+ try:+ from cubepi.mcp import _tracing as _mcp_tracing++ cv_token = _mcp_tracing.register_tool_span(+ event.tool_call_id,+ span,+ provider=self._tracer._provider,+ )+ run.tool_span_tokens[event.tool_call_id] = cv_token+ except ImportError: # pragma: no cover — mcp module always present+ passif self._record_content and event.args is not None:self._set_content_attr(span, GEN_AI_TOOL_CALL_ARGUMENTS, _coerce_dict(event.args)@@ -449,6 +525,13 @@ class Recorder:if run is None:returnspan = run.tool_spans.pop(event.tool_call_id, None)+ cv_token = run.tool_span_tokens.pop(event.tool_call_id, None)+ try:+ from cubepi.mcp import _tracing as _mcp_tracing++ _mcp_tracing.unregister_tool_span(cv_token)+ except ImportError: # pragma: no cover — mcp module always present+ passif span is None:returnspan.set_attribute(CUBEPI_TOOL_IS_ERROR, event.is_error)diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.pyindex 6839755..163f2a3 100644--- a/cubepi/tracing/tracer.py+++ b/cubepi/tracing/tracer.py@@ -135,6 +135,13 @@ class Tracer:installed by this attach, then calls :meth:`force_flush` toensure spans produced by the agent's runs are persisted beforethe caller proceeds.++ Also registers this Tracer's private TracerProvider with+ :mod:`cubepi.mcp._tracing` so MCP CLIENT spans flow through+ the same exporters — without this step, the MCP module falls+ back to the OTel global default (a no-op provider when the+ caller didn't separately call ``trace.set_tracer_provider``).+ The detach callable unregisters."""from cubepi.tracing.recorder import Recorder@@ -143,7 +150,30 @@ class Tracer:record_content=self._record_content,redact=self._redact,)- return recorder.attach(agent)+ recorder_detach = recorder.attach(agent)++ # Route MCP spans through this Tracer's provider. Capture the+ # token returned by register_provider so the detach below only+ # removes this attach's registration — multiple attaches of the+ # same Tracer to different agents must not clobber each other+ # (see codex round-6 review on PR #86).+ mcp_token: object | None = None+ try:+ from cubepi.mcp import _tracing as mcp_tracing++ mcp_token = mcp_tracing.register_provider(self._provider)+ except ImportError: # pragma: no cover — mcp module always present+ mcp_tracing = None++ def detach() -> None:+ recorder_detach()+ if mcp_tracing is not None and mcp_token is not None:+ try:+ mcp_tracing.unregister_provider(mcp_token)+ except Exception:+ pass++ return detachasync def force_flush(self, timeout_seconds: float = 30.0) -> bool:"""Block until all currently buffered spans are exported.diff --git a/tests/tracing/test_mcp_spans.py b/tests/tracing/test_mcp_spans.pynew file mode 100644index 0000000..801154e--- /dev/null+++ b/tests/tracing/test_mcp_spans.py@@ -0,0 +1,1043 @@+"""Phase 5: pin MCP CLIENT span emissions + W3C traceparent propagation.++The MCP adapter wraps every ``call_remote`` invocation in+:func:`cubepi.mcp._tracing.mcp_client_span`, which opens a CLIENT span+with the GenAI MCP semconv attributes. When the OTel API is absent the+context manager is a no-op (verified separately).+"""++from __future__ import annotations++import asyncio+from typing import Any++from opentelemetry import trace as _trace+from opentelemetry.sdk.resources import Resource+from opentelemetry.sdk.trace import ReadableSpan, TracerProvider+from opentelemetry.sdk.trace.export import (+ SimpleSpanProcessor,+ SpanExporter,+ SpanExportResult,+)+from opentelemetry.trace import SpanKind, StatusCode++from cubepi.mcp._adapter import make_mcp_agent_tool+++class _CaptureExporter(SpanExporter):+ def __init__(self) -> None:+ self.spans: list[ReadableSpan] = []++ def export(self, spans): # noqa: ANN001+ self.spans.extend(spans)+ return SpanExportResult.SUCCESS++ def shutdown(self) -> None:+ pass++ def force_flush(self, timeout_millis: int = 30_000) -> bool:+ return True+++def _make_provider() -> tuple[TracerProvider, _CaptureExporter]:+ """Build a fresh TracerProvider with an in-memory exporter.++ Each test gets its own provider; we don't use trace.set_tracer_provider+ globally, instead we monkeypatch the module-level ``_otel_trace`` in+ ``cubepi.mcp._tracing`` so MCP fetches the test's tracer.+ """+ resource = Resource.create({"service.name": "mcp-span-tests"})+ provider = TracerProvider(resource=resource)+ exporter = _CaptureExporter()+ provider.add_span_processor(SimpleSpanProcessor(exporter))+ return provider, exporter+++def _patch_mcp_trace(monkeypatch, provider: TracerProvider) -> None:+ """Swap the cubepi.mcp._tracing module's ``get_tracer`` to use ours."""+ import cubepi.mcp._tracing as mcp_tracing++ class _ShimTraceMod:+ @staticmethod+ def get_tracer(name: str): # noqa: D401+ return provider.get_tracer(name)++ @staticmethod+ def use_span(span, **kwargs):+ return _trace.use_span(span, **kwargs)++ @staticmethod+ def get_current_span():+ return _trace.get_current_span()++ @staticmethod+ def set_span_in_context(span, context=None):+ return _trace.set_span_in_context(span, context)++ monkeypatch.setattr(mcp_tracing, "_otel_trace", _ShimTraceMod)+ monkeypatch.setattr(mcp_tracing, "_OTEL_AVAILABLE", True)+ # Other tests' Tracer.attach() may have left entries on the provider+ # stack; clear so this test resolves via the shim above. The+ # current-tool contextvar is per-task and won't leak between tests+ # (pytest-asyncio runs each test in a fresh task), so no reset+ # needed there.+ monkeypatch.setattr(mcp_tracing, "_provider_stack", [])+++async def _make_tool(+ call_remote,+ *,+ server_address=None,+ server_port=None,+ protocol_version=None,+ session_id=None,+):+ """Build the MCP-adapted AgentTool. Mirrors what loaders produce."""+ return make_mcp_agent_tool(+ name="search",+ description="search the web",+ input_schema={"type": "object", "properties": {"q": {"type": "string"}}},+ call_remote=call_remote,+ server_address=server_address,+ server_port=server_port,+ protocol_version=protocol_version,+ session_id=session_id,+ )+++def _attrs(span: ReadableSpan) -> dict[str, Any]:+ return dict(span.attributes or {})+++class TestMCPClientSpan:+ async def test_span_emitted_with_required_attrs(self, monkeypatch):+ provider, exporter = _make_provider()+ _patch_mcp_trace(monkeypatch, provider)++ async def call_remote(name, args):+ return {"content": [{"type": "text", "text": "ok"}], "isError": False}++ tool = await _make_tool(+ call_remote,+ server_address="example.com",+ server_port=443,+ protocol_version="2025-11-25",+ session_id="sess-abc",+ )+ result = await tool.execute("tc1", tool.parameters.model_validate({"q": "x"}))+ assert result.is_error is None # success path++ # One MCP CLIENT span captured.+ mcp_spans = [s for s in exporter.spans if s.name.startswith("tools/call ")]+ assert len(mcp_spans) == 1+ span = mcp_spans[0]+ assert span.kind == SpanKind.CLIENT+ attrs = _attrs(span)+ assert attrs["mcp.method.name"] == "tools/call"+ assert attrs["gen_ai.tool.name"] == "search"+ assert attrs["gen_ai.operation.name"] == "execute_tool"+ assert attrs["mcp.session.id"] == "sess-abc"+ assert attrs["mcp.protocol.version"] == "2025-11-25"+ assert attrs["server.address"] == "example.com"+ assert attrs["server.port"] == 443++ async def test_span_records_exception_on_failure(self, monkeypatch):+ provider, exporter = _make_provider()+ _patch_mcp_trace(monkeypatch, provider)++ async def call_remote(name, args):+ raise RuntimeError("server unavailable")++ tool = await _make_tool(call_remote)+ try:+ await tool.execute("tc1", tool.parameters.model_validate({"q": "x"}))+ except RuntimeError:+ pass++ mcp_spans = [s for s in exporter.spans if s.name.startswith("tools/call ")]+ assert len(mcp_spans) == 1+ span = mcp_spans[0]+ assert span.status.status_code == StatusCode.ERROR+ attrs = _attrs(span)+ assert attrs["error.type"] == "RuntimeError"+ evnames = [e.name for e in span.events]+ assert "exception" in evnames++ async def test_exception_event_is_recorded_only_once(self, monkeypatch):+ """OTel's ``use_span`` defaults to record_exception=True; if we+ leave that on, the auto-recording on context exit and our own+ ``record_exception`` in the except branch both fire — duplicate+ exception events double-count errors at the backend.++ We disable auto-recording on ``use_span`` and own the+ recording. Pin: exactly one ``exception`` event per failure."""+ provider, exporter = _make_provider()+ _patch_mcp_trace(monkeypatch, provider)++ async def call_remote(name, args):+ raise RuntimeError("boom")++ tool = await _make_tool(call_remote)+ try:+ await tool.execute("tc1", tool.parameters.model_validate({"q": "x"}))+ except RuntimeError:+ pass++ mcp_spans = [s for s in exporter.spans if s.name.startswith("tools/call ")]+ assert len(mcp_spans) == 1+ exception_events = [e for e in mcp_spans[0].events if e.name == "exception"]+ assert len(exception_events) == 1, (+ f"expected exactly 1 exception event; got {len(exception_events)}"+ )++ async def test_span_records_cancellation(self, monkeypatch):+ """Cancellation is a control signal, not a failure — match the+ chat / turn / invoke_agent convention: leave Status UNSET,+ record cubepi.aborted=true + error.type, do NOT add an+ ``exception`` event."""+ provider, exporter = _make_provider()+ _patch_mcp_trace(monkeypatch, provider)++ async def call_remote(name, args):+ raise asyncio.CancelledError()++ tool = await _make_tool(call_remote)+ try:+ await tool.execute("tc1", tool.parameters.model_validate({"q": "x"}))+ except asyncio.CancelledError:+ pass++ mcp_spans = [s for s in exporter.spans if s.name.startswith("tools/call ")]+ assert len(mcp_spans) == 1+ span = mcp_spans[0]+ attrs = _attrs(span)+ assert attrs["error.type"] == "cubepi.aborted"+ assert attrs["cubepi.aborted"] is True+ # Status stays UNSET; cancel is not a failure.+ assert span.status.status_code == StatusCode.UNSET+ # No exception event — cancel is signaled via cubepi.aborted only.+ assert not any(e.name == "exception" for e in span.events)+++class TestMCPIsErrorResponse:+ """When an MCP server returns ``isError: true``, the CLIENT span+ must reflect the protocol-level failure — codex round 4."""++ async def test_iserror_response_marks_span_error(self, monkeypatch):+ provider, exporter = _make_provider()+ _patch_mcp_trace(monkeypatch, provider)++ async def call_remote(name, args):+ return {+ "content": [{"type": "text", "text": "tool failed"}],+ "isError": True,+ }++ tool = await _make_tool(call_remote)+ result = await tool.execute("tc1", tool.parameters.model_validate({"q": "x"}))+ # Adapter still surfaces is_error on the AgentToolResult.+ assert result.is_error is True++ mcp_spans = [s for s in exporter.spans if s.name.startswith("tools/call ")]+ assert len(mcp_spans) == 1+ span = mcp_spans[0]+ assert span.status.status_code == StatusCode.ERROR+ attrs = _attrs(span)+ assert attrs["error.type"] == "mcp.is_error"++ async def test_iserror_false_keeps_span_unset(self, monkeypatch):+ provider, exporter = _make_provider()+ _patch_mcp_trace(monkeypatch, provider)++ async def call_remote(name, args):+ return {+ "content": [{"type": "text", "text": "ok"}],+ "isError": False,+ }++ tool = await _make_tool(call_remote)+ await tool.execute("tc1", tool.parameters.model_validate({"q": "x"}))++ mcp_spans = [s for s in exporter.spans if s.name.startswith("tools/call ")]+ assert len(mcp_spans) == 1+ span = mcp_spans[0]+ assert span.status.status_code == StatusCode.UNSET+ assert "error.type" not in _attrs(span)+++class TestNoOpWhenOTelMissing:+ async def test_context_manager_yields_none_when_no_otel(self, monkeypatch):+ import cubepi.mcp._tracing as mcp_tracing++ monkeypatch.setattr(mcp_tracing, "_OTEL_AVAILABLE", False)++ async def call_remote(name, args):+ return {"content": [], "isError": False}++ tool = await _make_tool(call_remote)+ # Must run without errors and without emitting any spans.+ await tool.execute("tc1", tool.parameters.model_validate({"q": "x"}))+++class TestTraceparentHelper:+ async def test_current_traceparent_returns_w3c_string_when_in_span(+ self, monkeypatch+ ):+ provider, _ = _make_provider()+ _patch_mcp_trace(monkeypatch, provider)+ from cubepi.mcp._tracing import current_traceparent++ tracer = provider.get_tracer("test")+ with tracer.start_as_current_span("test-span"):+ tp = current_traceparent()+ assert tp is not None+ # Format: 00-<32hex>-<16hex>-<flags>+ parts = tp.split("-")+ assert len(parts) == 4+ assert parts[0] == "00"+ assert len(parts[1]) == 32+ assert len(parts[2]) == 16+ assert len(parts[3]) == 2++ async def test_current_traceparent_none_without_span(self, monkeypatch):+ from cubepi.mcp._tracing import current_traceparent++ # No active span (and no recording context set up).+ assert current_traceparent() is None+++class TestTraceparentInjection:+ """The HTTP loader must inject ``traceparent`` into outbound+ session headers whenever the MCP CLIENT span is active so that+ instrumented MCP servers can continue the trace (codex round 2)."""++ async def test_traceparent_header_set_inside_mcp_span(self, monkeypatch):+ from cubepi.mcp import _tracing as mcp_tracing+ from cubepi.mcp._tracing import mcp_client_span++ # Force OTel on with a deterministic tracer.+ provider, _exporter = _make_provider()+ _patch_mcp_trace(monkeypatch, provider)++ # Reproduce the http_loader.call_remote injection logic.+ seen_headers: list[dict] = []++ base_headers = {"x-test": "yes"}++ async def fake_call_remote():+ # Mirrors http_loader._call_remote header-merge logic.+ tp = mcp_tracing.current_traceparent()+ call_headers = base_headers+ if tp is not None:+ call_headers = {**base_headers, "traceparent": tp}+ seen_headers.append(call_headers)++ async with mcp_client_span(method="tools/call", tool_name="search"):+ await fake_call_remote()++ assert len(seen_headers) == 1+ assert seen_headers[0]["x-test"] == "yes" # caller headers preserved+ assert "traceparent" in seen_headers[0]+ # Format: 00-<32hex>-<16hex>-<flags>+ tp = seen_headers[0]["traceparent"]+ assert tp.startswith("00-") and len(tp.split("-")) == 4++ async def test_no_header_added_when_no_active_span(self, monkeypatch):+ from cubepi.mcp._tracing import current_traceparent++ # Outside any span: helper returns None and loader must not add+ # a traceparent header.+ assert current_traceparent() is None+++class TestTracerProviderRouting:+ """When a user constructs a cubepi.tracing.Tracer with its own+ private provider and calls attach(agent), MCP CLIENT spans must+ flow through that same provider's exporters — without this, MCP+ spans would silently land in the OTel global no-op provider+ (codex round 5)."""++ async def test_mcp_span_lands_in_tracer_exporter(self):+ from cubepi.agent.agent import Agent+ from cubepi.providers.base import Model, ToolCall+ from cubepi.providers.faux import (+ FauxProvider,+ faux_assistant_message,+ )+ from cubepi.tracing import Tracer++ from pydantic import BaseModel++ # Capture exporter shared by the cubepi Tracer.+ exporter = _CaptureExporter()++ # Build an MCP-backed tool whose call_remote we can drive.+ class P(BaseModel):+ q: str = ""++ async def call_remote(name, args):+ return {"content": [{"type": "text", "text": "ok"}], "isError": False}++ from cubepi.mcp._adapter import make_mcp_agent_tool++ mcp_tool = make_mcp_agent_tool(+ name="search",+ description="search",+ input_schema={"type": "object", "properties": {"q": {"type": "string"}}},+ call_remote=call_remote,+ server_address="api.example.com",+ protocol_version="2025-11-25",+ )++ provider = FauxProvider()+ provider.append_responses(+ [+ faux_assistant_message(+ [ToolCall(id="tc1", name="search", arguments={"q": "x"})],+ stop_reason="tool_use",+ ),+ faux_assistant_message("done"),+ ]+ )+ agent = Agent(+ provider=provider,+ model=Model(id="faux-1", provider="faux"),+ system_prompt="s",+ tools=[mcp_tool],+ )++ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])+ detach = tracer.attach(agent)++ try:+ await agent.prompt("go")+ await agent.wait_for_idle()+ finally:+ detach()+ await tracer.shutdown()++ # Exactly one MCP tools/call CLIENT span landed in the Tracer's+ # exporter — proving the routing worked.+ mcp_spans = [s for s in exporter.spans if s.name.startswith("tools/call ")]+ assert len(mcp_spans) == 1+ attrs = dict(mcp_spans[0].attributes or {})+ assert attrs["mcp.method.name"] == "tools/call"+ assert attrs["gen_ai.tool.name"] == "search"++ # The CLIENT span must be a child of the recorder's+ # execute_tool span (same trace_id, parent_span_id set), not an+ # orphan root trace (codex round-6 review on PR #86).+ client_span = mcp_spans[0]+ execute_spans = [+ s for s in exporter.spans if s.name.startswith("execute_tool ")+ ]+ assert len(execute_spans) == 1+ tool_ctx = execute_spans[0].get_span_context()+ client_ctx = client_span.get_span_context()+ assert client_ctx.trace_id == tool_ctx.trace_id+ assert client_span.parent is not None+ assert client_span.parent.span_id == tool_ctx.span_id++ async def test_two_attaches_detach_one_keeps_other_routing(self):+ """When a Tracer is attached to two agents and one is detached,+ the remaining agent's MCP spans must still land in the Tracer's+ exporter. Refcounted register/unregister is the contract+ (codex round-6 review on PR #86)."""+ from cubepi.agent.agent import Agent+ from cubepi.providers.base import Model, ToolCall+ from cubepi.providers.faux import FauxProvider, faux_assistant_message+ from cubepi.tracing import Tracer++ exporter = _CaptureExporter()++ async def call_remote(name, args):+ return {"content": [{"type": "text", "text": "ok"}], "isError": False}++ from cubepi.mcp._adapter import make_mcp_agent_tool++ def _make_agent():+ mcp_tool = make_mcp_agent_tool(+ name="search",+ description="search",+ input_schema={+ "type": "object",+ "properties": {"q": {"type": "string"}},+ },+ call_remote=call_remote,+ )+ provider_a = FauxProvider()+ provider_a.append_responses(+ [+ faux_assistant_message(+ [ToolCall(id="tc1", name="search", arguments={"q": "x"})],+ stop_reason="tool_use",+ ),+ faux_assistant_message("done"),+ ]+ )+ return Agent(+ provider=provider_a,+ model=Model(id="faux-1", provider="faux"),+ system_prompt="s",+ tools=[mcp_tool],+ )++ agent_a = _make_agent()+ agent_b = _make_agent()++ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])+ detach_a = tracer.attach(agent_a)+ detach_b = tracer.attach(agent_b)++ try:+ # Detach the first attachment; agent_b's runs must still+ # route MCP spans through the Tracer's exporter.+ detach_a()++ await agent_b.prompt("go")+ await agent_b.wait_for_idle()+ finally:+ detach_b()+ await tracer.shutdown()++ mcp_spans = [s for s in exporter.spans if s.name.startswith("tools/call ")]+ assert len(mcp_spans) == 1, (+ "MCP routing for the still-attached agent broke when the "+ "other agent's detach was called"+ )++ def test_register_and_unregister_provider(self, monkeypatch):+ from cubepi.mcp import _tracing as mcp_tracing++ # Start from a clean stack so the assertion below is well-defined+ # regardless of other tests' attach()/detach() side-effects.+ monkeypatch.setattr(mcp_tracing, "_provider_stack", [])++ sentinel = object()+ token = mcp_tracing.register_provider(sentinel)+ try:+ assert mcp_tracing._provider_stack[-1][1] is sentinel+ finally:+ mcp_tracing.unregister_provider(token)+ assert mcp_tracing._provider_stack == []++ def test_unregister_only_removes_own_token(self, monkeypatch):+ """Two providers registered in sequence; detaching the first+ must leave the second's registration intact so MCP spans+ continue flowing through it. Without this, a Tracer attached to+ agent A and B then detached from A would drop MCP routing for B+ (codex round-6 review on PR #86)."""+ from cubepi.mcp import _tracing as mcp_tracing++ monkeypatch.setattr(mcp_tracing, "_provider_stack", [])++ first = object()+ second = object()+ t1 = mcp_tracing.register_provider(first)+ t2 = mcp_tracing.register_provider(second)+ try:+ # Detach the first registration; the second must remain+ # routable. The most-recently-pushed provider wins on lookup.+ mcp_tracing.unregister_provider(t1)+ assert len(mcp_tracing._provider_stack) == 1+ assert mcp_tracing._provider_stack[-1][1] is second+ finally:+ mcp_tracing.unregister_provider(t2)+ assert mcp_tracing._provider_stack == []+++class TestMCPSpanParentage:+ """Phase 5 round 6: the MCP CLIENT span must nest under the+ cubepi recorder's ``execute_tool`` span, not start an orphan root+ trace. The recorder publishes its execute_tool span by tool_call_id;+ the adapter passes the id through to ``mcp_client_span`` which uses+ it as the explicit parent context."""++ async def test_mcp_span_parented_to_registered_tool_span(self, monkeypatch):+ provider, exporter = _make_provider()+ _patch_mcp_trace(monkeypatch, provider)++ # Open a synthetic "execute_tool" span and register it as the+ # parent for tool_call_id "tc1" — the same hook the cubepi+ # recorder uses.+ from cubepi.mcp import _tracing as mcp_tracing++ tracer = provider.get_tracer("test")+ tool_span = tracer.start_span("execute_tool search")+ token = mcp_tracing.register_tool_span("tc1", tool_span)+ try:++ async def call_remote(name, args):+ return {"content": [], "isError": False}++ tool = await _make_tool(call_remote)+ await tool.execute("tc1", tool.parameters.model_validate({"q": "x"}))+ finally:+ mcp_tracing.unregister_tool_span(token)+ tool_span.end()++ mcp_spans = [s for s in exporter.spans if s.name.startswith("tools/call ")]+ assert len(mcp_spans) == 1+ client_span = mcp_spans[0]+ tool_ctx = tool_span.get_span_context()+ client_ctx = client_span.get_span_context()+ # Same trace_id, parent points at the execute_tool span.+ assert client_ctx.trace_id == tool_ctx.trace_id+ assert client_span.parent is not None+ assert client_span.parent.span_id == tool_ctx.span_id++ async def test_two_tracers_route_mcp_by_parent_owner(self):+ """Two different cubepi.Tracer instances attached to two agents+ in the same process. An MCP CLIENT span emitted under agent A's+ execute_tool span must export through Tracer A's exporter — not+ Tracer B's, even if B was attached more recently (LIFO order on+ the provider stack).++ Without this routing, agent A's trace would be missing its MCP+ leg and Tracer B's exporter would receive a stray span with+ agent A's trace_id (codex round-7 review on PR #86)."""+ from cubepi.agent.agent import Agent+ from cubepi.providers.base import Model, ToolCall+ from cubepi.providers.faux import FauxProvider, faux_assistant_message+ from cubepi.tracing import Tracer++ from cubepi.mcp._adapter import make_mcp_agent_tool++ async def call_remote(name, args):+ return {"content": [{"type": "text", "text": "ok"}], "isError": False}++ def _make_agent():+ mcp_tool = make_mcp_agent_tool(+ name="search",+ description="search",+ input_schema={+ "type": "object",+ "properties": {"q": {"type": "string"}},+ },+ call_remote=call_remote,+ )+ provider = FauxProvider()+ provider.append_responses(+ [+ faux_assistant_message(+ [ToolCall(id="tc1", name="search", arguments={"q": "x"})],+ stop_reason="tool_use",+ ),+ faux_assistant_message("done"),+ ]+ )+ return Agent(+ provider=provider,+ model=Model(id="faux-1", provider="faux"),+ system_prompt="s",+ tools=[mcp_tool],+ )++ exporter_a = _CaptureExporter()+ exporter_b = _CaptureExporter()++ agent_a = _make_agent()+ agent_b = _make_agent()++ tracer_a = Tracer(service_name="a", agent_name="a", exporters=[exporter_a])+ tracer_b = Tracer(service_name="b", agent_name="b", exporters=[exporter_b])++ # Attach A first then B so B is at the top of the LIFO stack.+ # The buggy implementation would route both agents' MCP spans+ # through B; we want A's spans in A's exporter and B's in B's.+ detach_a = tracer_a.attach(agent_a)+ detach_b = tracer_b.attach(agent_b)++ try:+ await agent_a.prompt("go")+ await agent_a.wait_for_idle()+ await agent_b.prompt("go")+ await agent_b.wait_for_idle()+ finally:+ detach_a()+ detach_b()+ await tracer_a.shutdown()+ await tracer_b.shutdown()++ # Each exporter saw exactly one tools/call CLIENT span — its+ # own agent's — with matching trace_id.+ mcp_a = [s for s in exporter_a.spans if s.name.startswith("tools/call ")]+ mcp_b = [s for s in exporter_b.spans if s.name.startswith("tools/call ")]+ assert len(mcp_a) == 1, "agent_a's MCP span did not land in tracer_a"+ assert len(mcp_b) == 1, "agent_b's MCP span did not land in tracer_b"++ # Cross-check trace_id consistency: each exporter's MCP span+ # shares trace_id with that exporter's execute_tool span (i.e.,+ # parent and child went to the same backend together).+ for exporter in (exporter_a, exporter_b):+ execute = [s for s in exporter.spans if s.name.startswith("execute_tool ")]+ mcp = [s for s in exporter.spans if s.name.startswith("tools/call ")]+ assert len(execute) == 1 and len(mcp) == 1+ assert (+ execute[0].get_span_context().trace_id+ == mcp[0].get_span_context().trace_id+ )++ async def test_concurrent_agents_with_colliding_tool_call_ids(self):+ """Two agents executing MCP tools concurrently with the SAME+ tool_call_id (``tc1``, mimicking how Faux/OpenAI-style providers+ mint ids per conversation). A global dict keyed by tool_call_id+ would let the second registration overwrite the first; the MCP+ span lookup could then parent/export agent A's CLIENT span+ through agent B's owning provider, reintroducing the cross-+ Tracer misrouting that the sequential test does not cover.++ ContextVars scope per asyncio task, so each agent's run sees+ only its own parent (codex round-8 review on PR #86)."""+ import asyncio as _asyncio++ from cubepi.agent.agent import Agent+ from cubepi.mcp._adapter import make_mcp_agent_tool+ from cubepi.providers.base import Model, ToolCall+ from cubepi.providers.faux import FauxProvider, faux_assistant_message+ from cubepi.tracing import Tracer++ # Gate that holds both agents' MCP calls inside the+ # ``execute_tool`` span at the same time, so any global-dict+ # collision would be exercised. Without the gate the calls+ # would serialize trivially.+ in_call = _asyncio.Event()+ release = _asyncio.Event()++ async def call_remote(name, args):+ in_call.set()+ await release.wait()+ return {"content": [{"type": "text", "text": "ok"}], "isError": False}++ def _make_agent():+ mcp_tool = make_mcp_agent_tool(+ name="search",+ description="search",+ input_schema={+ "type": "object",+ "properties": {"q": {"type": "string"}},+ },+ call_remote=call_remote,+ )+ prov = FauxProvider()+ prov.append_responses(+ [+ faux_assistant_message(+ [ToolCall(id="tc1", name="search", arguments={"q": "x"})],+ stop_reason="tool_use",+ ),+ faux_assistant_message("done"),+ ]+ )+ return Agent(+ provider=prov,+ model=Model(id="faux-1", provider="faux"),+ system_prompt="s",+ tools=[mcp_tool],+ )++ exporter_a = _CaptureExporter()+ exporter_b = _CaptureExporter()+ agent_a = _make_agent()+ agent_b = _make_agent()+ tracer_a = Tracer(service_name="a", agent_name="a", exporters=[exporter_a])+ tracer_b = Tracer(service_name="b", agent_name="b", exporters=[exporter_b])+ detach_a = tracer_a.attach(agent_a)+ detach_b = tracer_b.attach(agent_b)++ async def _run(agent):+ await agent.prompt("go")+ await agent.wait_for_idle()++ try:+ task_a = _asyncio.create_task(_run(agent_a))+ task_b = _asyncio.create_task(_run(agent_b))++ # Both agents have entered their MCP call_remote.+ await in_call.wait()+ in_call.clear()+ # Give the second one a moment to also enter; the gate keeps+ # it parked there.+ await _asyncio.sleep(0.05)+ release.set()+ await _asyncio.gather(task_a, task_b)+ finally:+ detach_a()+ detach_b()+ await tracer_a.shutdown()+ await tracer_b.shutdown()++ for exporter, who in ((exporter_a, "a"), (exporter_b, "b")):+ execute = [s for s in exporter.spans if s.name.startswith("execute_tool ")]+ mcp = [s for s in exporter.spans if s.name.startswith("tools/call ")]+ assert len(execute) == 1, f"agent_{who}: execute_tool count"+ assert len(mcp) == 1, f"agent_{who}: tools/call count"+ assert (+ execute[0].get_span_context().trace_id+ == mcp[0].get_span_context().trace_id+ ), f"agent_{who}: MCP span landed in wrong trace"+ assert mcp[0].parent is not None+ assert mcp[0].parent.span_id == execute[0].get_span_context().span_id, (+ f"agent_{who}: MCP span parented to the wrong execute_tool"+ )++ async def test_parallel_tool_mode_parents_mcp_span(self):+ """In ``parallel`` tool execution, the cubepi agent loop emits+ ``ToolExecutionStartEvent`` in the parent task and+ ``ToolExecutionEndEvent`` from the per-tool *child* task it+ spawns. A naive ``ContextVar.reset(token)`` would raise+ ``ValueError`` in the child task because the Token was minted+ in a different context. The dict+contextvar hybrid keeps the+ registry valid until the child task's cleanup runs — pin that+ an MCP CLIENT span is still correctly parented under+ ``execute_tool`` in this mode (codex round-9 review)."""+ from cubepi.agent.agent import Agent+ from cubepi.agent.types import AgentTool+ from cubepi.mcp._adapter import make_mcp_agent_tool+ from cubepi.providers.base import Model, ToolCall+ from cubepi.providers.faux import FauxProvider, faux_assistant_message+ from cubepi.tracing import Tracer++ async def call_remote(name, args):+ return {"content": [{"type": "text", "text": "ok"}], "isError": False}++ # Build the MCP tool with execution_mode="parallel" so the+ # agent's _execute_parallel path is taken.+ base_tool = make_mcp_agent_tool(+ name="search",+ description="search",+ input_schema={+ "type": "object",+ "properties": {"q": {"type": "string"}},+ },+ call_remote=call_remote,+ )+ mcp_tool = AgentTool(+ name=base_tool.name,+ description=base_tool.description,+ parameters=base_tool.parameters,+ execute=base_tool.execute,+ execution_mode="parallel",+ )++ provider = FauxProvider()+ provider.append_responses(+ [+ faux_assistant_message(+ [ToolCall(id="tc1", name="search", arguments={"q": "x"})],+ stop_reason="tool_use",+ ),+ faux_assistant_message("done"),+ ]+ )+ agent = Agent(+ provider=provider,+ model=Model(id="faux-1", provider="faux"),+ system_prompt="s",+ tools=[mcp_tool],+ )++ exporter = _CaptureExporter()+ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])+ detach = tracer.attach(agent)+ try:+ await agent.prompt("go")+ await agent.wait_for_idle()+ finally:+ detach()+ await tracer.shutdown()++ execute = [s for s in exporter.spans if s.name.startswith("execute_tool ")]+ mcp = [s for s in exporter.spans if s.name.startswith("tools/call ")]+ assert len(execute) == 1+ assert len(mcp) == 1+ assert (+ mcp[0].get_span_context().trace_id == execute[0].get_span_context().trace_id+ )+ assert mcp[0].parent is not None+ assert mcp[0].parent.span_id == execute[0].get_span_context().span_id++ async def test_cancellation_does_not_leak_tool_registrations(self):+ """``asyncio.CancelledError`` inherits ``BaseException`` and+ bypasses the cubepi agent loop's ``except Exception`` handler,+ so a cancelled run never emits ``ToolExecutionEndEvent`` and+ never reaches the per-event unregister. Without an explicit+ cleanup path, ``_active_entries`` in ``cubepi.mcp._tracing``+ would grow unbounded across aborted runs (codex round-10).++ Pin: after a cancelled run + detach, ``_active_entries`` is+ back to its pre-run size."""+ import asyncio as _asyncio++ from cubepi.agent.agent import Agent+ from cubepi.mcp import _tracing as mcp_tracing+ from cubepi.mcp._adapter import make_mcp_agent_tool+ from cubepi.providers.base import Model, ToolCall+ from cubepi.providers.faux import FauxProvider, faux_assistant_message+ from cubepi.tracing import Tracer++ baseline = len(mcp_tracing._active_entries)++ # Gate the MCP call so we can cancel mid-flight, simulating+ # the real "agent run cancelled while a tool is awaiting" path.+ in_call = _asyncio.Event()+ never = _asyncio.Event()++ async def call_remote(name, args):+ in_call.set()+ await never.wait() # cancellation lands here+ return {"content": [], "isError": False}++ mcp_tool = make_mcp_agent_tool(+ name="search",+ description="search",+ input_schema={+ "type": "object",+ "properties": {"q": {"type": "string"}},+ },+ call_remote=call_remote,+ )++ provider = FauxProvider()+ provider.append_responses(+ [+ faux_assistant_message(+ [ToolCall(id="tc1", name="search", arguments={"q": "x"})],+ stop_reason="tool_use",+ ),+ faux_assistant_message("done"),+ ]+ )+ agent = Agent(+ provider=provider,+ model=Model(id="faux-1", provider="faux"),+ system_prompt="s",+ tools=[mcp_tool],+ )++ exporter = _CaptureExporter()+ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])+ detach = tracer.attach(agent)++ try:+ run_task = _asyncio.create_task(agent.prompt("go"))+ await in_call.wait()+ # During registration_active = baseline + 1.+ assert len(mcp_tracing._active_entries) == baseline + 1, (+ "expected exactly one active MCP tool registration mid-run"+ )+ run_task.cancel()+ try:+ await run_task+ except _asyncio.CancelledError:+ pass+ # Drain any post-cancel events; agent doesn't emit on cancel+ # but wait_for_idle is harmless.+ try:+ await _asyncio.wait_for(agent.wait_for_idle(), timeout=1.0)+ except (_asyncio.TimeoutError, _asyncio.CancelledError):+ pass+ finally:+ detach()+ # ``detach()`` runs the synchronous sweep eagerly — the+ # registration must already be gone before we even reach+ # ``tracer.shutdown()`` (codex round-11). Asserting *before*+ # shutdown pins that contract; the post-shutdown assertion+ # below is a belt-and-braces check.+ assert len(mcp_tracing._active_entries) == baseline, (+ "detach() did not synchronously sweep the cancelled "+ "tool's registration; cleanup was deferred to a loop "+ "tick that may not run before tracer.shutdown()"+ )+ await tracer.shutdown()++ assert len(mcp_tracing._active_entries) == baseline++ async def test_unregister_cleans_dict_even_from_different_task(self):+ """Direct contract test for the dict+contextvar hybrid:+ ``register_tool_span`` in one task, ``unregister_tool_span`` in+ a different task. The ``ContextVar.reset`` raises and is+ swallowed; the dict entry must still be cleaned up so any+ subsequent lookup via a stale contextvar returns ``None``+ (codex round-9 review)."""+ import asyncio as _asyncio++ from cubepi.mcp import _tracing as mcp_tracing++ # Build a parent task that registers, then a child task that+ # unregisters. We assert the dict is empty after cleanup.+ registered_count_before = len(mcp_tracing._active_entries)++ token_holder: list = []++ async def _register():+ token = mcp_tracing.register_tool_span("tc1", "span-A", provider="prov-A")+ token_holder.append(token)+ # Don't unregister here — let the child task do it.++ async def _unregister(token):+ mcp_tracing.unregister_tool_span(token)++ await _register()+ # Confirm the dict gained one entry.+ assert len(mcp_tracing._active_entries) == registered_count_before + 1++ # Unregister from a different task; ContextVar.reset will+ # ValueError but the dict cleanup must still happen.+ await _asyncio.create_task(_unregister(token_holder[0]))+ assert len(mcp_tracing._active_entries) == registered_count_before, (+ "_active_entries leaked after cross-task unregister_tool_span"+ )++ async def test_mcp_span_orphan_when_no_registered_parent(self, monkeypatch):+ """Without a registered parent, the MCP span starts a new+ root trace. Pinning this so the parented-path test above is+ meaningful (i.e., parenting only kicks in when we ask for it)."""+ provider, exporter = _make_provider()+ _patch_mcp_trace(monkeypatch, provider)++ async def call_remote(name, args):+ return {"content": [], "isError": False}++ tool = await _make_tool(call_remote)+ await tool.execute("no-parent-tc", tool.parameters.model_validate({"q": "x"}))++ mcp_spans = [s for s in exporter.spans if s.name.startswith("tools/call ")]+ assert len(mcp_spans) == 1+ assert mcp_spans[0].parent is None+++class TestLoaderHelpers:+ def test_split_address_parses_url(self):+ from cubepi.mcp.http_loader import _split_address++ assert _split_address("https://api.example.com:8443/mcp") == (+ "api.example.com",+ 8443,+ )+ host, port = _split_address("http://localhost/mcp")+ assert host == "localhost"+ assert port is None++ def test_split_address_on_empty(self):+ from cubepi.mcp.http_loader import _split_address++ # urlparse("") returns hostname=None, port=None — both nones is+ # the documented signal that the helper couldn't extract values.+ host, port = _split_address("")+ assert host is None+ assert port is None++ def test_extract_protocol_version(self):+ from cubepi.mcp.http_loader import _extract_protocol_version++ class FakeInit:+ protocolVersion = "2025-11-25"++ assert _extract_protocol_version(FakeInit()) == "2025-11-25"+ assert _extract_protocol_version(object()) is None++ class FakeBadInit:+ protocolVersion = 123 # not a string++ assert _extract_protocol_version(FakeBadInit()) is None