-
Notifications
You must be signed in to change notification settings - Fork 493
Add CostManagement query tool #2603
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
francesco1501
wants to merge
2
commits into
microsoft:main
Choose a base branch
from
francesco1501:feature/add-costmanagement-query
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -381,6 +381,7 @@ | |
| "conv", | ||
| "copilotmd", | ||
| "cosell", | ||
| "costmanagement", | ||
| "csdevkit", | ||
| "cslschema", | ||
| "cvzf", | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3 changes: 3 additions & 0 deletions
3
servers/Azure.Mcp.Server/changelog-entries/francesco1501-add-costmanagement-query.yml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| changes: | ||
| - section: "Features Added" | ||
| description: "Added `azmcp costmanagement query run` tool to retrieve actual Azure costs and usage from the Azure Cost Management Query/Usage API for a subscription or resource group, with support for predefined timeframes (MonthToDate, BillingMonthToDate, TheLastBillingMonth, WeekToDate) and a custom range, optional Daily granularity, and grouping by a single dimension (ServiceName, ResourceGroupName, ResourceLocation, ResourceId, MeterCategory, MeterSubCategory, ChargeType, BillingPeriod). Closes the gap tracked in #1420 and supersedes #447." |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using System.Runtime.CompilerServices; | ||
|
|
||
| [assembly: InternalsVisibleTo("Azure.Mcp.Tools.CostManagement.UnitTests")] | ||
| [assembly: InternalsVisibleTo("Azure.Mcp.Tools.CostManagement.LiveTests")] |
20 changes: 20 additions & 0 deletions
20
tools/Azure.Mcp.Tools.CostManagement/src/Azure.Mcp.Tools.CostManagement.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
| <PropertyGroup> | ||
| <IsAotCompatible>true</IsAotCompatible> | ||
| </PropertyGroup> | ||
| <ItemGroup> | ||
| <EmbeddedResource Include="**\Resources\*.txt" /> | ||
| <EmbeddedResource Include="**\Resources\*.json" /> | ||
| </ItemGroup> | ||
| <ItemGroup> | ||
| <ProjectReference Include="..\..\..\core\Azure.Mcp.Core\src\Azure.Mcp.Core.csproj" /> | ||
| </ItemGroup> | ||
| <ItemGroup> | ||
| <PackageReference Include="Azure.ResourceManager" /> | ||
| <PackageReference Include="Azure.ResourceManager.CostManagement" /> | ||
|
|
||
| <PackageReference Include="Microsoft.Extensions.DependencyInjection" /> | ||
| <PackageReference Include="ModelContextProtocol" /> | ||
| <PackageReference Include="System.CommandLine" /> | ||
| </ItemGroup> | ||
| </Project> |
32 changes: 32 additions & 0 deletions
32
tools/Azure.Mcp.Tools.CostManagement/src/Commands/BaseCostManagementCommand.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using System.Diagnostics.CodeAnalysis; | ||
| using Azure.Mcp.Core.Commands.Subscription; | ||
| using Azure.Mcp.Tools.CostManagement.Options; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.Mcp.Core.Commands; | ||
| using Microsoft.Mcp.Core.Extensions; | ||
| using Microsoft.Mcp.Core.Models.Option; | ||
|
|
||
| namespace Azure.Mcp.Tools.CostManagement.Commands; | ||
|
|
||
| public abstract class BaseCostManagementCommand< | ||
| [DynamicallyAccessedMembers(TrimAnnotations.CommandAnnotations)] TOptions>(ILogger<BaseCostManagementCommand<TOptions>> logger) | ||
| : SubscriptionCommand<TOptions> where TOptions : BaseCostManagementOptions, new() | ||
| { | ||
| protected readonly ILogger<BaseCostManagementCommand<TOptions>> _logger = logger; | ||
|
|
||
| protected override void RegisterOptions(Command command) | ||
| { | ||
| base.RegisterOptions(command); | ||
| command.Options.Add(OptionDefinitions.Common.ResourceGroup.AsOptional()); | ||
| } | ||
|
|
||
| protected override TOptions BindOptions(ParseResult parseResult) | ||
| { | ||
| var options = base.BindOptions(parseResult); | ||
| options.ResourceGroup ??= parseResult.GetValueOrDefault<string>(OptionDefinitions.Common.ResourceGroup.Name); | ||
| return options; | ||
| } | ||
| } |
16 changes: 16 additions & 0 deletions
16
tools/Azure.Mcp.Tools.CostManagement/src/Commands/CostManagementJsonContext.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using System.Text.Json.Serialization; | ||
| using Azure.Mcp.Tools.CostManagement.Commands.Query; | ||
| using Azure.Mcp.Tools.CostManagement.Models; | ||
|
|
||
| namespace Azure.Mcp.Tools.CostManagement.Commands; | ||
|
|
||
| [JsonSerializable(typeof(QueryRunCommand.QueryRunCommandResult))] | ||
| [JsonSerializable(typeof(CostQueryResult))] | ||
| [JsonSerializable(typeof(CostQueryRow))] | ||
| [JsonSourceGenerationOptions( | ||
| PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, | ||
| DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] | ||
| internal partial class CostManagementJsonContext : JsonSerializerContext; |
142 changes: 142 additions & 0 deletions
142
tools/Azure.Mcp.Tools.CostManagement/src/Commands/Query/QueryRunCommand.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using System.Net; | ||
| using Azure.Mcp.Tools.CostManagement.Models; | ||
| using Azure.Mcp.Tools.CostManagement.Options; | ||
| using Azure.Mcp.Tools.CostManagement.Options.Query; | ||
| using Azure.Mcp.Tools.CostManagement.Services; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.Mcp.Core.Commands; | ||
| using Microsoft.Mcp.Core.Models.Command; | ||
|
|
||
| namespace Azure.Mcp.Tools.CostManagement.Commands.Query; | ||
|
|
||
| [CommandMetadata( | ||
| Id = "f7c4b3a8-9e62-4d18-bc41-2a5d8e6f1b09", | ||
| Name = "run", | ||
| Title = "Query Azure Costs", | ||
| Description = """ | ||
| Query actual Azure costs and usage data for a subscription or resource group over a time period. | ||
| Returns aggregated costs in the billing currency, optionally broken down daily and grouped by | ||
| a single Azure dimension. Caller must have 'Cost Management Reader' or 'Reader' on the scope. | ||
| """, | ||
| Destructive = false, | ||
| Idempotent = true, | ||
| OpenWorld = false, | ||
| ReadOnly = true, | ||
| Secret = false, | ||
| LocalRequired = false)] | ||
| public sealed class QueryRunCommand(ILogger<QueryRunCommand> logger, ICostManagementService costManagementService) | ||
| : BaseCostManagementCommand<QueryRunOptions>(logger) | ||
| { | ||
| private readonly ICostManagementService _costManagementService = costManagementService; | ||
|
|
||
| protected override void RegisterOptions(Command command) | ||
| { | ||
| base.RegisterOptions(command); | ||
| command.Options.Add(CostManagementOptionDefinitions.Timeframe); | ||
| command.Options.Add(CostManagementOptionDefinitions.From); | ||
| command.Options.Add(CostManagementOptionDefinitions.To); | ||
| command.Options.Add(CostManagementOptionDefinitions.Granularity); | ||
| command.Options.Add(CostManagementOptionDefinitions.GroupBy); | ||
|
|
||
| command.Validators.Add(result => | ||
| { | ||
| var timeframe = result.GetValue(CostManagementOptionDefinitions.Timeframe); | ||
| if (timeframe == QueryTimeframe.Custom) | ||
| { | ||
| var from = result.GetValue(CostManagementOptionDefinitions.From); | ||
| var to = result.GetValue(CostManagementOptionDefinitions.To); | ||
| if (from is null || to is null) | ||
| { | ||
| result.AddError( | ||
| "When --timeframe is Custom, both --from and --to must be provided (ISO-8601 dates, UTC)."); | ||
| } | ||
| else if (from > to) | ||
| { | ||
| result.AddError("--from must be earlier than or equal to --to."); | ||
| } | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| protected override QueryRunOptions BindOptions(ParseResult parseResult) | ||
| { | ||
| var options = base.BindOptions(parseResult); | ||
| options.Timeframe = parseResult.GetValue(CostManagementOptionDefinitions.Timeframe); | ||
| options.From = parseResult.GetValue(CostManagementOptionDefinitions.From); | ||
| options.To = parseResult.GetValue(CostManagementOptionDefinitions.To); | ||
| options.Granularity = parseResult.GetValue(CostManagementOptionDefinitions.Granularity); | ||
| options.GroupBy = parseResult.GetValue(CostManagementOptionDefinitions.GroupBy); | ||
| return options; | ||
| } | ||
|
|
||
| public override async Task<CommandResponse> ExecuteAsync( | ||
| CommandContext context, | ||
| ParseResult parseResult, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| if (!Validate(parseResult.CommandResult, context.Response).IsValid) | ||
| { | ||
| return context.Response; | ||
| } | ||
|
|
||
| var options = BindOptions(parseResult); | ||
|
|
||
| try | ||
| { | ||
| var timeframe = options.Timeframe ?? QueryTimeframe.MonthToDate; | ||
| var granularity = options.Granularity ?? QueryGranularity.None; | ||
|
|
||
| var result = await _costManagementService.QueryAsync( | ||
| subscription: options.Subscription!, | ||
| resourceGroup: options.ResourceGroup, | ||
| timeframe: timeframe, | ||
| from: options.From, | ||
| to: options.To, | ||
| granularity: granularity, | ||
| groupBy: options.GroupBy, | ||
| tenant: options.Tenant, | ||
| retryPolicy: options.RetryPolicy, | ||
| cancellationToken: cancellationToken); | ||
|
|
||
| context.Response.Results = ResponseResult.Create( | ||
| new QueryRunCommandResult(result), | ||
| CostManagementJsonContext.Default.QueryRunCommandResult); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogError(ex, | ||
| "Error querying Cost Management. Subscription: {Subscription}, ResourceGroup: {ResourceGroup}, Timeframe: {Timeframe}, Granularity: {Granularity}, GroupBy: {GroupBy}.", | ||
| options.Subscription, options.ResourceGroup, options.Timeframe, options.Granularity, options.GroupBy); | ||
| HandleException(context, ex); | ||
| } | ||
|
|
||
| return context.Response; | ||
| } | ||
|
|
||
| protected override string GetErrorMessage(Exception ex) => ex switch | ||
| { | ||
| RequestFailedException reqEx when reqEx.Status == (int)HttpStatusCode.NotFound => | ||
| "Cost data not found. Verify the subscription and resource group exist and are accessible.", | ||
| RequestFailedException reqEx when reqEx.Status == (int)HttpStatusCode.Forbidden => | ||
| $"Authorization failed querying Cost Management. The caller needs the 'Cost Management Reader' or 'Reader' role on the subscription or resource group. Details: {reqEx.Message}", | ||
| RequestFailedException reqEx when reqEx.Status == (int)HttpStatusCode.TooManyRequests => | ||
| $"Cost Management API throttled the request. Retry after the duration specified in the 'x-ms-ratelimit-microsoft.consumption-retry-after' response header. Details: {reqEx.Message}", | ||
| RequestFailedException reqEx when reqEx.Status == (int)HttpStatusCode.BadRequest => | ||
| $"Cost Management API rejected the query. Common causes: unsupported --group-by dimension; --timeframe value not allowed at this scope (subscription/resource group accept MonthToDate, BillingMonthToDate, TheLastBillingMonth, WeekToDate, Custom); --from later than --to; date range too large. Details: {reqEx.Message}", | ||
| RequestFailedException reqEx => reqEx.Message, | ||
| ArgumentException argEx => argEx.Message, | ||
| _ => base.GetErrorMessage(ex) | ||
| }; | ||
|
|
||
| protected override HttpStatusCode GetStatusCode(Exception ex) => ex switch | ||
| { | ||
| RequestFailedException reqEx => (HttpStatusCode)reqEx.Status, | ||
| ArgumentException => HttpStatusCode.BadRequest, | ||
| _ => base.GetStatusCode(ex) | ||
| }; | ||
|
|
||
| internal record QueryRunCommandResult(CostQueryResult Result); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
ServiceOwnersline lists only the external contributor. Other toolsets in this repo have at least one Microsoft team member as ServiceOwner/CODEOWNER. Consider adding a team member alongside so code ownership doesn't depend entirely on an external contributor's availability.