Azure成本管理服务器

用于Azure成本管理API集成的MCP服务器,支持成本查询、预算管理和成本优化建议。

  • by bigonil
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 bigonil/azure-cost-management-mcp

使用说明

Azure成本管理MCP服务器

MCP(模型上下文协议)服务器,用于与 API 集成 Azure成本管理符合指导方针 WAF成本优化 e CAF(云采用框架) 微软。

兼容 GitHub Copilot 聊天助手, 克劳德桌面和任何MCP客户端。


索引


先决条件

要求 最低版本
Node.js 18.0.0
npm 9.x
Azure命令行界面(az) 任何 — 仅用于本地身份验证

安装

cd azure-cost-management-mcp
npm install
npm run build

已编译的服务器将可在 dist/index.js.


Azure 身份验证

美国服务器 DefaultAzureCredential 从 SDK @azure/identity按顺序自动尝试以下模式:

选项 A — Azure CLI(本地开发,推荐)

az login
# oppure, per un tenant specifico:
az login --tenant <TENANT_ID>

不需要环境变量。服务器会自动检测 CLI 令牌。

选项 B — 主要服务(CI/CD、自动化)

设置以下环境变量(参见 .env.example):

AZURE_TENANT_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
AZURE_CLIENT_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
AZURE_CLIENT_SECRET=your-client-secret
AZURE_SUBSCRIPTION_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx  # default subscription

选项 C — Managed Identity(在 Azure 上托管的工作负载)

无配置 。 DefaultAzureCredential 自动检测通过 IMDS 管理的身份。


IDE 配置

VS Code+GitHub副驾驶聊天

Metodo 1--文件 .vscode/mcp.json 工作空间(推荐)

创建或编辑文件 <cartella-workspace>/.vscode/mcp.json:

{
  "servers": {
    "azure-cost-management": {
      "type": "stdio",
      "command": "node",
      "args": ["${userHome}/azure-cost-management-mcp/dist/index.js"],
      "env": {
        "AZURE_SUBSCRIPTION_ID": "${env:AZURE_SUBSCRIPTION_ID}"
      }
    }
  }
}

它使用 az login,该部分 env 可能是空的—— DefaultAzureCredential 美国il代币CLI。 根据服务负责人aggiungi AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET.

方法 2 — VS 代码用户设置(全局)

四月 Ctrl+Shift+P → 首选项:打开用户设置(JSON) 并添加:

{
  "mcp.servers": {
    "azure-cost-management": {
      "type": "stdio",
      "command": "node",
      "args": ["C:/Users/<TUO_UTENTE>/azure-cost-management-mcp/dist/index.js"]
    }
  }
}

在VS代码中检查连接:

  1. 打开面板 GitHub Copilot 聊天助手 (Ctrl+Alt+I)
  2. 选择模式 代理 (@)
  3. 请输入 : @azure-cost-management qual è la spesa del mese corrente per la subscription xxx?

克劳德桌面

编辑 Claude Desktop 配置文件:

  • 窗户: %APPDATA%\Claude\claude_desktop_config.json
  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "azure-cost-management": {
      "command": "node",
      "args": ["C:/Users/<TUO_UTENTE>/azure-cost-management-mcp/dist/index.js"],
      "env": {
        "AZURE_SUBSCRIPTION_ID": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
      }
    }
  }
}

修改后重新启动 Claude Desktop。


光标

创建或修改 .cursor/mcp.json 在用户主页或项目文件夹中:

{
  "mcpServers": {
    "azure-cost-management": {
      "command": "node",
      "args": ["C:/Users/<TUO_UTENTE>/azure-cost-management-mcp/dist/index.js"],
      "env": {
        "AZURE_SUBSCRIPTION_ID": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
      }
    }
  }
}

帆板运动

修改 ~/.codeium/windsurf/mcp_config.json:

{
  "mcpServers": {
    "azure-cost-management": {
      "command": "node",
      "args": ["C:/Users/<TUO_UTENTE>/azure-cost-management-mcp/dist/index.js"],
      "env": {
        "AZURE_SUBSCRIPTION_ID": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
      }
    }
  }
}

参考范围

所有工具都接受一个参数 scope 确定要操作的 Azure 级别。

格式 示例 结果范围
完整路径 /subscriptions/aaaa-bbbb 订阅
完整路径 /subscriptions/aaaa/resourceGroups/my-rg 资源组
UUID Nudo aaaa-bbbb-cccc-dddd-eeee 订阅
sub:{id} sub:aaaa-bbbb 订阅
sub:{id}/rg:{name} sub:aaaa/rg:my-rg 资源组
rg:{name} rg:my-rg RG nella订阅默认(AZURE_SUBSCRIPTION_ID)
mg:{id} mg:my-management-group 管理集团(CAF企业)
ba:{id} ba:12345678 账单账户(EA/MCA)
ba:{id}/bp:{id} ba:12345/bp:ABCD 计费配置文件(MCA)

