Agent Mode in Dev

Agent mode is usable today but still evolving. Verify available endpoints by calling GET / on the running agent server. Some details on this page may change between Stacktape releases.

Stacktape dev mode can start an HTTP API server alongside your local workloads and databases. This agent mode gives AI coding assistants — and any HTTP client — programmatic access to check workload status, trigger rebuilds, read log file paths, query local databases, and call AWS SDK commands, enabling automated edit-test-fix loops without manual intervention.

When to use

Agent mode is designed for workflows where an AI coding assistant drives the edit-test-fix loop. Enable it when:

  • AI-driven development — You're using Claude Code, Codex, Cursor, Windsurf, or another AI coding assistant to build your application. The assistant starts stacktape dev --agent as a shell command, then uses the HTTP API to check status, rebuild workloads, read the log file path, query local databases, call AWS SDK commands, and stop dev mode.
  • Automated test harnesses — You want a script to verify application behavior during development by hitting the status, env, or database endpoints.
  • Database inspection without client tools — You need to run SQL queries, check Redis keys, scan DynamoDB items, or search OpenSearch indices against local dev databases without installing separate database clients.

When NOT to use

  • Manual development — If you're editing code yourself and checking results in a browser, standard dev mode without --agent is simpler. The TUI output is optimized for human reading.
  • Production observability — Agent mode runs locally. For deployed stacks, use stacktape logs, stacktape metrics, or the Stacktape Console.
  • CI/CD pipelines — Use stacktape deploy directly in your pipeline. Agent mode is a development-time feature.

Starting agent mode

Add the --agent flag to the stacktape dev command to start the HTTP API server alongside your workloads.

stacktape dev --agent --agent-port 9900 --stage dev --region eu-west-1
FlagDescription
--agentEnables the agent HTTP API server alongside dev mode
--agent-portPort for the agent HTTP server
--stageStage used for dev mode and the .stacktape/dev-data/{stage}/ directory
--regionSession AWS region; /aws/sdk rejects any different region
--resourcesWhich workloads to run (all or comma-separated names)
--fresh-dbReset local database data on startup
--yesConfirms creating a project that does not exist yet. --agent never confirms it; without --yes the start fails with CONFIRMATION_REQUIRED

Once ready, Stacktape prints the agent URL and a summary of available endpoints. Local database data persists in .stacktape/dev-data/{stage}/ between runs — see reset scope before using --fresh-db. It resets prepared databases, including relay dependencies, and DynamoDB Local tables share storage.

Startup progress

A first start creates the account's dev network and the stage's dev stack and takes several minutes; a warm start takes seconds. While the agent starts, the command prints one JSONL event line per step with "phase": "DEV_STARTUP", so an assistant can tell a long start from a hung one:

eventTypeReports
DEV_SESSIONThe agent's port and token file first (detail.kind: "dev-agent"), the project, stage, region and config file the session resolved (detail.kind: "dev-target"), a heartbeat every 20 s, and "Dev session ready"
DEV_NETWORKCreating, updating or reusing the dev network
DEV_BOXStarting the dev box and connecting to it
DEV_STACKCreating or updating the dev stack; CloudFormation UPDATE_STACK events carry resource counts
DEV_WORKLOADEach workload starting and running, or its error (instanceId is the workload name)
DEV_DATABASEEach local database starting and running, or its error

If the start fails, the final result line carries the failure's own code and hints, for example CLI_DEV_STACK_CONFLICT with how to resolve it. Dev mode never updates or deletes a stack it did not create. A dev stack in ROLLBACK_COMPLETE requires explicit deletion before another start; UPDATE_ROLLBACK_COMPLETE permits another start. A stack still rolling back or in UPDATE_ROLLBACK_FAILED must finish or recover before an update can proceed. A Lambda build/deploy failure may leave the agent running with DEV_STARTED_WITH_FAILURES and ready: false; inspect status and rebuild it.

Authentication

The agent listens on 127.0.0.1 only and accepts a request only when it carries the session's token. Each stacktape dev --agent run creates a new random token and stores it in ~/.stacktape/dev-agent-tokens/{port}.token in your home directory (%USERPROFILE%\.stacktape\dev-agent-tokens\{port}.token on Windows). Because the file is named after the agent's port, any of your tools can find it from any directory. Only your user can read the file. Stacktape deletes it when the agent stops, and an agent that starts later removes the files of agents that were killed. The startup message and the AGENT_READY result print the file path, never the token.

Every request must send the token in an Authorization: Bearer header. POST requests must also send content-type: application/json. The examples on this page use these shell variables:

AGENT=http://127.0.0.1:9900
AUTH="Authorization: Bearer $(cat ~/.stacktape/dev-agent-tokens/9900.token)"
JSON='content-type: application/json'

curl -H "$AUTH" $AGENT/status

The agent refuses requests that a web page or another machine could send:

RequestResponse
No token or a wrong token401 UNAUTHORIZED
A Host header other than 127.0.0.1:{port} or localhost:{port}403 FORBIDDEN
Any request with an Origin header (sent by browsers)403 FORBIDDEN
A POST without content-type: application/json415 UNSUPPORTED_MEDIA_TYPE

