Skip to main content
Glama
tldraw-mcp

tldraw-mcp

by m9810223

tldraw-mcp

Минималистичный MCP-сервер для редактирования файлов tldraw .tldr через манипуляции с JSON. Работает без графического интерфейса, браузер не требуется.

Статус

Рабочий каркас. Валидация схемы настроена (валидаторы @tldraw/tlschema запускаются перед каждой записью), дробная индексация использует @tldraw/utils, запись файлов защищена с помощью proper-lockfile. Вывод проверен сквозным тестированием с реальной средой выполнения tldraw через Store.loadStoreSnapshot() в слое контрактных тестов.

Related MCP server: obsidian-codex-mcp

Инструменты

Жизненный цикл файла / страницы

Инструмент

Что делает

create_empty_file

Создает новый файл .tldr со страницей по умолчанию

create_page

Добавляет новую страницу

list_pages

Выводит список страниц с id, именем и порядковым индексом

move_to_page

Перемещает фигуры; `bindings: 'error'

'pull'

'cut'` управляет обработкой привязок

Фигуры

Инструмент

Что делает

create_rect

Создает прямоугольник (геометрическая фигура)

create_text

Создает текстовую фигуру

create_group

Группирует фигуры путем изменения их родителя

ungroup

Разгруппировывает, перенося дочерние элементы к родителю группы

connect

Стрелка + привязки между двумя фигурами на одной странице

list_shapes

Список фигур — только id, тип, x, y, метка

get_shape

Полная запись одной фигуры по id

update_shape

Поверхностное слияние (используйте вложенный { "props": {...} } для правки свойств)

delete_shape

Удаление по id; cascade: true (по умолчанию) также удаляет привязанные стрелки + привязки

Обнаружение и «аварийный выход» (вдохновлено официальным tldraw-mcp-app)

Инструмент

Что делает

Стоимость токенов

search_api

Список поддерживаемых типов фигур + отобранные обязательные свойства. Передайте {type, verbose:true}, чтобы получить актуальные имена свойств из @tldraw/tlschema для любого типа (включая те, что не входят в основной список)

низкая / средняя

exec_jq

Запуск фильтра jq для файла. write=true сохраняет изменения (сначала автоматически создает контрольную точку)

варьируется

Контрольные точки (безопасность)

Инструмент

Что делает

Стоимость токенов

save_checkpoint

Копирует .tldr в резервную копию с отметкой времени

низкая

list_checkpoints

Список резервных копий, начиная с самых новых

низкая

restore_checkpoint

Восстановление резервной копии (самой последней, если checkpoint не указан)

низкая

Дизайн с экономией токенов: инструменты принимают примитивные аргументы, возвращают id или ok. Полный JSON попадает в контекст только тогда, когда вы намеренно вызываете get_shape.

Установка

Вариант 1 · npx (без установки, рекомендуется)

npx -y github:m9810223/tldraw-mcp

Первый запуск клонирует репозиторий, выполняет npm install, затем запускает скрипт prepare, который собирает dist/. Последующие запуски кэшируются.

Закрепление ветки / тега / коммита:

npx -y github:m9810223/tldraw-mcp#main
npx -y github:m9810223/tldraw-mcp#v0.1.0
npx -y github:m9810223/tldraw-mcp#abc1234

Вариант 2 · Глобальная установка

npm install -g github:m9810223/tldraw-mcp
tldraw-mcp   # the bin is on PATH

Вариант 3 · Частный репозиторий через SSH

npx -y git+ssh://git@github.com/m9810223/tldraw-mcp.git

Вариант 4 · Локальное клонирование (для разработки)

git clone https://github.com/m9810223/tldraw-mcp.git
cd tldraw-mcp
npm install
npm run build
node dist/index.js   # stdio MCP — waits on stdin

Требования

  • Node.js ≥ 20 (принудительно через engines.node)

  • jq в PATH (требуется только для инструмента exec_jq)

    • macOS: brew install jq

    • Debian/Ubuntu: sudo apt-get install -y jq

Подключение к Claude Code

claude mcp add (рекомендуется). Разделитель -- обязателен, чтобы -y был передан в npx, а не распознан как флаг claude mcp add:

claude mcp add tldraw -- npx -y github:m9810223/tldraw-mcp

Добавьте -s user для глобального использования (все проекты) или -s project для .mcp.json, зафиксированного в репозитории. По умолчанию используется -s local (этот проект, ваша машина).

…или путем редактирования .mcp.json (проект) / ~/.claude.json (глобально для пользователя):

{
  "mcpServers": {
    "tldraw": {
      "command": "npx",
      "args": ["-y", "github:m9810223/tldraw-mcp"]
    }
  }
}

Если вы установили глобально с помощью Варианта 2:

{
  "mcpServers": {
    "tldraw": { "command": "tldraw-mcp" }
  }
}

Перезапустите Claude Code, после чего /mcp должен показать сервер tldraw с 17 инструментами.

Подключение к другим MCP-клиентам

Та же структура JSON, другое расположение файла конфигурации:

Клиент

Путь к конфигурации

Claude Desktop

~/Library/Application Support/Claude/claude_desktop_config.json (macOS)

Cursor

~/.cursor/mcp.json

VS Code

.vscode/mcp.json

Создание файла .tldr с нуля

Используйте инструмент create_empty_file или сохраните пустой холст с tldraw.com и укажите инструментам абсолютный путь.

create_empty_file({ file: "/tmp/demo.tldr" })

Сравнение дизайна с официальным tldraw-mcp-app

