Skip to main content
The @contextcompany/mastra package provides automatic instrumentation for Mastra AI agents via Mastra’s built-in AI tracing system. It exports all agent traces, LLM calls, and tool executions to The Context Company for observability.

Installation

npm install @contextcompany/mastra

Quick Start

Register the TCC exporter in your Mastra configuration:
import { Mastra } from '@mastra/core';
import { TCCMastraExporter } from '@contextcompany/mastra';

const mastra = new Mastra({
  agents: [/* your agents */],
  tracing: {
    exporters: [new TCCMastraExporter()],
  },
});

// Use Mastra normally - all traces are automatically captured
const result = await mastra.agents.myAgent.generate({
  messages: [{ role: 'user', content: 'What is AI?' }],
  metadata: {
    'tcc.runId': 'custom-run-id',
  },
});

API Reference

TCCMastraExporter

The Mastra AI tracing exporter that captures and exports traces to The Context Company.
class TCCMastraExporter implements AITracingExporter {
  constructor(config?: TCCMastraExporterConfig);
  exportEvent(event: AITracingEvent): Promise<void>;
  shutdown(): Promise<void>;
  init(config: TracingConfig): void;
}
config
TCCMastraExporterConfig
Configuration options for the exporter.
Example:
const exporter = new TCCMastraExporter({
  apiKey: 'tcc_abc123',
  debug: true,
});

TCCMastraExporterConfig

Configuration object for the exporter.
type TCCMastraExporterConfig = {
  apiKey?: string;
  endpoint?: string;
  debug?: boolean;
}
apiKey
string
TCC API key. If not provided, reads from TCC_API_KEY environment variable.Keys starting with dev_ automatically route to the development endpoint.
endpoint
string
Custom TCC endpoint URL. Defaults to https://api.thecontext.company/v1/mastra (or dev endpoint for dev API keys).
debug
boolean
Enable debug logging to console. Logs all span events and export payloads.

submitFeedback

Submit user feedback for a specific run.
function submitFeedback(params: {
  runId: string;
  score?: "thumbs_up" | "thumbs_down";
  text?: string;
}): Promise<Response | undefined>
params
object
required

Usage Patterns

Basic Configuration

Minimal setup with environment variable for API key:
import { Mastra } from '@mastra/core';
import { TCCMastraExporter } from '@contextcompany/mastra';

const mastra = new Mastra({
  agents: [
    // Your agent definitions
  ],
  tracing: {
    exporters: [new TCCMastraExporter()],
  },
});

With Explicit API Key

Provide the API key directly in configuration:
const mastra = new Mastra({
  agents: [/* agents */],
  tracing: {
    exporters: [
      new TCCMastraExporter({
        apiKey: process.env.TCC_API_KEY,
        debug: process.env.NODE_ENV === 'development',
      }),
    ],
  },
});

With Custom Run IDs

Attach custom run IDs using Mastra’s metadata:
const result = await mastra.agents.myAgent.generate({
  messages: [{ role: 'user', content: 'Explain AI' }],
  metadata: {
    'tcc.runId': 'run_abc123',
  },
});
If tcc.runId is not provided in metadata, a random UUID will be generated automatically.

With Additional Metadata

Attach contextual metadata to your runs:
const result = await mastra.agents.myAgent.generate({
  messages: [{ role: 'user', content: 'What is the weather?' }],
  metadata: {
    'tcc.runId': 'run_123',
    userId: 'user_456',
    environment: 'production',
    feature: 'weather-query',
    version: '1.0.0',
  },
});
All metadata fields (except tcc.runId) are forwarded to The Context Company and appear in the dashboard.

With Debug Logging

Enable detailed logging for troubleshooting:
const mastra = new Mastra({
  agents: [/* agents */],
  tracing: {
    exporters: [
      new TCCMastraExporter({ debug: true }),
    ],
  },
});

// Console will show:
// [TCC] Initialized for service: my-mastra-service
// [TCC] Endpoint: https://api.thecontext.company/v1/mastra
// [TCC] Run ID abc-123 for trace trace_xyz
// [TCC] Started llm span: generate
// [TCC] Ended llm span: generate
// [TCC] Exporting 3 spans for run abc-123
// [TCC] Successfully exported run abc-123

Multiple Exporters

Use TCC alongside other exporters:
import { TCCMastraExporter } from '@contextcompany/mastra';
import { ConsoleExporter } from '@mastra/core/ai-tracing';

const mastra = new Mastra({
  agents: [/* agents */],
  tracing: {
    exporters: [
      new TCCMastraExporter(),
      new ConsoleExporter(), // Also log to console
    ],
  },
});

How It Works

  1. Span Collection: The exporter implements Mastra’s AITracingExporter interface and listens to all tracing events
  2. Event Types: It handles three event types:
    • SPAN_STARTED: When a span begins (agent call, LLM call, tool call)
    • SPAN_UPDATED: When span data changes
    • SPAN_ENDED: When a span completes
  3. Batching: Spans are collected in memory and grouped by trace ID
  4. Root Span Detection: The exporter waits for the root span (top-level agent call) to complete
  5. Batch Export: When the root span ends, all collected spans for that trace are sent to TCC in a single batch
  6. Metadata Extraction: Custom run IDs and metadata from the root span are attached to all spans in the trace

Captured Data

The exporter automatically captures:
  • Agent invocations
  • LLM calls (prompts, responses, tokens, costs)
  • Tool calls (arguments, results)
  • Span timing (start/end times)
  • Span hierarchy (parent-child relationships)
  • Custom metadata from the root span
  • Error states and exceptions

Environment Variables

TCC_API_KEY
string
required
Your Context Company API key. Get one from the dashboard.
TCC_URL
string
Custom ingestion endpoint URL. Overrides the default endpoint.
If TCC_API_KEY is not set and no apiKey is provided in the config, the exporter will throw an error during initialization.

Graceful Shutdown

The exporter provides a shutdown method to ensure all traces are exported before your application exits:
process.on('SIGTERM', async () => {
  console.log('Shutting down...');
  
  // Export any remaining traces
  await mastra.tracing.shutdown();
  
  process.exit(0);
});

Type Safety

The exporter is fully typed and compatible with Mastra’s TypeScript types:
import type { TCCMastraExporterConfig } from '@contextcompany/mastra';
import { TCCMastraExporter } from '@contextcompany/mastra';

const config: TCCMastraExporterConfig = {
  apiKey: 'tcc_abc',
  debug: true,
};

const exporter = new TCCMastraExporter(config);

Next Steps

Mastra Documentation

Learn more about Mastra AI framework

View Traces

View your traces in the dashboard

Build docs developers (and LLMs) love