Build a custom adapter: Snowflake example
Build your own adapter with the public adapter SDK, using a working Snowflake adapter as the example, then load it into your engine and use it in workflows that write polled REST records to Snowflake and poll a Snowflake table.
On this page
- When to build one
- Before you start
- Steps
- 1. Scaffold from the SDK
- 2. Describe the settings
- 3. Define the actions
- 4. Authenticate, and cache the token
- 5. Handle async statements, partitions and errors
- 6. Test it
- 7. Package it and load it into your engine
- Write each polled REST record into Snowflake
- Read a Snowflake table with a polling trigger
- Troubleshooting
- Reference
The engine ships with adapters for EHRs, FHIR servers, files, queues and databases. When a system has none, you can write one with the public adapter SDK, @medhook/adapter-sdk, and load it into your engine without a new engine release. This guide walks through a complete adapter for Snowflake's SQL API, then uses it in two workflows.
The example is in the repository at packages/adapter-sdk/examples/snowflake-adapter/, with its tests. It depends only on the SDK and Node's built-in crypto.
sequenceDiagram
participant Engine as MedHook engine
participant Adapter as Your adapter
participant SF as Snowflake SQL API
Engine->>Adapter: execute(profile, "insert", { table, rows })
Adapter->>Adapter: Sign a key-pair JWT (cached)
Adapter->>SF: POST /api/v2/statements (SQL with ?, values as bindings)
alt Done
SF-->>Adapter: 200 with the result
else Still running
SF-->>Adapter: 202 with a statement handle
Adapter->>SF: GET /api/v2/statements/{handle} until 200
end
Adapter-->>Engine: { rowsAffected }When to build one
Check what the engine already does first. A custom adapter is code you own, test and rebuild for every engine upgrade.
| The system | Use |
|---|---|
| Has a REST API with a standard auth scheme | Generic REST: paging, OAuth2, API keys and URL templates, no code |
| Is PostgreSQL, SQL Server, MySQL or Oracle | SQL database |
| Has a SOAP API | SOAP |
| Is BigQuery | Google BigQuery |
| Is Salesforce | See Salesforce before you build one |
| Needs a signature, a token exchange or a protocol none of these speak | A custom adapter |
Snowflake is a good example of the last row. Its SQL API takes a JWT signed with the user's private key, runs long statements asynchronously and returns large results in partitions. Generic REST can't sign that JWT, and the SQL database adapter doesn't speak Snowflake.
Before you start
- Node.js 22 and a package manager.
- A Snowflake user for the engine, with a role that has only the rights the workflows need, and a warehouse.
- An engine you can deploy a derived image to. See Custom adapters.
Steps
1. Scaffold from the SDK
Start a package and add the SDK and zod:
mkdir snowflake-adapter && cd snowflake-adapter
npm init -y
npm pkg set type=module
npm install @medhook/adapter-sdk zod
npm install -D typescript tsup vitest @types/nodeAn adapter is a class that extends BaseAdapter. It names itself, describes its settings with a zod schema, lists its actions and implements read() and write():
import { z } from "zod";
import { BaseAdapter } from "@medhook/adapter-sdk";
import type { AdapterAction, AdapterProfile } from "@medhook/adapter-sdk";
export class SnowflakeAdapter extends BaseAdapter {
readonly type = "snowflake-sql"; // never change it once profiles use it
readonly name = "Snowflake";
readonly description = "Query and load Snowflake tables through the SQL API";
readonly version = "1.0.0";
readonly configSchema = configSchema;
readonly actions: AdapterAction[] = [
/* query, insert, execute */
];
async read(profile: AdapterProfile, params: unknown) {
/* ... */
}
async write(profile: AdapterProfile, data: unknown) {
/* ... */
}
}The type must be new: the engine refuses a package whose type is a built-in adapter's.
2. Describe the settings
The settings schema is what a user fills in under Adapters › New connection. The engine encrypts the whole profile at rest, so the private key is stored like any other adapter credential.
const configSchema = z.object({
account: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/), // myorg-myaccount
user: z.string().min(1),
privateKeyPem: z.string().refine((v) => v.includes("PRIVATE KEY-----")),
privateKeyPassphrase: z.string().optional(),
warehouse: z.string().optional(),
database: z.string().optional(),
schema: z.string().optional(),
role: z.string().optional(),
statementTimeoutSeconds: z.number().int().min(1).optional().default(60),
maxWaitMs: z.number().int().positive().optional().default(120_000),
});The account pattern matters: the adapter builds the host name from it (https://<account>.snowflakecomputing.com), so the schema refuses anything that could point the request somewhere else. Inside each method, this.validateConfig(profile.config) returns the settings, typed, or throws a VALIDATION_FAILED error.
3. Define the actions
Each action is a choice under Action on a step, with its parameters as fields. The example has three:
| Action | Kind | Parameters | Returns |
|---|---|---|---|
query | read | sql, bindings, cursor, cursorInitial, maxRows | { rows, rowCount, truncated, statementHandle } |
insert | write | table, and the message's row or rows | { rowsAffected, stats, statementHandle } |
execute | write | sql, and the message's bindings | { rowsAffected, stats, statementHandle } |
Because the names are not the SDK's default read and write, the adapter routes them itself in execute(), and throws UNSUPPORTED_OPERATION for anything else:
override async execute(profile: AdapterProfile, action: string, params: unknown) {
await this.validate(profile);
switch (action) {
case "query":
return this.read(profile, params);
case "insert":
return this.insert(profile, params);
case "execute":
return this.write(profile, params);
default:
throw new AdapterError(`Unsupported action '${action}'`, AdapterErrorCode.UNSUPPORTED_OPERATION);
}
}What a message may supply
A step's parameters come from its own settings. A message adds only the keys the adapter lists in inputKeys(action), and the step's settings win on every key. List values, never a table name, a URL or SQL text, so a message can't redirect the step:
override inputKeys(action: string): readonly string[] {
if (action === "insert") return ["rows", "row"];
if (action === "execute") return ["bindings"];
return [];
}Values are always bound
The SQL text holds a ? for each value, and the values travel separately as Snowflake bindings: { "1": { "type": "TEXT", "value": "..." } }. A value such as x'); DROP TABLE APPOINTMENTS; -- is stored as that text. The insert action builds its INSERT ... VALUES (?, ?) from the row's column names, and refuses any name that is not a plain identifier, because names can't be bound.
A binding is a plain value (its type is inferred), { "type": "TIMESTAMP_TZ", "value": "..." } to choose the type, or { "cursor": true } for the poll cursor (see step 2 of the second workflow). SQL text that contains a {{...}} template is refused before any request.
4. Authenticate, and cache the token
Snowflake's key-pair authentication needs a JWT, signed RS256 with the user's private key, with:
| Claim | Value |
|---|---|
iss | <ACCOUNT>.<USER>.SHA256:<fingerprint> |
sub | <ACCOUNT>.<USER> |
iat | now, in seconds |
exp | at most one hour after iat |
ACCOUNT and USER are upper case, and an account locator drops its region (xy12345.us-east-2.aws signs as XY12345). The fingerprint is the base64 SHA-256 of the public key in DER form. Every request sends the token as Authorization: Bearer <jwt> with X-Snowflake-Authorization-Token-Type: KEYPAIR_JWT. The example signs it with Node's crypto in jwt.ts, so it needs no JWT library.
Signing on every call would work, but the SDK's TokenCache keeps one token per profile until a minute before it expires:
private readonly tokens = new TokenCache<string>();
const cached = this.tokens.get(cacheKey);
if (cached) return cached;
const jwt = createKeyPairJwt({ account, user, privateKeyPem });
this.tokens.set(cacheKey, jwt.token, (jwt.expiresAt - 60) * 1000 - Date.now());The cache key includes a hash of the private key, so a rotated key signs a new token straight away. When Snowflake answers 401, the adapter signs a new token once and tries again.
To set the key up, create a key pair and give Snowflake the public half:
openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out rsa_key.p8 -nocrypt
openssl rsa -in rsa_key.p8 -pubout -out rsa_key.pubALTER USER MEDHOOK_SVC SET RSA_PUBLIC_KEY='MIIBIjANBgkqh...';
DESC USER MEDHOOK_SVC; -- RSA_PUBLIC_KEY_FP is the fingerprint the JWT carriesPaste the contents of rsa_key.p8 into the profile's privateKeyPem.
5. Handle async statements, partitions and errors
POST /api/v2/statements answers 200 when the statement finished, or 202 with a statementHandle when it is still running. The adapter then asks GET /api/v2/statements/{handle} every pollIntervalMs until it gets 200. If the statement still runs after maxWaitMs, the adapter cancels it and fails with TIMEOUT, so a retry of the step starts clean.
A large result arrives in partitions. The first comes with the 200; the adapter reads the others with ?partition=N, in order, until it has maxRows rows, and sets truncated when it stopped early. Every value arrives as a string, and the adapter turns each row into an object by the column types in rowType: numbers, booleans, YYYY-MM-DD dates, timestamps as UTC ISO-8601 text with nine fraction digits, and VARIANT as parsed JSON.
The SDK's error codes decide what the engine retries. The example maps Snowflake's answers like this:
| Snowflake answers | Error code | Retried |
|---|---|---|
| 429, 500, 502, 503, a network error | RATE_LIMITED, CONNECTION_FAILED | Yes |
| 202 or 429 while checking a statement | still running: keep waiting | — |
| 408 (the statement passed its timeout), 504 | TIMEOUT | Yes |
| 422 (a SQL error, such as a compilation error) | VALIDATION_FAILED | No |
| 401 after a fresh token, or 403 | AUTHENTICATION_FAILED | No |
The SDK's withRetry retries the retryable ones with backoff. Every attempt of one submission reuses the same requestId and adds retry=true, so Snowflake does not run an INSERT twice that already succeeded.
testConnection() runs SELECT 1 with the profile's warehouse, database and role, so Test connection checks the key, the user and the role together.
6. Test it
Run the SDK's contract tests, the same checks the engine runs when it loads the package, and test the behaviour with fetch stubbed, so no test needs a Snowflake account:
import { describe } from "vitest";
import {
createMockProfile,
runAdapterContractTests,
} from "@medhook/adapter-sdk/testing";
import { SnowflakeAdapter } from "./index";
describe("SnowflakeAdapter contract", () => {
runAdapterContractTests({
adapter: new SnowflakeAdapter(),
validProfile: createMockProfile({
adapterType: "snowflake-sql",
config: syntheticConfig,
}),
invalidProfileConfig: { account: "", user: "" },
});
});The example's tests also check the JWT's claims and its signature against the public key, that an injection attempt stays a bound value, the 202 polling, the partitions and each row of the error table above.
7. Package it and load it into your engine
Bundle the adapter as one ES module, zod and the SDK included, and export the adapter and a synthetic contract profile:
export default SnowflakeAdapter;
export const contract = {
validProfile: {
config: {
account: "demohealth-test",
user: "MEDHOOK_SVC",
privateKeyPem:
"-----BEGIN PRIVATE KEY-----\nsynthetic-not-a-key\n-----END PRIVATE KEY-----",
},
},
invalidProfileConfig: { account: "", user: "" },
};// tsup.config.ts
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["index.ts"],
format: ["esm"],
platform: "node",
target: "node22",
noExternal: [/.*/], // bundle everything; Node built-ins stay external
});Give package.json the same name you will list in the engine's allowlist, "type": "module" and "exports": "./dist/index.js". Then build the derived image, pin the package's hash and deploy it as Custom adapters describes. After the deploy, GET /api/health lists the package under runtimeAdapters, and Snowflake appears under Adapters › New connection.
Write each polled REST record into Snowflake
This workflow reads an appointments API with a polling trigger and writes each new or changed appointment to a Snowflake table. Set up the trigger as in Poll a paginated REST API: each record runs once, as input.item.
-
Create the table, with the key the merge below matches on:
sqlCREATE TABLE RAW.APPOINTMENTS ( ID STRING PRIMARY KEY, STATUS STRING, START_AT TIMESTAMP_TZ, PATIENT_MRN STRING, UPDATED_AT TIMESTAMP_TZ ); -
Create a Snowflake connection with the account, user, private key, warehouse, database
CLINICAL, schemaRAWand a role that can only write that table. Choose Test connection. -
After the trigger, add a JavaScript step that turns the record into the statement's values, in the order of the
?s:javascriptconst a = input.item; return { bindings: [a.id, a.status, a.start, a.patient.mrn, a.updatedAt], }; -
Add a destination with Adapter profile set to the Snowflake connection and Action set to execute. Set sql to a
MERGE, and leave bindings empty so they come from the message:sqlMERGE INTO RAW.APPOINTMENTS t USING (SELECT ? AS ID, ? AS STATUS, TO_TIMESTAMP_TZ(?) AS START_AT, ? AS PATIENT_MRN, TO_TIMESTAMP_TZ(?) AS UPDATED_AT) s ON t.ID = s.ID WHEN MATCHED THEN UPDATE SET STATUS = s.STATUS, START_AT = s.START_AT, PATIENT_MRN = s.PATIENT_MRN, UPDATED_AT = s.UPDATED_AT WHEN NOT MATCHED THEN INSERT (ID, STATUS, START_AT, PATIENT_MRN, UPDATED_AT) VALUES (s.ID, s.STATUS, s.START_AT, s.PATIENT_MRN, s.UPDATED_AT)
A MERGE keyed on the record's id makes a replay or a retry update the same row instead of adding a second one. For an append-only table, use Action insert with table RAW.APPOINTMENTS, and have the JavaScript step return { row: { ID: a.id, STATUS: a.status, ... } }. Each key is a column name.
Choose Run test with a sample record, then deploy. Each execution's destination shows the rowsAffected Snowflake reported.
Read a Snowflake table with a polling trigger
This workflow starts one execution for each new or changed row of a results table. It keeps a cursor on a timestamp column, as the SQL database reader does.
-
On the workflow's Source step, set Trigger type to polling, Adapter profile to the Snowflake connection (with a role that can only read the table) and Action to query.
-
Set Params to:
json{ "sql": "SELECT ID, MRN, RESULT_CODE, UPDATED_AT FROM RAW.LAB_RESULTS WHERE UPDATED_AT >= TO_TIMESTAMP_TZ(?) ORDER BY UPDATED_AT LIMIT 500", "bindings": [{ "cursor": true }], "cursor": "{{cursor}}", "cursorInitial": "1970-01-01T00:00:00Z" }The engine fills
cursorwith the last cursor it stored, and leaves it out before the first one, when{ "cursor": true }bindscursorInitialinstead. The cursor reaches Snowflake only as a bound value: the engine never puts it intosql. -
Set the trigger's other fields:
Field Value Items path rowsCursor field UPDATED_ATCursor format as is: the adapter returns timestamps as UTC ISO-8601, which sort as text Id field IDSnowflake returns unquoted column names in upper case, so the fields name them that way, and a step reads
input.item.MRN.
Use >= with the cursor so a row that shares the last stored timestamp is read again, not missed; the trigger skips rows at the stored cursor that already ran. Keep the LIMIT above the number of rows that can share one UPDATED_AT. See Duplicates and the cursor.
Troubleshooting
- Test connection fails with
JWT token is invalid. The public key on the user is not the pair of the profile's private key, or the account in the profile is not the one in your account URL. CompareDESC USER'sRSA_PUBLIC_KEY_FPwith the fingerprint of your key. - A step fails with
SQL compilation errorandVALIDATION_FAILED. The SQL refers to an object the role can't see, or the number of?s and values differ. It is not retried: fix the SQL or the role's grants. - The poll fails with
The poll has no cursor yet. Params has{ "cursor": true }but nocursorInitial. Add it. - A step fails with
TIMEOUTafter it was cancelled. The statement ran pastmaxWaitMs. Check the warehouse size and the query, or raisemaxWaitMsandstatementTimeoutSecondson the connection. - The package is refused at startup.
GET /api/health(signed in) gives the reason. See Custom adapters.