Skip to main content
Glama
Toligrim

letopis-mcp

by Toligrim

📜 Летопись (Letopis)

Archive and smart search engine for Telegram chat history

Raw messages in JSONL · full-text search with Russian morphology · downloader with manager

Python 3.10+ Telethon SQLite FTS5 License


Idea

Letopis is not a bot and not a service, but a CLI tool designed so that an LLM agent (primarily Claude Code) can read your Telegram chat history and answer questions from it, just like from a regular knowledge base.

The archive is stored as plain files — .jsonl, one per chat and month, append-only. An SQLite index with full-text search (FTS5) is built on top; it understands Russian word forms: the query «хостинг» finds messages containing the word «хостингами». Voice message transcripts, file names, and poll text are also connected to the search.

$ ./tg search переезд хостинг --chat devops --from 2025-06

Engine and data are separated. This repository contains only code — the chat archives themselves, config.toml, .env, and the Telegram session live in a separate private repository, which keeps you in control of what is public and what is not. More in the Structure section.


Related MCP server: telegram-user-mcp

✨ Features

🔎 Full-text search

SQLite FTS5 + pymorphy3: searches by lemmas, not only exact words

📦 Archive as files

archive/<chat_id>/<YYYY-MM>.jsonl, append-only, nothing is rewritten retroactively

⬇️ Downloader with manager

download / sync only fetch new data; manifest.json remembers what is tracked

🎙️ Voice transcriptions

locally (faster-whisper), via Telegram Premium or OpenAI Whisper API

🌐 Web viewer

chats → topic chips, infinite scroll, filters, voice player, reply jumps

⌨️ TUI viewer

the same functionality in the terminal (textual)

👥 Multiple accounts

different chats can be downloaded by different Telegram accounts

🤖 Built for agents

JSON output, compact short formats, stable CLI contract


🚀 Quick start

git clone https://github.com/Toligrim/letopis.git
cd letopis
python3 -m venv .venv && .venv/bin/pip install -e .
.venv/bin/pip install faster-whisper   # опционально: локальная транскрипция голосовых

Letopis is just the engine. To connect it to a specific archive, create a separate data repository and put the ./tg wrapper there:

#!/bin/sh
exec "$HOME/projects/letopis/.venv/bin/tg" "$@"

Everything then runs from the root of the data repository:

chmod +x tg
./tg login              # авторизация Telegram-сессии (телефон / код / 2FA)
./tg download --chat mychat --media all
./tg index && ./tg meta
./tg search привет

The engine finds the data root itself: when started, tg looks upward from the current directory for a folder where config.toml and archive/ are located next to each other (or this is explicitly set via the TG_ROOT environment variable).

🤖 Read-only MCP for ChatGPT

Letopis can work as a read-only MCP retrieval gateway for ChatGPT: the server uses the same data/index.db as regular search, but only returns five safe retrieval tools — archive overview, search, aggregates, message lookup, and local context. The MCP process does not sync Telegram, download files, or modify the index.

Installation and launch

Install the MCP SDK and test dependencies into the engine environment:

.venv/bin/pip install -e ".[mcp,test]"

Launch via the entrypoint:

.venv/bin/letopis-mcp

Alternative form — .venv/bin/python -m tgarchive server. Wait, actually source says .venv/bin/python -m tgarchive.mcp.server? The prompt says: "— .venv/bin/python -m tgarchive.mcp.server." Wait check the source: "Альтернативная форма — .venv/bin/python -m tgarchive.mcp.server." Yes, keep tgarchive.mcp.server. So continue.

By default the server listens on http://127.0.0.1:8765/mcp and accepts only loopback events. For production, set a stable cursor secret and index path in the process environment, for example:

export LETOPIS_MCP_DB=/srv/letopis-data/data/index.db
export LETOPIS_MCP_CURSOR_SECRET='случайный-длинный-секрет'
.venv/bin/letopis-mcp

Environment variables

Variable

Replaced

Purpose

LETOPIS_MCP_DB

value of [general].db from config.toml, usually data/index.db

Path to the SQLite index; relative path is calculated from the project root

LETOPIS_MCP_CURSOR_SECRET

none; a temporary random secret per process

HMAC-SHA256 for opaque cursors. Required in production: without it, cursors do not survive a process restart