The 401 response names the token file, so a coding assistant that forgot the header can recover on its own. stacktape dev stop and the MCP server read the token file themselves. dev stop stops the agent of the project in the current directory; pass --cwd <directory> for another project directory and --stage <stage> when several stages run.

AI coding assistants can call GET / on the agent server to receive a full endpoint listing dynamically. Use GET /?compact=true for a shorter LLM-oriented response — it includes the current phase, workload names, available local resources with their primary query/schema endpoints, core action templates (rebuild, logs, env, aws, stop), and a pointer to GET / for full docs.

Response format

Every agent endpoint wraps its result in a consistent JSON envelope so clients can handle success and error uniformly.

{
  "v": "1.0",
  "ok": true,
  "code": "OK",
  "message": "OK",
  "data": {}
}
FieldDescription
vEnvelope version (currently "1.0")
oktrue on success, false on error
codeMachine-readable status. Common values include OK, NOT_FOUND, VALIDATION_ERROR, INTERNAL_ERROR, ALREADY_EXISTS, AUTH_ERROR, and READ_ONLY_VIOLATION
messageHuman-readable description (optional — most responses include it, but not all)
dataEndpoint-specific payload (optional — present when the endpoint returns structured data)

Many not-found and validation errors include contextual hints in data, such as an available array of valid resource names or a hint string describing expected input. For example, referencing a non-existent workload returns the list of available workloads in data.available and a usage hint in data.hint. This makes it easy for AI agents to self-correct without extra calls.

Agent endpoints return a JSON envelope with v, ok, and code on every response; most successful responses also include message and endpoint-specific data. Response examples throughout this page may omit envelope fields like v for brevity.

Core endpoints

Status

The /status endpoint reports the current agent phase and a map of workload names to their local URLs (if running) or status strings. AI agents should poll this endpoint after starting dev mode and wait for "ready" before testing workload URLs.

curl -H "$AUTH" $AGENT/status
{
  "v": "1.0",
  "ok": true,
  "code": "OK",
  "data": {
    "phase": "ready",
    "ready": true,
    "failedWorkloads": [],
    "workloads": {
      "api": "http://localhost:3000",
      "worker": "running"
    },
    "sessionId": "0b6c…",
    "projectDirectory": "/home/me/my-app",
    "projectName": "my-app",
    "stage": "dev",
    "region": "eu-west-1",
    "pid": 12345
  }
}

sessionId, projectDirectory, projectName, stage and region identify the session; dev stop and the MCP server use them to find the agent of a project.

The phase value is one of starting, ready, rebuilding, stopping, or stopped. Phase becomes ready once dev mode has started every selected workload and local resource, and /stop moves it to stopping. The ready field is true only when the phase is ready, every workload is running, and the configuration file still matches the one the session started with. A container workload with a port is running once that port accepts connections, after a start and after a rebuild; one that does not within 120 seconds gets the status error. A workload that failed, crashed or failed to rebuild makes ready false and appears in failedWorkloads with its error, so an assistant waiting for ready never tests against a workload that is down or runs outdated code. When the configuration file changed, ready is false and restartRequired explains that dev mode has to restart (see Rebuild). A frontend whose running dev server printed an error, such as a request that failed in the app's code with its cause, stays running and keeps the session ready, because its server still serves: the error is in requestErrors (and the workload's requestError in verbose mode) until the next successful request, compile or code update.

If a workload fails while stacktape dev --agent is starting, the command stops the session, prints each failed workload with its error and the log file path, and exits with a non-zero code.

For detailed information including uptime, per-workload type/port/error data, local resource status, and the log file path, use verbose mode.

curl -H "$AUTH" "$AGENT/status?verbose=true"

The verbose response replaces the workload string map with an array of objects containing name, type, status, url, port, and error fields, plus a localResources array, uptime in seconds, and the logFile path. Workload status is one of pending, starting, running, error, or stopped. Local resource status uses the same values.

Logs

The /logs endpoint returns the path to the JSONL log file on disk. Logs are not streamed through the HTTP response — AI agents should read the file directly using standard tools like tail, grep, or jq.

curl -H "$AUTH" $AGENT/logs
{
  "v": "1.0",
  "ok": true,
  "code": "OK",
  "data": {
    "logFile": ".stacktape/dev-agent/9900-logs.txt",
    "format": "jsonl",
    "hint": "Use standard tools: tail -n 50 <logFile> | jq ."
  }
}

Each line in the log file is a JSON object with these fields:

FieldExampleDescription
ts"2025-03-15T14:30:15Z"When the line was produced. For a deployed function, the CloudWatch event time, not the time it was fetched
source"api", "dev"Workload or database that produced the line, or dev for dev mode itself
level"info", "warn", "error"Severity level
msg"Server started on :3000"Log message content, without terminal colors

Lines with "source":"dev" record dev mode's own lifecycle: startup steps, file changes, rebuilds started, finished or failed with the error, dev stack updates and dev box state. Grep them to see what dev mode did, for example whether a rebuild failed:

grep '"source":"dev"' .stacktape/dev-agent/9900-logs.txt

A restart keeps the previous session's lines. Each session appends to the file and starts with a "msg":"Dev session started" line whose session field names its session ID, project directory and stage. A file over 10 MB moves to <file>.1 when the next session starts.

Deployed dev functions keep their source maps and run with --enable-source-maps, so stack traces in the log point at your source files rather than the bundle.

View the last 50 lines:

tail -n 50 .stacktape/dev-agent/9900-logs.txt

Filter for errors only:

grep '"level":"error"' .stacktape/dev-agent/9900-logs.txt

Filter by a specific workload:

grep '"source":"api"' .stacktape/dev-agent/9900-logs.txt

This file-based approach is intentional — AI coding assistants already have file-reading tools, and tail -f provides real-time streaming without polling overhead.

Environment variables

The /env/{workload} endpoint returns the environment variables available to a specific workload. For Lambda functions, variables are fetched from the deployed AWS function configuration. A function that uses a local database shows that database's STP_* variables with the address of the dev box, through which the function reaches it. For containers and frontends, variables are read from the local runner state. A container whose image failed to build still shows the environment it would get. A workload that failed before dev mode prepared its environment, for example because the dev stack did not deploy, returns WORKLOAD_NOT_STARTED with its error.

curl -H "$AUTH" $AGENT/env/api
{
  "v": "1.0",
  "ok": true,
  "code": "OK",
  "data": {
    "workload": "api",
    "type": "function",
    "source": "aws",
    "envVars": {
      "STP_NOTES_TABLE_TABLE_NAME": "my-project-dev-notesTable",
      "AWS_REGION": "eu-west-1"
    },
    "count": 2
  }
}

Secret values are masked. The agent replaces the values of variables read from $Secret or $SsmParam, of variables whose names mark them as secret (such as PASSWORD, TOKEN, KEY, SECRET or AUTHORIZATION, which includes the AWS credentials of container workloads), and the password inside connection strings, for example postgresql://[redacted:credentials]@localhost:5432/app. Host names, private IP addresses, ports, database names and plain settings stay readable. A deployed dev function reaches a local database at the private address of the dev box, such as 10.230.4.17, so its /env shows that address. Public IP addresses are masked as [redacted:ip]. Your workloads still receive the real values.

Local databases never use the deployed database's secret. When the configured password is a directive such as $Secret('db', 'password'), dev mode generates a local password, keeps it in .stacktape/dev-data/{stage}/{resource}/password, and gives that same password to the container, the deployed dev functions and local workloads.

This endpoint is useful for debugging connectTo wiring. If an expected STP_* variable is missing, the workload's connectTo array likely doesn't reference the target resource. The response also includes the source field — "aws" for Lambda functions (fetched from the deployed function configuration) or "local" for other tracked workload types (currently container, hosting-bucket, and nextjs-web workloads, read from the local runner state).

Rebuild

After editing application code, trigger a workload rebuild to pick up the changes. Rebuilding a specific workload is faster than rebuilding all of them — AI agents should target only the workload whose code changed.

Rebuild a specific workload:

curl -X POST -H "$AUTH" -H "$JSON" -d '{}' $AGENT/rebuild/api

Rebuild all workloads at once:

curl -X POST -H "$AUTH" -H "$JSON" -d '{}' $AGENT/rebuild/all

The request answers after the workload has been rebuilt and, for a Lambda function, its new code deployed. A rebuild that fails, for example because of a syntax error, answers with ok: false, the code REBUILD_FAILED, the build error, the failed workloads and the log file path:

{
  "v": "1.0",
  "ok": false,
  "code": "REBUILD_FAILED",
  "message": "Rebuild failed. api: Build failed: Unexpected ;",
  "data": {
    "failedWorkloads": [{ "name": "api", "error": "Build failed: Unexpected ;" }],
    "logFile": ".stacktape/dev-agent/9900-logs.txt",
    "hint": "The failed workloads keep the status error. A failed function keeps its deployed code, and a container's error says whether its previous build still serves requests. Fix the error and rebuild again."
  }
}

The workload then has the status error and /status reports ready: false until a rebuild of it succeeds. Its previous code may still answer requests, so a test that passes while the workload is in error does not test your change.

When the rebuilt workload's files are also used by other workloads, such as a shared package in a monorepo, and changed after those workloads were last built, the result names them in staleWorkloads with the changed files, and the message says so: Rebuilt api. quote, report also use changed files (packages/shared/src/index.ts) and still run the previous build; rebuild them or rebuild all. With --watch, a change rebuilds every workload that uses the file.

A batch job runs in AWS from the image dev mode built when it started, and no rebuild builds it again. When that image also uses the changed files, the result names the job in staleRemoteImages and the message says to restart dev mode, which builds and pushes the image again. Images built from a Dockerfile or with Railpack report their files; a job whose image reports none is not named.

/rebuild/all leaves running frontends (Next.js, other SSR frameworks and static sites with a dev command) alone, because their dev servers load changed code themselves; the result lists them in leftRunning. A frontend whose server failed is restarted, and /rebuild/{name} restarts a frontend's server.

