Skip to content

Feat/add mcp gateway metrics - #289

Merged
iFurySt merged 7 commits into
AmoyLab:mainfrom
kx-byte:feat/add_mcp_gateway_metrics
Dec 11, 2025
Merged

iFurySt merged 7 commits into
AmoyLab:mainfrom
kx-byte:feat/add_mcp_gateway_metrics

Conversation

@kx-byte

@kx-byte kx-byte commented Dec 11, 2025 •

Copy link
Copy Markdown
Contributor

Summary by Sourcery

Add configurable Prometheus metrics support to the MCP gateway and instrument core request and tool execution paths.

New Features:

  • Introduce a MetricsConfig section to configure metrics exposure, namespace, and histogram buckets for the MCP gateway.
  • Expose a Prometheus metrics endpoint with HTTP, MCP request, and tool execution metrics collected via a dedicated registry and Gin middleware.
  • Instrument MCP request handling and tool execution flows to record counts, durations, and inflight operations per method and tool.

Enhancements:

  • Skip tracing for the configurable metrics endpoint to avoid noisy spans.
  • Extend the server to manage metrics state and initialization from configuration.

Build:

  • Add Prometheus client dependencies for metrics collection.

Documentation:

  • Document MCP gateway metrics configuration options in the default YAML config.

@sourcery-ai

sourcery-ai Bot commented Dec 11, 2025 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Adds configurable Prometheus metrics support for the MCP gateway, including HTTP, MCP request, and tool execution metrics, wired through config, server initialization, and request handling paths.

Sequence diagram for MCP tool execution with metrics

sequenceDiagram
  actor McpClient
  participant GinServer
  participant Server
  participant Metrics
  participant BackendTool

  McpClient->>GinServer: HTTP request (MCP CallTool)
  GinServer->>Server: handleMCPRequest
  alt Metrics enabled
    Server->>Metrics: McpReqStart(method)
  end
  Server->>Server: resolve tool and backend
  alt Metrics enabled
    Server->>Metrics: ToolExecStart(toolName)
  end
  Server->>BackendTool: CallTool(params)
  BackendTool-->>Server: CallToolResult or error
  alt error
    Server->>McpClient: sendToolExecutionError
    alt Metrics enabled
      Server->>Metrics: ToolExecDone(toolName, startTime, status="error")
    end
  else success
    Server->>McpClient: send result
    alt Metrics enabled
      Server->>Metrics: ToolExecDone(toolName, startTime, status="success")
    end
  end
  alt Metrics enabled
    Server->>Metrics: McpReqDone(method, startTime)
  end
Loading

Class diagram for new metrics configuration and server wiring

classDiagram

class MetricsConfig {
  bool Enabled
  string Path
  string Namespace
  float64[] Buckets
}

class Metrics {
  -prometheus.Registry registry
  -string namespace
  -prometheus.CounterVec httpReqCnt
  -prometheus.HistogramVec httpDur
  -prometheus.GaugeVec httpInfl
  -prometheus.CounterVec mcpReqCnt
  -prometheus.HistogramVec mcpReqDur
  -prometheus.GaugeVec mcpReqInfl
  -prometheus.CounterVec toolExecCnt
  -prometheus.HistogramVec toolExecDur
  -prometheus.GaugeVec toolExecInfl
  +New(cfg MetricsConfig) Metrics
  +McpReqStart(method string)
  +McpReqDone(method string, since time.Time)
  +ToolExecStart(toolName string)
  +ToolExecDone(toolName string, since time.Time, status *string)
  +Middleware() gin.HandlerFunc
  +Handler() http.Handler
}

class Server {
  -Metrics metrics
  -string metricsPath
  +EnableMetrics(cfg MetricsConfig)
}

MetricsConfig <.. Server : used_by
Server "1" o-- "0..1" Metrics : holds
MetricsConfig <.. Metrics : configures
Loading

File-Level Changes

Change Details Files
Introduce configurable metrics settings and defaults for MCP gateway
  • Extend main configuration struct with a metrics section including enabled flag, path, namespace, and histogram buckets
  • Set sensible defaults for metrics path, namespace, and latency buckets when metrics are enabled but fields are unset
  • Expose metrics configuration in mcp-gateway.yaml with environment-variable overrides
internal/common/config/config.go
configs/mcp-gateway.yaml
Wire metrics into MCP gateway server lifecycle and HTTP stack
  • Add metrics fields to the Server struct for holding metrics instance and metrics endpoint path
  • Add EnableMetrics method to initialize metrics, attach Gin middleware, and register the metrics endpoint handler
  • Skip tracing for the configured metrics path to avoid noisy spans
  • Invoke EnableMetrics from main before route registration so metrics middleware is active
