Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion e2e/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,3 @@ When adding new tests:
2. Use `callTool()` helper for making tool calls
3. Use `unmarshalToolResponse()` for parsing responses
4. For tests that create resources, ensure proper cleanup in `t.Cleanup()`
5. Consider using the native API client (`getAPIClient()`) for verification
74 changes: 35 additions & 39 deletions e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"testing"
"time"

sdk "github.com/flashcatcloud/flashduty-sdk"
mcpClient "github.com/mark3labs/mcp-go/client"
"github.com/mark3labs/mcp-go/mcp"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -57,23 +56,6 @@ func getE2EBaseURL() string {
return baseURL
}

// getAPIClient creates a native Flashduty SDK client for verification purposes
func getAPIClient(t *testing.T) *sdk.Client {
appKey := getE2EAppKey(t)
baseURL := getE2EBaseURL()

opts := []sdk.Option{
sdk.WithUserAgent("e2e-test-client/1.0.0"),
}
if baseURL != "" {
opts = append(opts, sdk.WithBaseURL(baseURL))
}
client, err := sdk.NewClient(appKey, opts...)
require.NoError(t, err, "expected to create Flashduty SDK client")

return client
}

// ensureDockerImageBuilt makes sure the Docker image is built only once across all tests
func ensureDockerImageBuilt(t *testing.T) {
buildOnce.Do(func() {
Expand Down Expand Up @@ -420,21 +402,24 @@ func TestQueryIncidents(t *testing.T) {

t.Log("Querying incidents from the last 7 days...")
responseText := callTool(t, mcpClient, "query_incidents", map[string]any{
"since": strconv.FormatInt(startTime, 10),
"until": strconv.FormatInt(now, 10),
"limit": 10,
"since": strconv.FormatInt(startTime, 10),
"until": strconv.FormatInt(now, 10),
"limit": 10,
})

var result struct {
Incidents []struct {
IncidentID string `json:"incident_id"`
Title string `json:"title"`
Severity string `json:"severity"`
Progress string `json:"progress"`
ChannelID int64 `json:"channel_id"`
ChannelName string `json:"channel_name,omitempty"`
CreatedAt int64 `json:"created_at"`
AlertsTotal int `json:"alerts_total,omitempty"`
IncidentID string `json:"incident_id"`
Title string `json:"title"`
// go-flashduty renames severity -> incident_severity and renders
// created_at as an RFC3339 string (Timestamp type) instead of a
// Unix integer; alerts_total is now the server-side alert_cnt.
IncidentSeverity string `json:"incident_severity"`
Progress string `json:"progress"`
ChannelID int64 `json:"channel_id"`
ChannelName string `json:"channel_name,omitempty"`
CreatedAt string `json:"created_at"`
AlertCnt int `json:"alert_cnt,omitempty"`
} `json:"incidents"`
Total int `json:"total"`
}
Expand Down Expand Up @@ -603,15 +588,15 @@ func TestIncidentLifecycle(t *testing.T) {
// Step 2: Query the incident to verify it was created
t.Log("Querying the created incident...")
queryResponseText := callTool(t, mcpClient, "query_incidents", map[string]any{
"incident_ids": incidentID,
"incident_ids": incidentID,
})

var queryResult struct {
Incidents []struct {
IncidentID string `json:"incident_id"`
Title string `json:"title"`
Progress string `json:"progress"`
Severity string `json:"severity"`
IncidentID string `json:"incident_id"`
Title string `json:"title"`
Progress string `json:"progress"`
IncidentSeverity string `json:"incident_severity"`
} `json:"incidents"`
Total int `json:"total"`
}
Expand Down Expand Up @@ -640,7 +625,7 @@ func TestIncidentLifecycle(t *testing.T) {
// Step 4: Verify the incident is now in Processing state
t.Log("Verifying incident is in Processing state...")
queryResponseText = callTool(t, mcpClient, "query_incidents", map[string]any{
"incident_ids": incidentID,
"incident_ids": incidentID,
})
unmarshalToolResponse(t, queryResponseText, &queryResult)

Expand All @@ -665,7 +650,7 @@ func TestIncidentLifecycle(t *testing.T) {
// Step 6: Verify the incident is now Closed
t.Log("Verifying incident is Closed...")
queryResponseText = callTool(t, mcpClient, "query_incidents", map[string]any{
"incident_ids": incidentID,
"incident_ids": incidentID,
})
unmarshalToolResponse(t, queryResponseText, &queryResult)

Expand Down Expand Up @@ -722,7 +707,8 @@ func TestIncidentQueryByTimeline(t *testing.T) {
IncidentID string `json:"incident_id"`
Timeline []struct {
Type string `json:"type"`
Timestamp int64 `json:"timestamp"`
CreatedAt string `json:"created_at"`
CreatorID int64 `json:"creator_id"`
Detail any `json:"detail,omitempty"`
} `json:"timeline"`
Total int `json:"total"`
Expand All @@ -735,7 +721,8 @@ func TestIncidentQueryByTimeline(t *testing.T) {

var timeline []struct {
Type string `json:"type"`
Timestamp int64 `json:"timestamp"`
CreatedAt string `json:"created_at"`
CreatorID int64 `json:"creator_id"`
Detail any `json:"detail,omitempty"`
}
for _, r := range timelineResult.Results {
Expand All @@ -746,6 +733,15 @@ func TestIncidentQueryByTimeline(t *testing.T) {
}
require.NotEmpty(t, timeline, "expected at least one timeline event")

// Assert the migrated shape (raw go-flashduty IncidentFeedItem): each event
// carries created_at as an RFC3339 string (TimestampMilli), not a raw epoch
// int, and a numeric creator_id. This pins the post-migration contract so a
// future shape drift cannot pass silently.
for _, event := range timeline {
require.NotEmpty(t, event.CreatedAt, "timeline event missing created_at")
require.Contains(t, event.CreatedAt, "T", "created_at must be RFC3339, got %q", event.CreatedAt)
}

t.Logf("Found %d timeline events", len(timeline))

// Verify the first event is the creation event
Expand Down Expand Up @@ -820,7 +816,7 @@ func TestUpdateIncident(t *testing.T) {
// Verify the update
t.Log("Verifying the update...")
queryResponseText := callTool(t, mcpClient, "query_incidents", map[string]any{
"incident_ids": incidentID,
"incident_ids": incidentID,
})

var queryResult struct {
Expand Down
14 changes: 7 additions & 7 deletions e2e/fixes_validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ func TestQueryIncidentsChannelFilter(t *testing.T) {
startTime := now - 30*24*60*60

allText := callTool(t, mcpClient, "query_incidents", map[string]any{
"since": strconv.FormatInt(startTime, 10),
"until": strconv.FormatInt(now, 10),
"limit": 100,
"since": strconv.FormatInt(startTime, 10),
"until": strconv.FormatInt(now, 10),
"limit": 100,
})
var allResp struct {
Incidents []struct {
Expand Down Expand Up @@ -58,10 +58,10 @@ func TestQueryIncidentsChannelFilter(t *testing.T) {
target, maxCount, otherChannelCount)

filteredText := callTool(t, mcpClient, "query_incidents", map[string]any{
"since": strconv.FormatInt(startTime, 10),
"until": strconv.FormatInt(now, 10),
"limit": 100,
"channel_ids": strconv.FormatInt(target, 10),
"since": strconv.FormatInt(startTime, 10),
"until": strconv.FormatInt(now, 10),
"limit": 100,
"channel_ids": strconv.FormatInt(target, 10),
})
var filtered struct {
Incidents []struct {
Expand Down
5 changes: 2 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ go 1.25.5

require (
github.com/bluele/gcache v0.0.2
github.com/flashcatcloud/flashduty-sdk v0.9.1
github.com/flashcatcloud/go-flashduty v0.5.2
github.com/google/go-github/v72 v72.0.0
github.com/josephburnett/jd v1.9.2
github.com/mark3labs/mcp-go v0.52.0
github.com/spf13/cobra v1.10.2
github.com/spf13/viper v1.20.1
github.com/stretchr/testify v1.10.0
github.com/toon-format/toon-go v0.0.0-20251202084852-7ca0e27c4e8c
)

require (
Expand All @@ -22,11 +23,9 @@ require (
github.com/mailru/easyjson v0.7.7 // indirect
github.com/rogpeppe/go-internal v1.13.1 // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect
github.com/toon-format/toon-go v0.0.0-20251202084852-7ca0e27c4e8c // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect
golang.org/x/sync v0.19.0 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
Expand Down
6 changes: 2 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/flashcatcloud/flashduty-sdk v0.9.1 h1:vDTkSjAJJD6Ex5r7S+VCxPi4yxSFNw1bU/SfoRCvk+k=
github.com/flashcatcloud/flashduty-sdk v0.9.1/go.mod h1:dG4eJfdZaj4jNBMwEexbfK/3PmcIMhNeJ88L/DcZzUY=
github.com/flashcatcloud/go-flashduty v0.5.2 h1:mYg/M0jqkil30WTLdICVtTJVGxEIGmae/3zBpRkwLRQ=
github.com/flashcatcloud/go-flashduty v0.5.2/go.mod h1:aA0RtZEs0AYOwwdNKdtVeD8YMOdnmVY1zAlVD+9Ovx8=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
Expand Down Expand Up @@ -96,8 +96,6 @@ go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN8
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8=
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
Expand Down
67 changes: 36 additions & 31 deletions internal/flashduty/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import (
"time"

"github.com/bluele/gcache"
sdk "github.com/flashcatcloud/flashduty-sdk"
goflashduty "github.com/flashcatcloud/go-flashduty"

"github.com/flashcatcloud/flashduty-mcp-server/pkg/flashduty"
"github.com/flashcatcloud/flashduty-mcp-server/pkg/trace"
)

Expand All @@ -30,28 +31,28 @@ func ConfigFromContext(ctx context.Context) (FlashdutyConfig, bool) {
return cfg, ok
}

// clientFromContext returns the Flashduty client from the context.
func clientFromContext(ctx context.Context) (*sdk.Client, bool) {
client, ok := ctx.Value(flashdutyClientKey).(*sdk.Client)
return client, ok
// clientsFromContext returns the Flashduty clients from the context.
func clientsFromContext(ctx context.Context) (*flashduty.Clients, bool) {
clients, ok := ctx.Value(flashdutyClientKey).(*flashduty.Clients)
return clients, ok
}

// contextWithClient adds the Flashduty client to the context.
func contextWithClient(ctx context.Context, client *sdk.Client) context.Context {
return context.WithValue(ctx, flashdutyClientKey, client)
// contextWithClients adds the Flashduty clients to the context.
func contextWithClients(ctx context.Context, clients *flashduty.Clients) context.Context {
return context.WithValue(ctx, flashdutyClientKey, clients)
}

var clientCache = gcache.New(1000).
Expiration(time.Hour).
Build()

// getClient is a helper function for tool handlers to get a flashduty client.
// It will try to get the client from the context first. If not found, it will create a new one
// based on the config in the context, and cache it in the context for future use in the same request.
// It falls back to the default config if no config is found in the context.
func getClient(ctx context.Context, defaultCfg FlashdutyConfig, version string) (context.Context, *sdk.Client, error) {
if client, ok := clientFromContext(ctx); ok {
return ctx, client, nil
// getClient is a helper for tool handlers to obtain the Flashduty clients. It
// tries the context first; on a miss it builds the typed go-flashduty client,
// caches it, and stores it on the context for reuse within the same request. It
// falls back to the default config when the context carries none.
func getClient(ctx context.Context, defaultCfg FlashdutyConfig, version string) (context.Context, *flashduty.Clients, error) {
if clients, ok := clientsFromContext(ctx); ok {
return ctx, clients, nil
}

cfg, ok := ConfigFromContext(ctx)
Expand All @@ -65,31 +66,35 @@ func getClient(ctx context.Context, defaultCfg FlashdutyConfig, version string)

// Use APP key and BaseURL as cache key to handle different environments.
cacheKey := fmt.Sprintf("%s|%s", cfg.APPKey, cfg.BaseURL)
if client, err := clientCache.Get(cacheKey); err == nil {
return contextWithClient(ctx, client.(*sdk.Client)), client.(*sdk.Client), nil
if cached, err := clientCache.Get(cacheKey); err == nil {
clients := cached.(*flashduty.Clients)
return contextWithClients(ctx, clients), clients, nil
}

userAgent := fmt.Sprintf("flashduty-mcp-server/%s", version)

opts := []sdk.Option{
sdk.WithUserAgent(userAgent),
sdk.WithRequestHook(func(req *http.Request) {
if traceCtx := trace.FromContext(req.Context()); traceCtx != nil {
traceCtx.SetHTTPHeaders(req.Header)
}
}),
requestHook := func(req *http.Request) {
if traceCtx := trace.FromContext(req.Context()); traceCtx != nil {
traceCtx.SetHTTPHeaders(req.Header)
}
}

newOpts := []goflashduty.Option{
goflashduty.WithUserAgent(userAgent),
goflashduty.WithRequestHook(requestHook),
}
if cfg.BaseURL != "" {
opts = append(opts, sdk.WithBaseURL(cfg.BaseURL))
newOpts = append(newOpts, goflashduty.WithBaseURL(cfg.BaseURL))
}

client, err := sdk.NewClient(cfg.APPKey, opts...)
newClient, err := goflashduty.NewClient(cfg.APPKey, newOpts...)
if err != nil {
return ctx, nil, fmt.Errorf("failed to create Flashduty client: %w", err)
return ctx, nil, fmt.Errorf("failed to create go-flashduty client: %w", err)
}

_ = clientCache.Set(cacheKey, client)
ctx = contextWithClient(ctx, client)
clients := &flashduty.Clients{New: newClient}

_ = clientCache.Set(cacheKey, clients)
ctx = contextWithClients(ctx, clients)

return ctx, client, nil
return ctx, clients, nil
}
7 changes: 3 additions & 4 deletions internal/flashduty/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"syscall"
"time"

sdk "github.com/flashcatcloud/flashduty-sdk"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"

Expand Down Expand Up @@ -61,7 +60,7 @@ type FlashdutyConfig struct {
func NewMCPServer(cfg FlashdutyConfig) (*server.MCPServer, error) {
// When a client send an initialize request, update the user agent to include the client info.
beforeInit := func(ctx context.Context, _ any, message *mcp.InitializeRequest) {
_, client, err := getClient(ctx, cfg, cfg.Version)
_, clients, err := getClient(ctx, cfg, cfg.Version)
if err != nil {
// Cannot return error here, just log it.
// For HTTP server, the APP key is per-request, so it might not be available
Expand All @@ -78,7 +77,7 @@ func NewMCPServer(cfg FlashdutyConfig) (*server.MCPServer, error) {
message.Params.ClientInfo.Name,
message.Params.ClientInfo.Version,
)
client.SetUserAgent(userAgent)
clients.New.UserAgent = userAgent
}

if len(cfg.EnabledToolsets) == 0 {
Expand Down Expand Up @@ -129,7 +128,7 @@ func NewMCPServer(cfg FlashdutyConfig) (*server.MCPServer, error) {

flashdutyServer := server.NewMCPServer("flashduty-mcp-server", cfg.Version, server.WithHooks(hooks))

getClientFn := func(ctx context.Context) (context.Context, *sdk.Client, error) {
getClientFn := func(ctx context.Context) (context.Context, *flashduty.Clients, error) {
return getClient(ctx, cfg, cfg.Version)
}

Expand Down
6 changes: 3 additions & 3 deletions pkg/flashduty/alerts.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"context"
"fmt"

sdk "github.com/flashcatcloud/flashduty-sdk"
flashduty "github.com/flashcatcloud/go-flashduty"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"

Expand Down Expand Up @@ -33,13 +33,13 @@ func QueryAlertEvents(getClient GetFlashdutyClientFn, t translations.Translation
return mcp.NewToolResultError(err.Error()), nil
}

output, err := client.ListAlertEvents(ctx, &sdk.ListAlertEventsInput{AlertID: alertID})
out, _, err := client.New.Alerts.ReadEventList(ctx, &flashduty.AlertEventListRequest{AlertID: alertID})
if err != nil {
return mcp.NewToolResultError(fmt.Sprintf("Unable to retrieve alert events: %v", err)), nil
}

return MarshalResult(map[string]any{
"alert_events": output.AlertEvents,
"alert_events": out.Items,
}), nil
}
}
Loading
Loading