Repository navigation
OSPP2: Add terminal MCP tool call metrics to Agent Gateway - #7522
Conversation
Aias00
left a comment
There was a problem hiding this comment.
Summary
Adds terminal MCP tool-call metrics to the Agent Gateway via a bounded observer pattern.
Design strengths
- Bounded labels: the
Outcomeenum has exactly 6 values (success, tool_error, rejected,
server_error, timeout, cancelled) and explicitly excludes tool names, principals, RPC/request ids,
or arguments — no label explosion, no PII leakage. - Per-subscription isolation:
AgentMcpCallObservationis constructed insideMono.defer, so
concurrent calls and repeated RPC ids get independent state.AtomicBoolean recordedguarantees
at most one terminal record even with late signals. - Fail-safe observability:
finish()wrapsobserver.record(...)in try/catch downgraded to
LOG.debug, so a callback failure can never alter a response or trigger retries. - Correct outcome resolution: deadline wins over downstream cancellation (timeout vs cancelled),
and a computed result is not "success" until the response write completes.
Verification
MetricsReporter.counterIncrement(String, String[], long)(line 168) and
recordTime(String, String[], long)(line 217) match the call sites exactly.AgentMcpProtocolException.getHttpStatus()exists;java.util.Objectsis imported in the
three touched service impls.- Test suite (346 lines) is thorough: business-vs-HTTP status, rejection without provider
invocation, internal error, deadline vs cancellation, stalled write, write error, response-limit
failure, discovery/listing excluded, unauthenticated excluded, callback failure does not change
the response, concurrent independence, fresh-subscription no reuse, late-signal single record,
wrong-type callback safe, cancel-before-parse excluded. - CI:
buildand allshenyu-integrated-test-*jobs pass. Onlye2efails, which is the
out-of-reactorshenyu-e2e/**workflow and unrelated to this metrics change — infra.
Non-blocking nits
.doOnError(observation::failure)appears twice (once before and once afteronErrorResume);
the second is redundant sincefailureonly mutates a field and the first already covered the
original error.- The metrics callback is only installed when the Metrics plugin runs before Agent Gateway —
already documented in the README, but a one-line inline comment at the attribute write would help.
Conclusion
Approved. Solid, well-tested observability addition with proper privacy boundaries.
wy471x
left a comment
There was a problem hiding this comment.
Verified on the branch (JDK 21): ./mvnw -o -pl shenyu-plugin/shenyu-plugin-agent-gateway,shenyu-plugin/shenyu-plugin-metrics -am test -Dtest='AgentMcpCallObservationTest,MetricsPluginTest,MetricsReporterTest' -> 30/30, 6/6 and 5/5 green, checkstyle clean in every module of the reactor.
I read the observation lifecycle carefully and it holds up: parsed() arms state only for an authenticated, successfully parsed tools/call, response()/failure() only classify, and finish() is the single emitter behind the compareAndSet, so one subscription produces at most one terminal event even with repeated RPC ids or a late signal. SignalType.CANCEL -> cancelled overriding a computed outcome, TimeoutException -> timeout, AgentMcpProtocolException with a 4xx status -> rejected, everything else -> server_error matches the documented table, and the "a computed result is not a success until the write completed" rule is genuinely enforced by the stalled-write/limit tests. The ordering the README relies on is satisfied in the plugin chain (PluginEnum.METRICS is 15, AGENT_GATEWAY is 198), and with the metrics plugin absent the attribute is null and the class degrades to a no-op.
Non-blocking notes:
AgentMcpHttpHandler#handlehas.doOnError(observation::failure)twice, once before and once after.onErrorResume(...). The second can only observe errors produced byhandleFailureitself (or the re-emitted original when the response is already committed), and those classify to the same outcome orserver_error, so the second call looks redundant. If it is there to cover the best-effort error write, a one-line comment would stop the next reader from removing the wrong one.AgentMcpCallObservation(final Object observer)takesObjectand then doesinstanceof AgentMcpCallObserver, even though the class imports the interface and the call site only passes the raw exchange attribute because that is how the callback plumbing works. Taking the typed interface directly (null check at the call site, or a small static factory) would remove the untyped parameter — same behaviour, less to misread.- Unit check for the histogram:
MetricsReporter.recordTime->PrometheusMetricsRegister#recordTime->histogram.observe(duration)with the raw millis value, so_sum/_countreally are milliseconds, matching the README and the existingshenyu_execute_latency_millisusage. Nothing to change; for the record, the buckets are still the Prometheus client defaults (the registration helper passes no bucket policy), and the README correctly declines to claim anything about_bucket/percentiles. MetricsReporterTeststill asserts hard-coded map sizes (now 10/4 and 11/5). Fine for this change, but every future metric registration has to chase those numbers — a name-based assertion would be less brittle (pre-existing style, not something this PR has to fix).
Background
The existing HTTP metrics cannot distinguish a successful MCP tool result from
an HTTP 200 result with
isError=true. This change adds logicaltools/callstatistics to the tools-only Agent Gateway entry already merged in #7424. It
does not depend on the remote aggregation changes in #7512.
Changes
a typed server-side exchange callback; add no dependency, exporter or Admin
configuration.
success,tool_error,rejected,server_error,timeoutandcancelledoutcomes. Discovery/list and failures before parsing stay in HTTP metrics.
completion if encoding, writing, the deadline or cancellation prevents the
response write from completing successfully.
Keep observation state private even when client RPC ids are repeated.
outcome label. Do not expose tool names, principals, request ids, credentials,
arguments or response bodies as metric labels. Callback exceptions do not
change the tool response or introduce retries.
and cancellations separately. Reuse histogram sum/count without claiming a
new bucket or percentile policy.
Token/cost accounting, per-tool dimensions, result transformations, model
degradation, prompts/resources and remote-catalog integration are outside this
change. No model usage is inferred from tool-call count or response length.
Verification
Local verification on the accepted 11-file candidate and its recorded baseline:
errors or skips; 14-module Checkstyle/RAT passed. All 4647 compared source files
match byte hashes. These are the same cases across platforms, not 620 unique
tests or native RISC hardware coverage.
53 checks passed, including whitelist update/restore, JSON/SSE, business
failures, denial, timeout, output limits, disconnect isolation and 32 concurrent
requests with the same RPC id. All 46 observed logical calls have matching
counter/histogram counts.
CodeMode each made one actual
order_statuscall, with model/tool/wirecorrelation and an exact success-counter increase of three.
credential checks passed; owned ports were released. Admin/Bootstrap assembly
(193 modules) and example packaging succeeded with tests explicitly skipped.