better-tg-cli 0.39.0 → 0.39.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.es.md CHANGED
@@ -119,7 +119,8 @@ La skill y el servidor MCP juntos, en una sola instalación:
119
119
  /plugin install better-tg-cli@better-tg-cli
120
120
  ```
121
121
 
122
- Ejecuta el servidor MCP mediante `npx`, así que basta con Node 20+. Inicia sesión una vez con
122
+ Ejecuta su propia copia del servidor MCP, incluida en el plugin, así que basta con Node 20+ y no se
123
+ descarga nada al instalar. Inicia sesión una vez con
123
124
  `telegram auth --qr` (o `npx better-tg-cli auth --qr`) en un terminal.
124
125
 
125
126
  ### Plugin para Codex
@@ -196,8 +197,10 @@ La sesión se guarda en el Keychain de macOS (servicio `tg-cli`) o en 1Password
196
197
  `--op-vault <vault>`. `telegram logout` la elimina. En Linux va al Secret Service (GNOME Keyring,
197
198
  KWallet, KeePassXC) a través de `secret-tool`, que necesita el paquete `libsecret-tools`. Una sesión
198
199
  ya guardada en el archivo de configuración se traslada allí automáticamente. Sin ningún almacén de
199
- secretos, la sesión se guarda en `~/.config/tg/config.json5` (modo 0600) y los comandos de escritura
200
- siguen desactivados. En Linux, `write-access on` se confirma en un prompt del terminal. En Windows los
200
+ secretos, la sesión se guarda en `~/.config/tg/config.json5` (modo 0600). En Linux sin un Secret
201
+ Service que funcione (sin `secret-tool` o sin bus de sesión, como en los ordenadores de agentes en la
202
+ nube) el modo de escritura también se guarda en un archivo normal del perfil, que protege de errores
203
+ pero no de un agente que pueda editar archivos. En Linux, `write-access on` se confirma en un prompt del terminal. En Windows los
201
204
  secretos se guardan en `%APPDATA%\tg\secrets.dpapi`, cifrados con DPAPI para tu usuario de Windows
202
205
  (solo tú puedes descifrarlos en esta máquina), y `write-access on` pregunta en una ventana Sí/No
203
206
  cuando no hay terminal.
@@ -254,8 +257,7 @@ claude mcp add telegram -- telegram mcp # Claude Code (o usa el plugin
254
257
 
255
258
  Usa la forma JSON para Claude Desktop (`claude_desktop_config.json`) o Cursor (`.cursor/mcp.json`).
256
259
  Puede que las apps con interfaz gráfica no vean el PATH de tu shell, así que indica la ruta completa
257
- que devuelve `which telegram`. Sin una instalación global, ejecútalo mediante npx, que es también lo
258
- que hace el plugin de Claude Code:
260
+ que devuelve `which telegram`. Sin una instalación global, ejecútalo mediante npx:
259
261
 
260
262
  ```json
261
263
  { "mcpServers": { "telegram": { "command": "npx", "args": ["-y", "better-tg-cli@latest", "mcp"] } } }
@@ -282,12 +284,120 @@ telegram mcp --http --read-only # escucha en 127.0.0.1:8787; quita -
282
284
  tailscale funnel --bg 8787 # o: cloudflared tunnel --url http://127.0.0.1:8787
283
285
  ```
284
286
 
285
- Mantén el servidor y el túnel en un terminal o en tmux. Después añade un conector en Grok Bot con la
287
+ Mantén el servidor y el túnel en un terminal o en tmux, o ejecuta el servidor como servicio en
288
+ segundo plano (abajo). Después añade un conector en Grok Bot con la
286
289
  URL del túnel más `/mcp` (por ejemplo `https://<machine>.<tailnet>.ts.net/mcp`) y la cabecera
287
290
  `Authorization: Bearer <token>`. `tailscale funnel` da una URL estable, pero antes hay que permitirlo
288
291
  para tu tailnet. Un túnel rápido de `cloudflared` obtiene una URL nueva en cada arranque. Lee antes
289
292
  "Remote MCP over HTTP" en [SECURITY.md](SECURITY.md).
