Skip to main content
Glama
Telegram Human-in-the-Loop MCP Server

Telegram Human-in-the-Loop MCP Server

by theohero
README.md
# ๐Ÿค–๐Ÿ’ฌ Telegram Human-in-the-Loop MCP Server

> **Let your AI talk to you through Telegram.** This MCP server gives any AI coding assistant the ability to pause, ask you questions, and wait for your reply โ€” right in your Telegram chat. Now with **rich text formatting**, **image support**, **local file browsing**, **window screenshots**, **OCR**, and **voice message transcription**.

<p align="center">
  <img src="https://img.shields.io/badge/Python-3.10+-blue?logo=python&logoColor=white" />
  <img src="https://img.shields.io/badge/MCP-stdio-green" />
  <img src="https://img.shields.io/badge/Telegram-Bot%20API-26A5E4?logo=telegram&logoColor=white" />
  <img src="https://img.shields.io/badge/Windows-โœ…-0078D4?logo=windows" />
  <img src="https://img.shields.io/badge/macOS-โœ…-000?logo=apple" />
  <img src="https://img.shields.io/badge/Linux-โœ…-FCC624?logo=linux&logoColor=black" />
</p>

---

## ๐Ÿ“Œ What is this?

When an AI agent works on your code, it sometimes needs to ask you a question โ€” "What should I name this?", "Which approach do you prefer?", "Is this the right file?"

This server intercepts those questions and **sends them to your Telegram**. You reply on your phone (or desktop Telegram), and the AI continues working with your answer.

**No browser tabs. No terminal switching. Just Telegram.**

---

## โœจ Key Features

### ๐Ÿ’ฌ Bidirectional Text Communication
- AI sends prompts to your Telegram chat
- You reply with text โ€” AI receives it and continues working
- Supports multi-line input, choices, confirmations, and info messages
- **Rich text formatting** โ€” AI messages render with **bold**, *italic*, `inline code`, and ```code blocks``` in Telegram (Markdown โ†’ HTML conversion with automatic plain-text fallback)
- **Auto-splitting** for long messages โ€” messages over 4096 chars are automatically chunked at paragraph/newline/space boundaries with part indicators (๐Ÿ“„ 1/3, 2/3, etc.)

### ๐Ÿ“ธ Image Support (Telegram โ†’ AI)
- **Send photos** from your phone/desktop directly to the AI
- Images are forwarded as MCP `ImageContent` โ€” the AI can "see" what you send
- Includes **OCR extraction** โ€” text in photos is automatically extracted
- Perfect for: sharing error screenshots, UI mockups, diagrams, handwritten notes

### ๐Ÿ—‚๏ธ Local Image Browsing (AI โ†’ AI)
- AI can **read any image file** from the local filesystem
- Browse folders to discover and preview multiple images at once
- Automatic **resizing** for large images (configurable max size)
- Optional **OCR text extraction** from local images
- Supports PNG, JPEG, GIF, BMP, WebP, TIFF, SVG
- Toggleable via `HITL_IMAGE_TOOLS_ENABLED` environment variable

### ๐Ÿ–ฅ๏ธ Window Screenshots (AI โ†’ Telegram)
- AI can capture screenshots of any window by title
- **Win32 PrintWindow API** โ€” works even for minimized or occluded windows
- Automatic **OCR text extraction** from captured screenshots
- Results returned as image + metadata (dimensions, OCR text, confidence)

### ๐ŸŽค Voice Message Transcription (Whispr)
- Send **voice messages** in Telegram โ€” they are transcribed to text automatically
- Uses a local Whisper model (Whispr module) for privacy
- Transcribed text is sent to the AI as a regular text response
- Edit tracking: shows original transcription plus any edits applied

### ๐Ÿ”„ Fallback System
- If Telegram is not configured, all tools fall back to **native GUI popups** (tkinter)
- Works offline with local dialog boxes
- Graceful degradation โ€” never blocks the AI

---

## ๐Ÿงฉ Compatible Platforms

| Platform | Status | Config location |
|----------|--------|-----------------|
| **VS Code (GitHub Copilot Agent Mode)** | โœ… Fully tested | User `mcp.json` or workspace `.vscode/mcp.json` |
| **VS Code (Copilot Chat)** | โœ… Works | Same as above |
| **Claude Code (CLI)** | โœ… Compatible | `~/.claude/mcp.json` |
| **Claude Desktop** | โœ… Compatible | See config examples below |
| **Cursor** | โœ… Compatible | `.cursor/mcp.json` in workspace |
| **Windsurf (Codeium)** | โœ… Compatible | `~/.codeium/windsurf/mcp_config.json` |
| **Cline** | โœ… Compatible | Via Cline MCP settings UI |
| **Any MCP stdio client** | โœ… Compatible | Pass `python hitl_mcp_server.py` as command |

