Repository navigation
Observe vMCP code mode: usage-report tool calls, OTel metrics, spans and logs - #7275
Conversation
Codecov Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
71e227e to
7441222
Compare
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]>
7441222 to
86f14c2
Compare
jhrozek
left a comment
There was a problem hiding this comment.
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.
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]>
|
@jhrozek on the The proper fix is small, so I recommend it as a separate follow-up PR: in the middleware, also count a |
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 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]>
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:
86f14c235and86ab97a0b(usage report),5c3e8f759(OTel, #7278),5c4f74aa8(optimizercall_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 acode_mode_tool_callsfield and a collector method for it (#7274); this PR fills it in.codemode.Config.OnScript: an optionalScriptObserver func(ctx, ScriptStats)called once perexecute_tool_scriptcall.ScriptStatshas 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.Callclosure increments an atomic counter, so calls underparallel()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.OnScript, on a copy of the code mode config, to add each script's count to the collector ascode_mode_tool_calls. It is never added tocountorcalls_by_client. With usage metrics disabled, nothing is set.countis zero (a script that straddled midnight, or the last script before shutdown). The midnight flush and the shutdown flush also fire on pendingcode_mode_tool_calls, still without adding them tocount.Script execution, authorization, limits, results, the
code_modefeature flag andcalls_by_clientattribution are unchanged.Usage report: scripts reached through the optimizer
With the vMCP optimizer on, clients reach scripts through the optimizer's
call_toolmeta-tool rather than callingexecute_tool_scriptdirectly, socode_mode_callsalso counts those.pkg/usagemetrics:NewMiddlewaretakes options.WithCodeModeCall(match)also counts atools/callas a code mode call whenmatchaccepts it. The directexecute_tool_scriptcheck is unchanged.pkg/vmcp/cli: vMCP passes that option only when the optimizer is on. Its matcher accepts acall_toolcall whose arguments decode, throughoptimizer.CallToolInput(the same decode authz and dispatch use), totool_name: execute_tool_script. Plain proxies build their middleware without options, so a backend tool namedcall_toolis never treated as code mode.docs/middleware.md:code_mode_callsdescribes both paths.OTel: metrics, spans and logs
Operators running vMCP with code mode cannot see how
execute_tool_scriptbehaves 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.
github.com/stacklok/toolhive/pkg/vmcp), built from the server'sMeterProvider, with astatusattribute (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 byparallel())toolhive_vmcp_code_mode_enabled{server}is 1 or 0 on every vMCP server that has telemetry configured, including servers without code mode.tools/callintoolhive_mcp_tool_calls{tool}, and a script counts there once astool="execute_tool_script". The observability doc has the PromQL.codemode.ExecuteToolScriptspan per script, withscript.tool_count,script.parallel_used,script.parallel_calls,script.parallel_tasks,script.step_count,script.statusandscript.hash. Each inner tool call gets acodemode.CallToolchild span, including calls underparallel(). The backend client span nests under it.codemode: script startedandcodemode: script finishedat DEBUG, withscript_hash,session_id,status,duration,tool_calls,steps, theparallel()counts anderror. The script body is never logged.pkg/script): step-limit failures matchscript.ErrStepLimitExceeded, including a step limit hit inside aparallel()child. The error message is unchanged. A new optionalConfig.OnStatsreports the step count (script plusparallel()children) and theparallel()fan-out for eachExecute.codemode.ScriptStatsgainsOutcome,Duration,Steps,ParallelCallsandParallelTasks. TheOnScriptsignature and thecode_mode_tool_callsusage field are unchanged.Closes #4743
Closes #4744
Type of change
Test plan
Usage report part:
task testcommand (go test -race -ldflags=-extldflags=-Wl,-w) on./pkg/vmcp/codemode/... ./pkg/vmcp/cli/... ./pkg/vmcp/server/... ./pkg/usagemetrics/...go veton the same packages (localtask lint-fixis 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 underparallel()withParallelMax: 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 reportedcode_mode_tool_callsis the sum of the scripts' counts whilecountstays at the one script call; the caller's config is not changed; code mode off stays nil.OTel part:
go test -raceonpkg/script/...,pkg/vmcp/codemode/...,pkg/vmcp/server/...,pkg/vmcp/cli/...)pkg/script/...,pkg/vmcp/codemode/...,pkg/vmcp/server/...: 0 issues)New tests:
parallel()child, an inner-call timeout whose error does not wrap the deadline, and argument errors.ManualReader: exact counts perstatus, tool call sums andparallel()tasks.tracetest.SpanRecorder: the script span is a child of the request span, there is onecodemode.CallToolchild per inner call (including those underparallel()), and the backend sees the inner call span as current.Telemetryconfigured, the caller's span stays current and nothing is recorded.NewTelemetry(nil, nil)is a working no-op.pkg/script:ErrStepLimitExceededat top level and inparallel(),OnStatscounts nestedparallel()calls and children's steps, and runs once even on failure.TestIntegration_CodeModeTelemetry): a real vMCP server with code mode on runs aparallel()script over HTTP. Scraping/metricsshowstoolhive_mcp_tool_calls_total{tool="execute_tool_script"} 1, no request-level sample for the inner tool, the four script metrics with exact values, andtoolhive_vmcp_code_mode_enabled 1. With code mode off, the gauge is0and no script metrics appear.task lint-fixcannot run on this machine (local golangci-lint cannot read Go 1.27 export data), so lint ran throughgo runof the CI-pinned version. E2E is left to CI.Changes (OTel part)
pkg/script/internal/core/{execute,stats}.goErrStepLimitExceededthroughOnMaxSteps; per-execution step andparallel()counters on the threadpkg/script/internal/builtins/parallel.goOnMaxStepsand the counters;parallel()reports its task countpkg/script/{script,executor}.goErrStepLimitExceeded,Stats,Config.OnStatspkg/vmcp/codemode/observer.goScriptOutcome, the extendedScriptStats, outcome classificationpkg/vmcp/codemode/telemetry.goTelemetryinstruments and spans (NewTelemetry)pkg/vmcp/codemode/decorator.go,config.goConfig.Telemetrywired intoexecute_tool_scriptpkg/vmcp/server/code_mode_telemetry.go,server.gocode_mode_enabledgaugedocs/operator/virtualmcpserver-observability.mdDoes 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:
/metricsexposestoolhive_vmcp_code_mode_enabledon every vMCP server, and the fourtoolhive_vmcp_script_*metrics when code mode is on. Traces gaincodemode.ExecuteToolScriptandcodemode.CallToolspans. 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
codeModeConfigrecords this.Optimizer. vMCP counts
call_toolcalls that run a script incode_mode_callsonly 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 casedtool_name.Embedder API.
OnScriptis also the hook an embedder ofserver.Newcan use for its own usage capture;ScriptStatsis 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_callsdepends 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, andtoolhive_vmcp_backend_revision_reclassifications, which is recent). No toolhive metric uses the dottedstacklok.<service>.*form, and there is no migration switch, so this PR follows the repo and the names in #4743. The outcome attribute isstatus, as #4743 asks and as thetoolhive_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.
toolhive_vmcp_script_parallel_goroutines.parallel()runs its callables on a pool of at mostParallelMaxgoroutines (foreach.Concurrent), so a goroutine count mostly echoes the config.toolhive_vmcp_script_parallel_taskscounts the callables, which is the real fan-out. Accepted criterion: "countertoolhive_vmcp_script_parallel_tasksincrements by the number of callables eachparallel()call starts."toolhive_vmcp_tool_calls{method}counter.toolhive_mcp_tool_calls{tool}already counts every vMCPtools/callwith 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 fromtoolhive_mcp_tool_calls{tool="execute_tool_script"}, with example PromQL in the observability doc."vmcp_server_nameon the gauge. It usesserverinstead, the labeltoolhive_mcp_tool_callscarries, 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.CallToolhas no session parameter, so the decorator reads it withserver.ClientSessionFromContextfor logs only. Stateless Modern requests have no session, and theirsession_idis 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
Telemetryleaves the context and spans untouched. Recording is synchronous and non-blocking, and a panic while recording metrics is recovered.OnStatsruns on theExecutegoroutine 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