agentleFS
buildpad-aibuildpad-ai/skills/daas-platform/SKILL.md

daas-platform

Skill1 starsChanged 4 months agoMITView on GitHub

Core DaaS (Data-as-a-Service) platform knowledge including two-tier architecture, DaaS-compatible REST API, Supabase integration, Next.js App Router patterns, MCP tool usage, and environment configuration. Automatically loaded as background context for all DaaS development tasks.

  • Reads credentials

The file

We split this skill into the rules it gives an agent

6 rules. About 0 are common, 2 are distinctive, and 4 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.

  • 4

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Never query Supabase directly from frontend code

    line 18
  2. Very specific:

    Always read .env.local to get actual configured values before making API calls.

    line 37
  3. Distinctive:

    Before writing any API route or page that queries a collection:

    line 166
  4. Very specific:

    Use mcp_daas_schema (with keys: ["collection_name"]) or mcp_daas_fields to get the actual field names

    line 168
  5. Very specific:

    Use only the field names returned by the schema in sort, fields, and filter parameters

    line 169
  6. Very specific:

    Only set ready = true when tok is non-null — INITIAL_SESSION can fire with session = null when the access token is expired and Supabase is …

    line 217

≈ “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

DaaS Platform Reference

Two-Tier Architecture

Frontend App  →  DaaS Backend (DaaS)  →  Supabase (PostgreSQL)
(Next.js)        (DaaS-compatible REST API)           (Database)
  • Frontend connects to DaaS backend for ALL data operations
  • Frontend uses Supabase ONLY for authentication (via proxy routes)
  • Never query Supabase directly from frontend code

Technology Stack

  • Frontend: Next.js 16 (App Router), React 19, TypeScript 5.x
  • UI: Mantine v8 + Buildpad components (Copy & Own)
  • Backend: DaaS (DaaS-compatible REST API)
  • Auth: Supabase Auth via server-side proxy routes
  • Testing: Playwright (E2E) + Vitest (unit)
  • Design: Token-based theming with CSS custom properties (--ds-*)

Environment Variables (.env.local)

NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key
NEXT_PUBLIC_BUILDPAD_DAAS_URL=http://localhost:3000

Always read .env.local to get actual configured values before making API calls.

REST API Pattern

GET    /api/items/:collection          # List items
POST   /api/items/:collection          # Create item
GET    /api/items/:collection/:id      # Get item
PATCH  /api/items/:collection/:id      # Update item
DELETE /api/items/:collection/:id      # Delete item
GET    /api/fields/:collection         # Get field schema
GET    /api/relations                  # Get relations

Query Parameters

  • fields: * or comma-separated field names
  • filter: { "status": { "_eq": "published" } }
  • sort: Field name, - prefix for descending
  • limit, offset: Pagination
  • aggregate: Aggregate functions — { "count": ["id"], "sum": ["amount"] } or bracket notation aggregate[count]=id
  • groupBy: Group aggregate results — comma-separated field names

Aggregate Functions

Perform calculations on collection data without fetching individual items:

GET /api/items/:collection?aggregate[count]=id&groupBy=status
GET /api/items/:collection?aggregate={"count":["*"],"sum":["amount"]}&filter={"status":{"_eq":"completed"}}

Supported operations: count, countDistinct, countAll, sum, sumDistinct, avg, avgDistinct, min, max

Response format (nested, permission-aware):

{
  "data": [
    { "status": "completed", "count": { "id": 42 }, "sum": { "amount": 12500 } }
  ]
}

Aggregate queries respect collection-level read permissions and item-level RLS filters.

Filter Operators

_eq, _neq, _lt, _lte, _gt, _gte, _in, _nin, _contains, _icontains, _starts_with, _ends_with, _null, _nnull, _and, _or

DaaS MCP Tools

ToolPurpose
mcp_daas_itemsCRUD + aggregate on collection items
mcp_daas_schemaRead collection/field schema (no action param!)
mcp_daas_collectionsManage tables (admin)
mcp_daas_fieldsManage columns — data accepts object OR array
mcp_daas_relationsForeign key relationships
mcp_daas_filesFile management
mcp_daas_usersUser profiles
mcp_daas_rolesRole definitions (CRUD — create/read/update/delete)
mcp_daas_permissionsPermission rules (CRUD — create/read/update/delete)
mcp_daas_extensionsRuntime hooks (admin)
mcp_daas_cronScheduled background jobs (admin)
mcp_daas_servicesReusable custom service modules shared between extensions and cron jobs (admin)
mcp_daas_scopeHierarchical scope management — types, items, collection configs, scoped role assignments (admin)

MCP Action Quick Reference

mcp_daas_services — Custom Services:

ActionKey ParametersPurpose
liststatus?List all services
readidRead service details
createname, code, tests[]?, status?Create a service (snake_case names!)
updateid, code?, tests[]?, status?Update service (auto-increments version)
deleteidDelete service (fails if dependents)
run_testsidRun all built-in tests
run_testid, testRun a single test by name
activateidSet status to active
deactivateidSet status to inactive

mcp_daas_cron — Cron Jobs:

ActionKey ParametersPurpose
list—List all cron jobs
readidRead job details
createname, code, schedule, status?Create a cron job
updateid, code?, schedule?, status?Update a cron job
deleteidDelete a cron job
run_nowidManually trigger immediately
activateidSet status to active
deactivateidSet status to inactive
historyid, limit?View run history with logs
cloneid, name?Clone a cron job

mcp_daas_extensions — Runtime Extensions:

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

All MCP tools use top-level parameters in arguments — do NOT wrap in a data object.

Delete restriction (expected, not a bug): The delete action on most tools is blocked by default — this is an intentional safety gate, not an error condition to work around. The platform setting mcp_allow_deletes (env: MCP_ALLOW_DELETES) must be true for delete to work. RBAC tools (roles, policies, permissions, access) are exempt from this restriction.

If a delete call errors with "Delete operations are disabled", do not retry, switch tools, use raw SQL, or attempt any other workaround. Tell the user this is expected and that they need to enable it in the DaaS Admin dashboard under Settings → AI (mcp_allow_deletes), then stop.

MCP Pitfalls

  • schema tool has NO action parameter — just use keys
  • permissions, roles, and policies all support full CRUD via their own dedicated MCP tools — do NOT use the items tool for these collections
  • For permissions create: the data.action field is the permission action ("create"/"read"/"update"/"delete"/"share"), which is different from the top-level action parameter ("create") — pass them both explicitly
  • fields.delete uses fields: [] (array), not field (string)

Schema Verification Rule (CRITICAL)

Always verify field names against the actual DaaS schema before writing queries, sort parameters, or filter expressions. Do NOT assume field names — they may differ from common conventions (e.g., created_at vs date_created). Using a non-existent field in sort, fields, or filter causes the DaaS backend to return a 500 error with no helpful message.

Before writing any API route or page that queries a collection:

  1. Use mcp_daas_schema (with keys: ["collection_name"]) or mcp_daas_fields to get the actual field names
  2. Use only the field names returned by the schema in sort, fields, and filter parameters
  3. Pay special attention to audit/timestamp columns — names vary between DaaS instances (e.g., created_at vs date_created vs date_created)

Backend-First Rule

Before implementing ANY server-side feature, check the Built-in DaaS Features reference. If DaaS provides it natively, use it — do NOT rebuild it in Next.js. This is the most common source of agent errors: building custom implementations of features that DaaS already provides.

