@hs-x/sdk
v0.4.10
Published
HS-X SDK — typed worker/handler surface for HubSpot apps.
Readme
@hs-x/sdk
@hs-x/sdk is the authoring surface for HS-X, a type-safe HubSpot app framework
that deploys to Cloudflare Workers. You import it to declare your app and its
capabilities: workflow actions and agent tools, card backends, triggers, syncs,
app objects, and app events. The hs-x CLI compiles those declarations into
HubSpot project artifacts and a Cloudflare Worker, then deploys them into your
own HubSpot developer app and your own Cloudflare account.
Install
bun add @hs-x/sdk @hs-x/runtimeThese are the two dependencies an HS-X app lists; hs-x init scaffolds them for
you. Backend code imports from @hs-x/sdk. Card code that runs inside a HubSpot
iframe imports from @hs-x/sdk/ui.
Thirty seconds
An app is an hsx.config.ts plus one or more workers. This is the default
scaffold, a workflow action that tags high-value deals:
// hsx.config.ts
import { defineApp } from "@hs-x/sdk";
export default defineApp({
name: "deal-tagger",
distribution: "private",
auth: "oauth",
platformVersion: "2026.03",
scopes: ["crm.objects.deals.read", "crm.objects.deals.write"],
});// src/workers/deals.ts
import { defineWorker, ok } from "@hs-x/sdk";
const worker = defineWorker("deals");
worker.tool("tag-high-value-deals", {
label: "Tag high value deals",
objectType: "deal",
input: {
threshold: { type: "number", label: "Amount threshold", default: 50000 },
},
output: {
tagged: { type: "boolean" },
},
async handler({ input, enrolledObject }) {
const amount = Number(enrolledObject.properties.amount ?? 0);
return ok({ tagged: amount >= input.threshold });
},
});
export default worker;hs-x dev runs the local loop, hs-x dev invoke tag-high-value-deals exercises
the handler through the same dispatch path a deployed Worker uses, and
hs-x deploy ships it.
Exports
Declaration factories:
| Export | Declares |
| --- | --- |
| defineApp | The app: name, distribution, auth mode, platform version, scopes, cards, app objects/events (hsx.config.ts) |
| defineWorker | A worker grouping; its builder methods (tool, action, cardBackend, trigger, sync, use) register capabilities |
| tool | A HubSpot custom workflow action; an agent block additionally exposes it to agents |
| action | Exact alias of tool for people who think in HubSpot's native term |
| cardBackend | A backend handler a UI card calls over the dispatch route |
| trigger | A HubSpot webhook/event handler, keyed by eventType |
| sync | A scheduled or event-driven sync into a HubSpot object |
| defineSource | A pull source with a fetch({ cursor, http }) function; defineSource.push declares a webhook push source with receive({ event }) |
| card | A UI-extension card, passed to defineApp in cards |
| mcpServer | A HubSpot Breeze MCP server component, passed to defineApp in mcpServers (2026.09 beta+) |
| appObject, appObjectAssociation, appEvent | App-owned CRM schema declarations |
| usesScopes | Honor-system scope annotation for raw HubSpot calls |
Result helpers, returned from a handler: ok, failContinue, failStop,
retryLater, block. A handler may also return a plain output object, which
the runtime normalizes to ok(output). There is no ctx.success() or
ctx.fail(); the helpers are standalone functions.
Feature-flag evaluators, pure functions with no I/O: evaluateFlag,
evaluateFlags, evaluateBooleanFlag, evaluateStringFlag,
evaluateNumberFlag, evaluateJsonFlag, and createHsxOpenFeatureProvider,
which wraps the same evaluator as an OpenFeature-compatible provider.
Field-type helpers: normalizeHubSpotFieldType, defaultHubSpotFieldType,
HUBSPOT_FIELD_TYPE_MAP. The package also exports SDK_VERSION and re-exports
the key types (AppDefinition, WorkerDefinition, ToolDefinition,
TriggerDefinition, SyncDefinition, CardBackendDefinition,
HandlerContext, InstallContext, ActionResult, and friends).
Breeze MCP server components
Breeze MCP server registration is a HubSpot project component, distinct from the
HS-X authoring MCP package (@hs-x/mcp). It requires OAuth and HubSpot platform
version 2026.09-beta or newer:
import { defineApp, mcpServer } from "@hs-x/sdk";
const customerData = mcpServer("customer-data", {
name: "Customer Data",
description: "Search customer records from Breeze.",
mcpUrl: "https://mcp.example.com/server",
mcpClientId: "customer-data-client",
requiredScopes: ["crm.objects.contacts.read"],
websiteUrl: "https://example.com",
privacyPolicyUrl: "https://example.com/privacy",
});
export default defineApp({
name: "customer-data-app",
distribution: "marketplace",
auth: "oauth",
platformVersion: "2026.09-beta",
scopes: ["crm.objects.contacts.read"],
mcpServers: [customerData],
});The helper defaults uid to its id, version to 1.0.0, and enabled to
true. Deploy rejects non-HTTPS and obvious local/private mcpUrl hosts; DNS
reachability remains a runtime concern and cannot be proven during codegen.
The handler context
Every capability handler receives a single HandlerContext value. Destructure
what you need:
async handler({ input, enrolledObject, install, hubspot, flags, logger }) {
const config = await install.config<{ datasetId: string }>();
const useV2 = (await flags?.getBoolean("enrichment-v2", false)) ?? false;
// ...
return ok();
}Its fields: input (resolved input values, never HubSpot property references),
enrolledObject (id, objectType, properties), install (install id,
portal id, state, and config<T>()), env, hubspot (an install-scoped,
rate-limit-aware HubSpot client), appObjects, appEvents, http, logger,
request, plus optional billing, sync, and flags. The flags getters
(getBoolean, getString, getNumber, getJson) run an edge evaluation and
fail safe to the default you pass, so a flag read can never break a handler.
appEvents.send auto-batches per install by default at 500 occurrences or 5
seconds; override it in hsx.config.ts with
appEvents: { batching: { maxSize, maxDelayMs } }.
HubSpot calls made through hubspot retry 429/5xx responses by default with
{ max: 5, baseMs: 200, capMs: 10000 } and use separate general/Search buckets;
override those defaults with rateLimits in hsx.config.ts.
Syncs
A source owns auth and fetching; worker.sync owns the HubSpot-facing target,
schema, and schedule. Pull sources page with an opaque cursor:
import { defineSource, defineWorker } from "@hs-x/sdk";
const tickets = defineSource({
name: "tickets",
auth: { type: "bearer", token: process.env.TICKETS_TOKEN },
async fetch({ cursor, http }) {
const { body } = await http.get(`https://api.example.com/tickets?since=${cursor ?? ""}`);
const page = body as { items: { id: string; subject: string }[]; next?: string };
return {
cursor: page.next,
rows: page.items.map((t) => ({ key: t.id, data: { subject: t.subject } })),
};
},
});
const worker = defineWorker("sync");
worker.sync(tickets, {
schedule: "*/15 * * * *",
into: "p_ticket",
schema: { subject: "string" },
manageSchema: "full",
});Each row's key is the stable identity used to upsert, so re-running a sync
updates rather than duplicates. defineSource.push({ auth: { type: "hmac", ... },
receive }) declares a webhook-driven source instead, turning inbound events
into rows through its receive({ event }) function. With manageSchema,
deploy plans portal property creation from the declared schema
(hs-x deploy --apply-schema applies the managed changes).
Agent tools
A tool with an agent block is also surfaced to HubSpot agents. Exposure is
explicit: only the inputs you list in expose become agent-callable arguments,
so adding a workflow input later never silently widens the agent surface.
worker.tool("enrich-company", {
label: "Enrich company firmographics",
objectType: "company",
input: {
depth: { type: "enumeration", options: ["basic", "full"], default: "basic" },
},
agent: {
description: "Use when a company record is missing firmographic data.",
expose: ["depth"],
},
async handler({ input }) {
return ok({});
},
});The @hs-x/sdk/ui surface
Card code runs inside a HubSpot iframe, not in your Worker, and imports from the
/ui subpath (the main entry is backend-only):
import { createFlagsSnapshotProvider, logger } from "@hs-x/sdk/ui";
logger.info("card mounted");
const flags = createFlagsSnapshotProvider({
"enrichment-v2": { value: true, reason: "targeting_match" },
});
const showBeta = flags.getBoolean("enrichment-v2", false);logger mirrors the @hubspot/ui-extensions logger and, when running under
HubSpot's local dev server, also forwards each line to the HS-X dev sidecar so
it lands in your terminal. enableHsxDev(url?) and disableHsxDev() override
the auto-detection. Feature flags are server-only at launch: a trusted card
backend evaluates through ctx.flags and returns an inert snapshot.
createFlagsSnapshotProvider reads that snapshot synchronously and fails safe
to supplied defaults; the UI bundle has no endpoint, signer, or grant bootstrap.
@hubspot/ui-extensions is an optional peer dependency, imported dynamically.
React flag reads
React cards put the server-delivered snapshot behind FlagsProvider and read
several flags with useFlags from the isolated /ui/react subpath:
import { Text } from "@hubspot/ui-extensions";
import type { UiFlagsSnapshot } from "@hs-x/sdk/ui";
import { FlagsProvider, useFlags } from "@hs-x/sdk/ui/react";
declare const flagsSnapshot: UiFlagsSnapshot; // signed card-backend response
const defaults = {
"beta-card": false,
"card-density": "comfortable",
};
function CardBody() {
const { flags, details, isLoading } = useFlags(
["beta-card", "card-density"],
defaults,
);
const mode = flags["beta-card"] ? "Beta" : "Stable";
return (
<Text>
{isLoading
? `${mode} with defaults`
: `${mode} · ${flags["card-density"]} · ${details["beta-card"]?.reason}`}
</Text>
);
}
export function Card() {
return (
<FlagsProvider initialSnapshot={flagsSnapshot}>
<CardBody />
</FlagsProvider>
);
}Defaults cover missing or mistyped snapshot values. useFlags must be called
below a provider. Replacing the snapshot object starts a new cache epoch. Only
/ui/react imports React, so the base /ui entry remains usable without the
optional React peer.
The @hs-x/sdk/experimental surface
Helpers that are declared but not yet delivered end-to-end live under
@hs-x/sdk/experimental so the main entry only advertises what ships. Today
that is the feature-flag CRM projection family (featureFlagAppObject,
flagDefinitionToAppObjectRecord, flagToCompanyAssociation,
flagToContactAssociation, and related constants). Expect this surface to
change between releases.
Leaveable by design
The compiled Worker runs in your Cloudflare account and talks to HubSpot
directly with your tokens; HS-X is not in the request path. The generated
.hs-x/alchemy.run.ts, checked into your repo, describes the Cloudflare
resources your app owns, so the app keeps running and stays deployable even if
you stop using HS-X.
Docs
Guides and reference live at hs-x.dev/docs, starting
with the getting-started guide. The CLI is
@hs-x/cli on npm (the installed
commands are hs-x and hsx); the Worker runtime is
@hs-x/runtime.
License
Apache-2.0
