### Development Environment Setup Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/CONTRIBUTING.md Standard commands to clone the repository and install dependencies including development tools. ```bash git clone https://github.com/alexeyleshchenko/fast-mcp-telegram.git cd fast-mcp-telegram pip install -e .[dev] # Install all dependencies including dev tools ``` -------------------------------- ### Quick Setup Commands Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/CONTRIBUTING.md Initial steps to clone the repository, install development dependencies, configure environment variables, and run tests. ```bash # 1. Fork and clone the repository git clone https://github.com/your-username/fast-mcp-telegram.git cd fast-mcp-telegram # 2. Set up development environment pip install -e .[dev] # 3. Configure environment echo "API_ID=your_api_id" > .env echo "API_HASH=your_api_hash" >> .env echo "PHONE_NUMBER=+123456789" >> .env # Edit .env with your actual credentials # 4. Authenticate with Telegram python -m src.cli_setup # 5. Run tests pytest tests/ ``` -------------------------------- ### Local Test Environment Setup Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/CONTRIBUTING.md Commands to install test dependencies and execute the full test suite with coverage reporting. ```bash # Install test dependencies pip install pytest pytest-asyncio pytest-cov pytest-xdist # Run all tests pytest tests/ -v # Run with coverage pytest tests/ --cov=src --cov-report=html # Open coverage report in browser open htmlcov/index.html ``` -------------------------------- ### Start the Server Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Installation.md Commands to pull the latest image and start the container in detached mode. ```bash docker compose up -d --pull docker compose logs -f ``` -------------------------------- ### JavaScript Setup Flow Controller Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/src/templates/setup.html Handles form visibility toggling and URL parameter management for the setup flow. ```javascript (function () { 'use strict'; const BRANCH_IDS = ['new-session', 'reauthorize', 'delete-session']; /** True when initial three sections are still in the DOM (HTMX has not replaced the shell). */ function setupShellIntact() { return BRANCH_IDS.every((name) => document.getElementById(name + '-form')); } function showForm(formName) { if (!BRANCH_IDS.includes(formName)) { return; } // After HTMX swaps #setup-flow, branch sections may be missing. Reload with ?branch= so // the full shell is restored and the chosen branch opens (avoid hiding the only visible block first). if (!setupShellIntact()) { const u = new URL('/setup', window.location.origin); u.searchParams.set('branch', formName); window.location.assign(u.pathname + u.search); return; } BRANCH_IDS.forEach((name) => { const form = document.getElementById(name + '-form'); const button = document.querySelector('[data-form="' + name + '"]'); if (name === formName) { form.hidden = false; button?.setAttribute('aria-expanded', 'true'); } else { form.hidden = true; button?.setAttribute('aria-expanded', 'false'); } }); } document.addEventListener('click', function (e) { const button = e.target.closest('[data-form]'); if (button) { e.preventDefault(); showForm(button.dataset.form); } }); document.addEventListener('keydown', function (e) { if (e.key === 'Enter' || e.key === ' ') { const button = e.target.closest('[data-form]'); if (button) { e.preventDefault(); showForm(button.dataset.form); } } }); document.addEventListener('DOMContentLoaded', function () { const params = new URLSearchParams(window.location.search); const branch = params.get('branch'); if (branch && BRANCH_IDS.includes(branch)) { showForm(branch); if (window.history.replaceState) { window.history.replaceState({}, '', '/setup'); } } }); })(); ``` -------------------------------- ### CSS Styles for Setup Interface Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/src/templates/setup.html Defines layout and interaction styles for the setup form buttons and responsive behavior. ```css #step>h1 { margin-bottom: 8px; } .setup-form { margin-top: 1.5rem; } #setup-flow { margin-top: 1rem; } .option-buttons { display: flex; flex-wrap: wrap; gap: 0.75rem; margin-top: 12px; margin-bottom: 16px; } /* Enhanced button interactions */ .option-buttons button { position: relative; transition: all 0.2s ease; border: 2px solid transparent; margin-top: 0; } .option-buttons button:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); } .option-buttons button:focus { outline: 2px solid #4f46e5; outline-offset: 2px; } .option-buttons button[aria-expanded="true"] { border-color: #4f46e5; background: #1e293b; } /* Responsive design improvements */ @media (max-width: 640px) { .option-buttons { flex-direction: column; gap: 0.75rem; } .option-buttons button { padding: 0.875rem; font-size: 1rem; } } ``` -------------------------------- ### Chat Information Tool Examples Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Tools-Reference.md JSON examples for invoking the get_chat_info tool with various parameters. ```json // Get user details by ID {"tool": "get_chat_info", "params": {"chat_id": "133526395"}} // Get details by username {"tool": "get_chat_info", "params": {"chat_id": "telegram"}} // Get forum topics (returns up to 20 by default) {"tool": "get_chat_info", "params": {"chat_id": "-1001234567890"}} // Get more forum topics {"tool": "get_chat_info", "params": {"chat_id": "-1001234567890", "topics_limit": 50}} // Get common groups for a user target (returns up to 10 by default) {"tool": "get_chat_info", "params": {"chat_id": "133526395"}} // Get more common groups {"tool": "get_chat_info", "params": {"chat_id": "133526395", "common_chats_limit": 50}} ``` -------------------------------- ### Deploy via Script Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Installation.md Use the deployment script to sync, build, and start the service on a remote host. ```bash ./scripts/deploy.sh # uses git describe for the image tag ./scripts/deploy.sh v0.42.0 # explicit version tag ``` -------------------------------- ### Install with S3 Support Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Installation.md Use the S3 extra dependency to install the necessary packages for object storage integration. ```bash uv pip install fast-mcp-telegram[s3] ``` -------------------------------- ### Setup Bot Session via CLI Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/MTProto-Bridge.md Initializes a new bot session and generates a Bearer token for authentication. ```bash # Create a bot session (replace with your bot token from BotFather) python -m src.cli_setup --api-id --api-hash --bot-api-token # The command will print a Bearer token - this identifies your bot # Example output: # πŸ”‘ Bearer Token: abc123def456... # πŸ€– Bot setup complete! You can now use the MTProto bridge: # - Use /mtproto-api/... endpoints for bot operations # - High-level tools (search, send_message, etc.) are disabled for bots ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/CONTRIBUTING.md Examples of valid commit messages following the conventional commit format. ```text feat(auth): add multi-user Bearer token authentication fix(tools): resolve message search timeout issue docs(readme): update installation instructions ``` -------------------------------- ### Start the HTTP server for ACL testing Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/CONTRIBUTING.md Launches the server in http-auth mode with a custom ACL configuration file. ```bash SERVER_MODE=http-auth HOST=127.0.0.1 PORT=8765 \ ACL_ENABLED=true ACL_CONFIG_PATH=acl.dev.yaml \ python3 -m src.server ``` -------------------------------- ### send_message Tool Usage Examples Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Tools-Reference.md Various JSON examples demonstrating how to use the send_message tool for text, files, rich messages, and replies. ```json // Send text message {"tool": "send_message", "params": { "chat_id": "me", "message": "Hello from AI! πŸš€" }} ``` ```json // Send file from URL {"tool": "send_message", "params": { "chat_id": "me", "message": "Check this document", "files": ["https://example.com/document.pdf"] }} ``` ```json // Send multiple images as album {"tool": "send_message", "params": { "chat_id": "@channel", "message": "Project screenshots", "files": ["https://example.com/img1.png", "https://example.com/img2.png"] }} ``` ```json // Send local file (stdio mode only) {"tool": "send_message", "params": { "chat_id": "me", "message": "Report attached", "files": ["/path/to/report.pdf"] }} ``` ```json // Send inline data: URI with filename (all transport modes) {"tool": "send_message", "params": { "chat_id": "@username", "message": "Report", "files": ["data:application/pdf;filename=report.pdf;base64,Khs="] }} ``` ```json // Reply with formatting {"tool": "send_message", "params": { "chat_id": "@username", "message": "*Important:* Meeting at 3 PM", "parse_mode": "markdown", "reply_to_id": 67890 }} ``` ```json // Rich Message document (headings, lists) {"tool": "send_message", "params": { "chat_id": "me", "message": "## Status\n\n- item a\n- item b", "parse_mode": "rich" }} ``` ```json // Post into a forum topic (use topic_id from get_chat_info topics list as reply_to_id) {"tool": "send_message", "params": { "chat_id": "-1001234567890", "message": "Hello forum thread!", "reply_to_id": 52 }} ``` ```json // Post comment on channel post (auto-detects discussion group) {"tool": "send_message", "params": { "chat_id": "-1001234567890", "message": "Great post!", "reply_to_id": 42 }} ``` -------------------------------- ### Send Message to Phone Tool Examples Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Tools-Reference.md JSON examples for sending messages to phone numbers with optional file attachments and contact management. ```json // Basic message to new contact {"tool": "send_message_to_phone", "params": { "phone_number": "+1234567890", "message": "Hello from AI! πŸ€–" }} ``` ```json // Message with file {"tool": "send_message_to_phone", "params": { "phone_number": "+1234567890", "message": "Check this document", "files": "https://example.com/document.pdf" }} ``` ```json // Message with formatting and cleanup {"tool": "send_message_to_phone", "params": { "phone_number": "+1234567890", "message": "*Urgent:* Meeting rescheduled to 4 PM", "parse_mode": "markdown", "remove_if_new": true }} ``` -------------------------------- ### Setup Multiple Accounts Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Installation.md Create distinct session files for different Telegram accounts using the CLI. ```bash # Create sessions for different accounts SESSION_NAME=personal fast-mcp-telegram-setup \ --api-id="xxx" --api-hash="yyy" --phone-number="+111" SESSION_NAME=work fast-mcp-telegram-setup \ --api-id="xxx" --api-hash="yyy" --phone-number="+222" ``` -------------------------------- ### Post annotation via cURL Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Grafana-Annotations-API.md Minimal example for creating a release annotation using the command line. ```bash curl -X POST "$GRAFANA_URL/api/annotations" \ -H "Authorization: Bearer $GRAFANA_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "text": "v0.0.32 β€” OAuth2 PKCE", "time": 1750000000000, "tags": ["release", "fast-mcp-telegram"], "data": { "tag": "v0.0.32", "url": "https://github.com/alexeyleshchenko/fast-mcp-telegram/releases/tag/v0.0.32" } }' ``` -------------------------------- ### Global Message Search Examples Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Tools-Reference.md JSON examples for invoking the search_messages_globally tool with various filters. ```json // Global search across all chats {"tool": "search_messages_globally", "params": {"query": "deadline", "limit": 20}} // Multi-term global search (comma-separated) {"tool": "search_messages_globally", "params": {"query": "project, launch", "limit": 30}} // Partial word search (finds "project", "projects", etc.) {"tool": "search_messages_globally", "params": {"query": "proj", "limit": 20}} // Filtered by date and type {"tool": "search_messages_globally", "params": { "query": "meeting", "chat_type": "private", "min_date": "2024-01-01" }} // Search only in public groups and channels {"tool": "search_messages_globally", "params": { "query": "announcement", "public": true }} // Search private groups only {"tool": "search_messages_globally", "params": { "query": "team", "chat_type": "group", "public": false }} // Search in multiple chat types {"tool": "search_messages_globally", "params": { "query": "urgent", "chat_type": "private,group" }} ``` -------------------------------- ### Post annotation via Python Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Grafana-Annotations-API.md Programmatic example using the standard library to send an annotation request. ```python import json import urllib.request from datetime import datetime, timezone RELEASE_TAG = "v0.0.32" RELEASE_NAME = "OAuth2 PKCE" RELEASE_URL = f"https://github.com/alexeyleshchenko/fast-mcp-telegram/releases/tag/{RELEASE_TAG}" PUBLISHED_AT = datetime(2026, 1, 1, 12, 0, 0, tzinfo=timezone.utc) body = { "text": f"{RELEASE_TAG} β€” {RELEASE_NAME}", "time": int(PUBLISHED_AT.timestamp() * 1000), "tags": ["release", "fast-mcp-telegram"], "data": {"tag": RELEASE_TAG, "url": RELEASE_URL}, } req = urllib.request.Request( f"{GRAFANA_URL}/api/annotations", data=json.dumps(body).encode(), headers={ "Authorization": f"Bearer {GRAFANA_API_TOKEN}", "Content-Type": "application/json", }, method="POST", ) with urllib.request.urlopen(req) as resp: print(resp.status, resp.read().decode()) ``` -------------------------------- ### Edit Message Tool Examples Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Tools-Reference.md JSON examples for editing messages with various formatting options. ```json // Edit existing message {"tool": "edit_message", "params": { "chat_id": "-1001234567890", "message_id": 12345, "message": "Updated: Project deadline extended" }} ``` ```json // Edit with formatting (auto-detected) {"tool": "edit_message", "params": { "chat_id": "me", "message_id": 67890, "message": "*Updated:* Meeting rescheduled to 4 PM" }} ``` ```json // Edit with explicit formatting {"tool": "edit_message", "params": { "chat_id": "me", "message_id": 67890, "message": "Updated: Meeting rescheduled to 4 PM", "parse_mode": "html" }} ``` ```json // Edit to Rich Message {"tool": "edit_message", "params": { "chat_id": "me", "message_id": 67890, "message": "## Updated\n\n- done", "parse_mode": "rich" }} ``` -------------------------------- ### get_messages Usage Examples Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Tools-Reference.md Various configurations for searching, browsing, and retrieving specific message threads or contexts. ```json // 1. Search in chat {"tool": "get_messages", "params": { "chat_id": "-1001234567890", "query": "launch" }} // 2. Browse latest messages (no query) {"tool": "get_messages", "params": { "chat_id": "me", "limit": 10 }} // 3. Read specific messages by ID {"tool": "get_messages", "params": { "chat_id": "me", "message_ids": [680204, 680205] }} // 4. Get channel post comments (auto-detects discussion) {"tool": "get_messages", "params": { "chat_id": "-1001234567890", "reply_to_id": 123 }} // 5. Get forum topic messages (topic_id from get_chat_info) {"tool": "get_messages", "params": { "chat_id": "-1001234567890", "reply_to_id": 52 }} // 5b. Replies to a message inside a forum topic (direct) {"tool": "get_messages", "params": { "chat_id": "telemtrs", "reply_to_id": 13204, "thread_scope": "auto" }} // 5c. Same anchor, nested branch (replies to replies) {"tool": "get_messages", "params": { "chat_id": "telemtrs", "reply_to_id": 13204, "thread_scope": "full" }} // 6. Get replies to any message {"tool": "get_messages", "params": { "chat_id": "me", "reply_to_id": 100 }} // 7. Search within replies {"tool": "get_messages", "params": { "chat_id": "-1001234567890", "reply_to_id": 123, "query": "bug" }} // Multi-term search {"tool": "get_messages", "params": { "chat_id": "telegram", "query": "update, news" }} // 8. Search with context (3 messages before/after each result) {"tool": "get_messages", "params": { "chat_id": "-1001234567890", "query": "deadline", "context": 3, "limit": 10 }} // 9. Search with context + reply threads {"tool": "get_messages", "params": { "chat_id": "-1001234567890", "query": "announcement", "context": 2, "include_replies": true, "limit": 10 }} // 10. Reply threads only (no neighbor context) {"tool": "get_messages", "params": { "chat_id": "-1001234567890", "query": "question", "include_replies": true, "limit": 5 }} ``` -------------------------------- ### Global Search Examples Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Search-Guidelines.md Shows valid and invalid query patterns for global message searches. ```json // βœ… Good: Simple, common words {"tool": "search_messages_globally", "params": {"query": "deadline", "limit": 20}} // βœ… Good: Multiple related terms {"tool": "search_messages_globally", "params": {"query": "deadline, due, urgent", "limit": 30}} // βœ… Good: Partial word for broader matches {"tool": "search_messages_globally", "params": {"query": "proj", "limit": 20}} // ❌ Bad: Wildcards don't work {"tool": "search_messages_globally", "params": {"query": "proj*"}} // ❌ Bad: Regex patterns don't work {"tool": "search_messages_globally", "params": {"query": "^project"}} // ❌ Bad: Boolean operators don't work {"tool": "search_messages_globally", "params": {"query": "project AND deadline"}} ``` -------------------------------- ### Development Workflow Commands Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/CONTRIBUTING.md Commands for installing development dependencies, running the server, and executing specific development tasks. ```bash # Install dev dependencies pip install -e .[dev] # Format code ruff format . # Lint code ruff check . # Test server python -m src.server # Run specific test pytest tests/test_specific.py -v # Development server with auto-reload uvicorn src.server:app --host 0.0.0.0 --port 8000 --reload ``` -------------------------------- ### Authenticate via QR Code Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Installation.md Use this method for a seamless setup without phone numbers or OTPs. Works over SSH connections. ```bash uvx --from fast-mcp-telegram fast-mcp-telegram-setup \ --api-id="your_api_id" \ --api-hash="your_api_hash" ``` -------------------------------- ### Chat-Specific Search Examples Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Search-Guidelines.md Examples for searching within a specific chat context using chat_id. ```json // βœ… Good: Search in specific chat {"tool": "get_messages", "params": {"chat_id": "-1001234567890", "query": "launch"}} // βœ… Good: Get latest messages (no query) {"tool": "get_messages", "params": {"chat_id": "me", "limit": 10}} // βœ… Good: Multi-term search in chat {"tool": "get_messages", "params": {"chat_id": "telegram", "query": "update, news"}} // βœ… Good: Partial word search {"tool": "get_messages", "params": {"chat_id": "me", "query": "proj"}} ``` -------------------------------- ### Filtered Search Examples Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Search-Guidelines.md Demonstrates applying filters like chat type and date ranges to global searches. ```json // βœ… Good: Filter by chat type {"tool": "search_messages_globally", "params": { "query": "meeting", "chat_type": "private", "limit": 20 }} // βœ… Good: Filter by date range {"tool": "search_messages_globally", "params": { "query": "project", "min_date": "2025-01-01", "max_date": "2025-12-31", "limit": 30 }} // βœ… Good: Combined filters {"tool": "search_messages_globally", "params": { "query": "deadline, urgent", "chat_type": "private", "min_date": "2025-01-01", "limit": 15 }} ``` -------------------------------- ### Sender-Specific Search Examples Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Search-Guidelines.md Demonstrates how to filter messages by sender using the from_user parameter in per-chat searches. ```json // βœ… Good: Filter by sender name (server-side, per-chat only) {"tool": "get_messages", "params": {"chat_id": "-1001234567890", "from_user": "alice", "limit": 20}} // βœ… Good: Search text + sender filter {"tool": "get_messages", "params": {"chat_id": "-1001234567890", "query": "docs.google.com", "from_user": "Π‘ΡƒΠΊΡ€Π΅ΠΉ", "limit": 20}} // βœ… Good: Browse messages from specific sender with date range {"tool": "get_messages", "params": {"chat_id": "-1001234567890", "from_user": "@username", "min_date": "2025-01-01", "limit": 50}} // ❌ Bad: Sender names in query don't work {"tool": "get_messages", "params": {"chat_id": "-1001234567890", "query": "Π‘ΡƒΠΊΡ€Π΅ΠΉ"}} // ❌ Bad: from_user not supported in global search {"tool": "search_messages_globally", "params": {"query": "hello", "from_user": "alice"}} ``` -------------------------------- ### Telegram Authentication Options Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/CONTRIBUTING.md Various methods to authenticate with Telegram using the setup script, including file-based, CLI arguments, and environment variables. ```bash # Automatic .env file loading (recommended) echo "API_ID=your_api_id" > .env echo "API_HASH=your_api_hash" >> .env echo "PHONE_NUMBER=+123456789" >> .env python -m src.cli_setup # Using CLI arguments python -m src.cli_setup --api-id="your_api_id" --api-hash="your_api_hash" --phone-number="+123456789" # Using environment variables API_ID="your_api_id" API_HASH="your_api_hash" PHONE_NUMBER="+123456789" \ python -m src.cli_setup # Additional options available: # --overwrite # Auto-overwrite existing session # --session-name NAME # Use custom session name ``` -------------------------------- ### Common Search Patterns by Content Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Search-Guidelines.md Examples for finding messages based on topics, time-related keywords, or action items. ```json // Look for specific topics {"tool": "search_messages_globally", "params": {"query": "budget, finance, money", "limit": 20}} // Look for time-related messages {"tool": "search_messages_globally", "params": {"query": "tomorrow, next week, deadline", "limit": 20}} // Look for action items {"tool": "search_messages_globally", "params": {"query": "todo, task, action", "limit": 20}} ``` -------------------------------- ### Execute MCP Tools Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/README.md Example JSON payloads for interacting with Telegram tools like searching, retrieving, and sending messages. ```json {"tool": "search_messages_globally", "params": {"query": "hello", "limit": 5}} {"tool": "get_messages", "params": {"chat_id": "me", "limit": 10}} {"tool": "send_message", "params": {"chat_id": "me", "message": "Hello!"}} ``` -------------------------------- ### Construct Complex Todo List Object Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/MTProto-Bridge.md Example of creating a nested TodoList object using automatic TL object construction. ```bash curl -X POST "https://your-domain.com/mtproto-api/messages.sendMedia" \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "params": { "peer": "me", "media": { "_": "InputMediaTodo", "todo": { "_": "TodoList", "title": { "_": "TextWithEntities", "text": "My Todo List", "entities": [] }, "list": [ { "_": "TodoItem", "id": 1, "title": { "_": "TextWithEntities", "text": "Complete project documentation", "entities": [] } }, { "_": "TodoItem", "id": 2, "title": { "_": "TextWithEntities", "text": "Review code changes", "entities": [] } } ], "others_can_append": true, "others_can_complete": false } }, "message": "Check out my new todo list!", "random_id": 1234567890123456789 } }' ``` -------------------------------- ### Iterative Search Strategy Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Search-Guidelines.md Demonstrates how to refine search queries by starting with specific terms and broadening to related or partial terms if no results are found. ```json // Start with specific term {"tool": "search_messages_globally", "params": {"query": "deadline", "limit": 10}} // If no results, try related terms {"tool": "search_messages_globally", "params": {"query": "deadline, due, urgent", "limit": 20}} // If still no results, try partial words {"tool": "search_messages_globally", "params": {"query": "dead", "limit": 20}} ``` -------------------------------- ### Clone or Download Repository Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Installation.md Choose between cloning the repository or downloading the necessary configuration files directly. ```bash git clone https://github.com/alexeyleshchenko/fast-mcp-telegram.git cd fast-mcp-telegram ``` ```bash curl -O https://raw.githubusercontent.com/alexeyleshchenko/fast-mcp-telegram/main/docker-compose.yml curl -O https://raw.githubusercontent.com/alexeyleshchenko/fast-mcp-telegram/main/.env.example mv .env.example .env ``` -------------------------------- ### Manage Multiple Bot Sessions Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/MTProto-Bridge.md Demonstrates creating and using distinct sessions for multiple bots. ```bash # Bot 1 python -m src.cli_setup --api-id --api-hash --bot-api-token # Bearer Token: token1_abc123... # Bot 2 python -m src.cli_setup --api-id --api-hash --bot-api-token # Bearer Token: token2_def456... # Use Bot 1 curl -X POST "https://your-domain.com/mtproto-api/messages.SendMessage" \ -H "Authorization: Bearer token1_abc123..." \ -H "Content-Type: application/json" \ -d '{"params": {"peer": "@channel1", "message": "From Bot 1"}}' # Use Bot 2 curl -X POST "https://your-domain.com/mtproto-api/messages.SendMessage" \ -H "Authorization: Bearer token2_def456..." \ -H "Content-Type: application/json" \ -d '{"params": {"peer": "@channel2", "message": "From Bot 2"}}' ``` -------------------------------- ### Example tool usage JSON Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/CONTRIBUTING.md JSON payloads for invoking specific Telegram tools. ```json {"tool": "search_messages_globally", "params": {"query": "hello", "limit": 5}} {"tool": "send_message", "params": {"chat_id": "me", "message": "Hello from AI!"}} ``` -------------------------------- ### Bump project version with uv Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/.cursor/skills/release-notes/SKILL.md Use uv to manage version increments instead of manual file edits. ```bash uv version # or: uv version --bump patch | minor | major ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Installation.md Define required API credentials and optional server settings in a .env file. ```bash # Required (pick one auth method) # β€” User account (phone + OTP): API_ID=your_api_id API_HASH=your_api_hash # β€” Bot account (no phone, no OTP): # BOT_API_TOKEN=1234567890:ABCdef... # Optional SERVER_MODE=http-auth # stdio (default) or http-auth for remote HOST=127.0.0.1 # Bind address (use 0.0.0.0 for production HTTP behind a proxy) PORT=8000 # Server port (http-auth mode) LOG_LEVEL=INFO # Logging verbosity SESSION_NAME=telegram # Session file name (stdio mode only) SESSION_DIR=~/.config/fast-mcp-telegram # Custom session directory MTPROTO_PROXY=tg://proxy?server=your-proxy.com&port=443&secret=your-secret # Firewall proxy TELEGRAM_INACTIVE_SESSION_DAYS=30 # Auto-delete .session files unused >N days (0 = disable) # Session ACL (http-auth only) β€” see #session-acl-http-auth ACL_ENABLED=false # Opt-in per-principal MCP limits (http-auth) ACL_CONFIG_PATH= # Override default {session_directory}/acl.yaml ACL_DENY_UNLISTED_PRINCIPALS=false # Deny principals omitted from principals: map ``` -------------------------------- ### Project Directory Structure Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/benchmark-spec.md Overview of the integration test and documentation file layout. ```text tests/integration/ β”œβ”€β”€ bench_core.py # Shared infrastructure: BenchScenario, ScenarioRunner, reporting β”œβ”€β”€ scenarios.py # 13 scenario definitions across find_chats + search_messages β”œβ”€β”€ run_bench.py # Unified standalone CLI β€” warmup, N iterations, ASCII table, JSON output β”œβ”€β”€ conftest.py # Pytest module-scoped Telethon client fixture β”œβ”€β”€ test_bench_scenarios.py # Parametrized pytest smoke test β€” 13 scenarios, 1 iteration each β”œβ”€β”€ test_date_filtering.py # Standalone validation script (not a benchmark) β”œβ”€β”€ test_filter_resolution.py # Standalone validation script β”œβ”€β”€ test_find_chats_date_filtering.py # Standalone validation script └── test_get_messages_timing.py # Standalone validation script docs/ └── benchmark-spec.md # This document β€” spec, targets, running instructions ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Installation.md Set the required API credentials and domain in the .env file. ```bash API_ID=your_api_id API_HASH=your_api_hash DOMAIN=your-domain.com ``` -------------------------------- ### Resolve Peer Identifiers via JSON Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/MTProto-Bridge.md Examples of various peer identifier formats supported when resolve is enabled. ```bash # These all work with resolve: true {"params": {"peer": "@durov"}} # Username {"params": {"peer": "me"}} # Saved Messages {"params": {"peer": 123456789}} # User ID {"params": {"peer": "-1001234567890"}} # Channel ID {"params": {"peer": "+1234567890"}} # Phone number {"params": {"peer": "https://t.me/durov"}} # t.me URL β†’ username {"params": {"peer": "https://t.me/c/1234567890"}} # t.me channel URL β†’ -1001234567890 {"params": {"peer": "tg://resolve?domain=durov"}} # tg:// scheme β†’ username {"params": {"peer": "tg://user?id=123456789"}} # tg:// user β†’ numeric ID ``` -------------------------------- ### Authenticate via CLI Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/README.md Run this command to initialize the Telegram session using your API credentials. ```bash uvx --from fast-mcp-telegram fast-mcp-telegram-setup \ --api-id="your_api_id" \ --api-hash="your_api_hash" \ --phone-number="+123456789" ``` -------------------------------- ### Initialize Telemetry Database Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/adr/0006-abuse-prevention-for-collection-endpoint.md Sets up a dedicated database and table for telemetry events to isolate storage from other services. ```sql CREATE DATABASE telemetry; \c telemetry CREATE TABLE telemetry_events ( id BIGSERIAL PRIMARY KEY, payload JSONB NOT NULL, received_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); ``` -------------------------------- ### Implement S3 startup health check and orphan cleanup Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/design/s3-session-storage-design.md Validates S3 configuration and dependencies at startup, and performs cleanup of orphaned temporary session files. ```python async def _startup_s3_check() -> None: if not is_s3_enabled(): return try: import aiobotocore # noqa: F401 except ImportError: logger.critical("S3_SESSION_STORAGE=true but aiobotocore not installed. " "Install with: pip install fast-mcp-telegram[s3]") raise SystemExit(1) # Validate required env vars bucket = os.environ.get("AWS_S3_BUCKET", "") if not bucket: logger.critical("S3_SESSION_STORAGE=true but AWS_S3_BUCKET is not set") raise SystemExit(1) # Fail-fast: disable_auth + S3 is not supported (path divergence) if cfg().disable_auth: logger.critical("S3_SESSION_STORAGE=true with disable_auth=true is not supported") raise SystemExit(1) # Configure s3_session module s3_session.configure(bucket) try: await s3_session.health_check() logger.info("S3 session storage: connected") except Exception as e: logger.critical(f"S3 health check failed: {e}") raise SystemExit(1) # Also called unconditionally at startup (not just in S3 mode): async def _cleanup_orphaned_tmp_files() -> None: """Remove orphaned .session.tmp files from previous crashes. Always runs.""" session_dir = cfg().session_directory if session_dir.exists(): for tmp_file in session_dir.glob("*.session.tmp"): logger.info(f"Removing orphaned temp file: {tmp_file.name}") tmp_file.unlink(missing_ok=True) ``` -------------------------------- ### Send Formatted Message via API Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/MTProto-Bridge.md Example of sending a message with bold text formatting using the MTProto bridge. ```bash curl -X POST "https://your-domain.com/mtproto-api/messages.SendMessage" \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{"params": {"peer": "me", "message": "Hello!", "entities": [{"_": "messageEntityBold", "offset": 0, "length": 5}]}}' ``` -------------------------------- ### Configure MCP Client for stdio Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/README.md Add this configuration to your MCP client settings to run the server locally via stdio. ```json { "mcpServers": { "telegram": { "command": "uvx", "args": ["fast-mcp-telegram"], "env": { "API_ID": "your_api_id", "API_HASH": "your_api_hash" } } } } ``` -------------------------------- ### Configure Multiple Accounts in MCP Client Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Installation.md Define multiple server instances in the MCP client configuration file. ```json { "mcpServers": { "telegram-personal": { "command": "uvx", "args": ["fast-mcp-telegram"], "env": { "API_ID": "your_api_id", "API_HASH": "your_api_hash", "SESSION_NAME": "personal" } }, "telegram-work": { "command": "uvx", "args": ["fast-mcp-telegram"], "env": { "API_ID": "your_api_id", "API_HASH": "your_api_hash", "SESSION_NAME": "work" } } } } ``` -------------------------------- ### Common Search Patterns by Context Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Search-Guidelines.md Examples for finding messages based on specific users, time ranges, or chat types. ```json // Recent messages from a specific person {"tool": "get_messages", "params": {"chat_id": "@username", "limit": 10}} // Messages in a specific time period {"tool": "search_messages_globally", "params": { "query": "project", "min_date": "2025-01-01", "max_date": "2025-01-31", "limit": 30 }} // Messages in specific chat types {"tool": "search_messages_globally", "params": { "query": "announcement", "chat_type": "channel", "limit": 20 }} ``` -------------------------------- ### Constructing Complex TL Objects Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Tools-Reference.md Examples of using the invoke_mtproto tool to send complex objects and use case-insensitive type names. ```json // Create a todo list (automatic object construction) {"tool": "invoke_mtproto", "params": { "method_full_name": "messages.sendMedia", "params_json": { "peer": "me", "media": { "_": "InputMediaTodo", "todo": { "_": "TodoList", "title": { "_": "TextWithEntities", "text": "My Todo List", "entities": [] }, "list": [ { "_": "TodoItem", "id": 1, "title": { "_": "TextWithEntities", "text": "Complete project documentation", "entities": [] } }, { "_": "TodoItem", "id": 2, "title": { "_": "TextWithEntities", "text": "Review code changes", "entities": [] } } ], "others_can_append": true, "others_can_complete": false } }, "message": "Check out my new todo list!", "random_id": 1234567890123456789 } }} // Case-insensitive type names work too! {"tool": "invoke_mtproto", "params": { "method_full_name": "messages.sendMessage", "params_json": { "peer": "me", "message": "Hello!", "entities": [ { "_": "messageentitybold", // lowercase works! "offset": 0, "length": 5 } ] } }} ``` -------------------------------- ### Project Source Tree Structure Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/adr/0005-anonymous-tool-telemetry.md Overview of the relevant files for telemetry implementation within the project. ```text src/ β”œβ”€β”€ server.py # spawn telemetry task in lifespan β”œβ”€β”€ telemetry.py # should_send(), send_heartbeat(), gather_payload(), β”‚ # MetricsStore, instance_id, HTTP POST └── config/server_config.py # add: DO_NOT_TRACK env detection ``` -------------------------------- ### Common API Error Responses Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/MTProto-Bridge.md Examples of JSON error responses for invalid methods, missing authentication, and blocked dangerous methods. ```json { "ok": false, "error": "Unknown method: invalidMethod", "error_type": "MethodNotFound", "operation": "mtproto_api_call" } ``` ```json { "ok": false, "error": "Bearer token required for HTTP_AUTH mode", "error_type": "AuthenticationRequired", "operation": "mtproto_api_call" } ``` ```json { "ok": false, "error": "Dangerous method blocked. Set allow_dangerous=true to override.", "error_type": "DangerousMethodBlocked", "operation": "mtproto_api_call" } ``` -------------------------------- ### Enable Tool Name Prefixes Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/Installation.md Set this environment variable to distinguish tool names when connecting multiple Telegram accounts to a single agent. ```bash PREFIX_MCP_TOOLS_WITH_ACCOUNT=true ``` -------------------------------- ### Implement Migration Runner Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/research/oidc-self-service-design.md Python function to apply SQL migration files sequentially based on the schema_version table. ```python import sqlite3 from pathlib import Path MIGRATIONS_DIR = Path(__file__).parent / "migrations" def run_migrations(db_path: str) -> None: conn = sqlite3.connect(db_path) conn.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA foreign_keys=ON") # Ensure version table exists conn.execute(""" CREATE TABLE IF NOT EXISTS schema_version ( version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), description TEXT ) """) current = conn.execute("SELECT COALESCE(MAX(version), 0) FROM schema_version").fetchone()[0] for migration_file in sorted(MIGRATIONS_DIR.glob("*.sql")): version = int(migration_file.stem.split("_")[0]) if version > current: sql = migration_file.read_text() conn.executescript(sql) conn.execute( "INSERT INTO schema_version (version, description) VALUES (?, ?)", (version, migration_file.stem) ) conn.commit() conn.close() ``` -------------------------------- ### Define OIDC Storage Schema Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/research/oidc-self-service-design.md SQL schema definitions for identity mapping, setup state machine, and migration tracking tables. ```sql -- OIDC identity mapping CREATE TABLE IF NOT EXISTS oidc_identity ( oidc_key TEXT PRIMARY KEY, -- SHA-256(sub + issuer) oidc_sub TEXT NOT NULL, oidc_issuer TEXT NOT NULL, telegram_user_id INTEGER NOT NULL, telegram_username TEXT, telegram_phone TEXT, created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')) ); -- Elicitation state machine CREATE TABLE IF NOT EXISTS setup_state ( oidc_key TEXT PRIMARY KEY, state TEXT NOT NULL CHECK (state IN ('WAITING_PHONE','WAITING_CODE','WAITING_PASS','COMPLETED','FAILED')), phone_number TEXT, tg_code_hash TEXT, -- Telethon phone_code_hash retry_count INTEGER NOT NULL DEFAULT 0, metadata TEXT, -- JSON blob for extra state created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')) ); -- Migration tracking CREATE TABLE IF NOT EXISTS schema_version ( version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), description TEXT ); ``` -------------------------------- ### Execute Forum Topics Tests Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/CONTRIBUTING.md Commands for running specific forum topic tests, including optional live integration checks requiring environment variables. ```bash # Focused forum topics suite pytest tests/test_forum_topics_minimal.py -v # Optional live integration checks (disabled by default) FAST_MCP_TELEGRAM_LIVE_TESTS=1 \ FAST_MCP_TELEGRAM_FORUM_CHAT_ID= \ pytest tests/test_forum_topics_minimal.py -m integration -v ``` -------------------------------- ### Execute Telegram API methods via curl Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/docs/MTProto-Bridge.md Use these examples to send messages or retrieve history by calling the MTProto API endpoint directly. ```bash # Send message with automatic entity resolution curl -X POST "https://your-domain.com/mtproto-api/messages.SendMessage" \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{"params": {"peer": "@username", "message": "Hello from curl!"}}' # Get message history with peer resolution curl -X POST "https://your-domain.com/mtproto-api/messages.getHistory" \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{"params": {"peer": "me", "limit": 10}}' ``` -------------------------------- ### Clipboard Copy Utility Function Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/src/templates/fragments/config.html JavaScript utility to copy configuration text to the system clipboard. ```javascript async function copyConfig(preId, btn) { const pre = document.getElementById(preId); if (!pre) { return; } const originalText = btn.innerText; try { await navigator.clipboard.writeText(pre.innerText); btn.innerText = 'Copied'; } catch (_) { btn.innerText = 'Copy failed'; } setTimeout(() => { btn.innerText = originalText; }, 2000); } ``` -------------------------------- ### Code Quality and Linting Commands Source: https://github.com/alexeyleshchenko/fast-mcp-telegram/blob/master/CONTRIBUTING.md Standard commands for formatting, linting, and type checking the codebase. ```bash # Format code ruff format . # Lint code ruff check . # Type checking mypy src/ # Run tests with coverage pytest tests/ --cov=src --cov-report=html # Run all checks ruff format . && ruff check . && mypy src/ ```