Официальный MCP, размещенный на Cloudflare, предоставляет только search + exec (запуск любого JS в активном редакторе tldraw). Этот каркас идет противоположным путем — типизированное редактирование JSON в файлах .tldr — и заимствует паттерн обнаружения (search_api) и «аварийный выход» (exec_jq), чтобы LLM могла воспользоваться ими, когда типизированных инструментов недостаточно для операции.

Официальный tldraw-mcp-app

Этот каркас

Транспорт

streamable-http + sse (Cloudflare)

stdio (работает напрямую в Claude Code)

Среда

Реальный редактор tldraw в iframe

Чистый Node, редактирует «сырой» JSON

Инструменты

2 (search, exec) + контрольные точки

17: жизненный цикл файла/страницы + 9 операций с фигурами + search_api + exec_jq + ckpt

Предпросмотр

Да (виджет в iframe)

Нет (откройте файл в tldraw для просмотра)

Покрытие

Весь API редактора

Геометрия / текст / стрелки + аварийный выход jq

Известные ограничения

  • index (z-порядок) поддерживает только добавление поверх текущего максимума — вставка между элементами невозможна

  • Нет инструментов выравнивания / распределения (используйте update_shape для прямой установки x/y или exec_jq)

  • Нет поддержки изображений / видео / ассетов

  • Закрепление версии схемы носит только информационный характер — открытие файла в более новой версии tldraw может вызвать миграции

  • Список search_api поддерживается вручную параллельно с рефлексией актуального @tldraw/tlschema

Архитектура

src/
  index.ts       MCP server entry, tool registration (stdio transport)
  tools.ts       Tool handlers + zod input schemas
  shapes.ts      tldraw record factories (geo/text/arrow/group/binding)
  store.ts       Load/save .tldr + withFileLock; helpers (id gen, indexing, find, page-of-shape, bindings-for-shape)
  template.ts    Empty .tldr generator using @tldraw/tlschema serialize()
  validate.ts    validateShape / validateBinding using createShapeValidator + createBindingValidator
  checkpoint.ts  Timestamped backups under .tldraw-mcp-checkpoints/
  jq.ts          Shell-out to jq for the exec_jq escape hatch

test/
  unit/          store + validate (13 tests)
  integration/   tools end-to-end on tmp .tldr (18 tests)
  contract/      loadStoreSnapshot against real @tldraw/store (4 tests)

Чистая манипуляция JSON — без @tldraw/store, без DOM, без React.

Available Tools

18 tools
connectA

Connect two shapes with an arrow. Arrow position is binding-driven (start/end stored as 0,0 fallback). Returns arrow id + binding ids.

Inputs: file (required), fromId (required), toId (required), text.

create_empty_fileA

Create a new empty .tldr file with one default page. Errors if file exists unless overwrite=true.

Inputs: file (required), overwrite.

create_groupA

Group existing shapes into a new group. Reparents the given shape ids under a new group shape.

Inputs: file (required), childIds (required).

create_pageB

Create a new page in the document. Returns the new page id.

Inputs: file (required), name (required).

create_rectC

Create a rectangle shape on the main page. Returns its id.

Inputs: file (required), x (required), y (required), w (required), +3 more.

create_textC

Create a text shape on the main page. Returns its id.

Inputs: file (required), x (required), y (required), text (required), +2 more.

delete_shapeC

Delete a shape by id.

Inputs: file (required), id (required), cascade.

exec_jqA

Escape hatch: run a jq filter against the .tldr JSON. Set write=true to persist (auto-checkpoints first).

Inputs: file (required), filter (required), write.

get_shapeB

Get the full record of a single shape by id.

Inputs: file (required), id (required).

list_checkpointsA

List checkpoint backups for a .tldr file, newest first.

Inputs: file (required).

list_pagesB

List all pages with id, name, and ordering index.

Inputs: file (required).

list_shapesA

List shapes (id, type, x, y, label only - props omitted to save tokens).

Inputs: file (required), type.

move_to_pageB

Move shapes to a different page by reparenting them. Note: arrows and bindings should move together for correctness.

Inputs: file (required), shapeIds (required), pageId (required), bindings.

restore_checkpointA

Restore a checkpoint over the .tldr file. Omits checkpoint to restore the most recent.

Inputs: file (required), checkpoint.

save_checkpointA

Copy the .tldr file to a timestamped backup. Returns the backup path.

Inputs: file (required), label.

search_apiA

List supported tldraw shape types and their required props. Use this to discover what can be created before falling back to exec_jq.

Inputs: query, type, verbose.

ungroupA

Dissolve a group: reparent its children to the group's parent and delete the group shape.

Inputs: file (required), groupId (required).

update_shapeA

Update a shape via shallow merge. Pass nested {"props": {...}} to update props.

Inputs: file (required), id (required), patch (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.6/5.0

    Scored across 18 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose, from creating shapes and pages to managing checkpoints and connecting shapes. The exec_jq escape hatch is intentionally broad but its role as a fallback is well-documented, avoiding confusion.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern in snake_case (e.g., create_rect, list_pages, update_shape). No mixed conventions or ambiguous verbs.

    Tool Count5/5

    With 18 tools, the set is well-scoped for a drawing application: it covers shape CRUD, grouping, pages, checkpoints, and an escape hatch. The count feels complete without being overwhelming.

    Completeness4/5

    The toolset covers core operations but misses explicit tools for creating non-rectangle shapes (e.g., ellipses, lines). However, search_api and exec_jq fill these gaps, so agents can still achieve full functionality.

    Maintenance

    ActivityInactive
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers