tldraw-mcp
tldraw-mcp
Минималистичный MCP-сервер для редактирования файлов tldraw .tldr через манипуляции с JSON. Работает без графического интерфейса, браузер не требуется.
Статус
Рабочий каркас. Валидация схемы настроена (валидаторы @tldraw/tlschema запускаются перед каждой записью), дробная индексация использует @tldraw/utils, запись файлов защищена с помощью proper-lockfile. Вывод проверен сквозным тестированием с реальной средой выполнения tldraw через Store.loadStoreSnapshot() в слое контрактных тестов.
Related MCP server: obsidian-codex-mcp
Инструменты
Жизненный цикл файла / страницы
Инструмент | Что делает | ||
| Создает новый файл | ||
| Добавляет новую страницу | ||
| Выводит список страниц с id, именем и порядковым индексом | ||
| Перемещает фигуры; `bindings: 'error' | 'pull' | 'cut'` управляет обработкой привязок |
Фигуры
Инструмент | Что делает |
| Создает прямоугольник (геометрическая фигура) |
| Создает текстовую фигуру |
| Группирует фигуры путем изменения их родителя |
| Разгруппировывает, перенося дочерние элементы к родителю группы |
| Стрелка + привязки между двумя фигурами на одной странице |
| Список фигур — только id, тип, x, y, метка |
| Полная запись одной фигуры по id |
| Поверхностное слияние (используйте вложенный |
| Удаление по id; |
Обнаружение и «аварийный выход» (вдохновлено официальным tldraw-mcp-app)
Инструмент | Что делает | Стоимость токенов |
| Список поддерживаемых типов фигур + отобранные обязательные свойства. Передайте | низкая / средняя |
| Запуск фильтра | варьируется |
Контрольные точки (безопасность)
Инструмент | Что делает | Стоимость токенов |
| Копирует | низкая |
| Список резервных копий, начиная с самых новых | низкая |
| Восстановление резервной копии (самой последней, если | низкая |
Дизайн с экономией токенов: инструменты принимают примитивные аргументы, возвращают 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 jqDebian/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 |
|
Cursor |
|
VS Code |
|
Создание файла .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 могла воспользоваться ими, когда типизированных инструментов недостаточно для операции.
Официальный | Этот каркас | |
Транспорт | streamable-http + sse (Cloudflare) | stdio (работает напрямую в Claude Code) |
Среда | Реальный редактор tldraw в iframe | Чистый Node, редактирует «сырой» JSON |
Инструменты | 2 ( | 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 toolsconnectA
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
Scored across 18 tools
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.
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.
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.
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
Related MCP Connectors
Collaborative whiteboard MCP server — create objects, connectors, C4 diagrams, and manage boards
Hosted MCP server for Obsidian Sync vaults: read, search, edit notes. Not affiliated with Obsidian.
Related MCP Servers
- AlicenseAqualityDmaintenanceA minimal MCP server for AI-driven canvas manipulation and visualization using tldraw. It enables AI clients to programmatically create, update, and manage shapes, flowcharts, and frames on a live interactive canvas.92MIT
- AlicenseAqualityCmaintenanceLocal-first MCP server for working with an Obsidian vault. No API key required1719MIT
- AlicenseNot gradedqualityBmaintenanceA Codex stdio MCP server that generates simple tldraw product workflow diagrams as .tldr files.125 npm25MIT
- FlicenseNot gradedqualityDmaintenanceMCP server that exposes an Obsidian vault (search, read, create, and update notes) via Streamable HTTP.-