Skip to content

Commit 492bb68

Browse files
authored
Merge pull request #443 from hookdeck/fix/metrics-dimension-roundtrip
fix(metrics): answer with the dimension name the caller asked with
2 parents e3d4c45 + 226abf8 commit 492bb68

5 files changed

Lines changed: 188 additions & 18 deletions

File tree

‎pkg/cmd/metrics.go‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,13 @@ import (
1212
)
1313

1414
// printMetricsResponse prints data as JSON or a human-readable table.
15+
//
16+
// Dimension keys are translated back to the caller's vocabulary first: the API
17+
// answers with webhook_id, and a user who asked for connection_id should not
18+
// have to know the internal name to read their own result (#442). Every metrics
19+
// command prints through here, so this is the one place it has to happen.
1520
func printMetricsResponse(data hookdeck.MetricsResponse, output string) error {
21+
data = hookdeck.RestoreDimensionNames(data)
1622
if output == "json" {
1723
bytes, err := json.MarshalIndent(data, "", " ")
1824
if err != nil {
@@ -127,13 +133,17 @@ func metricsParamsFromFlags(f *metricsCommonFlags) hookdeck.MetricsQueryParams {
127133
if f.dimensions != "" {
128134
for _, s := range strings.Split(f.dimensions, ",") {
129135
if t := strings.TrimSpace(s); t != "" {
130-
// API expects webhook_id for connection dimension; CLI accepts connection_id/connection-id for consistency.
131-
if t == "connection_id" || t == "connection-id" {
132-
t = "webhook_id"
136+
// The API spells this webhook_id; the CLI accepts the
137+
// user-facing connection_id (and the flag-style spelling) and
138+
// translates. printMetricsResponse translates the response keys
139+
// back, so the answer uses the name that was asked for (#442).
140+
if t == "connection-id" {
141+
t = hookdeck.ConnectionDimension
133142
}
134143
dimensions = append(dimensions, t)
135144
}
136145
}
146+
dimensions = hookdeck.MapDimensionsToAPI(dimensions)
137147
}
138148
return hookdeck.MetricsQueryParams{
139149
Start: f.start,

‎pkg/gateway/mcp/tool_metrics.go‎

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -86,18 +86,10 @@ func rejectDimensions(params hookdeck.MetricsQueryParams, allowed []string, rout
8686
// mapDimensions rewrites connection_id to the webhook_id the API expects. The
8787
// tool schema tells callers connection_id "maps to webhook_id", which was true
8888
// of the filter and not of the dimension.
89+
// mapDimensions delegates to the shared pair in pkg/hookdeck so the outbound
90+
// rewrite and the inbound one in RestoreDimensionNames cannot drift. See #442.
8991
func mapDimensions(dimensions []string) []string {
90-
if len(dimensions) == 0 {
91-
return dimensions
92-
}
93-
out := make([]string, 0, len(dimensions))
94-
for _, d := range dimensions {
95-
if d == "connection_id" {
96-
d = "webhook_id"
97-
}
98-
out = append(out, d)
99-
}
100-
return out
92+
return hookdeck.MapDimensionsToAPI(dimensions)
10193
}
10294

10395
func buildMetricsParams(in mcpcore.Input) (hookdeck.MetricsQueryParams, error) {
@@ -226,7 +218,7 @@ func metricsEvents(ctx context.Context, client *hookdeck.Client, in mcpcore.Inpu
226218
if err != nil {
227219
return mcpcore.ErrorResult(mcpcore.TranslateAPIError(err)), nil
228220
}
229-
return mcpcore.JSONResultEnvelopeForClient(result, client)
221+
return mcpcore.JSONResultEnvelopeForClient(hookdeck.RestoreDimensionNames(result), client)
230222
}
231223

232224
func metricsRequests(ctx context.Context, client *hookdeck.Client, in mcpcore.Input) (*mcpsdk.CallToolResult, error) {
@@ -244,7 +236,7 @@ func metricsRequests(ctx context.Context, client *hookdeck.Client, in mcpcore.In
244236
if err != nil {
245237
return mcpcore.ErrorResult(mcpcore.TranslateAPIError(err)), nil
246238
}
247-
return mcpcore.JSONResultEnvelopeForClient(result, client)
239+
return mcpcore.JSONResultEnvelopeForClient(hookdeck.RestoreDimensionNames(result), client)
248240
}
249241

250242
func metricsAttempts(ctx context.Context, client *hookdeck.Client, in mcpcore.Input) (*mcpsdk.CallToolResult, error) {
@@ -262,7 +254,7 @@ func metricsAttempts(ctx context.Context, client *hookdeck.Client, in mcpcore.In
262254
if err != nil {
263255
return mcpcore.ErrorResult(mcpcore.TranslateAPIError(err)), nil
264256
}
265-
return mcpcore.JSONResultEnvelopeForClient(result, client)
257+
return mcpcore.JSONResultEnvelopeForClient(hookdeck.RestoreDimensionNames(result), client)
266258
}
267259

268260
func metricsTransformations(ctx context.Context, client *hookdeck.Client, in mcpcore.Input) (*mcpsdk.CallToolResult, error) {
@@ -280,5 +272,5 @@ func metricsTransformations(ctx context.Context, client *hookdeck.Client, in mcp
280272
if err != nil {
281273
return mcpcore.ErrorResult(mcpcore.TranslateAPIError(err)), nil
282274
}
283-
return mcpcore.JSONResultEnvelopeForClient(result, client)
275+
return mcpcore.JSONResultEnvelopeForClient(hookdeck.RestoreDimensionNames(result), client)
284276
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package mcp
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
"testing"
7+
8+
"github.com/stretchr/testify/assert"
9+
10+
"github.com/hookdeck/hookdeck-cli/pkg/hookdeck"
11+
)
12+
13+
// The helper tests in pkg/hookdeck cover the mapping itself; this covers the
14+
// tool calling it. Without a test at this level, removing the call from the
15+
// handler leaves those unit tests green while the agent-facing result goes back
16+
// to being keyed with an internal name the caller never used (#442).
17+
func TestMetricsToolAnswersWithTheDimensionNameTheCallerAsked(t *testing.T) {
18+
session := mockAPIWithClient(t, map[string]http.HandlerFunc{
19+
hookdeck.APIPathPrefix + "/metrics/events": func(w http.ResponseWriter, r *http.Request) {
20+
// The API answers in its own spelling, whatever we asked with.
21+
_ = json.NewEncoder(w).Encode(map[string]any{"data": []any{
22+
map[string]any{
23+
"time_bucket": "2025-01-01T00:00:00.000Z",
24+
"dimensions": map[string]any{"webhook_id": "web_123"},
25+
"metrics": map[string]any{"count": 7},
26+
},
27+
}})
28+
},
29+
})
30+
31+
result := callTool(t, session, "gateway_metrics_read", map[string]any{
32+
"action": "events",
33+
"start": "2025-01-01T00:00:00Z",
34+
"end": "2025-01-02T00:00:00Z",
35+
"measures": []any{"count"},
36+
"dimensions": []any{"connection_id"},
37+
})
38+
39+
assert.False(t, result.IsError)
40+
body := textContent(t, result)
41+
assert.Contains(t, body, "connection_id",
42+
"the result must be keyed with the name the caller asked with")
43+
assert.Contains(t, body, "web_123", "the value itself is unchanged")
44+
assert.NotContains(t, body, "webhook_id",
45+
"the API's internal spelling must not reach the caller")
46+
}

‎pkg/hookdeck/metrics.go‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,60 @@ type MetricDataPoint struct {
2020
// MetricsResponse is the response from any of the metrics GET endpoints.
2121
type MetricsResponse = []MetricDataPoint
2222

23+
// The API spells the connection dimension webhook_id. "connection" is the
24+
// user-facing noun everywhere else in this CLI, so both surfaces accept
25+
// connection_id and translate it on the way out to the API.
26+
//
27+
// The translation used to be one-way: a caller asked for connection_id and got
28+
// results keyed webhook_id, so they had to know an internal name they never
29+
// used in order to read their own answer. For an agent that is worse than
30+
// untidy -- it looks for the key it asked for, does not find it, and cannot
31+
// learn that webhook_id means the same thing. See #442.
32+
//
33+
// Both directions live here, next to each other and shared by the MCP tool and
34+
// the CLI, so neither half can drift from the other.
35+
const (
36+
ConnectionDimension = "connection_id"
37+
APIConnectionDimension = "webhook_id"
38+
)
39+
40+
// MapDimensionsToAPI rewrites caller-facing dimension names to the API's.
41+
func MapDimensionsToAPI(dimensions []string) []string {
42+
if len(dimensions) == 0 {
43+
return dimensions
44+
}
45+
out := make([]string, 0, len(dimensions))
46+
for _, d := range dimensions {
47+
if d == ConnectionDimension {
48+
d = APIConnectionDimension
49+
}
50+
out = append(out, d)
51+
}
52+
return out
53+
}
54+
55+
// RestoreDimensionNames rewrites the API's dimension keys back to the ones the
56+
// caller used, in place, so a response answers in the vocabulary of its query.
57+
func RestoreDimensionNames(points MetricsResponse) MetricsResponse {
58+
for i := range points {
59+
d := points[i].Dimensions
60+
if d == nil {
61+
continue
62+
}
63+
v, ok := d[APIConnectionDimension]
64+
if !ok {
65+
continue
66+
}
67+
// Never clobber a connection_id the API itself returned.
68+
if _, exists := d[ConnectionDimension]; exists {
69+
continue
70+
}
71+
d[ConnectionDimension] = v
72+
delete(d, APIConnectionDimension)
73+
}
74+
return points
75+
}
76+
2377
// MetricsQueryParams holds shared query parameters for all metrics endpoints.
2478
// Start and End are required (ISO 8601 date-time).
2579
// ConnectionID is mapped to API webhook_id in the CLI layer.
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package hookdeck
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
// The API spells the connection dimension webhook_id. The CLI and the MCP tool
10+
// both accept connection_id and translate outbound, but neither translated the
11+
// response, so a caller who asked for connection_id got results keyed
12+
// webhook_id and had to know an internal name to read their own answer (#442).
13+
//
14+
// These cover the round trip, which is the property that matters: whatever
15+
// dimension name went out is the one that comes back.
16+
func TestDimensionNamesRoundTrip(t *testing.T) {
17+
asked := []string{"connection_id", "status"}
18+
sent := MapDimensionsToAPI(asked)
19+
assert.Equal(t, []string{"webhook_id", "status"}, sent, "the API is asked in its own spelling")
20+
21+
// What the API answers with, keyed as it sent it.
22+
response := MetricsResponse{
23+
{Dimensions: map[string]interface{}{"webhook_id": "web_123", "status": "SUCCESSFUL"}},
24+
}
25+
got := RestoreDimensionNames(response)
26+
27+
assert.Equal(t, "web_123", got[0].Dimensions["connection_id"],
28+
"the answer must use the name the caller asked with")
29+
assert.NotContains(t, got[0].Dimensions, "webhook_id",
30+
"the internal name must not leak back to the caller")
31+
assert.Equal(t, "SUCCESSFUL", got[0].Dimensions["status"],
32+
"untranslated dimensions are left alone")
33+
}
34+
35+
func TestRestoreDimensionNamesEdgeCases(t *testing.T) {
36+
t.Run("nil dimensions are left alone", func(t *testing.T) {
37+
got := RestoreDimensionNames(MetricsResponse{{Dimensions: nil}})
38+
assert.Nil(t, got[0].Dimensions)
39+
})
40+
41+
t.Run("no webhook_id is a no-op", func(t *testing.T) {
42+
got := RestoreDimensionNames(MetricsResponse{
43+
{Dimensions: map[string]interface{}{"status": "FAILED"}},
44+
})
45+
assert.Equal(t, map[string]interface{}{"status": "FAILED"}, got[0].Dimensions)
46+
})
47+
48+
// If the API ever answers with both, the one it called connection_id wins;
49+
// silently overwriting it would be the same class of bug this fixes.
50+
t.Run("an existing connection_id is never clobbered", func(t *testing.T) {
51+
got := RestoreDimensionNames(MetricsResponse{
52+
{Dimensions: map[string]interface{}{"webhook_id": "web_1", "connection_id": "conn_real"}},
53+
})
54+
assert.Equal(t, "conn_real", got[0].Dimensions["connection_id"])
55+
assert.Equal(t, "web_1", got[0].Dimensions["webhook_id"])
56+
})
57+
58+
t.Run("empty response", func(t *testing.T) {
59+
assert.Empty(t, RestoreDimensionNames(MetricsResponse{}))
60+
})
61+
}
62+
63+
func TestMapDimensionsToAPIIsIdempotent(t *testing.T) {
64+
once := MapDimensionsToAPI([]string{"connection_id"})
65+
assert.Equal(t, once, MapDimensionsToAPI(once),
66+
"mapping an already-mapped slice must not change it")
67+
assert.Nil(t, MapDimensionsToAPI(nil))
68+
}

0 commit comments

Comments
 (0)