### Deploy Mini App with npx tgcloud push Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Deploys the static files and shows output with uploaded file count and static URL. Example output included. ```bash npx tgcloud push # Deploying 3 changes... # ✓ web/ — 1 file uploaded (2.1 KB) # Static: https://app5888700151.tgcloud.ai/ ``` -------------------------------- ### Установка и настройка tgcloud-mcp Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/index.ru.mdx Команда для глобальной установки пакета и запуска setup. Используется для быстрого старта с MCP-сервером. ```bash npm install -g tgcloud-mcp && tgcloud-mcp setup ``` -------------------------------- ### Test handler locally with npx tgcloud run Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Runs a handler with a JSON5 payload. The example shows a failure due to chat not found, which is expected for fake chat IDs. ```bash npx tgcloud run handlers/message '{ chat: { id: 1 }, text: "выучил serverless" }' # ✗ Uncaught exception: BotApiError: api.sendMessage failed [400]: chat not found ``` -------------------------------- ### init_project Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Скаффолд в существующем каталоге, в том числе с обнаруженным Mini App. ```APIDOC ## init_project ### Description Скаффолд в существующем каталоге, в том числе с обнаруженным Mini App. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud ### CLI Command `tgcloud init` ``` -------------------------------- ### deploy Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Сборка, если в package.json есть script build, затем push. skip_build: true — только push. ```APIDOC ## deploy ### Description Сборка, если в package.json есть script build, затем push. skip_build: true — только push. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud - **skip_build** (boolean) - Optional - Если true, только push ### CLI Command `npm run build` + `tgcloud push` ``` -------------------------------- ### Preview migration with npx tgcloud migrate --dry-run Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Shows the SQL that would be applied without applying it. Output includes the new table creation statement and confirms nothing was applied. ```bash npx tgcloud migrate --dry-run # @@ notes: new table @@ # CREATE TABLE notes ( ... ) # (dry-run — nothing was applied) ``` -------------------------------- ### migrate Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Миграция БД. dry_run: true (по умолчанию) — предпросмотр. Применение: dry_run: false и confirm: true. apply: "safe" — это --safe; apply: "yes" (по умолчанию при применении) — --yes. local: true — --local. ```APIDOC ## migrate ### Description Миграция БД. dry_run: true (по умолчанию) — предпросмотр. Применение: dry_run: false и confirm: true. apply: "safe" — это --safe; apply: "yes" (по умолчанию при применении) — --yes. local: true — --local. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud - **dry_run** (boolean) - Optional - По умолчанию true - **confirm** (boolean) - Optional - Требуется для применения - **apply** (string) - Optional - "safe" или "yes" - **local** (boolean) - Optional - Если true, --local ### CLI Command `tgcloud migrate` ``` -------------------------------- ### upgrade Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Перенос layout до 0.2.0 в tgcloud/. По умолчанию dry_run: true; применение требует confirm: true. ```APIDOC ## upgrade ### Description Перенос layout до 0.2.0 в tgcloud/. По умолчанию dry_run: true; применение требует confirm: true. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud - **dry_run** (boolean) - Optional - По умолчанию true - **confirm** (boolean) - Optional - Требуется для применения ### CLI Command `tgcloud upgrade` ``` -------------------------------- ### Mini App configuration tgcloud.jsonc Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Configuration file for static hosting with SPA mode enabled. Source directory is 'web'. ```jsonc { "static": { "source": "web", "spa": true } } ``` -------------------------------- ### Установка через npm и запуск мастера настройки Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/installation.ru.mdx Устанавливает tgcloud-mcp глобально и запускает мастер настройки клиента. Мастер записывает MCP-конфиг и спрашивает про установку Agent Plugin. ```bash npm install -g tgcloud-mcp tgcloud-mcp setup # мастер настройки клиента ``` -------------------------------- ### create_project Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Скаффолд нового проекта tgcloud. Принимает parent_dir и name. ```APIDOC ## create_project ### Description Скаффолд нового проекта tgcloud. ### Parameters - **parent_dir** (string) - Required - Абсолютный путь к родительскому каталогу - **name** (string) - Required - Имя проекта ### CLI Command `npm create @tgcloud/bot` ``` -------------------------------- ### Troubleshooting Commands for Webhook and Deployment Issues Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Use these commands to diagnose webhook delivery errors, re-sync webhooks, check deployment status, and run server-side modules with local files. The 'sync' command can drop pending updates with --drop-pending, which is destructive. ```bash npx tgcloud webhook # нет ли ошибок доставки, совпадает ли allowed_updates npx tgcloud webhook sync # перепривязать (--drop-pending отбросит очередь — деструктивно) npx tgcloud status/diff # что не задеплоено npx tgcloud run '' # прогон server-side с локальными файлами ``` -------------------------------- ### Запуск через Docker Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/installation.ru.mdx Запускает tgcloud-mcp в контейнере с stdio, без необходимости Node.js на хосте. ```bash docker run -i --rm ghcr.io/sdamarketing/tgcloud-mcp ``` -------------------------------- ### Проверка логики: run_handler Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/quickstart.ru.mdx Команда для проверки логики бота без живого чата. run_handler запускает и endpoints, init data передаётся в ctx. ```text Агент: run_handler { module: 'handlers/message', args: '{ chat: { id: 1 }, text: "hi" }' } ``` -------------------------------- ### Mini App endpoint for listing notes Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Endpoint called from the Mini App as POST /api/listNotes. Platform verifies init data before execution. Returns notes as JSON, throws EndpointError if no user. ```javascript import { db, EndpointError } from 'sdk'; import { notes } from '../schema.js'; import { eq, desc } from 'sdk/db'; export default async function (input, ctx) { const user = ctx.initData?.user; // уже проверен платформой if (!user) throw new EndpointError('No user', { code: 'AUTH' }); const rows = await db.select().from(notes) .where(eq(notes.chatId, user.id)) # в личке chat id == user id .orderBy(desc(notes.id)).limit(50).all(); return { notes: rows }; // вернётся как JSON } ``` -------------------------------- ### Диалог с агентом: создание бота Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/quickstart.ru.mdx Пример диалога с агентом для создания бота в ~/bots/echo. Агент запросит CLI access token, выполнит login_bot, отредактирует tgcloud/handlers/message.js, выполнит push и webhook_sync. ```text Вы: создай бота в ~/bots/echo Агент: create_project → попросит CLI access token → login_bot → поправит tgcloud/handlers/message.js → push → webhook_sync ``` -------------------------------- ### Установка сервера через Docker Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/SETUP.ru.md Вариант C: запуск контейнера Docker с образом ghcr.io/sdamarketing/tgcloud-mcp. ```bash docker run -i --rm ghcr.io/sdamarketing/tgcloud-mcp ``` -------------------------------- ### Логин для CI/неинтерактива: printf и TGCLOUD_ASSUME_TTY Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Неинтерактивный вход в CLI с передачей токена через printf. Альтернатива — export TGCLOUD_TOKEN, тогда login не нужен. ```bash printf 'app...\n' | TGCLOUD_ASSUME_TTY=1 npx tgcloud login # или export TGCLOUD_TOKEN='app...' — тогда login вообще не нужен ``` -------------------------------- ### Scaffold callback_query handler with npx tgcloud add Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Generates a new handler for callback_query events using the tgcloud CLI. Run this command to create the handler file before implementing the callback logic. ```bash npx tgcloud add handlers/callback_query ``` -------------------------------- ### login_bot Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Привязка бота по CLI access token (app:). Токен передаётся через stdin и маскируется. ```APIDOC ## login_bot ### Description Привязка бота по CLI access token (app:). Токен передаётся через stdin и маскируется. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud ### CLI Command `tgcloud login` ``` -------------------------------- ### run_handler Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Прогон handler или endpoint без деплоя. args и ctx — JSON5. ```APIDOC ## run_handler ### Description Прогон handler или endpoint без деплоя. args и ctx — JSON5. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud - **args** (object) - Optional - JSON5 - **ctx** (object) - Optional - JSON5 ### CLI Command `tgcloud run` ``` -------------------------------- ### Implement message handler in tgcloud/handlers/message.js Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Exports default async function that receives a Message payload. Handles /start command and saves any other text as a note, then replies with the note ID. All DB operations are async and require await. ```javascript import { api, db } from 'sdk'; import { notes } from '../schema.js'; import { eq } from 'sdk/db'; export default async function (message) { const chatId = message.chat.id; const text = (message.text ?? '').trim(); if (text.startsWith('/start')) { await api.sendMessage({ chat_id: chatId, text: 'Пиши заметки — сохраню.' }); return; } // любая другая строка — заметка const [row] = await db.insert(notes).values({ chatId, text }).returning().run(); await api.sendMessage({ chat_id: chatId, text: `Записал (#${row.id}) 📝` }); } ``` -------------------------------- ### Структура проекта: tgcloud/ Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Схема файлов проекта: schema.js, handlers/, endpoints/, lib/, tgcloud.jsonc, docs/tgcloud-sdk.md. Импорты проектных модулей — относительные пути с расширением .js, SDK — по имени. ```text tgcloud/schema.js # схема БД, один файл tgcloud/handlers/ # хендлеры апдейтов, плоско: message.js, callback_query.js, … tgcloud/endpoints/ # серверные функции для Mini App (POST /api/) tgcloud/lib/ # общие модули (можно вложенно) tgcloud.jsonc # конфиг: static-блок мини-аппа docs/tgcloud-sdk.md # полный SDK-референс — читайте его! ``` -------------------------------- ### fetch Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Облако → только снапшот. ```APIDOC ## fetch ### Description Облако → только снапшот. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud ### CLI Command `tgcloud fetch` ``` -------------------------------- ### Установка через curl и запуск через Docker Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/README.ru.md Альтернативные способы установки и запуска: скрипт установки через curl и запуск контейнера Docker. ```bash curl -fsSL https://raw.githubusercontent.com/sdamarketing/tgcloud_mcp/main/install.sh | bash ``` ```bash docker run -i --rm ghcr.io/sdamarketing/tgcloud-mcp ``` -------------------------------- ### Deploy changes with npx tgcloud push Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Deploys schema and handler files. Shows expected output indicating 2 changes deployed and schema out of sync with 1 new table. ```bash npx tgcloud push # Deploying 2 changes... # ✓ tgcloud/schema.js # ✓ tgcloud/handlers/message.js # Schema out of sync — 1 change: # + notes new table ``` -------------------------------- ### webhook_sync Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Перепривязка вебхука. drop_pending: true требует confirm: true. ```APIDOC ## webhook_sync ### Description Перепривязка вебхука. drop_pending: true требует confirm: true. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud - **drop_pending** (boolean) - Optional - Требует confirm: true - **confirm** (boolean) - Optional - Требуется при drop_pending: true ### CLI Command `tgcloud webhook sync` ``` -------------------------------- ### Конфиг opencode Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/installation.ru.mdx Настройка MCP-сервера для opencode в файле ~/.config/opencode/opencode.json. ```json { "mcp": { "tgcloud": { "type": "local", "command": ["npx", "-y", "tgcloud-mcp"], "enabled": true } } } ``` -------------------------------- ### Manage webhook with npx tgcloud webhook Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Shows the current webhook URL and allowed updates, confirming it is in sync with deployed handlers. ```bash npx tgcloud webhook # url: https://cloud.telegram.org/app5888700151/webhook # allowed updates: message # ✓ in sync with your deployed handlers ``` -------------------------------- ### push Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Атомарный деплой. Не собирает фронтенд и не мигрирует БД. force: true требует confirm: true. ```APIDOC ## push ### Description Атомарный деплой. Не собирает фронтенд и не мигрирует БД. force: true требует confirm: true. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud - **force** (boolean) - Optional - Требует confirm: true - **confirm** (boolean) - Optional - Требуется при force: true ### CLI Command `tgcloud push` ``` -------------------------------- ### Mini App static frontend HTML Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Static HTML page using official telegram-web-app.js to call the listNotes endpoint and display results. No build step required. ```html ``` -------------------------------- ### add_module Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Добавление нового модуля: handlers/, endpoints/, lib/. ```APIDOC ## add_module ### Description Добавление нового модуля: handlers/, endpoints/, lib/. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud ### CLI Command `tgcloud add` ``` -------------------------------- ### Конфигурация opencode (opencode.json) Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/SETUP.ru.md Ручная настройка MCP-сервера tgcloud для opencode в файле ~/.config/opencode/opencode.json. ```json { "mcp": { "tgcloud": { "type": "local", "command": ["npx", "-y", "tgcloud-mcp"], "enabled": true } } } ``` -------------------------------- ### Скаффолд и логин: npm create @tgcloud/bot my_diary Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Команды для создания проекта и входа в CLI. Требуется Node.js 18+ и npm. Вставьте CLI access token (ввод скрыт). ```bash npm create @tgcloud/bot my_diary cd my_diary npx tgcloud login # вставьте CLI access token (ввод скрыт) ``` -------------------------------- ### Добавление скилла для Claude Code и opencode Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/SETUP.ru.md Команда для добавления скилла tgcloud_mcp через npx skills. ```bash npx skills add sdamarketing/tgcloud_mcp ``` -------------------------------- ### reset Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Откатить локальные правки модулей; требует confirm: true. ```APIDOC ## reset ### Description Откатить локальные правки модулей; требует confirm: true. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud - **confirm** (boolean) - Required - Требуется для выполнения ### CLI Command `tgcloud reset` ``` -------------------------------- ### Apply migration non-interactively with npx tgcloud migrate --yes Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Applies migrations without interactive prompts. Use --safe to only apply safe changes. Output confirms applied count. ```bash npx tgcloud migrate --yes # или --safe (только безопасные изменения) # ✓ notes # Migration complete. Applied: 1, skipped: 0. ``` -------------------------------- ### Конфиг Claude Code / Cursor Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/installation.ru.mdx Настройка MCP-сервера для Claude Code и Cursor с использованием mcpServers. ```json { "mcpServers": { "tgcloud": { "command": "npx", "args": ["-y", "tgcloud-mcp"] } } } ``` -------------------------------- ### Конфиг VS Code Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/installation.ru.mdx Настройка MCP-сервера для VS Code в файле mcp.json. ```json { "servers": { "tgcloud": { "type": "stdio", "command": "npx", "args": ["-y", "tgcloud-mcp"] } } } ``` -------------------------------- ### Callback query handler for inline buttons Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Handles callback_query events for like and delete actions. Verifies note ownership, deletes notes, edits message text, and answers callback queries. Uses sdk and sdk/db imports. ```javascript import { api, db } from 'sdk'; import { notes } from '../schema.js'; import { eq, and } from 'sdk/db'; export default async function (cb) { const chatId = cb.message?.chat?.id; const [action, idRaw] = (cb.data ?? '').split(':'); const noteId = Number(idRaw); const answer = (text) => api.answerCallbackQuery({ callback_query_id: cb.id, text }).catch(() => {}); // чужие заметки не трогаем const note = await db.select().from(notes) .where(and(eq(notes.id, noteId), eq(notes.chatId, chatId))).get(); if (!note) return answer('Запись не найдена'); if (action === 'del') { await db.delete(notes).where(and(eq(notes.id, noteId), eq(notes.chatId, chatId))).run(); await api.editMessageText({ chat_id: chatId, message_id: cb.message.message_id, text: `🗑 Запись #${noteId} удалена.`, }).catch(() => {}); return answer('Удалено'); } return answer('👍'); } ``` -------------------------------- ### Конфигурация VS Code (mcp.json) Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/SETUP.ru.md Ручная настройка MCP-сервера tgcloud для VS Code в файле mcp.json. ```json { "servers": { "tgcloud": { "type": "stdio", "command": "npx", "args": ["-y", "tgcloud-mcp"] } } } ``` -------------------------------- ### pull Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Облако → снапшот и рабочие файлы. Папку сборки Mini App не пишет. ```APIDOC ## pull ### Description Облако → снапшот и рабочие файлы. Папку сборки Mini App не пишет. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud ### CLI Command `tgcloud pull` ``` -------------------------------- ### webhook_status Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Показывает URL, allowed_updates, очередь, ошибки доставки, синхронен ли вебхук. ```APIDOC ## webhook_status ### Description Показывает URL, allowed_updates, очередь, ошибки доставки, синхронен ли вебхук. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud ### CLI Command `tgcloud webhook` ``` -------------------------------- ### Define notes table schema in tgcloud/schema.js Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Defines the 'notes' table with auto-incrementing id, chat_id, text, and created_at timestamp columns. Uses sdk/db imports and SQL default for unixepoch. Note: no foreign keys are supported; use .deprecated() for removals. ```javascript import { table, integer, text, sql } from 'sdk/db'; export const notes = table('notes', { id: integer('id').primaryKey({ autoIncrement: true }), chatId: integer('chat_id').notNull(), text: text('text').notNull(), created: integer('created_at', { mode: 'timestamp' }).default(sql`(unixepoch())`), }); ``` -------------------------------- ### Установка сервера одной командой (curl) Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/SETUP.ru.md Вариант B: клонирование репозитория в ~/.tgcloud-mcp и запуск мастера установки. ```bash curl -fsSL https://raw.githubusercontent.com/sdamarketing/tgcloud_mcp/main/install.sh | bash ``` -------------------------------- ### Конфигурация Claude Code / Cursor Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/SETUP.ru.md Ручная настройка MCP-сервера tgcloud для Claude Code и Cursor через mcpServers. ```json { "mcpServers": { "tgcloud": { "command": "npx", "args": ["-y", "tgcloud-mcp"] } } } ``` -------------------------------- ### Send message with inline keyboard buttons Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/cookbook-srl-bot.md Sends a message with inline keyboard buttons '👍 Полезно' and '🗑 Удалить' using callback_data like:ID and del:ID. Used in message.js to provide actions on saved notes. ```javascript await api.sendMessage({ chat_id: chatId, text: `Записал (#${row.id}).\n\n${text}`, reply_markup: { inline_keyboard: [[ { text: '👍 Полезно', callback_data: `like:${row.id}` }, { text: '🗑 Удалить', callback_data: `del:${row.id}` }, ]], }, }); ``` -------------------------------- ### status Source: https://github.com/sdamarketing/tgcloud_mcp/blob/main/docs/tools.ru.mdx Показывает локальные изменения vs снапшот (офлайн), включая статику и рассинхрон вебхука. ```APIDOC ## status ### Description Показывает локальные изменения vs снапшот (офлайн), включая статику и рассинхрон вебхука. ### Parameters - **project_dir** (string) - Required - Абсолютный путь к проекту tgcloud ### CLI Command `tgcloud status` ```