diff --git a/pkg/cli/mcp_server.go b/pkg/cli/mcp_server.go index ea7797c76e4..faf4249cfee 100644 --- a/pkg/cli/mcp_server.go +++ b/pkg/cli/mcp_server.go @@ -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 != "" { @@ -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 @@ -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 @@ -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{ @@ -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 @@ -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"} @@ -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{ @@ -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"} diff --git a/pkg/cli/mcp_server_test.go b/pkg/cli/mcp_server_test.go index 030f8abd21c..34de8b50296 100644 --- a/pkg/cli/mcp_server_test.go +++ b/pkg/cli/mcp_server_test.go @@ -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 + }) + } +}