Labsco
knishioka logo

Cost Management MCP

from knishioka

A server for unified cost management across various cloud providers and API services.

🔥🔥🔥✓ VerifiedPaid serviceAdvanced setup

Cost Management MCP

CI Security Scan Release License: MIT Node.js Version TypeScript codecov

A Model Context Protocol (MCP) server for unified cost management across cloud providers and API services.

English | 日本語

🚀 Quick Examples

Once integrated with Claude Desktop, you can ask:

📊 "What are my AWS costs for December 2024?"
📈 "Show me OpenAI API usage trends for the last 30 days"
🤖 "What are my Anthropic API costs this month?"
🔍 "Break down my cloud expenses by service"
📋 "Which providers are currently configured?"
💰 "How much have I spent across all services this month?"

<a name="english"></a>

Features

  • 🔍 Unified cost tracking across AWS, OpenAI, and Anthropic
  • 💾 Intelligent caching to minimize API costs
  • 📊 Flexible date ranges and granularity options
  • 🔐 Secure credential management via environment variables
  • 🚀 Easy integration with Claude Desktop and other MCP clients
  • ⚡ Written in TypeScript with full type safety
  • 🧪 Comprehensive test coverage
  • 🔄 Automatic retry logic with exponential backoff
  • 🛡️ Security scanning with CodeQL and Trufflehog
  • 📦 Automated dependency updates with Dependabot

🛠️ MCP Tools

This server provides three powerful tools for cost management:

📊 cost_get

Get detailed cost breakdowns

  • Check costs for any date range
  • Filter by specific provider (AWS, OpenAI, Anthropic)
  • View daily, monthly, or total costs
  • See service-level breakdowns

Example questions in Claude:

  • "What are my AWS costs for this month?"
  • "Show me daily OpenAI usage for the last week"
  • "Break down my cloud costs by service"

📋 provider_list

Check provider status

  • See which providers are configured
  • Verify API credentials are valid
  • Quick health check for all integrations

Example usage:

  • "List all my cloud providers"
  • "Which cost tracking services are active?"

💰 provider_balance

Check remaining credits (Coming soon)

  • View prepaid balances
  • Monitor API credit usage
  • Get alerts before credits expire

📊 openai_costs

Get detailed OpenAI usage

  • Model-by-model breakdown (GPT-4, GPT-3.5, etc.)
  • Token usage statistics
  • Cost optimization recommendations

Example usage:

  • "Show my OpenAI costs grouped by model"
  • "How many tokens did I use with GPT-4 this week?"

🤖 anthropic_costs

Get detailed Anthropic usage

  • Model-by-model breakdown (Claude 3.5 Sonnet, Haiku, etc.)
  • Token usage statistics with prompt caching details
  • Cost optimization recommendations
  • Support for both cost report and usage report APIs

Example usage:

  • "Show my Anthropic costs grouped by model"
  • "How much did I spend on Claude 3.5 Sonnet this month?"
  • "What are my Anthropic costs with token-level details?"

☁️ aws_costs

AWS cost analysis with insights

  • Service-level breakdown (EC2, S3, RDS, etc.)
  • Filter by specific AWS service
  • Automatic cost optimization tips
  • High spend warnings

Example usage:

  • "What are my EC2 costs this month?"
  • "Show AWS costs grouped by service"
  • "Give me AWS cost optimization tips"

📈 provider_compare

Compare costs across providers

  • Side-by-side cost comparison
  • ASCII chart visualization
  • Vendor lock-in warnings
  • Cost distribution insights

Example usage:

  • "Compare my costs across all cloud providers"
  • "Show me a chart of provider costs"
  • "Which provider is most expensive?"

Analyze cost trends over time

  • Historical cost analysis (30d, 60d, 90d, 6m, 1y)
  • Trend detection (increasing/decreasing/stable)
  • Volatility analysis
  • Spike detection
  • Daily/weekly/monthly granularity

Example usage:

  • "Show me cost trends for the last 30 days"
  • "Are my AWS costs increasing?"
  • "Detect any cost spikes in the past month"

🔍 cost_breakdown

Detailed cost breakdown analysis

  • Multi-dimensional breakdown (service, region, date, tag)
  • Top N cost drivers
  • Percentage-based filtering
  • Hierarchical drill-down
  • Cost concentration analysis

Example usage:

  • "Break down my costs by service"
  • "Show top 5 cost drivers"
  • "What services make up 80% of my costs?"

📅 cost_periods

Compare costs between time periods

  • Period-over-period comparison
  • Absolute and percentage changes
  • Service-level change tracking
  • Daily average comparison
  • New/discontinued service detection

Example usage:

  • "Compare this month vs last month"
  • "How much did costs increase since Q1?"
  • "Which services grew the most?"

Table of Contents

Available Tools

cost_get

Retrieve cost data for specified providers and time periods.

Parameters:

  • provider (optional): Specific provider to query ('aws', 'openai', 'anthropic')
  • startDate (required): Start date in YYYY-MM-DD format
  • endDate (required): End date in YYYY-MM-DD format
  • granularity (optional): 'daily', 'monthly', or 'total' (default: 'total')
  • groupBy (optional): Array of dimensions to group by (e.g., ['SERVICE', 'REGION'])

Example Request:

{
  "provider": "aws",
  "startDate": "2024-01-01",
  "endDate": "2024-01-31",
  "granularity": "daily",
  "groupBy": ["SERVICE"]
}

Example Response:

{
  "success": true,
  "data": {
    "provider": "aws",
    "period": {
      "start": "2024-01-01T00:00:00.000Z",
      "end": "2024-01-31T23:59:59.999Z"
    },
    "costs": {
      "total": 1234.56,
      "currency": "USD",
      "breakdown": [
        {
          "service": "Amazon EC2",
          "amount": 800.0,
          "usage": {
            "quantity": 720,
            "unit": "Hours"
          }
        },
        {
          "service": "Amazon S3",
          "amount": 434.56
        }
      ]
    },
    "metadata": {
      "lastUpdated": "2024-01-31T12:00:00.000Z",
      "source": "api"
    }
  }
}

provider_list

List all configured providers and their connection status.

Response includes:

  • Provider name
  • Configuration status
  • Credential validation status

Example Response:

{
  "success": true,
  "data": {
    "providers": [
      {
        "name": "aws",
        "status": "active",
        "configured": true
      },
      {
        "name": "openai",
        "status": "active",
        "configured": true
    ],
    "configured": 2,
    "total": 3
  }
}

provider_balance

Check remaining balance or credits (provider-specific). Note: Currently not implemented for most providers

Development

Project Structure

cost-management-mcp/
├── src/
│   ├── common/          # Shared utilities and types
│   │   ├── cache.ts     # Caching implementation
│   │   ├── config.ts    # Configuration management
│   │   ├── errors.ts    # Custom error classes
│   │   ├── types.ts     # TypeScript interfaces
│   │   └── utils.ts     # Helper functions
│   ├── providers/       # Provider implementations
│   │   ├── aws/         # AWS Cost Explorer
│   │   ├── openai/      # OpenAI Usage API
│   │   ├── anthropic/   # Anthropic Admin API
│   ├── tools/           # MCP tool implementations
│   │   ├── getCosts.ts
│   │   ├── listProviders.ts
│   │   └── checkBalance.ts
│   ├── server.ts        # MCP server setup
│   └── index.ts         # Entry point
├── tests/               # Test files
├── docs/                # Additional documentation
└── scripts/             # Utility scripts

Commands

# Development with hot reload
npm run dev

# Build TypeScript to JavaScript
npm run build

# Run production server
npm start

# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

# Lint code
npm run lint

# Fix linting issues
npm run lint:fix

# Type check without building
npm run typecheck

# Clean build artifacts
npm run clean

Adding a New Provider

  1. Create provider directory:
mkdir -p src/providers/newprovider
  1. Implement required files:
  • types.ts - TypeScript interfaces
  • transformer.ts - Convert API response to unified format
  • client.ts - API client implementing ProviderClient
  • index.ts - Public exports
  1. Update server.ts to include the new provider

  2. Add tests in tests/providers/newprovider/

Testing

Tests use Jest with TypeScript support:

# Run all tests
npm test

# Run tests for specific provider
npm test -- aws

# Run with coverage
npm run test:coverage

# Debug tests
node --inspect-brk node_modules/.bin/jest --runInBand

Architecture

Design Principles

  1. Unified Interface: All providers implement the same ProviderClient interface
  2. Error Resilience: Automatic retry with exponential backoff
  3. Cost Optimization: Aggressive caching to minimize API calls
  4. Type Safety: Full TypeScript coverage with strict mode
  5. Extensibility: Easy to add new providers or tools

Data Flow

User Request → MCP Tool → Provider Client → Cache Check
                                              ↓ (miss)
                                          External API
                                              ↓
                                          Transformer
                                              ↓
                                          Cache Store
                                              ↓
                                          Response

Error Handling

The system implements a hierarchical error handling strategy:

  1. Provider Errors: Specific to each cloud provider
  2. Authentication Errors: Invalid or expired credentials
  3. Rate Limit Errors: Automatic retry with backoff
  4. Validation Errors: Invalid input parameters
  5. Network Errors: Retryable connection issues

📊 Project Status

Build & Test

  • CI/CD: Automated testing on push and PR
  • Node Support: Runtime floor is Node.js 18+. CI verifies 18.x, 20.x, 22.x, and 24.x with 20.x as the primary lane for coverage upload and representative build checks.
  • Coverage: Comprehensive test suite with coverage reporting

Security

  • Dependency Scanning: Weekly automated updates
  • Secret Detection: Continuous monitoring for exposed credentials
  • Code Analysis: CodeQL security scanning

Quality

  • Type Safety: Strict TypeScript configuration
  • Linting: ESLint with auto-fix on commit
  • Formatting: Prettier code formatting

日本語ドキュメント

概要

Cost Management MCPは、複数のクラウドプロバイダーとAPIサービスのコストを統一的に管理するためのModel Context Protocol (MCP)サーバーです。

主な機能

  • 🔍 AWS、OpenAI、Anthropicのコストを一元管理
  • 💾 APIコストを最小限に抑えるインテリジェントキャッシング
  • 📊 柔軟な日付範囲と集計オプション
  • 🔐 環境変数による安全な認証情報管理
  • 🚀 Claude Desktopとの簡単な統合
  • ⚡ TypeScriptによる型安全性
  • 🧪 包括的なテストカバレッジ
  • 🔄 指数バックオフによる自動リトライ
  • 🛡️ CodeQLとTrufflehogによるセキュリティスキャン
  • 📦 Dependabotによる自動依存関係更新

🛠️ 利用可能なMCPツール

このサーバーは、コスト管理のための3つの強力なツールを提供します:

📊 cost.get

詳細なコスト内訳を取得

  • 任意の期間のコストをチェック
  • 特定のプロバイダー(AWS、OpenAI)でフィルタリング
  • 日次、月次、または合計コストを表示
  • サービスレベルの内訳を確認

Claudeでの使用例:

  • 「今月のAWSのコストを教えて」
  • 「過去1週間のOpenAIの日次使用量を表示して」
  • 「クラウドコストをサービス別に分解して」

📋 provider_list

プロバイダーの状態を確認

  • 設定されているプロバイダーを確認
  • API認証情報が有効かを検証
  • すべての統合のヘルスチェック

使用例:

  • 「すべてのクラウドプロバイダーを一覧表示」
  • 「どのコスト追跡サービスがアクティブ?」

💰 provider_balance

残高の確認 (近日公開)

  • プリペイド残高の表示
  • APIクレジット使用量の監視
  • クレジット期限前のアラート

インストール

前提条件

  • Node.js 18 以上
  • npm または yarn
  • 監視対象クラウドプロバイダーのアカウント

CI は現在 Node.js 18.x / 20.x / 22.x / 24.x を検証しており、20.x を カバレッジアップロードおよび代表的なビルド検証用の主要レーンとして扱います。

# リポジトリのクローン
git clone https://github.com/knishioka/cost-management-mcp.git
cd cost-management-mcp

# 依存関係のインストール
npm install

# 環境変数の設定
cp .env.example .env
# .envファイルを編集して認証情報を追加

# ビルド
npm run build

Claude Desktopとの統合

Claude Desktopの設定ファイルに以下を追加:

{
  "mcpServers": {
    "cost-management": {
      "command": "node",
      "args": ["/path/to/cost-management-mcp/dist/index.js"],
      "env": {
        "AWS_ACCESS_KEY_ID": "your-key",
        "AWS_SECRET_ACCESS_KEY": "your-secret",
        "OPENAI_API_KEY": "your-key"
      }
    }
  }
}

Claude Codeとの統合

Claude Codeは2つの設定方法でMCPサーバーをサポートしています:

方法1: プロジェクト固有の設定(推奨)

プロジェクトのルートディレクトリに .mcp.json ファイルを作成:

{
  "mcpServers": {
    "cost-management": {
      "command": "node",
      "args": ["/absolute/path/to/cost-management-mcp/dist/index.js"],
      "env": {
        "AWS_ACCESS_KEY_ID": "your-aws-access-key",
        "AWS_SECRET_ACCESS_KEY": "your-aws-secret-key",
        "AWS_REGION": "us-east-1",
        "OPENAI_API_KEY": "sk-...your-openai-key",
        "ANTHROPIC_API_KEY": "sk-ant-admin-...your-admin-key",
        "CACHE_TTL": "3600",
        "LOG_LEVEL": "info"
      }
    }
  }
}

この設定は、Claude Codeでプロジェクトを開いたときに自動的に読み込まれます。

方法2: VS Code設定(グローバル設定)

  1. VS Code設定を開く(Cmd/Ctrl + ,)
  2. 「Claude Code MCP Servers」を検索
  3. 「settings.jsonで編集」をクリック
  4. コスト管理サーバーの設定を追加:
{
  "claudeCode.mcpServers": {
    "cost-management": {
      "command": "node",
      "args": ["/absolute/path/to/cost-management-mcp/dist/index.js"],
      "env": {
        "AWS_ACCESS_KEY_ID": "your-aws-access-key",
        "AWS_SECRET_ACCESS_KEY": "your-aws-secret-key",
        "AWS_REGION": "us-east-1",
        "OPENAI_API_KEY": "sk-...your-openai-key",
        "GOOGLE_APPLICATION_CREDENTIALS": "/path/to/gcp-service-account.json",
        "GCP_BILLING_ACCOUNT_ID": "your-billing-account-id"
      }
    }
  }
}
  1. VS Codeウィンドウをリロード(Cmd/Ctrl + Shift + P → 「開発者: ウィンドウの再読み込み」)

コスト管理サーバーの使用

設定が完了したら、Claude Codeでクラウドコストについて質問できます:

📊 「今月のAWSコストを教えて」
📈 「OpenAI APIの使用傾向を表示」
🔍 「サービス別にクラウド費用を分析」
💰 「全プロバイダーのコストを比較」

セキュリティに関する注意:

  • プロジェクト固有の .mcp.json.gitignore に追加して、APIキーをコミットしないようにしてください
  • 本番環境では環境変数やシークレット管理ツールの使用を検討してください
  • キャッシュはオプションです - 設定されていない場合、サーバーはキャッシュなしで動作します

使用例

今月のAWSのコストを教えて
過去7日間のOpenAI APIの使用料金は?
設定されているクラウドプロバイダーを一覧表示して

プロバイダーの設定

各プロバイダーの詳細な設定方法は英語版ドキュメントを参照してください。

開発

# 開発モード(ホットリロード付き)
npm run dev

# テストの実行
npm test

# リントチェック
npm run lint

# 型チェック
npm run typecheck

📊 プロジェクトステータス

ビルド&テスト

  • CI/CD: プッシュとPR時の自動テスト
  • Node サポート: 動作要件(runtime floor)は Node.js 18+。CI は 18.x / 20.x / 22.x / 24.x を検証し、 20.x を主要なカバレッジアップロードおよびビルド検証用レーン(primary coverage lane)として扱います
  • カバレッジ: カバレッジレポート付きの包括的なテストスイート

セキュリティ

  • 依存関係スキャン: 週次自動更新
  • シークレット検出: 公開された認証情報の継続的監視
  • コード分析: CodeQLセキュリティスキャン

品質

  • 型安全性: 厳格なTypeScript設定
  • リンティング: コミット時のESLint自動修正
  • フォーマット: Prettierコードフォーマット

ライセンス

MIT License


Built with ❤️ using TypeScript and MCP