A rebuild deploys code only. When the Stacktape configuration file changed since dev mode started, the rebuild does nothing and answers with the code CONFIG_CHANGED_RESTART_REQUIRED. A change to the scripts section alone does not count: scripts run only on request, and the seed endpoint reads them from the file each time. It still counts when another part of the configuration reads the scripts with $This(). Stop dev mode and start it again: the start updates the dev stack with the new configuration. Formatting and comments do not count as a change. The refused workloads keep their status and their previous build keeps serving; ready stays false and restartRequired explains why. If you revert the configuration instead, the next rebuild, or with --watch the configuration check, rebuilds them.

With --watch, dev mode rebuilds a workload when one of its source files changes, through the same path, so a failed build sets the same error status and writes the error to the log file. It also watches the configuration file and sets restartRequired when it changes. stacktape dev --agent --watch reports the session started only after the watcher is running, so an edit made right after the start is rebuilt.

A workload builds one rebuild at a time. A request for a workload that is rebuilding waits for that build and then builds the current files, and further requests made meanwhile join it. Only the last build sets the workload's status, so the status always reflects the newest files.

Running stacktape dev --agent again while the session runs reports the same workloads, URLs and database ports as the start did. When the session waits for a restart, the command fails with CLI_DEV_RESTART_REQUIRED. When a workload in it failed, the command fails with DEV_STARTED_WITH_FAILURES, and while it still starts, with DEV_SESSION_NOT_READY; the session keeps running and the result's data carries it with ready: false and failedWorkloads.

Liveness check

GET /health returns the current agent phase and can be used as a simple liveness check. Unlike /status, /health does not include workloads or local resources — it only returns ok and the current agent phase inside the standard envelope. Use /status for full workload details.

curl -H "$AUTH" $AGENT/health

Resource health checks

Check the health of a specific local resource (database, cache). The agent monitors local resources automatically, but this endpoint triggers an immediate check and returns the result.

curl -H "$AUTH" $AGENT/health/myDb

The response includes name, type, port, host, and the status value returned by the local health monitor. If the resource name doesn't match any running local resource, the error response includes an available array listing valid resource names.

Stop

Gracefully shut down dev mode, all workloads, and all local resources.

curl -X POST -H "$AUTH" -H "$JSON" -d '{}' $AGENT/stop

Calling stop when the agent is already stopping or stopped returns success without side effects.

Database endpoints

Agent mode exposes database endpoints for PostgreSQL, MySQL/MariaDB, Redis, DynamoDB and OpenSearch. Most operate on local instances. DynamoDB query, scan, schema and sample can also read a table deployed by the dev stack and mark responses deployed: true; get, put, delete and reset require a local table. GET / lists endpoint groups for running local resources. Errors include available resource names where applicable.

The {name} path parameter in every database endpoint matches the resource name in your Stacktape configuration. If you reference a name that doesn't exist, the error response includes an available array listing the valid resource names.

The PostgreSQL, MySQL, and Redis command/query endpoints accept an optional confirm field. The startup documentation warns that destructive operations require {"confirm": true} in the request body — without it, the request is rejected. The DynamoDB and OpenSearch delete handlers do not accept a confirm parameter; they require the key or document identifier fields shown below.

PostgreSQL

Available when dev mode is running a local instance for a relational database with a PostgreSQL engine in your Stacktape configuration.

curl -X POST -H "$AUTH" -H "$JSON" $AGENT/postgres/myDb/query \
  -d '{"sql": "SELECT * FROM users LIMIT 10"}'
EndpointMethodDescriptionParameters
/postgres/{name}/queryPOSTExecute SQL{sql, limit?, timeout?, confirm?}
/postgres/{name}/schemaGETColumn types and constraints?tables=t1,t2 (optional filter)
/postgres/{name}/tablesGETList all tables
/postgres/{name}/explainPOSTQuery execution plan{sql, analyze?}
/postgres/{name}/indexesGETIndex definitions?table=name (optional filter)
/postgres/{name}/statsGETTable statistics?table=name (optional filter)
/postgres/{name}/sampleGETSample rows from a table?table=name&limit=5

MySQL

Available when dev mode is running a local instance for a relational database with a MySQL or MariaDB engine in your Stacktape configuration. The endpoint path uses /mysql/ for both MySQL and MariaDB resources.

curl -X POST -H "$AUTH" -H "$JSON" $AGENT/mysql/myDb/query \
  -d '{"sql": "SHOW TABLES"}'
EndpointMethodDescriptionParameters
/mysql/{name}/queryPOSTExecute SQL{sql, limit?, timeout?, confirm?}
/mysql/{name}/schemaGETColumn types and constraints?tables=t1,t2 (optional filter)
/mysql/{name}/tablesGETList all tables
/mysql/{name}/explainPOSTQuery execution plan{sql, format?} (format: "traditional", "json", or "tree")
/mysql/{name}/indexesGETIndex definitions?table=name (optional filter)
/mysql/{name}/statsGETTable statistics?table=name (optional filter)
/mysql/{name}/sampleGETSample rows from a table?table=name&limit=5

