-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
425 lines (390 loc) · 11.2 KB
/
index.ts
File metadata and controls
425 lines (390 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import express from "express";
import type { Request, Response, NextFunction } from "express";
import cors from "cors";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
import crypto from "node:crypto";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { config } from "./config.js";
import { pool } from "./db.js";
import { embedText } from "./llm_backend.js";
import { logger } from "./logger.js";
const app = express();
app.use(cors());
app.use(express.json({ limit: "1mb" }));
app.use((req: Request, res: Response, next: NextFunction) => {
const start = Date.now();
const requestId = crypto.randomUUID();
(req as any).requestId = requestId;
logger.info("http.request", {
id: requestId,
method: req.method,
path: req.path,
});
res.on("finish", () => {
logger.info("http.response", {
id: requestId,
method: req.method,
path: req.path,
status: res.statusCode,
ms: Date.now() - start,
});
});
next();
});
interface ToolDef {
name: string;
description: string;
parameters: z.ZodTypeAny;
execute: (params: any) => Promise<any>;
}
const tools: ToolDef[] = [];
function addTool(tool: ToolDef) {
tools.push(tool);
}
function findTool(name: string) {
return tools.find((t) => t.name === name);
}
function vectorToSql(vector: number[]): string {
return `[${vector.join(",")}]`;
}
const authMiddleware = (req: any, res: any, next: any) => {
if (!config.mcpHttpToken) return next();
const token = req.headers.authorization?.replace("Bearer ", "");
if (token !== config.mcpHttpToken) {
return res.status(401).json({ error: "unauthorized" });
}
return next();
};
app.get("/health", (_req: Request, res: Response) => {
res.json({
status: "ok",
version: "2026.02.8",
time: new Date().toISOString(),
});
});
app.get("/tools", authMiddleware, (_req: Request, res: Response) => {
res.json(
tools.map((t) => ({
name: t.name,
description: t.description,
inputSchema: (zodToJsonSchema as any)(t.parameters, t.name),
}))
);
});
app.post("/tools/:name", authMiddleware, async (req: Request, res: Response) => {
const requestId = (req as any).requestId;
const tool = findTool(req.params.name);
if (!tool) return res.status(404).json({ error: "tool not found" });
const parsed = tool.parameters.safeParse(req.body || {});
if (!parsed.success) {
logger.warn("http.tool.invalid", {
id: requestId,
tool: req.params.name,
error: parsed.error.message,
});
return res.status(400).json({ error: parsed.error.message });
}
try {
const result = await tool.execute(parsed.data);
return res.json(result);
} catch (err: any) {
logger.error("http.tool.error", {
id: requestId,
tool: req.params.name,
error: err?.message || String(err),
});
return res.status(500).json({ error: err?.message || String(err) });
}
});
// --- Tools ---
addTool({
name: "channels.list",
description: "Список отслеживаемых публичных каналов (Channel-MCP)",
parameters: z.object({}).optional(),
execute: async () => {
const { rows } = await pool.query(
`SELECT id, username, title, category, is_private, last_fetched_at, last_message_id
FROM channels
ORDER BY username`
);
return rows;
},
});
addTool({
name: "channel.messages.fetch",
description: "Получить посты из публичных каналов по дате/каналу/тегу (Channel-MCP)",
parameters: z.object({
channel: z.string().optional(),
date_from: z.string().optional(),
date_to: z.string().optional(),
tag: z.string().optional(),
limit: z.number().int().min(1).max(500).optional().default(100),
offset: z.number().int().min(0).optional().default(0),
}),
execute: async (params) => {
const where: string[] = [];
const values: any[] = [];
let idx = 1;
let joinTag = "";
if (params.tag) {
joinTag = "JOIN message_tags mt ON mt.message_id = m.id JOIN tags t ON t.id = mt.tag_id";
where.push(`t.canonical = $${idx++}`);
values.push(params.tag);
}
if (params.channel) {
where.push(`c.username = $${idx++}`);
values.push(params.channel);
}
if (params.date_from) {
where.push(`m.date >= $${idx++}`);
values.push(params.date_from);
}
if (params.date_to) {
where.push(`m.date <= $${idx++}`);
values.push(params.date_to);
}
const sql = `
SELECT
m.id,
c.username,
m.message_id,
m.ts,
m.date,
m.permalink,
m.content,
m.views,
m.emoji_line,
m.code_json,
(SELECT array_agg(t2.canonical ORDER BY t2.canonical)
FROM message_tags mt2
JOIN tags t2 ON t2.id = mt2.tag_id
WHERE mt2.message_id = m.id) AS tags
FROM messages m
JOIN channels c ON c.id = m.channel_id
${joinTag}
${where.length ? "WHERE " + where.join(" AND ") : ""}
ORDER BY m.ts DESC
LIMIT $${idx++} OFFSET $${idx++}
`;
values.push(params.limit, params.offset);
const { rows } = await pool.query(sql, values);
return rows;
},
});
addTool({
name: "tags.top",
description: "Топ тегов по постам каналов за период (Channel-MCP)",
parameters: z.object({
channel: z.string().optional(),
date_from: z.string().optional(),
date_to: z.string().optional(),
limit: z.number().int().min(1).max(200).optional().default(20),
}),
execute: async (params) => {
const where: string[] = [];
const values: any[] = [];
let idx = 1;
if (params.channel) {
where.push(`c.username = $${idx++}`);
values.push(params.channel);
}
if (params.date_from) {
where.push(`m.date >= $${idx++}`);
values.push(params.date_from);
}
if (params.date_to) {
where.push(`m.date <= $${idx++}`);
values.push(params.date_to);
}
const sql = `
SELECT t.canonical, COUNT(*)::int AS count
FROM message_tags mt
JOIN tags t ON t.id = mt.tag_id
JOIN messages m ON m.id = mt.message_id
JOIN channels c ON c.id = m.channel_id
${where.length ? "WHERE " + where.join(" AND ") : ""}
GROUP BY t.canonical
ORDER BY count DESC, t.canonical
LIMIT $${idx++}
`;
values.push(params.limit);
const { rows } = await pool.query(sql, values);
return rows;
},
});
addTool({
name: "channel.messages.search",
description: "Семантический поиск по постам каналов (pgvector + LLM embeddings, Channel-MCP)",
parameters: z.object({
query: z.string(),
channel: z.string().optional(),
date_from: z.string().optional(),
date_to: z.string().optional(),
limit: z.number().int().min(1).max(100).optional().default(20),
min_score: z.number().min(0).max(1).optional(),
}),
execute: async (params) => {
const embedding = await embedText(params.query);
if (!embedding.length) {
return [];
}
const vector = vectorToSql(embedding);
const where: string[] = [];
const values: any[] = [vector];
let idx = 2;
if (params.channel) {
where.push(`c.username = $${idx++}`);
values.push(params.channel);
}
if (params.date_from) {
where.push(`m.date >= $${idx++}`);
values.push(params.date_from);
}
if (params.date_to) {
where.push(`m.date <= $${idx++}`);
values.push(params.date_to);
}
if (params.min_score !== undefined) {
where.push(`1 - (e.embedding <=> $1::vector) >= $${idx++}`);
values.push(params.min_score);
}
const sql = `
SELECT
m.id,
c.username,
m.message_id,
m.ts,
m.date,
m.permalink,
m.content,
(1 - (e.embedding <=> $1::vector)) AS score,
m.emoji_line,
m.code_json,
(SELECT array_agg(t2.canonical ORDER BY t2.canonical)
FROM message_tags mt2
JOIN tags t2 ON t2.id = mt2.tag_id
WHERE mt2.message_id = m.id) AS tags
FROM embeddings e
JOIN messages m ON m.id = e.message_id
JOIN channels c ON c.id = m.channel_id
${where.length ? "WHERE " + where.join(" AND ") : ""}
ORDER BY e.embedding <=> $1::vector
LIMIT $${idx++}
`;
values.push(params.limit);
const { rows } = await pool.query(sql, values);
return rows;
},
});
// --- MCP server wiring ---
const server = new Server(
{ name: "channel-mcp", version: "26.02.4" },
{ capabilities: { tools: {} } }
);
server.setRequestHandler(ListToolsRequestSchema, async () => {
logger.debug("mcp.list_tools");
return {
tools: tools.map((t) => ({
name: t.name,
description: t.description,
inputSchema: (zodToJsonSchema as any)(t.parameters, t.name),
})),
};
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const requestId = crypto.randomUUID();
logger.info("mcp.tool.call", {
id: requestId,
tool: request.params.name,
});
const tool = findTool(request.params.name);
if (!tool) {
return {
content: [
{
type: "text",
text: `Unknown tool: ${request.params.name}`,
},
],
isError: true,
};
}
const parsed = tool.parameters.safeParse(request.params.arguments ?? {});
if (!parsed.success) {
return {
content: [
{
type: "text",
text: `Invalid input: ${parsed.error.message}`,
},
],
isError: true,
};
}
try {
const started = Date.now();
const result = await tool.execute(parsed.data);
logger.info("mcp.tool.ok", {
id: requestId,
tool: request.params.name,
ms: Date.now() - started,
result: logger.summarize(result),
});
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
} catch (err: any) {
logger.error("mcp.tool.error", {
id: requestId,
tool: request.params.name,
error: err?.message || String(err),
});
return {
content: [
{
type: "text",
text: `Tool error: ${err?.message || String(err)}`,
},
],
isError: true,
};
}
});
async function start() {
logger.info("startup.config", {
mcpTransport: config.mcpTransport,
mcpHost: config.mcpHost,
mcpPort: config.mcpPort,
db: config.db,
ollama: config.ollama,
});
if (config.mcpTransport === "stdio") {
const transport = new StdioServerTransport();
await server.connect(transport);
logger.info("mcp.transport.ready", { transport: "stdio" });
} else {
logger.warn(
`[mcp] MCP_TRANSPORT=${config.mcpTransport} not supported; falling back to stdio`
);
const transport = new StdioServerTransport();
await server.connect(transport);
}
app.listen(config.mcpPort, config.mcpHost, () => {
logger.info("http.listen", { host: config.mcpHost, port: config.mcpPort });
});
}
start().catch((err) => {
logger.error("startup.error", { error: err?.message || String(err) });
process.exit(1);
});