Skip to content

Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.

ensure link is shown after finalizing traces (#7593)

Lorenze Jay3831e8b6c86f
diff --git a/lib/crewai/src/crewai/execution.py b/lib/crewai/src/crewai/execution.py
index 0d52933b2..ceda6969e 100644
--- a/lib/crewai/src/crewai/execution.py
+++ b/lib/crewai/src/crewai/execution.py
@@ -159,8 +159,14 @@ def _start_tracing(execution_uuid: str, tracing: bool | None) -> None:
else:
client = TraceGrantClient(amp_credential)
grant = client.create(execution_uuid)
- session = TraceSession(grant.execution_uuid, [GrantSpanExporter(client, grant)])
- stack.callback(session.shutdown)
+ exporter = GrantSpanExporter(client, grant)
+ session = TraceSession(grant.execution_uuid, [exporter])
+
+ def finish_authenticated_trace() -> None:
+ if session.shutdown():
+ exporter.show_trace_summary()
+
+ stack.callback(finish_authenticated_trace)
_activate_tracing(ExecutionTrace(session, stack))
diff --git a/lib/crewai/src/crewai/telemetry/tracing/ephemeral.py b/lib/crewai/src/crewai/telemetry/tracing/ephemeral.py
index 9fbc9f1be..67c263cf0 100644
--- a/lib/crewai/src/crewai/telemetry/tracing/ephemeral.py
+++ b/lib/crewai/src/crewai/telemetry/tracing/ephemeral.py
@@ -143,6 +143,7 @@ class EphemeralSpanBuffer(SpanExporter):
logger.warning("Ephemeral trace export failed; buffer discarded")
finally:
exporter.shutdown()
+ exporter.show_trace_summary()
except TraceGrantError as error:
logger.warning(
"Ephemeral trace grant failed (HTTP %s); buffer discarded",
diff --git a/lib/crewai/src/crewai/telemetry/tracing/grants.py b/lib/crewai/src/crewai/telemetry/tracing/grants.py
index ad317dcb6..7025eae22 100644
--- a/lib/crewai/src/crewai/telemetry/tracing/grants.py
+++ b/lib/crewai/src/crewai/telemetry/tracing/grants.py
@@ -16,9 +16,16 @@ from crewai_core.plus_api import PlusAPI
from opentelemetry.exporter.otlp.proto.common.trace_encoder import encode_spans
from opentelemetry.sdk.trace import ReadableSpan
from opentelemetry.sdk.trace.export import SpanExportResult, SpanExporter
+from rich.style import Style
+from rich.text import Text
from crewai.auth.token import AuthError, get_auth_token
from crewai.context import get_platform_integration_token
+from crewai.events.listeners.tracing.utils import (
+ is_tui_mode,
+ should_suppress_tracing_messages,
+)
+from crewai.events.utils.console_formatter import ConsoleFormatter
from crewai.telemetry.tracing.session import MAX_EXPORT_BATCH_SIZE, otlp_exporter
@@ -53,6 +60,32 @@ class TraceGrant:
collector_url: str
execution_uuid: str
expires_at: datetime
+ # Optional for compatibility with AMP versions without the standalone viewer.
+ trace_url: str | None = field(default=None, repr=False)
+
+
+def _trace_viewer_url(value: object, base_url: str) -> str | None:
+ """Accept an absolute AMP viewer URL without terminal control characters."""
+ if (
+ not isinstance(value, str)
+ or not value
+ or any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in value)
+ ):
+ return None
+ try:
+ endpoint, base = urlsplit(value), urlsplit(base_url)
+ if (
+ endpoint.scheme in ("http", "https")
+ and endpoint.hostname
+ and endpoint.username is None
+ and endpoint.password is None
+ and (endpoint.scheme, endpoint.hostname, endpoint.port)
+ == (base.scheme, base.hostname, base.port)
+ ):
+ return value
+ except ValueError:
+ pass
+ return None
def _is_local_collector(hostname: str) -> bool:
@@ -89,7 +122,8 @@ class TraceGrantClient:
response = self._api._make_request(
"POST",
f"{PlusAPI.TRACING_RESOURCE}/grants",
- json={"execution_uuid": execution_uuid},
+ # Keep viewer opt-in on renewals as well as the initial grant.
+ json={"execution_uuid": execution_uuid, "include_trace_url": True},
timeout=5,
)
except Exception as error:
@@ -125,7 +159,11 @@ class TraceGrantClient:
):
raise ValueError("Invalid grant")
return TraceGrant(
- data["token"], data["collector_url"], execution_uuid, expiry
+ data["token"],
+ data["collector_url"],
+ execution_uuid,
+ expiry,
+ trace_url=_trace_viewer_url(data.get("trace_url"), self._api.base_url),
)
except (KeyError, TypeError, ValueError, AttributeError):
raise TraceGrantError(
@@ -141,6 +179,11 @@ class GrantSpanExporter(SpanExporter):
self._grant = grant
self._lock = Lock()
self._delegate = self._exporter(grant)
+ self._trace_url = grant.trace_url
+ self._exported = False
+ self._export_failed = False
+ self._summary_shown = False
+ self._suppress_output = should_suppress_tracing_messages() or is_tui_mode()
@staticmethod
def _exporter(grant: TraceGrant) -> SpanExporter:
@@ -151,50 +194,88 @@ class GrantSpanExporter(SpanExporter):
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
"""Bound each request; oversized single spans are skipped with FAILURE."""
with self._lock:
- result = SpanExportResult.SUCCESS
- pending = [
- spans[offset : offset + MAX_EXPORT_BATCH_SIZE]
- for offset in reversed(range(0, len(spans), MAX_EXPORT_BATCH_SIZE))
- ]
- while pending:
- batch = pending.pop()
- size = encode_spans(batch).ByteSize()
- if size > MAX_EXPORT_BODY_BYTES:
- if len(batch) == 1:
- logger.warning(
- "Skipping execution trace span: encoded size %d exceeds "
- "Wharf's %d-byte request limit",
- size,
- MAX_EXPORT_BODY_BYTES,
- )
- result = SpanExportResult.FAILURE
- else:
- midpoint = len(batch) // 2
- # Process the left half first to retain span order.
- pending.extend((batch[midpoint:], batch[:midpoint]))
- continue
- if (
- self._grant.expires_at - datetime.now(timezone.utc)
- ).total_seconds() <= 30:
- try:
- grant = self._client.create(self._grant.execution_uuid)
- except TraceGrantError as error:
- logger.warning(
- "Could not renew execution trace grant (HTTP %s)",
- error.status_code,
- )
- return SpanExportResult.FAILURE
- exporter = self._exporter(grant)
- self._delegate.shutdown()
- self._delegate, self._grant = exporter, grant
- if self._delegate.export(batch) != SpanExportResult.SUCCESS:
+ try:
+ result = self._export(spans)
+ except Exception:
+ self._export_failed = True
+ raise
+ self._export_failed |= result != SpanExportResult.SUCCESS
+ self._exported |= bool(spans) and result == SpanExportResult.SUCCESS
+ return result
+
+ def _export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
+ result = SpanExportResult.SUCCESS
+ pending = [
+ spans[offset : offset + MAX_EXPORT_BATCH_SIZE]
+ for offset in reversed(range(0, len(spans), MAX_EXPORT_BATCH_SIZE))
+ ]
+ while pending:
+ batch = pending.pop()
+ size = encode_spans(batch).ByteSize()
+ if size > MAX_EXPORT_BODY_BYTES:
+ if len(batch) == 1:
+ logger.warning(
+ "Skipping execution trace span: encoded size %d exceeds "
+ "Wharf's %d-byte request limit",
+ size,
+ MAX_EXPORT_BODY_BYTES,
+ )
+ result = SpanExportResult.FAILURE
+ else:
+ midpoint = len(batch) // 2
+ # Process the left half first to retain span order.
+ pending.extend((batch[midpoint:], batch[:midpoint]))
+ continue
+ if (
+ self._grant.expires_at - datetime.now(timezone.utc)
+ ).total_seconds() <= 30:
+ try:
+ grant = self._client.create(self._grant.execution_uuid)
+ except TraceGrantError as error:
+ logger.warning(
+ "Could not renew execution trace grant (HTTP %s)",
+ error.status_code,
+ )
return SpanExportResult.FAILURE
- logger.info(
- "Exported %d spans to Wharf for execution %s",
- len(batch),
- self._grant.execution_uuid,
+ exporter = self._exporter(grant)
+ self._delegate.shutdown()
+ self._delegate, self._grant = exporter, grant
+ self._trace_url = grant.trace_url or self._trace_url
+ if self._delegate.export(batch) != SpanExportResult.SUCCESS:
+ return SpanExportResult.FAILURE
+ logger.info(
+ "Exported %d spans to Wharf for execution %s",
+ len(batch),
+ self._grant.execution_uuid,
+ )
+ return result
+
+ def show_trace_summary(self) -> None:
+ """Display the exported execution UUID and AMP's optional viewer link once."""
+ with self._lock:
+ if (
+ not self._exported
+ or self._export_failed
+ or self._summary_shown
+ or self._suppress_output
+ or should_suppress_tracing_messages()
+ or is_tui_mode()
+ ):
+ return
+ self._summary_shown = True
+ content = Text()
+ content.append("Traces exported\n", style="green bold")
+ content.append("Execution trace ID: ", style="white")
+ content.append(self._grant.execution_uuid, style="green")
+ if self._trace_url:
+ content.append("\n\nView traces:\n", style="white bold")
+ content.append(
+ self._trace_url,
+ style=Style(color="cyan", underline=True, link=self._trace_url),
)
- return result
+ ConsoleFormatter(verbose=True).print_panel(
+ content, "🔗 Execution Traces", "green"
+ )
def shutdown(self) -> None:
with self._lock:
diff --git a/lib/crewai/tests/telemetry/test_session_trace_export.py b/lib/crewai/tests/telemetry/test_session_trace_export.py
index 556a93eb8..865824e19 100644
--- a/lib/crewai/tests/telemetry/test_session_trace_export.py
+++ b/lib/crewai/tests/telemetry/test_session_trace_export.py
@@ -2,6 +2,7 @@
import asyncio
from concurrent.futures import ThreadPoolExecutor
+from contextvars import copy_context
from dataclasses import replace
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -41,6 +42,8 @@ pytestmark = pytest.mark.block_network(allowed_hosts=[r"^127\.0\.0\.1$"])
@pytest.fixture(autouse=True)
def tracing_environment(monkeypatch):
+ # Keep viewer URLs on one line when asserting their literal output.
+ monkeypatch.setenv("COLUMNS", "240")
monkeypatch.setenv("OTEL_SDK_DISABLED", "false")
monkeypatch.setenv("CREWAI_DISABLE_TELEMETRY", "true")
for name in (
@@ -82,6 +85,8 @@ def collector(monkeypatch):
).isoformat(),
**state.grant_override,
}
+ if not payload.get("include_trace_url"):
+ response.pop("trace_url", None)
encoded = json.dumps(response).encode()
else:
state.batches.append(
@@ -155,7 +160,7 @@ def test_authenticated_spans_go_directly_to_collector(collector, credential):
assert len(collector.grants) == 1
auth, _, payload = collector.grants[0]
assert auth == f"Bearer {credential}"
- assert payload == {"execution_uuid": execution_uuid}
+ assert payload == {"execution_uuid": execution_uuid, "include_trace_url": True}
assert len(collector.batches) == 1
bearer, batch = collector.batches[0]
assert bearer == "Bearer grant-1"
@@ -174,6 +179,186 @@ def test_invalid_credentials_do_not_request_anonymous_grants(collector):
assert collector.grants[0][0] == "Bearer invalid"
[email protected]("credential", [None, "pat"])
+def test_grant_preserves_optional_viewer_url_without_exposing_it_in_repr(
+ collector, credential
+):
+ client = TraceGrantClient(credential)
+ assert client.create(str(uuid4())).trace_url is None
+ url = collector.url + "/crewai_plus/ephemeral_trace_batches/run?access_code=private"
+ collector.grant_override = {"trace_url": url}
+ grant = client.create(str(uuid4()))
+ assert grant.trace_url == url
+ assert url not in repr(grant) and "private" not in repr(grant)
+ assert grant.token not in repr(grant)
+
+
+ "value",
+ [
+ None,
+ "",
+ 42,
+ {},
+ "/relative",
+ "javascript:alert(1)",
+ "https://unrelated.example/trace",
+ "http://[invalid/trace",
+ "http://user:[email protected]/trace",
+ "\n",
+ "\x1b[2J",
+ ],
+)
+def test_unusable_optional_viewer_url_does_not_break_grant(collector, value):
+ collector.grant_override = {"trace_url": value}
+ assert TraceGrantClient("pat").create(str(uuid4())).trace_url is None
+
+
+ ("authenticated", "approved", "status", "suppression", "shows_link"),
+ [
+ (True, True, 200, None, True),
+ (False, True, 200, None, True),
+ (False, False, 200, None, False),
+ (True, True, 401, None, False),
+ (False, True, 401, None, False),
+ (True, True, 200, "messages", False),
+ (False, True, 200, "messages", False),
+ (True, True, 200, "tui", False),
+ (False, True, 200, "tui", False),
+ ],
+)
+def test_viewer_link_is_printed_once_after_successful_execution_export(
+ collector,
+ monkeypatch,
+ capsys,
+ authenticated,
+ approved,
+ status,
+ suppression,
+ shows_link,
+):
+ from crewai.events.listeners.tracing.utils import (
+ set_suppress_tracing_messages,
+ set_tui_mode,
+ )
+ from crewai.execution import begin_execution, end_execution
+ from crewai.telemetry.tracing.context import get_trace_session
+
+ url = collector.url + "/crewai_plus/otel_traces/run?access_code=secret&x=[value]"
+ collector.grant_override = {"trace_url": url}
+ collector.export_status = status
+ if authenticated:
+ monkeypatch.setenv("CREWAI_USER_PAT", "synthetic-pat")
+
+ def run():
+ if suppression == "messages":
+ set_suppress_tracing_messages(True)
+ elif suppression == "tui":
+ set_tui_mode(True)
+ with trace_consent(lambda: approved):
+ token = begin_execution(tracing=True)
+ try:
+ session = get_trace_session()
+ record(session)
+ nested = begin_execution(tracing=True)
+ end_execution(nested)
+ assert "View traces:" not in capsys.readouterr().out
+ finally:
+ end_execution(token)
+
+ copy_context().run(run)
+ output = capsys.readouterr().out
+ assert output.count(url) == int(shows_link)
+ assert output.count("View traces:") == int(shows_link)
+ assert output.count("Execution trace ID:") == int(shows_link)
+ assert len(collector.batches) == int(authenticated or approved)
+
+
[email protected]("first_status", [200, 401])
+def test_deferred_trace_link_waits_for_finalization_and_remembers_export_failures(
+ collector, monkeypatch, capsys, first_status
+):
+ from crewai.execution import begin_execution, end_execution
+ from crewai.telemetry.tracing.context import get_trace_session
+
+ monkeypatch.setenv("CREWAI_USER_PAT", "synthetic-pat")
+ url = collector.url + "/crewai_plus/otel_traces/run"
+ collector.grant_override = {"trace_url": url}
+ collector.export_status = first_status
+ token = begin_execution(tracing=True)
+ try:
+ session = get_trace_session()
+ record(session)
+ session.flush()
+ finally:
+ lifetime = end_execution(token, defer=True)
+ assert url not in capsys.readouterr().out
+
+ collector.export_status = 200
+ token = begin_execution(tracing=True, trace_session=lifetime)
+ try:
+ record(get_trace_session())
+ finally:
+ end_execution(token)
+ lifetime.finish()
+ assert capsys.readouterr().out.count(url) == int(first_status == 200)
+
+
[email protected]("updated_url", [False, True])
[email protected]("credential", [None, "pat"])
+def test_refreshed_grant_preserves_or_updates_viewer_url(
+ collector, capsys, updated_url, credential
+):
+ original = collector.url + "/crewai_plus/otel_traces/original"
+ renewed = collector.url + "/crewai_plus/otel_traces/renewed"
+ collector.grant_override = {"trace_url": original}
+ client = TraceGrantClient(credential)
+ grant = replace(
+ client.create(str(uuid4())),
+ expires_at=datetime.now(timezone.utc) + timedelta(seconds=1),
+ )
+ collector.grant_override = {"trace_url": renewed} if updated_url else {}
+ exporter = GrantSpanExporter(client, grant)
+ session = TraceSession(grant.execution_uuid, [exporter])
+ try:
+ record(session)
+ finally:
+ session.shutdown()
+ exporter.show_trace_summary()
+ exporter.show_trace_summary()
+ output = capsys.readouterr().out
+ assert output.count("View traces:") == 1
+ assert (renewed if updated_url else original) in output
+ assert len(collector.grants) == 2
+ assert all(
+ payload["include_trace_url"] is True for _, _, payload in collector.grants
+ )
+
+
[email protected]("authenticated", [True, False])
+def test_export_without_viewer_url_still_shows_execution_uuid(
+ collector, monkeypatch, capsys, authenticated
+):
+ from crewai.execution import begin_execution, end_execution, get_execution_uuid
+ from crewai.telemetry.tracing.context import get_trace_session
+
+ if authenticated:
+ monkeypatch.setenv("CREWAI_USER_PAT", "synthetic-pat")
+ with trace_consent(lambda: True):
+ token = begin_execution(tracing=True)
+ try:
+ execution_uuid = get_execution_uuid()
+ record(get_trace_session())
+ assert "Execution trace ID:" not in capsys.readouterr().out
+ finally:
+ end_execution(token)
+ output = capsys.readouterr().out
+ assert output.count(f"Execution trace ID: {execution_uuid}") == 1
+ assert "View traces:" not in output
+ assert len(collector.batches) == 1
+
+
@pytest.mark.parametrize(
"override",
[
@@ -224,7 +409,8 @@ def test_anonymous_grant_omits_saved_organization_and_rejects_wrong_tier(collect
client.create(str(uuid4()))
auth, headers, payload = collector.grants[0]
assert auth is None and "X-Crewai-Organization-Id" not in headers
- assert set(payload) == {"execution_uuid"}
+ assert set(payload) == {"execution_uuid", "include_trace_url"}
+ assert payload["include_trace_url"] is True
collector.grant_override = {"tier": "authenticated"}
with pytest.raises(TraceGrantError):
client.create(str(uuid4()))
@@ -281,8 +467,8 @@ def test_expired_grant_is_renewed_for_same_execution(collector):
record(session)
session.shutdown()
assert [payload for _, _, payload in collector.grants] == [
- {"execution_uuid": execution_uuid},
- {"execution_uuid": execution_uuid},
+ {"execution_uuid": execution_uuid, "include_trace_url": True},
+ {"execution_uuid": execution_uuid, "include_trace_url": True},
]
assert collector.batches[0][0] == "Bearer grant-2"
diff --git a/pyproject.toml b/pyproject.toml
index bd82e60d9..5ad51f65e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -262,6 +262,7 @@ exclude-newer-package = { msgpack = "2026-06-20T00:00:00Z", pydantic-settings =
# Keep OpenAI on the SDK range required by CrewAI when transitive dependencies
# loosen or pin their own lower versions.
override-dependencies = [
+ "anyio>=4.14.2", # GHSA-82r6-8w77-94w6 / GHSA-5p39-cfhj-2xmp
"openai>=2.30.0,<3",
"rich>=13.7.1",
"onnxruntime<1.24; python_version < '3.11'",
diff --git a/uv.lock b/uv.lock
index 085e71bb0..7716bacce 100644
--- a/uv.lock
+++ b/uv.lock
@@ -36,6 +36,7 @@ members = [
]
overrides = [
{ name = "aiohttp", specifier = ">=3.14.3" },
+ { name = "anyio", specifier = ">=4.14.2" },
{ name = "authlib", specifier = ">=1.6.12" },
{ name = "cryptography", specifier = ">=50.0.0" },
{ name = "docling-core", extras = ["chunking"], specifier = ">=2.74.1" },
@@ -392,16 +393,16 @@ sdist = { url = "https://files.pythonhosted.org/packages/3e/38/7859ff46355f76f8d
[[package]]
name = "anyio"
-version = "4.13.0"
+version = "4.14.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "exceptiongroup", marker = "python_full_version < '3.11'" },
{ name = "idna" },
{ name = "typing-extensions", marker = "python_full_version < '3.13'" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/19/14/2c5dd9f512b66549ae92767a9c7b330ae88e1932ca57876909410251fe13/anyio-4.13.0.tar.gz", hash = "sha256:334b70e641fd2221c1505b3890c69882fe4a2df910cba14d97019b90b24439dc", size = 231622, upload-time = "2026-03-24T12:59:09.671Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/61/cc/a381afa6efea9f496eff839d4a6a1aed3bfafc7b3ab4b0d1b243a12573dd/anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f", size = 260176, upload-time = "2026-07-12T20:29:07.082Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/da/42/e921fccf5015463e32a3cf6ee7f980a6ed0f395ceeaa45060b61d86486c2/anyio-4.13.0-py3-none-any.whl", hash = "sha256:08b310f9e24a9594186fd75b4f73f4a4152069e3853f1ed8bfbf58369f4ad708", size = 114353, upload-time = "2026-03-24T12:59:08.246Z" },
+ { url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" },
]
[[package]]