Rayfin

Rules for coding agents

The condensed set of rules and anti-patterns for writing Rayfin code — read this before generating entities, queries, permissions, functions, connectors, or deployment commands.

This is the short version of everything on this site that changes whether generated Rayfin code works. If you are an agent and you read only one page, read this one.

Full detail lives in Known limitations, Modeling entities, Permissions, and the Changelog.

Versions

  • Every @microsoft/rayfin-* package — SDK, connectors, CLI — shares one version number. Install them all at the same exact version (for example 2.0.0), including @microsoft/fabric-user-data-functions in the functions project. Mixed versions produce type errors or two copies of @microsoft/rayfin-data.
  • Read the project's package.json before you use an API. Anything tagged "New in 2.0" or "Changed in 2.0" on this site does not exist in older packages, and 2.0 client code does not compile against 1.x packages. To move a 1.x project forward, follow Upgrade to 2.0.
  • Run the CLI from the project with npx rayfin, so it matches the installed packages.

Platform

  • Rayfin uses TC39 Stage 3 decorators. Never enable experimentalDecorators or emitDecoratorMetadata.
  • Include ESNext.Decorators in the tsconfig lib array.
  • The schema package needs TypeScript ^5.7.2 || ^6.0.2.
  • Relative imports between files under rayfin/ end in .js (import { Category } from './Category.js'). Keep rayfin/package.json when rayfin init creates it.
  • If the frontend imports an entity class as a value and uses @vitejs/plugin-react-swc, enable Stage 3 decorators in the plugin, as the templates do.
  • Rayfin has one deployment target: a managed Fabric app (MSSQL only).
  • Prefer npm create @microsoft/rayfin@latest for new projects — it generates a correct tsconfig, schema boilerplate, and agent files.

Development loop

  • Sign in before anything that touches Fabric: npx rayfin login. Add --encryption-fallback-enabled only on machines with no OS keychain (dev containers, Codespaces), because it stores tokens in plaintext.
  • npm run dev runs rayfin dev. It provisions or reuses the app's backend in Fabric, applies runtime settings and the data schema, writes rayfin/.env and .env.local, then starts the frontend — and Functions, when enabled — on the local machine.
  • rayfin dev is long-running. Start it as a background process and stop it with Ctrl+C.
  • The schema is applied when the session starts. Restart npm run dev after editing rayfin.yml or files in rayfin/data/.
  • rayfin dev never publishes the frontend and does not wire connectors. Use rayfin up to publish, and to test connectors.
  • Leave rayfin dev --provider at its fabric default. The managed backend always runs in Fabric.

Client

  • Build the client with RayfinClient.create, never new RayfinClient(...): RayfinClient.create({ baseUrl, publishableKey, auth: browserSession(), services: { data: dataService<AppSchema>() } }).
  • Import browserSession from @microsoft/rayfin-auth, dataService from @microsoft/rayfin-data, functionsService from @microsoft/rayfin-functions, connectorsService from @microsoft/rayfin-connectors, and storageService from @microsoft/rayfin-storage. Register only the services the app uses, and declare each package in package.json.
  • Derive the type from a factory — export type AppClient = ReturnType<typeof createClient> — instead of writing RayfinClient<AppSchema>.
  • Resolve configuration with resolveRayfinConfig() before calling create, so a promoted bundle reads the deployed rayfin.config.json.
  • In Node.js scripts and servers use auth: suppliedToken({ accessToken }); that client has no client.auth. Call client.dispose() when the script ends.
  • There is no useProxy. Use baseUrl: '' for same-origin routing.