290
293
 
294
+ #### El servidor como servicio en segundo plano
295
+
296
+ Un servicio arranca el servidor por sí solo y lo vuelve a levantar tras un fallo. En macOS el
297
+ LaunchAgent de abajo arranca al iniciar sesión y funciona mientras sigues con la sesión iniciada. En
298
+ Linux la unidad de usuario también puede arrancar al encender, sin iniciar sesión (ver linger
299
+ abajo). Ninguno de los archivos de abajo guarda secretos: la sesión y el token bearer siguen en el Keychain o en el
300
+ Secret Service, y el servidor los lee al arrancar. El túnel también tiene que seguir activo:
301
+ `tailscale funnel --bg` sigue funcionando por sí solo, un túnel rápido de `cloudflared` no.
302
+
303
+ Ambos archivos necesitan las rutas que imprimen `command -v telegram` y, tras instalar con npm,
304
+ `command -v node`. La versión npm de `telegram` es un script de Node, y un servicio arranca con un
305
+ `PATH` corto sin los directorios de Homebrew ni de nvm, así que sin el `PATH` correcto termina con
306
+ `env: node: No such file or directory`.
307
+
308
+ **macOS (launchd).** Guarda esto como `~/Library/LaunchAgents/com.better-tg-cli.mcp.plist`, con tu
309
+ ruta a `telegram` en `ProgramArguments`, el directorio de `node` en `PATH` y tu nombre de usuario
310
+ (`id -un`) en lugar de `you` (launchd no expande ni `~` ni `$HOME`):
311
+
312
+ ```xml
313
+ <?xml version="1.0" encoding="UTF-8"?>
314
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
315
+ <plist version="1.0">
316
+ <dict>
317
+ <key>Label</key>
318
+ <string>com.better-tg-cli.mcp</string>
319
+ <key>ProgramArguments</key>
320
+ <array>
321
+ <string>/opt/homebrew/bin/telegram</string>
322
+ <string>mcp</string>
323
+ <string>--http</string>
324
+ <string>--read-only</string>
325
+ </array>
326
+ <key>EnvironmentVariables</key>
327
+ <dict>
328
+ <key>PATH</key>
329
+ <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
330
+ <key>TG_NO_UPDATE_CHECK</key>
331
+ <string>1</string>
332
+ </dict>
333
+ <key>RunAtLoad</key>
334
+ <true/>
335
+ <key>KeepAlive</key>
336
+ <dict>
337
+ <key>SuccessfulExit</key>
338
+ <false/>
339
+ </dict>
340
+ <key>StandardOutPath</key>
341
+ <string>/Users/you/Library/Logs/better-tg-cli-mcp.log</string>
342
+ <key>StandardErrorPath</key>
343
+ <string>/Users/you/Library/Logs/better-tg-cli-mcp.log</string>
344
+ </dict>
345
+ </plist>
346
+ ```
347
+
348
+ ```bash
349
+ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.better-tg-cli.mcp.plist
350
+ launchctl print gui/$(id -u)/com.better-tg-cli.mcp | grep -E 'state|last exit'
351
+ launchctl kickstart -k gui/$(id -u)/com.better-tg-cli.mcp # reiniciar
352
+ launchctl bootout gui/$(id -u)/com.better-tg-cli.mcp # detener y descargar
353
+ ```
354
+
355
+ `KeepAlive` con `SuccessfulExit` false reinicia el servidor cuando falla o lo matan. Si macOS pide
356
+ acceso al Keychain en el primer arranque, permítelo.
357
+
358
+ **Linux (unidad de usuario de systemd).** Guarda esto como
359
+ `~/.config/systemd/user/better-tg-cli-mcp.service`, con los directorios de `telegram` y `node` en
360
+ `PATH`:
361
+
362
+ ```ini
363
+ [Unit]
364
+ Description=Better-TG-CLI MCP server over HTTP
365
+ After=network-online.target
366
+
367
+ [Service]
368
+ Environment=PATH=/usr/local/bin:/usr/bin:/bin
369
+ Environment=TG_NO_UPDATE_CHECK=1
370
+ ExecStart=/usr/bin/env telegram mcp --http --read-only
371
+ Restart=on-failure
372
+ RestartSec=5
373
+
374
+ [Install]
375
+ WantedBy=default.target
376
+ ```
377
+
378
+ ```bash
379
+ systemctl --user daemon-reload
380
+ systemctl --user enable --now better-tg-cli-mcp.service
381
+ systemctl --user status better-tg-cli-mcp.service
382
+ journalctl --user -u better-tg-cli-mcp.service -f
383
+ ```
384
+
385
+ La unidad funciona mientras tienes la sesión iniciada. `sudo loginctl enable-linger "$USER"` la
386
+ arranca al encender y la mantiene tras cerrar sesión, pero no desbloquea el llavero. Si el servicio
387
+ no tiene Secret Service o está bloqueado, el servidor termina con "The HTTP server needs a secret
388
+ store for its token" y systemd lo vuelve a arrancar 5 segundos después. Para ver qué almacén de
389
+ secretos encuentra el servicio, ejecuta `telegram check` con el entorno de la unidad.
390
+
391
+ Si el servicio no tiene Secret Service (por ejemplo, en un servidor sin escritorio), usa el almacén
392
+ de 1Password. Inicia sesión una vez con `telegram auth --op-vault <vault>` en el mismo perfil, añade
393
+ el directorio de `op` al `PATH` de la unidad y guarda `OP_SERVICE_ACCOUNT_TOKEN=…` en un archivo que
394
+ solo tú puedas leer (modo 0600), cargado con `EnvironmentFile=%h/.config/tg/mcp.env` en
395
+ `[Service]`. Ese token es un secreto, así que no va en la unidad.
396
+
397
+ Tras `telegram mcp --rotate-token`, reinicia el servicio (`launchctl kickstart -k …` o
398
+ `systemctl --user restart better-tg-cli-mcp`): hasta entonces el servidor en marcha acepta el token
399
+ antiguo.
400
+
291
401
  ## FAQ
