MCP server
Marimohub exposes notebooks that a user can access through the Model Context Protocol (MCP). By default, the Hub issues a scoped personal access token after browser consent. Deployments can instead enable external authorization through their OIDC issuer. For clients that accept headers only, deployments can enable manual MCP tokens.
Enable MCP
MCP is off by default and runs only on the Node server. Set these variables:
MARIMOHUB_MCP=on
MARIMOHUB_APP_BASE_URL=https://hub.example.comMARIMOHUB_APP_BASE_URL must include the public origin and any path prefix. MARIMOHUB_APP_BASE_URL must use HTTPS, because the OAuth issuer derives from it. The server refuses to start with a plain http:// URL unless the host is localhost or 127.0.0.1.
The MCP server URL adds /mcp to this value:
https://hub.example.com/mcpOAuth discovery uses the base URL to publish stable, absolute URLs. The MCP dialog in the user menu shows the MCP URL and client setup instructions.
Connect a client
For Claude Code, run:
claude mcp add --transport http marimohub https://hub.example.com/mcpFor Claude.ai, add a custom connector and enter the MCP server URL. For Cursor, add a remote HTTP MCP server. The client discovers the authorization server.
By default, the client registers with the Hub and opens the marimohub consent page. With external authorization, the client uses the configured issuer.
For the default Hub authorization flow, use the following consent checklist. Check the client name and redirect URL before approval. The default grant permits notebook editing and execution. Use the smallest practical set of actions and projects. The token lifetime defaults to 7 days and cannot exceed 90 days. Revoke a token from the API tokens dialog. Marimohub does not issue refresh tokens. Expiry or revocation requires a new authorization. The Hub-issued token does not carry your IdP groups, so IdP group project access does not apply to it. External authorization access tokens carry the groups selected by MARIMOHUB_AUTH_OIDC_MEMBERSHIP_GROUPS or MARIMOHUB_AUTH_OIDC_MEMBERSHIP_GROUP_PREFIXES; without that configuration they carry none.
Header-only clients
With MCP enabled, set MARIMOHUB_MCP_MANUAL_TOKENS=on and restart the server. This option defaults to off.
- Open the user menu → MCP → Token.
- Enter a name and choose the permitted actions and projects.
- Set an expiry from 1 to 90 days (default: 30), then select Create MCP token.
- Copy the server URL and header into your client's Streamable HTTP configuration:
Authorization: Bearer mhub_pat_…Creation requires a browser session. The token appears once and is bound to the deployment's exact MCP URL. It works only on MCP: the REST API rejects it with 401. Ordinary API tokens cannot access MCP. Manage and revoke tokens in API tokens.
Setting MARIMOHUB_MCP_MANUAL_TOKENS=off blocks creation and MCP access without revoking tokens or changing OAuth. If you re-enable the option, valid manual tokens work again at the same URL. Setting the option to on while MARIMOHUB_MCP is off stops server startup.
Work with notebooks
Use list_catalog to find accessible projects, notebooks, and active sessions. Project and notebook selectors accept IDs or exact names, case-insensitively. Use IDs when names are duplicated and for subsequent calls. Use project_tag_namespace to filter project namespaces.
| Tool | Purpose |
|---|---|
list_catalog | Discover notebooks by project, namespace, notebook status, tag, or text. |
get_notebook | Read notebook metadata and stored source. |
create_notebook | Create a local notebook. Optional launch starts an edit session. |
update_notebook | Replace supplied metadata fields or the complete local source. |
sync_notebook_source | Sync a Git source and report which sessions need restarting. |
search_workspace | Search notebooks, code, outputs, and data catalogs, when enabled. |
delete_notebook | Soft-delete a notebook, retire live apps, and cancel job runs. |
start_session | Start or reuse an edit or app session. |
execute_code | Run Python in an edit session's live scratchpad. |
stop_session | Stop a session and destroy its sandbox, with a save attempt for persistent edits. |
When profile selection is enabled, both tools accept an optional compute_profile:
create_notebooksaves the profile and uses it withlaunch: true. Omission uses the deployment default.start_sessionoverrides the profile for a new persistent edit session without changing the saved choice. Omission uses the saved profile.
Reused sessions and restored filesystem snapshots retain their profile. "default" selects the deployment default, except during creation when a configured profile is named default.
Edit stored source
Notebook reads, updates, and deletions work without a session. get_notebook returns stored source, which can differ from unsaved edits in a live session.
- Read the notebook with
get_notebook. - Pass the changed fields to
update_notebook, usingexpected_updated_atfrom the read.
Omitted fields remain unchanged. Supplied fields replace their previous values. A code update creates a version. Remote source changes go through sync. delete_notebook also accepts expected_updated_at.
If the precondition fails, read the latest notebook before retrying. A persistent edit session blocks stored code replacement until its sandbox is cleaned up. Edit in the live session, or stop it and call get_notebook to include its saved changes before retrying. Metadata updates, app sessions, and temporary sessions do not have this restriction.
Sync a Git source
sync_notebook_source accepts nonblank project and notebook IDs or names, with no additional arguments:
{ "project": "Analytics", "notebook": "Report" }It uses the Sync now workflow, including provider support, pending settings, notebook.write authorization, and manual sync audit events. It never restarts sessions.
Results include project_id, notebook_id, commit, synced (whether this call published a version), and:
version_id: the version published by this call, ornullif already up to date.current_version_id: the stored version after sync, even if unchanged.nullmeans unknown.sessions: each active session'ssession_id,mode,status,source_version_id, andrestart_needed.nullmeans the session lookup failed after sync;restart_neededis thennull.restart_needed:trueif any session is stale, otherwisenullif any per-sessionrestart_neededisnull, otherwisefalse.
Per-session restart_needed compares the current notebook version with the session's latest acknowledged working-branch save, when one exists. Otherwise, it uses source_version_id, which records the session's launch version and does not change after saves. The result is true for different versions, false for a match, and null if either version is missing. Active sessions have status starting, running, or terminating. To restart one, use stop_session then start_session with the same notebook and mode, subject to session permissions.
Source format
The code parameter for create_notebook and update_notebook contains a complete marimo Python notebook. For example:
import marimo
app = marimo.App()
@app.cell
def _():
import marimo as mo
mo.md("Hello from MCP")
return
if __name__ == "__main__":
app.run()The Hub stores source verbatim, without syntax validation or script conversion.
Notebook dependencies
Prefix the code supplied to create_notebook or update_notebook with a PEP 723 header:
# /// script
# dependencies = ["cowsay==6.1"]
# ///For local and synced notebooks, dependencies install before edit sessions, app sessions, and jobs start. Creation without launch: true only saves the source. Imports alone do not declare dependencies.
Workspace pyproject.toml dependencies install first, then inline dependencies. Keep requirements compatible: inline pins can replace project versions. The sandbox image supplies marimo. See the dependency contract for source-version behavior, Python requirements, and custom indexes.
To change dependencies:
- Stop the persistent edit session.
- Read its saved source with
get_notebook. - Call
update_notebookwith the complete updated source. - Start a new session.
Running kernels do not reinstall dependencies after header changes. Invalid metadata or unresolved dependencies fail startup with PYTHON_ENV_SETUP_FAILED. If the MCP client times out during installation, retry start_session to inspect startup. Preinstall large packages to avoid repeated cold installs.
Work in a live session
- Call
start_sessionwithmode: "edit". - Read
execution.ready. If it is false, followexecution.next_step. - Call
execute_codewith the returned project and session IDs. - When finished, call
stop_sessionfor sessions you no longer need.
Edit sessions initialize kernels without a browser and respect the notebook's automatic-execution settings. create_notebook with launch: true does the same. Repeated starts reuse the kernel without rerunning cells. The first start can take about two minutes.
Session status describes the sandbox lifecycle. execution.status reports kernel readiness:
| Status | Next step |
|---|---|
ready | Call execute_code. Execution queues behind any running cells. |
starting | Retry start_session to check sandbox startup. If authorization is required, follow execution.next_step. |
initializing | Retry start_session with a positive wait_seconds. |
awaiting_client | Open notebook_url in a browser. This runtime requires browser initialization. |
unavailable | Retry start_session. If it fails again, check the session logs or open the notebook in a browser. |
forbidden | Obtain session.attach access before executing code. |
app_mode | Call start_session with mode: "edit" to execute code. |
terminating, terminated, failed, expired | Check the session status and error before retrying start_session. |
If a kernel stays initializing, awaiting_client, or unavailable, search the server logs for the mcp_kernel_bootstrap event. The hub writes one event for each kernel check. Each event has project_id, notebook_id, session_id, sandbox_id, inspect_only, wait_seconds, outcome, and duration_ms. An optional bootstrap object records the last check:
| Field | Values |
|---|---|
stage | discovery, client, lock, sessions, configure, websocket, instantiate, kernel_status, exec |
reason | runtime_not_found, missing_dependency, incompatible_runtime, http_error, connection_error, timeout, client_exit, invalid_output, launcher_error, client_error, initialization_failed, exec_failed |
runtime_kind | marimo (a marimo server) or bridge (the notebook bridge launcher) |
authenticated | true if the server requires the sandbox token |
http_status | The marimo server's HTTP status when reason is http_error |
processes_scanned | The number of sandbox processes checked during discovery |
port_matches | The number of processes started with the expected kernel --port |
For example, stage: "discovery" with reason: "runtime_not_found" and port_matches: 0 means that no scanned process was started with the kernel --port. The event never contains tokens, URLs, process arguments, or sandbox output. The hub drops any bootstrap field or value that is not in this table. A failed event also has an error object. It holds only the name, code, status, and operation of the error and its causes.
wait_seconds accepts integers from 0 to 120 (default 60). It bounds kernel initialization retries after sandbox startup while readiness remains initializing. If the wait expires, call start_session again. Zero inspects existing kernels, including browser sessions, without creating a kernel or running cells.
Custom images need compatible marimo and WebSocket support. execute_code does not install dependencies automatically.
A browser can attach later without losing notebook variables or cell edits. If the kernel disappears, execute_code directs you to start_session. It does not recreate the kernel or replay code after ambiguous failures.
execute_code reads live notebook variables, but scratchpad assignments are temporary. For persistent variables and cell edits, use marimo's code-mode API: import marimo._code_mode as cm; help(cm). App sessions do not support scratchpad execution.
Authorized MCP requests keep sessions active until completion, authorization expiry, or session termination. When MCP requests and browser activity stop, idle cleanup applies.
Cancellation or disconnection stops the call's wait and heartbeats. It does not stop an existing session or undo work already sent to the runtime. A sandbox already provisioning can finish startup and remains subject to normal idle cleanup. Use stop_session to stop a session explicitly.
Discover data
These read-only tools work in MCP clients and project chat. They share REST authorization, limits, cancellation, and audit behavior.
| Tool | Purpose |
|---|---|
list_integrations | List project and inherited organization integrations without credentials or configuration. |
list_namespaces | List namespaces, optionally under a parent. |
list_tables | List tables in a namespace. |
get_table_schema | Read columns, types, partitioning, and an available loading snippet. |
preview_table | Read a bounded row sample. Can start temporary compute. |
run_query | Run bounded read-only SQL. |
search_tables | Search table names and report incomplete coverage. |
profile_table | Count nulls and distinct primitive values in a sample. |
find_notebooks_using_table | Find indexed code candidates. Integration bindings remain unverified. |
list_object_buckets | List accessible buckets or containers. |
list_objects | List objects and prefixes at one directory level. |
get_object_metadata | Read metadata, tags, and an available loading snippet. |
preview_object | Preview text or rows, or describe an image. |
list_integrations requires integration.read. SQL requires integration.manage (admin or above). Other tools require integration.use (editor or above). Token grants must permit the action in the selected project.
Except for integration listing, these tools require the data browser. Table previews and profiles require the preview feature. SQL, object tools, and notebook discovery require their respective query, object-browser, and search features. Disabled tool families are absent from tools/list. Each integration must also support the operation.
All tools accept a project ID or exact name. Other than list_integrations, they also accept an integration ID or exact name. Integration listing marks disabled and shadowed entries, which cannot be browsed. Names resolve to the unshadowed entry. Namespaces are arrays such as ["sales", "eu.central"]. Dots within each part remain intact.
Paged lists return items and next_cursor. To continue, pass next_cursor as cursor with the same filters.
| Input | Default | Maximum |
|---|---|---|
Integration, namespace, and table list limit | 100 | 500 |
Object list limit | 50 | 100 |
Table or tabular object preview limit | 20 rows | 100 rows |
Search or notebook discovery limit | 20 | 50 |
Profile sample_rows | 20 | 100 |
Table search stops at 1,000 entries, 32 browse calls, or 6.5 seconds. It returns coverage.complete and coverage.reason. If coverage is incomplete, narrow the namespace. Profiles cover at most 50 columns and are not whole-table estimates. Previews also enforce configured byte limits. Unsupported object formats return a reason. Image previews return content type and size. Images are visible on the Data page.
Chat asks for consent before SQL, profiling, or previews send data to the model. SQL asks on every call. Chat caps pages at 100 items. Saved table previews fit within 2,000 characters, with at most 100 rows and 50 columns. They redact credential-like columns and inline secrets, omit nested values, and label partial results.
Project chat
With managed AI on, project_conversations manages the caller's private chat conversations. Human credentials only.
| Action | Purpose |
|---|---|
list, get | Browse your conversations in a project and read recent messages. |
create, send | Start a conversation or send a message and wait for the saved reply. |
resume | Continue an interrupted task; set acknowledge_uncertain when asked. |
stop | Stop a reply in progress, wherever it runs. |
dismiss_continuation | Drop an interrupted task without resuming it. |
delete | Remove a conversation. |
permissions | List remembered "always allow" tool consents. |
revoke_permission | Forget a remembered consent. |
decide_permission | Answer an open consent card of a running turn. |
Consent-gated tools cannot prompt during an MCP send: they are skipped and the assistant is told. Approve changes in the hub UI.
Run and schedule jobs
Set MARIMOHUB_JOBS=on and restart the deployment to register these tools. When disabled, they are absent from tools/list and direct calls return an unknown-tool error.
| Tool | Purpose |
|---|---|
list_jobs | List saved jobs with cursor pagination. |
create_job | Save a manual or scheduled job without starting a run. |
schedule_job | Change or remove a schedule, or pause and resume scheduled runs. |
run_job | Queue a saved job for headless execution. |
get_job_run | Read or wait for an existing run attempt. |
All tools require project and notebook. These selectors and job accept IDs or exact, case-insensitive names. Duplicate names require an ID.
With jobs enabled, get_notebook returns a jobs array with IDs, schedules, enabled state, parameters, and updated_at. The array is empty for notebooks without jobs. Disabled deployments omit it.
create_job accepts the job API fields: name, parameters, schedule, timeout, retry policy, concurrency policy, notifications, and enabled state. Omitting the schedule creates a manual-only job. Parameters are strings available through mo.cli_args() and visible to project readers.
schedule_job requires expected_updated_at from list_jobs, get_notebook, or a previous job mutation. At least one change is required:
| Argument | Effect |
|---|---|
schedule: { cron, timezone } | Set a cron schedule with an IANA timezone. |
schedule: null | Remove the schedule. |
enabled: false / enabled: true | Pause / resume scheduled runs. |
Omitted fields remain unchanged.
Start and poll a run
Call run_job with a saved job:
{
"project": "Analytics",
"notebook": "Report",
"job": "Nightly",
"parameters": { "region": "eu" },
"idempotency_key": "report-eu-2026-09-15",
"wait": false
}Supplied parameters replace the stored map for this run. An empty map clears them. The maintenance scheduler must be active to start queued runs.
Results contain run, completed, wait_expired, and links to the browser run page and REST status endpoint. Available artifacts add HTML and log links, not their contents. All links require Hub authentication. Logs require editor access.
Active results include poll with tool: "get_job_run", its arguments, and interval_seconds: 2. Use those arguments to poll. Another run_job call can start another run.
create_job and run_job accept idempotency_key. After a lost response, reuse the key and inputs. Replay records last 24 hours. Concurrent run_job calls with the same key, caller, and job reuse one run. create_job and REST retain best-effort replay: concurrent first requests can create duplicates. A crash or storage failure between enqueueing and recording the replay can still cause a duplicate run on retry.
Wait with optional progress
Both run tools default to wait: false. With wait: true, they check status every two seconds for up to wait_seconds (default 60, range 1–120). Expiry returns the latest status, wait_expired: true, and polling details. The run continues under its separate execution timeout.
For progress, send _meta.progressToken in the MCP request parameters, outside the tool arguments. Streamable HTTP delivers an initial notification and observed status changes over SSE. The counter increases without a completion percentage. Without a token, the call returns only the final result.
Cancellation or disconnection stops observation. The run continues. Each poll checks current project membership and notebook visibility. To cancel execution, use the job UI or REST cancellation endpoint.
Each call tracks one attempt. Automatic retries have separate run IDs linked by retry_of. Failed, timed-out, cancelled, and skipped attempts return normal status data. Tool errors indicate invalid input, denied access, or another request failure.
Working branches
These tools register only when working notebooks are enabled. They require working-branch.write. Recovery defines save stages, retry rules, and capture retention.
| Tool | Purpose |
|---|---|
create_branch_notebook | Create a working branch from a base branch and import an entry notebook. |
save_to_branch | Commit eligible source files from a running edit session to the branch. |
open_change_request | Open or return the branch's PR, draft by default. Does not commit unsaved edits. |
get_working_branch | Read the remote branch, PR state, and latest save stage. |
get_branch_save | Read your save receipt and its recovery ZIP URL. Managers can read any receipt. |
retry_branch_save | Resume a save by ID without a new capture. |
create_branch_notebook and save_to_branch require idempotency_key. After a lost response, reuse the key. In project chat, the four tools that write to GitHub need consent.
External authorization
With external OIDC access tokens enabled, MCP discovery advertises the configured OIDC issuer. Clients use that issuer for authorization and consent. The issuer must support the discovery, client registration, and PKCE flow that each MCP client requires.
Configure the issuer to accept the exact public MCP URL as an OAuth resource, including any deployment path prefix.
Clients must request mcp:tools and at least one Hub grant scope, such as marimohub:read or marimohub:edit. The issuer controls which clients can request these scopes and what the user approves.
The initial authorization challenge requests mcp:tools marimohub:read. Discovery lists all supported scopes, but clients that honor the challenge start with read access. For execution or editing, authorize the client with the corresponding grant scope. The Hub does not automatically request broader scopes after a tool is denied.
External authorization does not use the Hub consent page or its project selector. Token scopes limit actions across all projects that the user can already access. They cannot increase user permissions or permit session-only administration.
Existing Hub-issued MCP tokens continue to work. Hub OAuth endpoints remain available, but protected-resource metadata advertises only the external issuer. External tokens expire within one hour, or sooner under the configured group-session limit. The Hub cannot revoke or refresh them.
A gateway needs an access token for the Hub with the required audience and scopes. A shared issuer alone does not guarantee one authorization step. Test discovery, client registration, resource requests, and scope requests with your gateway before deployment.
OAuth and security
The following OAuth rules apply to Hub-issued credentials. External credentials use the issuer requirements in external authorization.
Dynamic registration creates public clients that use authorization code and PKCE S256. Redirect URIs must use HTTPS, loopback HTTP, or a private-use application scheme. Marimohub supports cursor: and reverse-domain, single-slash application schemes. Authorization codes expire after ten minutes and can be used once. Authorization requests, token exchanges, and issued tokens must target the configured MCP URL. Each token also stores the registered client ID. Manual MCP tokens use a separate resource binding. Other PATs cannot access /mcp.
The mcp:tools OAuth scope permits MCP access. The consent grant restricts Hub actions and projects for each tool call.
Within the configured app base path, MCP reserves these paths:
/mcp/authorize/oauth/consent/token/register/revoke/.well-known/oauth-authorization-server/.well-known/oauth-protected-resource/.well-known/oauth-protected-resource/mcp
The grant does not restrict kernel code or injected credentials. Use a short token lifetime.
Hub dynamic registration remains available in both authorization modes. Registration is anonymous. Marimohub checks client metadata, enforces deployment-wide rate limits, and expires registrations after 90 days. Each successful registration emits an oauth_client_registered event without client-supplied names or URIs. Deployments that require client vetting must add trusted registration controls before enabling MCP.