Custom agents (OpenTelemetry Integration)

Monte Carlo works with any agent instrumented with OpenTelemetry, in any language or framework. Point your OTLP exporter at your Agent Observability Data Platform and your agent gets everything in Agent Trust: Bayes finds what's breaking it and proposes fixes.

Snowflake Cortex and Databricks AI/BI Genie & AgentBricks agents don't require OpenTelemetry instrumentation. Monte Carlo reads their traces through your existing warehouse connection — see Platform-native agents.

Before you start

1. Deploy the Agent Observability Data Platform. Every OpenTelemetry agent sends traces to it, so it comes first.

See Agent Observability Data Platform for architecture and prerequisites.

How you run itWhat to do
Self-hosted in your own cloud accountDeploy: AWS · Azure · GCP — then connect it to Monte Carlo
Monte Carlo-hostedInterested in Monte Carlo hosting the data platform? Reach out to your Monte Carlo representative. You'll get an endpoint and credentials.

2. Pick your path.

Your agentDo this
Already instrumented with OpenTelemetryFollow steps 1–4 below. In Node.js, see Already using OpenTelemetry instead.
Python, no OpenTelemetry yetInstall the Monte Carlo SDK and call mc.setup() (see Using the Monte Carlo SDK below). Or run the instrument-agent skill from the Agent Toolkit in Claude Code, Cursor, or similar. Either way, then do steps 2–4.
Node.jsNo Monte Carlo SDK is needed. With no OpenTelemetry yet, use the OpenTelemetry Node SDK with an OpenLLMetry instrumentation (see Node.js Integration), or the Vercel AI SDK's own tracing. Already using OpenTelemetry: see Already using OpenTelemetry.
Built on Google ADKADK emits traces natively, but capturing prompts and completions takes runtime-specific setup for Python and Go. See Google ADK Integration.
Already exporting to another backendRead Already exporting to another backend first, then follow steps 1–4.

To collect ratings and comments from your users, also follow Capture end-user feedback after traces are arriving.

Using the Monte Carlo SDK

  • Call mc.setup() with your agent's name (agent_name, its name in Monte Carlo), your traces URL from step 1, and the instrumentor for your LLM library or framework (instrumentors=[...]). Without an instrumentor, no LLM spans are created unless you create them yourself.
  • mc.setup() sets up the exporter and the attribute limit from step 2, and reads Monte Carlo-hosted credentials from MCD_DEFAULT_API_ID / MCD_DEFAULT_API_TOKEN.
  • Call it before any library that sets its own tracer provider. If one is already set, mc.setup() doesn't apply its exporter, attribute limit or Monte Carlo span attributes, and logs a warning. To keep that provider, call mc.add_processor() and mc.add_exporter("<your-otlp-traces-url>") instead of mc.setup(), after the provider is created, and call .instrument() on your instrumentors yourself. The provider's attribute limit and service name are already fixed, so set OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT=1024 and OTEL_SERVICE_NAME in the environment that starts the process.
  • The SDK also adds workflow tagging decorators.

1. Point your exporter at the Data Platform

export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=<your-otlp-traces-url>
export OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_TRACES_COMPRESSION=gzip
export OTEL_BSP_MAX_EXPORT_BATCH_SIZE=128
export OTEL_SERVICE_NAME=<your-agent-name>
# Monte Carlo-hosted only:
export OTEL_EXPORTER_OTLP_TRACES_HEADERS="x-mcd-id=<your-api-id>,x-mcd-token=<your-api-token>"
  • Endpoint: your Data Platform's OTLP traces URL, ending in /v1/traces. The variable is used exactly as given, with no path appended. For Monte Carlo-hosted deployments, use the URL Monte Carlo provides. On a self-hosted Data Platform on AWS, use https://<otel_collector_domain>:4318/v1/traces, with the collector domain you set at deploy time. On GCP and Azure, send to its gateway on port 443.
  • Protocol: http/protobuf. Some SDKs, Python's included, default to gRPC, and the Monte Carlo-hosted collector accepts only OTLP/HTTP. The variable applies only when the SDK builds the exporter from environment variables. If you create the exporter in code, use the OTLP/HTTP exporter, such as opentelemetry-exporter-otlp-proto-http in Python.
  • Compression: gzip keeps requests small when spans carry full prompts and completions.
  • Batch size: OTEL_BSP_MAX_EXPORT_BATCH_SIZE sets how many spans the batch span processor sends per request. Use 128, down from OpenTelemetry's default of 512. GenAI spans can be several MB each, and the collector rejects a request over its size limit with a 400, dropping every span in it. In Python, the variable applies when the batch span processor is created without its own batch size, and the Monte Carlo SDK's mc.setup() sets 128 for you. In Node.js, the BatchSpanProcessor from @opentelemetry/sdk-trace doesn't read the variable, so pass it maxExportBatchSize: 128, as in Node.js Integration.
  • Credentials: only Monte Carlo-hosted deployments need them. Use the x-mcd-id / x-mcd-token Monte Carlo provides. A self-hosted Data Platform needs no Monte Carlo credentials. Its collector doesn't check them, and Monte Carlo's deployment modules put it behind an internal load balancer.
  • Use the _TRACES_ variables, not the bare OTEL_EXPORTER_OTLP_ENDPOINT / OTEL_EXPORTER_OTLP_HEADERS. The bare endpoint also applies to the metrics and logs exporters. Monte Carlo ingests only traces, and a Monte Carlo-hosted collector rejects metrics and logs with 403 errors in your agent's logs.

