From 48cb4be4cdbecd6bddf283d7f1b4b7b925ee6218 Mon Sep 17 00:00:00 2001 From: phernandez Date: Wed, 8 Oct 2025 08:10:54 -0500 Subject: [PATCH] fix: instrument httpx client at module level for MCP context The lifespan-based instrumentation only runs when FastAPI app starts. In MCP context, the app never starts but the httpx client is still used. Solution: Instrument the client immediately after creation at module level. This works in both contexts: - MCP: client is instrumented when module is imported - API: client is instrumented before lifespan runs (lifespan still safe) This enables distributed tracing from MCP -> Cloud -> API. Signed-off-by: phernandez --- src/basic_memory/mcp/async_client.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/basic_memory/mcp/async_client.py b/src/basic_memory/mcp/async_client.py index 905b12f8..62f4403a 100644 --- a/src/basic_memory/mcp/async_client.py +++ b/src/basic_memory/mcp/async_client.py @@ -38,3 +38,15 @@ def create_client() -> AsyncClient: # Create shared async client client = create_client() + +# Instrument client for distributed tracing when in cloud mode +# This must happen AFTER client creation and works in both MCP and API contexts +config = ConfigManager().config +if config.cloud_mode_enabled: + try: + import logfire # pyright: ignore[reportMissingImports] + + logger.info("Cloud mode: instrumenting httpx client for distributed tracing") + logfire.instrument_httpx(client=client) + except ImportError: + logger.warning("logfire not available - skipping httpx instrumentation")