CAF提示: 美国 mg: 用于对所有着陆区进行跨订阅分析,而无需对每个订阅单独迭代。


可用工具

azure_cost_query

查询具有分组和时间过滤器的 Azure 范围的实际成本或折旧成本。

参数 :

参数 类型 默认 描述
scope string -- 作用域Azure(vedi 参考范围)
type ActualCost AmortizedCost ActualCost
timeframe enum MonthToDate 时间窗口: BillingMonth, MonthToDate, TheLastMonth, TheLastBillingMonth, WeekToDate, Custom
from string (ISO 8601) — 开始日期 (仅与 timeframe=Custom)
to string (ISO 8601) — 结束日期(仅与 timeframe=Custom)
granularity None Daily Monthly
groupBy string[] [] 分组大小(见下面的示例)
top 整数(1-1000) 100 返回的最大行数

共同的价值观 groupBy:

ResourceGroup       ServiceName         ResourceType
Location            SubscriptionName    MeterCategory
MeterSubCategory    ChargeType
tag:CostCenter      tag:Environment     tag:Application

azure_cost_forecast

根据当前使用趋势返回支出预测。

参数 :

参数 类型 默认 描述
scope string -- 作用域Azure
from string (ISO 8601) — 开始日期预测
to string(ISO 8601) -- 数据精细预测
granularity Daily Monthly Monthly
includeActualCost 布尔值 true 包括实际成本与预测进行比较。

azure_cost_dimensions

列出在指定范围内可用的分组和过滤器大小。在使用之前 azure_cost_query 找出有效的值 groupBy.

参数 :

参数 类型 描述
scope string 作用域Azure

azure_cost_alerts

列出一个范围的活动成本警报:预算压力,信用警报,违反配额,异常。

参数 :

参数 类型 描述
scope string 作用域Azure

答案 — 主要字段:

{
  "total": 2,
  "active": 1,
  "alerts": [
    {
      "name": "alert-xxx",
      "definitionType": "Budget",
      "definitionCategory": "Cost",
      "status": "Active",
      "creationTime": "2024-01-15T10:30:00Z"
    }
  ]
}

azure_budget_list

列出范围内的所有成本预算,包括当前支出、门槛和状态。

参数 :

参数 类型 描述
scope string 作用域Azure(richiede订阅)

现场可能的状态 status:

状态 意义
OK 预算的80%。
WARNING 80%到90%之间。
CRITICAL 90%到100%之间。
EXCEEDED 预算的100%。

azure_budget_get

检索特定预算的完整详细信息:当前支出,预计支出,通知门槛和过滤器。

参数 :

参数 类型 描述
scope string 作用域Azure
budgetName string 预算名称

azure_budget_create

使用 WAF 推荐的警报门槛创建或更新成本预算。如果在同一范围内已经存在具有相同名称的预算,则将更新。

参数 :

参数 类型 默认 描述
scope string -- 作用域Azure(richiede订阅)
name string — 范围内唯一的预算名称
amount number — 订阅货币的预算金额
timeGrain enum Monthly 重置期: Monthly, Quarterly, Annually, BillingMonth, BillingQuarter, BillingAnnually
startDate string (YYYY-MM-DD) — 开始日期。每粒 Monthly 应该是本月的第一个。
endDate string (YYYY-MM-DD) +10 年 结束日期 (可选)
contactEmails string[] [] 达到门槛时通知电子邮件
contactRoles string[] ["Owner","Contributor"] 要通知的RBAC角色
notifyAt80Percent 布尔值 true WAF警报:预警80%的实际支出
notifyAt100Percent 布尔值 true WAF警报:预算达到实际支出的100%。
notifyForecastAt100Percent 布尔值 true WAF警报:预测期间结束前将达到100%。

azure_budget_delete

永久删除预算。 手术是不可逆的。

参数 :

参数 类型 描述
scope string 作用域Azure
budgetName string 要删除的预算名称

azure_advisor_recommendations

获取 Azure Advisor 关于成本优化类别的建议。

涵盖:缩放未使用的 VM,消除闲置资源(未连接磁盘,未使用的公共 IP),购买预留实例或节省计划以实现可预测的工作负载。

参数 :

参数 类型 默认 描述
scope string -- 确定livello订阅的范围(UUID, sub:{id}完整路径)。
impact High Medium Low
top 整数(1-500) 50 建议的最大数量