Serverless runtimes

AWS Lambda, Cloud Run and other runtimes that freeze the process between invocations lose spans the batch span processor hasn't exported yet, because it exports on a timer. Call your tracer provider's force_flush() before each invocation returns, or, in Python, use SimpleSpanProcessor, which exports each span as it ends. With the Monte Carlo SDK, pass it as mc.setup(span_processor=...). A custom span processor replaces the SDK's default exporter, so configure compression and credentials on it yourself. See the SDK README for an example. In Node.js, NodeSDK has no flush method, so await the forceFlush() of each BatchSpanProcessor instead. See Node.js Integration.

2. Capture prompts and completions

Monte Carlo reads prompts and completions in these standard formats, not a Monte Carlo-specific one:

  • OpenTelemetry's GenAI semantic conventions: the gen_ai.input.messages / gen_ai.output.messages attributes, the older gen_ai.prompt.<n>.* / gen_ai.completion.<n>.* attributes, or the gen_ai.user.message, gen_ai.assistant.message and gen_ai.choice span events.
  • OpenInference: llm.input_messages / llm.output_messages.

Content in other attributes, such as OpenInference's input.value / output.value, isn't read as prompts or completions. Many instrumentation libraries don't capture message content by default, so turn it on to get the full capabilities of Agent Trust.

For OpenTelemetry's Python GenAI instrumentations and Python ADK, set:

OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=SPAN_ONLY

The OpenLLMetry instrumentors used in the Monte Carlo SDK examples capture content by default, so you don't need these. TRACELOOP_TRACE_CONTENT=false turns capture off, including the conversation input and output Monte Carlo groups into conversations.

Other instrumentation libraries have their own content setting. Check their docs.

Whatever you use, raise the span attribute limit:

OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT=1024

mc.setup() in the Monte Carlo SDK sets this for you. Otherwise, don't skip it. GenAI spans regularly go past OpenTelemetry's default of 128 attributes, and attributes over the limit are dropped without an error.