292
402
 
293
403
  **¿Telegram baneará mi cuenta?**
package/README.md CHANGED
@@ -117,7 +117,8 @@ The skill and the MCP server together, in one install:
117
117
  /plugin install better-tg-cli@better-tg-cli
118
118
  ```
119
119
 
120
- It runs the MCP server through `npx`, so Node 20+ is enough. Log in once with `telegram auth --qr`
120
+ It runs its own copy of the MCP server, included in the plugin, so Node 20+ is enough and nothing
121
+ is downloaded at install time. Log in once with `telegram auth --qr`
121
122
  (or `npx better-tg-cli auth --qr`) in a terminal.
122
123
 
123
124
  ### Codex plugin
@@ -189,8 +190,10 @@ The session is stored in the macOS Keychain (service `tg-cli`), or in 1Password
189
190
  `--op-vault <vault>`. `telegram logout` removes it. On Linux it goes to the Secret Service (GNOME
190
191
  Keyring, KWallet, KeePassXC) through `secret-tool`, which needs the `libsecret-tools` package. A
191
192
  session already saved in the config file moves there automatically. Without any secret store, the
192
- session is kept in `~/.config/tg/config.json5` (mode 0600) and write commands stay disabled.
193
- On Linux, `write-access on` is confirmed at a terminal prompt. On Windows the secrets live in
193
+ session is kept in `~/.config/tg/config.json5` (mode 0600). On Linux without a working Secret
194
+ Service (no `secret-tool` or no session bus, as on cloud agent computers) the write mode is then kept
195
+ in a plain file in the profile too, which guards against mistakes, not against an agent that can
196
+ edit files. On Linux, `write-access on` is confirmed at a terminal prompt. On Windows the secrets live in
194
197
  `%APPDATA%\tg\secrets.dpapi`, encrypted with DPAPI for your Windows user (only you on this machine
195
198
  can decrypt it), and `write-access on` asks in a Yes/No window when there's no terminal.
196
199
 
@@ -275,7 +278,7 @@ claude mcp add telegram -- telegram mcp # Claude Code (or use the plugi
275
278
 
276
279
  Use the JSON form for Claude Desktop (`claude_desktop_config.json`) or Cursor (`.cursor/mcp.json`).
277
280
  GUI apps may not see your shell PATH, so give the full path from `which telegram`. Without a
278
- global install, run it through npx, which is also what the Claude Code plugin does:
281
+ global install, run it through npx:
279
282
 
280
283
  ```json
281
284
  { "mcpServers": { "telegram": { "command": "npx", "args": ["-y", "better-tg-cli@latest", "mcp"] } } }
@@ -302,12 +305,117 @@ telegram mcp --http --read-only # listens on 127.0.0.1:8787; drop --
302
305
  tailscale funnel --bg 8787 # or: cloudflared tunnel --url http://127.0.0.1:8787
303
306
  ```
304
307
 
305
- Keep the server and the tunnel in a terminal or tmux. Then add a connector in Grok Bot with the
308
+ Keep the server and the tunnel in a terminal or tmux, or run the server as a background service
309
+ (below). Then add a connector in Grok Bot with the
306
310
  tunnel URL plus `/mcp` (for example `https://<machine>.<tailnet>.ts.net/mcp`) and the header
307
311
  `Authorization: Bearer <token>`. `tailscale funnel` gives a stable URL, but it has to be allowed
308
312
  for your tailnet first. A `cloudflared` quick tunnel gets a new URL on every start. Read "Remote
309
313
  MCP over HTTP" in [SECURITY.md](SECURITY.md) first.
310
314
 
315
+ #### Running the server as a background service
316
+
317
+ A service starts the server on its own and brings it back after a crash. On macOS the LaunchAgent
318
+ below starts when you log in and runs while you stay logged in. On Linux the user unit can also
319
+ start at boot without a login (see linger below). Neither file below holds a secret: the session and the bearer token stay in the Keychain or the Secret Service, and the server
320
+ reads them when it starts. The tunnel has to stay up as well: `tailscale funnel --bg` keeps running
321
+ by itself, a `cloudflared` quick tunnel does not.
322
+
323
+ Both files need the paths that `command -v telegram` and, after an npm install, `command -v node`
324
+ print. The npm build of `telegram` is a Node script, and a service starts with a short `PATH`
325
+ without Homebrew's or nvm's directories, so without the right `PATH` it exits with
326
+ `env: node: No such file or directory`.
327
+
328
+ **macOS (launchd).** Save this as `~/Library/LaunchAgents/com.better-tg-cli.mcp.plist`, with your
329
+ path to `telegram` in `ProgramArguments`, the directory of `node` in `PATH`, and your user name
330
+ (`id -un`) where `you` is (launchd expands neither `~` nor `$HOME`):
331
+
332
+ ```xml
333
+ <?xml version="1.0" encoding="UTF-8"?>
334
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
335
+ <plist version="1.0">
336
+ <dict>
337
+ <key>Label</key>
338
+ <string>com.better-tg-cli.mcp</string>
339
+ <key>ProgramArguments</key>
340
+ <array>
341
+ <string>/opt/homebrew/bin/telegram</string>
342
+ <string>mcp</string>
343
+ <string>--http</string>
344
+ <string>--read-only</string>
345
+ </array>
346
+ <key>EnvironmentVariables</key>
347
+ <dict>
348
+ <key>PATH</key>
349
+ <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
350
+ <key>TG_NO_UPDATE_CHECK</key>
351
+ <string>1</string>
352
+ </dict>
353
+ <key>RunAtLoad</key>
354
+ <true/>
355
+ <key>KeepAlive</key>
356
+ <dict>
357
+ <key>SuccessfulExit</key>
358
+ <false/>
359
+ </dict>
360
+ <key>StandardOutPath</key>
361
+ <string>/Users/you/Library/Logs/better-tg-cli-mcp.log</string>
362
+ <key>StandardErrorPath</key>
363
+ <string>/Users/you/Library/Logs/better-tg-cli-mcp.log</string>
364
+ </dict>
365
+ </plist>
366
+ ```
367
+
368
+ ```bash
369
+ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.better-tg-cli.mcp.plist
370
+ launchctl print gui/$(id -u)/com.better-tg-cli.mcp | grep -E 'state|last exit'
371
+ launchctl kickstart -k gui/$(id -u)/com.better-tg-cli.mcp # restart
372
+ launchctl bootout gui/$(id -u)/com.better-tg-cli.mcp # stop and unload
373
+ ```
374
+
375
+ `KeepAlive` with `SuccessfulExit` false restarts the server whenever it fails or is killed. If macOS
376
+ asks for Keychain access on the first start, allow it.
377
+
378
+ **Linux (systemd user unit).** Save this as `~/.config/systemd/user/better-tg-cli-mcp.service`, with
379
+ the directories of `telegram` and `node` in `PATH`:
380
+
381
+ ```ini
382
+ [Unit]
383
+ Description=Better-TG-CLI MCP server over HTTP
384
+ After=network-online.target
385
+
386
+ [Service]
387
+ Environment=PATH=/usr/local/bin:/usr/bin:/bin
388
+ Environment=TG_NO_UPDATE_CHECK=1
389
+ ExecStart=/usr/bin/env telegram mcp --http --read-only
390
+ Restart=on-failure
391
+ RestartSec=5
392
+
393
+ [Install]
394
+ WantedBy=default.target
395
+ ```
396
+
397
+ ```bash
398
+ systemctl --user daemon-reload
399
+ systemctl --user enable --now better-tg-cli-mcp.service
400
+ systemctl --user status better-tg-cli-mcp.service
401
+ journalctl --user -u better-tg-cli-mcp.service -f
402
+ ```
403
+
404
+ The unit runs while you are logged in. `sudo loginctl enable-linger "$USER"` starts it at boot and
405
+ keeps it after you log out, but it does not unlock the keyring. If the Secret Service is missing or
406
+ locked for the service, the server exits with "The HTTP server needs a secret store for its token",
407
+ and systemd starts it again 5 seconds later. To see which secret store the service finds, run
408
+ `telegram check` with the unit's environment.
409
+
410
+ Where the service has no Secret Service (a headless server, say), use the 1Password store. Log in
411
+ once with `telegram auth --op-vault <vault>` under the same profile, put the directory of `op` in
412
+ the unit's `PATH`, and keep `OP_SERVICE_ACCOUNT_TOKEN=…` in a file only you can read (mode 0600),
413
+ loaded with `EnvironmentFile=%h/.config/tg/mcp.env` in `[Service]`. That token is a secret, so it
414
+ stays out of the unit file.
415
+
416
+ After `telegram mcp --rotate-token`, restart the service (`launchctl kickstart -k …` or
417
+ `systemctl --user restart better-tg-cli-mcp`): the running server keeps the old token until then.
418
+
311
419
  ## FAQ