> The server uses the standard **MCP stdio** transport โ€” it works with **any client** that supports MCP.

---

## ๐Ÿ›  Available Tools

| Tool | Description |
|------|-------------|
| `get_multiline_input` | Send a prompt to Telegram, wait for the user's reply. Supports **text**, **photos** (returned as ImageContent + OCR), and **voice messages** (Whispr transcription). Main communication tool. |
| `get_user_input` | Simple text/number input dialog |
| `get_user_choice` | Multiple choice selection dialog |
| `get_image` | Read a single image file from the local filesystem. Resizes if needed, optional OCR. Returns image + metadata. |
| `list_images` | Browse a folder for images. Returns up to N images with thumbnails + metadata. Supports sorting, filtering, recursive scan. |
| `get_window_screenshot` | Capture a screenshot of any window by title. Uses Win32 PrintWindow (works minimized). Returns image + OCR metadata. Windows only. |
| `show_confirmation_dialog` | Yes/No confirmation dialog |
| `show_info_message` | Display information to the user |
| `toggle_whispr` | Enable/disable voice message transcription module |
| `health_check` | Check server status, Telegram connectivity, available features |

---

## ๐Ÿ”ง How it Works

```
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     MCP stdio      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    Telegram API    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  AI Agent    โ”‚ โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ โ”‚  HITL Server  โ”‚ โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ โ”‚ You       โ”‚
โ”‚ (Copilot,    โ”‚   tool calls +     โ”‚  (Python)     โ”‚   send message     โ”‚ Telegram  โ”‚
โ”‚  Claude...)  โ”‚   results          โ”‚               โ”‚   wait for reply   โ”‚           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
```

1. The AI calls `get_multiline_input` (or another tool)
2. The server sends the prompt to your **Telegram chat** via Bot API
3. You read the message on your phone/desktop and **reply** (text, photo, or voice)
4. The server captures your reply and returns it to the AI
5. The AI continues working with your input

### Image Flow
```
You (Telegram)                    HITL Server                     AI Agent
     โ”‚                                โ”‚                               โ”‚
     โ”‚โ”€โ”€ Send photo โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บโ”‚                               โ”‚
     โ”‚                                โ”‚โ”€โ”€ Download image               โ”‚
     โ”‚                                โ”‚โ”€โ”€ Run OCR extraction           โ”‚
     โ”‚                                โ”‚โ”€โ”€ Return ImageContent โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บโ”‚
     โ”‚                                โ”‚   + OCR text metadata          โ”‚
     โ”‚                                โ”‚                               โ”‚โ”€โ”€ AI "sees" the image
```

### Window Screenshot Flow
```
AI Agent                          HITL Server                     AI Agent
     โ”‚                                โ”‚                               โ”‚
     โ”‚โ”€โ”€ get_window_screenshot โ”€โ”€โ”€โ”€โ”€โ”€โ–บโ”‚                               โ”‚
     โ”‚   (window_title="Settings")   โ”‚โ”€โ”€ Find window by title        โ”‚
     โ”‚                                โ”‚โ”€โ”€ Win32 PrintWindow capture   โ”‚
     โ”‚                                โ”‚โ”€โ”€ Run OCR on screenshot       โ”‚
     โ”‚                                โ”‚โ”€โ”€ Return image + metadata โ”€โ”€โ”€โ–บโ”‚
     โ”‚                                โ”‚                               โ”‚โ”€โ”€ AI processes screenshot
```

**Fallback:** If Telegram is not configured, all tools fall back to native **GUI popups** (tkinter).

---

## ๐Ÿš€ Quick Start

