This guide is for maintainers adding or changing integration kinds. For
deployment configuration, project administration, and notebook usage, see the
integrations guide. The object layout and
concurrency protocol are specified in
bucket_spec.md §4.12.
Integrations store versioned configuration for connections, runtime tools, and agent context. Each kind renders its contributions. Browsing and connection tests are optional.
Integrations follow the repository's ports-and-adapters boundary:
packages/core/src/ports/integrations.tsdefines the provider and render contracts used by the API and session pipeline.packages/core/src/services/integrations/sdk.tsdefines a kind: its Zod config schema, UI hints, renderer, optional connectivity probe, and migration.packages/core/src/services/integrations/registry.tsturns registered definitions into JSON Schema descriptors for the API and web form.packages/core/src/services/integrations/ProjectIntegrationsStore.tscontains shared storage, versioning, name-claim, secret, migration, and rendering logic.ProjectIntegrationsStoreuses this logic underprojects/{pid}/integrations/.OrgIntegrationsStoreuses it under_system/integrations/.packages/core/src/services/integrations/bundle.tsmerges rendered files and environment variables into the session payload. Structured YAML fragments sharing a path are recursively merged, with conflicting leaves rejected.packages/api/src/routes/integrations.tsexposes management routes, whilepackages/api/src/routes/sessions.tsresolves enabled integrations during provisioning.
Concrete deployment wiring stays in packages/config and entrypoints. Core and
API code must not import vendor adapters.
The kind's Zod schema is the source for write validation, secret-field discovery, generated JSON Schema, and the schema-driven web form. At session launch, the store loads each enabled integration's current version and migrates it to the current kind schema. It decrypts managed fields and resolves external references before it calls the renderer. The session then records that version as its audit pin. Rendered files and environment variables are bundled outside the notebook workspace so credentials cannot be captured in a notebook version.
Before rendering, ProjectIntegrationsStore combines the project and
organization tiers. It includes each enabled organization integration unless
the project has an integration with the same name. The project entry takes
precedence even when it is disabled. This rule supports overrides and opt-outs,
and it prevents duplicate names in the bundle.
The renderer receives the session's project ID for integrations from either
tier. Organization configuration and secret-encryption contexts remain under
_system/. The /api/v1/org/integrations routes call assertSuperAdmin, which
uses MARIMOHUB_SUPER_ADMINS.
- Define the kind under
packages/core/src/services/integrations/kinds/and export it fromdefinitions.ts. - Add a sample to
kinds/sampleConfigs.tsand tests for the kind's behavior. - Document the kind in
docs/integrations.mdand runpnpm schemas:generate.
The registry loads every exported definition. Routes, forms, schemas, and field references come from that registry.
export const postgres = defineIntegration({
kind: 'postgres',
title: 'PostgreSQL',
description: 'Direct Postgres connection for SQL cells and SQLAlchemy.',
category: 'database',
brand: { color: '#4169E1' },
schemaVersion: 1,
configSchema: z.object({
host: z.string().min(1),
port: z.number().int().min(1).max(65535).default(5432),
password: zSecret(),
}),
requirements: ['sqlalchemy>=2'],
uiHints: { host: { group: 'Connection', order: 1 } },
render({ config, instanceName }) {
const segment = envSegment(instanceName);
const hostEnv = `MARIMOHUB_PG_${segment}_HOST`;
return {
env: { [hostEnv]: config.host },
files: [
{
path: `postgres/${instanceName}.json`,
content: JSON.stringify({ host_env: hostEnv }),
},
],
};
},
});The kind discriminator is permanent; changing it is a data migration. Keep
render pure and synchronous: all session-specific values arrive in its input,
and identical input must produce byte-identical output.
requirements is informational. It is shown in the UI and written to the
integration manifest, but the hub does not install or preflight those packages.
For installed tools, use runtimePackages in the render output.
| Extension point | Responsibility |
|---|---|
configSchema, uiHints |
Validation, secret fields, generated forms, and file import controls |
validate, migrate |
Cross-field rules and stored schema upgrades |
render |
Pure configuration and runtime contributions for one workload |
testConnection |
Optional connection check through the guarded probe |
browse, objectBrowse, databaseBrowse, preview |
Optional data access capabilities |
packageRegistry |
Optional credential resolution before rendering |
Data access and connection tests are optional. All kinds share versioning, inheritance, and authorization.
Use boundedText for UTF-8 limits, or textFileContent for nonblank text files without NUL characters (64 KiB maximum).
A textarea with file_accept: ['.sh'] imports file contents into its configuration field.
RuntimeContributions is the common contract for rendering, environment composition, and launch planning.
mergeRuntimeContributions carries its fields through each stage. Kinds that use existing contributions need no launch or adapter changes.
Render script contents through files and list their relative paths in startupScripts.
Each path must reference a file from the same integration. The bundler rejects invalid paths, duplicate execution, and file collisions.
It sorts integrations by name and preserves script order within each integration.
The shared launch planner applies the startup script execution contract.
It uses the existing setup deadline and failure reporting. A failure prevents launch and destroys the sandbox.
Only the current bundle selects scripts, so stale snapshot files cannot activate disabled hooks.
Use workspaceLoadMode: 'copy-only' for scripts that need local filesystem semantics, as the startup_script kind does.
runtimePackages accepts exact index pins such as marimo-studio[deno]==0.4.1.
mergeRuntimePackages normalizes names, combines extras, and rejects version conflicts or marimo overrides.
Paths, URLs, markers, installer flags, and version ranges are unsupported.
SessionEnv carries these packages to runtimePackageCommand.
After notebook dependency setup, this helper resolves the layer once with uv run --with and starts the process.
It uses the configured package registries and pins marimo to the installed base version.
The local backend supplies marimo through uv run --with marimo for both the version lookup and launch.
Other layer packages override base packages. Resolution failure stops launch.
The layer covers the notebook process, bridge, and children. Independent terminals use the base environment.
Resolution adds no sandbox request and uses the existing startup deadline or job execution timeout. Boot, credential injection, and bridge upload remain concurrent. The base environment and dependency files remain unchanged. Removal omits the layer on subsequent launches, including snapshot restores. Caches and notebook-declared dependencies can remain.
See kinds/marimoStudio.ts for an example. Its experimental label is display text only.
For each new contribution, document its destination, precedence, and behavior after update, disable, delete, and snapshot restore.
Renderers cannot edit workspace files. Persistent source changes require an ownership and cleanup contract.
See Changes and removal for existing cleanup behavior.
Return presentation: { css, htmlHead } from render; both text fields are optional (PresentationContent).
composePresentation builds separate CSS assets and one combined HTML fragment, ordered by integration name.
Assets live under /tmp/marimohub-integrations/presentation/ and pass the bundler's path collision checks.
Their paths form PresentationFiles, carried by RuntimeContributions.marimoPresentation.
mergePresentationFiles deduplicates CSS paths in order and rejects conflicting HTML head paths.
Before injection, prepareMarimoPresentation sets display.custom_css in the generated marimo.toml, preserving editor and AI settings and resolving local compute paths.
Apps and jobs also receive _MARIMO_APP_OVERLOAD_HTML_HEAD_FILE, which overrides the notebook's head file for that launch.
Editors omit this override so saves cannot persist generated paths into notebook source.
Snapshot restores rebuild configuration from current contributions, leaving retained assets unreferenced when disabled.
Without an active HTML head contribution, restores set the override to the literal string None.
Marimo treats this as unset; an empty string does not clear the override correctly.
See Custom CSS and HTML head for configuration precedence, scope, and user examples.
Render workspaceLoadMode: 'copy-only' for tools that require local filesystem semantics, such as Studio.
The bundler and environment merger preserve this requirement from any integration.
Mount-capable launches await the existing integration result before choosing the loader. They make no additional resolution request.
Existing copy-only paths still prefetch during integration resolution and boot.
The copied workspace uses the existing save flow. Disabling the integration restores the source's normal loading policy on subsequent launches.
kinds.test.ts requires every registered kind to stay within the form
renderer's supported JSON Schema dialect:
- strings, numbers, integers, booleans, and enums;
- nested objects and discriminated unions;
z.record(z.string(), z.string())for key/value fields;- arrays of objects; and
zSecret()for secret-bearing strings.
Scalar arrays and other unsupported constructs fail the schema-dialect test so
they cannot reach users as uneditable forms. uiHints can control presentation
such as grouping, order, widgets, and advanced sections, but must not change
validation or storage semantics.
Renderers emit relative POSIX file paths, mergeable YAML fragments, and environment variables. The bundler rejects:
- absolute paths, backslashes, empty segments,
.or..; - the reserved
manifest.jsonpath; - malformed or process-sensitive environment variable names; and
- conflicting file paths or environment values across integrations.
Use yamlFiles only when multiple instances must contribute to one
tool-owned configuration document. Leaves must be scalar/array/object data and
must either be unique or byte-equivalent after JSON serialization; the bundler
fails on divergent values rather than choosing an owner.
Kinds live in core, so they cannot import vendor SDKs. Render text files and
environment variables instead. The bundle is placed under
/tmp/marimohub-integrations, outside the notebook workspace.
Kinds in the package_registry category configure uv package indexes; user
docs are in docs/integrations.md#package-registries. A kind's render returns
packageIndexes (name, URL, default flag) and keeps credentials out of URLs.
Static Python indexes share definePythonIndex in kinds/pythonPackageIndexes.ts.
Each definition supplies its schema and a pure URL/credentials mapping.
The helper validates that mapping locally before rendering or testing a connection.
Connection tests make network requests only through IntegrationProbe.
Static credentials require no credential adapter.
Kinds that mint credentials (aws_codeartifact) declare packageRegistry with a credential source; the index URL still comes from the preset's connection mapping, which receives the minted credentials.
Before rendering, the store resolves credentials through PackageRegistryCredentialProvider.
The Node configuration supplies the AWS adapter and guarded probe. AWS requests use explicit credentials, never the server's ambient identity.
static auth uses the stored access key; ambient auth uses project WIF credentials from a lazy resolver that session and job callers supply.
A missing resolver or project WIF fails the render; there is no fallback to public PyPI.
The bundle combines packageIndexes into UV_INDEX and UV_DEFAULT_INDEX, and writes credentials to
UV_INDEX_<NAME>_USERNAME / UV_INDEX_<NAME>_PASSWORD.
A custom_env UV_INDEX is merged after the registry entries, with duplicates removed.
A second default index, or a custom_env UV_DEFAULT_INDEX that differs from the registry's, fails the bundle; an identical value is tolerated.
Restricted-viewer renders skip integrations entirely, so they get no index configuration.
In SandboxProvisioner, dependency setup and its timeout start after credential injection.
testConnection must access the network only through the injected
IntegrationProbe. Never use ambient fetch. The probe is the deployment's
SSRF boundary: the Node adapter validates and pins resolved addresses, blocks
redirects, caps response size and time, and rate-limits requests.
HTTP-native kinds use fetch. Protocols without an HTTP endpoint may use
connect for DNS, TCP, and optional TLS reachability only; it does not validate
application-protocol authentication.
When no probe is wired, every kind reports supports_test: false. This is the
case for the Cloudflare Worker example because Workers do not expose the DNS
hooks needed to pin validated addresses.
Probe results and errors must never include credentials or resolved plaintext secret values.
A kind can implement BrowseCapability when it has an HTTP metadata API. The
capability lists namespaces, tables, and schemas. It also creates a notebook
snippet. MARIMOHUB_DATA_BROWSER controls access to this capability.
Object stores implement the provider-neutral ObjectBrowser port separately from table
BrowseCapability. The S3 adapter lives in packages/object-browser-s3; only packages/config
imports it. Core owns source/context/result contracts, and API/web dispatch on the advertised
tables or objects surface instead of importing provider code.
Kinds can implement previewRows for bounded reads through the guarded HTTP
path. Otherwise, IntegrationDefinition.preview emits DuckDB SQL and/or Python
programs. DataPreviewService selects DuckDBWasmDataPreview first when its
required runtime features are healthy, then SandboxDataPreview. Neither
executor switches on integration kind.
The DuckDB SDK lives in packages/duckdb-wasm-runtime. Core owns only the runtime-neutral orchestration seam.
The Node implementation locks its configuration and runs each result query in a read-only transaction.
The unbrokered runtime disables external access. Its Node file callbacks reject all remote protocols.
The configured runtime advertises guarded-http and uses a parent-owned HTTP broker.
It keeps iceberg-http as a compatibility alias.
The worker submits synchronous requests through fixed shared-memory buffers.
The parent authorizes each target, injects credentials, checks DNS results, and pins the socket.
The Iceberg integration supports explicit S3 prefixes, parent-owned OAuth2, Cloudflare R2, and bounded vended S3 routes. Generic vended routes must stay inside administrator-owned storage bounds.
R2 uses a bearer token and a bound from the catalog URI. The S3 integration supports exact Parquet and CSV object reads from configured prefixes. Unsupported authentication, storage, TLS, delegation, and runtime options use the sandbox executor. See the DuckDB-Wasm Iceberg HTTP broker for the security boundary and test procedure.
Parent-owned OAuth2 and guarded S3 object queries are enabled whenever Run SQL is. The query gate is evaluated before secret resolution and again after resolved configuration is loaded, so a concurrent integration update cannot bypass it.
The sandbox adapter renders only the selected integration. It uses
MARIMOHUB_DATA_PREVIEW_IMAGE and injects applicable WIF credentials.
The first sandbox preview validates the image's runtime dependencies. Replica startup
does not create a sandbox for this check. Missing or incompatible Python imports
produce an error that identifies the import and points to the image setting.
DuckDB-Wasm still initializes during replica preflight.
Per-user and process-wide limits control admission across both executors.
Deadlines bound startup and execution. A finally block destroys each sandbox;
DuckDB failures poison and close the affected engine slot before later traffic.
Run SQL has a separate, fail-closed DataQueryService contract and does not
reuse trusted preview programs. It selects an executor from the plan's engine.
The Node composition root wires a fresh DuckDB-Wasm worker per request only when
MARIMOHUB_DATA_BROWSER=full. The
route remains in OpenAPI while the runtime is disabled and returns 404.
Read-only execution, one-statement validation, row, byte, memory, concurrency,
and deadline limits apply; inline execution is forbidden.
Database-native browsers use DatabaseBrowseDefinition and the DatabaseBrowser port. The
definition creates a closed connection capability from resolved configuration. Only the matching
adapter can open it. PostgreSQL uses one worker and one connection per operation. The adapter pins
guarded DNS results, preserves the original hostname for TLS, streams arrays with a cursor, and
normalizes values before they cross the worker boundary. Its query plan uses the postgres engine
and advertises the postgresql dialect. The insecure-transport switch is checked before secret
resolution.
BigQuery also implements DatabaseBrowser, through packages/database-browser-bigquery.
Its adapter signs service-account assertions and sends requests through the injected
guarded probe. It uses fixed Google API and token endpoints. Metadata and connection
tests use separate probe budgets. The core kind rejects ambient authentication before
browse operations resolve secrets. The adapter permits base-table previews only in full mode.
Databricks implements the HTTP BrowseCapability. Its probe exchanges OAuth M2M credentials
at the workspace token endpoint, then reads Unity Catalog metadata. PAT configurations
skip the exchange. Each operation has one deadline across authentication and metadata requests.
Neither connection tests nor metadata browsing execute warehouse queries.
All network access must use the injected browse probe. This probe has a separate request budget and a larger response limit than the connection-test probe.
Browse errors must not include secrets. defineIntegration replaces transport
errors with a generic failure. It also replaces a DomainError that contains a
schema-marked secret value.
browse.available(config) checks whether the hub supports one stored instance.
For example, it can reject unsupported authentication methods or TLS material.
This function receives secret placeholders, so it must not inspect secret
values.
The kind descriptor uses supports_browse to report kind-level support. The
GET …/browse route reports support for one instance. All browse routes require
the editor role or a higher role.
The API resolves a browse ID in the project tier before the organization tier. A project integration shadows an organization integration with the same name. Browse operations do not write to the bucket.
S3 content routes are the raw-response exception to the JSON envelope on success. They authorize
and resolve the integration before opening a stream, accept at most one byte range, set no-store and
nosniff headers, sanitize Content-Disposition, and release the provider client on completion,
failure, deadline, or client cancellation. Pre-stream failures still use the standard envelope.
Metadata lists use a short state-token cache. Short-lived federated credentials are cached in memory
until their refresh window; details, search, previews, tags, versions, streams, provider clients, and
failures are not cached. Explicit preview/download reads append audit events; navigation does not.
Live S3 transport behavior is covered by
objectBrowseContract against pinned MinIO in the Object browser conformance workflow.
Servers differ in pagination and namespace addressing, so the iceberg_rest
client filters listings to direct children, stops on a non-advancing page
token, and honors a namespace-separator declared by /v1/config.
Every browsable kind must provide a shared live suite: browseContract
(@marimo-hub/core/testing/browse-contract) pins the cross-kind guarantees —
roots without descendants, exact direct children under a parent, tables in
their namespace, schema round-trip — while the kind supplies config, probe,
and seeding. See icebergRest.browse.live.test.ts for the shape; suites gate
on a MARIMOHUB_TEST_* env var and skip otherwise. On every PR, the
Catalog conformance workflow runs the Iceberg REST, Trino, ClickHouse, and
PostgreSQL suites against pinned containers. Add new container-backed kinds
and their env vars there. Databricks and BigQuery require hosted credentials
and do not run in this workflow; see Databricks and BigQuery live suites
for their separate live-validation setup.
Mark secret-bearing string fields with zSecret(). The framework derives their
paths from JSON Schema and transforms values through three shapes:
| Context | Shape |
|---|---|
| Authoring | Plaintext string or the keep marker |
| Stored | { $secret: { kind: 'managed', envelope: … } } |
| API read | { $secret: { set: true } } |
Encryption context combines the integration head path with the wildcard field path. A secret in an array therefore remains decryptable after item reordering, but an envelope copied to another integration or field does not.
Every array item that contains zSecret() must have a required, unique, and
stable name field. Keep-marker resolution uses this field to match an edited
item to its stored value. Without it, matching falls back to the array position.
Deleting or reordering items can then attach stored ciphertext to the wrong
item.
The custom_env.secret_bundles schema follows this rule. Its deletion and
reorder tests make sure that each retained ciphertext stays with its named
bundle. Add the same coverage for every new secret-bearing array.
Do not move a zSecret() field in a normal schema migration. Its envelope is
bound to the old path and must be decrypted and resealed under the new one.
Until a dedicated resealing migration exists, treat a secret-field rename as
unsupported.
Bump schemaVersion for incompatible config-shape changes and provide a
stepwise migrate(stored, fromVersion) implementation. Migrations receive the
stored shape, including secret envelopes, and must preserve those envelopes
unchanged.
Reads fail closed when:
- the stored schema version is newer than the running deployment;
- a migration step is missing;
- the migrated config no longer matches the current schema; or
- a secret envelope appears outside a registered secret path.
The store applies migrations before redaction, keep-marker resolution, testing, and session rendering so every consumer sees the current shape.
The warehouse suites read dedicated, pre-existing test resources. They do not create or delete cloud resources. Ordinary tests use deterministic fixtures and run the same browse contract.
Set these environment variables before a live run:
| Provider | Configuration variable | Fixture variable |
|---|---|---|
| Databricks | MARIMOHUB_TEST_DATABRICKS_CONFIG |
MARIMOHUB_TEST_DATABRICKS_FIXTURE |
| BigQuery | MARIMOHUB_TEST_BIGQUERY_CONFIG |
MARIMOHUB_TEST_BIGQUERY_FIXTURE |
Configuration values are JSON. Databricks uses its integration configuration with a PAT or
OAuth M2M credentials. BigQuery uses provider: "bigquery", project_id, and credentials_json.
The latter contains the service-account key as a JSON string. Supply credentials through your
test environment's secret manager.
Each fixture value follows BrowseContractFixture in packages/core/src/testing/browseContract.ts.
For Databricks, use hierarchy: "two-level", a catalog root, at least two schema children,
and a table in the first child. For BigQuery, use hierarchy: "flat", a dataset root,
an empty children array, and a base table. Set grandchild to an empty string in both fixtures.
Include the expected columns. BigQuery can also include expected preview rows.
pnpm --filter @marimo-hub/core test src/services/integrations/kinds/databricks.browse.live.test.ts
pnpm --filter @marimo-hub/database-browser-bigquery test src/bigquery.live.test.tsEach suite skips when either variable is absent. These hosted-provider suites do not run in the container-based catalog workflow. Record live results separately from fixture test results.
Add kind-specific coverage to
packages/core/src/services/integrations/kinds/kinds.test.ts. The shared tests
enforce:
- deterministic rendering;
- the supported schema dialect;
- collision-free static outputs;
- no ambient network access from probes; and
- registry descriptors that can be serialized for the web form.
Also test URL encoding, authentication headers, sensitive-field handling, connectivity responses, and any kind-specific validation. Run the repository done criteria before finishing:
pnpm check
pnpm typecheck
pnpm test
pnpm buildThe otlp_logs kind renders typed logging destinations and no runtimePackages.
Remote logging documents configuration, delivery limits, and process startup cost.
SandboxProvisioner writes the bootstrap and destination configuration to the fixed directory /tmp/marimohub-logging.
Each launch overwrites the previous credentials there. Credentials stay outside the integration manifest.
After uv selects the package environment, the launch command adds that directory to PYTHONPATH for the workload command only.
Launches without logging contributions leave retained bootstrap files inactive.
The bootstrap chains an existing sitecustomize and initializes once per process, including spawned kernels.
It attaches handlers to the root and marimo loggers and suppresses duplicate records.
It does not change global OpenTelemetry providers.
Each destination has a bounded queue and a background thread.
The thread sends OTLP/HTTP JSON with urllib.request.
The exporter uses only the Python standard library and starts no other process.
Records keep timestamps, structured attributes, and exceptions.
The exporter reads trace context only when the notebook already loaded the OTel trace API.
Each batch gets two HTTP attempts. Their socket timeouts share a two-second budget.
A retry waits for jitter, or for Retry-After when it fits the budget.
Partial acceptance is not retried. Response bodies are read up to 64 KiB and never appear in diagnostics.
Two marimo compatibility hooks keep remote verbosity (_loggers.set_level) and flush before kernel os._exit() (handlers.construct_sigterm_handler).
Normal exit and multiprocessing finalization call the same shutdown function.
Each hook initializes independently after handler installation. A failed hook emits a diagnostic, and log export continues.
Forked children inherit the hooks without rerunning sitecustomize.
An at-fork callback replaces inherited handlers, queues, locks, and workers, and does not replay parent records.
Multiprocessing clears its finalizer registry after that callback, so a separate multiprocessing callback restores the child's shutdown finalizer.
The exporter skips system-proxy discovery because on macOS it can crash a forked child through CFNetwork.
The otlp_logs connection test probes the configured URL through IntegrationProbe, with the same header validation and credentials as runtime export.
It posts an empty resourceLogs array and never returns response bodies or transport error text.
All custom header values are secrets, including tenant identifiers. A later plain-header field can be additive without moving existing secret paths.
Use a Python environment with the marimo, uv, and test dependency versions from .github/workflows/ci.yml.
Run the suite with that environment:
PATH="/absolute/path/to/venv/bin:$PATH" \
MARIMO_INTEGRATION_PYTHON=/absolute/path/to/venv/bin/python \
pnpm exec vp test packages/core/src/services/runtime/logging.integration.test.tsThe suite executes the generated bootstrap in real Python and marimo processes and decodes JSON with the official Protobuf schema.
It covers marimo sessions, absent and old OTel packages, typed attributes, retries, partial acceptance, and bounded shutdown.
OTel packages are test dependencies only. Compatibility cases install OTel 1.20.0 into disposable environments.
CI enables this suite. Without MARIMO_INTEGRATION_PYTHON, tests are skipped.