struct-sdk 0.5.28__tar.gz → 0.5.29__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/PKG-INFO +2 -1
  2. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/pyproject.toml +4 -1
  3. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_auto.py +7 -7
  4. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_observations/health.py +2 -2
  5. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_operation_details.py +4 -7
  6. struct_sdk-0.5.29/src/struct_sdk/_otel_logs.py +52 -0
  7. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/core.py +46 -18
  8. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/mcp.py +43 -23
  9. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/.gitignore +0 -0
  10. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/LICENSE +0 -0
  11. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/PYPI.md +0 -0
  12. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/README.md +0 -0
  13. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/__init__.py +0 -0
  14. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_container.py +0 -0
  15. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_distro.py +0 -0
  16. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_event_loop.py +0 -0
  17. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_fork_safe_http.py +0 -0
  18. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_genai_content.py +0 -0
  19. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_metrics.py +0 -0
  20. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_observations/__init__.py +0 -0
  21. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_observations/config.py +0 -0
  22. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_observations/identity.py +0 -0
  23. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_observations/native_events.py +0 -0
  24. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_observations/outputs.py +0 -0
  25. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_observations/poller.py +0 -0
  26. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_observations/routing.py +0 -0
  27. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_observations/runtime.py +0 -0
  28. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_observations/self_metrics.py +0 -0
  29. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_observations/uwsgi.py +0 -0
  30. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/_pool.py +0 -0
  31. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/ag2.py +0 -0
  32. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/anthropic.py +0 -0
  33. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/autogen.py +0 -0
  34. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/claude_agent.py +0 -0
  35. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/crewai.py +0 -0
  36. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/gcp.py +0 -0
  37. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/google_genai.py +0 -0
  38. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/langchain.py +0 -0
  39. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/litellm.py +0 -0
  40. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/llamaindex.py +0 -0
  41. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/openai.py +0 -0
  42. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/openai_agents.py +0 -0
  43. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/pydantic_ai.py +0 -0
  44. {struct_sdk-0.5.28 → struct_sdk-0.5.29}/src/struct_sdk/temporal.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: struct-sdk
3
- Version: 0.5.28
3
+ Version: 0.5.29
4
4
  Summary: Python SDK for OTel auto-instrumentation and live instrumentation on Struct.
5
5
  Project-URL: Homepage, https://struct.ai
6
6
  Project-URL: Documentation, https://docs.struct.ai/observability/instrumentation/python
@@ -24,6 +24,7 @@ Classifier: Topic :: System :: Monitoring
24
24
  Requires-Python: >=3.10
25
25
  Requires-Dist: opentelemetry-api>=1.45.1
26
26
  Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27.0
27
+ Requires-Dist: opentelemetry-instrumentation-logging>=0.66b1
27
28
  Requires-Dist: opentelemetry-sdk>=1.27.0
28
29
  Requires-Dist: struct-sdk-native==0.2.1
29
30
  Requires-Dist: wrapt>=1.17.3
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "struct-sdk"
7
- version = "0.5.28"
7
+ version = "0.5.29"
8
8
  description = "Python SDK for OTel auto-instrumentation and live instrumentation on Struct."
9
9
  readme = "PYPI.md"
10
10
  requires-python = ">=3.10"
