forked from grafana/mcp-grafana
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcpgrafana_test.go
More file actions
557 lines (464 loc) · 18.1 KB
/
Copy pathmcpgrafana_test.go
File metadata and controls
557 lines (464 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//go:build unit
// +build unit
package mcpgrafana
import (
"context"
"net/http"
"testing"
"github.com/go-openapi/runtime/client"
grafana_client "github.com/grafana/grafana-openapi-client-go/client"
"github.com/mark3labs/mcp-go/mcp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
)
func TestExtractIncidentClientFromEnv(t *testing.T) {
t.Setenv("GRAFANA_URL", "http://my-test-url.grafana.com/")
ctx := ExtractIncidentClientFromEnv(context.Background())
client := IncidentClientFromContext(ctx)
require.NotNil(t, client)
assert.Equal(t, "http://my-test-url.grafana.com/api/plugins/grafana-irm-app/resources/api/v1/", client.RemoteHost)
}
func TestExtractIncidentClientFromHeaders(t *testing.T) {
t.Run("no headers, no env", func(t *testing.T) {
req, err := http.NewRequest("GET", "http://example.com", nil)
require.NoError(t, err)
ctx := ExtractIncidentClientFromHeaders(context.Background(), req)
client := IncidentClientFromContext(ctx)
require.NotNil(t, client)
assert.Equal(t, "http://localhost:3000/api/plugins/grafana-irm-app/resources/api/v1/", client.RemoteHost)
})
t.Run("no headers, with env", func(t *testing.T) {
t.Setenv("GRAFANA_URL", "http://my-test-url.grafana.com/")
req, err := http.NewRequest("GET", "http://example.com", nil)
require.NoError(t, err)
ctx := ExtractIncidentClientFromHeaders(context.Background(), req)
client := IncidentClientFromContext(ctx)
require.NotNil(t, client)
assert.Equal(t, "http://my-test-url.grafana.com/api/plugins/grafana-irm-app/resources/api/v1/", client.RemoteHost)
})
t.Run("with headers, no env", func(t *testing.T) {
req, err := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(grafanaURLHeader, "http://my-test-url.grafana.com")
require.NoError(t, err)
ctx := ExtractIncidentClientFromHeaders(context.Background(), req)
client := IncidentClientFromContext(ctx)
require.NotNil(t, client)
assert.Equal(t, "http://my-test-url.grafana.com/api/plugins/grafana-irm-app/resources/api/v1/", client.RemoteHost)
})
t.Run("with headers, with env", func(t *testing.T) {
t.Setenv("GRAFANA_URL", "will-not-be-used")
req, err := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set(grafanaURLHeader, "http://my-test-url.grafana.com")
require.NoError(t, err)
ctx := ExtractIncidentClientFromHeaders(context.Background(), req)
client := IncidentClientFromContext(ctx)
require.NotNil(t, client)
assert.Equal(t, "http://my-test-url.grafana.com/api/plugins/grafana-irm-app/resources/api/v1/", client.RemoteHost)
})
}
func TestExtractGrafanaInfoFromHeaders(t *testing.T) {
t.Run("no headers, no env", func(t *testing.T) {
// Explicitly clear environment variables to ensure test isolation
t.Setenv("GRAFANA_URL", "")
t.Setenv("GRAFANA_API_KEY", "")
req, err := http.NewRequest("GET", "http://example.com", nil)
require.NoError(t, err)
ctx := ExtractGrafanaInfoFromHeaders(context.Background(), req)
config := GrafanaConfigFromContext(ctx)
assert.Equal(t, defaultGrafanaURL, config.URL)
assert.Equal(t, "", config.APIKey)
})
t.Run("no headers, with env", func(t *testing.T) {
t.Setenv("GRAFANA_URL", "http://my-test-url.grafana.com")
t.Setenv("GRAFANA_API_KEY", "my-test-api-key")
req, err := http.NewRequest("GET", "http://example.com", nil)
require.NoError(t, err)
ctx := ExtractGrafanaInfoFromHeaders(context.Background(), req)
config := GrafanaConfigFromContext(ctx)
assert.Equal(t, "http://my-test-url.grafana.com", config.URL)
assert.Equal(t, "my-test-api-key", config.APIKey)
})
t.Run("with headers, no env", func(t *testing.T) {
req, err := http.NewRequest("GET", "http://example.com", nil)
require.NoError(t, err)
req.Header.Set(grafanaURLHeader, "http://my-test-url.grafana.com")
req.Header.Set(grafanaAPIKeyHeader, "my-test-api-key")
ctx := ExtractGrafanaInfoFromHeaders(context.Background(), req)
config := GrafanaConfigFromContext(ctx)
assert.Equal(t, "http://my-test-url.grafana.com", config.URL)
assert.Equal(t, "my-test-api-key", config.APIKey)
})
t.Run("with headers, with env", func(t *testing.T) {
// Env vars should be ignored if headers are present.
t.Setenv("GRAFANA_URL", "will-not-be-used")
t.Setenv("GRAFANA_API_KEY", "will-not-be-used")
req, err := http.NewRequest("GET", "http://example.com", nil)
require.NoError(t, err)
req.Header.Set(grafanaURLHeader, "http://my-test-url.grafana.com")
req.Header.Set(grafanaAPIKeyHeader, "my-test-api-key")
ctx := ExtractGrafanaInfoFromHeaders(context.Background(), req)
config := GrafanaConfigFromContext(ctx)
assert.Equal(t, "http://my-test-url.grafana.com", config.URL)
assert.Equal(t, "my-test-api-key", config.APIKey)
})
}
func TestExtractGrafanaClientPath(t *testing.T) {
t.Run("no custom path", func(t *testing.T) {
t.Setenv("GRAFANA_URL", "http://my-test-url.grafana.com/")
ctx := ExtractGrafanaClientFromEnv(context.Background())
c := GrafanaClientFromContext(ctx)
require.NotNil(t, c)
rt := c.Transport.(*client.Runtime)
assert.Equal(t, "/api", rt.BasePath)
})
t.Run("custom path", func(t *testing.T) {
t.Setenv("GRAFANA_URL", "http://my-test-url.grafana.com/grafana")
ctx := ExtractGrafanaClientFromEnv(context.Background())
c := GrafanaClientFromContext(ctx)
require.NotNil(t, c)
rt := c.Transport.(*client.Runtime)
assert.Equal(t, "/grafana/api", rt.BasePath)
})
t.Run("custom path, trailing slash", func(t *testing.T) {
t.Setenv("GRAFANA_URL", "http://my-test-url.grafana.com/grafana/")
ctx := ExtractGrafanaClientFromEnv(context.Background())
c := GrafanaClientFromContext(ctx)
require.NotNil(t, c)
rt := c.Transport.(*client.Runtime)
assert.Equal(t, "/grafana/api", rt.BasePath)
})
}
// minURL is a helper struct representing what we can extract from a constructed
// Grafana client.
type minURL struct {
host, basePath string
}
// minURLFromClient extracts some minimal amount of URL info from a Grafana client.
func minURLFromClient(c *grafana_client.GrafanaHTTPAPI) minURL {
rt := c.Transport.(*client.Runtime)
return minURL{rt.Host, rt.BasePath}
}
func TestExtractGrafanaClientFromHeaders(t *testing.T) {
t.Run("no headers, no env", func(t *testing.T) {
req, err := http.NewRequest("GET", "http://example.com", nil)
require.NoError(t, err)
ctx := ExtractGrafanaClientFromHeaders(context.Background(), req)
c := GrafanaClientFromContext(ctx)
url := minURLFromClient(c)
assert.Equal(t, "localhost:3000", url.host)
assert.Equal(t, "/api", url.basePath)
})
t.Run("no headers, with env", func(t *testing.T) {
t.Setenv("GRAFANA_URL", "http://my-test-url.grafana.com")
req, err := http.NewRequest("GET", "http://example.com", nil)
require.NoError(t, err)
ctx := ExtractGrafanaClientFromHeaders(context.Background(), req)
c := GrafanaClientFromContext(ctx)
url := minURLFromClient(c)
assert.Equal(t, "my-test-url.grafana.com", url.host)
assert.Equal(t, "/api", url.basePath)
})
t.Run("with headers, no env", func(t *testing.T) {
req, err := http.NewRequest("GET", "http://example.com", nil)
require.NoError(t, err)
req.Header.Set(grafanaURLHeader, "http://my-test-url.grafana.com")
ctx := ExtractGrafanaClientFromHeaders(context.Background(), req)
c := GrafanaClientFromContext(ctx)
url := minURLFromClient(c)
assert.Equal(t, "my-test-url.grafana.com", url.host)
assert.Equal(t, "/api", url.basePath)
})
t.Run("with headers, with env", func(t *testing.T) {
// Env vars should be ignored if headers are present.
t.Setenv("GRAFANA_URL", "will-not-be-used")
req, err := http.NewRequest("GET", "http://example.com", nil)
require.NoError(t, err)
req.Header.Set(grafanaURLHeader, "http://my-test-url.grafana.com")
ctx := ExtractGrafanaClientFromHeaders(context.Background(), req)
c := GrafanaClientFromContext(ctx)
url := minURLFromClient(c)
assert.Equal(t, "my-test-url.grafana.com", url.host)
assert.Equal(t, "/api", url.basePath)
})
}
func TestToolTracingInstrumentation(t *testing.T) {
// Set up in-memory span recorder
spanRecorder := tracetest.NewSpanRecorder()
tracerProvider := sdktrace.NewTracerProvider(
sdktrace.WithSpanProcessor(spanRecorder),
)
originalProvider := otel.GetTracerProvider()
otel.SetTracerProvider(tracerProvider)
defer otel.SetTracerProvider(originalProvider) // Restore original provider
t.Run("successful tool execution creates span with correct attributes", func(t *testing.T) {
// Clear any previous spans
spanRecorder.Reset()
// Define a simple test tool
type TestParams struct {
Message string `json:"message" jsonschema:"description=Test message"`
}
testHandler := func(ctx context.Context, args TestParams) (string, error) {
return "Hello " + args.Message, nil
}
// Create tool using MustTool (this applies our instrumentation)
tool := MustTool("test_tool", "A test tool for tracing", testHandler)
// Create context with argument logging enabled
config := GrafanaConfig{
IncludeArgumentsInSpans: true,
}
ctx := WithGrafanaConfig(context.Background(), config)
// Create a mock MCP request
request := mcp.CallToolRequest{
Params: struct {
Name string `json:"name"`
Arguments any `json:"arguments,omitempty"`
Meta *mcp.Meta `json:"_meta,omitempty"`
}{
Name: "test_tool",
Arguments: map[string]interface{}{
"message": "world",
},
},
}
// Execute the tool
result, err := tool.Handler(ctx, request)
require.NoError(t, err)
require.NotNil(t, result)
// Verify span was created
spans := spanRecorder.Ended()
require.Len(t, spans, 1)
span := spans[0]
assert.Equal(t, "mcp.tool.test_tool", span.Name())
assert.Equal(t, codes.Ok, span.Status().Code)
// Check attributes
attributes := span.Attributes()
assertHasAttribute(t, attributes, "mcp.tool.name", "test_tool")
assertHasAttribute(t, attributes, "mcp.tool.description", "A test tool for tracing")
assertHasAttribute(t, attributes, "mcp.tool.arguments", `{"message":"world"}`)
})
t.Run("tool execution error records error on span", func(t *testing.T) {
// Clear any previous spans
spanRecorder.Reset()
// Define a test tool that returns an error
type TestParams struct {
ShouldFail bool `json:"shouldFail" jsonschema:"description=Whether to fail"`
}
testHandler := func(ctx context.Context, args TestParams) (string, error) {
if args.ShouldFail {
return "", assert.AnError
}
return "success", nil
}
// Create tool
tool := MustTool("failing_tool", "A tool that can fail", testHandler)
// Create context (spans always created)
config := GrafanaConfig{}
ctx := WithGrafanaConfig(context.Background(), config)
// Create a mock MCP request that will cause failure
request := mcp.CallToolRequest{
Params: struct {
Name string `json:"name"`
Arguments any `json:"arguments,omitempty"`
Meta *mcp.Meta `json:"_meta,omitempty"`
}{
Name: "failing_tool",
Arguments: map[string]interface{}{
"shouldFail": true,
},
},
}
// Execute the tool (should fail)
result, err := tool.Handler(ctx, request)
assert.Error(t, err)
assert.Nil(t, result)
// Verify span was created and marked as error
spans := spanRecorder.Ended()
require.Len(t, spans, 1)
span := spans[0]
assert.Equal(t, "mcp.tool.failing_tool", span.Name())
assert.Equal(t, codes.Error, span.Status().Code)
assert.Equal(t, assert.AnError.Error(), span.Status().Description)
// Verify error was recorded (check events for error record)
events := span.Events()
hasErrorEvent := false
for _, event := range events {
if event.Name == "exception" {
hasErrorEvent = true
break
}
}
assert.True(t, hasErrorEvent, "Expected error event to be recorded on span")
})
t.Run("spans always created for context propagation", func(t *testing.T) {
// Clear any previous spans
spanRecorder.Reset()
// Define a simple test tool
type TestParams struct {
Message string `json:"message" jsonschema:"description=Test message"`
}
testHandler := func(ctx context.Context, args TestParams) (string, error) {
return "processed", nil
}
// Create tool
tool := MustTool("context_prop_tool", "A tool for context propagation", testHandler)
// Create context with default config (no special flags)
config := GrafanaConfig{}
ctx := WithGrafanaConfig(context.Background(), config)
// Create a mock MCP request
request := mcp.CallToolRequest{
Params: struct {
Name string `json:"name"`
Arguments any `json:"arguments,omitempty"`
Meta *mcp.Meta `json:"_meta,omitempty"`
}{
Name: "context_prop_tool",
Arguments: map[string]interface{}{
"message": "test",
},
},
}
// Execute the tool (should always create spans for context propagation)
result, err := tool.Handler(ctx, request)
require.NoError(t, err)
require.NotNil(t, result)
// Verify spans ARE always created
spans := spanRecorder.Ended()
require.Len(t, spans, 1)
span := spans[0]
assert.Equal(t, "mcp.tool.context_prop_tool", span.Name())
assert.Equal(t, codes.Ok, span.Status().Code)
})
t.Run("arguments not logged by default (PII safety)", func(t *testing.T) {
// Clear any previous spans
spanRecorder.Reset()
// Define a simple test tool
type TestParams struct {
SensitiveData string `json:"sensitiveData" jsonschema:"description=Potentially sensitive data"`
}
testHandler := func(ctx context.Context, args TestParams) (string, error) {
return "processed", nil
}
// Create tool
tool := MustTool("sensitive_tool", "A tool with sensitive data", testHandler)
// Create context with argument logging disabled (default)
config := GrafanaConfig{
IncludeArgumentsInSpans: false, // Default: safe
}
ctx := WithGrafanaConfig(context.Background(), config)
// Create a mock MCP request with potentially sensitive data
request := mcp.CallToolRequest{
Params: struct {
Name string `json:"name"`
Arguments any `json:"arguments,omitempty"`
Meta *mcp.Meta `json:"_meta,omitempty"`
}{
Name: "sensitive_tool",
Arguments: map[string]interface{}{
"sensitiveData": "user@example.com",
},
},
}
// Execute the tool (arguments should NOT be logged by default)
result, err := tool.Handler(ctx, request)
require.NoError(t, err)
require.NotNil(t, result)
// Verify span was created
spans := spanRecorder.Ended()
require.Len(t, spans, 1)
span := spans[0]
assert.Equal(t, "mcp.tool.sensitive_tool", span.Name())
assert.Equal(t, codes.Ok, span.Status().Code)
// Check that arguments are NOT logged (PII safety)
attributes := span.Attributes()
assertHasAttribute(t, attributes, "mcp.tool.name", "sensitive_tool")
assertHasAttribute(t, attributes, "mcp.tool.description", "A tool with sensitive data")
// Verify arguments are NOT present
for _, attr := range attributes {
assert.NotEqual(t, "mcp.tool.arguments", string(attr.Key), "Arguments should not be logged by default for PII safety")
}
})
t.Run("arguments logged when argument logging enabled", func(t *testing.T) {
// Clear any previous spans
spanRecorder.Reset()
// Define a simple test tool
type TestParams struct {
SafeData string `json:"safeData" jsonschema:"description=Non-sensitive data"`
}
testHandler := func(ctx context.Context, args TestParams) (string, error) {
return "processed", nil
}
// Create tool
tool := MustTool("debug_tool", "A tool for debugging", testHandler)
// Create context with argument logging enabled
config := GrafanaConfig{
IncludeArgumentsInSpans: true,
}
ctx := WithGrafanaConfig(context.Background(), config)
// Create a mock MCP request
request := mcp.CallToolRequest{
Params: struct {
Name string `json:"name"`
Arguments any `json:"arguments,omitempty"`
Meta *mcp.Meta `json:"_meta,omitempty"`
}{
Name: "debug_tool",
Arguments: map[string]interface{}{
"safeData": "debug-value",
},
},
}
// Execute the tool (arguments SHOULD be logged when flag enabled)
result, err := tool.Handler(ctx, request)
require.NoError(t, err)
require.NotNil(t, result)
// Verify span was created
spans := spanRecorder.Ended()
require.Len(t, spans, 1)
span := spans[0]
assert.Equal(t, "mcp.tool.debug_tool", span.Name())
assert.Equal(t, codes.Ok, span.Status().Code)
// Check that arguments ARE logged when flag enabled
attributes := span.Attributes()
assertHasAttribute(t, attributes, "mcp.tool.name", "debug_tool")
assertHasAttribute(t, attributes, "mcp.tool.description", "A tool for debugging")
assertHasAttribute(t, attributes, "mcp.tool.arguments", `{"safeData":"debug-value"}`)
})
}
func TestHTTPTracingConfiguration(t *testing.T) {
t.Run("HTTP tracing always enabled for context propagation", func(t *testing.T) {
// Create context (HTTP tracing always enabled)
config := GrafanaConfig{}
ctx := WithGrafanaConfig(context.Background(), config)
// Create Grafana client
client := NewGrafanaClient(ctx, "http://localhost:3000", "test-api-key")
require.NotNil(t, client)
// Verify the client was created successfully (should not panic)
assert.NotNil(t, client.Transport)
})
t.Run("tracing works gracefully without OpenTelemetry configured", func(t *testing.T) {
// No OpenTelemetry tracer provider configured
// Create context (tracing always enabled for context propagation)
config := GrafanaConfig{}
ctx := WithGrafanaConfig(context.Background(), config)
// Create Grafana client (should not panic even without OTEL configured)
client := NewGrafanaClient(ctx, "http://localhost:3000", "test-api-key")
require.NotNil(t, client)
// Verify the client was created successfully
assert.NotNil(t, client.Transport)
})
}
// Helper function to check if an attribute exists with expected value
func assertHasAttribute(t *testing.T, attributes []attribute.KeyValue, key string, expectedValue string) {
for _, attr := range attributes {
if string(attr.Key) == key {
assert.Equal(t, expectedValue, attr.Value.AsString())
return
}
}
t.Errorf("Expected attribute %s with value %s not found", key, expectedValue)
}