Data modeling

  • Define entities with @entity() in rayfin/data/, and register each one in rayfin/data/schema.ts as type AppSchema = { Todo: Todo }.
  • Every field needs exactly one type decorator: @uuid, @text, @int, @decimal, @boolean, @date, @email, @set.
  • Fields are required by default. For a nullable field use { optional: true } and ? together. Do not add | null to a decorated field's type — the decorator rejects it at compile time (TS1240).
  • Property names must be valid GraphQL names (letters, digits, _; not starting with __). Map an odd column name with { column: '$price' }.
  • @text()'s length option is max, not maxLength — @text({ max: 200 }). Always set it on MSSQL; see Known limitations.
  • Never name an entity after a GraphQL built-in type such as Date, String, Int, UUID, Query, or Mutation, or with a __ prefix. The CLI rejects it (for example Entity name 'Date' is a built-in GraphQL scalar type reserved by the platform). Rename the class, or pass a different name with @entity('EventDate').
  • Use @one(() => Target) with a lazy arrow function for relationships. Rayfin auto-generates the foreign key column, named {property}_id — see Known limitations.
  • Use import, not import type, for entity classes referenced inside @one() / @many() arrow functions — the decorator needs the runtime class value.
  • A foreign key column referencing another entity ({property}_id) must be @uuid() to match the primary key type. An auth-derived field such as user_id from claims.sub is @text(), not a foreign key.
  • Many-to-many is not supported. Use an explicit join entity with two @one() fields. See Known limitations.

Security

  • Every entity needs an explicit permission decorator (@role, @anonymous, @authenticated). Omitting one silently applies authenticated: * — full CRUD for any signed-in user — which is almost never what you want in production.
  • Default to @authenticated(...). @anonymous(...) deploys only when a Fabric tenant admin has turned on Enable anonymous data access for Fabric Apps (Preview); otherwise schema apply fails with ANONYMOUS_DATA_ACCESS_BLOCKED_BY_TENANT_ADMIN.
  • Add a policy for row-level filtering on user-scoped data: policy: (claims, item) => claims.sub.eq(item.user_id).
  • Use exclude in role options to hide sensitive fields, e.g. exclude: ['secret'].
  • Publishable keys (pk-*) are safe in client-side code. Never expose service secrets, connection strings, or tokens from ctx.Tokens.
  • Keep allowedRedirectUris in rayfin.yml scoped to your app's own origins.
  • Microsoft Entra ID is the only identity provider. Use Fabric SSO in browser apps — its popup flow works from any registered origin, including http://localhost:5173; only the embedded (iframe) flow requires the Fabric portal. Use signInWithEntraToken() when code already holds a delegated Entra token, and the embed host when your own portal embeds the app.
  • Set services.staticHosting.assetAccess explicitly: protected (requires Fabric sign-in to load the app) unless the app must be public.

Querying

  • The query chain is .select() → .where() → .orderBy() → .execute().
  • Results contain only the selected fields. A query without .select() returns the primary key only — and so do findById(), findMany(), and findFirst(filter) on the entity client. To read one record, write client.data.Entity.select(['id', 'title']).where({ id: { eq: id } }).findFirst(). There is no findByPk.
  • Always use the builder select() returns.
  • Select a to-one relationship field with 'notebook.name' and a to-many one with 'notes[].title'. Only one relationship level per path.
  • Selected Date fields are typed Date | string and booleans boolean | 'true' | 'false'. Convert them explicitly before using date methods or truthiness.
  • Filter by foreign key columns using {property}_id (customer_id), not a dot-path (customer.id). Dot-paths are for .select() only.
  • In a mutation, set a relationship with either the object (notebook: { id }) or the foreign key (notebook_id), not both.
  • Sort directions are lowercase: 'asc' or 'desc'.
  • Use .first(n).executePaginated() with .after(endCursor) for pagination. Collection queries return a single page otherwise; the default page size is 100.
  • count() does not exist on the fluent client. count is an aggregation operation and, like sum/avg/min/max, accepts numeric fields only — so it counts non-null numeric values, not rows. For a row count, select minimal fields and use results.length. See Known limitations.
  • Grouped aggregation cannot be combined with .select(), .orderBy(), .first() or .after() — Data API Builder rejects groupBy alongside items. Sort the returned array in TypeScript instead.

