Repository files navigation

CDK Serverless

npm version

CDK Serverless is a powerful toolkit designed to simplify serverless application development using the AWS Cloud Development Kit (CDK). It offers project management features, higher-level (L3) constructs, and utility libraries to streamline the creation and management of serverless architectures. Additionally, it leverages utility libraries to write Lambda functions and do live updates to Lambda function code during development.

Video introduction: https://www.youtube.com/watch?v=xhNJ0cXG3O8

Features

  • Projen helper classes for easy project configuration
  • AWS CDK L3-constructs for RestApi, GraphQlApi, and more
  • Zero-config Lambda function and VTL template generation
  • Automatic DynamoDB single-table infrastructure setup
  • Built-in monitoring for Lambda functions and APIs
  • Full compatibility with CDK for custom implementations
  • Type-safe auto-completion for routes, resolvers, etc.
  • Support for Cognito authentication and authorization
  • Automated generation of CloudFormation outputs for testing

Quick Start

To begin a new project with CDK Serverless:

Create a new CDK TypeScript app using projen:

$ npx projen new awscdk-app-ts

Adding CDK Serverless is a two step process:

  1. Add 'cdk-serverless' as a dependency to your project
  2. Run npx projen to install it

Now you can use the project type ServerlessProject for your app.

Adding projen constructs

First you need to add the desired construct to your projen configuration: (e.g. RestApi)

import{RestApi}from'cdk-serverless/projen';newRestApi(project,{apiName: 'TestApi',// logical name of your APIdefinitionFile: 'testapi.yaml',// path to your OpenAPI spec});

Then run projen to generate construct files and models for the API.

Using the CDK serverless L3 constructs

In your stack you can then reference the generated L3s to create the API:

import{TestApiRestApi}from'./generated/rest.testapi-api.generated';constapi=newTestApiRestApi(this,'Api',{stageName: props.stageName,domainName: props.domainName,apiHostname: 'api',
singleTableDatastore,cors: true,additionalEnv: {DOMAIN_NAME: props.domainName,},});

This will also create Lambda functions for all operations defined in your spec and wire them accordingly.

Testing Utilities

CDK Serverless provides two powerful test utilities to help you write comprehensive tests for your serverless applications.

LambdaTestUtil

The LambdaTestUtil provides classes for testing both REST and GraphQL Lambda functions in isolation. It's perfect for unit testing your Lambda handlers.

REST API Testing

import{LambdaRestUnitTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaRestUnitTest(handler,{// Optional default headers for all requestsheaders: {'Content-Type': 'application/json',},// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GET requestconstresult=awaittest.call({path: '/items',method: 'GET',});// Test a POST request with bodyconstresult=awaittest.call({path: '/items',method: 'POST',body: JSON.stringify({name: 'test'}),});

GraphQL Testing

import{LambdaGraphQLTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaGraphQLTest(handler,{// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GraphQL queryconstresult=awaittest.call({fieldName: 'getItem',arguments: {id: '123'},});

IntegTestUtil

The IntegTestUtil provides a comprehensive set of tools for integration testing your deployed serverless applications. It handles authentication, data cleanup, and API testing.

import{IntegTestUtil}from'cdk-serverless/tests/integ-test-util';// Initialize with your stack outputsconsttest=newIntegTestUtil({region: 'us-east-1',apiOptions: {baseURL: 'https://api.example.com',},authOptions: {userPoolId: 'us-east-1_xxxxx',userPoolClientId: 'xxxxxxxx',identityPoolId: 'us-east-1:xxxxxxxx',},datastoreOptions: {tableName: 'MyTable',},});// Create and authenticate a test userawaittest.createUser('test@example.com',{'custom:attribute': 'value',},['admin']);// Get an authenticated API clientconstclient=awaittest.getAuthenticatedClient('test@example.com');// Make API callsconstresponse=awaitclient.get('/items');// Clean up test dataawaittest.cleanupItems();awaittest.removeUser('test@example.com');

MCP Auth

CDK Serverless includes built-in support for adding Model Context Protocol (MCP) OAuth authentication to your API. This enables MCP clients like Claude and ChatGPT to authenticate with your API using standard OAuth 2.0 flows.

When activated, the following endpoints are automatically added to your OpenAPI spec:

EndpointMethodRFCPurpose
/.well-known/oauth-protected-resourceGETRFC 9728Resource metadata discovery
/.well-known/oauth-authorization-serverGETRFC 8414Authorization server metadata
/oauth/authorizeGETAuthorize proxy (redirect to upstream)
/oauth/tokenPOSTToken proxy (forward to upstream)
/oauth/registerPOSTRFC 7591Dynamic client registration

All MCP auth endpoints are anonymous (no API authorizer applied).

With Cognito

MCP clients like Claude enforce that all OAuth endpoints (discovery, authorize, token, register) live on the same origin as the API itself. Cognito's hosted UI lives on a different domain (auth.example.com), so MCP clients cannot talk to it directly. Additionally:

  • Cognito Managed Login v2 requires the RFC 8707 resource parameter for custom scopes in authorize requests — MCP clients do not send this parameter.
  • MCP clients construct the token endpoint URL from the OAuth metadata issuer field rather than using the explicit token_endpoint — so the token exchange must be proxied through the API domain.
  • Dynamic Client Registration (RFC 7591) is not natively supported by Cognito.

The MCP auth proxy solves all three problems: it serves discovery metadata on the API domain, strips unsupported parameters before forwarding to Cognito, and implements a simplified registration endpoint that returns a pre-provisioned client ID.

If your API already uses CognitoAuthentication, add MCP auth with minimal config — a dedicated user pool client is created automatically:

constapi=newTestApiRestApi(this,'Api',{stageName: 'dev',domainName: 'example.com',apiHostname: 'api',authentication: cognitoAuth,cors: true,mcpAuth: {cognito: {auth: cognitoAuth,// your CognitoAuthentication constructauthDomain: 'auth.example.com',// Cognito custom/hosted domain (required)},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

The apiDomain is derived from the RestApi's own domain config (apiHostname + domainName), and stageName is reused — no duplication needed.

With any OAuth2 provider

For non-Cognito providers, use generic mode with explicit endpoint URLs:

constapi=newTestApiRestApi(this,'Api',{// ...mcpAuth: {generic: {authorizeEndpoint: 'https://auth.example.com/authorize',tokenEndpoint: 'https://auth.example.com/token',clientId: 'my-pre-provisioned-client-id',},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

Configuration options

OptionDefaultDescription
serverInfo(required){ name, version } returned in MCP initialize
allowedRedirectUrisClaude + ChatGPT callbacksAllowlist for dynamic registration
protocolVersions['2025-11-25', '2025-03-26', '2024-11-05']Supported MCP versions
scopes['openid', 'email', 'profile']Advertised OAuth scopes
stripParameters['resource']Params stripped from authorize/token proxying
lambdaOptionsLambda config for MCP auth handlers

MCP Server runtime

The cdk-serverless/mcp-auth module also exports a JSON-RPC server for implementing the MCP tool endpoint itself:

import{createMcpServer}from'cdk-serverless/mcp-auth';constserver=createMcpServer({serverInfo: {name: 'my-server',version: '1.0.0'},protocolVersions: ['2025-11-25'],resolver: {asyncresolve(headers){// Validate Bearer token, return principal or throw McpUnauthorizedErrorconsttoken=headers.authorization?.replace('Bearer ','');if(!token)thrownewMcpUnauthorizedError('Bearer');returnverifyToken(token);},},tools: [{name: 'search',description: 'Search documents',inputSchema: {type: 'object',properties: {query: {type: 'string'}}},asyncinvoke(principal,args){constresults=awaitsearch(principal,(argsasany).query);return{content: [{type: 'text',text: JSON.stringify(results)}]};},},],});// In your Lambda handler:constresponse=awaitserver.handle(parsedBody,event.headers);

Breaking Change: axios Removed

CDK Serverless no longer depends on axios. The library now uses the platform-native fetch API (stable in Node.js 18+; the Lambda functions created by this library use Runtime.NODEJS_LATEST, currently Node 22).

This removes one third-party runtime dependency from every Lambda bundle that imports from cdk-serverless/lambda and from every test workspace that imports from cdk-serverless/tests. It was motivated by repeated axios security advisories — landing this as a deliberate breaking change so the fix is permanent rather than chasing CVE upgrades.

Impact on Lambda handlers (cdk-serverless/lambda)

None. The internal JWKS / well-known-issuer fetches in the JWT authorizers were the only axios call sites in the Lambda runtime code, and their public behavior is unchanged. Errors now surface as Error (or a TimeoutError from AbortSignal.timeout) instead of AxiosError; if you catch errors inside the authorizer, the message text is similar but the type guard is different.

Impact on IntegTestUtil (cdk-serverless/tests)

IntegTestUtil.getClient() and IntegTestUtil.getAuthenticatedClient() previously returned an Axios instance. They now return a small HttpClient exported from cdk-serverless/tests. The migration is mechanical:

// Beforeconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.data is the parsed JSON, response.status is the HTTP status codeconstitems=response.data.items;// Afterconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.body is the raw string, response.json() parses it, response.ok// reports 2xx, response.status is the HTTP status codeconstitems=response.json<{items: Item[]}>().items;

The HttpClient exposes the methods that integration tests in this ecosystem actually use:

  • get(path, options?)
  • post(path, body?, options?)body may be a string or any JSON-serializable value; objects are stringified and Content-Type: application/json is added automatically if the caller did not set it.
  • put(path, body?, options?), patch(path, body?, options?), delete(path, options?)

Configuration accepted by HttpClient and by getClient(config):

  • baseURL — prepended to relative paths.
  • headers — default headers applied to every request; per-request headers override these on collision.

If you relied on axios-specific features (interceptors, defaults, transformRequest / transformResponse, automatic data parsing), implement the equivalent in your test code or wrap HttpClient. If your use case needs richer client features and we should expose them, please open an issue.

Contribute

How to contribute to CDK Serverless

Did you find a bug?

  • Ensure the bug was not already reported by searching on GitHub under Issues.

  • If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.

Did you write a patch that fixes a bug?

  • Open a new GitHub pull request with the patch.

  • Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.

Did you fix whitespace, format code, or make a purely cosmetic patch?

Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability will normally not be accepted.

Do you intend to add a new feature or change an existing one?

  • Suggest your change under Issues.

  • Do not open a pull request on GitHub until you have collected positive feedback about the change.

Do you want to contribute to the CDK Serverless documentation?

  • Just file a PR with your recommended changes

Authors

Brought to you by Taimos

About

AWS CDK Serverless Toolsuite

Resources

Stars

87 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

CDK Serverless

npm version

CDK Serverless is a powerful toolkit designed to simplify serverless application development using the AWS Cloud Development Kit (CDK). It offers project management features, higher-level (L3) constructs, and utility libraries to streamline the creation and management of serverless architectures. Additionally, it leverages utility libraries to write Lambda functions and do live updates to Lambda function code during development.

Video introduction: https://www.youtube.com/watch?v=xhNJ0cXG3O8

Features

  • Projen helper classes for easy project configuration
  • AWS CDK L3-constructs for RestApi, GraphQlApi, and more
  • Zero-config Lambda function and VTL template generation
  • Automatic DynamoDB single-table infrastructure setup
  • Built-in monitoring for Lambda functions and APIs
  • Full compatibility with CDK for custom implementations
  • Type-safe auto-completion for routes, resolvers, etc.
  • Support for Cognito authentication and authorization
  • Automated generation of CloudFormation outputs for testing

Quick Start

To begin a new project with CDK Serverless:

Create a new CDK TypeScript app using projen:

$ npx projen new awscdk-app-ts

Adding CDK Serverless is a two step process:

  1. Add 'cdk-serverless' as a dependency to your project
  2. Run npx projen to install it

Now you can use the project type ServerlessProject for your app.

Adding projen constructs

First you need to add the desired construct to your projen configuration: (e.g. RestApi)

import{RestApi}from'cdk-serverless/projen';newRestApi(project,{apiName: 'TestApi',// logical name of your APIdefinitionFile: 'testapi.yaml',// path to your OpenAPI spec});

Then run projen to generate construct files and models for the API.

Using the CDK serverless L3 constructs

In your stack you can then reference the generated L3s to create the API:

import{TestApiRestApi}from'./generated/rest.testapi-api.generated';constapi=newTestApiRestApi(this,'Api',{stageName: props.stageName,domainName: props.domainName,apiHostname: 'api',
singleTableDatastore,cors: true,additionalEnv: {DOMAIN_NAME: props.domainName,},});

This will also create Lambda functions for all operations defined in your spec and wire them accordingly.

Testing Utilities

CDK Serverless provides two powerful test utilities to help you write comprehensive tests for your serverless applications.

LambdaTestUtil

The LambdaTestUtil provides classes for testing both REST and GraphQL Lambda functions in isolation. It's perfect for unit testing your Lambda handlers.

REST API Testing

import{LambdaRestUnitTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaRestUnitTest(handler,{// Optional default headers for all requestsheaders: {'Content-Type': 'application/json',},// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GET requestconstresult=awaittest.call({path: '/items',method: 'GET',});// Test a POST request with bodyconstresult=awaittest.call({path: '/items',method: 'POST',body: JSON.stringify({name: 'test'}),});

GraphQL Testing

import{LambdaGraphQLTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaGraphQLTest(handler,{// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GraphQL queryconstresult=awaittest.call({fieldName: 'getItem',arguments: {id: '123'},});

IntegTestUtil

The IntegTestUtil provides a comprehensive set of tools for integration testing your deployed serverless applications. It handles authentication, data cleanup, and API testing.

import{IntegTestUtil}from'cdk-serverless/tests/integ-test-util';// Initialize with your stack outputsconsttest=newIntegTestUtil({region: 'us-east-1',apiOptions: {baseURL: 'https://api.example.com',},authOptions: {userPoolId: 'us-east-1_xxxxx',userPoolClientId: 'xxxxxxxx',identityPoolId: 'us-east-1:xxxxxxxx',},datastoreOptions: {tableName: 'MyTable',},});// Create and authenticate a test userawaittest.createUser('test@example.com',{'custom:attribute': 'value',},['admin']);// Get an authenticated API clientconstclient=awaittest.getAuthenticatedClient('test@example.com');// Make API callsconstresponse=awaitclient.get('/items');// Clean up test dataawaittest.cleanupItems();awaittest.removeUser('test@example.com');

MCP Auth

CDK Serverless includes built-in support for adding Model Context Protocol (MCP) OAuth authentication to your API. This enables MCP clients like Claude and ChatGPT to authenticate with your API using standard OAuth 2.0 flows.

When activated, the following endpoints are automatically added to your OpenAPI spec:

EndpointMethodRFCPurpose
/.well-known/oauth-protected-resourceGETRFC 9728Resource metadata discovery
/.well-known/oauth-authorization-serverGETRFC 8414Authorization server metadata
/oauth/authorizeGETAuthorize proxy (redirect to upstream)
/oauth/tokenPOSTToken proxy (forward to upstream)
/oauth/registerPOSTRFC 7591Dynamic client registration

All MCP auth endpoints are anonymous (no API authorizer applied).

With Cognito

MCP clients like Claude enforce that all OAuth endpoints (discovery, authorize, token, register) live on the same origin as the API itself. Cognito's hosted UI lives on a different domain (auth.example.com), so MCP clients cannot talk to it directly. Additionally:

  • Cognito Managed Login v2 requires the RFC 8707 resource parameter for custom scopes in authorize requests — MCP clients do not send this parameter.
  • MCP clients construct the token endpoint URL from the OAuth metadata issuer field rather than using the explicit token_endpoint — so the token exchange must be proxied through the API domain.
  • Dynamic Client Registration (RFC 7591) is not natively supported by Cognito.

The MCP auth proxy solves all three problems: it serves discovery metadata on the API domain, strips unsupported parameters before forwarding to Cognito, and implements a simplified registration endpoint that returns a pre-provisioned client ID.

If your API already uses CognitoAuthentication, add MCP auth with minimal config — a dedicated user pool client is created automatically:

constapi=newTestApiRestApi(this,'Api',{stageName: 'dev',domainName: 'example.com',apiHostname: 'api',authentication: cognitoAuth,cors: true,mcpAuth: {cognito: {auth: cognitoAuth,// your CognitoAuthentication constructauthDomain: 'auth.example.com',// Cognito custom/hosted domain (required)},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

The apiDomain is derived from the RestApi's own domain config (apiHostname + domainName), and stageName is reused — no duplication needed.

With any OAuth2 provider

For non-Cognito providers, use generic mode with explicit endpoint URLs:

constapi=newTestApiRestApi(this,'Api',{// ...mcpAuth: {generic: {authorizeEndpoint: 'https://auth.example.com/authorize',tokenEndpoint: 'https://auth.example.com/token',clientId: 'my-pre-provisioned-client-id',},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

Configuration options

OptionDefaultDescription
serverInfo(required){ name, version } returned in MCP initialize
allowedRedirectUrisClaude + ChatGPT callbacksAllowlist for dynamic registration
protocolVersions['2025-11-25', '2025-03-26', '2024-11-05']Supported MCP versions
scopes['openid', 'email', 'profile']Advertised OAuth scopes
stripParameters['resource']Params stripped from authorize/token proxying
lambdaOptionsLambda config for MCP auth handlers

MCP Server runtime

The cdk-serverless/mcp-auth module also exports a JSON-RPC server for implementing the MCP tool endpoint itself:

import{createMcpServer}from'cdk-serverless/mcp-auth';constserver=createMcpServer({serverInfo: {name: 'my-server',version: '1.0.0'},protocolVersions: ['2025-11-25'],resolver: {asyncresolve(headers){// Validate Bearer token, return principal or throw McpUnauthorizedErrorconsttoken=headers.authorization?.replace('Bearer ','');if(!token)thrownewMcpUnauthorizedError('Bearer');returnverifyToken(token);},},tools: [{name: 'search',description: 'Search documents',inputSchema: {type: 'object',properties: {query: {type: 'string'}}},asyncinvoke(principal,args){constresults=awaitsearch(principal,(argsasany).query);return{content: [{type: 'text',text: JSON.stringify(results)}]};},},],});// In your Lambda handler:constresponse=awaitserver.handle(parsedBody,event.headers);

Breaking Change: axios Removed

CDK Serverless no longer depends on axios. The library now uses the platform-native fetch API (stable in Node.js 18+; the Lambda functions created by this library use Runtime.NODEJS_LATEST, currently Node 22).

This removes one third-party runtime dependency from every Lambda bundle that imports from cdk-serverless/lambda and from every test workspace that imports from cdk-serverless/tests. It was motivated by repeated axios security advisories — landing this as a deliberate breaking change so the fix is permanent rather than chasing CVE upgrades.

Impact on Lambda handlers (cdk-serverless/lambda)

None. The internal JWKS / well-known-issuer fetches in the JWT authorizers were the only axios call sites in the Lambda runtime code, and their public behavior is unchanged. Errors now surface as Error (or a TimeoutError from AbortSignal.timeout) instead of AxiosError; if you catch errors inside the authorizer, the message text is similar but the type guard is different.

Impact on IntegTestUtil (cdk-serverless/tests)

IntegTestUtil.getClient() and IntegTestUtil.getAuthenticatedClient() previously returned an Axios instance. They now return a small HttpClient exported from cdk-serverless/tests. The migration is mechanical:

// Beforeconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.data is the parsed JSON, response.status is the HTTP status codeconstitems=response.data.items;// Afterconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.body is the raw string, response.json() parses it, response.ok// reports 2xx, response.status is the HTTP status codeconstitems=response.json<{items: Item[]}>().items;

The HttpClient exposes the methods that integration tests in this ecosystem actually use:

  • get(path, options?)
  • post(path, body?, options?)body may be a string or any JSON-serializable value; objects are stringified and Content-Type: application/json is added automatically if the caller did not set it.
  • put(path, body?, options?), patch(path, body?, options?), delete(path, options?)

Configuration accepted by HttpClient and by getClient(config):

  • baseURL — prepended to relative paths.
  • headers — default headers applied to every request; per-request headers override these on collision.

If you relied on axios-specific features (interceptors, defaults, transformRequest / transformResponse, automatic data parsing), implement the equivalent in your test code or wrap HttpClient. If your use case needs richer client features and we should expose them, please open an issue.

Contribute

How to contribute to CDK Serverless

Did you find a bug?

  • Ensure the bug was not already reported by searching on GitHub under Issues.

  • If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.

Did you write a patch that fixes a bug?

  • Open a new GitHub pull request with the patch.

  • Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.

Did you fix whitespace, format code, or make a purely cosmetic patch?

Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability will normally not be accepted.

Do you intend to add a new feature or change an existing one?

  • Suggest your change under Issues.

  • Do not open a pull request on GitHub until you have collected positive feedback about the change.

Do you want to contribute to the CDK Serverless documentation?

  • Just file a PR with your recommended changes

Authors

Brought to you by Taimos

About

AWS CDK Serverless Toolsuite

Resources

Stars

87 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

CDK Serverless

npm version

CDK Serverless is a powerful toolkit designed to simplify serverless application development using the AWS Cloud Development Kit (CDK). It offers project management features, higher-level (L3) constructs, and utility libraries to streamline the creation and management of serverless architectures. Additionally, it leverages utility libraries to write Lambda functions and do live updates to Lambda function code during development.

Video introduction: https://www.youtube.com/watch?v=xhNJ0cXG3O8

Features

  • Projen helper classes for easy project configuration
  • AWS CDK L3-constructs for RestApi, GraphQlApi, and more
  • Zero-config Lambda function and VTL template generation
  • Automatic DynamoDB single-table infrastructure setup
  • Built-in monitoring for Lambda functions and APIs
  • Full compatibility with CDK for custom implementations
  • Type-safe auto-completion for routes, resolvers, etc.
  • Support for Cognito authentication and authorization
  • Automated generation of CloudFormation outputs for testing

Quick Start

To begin a new project with CDK Serverless:

Create a new CDK TypeScript app using projen:

$ npx projen new awscdk-app-ts

Adding CDK Serverless is a two step process:

  1. Add 'cdk-serverless' as a dependency to your project
  2. Run npx projen to install it

Now you can use the project type ServerlessProject for your app.

Adding projen constructs

First you need to add the desired construct to your projen configuration: (e.g. RestApi)

import{RestApi}from'cdk-serverless/projen';newRestApi(project,{apiName: 'TestApi',// logical name of your APIdefinitionFile: 'testapi.yaml',// path to your OpenAPI spec});

Then run projen to generate construct files and models for the API.

Using the CDK serverless L3 constructs

In your stack you can then reference the generated L3s to create the API:

import{TestApiRestApi}from'./generated/rest.testapi-api.generated';constapi=newTestApiRestApi(this,'Api',{stageName: props.stageName,domainName: props.domainName,apiHostname: 'api',
singleTableDatastore,cors: true,additionalEnv: {DOMAIN_NAME: props.domainName,},});

This will also create Lambda functions for all operations defined in your spec and wire them accordingly.

Testing Utilities

CDK Serverless provides two powerful test utilities to help you write comprehensive tests for your serverless applications.

LambdaTestUtil

The LambdaTestUtil provides classes for testing both REST and GraphQL Lambda functions in isolation. It's perfect for unit testing your Lambda handlers.

REST API Testing

import{LambdaRestUnitTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaRestUnitTest(handler,{// Optional default headers for all requestsheaders: {'Content-Type': 'application/json',},// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GET requestconstresult=awaittest.call({path: '/items',method: 'GET',});// Test a POST request with bodyconstresult=awaittest.call({path: '/items',method: 'POST',body: JSON.stringify({name: 'test'}),});

GraphQL Testing

import{LambdaGraphQLTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaGraphQLTest(handler,{// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GraphQL queryconstresult=awaittest.call({fieldName: 'getItem',arguments: {id: '123'},});

IntegTestUtil

The IntegTestUtil provides a comprehensive set of tools for integration testing your deployed serverless applications. It handles authentication, data cleanup, and API testing.

import{IntegTestUtil}from'cdk-serverless/tests/integ-test-util';// Initialize with your stack outputsconsttest=newIntegTestUtil({region: 'us-east-1',apiOptions: {baseURL: 'https://api.example.com',},authOptions: {userPoolId: 'us-east-1_xxxxx',userPoolClientId: 'xxxxxxxx',identityPoolId: 'us-east-1:xxxxxxxx',},datastoreOptions: {tableName: 'MyTable',},});// Create and authenticate a test userawaittest.createUser('test@example.com',{'custom:attribute': 'value',},['admin']);// Get an authenticated API clientconstclient=awaittest.getAuthenticatedClient('test@example.com');// Make API callsconstresponse=awaitclient.get('/items');// Clean up test dataawaittest.cleanupItems();awaittest.removeUser('test@example.com');

MCP Auth

CDK Serverless includes built-in support for adding Model Context Protocol (MCP) OAuth authentication to your API. This enables MCP clients like Claude and ChatGPT to authenticate with your API using standard OAuth 2.0 flows.

When activated, the following endpoints are automatically added to your OpenAPI spec:

EndpointMethodRFCPurpose
/.well-known/oauth-protected-resourceGETRFC 9728Resource metadata discovery
/.well-known/oauth-authorization-serverGETRFC 8414Authorization server metadata
/oauth/authorizeGETAuthorize proxy (redirect to upstream)
/oauth/tokenPOSTToken proxy (forward to upstream)
/oauth/registerPOSTRFC 7591Dynamic client registration

All MCP auth endpoints are anonymous (no API authorizer applied).

With Cognito

MCP clients like Claude enforce that all OAuth endpoints (discovery, authorize, token, register) live on the same origin as the API itself. Cognito's hosted UI lives on a different domain (auth.example.com), so MCP clients cannot talk to it directly. Additionally:

  • Cognito Managed Login v2 requires the RFC 8707 resource parameter for custom scopes in authorize requests — MCP clients do not send this parameter.
  • MCP clients construct the token endpoint URL from the OAuth metadata issuer field rather than using the explicit token_endpoint — so the token exchange must be proxied through the API domain.
  • Dynamic Client Registration (RFC 7591) is not natively supported by Cognito.

The MCP auth proxy solves all three problems: it serves discovery metadata on the API domain, strips unsupported parameters before forwarding to Cognito, and implements a simplified registration endpoint that returns a pre-provisioned client ID.

If your API already uses CognitoAuthentication, add MCP auth with minimal config — a dedicated user pool client is created automatically:

constapi=newTestApiRestApi(this,'Api',{stageName: 'dev',domainName: 'example.com',apiHostname: 'api',authentication: cognitoAuth,cors: true,mcpAuth: {cognito: {auth: cognitoAuth,// your CognitoAuthentication constructauthDomain: 'auth.example.com',// Cognito custom/hosted domain (required)},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

The apiDomain is derived from the RestApi's own domain config (apiHostname + domainName), and stageName is reused — no duplication needed.

With any OAuth2 provider

For non-Cognito providers, use generic mode with explicit endpoint URLs:

constapi=newTestApiRestApi(this,'Api',{// ...mcpAuth: {generic: {authorizeEndpoint: 'https://auth.example.com/authorize',tokenEndpoint: 'https://auth.example.com/token',clientId: 'my-pre-provisioned-client-id',},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

Configuration options

OptionDefaultDescription
serverInfo(required){ name, version } returned in MCP initialize
allowedRedirectUrisClaude + ChatGPT callbacksAllowlist for dynamic registration
protocolVersions['2025-11-25', '2025-03-26', '2024-11-05']Supported MCP versions
scopes['openid', 'email', 'profile']Advertised OAuth scopes
stripParameters['resource']Params stripped from authorize/token proxying
lambdaOptionsLambda config for MCP auth handlers

MCP Server runtime

The cdk-serverless/mcp-auth module also exports a JSON-RPC server for implementing the MCP tool endpoint itself:

import{createMcpServer}from'cdk-serverless/mcp-auth';constserver=createMcpServer({serverInfo: {name: 'my-server',version: '1.0.0'},protocolVersions: ['2025-11-25'],resolver: {asyncresolve(headers){// Validate Bearer token, return principal or throw McpUnauthorizedErrorconsttoken=headers.authorization?.replace('Bearer ','');if(!token)thrownewMcpUnauthorizedError('Bearer');returnverifyToken(token);},},tools: [{name: 'search',description: 'Search documents',inputSchema: {type: 'object',properties: {query: {type: 'string'}}},asyncinvoke(principal,args){constresults=awaitsearch(principal,(argsasany).query);return{content: [{type: 'text',text: JSON.stringify(results)}]};},},],});// In your Lambda handler:constresponse=awaitserver.handle(parsedBody,event.headers);

Breaking Change: axios Removed

CDK Serverless no longer depends on axios. The library now uses the platform-native fetch API (stable in Node.js 18+; the Lambda functions created by this library use Runtime.NODEJS_LATEST, currently Node 22).

This removes one third-party runtime dependency from every Lambda bundle that imports from cdk-serverless/lambda and from every test workspace that imports from cdk-serverless/tests. It was motivated by repeated axios security advisories — landing this as a deliberate breaking change so the fix is permanent rather than chasing CVE upgrades.

Impact on Lambda handlers (cdk-serverless/lambda)

None. The internal JWKS / well-known-issuer fetches in the JWT authorizers were the only axios call sites in the Lambda runtime code, and their public behavior is unchanged. Errors now surface as Error (or a TimeoutError from AbortSignal.timeout) instead of AxiosError; if you catch errors inside the authorizer, the message text is similar but the type guard is different.

Impact on IntegTestUtil (cdk-serverless/tests)

IntegTestUtil.getClient() and IntegTestUtil.getAuthenticatedClient() previously returned an Axios instance. They now return a small HttpClient exported from cdk-serverless/tests. The migration is mechanical:

// Beforeconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.data is the parsed JSON, response.status is the HTTP status codeconstitems=response.data.items;// Afterconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.body is the raw string, response.json() parses it, response.ok// reports 2xx, response.status is the HTTP status codeconstitems=response.json<{items: Item[]}>().items;

The HttpClient exposes the methods that integration tests in this ecosystem actually use:

  • get(path, options?)
  • post(path, body?, options?)body may be a string or any JSON-serializable value; objects are stringified and Content-Type: application/json is added automatically if the caller did not set it.
  • put(path, body?, options?), patch(path, body?, options?), delete(path, options?)

Configuration accepted by HttpClient and by getClient(config):

  • baseURL — prepended to relative paths.
  • headers — default headers applied to every request; per-request headers override these on collision.

If you relied on axios-specific features (interceptors, defaults, transformRequest / transformResponse, automatic data parsing), implement the equivalent in your test code or wrap HttpClient. If your use case needs richer client features and we should expose them, please open an issue.

Contribute

How to contribute to CDK Serverless

Did you find a bug?

  • Ensure the bug was not already reported by searching on GitHub under Issues.

  • If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.

Did you write a patch that fixes a bug?

  • Open a new GitHub pull request with the patch.

  • Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.

Did you fix whitespace, format code, or make a purely cosmetic patch?

Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability will normally not be accepted.

Do you intend to add a new feature or change an existing one?

  • Suggest your change under Issues.

  • Do not open a pull request on GitHub until you have collected positive feedback about the change.

Do you want to contribute to the CDK Serverless documentation?

  • Just file a PR with your recommended changes

Authors

Brought to you by Taimos

About

AWS CDK Serverless Toolsuite

Resources

Stars

87 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

CDK Serverless

npm version

CDK Serverless is a powerful toolkit designed to simplify serverless application development using the AWS Cloud Development Kit (CDK). It offers project management features, higher-level (L3) constructs, and utility libraries to streamline the creation and management of serverless architectures. Additionally, it leverages utility libraries to write Lambda functions and do live updates to Lambda function code during development.

Video introduction: https://www.youtube.com/watch?v=xhNJ0cXG3O8

Features

  • Projen helper classes for easy project configuration
  • AWS CDK L3-constructs for RestApi, GraphQlApi, and more
  • Zero-config Lambda function and VTL template generation
  • Automatic DynamoDB single-table infrastructure setup
  • Built-in monitoring for Lambda functions and APIs
  • Full compatibility with CDK for custom implementations
  • Type-safe auto-completion for routes, resolvers, etc.
  • Support for Cognito authentication and authorization
  • Automated generation of CloudFormation outputs for testing

Quick Start

To begin a new project with CDK Serverless:

Create a new CDK TypeScript app using projen:

$ npx projen new awscdk-app-ts

Adding CDK Serverless is a two step process:

  1. Add 'cdk-serverless' as a dependency to your project
  2. Run npx projen to install it

Now you can use the project type ServerlessProject for your app.

Adding projen constructs

First you need to add the desired construct to your projen configuration: (e.g. RestApi)

import{RestApi}from'cdk-serverless/projen';newRestApi(project,{apiName: 'TestApi',// logical name of your APIdefinitionFile: 'testapi.yaml',// path to your OpenAPI spec});

Then run projen to generate construct files and models for the API.

Using the CDK serverless L3 constructs

In your stack you can then reference the generated L3s to create the API:

import{TestApiRestApi}from'./generated/rest.testapi-api.generated';constapi=newTestApiRestApi(this,'Api',{stageName: props.stageName,domainName: props.domainName,apiHostname: 'api',
singleTableDatastore,cors: true,additionalEnv: {DOMAIN_NAME: props.domainName,},});

This will also create Lambda functions for all operations defined in your spec and wire them accordingly.

Testing Utilities

CDK Serverless provides two powerful test utilities to help you write comprehensive tests for your serverless applications.

LambdaTestUtil

The LambdaTestUtil provides classes for testing both REST and GraphQL Lambda functions in isolation. It's perfect for unit testing your Lambda handlers.

REST API Testing

import{LambdaRestUnitTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaRestUnitTest(handler,{// Optional default headers for all requestsheaders: {'Content-Type': 'application/json',},// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GET requestconstresult=awaittest.call({path: '/items',method: 'GET',});// Test a POST request with bodyconstresult=awaittest.call({path: '/items',method: 'POST',body: JSON.stringify({name: 'test'}),});

GraphQL Testing

import{LambdaGraphQLTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaGraphQLTest(handler,{// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GraphQL queryconstresult=awaittest.call({fieldName: 'getItem',arguments: {id: '123'},});

IntegTestUtil

The IntegTestUtil provides a comprehensive set of tools for integration testing your deployed serverless applications. It handles authentication, data cleanup, and API testing.

import{IntegTestUtil}from'cdk-serverless/tests/integ-test-util';// Initialize with your stack outputsconsttest=newIntegTestUtil({region: 'us-east-1',apiOptions: {baseURL: 'https://api.example.com',},authOptions: {userPoolId: 'us-east-1_xxxxx',userPoolClientId: 'xxxxxxxx',identityPoolId: 'us-east-1:xxxxxxxx',},datastoreOptions: {tableName: 'MyTable',},});// Create and authenticate a test userawaittest.createUser('test@example.com',{'custom:attribute': 'value',},['admin']);// Get an authenticated API clientconstclient=awaittest.getAuthenticatedClient('test@example.com');// Make API callsconstresponse=awaitclient.get('/items');// Clean up test dataawaittest.cleanupItems();awaittest.removeUser('test@example.com');

MCP Auth

CDK Serverless includes built-in support for adding Model Context Protocol (MCP) OAuth authentication to your API. This enables MCP clients like Claude and ChatGPT to authenticate with your API using standard OAuth 2.0 flows.

When activated, the following endpoints are automatically added to your OpenAPI spec:

EndpointMethodRFCPurpose
/.well-known/oauth-protected-resourceGETRFC 9728Resource metadata discovery
/.well-known/oauth-authorization-serverGETRFC 8414Authorization server metadata
/oauth/authorizeGETAuthorize proxy (redirect to upstream)
/oauth/tokenPOSTToken proxy (forward to upstream)
/oauth/registerPOSTRFC 7591Dynamic client registration

All MCP auth endpoints are anonymous (no API authorizer applied).

With Cognito

MCP clients like Claude enforce that all OAuth endpoints (discovery, authorize, token, register) live on the same origin as the API itself. Cognito's hosted UI lives on a different domain (auth.example.com), so MCP clients cannot talk to it directly. Additionally:

  • Cognito Managed Login v2 requires the RFC 8707 resource parameter for custom scopes in authorize requests — MCP clients do not send this parameter.
  • MCP clients construct the token endpoint URL from the OAuth metadata issuer field rather than using the explicit token_endpoint — so the token exchange must be proxied through the API domain.
  • Dynamic Client Registration (RFC 7591) is not natively supported by Cognito.

The MCP auth proxy solves all three problems: it serves discovery metadata on the API domain, strips unsupported parameters before forwarding to Cognito, and implements a simplified registration endpoint that returns a pre-provisioned client ID.

If your API already uses CognitoAuthentication, add MCP auth with minimal config — a dedicated user pool client is created automatically:

constapi=newTestApiRestApi(this,'Api',{stageName: 'dev',domainName: 'example.com',apiHostname: 'api',authentication: cognitoAuth,cors: true,mcpAuth: {cognito: {auth: cognitoAuth,// your CognitoAuthentication constructauthDomain: 'auth.example.com',// Cognito custom/hosted domain (required)},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

The apiDomain is derived from the RestApi's own domain config (apiHostname + domainName), and stageName is reused — no duplication needed.

With any OAuth2 provider

For non-Cognito providers, use generic mode with explicit endpoint URLs:

constapi=newTestApiRestApi(this,'Api',{// ...mcpAuth: {generic: {authorizeEndpoint: 'https://auth.example.com/authorize',tokenEndpoint: 'https://auth.example.com/token',clientId: 'my-pre-provisioned-client-id',},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

Configuration options

OptionDefaultDescription
serverInfo(required){ name, version } returned in MCP initialize
allowedRedirectUrisClaude + ChatGPT callbacksAllowlist for dynamic registration
protocolVersions['2025-11-25', '2025-03-26', '2024-11-05']Supported MCP versions
scopes['openid', 'email', 'profile']Advertised OAuth scopes
stripParameters['resource']Params stripped from authorize/token proxying
lambdaOptionsLambda config for MCP auth handlers

MCP Server runtime

The cdk-serverless/mcp-auth module also exports a JSON-RPC server for implementing the MCP tool endpoint itself:

import{createMcpServer}from'cdk-serverless/mcp-auth';constserver=createMcpServer({serverInfo: {name: 'my-server',version: '1.0.0'},protocolVersions: ['2025-11-25'],resolver: {asyncresolve(headers){// Validate Bearer token, return principal or throw McpUnauthorizedErrorconsttoken=headers.authorization?.replace('Bearer ','');if(!token)thrownewMcpUnauthorizedError('Bearer');returnverifyToken(token);},},tools: [{name: 'search',description: 'Search documents',inputSchema: {type: 'object',properties: {query: {type: 'string'}}},asyncinvoke(principal,args){constresults=awaitsearch(principal,(argsasany).query);return{content: [{type: 'text',text: JSON.stringify(results)}]};},},],});// In your Lambda handler:constresponse=awaitserver.handle(parsedBody,event.headers);

Breaking Change: axios Removed

CDK Serverless no longer depends on axios. The library now uses the platform-native fetch API (stable in Node.js 18+; the Lambda functions created by this library use Runtime.NODEJS_LATEST, currently Node 22).

This removes one third-party runtime dependency from every Lambda bundle that imports from cdk-serverless/lambda and from every test workspace that imports from cdk-serverless/tests. It was motivated by repeated axios security advisories — landing this as a deliberate breaking change so the fix is permanent rather than chasing CVE upgrades.

Impact on Lambda handlers (cdk-serverless/lambda)

None. The internal JWKS / well-known-issuer fetches in the JWT authorizers were the only axios call sites in the Lambda runtime code, and their public behavior is unchanged. Errors now surface as Error (or a TimeoutError from AbortSignal.timeout) instead of AxiosError; if you catch errors inside the authorizer, the message text is similar but the type guard is different.

Impact on IntegTestUtil (cdk-serverless/tests)

IntegTestUtil.getClient() and IntegTestUtil.getAuthenticatedClient() previously returned an Axios instance. They now return a small HttpClient exported from cdk-serverless/tests. The migration is mechanical:

// Beforeconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.data is the parsed JSON, response.status is the HTTP status codeconstitems=response.data.items;// Afterconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.body is the raw string, response.json() parses it, response.ok// reports 2xx, response.status is the HTTP status codeconstitems=response.json<{items: Item[]}>().items;

The HttpClient exposes the methods that integration tests in this ecosystem actually use:

  • get(path, options?)
  • post(path, body?, options?)body may be a string or any JSON-serializable value; objects are stringified and Content-Type: application/json is added automatically if the caller did not set it.
  • put(path, body?, options?), patch(path, body?, options?), delete(path, options?)

Configuration accepted by HttpClient and by getClient(config):

  • baseURL — prepended to relative paths.
  • headers — default headers applied to every request; per-request headers override these on collision.

If you relied on axios-specific features (interceptors, defaults, transformRequest / transformResponse, automatic data parsing), implement the equivalent in your test code or wrap HttpClient. If your use case needs richer client features and we should expose them, please open an issue.

Contribute

How to contribute to CDK Serverless

Did you find a bug?

  • Ensure the bug was not already reported by searching on GitHub under Issues.

  • If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.

Did you write a patch that fixes a bug?

  • Open a new GitHub pull request with the patch.

  • Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.

Did you fix whitespace, format code, or make a purely cosmetic patch?

Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability will normally not be accepted.

Do you intend to add a new feature or change an existing one?

  • Suggest your change under Issues.

  • Do not open a pull request on GitHub until you have collected positive feedback about the change.

Do you want to contribute to the CDK Serverless documentation?

  • Just file a PR with your recommended changes

Authors

Brought to you by Taimos

About

AWS CDK Serverless Toolsuite

Resources

Stars

87 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

CDK Serverless

npm version

CDK Serverless is a powerful toolkit designed to simplify serverless application development using the AWS Cloud Development Kit (CDK). It offers project management features, higher-level (L3) constructs, and utility libraries to streamline the creation and management of serverless architectures. Additionally, it leverages utility libraries to write Lambda functions and do live updates to Lambda function code during development.

Video introduction: https://www.youtube.com/watch?v=xhNJ0cXG3O8

Features

  • Projen helper classes for easy project configuration
  • AWS CDK L3-constructs for RestApi, GraphQlApi, and more
  • Zero-config Lambda function and VTL template generation
  • Automatic DynamoDB single-table infrastructure setup
  • Built-in monitoring for Lambda functions and APIs
  • Full compatibility with CDK for custom implementations
  • Type-safe auto-completion for routes, resolvers, etc.
  • Support for Cognito authentication and authorization
  • Automated generation of CloudFormation outputs for testing

Quick Start

To begin a new project with CDK Serverless:

Create a new CDK TypeScript app using projen:

$ npx projen new awscdk-app-ts

Adding CDK Serverless is a two step process:

  1. Add 'cdk-serverless' as a dependency to your project
  2. Run npx projen to install it

Now you can use the project type ServerlessProject for your app.

Adding projen constructs

First you need to add the desired construct to your projen configuration: (e.g. RestApi)

import{RestApi}from'cdk-serverless/projen';newRestApi(project,{apiName: 'TestApi',// logical name of your APIdefinitionFile: 'testapi.yaml',// path to your OpenAPI spec});

Then run projen to generate construct files and models for the API.

Using the CDK serverless L3 constructs

In your stack you can then reference the generated L3s to create the API:

import{TestApiRestApi}from'./generated/rest.testapi-api.generated';constapi=newTestApiRestApi(this,'Api',{stageName: props.stageName,domainName: props.domainName,apiHostname: 'api',
singleTableDatastore,cors: true,additionalEnv: {DOMAIN_NAME: props.domainName,},});

This will also create Lambda functions for all operations defined in your spec and wire them accordingly.

Testing Utilities

CDK Serverless provides two powerful test utilities to help you write comprehensive tests for your serverless applications.

LambdaTestUtil

The LambdaTestUtil provides classes for testing both REST and GraphQL Lambda functions in isolation. It's perfect for unit testing your Lambda handlers.

REST API Testing

import{LambdaRestUnitTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaRestUnitTest(handler,{// Optional default headers for all requestsheaders: {'Content-Type': 'application/json',},// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GET requestconstresult=awaittest.call({path: '/items',method: 'GET',});// Test a POST request with bodyconstresult=awaittest.call({path: '/items',method: 'POST',body: JSON.stringify({name: 'test'}),});

GraphQL Testing

import{LambdaGraphQLTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaGraphQLTest(handler,{// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GraphQL queryconstresult=awaittest.call({fieldName: 'getItem',arguments: {id: '123'},});

IntegTestUtil

The IntegTestUtil provides a comprehensive set of tools for integration testing your deployed serverless applications. It handles authentication, data cleanup, and API testing.

import{IntegTestUtil}from'cdk-serverless/tests/integ-test-util';// Initialize with your stack outputsconsttest=newIntegTestUtil({region: 'us-east-1',apiOptions: {baseURL: 'https://api.example.com',},authOptions: {userPoolId: 'us-east-1_xxxxx',userPoolClientId: 'xxxxxxxx',identityPoolId: 'us-east-1:xxxxxxxx',},datastoreOptions: {tableName: 'MyTable',},});// Create and authenticate a test userawaittest.createUser('test@example.com',{'custom:attribute': 'value',},['admin']);// Get an authenticated API clientconstclient=awaittest.getAuthenticatedClient('test@example.com');// Make API callsconstresponse=awaitclient.get('/items');// Clean up test dataawaittest.cleanupItems();awaittest.removeUser('test@example.com');

MCP Auth

CDK Serverless includes built-in support for adding Model Context Protocol (MCP) OAuth authentication to your API. This enables MCP clients like Claude and ChatGPT to authenticate with your API using standard OAuth 2.0 flows.

When activated, the following endpoints are automatically added to your OpenAPI spec:

EndpointMethodRFCPurpose
/.well-known/oauth-protected-resourceGETRFC 9728Resource metadata discovery
/.well-known/oauth-authorization-serverGETRFC 8414Authorization server metadata
/oauth/authorizeGETAuthorize proxy (redirect to upstream)
/oauth/tokenPOSTToken proxy (forward to upstream)
/oauth/registerPOSTRFC 7591Dynamic client registration

All MCP auth endpoints are anonymous (no API authorizer applied).

With Cognito

MCP clients like Claude enforce that all OAuth endpoints (discovery, authorize, token, register) live on the same origin as the API itself. Cognito's hosted UI lives on a different domain (auth.example.com), so MCP clients cannot talk to it directly. Additionally:

  • Cognito Managed Login v2 requires the RFC 8707 resource parameter for custom scopes in authorize requests — MCP clients do not send this parameter.
  • MCP clients construct the token endpoint URL from the OAuth metadata issuer field rather than using the explicit token_endpoint — so the token exchange must be proxied through the API domain.
  • Dynamic Client Registration (RFC 7591) is not natively supported by Cognito.

The MCP auth proxy solves all three problems: it serves discovery metadata on the API domain, strips unsupported parameters before forwarding to Cognito, and implements a simplified registration endpoint that returns a pre-provisioned client ID.

If your API already uses CognitoAuthentication, add MCP auth with minimal config — a dedicated user pool client is created automatically:

constapi=newTestApiRestApi(this,'Api',{stageName: 'dev',domainName: 'example.com',apiHostname: 'api',authentication: cognitoAuth,cors: true,mcpAuth: {cognito: {auth: cognitoAuth,// your CognitoAuthentication constructauthDomain: 'auth.example.com',// Cognito custom/hosted domain (required)},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

The apiDomain is derived from the RestApi's own domain config (apiHostname + domainName), and stageName is reused — no duplication needed.

With any OAuth2 provider

For non-Cognito providers, use generic mode with explicit endpoint URLs:

constapi=newTestApiRestApi(this,'Api',{// ...mcpAuth: {generic: {authorizeEndpoint: 'https://auth.example.com/authorize',tokenEndpoint: 'https://auth.example.com/token',clientId: 'my-pre-provisioned-client-id',},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

Configuration options

OptionDefaultDescription
serverInfo(required){ name, version } returned in MCP initialize
allowedRedirectUrisClaude + ChatGPT callbacksAllowlist for dynamic registration
protocolVersions['2025-11-25', '2025-03-26', '2024-11-05']Supported MCP versions
scopes['openid', 'email', 'profile']Advertised OAuth scopes
stripParameters['resource']Params stripped from authorize/token proxying
lambdaOptionsLambda config for MCP auth handlers

MCP Server runtime

The cdk-serverless/mcp-auth module also exports a JSON-RPC server for implementing the MCP tool endpoint itself:

import{createMcpServer}from'cdk-serverless/mcp-auth';constserver=createMcpServer({serverInfo: {name: 'my-server',version: '1.0.0'},protocolVersions: ['2025-11-25'],resolver: {asyncresolve(headers){// Validate Bearer token, return principal or throw McpUnauthorizedErrorconsttoken=headers.authorization?.replace('Bearer ','');if(!token)thrownewMcpUnauthorizedError('Bearer');returnverifyToken(token);},},tools: [{name: 'search',description: 'Search documents',inputSchema: {type: 'object',properties: {query: {type: 'string'}}},asyncinvoke(principal,args){constresults=awaitsearch(principal,(argsasany).query);return{content: [{type: 'text',text: JSON.stringify(results)}]};},},],});// In your Lambda handler:constresponse=awaitserver.handle(parsedBody,event.headers);

Breaking Change: axios Removed

CDK Serverless no longer depends on axios. The library now uses the platform-native fetch API (stable in Node.js 18+; the Lambda functions created by this library use Runtime.NODEJS_LATEST, currently Node 22).

This removes one third-party runtime dependency from every Lambda bundle that imports from cdk-serverless/lambda and from every test workspace that imports from cdk-serverless/tests. It was motivated by repeated axios security advisories — landing this as a deliberate breaking change so the fix is permanent rather than chasing CVE upgrades.

Impact on Lambda handlers (cdk-serverless/lambda)

None. The internal JWKS / well-known-issuer fetches in the JWT authorizers were the only axios call sites in the Lambda runtime code, and their public behavior is unchanged. Errors now surface as Error (or a TimeoutError from AbortSignal.timeout) instead of AxiosError; if you catch errors inside the authorizer, the message text is similar but the type guard is different.

Impact on IntegTestUtil (cdk-serverless/tests)

IntegTestUtil.getClient() and IntegTestUtil.getAuthenticatedClient() previously returned an Axios instance. They now return a small HttpClient exported from cdk-serverless/tests. The migration is mechanical:

// Beforeconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.data is the parsed JSON, response.status is the HTTP status codeconstitems=response.data.items;// Afterconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.body is the raw string, response.json() parses it, response.ok// reports 2xx, response.status is the HTTP status codeconstitems=response.json<{items: Item[]}>().items;

The HttpClient exposes the methods that integration tests in this ecosystem actually use:

  • get(path, options?)
  • post(path, body?, options?)body may be a string or any JSON-serializable value; objects are stringified and Content-Type: application/json is added automatically if the caller did not set it.
  • put(path, body?, options?), patch(path, body?, options?), delete(path, options?)

Configuration accepted by HttpClient and by getClient(config):

  • baseURL — prepended to relative paths.
  • headers — default headers applied to every request; per-request headers override these on collision.

If you relied on axios-specific features (interceptors, defaults, transformRequest / transformResponse, automatic data parsing), implement the equivalent in your test code or wrap HttpClient. If your use case needs richer client features and we should expose them, please open an issue.

Contribute

How to contribute to CDK Serverless

Did you find a bug?

  • Ensure the bug was not already reported by searching on GitHub under Issues.

  • If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.

Did you write a patch that fixes a bug?

  • Open a new GitHub pull request with the patch.

  • Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.

Did you fix whitespace, format code, or make a purely cosmetic patch?

Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability will normally not be accepted.

Do you intend to add a new feature or change an existing one?

  • Suggest your change under Issues.

  • Do not open a pull request on GitHub until you have collected positive feedback about the change.

Do you want to contribute to the CDK Serverless documentation?

  • Just file a PR with your recommended changes

Authors

Brought to you by Taimos

About

AWS CDK Serverless Toolsuite

Resources

Stars

87 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

CDK Serverless

npm version

CDK Serverless is a powerful toolkit designed to simplify serverless application development using the AWS Cloud Development Kit (CDK). It offers project management features, higher-level (L3) constructs, and utility libraries to streamline the creation and management of serverless architectures. Additionally, it leverages utility libraries to write Lambda functions and do live updates to Lambda function code during development.

Video introduction: https://www.youtube.com/watch?v=xhNJ0cXG3O8

Features

  • Projen helper classes for easy project configuration
  • AWS CDK L3-constructs for RestApi, GraphQlApi, and more
  • Zero-config Lambda function and VTL template generation
  • Automatic DynamoDB single-table infrastructure setup
  • Built-in monitoring for Lambda functions and APIs
  • Full compatibility with CDK for custom implementations
  • Type-safe auto-completion for routes, resolvers, etc.
  • Support for Cognito authentication and authorization
  • Automated generation of CloudFormation outputs for testing

Quick Start

To begin a new project with CDK Serverless:

Create a new CDK TypeScript app using projen:

$ npx projen new awscdk-app-ts

Adding CDK Serverless is a two step process:

  1. Add 'cdk-serverless' as a dependency to your project
  2. Run npx projen to install it

Now you can use the project type ServerlessProject for your app.

Adding projen constructs

First you need to add the desired construct to your projen configuration: (e.g. RestApi)

import{RestApi}from'cdk-serverless/projen';newRestApi(project,{apiName: 'TestApi',// logical name of your APIdefinitionFile: 'testapi.yaml',// path to your OpenAPI spec});

Then run projen to generate construct files and models for the API.

Using the CDK serverless L3 constructs

In your stack you can then reference the generated L3s to create the API:

import{TestApiRestApi}from'./generated/rest.testapi-api.generated';constapi=newTestApiRestApi(this,'Api',{stageName: props.stageName,domainName: props.domainName,apiHostname: 'api',
singleTableDatastore,cors: true,additionalEnv: {DOMAIN_NAME: props.domainName,},});

This will also create Lambda functions for all operations defined in your spec and wire them accordingly.

Testing Utilities

CDK Serverless provides two powerful test utilities to help you write comprehensive tests for your serverless applications.

LambdaTestUtil

The LambdaTestUtil provides classes for testing both REST and GraphQL Lambda functions in isolation. It's perfect for unit testing your Lambda handlers.

REST API Testing

import{LambdaRestUnitTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaRestUnitTest(handler,{// Optional default headers for all requestsheaders: {'Content-Type': 'application/json',},// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GET requestconstresult=awaittest.call({path: '/items',method: 'GET',});// Test a POST request with bodyconstresult=awaittest.call({path: '/items',method: 'POST',body: JSON.stringify({name: 'test'}),});

GraphQL Testing

import{LambdaGraphQLTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaGraphQLTest(handler,{// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GraphQL queryconstresult=awaittest.call({fieldName: 'getItem',arguments: {id: '123'},});

IntegTestUtil

The IntegTestUtil provides a comprehensive set of tools for integration testing your deployed serverless applications. It handles authentication, data cleanup, and API testing.

import{IntegTestUtil}from'cdk-serverless/tests/integ-test-util';// Initialize with your stack outputsconsttest=newIntegTestUtil({region: 'us-east-1',apiOptions: {baseURL: 'https://api.example.com',},authOptions: {userPoolId: 'us-east-1_xxxxx',userPoolClientId: 'xxxxxxxx',identityPoolId: 'us-east-1:xxxxxxxx',},datastoreOptions: {tableName: 'MyTable',},});// Create and authenticate a test userawaittest.createUser('test@example.com',{'custom:attribute': 'value',},['admin']);// Get an authenticated API clientconstclient=awaittest.getAuthenticatedClient('test@example.com');// Make API callsconstresponse=awaitclient.get('/items');// Clean up test dataawaittest.cleanupItems();awaittest.removeUser('test@example.com');

MCP Auth

CDK Serverless includes built-in support for adding Model Context Protocol (MCP) OAuth authentication to your API. This enables MCP clients like Claude and ChatGPT to authenticate with your API using standard OAuth 2.0 flows.

When activated, the following endpoints are automatically added to your OpenAPI spec:

EndpointMethodRFCPurpose
/.well-known/oauth-protected-resourceGETRFC 9728Resource metadata discovery
/.well-known/oauth-authorization-serverGETRFC 8414Authorization server metadata
/oauth/authorizeGETAuthorize proxy (redirect to upstream)
/oauth/tokenPOSTToken proxy (forward to upstream)
/oauth/registerPOSTRFC 7591Dynamic client registration

All MCP auth endpoints are anonymous (no API authorizer applied).

With Cognito

MCP clients like Claude enforce that all OAuth endpoints (discovery, authorize, token, register) live on the same origin as the API itself. Cognito's hosted UI lives on a different domain (auth.example.com), so MCP clients cannot talk to it directly. Additionally:

  • Cognito Managed Login v2 requires the RFC 8707 resource parameter for custom scopes in authorize requests — MCP clients do not send this parameter.
  • MCP clients construct the token endpoint URL from the OAuth metadata issuer field rather than using the explicit token_endpoint — so the token exchange must be proxied through the API domain.
  • Dynamic Client Registration (RFC 7591) is not natively supported by Cognito.

The MCP auth proxy solves all three problems: it serves discovery metadata on the API domain, strips unsupported parameters before forwarding to Cognito, and implements a simplified registration endpoint that returns a pre-provisioned client ID.

If your API already uses CognitoAuthentication, add MCP auth with minimal config — a dedicated user pool client is created automatically:

constapi=newTestApiRestApi(this,'Api',{stageName: 'dev',domainName: 'example.com',apiHostname: 'api',authentication: cognitoAuth,cors: true,mcpAuth: {cognito: {auth: cognitoAuth,// your CognitoAuthentication constructauthDomain: 'auth.example.com',// Cognito custom/hosted domain (required)},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

The apiDomain is derived from the RestApi's own domain config (apiHostname + domainName), and stageName is reused — no duplication needed.

With any OAuth2 provider

For non-Cognito providers, use generic mode with explicit endpoint URLs:

constapi=newTestApiRestApi(this,'Api',{// ...mcpAuth: {generic: {authorizeEndpoint: 'https://auth.example.com/authorize',tokenEndpoint: 'https://auth.example.com/token',clientId: 'my-pre-provisioned-client-id',},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

Configuration options

OptionDefaultDescription
serverInfo(required){ name, version } returned in MCP initialize
allowedRedirectUrisClaude + ChatGPT callbacksAllowlist for dynamic registration
protocolVersions['2025-11-25', '2025-03-26', '2024-11-05']Supported MCP versions
scopes['openid', 'email', 'profile']Advertised OAuth scopes
stripParameters['resource']Params stripped from authorize/token proxying
lambdaOptionsLambda config for MCP auth handlers

MCP Server runtime

The cdk-serverless/mcp-auth module also exports a JSON-RPC server for implementing the MCP tool endpoint itself:

import{createMcpServer}from'cdk-serverless/mcp-auth';constserver=createMcpServer({serverInfo: {name: 'my-server',version: '1.0.0'},protocolVersions: ['2025-11-25'],resolver: {asyncresolve(headers){// Validate Bearer token, return principal or throw McpUnauthorizedErrorconsttoken=headers.authorization?.replace('Bearer ','');if(!token)thrownewMcpUnauthorizedError('Bearer');returnverifyToken(token);},},tools: [{name: 'search',description: 'Search documents',inputSchema: {type: 'object',properties: {query: {type: 'string'}}},asyncinvoke(principal,args){constresults=awaitsearch(principal,(argsasany).query);return{content: [{type: 'text',text: JSON.stringify(results)}]};},},],});// In your Lambda handler:constresponse=awaitserver.handle(parsedBody,event.headers);

Breaking Change: axios Removed

CDK Serverless no longer depends on axios. The library now uses the platform-native fetch API (stable in Node.js 18+; the Lambda functions created by this library use Runtime.NODEJS_LATEST, currently Node 22).

This removes one third-party runtime dependency from every Lambda bundle that imports from cdk-serverless/lambda and from every test workspace that imports from cdk-serverless/tests. It was motivated by repeated axios security advisories — landing this as a deliberate breaking change so the fix is permanent rather than chasing CVE upgrades.

Impact on Lambda handlers (cdk-serverless/lambda)

None. The internal JWKS / well-known-issuer fetches in the JWT authorizers were the only axios call sites in the Lambda runtime code, and their public behavior is unchanged. Errors now surface as Error (or a TimeoutError from AbortSignal.timeout) instead of AxiosError; if you catch errors inside the authorizer, the message text is similar but the type guard is different.

Impact on IntegTestUtil (cdk-serverless/tests)

IntegTestUtil.getClient() and IntegTestUtil.getAuthenticatedClient() previously returned an Axios instance. They now return a small HttpClient exported from cdk-serverless/tests. The migration is mechanical:

// Beforeconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.data is the parsed JSON, response.status is the HTTP status codeconstitems=response.data.items;// Afterconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.body is the raw string, response.json() parses it, response.ok// reports 2xx, response.status is the HTTP status codeconstitems=response.json<{items: Item[]}>().items;

The HttpClient exposes the methods that integration tests in this ecosystem actually use:

  • get(path, options?)
  • post(path, body?, options?)body may be a string or any JSON-serializable value; objects are stringified and Content-Type: application/json is added automatically if the caller did not set it.
  • put(path, body?, options?), patch(path, body?, options?), delete(path, options?)

Configuration accepted by HttpClient and by getClient(config):

  • baseURL — prepended to relative paths.
  • headers — default headers applied to every request; per-request headers override these on collision.

If you relied on axios-specific features (interceptors, defaults, transformRequest / transformResponse, automatic data parsing), implement the equivalent in your test code or wrap HttpClient. If your use case needs richer client features and we should expose them, please open an issue.

Contribute

How to contribute to CDK Serverless

Did you find a bug?

  • Ensure the bug was not already reported by searching on GitHub under Issues.

  • If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.

Did you write a patch that fixes a bug?

  • Open a new GitHub pull request with the patch.

  • Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.

Did you fix whitespace, format code, or make a purely cosmetic patch?

Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability will normally not be accepted.

Do you intend to add a new feature or change an existing one?

  • Suggest your change under Issues.

  • Do not open a pull request on GitHub until you have collected positive feedback about the change.

Do you want to contribute to the CDK Serverless documentation?

  • Just file a PR with your recommended changes

Authors

Brought to you by Taimos

About

AWS CDK Serverless Toolsuite

Resources

Stars

87 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

CDK Serverless

npm version

CDK Serverless is a powerful toolkit designed to simplify serverless application development using the AWS Cloud Development Kit (CDK). It offers project management features, higher-level (L3) constructs, and utility libraries to streamline the creation and management of serverless architectures. Additionally, it leverages utility libraries to write Lambda functions and do live updates to Lambda function code during development.

Video introduction: https://www.youtube.com/watch?v=xhNJ0cXG3O8

Features

  • Projen helper classes for easy project configuration
  • AWS CDK L3-constructs for RestApi, GraphQlApi, and more
  • Zero-config Lambda function and VTL template generation
  • Automatic DynamoDB single-table infrastructure setup
  • Built-in monitoring for Lambda functions and APIs
  • Full compatibility with CDK for custom implementations
  • Type-safe auto-completion for routes, resolvers, etc.
  • Support for Cognito authentication and authorization
  • Automated generation of CloudFormation outputs for testing

Quick Start

To begin a new project with CDK Serverless:

Create a new CDK TypeScript app using projen:

$ npx projen new awscdk-app-ts

Adding CDK Serverless is a two step process:

  1. Add 'cdk-serverless' as a dependency to your project
  2. Run npx projen to install it

Now you can use the project type ServerlessProject for your app.

Adding projen constructs

First you need to add the desired construct to your projen configuration: (e.g. RestApi)

import{RestApi}from'cdk-serverless/projen';newRestApi(project,{apiName: 'TestApi',// logical name of your APIdefinitionFile: 'testapi.yaml',// path to your OpenAPI spec});

Then run projen to generate construct files and models for the API.

Using the CDK serverless L3 constructs

In your stack you can then reference the generated L3s to create the API:

import{TestApiRestApi}from'./generated/rest.testapi-api.generated';constapi=newTestApiRestApi(this,'Api',{stageName: props.stageName,domainName: props.domainName,apiHostname: 'api',
singleTableDatastore,cors: true,additionalEnv: {DOMAIN_NAME: props.domainName,},});

This will also create Lambda functions for all operations defined in your spec and wire them accordingly.

Testing Utilities

CDK Serverless provides two powerful test utilities to help you write comprehensive tests for your serverless applications.

LambdaTestUtil

The LambdaTestUtil provides classes for testing both REST and GraphQL Lambda functions in isolation. It's perfect for unit testing your Lambda handlers.

REST API Testing

import{LambdaRestUnitTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaRestUnitTest(handler,{// Optional default headers for all requestsheaders: {'Content-Type': 'application/json',},// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GET requestconstresult=awaittest.call({path: '/items',method: 'GET',});// Test a POST request with bodyconstresult=awaittest.call({path: '/items',method: 'POST',body: JSON.stringify({name: 'test'}),});

GraphQL Testing

import{LambdaGraphQLTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaGraphQLTest(handler,{// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GraphQL queryconstresult=awaittest.call({fieldName: 'getItem',arguments: {id: '123'},});

IntegTestUtil

The IntegTestUtil provides a comprehensive set of tools for integration testing your deployed serverless applications. It handles authentication, data cleanup, and API testing.

import{IntegTestUtil}from'cdk-serverless/tests/integ-test-util';// Initialize with your stack outputsconsttest=newIntegTestUtil({region: 'us-east-1',apiOptions: {baseURL: 'https://api.example.com',},authOptions: {userPoolId: 'us-east-1_xxxxx',userPoolClientId: 'xxxxxxxx',identityPoolId: 'us-east-1:xxxxxxxx',},datastoreOptions: {tableName: 'MyTable',},});// Create and authenticate a test userawaittest.createUser('test@example.com',{'custom:attribute': 'value',},['admin']);// Get an authenticated API clientconstclient=awaittest.getAuthenticatedClient('test@example.com');// Make API callsconstresponse=awaitclient.get('/items');// Clean up test dataawaittest.cleanupItems();awaittest.removeUser('test@example.com');

MCP Auth

CDK Serverless includes built-in support for adding Model Context Protocol (MCP) OAuth authentication to your API. This enables MCP clients like Claude and ChatGPT to authenticate with your API using standard OAuth 2.0 flows.

When activated, the following endpoints are automatically added to your OpenAPI spec:

EndpointMethodRFCPurpose
/.well-known/oauth-protected-resourceGETRFC 9728Resource metadata discovery
/.well-known/oauth-authorization-serverGETRFC 8414Authorization server metadata
/oauth/authorizeGETAuthorize proxy (redirect to upstream)
/oauth/tokenPOSTToken proxy (forward to upstream)
/oauth/registerPOSTRFC 7591Dynamic client registration

All MCP auth endpoints are anonymous (no API authorizer applied).

With Cognito

MCP clients like Claude enforce that all OAuth endpoints (discovery, authorize, token, register) live on the same origin as the API itself. Cognito's hosted UI lives on a different domain (auth.example.com), so MCP clients cannot talk to it directly. Additionally:

  • Cognito Managed Login v2 requires the RFC 8707 resource parameter for custom scopes in authorize requests — MCP clients do not send this parameter.
  • MCP clients construct the token endpoint URL from the OAuth metadata issuer field rather than using the explicit token_endpoint — so the token exchange must be proxied through the API domain.
  • Dynamic Client Registration (RFC 7591) is not natively supported by Cognito.

The MCP auth proxy solves all three problems: it serves discovery metadata on the API domain, strips unsupported parameters before forwarding to Cognito, and implements a simplified registration endpoint that returns a pre-provisioned client ID.

If your API already uses CognitoAuthentication, add MCP auth with minimal config — a dedicated user pool client is created automatically:

constapi=newTestApiRestApi(this,'Api',{stageName: 'dev',domainName: 'example.com',apiHostname: 'api',authentication: cognitoAuth,cors: true,mcpAuth: {cognito: {auth: cognitoAuth,// your CognitoAuthentication constructauthDomain: 'auth.example.com',// Cognito custom/hosted domain (required)},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

The apiDomain is derived from the RestApi's own domain config (apiHostname + domainName), and stageName is reused — no duplication needed.

With any OAuth2 provider

For non-Cognito providers, use generic mode with explicit endpoint URLs:

constapi=newTestApiRestApi(this,'Api',{// ...mcpAuth: {generic: {authorizeEndpoint: 'https://auth.example.com/authorize',tokenEndpoint: 'https://auth.example.com/token',clientId: 'my-pre-provisioned-client-id',},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

Configuration options

OptionDefaultDescription
serverInfo(required){ name, version } returned in MCP initialize
allowedRedirectUrisClaude + ChatGPT callbacksAllowlist for dynamic registration
protocolVersions['2025-11-25', '2025-03-26', '2024-11-05']Supported MCP versions
scopes['openid', 'email', 'profile']Advertised OAuth scopes
stripParameters['resource']Params stripped from authorize/token proxying
lambdaOptionsLambda config for MCP auth handlers

MCP Server runtime

The cdk-serverless/mcp-auth module also exports a JSON-RPC server for implementing the MCP tool endpoint itself:

import{createMcpServer}from'cdk-serverless/mcp-auth';constserver=createMcpServer({serverInfo: {name: 'my-server',version: '1.0.0'},protocolVersions: ['2025-11-25'],resolver: {asyncresolve(headers){// Validate Bearer token, return principal or throw McpUnauthorizedErrorconsttoken=headers.authorization?.replace('Bearer ','');if(!token)thrownewMcpUnauthorizedError('Bearer');returnverifyToken(token);},},tools: [{name: 'search',description: 'Search documents',inputSchema: {type: 'object',properties: {query: {type: 'string'}}},asyncinvoke(principal,args){constresults=awaitsearch(principal,(argsasany).query);return{content: [{type: 'text',text: JSON.stringify(results)}]};},},],});// In your Lambda handler:constresponse=awaitserver.handle(parsedBody,event.headers);

Breaking Change: axios Removed

CDK Serverless no longer depends on axios. The library now uses the platform-native fetch API (stable in Node.js 18+; the Lambda functions created by this library use Runtime.NODEJS_LATEST, currently Node 22).

This removes one third-party runtime dependency from every Lambda bundle that imports from cdk-serverless/lambda and from every test workspace that imports from cdk-serverless/tests. It was motivated by repeated axios security advisories — landing this as a deliberate breaking change so the fix is permanent rather than chasing CVE upgrades.

Impact on Lambda handlers (cdk-serverless/lambda)

None. The internal JWKS / well-known-issuer fetches in the JWT authorizers were the only axios call sites in the Lambda runtime code, and their public behavior is unchanged. Errors now surface as Error (or a TimeoutError from AbortSignal.timeout) instead of AxiosError; if you catch errors inside the authorizer, the message text is similar but the type guard is different.

Impact on IntegTestUtil (cdk-serverless/tests)

IntegTestUtil.getClient() and IntegTestUtil.getAuthenticatedClient() previously returned an Axios instance. They now return a small HttpClient exported from cdk-serverless/tests. The migration is mechanical:

// Beforeconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.data is the parsed JSON, response.status is the HTTP status codeconstitems=response.data.items;// Afterconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.body is the raw string, response.json() parses it, response.ok// reports 2xx, response.status is the HTTP status codeconstitems=response.json<{items: Item[]}>().items;

The HttpClient exposes the methods that integration tests in this ecosystem actually use:

  • get(path, options?)
  • post(path, body?, options?)body may be a string or any JSON-serializable value; objects are stringified and Content-Type: application/json is added automatically if the caller did not set it.
  • put(path, body?, options?), patch(path, body?, options?), delete(path, options?)

Configuration accepted by HttpClient and by getClient(config):

  • baseURL — prepended to relative paths.
  • headers — default headers applied to every request; per-request headers override these on collision.

If you relied on axios-specific features (interceptors, defaults, transformRequest / transformResponse, automatic data parsing), implement the equivalent in your test code or wrap HttpClient. If your use case needs richer client features and we should expose them, please open an issue.

Contribute

How to contribute to CDK Serverless

Did you find a bug?

  • Ensure the bug was not already reported by searching on GitHub under Issues.

  • If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.

Did you write a patch that fixes a bug?

  • Open a new GitHub pull request with the patch.

  • Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.

Did you fix whitespace, format code, or make a purely cosmetic patch?

Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability will normally not be accepted.

Do you intend to add a new feature or change an existing one?

  • Suggest your change under Issues.

  • Do not open a pull request on GitHub until you have collected positive feedback about the change.

Do you want to contribute to the CDK Serverless documentation?

  • Just file a PR with your recommended changes

Authors

Brought to you by Taimos

About

AWS CDK Serverless Toolsuite

Resources

Stars

87 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

CDK Serverless

npm version

CDK Serverless is a powerful toolkit designed to simplify serverless application development using the AWS Cloud Development Kit (CDK). It offers project management features, higher-level (L3) constructs, and utility libraries to streamline the creation and management of serverless architectures. Additionally, it leverages utility libraries to write Lambda functions and do live updates to Lambda function code during development.

Video introduction: https://www.youtube.com/watch?v=xhNJ0cXG3O8

Features

  • Projen helper classes for easy project configuration
  • AWS CDK L3-constructs for RestApi, GraphQlApi, and more
  • Zero-config Lambda function and VTL template generation
  • Automatic DynamoDB single-table infrastructure setup
  • Built-in monitoring for Lambda functions and APIs
  • Full compatibility with CDK for custom implementations
  • Type-safe auto-completion for routes, resolvers, etc.
  • Support for Cognito authentication and authorization
  • Automated generation of CloudFormation outputs for testing

Quick Start

To begin a new project with CDK Serverless:

Create a new CDK TypeScript app using projen:

$ npx projen new awscdk-app-ts

Adding CDK Serverless is a two step process:

  1. Add 'cdk-serverless' as a dependency to your project
  2. Run npx projen to install it

Now you can use the project type ServerlessProject for your app.

Adding projen constructs

First you need to add the desired construct to your projen configuration: (e.g. RestApi)

import{RestApi}from'cdk-serverless/projen';newRestApi(project,{apiName: 'TestApi',// logical name of your APIdefinitionFile: 'testapi.yaml',// path to your OpenAPI spec});

Then run projen to generate construct files and models for the API.

Using the CDK serverless L3 constructs

In your stack you can then reference the generated L3s to create the API:

import{TestApiRestApi}from'./generated/rest.testapi-api.generated';constapi=newTestApiRestApi(this,'Api',{stageName: props.stageName,domainName: props.domainName,apiHostname: 'api',
singleTableDatastore,cors: true,additionalEnv: {DOMAIN_NAME: props.domainName,},});

This will also create Lambda functions for all operations defined in your spec and wire them accordingly.

Testing Utilities

CDK Serverless provides two powerful test utilities to help you write comprehensive tests for your serverless applications.

LambdaTestUtil

The LambdaTestUtil provides classes for testing both REST and GraphQL Lambda functions in isolation. It's perfect for unit testing your Lambda handlers.

REST API Testing

import{LambdaRestUnitTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaRestUnitTest(handler,{// Optional default headers for all requestsheaders: {'Content-Type': 'application/json',},// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GET requestconstresult=awaittest.call({path: '/items',method: 'GET',});// Test a POST request with bodyconstresult=awaittest.call({path: '/items',method: 'POST',body: JSON.stringify({name: 'test'}),});

GraphQL Testing

import{LambdaGraphQLTest}from'cdk-serverless/tests/lambda-test-utils';consttest=newLambdaGraphQLTest(handler,{// Optional default Cognito user for all requestscognito: {username: 'test-user',email: 'test@example.com',groups: ['admin'],},});// Test a GraphQL queryconstresult=awaittest.call({fieldName: 'getItem',arguments: {id: '123'},});

IntegTestUtil

The IntegTestUtil provides a comprehensive set of tools for integration testing your deployed serverless applications. It handles authentication, data cleanup, and API testing.

import{IntegTestUtil}from'cdk-serverless/tests/integ-test-util';// Initialize with your stack outputsconsttest=newIntegTestUtil({region: 'us-east-1',apiOptions: {baseURL: 'https://api.example.com',},authOptions: {userPoolId: 'us-east-1_xxxxx',userPoolClientId: 'xxxxxxxx',identityPoolId: 'us-east-1:xxxxxxxx',},datastoreOptions: {tableName: 'MyTable',},});// Create and authenticate a test userawaittest.createUser('test@example.com',{'custom:attribute': 'value',},['admin']);// Get an authenticated API clientconstclient=awaittest.getAuthenticatedClient('test@example.com');// Make API callsconstresponse=awaitclient.get('/items');// Clean up test dataawaittest.cleanupItems();awaittest.removeUser('test@example.com');

MCP Auth

CDK Serverless includes built-in support for adding Model Context Protocol (MCP) OAuth authentication to your API. This enables MCP clients like Claude and ChatGPT to authenticate with your API using standard OAuth 2.0 flows.

When activated, the following endpoints are automatically added to your OpenAPI spec:

EndpointMethodRFCPurpose
/.well-known/oauth-protected-resourceGETRFC 9728Resource metadata discovery
/.well-known/oauth-authorization-serverGETRFC 8414Authorization server metadata
/oauth/authorizeGETAuthorize proxy (redirect to upstream)
/oauth/tokenPOSTToken proxy (forward to upstream)
/oauth/registerPOSTRFC 7591Dynamic client registration

All MCP auth endpoints are anonymous (no API authorizer applied).

With Cognito

MCP clients like Claude enforce that all OAuth endpoints (discovery, authorize, token, register) live on the same origin as the API itself. Cognito's hosted UI lives on a different domain (auth.example.com), so MCP clients cannot talk to it directly. Additionally:

  • Cognito Managed Login v2 requires the RFC 8707 resource parameter for custom scopes in authorize requests — MCP clients do not send this parameter.
  • MCP clients construct the token endpoint URL from the OAuth metadata issuer field rather than using the explicit token_endpoint — so the token exchange must be proxied through the API domain.
  • Dynamic Client Registration (RFC 7591) is not natively supported by Cognito.

The MCP auth proxy solves all three problems: it serves discovery metadata on the API domain, strips unsupported parameters before forwarding to Cognito, and implements a simplified registration endpoint that returns a pre-provisioned client ID.

If your API already uses CognitoAuthentication, add MCP auth with minimal config — a dedicated user pool client is created automatically:

constapi=newTestApiRestApi(this,'Api',{stageName: 'dev',domainName: 'example.com',apiHostname: 'api',authentication: cognitoAuth,cors: true,mcpAuth: {cognito: {auth: cognitoAuth,// your CognitoAuthentication constructauthDomain: 'auth.example.com',// Cognito custom/hosted domain (required)},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

The apiDomain is derived from the RestApi's own domain config (apiHostname + domainName), and stageName is reused — no duplication needed.

With any OAuth2 provider

For non-Cognito providers, use generic mode with explicit endpoint URLs:

constapi=newTestApiRestApi(this,'Api',{// ...mcpAuth: {generic: {authorizeEndpoint: 'https://auth.example.com/authorize',tokenEndpoint: 'https://auth.example.com/token',clientId: 'my-pre-provisioned-client-id',},serverInfo: {name: 'my-mcp-server',version: '1.0.0'},},});

Configuration options

OptionDefaultDescription
serverInfo(required){ name, version } returned in MCP initialize
allowedRedirectUrisClaude + ChatGPT callbacksAllowlist for dynamic registration
protocolVersions['2025-11-25', '2025-03-26', '2024-11-05']Supported MCP versions
scopes['openid', 'email', 'profile']Advertised OAuth scopes
stripParameters['resource']Params stripped from authorize/token proxying
lambdaOptionsLambda config for MCP auth handlers

MCP Server runtime

The cdk-serverless/mcp-auth module also exports a JSON-RPC server for implementing the MCP tool endpoint itself:

import{createMcpServer}from'cdk-serverless/mcp-auth';constserver=createMcpServer({serverInfo: {name: 'my-server',version: '1.0.0'},protocolVersions: ['2025-11-25'],resolver: {asyncresolve(headers){// Validate Bearer token, return principal or throw McpUnauthorizedErrorconsttoken=headers.authorization?.replace('Bearer ','');if(!token)thrownewMcpUnauthorizedError('Bearer');returnverifyToken(token);},},tools: [{name: 'search',description: 'Search documents',inputSchema: {type: 'object',properties: {query: {type: 'string'}}},asyncinvoke(principal,args){constresults=awaitsearch(principal,(argsasany).query);return{content: [{type: 'text',text: JSON.stringify(results)}]};},},],});// In your Lambda handler:constresponse=awaitserver.handle(parsedBody,event.headers);

Breaking Change: axios Removed

CDK Serverless no longer depends on axios. The library now uses the platform-native fetch API (stable in Node.js 18+; the Lambda functions created by this library use Runtime.NODEJS_LATEST, currently Node 22).

This removes one third-party runtime dependency from every Lambda bundle that imports from cdk-serverless/lambda and from every test workspace that imports from cdk-serverless/tests. It was motivated by repeated axios security advisories — landing this as a deliberate breaking change so the fix is permanent rather than chasing CVE upgrades.

Impact on Lambda handlers (cdk-serverless/lambda)

None. The internal JWKS / well-known-issuer fetches in the JWT authorizers were the only axios call sites in the Lambda runtime code, and their public behavior is unchanged. Errors now surface as Error (or a TimeoutError from AbortSignal.timeout) instead of AxiosError; if you catch errors inside the authorizer, the message text is similar but the type guard is different.

Impact on IntegTestUtil (cdk-serverless/tests)

IntegTestUtil.getClient() and IntegTestUtil.getAuthenticatedClient() previously returned an Axios instance. They now return a small HttpClient exported from cdk-serverless/tests. The migration is mechanical:

// Beforeconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.data is the parsed JSON, response.status is the HTTP status codeconstitems=response.data.items;// Afterconstclient=awaittest.getAuthenticatedClient('test@example.com');constresponse=awaitclient.get('/items');// response.body is the raw string, response.json() parses it, response.ok// reports 2xx, response.status is the HTTP status codeconstitems=response.json<{items: Item[]}>().items;

The HttpClient exposes the methods that integration tests in this ecosystem actually use:

  • get(path, options?)
  • post(path, body?, options?)body may be a string or any JSON-serializable value; objects are stringified and Content-Type: application/json is added automatically if the caller did not set it.
  • put(path, body?, options?), patch(path, body?, options?), delete(path, options?)

Configuration accepted by HttpClient and by getClient(config):

  • baseURL — prepended to relative paths.
  • headers — default headers applied to every request; per-request headers override these on collision.

If you relied on axios-specific features (interceptors, defaults, transformRequest / transformResponse, automatic data parsing), implement the equivalent in your test code or wrap HttpClient. If your use case needs richer client features and we should expose them, please open an issue.

Contribute

How to contribute to CDK Serverless

Did you find a bug?

  • Ensure the bug was not already reported by searching on GitHub under Issues.

  • If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.

Did you write a patch that fixes a bug?

  • Open a new GitHub pull request with the patch.

  • Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.

Did you fix whitespace, format code, or make a purely cosmetic patch?

Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability will normally not be accepted.

Do you intend to add a new feature or change an existing one?

  • Suggest your change under Issues.

  • Do not open a pull request on GitHub until you have collected positive feedback about the change.

Do you want to contribute to the CDK Serverless documentation?

  • Just file a PR with your recommended changes

Authors

Brought to you by Taimos

About

AWS CDK Serverless Toolsuite

Resources

Stars

87 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages