Skip to content

Add OTel metrics, spans and logs for code mode - #7278

Merged
rdimitrov merged 1 commit into
claude/vmcp-codemode-metrics-ed9fe3from
claude/vmcp-codemode-otel-81ef10
Nov 24, 2026
Merged

rdimitrov merged 1 commit into
claude/vmcp-codemode-metrics-ed9fe3from
claude/vmcp-codemode-otel-81ef10

Conversation

@rdimitrov

@rdimitrov rdimitrov commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Stacked on #7275 (base claude/vmcp-codemode-metrics-ed9fe3).

Operators running vMCP with code mode cannot see how execute_tool_script behaves on their install. There is one debug line per script, and no metric or span. This PR adds per-install OTel observability for code mode: script metrics, tracing and logs (#4743), and the adoption signals in OTel (#4744).

The fleet-wide adoption questions in #4744 are answered by the anonymous usage report (#7145, #7274, #7275, stacklok/update-service#492, stacklok/infra#6414), as the comment on #4744 explains. This PR adds the per-install OTel side, which each operator sees in their own Prometheus.

  • Script metrics under the shared vMCP scope (github.com/stacklok/toolhive/pkg/vmcp), built from the server's MeterProvider, with a status attribute (success / error / timeout / step_limit):
    • toolhive_vmcp_script_executions (counter)
    • toolhive_vmcp_script_duration (histogram, seconds, MCP semconv buckets)
    • toolhive_vmcp_script_tool_calls (histogram of inner tool calls per script)
    • toolhive_vmcp_script_parallel_tasks (counter of callables started by parallel())
  • Adoption gauge: toolhive_vmcp_code_mode_enabled{server} is 1 or 0 on every vMCP server that has telemetry configured, including servers without code mode.
  • Traffic split: no new counter. vMCP's request middleware already counts every tools/call in toolhive_mcp_tool_calls{tool}, and a script counts there once as tool="execute_tool_script". The observability doc has the PromQL.
  • Tracing: a codemode.ExecuteToolScript span per script, with script.tool_count, script.parallel_used, script.parallel_calls, script.parallel_tasks, script.step_count, script.status and script.hash. Each inner tool call gets a codemode.CallTool child span, including calls under parallel(). The backend client span nests under it.
  • Logs: codemode: script started and codemode: script finished at DEBUG, with script_hash, session_id, status, duration, tool_calls, steps, the parallel() counts and error. The script body is never logged.
  • Engine (pkg/script): step-limit failures match script.ErrStepLimitExceeded, including a step limit hit inside a parallel() child. The error message is unchanged. A new optional Config.OnStats reports the step count (script plus parallel() children) and the parallel() fan-out for each Execute.
  • codemode.ScriptStats gains Outcome, Duration, Steps, ParallelCalls and ParallelTasks. The OnScript signature and the code_mode_tool_calls usage field from Observe vMCP code mode: usage-report tool calls, OTel metrics, spans and logs #7275 are unchanged.

Closes #4743
Closes #4744

Type of change

  • New feature

Test plan

  • Unit tests (go test -race on pkg/script/..., pkg/vmcp/codemode/..., pkg/vmcp/server/..., pkg/vmcp/cli/...)
  • Linting (CI-pinned golangci-lint v2.15.0 on pkg/script/..., pkg/vmcp/codemode/..., pkg/vmcp/server/...: 0 issues)
  • Manual testing (describe below)

New tests:

  • Outcome classification for every path, including a step limit inside a parallel() child, an inner-call timeout whose error does not wrap the deadline, and argument errors.
  • Metrics through an SDK ManualReader: exact counts per status, tool call sums and parallel() tasks.
  • Span parenting through a tracetest.SpanRecorder: the script span is a child of the request span, there is one codemode.CallTool child per inner call (including those under parallel()), and the backend sees the inner call span as current.
  • The span status of a failed script never carries the error text.
  • With no Telemetry configured, the caller's span stays current and nothing is recorded. NewTelemetry(nil, nil) is a working no-op.
  • The logs contain neither a secret placed in the script nor the script body, and they do carry hash, session ID, status, duration, tool call count and error.
  • pkg/script: ErrStepLimitExceeded at top level and in parallel(), OnStats counts nested parallel() calls and children's steps, and runs once even on failure.
  • Integration (TestIntegration_CodeModeTelemetry): a real vMCP server with code mode on runs a parallel() script over HTTP. Scraping /metrics shows toolhive_mcp_tool_calls_total{tool="execute_tool_script"} 1, no request-level sample for the inner tool, the four script metrics with exact values, and toolhive_vmcp_code_mode_enabled 1. With code mode off, the gauge is 0 and no script metrics appear.

task lint-fix cannot run on this machine (local golangci-lint cannot read Go 1.27 export data), so lint ran through go run of the CI-pinned version. E2E is left to CI.

Changes

File Change
pkg/script/internal/core/{execute,stats}.go ErrStepLimitExceeded through OnMaxSteps; per-execution step and parallel() counters on the thread
pkg/script/internal/builtins/parallel.go Children inherit OnMaxSteps and the counters; parallel() reports its task count
pkg/script/{script,executor}.go Public ErrStepLimitExceeded, Stats, Config.OnStats
pkg/vmcp/codemode/observer.go ScriptOutcome, the extended ScriptStats, outcome classification
pkg/vmcp/codemode/telemetry.go Telemetry instruments and spans (NewTelemetry)
pkg/vmcp/codemode/decorator.go, config.go Spans, logs, stats and Config.Telemetry wired into execute_tool_script
pkg/vmcp/server/code_mode_telemetry.go, server.go Attach telemetry when a provider is set; register the code_mode_enabled gauge
docs/operator/virtualmcpserver-observability.md Code mode metrics, spans, logs and example PromQL

Does this introduce a user-facing change?

Yes, for operators with vMCP telemetry configured:

  • Before: code mode produced no metrics or spans, and one DEBUG line per script with the principal and script length.
  • After: /metrics exposes toolhive_vmcp_code_mode_enabled on every vMCP server, and the four toolhive_vmcp_script_* metrics when code mode is on. Traces gain codemode.ExecuteToolScript and codemode.CallTool spans. The DEBUG log now has a start line and a finish line, keyed by script hash and session ID.

Script results, error messages, limits, authorization and the usage-report fields do not change.

Special notes for reviewers

Naming. Every vMCP metric in this repo uses toolhive_vmcp_* underscore names (backend, workflow and optimizer metrics, and toolhive_vmcp_backend_revision_reclassifications, which is recent). No toolhive metric uses the dotted stacklok.<service>.* form, and there is no migration switch, so this PR follows the repo and the names in #4743. The outcome attribute is status, as #4743 asks and as the toolhive_mcp_* metrics already use.

Where this differs from the acceptance criteria. Each difference is deliberate, and the issues' owner accepted them as the criteria for closing both.

  • Add observability for script execution #4743 asks for toolhive_vmcp_script_parallel_goroutines. parallel() runs its callables on a pool of at most ParallelMax goroutines (foreach.Concurrent), so a goroutine count mostly echoes the config. toolhive_vmcp_script_parallel_tasks counts the callables, which is the real fan-out. Accepted criterion: "counter toolhive_vmcp_script_parallel_tasks increments by the number of callables each parallel() call starts."
  • Track code mode adoption and usage #4744 asks for a new toolhive_vmcp_tool_calls{method} counter. toolhive_mcp_tool_calls{tool} already counts every vMCP tools/call with the tool name, so a second counter would double count. The doc has the PromQL, and the integration test proves the split. Accepted criterion: "the split is queryable from toolhive_mcp_tool_calls{tool="execute_tool_script"}, with example PromQL in the observability doc."
  • Track code mode adoption and usage #4744 suggests the label vmcp_server_name on the gauge. It uses server instead, the label toolhive_mcp_tool_calls carries, so the two join. The gauge is fixed per process: the operator rolls the vMCP pod when its config changes, so "updated on configuration change" holds.

Logging level. Start and finish lines are DEBUG, including on failure. A failed script is the caller's mistake and can happen at request rate (.claude/rules/go-style.md: silent success, callers do not set WARN volume). toolhive_vmcp_script_executions{status!="success"} is the operator signal.

Session ID. core.VMCP.CallTool has no session parameter, so the decorator reads it with server.ClientSessionFromContext for logs only. Stateless Modern requests have no session, and their session_id is empty.

Error text. Spans record the outcome only, never the error message, because Starlark errors can quote script data. The DEBUG log carries the message the caller already received.

Telemetry cannot break a script. A nil Telemetry leaves the context and spans untouched. Recording is synchronous and non-blocking, and a panic while recording metrics is recovered. OnStats runs on the Execute goroutine before it returns.

Size. The non-test, non-doc diff is about 690 lines across 11 files, over the 400-line guideline, and much of it is doc comments. If reviewers prefer, it splits cleanly into (1) the pkg/script changes (ErrStepLimitExceeded, Stats / OnStats) and (2) the codemode and server telemetry stacked on top.

🤖 Generated with Claude Code

@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Nov 24, 2026
@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.18182% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.88%. Comparing base (86ab97a) to head (8ce4408).
⚠️ Report is 1 commits behind head on claude/vmcp-codemode-metrics-ed9fe3.

Files with missing lines Patch % Lines
pkg/vmcp/codemode/telemetry.go 91.56% 7 Missing ⚠️
pkg/script/internal/core/stats.go 82.35% 3 Missing ⚠️
pkg/vmcp/server/code_mode_telemetry.go 91.30% 2 Missing ⚠️
pkg/vmcp/server/server.go 71.42% 2 Missing ⚠️
pkg/vmcp/codemode/decorator.go 98.21% 1 Missing ⚠️
Additional details and impacted files
@@                           Coverage Diff                           @@
##           claude/vmcp-codemode-metrics-ed9fe3    #7278      +/-   ##
=======================================================================
+ Coverage                                81.85%   81.88%   +0.03%     
=======================================================================
  Files                                      916      919       +3     
  Lines                                    92886    93089     +203     
=======================================================================
+ Hits                                     76031    76226     +195     
- Misses                                   16850    16858       +8     
  Partials                                     5        5              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@rdimitrov
rdimitrov marked this pull request as ready for review November 24, 2026 17:53
@rdimitrov
rdimitrov force-pushed the claude/vmcp-codemode-metrics-ed9fe3 branch from 7441222 to 86f14c2 Compare November 24, 2026 19:06
@rdimitrov
rdimitrov force-pushed the claude/vmcp-codemode-otel-81ef10 branch from c65e842 to 6d73c51 Compare November 24, 2026 19:10
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 24, 2026
@rdimitrov
rdimitrov requested a review from jhrozek November 24, 2026 20:38
Operators running vMCP with code mode cannot see how scripts behave:
there is one debug line per script and no metric or span. Add
per-install observability for execute_tool_script.

- Metrics under the vMCP scope: toolhive_vmcp_script_executions,
  _duration, _tool_calls and _parallel_tasks, split by a status
  attribute (success, error, timeout, step_limit), plus a
  toolhive_vmcp_code_mode_enabled gauge on every server.
- A codemode.ExecuteToolScript span per script with a
  codemode.CallTool child per inner call, under parallel() too.
- Debug logs for script start and finish keyed by a script hash and
  session ID; the script body is never logged.

The engine marks step-limit failures with script.ErrStepLimitExceeded,
including inside parallel() children, and reports step count and
parallel() fan-out through an optional Config.OnStats. Script results,
limits and error messages are unchanged.

Part of #4743
Part of #4744

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@rdimitrov
rdimitrov force-pushed the claude/vmcp-codemode-otel-81ef10 branch from 6d73c51 to 8ce4408 Compare November 24, 2026 21:20
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 24, 2026

@jerm-dro jerm-dro left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. The deviations from #4743 and #4744 are fine (reusing toolhive_mcp_tool_calls{tool} for the split, the server label, and parallel_tasks), so switch to Closes #4743 / Closes #4744.

@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 24, 2026
@rdimitrov
rdimitrov merged commit 5c3e8f7 into claude/vmcp-codemode-metrics-ed9fe3 Nov 24, 2026
28 checks passed
@rdimitrov
rdimitrov deleted the claude/vmcp-codemode-otel-81ef10 branch November 24, 2026 21:32
rdimitrov added a commit that referenced this pull request Nov 24, 2026
…and logs (#7275)

* Report code mode script tool calls in usage

Tool calls a code mode script makes run inside vMCP and never reach
the HTTP usage middleware, so the usage report does not see them.
Add an optional OnScript observer to codemode.Config that receives
the number of tool calls each script made, and have the vMCP CLI add
it to the report as code_mode_tool_calls, separate from count.

Part of #4744

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Report pending script tool calls at day end

Code mode script tool calls land when a script returns, so they can be
pending while the day's count is zero: a script that straddled midnight,
or the last script before shutdown. The midnight flush and the shutdown
flush now also fire on pending code_mode_tool_calls, without adding them
to count.

Also align the OnScript doc with ScriptStats ("started", including
failed and denied calls), note the accepted shutdown window for scripts
still running past the HTTP drain, and document that code_mode_calls
misses scripts reached through the optimizer's call_tool.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add OTel metrics, spans and logs for code mode (#7278)

Operators running vMCP with code mode cannot see how scripts behave:
there is one debug line per script and no metric or span. Add
per-install observability for execute_tool_script.

- Metrics under the vMCP scope: toolhive_vmcp_script_executions,
  _duration, _tool_calls and _parallel_tasks, split by a status
  attribute (success, error, timeout, step_limit), plus a
  toolhive_vmcp_code_mode_enabled gauge on every server.
- A codemode.ExecuteToolScript span per script with a
  codemode.CallTool child per inner call, under parallel() too.
- Debug logs for script start and finish keyed by a script hash and
  session ID; the script body is never logged.

The engine marks step-limit failures with script.ErrStepLimitExceeded,
including inside parallel() children, and reports step count and
parallel() fan-out through an optional Config.OnStats. Script results,
limits and error messages are unchanged.

Part of #4743
Part of #4744

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Count code mode calls made through the optimizer's call_tool (#7286)

Count code mode calls made through call_tool

With the vMCP optimizer on, clients reach code mode scripts through the
optimizer's call_tool meta-tool, so code_mode_calls missed them and a
report could show code_mode_tool_calls with no code_mode_calls.

The usage middleware gains a WithCodeModeCall option. vMCP sets it when
the optimizer is on, matching call_tool whose decoded target is
execute_tool_script. Plain proxies never set it, since a backend there
may have its own tool named call_tool.

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants