Протокол парного программирования для marimo-ноутбуков

Звёзды435
Форки36
Авторmarimo-team
Маркетплейс@marimo-pair
Компонентов1
Обновлённоя 13 2026

Установка

SKILL.md

marimo is a reactive Python runtime for building reproducible Python programs (marimo notebooks). Cells are connected by the variables they define and reference. Running a cell re-executes dependents in dataflow order. The active runtime holds the kernel namespace, cell state, and dataflow graph. The notebook (.py file) is the artifact the kernel writes from that state while a session is running.

A user interacts with the same runtime via a notebook UI with cells, outputs, and widgets.

WARNING. The active runtime is the source of truth. During a session, you SHOULD NOT modify the associated .py file directly. File edits WILL NOT reach the active kernel or user, and the kernel may overwrite them on save. Use marimo._code_mode (cm) for notebook changes. Reading disk is fine, but prefer ctx.cells[...].code for current cell code.

Connect to a Notebook

Use the bundled script (bash scripts/execute-code.sh) or MCP (execute_code(...)) to run Python in a live marimo kernel.

If the user provides a notebook URL, target it directly:

bash scripts/execute-code.sh --url http://localhost:2718 -c "print('connected')"

Use -c only for short one-liners. For multiline code or code containing quotes, backticks, $, or braces, use a single-quoted heredoc:

bash scripts/execute-code.sh --url http://localhost:2718 <<'PY'
import marimo._code_mode as cm

async with cm.get_context() as ctx:
    cid = ctx.create_cell("x = df.head()")
    ctx.run_cell(cid)
PY

When code already lives in a file, pass the file path:

bash scripts/execute-code.sh --url http://localhost:2718 /tmp/code.py

If no target is provided, find or start a session. First look for a running session with bash scripts/discover-servers.sh, MCP list_sessions(), or local process context. When multiple sessions are possible, target with --url, --port, or --session.

If no server is running and the user wants a notebook, start marimo with --no-token (and without --headless) so it auto-registers for discovery. The notebook UI must be open before there is an active session for execute-code to target. The right way to invoke marimo depends on context (project tooling, global install, sandbox mode). If the notebook file contains a PEP 723 # /// script header, it MUST be opened with --sandbox — otherwise marimo ignores the inline dependencies. See finding-marimo.md for the full decision tree and execution-context.md for scripts, MCP, and shell quoting.

Scratchpad Scope

execute-code evaluates Python in marimo's scratchpad: a temporary namespace with a shallow copy of the kernel globals. Notebook variables are available by name, but new top-level bindings and rebindings are discarded after each call. In-place mutations to notebook-owned objects can persist because those names still reference live objects.

Each call reports stdout and stderr from the scratchpad, plus console output from notebook cells it causes to run, including reactive descendants.

Ordinary Python

Use ordinary Python in the scratchpad to inspect variables, sample data, test transformations, probe APIs, check imports, and read widget state.

print(df.head())

x = 10
print(x)

Here df comes from notebook globals, while x is a scratchpad-local binding. x exists for this call only and WILL NOT be added to notebook globals.

Persist with cm

Top-level scratchpad assignments and rebindings are temporary. To persist work, including new variables, you MUST submit changes through marimo._code_mode (cm).

marimo._code_mode is a PRIVATE, UNSTABLE agent API (note the leading underscore). It exists for tools like this skill to drive a live kernel from the scratchpad. DO NOT import it from notebook cells, library code, or anything a user would run — methods can change or disappear across marimo versions and kernels. Treat every import marimo._code_mode as cm as scratchpad-only.

At session start, inspect what cm exposes in the active kernel:

import marimo._code_mode as cm

help(cm)

Open a code-mode context to queue notebook changes.

import marimo._code_mode as cm

async with cm.get_context() as ctx:
    cid = ctx.create_cell("x = df.head()")
    ctx.run_cell(cid)

The scratchpad supports top-level async code. Use async with directly; wrapping it in asyncio.run(...) is unnecessary and can conflict with the kernel's event loop.

After this block exits and the new cell runs, x is notebook state. Later scratchpad calls can read x by name. Code later in the same scratchpad call should read ctx.globals["x"], because the scratchpad namespace was copied before the cell ran.

Inside the context, queued mutation methods are synchronous. Call them directly; do not await them. Each call queues an operation for marimo to apply when the context exits normally. If the block raises, the queue is discarded.

On clean exit, marimo applies packages, validates and applies structural cell changes, runs queued cells, then may run dependents. Validation is only structural since queued cell runs can still error. create_cell and edit_cell change notebook structure only. Use run_cell to execute.

create_cell currently defaults to hide_code=True, which collapses the code editor in the UI. Pass hide_code=False if the user wants created cells to be visible without manually expanding them.

Marimo Rules

marimo imposes a small contract on notebook code so it can keep the notebook as a directed acyclic graph (DAG):

  • No cycles - cells cannot depend on each other in a cycle.
  • No public redefinitions across cells - each name has one owning cell.
  • No wildcard imports - import * prevents static analysis of definitions.

These rules keep the kernel, UI, and saved artifact consistent.

When cm submits a cell body, marimo parses its top-level definitions and references. A top-level name enters the graph unless it is private with a leading underscore.

# Public definitions: values, total, i, value, mean
values = np.array([1, 2, 3])
total = 0
for i, value in enumerate(values):
    total += value
mean = total / len(values)
mean
# Public definition: mean
_values = np.array([1, 2, 3])
_total = 0
for _i, _value in enumerate(_values):
    _total += _value
mean = _total / len(_values)
mean

Use private names for intermediates that no other cell should read. Public names define the notebook-level dataflow. If a cm edit violates the contract, marimo rejects the structural change and returns the validation error.

The Notebook's Shape

A notebook is an ordered collection of cells. ctx.cells is the document view and ctx.graph is the dataflow view.

for cell in ctx.cells:
    cell  # .id, .code, .name, .config, .status, .errors

ctx.cells["setup"]         # by name
ctx.cells[0]               # by position
list(ctx.cells.keys())     # all IDs, in notebook order

Cell IDs are opaque strings which can be queried from the notebook or captured from cm return values:

cid = ctx.create_cell("df = pd.read_csv('data.csv')")
print(cid)   # e.g. 'Hbol'

Alternatively, cells can be assigned and referenced by name. The graph can be used to understand its role in the dataflow.

for cid, impl in ctx.graph.cells.items():
    impl  # .defs, .refs   (sets of public names)

ctx.graph.descendants(cid)   # cells that re-run when this one changes
ctx.graph.ancestors(cid)     # cells this one depends on

In marimo, deletes are destructive so it can be useful to query the descendants prior to deleting to understand it's impact.

Writing Notebook Changes

The graph contract keeps marimo able to run and save the notebook. Passing those checks alone does not guarantee a useful artifact. Committed cells should still be readable, rerunnable, and editable.

Make durable edits that reuse the notebook's existing names, imports, dependencies, and UI model. Don't be lazy. Avoid one-off workarounds that pass cm validation but leave a brittle notebook.

Cell Bodies

Submit the code that belongs in the cell.

  • Submit cell contents - create_cell and edit_cell take cell contents, not saved-file @app.cell wrappers.
  • Read before replacing - for now, another editor may change a cell between scratchpad calls. Before edit_cell, read the current body from ctx.cells[...] and submit the full replacement.
  • Reuse notebook imports - if np already exists, use it or edit the owning import cell. DO NOT add import numpy as _np just to bypass the graph.
  • Define public names intentionally - use public names for values later cells should reference. Use private _name bindings or function locals for same-cell intermediates.
  • Define each public name once - a public name has one owning cell. Reassigning it in another cell fails with Multiply-defined names; edit the owning cell or give the result a new name. See gotchas.md.
  • Run cells deliberately - create_cell and edit_cell change structure only. Queue ctx.run_cell(...) when the cell should execute.

Prefer cm-Managed Changes

Use cm APIs when they exist. Avoid direct file edits, shell package commands, and scratchpad-only state for changes that should persist.

  • Do not edit the .py artifact - DO NOT use Edit, Write, or NotebookEdit on the notebook file during a live session. Use ctx.edit_cell(...) even for small changes.
  • Manage packages through cm - use ctx.packages.add() or ctx.packages.remove() instead of direct uv or pip; confirm non-obvious dependency changes.
  • Avoid transient paths - persisted cells should not depend on /tmp/... unless the work is intentionally transient.
  • Delete deliberately - deleting a cell removes globals it defines. Reuse empty cells when convenient and delete cells left empty after edits.

UI and Widgets

Inspect the object before changing it. Different UI objects update through different paths.

  • Set mo.ui.* through cm - use ctx.set_ui_value(element, value) inside cm.get_context().
  • Set anywidget traitlets directly - synced traitlets are Python attributes, for example widget.value = 5.

For designing custom visual or interactive output, see rich-representations.md.

