Skip to content

Observe vMCP code mode: usage-report tool calls, OTel metrics, spans and logs - #7275

Merged
rdimitrov merged 4 commits into
mainfrom
claude/vmcp-codemode-metrics-ed9fe3
Nov 24, 2026
Merged

rdimitrov merged 4 commits into
mainfrom
claude/vmcp-codemode-metrics-ed9fe3

Conversation

@rdimitrov

@rdimitrov rdimitrov commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR adds observability for vMCP code mode (execute_tool_script): the anonymous usage report counts the tool calls scripts make and scripts reached through the optimizer, and operators get per-install OTel metrics, spans and logs for every script.

Two stacked PRs were merged into this branch, so this PR carries all three parts: the OTel part was reviewed and approved by @jerm-dro in #7278, and the optimizer counting came from #7286. Commits: 86f14c235 and 86ab97a0b (usage report), 5c3e8f759 (OTel, #7278), 5c4f74aa8 (optimizer call_tool, #7286).

Usage report: script tool calls

A code mode script (execute_tool_script) makes its tool calls inside vMCP, so they never pass through the HTTP usage middleware. The anonymous usage report counts the script call itself, but not the tool calls it fans out to. The report already has a code_mode_tool_calls field and a collector method for it (#7274); this PR fills it in.

  • codemode.Config.OnScript: an optional ScriptObserver func(ctx, ScriptStats) called once per execute_tool_script call. ScriptStats has one field, ToolCalls: the number of tool calls the script started, including failed and denied ones. It carries no script body, arguments or tool names. Nil (the default) leaves behavior unchanged; a panic in the observer is recovered and logged and never changes the tool result.
  • Counting: each bound tool's Call closure increments an atomic counter, so calls under parallel() count individually. The observer runs after the engine has joined them all. A call that fails before the script runs (invalid arguments, a tool-listing error) reports zero.
  • Wiring: the vMCP CLI sets OnScript, on a copy of the code mode config, to add each script's count to the collector as code_mode_tool_calls. It is never added to count or calls_by_client. With usage metrics disabled, nothing is set.
  • Day-end flushes: script tool calls land when the script returns, so they can be pending while count is zero (a script that straddled midnight, or the last script before shutdown). The midnight flush and the shutdown flush also fire on pending code_mode_tool_calls, still without adding them to count.

Script execution, authorization, limits, results, the code_mode feature flag and calls_by_client attribution are unchanged.

Usage report: scripts reached through the optimizer

With the vMCP optimizer on, clients reach scripts through the optimizer's call_tool meta-tool rather than calling execute_tool_script directly, so code_mode_calls also counts those.

  • pkg/usagemetrics: NewMiddleware takes options. WithCodeModeCall(match) also counts a tools/call as a code mode call when match accepts it. The direct execute_tool_script check is unchanged.
  • pkg/vmcp/cli: vMCP passes that option only when the optimizer is on. Its matcher accepts a call_tool call whose arguments decode, through optimizer.CallToolInput (the same decode authz and dispatch use), to tool_name: execute_tool_script. Plain proxies build their middleware without options, so a backend tool named call_tool is never treated as code mode.
  • docs/middleware.md: code_mode_calls describes both paths.

OTel: metrics, spans and logs

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, the usage part of this PR, stacklok/update-service#492, stacklok/infra#6414), as the comment on #4744 explains. The OTel part adds the per-install 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 are unchanged.

Closes #4743
Closes #4744

Type of change

  • New feature

Test plan

Usage report part:

  • Unit tests: the task test command (go test -race -ldflags=-extldflags=-Wl,-w) on ./pkg/vmcp/codemode/... ./pkg/vmcp/cli/... ./pkg/vmcp/server/... ./pkg/usagemetrics/...
  • Linting: CI-pinned golangci-lint v2.15.0 and go vet on the same packages (local task lint-fix is broken on Go 1.27 export data)

New tests:

  • pkg/vmcp/codemode: the observer gets exactly one call per script with the right count for sequential calls, 25 calls under parallel() with ParallelMax: 4 (under -race), a failed call, no calls, invalid arguments and a transport error; it is not called for other tools; a no-op or panicking observer returns the same result as no observer.
  • pkg/vmcp/cli: the reported code_mode_tool_calls is the sum of the scripts' counts while count stays at the one script call; the caller's config is not changed; code mode off stays nil.

OTel part:

  • 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 (OTel part)

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?

Usage report: Yes, in the anonymous usage report only.
Before: a vMCP report never carried code_mode_tool_calls.
After: with code mode enabled, a vMCP report carries code_mode_tool_calls (tool calls made from inside scripts that day) when it is non-zero. A final report at shutdown, or a previous-day report at midnight, is also sent when the only thing pending is script tool calls.

OTel: 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

  • Accepted shutdown window. The server's HTTP drain gives up after 10s, but a script can run longer, so the final report can miss the tool calls of a script still running at shutdown. Timeouts are left as they are; a comment on codeModeConfig records this.

  • Optimizer. vMCP counts call_tool calls that run a script in code_mode_calls only when the optimizer is on (see the optimizer section above); tests send real JSON-RPC bodies through the parsing and usage middleware, including a nested and a differently cased tool_name.

  • Embedder API. OnScript is also the hook an embedder of server.New can use for its own usage capture; ScriptStats is a struct so fields can be added without breaking it.

  • Synchronous observer. It runs on the request path after the script, and is documented as must-be-cheap and non-blocking. The CLI's observer is one mutex-guarded add.

  • Receiving service. See Report code mode calls in anonymous usage metrics #7274: update-service accepts and drops unknown fields, so storing code_mode_tool_calls depends on stacklok/update-service#492.

🤖 Generated with Claude Code

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 combined diff is large. The OTel commit (5c3e8f759) is the bulk of it and was reviewed on its own in #7278; reviewing commit by commit follows the original split.

🤖 Generated with Claude Code

@github-actions github-actions Bot added the size/L Large PR: 600-999 lines changed label Nov 24, 2026
@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.18750% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.93%. Comparing base (8d64314) to head (5c4f74a).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
pkg/vmcp/codemode/telemetry.go 91.56% 7 Missing ⚠️
pkg/vmcp/cli/serve.go 0.00% 4 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/cli/usage_metrics.go 93.33% 1 Missing ⚠️
pkg/vmcp/codemode/decorator.go 98.21% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7275      +/-   ##
==========================================
+ Coverage   81.86%   81.93%   +0.06%     
==========================================
  Files         915      919       +4     
  Lines       92868    93104     +236     
==========================================
+ Hits        76029    76283     +254     
+ Misses      16834    16816      -18     
  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 16:32
@rdimitrov
rdimitrov force-pushed the claude/vmcp-codemode-metrics-ed9fe3 branch from 71e227e to 7441222 Compare November 24, 2026 16:41
@rdimitrov rdimitrov changed the title Observe code mode scripts with metrics and a callback Report code mode script tool calls in usage metrics Nov 24, 2026
@github-actions github-actions Bot added size/S Small PR: 100-299 lines changed and removed size/L Large PR: 600-999 lines changed labels Nov 24, 2026
@rdimitrov
rdimitrov deleted the branch claude/vmcp-codemode-usage-counts November 24, 2026 19:04
Base automatically changed from claude/vmcp-codemode-usage-counts to main November 24, 2026 19:04
@rdimitrov rdimitrov closed this Nov 24, 2026
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]>
@rdimitrov rdimitrov reopened this Nov 24, 2026
@rdimitrov
rdimitrov force-pushed the claude/vmcp-codemode-metrics-ed9fe3 branch from 7441222 to 86f14c2 Compare November 24, 2026 19:06
@github-actions github-actions Bot added size/M Medium PR: 300-599 lines changed size/S Small PR: 100-299 lines changed and removed size/S Small PR: 100-299 lines changed size/M Medium PR: 300-599 lines changed labels Nov 24, 2026
@rdimitrov
rdimitrov requested a review from jhrozek November 24, 2026 20:38
jhrozek
jhrozek previously approved these changes Nov 24, 2026

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM, the counting and wiring look right to me. I checked that parallel() joins every call before Execute returns (foreach.Concurrent waits on its WaitGroup even when the context is cancelled), so the deferred notify always sees the full count, and both the vmcp binary and thv vmcp serve go through the new wiring. A few nits inline, none blocking.

