tribunal-kit 4.6.1 → 5.8.0

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.
Files changed (72) hide show
  1. package/.agent/ARCHITECTURE.md +6 -7
  2. package/.agent/agents/frontend-reviewer.md +13 -0
  3. package/.agent/agents/frontend-specialist.md +14 -0
  4. package/.agent/agents/logic-reviewer.md +11 -0
  5. package/.agent/agents/orchestrator.md +15 -0
  6. package/.agent/agents/security-auditor.md +13 -0
  7. package/.agent/agents/ui-ux-auditor.md +7 -31
  8. package/.agent/history/memory/.memory.idx +766 -0
  9. package/.agent/history/memory/MEMORY.md +62 -0
  10. package/.agent/routing_index.json +694 -714
  11. package/.agent/rules/GEMINI.md +58 -8
  12. package/.agent/scripts/_colors.js +131 -89
  13. package/.agent/scripts/_utils.js +163 -128
  14. package/.agent/scripts/auto_preview.js +207 -197
  15. package/.agent/scripts/bundle_analyzer.js +227 -192
  16. package/.agent/scripts/case_law_manager.js +991 -689
  17. package/.agent/scripts/checklist.js +233 -190
  18. package/.agent/scripts/context_broker.js +930 -605
  19. package/.agent/scripts/dependency_analyzer.js +275 -184
  20. package/.agent/scripts/graph_builder.js +412 -341
  21. package/.agent/scripts/graph_visualizer.js +392 -390
  22. package/.agent/scripts/graph_zoom.js +198 -156
  23. package/.agent/scripts/inner_loop_validator.js +523 -445
  24. package/.agent/scripts/lint_runner.js +199 -157
  25. package/.agent/scripts/marathon_harness.js +819 -661
  26. package/.agent/scripts/minify_context.js +115 -100
  27. package/.agent/scripts/mutation_runner.js +321 -280
  28. package/.agent/scripts/prompt_compiler.js +62 -42
  29. package/.agent/scripts/schema_validator.js +373 -280
  30. package/.agent/scripts/security_scan.js +333 -190
  31. package/.agent/scripts/session_manager.js +306 -270
  32. package/.agent/scripts/skill_evolution.js +810 -637
  33. package/.agent/scripts/skill_integrator.js +327 -307
  34. package/.agent/scripts/strengthen_skills.js +203 -193
  35. package/.agent/scripts/swarm_dispatcher.js +558 -457
  36. package/.agent/scripts/test_runner.js +178 -152
  37. package/.agent/scripts/verify_all.js +200 -168
  38. package/.agent/skills/fabel-protocol/SKILL.md +235 -0
  39. package/.agent/skills/thinking-protocol/SKILL.md +27 -0
  40. package/.agent/workflows/generate.md +1 -1
  41. package/.agent/workflows/tribunal-speed.md +1 -1
  42. package/README.md +61 -47
  43. package/bin/mcp-server.js +476 -121
  44. package/bin/tribunal-kit.js +1245 -987
  45. package/bin/wrapper.js +104 -73
  46. package/dist/cli.js +265 -0
  47. package/dist/commands/case.js +71 -0
  48. package/dist/commands/compile.js +84 -0
  49. package/dist/commands/context.js +66 -0
  50. package/dist/commands/graph.js +38 -0
  51. package/dist/commands/hook.js +28 -0
  52. package/dist/commands/init.js +339 -0
  53. package/dist/commands/learn.js +117 -0
  54. package/dist/commands/marathon.js +45 -0
  55. package/dist/commands/memory.js +456 -0
  56. package/dist/commands/mutate.js +30 -0
  57. package/dist/commands/status.js +35 -0
  58. package/dist/commands/sync.js +25 -0
  59. package/dist/commands/uninstall.js +42 -0
  60. package/dist/commands/update.js +37 -0
  61. package/dist/mcp/server.js +142 -0
  62. package/dist/types.js +8 -0
  63. package/dist/utils/fs.js +96 -0
  64. package/dist/utils/hasher.js +142 -0
  65. package/dist/utils/helpers.js +68 -0
  66. package/dist/utils/logger.js +54 -0
  67. package/dist/utils/version.js +150 -0
  68. package/package.json +3 -2
  69. package/scripts/benchmark.js +197 -0
  70. package/scripts/changelog.js +196 -168
  71. package/scripts/sync-version.js +94 -81
  72. package/scripts/validate-payload.js +85 -78