A PostgreSQL or MySQL query that writes rows (INSERT, UPDATE, DELETE) returns the number of rows it changed in affectedRows, as the database driver reports it. rowCount is the number of rows returned, or the number of changed rows when the statement returns none.

Redis

Available when dev mode is running a local instance for a Redis cache in your Stacktape configuration. The cmd field accepts a Redis command as a single string (e.g. "GET mykey", "SET user:1 '{\"name\":\"Alice\"}'").

curl -X POST -H "$AUTH" -H "$JSON" $AGENT/redis/myCache/command \
  -d '{"cmd": "GET session:user123"}'
EndpointMethodDescriptionParameters
/redis/{name}/commandPOSTExecute any Redis command{cmd, confirm?}
/redis/{name}/keysGETList keys matching pattern?pattern=*&limit=100
/redis/{name}/getGETGet value by key?key=name
/redis/{name}/ttlGETGet TTL for a key?key=name
/redis/{name}/infoGETServer info?section=memory (optional)
/redis/{name}/typeGETGet type of a key?key=name

DynamoDB

query, scan, schema and sample support both local tables and tables deployed by the dev stack (responses include deployed: true). get, put, delete and reset require a local DynamoDB table. Key parameters (pk, sk) are objects mapping attribute names to values — for example, {"userId": "123"}.

curl -X POST -H "$AUTH" -H "$JSON" $AGENT/dynamodb/notesTable/scan \
  -d '{"limit": 10}'
EndpointMethodDescriptionParameters
/dynamodb/{name}/queryPOSTQuery by partition/sort key{pk: {key: val}, sk?, index?, limit?}
/dynamodb/{name}/scanPOSTFull table scan{filter?, limit?}
/dynamodb/{name}/getPOSTGet single item{pk: {key: val}, sk?}
/dynamodb/{name}/putPOSTPut an item{item: {...}}
/dynamodb/{name}/deletePOSTDelete an item{pk: {key: val}, sk?}
/dynamodb/{name}/schemaGETTable key schema and indexes
/dynamodb/{name}/sampleGETSample items?limit=5

OpenSearch

Available when dev mode is running a local instance for an OpenSearch domain in your Stacktape configuration. Query bodies follow standard OpenSearch query DSL.

curl -X POST -H "$AUTH" -H "$JSON" $AGENT/opensearch/searchDomain/search \
  -d '{"query": {"match": {"title": "serverless"}}, "limit": 10}'
EndpointMethodDescriptionParameters
/opensearch/{name}/searchPOSTSearch documents{query: {...}, index?, limit?}
/opensearch/{name}/getGETGet document by ID?index=idx&id=docid
/opensearch/{name}/putPOSTIndex a document{index, id?, doc: {...}}
/opensearch/{name}/deletePOSTDelete a document{index, id}
/opensearch/{name}/indicesGETList all indices
/opensearch/{name}/mappingGETGet index mapping?index=idx
/opensearch/{name}/analyzePOSTAnalyze text with tokenizer{text, analyzer?, index?}
/opensearch/{name}/countGETCount documents?index=idx (optional)

Reset and seed local databases

An end-to-end test needs a known database state. Resetting deletes the data of the local databases and keeps their schema, so a test can start from empty tables without restarting dev mode. A seed script then writes the rows the test expects.

# Every local database, keeping the settings table
curl -X POST -H "$AUTH" -H "$JSON" $AGENT/reset/all -d '{"confirm": true, "keepTables": ["settings"]}'
# One database
curl -X POST -H "$AUTH" -H "$JSON" $AGENT/reset/myDb -d '{"confirm": true}'
# Run the seed script from the config
curl -X POST -H "$AUTH" -H "$JSON" $AGENT/scripts/seed/run -d '{}'
EndpointMethodDescriptionParameters
/reset/{name}POSTDelete the data of one local database, or of all with /reset/all{confirm: true, keepTables?}
/scripts/{script}/runPOSTRun a local-script from the config against the local databases{timeoutSeconds?}

A reset requires {"confirm": true} and changes only databases that dev mode runs on your machine; any other name returns NOT_FOUND. What it does per database type:

  • PostgreSQL: one TRUNCATE ... RESTART IDENTITY of every table in the database's own schemas, so identity columns start again at 1. Tables that extensions own, such as PostGIS's spatial_ref_sys, stay.
  • MySQL and MariaDB: TRUNCATE of every table of the configured database, which also resets AUTO_INCREMENT. A database without dbName uses the MySQL system database mysql. The reset refuses it, like the other system databases sys, performance_schema and information_schema, because they hold the server's users and state; set dbName on the engine to reset the application's data.
  • Redis: FLUSHALL.
  • DynamoDB: deletes every item; the table and its indexes stay.
  • OpenSearch: not supported. /reset/all skips it and names it in skipped; start dev mode with --fresh-db to delete its data.

