Repository navigation
Expand file tree
/
Copy pathoncall.go
More file actions
775 lines (675 loc) · 27.5 KB
/
Copy pathoncall.go
File metadata and controls
775 lines (675 loc) · 27.5 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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
package tools
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"reflect"
"strings"
aapi "github.com/grafana/amixr-api-go-client"
mcpgrafana "github.com/grafana/mcp-grafana/v2"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// getOnCallURLFromSettings retrieves the OnCall API URL from the Grafana settings endpoint.
// Only used for the public API fallback path (when no OBO tokens are available).
func getOnCallURLFromSettings(ctx context.Context, cfg mcpgrafana.GrafanaConfig) (string, error) {
settingsURL := fmt.Sprintf("%s/api/plugins/grafana-irm-app/settings", cfg.URL)
req, err := http.NewRequestWithContext(ctx, "GET", settingsURL, nil)
if err != nil {
return "", fmt.Errorf("creating settings request: %w", err)
}
transport, err := mcpgrafana.BuildTransport(&cfg, nil)
if err != nil {
return "", fmt.Errorf("building transport: %w", err)
}
httpClient := &http.Client{Transport: transport}
resp, err := httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("fetching settings: %w", err)
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("unexpected status code from settings API: %d", resp.StatusCode)
}
var settings struct {
JSONData struct {
OnCallAPIURL string `json:"onCallApiUrl"`
} `json:"jsonData"`
}
if err := json.NewDecoder(resp.Body).Decode(&settings); err != nil {
return "", fmt.Errorf("decoding settings response: %w", err)
}
if settings.JSONData.OnCallAPIURL == "" {
return "", fmt.Errorf("OnCall API URL is not set in settings")
}
return settings.JSONData.OnCallAPIURL, nil
}
// oncallClientFromContext creates an amixr client for the public OnCall API.
// Used as fallback when OBO auth is not available (OSS / self-hosted with API key).
func oncallClientFromContext(ctx context.Context) (*aapi.Client, error) {
cfg := mcpgrafana.GrafanaConfigFromContext(ctx)
grafanaOnCallURL, err := getOnCallURLFromSettings(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("getting OnCall URL from settings: %w", err)
}
grafanaOnCallURL = strings.TrimRight(grafanaOnCallURL, "/")
client, err := aapi.NewWithGrafanaURL(grafanaOnCallURL, cfg.APIKey, cfg.URL)
if err != nil {
return nil, fmt.Errorf("creating OnCall client: %w", err)
}
// Customize the HTTP client's transport using reflection since the
// OnCall client doesn't expose its HTTP client directly. Auth is
// handled by the OnCall library (API key passed above), so we skip it.
transportInstalled := false
clientValue := reflect.ValueOf(client)
if clientValue.Kind() == reflect.Pointer && !clientValue.IsNil() {
clientValue = clientValue.Elem()
if clientValue.Kind() == reflect.Struct {
httpClientField := clientValue.FieldByName("HTTPClient")
if !httpClientField.IsValid() {
httpClientField = clientValue.FieldByName("HttpClient")
}
if !httpClientField.IsValid() {
httpClientField = clientValue.FieldByName("Client")
}
if httpClientField.IsValid() && httpClientField.CanSet() {
if httpClient, ok := httpClientField.Interface().(*http.Client); ok {
transport, err := mcpgrafana.BuildTransport(&cfg, nil, mcpgrafana.WithoutAuth())
if err != nil {
if cfg.SOCKS5ProxyURL != "" {
// Fail closed: a default transport would bypass the configured proxy.
return nil, fmt.Errorf("building transport for OnCall client: %w", err)
}
mcpgrafana.LoggerFromContext(ctx).Error("Failed to build transport for OnCall client", "error", err)
} else {
httpClient.Transport = transport
transportInstalled = true
}
}
}
}
}
if cfg.SOCKS5ProxyURL != "" && !transportInstalled {
// Fail closed: the reflection above could not reach the OnCall
// client's HTTP client, so its default transport would bypass the
// configured proxy.
return nil, fmt.Errorf("SOCKS5 proxy is configured but the OnCall client's transport could not be replaced")
}
return client, nil
}
// --- Schedules ---
type ListOnCallSchedulesParams struct {
TeamID string `json:"teamId,omitempty" jsonschema:"description=The ID of the team to list schedules for"`
ScheduleID string `json:"scheduleId,omitempty" jsonschema:"description=The ID of the schedule to get details for. If provided\\, returns only that schedule's details"`
Page int `json:"page,omitempty" jsonschema:"description=The page number to return (1-based)"`
}
// ScheduleSummary represents a simplified view of an OnCall schedule.
type ScheduleSummary struct {
ID string `json:"id" jsonschema:"description=The unique identifier of the schedule"`
Name string `json:"name" jsonschema:"description=The name of the schedule"`
TeamID string `json:"teamId" jsonschema:"description=The ID of the team this schedule belongs to"`
Timezone string `json:"timezone" jsonschema:"description=The timezone for this schedule"`
Shifts []string `json:"shifts" jsonschema:"description=List of shift IDs in this schedule"`
}
func listOnCallSchedules(ctx context.Context, args ListOnCallSchedulesParams) ([]*ScheduleSummary, error) {
if useOncallProxy(ctx) {
return proxyListSchedules(ctx, args)
}
return amixrListSchedules(ctx, args)
}
func amixrListSchedules(ctx context.Context, args ListOnCallSchedulesParams) ([]*ScheduleSummary, error) {
client, err := oncallClientFromContext(ctx)
if err != nil {
return nil, fmt.Errorf("getting OnCall client: %w", err)
}
scheduleService := aapi.NewScheduleService(client)
if args.ScheduleID != "" {
schedule, _, err := scheduleService.GetSchedule(args.ScheduleID, &aapi.GetScheduleOptions{})
if err != nil {
return nil, fmt.Errorf("getting OnCall schedule %s: %w", args.ScheduleID, err)
}
summary := &ScheduleSummary{
ID: schedule.ID,
Name: schedule.Name,
TeamID: schedule.TeamId,
Timezone: schedule.TimeZone,
}
if schedule.Shifts != nil {
summary.Shifts = *schedule.Shifts
}
return []*ScheduleSummary{summary}, nil
}
listOptions := &aapi.ListScheduleOptions{}
if args.Page > 0 {
listOptions.Page = args.Page
}
if args.TeamID != "" {
listOptions.TeamID = args.TeamID
}
response, _, err := scheduleService.ListSchedules(listOptions)
if err != nil {
return nil, fmt.Errorf("listing OnCall schedules: %w", err)
}
summaries := make([]*ScheduleSummary, 0, len(response.Schedules))
for _, schedule := range response.Schedules {
summary := &ScheduleSummary{
ID: schedule.ID,
Name: schedule.Name,
TeamID: schedule.TeamId,
Timezone: schedule.TimeZone,
}
if schedule.Shifts != nil {
summary.Shifts = *schedule.Shifts
}
summaries = append(summaries, summary)
}
return summaries, nil
}
var ListOnCallSchedules = mcpgrafana.MustTool(
"list_oncall_schedules",
"List Grafana OnCall schedules, optionally filtering by team ID. If a specific schedule ID is provided, retrieves details for only that schedule. Returns a list of schedule summaries including ID, name, team ID, timezone, and shift IDs. Supports pagination.",
listOnCallSchedules,
mcpgrafana.WithTitleAnnotation("List OnCall schedules"),
mcpgrafana.WithIdempotentHintAnnotation(true),
mcpgrafana.WithReadOnlyHintAnnotation(true),
mcpgrafana.WithDestructiveHintAnnotation(false),
mcpgrafana.WithOpenWorldHintAnnotation(false),
mcpgrafana.RequiresPermissions("plugins.app:access", "grafana-irm-app.schedules:read"),
)
// --- Shifts ---
type GetOnCallShiftParams struct {
ShiftID string `json:"shiftId" jsonschema:"required,description=The ID of the shift to get details for"`
}
func getOnCallShift(ctx context.Context, args GetOnCallShiftParams) (*OnCallShift, error) {
if useOncallProxy(ctx) {
return proxyGetShift(ctx, args.ShiftID)
}
return amixrGetShift(ctx, args.ShiftID)
}
func amixrGetShift(ctx context.Context, shiftID string) (*OnCallShift, error) {
client, err := oncallClientFromContext(ctx)
if err != nil {
return nil, fmt.Errorf("getting OnCall client: %w", err)
}
shiftService := aapi.NewOnCallShiftService(client)
shift, _, err := shiftService.GetOnCallShift(shiftID, &aapi.GetOnCallShiftOptions{})
if err != nil {
return nil, fmt.Errorf("getting OnCall shift %s: %w", shiftID, err)
}
return &OnCallShift{
ID: shift.ID,
Name: shift.Name,
Type: shift.Type,
PriorityLevel: shift.Level,
ShiftStart: shift.Start,
RotationStart: shift.Start, // amixr only has one "start" field
Frequency: shift.Frequency,
Interval: derefIntOr(shift.Interval, 0),
ByDay: derefStrSlice(shift.ByDay),
WeekStart: derefStrOr(shift.WeekStart, ""),
RollingUsers: shift.RollingUsers,
Until: derefStrOr(shift.Until, ""),
}, nil
}
var GetOnCallShift = mcpgrafana.MustTool(
"get_oncall_shift",
"Get detailed information for a specific Grafana OnCall shift using its ID. A shift represents a designated time period within a schedule when users are actively on-call. Returns the full shift details.",
getOnCallShift,
mcpgrafana.WithTitleAnnotation("Get OnCall shift"),
mcpgrafana.WithIdempotentHintAnnotation(true),
mcpgrafana.WithReadOnlyHintAnnotation(true),
mcpgrafana.WithDestructiveHintAnnotation(false),
mcpgrafana.WithOpenWorldHintAnnotation(false),
mcpgrafana.RequiresPermissions("plugins.app:access", "grafana-irm-app.schedules:read"),
)
// --- Current On-Call Users ---
// CurrentOnCallUsers represents the currently on-call users for a schedule.
type CurrentOnCallUsers struct {
ScheduleID string `json:"scheduleId" jsonschema:"description=The ID of the schedule"`
ScheduleName string `json:"scheduleName" jsonschema:"description=The name of the schedule"`
Users []*OnCallUser `json:"users" jsonschema:"description=List of users currently on call"`
}
type GetCurrentOnCallUsersParams struct {
ScheduleID string `json:"scheduleId" jsonschema:"required,description=The ID of the schedule to get current on-call users for"`
}
func getCurrentOnCallUsers(ctx context.Context, args GetCurrentOnCallUsersParams) (*CurrentOnCallUsers, error) {
if useOncallProxy(ctx) {
return proxyGetCurrentOnCallUsers(ctx, args.ScheduleID)
}
return amixrGetCurrentOnCallUsers(ctx, args.ScheduleID)
}
func amixrGetCurrentOnCallUsers(ctx context.Context, scheduleID string) (*CurrentOnCallUsers, error) {
client, err := oncallClientFromContext(ctx)
if err != nil {
return nil, fmt.Errorf("getting OnCall client: %w", err)
}
scheduleService := aapi.NewScheduleService(client)
schedule, _, err := scheduleService.GetSchedule(scheduleID, &aapi.GetScheduleOptions{})
if err != nil {
return nil, fmt.Errorf("getting schedule %s: %w", scheduleID, err)
}
result := &CurrentOnCallUsers{
ScheduleID: schedule.ID,
ScheduleName: schedule.Name,
Users: make([]*OnCallUser, 0, len(schedule.OnCallNow)),
}
if len(schedule.OnCallNow) == 0 {
return result, nil
}
userService := aapi.NewUserService(client)
for _, userID := range schedule.OnCallNow {
user, _, err := userService.GetUser(userID, &aapi.GetUserOptions{})
if err != nil {
continue
}
result.Users = append(result.Users, &OnCallUser{
ID: user.ID,
Username: user.Username,
Email: user.Email,
Role: user.Role,
})
}
return result, nil
}
var GetCurrentOnCallUsers = mcpgrafana.MustTool(
"get_current_oncall_users",
"Get the list of users currently on-call for a specific Grafana OnCall schedule ID. Returns the schedule ID, name, and a list of detailed user objects for those currently on call.",
getCurrentOnCallUsers,
mcpgrafana.WithTitleAnnotation("Get current on-call users"),
mcpgrafana.WithIdempotentHintAnnotation(true),
mcpgrafana.WithReadOnlyHintAnnotation(true),
mcpgrafana.WithDestructiveHintAnnotation(false),
mcpgrafana.WithOpenWorldHintAnnotation(false),
mcpgrafana.RequiresPermissions(
"plugins.app:access", "grafana-irm-app.schedules:read", "grafana-irm-app.user-settings:read",
),
)
// --- Teams ---
type ListOnCallTeamsParams struct {
Page int `json:"page,omitempty" jsonschema:"description=The page number to return"`
}
func listOnCallTeams(ctx context.Context, args ListOnCallTeamsParams) ([]*OnCallTeam, error) {
if useOncallProxy(ctx) {
return proxyListTeams(ctx, args)
}
return amixrListTeams(ctx, args)
}
func amixrListTeams(ctx context.Context, args ListOnCallTeamsParams) ([]*OnCallTeam, error) {
client, err := oncallClientFromContext(ctx)
if err != nil {
return nil, fmt.Errorf("getting OnCall client: %w", err)
}
teamService := aapi.NewTeamService(client)
listOptions := &aapi.ListTeamOptions{}
if args.Page > 0 {
listOptions.Page = args.Page
}
response, _, err := teamService.ListTeams(listOptions)
if err != nil {
return nil, fmt.Errorf("listing OnCall teams: %w", err)
}
result := make([]*OnCallTeam, 0, len(response.Teams))
for _, team := range response.Teams {
result = append(result, &OnCallTeam{
ID: team.ID,
Name: team.Name,
Email: team.Email,
AvatarURL: team.AvatarUrl,
})
}
return result, nil
}
var ListOnCallTeams = mcpgrafana.MustTool(
"list_oncall_teams",
"List teams configured in Grafana OnCall. Returns a list of team objects with their details. Supports pagination.",
listOnCallTeams,
mcpgrafana.WithTitleAnnotation("List OnCall teams"),
mcpgrafana.WithIdempotentHintAnnotation(true),
mcpgrafana.WithReadOnlyHintAnnotation(true),
mcpgrafana.WithDestructiveHintAnnotation(false),
mcpgrafana.WithOpenWorldHintAnnotation(false),
mcpgrafana.RequiresPermissions("plugins.app:access", "grafana-irm-app.user-settings:read"),
)
// --- Users ---
type ListOnCallUsersParams struct {
UserID string `json:"userId,omitempty" jsonschema:"description=The ID of the user to get details for. If provided\\, returns only that user's details"`
Username string `json:"username,omitempty" jsonschema:"description=The username to filter users by. If provided\\, returns only the user matching this username"`
Page int `json:"page,omitempty" jsonschema:"description=The page number to return"`
}
func listOnCallUsers(ctx context.Context, args ListOnCallUsersParams) ([]*OnCallUser, error) {
if useOncallProxy(ctx) {
return proxyListUsers(ctx, args)
}
return amixrListUsers(ctx, args)
}
func amixrListUsers(ctx context.Context, args ListOnCallUsersParams) ([]*OnCallUser, error) {
client, err := oncallClientFromContext(ctx)
if err != nil {
return nil, fmt.Errorf("getting OnCall client: %w", err)
}
userService := aapi.NewUserService(client)
if args.UserID != "" {
user, _, err := userService.GetUser(args.UserID, &aapi.GetUserOptions{})
if err != nil {
return nil, fmt.Errorf("getting OnCall user %s: %w", args.UserID, err)
}
return []*OnCallUser{{
ID: user.ID,
Username: user.Username,
Email: user.Email,
Role: user.Role,
}}, nil
}
listOptions := &aapi.ListUserOptions{}
if args.Page > 0 {
listOptions.Page = args.Page
}
if args.Username != "" {
listOptions.Username = args.Username
}
response, _, err := userService.ListUsers(listOptions)
if err != nil {
return nil, fmt.Errorf("listing OnCall users: %w", err)
}
result := make([]*OnCallUser, 0, len(response.Users))
for _, user := range response.Users {
result = append(result, &OnCallUser{
ID: user.ID,
Username: user.Username,
Email: user.Email,
Role: user.Role,
})
}
return result, nil
}
var ListOnCallUsers = mcpgrafana.MustTool(
"list_oncall_users",
"List users from Grafana OnCall. These are OnCall users (separate from Grafana users). Can retrieve all users in the OnCall directory, a specific user by ID, or filter by username. Returns a list of user objects with their details. Supports pagination.",
listOnCallUsers,
mcpgrafana.WithTitleAnnotation("List OnCall users"),
mcpgrafana.WithIdempotentHintAnnotation(true),
mcpgrafana.WithReadOnlyHintAnnotation(true),
mcpgrafana.WithDestructiveHintAnnotation(false),
mcpgrafana.WithOpenWorldHintAnnotation(false),
mcpgrafana.RequiresPermissions("plugins.app:access", "grafana-irm-app.user-settings:read"),
)
// --- Alert Groups ---
type ListAlertGroupsParams struct {
Page int `json:"page,omitempty" jsonschema:"description=The page number to return"`
AlertGroupID string `json:"id,omitempty" jsonschema:"description=Filter by specific alert group ID"`
RouteID string `json:"routeId,omitempty" jsonschema:"description=Filter by route ID"`
IntegrationID string `json:"integrationId,omitempty" jsonschema:"description=Filter by integration ID"`
State string `json:"state,omitempty" jsonschema:"description=Filter by alert group state (one of: new\\, acknowledged\\, resolved\\, silenced)"`
TeamID string `json:"teamId,omitempty" jsonschema:"description=Filter by team ID"`
StartedAt string `json:"startedAt,omitempty" jsonschema:"description=Filter by time range in format '{start}_{end}' ISO 8601 timestamp range (UTC assumed\\, no timezone indicator needed) (e.g.\\, '2025-01-19T00:00:00_2025-01-19T23:59:59')"`
Labels []string `json:"labels,omitempty" jsonschema:"description=Filter by labels in format key:value (e.g.\\, ['env:prod'\\, 'severity:high'])"`
Name string `json:"name,omitempty" jsonschema:"description=Filter by alert group name"`
}
func listAlertGroups(ctx context.Context, args ListAlertGroupsParams) ([]*OnCallAlertGroup, error) {
if useOncallProxy(ctx) {
return proxyListAlertGroups(ctx, args)
}
return amixrListAlertGroups(ctx, args)
}
func amixrListAlertGroups(ctx context.Context, args ListAlertGroupsParams) ([]*OnCallAlertGroup, error) {
client, err := oncallClientFromContext(ctx)
if err != nil {
return nil, fmt.Errorf("getting OnCall client: %w", err)
}
alertGroupService := aapi.NewAlertGroupService(client)
listOptions := &aapi.ListAlertGroupOptions{}
if args.Page > 0 {
listOptions.Page = args.Page
}
if args.AlertGroupID != "" {
listOptions.AlertGroupID = args.AlertGroupID
}
if args.RouteID != "" {
listOptions.RouteID = args.RouteID
}
if args.IntegrationID != "" {
listOptions.IntegrationID = args.IntegrationID
}
if args.State != "" {
listOptions.State = args.State
}
if args.TeamID != "" {
listOptions.TeamID = args.TeamID
}
if args.StartedAt != "" {
listOptions.StartedAt = args.StartedAt
}
if len(args.Labels) > 0 {
listOptions.Labels = args.Labels
}
if args.Name != "" {
listOptions.Name = args.Name
}
response, _, err := alertGroupService.ListAlertGroups(listOptions)
if err != nil {
return nil, fmt.Errorf("listing OnCall alert groups: %w", err)
}
result := make([]*OnCallAlertGroup, 0, len(response.AlertGroups))
for _, ag := range response.AlertGroups {
result = append(result, &OnCallAlertGroup{
ID: ag.ID,
IntegrationID: ag.IntegrationID,
AlertsCount: ag.AlertsCount,
State: ag.State,
CreatedAt: ag.CreatedAt,
ResolvedAt: ag.ResolvedAt,
AcknowledgedAt: ag.AcknowledgedAt,
Title: ag.Title,
Permalinks: ag.Permalinks,
})
}
return result, nil
}
var ListAlertGroups = mcpgrafana.MustTool(
"list_alert_groups",
"List alert groups from Grafana OnCall with filtering options. Supports filtering by alert group ID, route ID, integration ID, state (new, acknowledged, resolved, silenced), team ID, time range, labels, and name. For time ranges, use format '{start}_{end}' ISO 8601 timestamp range (e.g., '2025-01-19T00:00:00_2025-01-19T23:59:59' for a specific day). For labels, use format 'key:value' (e.g., ['env:prod', 'severity:high']). Returns a list of alert group objects with their details. Supports pagination.",
listAlertGroups,
mcpgrafana.WithTitleAnnotation("List IRM alert groups"),
mcpgrafana.WithIdempotentHintAnnotation(true),
mcpgrafana.WithReadOnlyHintAnnotation(true),
mcpgrafana.WithDestructiveHintAnnotation(false),
mcpgrafana.WithOpenWorldHintAnnotation(false),
mcpgrafana.RequiresPermissions("plugins.app:access", "grafana-irm-app.alert-groups:read"),
)
type GetAlertGroupParams struct {
AlertGroupID string `json:"alertGroupId" jsonschema:"required,description=The ID of the alert group to retrieve"`
}
func getAlertGroup(ctx context.Context, args GetAlertGroupParams) (*OnCallAlertGroup, error) {
if useOncallProxy(ctx) {
return proxyGetAlertGroup(ctx, args.AlertGroupID)
}
return amixrGetAlertGroup(ctx, args.AlertGroupID)
}
// oncallAlertGroupPublic mirrors the public OnCall API's alert group response.
//
// It exists because aapi.AlertGroup omits last_alert, and aapi.Alert types its
// payload as a fixed struct that would discard integration-specific fields. The
// request below therefore bypasses aapi.AlertGroupService and decodes into this
// type instead.
type oncallAlertGroupPublic struct {
ID string `json:"id"`
IntegrationID string `json:"integration_id"`
AlertsCount int `json:"alerts_count"`
State string `json:"state"`
CreatedAt string `json:"created_at"`
ResolvedAt string `json:"resolved_at"`
AcknowledgedAt string `json:"acknowledged_at"`
Title string `json:"title"`
Permalinks map[string]string `json:"permalinks"`
LastAlert *OnCallLastAlert `json:"last_alert"`
}
func amixrGetAlertGroup(ctx context.Context, alertGroupID string) (*OnCallAlertGroup, error) {
client, err := oncallClientFromContext(ctx)
if err != nil {
return nil, fmt.Errorf("getting OnCall client: %w", err)
}
// Mirrors aapi.AlertGroupService.GetAlertGroup's path construction.
path := fmt.Sprintf("alert_groups/%s/", url.PathEscape(alertGroupID))
req, err := client.NewRequest(http.MethodGet, path, nil)
if err != nil {
return nil, fmt.Errorf("creating OnCall alert group request %s: %w", alertGroupID, err)
}
var ag oncallAlertGroupPublic
if _, err := client.Do(req, &ag); err != nil {
return nil, fmt.Errorf("getting OnCall alert group %s: %w", alertGroupID, err)
}
return &OnCallAlertGroup{
ID: ag.ID,
IntegrationID: ag.IntegrationID,
AlertsCount: ag.AlertsCount,
State: ag.State,
CreatedAt: ag.CreatedAt,
ResolvedAt: ag.ResolvedAt,
AcknowledgedAt: ag.AcknowledgedAt,
Title: ag.Title,
Permalinks: ag.Permalinks,
LastAlert: ag.LastAlert,
}, nil
}
var GetAlertGroup = mcpgrafana.MustTool(
"get_alert_group",
"Get a specific alert group from Grafana OnCall by its ID. Returns the full alert group details, including the most recent alert and its raw payload when the OnCall API provides them. Alert payloads carry integration-specific fingerprints (for example Sentry's payload.data.event.hashes or Alertmanager's payload.alerts[].fingerprint) that identify recurring alerts across different alert groups.",
getAlertGroup,
mcpgrafana.WithTitleAnnotation("Get IRM alert group"),
mcpgrafana.WithIdempotentHintAnnotation(true),
mcpgrafana.WithReadOnlyHintAnnotation(true),
mcpgrafana.WithDestructiveHintAnnotation(false),
mcpgrafana.WithOpenWorldHintAnnotation(false),
mcpgrafana.RequiresPermissions("plugins.app:access", "grafana-irm-app.alert-groups:read"),
)
type UpdateAlertGroupParams struct {
AlertGroupID string `json:"alertGroupId" jsonschema:"required,description=The ID of the alert group to update"`
State string `json:"state" jsonschema:"required,description=New state for the alert group. One of: acknowledged\\, unacknowledged\\, resolved\\, unresolved"`
}
type UpdateAlertGroupResult struct {
AlertGroupID string `json:"alertGroupId"`
Action string `json:"action"`
Updated bool `json:"updated"`
State string `json:"state,omitempty"`
StateWarning string `json:"stateWarning,omitempty"`
}
// alertGroupActionForState maps a requested end state onto the OnCall action
// endpoint that produces it. OnCall has no single "set the state" endpoint;
// every transition is its own POST, and "unacknowledged"/"unresolved" name
// transitions rather than states (OnCall itself only ever reports new,
// acknowledged, resolved or silenced).
func alertGroupActionForState(state string) (string, error) {
switch strings.ToLower(strings.TrimSpace(state)) {
case "acknowledged":
return "acknowledge", nil
case "unacknowledged":
return "unacknowledge", nil
case "resolved":
return "resolve", nil
case "unresolved":
return "unresolve", nil
default:
return "", fmt.Errorf("unsupported alert group state %q: expected acknowledged, unacknowledged, resolved, or unresolved", state)
}
}
// updateAlertGroup transitions an alert group and then reads it back, so the
// caller is told OnCall's real resulting state instead of the transition it
// asked for. The write has already been committed by the time the read runs,
// so a read failure is reported in stateWarning rather than as a tool error:
// failing the call would invite a caller to retry a mutation that has already
// happened. Note this means the tool wants alert-groups:read alongside
// alert-groups:write to return a state at all.
func updateAlertGroup(ctx context.Context, args UpdateAlertGroupParams) (*UpdateAlertGroupResult, error) {
if strings.TrimSpace(args.AlertGroupID) == "" {
return nil, fmt.Errorf("alertGroupId is required")
}
action, err := alertGroupActionForState(args.State)
if err != nil {
return nil, err
}
if useOncallProxy(ctx) {
err = proxyUpdateAlertGroup(ctx, args.AlertGroupID, action)
} else {
err = amixrUpdateAlertGroup(ctx, args.AlertGroupID, action)
}
if err != nil {
return nil, err
}
result := &UpdateAlertGroupResult{
AlertGroupID: args.AlertGroupID,
Action: action,
Updated: true,
}
ag, err := getAlertGroup(ctx, GetAlertGroupParams{AlertGroupID: args.AlertGroupID})
if err != nil {
result.StateWarning = fmt.Sprintf(
"the %s succeeded but the resulting state could not be read back (does the caller have alert-groups:read?): %s",
action, err,
)
return result, nil
}
result.State = ag.State
return result, nil
}
func amixrUpdateAlertGroup(ctx context.Context, alertGroupID, action string) error {
client, err := oncallClientFromContext(ctx)
if err != nil {
return fmt.Errorf("getting OnCall client: %w", err)
}
path := fmt.Sprintf("alert_groups/%s/%s", url.PathEscape(alertGroupID), action)
req, err := client.NewRequest(http.MethodPost, path, nil)
if err != nil {
return fmt.Errorf("creating OnCall %s request for alert group %s: %w", action, alertGroupID, err)
}
if _, err := client.Do(req, nil); err != nil {
return fmt.Errorf("%s OnCall alert group %s: %w", action, alertGroupID, err)
}
return nil
}
var UpdateAlertGroup = mcpgrafana.MustTool(
"update_alert_group",
"Update the state of a Grafana OnCall alert group: acknowledge, unacknowledge, resolve, or unresolve it by ID. Returns the alert group's resulting OnCall state (one of new, acknowledged, resolved, silenced), or a stateWarning explaining why that state could not be read back after a successful update.",
updateAlertGroup,
mcpgrafana.WithTitleAnnotation("Update IRM alert group"),
mcpgrafana.WithIdempotentHintAnnotation(false),
mcpgrafana.WithReadOnlyHintAnnotation(false),
mcpgrafana.WithDestructiveHintAnnotation(true),
mcpgrafana.WithOpenWorldHintAnnotation(false),
mcpgrafana.RequiresPermissions(
"plugins.app:access", "grafana-irm-app.alert-groups:read", "grafana-irm-app.alert-groups:write",
),
)
func AddOnCallTools(s *mcp.Server, enableWriteTools bool) {
ListOnCallSchedules.Register(s)
GetOnCallShift.Register(s)
GetCurrentOnCallUsers.Register(s)
ListOnCallTeams.Register(s)
ListOnCallUsers.Register(s)
ListAlertGroups.Register(s)
GetAlertGroup.Register(s)
if enableWriteTools {
UpdateAlertGroup.Register(s)
}
}
// helpers for converting amixr pointer types
func derefStrOr(p *string, fallback string) string {
if p != nil {
return *p
}
return fallback
}
func derefIntOr(p *int, fallback int) int {
if p != nil {
return *p
}
return fallback
}
func derefStrSlice(p *[]string) []string {
if p != nil {
return *p
}
return nil
}