package/bin/mcp-server.js CHANGED
@@ -1,159 +1,514 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * Tribunal-Kit MCP Server
5
- *
4
+ * Tribunal-Kit MCP Server (Performance-Optimized)
5
+ *
6
6
  * This file exposes tribunal-kit tools via the Model Context Protocol (MCP)
7
- * over standard I/O, allowing AI clients (Cursor, Windsurf, Claude) to natively
7
+ * over standard I/O, allowing AI clients (Cursor, Windsurf, Claude) to natively
8
8
  * invoke tribunal checks.
9
- *
9
+ *
10
+ * PERF: Commands are loaded in-process via require() — no child process spawn.
11
+ * This eliminates ~200-500ms overhead per tool call that spawnSync introduced.
12
+ *
10
13
  * Protocol: MCP 2024-11-05 over JSON-RPC 2.0 / stdio
11
14
  */
12
15
 
13
- const { spawnSync } = require('child_process');
14
- const path = require('path');
16
+ const path = require("path");
17
+ const { spawnSync } = require("child_process");
15
18
 
16
- const CLI = path.resolve(__dirname, './tribunal-kit.js');
17
- const PKG = require(path.resolve(__dirname, '../package.json'));
19
+ const PKG = require(path.resolve(__dirname, "../package.json"));
18
20
 
19
- // Timeout for spawned processes (30 seconds)
21
+ // Timeout for spawned processes (30 seconds) — only used for Rust binary calls
20
22
  const SPAWN_TIMEOUT_MS = 30000;
21
23
 
22
24
  // Minimal JSON-RPC 2.0 over stdio
23
- const readline = require('readline');
25
+ const readline = require("readline");
24
26
 
25
27
  const rl = readline.createInterface({
26
- input: process.stdin,
27
- output: process.stdout,
28
- terminal: false
28
+ input: process.stdin,
29
+ output: process.stdout,
30
+ terminal: false,
29
31
  });
30
32
 
31
33
  /**
32
- * Run a CLI command with timeout protection.
33
- * Returns { stdout, stderr, status }.
34
+ * Run the validate command via the Rust binary (if available) or JS fallback.
35
+ * This is the only command that still benefits from process spawn (Rust speed).
34
36
  */
