Skip to the page

Learn · Logic

Actions

An action pairs a deployed gatekeeper query with external or hosted handler code. PostgreSQL selects the rows the caller’s policies allow before invoking your handler as that caller.

In the schema
—

The lifecycle of an action#

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

Gatekeeper to handler

PostgreSQL filters rows as the caller before Napalm invokes your handler.

Every action call passes through four stages between the caller and your handler.

  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, is hidden by access policies 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. Save the secret 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 that binds 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.

Caller identity

Gatekeeper queries run as the caller without forwarding raw credentials.

Signed assertion

Permitted rows arrive with a 60-second token bound to the body.

Caller write-back

Token exchange issues a 60-second session scoped to that same caller.

Deploy a write-back query under your schema’s access policies, and run that query through the exchanged session.

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 output reaches the caller token by token. Request a stream by sending Accept: text/event-stream on POST /query/{name}, and Napalm relays each frame to the caller immediately. Handlers that return JSON continue to return JSON, and streaming callers handle both response shapes.

Streamed answers

Generator handlers stream yielded frames over SSE and finish with a bookmark.

Write a handler as an async function* beside its gatekeeper query. 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.

dbschema/queries/summarizeNote.edgeql
# Select the caller's note so the handler can summarize it.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,    // Fall back automatically when Claude Opus 5.5 declines a request.    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 ?? ''}`,      },    ],  })  // Yield each text chunk as an SSE frame while the model writes.  for await (const event of reply) {    if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') yield event.delta.text  }}

Pass Accept: text/event-stream over HTTP to stream frames live, and include Napalm-Bookmark when you want a causal session bookmark at the end of the stream.

Ask for a stream
# An empty Napalm-Bookmark starts a causal session and appends a final bookmark event.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 = ''// Read each streamed frame as it arrives. Handler libraries encode text chunks as JSON strings.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 per call. A handler can act as the caller only while the stream stays open.
Idle timeoutThe action’s timeoutSeconds limit applies between consecutive reads from the handler. An SSE 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_idleSent as an error frame when the handler produces no bytes within timeoutSeconds.
stream_timed_outSent as an error frame when the stream exceeds 120 seconds.
stream_brokenSent as an error frame when the handler connection closes unexpectedly.
action_failedSent as an error frame when the handler emits an error event 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#

Deployed actions expose the same authorization and response contract across HTTP, generated SDKs, agent protocols and background jobs.

SurfaceHow the action is exposedDry-run and live behavior
Project HTTP APIPOST /query/{name} returns 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 agentsExposed as an MCP tool (with outputSchema) and A2A skill, and 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 lists every project, organization and Control API quota on one page.

Type a word or two to search every docs page.