tribunal-kit 5.7.0 → 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 (56) 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 +53 -53
  43. package/bin/mcp-server.js +460 -175
  44. package/bin/tribunal-kit.js +1245 -987
  45. package/bin/wrapper.js +104 -74
  46. package/dist/cli.js +31 -0
  47. package/dist/commands/case.js +23 -0
  48. package/dist/commands/compile.js +84 -0
  49. package/dist/commands/init.js +42 -0
  50. package/dist/commands/learn.js +57 -0
  51. package/dist/commands/memory.js +456 -0
  52. package/package.json +2 -2
  53. package/scripts/benchmark.js +162 -125
  54. package/scripts/changelog.js +196 -168
  55. package/scripts/sync-version.js +94 -81
  56. package/scripts/validate-payload.js +85 -78
package/bin/mcp-server.js CHANGED
@@ -2,32 +2,32 @@
2
2
 
3
3
  /**
4
4
  * Tribunal-Kit MCP Server (Performance-Optimized)
5
- *
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
10
  * PERF: Commands are loaded in-process via require() — no child process spawn.
11
11
  * This eliminates ~200-500ms overhead per tool call that spawnSync introduced.
12
- *
12
+ *
13
13
  * Protocol: MCP 2024-11-05 over JSON-RPC 2.0 / stdio
14
14
  */
15
15
 
16
- const path = require('path');
17
- const { spawnSync } = require('child_process');
16
+ const path = require("path");
17
+ const { spawnSync } = require("child_process");
18
18
 
19
- const PKG = require(path.resolve(__dirname, '../package.json'));
19
+ const PKG = require(path.resolve(__dirname, "../package.json"));
20
20
 
21
21
  // Timeout for spawned processes (30 seconds) — only used for Rust binary calls
22
22
  const SPAWN_TIMEOUT_MS = 30000;
23
23
 
24
24
  // Minimal JSON-RPC 2.0 over stdio
25
- const readline = require('readline');
25
+ const readline = require("readline");
26
26
 
27
27
  const rl = readline.createInterface({
28
- input: process.stdin,
29
- output: process.stdout,
30
- terminal: false
28
+ input: process.stdin,
29
+ output: process.stdout,
30
+ terminal: false,
31
31
  });
32
32
 
33
33
  /**
@@ -35,195 +35,480 @@ const rl = readline.createInterface({
35
35
  * This is the only command that still benefits from process spawn (Rust speed).
36
36
  */
37
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(path.dirname(pkgPath), `bin/tribunal-core${ext}`);
51
- if (fs.existsSync(candidatePath)) binPath = candidatePath;
52
- } catch (_) {}
53
- if (!binPath) {
54
- const devPath = path.resolve(__dirname, '..', 'target', 'release', `tribunal-core${ext}`);
55
- if (fs.existsSync(devPath)) binPath = devPath;
56
- }
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();
57
44
 
58
- if (binPath) {
59
- const result = spawnSync(binPath, ['validate'], {
60
- encoding: 'utf8',
61
- timeout: SPAWN_TIMEOUT_MS,
62
- });
63
- return result.stdout || result.stderr || "No output";
64
- }
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,
71
+ });
72
+ return result.stdout || result.stderr || "No output";
73
+ }
65
74
 
66
- // JS fallback — in-process
67
- return "Validate command requires the Rust binary. Run: cargo build --release";
75
+ // JS fallback — in-process
76
+ return "Validate command requires the Rust binary. Run: cargo build --release";
68
77
  }
69
78
 
70
79
  /**
71
80
  * Search case law — loaded in-process for zero-spawn latency.
72
81
  */
73
82
  function searchCaseLaw(query) {
74
- const caseLawScript = path.resolve(__dirname, '../.agent/scripts/case_law_manager.js');
75
- // We still spawn for case_law_manager since it's a standalone script
76
- // that modifies global state, but we use spawn with minimal overhead
77
- const result = spawnSync(process.execPath, [caseLawScript, 'search-cases', '--query', query], {
78
- encoding: 'utf8',
79
- timeout: SPAWN_TIMEOUT_MS,
80
- });
81
- return result.stdout || result.stderr || "No results";
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";
82
98
  }
83
99
 