@@ -29,6 +29,9 @@ dependencies = [
29
29
  "opentelemetry-api>=1.45.1",
30
30
  "opentelemetry-sdk>=1.27.0",
31
31
  "opentelemetry-exporter-otlp-proto-http>=1.27.0",
32
+ # The app-log bridge's handler. OpenTelemetry 1.46.0 removed the SDK's own;
33
+ # 0.66b1 is the first release paired with API 1.45.1.
34
+ "opentelemetry-instrumentation-logging>=0.66b1",
32
35
  # Stream proxies (struct_sdk.openai): isinstance-transparent, as in
33
36
  # OpenLLMetry and ddtrace. Already required by every OTel instrumentor.
34
37
  # 1.17.3 is the first release with CPython 3.14 wheels.
@@ -34,14 +34,14 @@ from dataclasses import dataclass, field
34
34
  from importlib.metadata import PackageNotFoundError, entry_points, version
35
35
  from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional
36
36
 
37
- from opentelemetry import _logs, context, metrics, trace
37
+ from opentelemetry import context, metrics, trace
38
38
  from opentelemetry.context import _SUPPRESS_INSTRUMENTATION_KEY, Context
39
39
  from opentelemetry.propagators.textmap import TextMapPropagator
40
- from opentelemetry.sdk._logs import LoggerProvider, LogRecordProcessor
41
40
  from opentelemetry.sdk.metrics import MeterProvider
42
41
  from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
43
42
 
44
- from struct_sdk import _metrics
43
+ from struct_sdk import _metrics, _otel_logs
44
+ from struct_sdk._otel_logs import LoggerProvider, LogRecordProcessor
45
45
  from struct_sdk.core import (
46
46
  _body_value,
47
47
  _contain_logged,
@@ -272,7 +272,7 @@ def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
272
272
 
273
273
  host_tracer_provider = trace.get_tracer_provider()
274
274
  host_meter_provider = metrics.get_meter_provider()
275
- host_logger_provider = _logs.get_logger_provider()
275
+ host_logger_provider = _otel_logs.api.get_logger_provider()
276
276
  options = _with_env_disabled(options)
277
277
  owns_traces = isinstance(host_tracer_provider, trace.ProxyTracerProvider)
278
278
  no_host = owns_traces and _is_unset(host_meter_provider) and _is_unset(host_logger_provider)
@@ -312,7 +312,7 @@ def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
312
312
  sdk._meter_provider = meter_provider
313
313
  metrics.set_meter_provider(meter_provider)
314
314
  if owns_logs:
315
- _logs.set_logger_provider(logger_provider)
315
+ _otel_logs.api.set_logger_provider(logger_provider)
316
316
 
317
317
  if _enabled(options, METRICS):
318
318
  def attach_metrics() -> None:
@@ -928,8 +928,8 @@ class _ExportPathFilteringLogProcessor(LogRecordProcessor):
928
928
  if not self._skip(log_data):
929
929
  _safe(lambda: self._inner.emit(log_data), site="auto.host_logs.emit") # type: ignore[attr-defined] # ty: ignore[missing-attribute]
930
930
 
931
- def shutdown(self) -> None:
932
- _shut_down_within(self._inner, self._budget_seconds)
931
+ def shutdown(self, timeout_millis: float = 30_000, **_kwargs: Any) -> None:
932
+ _shut_down_within(self._inner, min(self._budget_seconds, max(0, timeout_millis) / 1000))
933
933
 
934
934
  def force_flush(self, timeout_millis: int = 30000) -> bool:
935
935
  flushed = False
@@ -23,10 +23,10 @@ from typing import Any, Callable, Mapping, Optional, Sequence
23
23
  from uuid import uuid4
24
24
 
25
25
  from opentelemetry import context
26
- from opentelemetry._logs import LogRecord, LoggerProvider, SeverityNumber
27
26
  from opentelemetry.context import Context, _SUPPRESS_INSTRUMENTATION_KEY
28
27
 
29
28
  from struct_sdk import core
29
+ from struct_sdk._otel_logs import LogRecord, SeverityNumber, api
30
30
  from struct_sdk._observations.poller import ConfigClientStatus, ObservationConfigClient
31
31
 
32
32
  _MAX_INT = (1 << 63) - 1
@@ -154,7 +154,7 @@ class ObservationHealth:
154
154
  """
155
155
 
156
156
  def __init__(
157
- self, provider: Optional[LoggerProvider] = None, *, logger: Any = None,
157
+ self, provider: Optional[api.LoggerProvider] = None, *, logger: Any = None,
158
158
  limits: HealthLimits = HealthLimits(),
159
159
  config_client: Optional[ObservationConfigClient] = None,
160
160
  clock: Callable[[], float] = time.monotonic,
@@ -31,7 +31,7 @@ from typing import Any, Optional
31
31
 
32
32
  from opentelemetry.sdk.trace import Span as SdkSpan
33
33
  from opentelemetry.sdk.trace import SpanProcessor
34
- from opentelemetry.trace import StatusCode
34
+ from opentelemetry.trace import NonRecordingSpan, StatusCode, set_span_in_context
35
35
 
36
36
  from struct_sdk._genai_content import truncate_and_serialize
37
37
  from struct_sdk.core import _contain_logged
@@ -94,7 +94,7 @@ if hasattr(os, "register_at_fork"):
94
94
  def _log_record_has_event_name() -> bool:
95
95
  import inspect
96
96
 
97
- from opentelemetry._logs import LogRecord
97
+ from struct_sdk._otel_logs import LogRecord
98
98
 
99
99
  try:
100
100
  return "event_name" in inspect.signature(LogRecord.__init__).parameters
@@ -243,7 +243,7 @@ class OperationDetailsProcessor(SpanProcessor):
243
243
  "gen_ai.input.messages" in content or "gen_ai.output.messages" in content
244
244
  ):
245
245
  return
246
- from opentelemetry._logs import LogRecord, SeverityNumber
246
+ from struct_sdk._otel_logs import LogRecord, SeverityNumber
247
247
 
248
248
  span_attributes = dict(span.attributes or {})
249
249
  attributes: dict[str, Any] = {"event.name": OPERATION_DETAILS_EVENT}
@@ -260,12 +260,9 @@ class OperationDetailsProcessor(SpanProcessor):
260
260
  attributes.setdefault("error.type", _error_type(span, status))
261
261
  attributes.update(content)
262
262
 
263
- context = span.get_span_context()
264
263
  record: dict[str, Any] = {
265
264
  "timestamp": span.end_time,
266
- "trace_id": context.trace_id,
267
- "span_id": context.span_id,
268
- "trace_flags": context.trace_flags,
265
+ "context": set_span_in_context(NonRecordingSpan(span.get_span_context())),
269
266
  "severity_text": "DEBUG",
270
267
  "severity_number": SeverityNumber.DEBUG,
271
268
  "body": OPERATION_DETAILS_EVENT, # Struct's readers match the body
@@ -0,0 +1,52 @@
1
+ """OpenTelemetry's logs API and SDK, from where the installed release keeps them.
2
+
3
+ OpenTelemetry 1.46.0 moved both out of ``opentelemetry._logs`` and
4
+ ``opentelemetry.sdk._logs``, which it keeps as deprecated aliases, and removed
5
+ ``LogExportResult``, ``LogExporter`` and the SDK's ``LoggingHandler``. Older
6
+ releases have only the private modules, and only from 1.39 ``LogRecordExportResult``.
7
+ """
8
+
9
+ from typing import TYPE_CHECKING
10
+
11
+ if TYPE_CHECKING:
12
+ from opentelemetry import _logs as api
13
+ from opentelemetry.sdk._logs import LoggerProvider, LogRecordProcessor
14
+ from opentelemetry.sdk._logs.export import (
15
+ BatchLogRecordProcessor,
16
+ LogRecordExportResult,
17
+ )
18
+ else:
19
+ try:
20
+ from opentelemetry import logs as api
21
+ except ImportError:
22
+ from opentelemetry import _logs as api
23
+
24
+ try:
25
+ from opentelemetry.sdk.logs import LoggerProvider, LogRecordProcessor
26
+ from opentelemetry.sdk.logs.export import (
27
+ BatchLogRecordProcessor,
28
+ LogRecordExportResult,
29
+ )
30
+ except ImportError:
31
+ from opentelemetry.sdk._logs import LoggerProvider, LogRecordProcessor
32
+ from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
33
+
34
+ try:
35
+ from opentelemetry.sdk._logs.export import LogRecordExportResult
36
+ except ImportError:
37
+ from opentelemetry.sdk._logs.export import (
38
+ LogExportResult as LogRecordExportResult,
39
+ )
40
+
41
+ LogRecord = api.LogRecord
42
+ SeverityNumber = api.SeverityNumber
43
+
44
+ __all__ = [
45
+ "BatchLogRecordProcessor",
46
+ "LogRecord",
47
+ "LogRecordExportResult",
48
+ "LogRecordProcessor",
49
+ "LoggerProvider",
50
+ "SeverityNumber",
51
+ "api",
52
+ ]
@@ -45,15 +45,11 @@ from typing import (
45
45
 
46
46
  from opentelemetry import context as _otel_context
47
47
  from opentelemetry import trace
48
- from opentelemetry._logs import LogRecord
49
48
  from opentelemetry.context import create_key
50
49
  from opentelemetry.context.context import Context as _OtelContext
51
50
  from opentelemetry.exporter.otlp.proto.http import _OTLP_HTTP_HEADERS, Compression
52
- from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
53
51
  from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
54
52
  from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
55
- from opentelemetry.sdk._logs import LoggerProvider
56
- from opentelemetry.sdk._logs.export import BatchLogRecordProcessor, LogExportResult # ty: ignore[deprecated] — supported older OTel releases lack LogRecordExportResult
57
53
  from opentelemetry.sdk.metrics import (
58
54
  Counter,
59
55
  Histogram,
@@ -82,9 +78,17 @@ import requests
82
78
  from requests.adapters import HTTPAdapter
83
79
 
84
80
  from struct_sdk._fork_safe_http import fork_safe_session
81
+ from struct_sdk._otel_logs import BatchLogRecordProcessor, LoggerProvider, LogRecord, LogRecordExportResult
85
82
 
86
83
  if TYPE_CHECKING:
84
+ from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
85
+
87
86
  from struct_sdk._auto import FullAppState
87
+ else:
88
+ try:
89
+ from opentelemetry.exporter.otlp.proto.http.log_exporter import OTLPLogExporter
90
+ except ImportError:
91
+ from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
88
92
 
89
93
  logger = logging.getLogger("struct_sdk")
90
94
  # A library must not configure logging on the host's behalf. Attach a NullHandler
@@ -539,24 +543,37 @@ def _exception_type_name(exc: BaseException) -> str:
539
543
 
540
544
 
541
545
  def _record_span_error(
542
- span: Any, exc: BaseException, sdk: Any, site: str, *, error_type: Optional[str] = None
546
+ span: Any,
547
+ exc: BaseException,
548
+ sdk: Any,
549
+ site: str,
550
+ *,
551
+ error_type: Optional[str] = None,
552
+ description: Optional[str] = None,
543
553
  ) -> None:
544
554
  """Mark ``span`` failed by ``exc`` (SDK-PY-47): ``error.type`` and status ERROR always.
545
555
  In span-content modes the status description is ``str(exc)`` and ``record_exception``
546
556
  adds the message and stack trace; otherwise the description is the type name and the
547
557
  ``exception`` event carries only ``exception.type``. Each step is contained on its own,
548
558
  BaseException included: these run on the host's error path, where a hostile ``__str__``
549
- must not replace the host's exception (SDK-PY-19)."""
559
+ must not replace the host's exception (SDK-PY-19). A given ``description`` replaces the status
560
+ description: OpenTelemetry 1.46.0 keeps the first description an ERROR status gets."""
550
561
  type_name = _exception_type_name(exc)
551
562
  err_type = error_type or type_name
552
563
  _contain_logged(lambda: span.set_attribute("error.type", err_type), site=f"{site}.error_type")
553
564
  if _error_text_on_spans(sdk):
554
- description = [type_name] # kept when ``str(exc)`` raises
555
- _contain_logged(lambda: description.__setitem__(0, str(exc)), site=f"{site}.error_text")
556
- _contain_logged(lambda: span.set_status(StatusCode.ERROR, description[0]), site=f"{site}.error_status")
565
+ text = [type_name] # kept when ``str(exc)`` raises
566
+ if description is None:
567
+ _contain_logged(lambda: text.__setitem__(0, str(exc)), site=f"{site}.error_text")
568
+ else:
569
+ text[0] = description
570
+ _contain_logged(lambda: span.set_status(StatusCode.ERROR, text[0]), site=f"{site}.error_status")
557
571
  _contain_logged(lambda: span.record_exception(exc), site=f"{site}.record_exception")
558
572
  return
559
- _contain_logged(lambda: span.set_status(StatusCode.ERROR, type_name), site=f"{site}.error_status")
573
+ _contain_logged(
574
+ lambda: span.set_status(StatusCode.ERROR, type_name if description is None else description),
575
+ site=f"{site}.error_status",
576
+ )
560
577
  _contain_logged(
561
578
  lambda: span.add_event("exception", {"exception.type": _exception_type(exc)}),
562
579
  site=f"{site}.record_exception",
@@ -625,6 +642,7 @@ _BATCH_PROCESSOR_LOGGERS = (
625
642
  "opentelemetry.sdk._shared_internal",
626
643
  "opentelemetry.sdk.trace.export",
627
644
  "opentelemetry.sdk._logs._internal.export",
645
+ "opentelemetry.sdk.logs._internal.export",
628
646
  )
629
647
  # Where the metrics SDK reports a collection: a callback that raised, a reader
630
648
  # shut down twice or never registered.
@@ -976,7 +994,7 @@ class _StructSpanExporter(_InStructExportScope, OTLPSpanExporter):
976
994
 
977
995
 
978
996
  class _StructLogExporter(_InStructExportScope, OTLPLogExporter):
979
- _FAILURE = LogExportResult.FAILURE # ty: ignore[deprecated] — retain compatibility with older OTel
997
+ _FAILURE = LogRecordExportResult.FAILURE
980
998
 
981
999
  def export(self, batch: Any, *args: Any, **kwargs: Any) -> Any:
982
1000
  if _redact_patterns or any(
@@ -2580,17 +2598,21 @@ def _tool_error_status_message(result: Any) -> str:
2580
2598
 
2581
2599
 
2582
2600
  # An integration whose own call a Struct execute_tool span also records (MCP:
2583
- # SDK-PY-57) stores that call's outcome on the span, as a private field (state
2601
+ # SDK-PY-57) stores that call's outcome on the span, as private fields (state
2584
2602
  # on the object Struct created): the call's exception, or True for a failed
2585
- # result. A struct.tool() scope's exit keeps that outcome instead of
2586
- # overwriting it.
2603
+ # result, and the function that records it. A struct.tool() scope's exit runs
2604
+ # that function unless a different exception ends the scope, so the span's
2605
+ # status is set once: OpenTelemetry 1.46.0 keeps the first ERROR description.
2587
2606
  _INNER_OUTCOME = "_struct_inner_outcome"
2607
+ _INNER_RECORD = "_struct_inner_record"
2588
2608
  _NO_INNER_OUTCOME = object()
2589
2609
 
2590
2610
 
2591
- def _record_inner_outcome(span: Any, outcome: Any) -> None:
2592
- """Mark ``span``'s outcome as set by an inner call: its exception, or True."""
2611
+ def _record_inner_outcome(span: Any, outcome: Any, record: Callable[[], object]) -> None:
2612
+ """Mark ``span``'s outcome as set by an inner call: its exception, or True, and
2613
+ ``record``, which the enclosing scope's exit runs to write that outcome."""
2593
2614
  setattr(span, _INNER_OUTCOME, outcome)
2615
+ setattr(span, _INNER_RECORD, record)
2594
2616
 
2595
2617
 
2596
2618
  def _inner_outcome(span: Any) -> Any:
@@ -2600,6 +2622,12 @@ def _inner_outcome(span: Any) -> Any:
2600
2622
  return _NO_INNER_OUTCOME
2601
2623
 
2602
2624
 
2625
+ def _run_inner_record(span: Any) -> None:
2626
+ record = getattr(span, _INNER_RECORD, None)
2627
+ if record is not None:
2628
+ _contain_logged(record, site="tool.end_span.inner_outcome")
2629
+
2630
+
2603
2631
  class _ToolContext:
2604
2632
  """Creates an ``execute_tool {name}`` span per the OTel GenAI spec."""
2605
2633
 
@@ -2702,7 +2730,7 @@ class _ToolContext:
2702
2730
  if span is not None:
2703
2731
  inner = _inner_outcome(span)
2704
2732
  if exc_val and exc_val is inner:
2705
- pass # the inner call already recorded this exception (its code and status)
2733
+ _run_inner_record(span) # the inner call's exception: its code and status
2706
2734
  elif exc_val:
2707
2735
  _record_span_error(span, exc_val, self._sdk, "tool.end_span")
2708
2736
  elif self._result_is_error:
@@ -2711,7 +2739,7 @@ class _ToolContext:
2711
2739
  _safe(lambda: span.set_status(StatusCode.ERROR, self._result_error_message),
2712
2740
  site="tool.end_span.tool_error_status")
2713
2741
  elif inner is not _NO_INNER_OUTCOME:
2714
- pass # the inner call failed and recorded its ERROR; OK would override it
2742
+ _run_inner_record(span) # the inner call failed; its ERROR, not OK
2715
2743
  else:
2716
2744
  _safe(lambda: span.set_status(StatusCode.OK),
2717
2745
  site="tool.end_span.set_ok")
@@ -27,8 +27,9 @@ Owner per span: when a Struct ``execute_tool`` span is current and has no MCP
27
27
  call yet (``struct.tool()``), the MCP conventions say not to add a second span;
28
28
  that span gets the MCP attributes and the call's outcome (``error.type``,
29
29
  ``rpc.response.status_code``, status) and is propagated instead. The outcome
30
- is also marked on the span (``core._record_inner_outcome``) so the scope's
31
- exit keeps it. mcp 2.x also creates its own ``MCP send ...`` transport span (through
30
+ is handed to the span (``core._record_inner_outcome``) and the scope's exit
31
+ records it, unless a different exception ends the scope: the span's status is
32
+ set once, as OpenTelemetry 1.46.0 keeps the first ERROR description. mcp 2.x also creates its own ``MCP send ...`` transport span (through
32
33
  the global tracer provider); it nests under Struct's span.
33
34
 
34
35
  Auto-applied by ``struct.init()`` when the ``mcp`` package is installed.
@@ -186,7 +187,7 @@ def _call_tool_telemetry(
186
187
  ) -> Generator:
187
188
  """Telemetry around one ``call_tool``. ``f, args, kwargs = yield`` marks the
188
189
  host call; ``kwargs`` may carry the injected ``meta``."""
189
- from struct_sdk.core import _record_inner_outcome, _safe
190
+ from struct_sdk.core import _record_inner_outcome, _safe, _tool_result_signals_error
190
191
 
191
192
  # call_tool(self, name, arguments=None, ...); ``meta`` is keyword-only.
192
193
  session = args[0] if args else None
@@ -211,8 +212,11 @@ def _call_tool_telemetry(
211
212
  exc = e # ``except ... as e`` unbinds ``e`` before the closure runs
212
213
 
213
214
  def record_failure() -> None:
214
- _record_error(outer, exc, sdk)
215
- _record_inner_outcome(outer, exc)
215
+ # Read now: the caller can change the error before the scope ends.
216
+ code, description = _error_outcome(exc, sdk)
217
+ if code is not None:
218
+ outer.set_attribute("rpc.response.status_code", str(code))
219
+ _record_inner_outcome(outer, exc, lambda: _write_error(outer, exc, sdk, code, description))
216
220
 
217
221
  # On the host's error path, and stringifying a hostile exception
218
222
  # can raise anything: ``_contain``, not ``_safe``.
@@ -220,8 +224,9 @@ def _call_tool_telemetry(
220
224
  raise
221
225
 
222
226
  def outcome() -> None:
223
- if _record_tool_error(outer, sdk, result):
224
- _record_inner_outcome(outer, True)
227
+ if _tool_result_signals_error(result):
228
+ message = _tool_error_message(sdk, result) # the result is the caller's to change
229
+ _record_inner_outcome(outer, True, lambda: _mark_tool_error(outer, message))
225
230
 
226
231
  _safe(outcome, site="mcp.call_tool.outer_result")
227
232
  return result # noqa: B901
@@ -345,34 +350,49 @@ def _record_result(span: trace.Span, sdk: StructSDK, result: Any) -> None:
345
350
 
346
351
  def _record_tool_error(span: trace.Span, sdk: StructSDK, result: Any) -> bool:
347
352
  """Mark ``span`` as a tool error when ``result`` has ``isError`` set."""
348
- from struct_sdk.core import _tool_error_status_message, _tool_result_signals_error
353
+ from struct_sdk.core import _tool_result_signals_error
349
354
 
350
355
  if not _tool_result_signals_error(result):
351
356
  return False
352
- # The message is content on a span (the tool's error text): only the
353
- # span-content modes carry it, as for struct.tool().
354
- message = (
355
- _tool_error_status_message(result)
356
- if sdk.emit_span_content
357
- else "tool returned is_error=true"
358
- )
357
+ _mark_tool_error(span, _tool_error_message(sdk, result))
358
+ return True
359
+
360
+
361
+ def _tool_error_message(sdk: StructSDK, result: Any) -> str:
362
+ """The status description for an error result. It is content on a span (the
363
+ tool's error text): only the span-content modes carry it, as for struct.tool()."""
364
+ from struct_sdk.core import _tool_error_status_message
365
+
366
+ return _tool_error_status_message(result) if sdk.emit_span_content else "tool returned is_error=true"
367
+
368
+
369
+ def _mark_tool_error(span: trace.Span, message: str) -> None:
359
370
  span.set_attribute("error.type", "tool_error")
360
371
  span.set_status(StatusCode.ERROR, message)
361
- return True
362
372
 
363
373
 
364
374
  def _record_error(span: trace.Span, exc: BaseException, sdk: Any) -> None:
365
375
  """A failed call: a JSON-RPC error's code as ``error.type``, else the exception's type.
366
376
  Its text (the server's error message, the exception's message and stack trace) reaches
367
377
  the span only in span-content modes (SDK-PY-47): it can quote the tool's arguments."""
368
- error = getattr(exc, "error", None)
369
- code = getattr(error, "code", None)
370
- if isinstance(code, int) and not isinstance(code, bool):
378
+ _write_error(span, exc, sdk, *_error_outcome(exc, sdk))
379
+
380
+
381
+ def _error_outcome(exc: BaseException, sdk: Any) -> tuple[Optional[int], Optional[str]]:
382
+ """A JSON-RPC error's code and status description, else (None, None)."""
383
+ code = getattr(getattr(exc, "error", None), "code", None)
384
+ if not isinstance(code, int) or isinstance(code, bool):
385
+ return None, None
386
+ message = getattr(getattr(exc, "error", None), "message", None)
387
+ return code, span_error_description(sdk, message, str(code)) if isinstance(message, str) else None
388
+
389
+
390
+ def _write_error(
391
+ span: trace.Span, exc: BaseException, sdk: Any, code: Optional[int], description: Optional[str]
392
+ ) -> None:
393
+ if code is not None:
371
394
  span.set_attribute("rpc.response.status_code", str(code))
372
- message = getattr(error, "message", None)
373
- record_span_error(span, exc, sdk, "mcp.error", error_type=str(code))
374
- if isinstance(message, str):
375
- span.set_status(StatusCode.ERROR, span_error_description(sdk, message, str(code)))
395
+ record_span_error(span, exc, sdk, "mcp.error", error_type=str(code), description=description)
376
396
  else:
377
397
  record_span_error(span, exc, sdk, "mcp.error")
378
398
 
File without changes
File without changes
File without changes
File without changes