Cost Management MCP

by knishioka

Not rated
GitHub

About

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

Details

Author
knishioka
Categories
Cloud Service, Infrastructure

Method 1: Project-specific configuration (Recommended)

Create a.mcp.jsonfile in your project root:

{ "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" } } } }

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:
{ "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", "ANTHROPIC_API_KEY": "sk-ant-admin-...your-admin-key", "CACHE_TTL": "3600", "LOG_LEVEL": "info" } } } }

- Reload VS Code window (Cmd/Ctrl + Shift + P β†’ "Developer: Reload Window")

Once configured, you can ask Claude Code about your cloud costs:

πŸ“Š "What are my AWS costs for this month?" πŸ“ˆ "Show me OpenAI API usage trends" πŸ” "Break down my cloud expenses by service" πŸ’° "Compare costs across all providers"

- For project-specific.mcp.json, add it to.gitignoreto avoid committing sensitive API keys
- Consider using environment variables or a secrets manager for production use
- The cache is optional - if not configured, the server will work without caching

Retrieve cost data for specified providers and time periods.

- 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'])

{ "provider": "aws", "startDate": "2024-01-01", "endDate": "2024-01-31", "granularity": "daily", "groupBy": ["SERVICE"] }
{ "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" } } }

List all configured providers and their connection status.

- Provider name
- Configuration status
- Credential validation status

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

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

- 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 Userwith minimal permissions:

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["ce:GetCostAndUsage", "ce:GetCostForecast", "ce:GetDimensionValues"], "Resource": "*" } ] }
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.

- A paid account with usage history
- API access enabled

⚠️Note: The Usage API is relatively new (December 2024). Ensure your account has access.
-

Get Admin API KeyfromAnthropic Console

- Organization account (individual accounts are not supported)
- Admin role to provision Admin API keys
- Admin API key starts withsk-ant-admin...(different from regular API keys)

ANTHROPIC_API_KEY=sk-ant-admin-...your-admin-api-key

- 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

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

CACHE_TYPE=redis REDIS_URL=redis://localhost:6379

Structured JSON logging is used for easy parsing:

# View logs in development npm run dev # View logs in production with jq npm start 2>&1 | jq '.' # Filter errors only npm start 2>&1 | jq 'select(.level == "error")'
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
# 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

- types.ts- TypeScript interfaces
- transformer.ts- Convert API response to unified format
- client.ts- API client implementingProviderClient
- index.ts- Public exports
-

Update server.ts to include the new provider

Add tests intests/providers/newprovider/

# 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

- Unified Interface: All providers implement the sameProviderClientinterface
- Error 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

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

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

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

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?"

- πŸ” 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

This server provides three powerful tools for cost management:

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

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

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

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

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

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

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

- 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

- "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?"

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

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

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

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

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

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

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

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

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

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

- Installation
-
Quick Start
-
Available Tools

- cost_get
-
provider_list
-
provider_balance
-
openai_costs
-
anthropic_costs
-
aws_costs
-
provider_compare

- Node.js 18 or higher
- npm or yarn
- Active accounts with the cloud providers you want to monitor

CI currently verifies Node.js 18.x, 20.x, 22.x, and 24.x. Node.js 20.x is the primary lane for coverage upload and representative build checks.

git clone https://github.com/knishioka/cost-management-mcp.git cd cost-management-mcp

-

Edit.envand add your credentials (seeProvider Setup)

# Development mode (with hot reload) npm run dev # Production mode npm start

- Add to your Claude Desktop configuration (~/Library/Application Support/Claude/claude_desktop_config.jsonon macOS):

{ "mcpServers": { "cost-management": { "command": "node", "args": ["/absolute/path/to/cost-management-mcp/dist/index.js"], "env": { "AWS_ACCESS_KEY_ID": "your-key", "AWS_SECRET_ACCESS_KEY": "your-secret", "AWS_REGION": "us-east-1", "OPENAI_API_KEY": "your-key", "CACHE_TTL": "3600", "LOG_LEVEL": "info" } } } }
Can you check my AWS costs for this month? What are my OpenAI API costs for the last 7 days? List all my configured cloud providers.

Claude Code supports MCP servers through two configuration methods:

Method 1: Project-specific configuration (Recommended)

Create a.mcp.jsonfile in your project root:

{ "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" } } } }

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:
{ "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", "ANTHROPIC_API_KEY": "sk-ant-admin-...your-admin-key", "CACHE_TTL": "3600", "LOG_LEVEL": "info" } } } }

- Reload VS Code window (Cmd/Ctrl + Shift + P β†’ "Developer: Reload Window")

Once configured, you can ask Claude Code about your cloud costs:

πŸ“Š "What are my AWS costs for this month?" πŸ“ˆ "Show me OpenAI API usage trends" πŸ” "Break down my cloud expenses by service" πŸ’° "Compare costs across all providers"

- For project-specific.mcp.json, add it to.gitignoreto avoid committing sensitive API keys
- Consider using environment variables or a secrets manager for production use
- The cache is optional - if not configured, the server will work without caching

Retrieve cost data for specified providers and time periods.

- 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'])

{ "provider": "aws", "startDate": "2024-01-01", "endDate": "2024-01-31", "granularity": "daily", "groupBy": ["SERVICE"] }
{ "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" } } }

List all configured providers and their connection status.

- Provider name
- Configuration status
- Credential validation status

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

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

- 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 Userwith minimal permissions:

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["ce:GetCostAndUsage", "ce:GetCostForecast", "ce:GetDimensionValues"], "Resource": "*" } ] }
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.

- A paid account with usage history
- API access enabled

⚠️Note: The Usage API is relatively new (December 2024). Ensure your account has access.
-

Get Admin API KeyfromAnthropic Console

- Organization account (individual accounts are not supported)
- Admin role to provision Admin API keys
- Admin API key starts withsk-ant-admin...(different from regular API keys)

ANTHROPIC_API_KEY=sk-ant-admin-...your-admin-api-key

- 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

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

CACHE_TYPE=redis REDIS_URL=redis://localhost:6379

Structured JSON logging is used for easy parsing:

# View logs in development npm run dev # View logs in production with jq npm start 2>&1 | jq '.' # Filter errors only npm start 2>&1 | jq 'select(.level == "error")'
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
# 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

- types.ts- TypeScript interfaces
- transformer.ts- Convert API response to unified format
- client.ts- API client implementingProviderClient
- index.ts- Public exports
-

Update server.ts to include the new provider

Add tests intests/providers/newprovider/

# 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

- Unified Interface: All providers implement the sameProviderClientinterface
- Error 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

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

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

No reviews yet β€” be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.