Auth

  • The session change callback is onSessionChange. onAuthStateChange does not exist. See Known limitations.
  • Session objects are opaque. Gate UI on isAuthenticated or the presence of a user property — do not introspect the session. isAuthenticated is false while the access token is expired, even when user is still set.
  • Await initEmbeddedAuth() at startup before rendering authenticated content, even when a stored session already exists — in an embedded app it may belong to a different user. It never rejects: when it resolves null, show the sign-in button.
  • Call ensureSignedInWithFabric() directly from a click handler, never on page load or after an await, or the popup is blocked.
  • Surface every sign-in error. Catch errors from each sign-in call and render error.message on the sign-in screen. Never swallow them with an empty catch or by only resetting the user to signed out.
  • client.auth.getClaims() returns app-defined claims as strings. Make authorization decisions in server-side policies, not in the browser.
  • After changing services.auth in rayfin.yml, restart rayfin dev or redeploy with rayfin up so the backend picks up the new settings.

Configuration

  • Always declare services.auth and services.data explicitly in rayfin.yml, even as enabled: false.
  • If services.data.enabled is true, dialect is required — mssql is the only supported value. See Known limitations.
  • If services.functions.enabled is true, services.functions.auth.type: application is required.
  • No documented feature needs RAYFIN_FEATURE_FLAGS in 2.0. Do not set storage, functions, connectors, or dynamicclaims; enable dynamic claims with services.auth.dynamicClaims.enabled: true instead.

Functions

Read Functions before writing function code.

  • Import UserDataFunctions, RayfinContext, and AudienceType from @microsoft/fabric-user-data-functions. @microsoft/rayfin-functions is the client invocation SDK only.
  • Register every function with udf.func(name, handler, []). Bare exported functions are not discovered.
  • Never hand-edit rayfin/functions/src/types.ts; typegen regenerates it.
  • Use import type for entity types inside the functions package — a value import pulls the decorator runtime into the functions bundle.
  • Read secrets as ctx.Secrets.NAME after declaring them with npx rayfin secret set NAME --describe="...". Read resource tokens as ctx.Tokens.<Audience> after declaring the audience in RayfinContext<Schema, AudienceType.X>. ctx.getSecret() and ctx.getToken() are deprecated.
  • AudienceType has five members: Sql, Storage, Fabric, AzureAI, ADO. For any other Entra-protected resource, declare its application ID or https:// / api:// resource URI as a string — RayfinContext<Schema, 'api://contoso-api'> — and read ctx.Tokens['api://contoso-api']. Never declare a /.default scope.
  • Stamp owner fields with ctx.user.id and write through ctx.getDataClient(). Never decode ctx.accessToken.
  • Prefer ctx.getDataClient() over raw SQL. RayfinContext<Schema> & WithSql is experimental, bypasses entity policies, and runs only in deployed functions where the service has enabled it.
  • Deployed functions use ctx.Tokens as the app identity, not the signed-in user. Grant the app identity access to each resource. ctx.getDataClient() stays scoped to the caller. See Delegated and application access.
  • Install resource SDKs in the functions package's package.json, not the project root.
  • Log with console.log / console.error; there is no ctx.log.
  • Leave functionsBaseUrl unset in production code so invocations reach the deployed backend.

Connectors

Connectors reach data that already exists in Fabric. Read Connectors before writing connector code.

  • The rayfin connector command group is always available as of 1.36. Do not set RAYFIN_FEATURE_FLAGS=connectors or services.connectors.enabled.
  • The connector add flag is --type, not --connector. The type literals are fabric-sqlanalytics, fabric-warehouse, fabric-sqldatabase, fabric-semanticmodel, and fabriciqmcp. There is no fabric-sql. kusto was renamed eventhouse in 2.0, and new Eventhouse connectors cannot be added; existing ones must use type: eventhouse.
  • connector add lowercases connector names, scaffolds files, and installs nothing. Run the version-pinned npm install it prints, verbatim — never drop the version.
  • connector add discovers schema only from literal --workspace-id and --item-id values; ${VAR} placeholders are rejected.
  • connector add does not emit entity .ts files. Generate them from rayfin/connectors/<name>/metadata.json, following Generating entity files. metadata.json is the only source of truth for primary keys and relationships — absent metadata means keyless, not permission to infer a key from column names.
  • Never hand-edit a file with a // @generated — do not edit. banner, or metadata.json. Re-add the connector to regenerate them.
  • GraphQLBackedConnector is the marker for all three Category A types. Per-type names like FabricWarehouse do not exist.
  • Register connectors with connectorsService<AppConnectorsSchema>({ configs, runtime }) from @microsoft/rayfin-connectors in RayfinClient.create. Import Source / AutoGenerated and the connector types from @microsoft/rayfin-connectors too.
  • Category B connectors need their runtime in the runtime map — fabricSemanticModel() decodes the response. Omit it and calls do not work.
  • A query chain with .where(), .orderBy(), or .first() needs an explicit .select([...]), or it throws SELECTION_REQUIRED.
  • auth.type is lowercase, delegated or application, and connector add --auth sets it. connector add writes application for the three SQL types; set delegated for per-user access. fabric-semanticmodel and fabriciqmcp accept only delegated; eventhouse accepts only application. See Connector authentication.
  • An Eventhouse connector runs only queries saved in its additionalPayload. Send a queryId and typed parameters, never KQL text.
  • Pass DAX to rayfin connector invoke with --file pointing at a JSON payload such as {"query":"EVALUATE ..."}, not a raw .dax file and not inline --input.
  • Prove a connector returns rows with rayfin connector invoke or rayfin connector inspect before you build UI on it.

