Skip to the page

Learn · Logic

Actions

An action is a deployed query with a handler. The query selects the rows the caller’s access allows, then your handler does the work as that caller.

In the schema
—

The lifecycle of an action#

Actions bridge transactional queries and external side effects without duplicating authorization checks in route middleware. Queries read and mutate rows inside PostgreSQL, while external work such as charging a card, sending an email, calling a model or provisioning an external resource runs outside a SQL transaction.

Gatekeeper query to verified handler

PostgreSQL runs the gatekeeper query as the caller first and returns 403 nothing_found on zero rows without waking your code. Permitted rows dispatch with a signed ES256 assertion, and follow-up call.db() writes stream live under the same access rules.

  1. The caller invokes the deployed action name

    Any caller invokes POST /query/refundOrder over HTTP, through a generated client SDK, from your project CLI, from an MCP or A2A agent or via an ext::napalm::Job.

  2. PostgreSQL runs the gatekeeper query as the caller

    Napalm executes refundOrder.edgeql under the caller’s identity, session or AgentGrant. If the query returns zero rows, Napalm immediately answers 403 nothing_found and never wakes or contacts your handler. Zero rows means the record does not exist, belongs to another tenant or fails a state filter.

  3. Napalm dispatches the rows with a 60-second ES256 assertion

    Napalm posts the matching rows to your hosted handler or external HTTPS URL with an Authorization: Bearer JWT signed by the branch’s ES256 keypair. The caller never receives the gatekeeper rows directly.

  4. The handler does the external work and optionally writes back via call.db()

    Your handler performs the external work and returns JSON as the action’s response. To record the outcome in the database, the handler trades the assertion for a 60-second caller-scoped session.

Gatekeeper queries and answer schemas#

Write the gatekeeper query to select every field your handler needs, such as a Stripe charge ID or recipient email, and filter for the exact state in which the action is legal. The handler’s JSON output replaces the query’s rows as the caller’s response, so internal fields selected by the gatekeeper query stay private to your handler.

dbschema/queries/refundOrder.edgeql
# Refund a paid order owned by the callerselect Order {  id,  total_cents,  currency,  stripe_charge_id,}filter .id = <uuid>$order  and .status = OrderStatus.Paid  and exists .stripe_charge_id

Supply an optional OpenAPI 3.0 answerSchema so napalm generate, GET /openapi.json and MCP tool outputSchema definitions expose your handler’s exact return type. The schema is limited to 16 KiB, marks nullable fields with nullable: true and cannot use $ref.

refund-answer.json
{  "type": "object",  "required": ["refundId", "status"],  "properties": {    "refundId": { "type": "string" },    "status": { "type": "string", "enum": ["refunded"] }  }}
Attach to a hosted handler or external HTTPS endpoint
# Option A: Deploy a sleeping hosted handler (attaches the action automatically)napalm queries push notesnapalm handlers deploy notes # Option B: Point the action at an external HTTPS endpoint you already runnapalm queries push notesnapalm actions add notes refundOrder https://api.example.com/actions/refundOrder \  --answer-schema refund-answer.json \  --timeout 20# Prints the action secret once; store as NAPALM_ACTION_SECRET.

External HTTPS handler URLs must match your branch’s allowed-hosts list when host restrictions are enabled. See Actions in the Control API for managing actions and allowed hosts programmatically.

Call verification#

Hosted handlers verify calls automatically in the runtime. When you serve actions from your own Next.js route, Cloudflare Worker, Deno or Bun server or Go, Rust or Python backend, mount handleCalls from napalm-client or the equivalent in your language SDK.

app/actions/[action]/route.ts
import Stripe from 'stripe'import { handleCalls } from 'napalm-client' const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!) type RefundRow = {  id: string  total_cents: number  currency: string  stripe_charge_id: string} export const POST = handleCalls(  {    async refundOrder(call) {      // 1. ES256 JWKS signature, audience, expiry, and SHA-256 body hash are verified.      // 2. call.rows holds only rows the caller's access policies allowed.      const [order] = call.rows as RefundRow[]       // 3. Use call.job?.id on background retries so external APIs stay idempotent.      const refund = await stripe.refunds.create(        { charge: order.stripe_charge_id, amount: order.total_cents },        { idempotencyKey: call.job?.id ?? `refund:${order.id}` },      )       // 4. Exchange the assertion for a 60-second session bound to the caller.      const db = await call.db()      const res = await db.fetch('https://notes.napalmdata.com/query/markOrderRefunded', {        method: 'POST',        headers: { 'Content-Type': 'application/json' },        body: JSON.stringify({ variables: { order: order.id } }),      })      if (!res.ok) throw new Error(`Failed to record refund: ${res.status}`)       return { refundId: refund.id, status: 'refunded' as const }    },  },  {    address: 'https://notes.napalmdata.com',    handlers: 'https://api.example.com/actions',    secret: process.env.NAPALM_ACTION_SECRET,  },)

handleCalls fetches and caches your branch’s public keys from /.well-known/jwks.json and checks the ES256 signature, issuer, audience URL and expiration window. Before parsing JSON, handleCalls verifies the raw request body’s SHA-256 digest.

The ES256 assertion#

Every handler invocation arrives as an HTTP POST with a 60-second ES256 JWT in Authorization: Bearer. Napalm never forwards the caller’s raw session token or service key to the handler.

HTTP delivery sent to your handler
POST /actions/refundOrder HTTP/1.1Host: api.example.comAuthorization: Bearer eyJhbGciOiJFUzI1NiIsImtpZCI6ImJyYW5jaC1tYWluIn0…Content-Type: application/json {  "action": "refundOrder",  "variables": { "order": "8f2c1e64-0b7a-4f4e-9d2b-3a6c5e1f7d90" },  "data": [    {      "id": "8f2c1e64-0b7a-4f4e-9d2b-3a6c5e1f7d90",      "total_cents": 4200,      "currency": "usd",      "stripe_charge_id": "ch_3Q9xLm2eZvKYlo2C"    }  ]}

ES256 JWT assertion claims

iss / audstring
The branch’s base URL as issuer and your exact HTTPS handler URL as audience.
substring
Caller principal, either the user’s ext::auth::Identity UUID or key:<hash>.
napalm_callerstring
"person" for a user session or OAuth agent grant, or "key" for a service key.
napalm_grantstring
The ext::napalm::AgentGrant UUID when called through an OAuth 2.1 agent grant.
actobject
The OAuth client actor { "sub": client_id } per RFC 8693 on an agent call.
napalm_read_onlyboolean
Whether the caller’s credential is restricted to read-only operations.
napalm_actionstring
Name of the deployed action being invoked.
napalm_body_sha256string
Hex SHA-256 digest of the raw request body bytes, binding the token to that exact payload.

Writes back as the caller#

Handlers hold no standing service key to record results in your database. Calling await call.db() trades the signed assertion and your action secret at POST /sign-in/agents/token (RFC 8693 OAuth 2.0 Token Exchange) for a 60-second NapalmClient bound to the originating caller.

Verified caller identity

The caller’s ext::auth::Identity, AgentGrant and read-only cap scope the gatekeeper query without forwarding raw bearer credentials.

Signed invocation envelope

Permitted rows arrive sealed with a 60-second ES256 assertion bound to the handler URL and raw napalm_body_sha256 payload digest.

Caller-scoped hosted handler

An active hosted handler trades the assertion at POST /sign-in/agents/token for a 60-second call.db() client bound to that exact caller.

dbschema/queries/markOrderRefunded.edgeql
# Record completed refund under the caller's own access policyupdate Orderfilter .id = <uuid>$orderset { status := OrderStatus.Refunded }
Underlying RFC 8693 token exchange · curl
curl https://notes.napalmdata.com/sign-in/agents/token \  -H "Authorization: Bearer $NAPALM_ACTION_SECRET" \  -d grant_type=urn:ietf:params:oauth:grant-type:token-exchange \  -d subject_token_type=urn:ietf:params:oauth:token-type:jwt \  --data-urlencode "subject_token=$ASSERTION"
User and grant scope
A human caller yields a 60-second session for that person’s Identity. An OAuth 2.1 agent call inherits the exact AgentGrant and act claim. A revoked or expired grant is refused immediately.
Read-only inheritance
Actions default to isWrite: true, and read-only callers cannot invoke a write action. If you mark an action isWrite: false, a read-only caller’s exchanged call.db() token stays strictly read-only.
No recursive MCP loops
Exchanged 60-second tokens work on /query and /uploads. /mcp rejects exchanged tokens, so a handler cannot recursively invoke agent tool loops.

Streamed answers#

A handler can stream its response as server-sent events so model tokens reach the caller as they are generated. Request a stream by sending Accept: text/event-stream on POST /query/{name}, and Napalm relays each frame from the handler as it arrives. Handlers that return JSON continue to return JSON, and streaming callers handle both response shapes.

Streamed SSE action frames and causal bookmark

Sending Accept: text/event-stream relays each yielded value from an async function* handler over an SSE conduit and closes causal sessions with a final bookmark frame.

dbschema/queries/summarizeNote.edgeql
# The caller's note, for the model to summarize.select Note { title, body }filter .id = <uuid>$note
handlers/summarizeNote.ts
import Anthropic from '@anthropic-ai/sdk'import type { HandlerContext } from 'napalm-client' const claude = new Anthropic() export async function* summarizeNote(call: HandlerContext<{ title: string; body: string | null }>) {  const [note] = call.rows  const reply = claude.beta.messages.stream({    model: 'claude-opus-5-5',    max_tokens: 64000,    // A fallback model answers a request Claude Opus 5.5 declines.    betas: ['server-side-fallback-2026-07-01'],    fallbacks: 'default',    messages: [      {        role: 'user',        content: `Summarize this note in three sentences.\n\n${note.title}\n\n${note.body ?? ''}`,      },    ],  })  // One frame for each piece of text, sent as the model writes it.  for await (const event of reply) {    if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') yield event.delta.text  }}

Write a handler as an async function* to stream. Every yielded value becomes a JSON-encoded SSE frame. Napalm forwards Accept: text/event-stream to the handler only when the caller asks for a stream, while jobs, agents and JSON callers receive all yielded values collected into one JSON array. Stage ANTHROPIC_API_KEY with napalm handlers secrets set before the first call.

Ask for a stream
# An empty Napalm-Bookmark starts a session: the stream ends with the session's bookmark.curl -N https://notes.napalmdata.com/query/summarizeNote \  -H "Authorization: Bearer $SESSION" \  -H "Accept: text/event-stream" \  -H "Content-Type: application/json" \  -H "Napalm-Bookmark;" \  -d '{ "variables": { "note": "8f2c1e64-0b7a-4f4e-9d2b-3a6c5e1f7d90" } }'
The streamed answer
HTTP/1.1 200 OKContent-Type: text/event-streamNapalm-Action: summarizeNoteNapalm-Bookmark: 2026.11.1:7465436217498812345:3:2A/5F01C800 data: "The launch moves to March 3." data: " Maya owns the checklist." event: bookmarkdata: 2026.11.1:7465436217498812345:3:2A/5F01C8E0

Napalm reserves two event names. When a caller sends Napalm-Bookmark to maintain a causal session, a completed stream closes with a bookmark frame whose payload covers every write the handler made (mirroring the Napalm-Bookmark header on JSON responses). Sending that bookmark on the next request guarantees reads observe the handler’s writes. A failure mid-stream closes with one error frame containing a code and message. A session stream that ends with a bookmark frame and no error frame finished cleanly, whereas a stream that closes without a bookmark frame was cut short in transit.

summary.ts
import { napalm } from './napalm' let summary = ''// Each frame as the frame arrives. The handler libraries send text as a JSON string.for await (const frame of napalm.streamAction('summarizeNote', { note: noteId })) {  if (typeof frame.json === 'string') show((summary += frame.json))}

streamAction in napalm-client and napalm_client requests the stream, yields each frame as it arrives and advances the client’s session bookmark automatically. An error frame throws NapalmError (NapalmException in Dart), a JSON response arrives as a single answer frame and a truncated stream throws stream_ended. In React, useStreamedAction accumulates the text in place. See the copilot guide for a complete example.

Limit or errorBehavior
Stream length120 seconds from the call to the handler. A handler acts as the caller for that long at most.
SilenceThe action’s time limit between two reads of the handler’s bytes. A comment line counts as a read.
Frame size1 MiB for one frame and 16 MiB for the whole stream. Past either cap, the stream ends with answer_too_large.
406 stream_not_requestedThe handler streamed to a caller that asked for JSON. Jobs and agents never ask for a stream.
502 invalid_streamThe handler answered text/event-stream with a status other than 200.
stream_idleAn error frame. The handler sent nothing for the action’s time limit.
stream_timed_outAn error frame. The stream ran past 120 seconds.
stream_brokenAn error frame. The handler’s answer ended early.
action_failedAn error frame. The handler sent an error frame without a string code.

Streams do not resume. If a connection drops, call the action again to run it from the start.

Calls from HTTP, SDKs, the CLI and MCP#

SurfaceHow the action is exposedDry-run and live behavior
Project HTTP APIPOST /query/{name}, returning the handler’s status, content type and body with Napalm-Action: {name}.Dry-run and live behavioris_dry_run: true runs only the gatekeeper query and never calls the handler.
Generated SDKsTyped function returning answerSchema (or unknown if omitted).Dry-run and live behaviorLive subscriptions (subscribe) are refused with action_not_live.
MCP and A2A agentsAn MCP tool (with outputSchema) and A2A skill, hidden from read-only callers when isWrite is true.Dry-run and live behaviorAgents cannot dry-run an action. Non-2xx responses return structured tool errors.
Background jobsinsert ext::napalm::Job naming the action. Napalm passes job: { id, attempt } in the body.Dry-run and live behaviorJobs retry with exponential backoff if the query or handler fails. A gatekeeper result of 0 rows completes the job cleanly.

Limits and error codes#

Limit or errorBehavior
Actions per branchUp to 128 actions per branch. Branches created for PRs start with no actions.
Handler timeout1 to 30 seconds (timeoutSeconds). napalm actions add defaults to 10 s, and a hosted handler defaults to 30 s. Up to 120 s total when invoked from a job.
Payload sizesGatekeeper payload to handler capped at 64 KiB (413 request_too_large). Handler response capped at 1 MiB (502 answer_too_large).
403 nothing_foundThe gatekeeper query returned zero rows for the caller. The handler was not called.
403 read_onlyA read-only credential or agent grant attempted to call an action with isWrite: true.
502 action_unreachableThe handler could not be reached or exceeded timeoutSeconds.

Limits gathers every limit of a project, an org and the control API on one page.

Type a word or two to search every docs page.