# Add Lambda Powertools to an AWS CDK App from a Linear Issue

Yes. Label the issue and an agent adds Powertools logging, tracing and metrics to every Lambda in your CDK app, turns on X-Ray, proves it with tests and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-lambda-powertools/aws-cdk/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent clones the app into its own cloud sandbox and reads the stack and the handlers before it adds a library. In a CDK app like `typescript/api-cors-lambda-crud-dynamodb` in aws-samples/aws-cdk-examples, `index.ts` defines one stack with an `items` DynamoDB table, five `NodejsFunction` constructs built from `lambdas/get-one.ts`, `get-all.ts`, `create.ts`, `update-one.ts` and `delete-one.ts` on `Runtime.NODEJS_24_X`, and a `RestApi` named `Items Service` with `/items` and `/items/{id}` plus a mock `OPTIONS` integration for CORS. The functions share one `NodejsFunctionProps` object: `bundling.externalModules` keeps `@aws-sdk/*` out of the bundle, `depsLockFilePath` points at `lambdas/package-lock.json`, and `environment` carries `PRIMARY_KEY` and `TABLE_NAME`. `lambdas/package.json` depends on `@aws-sdk/client-dynamodb`, `@aws-sdk/lib-dynamodb` and `uuid`, installed by a `postinstall` hook in the outer `package.json`, which pins `aws-cdk-lib` 2.262.1 and `aws-cdk` 2.1133.0 and runs Jest with `@swc/jest`.

The handlers are where the gaps are. Each one is `export const handler = async (event: any = {})`, builds a `DynamoDBDocument` client at module scope and returns `{ statusCode, body }`; a failed DynamoDB call is caught and turned into a `500` with a fixed message, and nothing is logged on the way, so a production error leaves no trace beyond the status code. No example in the repository's TypeScript tree imports Powertools; one Python example, `python/api-eventbridge-lambda/requirements.txt`, lists `aws_lambda_powertools`. The agent adds `@aws-lambda-powertools/logger`, `@aws-lambda-powertools/tracer`, `@aws-lambda-powertools/metrics` and `@middy/core` to `lambdas/package.json`, writes a shared `lambdas/powertools.ts` that creates one `Logger`, `Tracer` and `Metrics` from `POWERTOOLS_SERVICE_NAME` and `POWERTOOLS_METRICS_NAMESPACE`, and wraps each handler with the `injectLambdaContext`, `captureLambdaHandler` and `logMetrics` middlewares. The DynamoDB client goes through `tracer.captureAWSv3Client`, so each `get`, `put`, `update` and `delete` becomes a subsegment, every `catch` block now calls `logger.error` with the thrown error before returning the same response, and each handler records one count metric such as `ItemCreated` or `ItemNotFound`.

The stack changes are small and deliberate. The agent adds `tracing: Tracing.ACTIVE` and the three `POWERTOOLS_*` and `LOG_LEVEL` variables to the shared `NodejsFunctionProps`, so all five functions pick them up from one place, and sets `deployOptions.tracingEnabled` on the `RestApi` so X-Ray traces start at the API Gateway stage rather than inside the function. Powertools is bundled by esbuild like the rest of the handler code; the agent leaves `@aws-sdk/*` external as before and does not reach for the Powertools Lambda layer, because a layer ARN is region-specific and the example deploys wherever the caller's credentials point. The `README.md` gains a short section on reading the structured logs in CloudWatch Logs Insights and the service map in X-Ray.

Proof follows the repository's own test style. `typescript/lambda-cron/lambda-cron.test.ts` uses `Template.fromStack` with `hasResourceProperties` and `Capture`, so the agent adds `api-cors-lambda-crud-dynamodb.test.ts` beside `index.ts` that asserts five `AWS::Lambda::Function` resources with `TracingConfig.Mode` of `Active` and the Powertools variables in `Environment.Variables`, and an `AWS::ApiGateway::Stage` with `TracingEnabled` true. Then it runs what `scripts/build-typescript.sh` runs for a changed example in CI: `npm ci`, `npm run build`, `npm test` and `cdk synth` through `scripts/synth.sh`, so the esbuild bundling of the five handlers with Powertools inside is exercised rather than assumed.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add AWS Lambda Powertools for TypeScript to this CDK app. Read index.ts, cdk.json, package.json, jest.config.js, lambdas/package.json and every handler under lambdas/ first, plus the nearest *.test.ts in the repository for the assertion style. Add @aws-lambda-powertools/logger, tracer and metrics and @middy/core to the lambdas package, create lambdas/powertools.ts with one Logger, Tracer and Metrics instance read from POWERTOOLS_SERVICE_NAME and POWERTOOLS_METRICS_NAMESPACE, wrap every handler with injectLambdaContext, captureLambdaHandler and logMetrics, capture the DynamoDB client with the tracer, log every caught error with logger.error without changing the response, and add one count metric per handler outcome. In the stack set tracing: Tracing.ACTIVE and the POWERTOOLS_SERVICE_NAME, POWERTOOLS_METRICS_NAMESPACE and LOG_LEVEL variables on the shared function props, and enable tracing on the RestApi deploy stage. Bundle Powertools with esbuild; do not add a layer. Add an assertion test that checks TracingConfig, the environment variables and the stage tracing flag. Run npm ci, npm run build, npm test and cdk synth, and open a pull request listing the files, the metric names and the test output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request on its own branch that adds `lambdas/powertools.ts`, edits the five handlers under `lambdas/` and `lambdas/package.json` with its lock file, changes `index.ts` to add tracing and the Powertools environment to the shared props and the API stage, adds `api-cors-lambda-crud-dynamodb.test.ts`, and extends the README. The handlers' request and response shapes are unchanged: a reviewer can diff each file and see that only the wrapper, the client capture, the `logger.error` calls and the metrics were added.

