persyst-mcp 2.2.4 → 2.2.5

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,183 +1,723 @@
1
- /**
2
- * server.js — MCP Server & Local HTTP Gateway Setup
3
- *
4
- * Creates the MCP server, registers all tools, and connects via stdio.
5
- * Also spins up a local HTTP/JSON Gateway on port 4321 to support low-latency
6
- * prompt hooks and local agent swarms without subprocess overhead.
7
- *
8
- * All logging goes to stderr via console.error().
9
- */
10
-
11
- import http from 'http';
12
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
13
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
14
- import { registerTools, cleanupWatchers, addMemoryInternal, executeToolInternal } from './tools.js';
15
- import { applyTemporalDecay, closeDatabase } from './database.js';
16
- import { consolidateMemories, searchHybrid, getOptimizedContext } from './search.js';
17
- import { startWatcher, stopWatcher } from './watcher.js';
18
- import { verifyChainIntegrity } from './attestation.js';
19
-
20
- /**
21
- * Start the Persyst MCP server & HTTP Gateway.
22
- */
23
- export async function startServer() {
24
- // --- Create MCP server ---
25
- const server = new McpServer({
26
- name: 'persyst',
27
- version: '2.2.1'
28
- });
29
-
30
- // --- Register all tools ---
31
- const registeredCount = registerTools(server);
32
- console.error(`[persyst] ${registeredCount} tools registered ✓`);
33
-
34
- // --- Start background log watcher daemon ---
35
- startWatcher();
36
-
37
- // --- Start local HTTP Gateway (port 4321) ---
38
- const httpPort = 4321;
39
- const httpServer = http.createServer((req, res) => {
40
- // CORS headers for local swarms and browser testing
41
- res.setHeader('Access-Control-Allow-Origin', '*');
42
- res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
43
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
44
-
45
- if (req.method === 'OPTIONS') {
46
- res.writeHead(204);
47
- res.end();
48
- return;
49
- }
50
-
51
- if (req.method !== 'POST') {
52
- res.writeHead(405, { 'Content-Type': 'application/json' });
53
- res.end(JSON.stringify({ error: 'Method Not Allowed. Use POST.' }));
54
- return;
55
- }
56
-
57
- let body = '';
58
- req.on('data', chunk => { body += chunk; });
59
- req.on('end', async () => {
60
- try {
61
- const payload = JSON.parse(body || '{}');
62
-
63
- if (req.url === '/search') {
64
- const { query, limit = 5, agent_id, session_id } = payload;
65
- if (!query) {
66
- res.writeHead(400, { 'Content-Type': 'application/json' });
67
- res.end(JSON.stringify({ error: 'Missing required field: query' }));
68
- return;
69
- }
70
- const results = await searchHybrid(query, limit, agent_id, session_id, agent_id || null);
71
- res.writeHead(200, { 'Content-Type': 'application/json' });
72
- res.end(JSON.stringify({ success: true, results }));
73
- return;
74
- }
75
-
76
- if (req.url === '/add') {
77
- const { content, importance = 1.0, agent_id, session_id, shared = true } = payload;
78
- if (!content) {
79
- res.writeHead(400, { 'Content-Type': 'application/json' });
80
- res.end(JSON.stringify({ error: 'Missing required field: content' }));
81
- return;
82
- }
83
- const result = await addMemoryInternal({ content, importance, agent_id, session_id, shared });
84
- if (result.error) {
85
- res.writeHead(400, { 'Content-Type': 'application/json' });
86
- } else {
87
- res.writeHead(200, { 'Content-Type': 'application/json' });
88
- }
89
- res.end(JSON.stringify(result));
90
- return;
91
- }
92
-
93
- if (req.url === '/context') {
94
- const { query, max_tokens = 2000, agent_id, session_id } = payload;
95
- if (!query) {
96
- res.writeHead(400, { 'Content-Type': 'application/json' });
97
- res.end(JSON.stringify({ error: 'Missing required field: query' }));
98
- return;
99
- }
100
- const context = await getOptimizedContext(query, max_tokens, agent_id, session_id);
101
- res.writeHead(200, { 'Content-Type': 'application/json' });
102
- res.end(JSON.stringify(context));
103
- return;
104
- }
105
-
106
- if (req.url === '/tool') {
107
- const { name, arguments: args } = payload;
108
- if (!name) {
109
- res.writeHead(400, { 'Content-Type': 'application/json' });
110
- res.end(JSON.stringify({ error: 'Missing required field: name' }));
111
- return;
112
- }
113
- const result = await executeToolInternal(name, args || {});
114
- res.writeHead(200, { 'Content-Type': 'application/json' });
115
- res.end(JSON.stringify(result));
116
- return;
117
- }
118
-
119
- if (req.url === '/verify') {
120
- const result = await verifyChainIntegrity();
121
- res.writeHead(200, { 'Content-Type': 'application/json' });
122
- res.end(JSON.stringify(result));
123
- return;
124
- }
125
-
126
- res.writeHead(404, { 'Content-Type': 'application/json' });
127
- res.end(JSON.stringify({ error: 'Endpoint Not Found' }));
128
- } catch (err) {
129
- res.writeHead(500, { 'Content-Type': 'application/json' });
130
- res.end(JSON.stringify({ error: err.message }));
131
- }
132
- });
133
- });
134
-
135
- httpServer.on('error', (err) => {
136
- if (err.code === 'EADDRINUSE') {
137
- console.error(`[persyst] HTTP Gateway port ${httpPort} is already in use. Stdio MCP server will continue running.`);
138
- } else {
139
- console.error('[persyst] HTTP Gateway error:', err.message);
140
- }
141
- });
142
-
143
- httpServer.listen(httpPort, '127.0.0.1', () => {
144
- console.error(`[persyst] HTTP Gateway listening on http://127.0.0.1:${httpPort} ✓`);
145
- });
146
-
147
- // --- Start temporal decay timer ---
148
- // Runs every hour: reduces importance of memories not accessed in 7+ days
149
- const decayTimer = setInterval(applyTemporalDecay, 3600000);
150
-
151
- // --- Start daily consolidation sweep ---
152
- // Runs every 24 hours: merges similar memories
153
- const consolidationTimer = setInterval(async () => {
154
- console.error('[persyst] Running scheduled daily memory consolidation sweep...');
155
- try {
156
- const report = await consolidateMemories();
157
- console.error(`[persyst] Consolidation sweep completed: consolidated ${report.consolidated_groups} duplicate groups.`);
158
- } catch (err) {
159
- console.error('[persyst] Daily consolidation sweep failed:', err.message);
160
- }
161
- }, 86400000);
162
-
163
- // --- Graceful shutdown ---
164
- const shutdown = () => {
165
- console.error('[persyst] Shutting down...');
166
- clearInterval(decayTimer);
167
- clearInterval(consolidationTimer);
168
- stopWatcher(); // Stop background log watcher
169
- cleanupWatchers(); // Stop all git repo watchers
170
- httpServer.close(); // Close HTTP gateway
171
- closeDatabase();
172
- process.exit(0);
173
- };
174
- process.on('SIGINT', shutdown);
175
- process.on('SIGTERM', shutdown);
176
-
177
- // --- Connect via stdio ---
178
- const transport = new StdioServerTransport();
179
- await server.connect(transport);
180
-
181
- console.error('[persyst] MCP server running on stdio ✓');
182
- console.error('[persyst] Ready to receive tool calls');
183
- }
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
+ }