Skip to content

OSPP2: Add terminal MCP tool call metrics to Agent Gateway - #7522

Merged
Aias00 merged 1 commit into
apache:masterfrom
BobSong-dev:feat/agent-gateway-tool-metrics
Oct 10, 2026
Merged

Aias00 merged 1 commit into
apache:masterfrom
BobSong-dev:feat/agent-gateway-tool-metrics

Conversation

@BobSong-dev

Copy link
Copy Markdown
Member

Background

The existing HTTP metrics cannot distinguish a successful MCP tool result from
an HTTP 200 result with isError=true. This change adds logical tools/call
statistics to the tools-only Agent Gateway entry already merged in #7424. It
does not depend on the remote aggregation changes in #7512.

Changes

  • Reuse the existing Metrics plugin, reporter and Prometheus exporter through
    a typed server-side exchange callback; add no dependency, exporter or Admin
    configuration.
  • Count authenticated, validly parsed calls once per subscription, with bounded
    success, tool_error, rejected, server_error, timeout and cancelled
    outcomes. Discovery/list and failures before parsing stay in HTTP metrics.
  • Observe through response writing: computing a result is not successful
    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.
  • Export terminal count and monotonic elapsed milliseconds using only the
    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.
  • Document the logical-call failure ratio and its denominator; report refusals
    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:

  • Windows and RISC-V/QEMU: each 310 targeted cases in 18 suites, zero failures,
    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.
  • In-process Metrics → Agent handler → real Prometheus registry: 46 checks passed.
  • Real local Admin/H2 → WebSocket → Bootstrap → existing Prometheus HTTP exporter:
    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.
  • OpenCode with the configured real model: JSON direct, SSE direct and SSE
    CodeMode each made one actual order_status call, with model/tool/wire
    correlation and an exact success-counter increase of three.
  • Runtime class origins, inactive fixture calls before shutdown and artifact
    credential checks passed; owned ports were released. Admin/Bootstrap assembly
    (193 modules) and example packaging succeeded with tests explicitly skipped.

@Aias00 Aias00 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.

Summary

Adds terminal MCP tool-call metrics to the Agent Gateway via a bounded observer pattern.

Design strengths

  • Bounded labels: the Outcome enum 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: AgentMcpCallObservation is constructed inside Mono.defer, so
    concurrent calls and repeated RPC ids get independent state. AtomicBoolean recorded guarantees
    at most one terminal record even with late signals.
  • Fail-safe observability: finish() wraps observer.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.Objects is 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: build and all shenyu-integrated-test-* jobs pass. Only e2e fails, which is the
    out-of-reactor shenyu-e2e/** workflow and unrelated to this metrics change — infra.

Non-blocking nits

  1. .doOnError(observation::failure) appears twice (once before and once after onErrorResume);
    the second is redundant since failure only mutates a field and the first already covered the
    original error.
  2. 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.

@Aias00
Aias00 merged commit 66b8fee into apache:master Oct 10, 2026
53 of 60 checks passed

@wy471x wy471x 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.

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:

  1. AgentMcpHttpHandler#handle has .doOnError(observation::failure) twice, once before and once after .onErrorResume(...). The second can only observe errors produced by handleFailure itself (or the re-emitted original when the response is already committed), and those classify to the same outcome or server_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.
  2. AgentMcpCallObservation(final Object observer) takes Object and then does instanceof 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.
  3. Unit check for the histogram: MetricsReporter.recordTime -> PrometheusMetricsRegister#recordTime -> histogram.observe(duration) with the raw millis value, so _sum/_count really are milliseconds, matching the README and the existing shenyu_execute_latency_millis usage. 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.
  4. MetricsReporterTest still 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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants