Enables monitoring and analysis of Amazon EC2 costs as part of AWS cost management, providing service-level breakdowns, optimization tips, and high-spend warnings.
Enables monitoring and analysis of Amazon S3 costs as part of AWS cost management, providing service-level breakdowns and cost optimization recommendations.
Provides detailed OpenAI cost and usage tracking, offering model-specific breakdowns (e.g., GPT-4), token usage statistics, and recommendations for cost optimization.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Cost Management MCPCompare my AWS and OpenAI spending for the last 30 days"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Cost Management MCP
A Model Context Protocol (MCP) server for unified cost management across cloud providers and API services.
🚀 Quick Examples
Once integrated with Claude Desktop, you can ask:
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?"
📊 cost_trends
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
Installation
Prerequisites
Node.js 18 or higher
npm or yarn
Active accounts with the cloud providers you want to monitor
Steps
Clone the repository:
Install dependencies:
Copy the environment template:
Edit
.envand add your credentials (see Provider Setup)Build the project:
Quick Start
Running Standalone
Integration with Claude Desktop
Build the project first:
Add to your Claude Desktop configuration (
~/Library/Application Support/Claude/claude_desktop_config.jsonon macOS):
Restart Claude Desktop
Use the tools in your conversation:
Integration with Claude Code
Claude Code supports MCP servers through two configuration methods:
Method 1: Project-specific configuration (Recommended)
Create a .mcp.json file in your project root:
This configuration will be automatically loaded when you open the project in Claude Code.
Method 2: VS Code settings (Global configuration)
Open VS Code Settings (Cmd/Ctrl + ,)
Search for "Claude Code MCP Servers"
Click "Edit in settings.json"
Add the cost management server configuration:
Reload VS Code window (Cmd/Ctrl + Shift + P → "Developer: Reload Window")
Using the Cost Management Server
Once configured, you can ask Claude Code about your cloud costs:
Security Note:
For project-specific
.mcp.json, add it to.gitignoreto avoid committing sensitive API keysConsider using environment variables or a secrets manager for production use
The cache is optional - if not configured, the server will work without caching
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 formatendDate(required): End date in YYYY-MM-DD formatgranularity(optional): 'daily', 'monthly', or 'total' (default: 'total')groupBy(optional): Array of dimensions to group by (e.g., ['SERVICE', 'REGION'])
Example Request:
Example Response:
provider_list
List all configured providers and their connection status.
Response includes:
Provider name
Configuration status
Credential validation status
Example Response:
provider_balance
Check remaining balance or credits (provider-specific). Note: Currently not implemented for most providers
Provider Setup
AWS
Enable Cost Explorer in AWS Console
Navigate to AWS Cost Management → Cost Explorer
Click "Enable Cost Explorer" (⚠️ This action is irreversible)
Wait 24 hours for data to be available
Create IAM User with minimal permissions:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["ce:GetCostAndUsage", "ce:GetCostForecast", "ce:GetDimensionValues"], "Resource": "*" } ] }Set environment variables:
AWS_ACCESS_KEY_ID=your-access-key AWS_SECRET_ACCESS_KEY=your-secret-key AWS_REGION=us-east-1 # Cost Explorer only works in us-east-1
⚠️ Important: AWS charges $0.01 per Cost Explorer API request. Caching is enabled by default (1 hour) to minimize costs.
OpenAI
Get API Key from OpenAI Dashboard
Ensure you have:
A paid account with usage history
API access enabled
Set environment variable:
OPENAI_API_KEY=sk-...your-api-key
⚠️ Note: The Usage API is relatively new (December 2024). Ensure your account has access.
Anthropic
Get Admin API Key from Anthropic Console
Requirements:
Organization account (individual accounts are not supported)
Admin role to provision Admin API keys
Admin API key starts with
sk-ant-admin...(different from regular API keys)
Set environment variable:
ANTHROPIC_API_KEY=sk-ant-admin-...your-admin-api-key
⚠️ Important Notes:
Only Admin API keys can access cost and usage data
Cost data is available through two APIs:
Cost Report API: Provides actual billing data in USD
Usage Report API: Provides token-level details with calculated costs
Data typically appears within 5 minutes of API request completion
Supports prompt caching cost tracking
Configuration
Environment Variables
Variable | Description | Default | Required |
| AWS access key | - | For AWS |
| AWS secret key | - | For AWS |
| AWS region | us-east-1 | For AWS |
| OpenAI API key | - | For OpenAI |
| Anthropic Admin API key | - | For Anthropic |
| Cache time-to-live in seconds | 3600 | No |
| Cache backend (memory/redis) | memory | No |
| Redis connection URL | - | If using Redis |
| Log verbosity (debug/info/warn/error) | info | No |
| Server port | 3000 | No |
Cache Configuration
The cache helps reduce API costs and improve performance:
Memory Cache (default): Fast, no setup required, data lost on restart
Redis Cache: Persistent, shared across instances, requires Redis server
To use Redis:
Logging
Structured JSON logging is used for easy parsing:
Development
Project Structure
Commands
Adding a New Provider
Create provider directory:
Implement required files:
types.ts- TypeScript interfacestransformer.ts- Convert API response to unified formatclient.ts- API client implementingProviderClientindex.ts- Public exports
Update server.ts to include the new provider
Add tests in
tests/providers/newprovider/
Testing
Tests use Jest with TypeScript support:
Architecture
Design Principles
Unified Interface: All providers implement the same
ProviderClientinterfaceError Resilience: Automatic retry with exponential backoff
Cost Optimization: Aggressive caching to minimize API calls
Type Safety: Full TypeScript coverage with strict mode
Extensibility: Easy to add new providers or tools
Data Flow
Error Handling
The system implements a hierarchical error handling strategy:
Provider Errors: Specific to each cloud provider
Authentication Errors: Invalid or expired credentials
Rate Limit Errors: Automatic retry with backoff
Validation Errors: Invalid input parameters
Network Errors: Retryable connection issues
Troubleshooting
Common Issues
"Authentication failed" error
Verify your API keys/credentials are correct
Check if the credentials have the required permissions
For AWS, ensure you're using us-east-1 region for Cost Explorer
No cost data returned
AWS: Wait 24 hours after enabling Cost Explorer
OpenAI: Verify you have a paid account with usage
High AWS costs
Cost Explorer API charges $0.01 per request
Increase
CACHE_TTLto reduce API callsUse Redis cache for persistence across restarts
"Rate limit exceeded" error
The system automatically retries with exponential backoff
If persistent, check your API quotas
Consider increasing cache TTL
Debug Mode
Enable debug logging for more information:
Health Check
Test individual providers:
Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Workflow
Fork the repository
Create a feature branch:
git checkout -b feature/your-featureMake your changes
Add tests for new functionality
Ensure all tests pass:
npm testLint your code:
npm run lintCommit with descriptive message
Push to your fork and submit a PR
Code Style
Follow TypeScript best practices
Use meaningful variable names
Add JSDoc comments for public APIs
Keep functions small and focused
Write tests for new features
📊 Project Status
Build & Test
CI/CD: Automated testing on push and PR
Node Support: 18.x and 20.x
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
License
MIT License - see LICENSE file for details
日本語ドキュメント
概要
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クレジット使用量の監視
クレジット期限前のアラート
インストール
Claude Desktopとの統合
Claude Desktopの設定ファイルに以下を追加:
Claude Codeとの統合
Claude Codeは2つの設定方法でMCPサーバーをサポートしています:
方法1: プロジェクト固有の設定(推奨)
プロジェクトのルートディレクトリに .mcp.json ファイルを作成:
この設定は、Claude Codeでプロジェクトを開いたときに自動的に読み込まれます。
方法2: VS Code設定(グローバル設定)
VS Code設定を開く(Cmd/Ctrl + ,)
「Claude Code MCP Servers」を検索
「settings.jsonで編集」をクリック
コスト管理サーバーの設定を追加:
VS Codeウィンドウをリロード(Cmd/Ctrl + Shift + P → 「開発者: ウィンドウの再読み込み」)
コスト管理サーバーの使用
設定が完了したら、Claude Codeでクラウドコストについて質問できます:
セキュリティに関する注意:
プロジェクト固有の
.mcp.jsonは.gitignoreに追加して、APIキーをコミットしないようにしてください本番環境では環境変数やシークレット管理ツールの使用を検討してください
キャッシュはオプションです - 設定されていない場合、サーバーはキャッシュなしで動作します
使用例
プロバイダーの設定
各プロバイダーの詳細な設定方法は英語版ドキュメントを参照してください。
開発
📊 プロジェクトステータス
ビルド&テスト
CI/CD: プッシュとPR時の自動テスト
Nodeサポート: 18.xと20.x
カバレッジ: カバレッジレポート付きの包括的なテストスイート
セキュリティ
依存関係スキャン: 週次自動更新
シークレット検出: 公開された認証情報の継続的監視
コード分析: CodeQLセキュリティスキャン
品質
型安全性: 厳格なTypeScript設定
リンティング: コミット時のESLint自動修正
フォーマット: Prettierコードフォーマット
ライセンス
MIT License
Built with ❤️ using TypeScript and MCP