3. Group conversations and tag workflows

  • Conversations: set gen_ai.conversation.id (or OpenInference's session.id) on every span in a conversation, not just the first. If a span carries both, session.id is used. A montecarlo.association_properties.thread_id takes precedence over both. LangGraph agents that pass a thread_id in their run config get it automatically with the Monte Carlo SDK. Other agents can set it with create_span_with_attributes("turn", {"association_properties.thread_id": conversation_id}), which also sets it on every child span. Reinforcement Loop and Conversation Clusters both work on conversations. In Node.js, see Node.js Integration.
  • Workflows and tasks: set montecarlo.workflow and montecarlo.task on every span in the workflow or task, like the conversation ID. The Monte Carlo SDK's trace_with_workflow / trace_with_task decorators and create_span_with_workflow / create_span_with_task context managers do this for you. Otherwise, set them with your language's OpenTelemetry API, the same way you'd set any custom span attribute. In Node.js, see Node.js Integration.

4. Confirm traces are arriving

Run your agent, then open Agents. Once traces are written, the agent appears on its own. Monte Carlo looks for new agents every 30 minutes, so it may not appear right away. Open the agent and check its Health or Activity card for incoming traces.

Not showing up? Check, in order:

  1. You used OTEL_EXPORTER_OTLP_TRACES_*, not the bare OTEL_EXPORTER_OTLP_* variables, and your exporter sends OTLP/HTTP, not gRPC.
  2. The endpoint ends in /v1/traces. On Monte Carlo-hosted, a wrong path returns 403 with Missing Authentication Token, even when the credentials are valid. A 403 with No data store is associated with this integration key means the key isn't set up for traces. Ask Monte Carlo to fix it. A 401 has one of three causes. The credentials are missing, or wrapped in quotes, which .env files often keep as part of the value. They aren't the ones Monte Carlo provided with that endpoint: a key minted for another Monte Carlo environment is rejected. Or the agent's IP isn't in your account's IP allowlist. On self-hosted, confirm the agent can reach the collector's private address from its network.
  3. Traces arrive but prompts or completions are missing: content capture is off, content goes to log events instead of span attributes (use SPAN_ONLY, or for an OpenLLMetry instrumentor, don't pass use_attributes=False, or use_legacy_attributes=False in older versions), or spans are over the attribute limit (step Capture prompts and completions).
  4. Each turn shows up as its own conversation: each turn sends a different conversation ID. Send the same gen_ai.conversation.id (or session.id) on every turn (step Group conversations and tag workflows). A trace with no conversation ID doesn't appear in conversations.
  5. The agent appears as unknown_service: set OTEL_SERVICE_NAME in the environment that starts the process, not in a file your code loads later.
  6. Self-hosted and still no agent: see No agents appear on the Agents page.

5. Capture end-user feedback (optional)

Let your users give feedback on your agent's answers: a thumbs-up or thumbs-down, categories, a comment, or any combination. Monte Carlo shows the latest feedback on the trace that produced the answer.

Monte Carlo doesn't add feedback buttons to your app. You add them, and your server sends the feedback:

  1. While the agent answers, capture its trace ID.
  2. Save or return that ID with the answer so the app keeps it with the right feedback button.
  3. When the user submits feedback, send it to your server with that trace ID.

Your server checks which signed-in user submitted the feedback and sends it to Monte Carlo. Keep Monte Carlo credentials on your server, never in the browser.

Choose how to send it: Python apps can use the SDK helper below. Google ADK and apps in other languages can use their existing OpenTelemetry tracing setup; see Send feedback with plain OpenTelemetry. Monte Carlo-hosted deployments also support a REST endpoint, linked in that section.

Prepare your deployment

  • Trace storage: feedback is supported for custom agents whose traces are stored in the Agent Observability Data Platform. It isn't supported for traces read from warehouse tables.
  • Data Platform version: for a self-hosted deployment, upgrade the Helm chart to 6.0.0 or later and finish both the database schema job and collector rollout before sending feedback. Follow the Helm 6.0.0 upgrade instructions. For a Monte Carlo-hosted deployment, confirm with your Monte Carlo representative that feedback is available at your endpoint.
  • Python SDK helper: use montecarlo-opentelemetry 0.6.0 or later, with the tracing setup described above. The process handling feedback must have a Monte Carlo exporter registered through mc.setup() or mc.add_exporter(), using the same destination and credentials as the agent's traces. The plain OpenTelemetry example below doesn't need the Monte Carlo SDK.

Feedback sent before the chart upgrade won't appear as feedback in Monte Carlo, even after upgrading. Chart versions earlier than 6.0.0 store it as ordinary traces, which remain until the deployment's retention period expires.

pip install "montecarlo-opentelemetry>=0.6.0"

If your existing code adds a Monte Carlo exporter directly to the tracer provider, use plain OpenTelemetry. record_feedback() doesn't use exporters registered that way, and adding another exporter would send ordinary traces twice.

Remove sensitive text before sending it. Redact the comment before calling record_feedback(), or in on_end() of the custom span_processor passed to mc.setup(). A scrubber added separately with provider.add_span_processor() won't see this feedback. See the SDK reference below for custom processor setup.

Keep the trace ID with the answer

Capture the ID while the agent is answering, and return or save it with that answer. Adapt this example to your existing answer handler after configuring the SDK:

import montecarlo_opentelemetry as mc

def answer(question):
    with mc.get_tracer().start_as_current_span("answer"):
        answer_trace_id = mc.current_trace_id()
        result = run_agent(question)  # Your existing agent call.
        return {"answer": result, "trace_id": answer_trace_id}

Keep this trace_id with the displayed answer so its feedback button sends back the right ID. Enable the feedback button only when this ID is present. Don't get the current trace ID in the later feedback request: that would identify the feedback request itself. Outside an active span, mc.current_trace_id() returns None.

Submit feedback from your backend

When the user submits feedback, pass the saved answer's trace ID and the agent's exact name as it appears in Monte Carlo. In this example, saved_answer is the answer associated with that user's feedback request:

from datetime import datetime, timezone
from uuid import uuid4

import montecarlo_opentelemetry as mc

# Create this event once on your server for this user action.
feedback_event = {
    "agent_name": "support-agent",  # Match the name on the original trace.
    "trace_id": saved_answer["trace_id"],
    "rating": "negative",
    "categories": ["incorrect"],
    "comment": "The answer used the wrong table.",
    "event_id": str(uuid4()),
    "submitted_at": datetime.now(timezone.utc),
}

accepted = mc.record_feedback(**feedback_event)

Use rating="positive" for a thumbs-up. Categories and comments are optional. Check accepted before telling your app the submission was accepted:

  • True means the SDK's processors accepted the feedback for processing. It doesn't prove the feedback reached storage.
  • False means the SDK couldn't accept the feedback: for example, the input is invalid, no Monte Carlo exporter is registered, tracing is disabled, or the provider has shut down. These failures log a warning at most once per reason every 60 seconds rather than raising an exception. Report the failure to your app; don't silently treat it as a successful submission.

Limit comments to 4096 UTF-8 bytes and categories to 20 entries, each at most 128 UTF-8 bytes. These are byte limits, not character counts: accented characters and emoji can use more than one byte. Validate them on your server before sending; over-limit input returns False rather than being shortened.

Edits and removal: each call replaces the complete feedback state for that trace. Include the current rating, categories and comment when editing any of them. Omitting the rating means no rating, rather than keeping the previous one. To remove feedback, send rating="none" with no categories or comment. Monte Carlo displays the latest state for the whole trace, including when several users rate it.

Retries: if your application retries a submission, reuse the same feedback_event, including its event_id and submitted_at. Create a new ID and timestamp for each new user change, including removal. This keeps an older retry from replacing newer feedback.

Process shutdown: after requests and background work finish, call trace.get_tracer_provider().shutdown() from the app's existing shutdown handler (trace is imported from opentelemetry). In an async handler, use await asyncio.to_thread(trace.get_tracer_provider().shutdown) after importing asyncio. Don't rely on Python exit hooks alone. For serverless apps, follow Serverless runtimes before each invocation returns.

If several apps share the provider, flush with mc.flush_feedback(timeout_millis=1000) when each app stops, then shut down the provider once it is no longer needed. In an async handler, use await asyncio.to_thread(mc.flush_feedback, timeout_millis=1000). Keep the app's existing cleanup; see the SDK reference below for full shutdown examples and timeout behavior.

Send feedback with plain OpenTelemetry

Use your existing OpenTelemetry setup to send a span named user_feedback to the same destination as the answer's traces. No Monte Carlo SDK is required. The following Node.js example uses the setup in Node.js Integration; Java, Go and other OpenTelemetry SDKs use the same span name and attribute keys. Start feedback as a new root span in each language, rather than a child of the request handling the click.

First, keep the trace ID with the answer, while its span is active:

const { trace, isSpanContextValid } = require("@opentelemetry/api");
const agentTracer = trace.getTracer("support-agent");

async function answer(question) {
  return agentTracer.startActiveSpan("answer", async (span) => {
    try {
      const spanContext = span.spanContext();
      const traceId = isSpanContextValid(spanContext) ? spanContext.traceId : null;
      const result = await runAgent(question); // Your existing agent call.
      return { answer: result, trace_id: traceId };
    } finally {
      span.end();
    }
  });
}

Keep that trace_id with the answer's feedback button, and enable the button only when the ID is present. When clicked, the button sends the saved ID and feedback to your server. Check the user, trace ID and submitted values, and remove any sensitive text. Create and save one feedbackEvent on your server for that user action, containing the complete feedback state and submitted_at: new Date().toISOString(). Keep that same event and time for retries; don't take the time from the browser or recreate it inside the retrying function:

function recordButtonFeedback(feedbackEvent) {
  const submittedAt = new Date(feedbackEvent.submitted_at);
  const span = agentTracer.startSpan("user_feedback", {
    root: true,
    startTime: submittedAt,
    attributes: {
      "gen_ai.evaluation.name": "user_feedback",
      "gen_ai.evaluation.evaluator.type": "human",
      "montecarlo.agent_name": "support-agent", // Match the original agent.
      "montecarlo.feedback.trace_id": feedbackEvent.trace_id,
      "gen_ai.evaluation.explanation": feedbackEvent.comment ?? "",
      "montecarlo.feedback.categories": feedbackEvent.categories ?? [],
    },
  });
  if (feedbackEvent.rating != null) {
    span.setAttribute("gen_ai.evaluation.score.label", feedbackEvent.rating);
  }
  span.end(submittedAt);
}

Use positive or negative for a rating, or omit it for feedback with only a comment or categories. To remove feedback, send none, an empty comment and no categories. Each submission replaces the complete previous state, just like the Python helper.

Retries: reuse the original event's complete state and submission time. Monte Carlo orders feedback by the span's start time, so an older retry won't replace an edit with a later timestamp. Give each edit or removal a new time. Each call still creates new span IDs, so retries can create duplicate stored records. JavaScript dates have millisecond precision; if two changes share a timestamp, Monte Carlo may show either one.

Sampling: root: true prevents feedback from inheriting an HTTP request's sampling decision. Your root sampler must still keep user_feedback spans, as must the collector. Filter them out of other destinations if needed, and use your existing flush or shutdown steps to send queued spans.

For an ADK callback that saves the trace ID with each answer, LangGraph run IDs, Python shutdown examples, and the Monte Carlo-hosted REST endpoint, see End-user feedback in the public SDK reference. The REST endpoint is available only with Monte Carlo-hosted ingestion; self-hosted deployments use the collector through the SDK or plain OpenTelemetry.

Check that feedback appears

  1. Run the agent and submit a rating and comment through your application's feedback controls.
  2. In Monte Carlo, open Agents → your agent, then select Traces in the Activity card. For code-based agents, the Feedback column appears after Monte Carlo detects the agent's first stored feedback. If it is missing after submitting and refreshing, follow the checks below. Otherwise, open the matching trace to check its rating and comment. Comment text follows your account's content access rules, including the agent-observability/content permission; see the content access guide.
  3. Edit the feedback, then remove it, and refresh the trace after each change to confirm the displayed state updates.

If feedback doesn't appear, check in order:

  1. The original trace arrived and is still retained. The feedback's trace ID and agent name must match it.
  2. The Python helper returned True, and the feedback process has a Monte Carlo exporter registered. If it returned False, check the input limits and setup above. For plain OpenTelemetry, check the exporter's logs instead.
  3. The app sent its queued spans before shutdown, and the collector preserves user_feedback spans when sampling. Plain OpenTelemetry also needs the application's sampler to preserve them. Feedback can't restore an agent trace that sampling discarded.
  4. If you see “Some feedback could not be matched to a trace,” feedback received more than 24 hours ago has no matching stored trace for that agent. Check its trace or run ID and whether the original trace expired. Its absence doesn't prove every submission matched.

Already exporting to another backend

If you already send traces to CloudWatch, Application Insights, or another backend, add Monte Carlo as a second exporter. Don't replace your existing one.

The environment variables in step 1 configure only one exporter. Set up the Monte Carlo exporter in code or in your OpenTelemetry Collector, with its own endpoint and its own headers. Use the endpoint, protocol and compression from step 1, but not its environment variables.

Don't put x-mcd-id / x-mcd-token in shared header configuration such as OTEL_EXPORTER_OTLP_HEADERS or OTEL_EXPORTER_OTLP_TRACES_HEADERS. Every OTLP exporter that reads these variables sends them. In OpenTelemetry Python 1.45 or later and in OpenTelemetry JavaScript, that includes an OTLP/HTTP exporter that sets its own headers in code. Your Monte Carlo credentials would reach your other backend, and credentials you keep in these variables for your other backend would reach Monte Carlo. Set each backend's credentials on its own exporters instead.

Using Node.js? See Already using OpenTelemetry on the Node.js page.

Next steps


Did this page help you?