agentleFS
buildpad-aibuildpad-ai/skills/hooks-extensions/SKILL.md

hooks-extensions

Skill1 starsChanged 4 months agoMITView on GitHub

DaaS runtime extensions (hooks) and utilities API reference. Covers filter hooks (validation, transformation before save), action hooks (audit logging, notifications after save), and utility endpoints. Use DaaS extensions instead of implementing backend logic in Next.js API routes. Automatically loaded as background context.

  • Reads credentials

The file

We split this skill into the rules it gives an agent

4 rules. About 0 are common, 2 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use top-level parameters (not wrapped in a data object):

    line 22
  2. Very specific:

    All service factory calls accept an optional { elevated: true } option (see below).

    line 126
  3. Distinctive:

    Use this when the extension must perform an operation the user is not directly allowed to do — e.g.

    line 149
  4. Distinctive:

    Instead of hooks for timestamps/user tracking, use special fields:

    line 211

≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Hooks & Extensions Reference

Runtime Extensions

DaaS runtime extensions (hooks) run server-side on data events. They replace custom backend logic in Next.js API routes.

Extension Types

TypeWhenUse ForBlocking?
filterBefore operationValidation, data transformation, auto-populate fieldsYes — can reject
actionAfter operationAudit logging, notifications, sync to external systemsNo — async

Creating Extensions via MCP

Use top-level parameters (not wrapped in a data object):

// Filter hook — validate before save
{
  "name": "mcp_daas_extensions",
  "arguments": {
    "action": "create",
    "name": "Validate Title Length",
    "event": "articles.items.create",
    "type": "filter",
    "code": "if (!payload.title || payload.title.length < 3) { throw new Error('Title too short'); } return payload;",
    "status": "active"
  }
}

// Action hook — audit logging (async, non-blocking)
{
  "name": "mcp_daas_extensions",
  "arguments": {
    "action": "create",
    "name": "Audit Logger",
    "event": "items.create",
    "type": "action",
    "code": "console.log('Created:', meta.collection, meta.key); await services.items(meta.collection).createOne({ action: 'create', collection: meta.collection, item_id: meta.key, payload_keys: Object.keys(meta.payload || {}) });",
    "status": "active"
  }
}

mcp_daas_extensions Actions

ActionParametersPurpose
listevent?, status?, type?List all extensions
readidRead extension details
createname, event, type, code, status?, sort?, timeout_ms?Create an extension
updateid, name?, event?, type?, code?, status?, sort?, timeout_ms?Update an extension
deleteidDelete an extension
activateidSet status to active
deactivateidSet status to inactive
cloneid, name?Clone an extension

Note: All parameters are top-level in arguments — do NOT wrap them in a data object. The delete action requires the platform setting mcp_allow_deletes = true (env: MCP_ALLOW_DELETES=true). Without it, delete returns "Delete operations are disabled".

Event Names

  • items.create / items.update / items.delete — All collections
  • [collection].items.create — Specific collection
  • auth.login / auth.logout — Auth events
  • System collections also emit events: daas_cron_jobs.items.*, daas_custom_services.items.*, daas_extensions.items.*, daas_scope_types.items.*, daas_scope_items.items.*, daas_scope_collection_config.items.*, daas_access.items.*, daas_user_roles.items.*, daas_settings.items.*, daas_folders.items.*, daas_users.items.*, daas_roles.items.*

Built-in Platform Hooks

The following hooks are hardcoded in the platform (not runtime extensions). They fire automatically and cannot be disabled or overridden via the extensions API.

HookEventPurpose
Role-scope readdaas_roles.items.readComputes the assignable boolean on each role based on the current scope context and scope_config.allowed_scopes
Role-scope validatedaas_users.items.create, daas_users.items.updateValidates role assignments against scope_config. Throws ROLE_SCOPE_MISMATCH or ROLE_SCOPE_LOCKED if the assignment violates scope restrictions

These hooks are implemented in lib/hooks/role-scope.ts. Do not create runtime extensions for the same events expecting to replicate or override this behavior.

Hook Context Variables

Common to all hooks:

VariableTypeDescription
servicesobjectFull services object (see table below)
contextobjectSupabase client (circular reference — do NOT JSON.stringify)
consoleobjectlog, warn, error — captured in logs
JSONobjectparse, stringify
DateclassStandard Date constructor
MathobjectStandard Math object

Filter hooks — additional variables:

VariableTypeDescription
payloadobjectThe data being written (modify and return payload)
metaobject{ event, collection } — event metadata (no payload or key)

Action hooks — additional variables:

VariableTypeDescription
metaobject{ event, payload, key, collection } — full event data

In action hooks, access event data via meta:

  • meta.payload — The data that was written
  • meta.key / meta.keys — The ID(s) of the created/updated/deleted item(s)
  • meta.collection — The collection name
  • meta.event — The event name string (e.g., "articles.items.create")

NOT available (despite Directus conventions):

  • ❌ event — Use meta.event
  • ❌ collection — Use meta.collection
  • ❌ key / keys — Use meta.key or meta.keys
  • ❌ accountability — Not injected into sandbox

services Object Members

All service factory calls accept an optional { elevated: true } option (see below).

MemberTypePurpose
services.items(coll, [opts])async fnCRUD + aggregate on any collection (17 methods)
services.collections([opts])async fnCollection management
services.fields([opts])async fnField management
services.files([opts])async fnFile upload, import, download, metadata
services.versions([opts])async fnContent versioning — create, save, promote
services.relations([opts])async fnRelation management
services.mail()async fnSend emails via SMTP (send(), verify())
services.mail(options)async fnSend email directly (shorthand)
services.custom(name, [opts])async fnLoad a reusable custom service (see Custom Services)
services.fetch(url)functionDomain-restricted HTTP fetch
services.supabaseobjectRaw Supabase client (service role, bypasses RLS)
services.envobjectRuntime whitelisted env vars. Always includes NODE_ENV and NEXT_PUBLIC_SITE_URL. Additional keys configured via RUNTIME_ENV_WHITELIST_EXTENSION or EXTENSION_PUBLIC_* deployment env vars. Use services.env.KEY or context.services.env.KEY (equivalent in extensions). context.env does NOT exist.

All factory calls are async — always await them. See Services API reference for complete method signatures.

Elevated Permissions

By default, service calls enforce the triggering user's own permission policies. Pass { elevated: true } to bypass permission checks while keeping the original user in the audit trail (user_created/user_updated fields and daas_activity log).

Use this when the extension must perform an operation the user is not directly allowed to do — e.g. writing to a field locked by their policy.

// Normal — user's own permissions enforced
const svc = await services.items('orders');

// Elevated — permission checks skipped, user still in audit trail
const svc = await services.items('orders', { elevated: true });
// Same flag works on every service factory:
// services.fields({ elevated: true })
// services.files({ elevated: true })
// services.versions({ elevated: true })
// services.relations({ elevated: true })
// services.collections({ elevated: true })
// services.custom('name', { elevated: true })  ← propagates admin acc into the nested service

// Example: action hook writing to a protected status log (orders.items.create)
const log = await services.items('order_status_log', { elevated: true });
await log.createOne({ order_id: meta.key, status: 'pending', note: 'auto-created' });

Cron jobs always run as the system account (admin: true). Permission checks are already bypassed — { elevated: true } is not needed in cron code.

Custom services inherit the calling context's accountability. Pass { elevated: true } when calling services.custom('name', { elevated: true }) to give the nested service admin-level accountability — permission checks inside the custom service are bypassed while the triggering user is still recorded in the audit trail. You can also use { elevated: true } on any context.services factory call within the custom service itself.

Correct Code Examples

Filter hook — validate and transform:

// payload and meta are available directly
const helper = await services.custom('my_validator');
const check = helper.validatePayload(payload, ['name', 'email']);
if (!check.valid) {
  throw new Error('Missing: ' + check.missing.join(', '));
}
payload.name = payload.name.trim().toUpperCase();
return payload; // MUST return payload

Action hook — audit logging:

// In action hooks, all event data is in meta (not direct variables)
const helper = await services.custom('audit_logger');
const audit = helper.buildAuditEntry(
  'create',
  meta.collection,    // NOT collection (undefined)
  meta.key,           // NOT key (undefined)
  { payload_keys: Object.keys(meta.payload || {}) }
);
const items = await services.items('audit_logs');
await items.createOne(audit);

Performance: Extensions vs API Routes

ApproachRequest FlowUser Waits For
API Route (❌)Request → DaaS → Audit → ResponseOperation + Audit
Action Extension (✅)Request → DaaS → Response → (async: Audit)Operation only

Special Fields (Auto-Populated)

Instead of hooks for timestamps/user tracking, use special fields:

Field Typemeta.special ValuePurpose
UUID PK["uuid"]Auto-generate UUID
Created date["date-created"]Auto-set on create
Updated date["date-updated"]Auto-set on update
Created by["user-created"]Auto-set creating user
Updated by["user-updated"]Auto-set updating user

References

  • Hooks & extensions guide
  • Services API reference — complete method signatures for all built-in services
  • Utilities API

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.