internal/core/server.go
internal/core/middleware.go
cmd/mcp-gateway/main.go
Collect MCP request and tool execution metrics for SSE and streamable handlers
  • Record MCP request inflight, count, and duration around handlePostMessage and handleMCPRequest based on JSON-RPC method
  • Track tool execution inflight, count, duration, and success/error status around tool invocations across protocols
  • Ensure error paths in tool execution update metrics status to error before returning
internal/core/sse.go
internal/core/streamable.go
Implement Prometheus-based metrics subsystem
  • Create Metrics type that owns a dedicated Prometheus registry and metric vectors for HTTP, MCP, and tool execution
  • Register standard Go and process collectors plus custom counters, histograms, and gauges using configured buckets and namespace
  • Provide Gin middleware to instrument HTTP requests with route, method, and status labels, including basic route normalization
  • Expose an HTTP handler for Prometheus scraping via promhttp.HandlerFor
pkg/metrics/metrics.go
Add Prometheus client dependencies
  • Add prometheus/client_golang as a direct dependency and supporting Prometheus packages as indirect dependencies in go.mod/go.sum
go.mod
go.sum

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot 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.

Hey there - I've reviewed your changes - here's some feedback:

  • In ToolExecDone you always pass a non-nil pointer to a local status string; consider changing the signature to take a plain status string to simplify the API and avoid pointer indirection.
  • The metrics middleware falls back to using the raw URL path as the route label when FullPath() is empty; if any routes include IDs or other dynamic segments this can cause high-cardinality metrics, so consider extending routeFromURL or using a more systematic normalization.
  • The httpStatus helper uses http.StatusText, which may return an empty string for non-standard codes; consider labeling by numeric code (or code plus text) to ensure the status label is always present and consistent.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `ToolExecDone` you always pass a non-nil pointer to a local `status` string; consider changing the signature to take a plain `status string` to simplify the API and avoid pointer indirection.
- The metrics middleware falls back to using the raw URL path as the `route` label when `FullPath()` is empty; if any routes include IDs or other dynamic segments this can cause high-cardinality metrics, so consider extending `routeFromURL` or using a more systematic normalization.
- The `httpStatus` helper uses `http.StatusText`, which may return an empty string for non-standard codes; consider labeling by numeric code (or code plus text) to ensure the status label is always present and consistent.

## Individual Comments

### Comment 1
<location> `internal/core/sse.go:443-445` </location>
<code_context>
+		status := "success"
+
+		toolName := params.Name
+		if s.metrics != nil {
+			s.metrics.ToolExecStart(toolName)
+			defer s.metrics.ToolExecDone(toolName, reqStartTime, &status)
+		}
+
</code_context>

<issue_to_address>
**issue (bug_risk):** Tool execution duration is measured from the request start time instead of the tool start time.

Using `reqStartTime` here overstates `tool_execution_duration_seconds` by including pre-tool handler time. Please capture a fresh `toolStartTime := time.Now()` immediately before `ToolExecStart(toolName)` and pass that into `ToolExecDone`. Apply the same change in `handleMCPRequest` in `streamable.go`.
</issue_to_address>

### Comment 2
<location> `internal/core/streamable.go:307-309` </location>
<code_context>
+		status := "success"
+
+		toolName := params.Name
+		if s.metrics != nil {
+			s.metrics.ToolExecStart(toolName)
+			defer s.metrics.ToolExecDone(toolName, reqStartTime, &status)
+		}
+
</code_context>

<issue_to_address>
**issue (bug_risk):** Same tool duration measurement issue in the streamable handler.

`reqStartTime` measures time since request, not tool execution. As in `handlePostMessage`, capture a `toolStartTime := time.Now()` when calling `ToolExecStart` and pass that to `ToolExecDone` instead.
</issue_to_address>

### Comment 3
<location> `pkg/metrics/metrics.go:120` </location>
<code_context>
+	return path
+}
+
+func httpStatus(code int) string { return http.StatusText(code) }
</code_context>

<issue_to_address>
**suggestion:** Using `http.StatusText` as the `status` label may be less stable than numeric codes.

Since label values define the Prometheus time series, it’s preferable to use numeric status codes (e.g., "200", "404") rather than text like "OK"/"Not Found", which can change over time. Consider returning `strconv.Itoa(code)` here and reserving the textual form for logs instead.

Suggested implementation:

```golang
import (
	"net/http"
	"strconv"

```

```golang
func httpStatus(code int) string { return strconv.Itoa(code) }

```

If your import block is organized differently (for example, additional imports or grouped with project-local packages), adjust the `import` edit accordingly, ensuring `strconv` is added to the existing import list without breaking formatting or tooling (e.g., `goimports` will also fix this automatically).
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread internal/core/sse.go Resolved
Comment thread internal/core/streamable.go Resolved
Comment thread pkg/metrics/metrics.go Resolved

@iFurySt iFurySt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM. Thanks!

@iFurySt
iFurySt merged commit 39f67f1 into AmoyLab:main Dec 11, 2025
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.

2 participants