335 lines
19 KiB
Python
335 lines
19 KiB
Python
"""Typed additive MCP surface. Transport/retry policy stays owned by server.py."""
|
|
from __future__ import annotations
|
|
import json
|
|
from typing import Literal
|
|
from pathlib import Path
|
|
from pydantic import BaseModel, Field, ConfigDict
|
|
from mcp.types import ToolAnnotations
|
|
|
|
Account = Literal["main", "reserve"]
|
|
class FolderRules(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
contacts: bool | None = None
|
|
nonContacts: bool | None = None
|
|
groups: bool | None = None
|
|
broadcasts: bool | None = None
|
|
bots: bool | None = None
|
|
excludeMuted: bool | None = None
|
|
excludeRead: bool | None = None
|
|
excludeArchived: bool | None = None
|
|
|
|
class FolderPatch(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
title: str | None = Field(default=None, min_length=1, max_length=12)
|
|
emoticon: str | None = None
|
|
color: int | None = Field(default=None, ge=0, le=6)
|
|
include: list[str] | None = Field(default=None, max_length=200)
|
|
exclude: list[str] | None = Field(default=None, max_length=200)
|
|
pinned: list[str] | None = Field(default=None, max_length=200)
|
|
rules: FolderRules | None = None
|
|
|
|
|
|
def register_tools(mcp, run, read):
|
|
def tool(write=False):
|
|
return mcp.tool(annotations=ToolAnnotations(readOnlyHint=not write, destructiveHint=write, idempotentHint=False, openWorldHint=True))
|
|
|
|
def error(message):
|
|
return {"ok": False, "code": "INVALID_INPUT", "error": message}
|
|
|
|
def organize(action, account, **payload):
|
|
if account not in ("main", "reserve"):
|
|
return error("account must be main or reserve")
|
|
payload = {k: v for k, v in payload.items() if v is not None}
|
|
return run(["bridge", "call", "organize", json.dumps({"action": action, "account": account, **payload}, ensure_ascii=False)], account)
|
|
|
|
def cli(group, action, account, positional=(), options=None, dry_run=False):
|
|
if account not in ("main", "reserve"):
|
|
return error("account must be main or reserve")
|
|
args = [group, action]
|
|
for key, value in (options or {}).items():
|
|
if value is None or value is False:
|
|
continue
|
|
if key in ("limit",) and (type(value) is not int or not 1 <= value <= 100):
|
|
return error("limit must be 1..100")
|
|
if key == "offset" and (type(value) is not int or not 0 <= value <= 5000):
|
|
return error("offset must be 0..5000")
|
|
if value is True:
|
|
args.append("--" + key)
|
|
else:
|
|
for item in value if isinstance(value, list) else [value]:
|
|
args.append("--" + key + "=" + str(item))
|
|
if any(not isinstance(s, str) or "\0" in s for s in positional):
|
|
return error("Arguments must be strings without NUL")
|
|
if positional:
|
|
args.extend(["--", *positional])
|
|
if dry_run:
|
|
return {"ok": True, "data": {"dry_run": True, "account": account, "command": args}}
|
|
return run(args, account)
|
|
|
|
def message_ids(values):
|
|
if not values or len(values) > 100 or any(type(v) is not int or v < 1 or v > 2147483647 for v in values):
|
|
raise ValueError("message_ids must contain 1..100 positive 32-bit IDs")
|
|
return ",".join(map(str, values))
|
|
|
|
@tool(write=False)
|
|
def telegram_list_folders(account: Account) -> dict:
|
|
"""Read folder order, rules, included/excluded/pinned peer IDs and revision. Does not read messages."""
|
|
return organize("folders", account)
|
|
|
|
@tool(write=False)
|
|
def telegram_list_dialogs(account: Account, limit: int = 100, offset: int = 0, cursor: str | None = None, refresh: bool = False) -> dict:
|
|
"""Read chat metadata without message bodies or read receipts. Cursor snapshot; pass next_offset and cursor. Wait retry_after_seconds on FloodWait. refresh starts a new snapshot. muted=null inherits defaults."""
|
|
return organize("dialogs", account, limit=limit, offset=offset, cursor=cursor, refresh=refresh)
|
|
|
|
@tool(write=True)
|
|
def telegram_update_folder(account: Account, folder_id: int, patch: FolderPatch, create: bool = False, revision: str | None = None, dry_run: bool = True) -> dict:
|
|
"""Create or patch an ordinary folder. Omitted fields are preserved; supplied lists replace those lists. Preview first; apply requires preview revision. Shared folders are refused."""
|
|
return organize("folder-put", account, id=folder_id, patch=patch.model_dump(exclude_none=True), create=create, revision=revision, dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_delete_folder(account: Account, folder_id: int, revision: str | None = None, dry_run: bool = True) -> dict:
|
|
"""Delete an ordinary folder only, not its chats. Preview first; apply requires revision."""
|
|
return organize("folder-delete", account, id=folder_id, revision=revision, dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_reorder_folders(account: Account, order: list[int], revision: str | None = None, dry_run: bool = True) -> dict:
|
|
"""Reorder folders; include every current ID exactly once, including All Chats when returned. Apply requires revision."""
|
|
return organize("folder-order", account, order=order, revision=revision, dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_set_archived(account: Account, chat: str, archived: bool, dry_run: bool = True) -> dict:
|
|
"""Archive or unarchive one chat."""
|
|
return organize('archive', account, chat=chat, archived=archived, dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_set_chat_pinned(account: Account, chat: str, pinned: bool, dry_run: bool = True) -> dict:
|
|
"""Pin or unpin a dialog in its main/archive list. Folder pins use update_folder."""
|
|
return organize('dialog-pin', account, chat=chat, pinned=pinned, dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_set_unread(account: Account, chat: str, unread: bool, dry_run: bool = True) -> dict:
|
|
"""Set or clear the manual unread mark; does not reset message read receipts."""
|
|
return organize('unread', account, chat=chat, unread=unread, dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_mark_read(account: Account, chat: str, max_id: int, dry_run: bool = True) -> dict:
|
|
"""Mark messages read up to max_id; this changes read receipts."""
|
|
return organize('read', account, chat=chat, max_id=max_id, dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_set_mute(account: Account, chat: str, mute_until: int, dry_run: bool = True) -> dict:
|
|
"""Set mute expiry Unix seconds: 0 unmute, 2147483647 indefinitely. Preserves other notification fields."""
|
|
return organize('notify-set', account, chat=chat, mute_until=mute_until, dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_save_draft(account: Account, chat: str, text: str, dry_run: bool = True) -> dict:
|
|
"""Save a plain-text draft; empty text clears it. Does not send a message."""
|
|
return organize('draft-save', account, chat=chat, text=text, dry_run=dry_run)
|
|
|
|
@tool(write=False)
|
|
def telegram_get_notification_settings(account: Account, chat: str) -> dict:
|
|
"""Read per-chat notification overrides. inherited=true means account defaults apply."""
|
|
return organize("notify-get", account, chat=chat)
|
|
|
|
@tool(write=False)
|
|
def telegram_list_scheduled_messages(account: Account, chat: str) -> dict:
|
|
"""Read the server-side scheduled message queue."""
|
|
return organize("scheduled-list", account, chat=chat)
|
|
|
|
@tool(write=True)
|
|
def telegram_cancel_scheduled_messages(account: Account, chat: str, ids: list[int], dry_run: bool = True) -> dict:
|
|
"""Cancel selected scheduled messages."""
|
|
return organize('scheduled-delete', account, chat=chat, ids=ids, dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_send_scheduled_now(account: Account, chat: str, ids: list[int], dry_run: bool = True) -> dict:
|
|
"""Send selected scheduled messages now. Never retry automatically after timeout."""
|
|
return organize('scheduled-send', account, chat=chat, ids=ids, dry_run=dry_run)
|
|
|
|
@tool(write=False)
|
|
def telegram_get_chat_info(account: Account, chat: str) -> dict:
|
|
"""Read chat details."""
|
|
return cli('chat', 'info', account, [chat])
|
|
|
|
@tool(write=False)
|
|
def telegram_resolve_peer(account: Account, peer: str) -> dict:
|
|
"""Resolve username or marked ID."""
|
|
return cli('chat', 'resolve', account, [peer])
|
|
|
|
@tool(write=False)
|
|
def telegram_get_invite_info(account: Account, link: str) -> dict:
|
|
"""Inspect invite without joining."""
|
|
return cli('chat', 'invite-info', account, [link])
|
|
|
|
@tool(write=False)
|
|
def telegram_get_user_profile(account: Account, user: str) -> dict:
|
|
"""Read accessible user profile."""
|
|
return cli('user', 'profile', account, [user])
|
|
|
|
@tool(write=False)
|
|
def telegram_list_members(account: Account, chat: str, limit: int = 50, offset: int = 0) -> dict:
|
|
"""List accessible members; Telegram may restrict completeness."""
|
|
return cli('chat', 'members', account, [chat], {"limit": limit, "offset": offset})
|
|
|
|
@tool(write=False)
|
|
def telegram_list_topics(account: Account, chat: str, limit: int = 50, offset: int = 0) -> dict:
|
|
"""List forum topics."""
|
|
return cli('chat', 'topics', account, [chat], {"limit": limit, "offset": offset})
|
|
|
|
@tool(write=False)
|
|
def telegram_list_pinned_messages(account: Account, chat: str, limit: int = 50, offset: int = 0) -> dict:
|
|
"""Read pinned messages."""
|
|
return cli('message', 'pinned', account, [chat], {"limit": limit, "offset": offset})
|
|
|
|
@tool(write=False)
|
|
def telegram_list_contacts(account: Account, limit: int = 50, offset: int = 0) -> dict:
|
|
"""Read contacts."""
|
|
return cli('contact', 'list', account, [], {"limit": limit, "offset": offset})
|
|
|
|
@tool(write=False)
|
|
def telegram_list_blocked_users(account: Account, limit: int = 50, offset: int = 0) -> dict:
|
|
"""Read blocked users."""
|
|
return cli('user', 'blocked', account, [], {"limit": limit, "offset": offset})
|
|
|
|
@tool(write=False)
|
|
def telegram_search_public_chats(account: Account, query: str, limit: int = 20) -> dict:
|
|
"""Search by name; does not join or contact anyone."""
|
|
return cli('chat', 'search', account, [query], {"limit": limit})
|
|
|
|
@tool(write=False)
|
|
def telegram_search_contacts(account: Account, query: str, limit: int = 20) -> dict:
|
|
"""Search by name; does not join or contact anyone."""
|
|
return cli('contact', 'search', account, [query], {"limit": limit})
|
|
|
|
@tool(write=False)
|
|
def telegram_get_history_page(account: Account, chat: str, limit: int = 50, offset: int = 0, since: str | None = None, until: str | None = None, topic_id: int | None = None) -> dict:
|
|
"""Read history with date bounds and topic selection; no read receipts."""
|
|
return cli("message", "history", account, [chat], {"limit": limit, "offset": offset, "since": since, "until": until, "topic": topic_id})
|
|
|
|
@tool(write=False)
|
|
def telegram_search_media(account: Account, chat: str, media_type: Literal["photos", "videos", "documents", "urls", "voice", "music", "gifs", "round", "photo_video", "round_voice", "chat_photos", "phone_calls", "mentions", "geo", "contacts", "pinned"], query: str = "", limit: int = 50, offset: int = 0, topic_id: int | None = None) -> dict:
|
|
"""Search messages by media type and optional text."""
|
|
return cli("message", "search", account, options={"chat": chat, "filter": media_type, "query": query, "limit": limit, "offset": offset, "topic": topic_id})
|
|
|
|
@tool(write=False)
|
|
def telegram_get_replies(account: Account, chat: str, post_id: int, limit: int = 50, offset: int = 0) -> dict:
|
|
"""Read replies/comments on a post."""
|
|
if post_id < 1: return error("post_id must be positive")
|
|
return cli("message", "replies", account, [chat, str(post_id)], {"limit": limit, "offset": offset})
|
|
|
|
@tool(write=True)
|
|
def telegram_join_chat(account: Account, target: str, dry_run: bool = True) -> dict:
|
|
"""Join a group/channel. May send a join request."""
|
|
return cli('chat', 'join', account, [target], dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_leave_chat(account: Account, chat: str, dry_run: bool = True) -> dict:
|
|
"""Leave a group/channel."""
|
|
return cli('chat', 'leave', account, [chat], dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_block_user(account: Account, user: str, dry_run: bool = True) -> dict:
|
|
"""Block a user."""
|
|
return cli('user', 'block', account, [user], dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_unblock_user(account: Account, user: str, dry_run: bool = True) -> dict:
|
|
"""Unblock a user."""
|
|
return cli('user', 'unblock', account, [user], dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_delete_contact(account: Account, user: str, dry_run: bool = True) -> dict:
|
|
"""Delete a contact from your address book."""
|
|
return cli('contact', 'delete', account, [user], dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_add_contact(account: Account, user: str, first_name: str | None = None, last_name: str | None = None, dry_run: bool = True) -> dict:
|
|
"""Add a contact; first_name is required for phone-number input."""
|
|
return cli("contact", "add", account, [user], {"first-name": first_name, "last-name": last_name}, dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_send_reply(account: Account, chat: str, text: str, reply_to: int | None = None, topic_id: int | None = None, comment_to: int | None = None, dry_run: bool = True) -> dict:
|
|
"""Send plain text, reply, forum message or channel comment. Do not retry a timed-out send."""
|
|
if not text or len(text) > 4096 or text == "-": return error("text must be 1..4096 characters, not a stdin marker")
|
|
if comment_to is not None and (reply_to is not None or topic_id is not None): return error("comment_to cannot be combined with reply_to/topic_id")
|
|
return cli("message", "send", account, [chat, text], {"reply-to": reply_to, "topic": topic_id, "comment-to": comment_to}, dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_edit_message(account: Account, chat: str, message_id: int, text: str, dry_run: bool = True) -> dict:
|
|
"""Edit a sent message."""
|
|
if message_id < 1 or not text or len(text) > 4096 or text == "-": return error("Invalid message_id or text")
|
|
return cli("message", "edit", account, [chat, str(message_id), text], dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_forward_messages(account: Account, chat: str, ids: list[int], destination: str, dry_run: bool = True) -> dict:
|
|
"""Forward selected messages to destination."""
|
|
try: joined = message_ids(ids)
|
|
except ValueError as exc: return error(str(exc))
|
|
return cli("message", "forward", account, [chat, joined, destination], dry_run=dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_delete_messages(account: Account, chat: str, ids: list[int], for_everyone: bool, dry_run: bool = True) -> dict:
|
|
"""Delete selected messages. Explicit for_everyone controls revocation; Telegram chat permissions still apply."""
|
|
try: joined = message_ids(ids)
|
|
except ValueError as exc: return error(str(exc))
|
|
return cli("message", "delete", account, [chat, joined], {"revoke": for_everyone, "for-me": not for_everyone}, dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_react(account: Account, chat: str, message_id: int, emoji: str, remove: bool = False, dry_run: bool = True) -> dict:
|
|
"""Add or remove a reaction."""
|
|
if message_id < 1: return error("message_id must be positive")
|
|
return cli("message", "react", account, [chat, str(message_id), emoji], {"remove": remove}, dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_pin_message(account: Account, chat: str, message_id: int, notify: bool = False, dry_run: bool = True) -> dict:
|
|
"""Pin a message, silent by default."""
|
|
if message_id < 1: return error("message_id must be positive")
|
|
return cli("message", "pin", account, [chat, str(message_id)], {"notify": notify}, dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_unpin_message(account: Account, chat: str, message_id: int, dry_run: bool = True) -> dict:
|
|
"""Unpin a message."""
|
|
if message_id < 1: return error("message_id must be positive")
|
|
return cli("message", "unpin", account, [chat, str(message_id)], dry_run=dry_run)
|
|
|
|
@tool(write=False)
|
|
def telegram_download_media(account: Account, chat: str, ids: list[int], output_path: str) -> dict:
|
|
"""Download message attachments to an absolute local path. Existing files are not overwritten."""
|
|
try: joined = message_ids(ids)
|
|
except ValueError as exc: return error(str(exc))
|
|
if not Path(output_path).is_absolute(): return error("output_path must be absolute")
|
|
return cli("media", "download", account, [chat, joined], {"output": output_path})
|
|
|
|
@tool(write=False)
|
|
def telegram_download_profile_photo(account: Account, user: str, output_path: str) -> dict:
|
|
"""Download an accessible current profile photo; no overwrite."""
|
|
if not Path(output_path).is_absolute(): return error("output_path must be absolute")
|
|
return cli("user", "download-photo", account, [user], {"output": output_path})
|
|
|
|
@tool(write=True)
|
|
def telegram_create_chat(account: Account, title: str, chat_type: Literal["supergroup", "channel"] = "supergroup", description: str | None = None, dry_run: bool = True) -> dict:
|
|
"""Create a supergroup or channel."""
|
|
return cli("chat", "create", account, [title], {"type": chat_type, "description": description}, dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_edit_chat(account: Account, chat: str, title: str | None = None, description: str | None = None, dry_run: bool = True) -> dict:
|
|
"""Change chat title/description with available administrator rights."""
|
|
if title is None and description is None: return error("Provide title or description")
|
|
return cli("chat", "edit", account, [chat], {"title": title, "description": description}, dry_run)
|
|
|
|
@tool(write=True)
|
|
def telegram_send_poll(account: Account, chat: str, question: str, options: list[str], multiple: bool = False, public: bool = False, dry_run: bool = True) -> dict:
|
|
"""Send an ordinary poll. Anonymous by default."""
|
|
if not 2 <= len(options) <= 10 or not question or len(question) > 300: return error("Expected question up to 300 characters and 2..10 options")
|
|
return cli("message", "poll", account, [chat], {"question": question, "option": options, "multiple": multiple, "public": public}, dry_run)
|
|
|
|
|
|
@tool()
|
|
def telegram_audit_folders(account: Account, scan_limit: int = 1000, cursor: str | None = None, refresh: bool = False) -> dict:
|
|
"""Read-only folder audit: computed membership, overlap, uncategorized chats, bounded counts. complete=false means partial scan. No message bodies/read receipts."""
|
|
return organize("audit", account, scan_limit=scan_limit, cursor=cursor, refresh=refresh)
|
|
|
|
@tool()
|
|
def telegram_get_folder_chats(account: Account, folder_id: int, scan_limit: int = 1000, cursor: str | None = None, refresh: bool = False) -> dict:
|
|
"""Compute folder membership using peers, rules and inherited mute settings. Inspect complete and note before interpreting counts."""
|
|
return organize("audit", account, folder_id=folder_id, scan_limit=scan_limit, cursor=cursor, refresh=refresh)
|