Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Generate named frontend type exports (#11303)

Trevor Manz89f57bc476b7
diff --git a/development_docs/openapi.md b/development_docs/openapi.md
index ef06725e62..aa2ba45af0 100644
--- a/development_docs/openapi.md
+++ b/development_docs/openapi.md
@@ -15,10 +15,13 @@ marimo development openapi
## Writing a new OpenAPI schema
-To modify the schema, add the type under `_generate_server_api_schema` in [`commands.py`](/marimo/_cli/development/commands.py) and run
+To expose a frontend type, add it to `roots` in
+[`schema.py`](/marimo/_cli/development/schema.py), or use `named_exports` to
+give a union or literal an exported name. Its dependencies are included
+automatically when you regenerate the schema and TypeScript with Python 3.12:
```bash
-marimo development openapi > packages/openapi/api.yaml
+make fe-codegen
```
## Validating an OpenAPI schema
diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.ts
index 76b420d489..91f025d072 100644
--- a/frontend/src/core/kernel/messages.ts
+++ b/frontend/src/core/kernel/messages.ts
@@ -2,7 +2,7 @@
import type { components } from "@marimo-team/marimo-api";
export type schemas = components["schemas"];
-export type DataType = schemas["KnownUnions"]["data_type"];
+export type DataType = schemas["DataType"];
export const DATA_TYPES = [
"string",
"boolean",
@@ -24,10 +24,7 @@ export type DatabaseSchema = schemas["Schema"];
export type DataSourceConnection = schemas["DataSourceConnection"];
export type OutputChannel = schemas["CellChannel"];
export type CellOutput = schemas["CellOutput"];
-export type MarimoError = Extract<
- CellOutput["data"],
- { type: string }[]
->[number];
+export type MarimoError = schemas["MarimoError"];
export type OutputMessage = schemas["CellOutput"];
export type CompletionOption =
schemas["CompletionResultNotification"]["options"][0];
@@ -54,8 +51,8 @@ export type Capabilities =
NotificationMessageData<"kernel-ready">["capabilities"];
export type CacheInfoFetched = NotificationMessageData<"cache-info">;
-export type NotificationMessage = schemas["KnownUnions"]["notification"];
-export type ClientCommand = schemas["KnownUnions"]["command"];
+export type NotificationMessage = schemas["NotificationMessage"];
+export type ClientCommand = schemas["ClientCommand"];
export type NotificationMessageType = NotificationMessage["op"];
export interface NotificationPayload {
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 40148d0d76..f2ebbc42bd 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -15,469 +15,11 @@ from marimo._cli.errors import (
MarimoCLIRuntimeError,
)
from marimo._cli.help_formatter import ColoredCommand, ColoredGroup
-from marimo._data.models import DataType
-from marimo._messaging.errors import Error as MarimoError
-from marimo._messaging.notification import NotificationMessage
-from marimo._runtime.commands import ClientCommand
if TYPE_CHECKING:
import psutil
-def _enrich_branded_types(
- component_schemas: dict[str, Any],
- models: list[object],
-) -> None:
- """Post-process schemas to replace NewType string fields with $ref
- branded types.
-
- msgspec.json.schema_components() strips NewType wrappers, emitting plain
- `{type: string}` for fields like `CellId_t`. This function:
-
- 1. Adds named schemas for each branded type (e.g. `CellId: {type: string}`).
- 2. Walks every model struct's type hints and replaces inline schemas with
- `$ref` pointers wherever a field's annotation is (or contains) a
- registered NewType.
- """
- import types as _types
- import typing
- from typing import Union
-
- import msgspec
-
- from marimo._types.ids import (
- CellId_t,
- RequestId,
- SessionId,
- UIElementId,
- VariableName,
- WidgetModelId,
- )
-
- branded: dict[Any, tuple[str, str]] = {
- CellId_t: ("CellId", "cell-id"),
- UIElementId: ("UIElementId", "ui-element-id"),
- SessionId: ("SessionId", "session-id"),
- VariableName: ("VariableName", "variable-name"),
- RequestId: ("RequestId", "request-id"),
- WidgetModelId: ("WidgetModelId", "widget-model-id"),
- }
-
- # Step 1 — add named schemas for each branded type
- for schema_name, format_value in branded.values():
- component_schemas[schema_name] = {
- "type": "string",
- "format": format_value,
- }
-
- def make_ref(name: str) -> dict[str, str]:
- return {"$ref": f"#/components/schemas/{name}"}
-
- def _is_union(origin: Any) -> bool:
- return origin is Union or origin is getattr(_types, "UnionType", None)
-
- def resolve(ty: Any) -> dict[str, Any] | None:
- """Produce a branded schema for *ty*, or `None`."""
- if ty in branded:
- return make_ref(branded[ty][0])
-
- origin = typing.get_origin(ty)
- args = typing.get_args(ty)
-
- # Union / Optional
- if _is_union(origin):
- non_none = [a for a in args if a is not type(None)]
- has_none = len(non_none) < len(args)
- if len(non_none) == 1:
- inner = resolve(non_none[0])
- if inner is not None:
- if has_none:
- return {"anyOf": [inner, {"type": "null"}]}
- return inner
- return None
-
- # list[T]
- if origin is list:
- if args:
- inner = resolve(args[0])
- if inner is not None:
- return {"type": "array", "items": inner}
- return None
-
- # tuple[T, ...]
- if origin is tuple:
- if len(args) == 2 and args[1] is Ellipsis:
- inner = resolve(args[0])
- if inner is not None:
- return {"type": "array", "items": inner}
- return None
-
- # dict[K, V] — brand the value type (keys are always strings in JSON)
- if origin is dict and len(args) == 2:
- val = resolve(args[1])
- if val is not None:
- return {"type": "object", "additionalProperties": val}
-
- return None
-
- # Step 2 — collect *all* reachable struct types (not just MODELS,
- # since msgspec pulls in transitively-referenced structs too).
- all_structs: dict[str, type] = {}
-
- def _visit_type(ty: Any) -> None:
- if isinstance(ty, type) and issubclass(ty, msgspec.Struct):
- if ty.__name__ in all_structs:
- return
- all_structs[ty.__name__] = ty
- try:
- for hint in typing.get_type_hints(ty).values():
- _visit_annotation(hint)
- except Exception:
- pass
-
- def _visit_annotation(ty: Any) -> None:
- if isinstance(ty, type):
- _visit_type(ty)
- return
- for arg in typing.get_args(ty):
- if arg is not Ellipsis and arg is not type(None):
- _visit_annotation(arg)
-
- for model in models:
- _visit_type(model)
-
- # Step 3 — walk collected structs and replace inline schemas with $refs.
- # Use msgspec.structs.fields() to map Python names → schema keys,
- # which accounts for rename="camel" and other rename strategies.
- for schema_name, struct_cls in all_structs.items():
- schema = component_schemas.get(schema_name)
- if schema is None:
- continue
-
- properties = schema.get("properties", {})
-
- try:
- hints = typing.get_type_hints(struct_cls)
- # Some models contain references that cannot be resolved here.
- except Exception: # noqa: S112
- continue
-
- field_to_schema_key: dict[str, str] = {}
- try:
- for fi in msgspec.structs.fields(struct_cls):
- field_to_schema_key[fi.name] = fi.encode_name
- except Exception:
- field_to_schema_key = {name: name for name in hints}
-
- for field_name, field_type in hints.items():
- schema_key = field_to_schema_key.get(field_name, field_name)
- if schema_key not in properties:
- continue
-
- replacement = resolve(field_type)
- if replacement is not None:
- # Preserve default value from the original schema
- existing = properties[schema_key]
- if isinstance(existing, dict) and "default" in existing:
- replacement["default"] = existing["default"]
- properties[schema_key] = replacement
-
- # Step 4 — replace inline {type: string, contentEncoding: base64}
- # with a named $ref. msgspec already emits contentEncoding for
- # bytes fields; we just need to give it a name so the TS codegen
- # can brand it.
- component_schemas["Base64String"] = {
- "type": "string",
- "format": "base64",
- "contentEncoding": "base64",
- }
-
- def _make_base64_ref() -> dict[str, str]:
- # Fresh dict each time to avoid YAML anchor deduplication
- return {"$ref": "#/components/schemas/Base64String"}
-
- def _replace_base64(obj: Any) -> Any:
- if isinstance(obj, dict):
- if (
- obj.get("type") == "string"
- and obj.get("contentEncoding") == "base64"
- ):
- return _make_base64_ref()
- return {k: _replace_base64(v) for k, v in obj.items()}
- if isinstance(obj, list):
- return [_replace_base64(item) for item in obj]
- return obj
-
- for schema_name in list(component_schemas):
- if schema_name == "Base64String":
- continue
- component_schemas[schema_name] = _replace_base64(
- component_schemas[schema_name]
- )
-
-
-def _generate_server_api_schema() -> dict[str, Any]:
- import msgspec
- import msgspec.json
- from starlette.schemas import SchemaGenerator
-
- import marimo._data._external_storage.models as storage
- import marimo._data.models as data
- import marimo._messaging.notification as notifications
- import marimo._secrets.models as secrets_models
- from marimo._ai._types import ChatMessage
- from marimo._ast.cell import CellConfig, RuntimeStateType
- from marimo._config import config
- from marimo._messaging import errors
- from marimo._messaging.cell_output import CellChannel, CellOutput
- from marimo._messaging.mimetypes import KnownMimeType
- from marimo._metadata import opengraph
- from marimo._runtime.packages.package_manager import PackageDescription
- from marimo._schemas import export
- from marimo._server.ai.tools.types import ToolDefinition
- from marimo._server.api.router import build_routes
- from marimo._server.models import (
- completion,
- files,
- home,
- lsp,
- models,
- packages,
- secrets,
- )
- from marimo._session import requests as session_requests
- from marimo._snippets import snippets
-
- MODELS = [
- # Base
- RuntimeStateType,
- KnownMimeType,
- CellChannel,
- data.NonNestedLiteral,
- data.DataType,
- CellConfig,
- config.OpenAiConfig,
- config.AnthropicConfig,
- config.GitHubConfig,
- config.GoogleAiConfig,
- config.BedrockConfig,
- config.AiConfig,
- config.MarimoConfig,
- config.StoreConfig,
- # Errors
- errors.SetupRootError,
- errors.MultipleDefinitionError,
- errors.CycleError,
- errors.MultipleDefinitionError,
- errors.ImportStarError,
- errors.MarimoInterruptionError,
- errors.MarimoInternalError,
- errors.MarimoAncestorStoppedError,
- errors.MarimoAncestorPreventedError,
- errors.MarimoStrictExecutionError,
- errors.MarimoExceptionRaisedError,
- errors.MarimoSyntaxError,
- errors.UnknownError,
- errors.Error,
- # Outputs
- CellOutput,
- # Data
- data.DataTableColumn,
- data.DataTable,
- data.ColumnStats,
- data.DataSourceConnection,
- data.Schema,
- data.Database,
- # Storage
- storage.StorageEntry,
- storage.StorageNamespace,
- # Secrets
- secrets_models.SecretKeysWithProvider,
- secrets.CreateSecretRequest,
- # Operations
- notifications.CellNotification,
- notifications.HumanReadableStatus,
- notifications.FunctionCallResultNotification,
- notifications.UIElementMessageNotification,
- notifications.RemoveUIElementsNotification,
- notifications.InterruptedNotification,
- notifications.CompletedRunNotification,
- notifications.KernelReadyNotification,
- notifications.CompletionResultNotification,
- notifications.AlertNotification,
- notifications.MissingPackageAlertNotification,
- notifications.EnvironmentOperationNotification,
- notifications.ReconnectedNotification,
- notifications.BannerNotification,
- notifications.ReloadNotification,
- notifications.VariableDeclarationNotification,
- notifications.VariableValue,
- notifications.VariablesNotification,
- notifications.VariableValuesNotification,
- notifications.DatasetsNotification,
- notifications.DataColumnPreviewNotification,
- notifications.SQLTablePreviewNotification,
- notifications.SQLTableListPreviewNotification,
- notifications.SQLSchemaListPreviewNotification,
- notifications.DataSourceConnectionsNotification,
- notifications.StorageNamespacesNotification,
- notifications.SecretKeysResultNotification,
- notifications.CacheClearedNotification,
- notifications.CacheInfoNotification,
- notifications.QueryParamsSetNotification,
- notifications.QueryParamsAppendNotification,
- notifications.QueryParamsDeleteNotification,
- notifications.QueryParamsClearNotification,
- notifications.FocusCellNotification,
- notifications.ActiveLineNotification,
- notifications.ConsumerCapabilitiesNotification,
- notifications.NotificationMessage,
- # ai
- ChatMessage,
- ToolDefinition,
- # Sub components
- home.MarimoFile,
- opengraph.OpenGraphMetadata,
- files.FileInfo,
- files.FileRoot,
- snippets.SnippetSection,
- snippets.Snippet,
- snippets.Snippets,
- # Requests/responses
- completion.VariableContext,
- completion.SchemaColumn,
- completion.SchemaTable,
- completion.AiCompletionContext,
- completion.AiCompletionRequest,
- completion.AiInlineCompletionRequest,
- completion.ChatRequest,
- export.AutoExportAsIPYNBRequest,
- export.AutoExportAsMarkdownRequest,
- export.ExportAsHTMLRequest,
- export.ExportAsMarkdownRequest,
- export.ExportAsScriptRequest,
- export.ExportAsIPYNBRequest,
- export.ExportAsPDFRequest,
- export.ExportAvailabilityResponse,
- export.InstallExportRequirementsRequest,
- export.UpdateCellOutputsRequest,
- files.FileCreateMultipartRequest,
- files.FileCreateRequest,
- files.FileCreateResponse,
- files.FileDeleteRequest,
- files.FileDeleteResponse,
- files.FileDetailsRequest,
- files.FileDetailsResponse,
- files.FileListRequest,
- files.FileListResponse,
- files.FileRootsResponse,
- files.FileSearchRequest,
- files.FileSearchResponse,
- files.FileMoveRequest,
- files.FileMoveResponse,
- files.FileCopyRequest,
- files.FileCopyResponse,
- files.FileOpenRequest,
- files.FileUpdateRequest,
- files.FileUpdateResponse,
- secrets.ListSecretKeysResponse,
- secrets.DeleteSecretRequest,
- packages.AddPackageRequest,
- PackageDescription,
- packages.ListPackagesResponse,
- packages.PackageOperationResponse,
- packages.RemovePackageRequest,
- packages.DependencyTreeResponse,
- packages.SandboxRequest,
- packages.SandboxResponse,
- packages.UpdateManifestRequest,
- packages.SyncSandboxResponse,
- lsp.LspHealthResponse,
- lsp.LspRestartRequest,
- lsp.LspRestartResponse,
- lsp.LspServerHealth,
- home.OpenTutorialRequest,
- home.RecentFilesResponse,
- home.RunningNotebooksResponse,
- home.ShutdownSessionRequest,
- home.WorkspaceFilesRequest,
- home.WorkspaceFilesResponse,
- models.BaseResponse,
- models.ClearCacheRequest,
- models.CodeCompletionRequest,
- models.CopyNotebookRequest,
- models.DebugCellRequest,
- models.DeleteCellRequest,
- models.DiscoverDataSourcesRequest,
- models.ExecuteScratchpadRequest,
- models.FormatCellsRequest,
- models.FormatResponse,
- models.GetCacheInfoRequest,
- models.InstallPackagesRequest,
- session_requests.InstantiateNotebookRequest,
- models.InvokeAiToolRequest,
- models.InvokeAiToolResponse,
- models.InvokeFunctionRequest,
- models.KernelStatusResponse,
- models.ListDataSourceConnectionRequest,
- models.ListSecretKeysRequest,
- models.ListSQLTablesRequest,
- models.ListSQLSchemasRequest,
- models.MCPRefreshResponse,
- models.MCPStatusResponse,
- models.PreviewDatasetColumnRequest,
- models.PreviewSQLTableRequest,
- models.SetBreakpointsRequest,
- models.StorageListEntriesRequest,
- models.StorageDownloadRequest,
- models.ReadCodeResponse,
- models.RenameNotebookRequest,
- models.ExecuteCellsRequest,
- models.SaveAppConfigurationRequest,
- models.SaveNotebookRequest,
- models.SaveUserConfigurationRequest,
- models.StdinRequest,
- models.SuccessResponse,
- models.SuccessResponse,
- models.UpdateCellConfigRequest,
- models.NotebookDocumentTransactionRequest,
- models.FocusCellRequest,
- session_requests.UpdateUIElementValuesRequest,
- models.UpdateUIElementRequest,
- models.UpdateUserConfigRequest,
- models.ModelRequest,
- models.ValidateSQLRequest,
- ]
-
- # Hack to get the unions included in the schema.
- class KnownUnions(msgspec.Struct):
- notification: NotificationMessage
- # Commands are exported only through ClientCommand and its dependencies.
- command: ClientCommand
- error: MarimoError
- data_type: DataType
-
- roots = [*MODELS, KnownUnions]
- _defs, component_schemas = msgspec.json.schema_components(
- roots,
- ref_template="#/components/schemas/{name}",
- )
-
- _enrich_branded_types(component_schemas, roots)
-
- schemas_generator = SchemaGenerator(
- {
- "openapi": "3.1.0",
- "info": {"title": "marimo API"},
- "components": {
- "schemas": component_schemas,
- },
- }
- )
-
- return schemas_generator.get_schema(routes=build_routes())
-
-
@click.group(
cls=ColoredGroup,
help="""Various commands for the marimo development.""",
@@ -496,8 +38,10 @@ def openapi() -> None:
"""
import yaml
+ from marimo._cli.development.schema import generate_server_api_schema
+
click.echo(
- yaml.dump(_generate_server_api_schema(), default_flow_style=False)
+ yaml.dump(generate_server_api_schema(), default_flow_style=False)
)
diff --git a/marimo/_cli/development/schema.py b/marimo/_cli/development/schema.py
new file mode 100644
index 0000000000..b2ddc14ebe
--- /dev/null
+++ b/marimo/_cli/development/schema.py
@@ -0,0 +1,439 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Any
+
+import msgspec
+import msgspec.json
+
+from marimo._data.models import DataType
+from marimo._messaging.errors import Error as MarimoError
+from marimo._messaging.notification import NotificationMessage
+from marimo._runtime.commands import ClientCommand
+
+
+def _generate_schema_components(
+ roots: list[object], named_exports: dict[str, object]
+) -> dict[str, Any]:
+ """Generate named exports and their dependencies, preserving brands."""
+ types = [*roots, *named_exports.values()]
+ schemas, components = msgspec.json.schema_components(
+ types, ref_template="#/components/schemas/{name}"
+ )
+ _enrich_branded_types(components, types)
+ for name, schema in zip(named_exports, schemas[len(roots) :], strict=True):
+ if name in components:
+ if schema == {"$ref": f"#/components/schemas/{name}"}:
+ continue
+ raise ValueError(
+ f"Schema export {name!r} conflicts with a generated schema"
+ )
+ components[name] = schema
+ return components
+
+
+def _enrich_branded_types(
+ component_schemas: dict[str, Any],
+ models: list[object],
+) -> None:
+ """Post-process schemas to replace NewType string fields with $ref
+ branded types.
+
+ msgspec.json.schema_components() strips NewType wrappers, emitting plain
+ `{type: string}` for fields like `CellId_t`. This function:
+
+ 1. Adds named schemas for each branded type (e.g. `CellId: {type: string}`).
+ 2. Walks every model struct's type hints and replaces inline schemas with
+ `$ref` pointers wherever a field's annotation is (or contains) a
+ registered NewType.
+ """
+ import types as _types
+ import typing
+ from typing import Union
+
+ from marimo._types.ids import (
+ CellId_t,
+ RequestId,
+ SessionId,
+ UIElementId,
+ VariableName,
+ WidgetModelId,
+ )
+
+ branded: dict[Any, tuple[str, str]] = {
+ CellId_t: ("CellId", "cell-id"),
+ UIElementId: ("UIElementId", "ui-element-id"),
+ SessionId: ("SessionId", "session-id"),
+ VariableName: ("VariableName", "variable-name"),
+ RequestId: ("RequestId", "request-id"),
+ WidgetModelId: ("WidgetModelId", "widget-model-id"),
+ }
+
+ # Step 1 — add named schemas for each branded type
+ for schema_name, format_value in branded.values():
+ component_schemas[schema_name] = {
+ "type": "string",
+ "format": format_value,
+ }
+
+ def make_ref(name: str) -> dict[str, str]:
+ return {"$ref": f"#/components/schemas/{name}"}
+
+ def _is_union(origin: Any) -> bool:
+ return origin is Union or origin is getattr(_types, "UnionType", None)
+
+ def resolve(ty: Any) -> dict[str, Any] | None:
+ """Produce a branded schema for *ty*, or `None`."""
+ if ty in branded:
+ return make_ref(branded[ty][0])
+
+ origin = typing.get_origin(ty)
+ args = typing.get_args(ty)
+
+ # Union / Optional
+ if _is_union(origin):
+ non_none = [a for a in args if a is not type(None)]
+ has_none = len(non_none) < len(args)
+ if len(non_none) == 1:
+ inner = resolve(non_none[0])
+ if inner is not None:
+ if has_none:
+ return {"anyOf": [inner, {"type": "null"}]}
+ return inner
+ return None
+
+ # list[T]
+ if origin is list:
+ if args:
+ inner = resolve(args[0])
+ if inner is not None:
+ return {"type": "array", "items": inner}
+ return None
+
+ # tuple[T, ...]
+ if origin is tuple:
+ if len(args) == 2 and args[1] is Ellipsis:
+ inner = resolve(args[0])
+ if inner is not None:
+ return {"type": "array", "items": inner}
+ return None
+
+ # dict[K, V] — brand the value type (keys are always strings in JSON)
+ if origin is dict and len(args) == 2:
+ val = resolve(args[1])
+ if val is not None:
+ return {"type": "object", "additionalProperties": val}
+
+ return None
+
+ # Step 2 — collect *all* reachable struct types (not just roots,
+ # since msgspec pulls in transitively-referenced structs too).
+ all_structs: dict[str, type] = {}
+
+ def _visit_type(ty: Any) -> None:
+ if isinstance(ty, type) and issubclass(ty, msgspec.Struct):
+ if ty.__name__ in all_structs:
+ return
+ all_structs[ty.__name__] = ty
+ try:
+ for hint in typing.get_type_hints(ty).values():
+ _visit_annotation(hint)
+ except Exception:
+ pass
+
+ def _visit_annotation(ty: Any) -> None:
+ if isinstance(ty, type):
+ _visit_type(ty)
+ return
+ for arg in typing.get_args(ty):
+ if arg is not Ellipsis and arg is not type(None):
+ _visit_annotation(arg)
+
+ for model in models:
+ _visit_annotation(model)
+
+ # Step 3 — walk collected structs and replace inline schemas with $refs.
+ # Use msgspec.structs.fields() to map Python names → schema keys,
+ # which accounts for rename="camel" and other rename strategies.
+ for schema_name, struct_cls in all_structs.items():
+ schema = component_schemas.get(schema_name)
+ if schema is None:
+ continue
+
+ properties = schema.get("properties", {})
+
+ try:
+ hints = typing.get_type_hints(struct_cls)
+ # Some models contain references that cannot be resolved here.
+ except Exception: # noqa: S112
+ continue
+
+ field_to_schema_key: dict[str, str] = {}
+ try:
+ for fi in msgspec.structs.fields(struct_cls):
+ field_to_schema_key[fi.name] = fi.encode_name
+ except Exception:
+ field_to_schema_key = {name: name for name in hints}
+
+ for field_name, field_type in hints.items():
+ schema_key = field_to_schema_key.get(field_name, field_name)
+ if schema_key not in properties:
+ continue
+
+ replacement = resolve(field_type)
+ if replacement is not None:
+ # Preserve default value from the original schema
+ existing = properties[schema_key]
+ if isinstance(existing, dict) and "default" in existing:
+ replacement["default"] = existing["default"]
+ properties[schema_key] = replacement
+
+ # Step 4 — replace inline {type: string, contentEncoding: base64}
+ # with a named $ref. msgspec already emits contentEncoding for
+ # bytes fields; we just need to give it a name so the TS codegen
+ # can brand it.
+ component_schemas["Base64String"] = {
+ "type": "string",
+ "format": "base64",
+ "contentEncoding": "base64",
+ }
+
+ def _make_base64_ref() -> dict[str, str]:
+ # Fresh dict each time to avoid YAML anchor deduplication
+ return {"$ref": "#/components/schemas/Base64String"}
+
+ def _replace_base64(obj: Any) -> Any:
+ if isinstance(obj, dict):
+ if (
+ obj.get("type") == "string"
+ and obj.get("contentEncoding") == "base64"
+ ):
+ return _make_base64_ref()
+ return {k: _replace_base64(v) for k, v in obj.items()}
+ if isinstance(obj, list):
+ return [_replace_base64(item) for item in obj]
+ return obj
+
+ for schema_name in list(component_schemas):
+ if schema_name == "Base64String":
+ continue
+ component_schemas[schema_name] = _replace_base64(
+ component_schemas[schema_name]
+ )
+
+
+def generate_server_api_schema() -> dict[str, Any]:
+ from starlette.schemas import SchemaGenerator
+
+ import marimo._data._external_storage.models as storage
+ import marimo._data.models as data
+ import marimo._secrets.models as secrets_models
+ from marimo._ai._types import ChatMessage
+ from marimo._ast.cell import CellConfig, RuntimeStateType
+ from marimo._config import config
+ from marimo._messaging.cell_output import CellChannel, CellOutput
+ from marimo._messaging.mimetypes import KnownMimeType
+ from marimo._metadata import opengraph
+ from marimo._runtime.packages.package_manager import PackageDescription
+ from marimo._schemas import export
+ from marimo._server.ai.tools.types import ToolDefinition
+ from marimo._server.api.router import build_routes
+ from marimo._server.models import (
+ completion,
+ files,
+ home,
+ lsp,
+ models,
+ packages,
+ secrets,
+ )
+ from marimo._session import requests as session_requests
+ from marimo._snippets import snippets
+
+ roots = [
+ # Base
+ RuntimeStateType,
+ KnownMimeType,
+ CellChannel,
+ data.NonNestedLiteral,
+ CellConfig,
+ config.OpenAiConfig,
+ config.AnthropicConfig,
+ config.GitHubConfig,
+ config.GoogleAiConfig,
+ config.BedrockConfig,
+ config.AiConfig,
+ config.MarimoConfig,
+ config.StoreConfig,
+ # Outputs
+ CellOutput,
+ # Data
+ data.DataTableColumn,
+ data.DataTable,
+ data.ColumnStats,
+ data.DataSourceConnection,
+ data.Schema,
+ data.Database,
+ # Storage
+ storage.StorageEntry,
+ storage.StorageNamespace,
+ # Secrets
+ secrets_models.SecretKeysWithProvider,
+ secrets.CreateSecretRequest,
+ # ai
+ ChatMessage,
+ ToolDefinition,
+ # Sub components
+ home.MarimoFile,
+ opengraph.OpenGraphMetadata,
+ files.FileInfo,
+ files.FileRoot,
+ snippets.SnippetSection,
+ snippets.Snippet,
+ snippets.Snippets,
+ # Requests/responses
+ completion.VariableContext,
+ completion.SchemaColumn,
+ completion.SchemaTable,
+ completion.AiCompletionContext,
+ completion.AiCompletionRequest,
+ completion.AiInlineCompletionRequest,
+ completion.ChatRequest,
+ export.AutoExportAsIPYNBRequest,
+ export.AutoExportAsMarkdownRequest,
+ export.ExportAsHTMLRequest,
+ export.ExportAsMarkdownRequest,
+ export.ExportAsScriptRequest,
+ export.ExportAsIPYNBRequest,
+ export.ExportAsPDFRequest,
+ export.ExportAvailabilityResponse,
+ export.InstallExportRequirementsRequest,
+ export.UpdateCellOutputsRequest,
+ files.FileCreateMultipartRequest,
+ files.FileCreateRequest,
+ files.FileCreateResponse,
+ files.FileDeleteRequest,
+ files.FileDeleteResponse,
+ files.FileDetailsRequest,
+ files.FileDetailsResponse,
+ files.FileListRequest,
+ files.FileListResponse,
+ files.FileRootsResponse,
+ files.FileSearchRequest,
+ files.FileSearchResponse,
+ files.FileMoveRequest,
+ files.FileMoveResponse,
+ files.FileCopyRequest,
+ files.FileCopyResponse,
+ files.FileOpenRequest,
+ files.FileUpdateRequest,
+ files.FileUpdateResponse,
+ secrets.ListSecretKeysResponse,
+ secrets.DeleteSecretRequest,
+ packages.AddPackageRequest,
+ PackageDescription,
+ packages.ListPackagesResponse,
+ packages.PackageOperationResponse,
+ packages.RemovePackageRequest,
+ packages.DependencyTreeResponse,
+ packages.SandboxRequest,
+ packages.SandboxResponse,
+ packages.UpdateManifestRequest,
+ packages.SyncSandboxResponse,
+ lsp.LspHealthResponse,
+ lsp.LspRestartRequest,
+ lsp.LspRestartResponse,
+ lsp.LspServerHealth,
+ home.OpenTutorialRequest,
+ home.RecentFilesResponse,
+ home.RunningNotebooksResponse,
+ home.ShutdownSessionRequest,
+ home.WorkspaceFilesRequest,
+ home.WorkspaceFilesResponse,
+ models.BaseResponse,
+ models.ClearCacheRequest,
+ models.CodeCompletionRequest,
+ models.CopyNotebookRequest,
+ models.DebugCellRequest,
+ models.DeleteCellRequest,
+ models.DiscoverDataSourcesRequest,
+ models.ExecuteScratchpadRequest,
+ models.FormatCellsRequest,
+ models.FormatResponse,
+ models.GetCacheInfoRequest,
+ models.InstallPackagesRequest,
+ session_requests.InstantiateNotebookRequest,
+ models.InvokeAiToolRequest,
+ models.InvokeAiToolResponse,
+ models.InvokeFunctionRequest,
+ models.KernelStatusResponse,
+ models.ListDataSourceConnectionRequest,
+ models.ListSecretKeysRequest,
+ models.ListSQLTablesRequest,
+ models.ListSQLSchemasRequest,
+ models.MCPRefreshResponse,
+ models.MCPStatusResponse,
+ models.PreviewDatasetColumnRequest,
+ models.PreviewSQLTableRequest,
+ models.SetBreakpointsRequest,
+ models.StorageListEntriesRequest,
+ models.StorageDownloadRequest,
+ models.ReadCodeResponse,
+ models.RenameNotebookRequest,
+ models.ExecuteCellsRequest,
+ models.SaveAppConfigurationRequest,
+ models.SaveNotebookRequest,
+ models.SaveUserConfigurationRequest,
+ models.StdinRequest,
+ models.SuccessResponse,
+ models.UpdateCellConfigRequest,
+ models.NotebookDocumentTransactionRequest,
+ models.FocusCellRequest,
+ session_requests.UpdateUIElementValuesRequest,
+ models.UpdateUIElementRequest,
+ models.UpdateUserConfigRequest,
+ models.ModelRequest,
+ models.ValidateSQLRequest,
+ ]
+
+ named_exports = {
+ "NotificationMessage": NotificationMessage,
+ "ClientCommand": ClientCommand,
+ "MarimoError": MarimoError,
+ "DataType": DataType,
+ }
+ component_schemas = _generate_schema_components(roots, named_exports)
+
+ # Preserve existing consumers while they migrate to the named exports.
+ legacy_exports = {
+ "notification": "NotificationMessage",
+ "command": "ClientCommand",
+ "error": "MarimoError",
+ "data_type": "DataType",
+ }
+ component_schemas["KnownUnions"] = {
+ "title": "KnownUnions",
+ "deprecated": True,
+ "description": (
+ "Use the named NotificationMessage, ClientCommand, MarimoError, "
+ "and DataType schemas directly."
+ ),
+ "type": "object",
+ "properties": {
+ field: {"$ref": f"#/components/schemas/{name}"}
+ for field, name in legacy_exports.items()
+ },
+ "required": list(legacy_exports),
+ }
+
+ schemas_generator = SchemaGenerator(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "marimo API"},
+ "components": {
+ "schemas": component_schemas,
+ },
+ }
+ )
+
+ return schemas_generator.get_schema(routes=build_routes())
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index f4247af772..a5cdd83eb1 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -722,6 +722,43 @@ components:
required: []
title: ClearCacheRequest
type: object
+ ClientCommand:
+ anyOf:
+ - $ref: '#/components/schemas/ExecuteCellsCommand'
+ - $ref: '#/components/schemas/ExecuteScratchpadCommand'
+ - $ref: '#/components/schemas/DeleteCellCommand'
+ - $ref: '#/components/schemas/UpdateCellConfigCommand'
+ - $ref: '#/components/schemas/UpdateUIElementCommand'
+ - $ref: '#/components/schemas/ModelCommand'
+ - $ref: '#/components/schemas/InvokeFunctionCommand'
+ - $ref: '#/components/schemas/InstallPackagesCommand'
+ - $ref: '#/components/schemas/PreviewDatasetColumnCommand'
+ - $ref: '#/components/schemas/PreviewSQLTableCommand'
+ - $ref: '#/components/schemas/ListSQLTablesCommand'
+ - $ref: '#/components/schemas/ListSQLSchemasCommand'
+ - $ref: '#/components/schemas/ValidateSQLCommand'
+ - $ref: '#/components/schemas/ListDataSourceConnectionCommand'
+ - $ref: '#/components/schemas/DiscoverDataSourcesCommand'
+ - $ref: '#/components/schemas/ListSecretKeysCommand'
+ discriminator:
+ mapping:
+ delete-cell: '#/components/schemas/DeleteCellCommand'
+ discover-data-sources: '#/components/schemas/DiscoverDataSourcesCommand'
+ execute-cells: '#/components/schemas/ExecuteCellsCommand'
+ execute-scratchpad: '#/components/schemas/ExecuteScratchpadCommand'
+ install-packages: '#/components/schemas/InstallPackagesCommand'
+ invoke-function: '#/components/schemas/InvokeFunctionCommand'
+ list-data-source-connection: '#/components/schemas/ListDataSourceConnectionCommand'
+ list-secret-keys: '#/components/schemas/ListSecretKeysCommand'
+ list-sql-schemas: '#/components/schemas/ListSQLSchemasCommand'
+ list-sql-tables: '#/components/schemas/ListSQLTablesCommand'
+ model: '#/components/schemas/ModelCommand'
+ preview-dataset-column: '#/components/schemas/PreviewDatasetColumnCommand'
+ preview-sql-table: '#/components/schemas/PreviewSQLTableCommand'
+ update-cell-config: '#/components/schemas/UpdateCellConfigCommand'
+ update-ui-element: '#/components/schemas/UpdateUIElementCommand'
+ validate-sql: '#/components/schemas/ValidateSQLCommand'
+ propertyName: type
CodeCompletionRequest:
properties:
cellId:
@@ -1267,6 +1304,17 @@ components:
- sample_values
title: DataTableColumn
type: object
+ DataType:
+ enum:
+ - boolean
+ - date
+ - datetime
+ - geometry
+ - integer
+ - number
+ - string
+ - time
+ - unknown
Database:
description: "Represents a collection of schemas.\n\nAttributes:\n name (str):\
\ The name of the database\n dialect (str): The dialect of the database\n\
@@ -3085,179 +3133,18 @@ components:
title: KeymapConfig
type: object
KnownUnions:
+ deprecated: true
+ description: Use the named NotificationMessage, ClientCommand, MarimoError,
+ and DataType schemas directly.
properties:
command:
- anyOf:
- - $ref: '#/components/schemas/ExecuteCellsCommand'
- - $ref: '#/components/schemas/ExecuteScratchpadCommand'
- - $ref: '#/components/schemas/DeleteCellCommand'
- - $ref: '#/components/schemas/UpdateCellConfigCommand'
- - $ref: '#/components/schemas/UpdateUIElementCommand'
- - $ref: '#/components/schemas/ModelCommand'
- - $ref: '#/components/schemas/InvokeFunctionCommand'
- - $ref: '#/components/schemas/InstallPackagesCommand'
- - $ref: '#/components/schemas/PreviewDatasetColumnCommand'
- - $ref: '#/components/schemas/PreviewSQLTableCommand'
- - $ref: '#/components/schemas/ListSQLTablesCommand'
- - $ref: '#/components/schemas/ListSQLSchemasCommand'
- - $ref: '#/components/schemas/ValidateSQLCommand'
- - $ref: '#/components/schemas/ListDataSourceConnectionCommand'
- - $ref: '#/components/schemas/DiscoverDataSourcesCommand'
- - $ref: '#/components/schemas/ListSecretKeysCommand'
- discriminator:
- mapping:
- delete-cell: '#/components/schemas/DeleteCellCommand'
- discover-data-sources: '#/components/schemas/DiscoverDataSourcesCommand'
- execute-cells: '#/components/schemas/ExecuteCellsCommand'
- execute-scratchpad: '#/components/schemas/ExecuteScratchpadCommand'
- install-packages: '#/components/schemas/InstallPackagesCommand'
- invoke-function: '#/components/schemas/InvokeFunctionCommand'
- list-data-source-connection: '#/components/schemas/ListDataSourceConnectionCommand'
- list-secret-keys: '#/components/schemas/ListSecretKeysCommand'
- list-sql-schemas: '#/components/schemas/ListSQLSchemasCommand'
- list-sql-tables: '#/components/schemas/ListSQLTablesCommand'
- model: '#/components/schemas/ModelCommand'
- preview-dataset-column: '#/components/schemas/PreviewDatasetColumnCommand'
- preview-sql-table: '#/components/schemas/PreviewSQLTableCommand'
- update-cell-config: '#/components/schemas/UpdateCellConfigCommand'
- update-ui-element: '#/components/schemas/UpdateUIElementCommand'
- validate-sql: '#/components/schemas/ValidateSQLCommand'
- propertyName: type
+ $ref: '#/components/schemas/ClientCommand'
data_type:
- enum:
- - boolean
- - date
- - datetime
- - geometry
- - integer
- - number
- - string
- - time
- - unknown
+ $ref: '#/components/schemas/DataType'
error:
- anyOf:
- - $ref: '#/components/schemas/SetupRootError'
- - $ref: '#/components/schemas/CycleError'
- - $ref: '#/components/schemas/MultipleDefinitionError'
- - $ref: '#/components/schemas/ImportStarError'
- - $ref: '#/components/schemas/MarimoAncestorStoppedError'
- - $ref: '#/components/schemas/MarimoAncestorPreventedError'
- - $ref: '#/components/schemas/MarimoExceptionRaisedError'
- - $ref: '#/components/schemas/MarimoStrictExecutionError'
- - $ref: '#/components/schemas/MarimoInterruptionError'
- - $ref: '#/components/schemas/MarimoSyntaxError'
- - $ref: '#/components/schemas/MarimoInternalError'
- - $ref: '#/components/schemas/MarimoSQLError'
- - $ref: '#/components/schemas/UnknownError'
- discriminator:
- mapping:
- ancestor-prevented: '#/components/schemas/MarimoAncestorPreventedError'
- ancestor-stopped: '#/components/schemas/MarimoAncestorStoppedError'
- cycle: '#/components/schemas/CycleError'
- exception: '#/components/schemas/MarimoExceptionRaisedError'
- import-star: '#/components/schemas/ImportStarError'
- internal: '#/components/schemas/MarimoInternalError'
- interruption: '#/components/schemas/MarimoInterruptionError'
- multiple-defs: '#/components/schemas/MultipleDefinitionError'
- setup-refs: '#/components/schemas/SetupRootError'
- sql-error: '#/components/schemas/MarimoSQLError'
- strict-exception: '#/components/schemas/MarimoStrictExecutionError'
- syntax: '#/components/schemas/MarimoSyntaxError'
- unknown: '#/components/schemas/UnknownError'
- propertyName: type
+ $ref: '#/components/schemas/MarimoError'
notification:
- anyOf:
- - $ref: '#/components/schemas/CellNotification'
- - $ref: '#/components/schemas/ExecutionNotification'
- - $ref: '#/components/schemas/FunctionCallResultNotification'
- - $ref: '#/components/schemas/UIElementMessageNotification'
- - $ref: '#/components/schemas/ModelLifecycleNotification'
- - $ref: '#/components/schemas/RemoveUIElementsNotification'
- - $ref: '#/components/schemas/ReloadNotification'
- - $ref: '#/components/schemas/ReconnectedNotification'
- - $ref: '#/components/schemas/InterruptedNotification'
- - $ref: '#/components/schemas/CompletedRunNotification'
- - $ref: '#/components/schemas/KernelReadyNotification'
- - $ref: '#/components/schemas/CompletionResultNotification'
- - $ref: '#/components/schemas/AlertNotification'
- - $ref: '#/components/schemas/BannerNotification'
- - $ref: '#/components/schemas/MissingPackageAlertNotification'
- - $ref: '#/components/schemas/EnvironmentOperationNotification'
- - $ref: '#/components/schemas/EnvironmentStateNotification'
- - $ref: '#/components/schemas/StartupLogsNotification'
- - $ref: '#/components/schemas/StartupProgressNotification'
- - $ref: '#/components/schemas/KernelStartupErrorNotification'
- - $ref: '#/components/schemas/VariablesNotification'
- - $ref: '#/components/schemas/VariableValuesNotification'
- - $ref: '#/components/schemas/QueryParamsSetNotification'
- - $ref: '#/components/schemas/QueryParamsAppendNotification'
- - $ref: '#/components/schemas/QueryParamsDeleteNotification'
- - $ref: '#/components/schemas/QueryParamsClearNotification'
- - $ref: '#/components/schemas/DatasetsNotification'
- - $ref: '#/components/schemas/DataColumnPreviewNotification'
- - $ref: '#/components/schemas/SQLTablePreviewNotification'
- - $ref: '#/components/schemas/SQLTableListPreviewNotification'
- - $ref: '#/components/schemas/SQLSchemaListPreviewNotification'
- - $ref: '#/components/schemas/DataSourceConnectionsNotification'
- - $ref: '#/components/schemas/DataSourceDiscoveryResultNotification'
- - $ref: '#/components/schemas/ValidateSQLResultNotification'
- - $ref: '#/components/schemas/StorageNamespacesNotification'
- - $ref: '#/components/schemas/StorageEntriesNotification'
- - $ref: '#/components/schemas/StorageDownloadReadyNotification'
- - $ref: '#/components/schemas/SecretKeysResultNotification'
- - $ref: '#/components/schemas/CacheClearedNotification'
- - $ref: '#/components/schemas/CacheInfoNotification'
- - $ref: '#/components/schemas/FocusCellNotification'
- - $ref: '#/components/schemas/ActiveLineNotification'
- - $ref: '#/components/schemas/NotebookDocumentTransactionNotification'
- - $ref: '#/components/schemas/ConsumerCapabilitiesNotification'
- discriminator:
- mapping:
- active-line: '#/components/schemas/ActiveLineNotification'
- alert: '#/components/schemas/AlertNotification'
- banner: '#/components/schemas/BannerNotification'
- cache-cleared: '#/components/schemas/CacheClearedNotification'
- cache-info: '#/components/schemas/CacheInfoNotification'
- cell-op: '#/components/schemas/CellNotification'
- completed-run: '#/components/schemas/CompletedRunNotification'
- completion-result: '#/components/schemas/CompletionResultNotification'
- consumer-capabilities: '#/components/schemas/ConsumerCapabilitiesNotification'
- data-column-preview: '#/components/schemas/DataColumnPreviewNotification'
- data-source-connections: '#/components/schemas/DataSourceConnectionsNotification'
- data-source-discovery-result: '#/components/schemas/DataSourceDiscoveryResultNotification'
- datasets: '#/components/schemas/DatasetsNotification'
- environment-operation: '#/components/schemas/EnvironmentOperationNotification'
- environment-state: '#/components/schemas/EnvironmentStateNotification'
- execution: '#/components/schemas/ExecutionNotification'
- focus-cell: '#/components/schemas/FocusCellNotification'
- function-call-result: '#/components/schemas/FunctionCallResultNotification'
- interrupted: '#/components/schemas/InterruptedNotification'
- kernel-ready: '#/components/schemas/KernelReadyNotification'
- kernel-startup-error: '#/components/schemas/KernelStartupErrorNotification'
- missing-package-alert: '#/components/schemas/MissingPackageAlertNotification'
- model-lifecycle: '#/components/schemas/ModelLifecycleNotification'
- notebook-document-transaction: '#/components/schemas/NotebookDocumentTransactionNotification'
- query-params-append: '#/components/schemas/QueryParamsAppendNotification'
- query-params-clear: '#/components/schemas/QueryParamsClearNotification'
- query-params-delete: '#/components/schemas/QueryParamsDeleteNotification'
- query-params-set: '#/components/schemas/QueryParamsSetNotification'
- reconnected: '#/components/schemas/ReconnectedNotification'
- reload: '#/components/schemas/ReloadNotification'
- remove-ui-elements: '#/components/schemas/RemoveUIElementsNotification'
- secret-keys-result: '#/components/schemas/SecretKeysResultNotification'
- send-ui-element-message: '#/components/schemas/UIElementMessageNotification'
- sql-schema-list-preview: '#/components/schemas/SQLSchemaListPreviewNotification'
- sql-table-list-preview: '#/components/schemas/SQLTableListPreviewNotification'
- sql-table-preview: '#/components/schemas/SQLTablePreviewNotification'
- startup-logs: '#/components/schemas/StartupLogsNotification'
- startup-progress: '#/components/schemas/StartupProgressNotification'
- storage-download-ready: '#/components/schemas/StorageDownloadReadyNotification'
- storage-entries: '#/components/schemas/StorageEntriesNotification'
- storage-namespaces: '#/components/schemas/StorageNamespacesNotification'
- validate-sql-result: '#/components/schemas/ValidateSQLResultNotification'
- variable-values: '#/components/schemas/VariableValuesNotification'
- variables: '#/components/schemas/VariablesNotification'
- propertyName: op
+ $ref: '#/components/schemas/NotificationMessage'
required:
- notification
- command
@@ -3726,6 +3613,37 @@ components:
- server
title: MarimoConfig
type: object
+ MarimoError:
+ anyOf:
+ - $ref: '#/components/schemas/SetupRootError'
+ - $ref: '#/components/schemas/CycleError'
+ - $ref: '#/components/schemas/MultipleDefinitionError'
+ - $ref: '#/components/schemas/ImportStarError'
+ - $ref: '#/components/schemas/MarimoAncestorStoppedError'
+ - $ref: '#/components/schemas/MarimoAncestorPreventedError'
+ - $ref: '#/components/schemas/MarimoExceptionRaisedError'
+ - $ref: '#/components/schemas/MarimoStrictExecutionError'
+ - $ref: '#/components/schemas/MarimoInterruptionError'
+ - $ref: '#/components/schemas/MarimoSyntaxError'
+ - $ref: '#/components/schemas/MarimoInternalError'
+ - $ref: '#/components/schemas/MarimoSQLError'
+ - $ref: '#/components/schemas/UnknownError'
+ discriminator:
+ mapping:
+ ancestor-prevented: '#/components/schemas/MarimoAncestorPreventedError'
+ ancestor-stopped: '#/components/schemas/MarimoAncestorStoppedError'
+ cycle: '#/components/schemas/CycleError'
+ exception: '#/components/schemas/MarimoExceptionRaisedError'
+ import-star: '#/components/schemas/ImportStarError'
+ internal: '#/components/schemas/MarimoInternalError'
+ interruption: '#/components/schemas/MarimoInterruptionError'
+ multiple-defs: '#/components/schemas/MultipleDefinitionError'
+ setup-refs: '#/components/schemas/SetupRootError'
+ sql-error: '#/components/schemas/MarimoSQLError'
+ strict-exception: '#/components/schemas/MarimoStrictExecutionError'
+ syntax: '#/components/schemas/MarimoSyntaxError'
+ unknown: '#/components/schemas/UnknownError'
+ propertyName: type
MarimoExceptionRaisedError:
properties:
exception_type:
@@ -4247,6 +4165,99 @@ components:
- changes
title: NotebookDocumentTransactionRequest
type: object
+ NotificationMessage:
+ anyOf:
+ - $ref: '#/components/schemas/CellNotification'
+ - $ref: '#/components/schemas/ExecutionNotification'
+ - $ref: '#/components/schemas/FunctionCallResultNotification'
+ - $ref: '#/components/schemas/UIElementMessageNotification'
+ - $ref: '#/components/schemas/ModelLifecycleNotification'
+ - $ref: '#/components/schemas/RemoveUIElementsNotification'
+ - $ref: '#/components/schemas/ReloadNotification'
+ - $ref: '#/components/schemas/ReconnectedNotification'
+ - $ref: '#/components/schemas/InterruptedNotification'
+ - $ref: '#/components/schemas/CompletedRunNotification'
+ - $ref: '#/components/schemas/KernelReadyNotification'
+ - $ref: '#/components/schemas/CompletionResultNotification'
+ - $ref: '#/components/schemas/AlertNotification'
+ - $ref: '#/components/schemas/BannerNotification'
+ - $ref: '#/components/schemas/MissingPackageAlertNotification'
+ - $ref: '#/components/schemas/EnvironmentOperationNotification'
+ - $ref: '#/components/schemas/EnvironmentStateNotification'
+ - $ref: '#/components/schemas/StartupLogsNotification'
+ - $ref: '#/components/schemas/StartupProgressNotification'
+ - $ref: '#/components/schemas/KernelStartupErrorNotification'
+ - $ref: '#/components/schemas/VariablesNotification'
+ - $ref: '#/components/schemas/VariableValuesNotification'
+ - $ref: '#/components/schemas/QueryParamsSetNotification'
+ - $ref: '#/components/schemas/QueryParamsAppendNotification'
+ - $ref: '#/components/schemas/QueryParamsDeleteNotification'
+ - $ref: '#/components/schemas/QueryParamsClearNotification'
+ - $ref: '#/components/schemas/DatasetsNotification'
+ - $ref: '#/components/schemas/DataColumnPreviewNotification'
+ - $ref: '#/components/schemas/SQLTablePreviewNotification'
+ - $ref: '#/components/schemas/SQLTableListPreviewNotification'
+ - $ref: '#/components/schemas/SQLSchemaListPreviewNotification'
+ - $ref: '#/components/schemas/DataSourceConnectionsNotification'
+ - $ref: '#/components/schemas/DataSourceDiscoveryResultNotification'
+ - $ref: '#/components/schemas/ValidateSQLResultNotification'
+ - $ref: '#/components/schemas/StorageNamespacesNotification'
+ - $ref: '#/components/schemas/StorageEntriesNotification'
+ - $ref: '#/components/schemas/StorageDownloadReadyNotification'
+ - $ref: '#/components/schemas/SecretKeysResultNotification'
+ - $ref: '#/components/schemas/CacheClearedNotification'
+ - $ref: '#/components/schemas/CacheInfoNotification'
+ - $ref: '#/components/schemas/FocusCellNotification'
+ - $ref: '#/components/schemas/ActiveLineNotification'
+ - $ref: '#/components/schemas/NotebookDocumentTransactionNotification'
+ - $ref: '#/components/schemas/ConsumerCapabilitiesNotification'
+ discriminator:
+ mapping:
+ active-line: '#/components/schemas/ActiveLineNotification'
+ alert: '#/components/schemas/AlertNotification'
+ banner: '#/components/schemas/BannerNotification'
+ cache-cleared: '#/components/schemas/CacheClearedNotification'
+ cache-info: '#/components/schemas/CacheInfoNotification'
+ cell-op: '#/components/schemas/CellNotification'
+ completed-run: '#/components/schemas/CompletedRunNotification'
+ completion-result: '#/components/schemas/CompletionResultNotification'
+ consumer-capabilities: '#/components/schemas/ConsumerCapabilitiesNotification'
+ data-column-preview: '#/components/schemas/DataColumnPreviewNotification'
+ data-source-connections: '#/components/schemas/DataSourceConnectionsNotification'
+ data-source-discovery-result: '#/components/schemas/DataSourceDiscoveryResultNotification'
+ datasets: '#/components/schemas/DatasetsNotification'
+ environment-operation: '#/components/schemas/EnvironmentOperationNotification'
+ environment-state: '#/components/schemas/EnvironmentStateNotification'
+ execution: '#/components/schemas/ExecutionNotification'
+ focus-cell: '#/components/schemas/FocusCellNotification'
+ function-call-result: '#/components/schemas/FunctionCallResultNotification'
+ interrupted: '#/components/schemas/InterruptedNotification'
+ kernel-ready: '#/components/schemas/KernelReadyNotification'
+ kernel-startup-error: '#/components/schemas/KernelStartupErrorNotification'
+ missing-package-alert: '#/components/schemas/MissingPackageAlertNotification'
+ model-lifecycle: '#/components/schemas/ModelLifecycleNotification'
+ notebook-document-transaction: '#/components/schemas/NotebookDocumentTransactionNotification'
+ query-params-append: '#/components/schemas/QueryParamsAppendNotification'
+ query-params-clear: '#/components/schemas/QueryParamsClearNotification'
+ query-params-delete: '#/components/schemas/QueryParamsDeleteNotification'
+ query-params-set: '#/components/schemas/QueryParamsSetNotification'
+ reconnected: '#/components/schemas/ReconnectedNotification'
+ reload: '#/components/schemas/ReloadNotification'
+ remove-ui-elements: '#/components/schemas/RemoveUIElementsNotification'
+ secret-keys-result: '#/components/schemas/SecretKeysResultNotification'
+ send-ui-element-message: '#/components/schemas/UIElementMessageNotification'
+ sql-schema-list-preview: '#/components/schemas/SQLSchemaListPreviewNotification'
+ sql-table-list-preview: '#/components/schemas/SQLTableListPreviewNotification'
+ sql-table-preview: '#/components/schemas/SQLTablePreviewNotification'
+ startup-logs: '#/components/schemas/StartupLogsNotification'
+ startup-progress: '#/components/schemas/StartupProgressNotification'
+ storage-download-ready: '#/components/schemas/StorageDownloadReadyNotification'
+ storage-entries: '#/components/schemas/StorageEntriesNotification'
+ storage-namespaces: '#/components/schemas/StorageNamespacesNotification'
+ validate-sql-result: '#/components/schemas/ValidateSQLResultNotification'
+ variable-values: '#/components/schemas/VariableValuesNotification'
+ variables: '#/components/schemas/VariablesNotification'
+ propertyName: op
OpenAiConfig:
description: "Configuration options for OpenAI or OpenAI-compatible services.\n\
\n **Keys.**\n\n - `api_key`: the OpenAI API key or an `env:` reference\n\
diff --git a/packages/openapi/convert_types.js b/packages/openapi/convert_types.js
index f86b234460..6bea735af3 100644
--- a/packages/openapi/convert_types.js
+++ b/packages/openapi/convert_types.js
@@ -7,10 +7,10 @@ import ts from "typescript";
/**
* Map from OpenAPI `format` values (emitted by _enrich_branded_types in
- * commands.py) to the TypeScript brand tag used in TypedString<T>.
+ * schema.py) to the TypeScript brand tag used in TypedString<T>.
*
* When a new NewType is added to marimo/_types/ids.py *and* registered in
- * _enrich_branded_types (commands.py), add a corresponding entry here so
+ * _enrich_branded_types (schema.py), add a corresponding entry here so
* the generated TypeScript carries the branded type.
*/
const BRANDED_FORMATS = /** @type {const} */ ({
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index f616c699c5..a0afbed67d 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -4283,6 +4283,23 @@ export interface components {
};
/** ClearCacheRequest */
ClearCacheRequest: Record<string, any>;
+ ClientCommand:
+ | components["schemas"]["ExecuteCellsCommand"]
+ | components["schemas"]["ExecuteScratchpadCommand"]
+ | components["schemas"]["DeleteCellCommand"]
+ | components["schemas"]["UpdateCellConfigCommand"]
+ | components["schemas"]["UpdateUIElementCommand"]
+ | components["schemas"]["ModelCommand"]
+ | components["schemas"]["InvokeFunctionCommand"]
+ | components["schemas"]["InstallPackagesCommand"]
+ | components["schemas"]["PreviewDatasetColumnCommand"]
+ | components["schemas"]["PreviewSQLTableCommand"]
+ | components["schemas"]["ListSQLTablesCommand"]
+ | components["schemas"]["ListSQLSchemasCommand"]
+ | components["schemas"]["ValidateSQLCommand"]
+ | components["schemas"]["ListDataSourceConnectionCommand"]
+ | components["schemas"]["DiscoverDataSourcesCommand"]
+ | components["schemas"]["ListSecretKeysCommand"];
/** CodeCompletionRequest */
CodeCompletionRequest: {
cellId: components["schemas"]["CellId"];
@@ -4593,6 +4610,17 @@ export interface components {
| "time"
| "unknown";
};
+ /** @enum {unknown} */
+ DataType:
+ | "boolean"
+ | "date"
+ | "datetime"
+ | "geometry"
+ | "integer"
+ | "number"
+ | "string"
+ | "time"
+ | "unknown";
/**
* Database
* @description Represents a collection of schemas.
@@ -5656,95 +5684,16 @@ export interface components {
preset: "default" | "vim";
vimrc?: string | null;
};
- /** KnownUnions */
+ /**
+ * KnownUnions
+ * @deprecated
+ * @description Use the named NotificationMessage, ClientCommand, MarimoError, and DataType schemas directly.
+ */
KnownUnions: {
- command:
- | components["schemas"]["ExecuteCellsCommand"]
- | components["schemas"]["ExecuteScratchpadCommand"]
- | components["schemas"]["DeleteCellCommand"]
- | components["schemas"]["UpdateCellConfigCommand"]
- | components["schemas"]["UpdateUIElementCommand"]
- | components["schemas"]["ModelCommand"]
- | components["schemas"]["InvokeFunctionCommand"]
- | components["schemas"]["InstallPackagesCommand"]
- | components["schemas"]["PreviewDatasetColumnCommand"]
- | components["schemas"]["PreviewSQLTableCommand"]
- | components["schemas"]["ListSQLTablesCommand"]
- | components["schemas"]["ListSQLSchemasCommand"]
- | components["schemas"]["ValidateSQLCommand"]
- | components["schemas"]["ListDataSourceConnectionCommand"]
- | components["schemas"]["DiscoverDataSourcesCommand"]
- | components["schemas"]["ListSecretKeysCommand"];
- /** @enum {unknown} */
- data_type:
- | "boolean"
- | "date"
- | "datetime"
- | "geometry"
- | "integer"
- | "number"
- | "string"
- | "time"
- | "unknown";
- error:
- | components["schemas"]["SetupRootError"]
- | components["schemas"]["CycleError"]
- | components["schemas"]["MultipleDefinitionError"]
- | components["schemas"]["ImportStarError"]
- | components["schemas"]["MarimoAncestorStoppedError"]
- | components["schemas"]["MarimoAncestorPreventedError"]
- | components["schemas"]["MarimoExceptionRaisedError"]
- | components["schemas"]["MarimoStrictExecutionError"]
- | components["schemas"]["MarimoInterruptionError"]
- | components["schemas"]["MarimoSyntaxError"]
- | components["schemas"]["MarimoInternalError"]
- | components["schemas"]["MarimoSQLError"]
- | components["schemas"]["UnknownError"];
- notification:
- | components["schemas"]["CellNotification"]
- | components["schemas"]["ExecutionNotification"]
- | components["schemas"]["FunctionCallResultNotification"]
- | components["schemas"]["UIElementMessageNotification"]
- | components["schemas"]["ModelLifecycleNotification"]
- | components["schemas"]["RemoveUIElementsNotification"]
- | components["schemas"]["ReloadNotification"]
- | components["schemas"]["ReconnectedNotification"]
- | components["schemas"]["InterruptedNotification"]
- | components["schemas"]["CompletedRunNotification"]
- | components["schemas"]["KernelReadyNotification"]
- | components["schemas"]["CompletionResultNotification"]
- | components["schemas"]["AlertNotification"]
- | components["schemas"]["BannerNotification"]
- | components["schemas"]["MissingPackageAlertNotification"]
- | components["schemas"]["EnvironmentOperationNotification"]
- | components["schemas"]["EnvironmentStateNotification"]
- | components["schemas"]["StartupLogsNotification"]
- | components["schemas"]["StartupProgressNotification"]
- | components["schemas"]["KernelStartupErrorNotification"]
- | components["schemas"]["VariablesNotification"]
- | components["schemas"]["VariableValuesNotification"]
- | components["schemas"]["QueryParamsSetNotification"]
- | components["schemas"]["QueryParamsAppendNotification"]
- | components["schemas"]["QueryParamsDeleteNotification"]
- | components["schemas"]["QueryParamsClearNotification"]
- | components["schemas"]["DatasetsNotification"]
- | components["schemas"]["DataColumnPreviewNotification"]
- | components["schemas"]["SQLTablePreviewNotification"]
- | components["schemas"]["SQLTableListPreviewNotification"]
- | components["schemas"]["SQLSchemaListPreviewNotification"]
- | components["schemas"]["DataSourceConnectionsNotification"]
- | components["schemas"]["DataSourceDiscoveryResultNotification"]
- | components["schemas"]["ValidateSQLResultNotification"]
- | components["schemas"]["StorageNamespacesNotification"]
- | components["schemas"]["StorageEntriesNotification"]
- | components["schemas"]["StorageDownloadReadyNotification"]
- | components["schemas"]["SecretKeysResultNotification"]
- | components["schemas"]["CacheClearedNotification"]
- | components["schemas"]["CacheInfoNotification"]
- | components["schemas"]["FocusCellNotification"]
- | components["schemas"]["ActiveLineNotification"]
- | components["schemas"]["NotebookDocumentTransactionNotification"]
- | components["schemas"]["ConsumerCapabilitiesNotification"];
+ command: components["schemas"]["ClientCommand"];
+ data_type: components["schemas"]["DataType"];
+ error: components["schemas"]["MarimoError"];
+ notification: components["schemas"]["NotificationMessage"];
};
/**
* LanguageServersConfig
@@ -6024,6 +5973,20 @@ export interface components {
snippets?: components["schemas"]["SnippetsConfig"];
venv?: components["schemas"]["VenvConfig"];
};
+ MarimoError:
+ | components["schemas"]["SetupRootError"]
+ | components["schemas"]["CycleError"]
+ | components["schemas"]["MultipleDefinitionError"]
+ | components["schemas"]["ImportStarError"]
+ | components["schemas"]["MarimoAncestorStoppedError"]
+ | components["schemas"]["MarimoAncestorPreventedError"]
+ | components["schemas"]["MarimoExceptionRaisedError"]
+ | components["schemas"]["MarimoStrictExecutionError"]
+ | components["schemas"]["MarimoInterruptionError"]
+ | components["schemas"]["MarimoSyntaxError"]
+ | components["schemas"]["MarimoInternalError"]
+ | components["schemas"]["MarimoSQLError"]
+ | components["schemas"]["UnknownError"];
/** MarimoExceptionRaisedError */
MarimoExceptionRaisedError: {
exception_type: string;
@@ -6324,6 +6287,51 @@ export interface components {
| components["schemas"]["SetConfig"]
)[];
};
+ NotificationMessage:
+ | components["schemas"]["CellNotification"]
+ | components["schemas"]["ExecutionNotification"]
+ | components["schemas"]["FunctionCallResultNotification"]
+ | components["schemas"]["UIElementMessageNotification"]
+ | components["schemas"]["ModelLifecycleNotification"]
+ | components["schemas"]["RemoveUIElementsNotification"]
+ | components["schemas"]["ReloadNotification"]
+ | components["schemas"]["ReconnectedNotification"]
+ | components["schemas"]["InterruptedNotification"]
+ | components["schemas"]["CompletedRunNotification"]
+ | components["schemas"]["KernelReadyNotification"]
+ | components["schemas"]["CompletionResultNotification"]
+ | components["schemas"]["AlertNotification"]
+ | components["schemas"]["BannerNotification"]
+ | components["schemas"]["MissingPackageAlertNotification"]
+ | components["schemas"]["EnvironmentOperationNotification"]
+ | components["schemas"]["EnvironmentStateNotification"]
+ | components["schemas"]["StartupLogsNotification"]
+ | components["schemas"]["StartupProgressNotification"]
+ | components["schemas"]["KernelStartupErrorNotification"]
+ | components["schemas"]["VariablesNotification"]
+ | components["schemas"]["VariableValuesNotification"]
+ | components["schemas"]["QueryParamsSetNotification"]
+ | components["schemas"]["QueryParamsAppendNotification"]
+ | components["schemas"]["QueryParamsDeleteNotification"]
+ | components["schemas"]["QueryParamsClearNotification"]
+ | components["schemas"]["DatasetsNotification"]
+ | components["schemas"]["DataColumnPreviewNotification"]
+ | components["schemas"]["SQLTablePreviewNotification"]
+ | components["schemas"]["SQLTableListPreviewNotification"]
+ | components["schemas"]["SQLSchemaListPreviewNotification"]
+ | components["schemas"]["DataSourceConnectionsNotification"]
+ | components["schemas"]["DataSourceDiscoveryResultNotification"]
+ | components["schemas"]["ValidateSQLResultNotification"]
+ | components["schemas"]["StorageNamespacesNotification"]
+ | components["schemas"]["StorageEntriesNotification"]
+ | components["schemas"]["StorageDownloadReadyNotification"]
+ | components["schemas"]["SecretKeysResultNotification"]
+ | components["schemas"]["CacheClearedNotification"]
+ | components["schemas"]["CacheInfoNotification"]
+ | components["schemas"]["FocusCellNotification"]
+ | components["schemas"]["ActiveLineNotification"]
+ | components["schemas"]["NotebookDocumentTransactionNotification"]
+ | components["schemas"]["ConsumerCapabilitiesNotification"];
/**
* OpenAiConfig
* @description Configuration options for OpenAI or OpenAI-compatible services.
diff --git a/tests/_cli/test_cli_development.py b/tests/_cli/test_cli_development.py
index 3c35179838..c2b7a26845 100644
--- a/tests/_cli/test_cli_development.py
+++ b/tests/_cli/test_cli_development.py
@@ -7,12 +7,12 @@ from typing import Any, get_args
import yaml
-from marimo._cli.development.commands import _generate_server_api_schema
+from marimo._cli.development.schema import generate_server_api_schema
from marimo._runtime import commands
def test_openapi_exports_only_client_commands() -> None:
- schemas = _generate_server_api_schema()["components"]["schemas"]
+ schemas = generate_server_api_schema()["components"]["schemas"]
command_names = {
model.__name__
for model in vars(commands).values()
@@ -25,7 +25,7 @@ def test_openapi_exports_only_client_commands() -> None:
def test_openapi_preserves_brands_in_client_commands() -> None:
- schemas = _generate_server_api_schema()["components"]["schemas"]
+ schemas = generate_server_api_schema()["components"]["schemas"]
assert schemas["ExecuteCellsCommand"]["properties"]["cellIds"] == {
"type": "array",
@@ -37,6 +37,35 @@ def test_openapi_preserves_brands_in_client_commands() -> None:
}
+def test_openapi_known_unions_reference_named_exports() -> None:
+ schemas = generate_server_api_schema()["components"]["schemas"]
+
+ assert {
+ "NotificationMessage",
+ "ClientCommand",
+ "MarimoError",
+ "DataType",
+ } <= schemas.keys()
+ assert schemas["KnownUnions"] == {
+ "title": "KnownUnions",
+ "deprecated": True,
+ "description": (
+ "Use the named NotificationMessage, ClientCommand, MarimoError, "
+ "and DataType schemas directly."
+ ),
+ "type": "object",
+ "properties": {
+ "notification": {
+ "$ref": "#/components/schemas/NotificationMessage"
+ },
+ "command": {"$ref": "#/components/schemas/ClientCommand"},
+ "error": {"$ref": "#/components/schemas/MarimoError"},
+ "data_type": {"$ref": "#/components/schemas/DataType"},
+ },
+ "required": ["notification", "command", "error", "data_type"],
+ }
+
+
def _normalize_union_order(schema: Any) -> Any:
if isinstance(schema, list):
return [_normalize_union_order(value) for value in schema]
diff --git a/tests/_cli/test_cli_schema.py b/tests/_cli/test_cli_schema.py
new file mode 100644
index 0000000000..15b280239e
--- /dev/null
+++ b/tests/_cli/test_cli_schema.py
@@ -0,0 +1,85 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Literal
+
+import msgspec
+import pytest
+
+from marimo._cli.development.schema import _generate_schema_components
+from marimo._types.ids import CellId_t
+
+
+class Payload(msgspec.Struct, rename="camel"):
+ cell_id: CellId_t
+
+
+class Read(msgspec.Struct, tag="read"):
+ payload: Payload
+
+
+class Write(msgspec.Struct, tag="write"):
+ payloads: list[Payload]
+
+
+def test_named_union_preserves_discriminator_and_transitive_brands() -> None:
+ schemas = _generate_schema_components([], {"Action": Read | Write})
+
+ assert sorted(
+ schemas["Action"]["anyOf"], key=lambda schema: schema["$ref"]
+ ) == [
+ {"$ref": "#/components/schemas/Read"},
+ {"$ref": "#/components/schemas/Write"},
+ ]
+ assert schemas["Action"]["discriminator"] == {
+ "propertyName": "type",
+ "mapping": {
+ "read": "#/components/schemas/Read",
+ "write": "#/components/schemas/Write",
+ },
+ }
+ assert schemas["Payload"] == {
+ "title": "Payload",
+ "type": "object",
+ "properties": {"cellId": {"$ref": "#/components/schemas/CellId"}},
+ "required": ["cellId"],
+ }
+ assert schemas["CellId"] == {"type": "string", "format": "cell-id"}
+
+
+def test_brands_in_dependencies_reachable_only_through_lists() -> None:
+ schemas = _generate_schema_components([], {"Write": Write})
+
+ assert schemas["Write"]["properties"]["payloads"] == {
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/Payload"},
+ }
+ assert schemas["Payload"]["properties"]["cellId"] == {
+ "$ref": "#/components/schemas/CellId"
+ }
+ assert schemas["CellId"] == {"type": "string", "format": "cell-id"}
+
+
+def test_named_literal() -> None:
+ schemas = _generate_schema_components(
+ [], {"Status": Literal["ready", "running"]}
+ )
+
+ assert schemas["Status"] == {"enum": ["ready", "running"]}
+
+
+def test_exporting_a_struct_under_its_own_name() -> None:
+ schemas = _generate_schema_components([], {"Payload": Payload})
+
+ assert schemas["Payload"] == {
+ "title": "Payload",
+ "type": "object",
+ "properties": {"cellId": {"$ref": "#/components/schemas/CellId"}},
+ "required": ["cellId"],
+ }
+
+
[email protected]("name", ["Payload", "CellId"])
+def test_export_name_cannot_overwrite_a_dependency(name: str) -> None:
+ with pytest.raises(ValueError, match=f"Schema export '{name}' conflicts"):
+ _generate_schema_components([Payload], {name: Literal["other"]})