-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
475 lines (443 loc) · 19.4 KB
/
Copy pathserver.ts
File metadata and controls
475 lines (443 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/**
* GitMem MCP Server
*
* Registers all tools and handles MCP protocol communication.
* Tool definitions are in ./tools/definitions.ts
*/
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const pkg = require("../package.json") as { version: string };
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { sessionStart, sessionRefresh } from "./tools/session-start.js";
import type { SessionRefreshParams } from "./tools/session-start.js";
import { sessionClose } from "./tools/session-close.js";
import { createLearning } from "./tools/create-learning.js";
import { createDecision } from "./tools/create-decision.js";
import { recordScarUsage } from "./tools/record-scar-usage.js";
import { recordScarUsageBatch } from "./tools/record-scar-usage-batch.js";
import { recall } from "./tools/recall.js";
import { confirmScars } from "./tools/confirm-scars.js";
import { reflectScars } from "./tools/reflect-scars.js";
import { saveTranscript } from "./tools/save-transcript.js";
import { getTranscript } from "./tools/get-transcript.js";
import { searchTranscripts } from "./tools/search-transcripts.js";
import type { SearchTranscriptsParams } from "./tools/search-transcripts.js";
import { search } from "./tools/search.js";
import { log } from "./tools/log.js";
import { analyze } from "./tools/analyze.js";
import type { AnalyzeParams } from "./tools/analyze.js";
import { graphTraverse } from "./tools/graph-traverse.js";
import type { GraphTraverseParams } from "./tools/graph-traverse.js";
import { prepareContext } from "./tools/prepare-context.js";
import type { PrepareContextParams } from "./tools/prepare-context.js";
import { absorbObservations } from "./tools/absorb-observations.js";
import { listThreads } from "./tools/list-threads.js";
import { resolveThread } from "./tools/resolve-thread.js";
import { createThread } from "./tools/create-thread.js";
import type { CreateThreadParams } from "./tools/create-thread.js";
import { promoteSuggestion } from "./tools/promote-suggestion.js";
import type { PromoteSuggestionParams } from "./tools/promote-suggestion.js";
import { dismissSuggestion } from "./tools/dismiss-suggestion.js";
import type { DismissSuggestionParams } from "./tools/dismiss-suggestion.js";
import { cleanupThreads } from "./tools/cleanup-threads.js";
import type { CleanupThreadsParams } from "./tools/cleanup-threads.js";
import { archiveLearning } from "./tools/archive-learning.js";
import type { ArchiveLearningParams } from "./tools/archive-learning.js";
import type { AbsorbObservationsParams, ListThreadsParams, ResolveThreadParams } from "./types/index.js";
import {
getCacheStatus,
checkCacheHealth,
flushCache,
startBackgroundInit,
} from "./services/startup.js";
import { getEffectTracker } from "./services/effect-tracker.js";
import { RIPPLE, ANSI } from "./services/display-protocol.js";
import { getProject } from "./services/session-state.js";
import { checkEnforcement } from "./services/enforcement.js";
import {
getTier,
hasSupabase,
hasCacheManagement,
hasBatchOperations,
hasTranscripts,
} from "./services/tier.js";
import { getRegisteredTools } from "./tools/definitions.js";
import { validateToolArgs } from "./schemas/registry.js";
import type { Project } from "./types/index.js";
import type {
SessionStartParams,
SessionCloseParams,
CreateLearningParams,
CreateDecisionParams,
RecordScarUsageParams,
RecordScarUsageBatchParams,
SaveTranscriptParams,
GetTranscriptParams,
ConfirmScarsParams,
ReflectScarsParams,
} from "./types/index.js";
import type { RecallParams } from "./tools/recall.js";
import type { SearchParams } from "./tools/search.js";
import type { LogParams } from "./tools/log.js";
/**
* Create and configure the MCP server
*/
export function createServer(): Server {
const server = new Server(
{
name: "gitmem-mcp",
version: pkg.version,
},
{
capabilities: {
tools: {},
},
}
);
// Register list tools handler (tier-gated)
const registeredTools = getRegisteredTools();
const registeredToolNames = new Set(registeredTools.map(t => t.name));
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: registeredTools,
}));
// Register call tool handler
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
const toolArgs = (args || {}) as Record<string, unknown>;
// Guard: reject calls to tools not available in current tier
if (!registeredToolNames.has(name)) {
return {
content: [
{
type: "text" as const,
text: JSON.stringify({ error: `Unknown tool: ${name}. Available tools depend on your GitMem tier (current: ${getTier()}).` }),
},
],
isError: true,
};
}
// Validate tool arguments against registered Zod schemas
const validationError = validateToolArgs(name, toolArgs);
if (validationError) {
return {
content: [
{
type: "text" as const,
text: JSON.stringify({ error: validationError }),
},
],
isError: true,
};
}
// Server-side enforcement: advisory warnings for protocol violations
const enforcement = checkEnforcement(name);
try {
let result: unknown;
switch (name) {
case "recall":
case "gitmem-r":
result = await recall(toolArgs as unknown as RecallParams);
break;
case "confirm_scars":
case "gitmem-cs":
case "gm-confirm":
result = await confirmScars(toolArgs as unknown as ConfirmScarsParams);
break;
case "reflect_scars":
case "gitmem-rf":
case "gm-reflect":
result = await reflectScars(toolArgs as unknown as ReflectScarsParams);
break;
case "session_start":
case "gitmem-ss":
case "gm-open":
result = await sessionStart(toolArgs as unknown as SessionStartParams);
break;
case "session_refresh":
case "gitmem-sr":
case "gm-refresh":
result = await sessionRefresh(toolArgs as unknown as SessionRefreshParams);
break;
case "session_close":
case "gitmem-sc":
case "gm-close":
result = await sessionClose(toolArgs as unknown as SessionCloseParams);
break;
case "create_learning":
case "gitmem-cl":
case "gm-scar":
result = await createLearning(toolArgs as unknown as CreateLearningParams);
break;
case "create_decision":
case "gitmem-cd":
result = await createDecision(toolArgs as unknown as CreateDecisionParams);
break;
case "record_scar_usage":
case "gitmem-rs":
result = await recordScarUsage(toolArgs as unknown as RecordScarUsageParams);
break;
case "record_scar_usage_batch":
case "gitmem-rsb":
result = await recordScarUsageBatch(toolArgs as unknown as RecordScarUsageBatchParams);
break;
case "save_transcript":
case "gitmem-st":
result = await saveTranscript(toolArgs as unknown as SaveTranscriptParams);
break;
case "get_transcript":
case "gitmem-gt":
result = await getTranscript(toolArgs as unknown as GetTranscriptParams);
break;
case "search_transcripts":
case "gitmem-stx":
case "gm-stx":
result = await searchTranscripts(toolArgs as unknown as SearchTranscriptsParams);
break;
case "search":
case "gitmem-search":
case "gm-search":
result = await search(toolArgs as unknown as SearchParams);
break;
case "log":
case "gitmem-log":
case "gm-log":
result = await log(toolArgs as unknown as LogParams);
break;
case "analyze":
case "gitmem-analyze":
case "gm-analyze":
result = await analyze(toolArgs as unknown as AnalyzeParams);
break;
case "prepare_context":
case "gitmem-pc":
case "gm-pc":
result = await prepareContext(toolArgs as unknown as PrepareContextParams);
break;
case "absorb_observations":
case "gitmem-ao":
case "gm-absorb":
result = await absorbObservations(toolArgs as unknown as AbsorbObservationsParams);
break;
case "list_threads":
case "gitmem-lt":
case "gm-threads":
result = await listThreads(toolArgs as unknown as ListThreadsParams);
break;
case "resolve_thread":
case "gitmem-rt":
case "gm-resolve":
result = await resolveThread(toolArgs as unknown as ResolveThreadParams);
break;
case "create_thread":
case "gitmem-ct":
case "gm-thread-new":
result = await createThread(toolArgs as unknown as CreateThreadParams);
break;
case "promote_suggestion":
case "gitmem-ps":
case "gm-promote":
result = await promoteSuggestion(toolArgs as unknown as PromoteSuggestionParams);
break;
case "dismiss_suggestion":
case "gitmem-ds":
case "gm-dismiss":
result = await dismissSuggestion(toolArgs as unknown as DismissSuggestionParams);
break;
case "cleanup_threads":
case "gitmem-cleanup":
case "gm-cleanup":
result = await cleanupThreads(toolArgs as unknown as CleanupThreadsParams);
break;
case "archive_learning":
case "gitmem-al":
case "gm-archive":
result = await archiveLearning(toolArgs as unknown as ArchiveLearningParams);
break;
case "gitmem-help": {
const tier = getTier();
const commands = [
{ alias: "gitmem-r", full: "recall", description: "Check scars before taking action" },
{ alias: "gitmem-cs", full: "confirm_scars", description: "Confirm recalled scars (APPLYING/N_A/REFUTED)" },
{ alias: "gitmem-rf", full: "reflect_scars", description: "End-of-session scar reflection (OBEYED/REFUTED)" },
{ alias: "gitmem-ss", full: "session_start", description: "Initialize session with context" },
{ alias: "gitmem-sr", full: "session_refresh", description: "Refresh context for active session" },
{ alias: "gitmem-sc", full: "session_close", description: "Close session with compliance validation" },
{ alias: "gitmem-cl", full: "create_learning", description: "Create scar/win/pattern entry" },
{ alias: "gitmem-cd", full: "create_decision", description: "Log architectural/operational decision" },
{ alias: "gitmem-rs", full: "record_scar_usage", description: "Track scar application" },
{ alias: "gitmem-search", full: "search", description: "Search institutional memory (exploration)" },
{ alias: "gitmem-log", full: "log", description: "List recent learnings chronologically" },
{ alias: "gitmem-analyze", full: "analyze", description: "Session analytics and insights" },
{ alias: "gitmem-pc", full: "prepare_context", description: "Generate memory payload for sub-agents" },
{ alias: "gitmem-ao", full: "absorb_observations", description: "Capture sub-agent/teammate observations" },
{ alias: "gitmem-lt", full: "list_threads", description: "List open threads across sessions" },
{ alias: "gitmem-rt", full: "resolve_thread", description: "Mark a thread as resolved" },
{ alias: "gitmem-ps", full: "promote_suggestion", description: "Promote a suggested thread to open thread" },
{ alias: "gitmem-ds", full: "dismiss_suggestion", description: "Dismiss a suggested thread" },
{ alias: "gitmem-cleanup", full: "cleanup_threads", description: "Triage threads by lifecycle health" },
{ alias: "gitmem-health", full: "health", description: "Show write health for fire-and-forget operations" },
{ alias: "gitmem-al", full: "archive_learning", description: "Archive a scar/win/pattern (is_active=false)" },
{ alias: "gitmem-graph", full: "graph_traverse", description: "Traverse knowledge graph over institutional memory" },
];
if (hasBatchOperations()) {
commands.push({ alias: "gitmem-rsb", full: "record_scar_usage_batch", description: "Track multiple scars (batch)" });
}
if (hasTranscripts()) {
commands.push(
{ alias: "gitmem-st", full: "save_transcript", description: "Save session transcript to storage" },
{ alias: "gitmem-gt", full: "get_transcript", description: "Retrieve session transcript" },
{ alias: "gitmem-stx", full: "search_transcripts", description: "Semantic search over transcript chunks" },
);
}
if (hasCacheManagement()) {
commands.push(
{ alias: "gitmem-cache-status", full: "cache_status", description: "Show cache status" },
{ alias: "gitmem-cache-health", full: "cache_health", description: "Compare local vs remote" },
{ alias: "gitmem-cache-flush", full: "cache_flush", description: "Force reload from Supabase" },
);
}
// Filter to only show commands whose canonical tool is actually registered
const visibleCommands = commands.filter(c => registeredToolNames.has(c.full));
// Build command table for display
const cmdLines = visibleCommands.map(c => ` ${c.alias.padEnd(22)} ${c.description}`).join("\n");
const display = [
`${RIPPLE} ${ANSI.red}gitmem${ANSI.reset} v${pkg.version} · ${tier} · ${registeredTools.length} tools · ${hasSupabase() ? "supabase" : "local (.gitmem/)"}`,
" Memory that compounds.",
"",
cmdLines,
"",
"**For detailed documentation and help, visit https://gitmem.ai/docs**",
"",
"───────────────────────────────────────────────────",
"DISPLAY PROTOCOL: Output the content above verbatim as your response text.",
"Tool results are collapsed in the CLI — the user cannot see them unless you echo them.",
].join("\n");
result = {
version: pkg.version,
tier,
tools_registered: registeredTools.length,
storage: hasSupabase() ? "supabase" : "local (.gitmem/)",
commands: visibleCommands,
display,
};
break;
}
// Effect Tracker health report
case "health":
case "gitmem-health":
case "gm-health": {
const failureLimit = typeof toolArgs.failure_limit === "number" ? toolArgs.failure_limit : 10;
const tracker = getEffectTracker();
const report = tracker.getHealthReport(failureLimit);
const summary = tracker.formatSummary();
result = {
...report,
text: summary || "No tracked effects this session.",
};
break;
}
// Knowledge graph traversal (Phase 3)
case "graph_traverse":
case "gitmem-graph":
case "gm-graph":
result = await graphTraverse(toolArgs as unknown as GraphTraverseParams);
break;
// Cache management tools
case "gitmem-cache-status":
case "gm-cache-s":
result = getCacheStatus((toolArgs.project as Project) || getProject() as Project || "default");
break;
case "gitmem-cache-health":
case "gm-cache-h":
result = await checkCacheHealth((toolArgs.project as Project) || getProject() as Project || "default");
break;
case "gitmem-cache-flush":
case "gm-cache-f":
result = await flushCache((toolArgs.project as Project) || getProject() as Project || "default");
break;
default:
throw new Error(`Unknown tool: ${name}`);
}
// Build the response text.
// When a `display` field exists, use it directly as the response.
// The display should contain everything both the user and LLM need —
// formatted output for readability, plus any key IDs/refs inline.
// No separate machine-data blob: it bloats the response and causes
// CLI auto-collapse ("+N lines"), hurting the user experience.
let responseText: string;
if (result && typeof result === "object" && "display" in result && typeof result.display === "string") {
responseText = (result as Record<string, unknown>).display as string;
} else if (result && typeof result === "object" && "text" in result && typeof result.text === "string") {
responseText = (result as { text: string }).text;
} else {
responseText = JSON.stringify(result, null, 2);
}
// Prepend enforcement warning if present (advisory, non-blocking)
if (enforcement.warning) {
responseText = enforcement.warning + "\n\n" + responseText;
}
return {
content: [
{
type: "text" as const,
text: responseText,
},
],
};
} catch (error) {
const rawMessage = error instanceof Error ? error.message : String(error);
// Redact internal details: file paths, SQL errors, stack traces
const safeMessage = rawMessage
.replace(/\/[^\s:]+/g, "[path]") // redact file paths
.replace(/\b\d{5}\b/g, "[code]") // redact PG error codes
.replace(/at\s+\S+\s+\(.+\)/g, "") // strip stack frames
.slice(0, 200); // cap length
console.error(`[server] Tool error:`, safeMessage);
return {
content: [
{
type: "text" as const,
text: JSON.stringify({ error: safeMessage }),
},
],
isError: true,
};
}
});
return server;
}
/**
* Run the server with stdio transport
*
* Initializes local vector search in background for fast startup.
* Uses direct Supabase queries to get embeddings for local cache.
*
* Server starts immediately; cache loads in background.
* First few queries may use Supabase fallback until cache is ready.
*/
export async function runServer(): Promise<void> {
const tier = getTier();
// Start server immediately (don't block on cache loading)
const server = createServer();
const transport = new StdioServerTransport();
await server.connect(transport);
const toolCount = getRegisteredTools().length;
const storage = hasSupabase() ? "supabase" : "local";
console.error(`[gitmem] Tier: ${tier} | Storage: ${storage} | Tools: ${toolCount}`);
if (hasSupabase()) {
// Pro/Dev: Initialize local vector search in background (non-blocking)
// This loads scars with embeddings directly from Supabase REST API
console.error("[gitmem] Starting background cache initialization...");
const warmupProject = process.env.GITMEM_DEFAULT_PROJECT || "default";
startBackgroundInit(warmupProject);
console.error("[gitmem] Server ready | Cache loading in background");
} else {
// Free tier: no Supabase cache to load
console.error("[gitmem] Server ready | Using local storage (.gitmem/)");
}
}