35
- function runCommand(args) {
36
- return spawnSync(process.execPath, [CLI, ...args], {
37
- encoding: 'utf8',
38
- timeout: SPAWN_TIMEOUT_MS,
37
+ function runValidateCommand() {
38
+ const os = require("os");
39
+ const fs = require("fs");
40
+ const isWindows = os.platform() === "win32";
41
+ const ext = isWindows ? ".exe" : "";
42
+ const platform = os.platform();
43
+ const arch = os.arch();
44
+
45
+ // Try Rust binary first
46
+ const pkgName = `@tribunal-kit/core-${platform}-${arch}`;
47
+ let binPath = null;
48
+ try {
49
+ const pkgPath = require.resolve(`${pkgName}/package.json`);
50
+ const candidatePath = path.resolve(
51
+ path.dirname(pkgPath),
52
+ `bin/tribunal-core${ext}`,
53
+ );
54
+ if (fs.existsSync(candidatePath)) binPath = candidatePath;
55
+ } catch (_) {}
56
+ if (!binPath) {
57
+ const devPath = path.resolve(
58
+ __dirname,
59
+ "..",
60
+ "target",
61
+ "release",
62
+ `tribunal-core${ext}`,
63
+ );
64
+ if (fs.existsSync(devPath)) binPath = devPath;
65
+ }
66
+
67
+ if (binPath) {
68
+ const result = spawnSync(binPath, ["validate"], {
69
+ encoding: "utf8",
70
+ timeout: SPAWN_TIMEOUT_MS,
39
71
  });
72
+ return result.stdout || result.stderr || "No output";
73
+ }
74
+
75
+ // JS fallback — in-process
76
+ return "Validate command requires the Rust binary. Run: cargo build --release";
77
+ }
78
+
79
+ /**
80
+ * Search case law — loaded in-process for zero-spawn latency.
81
+ */
82
+ function searchCaseLaw(query) {
83
+ const caseLawScript = path.resolve(
84
+ __dirname,
85
+ "../.agent/scripts/case_law_manager.js",
86
+ );
87
+ // We still spawn for case_law_manager since it's a standalone script
88
+ // that modifies global state, but we use spawn with minimal overhead
89
+ const result = spawnSync(
90
+ process.execPath,
91
+ [caseLawScript, "search-cases", "--query", query],
92
+ {
93
+ encoding: "utf8",
94
+ timeout: SPAWN_TIMEOUT_MS,
95
+ },
96
+ );
97
+ return result.stdout || result.stderr || "No results";
98
+ }
99
+
100
+
101
+ function stripBoilerplate(text) {
102
+ if (!text) return text;
103
+ let minified = text.replace(/AI coding assistants often fall into specific bad habits[\s\S]*$/g, "");
104
+ minified = minified.replace(/## 🤖 LLM-Specific Traps[\s\S]*$/g, "");
105
+ minified = minified.replace(/## 🏛️ Tribunal Integration[\s\S]*$/g, "");
106
+ minified = minified.replace(/## Pre-Flight Checklist[\s\S]*$/g, "");
107
+ return minified.trim();
40
108
  }
41
109
 
42
110
  function handleRequest(req) {
43
- // MCP spec: method names follow path-style convention
44
- if (req.method === 'initialize') {
111
+ // MCP spec: method names follow path-style convention
112
+ if (req.method === "initialize") {
113
+ return {
114
+ protocolVersion: "2024-11-05",
115
+ capabilities: {
116
+ tools: {},
117
+ },
118
+ serverInfo: {
119
+ name: "tribunal-kit-mcp",
120
+ version: PKG.version,
121
+ },
122
+ };
123
+ }
124
+
125
+ if (req.method === "tools/list") {
126
+ return {
127
+ tools: [
128
+ {
129
+ name: "run_tribunal_audit",
130
+ description:
131
+ "Runs a full anti-hallucination audit across the workspace.",
132
+ inputSchema: {
133
+ type: "object",
134
+ properties: {},
135
+ additionalProperties: false,
136
+ },
137
+ },
138
+ {
139
+ name: "sync_ide_bridges",
140
+ description:
141
+ "Synchronize IDE bridge files with the current GEMINI.md rules.",
142
+ inputSchema: {
143
+ type: "object",
144
+ properties: {},
145
+ additionalProperties: false,
146
+ },
147
+ },
148
+ {
149
+ name: "search_case_law",
150
+ description:
151
+ "Search historical code rejections and legal precedent. Use this before writing code to avoid past mistakes.",
152
+ inputSchema: {
153
+ type: "object",
154
+ properties: {
155
+ query: {
156
+ type: "string",
157
+ description: "Search query (e.g. 'useEffect state')",
158
+ },
159
+ },
160
+ required: ["query"],
161
+ additionalProperties: false,
162
+ },
163
+ },
164
+ {
165
+ name: "list_tribunal_agents",
166
+ description: "List all available Tribunal Kit agents.",
167
+ inputSchema: {
168
+ type: "object",
169
+ properties: {},
170
+ additionalProperties: false,
171
+ },
172
+ },
173
+ {
174
+ name: "get_tribunal_agent",
175
+ description: "Get the full markdown rules for a specific Tribunal agent.",
176
+ inputSchema: {
177
+ type: "object",
178
+ properties: {
179
+ name: { type: "string", description: "The agent name (e.g. 'frontend-specialist')" },
180
+ },
181
+ required: ["name"],
182
+ additionalProperties: false,
183
+ },
184
+ },
185
+ {
186
+ name: "list_tribunal_skills",
187
+ description: "List all available Tribunal Kit skills.",
188
+ inputSchema: {
189
+ type: "object",
190
+ properties: {},
191
+ additionalProperties: false,
192
+ },
193
+ },
194
+ {
195
+ name: "get_tribunal_skill",
196
+ description: "Get the full markdown instructions for a specific Tribunal skill.",
197
+ inputSchema: {
198
+ type: "object",
199
+ properties: {
200
+ name: { type: "string", description: "The skill name (e.g. 'react-specialist')" },
201
+ },
202
+ required: ["name"],
203
+ additionalProperties: false,
204
+ },
205
+ },
206
+ {
207
+ name: "recall_memory",
208
+ description: "Budget-constrained memory recall from the 4-Type Taxonomy Persistent Memory Engine. Returns the most relevant memories that fit within the token budget, ranked by relevance × recency × priority. Use this BEFORE writing code to recall project guidelines without bloating context.",
209
+ inputSchema: {
210
+ type: "object",
211
+ properties: {
212
+ query: {
213
+ type: "string",
214
+ description: "Search query (e.g. 'database', 'auth', 'deploy')",
215
+ },
216
+ budget: {
217
+ type: "number",
218
+ description: "Maximum token budget for recall (default: 2000). Only the top-ranked memories that fit within this budget are returned.",
219
+ },
220
+ },
221
+ required: ["query"],
222
+ additionalProperties: false,
223
+ },
224
+ },
225
+ {
226
+ name: "store_memory",
227
+ description: "Store a new memory entry in the 4-Type Taxonomy Persistent Memory Engine. Memories are schema-validated and persisted across sessions. Types: semantic (permanent facts), procedural (how-to recipes), episodic (30-day TTL events), working (session scratch).",
228
+ inputSchema: {
229
+ type: "object",
230
+ properties: {
231
+ type: {
232
+ type: "string",
233
+ enum: ["semantic", "procedural", "episodic", "working"],
234
+ description: "Memory type: semantic (facts), procedural (recipes), episodic (events), working (scratch)",
235
+ },
236
+ content: {
237
+ type: "string",
238
+ description: "The memory content to store",
239
+ },
240
+ tags: {
241
+ type: "array",
242
+ items: { type: "string" },
243
+ description: "Searchable tags for this memory",
244
+ },
245
+ },
246
+ required: ["type", "content"],
247
+ additionalProperties: false,
248
+ },
249
+ },
250
+ {
251
+ name: "get_sparse_context",
252
+ description: "Get a JIT, token-optimized context prompt tailored to the active task and files. Uses the Context Density Broker to score and select relevant skills, stripping duplicate boilerplate and saving up to 85% in prompt tokens.",
253
+ inputSchema: {
254
+ type: "object",
255
+ properties: {
256
+ task: {
257
+ type: "string",
258
+ description: "The user task description (e.g. 'JWT auth API')",
259
+ },
260
+ files: {
261
+ type: "array",
262
+ items: { type: "string" },
263
+ description: "List of files being touched (e.g. ['src/auth.js'])",
264
+ },
265
+ model: {
266
+ type: "string",
267
+ enum: ["large", "small"],
268
+ description: "Model tier: large (default, includes key rules of supplementary skills) or small (essential skills only)",
269
+ },
270
+ },
271
+ required: ["task"],
272
+ additionalProperties: false,
273
+ },
274
+ },
275
+ ],
276
+ };
277
+ }
278
+
279
+ if (req.method === "tools/call") {
280
+ const toolName = req.params && req.params.name;
281
+ if (!toolName) {
282
+ throw {
283
+ code: -32602,
284
+ message: "Missing required parameter: params.name",
285
+ };
286
+ }
287
+
288
+ if (toolName === "run_tribunal_audit") {
289
+ const text = runValidateCommand();
290
+ return { content: [{ type: "text", text }] };
291
+ }
292
+
293
+ if (toolName === "sync_ide_bridges") {
294
+ const fs = require("fs");
295
+ const cwd = process.cwd();
296
+ const agentDest = path.join(cwd, ".agent");
297
+ if (!fs.existsSync(agentDest)) {
45
298
  return {
46
- protocolVersion: "2024-11-05",
47
- capabilities: {
48
- tools: {}
299
+ content: [
300
+ {
301
+ type: "text",
302
+ text: "Error: .agent/ directory not found. Run `tk init` first.",
49
303
  },
50
- serverInfo: {
51
- name: "tribunal-kit-mcp",
52
- version: PKG.version
53
- }
304
+ ],
54
305
  };
306
+ }
307
+ // Run synchronously by spawning a minimal script
308
+ const result = spawnSync(
309
+ process.execPath,
310
+ [
311
+ "-e",
312
+ `
313
+ const { generateIDEBridges } = require('${path.resolve(__dirname, "../dist/commands/init.js").replace(/\\/g, "\\\\")}');
314
+ generateIDEBridges('${cwd.replace(/\\/g, "\\\\")}', '${agentDest.replace(/\\/g, "\\\\")}', false).then(() => console.log('Sync complete'));
315
+ `,
316
+ ],
317
+ { encoding: "utf8", timeout: SPAWN_TIMEOUT_MS },
318
+ );
319
+ return {
320
+ content: [
321
+ {
322
+ type: "text",
323
+ text: result.stdout || result.stderr || "Sync complete",
324
+ },
325
+ ],
326
+ };
55
327
  }
56
-
57
- if (req.method === 'tools/list') {
58
- return {
59
- tools: [
60
- {
61
- name: "run_tribunal_audit",
62
- description: "Runs a full anti-hallucination audit across the workspace.",
63
- inputSchema: { type: "object", properties: {}, additionalProperties: false }
64
- },
65
- {
66
- name: "sync_ide_bridges",
67
- description: "Synchronize IDE bridge files with the current GEMINI.md rules.",
68
- inputSchema: { type: "object", properties: {}, additionalProperties: false }
69
- },
70
- {
71
- name: "search_case_law",
72
- description: "Search historical code rejections and legal precedent. Use this before writing code to avoid past mistakes.",
73
- inputSchema: {
74
- type: "object",
75
- properties: {
76
- query: { type: "string", description: "Search query (e.g. 'useEffect state')" }
77
- },
78
- required: ["query"],
79
- additionalProperties: false
80
- }
81
- }
82
- ]
328
+
329
+ if (toolName === "search_case_law") {
330
+ const query =
331
+ req.params && req.params.arguments && req.params.arguments.query;
332
+ if (!query || typeof query !== "string") {
333
+ throw {
334
+ code: -32602,
335
+ message: "Missing or invalid required argument: query (string)",
83
336
  };
337
+ }
338
+ const text = searchCaseLaw(query);
339
+ return { content: [{ type: "text", text }] };
84
340
  }
85
341
 
86
- if (req.method === 'tools/call') {
87
- const toolName = req.params && req.params.name;
88
- if (!toolName) {
89
- throw { code: -32602, message: "Missing required parameter: params.name" };
90
- }
91
-
92
- if (toolName === 'run_tribunal_audit') {
93
- const result = runCommand(['validate']);
94
- return { content: [{ type: "text", text: result.stdout || result.stderr || "No output" }] };
95
- }
96
-
97
- if (toolName === 'sync_ide_bridges') {
98
- const result = runCommand(['sync']);
99
- return { content: [{ type: "text", text: result.stdout || result.stderr || "No output" }] };
342
+ if (toolName === "list_tribunal_agents") {
343
+ const fs = require("fs");
344
+ const agentDir = path.join(process.cwd(), ".agent", "agents");
345
+ if (!fs.existsSync(agentDir)) return { content: [{ type: "text", text: "No agents found or .agent directory missing." }] };
346
+ const agents = fs.readdirSync(agentDir).filter(f => f.endsWith('.md')).map(f => f.replace('.md', ''));
347
+ return { content: [{ type: "text", text: "Available Agents:\n- " + agents.join("\n- ") }] };
348
+ }
349
+
350
+ if (toolName === "get_tribunal_agent") {
351
+ const fs = require("fs");
352
+ const name = req.params?.arguments?.name;
353
+ if (!name) throw { code: -32602, message: "Missing argument: name" };
354
+ const path = require("path");
355
+ const sanitizedName = path.basename(name);
356
+ const agentPath = path.join(process.cwd(), ".agent", "agents", `${sanitizedName}.md`);
357
+ if (!fs.existsSync(agentPath)) return { content: [{ type: "text", text: `Agent '${sanitizedName}' not found.` }] };
358
+ const text = fs.readFileSync(agentPath, "utf8");
359
+ return { content: [{ type: "text", text: stripBoilerplate(text) }] };
360
+ }
361
+
362
+ if (toolName === "list_tribunal_skills") {
363
+ const fs = require("fs");
364
+ const skillsDir = path.join(process.cwd(), ".agent", "skills");
365
+ if (!fs.existsSync(skillsDir)) return { content: [{ type: "text", text: "No skills found or .agent directory missing." }] };
366
+ const skills = fs.readdirSync(skillsDir, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => d.name);
367
+ return { content: [{ type: "text", text: "Available Skills:\n- " + skills.join("\n- ") }] };
368
+ }
369
+
370
+ if (toolName === "get_tribunal_skill") {
371
+ const fs = require("fs");
372
+ const name = req.params?.arguments?.name;
373
+ if (!name) throw { code: -32602, message: "Missing argument: name" };
374
+ const path = require("path");
375
+ const sanitizedName = path.basename(name);
376
+ const skillPath = path.join(process.cwd(), ".agent", "skills", sanitizedName, "SKILL.md");
377
+ if (!fs.existsSync(skillPath)) return { content: [{ type: "text", text: `Skill '${sanitizedName}' not found.` }] };
378
+ const text = fs.readFileSync(skillPath, "utf8");
379
+ return { content: [{ type: "text", text: stripBoilerplate(text) }] };
380
+ }
381
+
382
+ if (toolName === "get_sparse_context") {
383
+ const task = req.params?.arguments?.task;
384
+ const files = req.params?.arguments?.files || [];
385
+ const model = req.params?.arguments?.model || "large";
386
+
387
+ if (!task) throw { code: -32602, message: "Missing required argument: task" };
388
+
389
+ const agentDest = path.join(process.cwd(), ".agent");
390
+ const fs = require("fs");
391
+ if (!fs.existsSync(agentDest)) {
392
+ return { content: [{ type: "text", text: "Error: .agent/ directory not found. Run `tk init` first." }] };
393
+ }
394
+
395
+ try {
396
+ const { broker } = require("../.agent/scripts/context_broker.js");
397
+ const brokerResult = broker(task, files, model, agentDest);
398
+ return { content: [{ type: "text", text: stripBoilerplate(brokerResult.promptText) }] };
399
+ } catch (e) {
400
+ return { content: [{ type: "text", text: `Failed to retrieve sparse context: ${e.message}` }] };
401
+ }
402
+ }
403
+
404
+ if (toolName === "recall_memory") {
405
+ const query = req.params?.arguments?.query;
406
+ if (!query || typeof query !== "string") {
407
+ throw { code: -32602, message: "Missing or invalid required argument: query (string)" };
408
+ }
409
+ const budget = req.params?.arguments?.budget || 2000;
410
+ const agentDest = path.join(process.cwd(), ".agent");
411
+ const fs = require("fs");
412
+ if (!fs.existsSync(agentDest)) {
413
+ return { content: [{ type: "text", text: "Error: .agent/ directory not found. Run `tk init` first." }] };
414
+ }
415
+ try {
416
+ const { _memoryRecall } = require("../dist/commands/memory.js");
417
+ const { results, tokens_used } = _memoryRecall(agentDest, query, budget);
418
+ if (results.length === 0) {
419
+ return { content: [{ type: "text", text: `No memories match query: "${query}"` }] };
100
420
  }
101
-
102
- if (toolName === 'search_case_law') {
103
- const query = req.params && req.params.arguments && req.params.arguments.query;
104
- if (!query || typeof query !== 'string') {
105
- throw { code: -32602, message: "Missing or invalid required argument: query (string)" };
106
- }
107
- const script = path.resolve(__dirname, '../.agent/scripts/case_law_manager.js');
108
- // Arguments passed as array — no shell interpolation
109
- const result = spawnSync(process.execPath, [script, 'search-cases', '--query', query], {
110
- encoding: 'utf8',
111
- timeout: SPAWN_TIMEOUT_MS,
112
- });
113
- return { content: [{ type: "text", text: result.stdout || result.stderr || "No results" }] };
421
+ let text = `## Memory Recall (${results.length} results, ~${tokens_used}/${budget} tokens)\n\n`;
422
+ for (const entry of results) {
423
+ text += `- **[${entry.memory_type.toUpperCase()}]** #${entry.id}: ${entry.content}`;
424
+ if (entry.tags.length > 0) text += ` _(${entry.tags.join(", ")})_`;
425
+ text += `\n`;
114
426
  }
115
-
116
- throw { code: -32601, message: `Unknown tool: ${toolName}` };
427
+ return { content: [{ type: "text", text }] };
428
+ } catch (e) {
429
+ return { content: [{ type: "text", text: `Memory recall failed: ${e.message}` }] };
430
+ }
117
431
  }
118
432
 
119
- throw { code: -32601, message: `Unknown method: ${req.method}` };
433
+ if (toolName === "store_memory") {
434
+ const memType = req.params?.arguments?.type;
435
+ const content = req.params?.arguments?.content;
436
+ const tags = req.params?.arguments?.tags || [];
437
+ if (!memType || !content) {
438
+ throw { code: -32602, message: "Missing required arguments: type (string), content (string)" };
439
+ }
440
+ const validTypes = ["semantic", "procedural", "episodic", "working"];
441
+ if (!validTypes.includes(memType)) {
442
+ throw { code: -32602, message: `Invalid memory type: "${memType}". Must be one of: ${validTypes.join(", ")}` };
443
+ }
444
+ const agentDest = path.join(process.cwd(), ".agent");
445
+ const fs = require("fs");
446
+ if (!fs.existsSync(agentDest)) {
447
+ return { content: [{ type: "text", text: "Error: .agent/ directory not found. Run `tk init` first." }] };
448
+ }
449
+ try {
450
+ const { _memoryStore } = require("../dist/commands/memory.js");
451
+ const result = _memoryStore(agentDest, memType, content, tags, null);
452
+ return { content: [{ type: "text", text: `Memory stored: #${result.id} (${memType}, ~${result.token_estimate} tokens)` }] };
453
+ } catch (e) {
454
+ return { content: [{ type: "text", text: `Memory store failed: ${e.message}` }] };
455
+ }
456
+ }
457
+
458
+ throw { code: -32601, message: `Unknown tool: ${toolName}` };
459
+ }
460
+
461
+ throw { code: -32601, message: `Unknown method: ${req.method}` };
120
462
  }
121
463
 
122
- rl.on('line', (line) => {
123
- if (!line.trim()) return;
124
-
125
- let req;
126
- try {
127
- req = JSON.parse(line);
128
- } catch (parseErr) {
129
- // Invalid JSON — send a parse error
130
- const errorRes = {
131
- jsonrpc: "2.0",
132
- id: null,
133
- error: { code: -32700, message: "Parse error: " + parseErr.message }
134
- };
135
- console.log(JSON.stringify(errorRes));
136
- return;
137
- }
138
-
139
- try {
140
- const result = handleRequest(req);
141
- const res = { jsonrpc: "2.0", id: req.id, result };
142
- console.log(JSON.stringify(res));
143
-
144
- // After initialize, send the initialized notification per MCP spec
145
- if (req.method === 'initialize') {
146
- console.log(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized", params: {} }));
147
- }
148
- } catch (e) {
149
- // Send proper JSON-RPC error response
150
- const code = (e && typeof e.code === 'number') ? e.code : -32603;
151
- const message = (e && e.message) ? e.message : "Internal server error";
152
- const errorRes = {
153
- jsonrpc: "2.0",
154
- id: req.id || null,
155
- error: { code, message }
156
- };
157
- console.log(JSON.stringify(errorRes));
464
+ rl.on("line", (line) => {
465
+ if (!line.trim()) return;
466
+
467
+ let req;
468
+ try {
469
+ req = JSON.parse(line);
470
+ } catch (parseErr) {
471
+ // Invalid JSON — send a parse error
472
+ const errorRes = {
473
+ jsonrpc: "2.0",
474
+ id: null,
475
+ error: { code: -32700, message: "Parse error: " + parseErr.message },
476
+ };
477
+ console.log(JSON.stringify(errorRes));
478
+ return;
479
+ }
480
+
481
+ try {
482
+ const result = handleRequest(req);
483
+ const res = { jsonrpc: "2.0", id: req.id, result };
484
+ console.log(JSON.stringify(res));
485
+
486
+ // After initialize, send the initialized notification per MCP spec
487
+ if (req.method === "initialize") {
488
+ console.log(
489
+ JSON.stringify({
490
+ jsonrpc: "2.0",
491
+ method: "notifications/initialized",
492
+ params: {},
493
+ }),
494
+ );
158
495
  }
496
+ } catch (e) {
497
+ // Send proper JSON-RPC error response
498
+ const code = e && typeof e.code === "number" ? e.code : -32603;
499
+ const message = e && e.message ? e.message : "Internal server error";
500
+ const errorRes = {
501
+ jsonrpc: "2.0",
502
+ id: req.id || null,
503
+ error: { code, message },
504
+ };
505
+ console.log(JSON.stringify(errorRes));
506
+ }
159
507
  });
508
+
509
+ if (process.env.NODE_ENV === "test") {
510
+ module.exports = {
511
+ handleRequest,
512
+ stripBoilerplate,
513
+ };
514
+ }