migration
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
# Gmail OAuth credentials (Desktop app OAuth recommended)
|
||||
GOOGLE_CLIENT_ID=
|
||||
GOOGLE_CLIENT_SECRET=
|
||||
GOOGLE_REFRESH_TOKEN=
|
||||
|
||||
# Mailbox to access. Use me to match authenticated account.
|
||||
GMAIL_USER=me
|
||||
|
||||
# Comma-separated allowlist of recipient addresses.
|
||||
# Only emails where To/Cc/Bcc contains one of these will be returned.
|
||||
GMAIL_TO_ALLOWLIST=alerts@example.com,ops@example.com
|
||||
|
||||
# Optional default result count for list_messages
|
||||
GMAIL_DEFAULT_MAX_RESULTS=20
|
||||
|
||||
# Telegram bot credentials (single bot + single chat)
|
||||
TELEGRAM_BOT_TOKEN=
|
||||
TELEGRAM_CHAT_ID=
|
||||
|
||||
# Optional Telegram server tuning
|
||||
TELEGRAM_POLLING_INTERVAL_MS=1000
|
||||
TELEGRAM_REQUEST_TTL_SECONDS=600
|
||||
@@ -0,0 +1,6 @@
|
||||
.venv
|
||||
.env
|
||||
screenshots
|
||||
__pycache__
|
||||
openacp
|
||||
node_modules
|
||||
@@ -0,0 +1,11 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies first for better build cache usage.
|
||||
COPY package*.json ./
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
COPY src ./src
|
||||
|
||||
CMD ["node", "src/index.js"]
|
||||
@@ -0,0 +1,11 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies first for better build cache usage.
|
||||
COPY package*.json ./
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
COPY src ./src
|
||||
|
||||
CMD ["node", "src/telegram.js"]
|
||||
@@ -0,0 +1,158 @@
|
||||
# MCP Servers: Gmail + Telegram
|
||||
|
||||
This repository contains two HTTP MCP servers:
|
||||
|
||||
- Gmail MCP server in `src/index.js`
|
||||
- Telegram MCP server in `src/telegram.js`
|
||||
|
||||
Both expose MCP over Streamable HTTP at `MCP_PATH` (default `/mcp`) and include `/health` endpoint.
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
cd gmail-mcp-server
|
||||
npm install
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
## Gmail server
|
||||
|
||||
Run locally:
|
||||
|
||||
```bash
|
||||
node src/index.js
|
||||
```
|
||||
|
||||
Required env:
|
||||
|
||||
- `GOOGLE_CLIENT_ID`
|
||||
- `GOOGLE_CLIENT_SECRET`
|
||||
- `GOOGLE_REFRESH_TOKEN`
|
||||
- `GMAIL_TO_ALLOWLIST`
|
||||
|
||||
Tools:
|
||||
|
||||
- `list_messages`
|
||||
- `get_message`
|
||||
|
||||
Security behavior:
|
||||
|
||||
- Query is automatically constrained with allowlist recipients.
|
||||
- Returned messages are post-filtered against message headers.
|
||||
- `get_message` denies access if recipients are outside allowlist.
|
||||
|
||||
## Telegram server
|
||||
|
||||
Run locally:
|
||||
|
||||
```bash
|
||||
node src/telegram.js
|
||||
```
|
||||
|
||||
Required env:
|
||||
|
||||
- `TELEGRAM_BOT_TOKEN`
|
||||
- `TELEGRAM_CHAT_ID`
|
||||
|
||||
Optional env:
|
||||
|
||||
- `TELEGRAM_POLLING_INTERVAL_MS` (default `1000`)
|
||||
- `TELEGRAM_REQUEST_TTL_SECONDS` (default `600`)
|
||||
- `HTTP_HOST` (default `127.0.0.1`)
|
||||
- `PORT` (default `3000`)
|
||||
- `MCP_PATH` (default `/mcp`)
|
||||
- `ENV_FILE` (default `/run/secrets/telegram-secrets`)
|
||||
|
||||
Telegram behavior:
|
||||
|
||||
- Configured for one bot and one chat room.
|
||||
- Sends text messages with optional image by URL or local file path.
|
||||
- Sends inline callback buttons.
|
||||
- Receives and stores button click responses.
|
||||
- Supports send-and-expect-reply flow using async request IDs.
|
||||
|
||||
Telegram tools:
|
||||
|
||||
- `send_message`
|
||||
- `send_message_with_buttons`
|
||||
- `send_message_with_buttons_blocking`
|
||||
- `send_message_expect_reply`
|
||||
- `send_message_expect_reply_blocking`
|
||||
- `get_request_result`
|
||||
- `cancel_request`
|
||||
- `wait_for_request_result`
|
||||
|
||||
### Async request flow (buttons and replies)
|
||||
|
||||
1. Call `send_message_with_buttons` or `send_message_expect_reply`.
|
||||
2. Tool returns `request_id`.
|
||||
3. User clicks a button or replies in Telegram.
|
||||
4. Call `get_request_result` with `request_id` to fetch status and payload.
|
||||
5. Optional: call `cancel_request` to cancel pending request.
|
||||
|
||||
Blocking alternative:
|
||||
|
||||
- Call `wait_for_request_result` with `request_id` to block until request completes or timeout.
|
||||
- Or call `send_message_with_buttons_blocking` to send buttons and wait for a click in a single blocking tool call.
|
||||
- Or call `send_message_expect_reply_blocking` to send and wait for reply in a single blocking tool call.
|
||||
|
||||
## Docker
|
||||
|
||||
- Gmail image uses `Dockerfile`.
|
||||
- Telegram image uses `Dockerfile.telegram`.
|
||||
- Compose includes both services: `gmail-mcp-server` and `telegram-mcp-server`.
|
||||
|
||||
Validate compose:
|
||||
|
||||
```bash
|
||||
docker compose config
|
||||
```
|
||||
|
||||
## Docker secret examples
|
||||
|
||||
Gmail:
|
||||
|
||||
```bash
|
||||
docker service scale gmail_mcp_gmail-mcp-server=0
|
||||
docker service update --secret-rm gmail-secrets gmail_mcp_gmail-mcp-server
|
||||
docker secret rm gmail-secrets
|
||||
```
|
||||
|
||||
```bash
|
||||
printf \
|
||||
"GOOGLE_CLIENT_ID=\n\
|
||||
GOOGLE_CLIENT_SECRET=\n\
|
||||
GOOGLE_REFRESH_TOKEN=\n\
|
||||
GMAIL_USER=me\n\
|
||||
GMAIL_TO_ALLOWLIST=alerts@example.com,ops@example.com\n\
|
||||
GMAIL_DEFAULT_MAX_RESULTS=20\n" | \
|
||||
docker secret create gmail-secrets -
|
||||
```
|
||||
|
||||
|
||||
```bash
|
||||
docker service update --secret-add gmail-secrets gmail_mcp_gmail-mcp-server
|
||||
docker service scale gmail_mcp_gmail-mcp-server=1
|
||||
```
|
||||
|
||||
Telegram:
|
||||
|
||||
```bash
|
||||
docker service scale gmail_mcp_telegram-mcp-server=0
|
||||
docker service update --secret-rm telegram-secrets gmail_mcp_telegram-mcp-server
|
||||
docker secret rm telegram-secrets
|
||||
```
|
||||
|
||||
```bash
|
||||
printf \
|
||||
"TELEGRAM_BOT_TOKEN=\n\
|
||||
TELEGRAM_CHAT_ID=\n\
|
||||
TELEGRAM_POLLING_INTERVAL_MS=1000\n\
|
||||
TELEGRAM_REQUEST_TTL_SECONDS=600\n" | \
|
||||
docker secret create telegram-secrets -
|
||||
```
|
||||
|
||||
```bash
|
||||
docker service update --secret-add telegram-secrets gmail_mcp_telegram-mcp-server
|
||||
docker service scale gmail_mcp_telegram-mcp-server=1
|
||||
```
|
||||
@@ -0,0 +1,55 @@
|
||||
services:
|
||||
gmail-mcp-server:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.gmail
|
||||
image: registry.rudolf.keenetic.link/gmail-mcp-server:${version}
|
||||
ports:
|
||||
- "3000:3000"
|
||||
|
||||
deploy:
|
||||
placement:
|
||||
max_replicas_per_node: 1
|
||||
constraints:
|
||||
- node.hostname==odroid
|
||||
# - node.hostname==rudolf-T
|
||||
mode: replicated
|
||||
environment:
|
||||
HTTP_HOST: 0.0.0.0
|
||||
PORT: 3000
|
||||
MCP_PATH: /mcp
|
||||
secrets:
|
||||
- gmail-secrets
|
||||
|
||||
telegram-mcp-server:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.telegram
|
||||
image: registry.rudolf.keenetic.link/telegram-mcp-server:${version}
|
||||
ports:
|
||||
- "3001:3000"
|
||||
|
||||
deploy:
|
||||
placement:
|
||||
max_replicas_per_node: 1
|
||||
constraints:
|
||||
- node.hostname==odroid
|
||||
# - node.hostname==rudolf-T
|
||||
mode: replicated
|
||||
environment:
|
||||
HTTP_HOST: 0.0.0.0
|
||||
PORT: 3000
|
||||
MCP_PATH: /mcp
|
||||
ENV_FILE: /run/secrets/telegram-secrets
|
||||
secrets:
|
||||
- telegram-secrets
|
||||
|
||||
secrets:
|
||||
gmail-secrets:
|
||||
external: true
|
||||
telegram-secrets:
|
||||
external: true
|
||||
|
||||
networks:
|
||||
nginx_ingress:
|
||||
external: true
|
||||
Generated
+1851
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "gmail-mcp-server",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "MCP server for Gmail with recipient allowlist enforcement",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "node src/index.js",
|
||||
"start:telegram": "node src/telegram.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.17.4",
|
||||
"dotenv": "^17.3.1",
|
||||
"googleapis": "^173.0.0",
|
||||
"node-telegram-bot-api": "^1.1.1",
|
||||
"zod": "^3.23.8"
|
||||
}
|
||||
}
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
import dotenv from "dotenv";
|
||||
import { google } from "googleapis";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import { z } from "zod";
|
||||
|
||||
const envFilePath = process.env.ENV_FILE?.trim() || "/run/secrets/gmail-secrets";
|
||||
const envLoadResult = dotenv.config({ path: envFilePath });
|
||||
if (envLoadResult.error && envLoadResult.error.code !== "ENOENT") {
|
||||
throw envLoadResult.error;
|
||||
}
|
||||
|
||||
function requiredEnv(name) {
|
||||
const value = process.env[name];
|
||||
if (!value || !value.trim()) {
|
||||
throw new Error(`Missing required environment variable: ${name}`);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
function normalizeEmail(value) {
|
||||
return value.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function parseAllowlist(raw) {
|
||||
const values = raw
|
||||
.split(",")
|
||||
.map((s) => normalizeEmail(s))
|
||||
.filter(Boolean);
|
||||
|
||||
if (values.length === 0) {
|
||||
throw new Error("GMAIL_TO_ALLOWLIST must contain at least one email address");
|
||||
}
|
||||
|
||||
return new Set(values);
|
||||
}
|
||||
|
||||
function getHeader(headers, name) {
|
||||
const hit = headers?.find((h) => h.name?.toLowerCase() === name.toLowerCase());
|
||||
return hit?.value || "";
|
||||
}
|
||||
|
||||
function collectRecipientsFromHeaders(headers) {
|
||||
const fields = ["to", "cc", "bcc"];
|
||||
const joined = fields
|
||||
.map((field) => getHeader(headers, field))
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
|
||||
const parsed = joined.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi) || [];
|
||||
return parsed.map((addr) => normalizeEmail(addr));
|
||||
}
|
||||
|
||||
function messageHasAllowedRecipient(message, allowlist) {
|
||||
const headers = message?.payload?.headers || [];
|
||||
const recipients = collectRecipientsFromHeaders(headers);
|
||||
return recipients.some((addr) => allowlist.has(addr));
|
||||
}
|
||||
|
||||
function extractSnippet(message) {
|
||||
return {
|
||||
id: message.id,
|
||||
threadId: message.threadId,
|
||||
snippet: message.snippet || "",
|
||||
from: getHeader(message.payload?.headers || [], "from"),
|
||||
to: getHeader(message.payload?.headers || [], "to"),
|
||||
subject: getHeader(message.payload?.headers || [], "subject"),
|
||||
date: getHeader(message.payload?.headers || [], "date")
|
||||
};
|
||||
}
|
||||
|
||||
function buildQueryWithAllowlist(query, allowlist) {
|
||||
const allowQuery = Array.from(allowlist)
|
||||
.map((addr) => `to:${addr}`)
|
||||
.join(" OR ");
|
||||
const safeBase = query?.trim() ? `(${query.trim()})` : "";
|
||||
if (safeBase) {
|
||||
return `${safeBase} (${allowQuery})`;
|
||||
}
|
||||
return `(${allowQuery})`;
|
||||
}
|
||||
|
||||
function buildQuery(query) {
|
||||
return query?.trim() ? `(${query.trim()})` : "";
|
||||
}
|
||||
|
||||
async function createGmailClient() {
|
||||
const clientId = requiredEnv("GOOGLE_CLIENT_ID");
|
||||
const clientSecret = requiredEnv("GOOGLE_CLIENT_SECRET");
|
||||
const refreshToken = requiredEnv("GOOGLE_REFRESH_TOKEN");
|
||||
|
||||
const auth = new google.auth.OAuth2(clientId, clientSecret);
|
||||
auth.setCredentials({ refresh_token: refreshToken });
|
||||
|
||||
return google.gmail({ version: "v1", auth });
|
||||
}
|
||||
|
||||
function createMcpServer({ gmail, gmailUser, allowlist, defaultMaxResults }) {
|
||||
const server = new McpServer({
|
||||
name: "gmail-mcp-server",
|
||||
version: "0.1.0"
|
||||
});
|
||||
|
||||
server.tool(
|
||||
"list_messages",
|
||||
"List Gmail messages, restricted to allowed recipients in To/Cc/Bcc.",
|
||||
{
|
||||
query: z.string().optional().describe("Gmail search query, for example from:billing newer_than:7d"),
|
||||
maxResults: z.number().int().min(1).max(100).optional().describe("Maximum messages to return (1-100)")
|
||||
},
|
||||
async ({ query, maxResults }) => {
|
||||
const effectiveMax = maxResults || defaultMaxResults;
|
||||
const q = buildQueryWithAllowlist(query, allowlist);
|
||||
// const q = buildQuery(query, allowlist);
|
||||
|
||||
const list = await gmail.users.messages.list({
|
||||
userId: gmailUser,
|
||||
q,
|
||||
maxResults: effectiveMax
|
||||
});
|
||||
|
||||
const ids = list.data.messages || [];
|
||||
const expanded = await Promise.all(
|
||||
ids.map(async (m) => {
|
||||
const full = await gmail.users.messages.get({
|
||||
userId: gmailUser,
|
||||
id: m.id,
|
||||
format: "metadata",
|
||||
metadataHeaders: ["From", "To", "Cc", "Bcc", "Subject", "Date"]
|
||||
});
|
||||
return full.data;
|
||||
})
|
||||
);
|
||||
|
||||
const filtered = expanded.filter((msg) => messageHasAllowedRecipient(msg, allowlist));
|
||||
const output = filtered.map((msg) => extractSnippet(msg));
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(
|
||||
{
|
||||
count: output.length,
|
||||
allowlist: Array.from(allowlist),
|
||||
messages: output
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
server.tool(
|
||||
"get_message",
|
||||
"Get one Gmail message by ID. Access is denied unless message recipients match allowlist.",
|
||||
{
|
||||
id: z.string().min(1).describe("Gmail message ID"),
|
||||
format: z.enum(["full", "metadata", "minimal", "raw"]).optional().describe("Gmail API format")
|
||||
},
|
||||
async ({ id, format }) => {
|
||||
const message = await gmail.users.messages.get({
|
||||
userId: gmailUser,
|
||||
id,
|
||||
format: format || "full"
|
||||
});
|
||||
|
||||
if (!messageHasAllowedRecipient(message.data, allowlist)) {
|
||||
throw new Error("Access denied: message recipients are outside GMAIL_TO_ALLOWLIST");
|
||||
}
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(message.data, null, 2)
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const gmailUser = process.env.GMAIL_USER?.trim() || "me";
|
||||
const defaultMaxResults = Number(process.env.GMAIL_DEFAULT_MAX_RESULTS || "20");
|
||||
const allowlist = parseAllowlist(requiredEnv("GMAIL_TO_ALLOWLIST"));
|
||||
const host = process.env.HTTP_HOST?.trim() || "127.0.0.1";
|
||||
const port = Number(process.env.PORT || process.env.HTTP_PORT || "3000");
|
||||
const mcpPath = process.env.MCP_PATH?.trim() || "/mcp";
|
||||
const gmail = await createGmailClient();
|
||||
|
||||
const app = createMcpExpressApp({ host });
|
||||
|
||||
app.post(mcpPath, async (req, res) => {
|
||||
const server = createMcpServer({ gmail, gmailUser, allowlist, defaultMaxResults });
|
||||
|
||||
try {
|
||||
const transport = new StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined
|
||||
});
|
||||
|
||||
await server.connect(transport);
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
|
||||
res.on("close", () => {
|
||||
transport.close().catch(() => {});
|
||||
server.close().catch(() => {});
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error handling MCP request:", error);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({
|
||||
jsonrpc: "2.0",
|
||||
error: {
|
||||
code: -32603,
|
||||
message: "Internal server error"
|
||||
},
|
||||
id: null
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
app.get("/health", (_req, res) => {
|
||||
res.json({ ok: true, service: "gmail-mcp-server" });
|
||||
});
|
||||
|
||||
const httpServer = app.listen(port, host, () => {
|
||||
console.log(`Gmail MCP Streamable HTTP server listening at http://${host}:${port}${mcpPath}`);
|
||||
});
|
||||
|
||||
const shutdown = () => {
|
||||
httpServer.close(() => {
|
||||
process.exit(0);
|
||||
});
|
||||
};
|
||||
|
||||
process.on("SIGINT", shutdown);
|
||||
process.on("SIGTERM", shutdown);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
+778
@@ -0,0 +1,778 @@
|
||||
import dotenv from "dotenv";
|
||||
import fs from "fs/promises";
|
||||
import { randomUUID } from "crypto";
|
||||
import TelegramBot from "node-telegram-bot-api";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import { z } from "zod";
|
||||
|
||||
const envFilePath = process.env.ENV_FILE?.trim() || "/run/secrets/telegram-secrets";
|
||||
const envLoadResult = dotenv.config({ path: envFilePath });
|
||||
if (envLoadResult.error && envLoadResult.error.code !== "ENOENT") {
|
||||
throw envLoadResult.error;
|
||||
}
|
||||
|
||||
function requiredEnv(name) {
|
||||
const value = process.env[name];
|
||||
if (!value || !value.trim()) {
|
||||
throw new Error(`Missing required environment variable: ${name}`);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
function toSafeString(value) {
|
||||
if (value === undefined || value === null) {
|
||||
return "";
|
||||
}
|
||||
return String(value).trim();
|
||||
}
|
||||
|
||||
function nowMs() {
|
||||
return Date.now();
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
||||
|
||||
function createRequestStore({ ttlSeconds }) {
|
||||
const requests = new Map();
|
||||
const buttonWaitByMessageId = new Map();
|
||||
const replyWaitByMessageId = new Map();
|
||||
|
||||
function addIndex(map, messageId, requestId) {
|
||||
const key = toSafeString(messageId);
|
||||
const existing = map.get(key) || [];
|
||||
existing.push(requestId);
|
||||
map.set(key, existing);
|
||||
}
|
||||
|
||||
function removeIndex(map, messageId, requestId) {
|
||||
const key = toSafeString(messageId);
|
||||
const existing = map.get(key) || [];
|
||||
const next = existing.filter((id) => id !== requestId);
|
||||
if (next.length > 0) {
|
||||
map.set(key, next);
|
||||
} else {
|
||||
map.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
function removeIndexes(entry) {
|
||||
if (entry.type === "button_wait") {
|
||||
removeIndex(buttonWaitByMessageId, entry.messageId, entry.id);
|
||||
}
|
||||
if (entry.type === "reply_wait") {
|
||||
removeIndex(replyWaitByMessageId, entry.messageId, entry.id);
|
||||
}
|
||||
}
|
||||
|
||||
function getEntryOrThrow(requestId) {
|
||||
const entry = requests.get(requestId);
|
||||
if (!entry) {
|
||||
throw new Error("Unknown request_id");
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
function markExpiredIfNeeded(entry) {
|
||||
if (entry.status === "pending" && entry.expiresAt <= nowMs()) {
|
||||
entry.status = "expired";
|
||||
entry.completedAt = nowMs();
|
||||
entry.error = "Request timed out before a matching Telegram update arrived";
|
||||
removeIndexes(entry);
|
||||
}
|
||||
}
|
||||
|
||||
function getPendingByMessageId(map, messageId) {
|
||||
const ids = map.get(toSafeString(messageId)) || [];
|
||||
const pending = ids
|
||||
.map((id) => requests.get(id))
|
||||
.filter((entry) => entry && entry.status === "pending");
|
||||
if (pending.length === 0) {
|
||||
return null;
|
||||
}
|
||||
pending.sort((a, b) => a.createdAt - b.createdAt);
|
||||
return pending[0];
|
||||
}
|
||||
|
||||
return {
|
||||
create(type, messageId) {
|
||||
const id = randomUUID();
|
||||
const createdAt = nowMs();
|
||||
const entry = {
|
||||
id,
|
||||
type,
|
||||
status: "pending",
|
||||
messageId,
|
||||
createdAt,
|
||||
expiresAt: createdAt + ttlSeconds * 1000,
|
||||
completedAt: null,
|
||||
result: null,
|
||||
error: null
|
||||
};
|
||||
|
||||
requests.set(id, entry);
|
||||
if (type === "button_wait") {
|
||||
addIndex(buttonWaitByMessageId, messageId, id);
|
||||
}
|
||||
if (type === "reply_wait") {
|
||||
addIndex(replyWaitByMessageId, messageId, id);
|
||||
}
|
||||
return entry;
|
||||
},
|
||||
|
||||
completeButton(messageId, payload) {
|
||||
const entry = getPendingByMessageId(buttonWaitByMessageId, messageId);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
entry.status = "completed";
|
||||
entry.result = payload;
|
||||
entry.completedAt = nowMs();
|
||||
removeIndexes(entry);
|
||||
return entry;
|
||||
},
|
||||
|
||||
completeReply(messageId, payload) {
|
||||
const entry = getPendingByMessageId(replyWaitByMessageId, messageId);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
entry.status = "completed";
|
||||
entry.result = payload;
|
||||
entry.completedAt = nowMs();
|
||||
removeIndexes(entry);
|
||||
return entry;
|
||||
},
|
||||
|
||||
get(requestId) {
|
||||
const entry = getEntryOrThrow(requestId);
|
||||
markExpiredIfNeeded(entry);
|
||||
return {
|
||||
...entry,
|
||||
remainingMs: entry.status === "pending" ? Math.max(entry.expiresAt - nowMs(), 0) : 0
|
||||
};
|
||||
},
|
||||
|
||||
cancel(requestId) {
|
||||
const entry = getEntryOrThrow(requestId);
|
||||
markExpiredIfNeeded(entry);
|
||||
if (entry.status !== "pending") {
|
||||
return entry;
|
||||
}
|
||||
entry.status = "canceled";
|
||||
entry.completedAt = nowMs();
|
||||
entry.error = "Canceled by user request";
|
||||
removeIndexes(entry);
|
||||
return entry;
|
||||
},
|
||||
|
||||
sweepExpired() {
|
||||
for (const entry of requests.values()) {
|
||||
markExpiredIfNeeded(entry);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function maybeReadPhotoInput({ imageUrl, imagePath }) {
|
||||
if (imageUrl && imagePath) {
|
||||
throw new Error("Provide only one of image_url or image_path");
|
||||
}
|
||||
|
||||
if (imageUrl) {
|
||||
return { type: "url", value: imageUrl };
|
||||
}
|
||||
|
||||
if (imagePath) {
|
||||
const stat = await fs.stat(imagePath);
|
||||
if (!stat.isFile()) {
|
||||
throw new Error("image_path must point to a file");
|
||||
}
|
||||
return { type: "file", value: imagePath };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function toInlineKeyboard(buttonRows) {
|
||||
return buttonRows.map((row) =>
|
||||
row.map((button) => {
|
||||
if (button.callback_data.length > 64) {
|
||||
throw new Error("callback_data must be 64 bytes or less");
|
||||
}
|
||||
return {
|
||||
text: button.text,
|
||||
callback_data: button.callback_data
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function summarizeRequest(entry) {
|
||||
return {
|
||||
request_id: entry.id,
|
||||
type: entry.type,
|
||||
status: entry.status,
|
||||
message_id: entry.messageId,
|
||||
created_at: new Date(entry.createdAt).toISOString(),
|
||||
expires_at: new Date(entry.expiresAt).toISOString(),
|
||||
completed_at: entry.completedAt ? new Date(entry.completedAt).toISOString() : null,
|
||||
remaining_ms: entry.remainingMs || 0,
|
||||
result: entry.result,
|
||||
error: entry.error
|
||||
};
|
||||
}
|
||||
|
||||
async function waitForRequestCompletion({ requestStore, requestId, timeoutMs, intervalMs }) {
|
||||
const startedAt = nowMs();
|
||||
|
||||
while (true) {
|
||||
const entry = requestStore.get(requestId);
|
||||
if (entry.status !== "pending") {
|
||||
return {
|
||||
entry,
|
||||
elapsedMs: nowMs() - startedAt,
|
||||
timeoutReached: false
|
||||
};
|
||||
}
|
||||
|
||||
if (nowMs() - startedAt >= timeoutMs) {
|
||||
return {
|
||||
entry,
|
||||
elapsedMs: nowMs() - startedAt,
|
||||
timeoutReached: true
|
||||
};
|
||||
}
|
||||
|
||||
await sleep(intervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
function createMcpServer({ bot, chatId, requestStore }) {
|
||||
const server = new McpServer({
|
||||
name: "telegram-mcp-server",
|
||||
version: "0.1.0"
|
||||
});
|
||||
|
||||
const imageArgs = {
|
||||
image_url: z.string().url().optional().describe("Public image URL"),
|
||||
image_path: z.string().min(1).optional().describe("Local image path inside container")
|
||||
};
|
||||
|
||||
const parseModeArg = z.enum(["Markdown", "MarkdownV2", "HTML"]).optional();
|
||||
|
||||
server.tool(
|
||||
"send_message",
|
||||
"Send message to the configured Telegram chat. Optional image_url or image_path can be attached.",
|
||||
{
|
||||
text: z.string().min(1).describe("Message text"),
|
||||
...imageArgs,
|
||||
parse_mode: parseModeArg.describe("Telegram parse mode")
|
||||
},
|
||||
async ({ text, image_url: imageUrl, image_path: imagePath, parse_mode: parseMode }) => {
|
||||
const imageInput = await maybeReadPhotoInput({ imageUrl, imagePath });
|
||||
|
||||
let sent;
|
||||
if (imageInput) {
|
||||
sent = await bot.sendPhoto(chatId, imageInput.value, {
|
||||
caption: text,
|
||||
parse_mode: parseMode
|
||||
});
|
||||
} else {
|
||||
sent = await bot.sendMessage(chatId, text, {
|
||||
parse_mode: parseMode
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(
|
||||
{
|
||||
ok: true,
|
||||
chat_id: toSafeString(sent.chat?.id),
|
||||
message_id: sent.message_id,
|
||||
date: sent.date,
|
||||
has_image: Boolean(imageInput)
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
server.tool(
|
||||
"send_message_with_buttons",
|
||||
"Send a message with inline callback buttons and return request_id for async callback retrieval.",
|
||||
{
|
||||
text: z.string().min(1).describe("Message text"),
|
||||
buttons: z
|
||||
.array(
|
||||
z.array(
|
||||
z.object({
|
||||
text: z.string().min(1),
|
||||
callback_data: z.string().min(1)
|
||||
})
|
||||
)
|
||||
)
|
||||
.min(1)
|
||||
.describe("Inline keyboard rows"),
|
||||
...imageArgs,
|
||||
parse_mode: parseModeArg.describe("Telegram parse mode")
|
||||
},
|
||||
async ({ text, buttons, image_url: imageUrl, image_path: imagePath, parse_mode: parseMode }) => {
|
||||
const imageInput = await maybeReadPhotoInput({ imageUrl, imagePath });
|
||||
const inlineKeyboard = toInlineKeyboard(buttons);
|
||||
|
||||
let sent;
|
||||
if (imageInput) {
|
||||
sent = await bot.sendPhoto(chatId, imageInput.value, {
|
||||
caption: text,
|
||||
parse_mode: parseMode,
|
||||
reply_markup: {
|
||||
inline_keyboard: inlineKeyboard
|
||||
}
|
||||
});
|
||||
} else {
|
||||
sent = await bot.sendMessage(chatId, text, {
|
||||
parse_mode: parseMode,
|
||||
reply_markup: {
|
||||
inline_keyboard: inlineKeyboard
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const request = requestStore.create("button_wait", sent.message_id);
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(
|
||||
{
|
||||
ok: true,
|
||||
request_id: request.id,
|
||||
message_id: sent.message_id,
|
||||
status: request.status
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
server.tool(
|
||||
"send_message_with_buttons_blocking",
|
||||
"Blocking alternative: send a message with inline callback buttons and wait for a button click.",
|
||||
{
|
||||
text: z.string().min(1).describe("Message text"),
|
||||
buttons: z
|
||||
.array(
|
||||
z.array(
|
||||
z.object({
|
||||
text: z.string().min(1),
|
||||
callback_data: z.string().min(1)
|
||||
})
|
||||
)
|
||||
)
|
||||
.min(1)
|
||||
.describe("Inline keyboard rows"),
|
||||
...imageArgs,
|
||||
parse_mode: parseModeArg.describe("Telegram parse mode"),
|
||||
timeout_seconds: z.number().int().min(1).max(600).optional().describe("Maximum wait time in seconds"),
|
||||
poll_interval_ms: z
|
||||
.number()
|
||||
.int()
|
||||
.min(100)
|
||||
.max(5000)
|
||||
.optional()
|
||||
.describe("Status poll interval in milliseconds")
|
||||
},
|
||||
async ({
|
||||
text,
|
||||
buttons,
|
||||
image_url: imageUrl,
|
||||
image_path: imagePath,
|
||||
parse_mode: parseMode,
|
||||
timeout_seconds: timeoutSeconds,
|
||||
poll_interval_ms: pollIntervalMs
|
||||
}) => {
|
||||
const imageInput = await maybeReadPhotoInput({ imageUrl, imagePath });
|
||||
const inlineKeyboard = toInlineKeyboard(buttons);
|
||||
|
||||
let sent;
|
||||
if (imageInput) {
|
||||
sent = await bot.sendPhoto(chatId, imageInput.value, {
|
||||
caption: text,
|
||||
parse_mode: parseMode,
|
||||
reply_markup: {
|
||||
inline_keyboard: inlineKeyboard
|
||||
}
|
||||
});
|
||||
} else {
|
||||
sent = await bot.sendMessage(chatId, text, {
|
||||
parse_mode: parseMode,
|
||||
reply_markup: {
|
||||
inline_keyboard: inlineKeyboard
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const request = requestStore.create("button_wait", sent.message_id);
|
||||
const timeoutMs = (timeoutSeconds || 120) * 1000;
|
||||
const intervalMs = pollIntervalMs || 1000;
|
||||
|
||||
const waitResult = await waitForRequestCompletion({
|
||||
requestStore,
|
||||
requestId: request.id,
|
||||
timeoutMs,
|
||||
intervalMs
|
||||
});
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(
|
||||
{
|
||||
waited: true,
|
||||
timeout_reached: waitResult.timeoutReached,
|
||||
elapsed_ms: waitResult.elapsedMs,
|
||||
request: summarizeRequest(waitResult.entry)
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
server.tool(
|
||||
"send_message_expect_reply",
|
||||
"Send message and create async request_id that completes when user replies to this message.",
|
||||
{
|
||||
text: z.string().min(1).describe("Message text"),
|
||||
...imageArgs,
|
||||
parse_mode: parseModeArg.describe("Telegram parse mode")
|
||||
},
|
||||
async ({ text, image_url: imageUrl, image_path: imagePath, parse_mode: parseMode }) => {
|
||||
const imageInput = await maybeReadPhotoInput({ imageUrl, imagePath });
|
||||
|
||||
let sent;
|
||||
if (imageInput) {
|
||||
sent = await bot.sendPhoto(chatId, imageInput.value, {
|
||||
caption: text,
|
||||
parse_mode: parseMode
|
||||
});
|
||||
} else {
|
||||
sent = await bot.sendMessage(chatId, text, {
|
||||
parse_mode: parseMode
|
||||
});
|
||||
}
|
||||
|
||||
const request = requestStore.create("reply_wait", sent.message_id);
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(
|
||||
{
|
||||
ok: true,
|
||||
request_id: request.id,
|
||||
message_id: sent.message_id,
|
||||
status: request.status
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
server.tool(
|
||||
"send_message_expect_reply_blocking",
|
||||
"Blocking alternative: send message and wait for user reply to that message in one call.",
|
||||
{
|
||||
text: z.string().min(1).describe("Message text"),
|
||||
...imageArgs,
|
||||
parse_mode: parseModeArg.describe("Telegram parse mode"),
|
||||
timeout_seconds: z.number().int().min(1).max(600).optional().describe("Maximum wait time in seconds"),
|
||||
poll_interval_ms: z
|
||||
.number()
|
||||
.int()
|
||||
.min(100)
|
||||
.max(5000)
|
||||
.optional()
|
||||
.describe("Status poll interval in milliseconds")
|
||||
},
|
||||
async ({
|
||||
text,
|
||||
image_url: imageUrl,
|
||||
image_path: imagePath,
|
||||
parse_mode: parseMode,
|
||||
timeout_seconds: timeoutSeconds,
|
||||
poll_interval_ms: pollIntervalMs
|
||||
}) => {
|
||||
const imageInput = await maybeReadPhotoInput({ imageUrl, imagePath });
|
||||
|
||||
let sent;
|
||||
if (imageInput) {
|
||||
sent = await bot.sendPhoto(chatId, imageInput.value, {
|
||||
caption: text,
|
||||
parse_mode: parseMode
|
||||
});
|
||||
} else {
|
||||
sent = await bot.sendMessage(chatId, text, {
|
||||
parse_mode: parseMode
|
||||
});
|
||||
}
|
||||
|
||||
const request = requestStore.create("reply_wait", sent.message_id);
|
||||
const timeoutMs = (timeoutSeconds || 120) * 1000;
|
||||
const intervalMs = pollIntervalMs || 1000;
|
||||
|
||||
const waitResult = await waitForRequestCompletion({
|
||||
requestStore,
|
||||
requestId: request.id,
|
||||
timeoutMs,
|
||||
intervalMs
|
||||
});
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(
|
||||
{
|
||||
waited: true,
|
||||
timeout_reached: waitResult.timeoutReached,
|
||||
elapsed_ms: waitResult.elapsedMs,
|
||||
request: summarizeRequest(waitResult.entry)
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
server.tool(
|
||||
"get_request_result",
|
||||
"Get current status and result for a button/reply async request.",
|
||||
{
|
||||
request_id: z.string().uuid().describe("Request ID returned by async tools")
|
||||
},
|
||||
async ({ request_id: requestId }) => {
|
||||
const entry = requestStore.get(requestId);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(summarizeRequest(entry), null, 2)
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
server.tool(
|
||||
"cancel_request",
|
||||
"Cancel a pending async request created by send_message_with_buttons or send_message_expect_reply.",
|
||||
{
|
||||
request_id: z.string().uuid().describe("Pending request ID")
|
||||
},
|
||||
async ({ request_id: requestId }) => {
|
||||
const entry = requestStore.cancel(requestId);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(summarizeRequest(entry), null, 2)
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const token = requiredEnv("TELEGRAM_BOT_TOKEN");
|
||||
const chatId = requiredEnv("TELEGRAM_CHAT_ID");
|
||||
|
||||
const host = process.env.HTTP_HOST?.trim() || "127.0.0.1";
|
||||
const port = Number(process.env.PORT || process.env.HTTP_PORT || "3000");
|
||||
const mcpPath = process.env.MCP_PATH?.trim() || "/mcp";
|
||||
const pollingIntervalMs = Number(process.env.TELEGRAM_POLLING_INTERVAL_MS || "1000");
|
||||
const requestTtlSeconds = Number(process.env.TELEGRAM_REQUEST_TTL_SECONDS || "600");
|
||||
|
||||
if (!Number.isFinite(requestTtlSeconds) || requestTtlSeconds <= 0) {
|
||||
throw new Error("TELEGRAM_REQUEST_TTL_SECONDS must be a positive number");
|
||||
}
|
||||
|
||||
const requestStore = createRequestStore({ ttlSeconds: requestTtlSeconds });
|
||||
const bot = new TelegramBot(token, {
|
||||
polling: {
|
||||
interval: pollingIntervalMs,
|
||||
autoStart: true,
|
||||
params: {
|
||||
timeout: 10
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
bot.on("polling_error", (error) => {
|
||||
console.error("Telegram polling error:", error.message || error);
|
||||
});
|
||||
|
||||
bot.on("callback_query", async (query) => {
|
||||
const queryChatId = toSafeString(query.message?.chat?.id);
|
||||
const configuredChatId = toSafeString(chatId);
|
||||
if (!queryChatId || queryChatId !== configuredChatId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const messageId = query.message?.message_id;
|
||||
if (!messageId) {
|
||||
return;
|
||||
}
|
||||
|
||||
requestStore.completeButton(messageId, {
|
||||
update_type: "callback_query",
|
||||
callback_query_id: query.id,
|
||||
from: {
|
||||
id: query.from?.id,
|
||||
username: query.from?.username || null,
|
||||
first_name: query.from?.first_name || null,
|
||||
last_name: query.from?.last_name || null
|
||||
},
|
||||
data: query.data || null,
|
||||
message_id: messageId,
|
||||
chat_id: queryChatId
|
||||
});
|
||||
|
||||
try {
|
||||
await bot.answerCallbackQuery(query.id);
|
||||
} catch (error) {
|
||||
console.error("Failed to answer callback query:", error.message || error);
|
||||
}
|
||||
});
|
||||
|
||||
bot.on("message", (message) => {
|
||||
const configuredChatId = toSafeString(chatId);
|
||||
const messageChatId = toSafeString(message.chat?.id);
|
||||
if (!messageChatId || messageChatId !== configuredChatId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const repliedToMessageId = message.reply_to_message?.message_id;
|
||||
if (!repliedToMessageId) {
|
||||
return;
|
||||
}
|
||||
|
||||
requestStore.completeReply(repliedToMessageId, {
|
||||
update_type: "message_reply",
|
||||
from: {
|
||||
id: message.from?.id,
|
||||
username: message.from?.username || null,
|
||||
first_name: message.from?.first_name || null,
|
||||
last_name: message.from?.last_name || null
|
||||
},
|
||||
message_id: message.message_id,
|
||||
chat_id: messageChatId,
|
||||
date: message.date,
|
||||
text: message.text || null,
|
||||
caption: message.caption || null
|
||||
});
|
||||
});
|
||||
|
||||
const sweepTimer = setInterval(() => {
|
||||
requestStore.sweepExpired();
|
||||
}, 10_000);
|
||||
|
||||
const app = createMcpExpressApp({ host });
|
||||
|
||||
app.post(mcpPath, async (req, res) => {
|
||||
const server = createMcpServer({
|
||||
bot,
|
||||
chatId,
|
||||
requestStore
|
||||
});
|
||||
|
||||
try {
|
||||
const transport = new StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined
|
||||
});
|
||||
|
||||
await server.connect(transport);
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
|
||||
res.on("close", () => {
|
||||
transport.close().catch(() => {});
|
||||
server.close().catch(() => {});
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error handling MCP request:", error);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({
|
||||
jsonrpc: "2.0",
|
||||
error: {
|
||||
code: -32603,
|
||||
message: "Internal server error"
|
||||
},
|
||||
id: null
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
app.get("/health", (_req, res) => {
|
||||
res.json({ ok: true, service: "telegram-mcp-server" });
|
||||
});
|
||||
|
||||
const httpServer = app.listen(port, host, () => {
|
||||
console.log(`Telegram MCP Streamable HTTP server listening at http://${host}:${port}${mcpPath}`);
|
||||
});
|
||||
|
||||
const shutdown = async () => {
|
||||
clearInterval(sweepTimer);
|
||||
|
||||
try {
|
||||
await bot.stopPolling();
|
||||
} catch (_error) {
|
||||
// Ignore stop errors during shutdown.
|
||||
}
|
||||
|
||||
httpServer.close(() => {
|
||||
process.exit(0);
|
||||
});
|
||||
};
|
||||
|
||||
process.on("SIGINT", shutdown);
|
||||
process.on("SIGTERM", shutdown);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in New Issue
Block a user