§7 — does this connector's discovery (DiscoverObjects/DiscoverFields → IntrospectSchema) return the
AUTHORITATIVE, COMPLETE gamut of objects/fields the credentials expose? Default false (safe):
a connector must explicitly affirm this. Override to true ONLY when DiscoverObjects hits a real
list/describe endpoint that returns EVERYTHING accessible — so an object/field absent from a refresh
genuinely means the source dropped it (and may be deactivated). Leave false for stubbed discovery
(returns nothing → static metadata is all we have), a cache-driven IntrospectSchema, or any
partial/scoped enumeration — there, absence proves nothing and MUST NOT deactivate.
The canonical integration name (e.g., "HubSpot", "Rasa.io"). Used by GetActionGeneratorConfig() and IntegrationActionExecutor to match connectors to action Config.IntegrationName.
Override in subclasses. Defaults to the class name.
HubSpot tolerates modest object-level parallelism; the engine's AIMD controller ramps toward this, with the token-bucket as the real backstop.
Whether the watermark this connector returns (FetchBatchResult.NewWatermarkValue) is a
RELIABLE, monotonically-increasing global maximum — i.e. the connector fetches in watermark
order so the last batch's value IS the true high-water mark, and an updated record always
re-surfaces at a NEW (higher) watermark. When true, the engine uses that watermark to NARROW
the next incremental (instead of advancing a full sync to wall-clock "now", and instead of the
keyset clear-and-re-scan), so incrementals fetch only what's new.
Default false — the safe, backwards-compatible choice: a connector whose source returns
records out of watermark order (e.g. HubSpot's creation-ordered list API, where the last batch
can carry old modstamps) MUST stay false so the engine keeps advancing to "now" and never saves
a stale watermark. Override to true ONLY when the source guarantees monotonic ordering.
~10 req/s sustained (honors MinRequestIntervalMs config) with a ~100-request burst window.
Whether this connector supports batched target writes (plan.md §7 aggressive batching).
Whether this connector supports creating new records in the external system.
Whether this connector supports deleting records from the external system.
Whether this connector supports reading/fetching records. Always true.
Whether this connector supports paginated listing of records.
Whether this connector supports searching/querying records with filters.
Whether this connector supports updating existing records in the external system.
Whether this connector supports idempotent upserts (create-or-update keyed
by a unique business property). Connectors override this AND Upsert to enable it.
ProtectedAppendAppends default query parameters from the IntegrationObject metadata. DefaultQueryParams is stored as a JSON object like {"key": "value"}. Automatically skips params whose key (case-insensitive) already appears in the URL to avoid duplicates with pagination params.
ProtectedapplyRuns TransformRecord, then RE-ADDS any source key the transform dropped (present in
raw, absent from the output) unless declared in ExcludedSourceKeys. This makes the
base-fetch path structurally full-record (§0 forward-compat contract): a TransformRecord
override may reshape/coerce but cannot SILENTLY drop a source key from ExternalRecord.Fields,
so the framework's custom-column capture sees everything the source returned. The default
identity transform returns raw unchanged → fast-path no-op (zero overhead, zero behavior
change for connectors that don't override TransformRecord).
ProtectedAuthenticateAuthenticate with the external system and return an auth context. Called once per FetchChanges invocation; the returned context is passed to BuildHeaders and MakeHTTPRequest for every request.
Batch-create. Default loops single-record CreateRecord, so the engine may always call the batch form.
Batch-delete. Default loops single-record DeleteRecord.
Batch-update. Default loops single-record UpdateRecord.
ProtectedBuildBuilds a CRUDResult for a record CREATE, failing LOUDLY when the external system returned no usable record ID. A 2xx response with an empty/undefined ID means the create did not durably produce a record we can track — returning Success:true there silently loses the record and causes duplicate creates on the next sync (the HubSpot-association class of bug, fixed in next commit 9f718a7e). This makes that failure explicit at the connector boundary.
ProtectedBuildBuild HTTP headers for an API request, including auth headers. Called before every HTTP request.
ProtectedBuildBuild the operation request body per BodyShape:
ProtectedBuildOverrides base pagination URL building to use HubSpot's parameter names.
HubSpot uses after for cursor pagination (not cursor), and needs
limit instead of pageSize. Also appends properties query param.
Optionalcursor: stringProtectedcomputePure decision for the next search window, given this page's pagination + total. No network.
after offset and keep
the same anchor.after, or it reached the 10k
cap). If records still match the current filter (total > cap), re-anchor the next window on
the last record's (dateField, hs_object_id) keyset; else the scan is complete.total is the count matching the CURRENT filter, so after each re-anchor it shrinks by roughly
one window until it falls to/under the cap — guaranteeing termination with no skipped records
(the anchor's id strictly increases) and no duplicates (the keyset predicate excludes it).
Creates a new record in HubSpot. Routes association objects to the v4 batch/create endpoint instead of v3 objects.
Deletes (archives) a record in HubSpot by ExternalID. Routes association objects to the v4 batch/archive endpoint instead of v3 objects.
Discovers all fields on a HubSpot object via the Properties API. Returns field types, constraints, PKs, and read-only flags from live metadata.
Discovery via the connector's READ PATH (FetchChanges), TIME-BOUNDED — the way to gather a statistically-significant sample when a single DiscoverFields sample is too small to PROVE a key. "Discovery is the sync read path with the save removed."
Loops FetchChanges as a read-only FULL fetch (WatermarkValue=null, nothing persisted), threading pagination/keyset cursors across batches, and streams every record through the data-informed field + provable-PK inference. It stops at the discovery TIME BUDGET (default 5 min), or a record cap, or source exhaustion — whichever comes first — so the provable-PK decision is made on as much real data as the budget allows. It NEVER fabricates a key: if even this larger sample yields no provable single/composite PK, the field set comes back PK-less and the object is honestly not added.
Falls back to the single-sample DiscoverFields if the read path can't run for this object (e.g. a connector whose FetchChanges needs an already-persisted IO row that doesn't exist yet).
Optionalopts: { BatchSize?: number; MaxRecords?: number; TimeBudgetMs?: number }ProtectedDiscoverStage-2 field discovery for sources WITHOUT a describe/introspection endpoint (file feeds,
undocumented JSON list endpoints): stream the source's actual records — READ-ONLY, no save,
no ack — and derive the full field set + data-informed PK/uniqueness/nullability from the
gathered statistics. The connector supplies whatever read-only fetch yields the records; this
helper turns that stream into ExternalFieldSchema[].
Why data-informed: streaming the real values lets pickPrimaryKeyFromStats pick the PK from
evidence (uniqueness/non-null statistics) COMBINED with the naming convention, rather than a
name guess alone. The PK is a SOFT key, so the pick is best-available, not strict-significance:
a confident unique+non-null column wins outright; otherwise a near-unique / convention-named
column is taken as a soft key (a PK-less object would stall CodeGen). The scan is time-bounded —
it stops on exhaustion OR opts.Discovery.TimeBudgetMs; more rows simply mean stronger claims.
Provable-only encoding into the standard flags:
IsPrimaryKey — set ONLY on the single statistics-first pick. Multiple equally-ranked unique
columns leave PK unset here (ambiguous → the pipeline's SoftPKClassifier LLM tiebreaker
decides, fed these same stats). Zero unique columns → no PK is fabricated.IsUniqueKey — set when the column was all-distinct over the scan AND uniqueness was provable
(the distinct-cap wasn't hit).AllowsNull — asserted true ONLY when a null/absent value was actually observed; otherwise
left undefined (permissive default). Never fabricates NOT NULL — critical under a time-capped
partial scan where unseen rows could still be null.The PK emitted here is SOFT (it rides additionalSchemaInfo via the persist + DDL path; it is
NEVER a hard DB key), so a wrong inference can never reject a valid row — the engine dedupes via
the record-map. IsReadOnly defaults to true (stream discovery targets read feeds); a writable
source overrides via opts.ReadOnly.
A read-only sync/async iterable of source records (the caller's fetch yields them).
Optionalopts: { Discovery?: StreamDiscoveryOptions; Pk?: PkPickOptions; ReadOnly?: boolean }OptionalDiscovery?: StreamDiscoveryOptionsTime budget / sample caps for the scan (see StreamDiscoveryOptions).
OptionalPk?: PkPickOptionsSignificance threshold + naming-rank tiebreaker (see PkPickOptions).
OptionalReadOnly?: booleanWhether discovered fields are read-only. Default true.
Discovers all HubSpot objects (standard + custom + non-CRM + associations) via live API and static lists.
ProtectedDiscoveryDISCOVERY-ONLY: last-resort SAFETY bound on the recursion depth for multi-level template chains (a
parent that is itself a template-var child), so a malformed metadata cycle cannot loop unboundedly.
This is only the fallback when the consumer sets no discoverySampleMaxDepth in Configuration and
no env override is present — the consumer decides the real value. A recursion cap MUST have some
bound, so a conservative default remains here; override the getter to change the fallback.
ProtectedDiscoveryREST override (§sample-discover): a SINGLE-template-var CHILD is sampled with the recursive, record-constrained StreamRecordsForDiscovery. Flat objects fall back to the generic FetchChanges loop; MULTI-var (composition) children are deferred — StreamRecordsForDiscovery adjourns them (declared-only until first sync) rather than fire malformed URLs.
ProtectedExcludedSource keys a connector DELIBERATELY removes in its TransformRecord override (vendor noise, a flattened parent blob, a nested child collection emitted as its own object). These are the only sanctioned drops — excluded from the applyTransformPreservingKeys re-add. Default: none. Override per-object to declare intentional removals.
ProtectedExtractBest-effort error message extraction from a vendor response. Override for vendor-specific shapes.
ProtectedExtractExtract the new record's external ID from a create response per IDLocation.
ProtectedExtractExtract pagination state from the vendor-specific response.
The parsed response body
The pagination strategy for this object
Current page number (1-based)
Current record offset
Page size used in the request
Pagination state indicating whether more data is available
HubSpot rate-limits on a rolling 10-second window; on a 429 that escaped internal retries, back off ~10s.
Overrides FetchChanges to support three fetch strategies:
hs_lastmodifieddate >= watermark filterProtectedFetchFetches changed records using the HubSpot search API with server-side date filtering. Much more efficient than fetching ALL records and filtering client-side.
Handles the search API's 10,000-results-per-window hard cap by keyset re-anchoring: results
are sorted by (dateField, hs_object_id) ASCENDING, paginated within a window by the API's
opaque after offset, and once that offset hits the 10k cap the NEXT window re-anchors with a
compound filter (dateField > anchor) OR (dateField == anchor AND hs_object_id > anchorId).
This makes an incremental window — or a bulk-import cluster of >10k records that all share one
hs_lastmodifieddate — page through completely in a single sync, instead of the watermark
stalling on a same-timestamp cluster it can never advance past (which silently lost records).
The date GTE watermark remains the primary filter throughout, so incremental sync is preserved.
LIVE-VERIFY (confirm during the credentialed run against a real >10k same-timestamp cluster):
total reflects the CURRENT filterGroups per re-anchored query (not a cached original count).Returns the ActionGeneratorConfig for this connector, combining the integration name, category, icon, and objects into a ready-to-use configuration for ActionMetadataGenerator.Generate().
Override in subclasses to customize the config (e.g., icon, category). Returns null by default if GetIntegrationObjects() returns empty.
ProtectedGetGet the base URL for API requests (e.g., "https://api.example.com/v1"). Combined with the object's APIPath to form the full request URL.
ProtectedGetGets IntegrationObjectField records from the engine's cache for a given object ID. Returns only active fields sorted by Sequence.
ProtectedGetGets an IntegrationObject from the engine's cache by integration ID and object name. Throws if not found.
Returns a proposed default configuration for quick setup. Override in subclasses to provide connector-specific defaults including schema name, objects to sync, and field mappings. Returns null by default (no quick setup available).
Returns suggested default field mappings for an external object to MJ entity. Override in subclasses to provide intelligent defaults.
Name of the external object
Name of the target MJ entity
Array of default field mappings (empty by default)
Returns the integration objects and their fields that this connector supports, for use by the ActionMetadataGenerator. This is static metadata that does NOT require a live connection — it describes the connector's known object model.
Override in subclasses to provide connector-specific objects/fields. Returns an empty array by default (no action generation available).
Retrieves a single record by ExternalID (HubSpot object ID).
Full schema introspection — discovers all objects and their fields from the live API.
Lists records from a HubSpot object with cursor-based pagination.
ProtectedMakeExecute an HTTP request. The concrete connector owns the transport layer (fetch, axios, got, etc.).
Optionalbody: unknownMaps HubSpot type + fieldType to a simplified data type string
Converts a HubSpot property definition to ExternalFieldSchema format
ProtectedNormalizeExtract the data array from the vendor-specific response envelope.
The parsed response body
The key to extract data from, or null for root-level arrays
Array of raw record objects
ProtectedparseParses the HubSpotSearchCursor threaded via FetchContext.CurrentCursor. Tolerates a
legacy raw after string (pre-keyset format) by treating it as a plain window offset, so an
in-flight sync mid-upgrade degrades gracefully rather than throwing.
Type-driven post-processing hook (plan.md §10): a connector may normalize/enforce a record's
values to the resolved column formats AFTER transform/normalize and BEFORE write. Default
returns the record unchanged. (Named for this system — NOT MCP, not take.) The engine ALSO
applies target-type constraint enforcement; this is the connector-side complement.
Searches HubSpot objects using the CRM search API.
Name of a stable, monotonic ordering key (PK/identity) usable for KEYSET/seek resume on
watermark-less objects (plan.md §7 — resume from last-seen key, robust to mid-stream
insert/delete). null → keyset resume unavailable for this object.
ProtectedSubstituteSubstitute the ExternalID into a URL path template at runtime. Path templates may use {ID}, {id}, or {ExternalID} as the placeholder; for symmetry with FetchChanges template-var handling, any unsubstituted {var} in the template is left in place (caller's responsibility to ensure consistency).
For IDLocation='body' or 'header' the ID is not substituted into the path (caller must handle separately); we just return the raw path.
ProtectedTemplatePer-call cap on how many PARENTS a parent-iterated object processes before yielding a resumable batch (the engine loops on HasMore). Kept conservative so a single FetchChanges call fits the engine's op-timeout even at a slow initial adaptive rate; the AIMD bucket ramps up over batches. Override in a concrete connector if a vendor tolerates larger per-call parent runs.
Tests connectivity by authenticating and fetching 1 contact.
ProtectedTransformOptional per-record CUSTOMIZATION hook called between NormalizeResponse (vendor envelope-stripping) and ToExternalRecord (composite-PK assembly).
Distinct from NormalizeResponse — that strips the vendor's response envelope to expose individual records. This hook is for vendor-specific record-level customization the standard pipeline shouldn't carry: nested-field flattening, empty-string→null coercion for date columns, computed fields, removing vendor metadata blobs (e.g. Salesforce 'attributes'), etc.
Default is identity (no transform). Override only when a concrete connector needs vendor-specific shape changes.
Updates an existing record in HubSpot by ExternalID. For association objects, re-creates the association (idempotent in HubSpot).
Idempotently creates-or-updates a record keyed by a unique business property
(default: the object's UpsertKey metadata, e.g. 'email' for contacts).
Uses HubSpot's batch/upsert endpoint with a batch of one. This is the ONLY HubSpot single-call idempotent path verified against the live API: the single-record PATCH .../{id}?idProperty=email does NOT create-on-missing (returns 404), while POST .../batch/upsert creates-on-missing and updates-on-existing with a 2xx (no 409). A batch of one sidesteps the documented batch caveats (whole-batch-409 on concurrent batches, no partial upserts) that only bite multi-input batches.
This defines the error out of existence: a search-then-create sequence has a window in
which a concurrent writer can create the same email-keyed contact, yielding
409 Contact already exists. Rather than catch and special-case that 409, the single keyed
upsert removes the window entirely — the collision is no longer a condition the caller (or
this code) ever has to handle.
Connector for HubSpot CRM via the HubSpot REST API v3.
Extends BaseRESTIntegrationConnector to leverage metadata-driven object/field discovery from IntegrationEngineBase cache and generic pagination handling.
Uses Bearer token authentication with a HubSpot Private App access token (API Key auth). Supports cursor-based pagination and automatic response flattening.
Configuration JSON (on CompanyIntegration) supports optional rate limit overrides: { "accessToken": "...", "MaxRetries": 5, // optional, default: 5 "RequestTimeoutMs": 30000, // optional, default: 30000 "MinRequestIntervalMs": 100 // optional, default: 100 }
Supports full CRUD: Get, Create, Update, Delete, Search, and List operations on all HubSpot CRM object types.