Storage

  • Storage is generally available in 2.0 and remote-only. Add it with npx rayfin storage init; there is no local emulator.
  • Import blob, StorageObject, ContentTypes, and the size helpers from @microsoft/rayfin-core. The /experimental entry point no longer exists.
  • Every folder needs an authenticated @role policy; anonymous Storage permissions are not supported. Register each folder in rayfin/storage/schema.ts.
  • Register storageService<AppStorageSchema>() on the client, and pass full relative object paths such as 'reports/2026/q1.pdf'. There is no prefix option.
  • Removing a folder declaration and applying it permanently deletes the folder's objects.

Deployment

  • rayfin up is the canonical command for "deploy this change", "apply this schema change", or "push my entity update". It builds and deploys the static app, deploys Functions, and applies pending schema migrations in one step. It skips the static upload when nothing changed since the last successful deploy; pass --force-static-deploy to upload anyway.
  • rayfin up db apply, rayfin up staticapp deploy, and rayfin up functions deploy are narrow subcommands. Use them only when you explicitly want to update one part.
  • In automation, pass -y and an explicit workspace (--workspace-id) so the deploy never depends on an interactive prompt.
  • After adding or changing an entity, verify with rayfin up status. A deploy can report success while a newly added entity is not yet readable.
  • --force permits destructive changes (drop table, drop column, alter type). Never use it without review.
  • When a user asks you to "build and deploy" or "make it live", run the workflow — rayfin login → rayfin up → rayfin up status — rather than printing steps for them to run.

Anti-patterns

Don'tDo
Raw fetch() or hand-built GraphQL for dataclient.data.<Entity> — typed queries with automatic auth
new RayfinClient(...) or ConnectorsRayfinClientRayfinClient.create({ auth, services }) with dataService(), connectorsService(), and the other adapters
Entities with no permission decoratorAn explicit @anonymous(), @authenticated(), or @role()
@text() with no max on MSSQL@text({ max: N }) — NVARCHAR(MAX) breaks GraphQL schema generation
@text() for a foreign key column@uuid(), to match the referenced primary key
An entity named Date, Query, or another GraphQL built-inA distinct name such as EventDate
onAuthStateChangeonSessionChange
findByPk, or reading fields from findById().select([...]).where({ id: { eq: id } }).findFirst()
'notes.title' for a to-many relationship'notes[].title'
An empty catch around sign-inRender error.message on the sign-in screen
rayfin up --exclude-services staticHosting plus a separate Vite server as the dev loopnpm run dev, which runs rayfin dev
ctx.getToken(AudienceType.Sql) / ctx.getSecret('KEY')ctx.Tokens.Sql / ctx.Secrets.KEY
RAYFIN_FEATURE_FLAGS=storage,functions,connectorsNothing — all three are generally available
Storage prefix optionsThe full relative object path
Mixing Rayfin package versionsOne exact version for every @microsoft/rayfin-* package
Guessing at an API surfaceFetch the relevant <route>.md page, or use the MCP server
Something wrong on this page?Report an issueEdit this page

On this page