Repository navigation
Feat/add mcp gateway metrics - #289
Merged
Merged
Conversation
Contributor
Reviewer's GuideAdds 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 metricssequenceDiagram
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
Class diagram for new metrics configuration and server wiringclassDiagram
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
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Contributor
There was a problem hiding this comment.
Hey there - I've reviewed your changes - here's some feedback:
- In
ToolExecDoneyou always pass a non-nil pointer to a localstatusstring; consider changing the signature to take a plainstatus stringto simplify the API and avoid pointer indirection. - The metrics middleware falls back to using the raw URL path as the
routelabel whenFullPath()is empty; if any routes include IDs or other dynamic segments this can cause high-cardinality metrics, so consider extendingrouteFromURLor using a more systematic normalization. - The
httpStatushelper useshttp.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>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary by Sourcery
Add configurable Prometheus metrics support to the MCP gateway and instrument core request and tool execution paths.
New Features:
Enhancements:
Build:
Documentation: