CLI reference
See package manager commands and troubleshooting for pnpm 11/12 and npm usage.
All SwallowKit CLI commands and their options.
React uses the same commands with a managed Functions BFF. See the React guide; the detailed app/ and Next.js API route examples below describe the Next.js variant.
Package manager
Bootstrap: pnpm dlx swallowkit@beta init my-app or npx swallowkit@beta init my-app. Inside the project: pnpm exec swallowkit … or npx swallowkit … uses the installed CLI. MCP independently resolves latest.
Table of Contents
- swallowkit init
- swallowkit machine
- swallowkit-mcp
- swallowkit create-model
- swallowkit add-connector
- swallowkit add-auth
- swallowkit dev
- swallowkit scaffold
- swallowkit status
- swallowkit verify
- swallowkit create-dev-seeds
- swallowkit migrations init
- swallowkit create-migration
- swallowkit migrations add-model
- swallowkit configure-mcp
- swallowkit provision
swallowkit machine
Machine-readable command group for AI / MCP integrations.
Usage
npx swallowkit machine <command> <subcommand> [options]Available commands
| Command | Purpose |
|---|---|
inspect project | Return framework-owned project metadata |
inspect entities | Return entity and schema metadata |
inspect routes | Return BFF / Functions route metadata |
inspect artifacts | Return the generated-artifact ledger with ownership |
inspect boundaries | Return the responsibility boundary contract between AI free-form authoring and deterministic generation |
inspect drift | Detect drift between generated artifacts and the current state |
inspect infra | Inspect Bicep assets (params / modules / outputs / container wiring) without calling Azure |
inspect capabilities | Return the framework capability contract: model declarations (with exact formats), auth workflow, generated-CRUD scope, seeding, and available commands |
validate project | Return structured validation violations, including missing or stale local Cosmos container migrations for persistent models |
generate model | Run create-model in non-interactive JSON mode |
generate scaffold | Run scaffold in non-interactive JSON mode |
plan model | Preview schema, shared export, container migration, manifest, and artifact-ledger writes without changing project files |
plan model-infrastructure | Preview container migration registration for an existing schema without changing model bytes; optional pending refresh checks are read-only |
apply model | Apply a model plan after checking input fingerprints and overwrite approval |
plan scaffold | Compute the scaffold change plan (with planId) without writing files; accepts multiple models |
apply scaffold | Apply scaffold changes with plan freshness and approval checks; accepts multiple models |
plan auth | Compute the add-auth change plan without writing files (--allowed-providers sets SWA identity providers) |
apply auth | Apply auth code with plan freshness and approval checks |
plan provision | Check local model-container migration completeness, inspect Azure state, and return a bootstrap, adoption, migration, or reconcile plan |
apply provision | Apply an approved provisioning plan (always requires --approve) |
verify project | Run structure (including local model-container migration completeness) / drift / typecheck / backend-build (plus opt-in build / lint / test and custom checks); this does not prove Azure provisioning; --compact suppresses info-severity findings |
explain failure | Return evidence and repair actions for the last verify failures |
Examples
npx swallowkit machine inspect project
npx swallowkit machine validate project
npx swallowkit machine plan model todo --overwrite never
npx swallowkit machine apply model --plan <planId>
npx swallowkit machine plan model-infrastructure handwritten-model
npx swallowkit machine apply model --plan <planId>
npx swallowkit machine generate scaffold todo --api-only
npx swallowkit machine plan scaffold todo
npx swallowkit machine plan scaffold todo note learner
npx swallowkit machine apply scaffold --plan <planId>
npx swallowkit machine apply scaffold todo note learner
npx swallowkit machine apply scaffold todo --approve
npx swallowkit machine plan auth --provider custom-jwt
npx swallowkit machine plan auth --provider swa --scheme admin --allowed-providers github
npx swallowkit machine apply auth --plan <planId>
npx swallowkit machine inspect boundaries
npx swallowkit machine inspect capabilities
npx swallowkit machine inspect infra
npx swallowkit machine plan provision -g my-rg --location japaneast --swa-location eastasia
npx swallowkit machine plan provision -g my-rg --location japaneast --swa-location eastasia --adopt-existing --baseline 0 --what-if
npx swallowkit machine apply provision --plan <planId> --approve
npx swallowkit machine verify project --checks structure,drift
npx swallowkit machine verify project --compact
npx swallowkit machine explain failure --check typecheckOutput contract
- stdout is always a single JSON document
- commands are non-interactive
- success and failure are both structured (the
statusfield reportscomplete/in-progress/blocked/requires-human/failed) generate modelrequires an explicit overwrite policy (alwaysornever)- generated artifacts are tracked in the
.swallowkit/artifacts.jsonledger (Git-managed) - scaffold analyzes supported Zod object/enum/literal expressions with the TypeScript AST before considering dynamic evaluation; it never applies lossy regex metadata
- scaffold plans include the parser mode, canonical model metadata, semantic fingerprint, and diagnostics; apply is blocked with
schema-analysis-mismatchif re-analysis differs - unavailable schema or verification child processes return
schema-evaluation-unavailableorverification-command-unavailablewithstatus: blockedand diagnostics
See the AI / MCP Guide for architecture details and response examples.
swallowkit-mcp
Bundled MCP stdio server for AI coding agents.
Usage
npx swallowkit-mcpExposed MCP tools
swallowkit_inspect_projectswallowkit_inspect_entitiesswallowkit_inspect_routesswallowkit_inspect_artifactsswallowkit_inspect_boundariesswallowkit_inspect_driftswallowkit_inspect_infraswallowkit_validate_projectswallowkit_generate_modelswallowkit_scaffold_modelswallowkit_plan_scaffoldswallowkit_apply_scaffoldswallowkit_plan_authswallowkit_apply_authswallowkit_plan_provisionswallowkit_apply_provisionswallowkit_verify_projectswallowkit_explain_failure
The MCP server is a thin adapter over swallowkit machine ... and does not introduce framework logic of its own.
swallowkit init
Initialize a new SwallowKit project.
Usage
npx swallowkit@beta init [project-name] [options]
# or
pnpm dlx swallowkit@beta init [project-name] [options]Arguments
project-name(optional): Project name. Initializes in current directory if omitted
Options
| Option | Description | Values | Default |
|---|---|---|---|
--template <template> | Template to use | default | default |
--package-manager <manager> | Select the project package manager | npm, pnpm | invocation |
--frontend <framework> | Frontend framework | nextjs, react | prompt; nextjs without a TTY |
--next-version <version> | Next.js version | e.g. 16.0.7, latest | latest |
--cicd <provider> | CI/CD provider | github, azure, skip | (prompt) |
--backend-language <language> | Azure Functions backend language | typescript, csharp, python | (prompt) |
--cosmos-db-mode <mode> | Cosmos DB mode | freetier, serverless | (prompt) |
--vnet <option> | Network security | outbound, none | (prompt) |
--swa-plan <plan> | Azure Static Web Apps plan | free, standard | (prompt; initial selection is standard) |
Interactive vs Non-Interactive Mode
By default, init asks interactive prompts for frontend framework, CI/CD, Azure Functions backend language, Static Web Apps plan, Cosmos DB mode, and network settings.
Free supports the toolkit's base configuration. Choose Standard when you need an SLA, custom authentication providers, function-based custom role assignment, a private endpoint for Static Web Apps itself, or higher quotas. The Functions/Cosmos DB VNet created by --vnet outbound is independent of the SWA plan.
You can skip prompts by passing flags directly:
# Fully non-interactive
npx swallowkit@beta init my-app --cicd github --backend-language csharp --swa-plan free --cosmos-db-mode serverless --vnet outbound
# Partially non-interactive (only --cicd specified; the rest will prompt)
npx swallowkit@beta init my-app --cicd skipThis is especially useful when calling the CLI from VS Code extensions or scripts where stdin is not a TTY.
When a non-interactive environment is detected (CI, coding agents, piped execution, etc.), init behaves as follows instead of hanging on prompts:
- If configuration flags are missing, it fails immediately with a list of the missing flags (no hang).
- pnpm projects record a local build-script policy in
pnpm-workspace.yaml: React builds permitesbuild, while unnecessarykeytar,protobufjs, andunrs-resolverscripts are denied. Unknown scripts are not automatically approved; see package-manager troubleshooting.
Invalid flag values produce a clear error:
❌ Invalid --cicd value: "invalid". Must be: github, azure, skipInteractive Prompts
When flags are not specified, the following prompts are shown:
- CI/CD Provider: GitHub Actions, Azure Pipelines, or Skip
- Backend Language: TypeScript, C#, or Python
- Cosmos DB Mode: Free Tier or Serverless
- Network Security: VNet Integration or None
Backend Language Notes
typescript: Functions consume the shared Zod package directly.csharp/python:swallowkit scaffoldexports OpenAPI intofunctions/openapi/and generates native backend schema assets intofunctions/generated/.
Generated Files
my-app/
├── app/ # Next.js App Router
│ ├── api/greet/ # BFF sample
│ ├── layout.tsx
│ └── page.tsx
├── components/ # React components
├── lib/
│ ├── api/backend.ts # BFF client (api.get/post/put/delete)
│ ├── database/ # Cosmos DB client (optional)
│ │ ├── client.ts # CosmosClient
│ │ └── repository.ts # Repository pattern
│ ├── models/ # Data models
│ └── schemas/ # Zod schemas
├── functions/ # Azure Functions
│ ├── src/ # TypeScript handlers
│ ├── Crud/ # C# handlers
│ ├── blueprints/ # Python handlers
│ ├── generated/ # Native-generated schema assets for C#/Python
│ ├── openapi/ # Exported OpenAPI specs for C#/Python
│ ├── host.json
│ └── local.settings.json
├── infra/ # Bicep IaC
│ ├── main.bicep
│ ├── main.parameters.json
│ └── modules/
│ ├── staticwebapp.bicep
│ ├── functions.bicep
│ └── cosmosdb.bicep
├── .github/workflows/ # CI/CD (GitHub Actions)
│ ├── static-web-app.yml
│ └── azure-functions.yml
├── .github/
│ ├── copilot-instructions.md # GitHub Copilot instructions
│ └── instructions/ # Copilot layer-specific rules
│ ├── shared-models.instructions.md
│ ├── bff-routes.instructions.md
│ └── azure-functions.instructions.md
├── .env.local # Environment variables
├── .env.example
├── next.config.js
├── swallowkit.config.js
├── staticwebapp.config.json
├── .mcp.json # Project-scoped MCP bootstrap resolving SwallowKit on each launch
├── AGENTS.md # Coding agent instructions (Codex)
├── CLAUDE.md # Claude Code instructions
└── package.jsonAI Agent Bootstrap Files
The init command automatically generates instruction files for multiple AI coding agents, plus a project-scoped MCP bootstrap for runtimes that support repository MCP discovery. Together, these files help AI agents (GitHub Copilot, Claude Code, OpenAI Codex, etc.) follow the project's architecture and conventions when generating or modifying code.
Generated Files
| File | Target Agent | Description |
|---|---|---|
AGENTS.md | OpenAI Codex / generic agents | Full architecture spec, conventions, naming rules, CLI commands, autonomous-loop procedures |
CLAUDE.md | Claude Code | Adapter to the canonical AGENTS.md contract |
.mcp.json | Claude Code / project MCP runtimes | Launcher resolving swallowkit-mcp on each start; SWALLOWKIT_MCP_VERSION can pin it |
.github/copilot-instructions.md | GitHub Copilot | Summary of key rules (auto-loaded by Copilot) |
.github/instructions/shared-models.instructions.md | GitHub Copilot | Layer-specific rules for shared/models/** |
.github/instructions/bff-routes.instructions.md | GitHub Copilot | Layer-specific rules for app/api/** (Next.js) or bff/** (React) |
.github/instructions/azure-functions.instructions.md | GitHub Copilot | Layer-specific rules for functions/** |
.github/skills/*/SKILL.md | Skills-aware agents (Copilot in VS Code / CLI / cloud agent, etc.) | Workflow skills in the Agent Skills open standard (swallowkit-add-model / swallowkit-modify-model / swallowkit-verify-repair / swallowkit-provision), auto-loaded when the task matches |
.swallowkit/workflows/*.md | All agents (incl. non-skills-aware) | Agent-agnostic autonomous-loop runbooks (same content as the skills) |
Canonical AGENTS.md and agent adapters
See the coding-agent guide for the complete current templates, including AGENTS.md, CLAUDE.md, and Copilot instructions. AGENTS.md owns the persistence, seed, runtime-evidence, and safety contract; adapters and runbooks refer to it rather than duplicating that guidance. The guide also explains reviewed manual merging for existing projects; init refuses an existing directory and is not an instruction-update command.
.github/copilot-instructions.md (GitHub Copilot)
This file is automatically loaded by GitHub Copilot in VS Code. It contains a summary of the architecture, key rules, naming conventions, managed fields, and the MCP / machine-interface fallback path for framework-owned operations.
.github/instructions/*.instructions.md (GitHub Copilot — Layer-Specific)
These files provide context-specific rules that GitHub Copilot applies when editing files matching the applyTo glob pattern:
| File | Applies To | Key Rules |
|---|---|---|
shared-models.instructions.md | shared/models/** | Zod schema conventions, id/createdAt/updatedAt management, re-export from shared/index.ts |
bff-routes.instructions.md | app/api/** (Next.js) or bff/** (React) | Proxy-only rule, callFunction() usage, no business logic |
azure-functions.instructions.md | functions/** | Cosmos DB bindings, Zod validation, UUID auto-generation |
Package Manager Detection
SwallowKit automatically selects the package manager:
- If pnpm is installed on the system, pnpm is always preferred
- Otherwise, npm is used
The generated project (lockfiles, workspace config, CI/CD scripts) matches the detected package manager.
Examples
# Initialize in new directory (interactive)
npx swallowkit@beta init my-awesome-app
# Initialize in new directory (non-interactive)
npx swallowkit@beta init my-awesome-app --cicd github --swa-plan free --cosmos-db-mode serverless --vnet outbound
# Using pnpm
pnpm dlx swallowkit@beta init my-awesome-app
# After initialization
cd my-awesome-appswallowkit create-model
Create one or more Zod model templates under shared/models/. For each newly created non-connector model, also generate and register its Cosmos container migration; this does not provision Azure or generate CRUD.
Usage
npx swallowkit create-model <names...> [options]
# or
pnpm dlx swallowkit create-model <names...> [options]Arguments
names...: One or more model names
Options
| Option | Description | Default |
|---|---|---|
--models-dir <dir> | Output directory for generated model files | shared/models |
--connector <name> | Create a connector-aware model linked to the named connector | (none) |
What it does
For each model name, the command:
- creates
shared/models/<name>.ts - normalizes the file name to kebab-case and the schema/type name to PascalCase
- appends a missing re-export to
shared/index.ts(creating the index if needed), preserving existing content - includes
id,name,createdAt, andupdatedAtin the starter schema - generates the container Bicep, migration manifest entry, and artifact ownership record
Example:
npx swallowkit create-model todo categoryGenerated template:
import { z } from 'zod/v4';
export const Todo = z.object({
id: z.string(),
name: z.string().min(1),
createdAt: z.string().optional(),
updatedAt: z.string().optional(),
});
export type Todo = z.infer<typeof Todo>;
export const displayName = 'Todo';Connector model
When --connector is specified, the generated template includes a connectorConfig export with connector-specific metadata:
- RDB connectors: includes
tableandidColumnfields - API connectors: includes
endpointsmapping - Both include an
operationsarray (defaults to all operations for API, read-only for RDB) - The Zod schema template is adapted (no
createdAt/updatedAtauto-management by backend)
Example:
npx swallowkit create-model user --connector mysql
npx swallowkit create-model backlog-issue --connector backlogExisting file behavior
If the target file already exists, the command asks whether it should overwrite that file. If you answer no, that model is skipped and the remaining models continue; it does not backfill infrastructure for skipped files. Use migrations add-model <name> to register a handwritten model without changing its schema.
Typical workflow
npx swallowkit create-model todo
# edit shared/models/todo.ts
npx swallowkit migrations add-model todo --dry-run # only needed for a handwritten or skipped model
npx swallowkit scaffold shared/models/todo.ts # only when CRUD is neededCustomize the generated Zod model before running scaffold or provision. To refresh an unapplied container definition after changing its partition key, explicitly preview migrations add-model <name> --refresh-pending --resource-group <name> --dry-run; it performs read-only remote checks and blocks if applied, attempted, unknown, or modified migration state cannot be proven safe.
swallowkit add-connector
Register an external data source connector in swallowkit.config.js.
Usage
npx swallowkit add-connector <name> --type=<type> [options]
# or
pnpm dlx swallowkit add-connector <name> --type=<type> [options]Arguments
name(required): Connector name (used as key in config)
Options
| Option | Description | Required |
|---|---|---|
--type <type> | Connector type: rdb or api | Yes |
--provider <provider> | RDB provider: mysql, postgres, sqlserver | Only for --type rdb |
--connection-env <var> | Environment variable for connection string | Only for --type rdb |
--base-url-env <var> | Environment variable for API base URL | Only for --type api |
--auth-type <type> | Auth type: apiKey, bearer, oauth2 | Only for --type api |
--auth-env <var> | Environment variable for auth credential | Only for --type api |
--auth-placement <placement> | Where to place auth: query or header | Only for --type api with apiKey |
--auth-param <name> | Parameter name for API key | Only for --type api with apiKey |
What it does
- Reads existing
swallowkit.config.js - Adds the connector definition to the
connectorssection - Creates the
connectorssection if it doesn't exist
Examples
# Add MySQL RDB connector
npx swallowkit add-connector mysql --type rdb --provider mysql --connection-env MYSQL_CONNECTION_STRING
# Add REST API connector with API key auth
npx swallowkit add-connector backlog --type api --base-url-env BACKLOG_API_BASE_URL --auth-type apiKey --auth-env BACKLOG_API_KEY --auth-placement query --auth-param apiKey
# Add REST API connector with bearer token
npx swallowkit add-connector github --type api --base-url-env GITHUB_API_BASE_URL --auth-type bearer --auth-env GITHUB_TOKENswallowkit add-auth
Set up authentication and authorization infrastructure for a SwallowKit project.
Usage
npx swallowkit add-auth [options]
# or
pnpm dlx swallowkit add-auth [options]Options
| Option | Description | Values | Default |
|---|---|---|---|
--provider <provider> | Authentication provider | custom-jwt | custom-jwt, swa, external-token, none |
Note:
swaandswa-customare reserved for future releases, but are not implemented by the current generated auth flow.
What it does
- Generates shared auth models (
shared/models/auth.ts— LoginRequest, AuthUser, LoginResponse) - Generates auth Functions (login, me, logout) for the configured backend language (TS/C#/Python)
- Generates JWT helper utilities for token verification and role checking
- Generates BFF routes (
app/api/auth/login|logout|me/route.ts) with httpOnly cookie management - Generates Next.js
proxy.tsfor preliminary cookie/expiry checks and redirects - Generates a login page (
app/login/page.tsx) - Generates an auth React context (
lib/auth/auth-context.tsx) withuseAuthhook - Updates
lib/api/call-function.tsto forward theAuthorizationheader - Adds
authsection toswallowkit.config.jsif not present - Installs backend dependencies (JWT library + RDB driver matching your connector provider)
Prerequisites
- A connector must be registered in
swallowkit.config.jsfor the user database (e.g., an RDB connector pointing to PostgreSQL, MySQL, or SQL Server) - The
auth.customJwt.userConnectorconfig must reference that connector name
Examples
# Set up custom JWT authentication (default)
npx swallowkit add-auth
# Explicitly specify provider
npx swallowkit add-auth --provider custom-jwtTypical workflow
# 1. Add RDB connector for user database
npx swallowkit add-connector userdb --type rdb --provider postgres --connection-env USERDB_CONNECTION_STRING
# 2. Configure auth in swallowkit.config.js (add auth section)
# 3. Run add-auth to generate all auth infrastructure
npx swallowkit add-auth
# 4. Set JWT_SECRET in functions/local.settings.json
# 5. Add authPolicy to models for role-based access
# 6. Re-scaffold to inject auth guards into functions
npx swallowkit scaffold shared/models/estimate.ts
# 7. Start development with mock connectors (user data is also mocked)
npx swallowkit dev --mock-connectors💡 See the Authentication Guide for full configuration details and architecture overview.
swallowkit dev
Start development servers: Next.js + standalone Functions, or React/Vite + managed BFF + standalone Functions + SWA.
For React, dev writes a temporary Vite wrapper under .swallowkit/vite-dev-*/config.mjs. Before creating it, SwallowKit ensures .swallowkit/.gitignore contains /vite-dev-*/, including for existing projects. This also excludes wrappers left by older versions or interrupted processes. Other user ignore rules are retained, and artifacts.json, project.json, and workflows/ remain shareable. Startup fails with the ignore-file path if the rule cannot be prepared. Normal exit removes only that run's temporary directory; older or concurrently used directories are not deleted.
Usage
npx swallowkit dev [options]
# or
pnpm dlx swallowkit dev [options]Options
| Option | Short | Description | Default |
|---|---|---|---|
--port <port> | -p | Frontend port (Next.js or Vite) | 3000 |
--functions-port <port> | Azure Functions port | 7071 | |
--bff-port <port> | React managed BFF Functions port | 7073 | |
--host <host> | Host name | localhost | |
--open | -o | Auto-open browser | false |
--no-functions | Skip Functions | false | |
--seed-env <environment> | Replace matching Cosmos Emulator containers from dev-seeds/<environment> before startup | (disabled) | |
--mock-connectors | Start a mock proxy server for connector models | false | |
--swa-port <port> | SWA authentication emulator port | 4280 | |
--no-swa | Skip the SWA authentication emulator | false | |
--verbose | -v | Show detailed logs | false |
Behavior
- Cosmos DB Emulator Check: Verify local emulator is running
- Cosmos DB Initialization:
- Create database if needed
- Create model containers if needed
- If
--seed-env <environment>is provided anddev-seeds/<environment>/exists, replace each matching container with the JSON documents from that environment
- Connector Mock Server (when
--mock-connectorsis enabled):- Starts a proxy server on Functions port + 1 (e.g., 7072)
- Routes matching connector models → in-memory CRUD with Zod-generated mock data
- All other routes → proxied to real Azure Functions
- Loads dev-seeds JSON as initial data if available
- BFF automatically routes through the mock proxy (no config change needed)
- Azure Functions Start:
- Check Azure Functions Core Tools
- Auto-install dependencies
- Start Functions in
functions/directory - Python backend: use uv with normal interpreter discovery and user settings, creating
functions/.venvfor the app andfunctions/.codegen-venvfor schema generation without forcing Python 3.11 or clearing existing environments - C# backend: allow extra cold-start time for the isolated worker build, and only report the Functions URL as ready after the host answers HTTP requests
- Next.js Start: Launch development server
- SWA authentication emulator (when
auth.provider: 'swa'and--no-swais not set):- Checks for a project-local or PATH-installed SWA CLI and exits with an installation command when missing
- Starts the authentication proxy on port 4280 while preserving Next.js as the BFF
- Prints the local login URL and authenticated application URL
Dev Seed Workflow
Use environment-specific seed data when you want reproducible emulator state for debugging:
npx swallowkit create-dev-seeds local
# edit dev-seeds/local/*.json
npx swallowkit dev --seed-env local
# or capture the current emulator data as reusable seeds
npx swallowkit create-dev-seeds local --from-emulator --force
npx swallowkit dev --seed-env localUseful scenarios:
- preserve realistic data you entered manually while exercising the app
- replay the same state for demos, onboarding, or acceptance checks
- share a broken or edge-case dataset when reproducing bugs across the team
- reset the emulator back to a known-good state before verification
Rules:
- File naming follows your schema files, for example
shared/models/todo.ts->dev-seeds/local/todo.json - Each matching seed file replaces the entire contents of the corresponding Cosmos container
- Containers without a matching seed file are not modified
- If
--seed-envis omitted, or the environment directory does not exist, existing emulator data is preserved - Each document must have a non-empty string
id
Example:
[
{
"id": "seed-todo-001",
"name": "Seed todo one",
"createdAt": "2026-03-21T00:00:00.000Z",
"updatedAt": "2026-03-21T00:00:00.000Z"
}
]Examples
# Start with default settings
npx swallowkit dev
# Start with custom ports
npx swallowkit dev --port 3001 --functions-port 7072
# Auto-open browser
npx swallowkit dev --open
# Next.js only (no Functions)
npx swallowkit dev --no-functions
# Start with a seed environment
npx swallowkit dev --seed-env local
# Verbose logging
npx swallowkit dev --verbose
# Start with connector mock server
npx swallowkit dev --mock-connectors
# Combine mock connectors with seed data
npx swallowkit dev --mock-connectors --seed-env localTroubleshooting
Cosmos DB Emulator not found:
Error: Cosmos DB Emulator is not runningSolution:
- Windows: Install from official site
- Docker:
docker run -p 8081:8081 mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator
Azure Functions Core Tools missing:
Error: Azure Functions Core Tools not foundSolution:
npm install -g azure-functions-core-tools@4
# or
pnpm add -g azure-functions-core-tools@4Port in use:
Error: Port 3000 is already in useSolution:
npx swallowkit dev --port 3001swallowkit scaffold
Auto-generate CRUD operations from Zod schemas.
Usage
npx swallowkit scaffold <model-file> [options]
# or
pnpm dlx swallowkit scaffold <model-file> [options]Arguments
model-file(required): Path to model file containing Zod schema
Options
| Option | Description | Default |
|---|---|---|
--functions-dir <dir> | Azure Functions directory | functions |
--api-dir <dir> | BFF directory | app/api (Next.js), bff (React) |
--api-only | Skip UI components only. Functions, BFF routes, OpenAPI, and native schema assets are still updated. | false |
--skip-infra | Do not create or update anything under infra/ as part of this scaffold operation. Existing model migrations are not removed; if the model has no registered container migration, add it later with migrations add-model. Also available on machine plan/apply/generate scaffold and MCP (skipInfra). | false |
--dry-run | Show planned file changes and conflicts without writing anything | false |
Connector model behavior
When a model file contains a connectorConfig export, scaffold detects it as a connector model:
- RDB connector models: generates SQL-based CRUD handlers in
functions/Connectors/(C#) or equivalent - API connector models: generates HTTP client handlers
- BFF routes and React UI are generated identically to standard models
- Cosmos DB Bicep generation is skipped for connector models
- Read-only models (operations limited to
getAll/getById) only get GET endpoints
Generated Code
| Target | Output |
|---|---|
| TypeScript Functions | functions/src/<model-kebab>.ts |
| C# Functions | functions/Crud/<Model>CrudFunctions.cs |
| Python Functions | functions/blueprints/<model_snake>.py |
| Next.js BFF | app/api/<modelCamel>/route.ts and [id]/route.ts |
| React managed BFF | bff/src/<modelCamel>/index.ts and bff/<modelCamel>/function.json |
| Next.js UI | Pages and _components/<Model>Form.tsx under app/<model-kebab>/ |
| React UI | Pages, forms, and route registration under src/pages/<model-kebab>/ |
TypeScript CRUD uses explicit handlers with Cosmos DB bindings or SDK calls as appropriate. The BFF validates input and responses with shared Zod schemas. Scaffold also records artifact ownership and infrastructure migrations.
Model requirements
Define Zod schemas in shared/models/. Scaffold does not require a BaseModel subclass.
// shared/models/todo.ts
import { z } from 'zod/v4';
export const Todo = z.object({
id: z.string(),
text: z.string().min(1),
completed: z.boolean().default(false),
createdAt: z.string().optional(),
updatedAt: z.string().optional(),
});
export type Todo = z.infer<typeof Todo>;npx swallowkit scaffold todo
npx swallowkit scaffold shared/models/product.tsCall the generated API
The standard Todo API uses the singular /api/todo. Updates validate the full input schema, so include required fields rather than sending only changed properties.
const response = await fetch('/api/todo');
const todos = await response.json();
const created = await fetch('/api/todo', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: 'Buy milk', completed: false }),
});Use the generated authenticated fetch helper on pages that use external-token authentication. See the Scaffold guide and Authentication guide.
swallowkit status
Show the generated-artifact ledger (.swallowkit/artifacts.json) and drift against the current project state.
Usage
npx swallowkit status [options]Options
| Option | Description | Default |
|---|---|---|
--artifacts | List all tracked artifacts with their ownership | false |
Output
- Number of tracked artifacts, files modified after generation, and missing files
- Drift findings (schema-drift / artifact-modified / artifact-missing / generator-drift / manifest-drift) with repair actions
swallowkit verify
Run verification checks (structure / drift / typecheck / backend-build by default, plus configured custom checks). Exits with code 1 if any check fails.
Usage
npx swallowkit verify [options]Options
| Option | Description | Default |
|---|---|---|
--checks <ids> | Check ids, quoted in PowerShell (e.g. "structure,drift,typecheck,backend-build,build") | default checks + custom checks |
Checks
| Check | What it does |
|---|---|
structure | Project structure conventions (same as validate project) |
drift | Detect divergence between generated artifacts and the current state |
typecheck | TypeScript type check (uses the typecheck script if present, otherwise runs tsc --noEmit with the project's package manager) |
backend-build | Standalone functions/: C# dotnet build; TypeScript project compiler tsc --noEmit; Python 3 compileall (syntax only, not imports or types). Uses functions/.venv before PATH for Python. |
build / lint / test | Opt-in root package scripts; skipped if no corresponding script exists |
Missing backend toolchains are skip with a reason, not validation. Restore the toolchain and re-run before claiming backend correctness. Root build does not replace backend-build. Compiler errors, including file/line evidence, are returned by machine explain failure.
Results are saved to .swallowkit/state/last-verify.json; use swallowkit machine explain failure to get failure details.
swallowkit create-dev-seeds
Generate JSON seed templates for a named local environment from the current schemas in shared/models/, or export the current local Cosmos DB Emulator data into the same layout.
Usage
npx swallowkit create-dev-seeds <environment> [options]
# or
pnpm dlx swallowkit create-dev-seeds <environment> [options]Arguments
environment(required): Name of the seed environment directory underdev-seeds/
Options
| Option | Description | Default |
|---|---|---|
--models-dir <dir> | Models directory to read schemas from | shared/models |
--seeds-dir <dir> | Base directory for generated seed environments | dev-seeds |
--force | Overwrite existing JSON seed files | false |
--from-emulator | Export current local Cosmos DB Emulator data instead of generating templates | false |
What It Generates
For every schema under shared/models/, SwallowKit generates a JSON file under dev-seeds/<environment>/:
dev-seeds/
local/
todo.json
category.jsonTemplate values are inferred from schema field types:
- strings -> sample strings
- numbers ->
0 - booleans ->
false - enums -> first enum value
...At/date fields -> ISO timestamp sample- nested schemas -> nested JSON objects
With --from-emulator, SwallowKit reads CosmosDBConnection and COSMOS_DB_DATABASE_NAME from functions/local.settings.json, exports documents from the matching local Cosmos DB Emulator containers, and strips Cosmos system properties such as _etag so the files can be replayed safely.
Why this helps:
- convert real local test data into reusable assets without manual copying
- keep demo and verification datasets close to actual app behavior
- make regression and bug-reproduction data easy to share
- plug directly into the existing
swallowkit dev --seed-env <environment>workflow
Typical Workflow
npx swallowkit create-model todo
npx swallowkit scaffold shared/models/todo.ts
npx swallowkit create-dev-seeds local
# edit dev-seeds/local/todo.json
npx swallowkit dev --seed-env local
# or export your current local Cosmos Emulator data
npx swallowkit create-dev-seeds local --from-emulator --force
npx swallowkit dev --seed-env localswallowkit migrations add-model
Register or backfill the Cosmos DB container migration for a model without overwriting its schema or generating CRUD:
npx swallowkit migrations add-model probe-item --dry-run
npx swallowkit migrations add-model probe-itemMachine/MCP callers should use machine plan model-infrastructure <model> and apply the returned plan with machine apply model --plan <planId> so the migration, manifest, and artifact-ledger writes are fingerprinted and reviewed before applying.
It writes infra/migrations/<version>-create-<model>-container/main.bicep, updates infra/migrations/manifest.json, and records generated-file ownership. It also synchronizes .swallowkit/project.json with all current models, even when the container migration is already registered. Plans include this metadata update and its fingerprints; dry runs do not write it. Once metadata is current, re-running is a no-op unless explicitly refreshing a proven-unapplied definition. Connector models have no container.
To repair only a stale project manifest (manifest-out-of-date or manifest-drift), without generating CRUD or touching infrastructure, use an existing model:
npx swallowkit machine plan model probe-item --overwrite never
npx swallowkit machine apply model --plan <planId>The existing schema is skipped, but the project manifest is synchronized. Review the plan before applying; schema files, existing migrations, and their checksums are preserved. This repair does not require Azure access or --refresh-pending.
After editing a partition key while its migration is still pending, refresh it only with an explicit target and read-only state check:
npx swallowkit migrations add-model probe-item --refresh-pending --resource-group <name> --dry-run
npx swallowkit migrations add-model probe-item --refresh-pending --resource-group <name>Add --subscription <id> when the target subscription is not selected in Azure CLI. A dry run writes nothing. Applied, attempted, unknown, or user-modified migrations are blocked; never edit a migration that may have been deployed.
swallowkit configure-mcp
Re-select the SwallowKit version launched by .mcp.json. Only SWALLOWKIT_MCP_VERSION is changed.
npx swallowkit configure-mcp # auto: latest unless the project is newer
npx swallowkit configure-mcp --version latest
npx swallowkit configure-mcp --version 2.0.0-alpha.3Restart the MCP server afterwards. See MCP version selection.
swallowkit provision
Inspect Azure state and either bootstrap the environment or apply pending infrastructure migrations. Existing environments do not normally redeploy main.bicep.
Usage
npx swallowkit provision [options]
# or
pnpm dlx swallowkit provision [options]Options
| Option | Short | Description | Required |
|---|---|---|---|
--resource-group <name> | -g | Resource group name; required for a new preview, not checkpoint status/resume | |
--subscription <id> | Subscription ID | ||
--location <region> | Functions/Cosmos DB region; required non-interactively | ||
--swa-location <region> | Static Web Apps region; required non-interactively | ||
--what-if | Include Azure what-if evidence in the preview | ||
--adopt-existing | Adopt an existing untagged environment as a baseline | ||
--baseline <version> | Adoption baseline; currently only 0 | ||
--reconcile | Explicitly redeploy all of main.bicep | ||
--approve | Compatibility option; normal provision invocation already requests execution | ||
--status <runId> | Read the original deployment/checkpoint without Azure or ledger writes | ||
--resume <runId> | Resume the original approved checkpoint; never resubmit an attempted deployment | ||
--resume-deployment <name> | Recover an older baseline after ARM/non-secure parameter verification; no deployment create | ||
--wait-seconds <seconds> | Hidden. Optional wait limit, 0-3600. By default provision and --resume wait until Azure finishes; status reads once |
Region Selection
The command prompts for these regions interactively:
- Primary location for Functions and Cosmos DB
- Static Web App location
Recommended region combinations:
japaneast+eastasiajapanwest+eastasiaeastus2+eastus2westeurope+westeurope
Primary location choices:
japaneast- Japan Eastjapanwest- Japan Westeastasia- East Asiasoutheastasia- Southeast Asiaeastus- East USeastus2- East US 2westus2- West US 2centralus- Central USwesteurope- West Europe
Static Web App location choices:
eastasia- Recommended for Japanwestus2- West US 2centralus- Central USeastus2- East US 2westeurope- West Europe
List all regions:
az account list-locations --output tableGenerated Resources
Azure Static Web Apps
- SKU: Free
- Build config: standalone Next.js
Azure Functions
- Plan: Flex Consumption
- Runtime: Node.js 22
- OS: Linux
Azure Cosmos DB
- Mode: Free Tier or Serverless (selected during initialization)
- API: NoSQL
- Consistency: Session
Azure Storage Account
- For Functions storage
- SKU: Standard_LRS
Managed Identity
- Type: System-assigned
- Role: Cosmos DB Data Contributor
Examples
# Basic usage
npx swallowkit provision --resource-group my-app-rg
# With subscription
npx swallowkit provision \
--resource-group my-app-rg \
--subscription "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \
--location japaneast --swa-location eastasiaBehavior by Azure State
| Azure state | Behavior |
|---|---|
| Resource group does not exist | Deploy main.bicep once and record baseline 0 |
| Tag matches the local checksum | Apply only pending migrations in version order |
| No pending migrations | noop; no Azure resources are changed |
| Resource group exists without a state tag | adoption-required; explicit adoption is required |
| Azure version is ahead or checksums differ | Stop without applying changes |
The tag is checked again immediately before apply and before every migration. A concurrent deployment causes stale-azure-state rather than applying against an unexpected version.
Waiting and Recovery
Deployments use --no-wait. Normal provision and provision --resume poll until Azure finishes and then print resource information and CI/CD settings; machine/MCP apply polls for a bounded time (default 300 seconds). If waiting stops early, Running/Accepted returns in-progress; an unreadable/missing state returns blocked with outcome: "unknown", not an invented Azure failure. Failed/Canceled includes sanitized Azure causes. Succeeded with incomplete tag/ledger updates is partial; only completed bookkeeping returns complete.
pnpm exec swallowkit provision --status <runId>
pnpm exec swallowkit provision --resume <runId>
# Machine/MCP equivalent: runId equals original planId
pnpm exec swallowkit machine inspect provision --plan <runId> --wait-seconds 300
pnpm exec swallowkit machine apply provision --plan <runId> --approveKeep the execution checkpoint under .swallowkit/state/provision/. Normal provision --resume explicitly requests continuation without another approval prompt. Machine/MCP resume still requires fresh human approval. Both preserve fingerprints, subscription, deployment identity and migration checksums. Normal CLI success includes resource information and CI/CD setup guidance; errors suggest normal provision commands, not machine commands. Ctrl+C/hard termination may leave Azure running; no automatic cancel/delete is performed. Do not replan/reconcile just to fix waiting or bookkeeping. See older untracked baseline recovery for --resume-deployment.
swallowkit migrations init
Record the current infra/ directory of a project created by an older SwallowKit version as baseline 0 without modifying it.
npx swallowkit migrations init --legacy-baselineCommit the generated infra/migrations/manifest.json. This command does not contact Azure and does not overwrite an existing manifest. Then adopt the deployed environment:
npx swallowkit provision -g my-app-rg \
--location japaneast --swa-location eastasia \
--adopt-existing --baseline 0 --what-ifAdoption never deploys main.bicep. It preserves existing resource-group tags and adds only the SwallowKit state tag. It stops if what-if contains Create/Delete changes.
swallowkit create-migration
Generate the next versioned Bicep file for an additional Azure resource:
npx swallowkit create-migration add-search-service
# Edit infra/migrations/0001-add-search-service/main.bicepThe template receives projectName and location. Reference existing resources with existing, and keep migrations additive and safe to retry. Applied migrations are immutable; add a corrective migration instead of editing one.
After Provisioning
# List resources
az resource list --resource-group my-app-rg --output table
# Get Static Web Apps URL
az staticwebapp show \
--name <swa-name> \
--resource-group my-app-rg \
--query "defaultHostname" -o tsv
# Get Functions URL
az functionapp show \
--name <function-name> \
--resource-group my-app-rg \
--query "defaultHostName" -o tsvCustomizing Baseline Bicep
Edit Bicep files in infra/ before provisioning:
// infra/modules/functions-flex.bicep
// Customize instance memory size
resource flexFunctionsServer 'Microsoft.Web/sites@2023-12-01' = {
// Flex Consumption properties
}Normal provision stops with baseline-drift after an intentional baseline edit. Review Azure what-if and use --reconcile --what-if to deploy it. Reconcile may reset template-managed properties such as Function App settings. Prefer create-migration for additional resources.
Troubleshooting
Resource group doesn't exist:
# Create it
az group create --name my-app-rg --location japaneastResources unavailable in region:
# Check available regions
az provider show --namespace Microsoft.Web \
--query "resourceTypes[?resourceType=='staticSites'].locations" -o tableQuota exceeded:
# Check quota
az vm list-usage --location japaneast --output tableGlobal Options
Available for all commands:
| Option | Description |
|---|---|
--help | Show help |
--version | Show version |
Environment Variables
Control CLI behavior with environment variables:
| Variable | Description | Default |
|---|---|---|
SWALLOWKIT_LOG_LEVEL | Log level (debug/info/warn/error) | info |
COSMOS_DB_ENDPOINT | Cosmos DB endpoint | https://localhost:8081/ |
BACKEND_API_URL | Functions URL | http://localhost:7071 |
Next Steps
- Deployment Guide - Deploy to Azure
- Scaffold Guide - CRUD code generation details
add-auth with named schemes
swallowkit add-auth --scheme admin --provider swa and swallowkit add-auth --scheme lineUser --provider external-token add isolated scheme directories. Existing scheme names stop safely, and verifier/adapter files are never overwritten. Omitting --scheme retains the legacy single-provider flow.