Migration history tables stay in every SQL database, so the schema and the migration tool still agree after a reset: _prisma_migrations, __drizzle_migrations, knex_migrations, kysely_migration, pgmigrations, migrations, mikro_orm_migrations, SequelizeMeta, schema_migrations, flyway_schema_history, databasechangelog, alembic_version, django_migrations, goose_db_version, __EFMigrationsHistory and their lock tables. keepTables names more tables to keep. A kept table that references a reset table through a foreign key stops the reset with an error instead of being emptied with it.

The seed is a script from the scripts section of your config. It runs as a beforeDev hook would: its connectTo resources resolve to the local databases of this session, and the response carries its output. It is stopped after timeoutSeconds (default 50, at most 280) and then returns SCRIPT_TIMEOUT. The seed reads the script from the config file as it is now, so a script added or edited after dev mode started runs without a restart; a config file that no longer loads returns CONFIG_INVALID.

The seed endpoint refuses scripts that reference a deployed resource it knows about. It checks every string of the script, including directives nested in $Format and directives inside commands: connectTo and $ResourceParam must name databases running locally, and $CfResourceParam, $StackOutput, $CfStackOutput and $CfFormat are refused. Bastion scripts and scripts that assume a workload's role are refused. After the directives resolve, a script whose environment or commands contain the host or endpoint of one of the stack's deployed databases is refused before it runs.

A seed script is not a sandbox. It runs on your machine with your AWS credentials, so it can still reach deployed data in ways the check cannot see: a value read with $Secret, a URL written literally in the script or in an .env file it loads, or an AWS SDK call. Keep seed scripts pointed at the connection that dev mode gives them.

scripts: {
  seed: {
    type: 'local-script',
    properties: {
      executeCommand: 'npx prisma db seed',
      // STP_MAIN_DATABASE_CONNECTION_STRING points at the local database
      connectTo: ['mainDatabase']
    }
  }
}

Invoke a function with a test event

A function that no URL reaches, such as one triggered by a schedule, a queue, a topic or a stream, can be tested by invoking it with an event of that shape. /functions/{name}/invoke invokes a function of this session in AWS and returns what it returned.

# sessionId and stage from /status, the function's ARN from its deployedResources
curl -X POST -H "$AUTH" -H "$JSON" $AGENT/functions/nightly-report/invoke \
  -d '{"event": {"source": "aws.events", "detail-type": "Scheduled Event"}, "confirm": true,
       "expectedSessionId": "<sessionId>", "expectedStage": "dev",
       "expectedFunctionArn": "arn:aws:lambda:eu-west-1:123456789012:function:my-app-dev-nightly-report"}'

The function runs its deployed code with its own role, so it can change data and call other services: without "confirm": true the endpoint returns CONFIRMATION_REQUIRED and invokes nothing. Only a function this session runs is invoked, and only while it is running: another name returns NOT_FOUND with the session's functions, a function the session leaves out returns NOT_IN_SESSION, and a function whose rebuild failed returns WORKLOAD_NOT_RUNNING. Before it invokes, the agent reads the function and its environment in AWS: the payload it returns is masked with that environment, values read with $Secret or $SsmParam included, and with every other environment the session knows, as the logs are. A JSON payload is masked value by value before it is serialized, so a secret with a quote or backslash in it is masked too. When the function cannot be read, or Lambda reports an environment error or returns no environment for a function whose configuration sets variables, the endpoint returns MASKING_UNAVAILABLE and invokes nothing. The response has the function's functionArn, statusCode, its payload (at most 16 KB) and durationMs. Every request must name the session it checked: expectedSessionId and expectedStage as /status reports them, and expectedFunctionArn from its deployedResources. A request without them returns SESSION_BINDING_REQUIRED; when the agent runs another session or the function has another ARN, it returns DEV_SESSION_CHANGED. Neither invokes anything.

Masking keeps secret values from reaching an assistant's transcript or the logs by accident: values read with $Secret or $SsmParam and values under names such as PASSWORD, SECRET, TOKEN or KEY are replaced wherever they appear as they are, trimmed, line by line or escaped in JSON. It is not a boundary against code the assistant writes itself, which can always print a secret in another form, such as base64, URL-encoded or split up; those forms are not matched. A handler that throws returns FUNCTION_ERROR with functionError and the error payload, and a failed call to Lambda returns INVOKE_FAILED. What the function logs arrives in the session's logs. The /aws/sdk endpoint below stays read-only and refuses Invoke.

AWS SDK access

Agent mode provides access to read-only AWS SDK commands through the /aws/sdk endpoint. It sends only the reviewed read-only operations that aws call accepts; any other operation, including the Secrets Manager and SSM value reads, is rejected before a request is sent. Environment variable values and Cognito client secrets come back redacted, CloudFormation templates come back as their structure without any value, while other reads, such as log events and S3 objects, return application data as it is. The endpoint uses the dev agent IAM role. The role only reads, and only the resources of this dev stack in the session region: it identifies them by the stack-name tag CloudFormation puts on every resource, or by their identifiers in the template. CloudWatch metric and alarm reads cover the whole session region, because metrics belong to no stack. The HTTP endpoint accepts only reviewed read operations and adds resource filtering for Batch, whose read actions IAM cannot limit to the stack. If the role is missing or cannot be assumed after the IAM-propagation retry, the request fails; it never falls back to the developer's credentials. Restart dev mode to update the stack and role when needed.

