409 lines
19 KiB
Python
409 lines
19 KiB
Python
"""Portable Telegram MCP backed by the bundled Teleproto CLI."""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import re
|
||
import subprocess
|
||
import time
|
||
from pathlib import Path
|
||
from urllib.parse import urlparse
|
||
|
||
from mcp.server.fastmcp import FastMCP
|
||
from runtime import cli_command, child_environment, resolve_account
|
||
|
||
mcp = FastMCP("telegram")
|
||
_resolve_account = resolve_account
|
||
_tg_env = child_environment
|
||
|
||
|
||
def _self_id(account: str) -> str:
|
||
result = _run(["user", "profile", "me"], account, 30)
|
||
profiles = result.get("data", {}).get("profiles", [])
|
||
if not result.get("ok") or not profiles or not profiles[0].get("id"):
|
||
raise ValueError("Cannot identify the selected account")
|
||
return str(profiles[0]["id"])
|
||
|
||
|
||
def _invoke(args: list[str], account: str, timeout: int = 60) -> dict:
|
||
"""One CLI invocation; never replay a potentially submitted operation."""
|
||
try:
|
||
env = _tg_env(account)
|
||
except ValueError as e:
|
||
return {"ok": False, "error": str(e)}
|
||
|
||
tg_cmd = cli_command(account) + args
|
||
try:
|
||
result = subprocess.run(
|
||
tg_cmd,
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=timeout,
|
||
env=env,
|
||
)
|
||
except FileNotFoundError:
|
||
return {
|
||
"ok": False,
|
||
"error": "Bundled CLI not available; run python3 scripts/manage.py setup",
|
||
}
|
||
except subprocess.TimeoutExpired:
|
||
return {"ok": False, "code": "TIMEOUT", "error": f"timeout {timeout}s; operation outcome may be unknown; verify before retrying"}
|
||
|
||
stdout = (result.stdout or "").strip()
|
||
if not stdout:
|
||
return {"ok": False, "code": "CLI_NO_OUTPUT", "error": "tg returned no structured output"}
|
||
|
||
json_lines = [ln for ln in stdout.splitlines() if ln.strip().startswith("{")]
|
||
if not json_lines:
|
||
return {"ok": False, "code": "CLI_INVALID_OUTPUT", "error": "tg returned no JSON envelope"}
|
||
try:
|
||
envelope = json.loads(json_lines[-1])
|
||
if not isinstance(envelope, dict) or not isinstance(envelope.get("ok"), bool):
|
||
raise ValueError("invalid envelope")
|
||
if result.returncode:
|
||
# Upstream can return ok:true plus partial data and exit status 1.
|
||
envelope["ok"] = False
|
||
data = envelope.get("data")
|
||
partial = isinstance(data, dict) and data.get("partial")
|
||
envelope.setdefault("code", "PARTIAL_FAILURE" if partial else "CLI_FAILED")
|
||
envelope.setdefault("error", "Some operations failed; inspect data.errors" if envelope["code"] == "PARTIAL_FAILURE" else "CLI operation failed")
|
||
return envelope
|
||
except (ValueError, TypeError):
|
||
return {"ok": False, "code": "CLI_INVALID_OUTPUT", "error": "Invalid JSON envelope"}
|
||
|
||
|
||
def _ensure_daemon(account: str) -> dict:
|
||
status = _invoke(["daemon", "status"], account, 15)
|
||
if not status.get("ok"):
|
||
return status
|
||
if not status.get("data", {}).get("running"):
|
||
started = _invoke(["daemon", "start", "--idle-timeout", "300"], account, 25)
|
||
# Another MCP process may have started this profile concurrently.
|
||
if not started.get("ok") and started.get("code") != "DAEMON_ALREADY_RUNNING":
|
||
return started
|
||
status = _invoke(["daemon", "status"], account, 15)
|
||
data = status.get("data", {})
|
||
if not status.get("ok") or not data.get("connected") or "execute" not in data.get("capabilities", []):
|
||
return {"ok": False, "code": "DAEMON_NOT_READY", "error": "Daemon is not connected or lacks execute; inspect daemon status"}
|
||
return status
|
||
|
||
|
||
def _run(args: list[str], account: str = "main", timeout: int = 60) -> dict:
|
||
result = _invoke(["--daemon", *args], account, timeout)
|
||
# This code is emitted before opening an API socket: nothing was submitted.
|
||
# Never retry timeouts, disconnected sockets, or any Telegram/API error.
|
||
if result.get("code") != "DAEMON_NOT_RUNNING":
|
||
return result
|
||
ready = _ensure_daemon(account)
|
||
if not ready.get("ok"):
|
||
return ready
|
||
return _invoke(["--daemon", *args], account, timeout)
|
||
|
||
|
||
def _read(args: list[str], account: str, fields: str | None, output_format: str) -> dict:
|
||
if output_format not in {"json", "toon"}:
|
||
return {"ok": False, "code": "INVALID_INPUT", "error": "output_format must be json or toon"}
|
||
if fields:
|
||
if not re.fullmatch(r"[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*(?:,[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*)*", fields):
|
||
return {"ok": False, "code": "INVALID_INPUT", "error": "fields must be comma-separated field paths"}
|
||
args = ["--fields", fields, *args]
|
||
result = _run(args, account)
|
||
if output_format == "json":
|
||
return result
|
||
# Format locally after parsing JSON so errors and exit status stay structured.
|
||
try:
|
||
formatted = subprocess.run(
|
||
[cli_command(account)[0], str(Path(__file__).with_name("format_toon.mjs")), cli_command(account)[1]],
|
||
input=json.dumps(result, ensure_ascii=False), capture_output=True, text=True, timeout=10,
|
||
)
|
||
if formatted.returncode:
|
||
raise ValueError("TOON conversion failed")
|
||
return {"ok": result["ok"], "format": "toon", "text": formatted.stdout.strip(),
|
||
**({"code": result.get("code"), "error": result.get("error")} if not result["ok"] else {})}
|
||
except (OSError, ValueError, subprocess.TimeoutExpired):
|
||
return {"ok": False, "code": "FORMAT_ERROR", "error": "TOON conversion failed", "result": result}
|
||
|
||
|
||
@mcp.tool()
|
||
def telegram_send_message(chat: str, text: str, account: str = "main") -> dict:
|
||
"""Отправить текстовое сообщение в Telegram.
|
||
|
||
Args:
|
||
chat: username (без @) или user_id или chat_id. Пример: "example_chat".
|
||
text: текст сообщения (до 4096 символов).
|
||
account: "main" (default) или "reserve".
|
||
Для main — только ad-hoc, не массовая рассылка (риск бана).
|
||
"""
|
||
return _run(["message", "send", "--", chat, text], account=account)
|
||
|
||
|
||
@mcp.tool()
|
||
def telegram_send_html(chat: str, html: str, account: str = "main") -> dict:
|
||
"""Отправить HTML-оформленное сообщение в Telegram.
|
||
|
||
Единственный форматированный режим этого MCP — HTML; Markdown не используется.
|
||
Поддерживаемые HTML-теги: b/strong, i/em, u, s/del, spoiler,
|
||
a, code, pre/code class="language-…", blockquote и blockquote expandable.
|
||
Символы <, > и & в данных, не являющихся тегами, необходимо экранировать.
|
||
"""
|
||
if len(html) > 4096:
|
||
return {"ok": False, "error": "Message too long (max 4096 chars before parsing)"}
|
||
return _bridge("html", {"chat": chat, "text": html}, account)
|
||
|
||
|
||
@mcp.tool()
|
||
def telegram_schedule_message(
|
||
chat: str, text: str, when_iso: str, account: str = "main"
|
||
) -> dict:
|
||
"""Запланировать отправку текстового сообщения на конкретное время (server-side).
|
||
|
||
Сообщение хранится у Telegram-сервера и доставляется в указанный момент —
|
||
мак может быть выключен/спать, доставка от этого не зависит.
|
||
|
||
Args:
|
||
chat: username (без @) / user_id / chat_id.
|
||
text: текст сообщения (до 4096 символов).
|
||
when_iso: момент отправки в ISO 8601, желательно с таймзоной.
|
||
Пример: "2026-05-06T09:00:00+03:00" (9:00 МСК).
|
||
Минимум 10 секунд в будущем.
|
||
account: "main" (default) или "reserve".
|
||
|
||
Возвращает {"ok": True, "data": {"id": <schedule_id>, "scheduled_for": <ISO>, ...}}
|
||
или {"ok": False, "error": "..."}.
|
||
|
||
Операция выполняется через CLI bridge на соединении демона выбранного
|
||
профиля. После таймаута не повторять без проверки очереди Telegram.
|
||
"""
|
||
if len(text) > 4096:
|
||
return {"ok": False, "error": "Message too long (max 4096 chars)"}
|
||
|
||
return _bridge("schedule", {"chat": chat, "text": text, "when": when_iso}, account)
|
||
|
||
|
||
@mcp.tool()
|
||
def telegram_send_file(
|
||
chat: str, file_path: str, caption: str | None = None, account: str = "main"
|
||
) -> dict:
|
||
"""Отправить файл (документ или фото) в Telegram.
|
||
|
||
Args:
|
||
chat: username (без @) или user_id / chat_id.
|
||
file_path: абсолютный путь к файлу. Форматы — любые; tg-cli сам определит тип.
|
||
caption: подпись к файлу (опционально).
|
||
account: "main" (default) или "reserve".
|
||
"""
|
||
if not Path(file_path).exists():
|
||
return {"ok": False, "error": f"File not found: {file_path}"}
|
||
|
||
args = ["media", "send"]
|
||
if caption:
|
||
args += ["--caption=" + caption]
|
||
args += ["--", chat, file_path]
|
||
return _run(args, account=account, timeout=120)
|
||
|
||
|
||
@mcp.tool()
|
||
def telegram_read_history(chat: str, limit: int = 5, account: str = "main",
|
||
fields: str | None = None, output_format: str = "json") -> dict:
|
||
"""Прочитать последние сообщения из чата.
|
||
|
||
Args:
|
||
chat: username или user_id.
|
||
limit: сколько сообщений вернуть (1–100).
|
||
account: "main" (default) или "reserve".
|
||
fields: поля через запятую, например id,text,date,senderId. По умолчанию все.
|
||
output_format: json (структура) или toon (компактный текст).
|
||
"""
|
||
limit = max(1, min(int(limit), 100))
|
||
return _read(["message", "history", "--limit", str(limit), "--", chat], account, fields, output_format)
|
||
|
||
|
||
def _message_target(chat: str, message_ids: str | None) -> tuple[str, str]:
|
||
if chat.startswith(("https://", "http://")):
|
||
link = urlparse(chat)
|
||
if link.hostname not in {"t.me", "www.t.me", "telegram.me"} or message_ids:
|
||
raise ValueError("Use a Telegram post link alone, or chat plus message_ids")
|
||
parts = link.path.strip("/").split("/")
|
||
if parts[0] == "s":
|
||
parts = parts[1:]
|
||
if len(parts) in {3, 4} and parts[0] == "c" and parts[1].isdigit():
|
||
chat, message_ids = "-100" + parts[1], parts[-1]
|
||
if len(parts) == 4 and not parts[2].isdigit():
|
||
raise ValueError("Invalid topic ID")
|
||
elif len(parts) in {2, 3}:
|
||
chat, message_ids = parts[0], parts[-1]
|
||
if len(parts) == 3 and not parts[1].isdigit():
|
||
raise ValueError("Invalid topic ID")
|
||
else:
|
||
raise ValueError("Expected a Telegram post link")
|
||
if not re.fullmatch(r"(?:@?[A-Za-z][A-Za-z0-9_]*|-?\d+)", chat):
|
||
raise ValueError("Invalid chat")
|
||
ids = (message_ids or "").split(",")
|
||
if not 1 <= len(ids) <= 100 or any(not x.isdigit() or not 0 < int(x) <= 2147483647 for x in ids):
|
||
raise ValueError("message_ids must contain 1–100 positive message IDs separated by commas")
|
||
return chat, ",".join(ids)
|
||
|
||
|
||
@mcp.tool()
|
||
def telegram_get_messages(chat: str, message_ids: str | None = None, account: str = "main",
|
||
fields: str | None = None, output_format: str = "json") -> dict:
|
||
"""Прочитать конкретные сообщения без загрузки истории.
|
||
|
||
chat: username/ID или ссылка https://t.me/channel/475 (также /c/ и темы).
|
||
message_ids: ID через запятую; при ссылке не указывать.
|
||
account: выбранный профиль main или reserve.
|
||
fields: поля через запятую, например id,text,date. output_format: json или toon.
|
||
"""
|
||
try:
|
||
chat, ids = _message_target(chat, message_ids)
|
||
except ValueError as error:
|
||
return {"ok": False, "code": "INVALID_INPUT", "error": str(error)}
|
||
return _read(["message", "get", chat, ids], account, fields, output_format)
|
||
|
||
|
||
@mcp.tool()
|
||
def telegram_search_messages(query: str, chat: str | None = None, limit: int = 10,
|
||
account: str = "main", fields: str | None = None,
|
||
output_format: str = "json") -> dict:
|
||
"""Поиск сообщений в доступных диалогах или одном chat; json/toon и выбор fields."""
|
||
args = ["message", "search", "--query", query, "--limit", str(max(1, min(int(limit), 100)))]
|
||
if chat:
|
||
args += ["--chat", chat]
|
||
return _read(args, account, fields, output_format)
|
||
|
||
|
||
def _bridge(operation: str, payload: dict, account: str) -> dict:
|
||
try:
|
||
key = _resolve_account(account)
|
||
except ValueError as error:
|
||
return {"ok": False, "code": "INVALID_INPUT", "error": str(error)}
|
||
return _run(["bridge", "call", operation, json.dumps({**payload, "account": key}, ensure_ascii=False)], key, 120)
|
||
|
||
|
||
def _stories_call(payload: dict, account: str) -> dict:
|
||
return _bridge("stories", payload, account)
|
||
|
||
|
||
def _story_chat(chat: str) -> str:
|
||
chat = chat.strip()
|
||
if chat.startswith("https://t.me/"):
|
||
chat = chat.removeprefix("https://t.me/").strip("/")
|
||
if not re.fullmatch(r"@?[A-Za-z][A-Za-z0-9_]{3,31}", chat):
|
||
raise ValueError("Use a Telegram username or https://t.me/username")
|
||
return chat.lstrip("@")
|
||
|
||
|
||
@mcp.tool()
|
||
def telegram_list_stories(chat: str, kind: str = "pinned", limit: int = 20,
|
||
offset_id: int = 0, account: str = "main") -> dict:
|
||
"""Список сохранённых в профиле (pinned) или действующих (active) историй.
|
||
|
||
chat: username или ссылка на канал/пользователя; limit 1–100.
|
||
Для pinned offset_id — ID последней истории предыдущей страницы.
|
||
Для active offset_id не поддерживается. Разовое чтение: account="main".
|
||
Содержимое картинок доступно отдельно через telegram_download_story_media.
|
||
"""
|
||
try:
|
||
chat = _story_chat(chat)
|
||
if kind not in {"pinned", "active"} or not 1 <= limit <= 100 or not 0 <= offset_id <= 2147483647 or (kind == "active" and offset_id):
|
||
raise ValueError("Invalid kind, limit or offset_id")
|
||
except (ValueError, TypeError) as error:
|
||
return {"ok": False, "code": "INVALID_INPUT", "error": str(error)}
|
||
return _stories_call({"action": "list", "chat": chat, "kind": kind, "limit": limit, "offset_id": offset_id}, account)
|
||
|
||
|
||
@mcp.tool()
|
||
def telegram_get_story(chat: str, story_id: int, account: str = "main") -> dict:
|
||
"""Прочитать метаданные и подпись одной истории по username и ID."""
|
||
try:
|
||
chat = _story_chat(chat)
|
||
if not 0 < story_id <= 2147483647:
|
||
raise ValueError("story_id must be positive")
|
||
except (ValueError, TypeError) as error:
|
||
return {"ok": False, "code": "INVALID_INPUT", "error": str(error)}
|
||
return _stories_call({"action": "get", "chat": chat, "story_id": story_id}, account)
|
||
|
||
|
||
@mcp.tool()
|
||
def telegram_download_story_media(chat: str, story_id: int, account: str = "main") -> dict:
|
||
"""Скачать фото или видео истории во временную локальную папку (не более 30 МБ).
|
||
|
||
Возвращает абсолютный путь для просмотра или распознавания; OCR не выполняется.
|
||
Нет автоматического распознавания, отметки прочтения или инкремента просмотров.
|
||
"""
|
||
try:
|
||
chat = _story_chat(chat)
|
||
if not 0 < story_id <= 2147483647:
|
||
raise ValueError("story_id must be positive")
|
||
except (ValueError, TypeError) as error:
|
||
return {"ok": False, "code": "INVALID_INPUT", "error": str(error)}
|
||
return _stories_call({"action": "download", "chat": chat, "story_id": story_id}, account)
|
||
|
||
|
||
@mcp.tool()
|
||
def telegram_wait_for_reply(
|
||
chat: str,
|
||
after_id: int,
|
||
timeout: int = 60,
|
||
poll_interval: int = 5,
|
||
account: str = "main",
|
||
) -> dict:
|
||
"""Ждать ответ от бота/собеседника в чате после сообщения с указанным id.
|
||
|
||
Args:
|
||
chat: username или user_id.
|
||
after_id: id сообщения, после которого ждём ответа.
|
||
timeout: максимальное время ожидания в секундах.
|
||
poll_interval: интервал опроса истории (в секундах).
|
||
account: "main" (default) или "reserve".
|
||
"""
|
||
try:
|
||
self_id = _self_id(account)
|
||
except ValueError as error:
|
||
return {"ok": False, "code": "AUTH_CHECK_FAILED", "error": str(error)}
|
||
deadline = time.time() + max(1, int(timeout))
|
||
while time.time() < deadline:
|
||
history = _run(
|
||
["message", "history", "--limit", "3", "--json", "--", chat],
|
||
account=account,
|
||
timeout=15,
|
||
)
|
||
if history.get("ok") and "data" in history:
|
||
messages = history["data"]
|
||
if isinstance(messages, dict):
|
||
messages = messages.get("messages", [])
|
||
for msg in messages:
|
||
msg_id = int(msg.get("id", 0) or 0)
|
||
sender = str(msg.get("senderId", "") or "")
|
||
if msg_id > int(after_id) and sender != self_id:
|
||
return {"ok": True, "data": msg}
|
||
time.sleep(max(1, int(poll_interval)))
|
||
return {"ok": False, "error": "timeout, no reply received"}
|
||
|
||
|
||
@mcp.tool()
|
||
def telegram_auth_status(account: str = "main") -> dict:
|
||
"""Проверить авторизацию выбранного аккаунта в tg-cli.
|
||
|
||
Args:
|
||
account: "main" (default) или "reserve".
|
||
"""
|
||
# auth status opens a direct session and cannot run beside the daemon.
|
||
result = _run(["user", "profile", "me"], account=account, timeout=30)
|
||
if not result.get("ok"):
|
||
return result
|
||
profiles = result.get("data", {}).get("profiles", [])
|
||
if not profiles:
|
||
return {"ok": False, "code": "AUTH_CHECK_FAILED", "error": "No self profile returned"}
|
||
user = profiles[0]
|
||
return {"ok": True, "data": {"authorized": True, "user": {
|
||
key: user.get(key) for key in ("id", "phone", "username", "firstName")
|
||
}}}
|
||
|
||
|
||
from extended import register_tools
|
||
register_tools(mcp, _run, _read)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
mcp.run()
|