/volcano:volcano-functionsfrom volcano
Use for Volcano server-side Functions and privileged or secret-bearing logic, including function invocation and visibility, streamed responses and server-sent events, functions served under a frontend path, generators such as QR codes or PDFs, outbound third-party APIs, orchestration, scheduled processing, and file or image processing.
Ships in volcano. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Use Volcano Functions for privileged, secret-bearing, or orchestration-heavy backend logic. This skill is self-contained: invocation, response shape, handler templates, env, and error handling are embedded.
volcano-database's "Direct Postgres Access" section — requires the application_name=volcano_user_access:{user_id} rewrite to stay RLS-safe).Every invocation returns { data, status, headers, version, error }.
status — HTTP status from the function response.headers — response headers.version — value of X-Volcano-Version (<version> in production, <env>-<version> otherwise).error — present on transport/runtime failure or non-2xx status; check this before consuming data.const { data, status, version, error } = await volcano.functions.invoke('send-welcome-email', {
template: 'welcome',
recipientId: user.id,
});
if (error) {
console.error('Function failed:', error.message);
return;
}
interface DashboardStats { totalUsers: number; activeToday: number; revenue: number; }
const { data, status, headers, version, error } = await volcano.functions.invoke<
{ timeframe: string },
DashboardStats
>('get-dashboard-stats', { timeframe: 'last-30-days' });
const { data, status, version, error } = await volcano.functions.invoke('health-check');
Functions automatically receive the caller's identity in event.__volcano_auth:
auth.user_id — the authenticated user's id.auth.email — the user's email.auth.role — the user's role (if set).auth.project_id — the project this user is acting in.auth.access_token — server-injected bearer token; use to call other Volcano APIs on the user's behalf.If __volcano_auth is absent, the request is unauthenticated.
Each function has a visibility level. New functions are private, so a
browser app's volcano.functions.invoke(...) gets 404, as if the function
didn't exist, until you choose a wider level. invoke resolves the name
first, and that lookup answers 404 to any caller the level refuses, so an
anon key on an authenticated function also gets 404 by name. Only a
direct invoke by function id answers it 403.
| Visibility | Who can invoke it | Use it for |
|---|---|---|
private (default) | Service keys and schedulers | Scheduled jobs, admin tasks, functions only your server code calls |
authenticated | Also the project's signed-in users, including anonymous sign-ins | Functions your app calls on behalf of a signed-in user |
public | Also anon keys with functions.invoke, and frontend function routes | Code that must work before sign-in: public forms, webhooks, a session endpoint behind a frontend route |
authenticated.authenticated still lets any signed-in user call the function. Check
__volcano_auth and enforce ownership in the handler or through RLS.public function is reachable without a user. Validate every input and
never trust identity claims from the request body.volcano-config.yaml (see volcano-platform) or with the
CLI. Changing a level is a permission change: ask the user before doing it
on a cloud project.# volcano-config.yaml
version: 1
functions:
- name: get-my-posts
visibility: authenticated
- name: nightly-report
visibility: private
volcano functions update get-my-posts --visibility authenticated # local
volcano cloud functions update get-my-posts --visibility authenticated # cloud
--private is no longer accepted: it used to mean what authenticated means
now. Write the level you want.
A frontend function route forwards every request under a path of your
frontend, such as /api/session, to an HTTP-mode function. The browser stays
on the frontend's origin, so the function can keep a session in HttpOnly
cookies and the page never handles an access token.
# volcano-config.yaml
version: 1
functions:
- name: session
visibility: public # routes require public
invocation_mode: http
frontends:
- name: web
function_routes:
- function: session
path_prefix: /api/session
strip_prefix: true # GET /api/session/me reaches the function as /me
public with invocation_mode: http. Volcano refuses
the route otherwise, and refuses to make a routed function non-public.__volcano_auth is never set,
even when the visitor sends a valid token. The function authenticates its
callers itself, typically by exchanging credentials with Volcano auth and
keeping the tokens in __Host- cookies with
Path=/; Secure; HttpOnly; SameSite=Strict and no Domain.Sec-Fetch-Site is
neither same-origin nor none (a page the visitor opened directly), GETs
included. Older browsers omit the header; then refuse an Origin that is
present and isn't the site's own. Require a CSRF token on every
state-changing request.event.method, event.path, event.headers,
and event.body (base64 when event.is_base64_encoded is true). Header
names arrive in canonical case (Sec-Fetch-Site) and every value is an
array, so look names up case-insensitively and join the values, as the
documented session example does. Return several cookies through
multiValueHeaders:
{ statusCode: 200, multiValueHeaders: { "Set-Cookie": [a, b] }, body }.volcano cloud frontends routes create web --path /api/session --function session --strip-prefix.
Locally (CLI 0.45.0+), use volcano frontends routes create ..., or
declare function_routes in the manifest and run volcano deploy, which
deploys the frontend and applies its routes.volcano docs search "function routes" finds the full session example,
including sign-in, sign-out, and the CSRF check.An HTTP-mode Node.js function can send its response while it runs:
server-sent events, model tokens, progress lines. Export
config = { supportsResponseStreaming: true } from the handler module and
return a Response whose body is a stream, or the usual response object with
an async iterable body:
# volcano-config.yaml
version: 1
functions:
- name: events
visibility: public
invocation_mode: http # streaming needs HTTP mode
http_auth_mode: none
// volcano/functions/events.js
exports.config = { supportsResponseStreaming: true };
exports.handler = async () => {
async function* events() {
for (let tick = 1; tick <= 5; tick++) {
yield `data: ${JSON.stringify({ tick })}\n\n`;
await new Promise((resolve) => setTimeout(resolve, 1000));
}
yield 'event: done\ndata: {}\n\n';
}
return new Response(ReadableStream.from(events()).pipeThrough(new TextEncoderStream()), {
headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' },
});
};
config export, returning a stream fails the invocation with a
500, and the function's logs name the export. A callback-style handler,
(event, context, callback), cannot opt in. A handler that returns an
ordinary response answers normally.done that lets a client tell a finished
stream from a cut one.http_auth_mode: none, anyone who finds the URL or route runs the
function. Before streaming anything that costs per call, such as model
tokens, authenticate the caller and check Sec-Fetch-Site as a routed
function does (see the function routes section above).volcano.functions.invoke(...) and
volcano functions invoke return one complete JSON result, and a stream
returned to an RPC call fails with
a streamed response needs the function's invocation_mode set to http.
Read a stream over plain HTTP from the function's invoke_url or a frontend
function route.functions.response_streaming capability in GET /capabilities
(curl "$VOLCANO_API_URL/capabilities"). Where it is unavailable, the URL
still answers, with the same status, headers, and body, but sends the whole
response once the function finishes, and a response over 6 MiB, headers
included, fails the invocation. Frontend function routes and
volcano start stream either way, so serve browser-facing events through a
frontend function route.Consume the stream with curl -N, which prints each event as it arrives
instead of buffering the output:
curl -N "$INVOKE_URL/events"
From Node.js, read the body as it arrives:
const response = await fetch(`${process.env.INVOKE_URL}/events`);
const decoder = new TextDecoder();
for await (const chunk of response.body) {
process.stdout.write(decoder.decode(chunk, { stream: true }));
}
A browser reads the same events with EventSource behind a frontend function
route, where no Authorization header is needed. EventSource reconnects
whenever a stream ends, which runs the function again, so close it on the final
event and on an error, which is how a stream cut at the time limit arrives:
const source = new EventSource('/api/events');
source.onmessage = (event) => render(JSON.parse(event.data));
source.addEventListener('done', () => source.close());
source.onerror = () => source.close();
In http_auth_mode: volcano, send the Authorization header as for any
HTTP-mode call, which EventSource cannot do; use fetch there. volcano docs search "stream a response" finds the full guide.
Volcano Functions return a standard response shape: handlers return { statusCode, body, headers? } where body is a string. Use JSON.stringify(...) to encode JSON responses. Use statusCode: 200 for all successful responses (not 201/202) — volcano functions invoke treats any non-200 status as a failed invocation, so a 201 Created reads as a failure to the CLI and to callers checking status; put the created resource in the body with 200.
Each handler lives directly under volcano/functions/: a file (hello.js deploys as hello) or a directory with an entry file (checkout/index.js deploys as checkout). Names starting with _ hold shared code.
Volcano compiles TypeScript, JSX included, when it builds the function, so you deploy .ts or .tsx source with no build step of your own. .ts, .mts and .cts need volcano CLI 0.76.0 or later, and .tsx needs 0.78.0 or later (volcano --version); older CLIs skip those files without deploying them.
volcano/functions/<name>.ts (or .mts, .cts, .tsx) and volcano/functions/<name>/index.ts (or index.mts, index.cts, index.tsx)..tsx ranks last: hello.ts beside hello.tsx, or index.ts beside index.tsx, deploys the .ts file, so rename or delete it to deploy the .tsx. hello.ts beside hello.mts stops the deploy.*.d.ts) or a handler nested deeper, such as volcano/functions/<name>/src/index.ts.tsc --noEmit yourself before deploying, with typescript and @types/node installed and a tsconfig.json whose include covers volcano/functions/**/* (so .mts, .cts and .tsx handlers are checked too). For .tsx, also install @types/react (and @types/react-dom when you import react-dom/server) and set "jsx": "react-jsx"..tsx compiles JSX with React's automatic runtime, so don't import React, but declare react (and react-dom for react-dom/server) in package.json. A directory function's own tsconfig.json can choose other JSX settings, such as "jsxImportSource": "preact"; a single-file handler uploads without one. A root tsc --noEmit ignores that nested tsconfig.json, so type-check such a directory on its own with tsc --noEmit -p volcano/functions/<name>.@volcano.dev/sdk, in volcano/functions/package.json (or the function directory's own package.json). Volcano installs it at build time; an undeclared import fails at runtime with Cannot find package.// volcano/functions/welcome-page/index.tsx — returns server-rendered HTML
import { renderToStaticMarkup } from 'react-dom/server';
function Welcome({ name }: { name: string }) {
return <h1>Welcome, {name}!</h1>;
}
export const handler = async (event: { name?: string }) => ({
statusCode: 200,
headers: { 'content-type': 'text/html; charset=utf-8' },
body: '<!doctype html>' + renderToStaticMarkup(<Welcome name={event.name ?? 'friend'} />),
});
Beside it, volcano/functions/welcome-page/package.json declares the packages Volcano installs:
{ "dependencies": { "react": "^19.0.0", "react-dom": "^19.0.0" } }
// volcano/functions/hello.js
exports.handler = async (event) => {
const name = event.name || 'World';
return {
statusCode: 200,
body: JSON.stringify({ message: `Hello, ${name}!` }),
};
};
// volcano/functions/_shared/client.ts — shared code, bundled into each function that imports it
import { VolcanoAuth } from '@volcano.dev/sdk';
export function createClient(auth?: { access_token?: string }): VolcanoAuth {
const volcano = new VolcanoAuth({
apiUrl: process.env.VOLCANO_API_URL!,
anonKey: process.env.VOLCANO_ANON_KEY!,
accessToken: auth?.access_token,
});
volcano.database(process.env.VOLCANO_DATABASE!);
return volcano;
}
// volcano/functions/get-my-posts.ts
import { createClient } from './_shared/client';
export const handler = async (event: { __volcano_auth?: { access_token?: string } }) => {
const auth = event.__volcano_auth;
if (!auth) {
return { statusCode: 401, body: JSON.stringify({ error: 'Unauthorized' }) };
}
const volcano = createClient(auth);
const { data, error } = await volcano
.from('posts')
.select('id, title, created_at')
.order('created_at', { ascending: false });
if (error) {
return { statusCode: 500, body: JSON.stringify({ error: error.message }) };
}
return { statusCode: 200, body: JSON.stringify({ posts: data ?? [] }) };
};
// volcano/functions/publish-post.ts
import { createClient } from './_shared/client';
export const handler = async (event: {
postId?: string;
__volcano_auth?: { access_token?: string };
}) => {
const auth = event.__volcano_auth;
if (!auth) return { statusCode: 401, body: JSON.stringify({ error: 'Unauthorized' }) };
if (!event.postId) return { statusCode: 400, body: JSON.stringify({ error: 'postId is required' }) };
const volcano = createClient(auth);
const { data, error } = await volcano
.update('posts', { status: 'published' })
.eq('id', event.postId);
if (error) return { statusCode: 500, body: JSON.stringify({ error: error.message }) };
return { statusCode: 200, body: JSON.stringify({ post: data?.[0] ?? null }) };
};
// volcano/functions/send-slack-notification.js
exports.handler = async (event) => {
const auth = event.__volcano_auth;
if (!auth) return { statusCode: 401, body: JSON.stringify({ error: 'Unauthorized' }) };
const { channel, message } = event;
const webhookUrl = process.env.SLACK_WEBHOOK_URL;
const response = await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ channel, text: message, username: 'Volcano Bot' }),
});
if (!response.ok) {
return { statusCode: 500, body: JSON.stringify({ error: 'Failed to send notification' }) };
}
return { statusCode: 200, body: JSON.stringify({ success: true }) };
};
A durable workflow waiting with ctx.waitForMessage resumes when the webhook
receiver sends it a message (see volcano-durable). Make the receiver a
public HTTP-mode function that skips Volcano auth, verify the provider's
signature, and send with the service key from a project variable. Add
PUBLISHER_WEBHOOK_SECRET, VOLCANO_API_URL, and VOLCANO_SERVICE_KEY to
volcano/volcano.env and volcano/cloud.env, and select them in the
function's entry so a deploy without them fails instead of the receiver
reading undefined. volcano status prints
the local server's service key. For the cloud, create a narrower one with
volcano projects keys service create webhooks --permission functions.invoke --json. It can still invoke any of the project's functions, private ones
included, and start and message any durable execution, so say that when you
ask the user to confirm creating it:
# volcano-config.yaml
version: 1
functions:
- name: publisher-webhook
visibility: public
invocation_mode: http
http_auth_mode: none
variable_scope: scoped
variables: [PUBLISHER_WEBHOOK_SECRET, VOLCANO_API_URL, VOLCANO_SERVICE_KEY]
// volcano/functions/publisher-webhook.js
const crypto = require('node:crypto');
const { VolcanoAuth } = require('@volcano.dev/sdk');
function header(event, name) {
const key = Object.keys(event.headers || {}).find((k) => k.toLowerCase() === name.toLowerCase());
return key ? event.headers[key].join(',') : '';
}
exports.handler = async (event) => {
const rawBody = Buffer.from(event.body || '', event.is_base64_encoded ? 'base64' : 'utf8');
const expected = crypto
.createHmac('sha256', process.env.PUBLISHER_WEBHOOK_SECRET)
.update(rawBody)
.digest('hex');
const supplied = Buffer.from(header(event, 'publisher-signature'));
if (supplied.length !== expected.length || !crypto.timingSafeEqual(supplied, Buffer.from(expected))) {
return { statusCode: 401, body: 'invalid signature' };
}
const hook = JSON.parse(rawBody.toString('utf8'));
// The id the app saved when it started the workflow for this post.
const executionId = await executionIdForPost(hook.post_id);
// The callback can beat the app saving the id; a retry delivers it.
if (!executionId) return { statusCode: 503, body: 'workflow not started' };
// Server code passes the service key as anonKey; the SDK refuses it only in a browser.
const volcano = new VolcanoAuth({
apiUrl: process.env.VOLCANO_API_URL,
anonKey: process.env.VOLCANO_SERVICE_KEY,
});
const sent = await volcano.durable.messages.send(
{ functionName: 'publish-post', executionId },
'posted',
{ url: hook.url },
{ idempotencyKey: hook.id },
);
if (sent.error) {
// Only an ended execution or data it will never take is final.
const final = sent.status === 400 || sent.error.code === 'execution_not_running';
if (!final) return { statusCode: 503, body: sent.error.message };
console.error('publisher webhook dropped', hook.id, sent.status, sent.error.message);
}
return { statusCode: 200, body: '' };
};
idempotencyKey makes its retries harmless.409
execution_not_running (the workflow ended) and a 400 (data over 64 KiB
or another invalid send). Return 503 for everything else so the provider
retries: an execution id not saved yet, a network error (status is
null), 429, a 5xx, a full queue,
and a 401, 403, or 404, which can each mean the variable holds the
wrong key (a 404 for a running execution usually means the anon key). The
provider stops on its own schedule, and a corrected variable lets its next
retry deliver.variables, and give every other function a
variable_scope: scoped list too: a function without one receives every
project variable, the service key included.| Use case | Example |
|---|---|
| Third-party APIs with secrets | Stripe, SendGrid, Slack |
| Background / scheduled jobs | Daily aggregations, report generation |
| Admin / privileged operations | Bulk moderation, approvals |
| File processing | Image resize, PDF generation |
| Multi-step orchestration | Stitching several API calls atomically |
If the work is "fetch this user's rows" with RLS, do it client-side; functions add latency and complexity for nothing.
const { data, error } = await volcano.functions.invoke('process-payment', {
amount: 1999,
currency: 'usd',
});
if (error) {
// Network error or function threw
showErrorToast('Payment failed. Please try again.');
return;
}
// Business-logic errors are returned in the body, not as `error`
if (data.error) {
showErrorToast(data.error);
return;
}
exports.handler = async (event) => {
try {
const result = await processPayment(event);
return { statusCode: 200, body: JSON.stringify({ success: true, paymentId: result.id }) };
} catch (err) {
console.error('Payment error:', err);
return {
statusCode: 400,
body: JSON.stringify({ error: err.message, code: err.code || 'PAYMENT_FAILED' }),
};
}
};
Functions receive only user-defined project variables. Volcano does not auto-inject any variables — you must deploy them yourself:
volcano variables deploy # local, from volcano/volcano.env
volcano cloud variables deploy -f volcano/cloud.env # cloud (requires volcano login + volcano use)
This sets project-scoped variables available to all functions at runtime. volcano/volcano.env holds the local server's values; keep the cloud project's in volcano/cloud.env. volcano deploy (or volcano cloud deploy --env-file volcano/cloud.env) deploys them before the functions in the same run.
Canonical names (the shared client factory expects these):
VOLCANO_API_URL, VOLCANO_ANON_KEY, VOLCANO_DATABASE (defaults to 'app').Custom secrets (any name): STRIPE_SECRET_KEY, SENDGRID_API_KEY, etc.
Never hardcode secrets in code.
400 with a descriptive message.__volcano_auth and return 401 early for unauthenticated calls.console.log for debug output, then fetch it with the CLI — volcano functions logs <name> --type runtime (--type build for deploy/packaging errors) — before reaching for the Volcano dashboard, which is a secondary view for cloud projects only. --follow streams indefinitely like tail -f; bound it (e.g. timeout 15 ... --follow) rather than running it as a bare synchronous call.status and error explicitly.event.__volcano_auth).What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub kong/volcano-agentic-plugins --plugin volcano18 skills in this plugin
/install-volcanoInstall, upgrade, or set up the Volcano CLI. Use this whenever a task needs the volcano CLI and `which volcano` hasn't been confirmed yet, even if the user never says "install" (e.g. "build me a todo API using volcano")./volcano-authUse for Volcano authentication and identity work including user accounts, email or password sign-up and sign-in, OAuth, sessions, anonymous users, password recovery, and private or per-user data./volcano-databaseUse whenever a Volcano app stores or persists data, including CRUD, records, per-user data, migrations, RLS, todos, chat messages, polls, analytics, counters, click tracking, CMS content, feature flags, and leaderboards.Other plugins' skills for the same job