312
420
 
313
421
  **Will Telegram ban my account?**
package/README.ru.md CHANGED
@@ -116,7 +116,8 @@ scoop install better-tg-cli
116
116
  /plugin install better-tg-cli@better-tg-cli
117
117
  ```
118
118
 
119
- MCP-сервер запускается через `npx`, так что хватит Node 20+. Один раз войдите в терминале:
119
+ Плагин запускает собственную копию MCP-сервера, которая лежит в нём самом, так что хватит Node 20+,
120
+ и при установке ничего не скачивается. Один раз войдите в терминале:
120
121
  `telegram auth --qr` (или `npx better-tg-cli auth --qr`).
121
122
 
122
123
  ### Плагин для Codex
@@ -188,7 +189,9 @@ npx skills add TheVilfer/better-tg-cli -g -a claude-code -a codex -y
188
189
  `telegram logout` её удаляет. На Linux сессия хранится в Secret Service (GNOME Keyring, KWallet,
189
190
  KeePassXC) через `secret-tool`, для этого нужен пакет `libsecret-tools`. Сессия, которая уже лежит
190
191
  в конфиге, переедет туда сама. Если хранилища секретов нет, сессия лежит в
191
- `~/.config/tg/config.json5` (права 0600), а запись остаётся выключенной. На Linux
192
+ `~/.config/tg/config.json5` (права 0600). На Linux без работающего Secret Service (нет `secret-tool`
193
+ или сессионной шины, как на облачных компьютерах агентов) режим записи тогда тоже хранится в
194
+ обычном файле профиля: это защита от ошибок, но не от агента, который может править файлы. На Linux
192
195
  `write-access on` подтверждается в терминале. На Windows секреты лежат в
193
196
  `%APPDATA%\tg\secrets.dpapi`, зашифрованные DPAPI для вашего пользователя Windows (расшифровать их
194
197
  можете только вы на этой машине), а `write-access on` без терминала спрашивает в окне «Да/Нет».
@@ -244,8 +247,7 @@ claude mcp add telegram -- telegram mcp # Claude Code (или плаг
244
247
 
245
248
  JSON-вариант подходит для Claude Desktop (`claude_desktop_config.json`) и Cursor
246
249
  (`.cursor/mcp.json`). GUI-приложения могут не видеть ваш PATH, поэтому укажите полный путь из
247
- `which telegram`. Без глобальной установки сервер запускается через npx, как и в плагине
248
- Claude Code:
250
+ `which telegram`. Без глобальной установки сервер запускается через npx:
249
251
 
250
252
  ```json