curl -X POST -H "$AUTH" -H "$JSON" $AGENT/aws/sdk \
  -d '{"service": "lambda", "command": "GetFunctionConfiguration", "input": {"FunctionName": "my-app-dev-api"}}'

The request body accepts service (required), command (required), input (optional, defaults to {}), and region (optional, must equal the session region if supplied; another region is rejected). Use stacktape aws call with an explicit target for a different region. If service or command is missing, the agent returns a validation error with a hint showing the expected request shape.

To list all supported services and example commands:

curl -H "$AUTH" $AGENT/aws/sdk/services

GET /aws/sdk/services returns a successful envelope whose payload lists the accepted operations for each supported service, nested under data.data in the response. Use the running endpoint response as the authoritative list of valid service and command values before constructing /aws/sdk calls. The service list in the startup message and on this page is a summary; the endpoint response is always up to date.

Common AWS SDK calls for AI agents:

Use caseServiceCommandExample input
Read Lambda logslogsFilterLogEvents{"logGroupName": "/aws/lambda/fn", "filterPattern": "ERROR"}
Scan a DynamoDB tabledynamodbScan{"TableName": "tbl", "Limit": 10}
List S3 objectss3ListObjectsV2{"Bucket": "bkt", "Prefix": "uploads/"}
Check a queue's backlogsqsGetQueueAttributes{"QueueUrl": "https://…/q", "AttributeNames": ["All"]}
Describe a stackcloudformationDescribeStacks{"StackName": "my-stack"}

The startup message lists supported service identifiers: lambda, dynamodb, s3, logs, cloudformation, cloudwatch, sqs, sns, sfn, eventbridge, secretsmanager, ssm, sts, iam, ec2, ecs, ecr, rds, ses, cognito, apigatewayv2, xray, kinesis, firehose, and more. Call GET /aws/sdk/services on the running agent for the complete, up-to-date list.

Typical AI agent workflow

The core value of agent mode is the automated feedback loop: an AI agent writes code, checks if it works, reads any errors, fixes them, and rebuilds — all without human intervention.

1

Write config

AI writes or edits stacktape.ts based on your requirements

2

Start agent mode

AI runs stacktape dev --agent to boot workloads and databases

3

Write application code

AI implements handlers, services, and frontend code

4

Rebuild and test

AI calls POST /rebuild/{name}, checks status, reads logs, queries databases

5

Fix and iterate

AI reads error logs, fixes code, rebuilds — repeating until everything works

6

Deploy

Once working locally, AI deploys to AWS with stacktape deploy

Example session

An AI coding assistant building a notes API would follow this sequence:

  1. Write stacktape.ts with a Lambda function, DynamoDB table, and HTTP API Gateway trigger
  2. Start agent mode: stacktape dev --agent --agent-port 9900 --stage dev --region eu-west-1
  3. Poll GET /status until phase is "ready" and ready is true
  4. Write the handler code in src/handler.ts
  5. Call POST /rebuild/api to pick up the new code
  6. Test the endpoint by calling the workload URL from the status response
  7. If errors occur, get the log file path from GET /logs, then read it: tail -n 50 <logFile>
  8. Check GET /env/api to verify that STP_NOTES_TABLE_TABLE_NAME is injected
  9. Query the database directly via POST /dynamodb/notesTable/scan to verify stored data
  10. Fix code, rebuild, and test again until everything works
  11. Deploy to AWS with stacktape deploy

Here is a minimal Stacktape configuration that an AI agent might produce for this workflow:

export default defineConfig(() => {
  const notesTable = new DynamoDbTable({
    primaryKey: { partitionKey: { name: 'noteId', type: 'string' } }
  });

  const api = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/handler.ts'
    }),
    connectTo: [notesTable],
    events: [
      {
        type: 'http-api-gateway',
        properties: { httpApiGatewayName: 'apiGw', path: '/{proxy+}', method: '*' }
      }
    ]
  });

  const apiGw = new HttpApiGateway({});

  return {
    resources: { notesTable, api, apiGw }
  };
});

Tips for AI agent integrations

  • Poll status before testing — Wait for "phase": "ready" before making requests to workload URLs. Workloads may still be compiling during the starting phase.
  • Use compact docs — Call GET /?compact=true at the start of a session to discover available endpoints with minimal token usage. The full GET / listing is more detailed but token-heavy.
  • Rebuild selectively — POST /rebuild/{name} rebuilds only the named workload. Use it instead of /rebuild/all when you changed code in a single workload.
  • Check env vars early — GET /env/{workload} reveals whether connectTo is wired correctly before you start debugging application code.
  • Read logs from the file — The /logs endpoint returns a file path. Use tail, grep, or jq to filter the JSONL log file. Use tail -f for real-time streaming.
  • Inspect schemas before writing queries — Call the /schema or /tables endpoint to discover table and column names before writing SQL or DynamoDB queries.
  • Use database endpoints for verification — After writing data through your API, query the database directly to confirm it was stored correctly.

