persyst-mcp 2.2.5 → 2.2.7

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/src/server.js CHANGED
@@ -1,723 +1,884 @@
1
- /**
2
- * server.js — MCP Server, Local HTTP Gateway & Swarm Hub
3
- *
4
- * Creates the MCP server, registers all tools, and connects via stdio.
5
- * Also runs a local HTTP/JSON Gateway on port 4321 (configurable) to support:
6
- * - Agentic swarms without subprocess overhead
7
- * - IDE context injection via /system-prompt
8
- * - Real-time event streaming via SSE (/events)
9
- * - Batch operations for high-throughput swarm agents
10
- * - Optional API key authentication for remote/multi-host setups
11
- *
12
- * Environment variables:
13
- * PORT — HTTP gateway port (default: 4321)
14
- * PERSYST_HOST — Bind address (default: 127.0.0.1, use 0.0.0.0 for Docker/remote)
15
- * PERSYST_API_KEY — Optional auth token. If set, all endpoints (except /health) require
16
- * Authorization: Bearer <token>
17
- *
18
- * All logging goes to stderr via console.error().
19
- */
20
-
21
- import http from 'http';
22
- import { URL } from 'url';
23
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
24
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
25
- import { registerTools, cleanupWatchers, addMemoryInternal, executeToolInternal } from './tools.js';
26
- import {
27
- applyTemporalDecay,
28
- closeDatabase,
29
- getActiveMemoryCount,
30
- getNamespaceStats,
31
- getAllAgentStats
32
- } from './database.js';
33
- import { consolidateMemories, searchHybrid, getOptimizedContext } from './search.js';
34
- import { startWatcher, stopWatcher } from './watcher.js';
35
- import { verifyChainIntegrity } from './attestation.js';
36
- import { memoryEventBus } from './events.js';
37
-
38
- // Track server birth time for uptime reporting
39
- const SERVER_START_TIME = Date.now();
40
-
41
- // Active SSE client response objects
42
- const sseClients = new Set();
43
-
44
- // ============================================================
45
- // SYSTEM PROMPT FORMATTER
46
- // ============================================================
47
-
48
- /**
49
- * Format optimized context data into a structured system-prompt block.
50
- * Supports three output formats: 'text', 'markdown', 'json'.
51
- *
52
- * @param {Object} contextData - Result from getOptimizedContext()
53
- * @param {string} format - 'text' | 'markdown' | 'json'
54
- * @param {string|null} agentId
55
- * @returns {string}
56
- */
57
- function formatSystemPrompt(contextData, format, agentId) {
58
- const { memories, suggested_actions } = contextData;
59
- const now = new Date().toLocaleString('en-US', { hour12: false }).replace(',', '');
60
- const count = memories.length;
61
-
62
- if (format === 'json') {
63
- return JSON.stringify({ ...contextData, generated_at: new Date().toISOString() }, null, 2);
64
- }
65
-
66
- // Group memories by category prefix
67
- const groups = {
68
- 'Rules & Conventions': [],
69
- 'Architecture & Stack': [],
70
- 'Decisions': [],
71
- 'Preferences': [],
72
- 'Context': []
73
- };
74
-
75
- for (const m of memories) {
76
- const c = m.content;
77
- if (/^(?:Rule|Config):/i.test(c)) groups['Rules & Conventions'].push(c);
78
- else if (/^(?:Stack|Architecture):/i.test(c)) groups['Architecture & Stack'].push(c);
79
- else if (/^Decision:/i.test(c)) groups['Decisions'].push(c);
80
- else if (/^Preference:/i.test(c)) groups['Preferences'].push(c);
81
- else groups['Context'].push(c);
82
- }
83
-
84
- if (format === 'markdown') {
85
- let md = `# Persyst Memory Context\n`;
86
- md += `> ${count} memories | Updated: ${now}`;
87
- if (agentId) md += ` | Agent: \`${agentId}\``;
88
- md += '\n\n';
89
-
90
- for (const [section, items] of Object.entries(groups)) {
91
- if (items.length === 0) continue;
92
- md += `## ${section}\n`;
93
- for (const item of items) md += `- ${item}\n`;
94
- md += '\n';
95
- }
96
-
97
- if (suggested_actions.length > 0) {
98
- md += `## Suggested Actions\n`;
99
- for (const a of suggested_actions) md += `- ${a}\n`;
100
- md += '\n';
101
- }
102
-
103
- md += `---\n*Refresh: \`curl http://127.0.0.1:4321/system-prompt?format=markdown\`*\n`;
104
- return md;
105
- }
106
-
107
- // Plain text (default) — safe to paste into any IDE custom instructions
108
- let text = `=== PERSYST MEMORY CONTEXT ===\n`;
109
- text += `Updated: ${now} | ${count} memories`;
110
- if (agentId) text += ` | Agent: ${agentId}`;
111
- text += '\n\n';
112
-
113
- for (const [section, items] of Object.entries(groups)) {
114
- if (items.length === 0) continue;
115
- text += `[${section.toUpperCase()}]\n`;
116
- for (const item of items) text += `• ${item}\n`;
117
- text += '\n';
118
- }
119
-
120
- if (suggested_actions.length > 0) {
121
- text += `[SUGGESTED ACTIONS]\n`;
122
- for (const a of suggested_actions) text += `• ${a}\n`;
123
- text += '\n';
124
- }
125
-
126
- text += `=== END MEMORY CONTEXT ===\n`;
127
- text += `Refresh: curl http://127.0.0.1:${process.env.PORT || '4321'}/system-prompt\n`;
128
- return text;
129
- }
130
-
131
- // ============================================================
132
- // REQUEST HANDLERS
133
- // ============================================================
134
-
135
- async function handleGetRequest(req, res, url) {
136
- const path = url.pathname;
137
-
138
- // ----------------------------------------------------------
139
- // GET /health — server liveness check for orchestrators
140
- // ----------------------------------------------------------
141
- if (path === '/health') {
142
- const uptime = Math.floor((Date.now() - SERVER_START_TIME) / 1000);
143
- let memories = 0;
144
- try { memories = getActiveMemoryCount(); } catch (_) {}
145
- res.writeHead(200, { 'Content-Type': 'application/json' });
146
- res.end(JSON.stringify({
147
- ok: true,
148
- version: '2.2.5',
149
- uptime_seconds: uptime,
150
- memories,
151
- sse_clients: sseClients.size
152
- }));
153
- return;
154
- }
155
-
156
- // ----------------------------------------------------------
157
- // GET /stats — memory and agent statistics
158
- // ----------------------------------------------------------
159
- if (path === '/stats') {
160
- try {
161
- const namespaces = getNamespaceStats();
162
- const agents = getAllAgentStats();
163
- const uptime = Math.floor((Date.now() - SERVER_START_TIME) / 1000);
164
- res.writeHead(200, { 'Content-Type': 'application/json' });
165
- res.end(JSON.stringify({ uptime_seconds: uptime, namespaces, agents }));
166
- } catch (err) {
167
- res.writeHead(500, { 'Content-Type': 'application/json' });
168
- res.end(JSON.stringify({ error: err.message }));
169
- }
170
- return;
171
- }
172
-
173
- // ----------------------------------------------------------
174
- // GET /system-prompt — formatted memory context for IDE injection
175
- //
176
- // Query params:
177
- // query — search query (default: broad project context)
178
- // max_tokens token budget (default: 1500)
179
- // agent_id restrict to this agent's namespace
180
- // format 'text' (default) | 'markdown' | 'json'
181
- // ----------------------------------------------------------
182
- if (path === '/system-prompt') {
183
- try {
184
- const query = url.searchParams.get('query') ||
185
- 'project conventions architecture preferences rules stack decisions';
186
- const maxTokens = Math.max(100, parseInt(url.searchParams.get('max_tokens') || '1500', 10));
187
- const agentId = url.searchParams.get('agent_id') || null;
188
- const format = url.searchParams.get('format') || 'text';
189
-
190
- const contextData = await getOptimizedContext(
191
- query, maxTokens, agentId, null, agentId || null, null
192
- );
193
-
194
- const output = formatSystemPrompt(contextData, format, agentId);
195
-
196
- const contentTypeMap = {
197
- json: 'application/json',
198
- markdown: 'text/markdown; charset=utf-8',
199
- text: 'text/plain; charset=utf-8'
200
- };
201
- res.writeHead(200, {
202
- 'Content-Type': contentTypeMap[format] || 'text/plain; charset=utf-8',
203
- 'Cache-Control': 'no-cache'
204
- });
205
- res.end(output);
206
- } catch (err) {
207
- res.writeHead(500, { 'Content-Type': 'application/json' });
208
- res.end(JSON.stringify({ error: err.message }));
209
- }
210
- return;
211
- }
212
-
213
- // ----------------------------------------------------------
214
- // GET /events — Server-Sent Events stream of memory changes
215
- //
216
- // Clients subscribe once and receive real-time push notifications
217
- // for memory_added, memory_deleted, memories_consolidated events.
218
- //
219
- // Example (Python):
220
- // import sseclient, requests
221
- // for event in sseclient.SSEClient('http://127.0.0.1:4321/events'):
222
- // print(event.event, event.data)
223
- //
224
- // Example (Node.js):
225
- // const es = new EventSource('http://127.0.0.1:4321/events');
226
- // es.addEventListener('memory_added', e => console.log(JSON.parse(e.data)));
227
- // ----------------------------------------------------------
228
- if (path === '/events') {
229
- res.writeHead(200, {
230
- 'Content-Type': 'text/event-stream',
231
- 'Cache-Control': 'no-cache',
232
- 'Connection': 'keep-alive',
233
- 'Access-Control-Allow-Origin': '*',
234
- 'X-Accel-Buffering': 'no' // Prevents nginx from buffering SSE
235
- });
236
-
237
- // Send initial connected event
238
- res.write(`event: connected\ndata: ${JSON.stringify({
239
- ok: true,
240
- timestamp: new Date().toISOString(),
241
- server_version: '2.2.5'
242
- })}\n\n`);
243
-
244
- sseClients.add(res);
245
-
246
- // Heartbeat every 15s to keep connection alive through proxies
247
- const heartbeat = setInterval(() => {
248
- try { res.write(': heartbeat\n\n'); } catch (_) { clearInterval(heartbeat); }
249
- }, 15000);
250
-
251
- const onAdded = (data) => {
252
- try { res.write(`event: memory_added\ndata: ${JSON.stringify(data)}\n\n`); } catch (_) {}
253
- };
254
- const onDeleted = (data) => {
255
- try { res.write(`event: memory_deleted\ndata: ${JSON.stringify(data)}\n\n`); } catch (_) {}
256
- };
257
- const onConsolidated = (data) => {
258
- try { res.write(`event: memories_consolidated\ndata: ${JSON.stringify(data)}\n\n`); } catch (_) {}
259
- };
260
-
261
- memoryEventBus.on('memory_added', onAdded);
262
- memoryEventBus.on('memory_deleted', onDeleted);
263
- memoryEventBus.on('memories_consolidated', onConsolidated);
264
-
265
- req.on('close', () => {
266
- clearInterval(heartbeat);
267
- memoryEventBus.off('memory_added', onAdded);
268
- memoryEventBus.off('memory_deleted', onDeleted);
269
- memoryEventBus.off('memories_consolidated', onConsolidated);
270
- sseClients.delete(res);
271
- console.error(`[persyst-sse] Client disconnected. Active: ${sseClients.size}`);
272
- });
273
-
274
- console.error(`[persyst-sse] Client connected. Active: ${sseClients.size}`);
275
- return; // Keep connection alive — do NOT end response
276
- }
277
-
278
- res.writeHead(404, { 'Content-Type': 'application/json' });
279
- res.end(JSON.stringify({ error: 'Not Found' }));
280
- }
281
-
282
- async function handlePostRequest(req, res, payload) {
283
- const path = new URL(req.url, 'http://127.0.0.1').pathname;
284
-
285
- // ----------------------------------------------------------
286
- // POST /remember — quick one-liner memory save
287
- //
288
- // The user explicitly wants to save something. No extraction,
289
- // no filtering, no pattern matching. Just store it.
290
- //
291
- // Body: { content: string, importance?: number, namespace?: string }
292
- // OR: plain text body (e.g. from curl --data "don't forget X")
293
- //
294
- // Example:
295
- // curl -X POST http://127.0.0.1:4321/remember \
296
- // -H 'Content-Type: text/plain' \
297
- // --data 'SSL cert expires March 15'
298
- // ----------------------------------------------------------
299
- if (path === '/remember') {
300
- // Support both plain text and JSON bodies
301
- let content, importance, namespace;
302
- if (typeof payload === 'string') {
303
- content = payload.trim();
304
- importance = 1.0;
305
- namespace = 'shared';
306
- } else {
307
- content = payload.content || payload.text || payload.note || payload.message;
308
- importance = payload.importance || 1.0;
309
- namespace = payload.namespace || 'shared';
310
- }
311
-
312
- if (!content) {
313
- res.writeHead(400, { 'Content-Type': 'application/json' });
314
- res.end(JSON.stringify({ error: 'No content provided. Pass plain text or { content: "..." }' }));
315
- return;
316
- }
317
-
318
- // Prefix with Note: if not already categorized
319
- const normalizedContent = /^(?:Note|Reminder|Rule|Decision|Preference|Stack|Architecture|Config|Warning|FYI):/i.test(content.trim())
320
- ? content.trim()
321
- : `Note: ${content.trim()}`;
322
-
323
- const result = await addMemoryInternal({
324
- content: normalizedContent,
325
- importance,
326
- agent_id: payload.agent_id || null,
327
- session_id: payload.session_id || null,
328
- shared: payload.shared !== false
329
- });
330
-
331
- if (!result.error) {
332
- memoryEventBus.emit('memory_added', {
333
- id: result.id,
334
- content: normalizedContent,
335
- namespace: result.namespace || namespace,
336
- source: 'user-explicit'
337
- });
338
- }
339
-
340
- res.writeHead(result.error ? 400 : 200, { 'Content-Type': 'application/json' });
341
- res.end(JSON.stringify(result));
342
- return;
343
- }
344
-
345
- // ----------------------------------------------------------
346
- // POST /search
347
- // ----------------------------------------------------------
348
- if (path === '/search') {
349
- const { query, limit = 5, agent_id, session_id } = payload;
350
- if (!query) {
351
- res.writeHead(400, { 'Content-Type': 'application/json' });
352
- res.end(JSON.stringify({ error: 'Missing required field: query' }));
353
- return;
354
- }
355
- const results = await searchHybrid(query, limit, agent_id, session_id, agent_id || null);
356
- res.writeHead(200, { 'Content-Type': 'application/json' });
357
- res.end(JSON.stringify({ success: true, results }));
358
- return;
359
- }
360
-
361
- // ----------------------------------------------------------
362
- // POST /add
363
- // ----------------------------------------------------------
364
- if (path === '/add') {
365
- const { content, importance = 1.0, agent_id, session_id, shared = true } = payload;
366
- if (!content) {
367
- res.writeHead(400, { 'Content-Type': 'application/json' });
368
- res.end(JSON.stringify({ error: 'Missing required field: content' }));
369
- return;
370
- }
371
- const result = await addMemoryInternal({ content, importance, agent_id, session_id, shared });
372
- if (result.error) {
373
- res.writeHead(400, { 'Content-Type': 'application/json' });
374
- } else {
375
- res.writeHead(200, { 'Content-Type': 'application/json' });
376
- // Broadcast to SSE subscribers
377
- memoryEventBus.emit('memory_added', {
378
- id: result.id,
379
- content,
380
- namespace: result.namespace,
381
- source: agent_id || 'http'
382
- });
383
- }
384
- res.end(JSON.stringify(result));
385
- return;
386
- }
387
-
388
- // ----------------------------------------------------------
389
- // POST /context
390
- // ----------------------------------------------------------
391
- if (path === '/context') {
392
- const { query, max_tokens = 2000, agent_id, session_id, intent } = payload;
393
- if (!query) {
394
- res.writeHead(400, { 'Content-Type': 'application/json' });
395
- res.end(JSON.stringify({ error: 'Missing required field: query' }));
396
- return;
397
- }
398
- const context = await getOptimizedContext(query, max_tokens, agent_id, session_id, agent_id || null, intent);
399
- res.writeHead(200, { 'Content-Type': 'application/json' });
400
- res.end(JSON.stringify(context));
401
- return;
402
- }
403
-
404
- // ----------------------------------------------------------
405
- // POST /tool — generic MCP tool invocation
406
- // ----------------------------------------------------------
407
- if (path === '/tool') {
408
- const { name, arguments: args } = payload;
409
- if (!name) {
410
- res.writeHead(400, { 'Content-Type': 'application/json' });
411
- res.end(JSON.stringify({ error: 'Missing required field: name' }));
412
- return;
413
- }
414
- const result = await executeToolInternal(name, args || {});
415
- res.writeHead(200, { 'Content-Type': 'application/json' });
416
- res.end(JSON.stringify(result));
417
- return;
418
- }
419
-
420
- // ----------------------------------------------------------
421
- // POST /verify chain integrity check
422
- // ----------------------------------------------------------
423
- if (path === '/verify') {
424
- const result = await verifyChainIntegrity();
425
- res.writeHead(200, { 'Content-Type': 'application/json' });
426
- res.end(JSON.stringify(result));
427
- return;
428
- }
429
-
430
- // ----------------------------------------------------------
431
- // POST /batch/add — store multiple memories in one round trip
432
- //
433
- // Body: { memories: [{ content, importance?, agent_id?, shared? }, ...] }
434
- // Returns: { success, results: [...], stored, skipped, errors }
435
- //
436
- // Designed for:
437
- // - Swarm agents ingesting session summaries in bulk
438
- // - Migration tools
439
- // - CI pipelines storing build/test results
440
- // ----------------------------------------------------------
441
- if (path === '/batch/add') {
442
- const { memories } = payload;
443
- if (!Array.isArray(memories) || memories.length === 0) {
444
- res.writeHead(400, { 'Content-Type': 'application/json' });
445
- res.end(JSON.stringify({ error: 'memories must be a non-empty array' }));
446
- return;
447
- }
448
-
449
- // Hard cap: prevent abuse
450
- if (memories.length > 200) {
451
- res.writeHead(400, { 'Content-Type': 'application/json' });
452
- res.end(JSON.stringify({ error: 'Batch size exceeds maximum of 200' }));
453
- return;
454
- }
455
-
456
- const results = [];
457
- let stored = 0;
458
- let skipped = 0;
459
- let errors = 0;
460
-
461
- for (const mem of memories) {
462
- const { content, importance = 1.0, agent_id, session_id, shared = true } = mem;
463
- if (!content) {
464
- results.push({ error: 'Missing content', input: mem });
465
- errors++;
466
- continue;
467
- }
468
- try {
469
- const result = await addMemoryInternal({ content, importance, agent_id, session_id, shared });
470
- results.push(result);
471
- if (result.error) {
472
- errors++;
473
- } else if (result.message && result.message.includes('already exists')) {
474
- skipped++;
475
- } else {
476
- stored++;
477
- memoryEventBus.emit('memory_added', {
478
- id: result.id,
479
- content,
480
- namespace: result.namespace,
481
- source: agent_id || 'batch'
482
- });
483
- }
484
- } catch (err) {
485
- results.push({ error: err.message, input: mem });
486
- errors++;
487
- }
488
- }
489
-
490
- res.writeHead(200, { 'Content-Type': 'application/json' });
491
- res.end(JSON.stringify({ success: true, results, stored, skipped, errors }));
492
- return;
493
- }
494
-
495
- // ----------------------------------------------------------
496
- // POST /batch/search run multiple queries in one round trip
497
- //
498
- // Body: { queries: string[] | Array<{query, limit?, agent_id?}>, limit?: number }
499
- // Returns: { results: { "<query>": [...memories] } }
500
- //
501
- // Designed for:
502
- // - Swarm agents loading context for multiple topics at once
503
- // - Parallel memory retrieval without sequential round trips
504
- // ----------------------------------------------------------
505
- if (path === '/batch/search') {
506
- const { queries, limit = 5 } = payload;
507
- if (!Array.isArray(queries) || queries.length === 0) {
508
- res.writeHead(400, { 'Content-Type': 'application/json' });
509
- res.end(JSON.stringify({ error: 'queries must be a non-empty array' }));
510
- return;
511
- }
512
-
513
- if (queries.length > 50) {
514
- res.writeHead(400, { 'Content-Type': 'application/json' });
515
- res.end(JSON.stringify({ error: 'Batch query size exceeds maximum of 50' }));
516
- return;
517
- }
518
-
519
- // Run all searches in parallel for speed
520
- const searchPromises = queries.map(async (q) => {
521
- if (typeof q === 'string') {
522
- return { key: q, results: await searchHybrid(q, limit, null, null, null) };
523
- } else if (q && typeof q === 'object' && q.query) {
524
- return {
525
- key: q.query,
526
- results: await searchHybrid(q.query, q.limit || limit, q.agent_id || null, null, q.agent_id || null)
527
- };
528
- }
529
- return { key: String(q), results: [] };
530
- });
531
-
532
- const settled = await Promise.allSettled(searchPromises);
533
- const results = {};
534
- for (const s of settled) {
535
- if (s.status === 'fulfilled') {
536
- results[s.value.key] = s.value.results;
537
- }
538
- }
539
-
540
- res.writeHead(200, { 'Content-Type': 'application/json' });
541
- res.end(JSON.stringify({ success: true, results }));
542
- return;
543
- }
544
-
545
- res.writeHead(404, { 'Content-Type': 'application/json' });
546
- res.end(JSON.stringify({ error: 'Endpoint Not Found' }));
547
- }
548
-
549
- // ============================================================
550
- // MAIN SERVER STARTUP
551
- // ============================================================
552
-
553
- /**
554
- * Start the Persyst MCP server & HTTP Gateway.
555
- */
556
- export async function startServer() {
557
- // --- Create MCP server ---
558
- const server = new McpServer({
559
- name: 'persyst',
560
- version: '2.2.5'
561
- });
562
-
563
- // --- Register all tools ---
564
- const registeredCount = registerTools(server);
565
- console.error(`[persyst] ${registeredCount} tools registered ✓`);
566
-
567
- // --- Start background log watcher daemon (skip in test mode) ---
568
- if (process.env.NODE_ENV !== 'test') {
569
- startWatcher();
570
- }
571
-
572
- // --- Gateway configuration ---
573
- const httpPort = parseInt(process.env.PORT || '4321', 10);
574
- const httpHost = process.env.PERSYST_HOST || '127.0.0.1';
575
- const configuredApiKey = process.env.PERSYST_API_KEY || null;
576
-
577
- if (configuredApiKey) {
578
- console.error(`[persyst] API key auth enabled — endpoints require Authorization: Bearer <key>`);
579
- }
580
- if (httpHost !== '127.0.0.1') {
581
- console.error(`[persyst] ⚠️ Gateway bound to ${httpHost} — ensure PERSYST_API_KEY is set for security`);
582
- }
583
-
584
- // --- Start local HTTP Gateway ---
585
- const httpServer = http.createServer((req, res) => {
586
- // CORS headers
587
- res.setHeader('Access-Control-Allow-Origin', '*');
588
- res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
589
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
590
-
591
- if (req.method === 'OPTIONS') {
592
- res.writeHead(204);
593
- res.end();
594
- return;
595
- }
596
-
597
- // API key authentication middleware
598
- // /health is always public (for orchestrators / Docker health checks)
599
- if (configuredApiKey) {
600
- const urlPath = new URL(req.url || '/', 'http://127.0.0.1').pathname;
601
- if (urlPath !== '/health') {
602
- const authHeader = req.headers['authorization'] || '';
603
- const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null;
604
- if (token !== configuredApiKey) {
605
- res.writeHead(401, { 'Content-Type': 'application/json' });
606
- res.end(JSON.stringify({
607
- error: 'Unauthorized. Set header: Authorization: Bearer <PERSYST_API_KEY>'
608
- }));
609
- return;
610
- }
611
- }
612
- }
613
-
614
- // Route GET requests (no body reading needed)
615
- if (req.method === 'GET') {
616
- try {
617
- const url = new URL(req.url || '/', `http://${httpHost}`);
618
- handleGetRequest(req, res, url).catch(err => {
619
- try {
620
- res.writeHead(500, { 'Content-Type': 'application/json' });
621
- res.end(JSON.stringify({ error: err.message }));
622
- } catch (_) {}
623
- });
624
- } catch (err) {
625
- res.writeHead(400, { 'Content-Type': 'application/json' });
626
- res.end(JSON.stringify({ error: 'Bad request URL' }));
627
- }
628
- return;
629
- }
630
-
631
- // Route POST requests
632
- if (req.method !== 'POST') {
633
- res.writeHead(405, { 'Content-Type': 'application/json' });
634
- res.end(JSON.stringify({ error: 'Method Not Allowed. Use POST or GET.' }));
635
- return;
636
- }
637
-
638
- let body = '';
639
- req.on('data', chunk => { body += chunk; });
640
- req.on('end', async () => {
641
- try {
642
- // Handle both JSON and plain-text bodies (plain text used by /remember)
643
- const contentType = req.headers['content-type'] || '';
644
- let payload;
645
- if (contentType.includes('text/plain')) {
646
- payload = body.trim(); // Will be handled as string in /remember
647
- } else {
648
- payload = JSON.parse(body || '{}');
649
- }
650
- await handlePostRequest(req, res, payload);
651
- } catch (err) {
652
- try {
653
- res.writeHead(500, { 'Content-Type': 'application/json' });
654
- res.end(JSON.stringify({ error: err.message }));
655
- } catch (_) {}
656
- }
657
- });
658
- });
659
-
660
- httpServer.on('error', (err) => {
661
- if (err.code === 'EADDRINUSE') {
662
- console.error(`[persyst] HTTP Gateway port ${httpPort} already in use. Stdio MCP server will continue.`);
663
- } else {
664
- console.error('[persyst] HTTP Gateway error:', err.message);
665
- }
666
- });
667
-
668
- httpServer.listen(httpPort, httpHost, () => {
669
- console.error(`[persyst] HTTP Gateway listening on http://${httpHost}:${httpPort} ✓`);
670
- console.error(`[persyst] Endpoints: /health /stats /system-prompt /events /remember /search /add /context /tool /verify /batch/add /batch/search`);
671
- });
672
-
673
- // --- Start temporal decay timer (every hour) ---
674
- const decayTimer = setInterval(applyTemporalDecay, 3600000);
675
-
676
- // --- Start daily consolidation sweep ---
677
- const consolidationTimer = setInterval(async () => {
678
- console.error('[persyst] Running scheduled daily memory consolidation sweep...');
679
- try {
680
- const report = await consolidateMemories();
681
- console.error(`[persyst] Consolidation sweep: consolidated ${report.consolidated_groups} duplicate groups.`);
682
- if (report.consolidated_groups > 0) {
683
- memoryEventBus.emit('memories_consolidated', {
684
- consolidated_groups: report.consolidated_groups,
685
- details: report.details
686
- });
687
- }
688
- } catch (err) {
689
- console.error('[persyst] Daily consolidation sweep failed:', err.message);
690
- }
691
- }, 86400000);
692
-
693
- // --- Graceful shutdown ---
694
- const shutdown = () => {
695
- console.error('[persyst] Shutting down...');
696
- clearInterval(decayTimer);
697
- clearInterval(consolidationTimer);
698
- stopWatcher();
699
- cleanupWatchers();
700
-
701
- // Close all SSE connections gracefully
702
- for (const client of sseClients) {
703
- try {
704
- client.write(`event: server_shutdown\ndata: ${JSON.stringify({ message: 'Server shutting down' })}\n\n`);
705
- client.end();
706
- } catch (_) {}
707
- }
708
- sseClients.clear();
709
-
710
- httpServer.close();
711
- closeDatabase();
712
- process.exit(0);
713
- };
714
- process.on('SIGINT', shutdown);
715
- process.on('SIGTERM', shutdown);
716
-
717
- // --- Connect via stdio ---
718
- const transport = new StdioServerTransport();
719
- await server.connect(transport);
720
-
721
- console.error('[persyst] MCP server running on stdio ✓');
722
- console.error('[persyst] Ready to receive tool calls');
723
- }
1
+ /**
2
+ * server.js — MCP Server, Local HTTP Gateway & Swarm Hub
3
+ *
4
+ * Creates the MCP server, registers all tools, and connects via stdio.
5
+ * Also runs a local HTTP/JSON Gateway on port 4321 (configurable) to support:
6
+ * - Agentic swarms without subprocess overhead
7
+ * - IDE context injection via /system-prompt
8
+ * - Real-time event streaming via SSE (/events)
9
+ * - Batch operations for high-throughput swarm agents
10
+ * - Optional API key authentication for remote/multi-host setups
11
+ *
12
+ * Environment variables:
13
+ * PORT — HTTP gateway port (default: 4321)
14
+ * PERSYST_HOST — Bind address (default: 127.0.0.1, use 0.0.0.0 for Docker/remote)
15
+ * PERSYST_API_KEY — Optional auth token. If set, all endpoints (except /health) require
16
+ * Authorization: Bearer <token>
17
+ *
18
+ * All logging goes to stderr via console.error().
19
+ */
20
+
21
+ import http from 'http';
22
+ import { URL } from 'url';
23
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
24
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
25
+ import { registerTools, cleanupWatchers, addMemoryInternal, executeToolInternal } from './tools.js';
26
+ import {
27
+ applyTemporalDecay,
28
+ closeDatabase,
29
+ getActiveMemoryCount,
30
+ getNamespaceStats,
31
+ getAllAgentStats,
32
+ getAttestationsByDateRange
33
+ } from './database.js';
34
+ import { consolidateMemories, searchHybrid, getOptimizedContext } from './search.js';
35
+ import { startWatcher, stopWatcher } from './watcher.js';
36
+ import { verifyChainIntegrity } from './attestation.js';
37
+ import { memoryEventBus } from './events.js';
38
+ import { logInfo } from './text-utils.js';
39
+
40
+ // Track server birth time for uptime reporting
41
+ const SERVER_START_TIME = Date.now();
42
+
43
+ // Active SSE client response objects
44
+ const sseClients = new Set();
45
+
46
+ // ============================================================
47
+ // SYSTEM PROMPT FORMATTER
48
+ // ============================================================
49
+
50
+ /**
51
+ * Format optimized context data into a structured system-prompt block.
52
+ * Supports three output formats: 'text', 'markdown', 'json'.
53
+ *
54
+ * @param {Object} contextData - Result from getOptimizedContext()
55
+ * @param {string} format - 'text' | 'markdown' | 'json'
56
+ * @param {string|null} agentId
57
+ * @returns {string}
58
+ */
59
+ function formatSystemPrompt(contextData, format, agentId) {
60
+ const { memories, suggested_actions } = contextData;
61
+ const now = new Date().toLocaleString('en-US', { hour12: false }).replace(',', '');
62
+ const count = memories.length;
63
+
64
+ if (format === 'json') {
65
+ return JSON.stringify({ ...contextData, generated_at: new Date().toISOString() }, null, 2);
66
+ }
67
+
68
+ // Group memories by category prefix
69
+ const groups = {
70
+ 'Rules & Conventions': [],
71
+ 'Architecture & Stack': [],
72
+ 'Decisions': [],
73
+ 'Preferences': [],
74
+ 'Context': []
75
+ };
76
+
77
+ for (const m of memories) {
78
+ const c = m.content;
79
+ if (/^(?:Rule|Config):/i.test(c)) groups['Rules & Conventions'].push(c);
80
+ else if (/^(?:Stack|Architecture):/i.test(c)) groups['Architecture & Stack'].push(c);
81
+ else if (/^Decision:/i.test(c)) groups['Decisions'].push(c);
82
+ else if (/^Preference:/i.test(c)) groups['Preferences'].push(c);
83
+ else groups['Context'].push(c);
84
+ }
85
+
86
+ if (format === 'markdown') {
87
+ let md = `# Persyst Memory Context\n`;
88
+ md += `> ${count} memories | Updated: ${now}`;
89
+ if (agentId) md += ` | Agent: \`${agentId}\``;
90
+ md += '\n\n';
91
+
92
+ for (const [section, items] of Object.entries(groups)) {
93
+ if (items.length === 0) continue;
94
+ md += `## ${section}\n`;
95
+ for (const item of items) md += `- ${item}\n`;
96
+ md += '\n';
97
+ }
98
+
99
+ if (suggested_actions.length > 0) {
100
+ md += `## Suggested Actions\n`;
101
+ for (const a of suggested_actions) md += `- ${a}\n`;
102
+ md += '\n';
103
+ }
104
+
105
+ md += `---\n*Refresh: \`curl http://127.0.0.1:4321/system-prompt?format=markdown\`*\n`;
106
+ return md;
107
+ }
108
+
109
+ // Plain text (default) safe to paste into any IDE custom instructions
110
+ let text = `=== PERSYST MEMORY CONTEXT ===\n`;
111
+ text += `Updated: ${now} | ${count} memories`;
112
+ if (agentId) text += ` | Agent: ${agentId}`;
113
+ text += '\n\n';
114
+
115
+ for (const [section, items] of Object.entries(groups)) {
116
+ if (items.length === 0) continue;
117
+ text += `[${section.toUpperCase()}]\n`;
118
+ for (const item of items) text += `• ${item}\n`;
119
+ text += '\n';
120
+ }
121
+
122
+ if (suggested_actions.length > 0) {
123
+ text += `[SUGGESTED ACTIONS]\n`;
124
+ for (const a of suggested_actions) text += `• ${a}\n`;
125
+ text += '\n';
126
+ }
127
+
128
+ text += `=== END MEMORY CONTEXT ===\n`;
129
+ text += `Refresh: curl http://127.0.0.1:${process.env.PORT || '4321'}/system-prompt\n`;
130
+ return text;
131
+ }
132
+
133
+ // ============================================================
134
+ // REQUEST HANDLERS
135
+ // ============================================================
136
+
137
+ async function handleGetRequest(req, res, url) {
138
+ const path = url.pathname;
139
+
140
+ // ----------------------------------------------------------
141
+ // GET /health — server liveness check for orchestrators
142
+ // ----------------------------------------------------------
143
+ if (path === '/health') {
144
+ const uptime = Math.floor((Date.now() - SERVER_START_TIME) / 1000);
145
+ let memories = 0;
146
+ try { memories = getActiveMemoryCount(); } catch (_) {}
147
+ res.writeHead(200, { 'Content-Type': 'application/json' });
148
+ res.end(JSON.stringify({
149
+ ok: true,
150
+ version: '2.2.6',
151
+ uptime_seconds: uptime,
152
+ memories,
153
+ sse_clients: sseClients.size
154
+ }));
155
+ return;
156
+ }
157
+
158
+ // ----------------------------------------------------------
159
+ // GET /stats — memory and agent statistics
160
+ // ----------------------------------------------------------
161
+ if (path === '/stats') {
162
+ try {
163
+ const namespaces = getNamespaceStats();
164
+ const agents = getAllAgentStats();
165
+ const uptime = Math.floor((Date.now() - SERVER_START_TIME) / 1000);
166
+ res.writeHead(200, { 'Content-Type': 'application/json' });
167
+ res.end(JSON.stringify({ uptime_seconds: uptime, namespaces, agents }));
168
+ } catch (err) {
169
+ res.writeHead(500, { 'Content-Type': 'application/json' });
170
+ res.end(JSON.stringify({ error: err.message }));
171
+ }
172
+ return;
173
+ }
174
+
175
+ // ----------------------------------------------------------
176
+ // GET /compliance/export — cryptographic audit log export
177
+ //
178
+ // Query params:
179
+ // start ISO timestamp or Unix epoch (default: beginning of time)
180
+ // end ISO timestamp or Unix epoch (default: current time)
181
+ // format — 'json' (default) | 'markdown'
182
+ // ----------------------------------------------------------
183
+ if (path === '/compliance/export') {
184
+ try {
185
+ const startParam = url.searchParams.get('start');
186
+ const endParam = url.searchParams.get('end');
187
+ const format = url.searchParams.get('format') || 'json';
188
+
189
+ // Parse start and end
190
+ let startDate = '0000-01-01T00:00:00.000Z';
191
+ let endDate = new Date().toISOString();
192
+
193
+ if (startParam) {
194
+ if (!isNaN(startParam)) {
195
+ startDate = new Date(parseInt(startParam, 10)).toISOString();
196
+ } else {
197
+ startDate = new Date(startParam).toISOString();
198
+ }
199
+ }
200
+ if (endParam) {
201
+ if (!isNaN(endParam)) {
202
+ endDate = new Date(parseInt(endParam, 10)).toISOString();
203
+ } else {
204
+ endDate = new Date(endParam).toISOString();
205
+ }
206
+ }
207
+
208
+ const attestations = getAttestationsByDateRange(startDate, endDate);
209
+ const agents = getAllAgentStats();
210
+ const summary = {
211
+ exported_at: new Date().toISOString(),
212
+ start_date: startDate,
213
+ end_date: endDate,
214
+ total_attestations: attestations.length,
215
+ system_integrity: 'SECURE'
216
+ };
217
+
218
+ if (format === 'markdown') {
219
+ let md = `# Persyst Cryptographic Compliance Export\n\n`;
220
+ md += `Exported at: \`${summary.exported_at}\` \n`;
221
+ md += `Period: \`${summary.start_date}\` to \`${summary.end_date}\` \n`;
222
+ md += `Total audit records: **${summary.total_attestations}** \n`;
223
+ md += `System cryptographic status: **${summary.system_integrity}** \n\n`;
224
+
225
+ md += `## Agent Trust Reputation Ledger\n\n`;
226
+ md += `| Agent ID | Created | Confirmed | Contradicted | Trust Score |\n`;
227
+ md += `|---|---|---|---|---|\n`;
228
+ for (const a of agents) {
229
+ md += `| \`${a.agent_id}\` | ${a.memories_created} | ${a.memories_confirmed} | ${a.memories_contradicted} | **${parseFloat(a.reputation_score).toFixed(2)}** |\n`;
230
+ }
231
+ md += `\n`;
232
+
233
+ md += `## Attestation Audit Trail\n\n`;
234
+ if (attestations.length === 0) {
235
+ md += `*No attestations found in the specified range.*\n`;
236
+ } else {
237
+ for (const att of attestations) {
238
+ md += `### Attestation \`${att.attestation_id}\`\n`;
239
+ md += `- **Timestamp:** \`${att.timestamp}\`\n`;
240
+ md += `- **Agent namespace:** \`${att.agent_id || 'shared'}\`\n`;
241
+ md += `- **Query:** *"${att.query}"*\n`;
242
+ md += `- **Previous Attestation Hash:** \`${att.previous_hash || 'GENESIS'}\`\n`;
243
+ md += `- **Current Signature Hash:** \`${att.hash}\`\n`;
244
+ md += `- **Signature:** \`${att.signature.substring(0, 32)}...\`\n`;
245
+
246
+ let retrieved = [];
247
+ try {
248
+ retrieved = JSON.parse(att.memories_retrieved);
249
+ } catch (_) {}
250
+
251
+ if (retrieved.length > 0) {
252
+ md += `- **Memories retrieved:**\n`;
253
+ for (const m of retrieved) {
254
+ md += ` - ID: \`${m.id}\`, Hash: \`${m.content_hash}\`, Score: \`${m.score}\`\n`;
255
+ }
256
+ } else {
257
+ md += `- **Memories retrieved:** None\n`;
258
+ }
259
+ md += `\n---\n`;
260
+ }
261
+ }
262
+ res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
263
+ res.end(md);
264
+ } else {
265
+ res.writeHead(200, { 'Content-Type': 'application/json' });
266
+ res.end(JSON.stringify({
267
+ summary,
268
+ agent_stats: agents,
269
+ attestations: attestations.map(att => ({
270
+ ...att,
271
+ memories_retrieved: (() => {
272
+ try { return JSON.parse(att.memories_retrieved); } catch (_) { return []; }
273
+ })()
274
+ }))
275
+ }, null, 2));
276
+ }
277
+ } catch (err) {
278
+ res.writeHead(500, { 'Content-Type': 'application/json' });
279
+ res.end(JSON.stringify({ error: err.message }));
280
+ }
281
+ return;
282
+ }
283
+
284
+ // ----------------------------------------------------------
285
+ // GET /system-prompt — formatted memory context for IDE injection
286
+ //
287
+ // Query params:
288
+ // query — search query (default: broad project context)
289
+ // max_tokens token budget (default: 1500)
290
+ // agent_id — restrict to this agent's namespace
291
+ // format — 'text' (default) | 'markdown' | 'json'
292
+ // ----------------------------------------------------------
293
+ if (path === '/system-prompt') {
294
+ try {
295
+ const query = url.searchParams.get('query') ||
296
+ 'project conventions architecture preferences rules stack decisions';
297
+ const maxTokens = Math.max(100, parseInt(url.searchParams.get('max_tokens') || '1500', 10));
298
+ const agentId = url.searchParams.get('agent_id') || null;
299
+ const format = url.searchParams.get('format') || 'text';
300
+
301
+ const contextData = await getOptimizedContext(
302
+ query, maxTokens, agentId, null, agentId || null, null
303
+ );
304
+
305
+ const output = formatSystemPrompt(contextData, format, agentId);
306
+
307
+ const contentTypeMap = {
308
+ json: 'application/json',
309
+ markdown: 'text/markdown; charset=utf-8',
310
+ text: 'text/plain; charset=utf-8'
311
+ };
312
+ res.writeHead(200, {
313
+ 'Content-Type': contentTypeMap[format] || 'text/plain; charset=utf-8',
314
+ 'Cache-Control': 'no-cache'
315
+ });
316
+ res.end(output);
317
+ } catch (err) {
318
+ res.writeHead(500, { 'Content-Type': 'application/json' });
319
+ res.end(JSON.stringify({ error: err.message }));
320
+ }
321
+ return;
322
+ }
323
+
324
+ // ----------------------------------------------------------
325
+ // GET /events — Server-Sent Events stream of memory changes
326
+ //
327
+ // Clients subscribe once and receive real-time push notifications
328
+ // for memory_added, memory_deleted, memories_consolidated events.
329
+ //
330
+ // Example (Python):
331
+ // import sseclient, requests
332
+ // for event in sseclient.SSEClient('http://127.0.0.1:4321/events'):
333
+ // print(event.event, event.data)
334
+ //
335
+ // Example (Node.js):
336
+ // const es = new EventSource('http://127.0.0.1:4321/events');
337
+ // es.addEventListener('memory_added', e => console.log(JSON.parse(e.data)));
338
+ // ----------------------------------------------------------
339
+ if (path === '/events') {
340
+ res.writeHead(200, {
341
+ 'Content-Type': 'text/event-stream',
342
+ 'Cache-Control': 'no-cache',
343
+ 'Connection': 'keep-alive',
344
+ 'Access-Control-Allow-Origin': '*',
345
+ 'X-Accel-Buffering': 'no' // Prevents nginx from buffering SSE
346
+ });
347
+
348
+ // Send initial connected event
349
+ res.write(`event: connected\ndata: ${JSON.stringify({
350
+ ok: true,
351
+ timestamp: new Date().toISOString(),
352
+ server_version: '2.2.7'
353
+ })}\n\n`);
354
+
355
+ sseClients.add(res);
356
+
357
+ // Heartbeat every 15s to keep connection alive through proxies
358
+ const heartbeat = setInterval(() => {
359
+ try { res.write(': heartbeat\n\n'); } catch (_) { clearInterval(heartbeat); }
360
+ }, 15000);
361
+
362
+ const onAdded = (data) => {
363
+ try { res.write(`event: memory_added\ndata: ${JSON.stringify(data)}\n\n`); } catch (_) {}
364
+ };
365
+ const onDeleted = (data) => {
366
+ try { res.write(`event: memory_deleted\ndata: ${JSON.stringify(data)}\n\n`); } catch (_) {}
367
+ };
368
+ const onUpdated = (data) => {
369
+ try { res.write(`event: memory_updated\ndata: ${JSON.stringify(data)}\n\n`); } catch (_) {}
370
+ };
371
+ const onRetrieved = (data) => {
372
+ try { res.write(`event: memory_retrieved\ndata: ${JSON.stringify(data)}\n\n`); } catch (_) {}
373
+ };
374
+ const onConsolidated = (data) => {
375
+ try { res.write(`event: memories_consolidated\ndata: ${JSON.stringify(data)}\n\n`); } catch (_) {}
376
+ };
377
+
378
+ memoryEventBus.on('memory_added', onAdded);
379
+ memoryEventBus.on('memory_deleted', onDeleted);
380
+ memoryEventBus.on('memory_updated', onUpdated);
381
+ memoryEventBus.on('memory_retrieved', onRetrieved);
382
+ memoryEventBus.on('memories_consolidated', onConsolidated);
383
+
384
+ req.on('close', () => {
385
+ clearInterval(heartbeat);
386
+ memoryEventBus.off('memory_added', onAdded);
387
+ memoryEventBus.off('memory_deleted', onDeleted);
388
+ memoryEventBus.off('memory_updated', onUpdated);
389
+ memoryEventBus.off('memory_retrieved', onRetrieved);
390
+ memoryEventBus.off('memories_consolidated', onConsolidated);
391
+ sseClients.delete(res);
392
+ console.error(`[persyst-sse] Client disconnected. Active: ${sseClients.size}`);
393
+ });
394
+
395
+ console.error(`[persyst-sse] Client connected. Active: ${sseClients.size}`);
396
+ return; // Keep connection alive — do NOT end response
397
+ }
398
+
399
+ res.writeHead(404, { 'Content-Type': 'application/json' });
400
+ res.end(JSON.stringify({ error: 'Not Found' }));
401
+ }
402
+
403
+ async function handlePostRequest(req, res, payload) {
404
+ const path = new URL(req.url, 'http://127.0.0.1').pathname;
405
+
406
+ // ----------------------------------------------------------
407
+ // POST /remember — quick one-liner memory save
408
+ //
409
+ // The user explicitly wants to save something. No extraction,
410
+ // no filtering, no pattern matching. Just store it.
411
+ //
412
+ // Body: { content: string, importance?: number, namespace?: string }
413
+ // OR: plain text body (e.g. from curl --data "don't forget X")
414
+ //
415
+ // Example:
416
+ // curl -X POST http://127.0.0.1:4321/remember \
417
+ // -H 'Content-Type: text/plain' \
418
+ // --data 'SSL cert expires March 15'
419
+ // ----------------------------------------------------------
420
+ if (path === '/remember') {
421
+ // Support both plain text and JSON bodies
422
+ let content, importance, namespace;
423
+ if (typeof payload === 'string') {
424
+ content = payload.trim();
425
+ importance = 1.0;
426
+ namespace = 'shared';
427
+ } else {
428
+ content = payload.content || payload.text || payload.note || payload.message;
429
+ importance = payload.importance || 1.0;
430
+ namespace = payload.namespace || 'shared';
431
+ }
432
+
433
+ if (!content) {
434
+ res.writeHead(400, { 'Content-Type': 'application/json' });
435
+ res.end(JSON.stringify({ error: 'No content provided. Pass plain text or { content: "..." }' }));
436
+ return;
437
+ }
438
+
439
+ // Prefix with Note: if not already categorized
440
+ const normalizedContent = /^(?:Note|Reminder|Rule|Decision|Preference|Stack|Architecture|Config|Warning|FYI):/i.test(content.trim())
441
+ ? content.trim()
442
+ : `Note: ${content.trim()}`;
443
+
444
+ const result = await addMemoryInternal({
445
+ content: normalizedContent,
446
+ importance,
447
+ agent_id: payload.agent_id || null,
448
+ session_id: payload.session_id || null,
449
+ shared: payload.shared !== false
450
+ });
451
+
452
+ if (!result.error) {
453
+ memoryEventBus.emit('memory_added', {
454
+ id: result.id,
455
+ content: normalizedContent,
456
+ namespace: result.namespace || namespace,
457
+ source: 'user-explicit'
458
+ });
459
+ }
460
+
461
+ res.writeHead(result.error ? 400 : 200, { 'Content-Type': 'application/json' });
462
+ res.end(JSON.stringify(result));
463
+ return;
464
+ }
465
+
466
+ // ----------------------------------------------------------
467
+ // POST /search
468
+ // ----------------------------------------------------------
469
+ if (path === '/search') {
470
+ const { query, limit = 5, agent_id, session_id } = payload;
471
+ if (!query) {
472
+ res.writeHead(400, { 'Content-Type': 'application/json' });
473
+ res.end(JSON.stringify({ error: 'Missing required field: query' }));
474
+ return;
475
+ }
476
+ const results = await searchHybrid(query, limit, agent_id, session_id, agent_id || null);
477
+ if (results && results.length > 0) {
478
+ memoryEventBus.emit('memory_retrieved', {
479
+ tool: 'http/search',
480
+ query,
481
+ count: results.length,
482
+ agent_id: agent_id || 'http',
483
+ namespace: agent_id || 'shared',
484
+ memory_ids: results.map(r => r.id)
485
+ });
486
+ }
487
+ res.writeHead(200, { 'Content-Type': 'application/json' });
488
+ res.end(JSON.stringify({ success: true, results }));
489
+ return;
490
+ }
491
+
492
+ // ----------------------------------------------------------
493
+ // POST /add
494
+ // ----------------------------------------------------------
495
+ if (path === '/add') {
496
+ const { content, importance = 1.0, agent_id, session_id, shared = true } = payload;
497
+ if (!content) {
498
+ res.writeHead(400, { 'Content-Type': 'application/json' });
499
+ res.end(JSON.stringify({ error: 'Missing required field: content' }));
500
+ return;
501
+ }
502
+ const result = await addMemoryInternal({ content, importance, agent_id, session_id, shared });
503
+ if (result.error) {
504
+ res.writeHead(400, { 'Content-Type': 'application/json' });
505
+ } else {
506
+ res.writeHead(200, { 'Content-Type': 'application/json' });
507
+ // Broadcast to SSE subscribers
508
+ memoryEventBus.emit('memory_added', {
509
+ id: result.id,
510
+ content,
511
+ namespace: result.namespace,
512
+ source: agent_id || 'http'
513
+ });
514
+ }
515
+ res.end(JSON.stringify(result));
516
+ return;
517
+ }
518
+
519
+ // ----------------------------------------------------------
520
+ // POST /context
521
+ // ----------------------------------------------------------
522
+ if (path === '/context') {
523
+ const { query, max_tokens = 2000, agent_id, session_id, intent } = payload;
524
+ if (!query) {
525
+ res.writeHead(400, { 'Content-Type': 'application/json' });
526
+ res.end(JSON.stringify({ error: 'Missing required field: query' }));
527
+ return;
528
+ }
529
+ const context = await getOptimizedContext(query, max_tokens, agent_id, session_id, agent_id || null, intent);
530
+ const retrievedCount = context?.memories?.length ?? 0;
531
+ if (retrievedCount > 0) {
532
+ memoryEventBus.emit('memory_retrieved', {
533
+ tool: 'http/context',
534
+ query,
535
+ count: retrievedCount,
536
+ agent_id: agent_id || 'http',
537
+ namespace: agent_id || 'shared',
538
+ token_budget: max_tokens,
539
+ memory_ids: context.memories.map(m => m.id)
540
+ });
541
+ }
542
+ res.writeHead(200, { 'Content-Type': 'application/json' });
543
+ res.end(JSON.stringify(context));
544
+ return;
545
+ }
546
+
547
+ // ----------------------------------------------------------
548
+ // POST /tool — generic MCP tool invocation
549
+ // ----------------------------------------------------------
550
+ if (path === '/tool') {
551
+ const { name, arguments: args } = payload;
552
+ if (!name) {
553
+ res.writeHead(400, { 'Content-Type': 'application/json' });
554
+ res.end(JSON.stringify({ error: 'Missing required field: name' }));
555
+ return;
556
+ }
557
+ let result;
558
+ try {
559
+ result = await executeToolInternal(name, args || {});
560
+ } catch (err) {
561
+ res.writeHead(400, { 'Content-Type': 'application/json' });
562
+ res.end(JSON.stringify({ error: err.message }));
563
+ return;
564
+ }
565
+ res.writeHead(200, { 'Content-Type': 'application/json' });
566
+ res.end(JSON.stringify(result));
567
+ return;
568
+ }
569
+
570
+ // ----------------------------------------------------------
571
+ // POST /verify — chain integrity check
572
+ // ----------------------------------------------------------
573
+ if (path === '/verify') {
574
+ const attestationId = payload?.attestation_id;
575
+ const result = verifyChainIntegrity(attestationId);
576
+ res.writeHead(200, { 'Content-Type': 'application/json' });
577
+ res.end(JSON.stringify(result));
578
+ return;
579
+ }
580
+
581
+ // ----------------------------------------------------------
582
+ // POST /batch/add — store multiple memories in one round trip
583
+ //
584
+ // Body: { memories: [{ content, importance?, agent_id?, shared? }, ...] }
585
+ // Returns: { success, results: [...], stored, skipped, errors }
586
+ //
587
+ // Designed for:
588
+ // - Swarm agents ingesting session summaries in bulk
589
+ // - Migration tools
590
+ // - CI pipelines storing build/test results
591
+ // ----------------------------------------------------------
592
+ if (path === '/batch/add') {
593
+ const { memories } = payload;
594
+ if (!Array.isArray(memories) || memories.length === 0) {
595
+ res.writeHead(400, { 'Content-Type': 'application/json' });
596
+ res.end(JSON.stringify({ error: 'memories must be a non-empty array' }));
597
+ return;
598
+ }
599
+
600
+ // Hard cap: prevent abuse
601
+ if (memories.length > 200) {
602
+ res.writeHead(400, { 'Content-Type': 'application/json' });
603
+ res.end(JSON.stringify({ error: 'Batch size exceeds maximum of 200' }));
604
+ return;
605
+ }
606
+
607
+ const results = [];
608
+ let stored = 0;
609
+ let skipped = 0;
610
+ let errors = 0;
611
+
612
+ for (const mem of memories) {
613
+ const { content, importance = 1.0, agent_id, session_id, shared = true } = mem;
614
+ if (!content) {
615
+ results.push({ error: 'Missing content', input: mem });
616
+ errors++;
617
+ continue;
618
+ }
619
+ try {
620
+ const result = await addMemoryInternal({ content, importance, agent_id, session_id, shared });
621
+ results.push(result);
622
+ if (result.error) {
623
+ errors++;
624
+ } else if (result.message && result.message.includes('already exists')) {
625
+ skipped++;
626
+ } else {
627
+ stored++;
628
+ memoryEventBus.emit('memory_added', {
629
+ id: result.id,
630
+ content,
631
+ namespace: result.namespace,
632
+ source: agent_id || 'batch'
633
+ });
634
+ }
635
+ } catch (err) {
636
+ results.push({ error: err.message, input: mem });
637
+ errors++;
638
+ }
639
+ }
640
+
641
+ res.writeHead(200, { 'Content-Type': 'application/json' });
642
+ res.end(JSON.stringify({ success: true, results, stored, skipped, errors }));
643
+ return;
644
+ }
645
+
646
+ // ----------------------------------------------------------
647
+ // POST /batch/search — run multiple queries in one round trip
648
+ //
649
+ // Body: { queries: string[] | Array<{query, limit?, agent_id?}>, limit?: number }
650
+ // Returns: { results: { "<query>": [...memories] } }
651
+ //
652
+ // Designed for:
653
+ // - Swarm agents loading context for multiple topics at once
654
+ // - Parallel memory retrieval without sequential round trips
655
+ // ----------------------------------------------------------
656
+ if (path === '/batch/search') {
657
+ const { queries, limit = 5 } = payload;
658
+ if (!Array.isArray(queries) || queries.length === 0) {
659
+ res.writeHead(400, { 'Content-Type': 'application/json' });
660
+ res.end(JSON.stringify({ error: 'queries must be a non-empty array' }));
661
+ return;
662
+ }
663
+
664
+ if (queries.length > 50) {
665
+ res.writeHead(400, { 'Content-Type': 'application/json' });
666
+ res.end(JSON.stringify({ error: 'Batch query size exceeds maximum of 50' }));
667
+ return;
668
+ }
669
+
670
+ // Run all searches in parallel for speed
671
+ const searchPromises = queries.map(async (q) => {
672
+ if (typeof q === 'string') {
673
+ return { key: q, results: await searchHybrid(q, limit, null, null, null) };
674
+ } else if (q && typeof q === 'object' && q.query) {
675
+ return {
676
+ key: q.query,
677
+ results: await searchHybrid(q.query, q.limit || limit, q.agent_id || null, null, q.agent_id || null)
678
+ };
679
+ }
680
+ return { key: String(q), results: [] };
681
+ });
682
+
683
+ const settled = await Promise.allSettled(searchPromises);
684
+ const results = {};
685
+ for (const s of settled) {
686
+ if (s.status === 'fulfilled') {
687
+ results[s.value.key] = s.value.results;
688
+ }
689
+ }
690
+
691
+ res.writeHead(200, { 'Content-Type': 'application/json' });
692
+ res.end(JSON.stringify({ success: true, results }));
693
+ return;
694
+ }
695
+
696
+ res.writeHead(404, { 'Content-Type': 'application/json' });
697
+ res.end(JSON.stringify({ error: 'Endpoint Not Found' }));
698
+ }
699
+
700
+ // ============================================================
701
+ // MAIN SERVER STARTUP
702
+ // ============================================================
703
+
704
+ export async function startServer() {
705
+ // --- Create MCP server ---
706
+ const server = new McpServer({
707
+ name: 'persyst',
708
+ version: '2.2.5'
709
+ });
710
+
711
+ // --- Register all tools ---
712
+ const registeredCount = registerTools(server);
713
+ logInfo(`[persyst] ${registeredCount} tools registered ✓`);
714
+
715
+ // --- Connect via stdio IMMEDIATELY so MCP handshake completes instantly (<10ms) ---
716
+ const transport = new StdioServerTransport();
717
+ await server.connect(transport);
718
+
719
+ logInfo('[persyst] MCP server running on stdio ✓');
720
+ logInfo('[persyst] Ready to receive tool calls');
721
+
722
+ // Interactive Terminal Banner (only shown when run directly by a user in terminal)
723
+ if (process.stderr.isTTY || process.stdout.isTTY) {
724
+ console.error(`\n[OK] Persyst MCP Server is active and listening (stdio mode)`);
725
+ console.error(`[OK] Workspace Project: ${process.env.PERSYST_PROJECT || 'shared'}`);
726
+ console.error(`[OK] Local HTTP Gateway: http://127.0.0.1:${process.env.PORT || '4321'}`);
727
+ console.error(`[OK] Process ID: ${process.pid} | Press Ctrl+C to stop.\n`);
728
+ }
729
+
730
+ // Defer background services & HTTP server so stdio handshake is never blocked
731
+ let httpServer = null;
732
+ let decayTimer = null;
733
+ let consolidationTimer = null;
734
+ let sseHealthCheck = null;
735
+
736
+ const shutdown = () => {
737
+ logInfo('[persyst] Shutting down...');
738
+ if (decayTimer) clearInterval(decayTimer);
739
+ if (consolidationTimer) clearInterval(consolidationTimer);
740
+ if (sseHealthCheck) clearInterval(sseHealthCheck);
741
+ stopWatcher();
742
+ cleanupWatchers();
743
+
744
+ for (const client of sseClients) {
745
+ try {
746
+ client.write(`event: server_shutdown\ndata: ${JSON.stringify({ message: 'Server shutting down' })}\n\n`);
747
+ client.end();
748
+ } catch (_) {}
749
+ }
750
+ sseClients.clear();
751
+
752
+ if (httpServer) httpServer.close();
753
+ closeDatabase();
754
+ };
755
+ process.on('SIGINT', shutdown);
756
+ process.on('SIGTERM', shutdown);
757
+
758
+ setTimeout(() => {
759
+ // --- Start background log watcher daemon (skip in test mode) ---
760
+ if (process.env.NODE_ENV !== 'test') {
761
+ startWatcher();
762
+ }
763
+
764
+ // --- Gateway configuration ---
765
+ const httpPort = parseInt(process.env.PORT || '4321', 10);
766
+ const httpHost = process.env.PERSYST_HOST || '127.0.0.1';
767
+ const configuredApiKey = process.env.PERSYST_API_KEY || null;
768
+
769
+ if (configuredApiKey) {
770
+ logInfo(`[persyst] API key auth enabled — endpoints require Authorization: Bearer <key>`);
771
+ }
772
+ if (httpHost !== '127.0.0.1') {
773
+ logInfo(`[persyst] ⚠️ Gateway bound to ${httpHost} — ensure PERSYST_API_KEY is set for security`);
774
+ }
775
+
776
+ // --- Start local HTTP Gateway ---
777
+ httpServer = http.createServer((req, res) => {
778
+ // CORS headers
779
+ res.setHeader('Access-Control-Allow-Origin', '*');
780
+ res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
781
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
782
+
783
+ if (req.method === 'OPTIONS') {
784
+ res.writeHead(204);
785
+ res.end();
786
+ return;
787
+ }
788
+
789
+ if (configuredApiKey) {
790
+ const urlPath = new URL(req.url || '/', 'http://127.0.0.1').pathname;
791
+ if (urlPath !== '/health') {
792
+ const authHeader = req.headers['authorization'] || '';
793
+ const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null;
794
+ if (token !== configuredApiKey) {
795
+ res.writeHead(401, { 'Content-Type': 'application/json' });
796
+ res.end(JSON.stringify({
797
+ error: 'Unauthorized. Set header: Authorization: Bearer <PERSYST_API_KEY>'
798
+ }));
799
+ return;
800
+ }
801
+ }
802
+ }
803
+
804
+ const url = new URL(req.url || '/', `http://${req.headers.host || '127.0.0.1'}`);
805
+ const path = url.pathname;
806
+
807
+ if (req.method === 'GET') {
808
+ handleGetRequest(req, res, path, url);
809
+ return;
810
+ }
811
+
812
+ if (req.method === 'POST') {
813
+ let body = '';
814
+ req.on('data', chunk => {
815
+ body += chunk;
816
+ if (body.length > 10 * 1024 * 1024) {
817
+ res.writeHead(413, { 'Content-Type': 'application/json' });
818
+ res.end(JSON.stringify({ error: 'Payload too large. Max 10MB.' }));
819
+ req.destroy();
820
+ }
821
+ });
822
+ req.on('end', () => {
823
+ try {
824
+ const payload = body ? JSON.parse(body) : {};
825
+ handlePostRequest(req, res, payload).catch(err => {
826
+ try {
827
+ res.writeHead(500, { 'Content-Type': 'application/json' });
828
+ res.end(JSON.stringify({ error: err.message }));
829
+ } catch (_) {}
830
+ });
831
+ } catch (err) {
832
+ res.writeHead(400, { 'Content-Type': 'application/json' });
833
+ res.end(JSON.stringify({ error: `Invalid JSON payload: ${err.message}` }));
834
+ }
835
+ });
836
+ return;
837
+ }
838
+
839
+ res.writeHead(405, { 'Content-Type': 'application/json' });
840
+ res.end(JSON.stringify({ error: 'Method not allowed' }));
841
+ });
842
+
843
+ httpServer.on('error', (err) => {
844
+ if (err.code === 'EADDRINUSE') {
845
+ logInfo(`[persyst] HTTP Gateway port ${httpPort} already in use. Stdio MCP server will continue.`);
846
+ } else {
847
+ console.error('[persyst] HTTP Gateway error:', err.message);
848
+ }
849
+ });
850
+
851
+ httpServer.listen(httpPort, httpHost, () => {
852
+ logInfo(`[persyst] HTTP Gateway listening on http://${httpHost}:${httpPort} ✓`);
853
+ });
854
+
855
+ decayTimer = setInterval(applyTemporalDecay, 3600000);
856
+
857
+ consolidationTimer = setInterval(async () => {
858
+ logInfo('[persyst] Running scheduled daily memory consolidation sweep...');
859
+ try {
860
+ const report = await consolidateMemories();
861
+ logInfo(`[persyst] Consolidation sweep: consolidated ${report.consolidated_groups} duplicate groups.`);
862
+ if (report.consolidated_groups > 0) {
863
+ memoryEventBus.emit('memories_consolidated', {
864
+ consolidated_groups: report.consolidated_groups,
865
+ details: report.details
866
+ });
867
+ }
868
+ } catch (err) {
869
+ console.error('[persyst] Daily consolidation sweep failed:', err.message);
870
+ }
871
+ }, 86400000);
872
+
873
+ sseHealthCheck = setInterval(() => {
874
+ for (const client of sseClients) {
875
+ try {
876
+ client.write(': health-check\n\n');
877
+ } catch (_) {
878
+ try { client.end(); } catch (_) {}
879
+ sseClients.delete(client);
880
+ }
881
+ }
882
+ }, 30000);
883
+ }, 50);
884
+ }