LETOPIS_MCP_HOST

127.0.0.1

Loopback bind address; the app rejects non-loopback addresses

LETOPIS_MCP_PORT

8765

TCP port of the Streamable HTTP endpoint

LETOPIS_MCP_LOG_LEVEL

INFO

Structured log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)

LETOPIS_MCP_MAX_CONCURRENCY

8

Max concurrent read-only DB operations

LETOPIS_MCP_QUERY_TIMEOUT_SECONDS

30.0

Deadline for the SQLite query and waiting for a concurrency slot

LETOPIS_MCP_ROLLING_CALLS_MAX

60

Max completed calls in the global rolling window

LETOPIS_MCP_ROLLING_CHARS_MAX

250000

Max characters returned in the rolling window

LETOPIS_MCP_ROLLING_WINDOW_SECONDS

600

Rolling window length in seconds

The rate limit is intentionally process-global: v1 has no OAuth and no identified principals, so this is not a per-user ACL. MCP reads these variables as process configuration and does not load .env automatically.

Connecting to ChatGPT

The recommended scheme does not publish Letopis directly to the internet:

ChatGPT ↔ OpenAI Secure MCP Tunnel ↔ tunnel-client на этом хосте
                                      ↔ 127.0.0.1:8765/mcp

Specific commands and setup steps for Secure MCP Tunnel depend on the current OpenAI workspace and current OpenAI documentation. Verify them at connection time; this repository does not make up an unverified OAuth/tunnel command.

Deployment security

The MCP process needs only data/index.db and the necessary SQLite sidecar files data/index.db-wal / data/index.db-shm. It should not have access to .env, telegram.session, archive/, media, or the manifest. Run the server as a separate Unix user with minimal rights, and perform sync and indexing as a separate process with the required write access.


🗂 Structure

репозиторий с данными/
├── config.toml              # настройки: аккаунты, транскрипция, веб-порт
├── .env                     # api_id / api_hash Telegram
├── telegram.session         # сессия аккаунта (и доп. сессии из [accounts])
├── tg -> letopis/.venv/bin/tg   # обёртка-энтрипоинт
├── data/
│   └── index.db             # SQLite + FTS5 — производный, пересобирается
└── archive/
    ├── manifest.json        # какие чаты отслеживаем, каким аккаунтом, какие медиа качаем
    └── <chat_id>/
        ├── 2025-06.jsonl    # сырые сообщения этого месяца — источник истины
        ├── 2025-07.jsonl
        ├── transcripts.jsonl   # расшифровки голосовых/кружков
        ├── media_index.jsonl   # реестр скачанных файлов
        └── media/               # сами файлы
  • JSONL — the source of truth. Files by month; sync only appends new messages and never touches old ones.

  • index.db — the derived layer. It can be deleted and rebuilt (./tg index --rebuild) at any time without data loss.

  • manifest.json — the manager. It survives index rebuilds and keeps track of which chats/topics are tracked and which media types to download for them.

This split (engine in git, open; data separate and private) allows you to freely develop and share the code without risking a leak of your conversations.


🧭 Commands

Search — the main feature for agents

Command

What it does

tg search <ₚараметры…>

Full-text search. Flags: --any (OR instead of AND), --chat, --topic, --sender, --from / --to, --media, --around N (context around matches), --count, --by-chat / --by-topic / --by-sender (aggregates), --rank (by relevance), --json, --short N, --limit N|0

tg dump --chat X [--topic N]

Chronological slice of the conversation as a whole

tg context --chat X --id N

Messages around a specific one (--before / --after / --whole-chat)

tg chats

Overview of the chats in the archive

tg topics --chat X

Topics of a forum chat

tg status

State of the archive and index

Viewers — manual mode

Command

What it does

tg web

Local web interface: chats → topic chips, infinite scroll, search with filters, jump to date, author filter (click a nickname), inline photo/video, voice player with transcription, replies that jump to thread, t.me links. Port is in config.toml [web]

tg tui

The same in terminal: / search · g date · s author · o/n older/newer · c context · m open in Telegram · f open file · Escc back · q exit

Downloader and manager

Command

What it does

tg dialogs

All account chats (✓ — already in archive)

tg download --chat <имя|id|@user>

Download chat/topics and add to tracking. Flags: --topic N, --from 2025-01, --media photo,voice|all|none

tg sync [--chat X]

Download new messages for all tracked chats

tg media --chat X --media voice

Download files for already downloaded messages

tg transcribe [--provider …]

Transcribe voice messages to text so they go into search

tg untract --chat X

Remove chat from tracking (files remain on disk)

tg meta / tg index

Update chat names / re-ندукст archive

tg login [--account name]

Authorize a Telegram session (tphone / code / 2FA)

A chat can be specified by id, alias from config.toml, part of the title, @username, or a t.me/... link. New messages are downloaded with all reactions, polls, and service events.


🎙 Voice transcription

The provider is configured in config.toml [transcription]:

| Provider | Cost | Requirements | | --- | --- | | whisper-local | free, local | faster-whisper, small model by default | | telegram | free | Telegram Premium on the account | | openai | paid (Whisper API) | OPENAI_API_KEY in `.```

Command

What it does

tg web

Local web interface: chats → topic chips, infinite scroll, search with filters, jump to date, filter by author (click a nickname), inline photo/video, voice player with transcription, replies that jump to thread, t.me links. Port is in config.toml [web]

tg tui

Same in terminal: / search · g date · s author · o/n older/newer · c context · m open in Telegram · f open file · Esc back · q exit

Downloader and manager

Command

What it does

tg dialogs

All chats of the account (✓ — already in archive)

tg download --chat <имя|id|@user>

Download a chat/topics and enable tracking. Flags: --topic N, --from 2025-01, --media photo,voice|all|none

tg sync [--chat X]

Download new messages of all tracked chats

tg media --chat X --media voice

Download files for already downloaded messages

tg transcribe [--provider …]

Transcribe voice messages to text so they appear in search

tg untrack --chat X

Stop tracking a chat (files stay on disk)

tg meta / tg index

Update chat names / re-index archive

tg login [--account name]

Authorize a Telegram session (phone / code / 2FA)

A chat can be specified as an id, an alias from config.toml, part of the name, @username, or a t.me/... link. New messages are downloaded with all reactions, polls, and service events.


🎙 Voice transcription

The provider is set in config.toml [transcription]:

Provider

Cost

Requirements

whisper-local

free, local

faster-whisper, small model by default

telegram

free

Telegram Premium on the account

openai

paid (Whisper API)

OPENAI_API_KEY in .env


👥 Multiple accounts

[accounts]
default = "telegram.session"
backup  = "sessions/backup.session"

tg login --account backup authorizes a new session. The download / sync / dialogs / meta commands have the --account flag. Each chat in the manifest is tied to its own account.


🗺 Status

Stage

Status

What's included

A

✅ ready

Index, search, CLI, Claude Code integration

B

✅ ready

Downloader (download/sync, append-only), media by settings, backfill, transcription, manager (manifest.json), multiple accounts, FloodWait protection

C

✅ ready

Viewers: tg web (browser, media) and tg tui (terminal)

Next: scheduled auto-sync, image OCR, Azure Speech provider, data export.


🔒 Security

telegram.session and .env give full access to your Telegram account. Keep them in a private repository with the data, do not commit them to this repository, and never publish them anywhere.


Made so the agent remembers conversations better than you do.

F
license - not found
Not graded
quality - not tested
B
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • A
    license
    Not graded
    quality
    B
    maintenance
    An MCP server that connects to Telegram as your real user account and exposes read-only tools to read and search messages, list chats and folders, inspect group info, and download media.
    9
    MIT
  • A
    license
    A
    quality
    C
    maintenance
    A local MCP server that enables full-text and semantic search over your own Telegram chats using your personal MTProto login, with everything running locally.
    7
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    Read-only MCP server for Telegram chats and channels that provides digest summaries, message search, and action items.
    27
    MIT

View all related MCP servers

Related MCP Connectors

  • Agent-native MCP server over the public saagarpatel.dev corpus. Read-only, stateless.

  • Search your AI chat history (ChatGPT, Claude, Codex) from any MCP client. Remote, private, read-only

  • Telegram bridge for your MCP-compatible agent. Bidirectional, no LLM in our stack.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Toligrim/Letopis-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server