MCP server integration

For MCP-based assistant setup, see the Stacktape MCP server page. If your AI assistant supports the Model Context Protocol (Claude Code, Cursor, Windsurf), the MCP server provides a higher-level integration layer. Agent mode's HTTP API is the lower-level alternative that works with any tool capable of making HTTP requests. The MCP stacktape_dev tool calls this API for the assistant, so it never handles the token file: its status, logs, rebuild, query, tables, reset_db, seed, invoke, env, aws and stop actions map to the endpoints on this page. Without a session ID it acts only on sessions of its own project directories, so an assistant in one worktree cannot rebuild or reset another worktree's session by accident.

Security

The agent can run SQL against your local databases, rebuild and stop workloads, and call AWS read operations with the dev agent's credentials. Only programs running as your user on this machine can call it:

  • It listens on 127.0.0.1 only, so other machines on your network cannot connect.
  • Every request needs the session token from ~/.stacktape/dev-agent-tokens/{port}.token, which only your user can read.
  • It refuses requests with an Origin header or a foreign Host header, so a web page cannot call it, even through DNS rebinding.
  • POST requests must be JSON, which a web page cannot send to another site without the browser asking the agent first.

Do not forward the agent port to other machines, and do not paste the token into chats or logs.

The /aws/sdk endpoint fails closed when the dev agent role is missing or cannot be assumed; it never falls back to developer credentials. The role reads only this dev stack's resources in the session region; CloudWatch metric and alarm reads cover the whole session region. The endpoint accepts only reviewed read operations and adds resource filtering for Batch. See AWS SDK access for the boundary.

Agent Mode in Dev FAQ

Should I use agent mode or the Stacktape MCP server?

Both work with assistants like Claude Code, Cursor, and Windsurf. Agent mode is a plain HTTP API that any tool can call with curl or HTTP libraries — no protocol integration needed, so it suits custom tooling or any client that can make HTTP requests. The MCP server uses the Model Context Protocol standard that those assistants support natively, providing a more integrated, higher-level layer. If your AI tool supports MCP, prefer the MCP server; reach for agent mode when you need raw HTTP access.

What databases can I query through the agent API?

Agent mode exposes typed HTTP endpoints for five local resource types started by dev mode — PostgreSQL, MySQL/MariaDB, Redis, DynamoDB, and OpenSearch — so agents can inspect schemas, run queries, and verify data without installing separate database client tools. Each type has its own endpoint group (SQL engines get query/schema/tables/explain/indexes/stats/sample, plus key-value and document operations for Redis, DynamoDB, and OpenSearch). GET / lists only the endpoint groups for resources currently running in the session.

Is my data persisted between agent mode sessions?

Yes. The startup message confirms local database data is stored in .stacktape/dev-data/{stage}/ and survives restarts. To empty the databases while dev mode runs, call /reset; it keeps the schema. The --fresh-db flag deletes the data directories when dev mode starts, including the schema.

Are destructive database operations safe during AI sessions?

The PostgreSQL, MySQL, and Redis query/command endpoints accept an optional confirm field. The startup documentation warns that destructive operations require {"confirm": true} — without it, the request is rejected. /reset always requires it. DynamoDB and OpenSearch delete handlers do not accept a confirm parameter; they require the key or document identifier fields directly. All of these endpoints reach only the databases dev mode runs locally, except that the DynamoDB query, scan, schema and sample endpoints also read a table the dev stack deploys (a remote resource). Their answer then has deployed: true, and the write endpoints refuse that table.

What happens if a workload fails?

If a function fails to build or deploy while stacktape dev --agent starts, the session keeps running and the function keeps its previous code. The command exits with DEV_STARTED_WITH_FAILURES, names the function and its error, and its result carries the session with ready: false. Fix the code and call POST /rebuild/{name}. Any other workload that fails during the start stops the session, and the command exits with CLI_DEV_WORKLOAD_FAILED; fix the code and start again. After the start, a workload that crashes or fails to rebuild does not stop the session: /status reports it in failedWorkloads with its error, and ready stays false. Fix the code and call POST /rebuild/{name} to retry without restarting the session.

Why does an /aws/sdk call fail or return access-denied?

The /aws/sdk endpoint uses the dev agent IAM role. Most resource permissions are limited to the stack, but CloudWatch metrics/alarm and API Gateway reads are account-wide within the session region; CloudWatch Logs reads use stack-name log-group ARN patterns. Only Batch gets additional resource filtering at the HTTP endpoint. A missing role or failed AssumeRole makes the call fail; it never falls back to your credentials. IAM can also deny a resource the role cannot read. Restart dev mode to update a missing or outdated role. A call is also rejected, without reaching AWS, when the operation is not a reviewed read-only one; the error lists the operations accepted for that service. The endpoint supports a broad set of services (lambda, dynamodb, s3, logs, cloudformation, sqs, sns, sfn, and more); call GET /aws/sdk/services for the authoritative, up-to-date list of valid service and command values before constructing a call.