251
253
  { "mcpServers": { "telegram": { "command": "npx", "args": ["-y", "better-tg-cli@latest", "mcp"] } } }
@@ -272,12 +274,117 @@ telegram mcp --http --read-only # слушает 127.0.0.1:8787; б
272
274
  tailscale funnel --bg 8787 # или: cloudflared tunnel --url http://127.0.0.1:8787
273
275
  ```
274
276
 
275
- Держите сервер и туннель в терминале или в tmux. Затем добавьте в Grok Bot коннектор: адрес
277
+ Держите сервер и туннель в терминале или в tmux либо запустите сервер как фоновую службу (ниже).
278
+ Затем добавьте в Grok Bot коннектор: адрес
276
279
  туннеля плюс `/mcp` (например, `https://<машина>.<tailnet>.ts.net/mcp`) и заголовок
277
280
  `Authorization: Bearer <токен>`. У `tailscale funnel` адрес постоянный, но сначала Funnel надо
278
281
  разрешить для вашего tailnet. Быстрый туннель `cloudflared` при каждом запуске получает новый
279
282
  адрес. Сначала прочитайте раздел «Remote MCP over HTTP» в [SECURITY.md](SECURITY.md).
280
283
 
284
+ #### Сервер как фоновая служба
285
+
286
+ Служба запускает сервер сама и поднимает его заново после сбоя. На macOS LaunchAgent ниже
287
+ стартует при входе в систему и работает, пока вы в ней. На Linux пользовательский юнит может
288
+ стартовать и при загрузке, без входа (см. linger ниже). Ни один из файлов ниже не хранит секретов: сессия и bearer-токен остаются в Keychain или Secret Service, и сервер
289
+ читает их при запуске. Туннель тоже должен работать постоянно: `tailscale funnel --bg` живёт сам по
290
+ себе, а быстрый туннель `cloudflared` — нет.
291
+
292
+ Обоим файлам нужны пути, которые печатают `command -v telegram` и, если вы ставили через npm,
293
+ `command -v node`. npm-сборка `telegram` — это скрипт Node, а служба стартует с коротким `PATH`, где
294
+ нет каталогов Homebrew и nvm. Без правильного `PATH` она завершится с
295
+ `env: node: No such file or directory`.
296
+
297
+ **macOS (launchd).** Сохраните это как `~/Library/LaunchAgents/com.better-tg-cli.mcp.plist`. В
298
+ `ProgramArguments` укажите свой путь к `telegram`, в `PATH` — каталог `node`, а вместо `you` — имя
299
+ пользователя (`id -un`): launchd не раскрывает ни `~`, ни `$HOME`.
300
+
301
+ ```xml
302
+ <?xml version="1.0" encoding="UTF-8"?>
303
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
304
+ <plist version="1.0">
305
+ <dict>
306
+ <key>Label</key>
307
+ <string>com.better-tg-cli.mcp</string>
308
+ <key>ProgramArguments</key>
309
+ <array>
310
+ <string>/opt/homebrew/bin/telegram</string>
311
+ <string>mcp</string>
312
+ <string>--http</string>
313
+ <string>--read-only</string>
314
+ </array>
315
+ <key>EnvironmentVariables</key>
316
+ <dict>
317
+ <key>PATH</key>
318
+ <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
319
+ <key>TG_NO_UPDATE_CHECK</key>
320
+ <string>1</string>
321
+ </dict>
322
+ <key>RunAtLoad</key>
323
+ <true/>
324
+ <key>KeepAlive</key>
325
+ <dict>
326
+ <key>SuccessfulExit</key>
327
+ <false/>
328
+ </dict>
329
+ <key>StandardOutPath</key>
330
+ <string>/Users/you/Library/Logs/better-tg-cli-mcp.log</string>
331
+ <key>StandardErrorPath</key>
332
+ <string>/Users/you/Library/Logs/better-tg-cli-mcp.log</string>
333
+ </dict>
334
+ </plist>
335
+ ```
336
+
337
+ ```bash
338
+ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.better-tg-cli.mcp.plist
339
+ launchctl print gui/$(id -u)/com.better-tg-cli.mcp | grep -E 'state|last exit'
340
+ launchctl kickstart -k gui/$(id -u)/com.better-tg-cli.mcp # перезапуск
341
+ launchctl bootout gui/$(id -u)/com.better-tg-cli.mcp # остановить и выгрузить
342
+ ```
343
+
344
+ `KeepAlive` с `SuccessfulExit` false перезапускает сервер, когда тот падает или его убивают. Если при
345
+ первом запуске macOS спросит доступ к Keychain, разрешите.
346
+
347
+ **Linux (пользовательский юнит systemd).** Сохраните это как
348
+ `~/.config/systemd/user/better-tg-cli-mcp.service`, указав в `PATH` каталоги `telegram` и `node`:
349
+
350
+ ```ini
351
+ [Unit]
352
+ Description=Better-TG-CLI MCP server over HTTP
353
+ After=network-online.target
354
+
355
+ [Service]
356
+ Environment=PATH=/usr/local/bin:/usr/bin:/bin
357
+ Environment=TG_NO_UPDATE_CHECK=1
358
+ ExecStart=/usr/bin/env telegram mcp --http --read-only
359
+ Restart=on-failure
360
+ RestartSec=5
361
+
362
+ [Install]
363
+ WantedBy=default.target
364
+ ```
365
+
366
+ ```bash
367
+ systemctl --user daemon-reload
368
+ systemctl --user enable --now better-tg-cli-mcp.service
369
+ systemctl --user status better-tg-cli-mcp.service
370
+ journalctl --user -u better-tg-cli-mcp.service -f
371
+ ```
372
+
373
+ Юнит работает, пока вы вошли в систему. `sudo loginctl enable-linger "$USER"` запускает его при
374
+ загрузке и оставляет после выхода, но связку ключей не разблокирует. Если Secret Service для службы
375
+ нет или он заблокирован, сервер завершается с «The HTTP server needs a secret store for its token»,
376
+ и systemd запускает его снова через 5 секунд. Чтобы увидеть, какое хранилище находит служба,
377
+ выполните `telegram check` с окружением юнита.
378
+
379
+ Если у службы нет Secret Service (например, на сервере без рабочего стола), используйте хранилище
380
+ 1Password. Один раз войдите с `telegram auth --op-vault <vault>` в том же профиле, добавьте каталог
381
+ `op` в `PATH` юнита, а `OP_SERVICE_ACCOUNT_TOKEN=…` держите в файле, доступном только вам (права
382
+ 0600), и подключите его строкой `EnvironmentFile=%h/.config/tg/mcp.env` в `[Service]`. Этот токен —
383
+ секрет, поэтому в самом юните его нет.
384
+
385
+ После `telegram mcp --rotate-token` перезапустите службу (`launchctl kickstart -k …` или
386
+ `systemctl --user restart better-tg-cli-mcp`): до этого работающий сервер принимает старый токен.
387
+
281
388
  ## FAQ
282
389
 
283
390
  **Не забанит ли Telegram мой аккаунт?**