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 <paul@basicmachines.co>
This commit is contained in:
phernandez
2025-10-08 08:10:54 -05:00
parent 3e876a7549
commit 48cb4be4cd
+12
View File
@@ -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")