|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using System.Runtime.InteropServices; |
| 5 | +using AzureMcp.Areas.Extension.Options; |
| 6 | +using AzureMcp.Commands.Subscription; |
| 7 | +using AzureMcp.Services.Azure.Subscription; |
| 8 | +using AzureMcp.Services.ProcessExecution; |
| 9 | +using Microsoft.Extensions.Logging; |
| 10 | + |
| 11 | +namespace AzureMcp.Areas.Extension.Commands; |
| 12 | + |
| 13 | +public sealed class AzqrCommand(ILogger<AzqrCommand> logger, int processTimeoutSeconds = 300) : SubscriptionCommand<AzqrOptions>() |
| 14 | +{ |
| 15 | + private const string CommandTitle = "Azure Quick Review CLI Command"; |
| 16 | + private readonly ILogger<AzqrCommand> _logger = logger; |
| 17 | + private readonly int _processTimeoutSeconds = processTimeoutSeconds; |
| 18 | + private static string? _cachedAzqrPath; |
| 19 | + |
| 20 | + public override string Name => "azqr"; |
| 21 | + |
| 22 | + public override string Description => |
| 23 | + """ |
| 24 | + Runs Azure Quick Review CLI (azqr) commands to generate compliance/security reports for Azure resources. |
| 25 | + This tool should be used when the user wants to identify any non-compliant configurations or areas for improvement in their Azure resources. |
| 26 | + Requires a subscription id and optionally a resource group name. Returns the generated report file's path. |
| 27 | + Note that Azure Quick Review CLI (azqr) is different from Azure CLI (az). |
| 28 | + """; |
| 29 | + |
| 30 | + public override string Title => CommandTitle; |
| 31 | + |
| 32 | + protected override void RegisterOptions(Command command) |
| 33 | + { |
| 34 | + base.RegisterOptions(command); |
| 35 | + command.AddOption(ExtensionOptionDefinitions.Azqr.OptionalResourceGroup); |
| 36 | + } |
| 37 | + |
| 38 | + [McpServerTool(Destructive = false, ReadOnly = true, Title = CommandTitle)] |
| 39 | + public override async Task<CommandResponse> ExecuteAsync(CommandContext context, ParseResult parseResult) |
| 40 | + { |
| 41 | + var options = BindOptions(parseResult); |
| 42 | + var response = context.Response; |
| 43 | + try |
| 44 | + { |
| 45 | + if (!Validate(parseResult.CommandResult, response).IsValid) |
| 46 | + { |
| 47 | + return response; |
| 48 | + } |
| 49 | + |
| 50 | + ArgumentNullException.ThrowIfNull(options.Subscription); |
| 51 | + |
| 52 | + var azqrPath = FindAzqrCliPath() ?? throw new FileNotFoundException("Azure Quick Review CLI (azqr) executable not found in PATH. Please ensure azqr is installed. Go to https://aka.ms/azqr to learn more about how to install Azure Quick Review CLI."); |
| 53 | + |
| 54 | + var subscriptionService = context.GetService<ISubscriptionService>(); |
| 55 | + var subscription = await subscriptionService.GetSubscription(options.Subscription, options.Tenant); |
| 56 | + |
| 57 | + // Compose azqr command |
| 58 | + var command = $"scan --subscription-id {subscription.Id}"; |
| 59 | + if (!string.IsNullOrWhiteSpace(options.ResourceGroup)) |
| 60 | + { |
| 61 | + command += $" --resource-group {options.ResourceGroup}"; |
| 62 | + } |
| 63 | + |
| 64 | + var tempDir = Path.GetTempPath(); |
| 65 | + var dateString = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss"); |
| 66 | + var reportFileName = Path.Combine(tempDir, $"azqr-report-{options.Subscription}-{dateString}"); |
| 67 | + |
| 68 | + // Azure Quick Review always appends the file extension to the report file's name, we need to create a new path with the file extension to check for the existence of the report file. |
| 69 | + var xlsxReportFilePath = $"{reportFileName}.xlsx"; |
| 70 | + var jsonReportFilePath = $"{reportFileName}.json"; |
| 71 | + command += $" --output-name \"{reportFileName}\""; |
| 72 | + |
| 73 | + // Azure Quick Review CLI can easily get throttle errors when scanning subscriptions with many resources with costs enabled. |
| 74 | + // Unfortunately, getting such an error will abort the entire job and waste all the partial results. |
| 75 | + // To reduce the chance of throttling, we disable costs reporting by default. |
| 76 | + command += " --costs=false"; |
| 77 | + |
| 78 | + // Also generate a JSON report for users who don't have access to Excel. |
| 79 | + command += " --json"; |
| 80 | + |
| 81 | + var processService = context.GetService<IExternalProcessService>(); |
| 82 | + var result = await processService.ExecuteAsync(azqrPath, command, _processTimeoutSeconds); |
| 83 | + |
| 84 | + if (result.ExitCode != 0) |
| 85 | + { |
| 86 | + response.Status = 500; |
| 87 | + response.Message = result.Error; |
| 88 | + return response; |
| 89 | + } |
| 90 | + |
| 91 | + if (!File.Exists(xlsxReportFilePath) && !File.Exists(jsonReportFilePath)) |
| 92 | + { |
| 93 | + response.Status = 500; |
| 94 | + response.Message = $"Report file '{xlsxReportFilePath}' and '{jsonReportFilePath}' were not found after azqr execution."; |
| 95 | + return response; |
| 96 | + } |
| 97 | + var resultObj = new AzqrReportResult(xlsxReportFilePath, jsonReportFilePath, result.Output); |
| 98 | + response.Results = ResponseResult.Create(resultObj, JsonSourceGenerationContext.Default.AzqrReportResult); |
| 99 | + response.Status = 200; |
| 100 | + response.Message = "azqr report generated successfully."; |
| 101 | + return response; |
| 102 | + } |
| 103 | + catch (Exception ex) |
| 104 | + { |
| 105 | + _logger.LogError(ex, "An exception occurred executing azqr command."); |
| 106 | + HandleException(context, ex); |
| 107 | + return response; |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + private static string? FindAzqrCliPath() |
| 112 | + { |
| 113 | + // Return cached path if available and still exists |
| 114 | + if (!string.IsNullOrEmpty(_cachedAzqrPath) && File.Exists(_cachedAzqrPath)) |
| 115 | + { |
| 116 | + return _cachedAzqrPath; |
| 117 | + } |
| 118 | + var exeName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "azqr.exe" : "azqr"; |
| 119 | + var pathEnv = Environment.GetEnvironmentVariable("PATH"); |
| 120 | + if (string.IsNullOrEmpty(pathEnv)) |
| 121 | + return null; |
| 122 | + foreach (var dir in pathEnv.Split(Path.PathSeparator)) |
| 123 | + { |
| 124 | + var fullPath = Path.Combine(dir.Trim(), exeName); |
| 125 | + if (File.Exists(fullPath)) |
| 126 | + { |
| 127 | + _cachedAzqrPath = fullPath; |
| 128 | + return fullPath; |
| 129 | + } |
| 130 | + } |
| 131 | + return null; |
| 132 | + } |
| 133 | +} |
0 commit comments