84
- /**
85
- * Sync IDE bridges — loaded in-process for zero-spawn latency.
86
- */
87
- async function syncIDEBridges() {
88
- try {
89
- const { cmdSync } = require('../dist/commands/sync.js');
90
- // Capture stdout
91
- const originalLog = console.log;
92
- let output = '';
93
- console.log = (...args) => { output += args.join(' ') + '\n'; };
94
- await cmdSync();
95
- console.log = originalLog;
96
- return output || "Sync complete";
97
- } catch (e) {
98
- return `Sync failed: ${e.message}`;
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();
100
108
  }
101
109
 
102
110
  function handleRequest(req) {
103
- // MCP spec: method names follow path-style convention
104
- 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)) {
105
298
  return {
106
- protocolVersion: "2024-11-05",
107
- capabilities: {
108
- tools: {}
299
+ content: [
300
+ {
301
+ type: "text",
302
+ text: "Error: .agent/ directory not found. Run `tk init` first.",
109
303
  },
110
- serverInfo: {
111
- name: "tribunal-kit-mcp",
112
- version: PKG.version
113
- }
304
+ ],
114
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
+ };
115
327
  }
116
-
117
- if (req.method === 'tools/list') {
118
- return {
119
- tools: [
120
- {
121
- name: "run_tribunal_audit",
122
- description: "Runs a full anti-hallucination audit across the workspace.",
123
- inputSchema: { type: "object", properties: {}, additionalProperties: false }
124
- },
125
- {
126
- name: "sync_ide_bridges",
127
- description: "Synchronize IDE bridge files with the current GEMINI.md rules.",
128
- inputSchema: { type: "object", properties: {}, additionalProperties: false }
129
- },
130
- {
131
- name: "search_case_law",
132
- description: "Search historical code rejections and legal precedent. Use this before writing code to avoid past mistakes.",
133
- inputSchema: {
134
- type: "object",
135
- properties: {
136
- query: { type: "string", description: "Search query (e.g. 'useEffect state')" }
137
- },
138
- required: ["query"],
139
- additionalProperties: false
140
- }
141
- }
142
- ]
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)",
143
336
  };
337
+ }
338
+ const text = searchCaseLaw(query);
339
+ return { content: [{ type: "text", text }] };
144
340
  }
145
341
 
146
- if (req.method === 'tools/call') {
147
- const toolName = req.params && req.params.name;
148
- if (!toolName) {
149
- throw { code: -32602, message: "Missing required parameter: params.name" };
150
- }
151
-
152
- if (toolName === 'run_tribunal_audit') {
153
- const text = runValidateCommand();
154
- return { content: [{ type: "text", text }] };
155
- }
156
-
157
- if (toolName === 'sync_ide_bridges') {
158
- // This is async but MCP protocol is request/response,
159
- // so we handle it synchronously for now via the dist module
160
- const { cmdSync } = require('../dist/commands/sync.js');
161
- const fs = require('fs');
162
- const cwd = process.cwd();
163
- const agentDest = path.join(cwd, '.agent');
164
- if (!fs.existsSync(agentDest)) {
165
- return { content: [{ type: "text", text: "Error: .agent/ directory not found. Run `tk init` first." }] };
166
- }
167
- // Direct in-process IDE bridge generation
168
- const { generateIDEBridges } = require('../dist/commands/init.js');
169
- // Run synchronously by spawning a minimal script
170
- const result = spawnSync(process.execPath, ['-e', `
171
- const { generateIDEBridges } = require('${path.resolve(__dirname, '../dist/commands/init.js').replace(/\\/g, '\\\\')}');
172
- generateIDEBridges('${cwd.replace(/\\/g, '\\\\')}', '${agentDest.replace(/\\/g, '\\\\')}', false).then(() => console.log('Sync complete'));
173
- `], { encoding: 'utf8', timeout: SPAWN_TIMEOUT_MS });
174
- return { content: [{ type: "text", text: result.stdout || result.stderr || "Sync complete" }] };
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}"` }] };
175
420
  }
176
-
177
- if (toolName === 'search_case_law') {
178
- const query = req.params && req.params.arguments && req.params.arguments.query;
179
- if (!query || typeof query !== 'string') {
180
- throw { code: -32602, message: "Missing or invalid required argument: query (string)" };
181
- }
182
- const text = searchCaseLaw(query);
183
- return { content: [{ type: "text", text }] };
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`;
184
426
  }
185
-
186
- 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
+ }
187
431
  }
188
432
 
189
- 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}` };
190
462
  }
191
463
 
192
- rl.on('line', (line) => {
193
- if (!line.trim()) return;
194
-
195
- let req;
196
- try {
197
- req = JSON.parse(line);
198
- } catch (parseErr) {
199
- // Invalid JSON — send a parse error
200
- const errorRes = {
201
- jsonrpc: "2.0",
202
- id: null,
203
- error: { code: -32700, message: "Parse error: " + parseErr.message }
204
- };
205
- console.log(JSON.stringify(errorRes));
206
- return;
207
- }
208
-
209
- try {
210
- const result = handleRequest(req);
211
- const res = { jsonrpc: "2.0", id: req.id, result };
212
- console.log(JSON.stringify(res));
213
-
214
- // After initialize, send the initialized notification per MCP spec
215
- if (req.method === 'initialize') {
216
- console.log(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized", params: {} }));
217
- }
218
- } catch (e) {
219
- // Send proper JSON-RPC error response
220
- const code = (e && typeof e.code === 'number') ? e.code : -32603;
221
- const message = (e && e.message) ? e.message : "Internal server error";
222
- const errorRes = {
223
- jsonrpc: "2.0",
224
- id: req.id || null,
225
- error: { code, message }
226
- };
227
- 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
+ );
228
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
+ }
229
507
  });
508
+
509
+ if (process.env.NODE_ENV === "test") {
510
+ module.exports = {
511
+ handleRequest,
512
+ stripBoilerplate,
513
+ };
514
+ }