PatternDaaS FeatureDO NOT Build
State machine / approvalsDaaS Workflows (create-workflow skill)Custom status fields, manual state logic
Audit / change trackingAutomatic — daas_activity + GET /api/activityCustom audit tables, logging hooks
Validation before saveRuntime Extensions (filter hooks)Next.js API middleware validation
Side effects after saveRuntime Extensions (action hooks)Custom webhook dispatchers
Scheduled tasksDaaS Cron Jobs (mcp_daas_cron)setInterval, Next.js cron, external schedulers
Shared reusable codeDaaS Custom Services (services.custom())Shared utility files for server-side logic
Auto timestampsSpecial fields: date-created, date-updatedManual new Date() in API routes
Auto user trackingSpecial fields: user-created, user-updatedManual req.user.id assignment
Permissions / access controlDaaS Permission system (RBAC)Custom permission tables, isAdmin fields
Content versioning / draftsDaaS Versions API (POST /api/versions)Custom version/draft tables
File upload / storageDaaS Files API (POST /api/files)Custom upload endpoints, storage logic
Multi-tenancy / scopingDaaS Scope system (manage-scope skill)Custom tenant_id columns, manual filtering
Data import/exportPOST /api/utils/import, GET /api/utils/exportCustom CSV parsers, import routes
Hashing / random tokensPOST /api/utils/hash/*, /random/stringCustom bcrypt/crypto code
Third-party integrations (Stripe API calls, Get Feedback widget, etc.)Connect via the Buildpad platform's Connectors page; credential(s) arrive as whitelisted env var(s) — check get_project_detail's connectors[] for the exact name(s), base URL, and auth header style (base URL may itself be one of the env vars for a self-hosted provider like Chocolate Factory or Get Feedback). Always check that provider's references/<key>.instructions.md (in the create-service skill's references/ folder) first — it tells you the actual integration shape, which is NOT always a backend API call: most providers are called from a custom service via raw services.fetch; one that ships an official SDK (e.g. Chocolate Factory) is called from a server-side Next.js API route instead, since custom services can't import npm packages; and one that ships a client-side embeddable widget (e.g. Get Feedback — a floating button dropped into the root layout via a single <script> tag) needs no backend code at all. For local dev, connectors[] also carries envVars (actual decrypted values) to populate .env.local — and since connecting a provider does NOT push anything to the deployed Amplify app, also push that same envVars map with amplify_set_env_vars + amplify_redeploy (see amplify-env-vars skill) once the feature is builtHardcoding API keys, inventing your own env var name, asking the user to paste a key into code, building a connector-dependent feature without pushing its env var(s) to Amplify (works locally, silently missing once deployed), asking the user what a named capability means before checking whether it's already a connected provider

Before asking a clarifying question about a named feature or capability (e.g. "feedback widget", "chat", "payments", "analytics"), check get_project_detail's connectors[] first. If it matches a connected provider, its references/<key>.instructions.md already answers "what is this and how do I add it" — no need to ask the user to disambiguate something the platform already knows.

References

  • DaaS API reference
  • DaaS MCP tools
  • Next.js patterns
  • Built-in DaaS features — DO NOT rebuild these

Provider Architecture Rules (Learned from Production)

Rule: DaaSProvider MUST be in (authenticated)/layout.tsx, NEVER in root layout (Bug 22)

Next.js root layouts never unmount during client-side navigation. If DaaSProviderWrapper is in app/layout.tsx, it stays alive across logout → /login → re-login, delivering a stale null token and causing 401 on every DaaS call after the second login. Fix: place it in app/(authenticated)/layout.tsx so it fully unmounts when the user navigates to /login.

Rule: DaaSProviderWrapper must use onAuthStateChange, NOT getSession, pass token as sync prop, and gate ready on non-null token (Bug 19 + Bug 27)

supabase.auth.getSession() from createBrowserClient can return { session: null } before the async storage adapter finishes reading cookies. Use onAuthStateChange which fires INITIAL_SESSION only after cookie parsing is complete.

Two additional requirements:

  1. Pass token: tokenState as a sync prop to DaaSProvider — without it effectiveToken is null on first render, so setGlobalDaaSConfig sets a null-token config and child components get 401.
  2. Only set ready = true when tok is non-null — INITIAL_SESSION can fire with session = null when the access token is expired and Supabase is performing a silent refresh. Setting ready unconditionally causes children to mount without auth.
  3. Make useMemo deps include tokenState so DaaSProvider re-renders when the token refreshes.
const [tokenState, setTokenState] = useState<string | null>(null);
const tokenRef = useRef<string | null>(null);

useEffect(() => {
  const { data: { subscription } } = supabase.auth.onAuthStateChange(
    (_event, session) => {
      const tok = session?.access_token ?? null;
      tokenRef.current = tok;
      setTokenState(tok);
      if (tok) setReady(true); // only gate-open when token is present
    }
  );
  return () => subscription.unsubscribe();
}, [supabase]);

const config = useMemo(() => ({
  url: process.env.NEXT_PUBLIC_BUILDPAD_DAAS_URL ?? '',
  token: tokenState ?? undefined,   // sync prop for first render
  getToken: async () => tokenRef.current,
  // ...
}), [tokenState]);                  // re-create when token refreshes

if (!ready) return null;

Rule: DaaSProvider must NOT clear globalDaaSConfig on unmount (Bug 27)

React 18+ StrictMode (on by default in Next.js dev) double-invokes effects: mount → cleanup → mount. If DaaSProvider runs setGlobalDaaSConfig(null) in an effect cleanup, the cleanup fires between the two mounts. Child components (CollectionList, VForm) that re-mount in the second pass call getApiHeadersAsync() during the null window → 401 on every hard reload in dev, and intermittently in production.

The render body already calls setGlobalDaaSConfig(resolvedConfig) synchronously on every mount, so the next mount overwrites the config. Do not add any cleanup that nulls out globalDaaSConfig.

Rule: DaaSConfig must include getHeaders for scope forwarding (Bug 16)

Buildpad components call DaaS directly from the browser — they do NOT go through the Next.js proxy. Without getHeaders, the X-Resource-Uri header is never sent on direct calls, and DaaS falls back to root scope where the user has no role → 403.

getHeaders: async () => {
  const raw = document.cookie
    .split('; ')
    .find(r => r.startsWith('daas_resource_uri='))
    ?.split('=')[1];
  return raw ? { 'X-Resource-Uri': decodeURIComponent(raw) } : {};
},

Rule: CORS must use explicit origins + allow X-Resource-Uri header (Bugs 17 + 25)

The DaaS default cors_origins: ["*"] is incompatible with Buildpad’s credentials: 'include' — the browser blocks every preflight. Also, X-Resource-Uri is not in the default cors_allowed_headers, so even after fixing origins the header is blocked. Always run this at project creation:

{
  "cors_origins": ["http://localhost:3000", "http://localhost:3001", "<amplifyUrl>"],
  "cors_allow_credentials": true,
  "cors_allowed_headers": ["Content-Type","Authorization","Origin","X-Requested-With","Accept","X-Resource-Uri"],
  "cors_max_age": 0
}

Rule: Any context that calls DaaS on mount must wait for scope to be ready (Bug 26)

If a context provider fetches from DaaS (e.g. /api/policies/me) and lives inside ScopeProvider, the first fetch will have no scope cookie yet and will get 401. The .catch() handler will set state to empty/false and the effect will never re-run if scopeLoading is not in deps.

Pattern — always consume useScope() and guard + react to scope changes:

const { resourceUri, isLoading: scopeLoading } = useScope();

useEffect(() => {
  if (scopeLoading) return; // wait for scope cookie to be set
  // ... fetch from DaaS
}, [version, resourceUri, scopeLoading]); // re-fetch when tenant switches

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.