Skip to main content

Tracing Setup

This guide covers how to initialize, configure, and shut down the MutagenT tracing system in both TypeScript and Python applications.

Quick Start

1

Install the SDK

npm install @mutagent/sdk
2

Initialize tracing at application startup

import { initTracing } from "@mutagent/sdk/tracing";

initTracing({
  apiKey: process.env.MUTAGENT_API_KEY!,
});
3

Shut down tracing before process exit

import { shutdownTracing } from "@mutagent/sdk/tracing";

// Flush remaining spans and clean up
await shutdownTracing();

initTracing() Configuration

The initTracing() function accepts a TracingConfig object. Call it once at application startup before any traced operations.
import { initTracing } from "@mutagent/sdk/tracing";

initTracing({
  apiKey: process.env.MUTAGENT_API_KEY!,
  endpoint: "https://api.mutagent.io",
  environment: "production",
  batchSize: 10,
  flushIntervalMs: 5000,
  debug: false,
  source: "sdk",
});

Configuration Options

OptionTypeDefaultDescription
apiKeystringRequiredYour MutagenT API key for authentication.
endpointstring"https://api.mutagent.io"The MutagenT API endpoint URL.
environmentstringundefinedEnvironment label attached to all traces (e.g., "production", "staging", "development").
batchSizenumber10Number of spans to buffer before triggering an automatic flush.
flushIntervalMsnumber5000Maximum time in milliseconds between automatic flushes.
debugbooleanfalseWhen enabled, logs span start/end events to the console for debugging.
sourcestring"sdk"Source identifier attached to traces. Integration packages override this automatically. Valid values: "sdk", "langchain", "langgraph", "vercel-ai", "openai", "otel", "manual".
The Python SDK uses snake_case parameter names (api_key, batch_size, flush_interval_ms). The TypeScript SDK uses camelCase (apiKey, batchSize, flushIntervalMs).

Environment Variables

You can provide your API key and endpoint via environment variables instead of passing them directly:
# .env
MUTAGENT_API_KEY=mt_xxxxxxxxxxxx
MUTAGENT_API_URL=https://api.mutagent.io
import { initTracing } from "@mutagent/sdk/tracing";

initTracing({
  apiKey: process.env.MUTAGENT_API_KEY!,
  endpoint: process.env.MUTAGENT_API_URL,
});

Lazy Initialization

In TypeScript, if you set the MUTAGENT_API_KEY environment variable, you can skip calling initTracing() entirely. The SDK will automatically initialize tracing on the first startSpan() call using the environment variable.
// No initTracing() call needed -- just set MUTAGENT_API_KEY in your environment

import { withTrace } from "@mutagent/sdk/tracing";

// Tracing initializes automatically on first use
const result = await withTrace({ kind: "chain", name: "my-pipeline" }, async (span) => {
  return "done";
});
This lazy initialization:
  • Only attempts once per process lifecycle (controlled by an internal lazyInitAttempted flag)
  • Reads process.env["MUTAGENT_API_KEY"] at the time of the first span creation
  • Uses the default endpoint (https://api.mutagent.io) and default batch settings
  • Resets when shutdownTracing() is called, allowing re-initialization
Lazy initialization is convenient for development and simple scripts. For production applications, prefer calling initTracing() explicitly so you can configure the environment, batchSize, and debug options.

Shutdown and Graceful Cleanup

Always call shutdownTracing() before your process exits. This ensures all buffered spans are flushed to the MutagenT API.
import { initTracing, shutdownTracing } from "@mutagent/sdk/tracing";

initTracing({ apiKey: process.env.MUTAGENT_API_KEY! });

// Your application logic here...

// Before exit: flush remaining spans
await shutdownTracing();
The Python SDK automatically registers an atexit handler, so shutdown_tracing() is called when the process exits normally. It is still good practice to call it explicitly for predictable behavior.

What shutdownTracing() Does

  1. Stops the background flush timer
  2. Flushes all remaining buffered spans to the API
  3. Clears all active span state (removes all spans from the SpanManager)
  4. Resets the tracing system completely, including the lazy initialization flag (can be re-initialized with a new initTracing() call or via lazy init from MUTAGENT_API_KEY)

Idempotency and Re-initialization

In TypeScript, calling initTracing() a second time silently shuts down the previous configuration and replaces it with the new one. This is useful for reconfiguring tracing in tests. In Python, calling init_tracing() a second time logs a warning and is a no-op. Call shutdown_tracing() first, then init_tracing() again to reconfigure.

Integration with Framework Packages

If you are using a MutagenT integration package (e.g., @mutagent/langchain, @mutagent/langgraph, @mutagent/openai, @mutagent/vercel-ai, @mutagent/mastra), the integration handles tracing initialization internally. You typically do not need to call initTracing() yourself — the integration configures it when you create its callback handler or wrapper. However, if you want to customize tracing configuration (e.g., change batch size or enable debug mode), you can call initTracing() before creating the integration handler, and the integration will use your existing configuration.
import { initTracing } from "@mutagent/sdk/tracing";
import { MutagentCallbackHandler } from "@mutagent/langchain";

// Optional: customize tracing config
initTracing({
  apiKey: process.env.MUTAGENT_API_KEY!,
  batchSize: 20,
  debug: true,
});

// Integration uses the existing tracing setup
const handler = new MutagentCallbackHandler();

Batch Collection Behavior

The tracing system buffers spans in memory and sends them in batches to minimize network overhead. Understanding the flush behavior helps with tuning:
TriggerBehavior
Buffer reaches batchSizeImmediate async flush
flushIntervalMs timer firesFlush whatever is in the buffer
shutdownTracing() calledForce flush all remaining spans
Spans are grouped by traceId in the HTTP payload, so spans belonging to the same trace are always sent together (within a single batch).
If your process exits without calling shutdownTracing(), any spans still in the buffer will be lost. In TypeScript, the flush timer uses unref() so it does not keep the process alive — this means you must explicitly flush before exit.

Retry Behavior

Failed flush attempts are retried with exponential backoff:
  • Max retries: 3 (configurable internally via BatchCollectorConfig)
  • Base delay: 1000ms (doubles each retry: 1s, 2s, 4s)
  • HTTP timeout: 10 seconds per request (via AbortController)
  • If all retries fail, the spans in that batch are dropped and a warning is logged in debug mode

Checking Initialization Status

You can check whether tracing has been initialized:
import { isTracingInitialized } from "@mutagent/sdk/tracing";

if (isTracingInitialized()) {
  console.log("Tracing is active");
}

Troubleshooting

  1. Verify your API key is correct and has write permissions
  2. Enable debug: true in your tracing config to see span start/end logs in the console
  3. Make sure you call shutdownTracing() before your process exits — buffered spans may not have been flushed
  4. Check that the endpoint is reachable from your environment
The apiKey field is required and cannot be empty. Make sure your environment variable is set:
echo $MUTAGENT_API_KEY  # Should print your key
If your application produces a very high volume of spans, reduce batchSize to flush more frequently, or reduce flushIntervalMs to flush on a shorter timer. The default settings (10 spans / 5 seconds) are designed for moderate throughput.

Next Steps

Tracing API Reference

Learn about decorators, wrappers, and low-level span primitives.

Tracing Overview

Understand core concepts, SpanKind taxonomy, and architecture.