注: Azure Advisor 仅在订阅级别上运行。范围 mg: 不支持此工具。


在聊天中使用示例

这些示例适用于 GitHub Copilot Chat 和 Claude Desktop、Cursor 和 Windsurf。

当前支出分析

Mostrami la spesa del mese corrente per la subscription aaaa-bbbb-cccc,
raggruppata per ServiceName e ordinata per costo decrescente.
Qual è la spesa degli ultimi 3 mesi raggruppata per ResourceGroup?
Usa il periodo Custom da 2024-01-01 a 2024-03-31 con granularità Monthly.
Mostrami la ripartizione dei costi per tag:CostCenter e tag:Environment
nella subscription aaaa — voglio fare il chargeback ai team.

预测和异常

Prevedi la spesa di marzo per la subscription aaaa.
Poi confronta con il budget esistente per capire se siamo a rischio sforamento.
Ci sono alert di costo attivi nella subscription aaaa?

预算管理

Elenca tutti i budget nella subscription aaaa con il loro stato attuale.
Crea un budget mensile da 5000 EUR per il resource group "prod-rg"
nella subscription aaaa, con notifiche a mario@example.com.
Il budget "monthly-prod" nella subscription aaaa è stato superato?
Mostrami i dettagli e la spesa prevista per fine mese.

成本优化(WAF/CAF)

Quali sono le raccomandazioni di Azure Advisor ad alto impatto
per la subscription aaaa? Voglio massimizzare i risparmi.
Fai un'analisi completa dei costi per il management group "my-mg":
spesa corrente per subscription, alert attivi, e raccomandazioni Advisor.
Quali dimensioni sono disponibili per il raggruppamento dei costi
nella subscription aaaa? Voglio capire su quali tag posso fare showback.

RBAC — 所需角色

将角色分配给适当的范围(订阅、资源组或管理组):

操作 最低角色要求
阅读成本,预测,规模,警报 成本管理阅读器
减少预算。 成本管理阅读器
创建/更新/删除预算 成本管理贡献者
Advisor的建议。 读者 (订阅级别)

CAF企业: 分配角色级别 管理小组 以单一分配覆盖所有登陆区订阅。

# Esempio: assegnare Cost Management Reader al management group
az role assignment create \
  --role "Cost Management Reader" \
  --assignee <CLIENT_ID_O_UPN> \
  --scope /providers/Microsoft.Management/managementGroups/<MG_ID>

代码架构

azure-cost-management-mcp/
├── src/
│   ├── index.ts              # Entry point MCP server, registrazione tool
│   ├── client.ts             # Client Azure singleton + helper scope/risposta
│   ├── tools/
│   │   ├── cost.ts           # azure_cost_query, forecast, dimensions, alerts
│   │   ├── budgets.ts        # azure_budget_list/get/create/delete
│   │   └── advisor.ts        # azure_advisor_recommendations
│   └── __tests__/
│       ├── client.test.ts    # Unit test: normalizeScope, transformRows, ecc.
│       └── server.integration.test.ts  # Integration test: protocollo MCP
├── dist/                     # Output compilato TypeScript (generato da npm run build)
├── package.json
├── tsconfig.json
└── .env.example

主要依赖关系:

包装 版本 使用
@modelcontextprotocol/sdk ^1.27.1 运输标准MCP协议
@azure/arm-costmanagement 1.0.0-beta.1 查询成本,预测,大小,警报
@azure/arm-consumption ^9.2.0 预算管理
@azure/arm-advisor ^3.2.0 成本优化建议
@azure/identity ^4.13.1 DefaultAzureCredentials(身份验证统一性)
zod ^3.23.0 验证输入方案工具

建筑流程:

GitHub Copilot / Claude / Cursor
         │ MCP (stdio)
         ▼
    src/index.ts  (McpServer + StdioServerTransport)
         │
    src/client.ts  (DefaultAzureCredential, singleton client, normalizeScope)
         │
    ┌────┼────────────────────┐
    ▼    ▼                    ▼
Azure Cost    Azure           Azure
Management    Consumption     Advisor
API           API (Budgets)   API

发展

# Avvia in watch mode (rebuild automatico al salvataggio)
npm run dev

# Verifica tipi senza compilare
npm run typecheck

# Build di produzione
npm run build

# Avvia il server compilato
npm start

# Esegui tutti i test (unit + integration)
npm test

# Solo unit test (client utilities)
npm run test:unit

# Solo integration test (protocollo MCP)
npm run test:integration

快速测试服务器:

# Verifica che il server si avvii e risponda al protocollo MCP
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}' \
  | node dist/index.js

注册工具列表:

(
  echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}'
  echo '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'
) | node dist/index.js