### Prerequisites
- Python 3.10+
- A Telegram Bot token (create via [@BotFather](https://t.me/BotFather))
- Your Telegram Chat ID

### Installation

```bash
git clone https://github.com/theohero/telegram-human-in-the-loop.git
cd telegram-human-in-the-loop
git checkout main
pip install fastmcp pydantic
```

**Optional dependencies** (for full feature set):
```bash
pip install pygetwindow pyautogui Pillow numpy rapidocr-onnxruntime
```

| Package | Required for |
|---------|-------------|
| `pygetwindow` | Window screenshot capture |
| `pyautogui` | Fallback screenshot method |
| `Pillow` | Image processing |
| `numpy` | OCR support |
| `rapidocr-onnxruntime` | OCR text extraction from images |

### Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| `TELEGRAM_BOT_TOKEN` | Yes | Your Telegram Bot API token |
| `TELEGRAM_CHAT_ID` | Yes | Your personal Telegram Chat ID |
| `HITL_TELEGRAM_TIMEOUT_SECONDS` | No | Timeout for waiting for reply (default: 3600) |

### VS Code Configuration (GitHub Copilot)

Add to your `.vscode/mcp.json` or user `mcp.json`:

```json
{
  "servers": {
    "hitl-mcp-server": {
      "type": "stdio",
      "command": "python",
      "args": ["path/to/hitl_mcp_server.py"],
      "env": {
        "HITL_TELEGRAM_BOT_TOKEN": "your-bot-token-here",
        "HITL_TELEGRAM_CHAT_ID": "your-chat-id-here"
      }
    }
  }
}
```

### Claude Desktop Configuration

Add to your Claude Desktop config:

```json
{
  "mcpServers": {
    "hitl-mcp-server": {
      "command": "python",
      "args": ["path/to/hitl_mcp_server.py"],
      "env": {
        "HITL_TELEGRAM_BOT_TOKEN": "your-bot-token-here",
        "HITL_TELEGRAM_CHAT_ID": "your-chat-id-here"
      }
    }
  }
}
```

### Claude Code (CLI)

```json
{
  "mcpServers": {
    "hitl-mcp-server": {
      "command": "python",
      "args": ["path/to/hitl_mcp_server.py"],
      "env": {
        "HITL_TELEGRAM_BOT_TOKEN": "your-bot-token-here",
        "HITL_TELEGRAM_CHAT_ID": "your-chat-id-here"
      }
    }
  }
}
```

---

## ๐Ÿ” Finding Your Chat ID

1. Open Telegram and search for **@userinfobot**
2. Send it any message โ€” it replies with your Chat ID
3. Copy the number (e.g., `123456789`)

**Alternative:** Open [https://web.telegram.org](https://web.telegram.org), go to any chat, and look at the URL โ€” the number after `#` is your Chat ID.

---

## ๐Ÿ“ธ Image Capabilities in Detail

### Receiving Images from Telegram

When you send a photo in Telegram as a reply to the AI's prompt:

1. The server downloads the highest-resolution version of the photo
2. Runs **OCR** (Optical Character Recognition) to extract any text in the image
3. Returns **mixed MCP content**: `TextContent` (metadata + OCR text) + `ImageContent` (the actual image)
4. The AI receives both the image and any extracted text

**Response metadata includes:**
```json
{
  "success": true,
  "user_input": "caption or OCR text",
  "has_image": true,
  "image_width": 1920,
  "image_height": 1080,
  "image_file_size": 245000,
  "image_mime_type": "image/jpeg",
  "ocr_enabled": true,
  "ocr_text": "extracted text from the image",
  "ocr_lines": ["line 1", "line 2"],
  "ocr_avg_confidence": 0.95
}
```

### Window Screenshots

The `get_window_screenshot` tool captures any window by title:

```python
# AI calls this tool with:
get_window_screenshot(window_title_contains="Settings", max_size=1400)
```

**Capture strategy:**
1. **Primary: Win32 PrintWindow API** โ€” works even for minimized or occluded windows (Windows only)
2. **Fallback: pyautogui region capture** โ€” requires the window to be visible

The screenshot is returned as:
- `TextContent` with metadata (title, dimensions, OCR text)
- `ImageContent` with the actual screenshot image

---

## ๐ŸŽค Voice Message Support (Whispr)

The server includes an optional **Whispr** module for local voice-to-text transcription using [faster-whisper](https://github.com/SYSTRAN/faster-whisper) (CTranslate2-based Whisper).

### How It Works

1. You send a voice message in Telegram
2. Whispr downloads the audio and transcribes it locally using a Whisper model
3. The transcribed text is sent to the AI as a regular text response
4. Metadata includes original transcription and any edits

### Setup โ€” Zero Configuration

Whispr auto-installs everything when you first enable it:

- **From Telegram:** Tap `/whispr_on` in any message footer (shown at the bottom of every AI message)
- **From AI:** The `toggle_whispr` MCP tool auto-installs dependencies and downloads the model

No `pip install`, no model downloads, no terminal โ€” just tap and go.

### Commands

| Command | Description |
|---------|-------------|
| `/whispr_on` | Enable voice transcription (auto-installs if needed) |
| `/whispr_off` | Disable voice transcription |
| `/whispr status` | Show current Whispr status and settings |
| `/whispr model <name>` | Change model: `tiny`, `base`, `small`, `medium`, `large-v3` |
| `/whispr lang <code>` | Set language: `en`, `ru`, `de`, `fr`, `auto` |

### Message Footer

Every AI message includes a Whispr status footer at the bottom:

```
๐ŸŽ™ Whispr: OFF ยท /whispr_on     โ† tap to enable
๐ŸŽ™ Whispr: ON  ยท /whispr_off    โ† tap to disable
```

### Models

| Model | Size | Speed | Accuracy | Best for |
|-------|------|-------|----------|----------|
| `tiny` | ~75 MB | Fastest | Basic | Quick notes, short phrases |
| `base` | ~150 MB | Fast | Good | General use (default) |
| `small` | ~500 MB | Medium | Better | Longer messages |
| `medium` | ~1.5 GB | Slower | High | Detailed transcription |
| `large-v3` | ~3 GB | Slowest | Best | Maximum accuracy |

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `HITL_WHISPR_ENABLED` | `false` | Enable Whispr on server start |
| `HITL_WHISPR_MODEL` | `base` | Whisper model to use |
| `HITL_WHISPR_LANGUAGE` | (auto) | Language code, or empty for auto-detect |

Models are cached locally in `~/.hitl-mcp/whispr_models/`.

---

## โ“ FAQ

**Q: Is there a message length limit?**
A: No practical limit. Messages over 4096 characters (Telegram's limit) are automatically split into multiple messages with part indicators. The reply keyboard is attached only to the last chunk.

**Q: Do I need all the optional dependencies?**
A: No. The core functionality (text chat via Telegram) only needs `fastmcp` and `pydantic`. Install optional packages only for the features you want.

**Q: Can I disable the image file browsing tools?**
A: Yes. Set `HITL_IMAGE_TOOLS_ENABLED=false` in your environment or MCP config. The `get_image` and `list_images` tools will not be registered.

**Q: Does it work without Telegram?**
A: Yes! All tools fall back to native GUI popup dialogs (tkinter) when Telegram is not configured.

**Q: Can the AI see my photos?**
A: Only photos you explicitly send as replies to the AI's prompts. The server does not access your Telegram in any other way.

**Q: Is OCR always enabled?**
A: OCR runs automatically if `rapidocr-onnxruntime`, `numpy`, and `Pillow` are installed. If not installed, images are still forwarded but without OCR text extraction.

**Q: Does it work on macOS/Linux?**
A: Text communication and image support work everywhere. Window screenshots (`get_window_screenshot`) currently use Win32 APIs and only work on Windows.

---

## ๐ŸŒ Environment Variables Reference

| Variable | Default | Description |
|----------|---------|-------------|
| `TELEGRAM_BOT_TOKEN` | โ€” | Telegram Bot API token (from @BotFather) |
| `TELEGRAM_CHAT_ID` | โ€” | Your Telegram Chat ID |
| `HITL_TELEGRAM_TIMEOUT_SECONDS` | `3600` | How long to wait for a reply (seconds) |
| `HITL_IMAGE_TOOLS_ENABLED` | `true` | Enable/disable `get_image` and `list_images` tools |
| `HITL_OCR_ENABLED` | `true` | Enable/disable OCR text extraction from images |
| `HITL_WHISPR_ENABLED` | `false` | Enable voice transcription on server start |
| `HITL_WHISPR_MODEL` | `base` | Whisper model size (`tiny`/`base`/`small`/`medium`/`large-v3`) |
| `HITL_WHISPR_LANGUAGE` | (auto) | Language code for transcription (`en`, `ru`, `de`, etc.) |
| `FASTMCP_LOG_LEVEL` | `INFO` | Logging level |

---

## ๐Ÿ“ License

MIT License. See [LICENSE](LICENSE) for details.

---

## ๐Ÿ™ Credits

Built with [FastMCP](https://github.com/jlowin/fastmcp) and the [Telegram Bot API](https://core.telegram.org/bots/api).