iflow-mcp_aws-samples-aws-cost-explorer-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ MIT No Attribution
2
+
3
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
13
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
14
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
15
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
16
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,361 @@
1
+ Metadata-Version: 2.4
2
+ Name: iflow-mcp_aws-samples-aws-cost-explorer-mcp
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ Requires-Python: <3.13,>=3.11
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: boto3>=1.37.9
9
+ Requires-Dist: botocore>=1.37.9
10
+ Requires-Dist: chainlit>=2.4.1
11
+ Requires-Dist: jmespath>=1.0.1
12
+ Requires-Dist: langchain>=0.3.20
13
+ Requires-Dist: langchain-anthropic>=0.3.9
14
+ Requires-Dist: langchain-aws>=0.2.15
15
+ Requires-Dist: langchain-mcp-adapters>=0.0.4
16
+ Requires-Dist: langgraph>=0.3.10
17
+ Requires-Dist: mcp>=1.3.0
18
+ Requires-Dist: pandas>=2.2.3
19
+ Requires-Dist: pydantic>=2.10.6
20
+ Requires-Dist: tabulate>=0.9.0
21
+ Requires-Dist: typing-extensions>=4.12.2
22
+ Dynamic: license-file
23
+
24
+ # A sample MCP server for understanding cloud spend
25
+
26
+ An MCP server for getting AWS spend data via Cost Explorer and Amazon Bedrock usage data via [`Model invocation logs`](https://docs.aws.amazon.com/bedrock/latest/userguide/model-invocation-logging.html) in Amazon Cloud Watch through [Anthropic's MCP (Model Control Protocol)](https://www.anthropic.com/news/model-context-protocol). See section on ["secure" remote MCP server](#secure-remote-mcp-server) to see how you can run your MCP server over HTTPS.
27
+
28
+ ```mermaid
29
+ flowchart LR
30
+ User([User]) --> UserApp[User Application]
31
+ UserApp --> |Queries| Host[Host]
32
+
33
+ subgraph "Claude Desktop"
34
+ Host --> MCPClient[MCP Client]
35
+ end
36
+
37
+ MCPClient --> |MCP Protocol over HTTPS| MCPServer[AWS Cost Explorer MCP Server]
38
+
39
+ subgraph "AWS Services"
40
+ MCPServer --> |API Calls| CostExplorer[(AWS Cost Explorer)]
41
+ MCPServer --> |API Calls| CloudWatchLogs[(AWS CloudWatch Logs)]
42
+ end
43
+ ```
44
+
45
+ You can run the MCP server locally and access it via the Claude Desktop or you could also run a Remote MCP server on Amazon EC2 and access it via a MCP client built into a LangGraph Agent.
46
+
47
+ ## Overview
48
+
49
+ This tool provides a convenient way to analyze and visualize AWS cloud spending data using Anthropic's Claude model as an interactive interface. It functions as an MCP server that exposes AWS Cost Explorer API functionality to Claude Desktop, allowing you to ask questions about your AWS spend in natural language.
50
+
51
+ ## Features
52
+
53
+ - **Amazon EC2 Spend Analysis**: View detailed breakdowns of EC2 spending for the last day
54
+ - **Amazon Bedrock Spend Analysis**: View breakdown by region, users and models over the last 30 days
55
+ - **Service Spend Reports**: Analyze spending across all AWS services for the last 30 days
56
+ - **Detailed Cost Breakdown**: Get granular cost data by day, region, service, and instance type
57
+ - **Interactive Interface**: Use Claude to query your cost data through natural language
58
+
59
+ ## Requirements
60
+
61
+ - Python 3.12
62
+ - AWS credentials with Cost Explorer access
63
+ - Anthropic API access (for Claude integration)
64
+ - [Optional] Amazon Bedrock access (for LangGraph Agent)
65
+ - [Optional] Amazon EC2 for running a remote MCP server
66
+
67
+ ## Installation
68
+
69
+ 1. Install `uv`:
70
+ ```bash
71
+ # On macOS and Linux
72
+ curl -LsSf https://astral.sh/uv/install.sh | sh
73
+ ```
74
+
75
+
76
+ ```powershell
77
+ # On Windows
78
+ powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
79
+ ```
80
+ Additional installation options are documented [here](https://docs.astral.sh/uv/getting-started/installation/)
81
+
82
+ 2. Clone this repository: (assuming this will be updated to point to aws-samples?)
83
+ ```
84
+ git clone https://github.com/aws-samples/sample-cloud-spend-mcp-server
85
+ cd aws-cost-explorer-mcp
86
+ ```
87
+
88
+ 3. Set up the Python virtual environment and install dependencies:
89
+ ```
90
+ uv venv --python 3.12 && source .venv/bin/activate && uv pip install --requirement pyproject.toml
91
+ ```
92
+
93
+ 4. Configure your AWS credentials:
94
+ ```
95
+ mkdir -p ~/.aws
96
+ # Set up your credentials in ~/.aws/credentials and ~/.aws/config
97
+ ```
98
+ If you use AWS IAM Identity Center, follow the [docs](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html) to configure your short-term credentials
99
+
100
+ ## Usage
101
+
102
+ ### Prerequisites
103
+
104
+ 1. Setup [model invocation logs](https://docs.aws.amazon.com/bedrock/latest/userguide/model-invocation-logging.html#setup-cloudwatch-logs-destination) in Amazon CloudWatch.
105
+ 1. Ensure that the IAM user/role being used has full read-only access to Amazon Cost Explorer and Amazon CloudWatch, this is required for the MCP server to retrieve data from these services.
106
+ See [here](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-example-policies.html) and [here](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/CloudWatchLogsReadOnlyAccess.html) for sample policy examples that you can use & modify as per your requirements.
107
+
108
+ ### Local setup
109
+
110
+ Uses `stdio` as a transport for MCP, both the MCP server and client are running on your local machine.
111
+
112
+ #### Starting the Server (local)
113
+
114
+ Run the server using:
115
+
116
+ ```
117
+ export MCP_TRANSPORT=stdio
118
+ export BEDROCK_LOG_GROUP_NAME=YOUR_BEDROCK_CW_LOG_GROUP_NAME
119
+ python server.py
120
+ ```
121
+
122
+ #### Claude Desktop Configuration
123
+
124
+ There are two ways to configure this tool with Claude Desktop:
125
+
126
+ ##### Option 1: Using Docker
127
+
128
+ Add the following to your Claude Desktop configuration file. The file can be found out these paths depending upon you operating system.
129
+
130
+ - macOS: ~/Library/Application Support/Claude/claude_desktop_config.json.
131
+ - Windows: %APPDATA%\Claude\claude_desktop_config.json.
132
+ - Linux: ~/.config/Claude/claude_desktop_config.json.
133
+
134
+ ```json
135
+ {
136
+ "mcpServers": {
137
+ "aws-cost-explorer": {
138
+ "command": "docker",
139
+ "args": [ "run", "-i", "--rm", "-e", "AWS_PROFILE", "-e", "AWS_REGION", "-e", "BEDROCK_LOG_GROUP_NAME", "-e", "MCP_TRANSPORT", "aws-cost-explorer-mcp:latest" ],
140
+ "env": {
141
+ "AWS_PROFILE": "YOUR_AWS_PROFILE_NAME",
142
+ "AWS_REGION": "us-east-1",
143
+ "BEDROCK_LOG_GROUP_NAME": "YOUR_CLOUDWATCH_BEDROCK_MODEL_INVOCATION_LOG_GROUP_NAME",
144
+ "MCP_TRANSPORT": "stdio"
145
+ }
146
+ }
147
+ }
148
+ }
149
+ ```
150
+
151
+ > **IMPORTANT**: Replace `YOUR_AWS_PROFILE_NAME` with your actual AWS profile name. This profile should be configured in your `~/.aws/credentials` and `~/.aws/config` files.
152
+
153
+ ##### Option 2: Using UV (without Docker)
154
+
155
+ If you prefer to run the server directly without Docker, you can use UV:
156
+
157
+ ```json
158
+ {
159
+ "mcpServers": {
160
+ "aws_cost_explorer": {
161
+ "command": "uv",
162
+ "args": [
163
+ "--directory",
164
+ "/path/to/aws-cost-explorer-mcp-server",
165
+ "run",
166
+ "server.py"
167
+ ],
168
+ "env": {
169
+ "AWS_PROFILE": "YOUR_AWS_PROFILE_NAME",
170
+ "AWS_REGION": "us-east-1",
171
+ "BEDROCK_LOG_GROUP_NAME": "YOUR_CLOUDWATCH_BEDROCK_MODEL_INVOCATION_LOG_GROUP_NAME",
172
+ "MCP_TRANSPORT": "stdio"
173
+ }
174
+ }
175
+ }
176
+ }
177
+ ```
178
+
179
+ Make sure to replace the directory path with the actual path to your repository on your system.
180
+
181
+ ### Remote setup
182
+
183
+ Uses `sse` as a transport for MCP, the MCP servers on EC2 and the client is running on your local machine. Note that Claude Desktop does not support remote MCP servers at this time (see [this](https://github.com/orgs/modelcontextprotocol/discussions/16) GitHub issue).
184
+
185
+ #### Starting the Server (remote)
186
+
187
+ You can start a remote MCP server on Amazon EC2 by following the same instructions as above. Make sure to set the `MCP_TRANSPORT` as `sse` (server side events) as shown below. **Note that the MCP uses JSON-RPC 2.0 as its wire format, therefore the protocol itself does not include authorization and authentication (see [this GitHub issue](https://github.com/modelcontextprotocol/specification/discussions/102)), do not send or receive sensitive data over MCP**.
188
+
189
+ Run the server using:
190
+
191
+ ```
192
+ export MCP_TRANSPORT=sse
193
+ export BEDROCK_LOG_GROUP_NAME=YOUR_BEDROCK_CW_LOG_GROUP_NAME
194
+ python server.py
195
+ ```
196
+
197
+ 1. The MCP server will start listening on TCP port 8000.
198
+ 1. Configure an ingress rule in the security group associated with your EC2 instance to allow access to TCP port 8000 from your local machine (where you are running the MCP client/LangGraph based app) to your EC2 instance.
199
+
200
+ >Also see section on running a ["secure" remote MCP server](#secure-remote-mcp-server) i.e. a server to which your MCP clients can connect over HTTPS.
201
+
202
+ #### Testing with a CLI MCP client
203
+
204
+ You can test your remote MCP server with the `mcp_sse_client.py` script. Running this script will print the list of tools available from the MCP server and an output for the `get_bedrock_daily_usage_stats` tool.
205
+
206
+ ```{.bashrc}
207
+ MCP_SERVER_HOSTNAME=YOUR_MCP_SERVER_EC2_HOSTNAME
208
+ python mcp_sse_client.py --host $MCP_SERVER_HOSTNAME
209
+ ```
210
+
211
+
212
+ #### Testing with Chainlit app
213
+
214
+ The `app.py` file in this repo provides a Chainlit app (chatbot) which creates a LangGraph agent that uses the [`LangChain MCP Adapter`](https://github.com/langchain-ai/langchain-mcp-adapters) to import the tools provided by the MCP server as tools in a LangGraph Agent. The Agent is then able to use an LLM to respond to user questions and use the tools available to it as needed. Thus if the user asks a question such as "_What was my Bedrock usage like in the last one week?_" then the Agent will use the tools available to it via the remote MCP server to answer that question. We use Claude 3.5 Haiku model available via Amazon Bedrock to power this agent.
215
+
216
+ Run the Chainlit app using:
217
+
218
+ ```{.bashrc}
219
+ chainlit run app.py --port 8080
220
+ ```
221
+
222
+ A browser window should open up on `localhost:8080` and you should be able to use the chatbot to get details about your AWS spend.
223
+
224
+ ### Available Tools
225
+
226
+ The server exposes the following tools that Claude can use:
227
+
228
+ 1. **`get_ec2_spend_last_day()`**: Retrieves EC2 spending data for the previous day
229
+ 1. **`get_detailed_breakdown_by_day(days=7)`**: Delivers a comprehensive analysis of costs by region, service, and instance type
230
+ 1. **`get_bedrock_daily_usage_stats(days=7, region='us-east-1', log_group_name='BedrockModelInvocationLogGroup')`**: Delivers a per-day breakdown of model usage by region and users.
231
+ 1. **`get_bedrock_hourly_usage_stats(days=7, region='us-east-1', log_group_name='BedrockModelInvocationLogGroup')`**: Delivers a per-day per-hour breakdown of model usage by region and users.
232
+
233
+ ### Example Queries
234
+
235
+ Once connected to Claude through an MCP-enabled interface, you can ask questions like:
236
+
237
+ - "Help me understand my Bedrock spend over the last few weeks"
238
+ - "What was my EC2 spend yesterday?"
239
+ - "Show me my top 5 AWS services by cost for the last month"
240
+ - "Analyze my spending by region for the past 14 days"
241
+ - "Which instance types are costing me the most money?"
242
+ - "Which services had the highest month-over-month cost increase?"
243
+
244
+ ## Docker Support
245
+
246
+ A Dockerfile is included for containerized deployment:
247
+
248
+ ```
249
+ docker build -t aws-cost-explorer-mcp .
250
+ docker run -v ~/.aws:/root/.aws aws-cost-explorer-mcp
251
+ ```
252
+
253
+ ## Development
254
+
255
+ ### Project Structure
256
+
257
+ - `server.py`: Main server implementation with MCP tools
258
+ - `pyproject.toml`: Project dependencies and metadata
259
+ - `Dockerfile`: Container definition for deployments
260
+
261
+ ### Adding New Cost Analysis Tools
262
+
263
+ To extend the functionality:
264
+
265
+ 1. Add new functions to `server.py`
266
+ 2. Annotate them with `@mcp.tool()`
267
+ 3. Implement the AWS Cost Explorer API calls
268
+ 4. Format the results for easy readability
269
+
270
+ ## Secure "remote" MCP server
271
+
272
+ We can use [`nginx`](https://nginx.org/) as a reverse-proxy so that it can provide an HTTPS endpoint for connecting to the MCP server. Remote MCP clients can connect to `nginx` over HTTPS and then it can proxy traffic internally to `http://localhost:8000`. The following steps describe how to do this.
273
+
274
+ 1. Enable access to TCP port 443 from the IP address of your MCP client (your laptop, or anywhere) in the inbound rules in the security group associated with your EC2 instance.
275
+
276
+ 1. You would need to have an HTTPS certificate and private key to proceed. Let's say you use `your-mcp-server-domain-name.com` as the domain for your MCP server then you will need an SSL cert for `your-mcp-server-domain-name.com` and it will be accessible to MCP clients as `https://your-mcp-server-domain-name.com/sse`. _While you can use a self-signed cert but it would require disabling SSL verification on the MCP client, we DO NOT recommend you do that_. If you are hosting your MCP server on EC2 then you could generate an SSL cert using [no-ip](https://www.noip.com/) or [Let's Encrypt](https://letsencrypt.org/) or other similar services. Place the SSL cert and private key files in `/etc/ssl/certs` and `/etc/ssl/privatekey` folders respectively on your EC2 machine.
277
+
278
+ 1. Install `nginx` on your EC2 machine using the following commands.
279
+
280
+ ```{.bashrc}
281
+ sudo apt-get install nginx
282
+ sudo nginx -t
283
+ sudo systemctl reload nginx
284
+ ```
285
+
286
+ 1. Get the hostname for your EC2 instance, this would be needed for configuring the `nginx` reverse proxy.
287
+
288
+ ```{.bashrc}
289
+ TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") && curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/public-hostname
290
+ ```
291
+
292
+ 1. Copy the following content into a new file `/etc/nginx/conf.d/ec2.conf`. Replace `YOUR_EC2_HOSTNAME`, `/etc/ssl/certs/cert.pem` and `/etc/ssl/privatekey/privkey.pem` with values appropriate for your setup.
293
+
294
+ ```{.bashrc}
295
+ server {
296
+ listen 80;
297
+ server_name YOUR_EC2_HOSTNAME;
298
+
299
+ # Optional: Redirect HTTP to HTTPS
300
+ return 301 https://$host$request_uri;
301
+ }
302
+
303
+ server {
304
+ listen 443 ssl;
305
+ server_name YOUR_EC2_HOSTNAME;
306
+
307
+ # Self-signed certificate paths
308
+ ssl_certificate /etc/ssl/certs/cert.pem;
309
+ ssl_certificate_key /etc/ssl/privatekey/privkey.pem;
310
+
311
+ # Optional: Good practice
312
+ ssl_protocols TLSv1.2 TLSv1.3;
313
+ ssl_ciphers HIGH:!aNULL:!MD5;
314
+
315
+ location / {
316
+ # Reverse proxy to your local app (e.g., port 8000)
317
+ proxy_pass http://127.0.0.1:8000;
318
+ proxy_http_version 1.1;
319
+ proxy_set_header Host $host;
320
+ proxy_set_header X-Real-IP $remote_addr;
321
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
322
+ }
323
+ }
324
+
325
+ ```
326
+
327
+ 1. Restart `nginx`.
328
+
329
+ ```{.bashrc}
330
+ sudo systemctl start nginx
331
+ ```
332
+
333
+ 1. Start your MCP server as usual as described in the [remote setup](#remote-setup) section.
334
+
335
+ 1. Your MCP server is now accessible over HTTPS as `https://your-mcp-server-domain-name.com/sse` to your MCP client.
336
+
337
+ 1. On the client side now (say on your laptop or in your Agent) configure your MCP client to communicate to your MCP server as follows.
338
+
339
+ ```{.bashrc}
340
+ MCP_SERVER_HOSTNAME=YOUR_MCP_SERVER_DOMAIN_NAME
341
+ python mcp_sse_client.py --host $MCP_SERVER_HOSTNAME --port 443
342
+ ```
343
+
344
+ Similarly you could run the chainlit app to talk to remote MCP server over HTTPS.
345
+
346
+ ```{.bashrc}
347
+ export MCP_SERVER_URL=YOUR_MCP_SERVER_DOMAIN_NAME
348
+ export MCP_SERVER_PORT=443
349
+ chainlit run app.py --port 8080
350
+ ```
351
+
352
+ Similarly you could run the LangGraph Agent to talk to remote MCP server over HTTPS.
353
+
354
+ ```{.bashrc}
355
+ python langgraph_agent_mcp_sse_client.py --host YOUR_MCP_SERVER_DOMAIN_NAME --port 443
356
+ ```
357
+
358
+ ## License
359
+
360
+ [MIT License](LICENSE)
361
+