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
88 changes: 88 additions & 0 deletions pkg/cli/mcp_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,17 @@ Returns a JSON array where each element has the following structure:

Note: Output can be filtered using the jq parameter.`,
}, func(ctx context.Context, req *mcp.CallToolRequest, args statusArgs) (*mcp.CallToolResult, any, error) {
// Check for cancellation before starting
select {
case <-ctx.Done():
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: fmt.Sprintf("Error: %v", ctx.Err())},
},
}, nil, nil
default:
}

// Build command arguments - always use JSON for MCP
cmdArgs := []string{"status", "--json"}
if args.Pattern != "" {
Expand Down Expand Up @@ -197,6 +208,17 @@ Returns JSON array with validation results for each workflow:

Note: Output can be filtered using the jq parameter.`,
}, func(ctx context.Context, req *mcp.CallToolRequest, args compileArgs) (*mcp.CallToolResult, any, error) {
// Check for cancellation before starting
select {
case <-ctx.Done():
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: fmt.Sprintf("Error: %v", ctx.Err())},
},
}, nil, nil
default:
}

// Check if any static analysis tools are requested that require Docker images
if args.Zizmor || args.Poutine || args.Actionlint {
// Check if Docker images are available; if not, start downloading and return retry message
Expand All @@ -207,6 +229,17 @@ Note: Output can be filtered using the jq parameter.`,
},
}, nil, nil
}

// Check for cancellation after Docker image preparation
select {
case <-ctx.Done():
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: fmt.Sprintf("Error: %v", ctx.Err())},
},
}, nil, nil
default:
}
}

// Build command arguments
Expand Down Expand Up @@ -298,6 +331,17 @@ to filter the output to a manageable size, or adjust the 'max_tokens' parameter.
- .runs[:5] (get first 5 runs)
- .runs | map(select(.conclusion == "failure")) (get only failed runs)`,
}, func(ctx context.Context, req *mcp.CallToolRequest, args logsArgs) (*mcp.CallToolResult, any, error) {
// Check for cancellation before starting
select {
case <-ctx.Done():
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: fmt.Sprintf("Error: %v", ctx.Err())},
},
}, nil, nil
default:
}

// Validate firewall parameters
if args.Firewall && args.NoFirewall {
return &mcp.CallToolResult{
Expand Down Expand Up @@ -410,6 +454,17 @@ Returns JSON with the following structure:

Note: Output can be filtered using the jq parameter.`,
}, func(ctx context.Context, req *mcp.CallToolRequest, args auditArgs) (*mcp.CallToolResult, any, error) {
// Check for cancellation before starting
select {
case <-ctx.Done():
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: fmt.Sprintf("Error: %v", ctx.Err())},
},
}, nil, nil
default:
}

// Build command arguments
// Force output directory to /tmp/gh-aw/aw-mcp/logs for MCP server (same as logs)
// Use --json flag to output structured JSON for MCP consumption
Expand Down Expand Up @@ -477,6 +532,17 @@ Returns formatted text output showing:
- Secret availability status (if GitHub token is available)
- Detailed tool information when tool parameter is specified`,
}, func(ctx context.Context, req *mcp.CallToolRequest, args mcpInspectArgs) (*mcp.CallToolResult, any, error) {
// Check for cancellation before starting
select {
case <-ctx.Done():
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: fmt.Sprintf("Error: %v", ctx.Err())},
},
}, nil, nil
default:
}

// Build command arguments
cmdArgs := []string{"mcp", "inspect"}

Expand Down Expand Up @@ -525,6 +591,17 @@ Returns formatted text output showing:
Name: "add",
Description: "Add workflows from remote repositories to .github/workflows",
}, func(ctx context.Context, req *mcp.CallToolRequest, args addArgs) (*mcp.CallToolResult, any, error) {
// Check for cancellation before starting
select {
case <-ctx.Done():
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: fmt.Sprintf("Error: %v", ctx.Err())},
},
}, nil, nil
default:
}

// Validate required arguments
if len(args.Workflows) == 0 {
return &mcp.CallToolResult{
Expand Down Expand Up @@ -593,6 +670,17 @@ Returns formatted text output showing:
- Updated workflows with their new versions
- Compilation status for each updated workflow`,
}, func(ctx context.Context, req *mcp.CallToolRequest, args updateArgs) (*mcp.CallToolResult, any, error) {
// Check for cancellation before starting
select {
case <-ctx.Done():
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: fmt.Sprintf("Error: %v", ctx.Err())},
},
}, nil, nil
default:
}

// Build command arguments
cmdArgs := []string{"update"}

Expand Down
85 changes: 85 additions & 0 deletions pkg/cli/mcp_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -726,3 +726,88 @@ func TestMCPServer_CapabilitiesConfiguration(t *testing.T) {

t.Logf("Server capabilities configured correctly: Tools.ListChanged = %v", serverCapabilities.Tools.ListChanged)
}

// TestMCPServer_ContextCancellation tests that tool handlers properly respond to context cancellation
func TestMCPServer_ContextCancellation(t *testing.T) {
// Skip if the binary doesn't exist
binaryPath := "../../gh-aw"
if _, err := os.Stat(binaryPath); os.IsNotExist(err) {
t.Skip("Skipping test: gh-aw binary not found. Run 'make build' first.")
}

// Get the current directory for proper path resolution
originalDir, _ := os.Getwd()

// Create MCP client
client := mcp.NewClient(&mcp.Implementation{
Name: "test-client",
Version: "1.0.0",
}, nil)

// Start the MCP server as a subprocess
serverCmd := exec.Command(filepath.Join(originalDir, binaryPath), "mcp-server")
transport := &mcp.CommandTransport{Command: serverCmd}

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

session, err := client.Connect(ctx, transport, nil)
if err != nil {
t.Fatalf("Failed to connect to MCP server: %v", err)
}
defer session.Close()

// Test context cancellation for different tools
tools := []string{"status", "audit"}

for _, toolName := range tools {
t.Run(toolName, func(t *testing.T) {
// Create a context that's already cancelled
cancelledCtx, immediateCancel := context.WithCancel(context.Background())
immediateCancel() // Cancel immediately

var params *mcp.CallToolParams
switch toolName {
case "status":
params = &mcp.CallToolParams{
Name: "status",
Arguments: map[string]any{},
}
case "audit":
params = &mcp.CallToolParams{
Name: "audit",
Arguments: map[string]any{
"run_id": int64(1),
},
}
}

// Call the tool with a cancelled context
result, err := session.CallTool(cancelledCtx, params)

// The tool should handle the cancellation gracefully
// It should either return an error OR return a result with error message
if err != nil {
// Check if it's a context cancellation error
if !strings.Contains(err.Error(), "context") && !strings.Contains(err.Error(), "cancel") {
t.Logf("Tool returned error (acceptable): %v", err)
} else {
t.Logf("Tool properly detected cancellation via error: %v", err)
}
} else if result != nil && len(result.Content) > 0 {
// Check if the result contains an error message about cancellation
if textContent, ok := result.Content[0].(*mcp.TextContent); ok {
text := textContent.Text
if strings.Contains(text, "context") || strings.Contains(text, "cancel") {
t.Logf("Tool properly detected cancellation via result: %s", text)
} else {
t.Logf("Tool returned result (may not have detected cancellation immediately): %s", text)
}
}
}

// The important thing is that the tool doesn't hang or crash
// Either returning an error or a result with error message is acceptable
})
}
}
Loading