Content
# S3-Athena Logs MCP Server
This project deploys an MCP (Model Context Protocol) server on Bedrock AgentCore Gateway for querying application logs stored in S3 via Athena.
Many AWS customers write application logs directly to S3 via Kinesis Data Firehose — often to manage costs compared to CloudWatch Logs. Querying these logs typically means reading files in S3 manually or running queries through AWS Glue and Amazon Athena.
With the rise of AIOps and the release of AWS DevOps Agent, there's a need for agents to query these logs programmatically. This project provides a sample MCP server that can be integrated with DevOps Agent as a telemetry source.
## Architecture
- **Bedrock AgentCore Gateway** — MCP protocol endpoint with OAuth (CUSTOM_JWT) auth
- **Cognito User Pool** — OAuth2 authorization server (client_credentials flow)
- **Secrets Manager** — Stores the Cognito client secret
- **Lambda** — Handles MCP tool requests, runs Athena queries
- **Athena** — SQL engine over S3 log data
- **Glue Catalog** — Table schema metadata
- **S3** — Log storage (Parquet via Firehose) + Athena query results
## Prerequisites
- Node.js 18+ and npm
- AWS CLI configured with credentials
- AWS CDK CLI: `npm install -g aws-cdk`
- Python 3.11+ (for log generator script)
## Quick Start
```bash
npm install
cdk bootstrap # first time only
cdk deploy --context environment=dev
```
## Configuration
Edit `config/dev.json` (or `config/prod.json`) before deploying:
```jsonc
{
"environment": "dev",
"s3": {
// S3 bucket(s) where your logs are stored (Firehose writes here)
"logBuckets": ["your-log-bucket-name"]
},
"athena": {
// Athena workgroup — must exist before deploy
"workgroup": "your-athena-workgroup",
// Glue database name for queries
"database": "your-glue-database",
"queryTimeoutSeconds": 300,
"maxConcurrentQueries": 5
},
"glue": {
// Glue database name (same as athena.database)
"database": "your-glue-database",
// Default table name — used by MCP tools when table param is omitted
"table": "your-log-table",
// Set true if you want CDK to create the Glue database
"createDatabase": false
},
"lambda": {
"memoryMB": 512,
"timeoutSeconds": 60,
"runtime": "python3.11",
"logRetentionDays": 7
},
"bedrock": {
"rateLimitPerMinute": 100,
"enableAuth": true
},
"cognito": {
// Cognito User Pool name
"userPoolName": "dev-mcp-log-server-pool",
// OAuth scope (resource-server/scope-action)
"oauthScopeName": "mcp/access"
},
"tags": {
"application": "bedrock-mcp-log-server",
"owner": "your-team",
"environment": "dev"
}
}
```
### What you must change
| Field | Description |
|---|---|
| `s3.logBuckets` | S3 bucket(s) where Firehose writes your logs |
| `athena.workgroup` | Your Athena workgroup name |
| `athena.database` | Your Glue database name |
| `glue.database` | Same as `athena.database` |
| `glue.table` | Your Glue table name (default table for MCP tools) |
The `cognito` section can stay at defaults — CDK creates the User Pool, domain, resource server, app client, and stores the client secret in Secrets Manager automatically.
### Assumptions
This project does not create the log pipeline or query infrastructure. It assumes you already have:
1. **Logs in S3** — Application logs are already being written to S3 (e.g. via Kinesis Data Firehose) in a queryable format (Parquet, JSON, etc.)
2. **Glue Database** — A Glue Catalog database exists and is configured with your log table(s)
3. **Glue Table** — At least one Glue table is defined over your S3 log data with the expected schema (see below)
4. **Athena Workgroup** — An Athena workgroup exists with a configured query results location in S3
5. **S3 results bucket** — The Athena workgroup has an output location for query results (e.g. `s3://your-bucket/athena-results/`)
The CDK stack deploys only the MCP server layer (Gateway, Lambda, Cognito) on top of your existing infrastructure.
### Expected log schema
The `search_logs` and `query_logs_by_time` tools generate SQL that assumes your Glue table has these columns:
| Column | Type | Description |
|---|---|---|
| `timestamp` | `string` | ISO 8601 UTC (e.g. `2025-03-17T14:30:00Z`) |
| `level` | `string` | `INFO`, `WARNING`, `ERROR` |
| `message` | `string` | Log message text |
Your table can have additional columns — the `query_logs` tool supports arbitrary SQL so it can access any column. But the two structured tools hardcode `SELECT timestamp, level, message`.
Partition keys (Hive-style, all `string`): `year`, `month`, `day`, `hour`
S3 path pattern: `s3://bucket/logs/year=2025/month=03/day=17/hour=14/`
## Deployment
```bash
# Dev
cdk deploy --context environment=dev
# Prod
cdk deploy --context environment=prod
```
### Stack outputs
After deploy, CDK outputs the values you need for testing and DevOps Agent registration:
| Output | Description |
|---|---|
| `GatewayUrl` | MCP endpoint URL |
| `GatewayId` | Gateway identifier |
| `GatewayArn` | Gateway ARN |
| `LambdaFunctionArn` | Lambda function ARN |
| `CognitoTokenEndpoint` | OAuth2 token endpoint (Exchange URL) |
| `CognitoClientId` | OAuth client ID |
| `CognitoClientSecretArn` | Secrets Manager ARN for the client secret |
| `CognitoOAuthScope` | OAuth scope (e.g. `mcp/access`) |
## Authentication (OAuth2)
The gateway uses OAuth2 `client_credentials` flow via Cognito. CDK creates:
1. A Cognito User Pool with a hosted domain (provides the `/oauth2/token` endpoint)
2. A Resource Server with a custom scope (`mcp/access`)
3. An App Client configured for `client_credentials` grant
4. A Secrets Manager secret containing the client secret
To get an access token manually:
```bash
# Retrieve the client secret
CLIENT_SECRET=$(aws secretsmanager get-secret-value \
--secret-id <CognitoClientSecretArn> \
--query 'SecretString' --output text)
# Request a token
curl -s -X POST <CognitoTokenEndpoint> \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id=<CognitoClientId>&client_secret=${CLIENT_SECRET}&scope=mcp/access"
```
Then use the token in gateway requests:
```bash
curl -X POST <GatewayUrl> \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"tools/call","params":{"name":"logs___list_log_tables","arguments":{}},"id":"1"}'
```
## Registering with AWS DevOps Agent
In the DevOps Agent console under Capabilities > MCP Servers > Add:
1. **MCP server details** — Enter the `GatewayUrl` as the Endpoint URL
2. **Authorization flow** — Select "OAuth Client Credentials"
3. **Authorization configuration**:
- **Client ID** — `CognitoClientId` output
- **Client Secret** — Retrieve from Secrets Manager: `aws secretsmanager get-secret-value --secret-id <CognitoClientSecretArn> --query 'SecretString' --output text`
- **Exchange URL** — `CognitoTokenEndpoint` output
- **Exchange Parameters** — Leave empty or `{}`
- **Scope** — `mcp/access`
4. **Review and submit**
## MCP Tools
The server exposes 5 tools via the MCP protocol:
| Tool | What it does | SQL generated |
|---|---|---|
| `query_logs` | Raw SQL passthrough. Use `{table}` placeholder for default table. | Caller-provided SQL |
| `search_logs` | Keyword search on `message` column with optional time range | `SELECT timestamp, level, message FROM {table} WHERE message LIKE '{pattern}' ...` |
| `list_log_tables` | Lists tables in Glue Catalog | No SQL (Glue API: `GetTables`) |
| `describe_table` | Returns table schema from Glue | No SQL (Glue API: `GetTable`) |
| `query_logs_by_time` | Time-range query with optional column filters and partition pruning | `SELECT timestamp, level, message FROM {table} WHERE timestamp >= '...' AND timestamp <= '...' ORDER BY timestamp` |
All tools that accept a `table` parameter will default to the table configured in `glue.table` if omitted. Through the gateway, tools are namespaced as `logs___<tool_name>` (e.g. `logs___query_logs`).
## Scripts
### Generate test logs
Sends JSON log records to a Firehose stream every 5 seconds:
```bash
python scripts/generate_logs.py --stream-name your-firehose-stream
```
### Test the MCP Gateway
Fetches an OAuth token from Cognito and calls all 5 MCP tools:
```bash
# Fill in the 4 CDK output values at the top of the script, then:
./scripts/test_mcp_gateway.sh
```
Requires `curl` and `jq`. The script retrieves the client secret from Secrets Manager automatically.
## Project Structure
```
├── bin/app.ts # CDK app entry point
├── lib/
│ ├── bedrock-mcp-log-stack.ts # CDK stack (Gateway, Cognito, Lambda, Glue)
│ ├── config/config.ts # Config types and loader
│ └── lambda/
│ ├── handler.py # Lambda handler (MCP tool routing)
│ ├── glue_catalog.py # Glue Catalog operations
│ ├── mcp_types.py # Type definitions
│ └── requirements.txt # Python deps (boto3)
├── config/
│ ├── dev.json # Dev config
│ └── prod.json # Prod config
├── scripts/
│ ├── generate_logs.py # Firehose log generator
│ └── test_mcp_gateway.sh # Gateway test script (OAuth)
└── cdk.json
```
## License
Apache-2.0
## Production Readiness
This section documents features and improvements to consider before running this MCP server in a production environment.
### Security
| Area | Current State | Recommendation |
|---|---|---|
| SQL injection | `search_logs` and `query_logs_by_time` interpolate user-supplied strings (`search_pattern`, filter values, timestamps) directly into SQL. `query_logs` accepts arbitrary SQL. | Sanitize all interpolated values (escape single quotes, reject semicolons, allowlist characters). For `query_logs`, restrict to read-only statements by rejecting DDL/DML keywords (`DROP`, `ALTER`, `CREATE`, `INSERT`, `DELETE`). See details below. |
| Cognito scope granularity | Single `mcp/access` scope for all tools and databases. | Add per-tool or per-database scopes so different clients can be granted different access levels. |
| Secrets rotation | Cognito client secret is stored in Secrets Manager but has no rotation policy. | Configure automatic rotation using a Secrets Manager rotation Lambda. |
| VPC placement | Lambda runs in the default (public) network. | Place the Lambda in a VPC with appropriate security groups if log data or Athena workgroup is VPC-bound, or to restrict egress. |
| WAF / IP restrictions | The Bedrock Gateway endpoint is publicly accessible. | Add request throttling at the Gateway level beyond `rateLimitPerMinute`, or restrict access by IP/VPC. |
### Reliability & Scalability
| Area | Current State | Recommendation |
|---|---|---|
| Athena result pagination | `get_query_results` fetches a single page. Large result sets silently lose rows beyond the first page (~1000 rows). | Paginate using `NextToken` until all rows are fetched. See details below. |
| Concurrency enforcement | `maxConcurrentQueries` exists in config but is never enforced in code. | Add reserved concurrency on the Lambda function, or implement concurrency tracking (e.g., DynamoDB atomic counter, or rely on Athena workgroup query limits). |
| Dead letter queue | No DLQ configured on the Lambda. Failed invocations are lost. | Add an SQS DLQ or a Lambda failure destination. |
| Retry logic | No retries on transient Athena failures (throttling, service unavailable). | Add exponential backoff with jitter on `start_query_execution` and the polling loop. |
| Glue pagination | `list_tables` does not handle pagination. Databases with 100+ tables return a partial list. | Paginate `get_tables` using `NextToken`. |
### Observability
| Area | Current State | Recommendation |
|---|---|---|
| Custom metrics | No CloudWatch custom metrics. | Emit metrics for query latency, success/failure rate, bytes scanned, and timeout count. Build dashboards and alarms. |
| X-Ray tracing | Not enabled. | Add `aws_xray_sdk` to trace the full request path (Gateway → Lambda → Athena). |
| CloudWatch alarms | None configured. | Add alarms on Lambda errors, throttles, duration, and Athena query failures. |
| Log correlation | `requestId` is logged but not correlated with Gateway request ID or X-Ray trace ID. | Include Gateway and X-Ray trace IDs in structured log entries for end-to-end tracing. |
### Cost Control
| Area | Current State | Recommendation |
|---|---|---|
| Athena scan limits | No limit on bytes scanned per query. A `SELECT *` on a large table can be expensive. | Set a per-query data scan limit in the Athena workgroup configuration. |
| Query results cleanup | Athena writes results to S3 with no lifecycle policy. | Add an S3 lifecycle rule to expire query result objects after a few days. |
| Lambda right-sizing | Prod config uses 2048 MB. The Lambda mostly waits on Athena I/O. | Profile with Lambda Power Tuning and reduce memory if CPU is not the bottleneck. |
### Operational
| Area | Current State | Recommendation |
|---|---|---|
| CI/CD | No pipeline defined. | Add a CI/CD pipeline (CodePipeline, GitHub Actions, etc.) for automated testing and deployment. |
| Tests | No unit or integration test suite. | Add tests for input validation, SQL generation, error handling, and the Athena polling logic. |
| Synthetic monitoring | None. | Add a CloudWatch Synthetics canary that periodically calls `list_log_tables` to verify system health. |
| Deployment strategy | No canary or blue/green deployment. | Use CodeDeploy with Lambda traffic shifting for safe rollouts. |
### Feature Gaps
| Area | Current State | Recommendation |
|---|---|---|
| Caching | Every `list_log_tables` and `describe_table` call hits Glue. | Add in-memory caching with TTL (Lambda warm invocations persist state) or use ElastiCache. |
| Query audit trail | Queries are logged to CloudWatch but there is no durable audit trail. | Write query metadata (who, what, when, bytes scanned) to DynamoDB or S3 for compliance. |
| Multi-tenancy | Single Cognito client, single database. | Support per-client database restrictions and query isolation for multi-team use. |
| Result streaming | Large results are buffered entirely in Lambda memory. | For very large result sets, return a pre-signed S3 URL to the Athena result file instead of inline data. |
| Athena results bucket | The workgroup output location is not managed by this stack. | Own the results bucket in CDK with encryption, access logging, and lifecycle policies. |
### Config & Deployment
| Area | Current State | Recommendation |
|---|---|---|
| Prod config placeholders | `config/prod.json` has `<your-prod-*>` placeholder values. | Source config values from SSM Parameter Store or Secrets Manager instead of hardcoded JSON in git. |
| Config validation | `loadConfig` checks field presence but not value ranges. | Validate that `memoryMB` is 128–10240, `queryTimeoutSeconds` < `lambda.timeoutSeconds`, bucket names are valid, etc. |
---
### SQL Injection Protection — Implementation
The `search_logs` and `query_logs_by_time` tools build SQL by interpolating user input into queries. The `query_logs` tool accepts arbitrary SQL. Three functions in `handler.py` protect against injection:
#### `sanitize_sql_value(value: str) -> str`
Escapes single quotes by doubling them (`'` → `''`) and rejects null bytes. Applied to all user-supplied string values before they are interpolated into SQL:
- `search_pattern` in `search_logs`
- `start_time` and `end_time` in both `search_logs` and `query_logs_by_time`
- String values in the `filters` dict in `query_logs_by_time`
#### `validate_table_name(name: str) -> Tuple[bool, str]`
Enforces `^[a-zA-Z0-9_]+$` on all table and database name parameters. Applied in `search_logs`, `query_logs_by_time`, `describe_table`, and to filter column names in `query_logs_by_time`. Prevents injection through identifier parameters.
#### `validate_sql_readonly(sql: str) -> Tuple[bool, str]`
Allowlist-based check on the `query_logs` tool's raw SQL. Strips leading comments and whitespace, then verifies the statement starts with one of: `SELECT`, `WITH`, `SHOW`, `DESCRIBE`, or `EXPLAIN`. Any other statement type (DROP, INSERT, DELETE, UPDATE, etc.) is rejected.
This is intentionally an allowlist on the statement type, not a blocklist scanning the full SQL body. Keywords like DELETE can legitimately appear inside string literals (e.g., `WHERE message LIKE '%DELETE failed%'`) since this server searches log content. Scanning the full body would produce false positives on valid log queries.
All rejections return a standard `VALIDATION_ERROR` response:
```json
{
"success": false,
"data": null,
"error": {
"code": "VALIDATION_ERROR",
"message": "Only read-only SQL is allowed (SELECT, WITH, SHOW, DESCRIBE, EXPLAIN). Detected statement type: DROP",
"details": { "parameter": "sql", "detectedKeyword": "DROP" },
"timestamp": "...",
"requestId": "..."
}
}
```
---
### Athena Pagination Fix — Design
Currently `fetch_query_results` calls `get_query_results` once and processes whatever comes back. Athena returns a maximum of ~1000 rows per page. If the result set is larger, the response includes a `NextToken` that must be used to fetch subsequent pages.
**What needs to change in `fetch_query_results`:**
1. **Loop on `NextToken`** — After the initial `get_query_results` call, check for `NextToken` in the response. If present, call `get_query_results` again with that token. Repeat until `NextToken` is absent.
2. **Accumulate rows across pages** — Append rows from each page to the `rows` list. Column metadata only needs to be parsed from the first page. Note: only the first page includes the header row, so skip-header logic (`rows[1:]`) applies only to page 1.
3. **Enforce `MAX_RESULT_ROWS` across pages** — Stop fetching additional pages once the accumulated row count reaches `MAX_RESULT_ROWS`. Set `truncated = True` in metadata.
**Pseudocode:**
```python
all_rows = []
next_token = None
is_first_page = True
while True:
params = {'QueryExecutionId': query_execution_id}
if next_token:
params['NextToken'] = next_token
response = athena_client.get_query_results(**params)
result_set = response['ResultSet']
if is_first_page:
columns = parse_column_metadata(result_set.get('ResultSetMetadata', {}))
page_rows = parse_row_data(result_set.get('Rows', []), columns) # skips header
is_first_page = False
else:
# Subsequent pages have no header row
page_rows = parse_row_data_no_header(result_set.get('Rows', []), columns)
all_rows.extend(page_rows)
if len(all_rows) >= MAX_RESULT_ROWS:
all_rows = all_rows[:MAX_RESULT_ROWS]
truncated = True
break
next_token = response.get('NextToken')
if not next_token:
break
```
**How the caller knows there are more rows:**
The MCP response already includes a `metadata` object. After this fix, the caller uses these fields:
| Field | Type | Meaning |
|---|---|---|
| `truncated` | `bool` | `true` if the result was cut short by `MAX_RESULT_ROWS` |
| `totalRows` | `int` | Total rows fetched from Athena before truncation |
| `rowCount` | `int` | Number of rows actually returned in this response |
If `truncated` is `true`, the caller knows they didn't get everything. They can either:
- Narrow their query (tighter time range, add filters) to reduce the result set
- Use `query_logs` with a SQL `OFFSET`/`LIMIT` pattern (though Athena doesn't support `OFFSET` natively, so the practical approach is to add a `WHERE timestamp > '<last_seen_timestamp>'` clause to paginate chronologically)
There is no MCP-level cursor or pagination token — the truncation signal tells the agent to refine its query. This is the standard pattern for MCP tools that return bounded result sets.
Connection Info
You Might Also Like
No recommendations available