References

  • execution-context.md — scripts, MCP, auth, startup, and shell quoting
  • finding-marimo.md — choosing the right marimo invocation
  • gotchas.md — name redefinition, cached module proxies, and notebook traps
  • rich-representations.md — custom widgets and visualizations
  • notebook-improvements.md — improving existing notebooks

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: marimo-pair](https://darkplay.ru/ai/plugins/marimo-team-marimo-pair-marimo-pair)

Похожие плагины и другие разделы каталога

Похожие плагины в категории «Программирование»

Та же категория — сравните, что ещё подойдёт под вашу задачу.

ruflo-dddruvnet · Каркас Domain-Driven Design: ограниченные контексты, агрегатные корни, доменные события и…
240 комп.
cli-anythinghkuds · Создавайте мощные CLI-интерфейсы с сохранением состояния для любого GUI-приложения по…
5 комп.
agentic-bundle-aas-python-api-buildersickn33 · Установите набор редакционных навыков "AAS Python API Builder" для Claude Code.
49 917 ★
agentic-bundle-architecture-designsickn33 · Установите набор редакционных навыков "Architecture & Design" для Claude Code.
49 917 ★
agentic-bundle-ddd-evented-architecturesickn33 · Установите набор редакционных навыков "DDD & Evented Architecture" для Claude Code.
49 917 ★
agentic-bundle-full-stack-developersickn33 · Установите набор редакционных навыков «Full-Stack Developer» для Claude Code.
49 917 ★
agentic-bundle-makepad-buildersickn33 · Установите набор редакционных навыков "Makepad Builder" для Claude Code.
49 917 ★
agentic-bundle-odoo-erpsickn33 · Установите набор редакционных навыков "Odoo ERP" для Claude Code.
49 917 ★
agentic-bundle-python-prosickn33 · Установите набор редакционных навыков «Python Pro» для Claude Code.
49 917 ★
agentic-bundle-systems-programmingsickn33 · Установите набор редакционных навыков «Systems Programming» для Claude Code.
49 917 ★
Популярное в разделе «Плагины»

Самые востребованные плагинов раздела по установкам и звёздам.

mattpocock-skillsmattpocock · Агентские навыки Matt Pocock для настоящей инженерии: разбор задач, потоки спецификаций и…
41 комп.
superpowersobra · Базовая библиотека навыков для Claude Code: TDD, отладка, паттерны совместной работы и…
16 комп.
eccaffaan-m · Нативный для harness операторский слой ECC: 67 агентов, 278 навыков, 94 шима устаревших…
441 комп.
andrej-karpathy-skillsmultica-ai · Правила поведения для снижения типичных ошибок LLM при программировании: думай перед…
1 комп.
claude-apianthropics · Навык по документации Claude API и SDK для создания приложений на базе LLM.
17 комп.
document-skillsanthropics · Набор инструментов для обработки документов: Excel, Word, PowerPoint и PDF.
17 комп.
example-skillsanthropics · Набор примеров навыков, демонстрирующих разные возможности: создание навыков, разработку…
17 комп.
ponytailDietrichGebert · Настаивает на самом простом работающем решении. YAGNI, сначала стандартная библиотека…
9 комп.
prompts.chatf · Доступ к тысячам AI-промптов и навыков прямо в AI-ассистенте для программирования. Поиск…
6 комп.
agent-sdk-devanthropics · Набор для разработки с Claude Agent SDK.
34 комп.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

ui-ux-pro-maxnextlevelbuilder · База знаний по UI/UX-дизайну для веба и мобильных: стили, палитры, шрифты
457 200 устан.
better-typographyjakubkrehel · Веб-типографика: выбор шрифтов, интервалы, переносы и доступность. Используй при подборе…
43 500 устан.
game-feelgamedev-skills · Добавляет «сочность» и игровое ощущение: тряска экрана, hit-stop, твининг, squash &…
18 300 устан.
game-ui-uxgamedev-skills · Проектирование игрового UI/UX — HUD, меню и оверлеи: адаптивная вёрстка, масштабирование…
18 100 устан.
performance-optimizationgamedev-skills · Методичный поиск и исправление проблем производительности: профилировщик, бюджет кадра…
14 600 устан.
game-aigamedev-skills · Поведение NPC и врагов: конечные автоматы, деревья поведения, steering и поиск пути A*.
14 500 устан.
camera-systemsgamedev-skills · Игровые камеры: 2D-следование с мёртвой зоной и сглаживанием, 3D-орбита от третьего лица…
14 400 устан.
pdftk-servergithub · Навык работы с PDF через CLI-утилиту pdftk
10 000 устан.
agent-architecture-auditaffaan-m · Полностековая диагностика агентных и LLM-приложений: аудит 12-слойного стека агента на…
6 300 устан.
guizang-social-card-skillop7418 · Генерирует соцкарточки в стиле Guizang, Live Photo-коллажи и обложки для WeChat из статей…
5 600 устан.

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8