The description names the service name and metrics namespace used, lists each handler with the metric it emits, and quotes the `npm test` summary and the `cdk synth` result. The transcript at `GET /o/{org}/sessions/{id}/messages` keeps `npm ci`, `npm run build`, `npm test` and `cdk synth` with their output, so the reviewer can see the esbuild bundles built with Powertools included and the assertions pass rather than read a sentence saying so.

Before merging, a reviewer checks that `LOG_LEVEL` is `INFO` or stricter for production and that the metrics namespace will not collide with another service's. A follow-up on the same session can add `logger.appendKeys` with the item id on each request, an idempotency store for `create.ts`, or Powertools for Python on a sibling example.

## Run it on every Linear issue labelled agent

Sign in to Linear once with `POST /me/connections {"type": "app", "name": "linear"}` and finish the authorize URL in the console. Then add an automation to the Project with this prompt and a `linear` trigger on `linear.issue.labeled`, filtered to the label you triage with. The trigger adds the issue after the prompt, so an issue such as "we have no logs when the update handler fails" tells the run which handlers matter most; only label changes made by a person in your Rush org fire it, and the automation starts at most `max_runs_per_hour` runs in an hour.

Each labelled issue runs in its own sandbox and opens its own pull request that links back to the issue. Once Powertools is in, a later issue such as "add a metric for reserved-keyword rejections" runs against the same app and adds one `addMetric` call and one assertion, because the shared `powertools.ts` module and the test already exist.

## Why run it on Rush?

Retrofitting observability into a working serverless app is mostly careful repetition: the same wrapper on every handler, the same variables on every function, and a test that proves none was missed. The agent does that against the actual handlers in its own sandbox, with Node and the CDK toolkit already installed, and it bundles the result with esbuild the way the deploy would, so a missing dependency or a wrong import fails in the run rather than in CloudWatch.

Every `npm test` and `cdk synth` and its output stay in the run's transcript, so the pull request's claim that five functions trace and log is checkable against the synthesized template, and the person who labelled the issue is free while it happens. Several CDK apps can get the same instrumentation at once, each in its own sandbox and its own pull request.

## Frequently asked questions

### Why bundle Powertools instead of using the Lambda layer?

Both work. The layer keeps bundles smaller but its ARN is specific to a region and a release, which does not suit an example deployed wherever the caller's credentials point. Bundling with esbuild keeps the function self-contained and lets `cdk synth` prove the import resolves. A follow-up can switch to the layer and add it to `bundling.externalModules`.

### Does this change what the API returns?

No. Each handler returns the same `statusCode` and `body` as before; the middlewares run around it. The only behavioural change is that a caught DynamoDB error is now logged with `logger.error` before the existing `500` response, and that each outcome increments a metric.

### Will X-Ray add cost or latency?

Tracing records a segment per invocation and a subsegment per captured DynamoDB call. The `Tracing.ACTIVE` setting is one line in the shared props, so it can be switched per environment, and the pull request leaves `LOG_LEVEL` as a variable so staging can run at `DEBUG` while production stays at `INFO`.

### Does it work for Python Lambdas too?

The same repository already lists `aws_lambda_powertools` in one Python example's `requirements.txt`. The approach is the same, with the Python decorators instead of Middy middleware; the agent reads the handler language from the `NodejsFunction` or `PythonFunction` constructs and follows whichever the stack uses.

### How do I find the logs afterwards?

Every log line is JSON with `service`, `function_request_id` and `xray_trace_id`, so the README section the agent adds shows a CloudWatch Logs Insights query that filters on the service name and a trace id, and the X-Ray service map shows the API stage, each function and its DynamoDB calls.

## More AWS CDK jobs

- [Set Lambda Log Retention in an AWS CDK Stack](https://getrush.ai/run/add-log-retention/aws-cdk/)
- [Tag Every Resource in an AWS CDK App from a Linear Issue](https://getrush.ai/run/add-resource-tags/aws-cdk/)
- [Add AWS WAF to an API Gateway REST API in AWS CDK](https://getrush.ai/run/add-waf/aws-cdk/)

## The same job on other stacks

- [Add Lambda Powertools to a Serverless Framework Node.js API](https://getrush.ai/run/add-lambda-powertools/serverless/)

## More jobs like this: Turn a Linear label into a PR

- [Run Credo and mix format in CI for an Elixir App](https://getrush.ai/run/add-lint-to-ci/credo/)
- [Add Liveness and Readiness Probes to Kubernetes Deployments](https://getrush.ai/run/add-liveness-readiness-probes/kubernetes/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