One thing that isn't from this PR but shows up because of it: with the optimizer on, clients reach execute_tool_script through call_tool, and the middleware only bumps code_mode_calls when the tools/call name is literally execute_tool_script (pkg/usagemetrics/middleware.go:71). So in that setup a report can have code_mode_tool_calls > 0 with code_mode_calls missing. Probably worth a small follow-up that also matches call_tool with tool_name=execute_tool_script, or at least a note next to code_mode_calls in docs/middleware.md.

Comment thread pkg/vmcp/codemode/config.go Resolved
Comment thread pkg/vmcp/cli/usage_metrics.go Resolved
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]>
@rdimitrov

Copy link
Copy Markdown
Member Author

@jhrozek on the call_tool gap: 86ab97a adds a note next to code_mode_calls in docs/middleware.md saying that with the optimizer on, scripts reached through call_tool are not counted, so a report can carry code_mode_tool_calls without code_mode_calls.

The proper fix is small, so I recommend it as a separate follow-up PR: in the middleware, also count a tools/call to call_tool whose tool_name argument is execute_tool_script (the parsed request already carries the arguments). It should only apply to vMCP, because pkg/usagemetrics also runs in plain proxies, where a backend tool could be named call_tool. It also needs a test pinning the names to the optimizer constants.

@rdimitrov
rdimitrov requested a review from jhrozek November 24, 2026 21:18
@github-actions github-actions Bot added size/M Medium PR: 300-599 lines changed and removed size/S Small PR: 100-299 lines changed size/M Medium PR: 300-599 lines changed labels Nov 24, 2026
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]>
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/M Medium PR: 300-599 lines changed labels Nov 24, 2026
@rdimitrov rdimitrov changed the title Report code mode script tool calls in usage metrics Observe vMCP code mode: usage-report tool calls, OTel metrics, spans and logs Nov 24, 2026
@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
jhrozek
jhrozek previously approved these changes Nov 24, 2026
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]>
@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 21:47
@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 2f7695a into main Nov 24, 2026
22 checks passed
@rdimitrov
rdimitrov deleted the claude/vmcp-codemode-metrics-ed9fe3 branch November 24, 2026 21:47
@github-actions github-actions Bot mentioned this pull request Nov 24, 2026
2 tasks
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.

Track code mode adoption and usage Add observability for script execution

2 participants