Skip to content

CLI Reference

mantle — Serverless TypeScript framework CLI.

bash
npx mantle <command> [flags]
# or install globally: pnpm add -g @mantleframework/cli

Build & Deploy

mantle build

Bundle Lambda functions with esbuild.

FlagDescription
-w, --watchWatch for changes and rebuild
-f, --function <name>Build a specific function only
--analyzeGenerate bundle analysis metafiles
--sourcemapGenerate source maps
--no-minifySkip minification

Scans src/lambdas/, outputs build/lambdas/<Name>/index.mjs. Target: Node.js 24 / ESM.

mantle dev

Start a local development server with hot reload. Watches src/lambdas/, simulates API Gateway routing locally.

mantle deploy

Deploy via OpenTofu.

bash
mantle deploy --stage staging
mantle deploy --stage production
FlagDescription
--stage <env>Target stage — required (dev, staging, production)

Runs tofu init, tofu plan, tofu apply. Requires AWS credentials. Never run without --stagedev has no tfvars and prompts interactively.


Generate

Alias: mantle g <subcommand>

mantle generate infra

Generate OpenTofu configuration from project structure and mantle.config.ts.

FlagDescription
--modules-path <path>Path to mantle modules (auto-detected if omitted)

Scans src/lambdas/, derives API routes from filesystem, auto-wires env vars from getRequiredEnv() / getOptionalEnv() calls. Safe to run repeatedly — skips ejected files.

mantle generate permissions

Extract @RequiresTable metadata and generate least-privilege DSQL permissions.

FlagDefaultDescription
--entity-dir <dir>src/entities/queriesEntity queries directory
--output-dir <dir>buildBuild output directory
--terraform-dir <dir>infraTerraform output directory
--permissions-dir <dir>permissionsPermissions output directory

mantle generate openapi

Generate an OpenAPI 3.1 specification from defineApiHandler metadata. Resolves Zod request/response schemas end-to-end via esbuild bundling and sibling extraction, producing fully-typed components/schemas with $ref operation bodies. Error responses are derived from each handler's auth mode and emitted as $refs to Models.ErrorResponse / Models.UnauthorizedError / Models.ForbiddenError / Models.InternalServerError when those schemas are sibling-extracted.

FlagDefaultDescription
--output <path>openapi.jsonOutput file path. Extension controls format — .json emits JSON, .yaml/.yml emits YAML.
--title <title>APIAPI title
--version <version>1.0.0API version
--server-url <url>Optional server URL in info.servers[0].url
--schema-prefix <prefix>Prepend a namespace to every component name (e.g., Models.). The Schema suffix is stripped first, so fileListResponseSchema becomes Models.FileListResponse. Preserves TypeSpec-era naming for iOS/Swift consumers.
--html <path>Also write a Redoc HTML docs bundle to the given path. Uses @redocly/cli build-docs under the hood (auto-installed via npx).
--verbosefalsePrint per-schema resolution diagnostics — which schemas resolved, which fell back to placeholders, and which inline handler-body schemas were promoted.

Default error response behavior

buildOperation computes the default error set from the handler's auth mode:

Auth modeStatus codes emitted
none (or unset)200, 400, 500
bearer200, 400, 401, 500
session200, 400, 401, 500
authorizer200, 400, 401, 403, 500

Each error code is only emitted when its matching component schema is present in the resolved schema set, so instances without an api-schema/schemas.ts barrel degrade gracefully to 200-only responses instead of producing broken $refs. The component name mapping is fixed:

  • 400ErrorResponse
  • 401UnauthorizedError
  • 403ForbiddenError
  • 500InternalServerError

Per-handler error override

Any handler may override the auth-derived defaults via openapi.errors:

typescript
const api = defineApiHandler({
  auth: 'bearer',
  openapi: {
    summary: 'Fetch by ID',
    errors: [400, 404, 500] // omits 401 even though auth is bearer
  }
})

The extractor parses the array literal via ts-morph; only integer literals are supported. Unknown codes (those without a ERROR_RESPONSES mapping) are silently dropped — useful for documenting non-standard codes in prose without producing broken refs.

Query parameters

defineApiHandler({ querySchema: MyQuerySchema }) emits OpenAPI parameters: [{in: 'query', ...}] — not requestBody. Each top-level property of the resolved query schema becomes a separate query parameter entry with its constraints (type, enum, minLength, etc.). Query parameters are appended after any path parameters on the same operation.

$ref promotion

After resolving all schemas to JSON Schema, the generator promotes inlined sub-schemas to $ref pointers when they are structurally identical to a top-level component. This produces clean Swift types (e.g., [HealthQuantity] instead of [HealthSyncRequestPayload.QuantitiesItem]). Self-matches are skipped — a component never $refs itself.

Schema resolution notes

  • Sibling extraction: schemas imported via import * as all surface every exported Zod schema in the module, so barrel files like src/types/api-schema/schemas.ts expose sub-schemas as named components even when no handler references them directly.
  • Inline handler schemas: const Schema = z.object(...) declared inside a handler body is promoted to export const at bundle time and resolved as a top-level component.
  • Zod identity: the generator bundles each schema together with its toJSONSchema() call via esbuild to avoid cross-package instanceof mismatches between different Zod copies. Do not import { z } from 'zod' directly in handler files — use @mantleframework/validation's re-export so all schemas share one Zod instance.
  • format: date-time: Zod 4's z.string().datetime() natively emits format: "date-time" via toJSONSchema(). Use .datetime() on timestamp schema fields to get proper date formatting in the spec.

mantle generate handler <Name>

Scaffold a new Lambda handler with matching test file.

FlagDefaultDescription
--trigger <type>apiTrigger type: api, sqs, s3, schedule, authorizer

mantle generate entity <name>

Scaffold a Drizzle entity schema.

FlagDescription
--fields <fields>Comma-separated name:type pairs (types: string, number, boolean, timestamp, uuid)
--queriesAlso generate entity query class with @RequiresTable methods

mantle generate migration <name>

Create a timestamped migration SQL file in migrations/.

mantle generate graph

Generate file-level dependency graph to build/graph.json. Auto-run during mantle build.

mantle generate graph:knowledge

Generate GraphRAG knowledge graph to graphrag/knowledge-graph.json.

mantle generate hooks

Generate Husky git hooks.

FlagDescription
--no-pre-commitSkip pre-commit hook
--no-pre-pushSkip pre-push hook

mantle generate ci-templates

Generate GitHub Actions CI/CD workflow files (.github/workflows/).

FlagDescription
--node-version <version>Node.js version

mantle generate agents

Generate AGENTS.md for AI assistants. Preserves content between <!-- CUSTOM:START --> and <!-- CUSTOM:END --> markers.

mantle generate repomix

Generate repomix.config.json for AI context packing (XML format, tree-sitter compression).

mantle generate deps-config

Generate .dependency-cruiser.cjs with Mantle architecture rules.

mantle generate integration-tests

Generate integration test scaffold with Docker Compose (LocalStack + PostgreSQL).

mantle generate knip-config

Generate knip.config.ts with Mantle-aware entry points for dead code detection.


Database

mantle db migrate

Run pending migrations using the Mantle migration runner.

FlagDefaultDescription
--folder <path>./migrationsMigrations folder
--provider <type>auto-detectedaurora-dsql, aurora-serverless-v2, neon
--endpoint <url>DSQL_ENDPOINT envDSQL cluster endpoint
--connection-string <url>DATABASE_URL envConnection string (non-DSQL)
--region <region>AWS_REGION envAWS region
--no-lockSkip migration lock

Auto-detects endpoint and region from Terraform state when infra/ is initialized.

mantle db generate

Generate migration file from schema diff (wraps drizzle-kit generate).

FlagDescription
--name <name>Migration file name
--customGenerate empty migration for manual SQL
--prefix <type>File prefix: index, timestamp, unix, none

mantle db check-dsql

Classify migration statements for Aurora DSQL compatibility.

FlagDefaultDescription
--migrations-dir <path>./migrationsMigrations directory

Output labels: OK (compatible), INDEX (auto-converted to ASYNC), STRIP (skipped — DSQL-unsupported), RECREATION (requires table recreation).

mantle db apply-permissions

Apply DSQL role permissions from permissions/ folder.

FlagDefaultDescription
--folder <path>./permissionsPermissions folder
--endpoint <url>DSQL_ENDPOINT envDSQL endpoint
--region <region>AWS_REGION envAWS region

mantle db push

Push schema directly to the database (dev only, wraps drizzle-kit push).

mantle db studio

Open Drizzle Studio (wraps drizzle-kit studio).


Quality

mantle ci

Run the full local CI pipeline.

FlagDescription
--fullAdd integration tests and extended quality checks
--step <number>Run a specific step only

Phases: Setup → Build → Validate → Test → Quality → Integration (full only). Exits non-zero on any CRITICAL or HIGH failure. Missing tools (ShellCheck, tofu) are skipped gracefully.

mantle check

Validate codebase against 20 convention rules via ts-morph.

FlagDescription
--fastCRITICAL rules only
--severity <level>Minimum severity: CRITICAL, HIGH, MEDIUM
--rule <name>Run one specific rule

mantle check deps

Enforce dependency architecture rules (no handler-to-handler imports, no circular deps, entity/service isolation).

mantle check bundles

Check Lambda bundle sizes against thresholds.

FlagDefaultDescription
--threshold <bytes>5000000Max bundle size in bytes
--jsonJSON output for CI

mantle check dead-code

Detect unused exports via Knip. Generate config first with mantle generate knip-config.

mantle check test-output [file]

Validate test output for problematic patterns (EMF metrics on stdout, unhandled rejections, deprecation warnings). Reads from stdin if no file given.


MCP Server

mantle mcp-server

Start the Model Context Protocol server for AI-assisted development (Claude Code, Cursor, etc.).

Provides 19 tools across Validation, Infrastructure, Reference, Workflow, Data Queries, and Performance categories.