@nxuss/lemma 0.7.1 → 0.7.3

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 (80) hide show
  1. package/README.md +6 -5
  2. package/dashboard/dist/assets/{index-BJzMIGrT.js → index-BNYoIN8-.js} +114 -114
  3. package/dashboard/dist/assets/index-BNYoIN8-.js.map +1 -0
  4. package/dashboard/dist/assets/index-DtEKr0hI.css +1 -0
  5. package/dashboard/dist/index.html +2 -2
  6. package/dist/cjs/api/dashboardRoutes.d.ts.map +1 -1
  7. package/dist/cjs/api/dashboardRoutes.js +41 -1
  8. package/dist/cjs/api/dashboardRoutes.js.map +1 -1
  9. package/dist/cjs/cli/lemma-proxy.d.ts +0 -6
  10. package/dist/cjs/cli/lemma-proxy.d.ts.map +1 -1
  11. package/dist/cjs/cli/lemma-proxy.js +233 -359
  12. package/dist/cjs/cli/lemma-proxy.js.map +1 -1
  13. package/dist/cjs/mcp/index.js +165 -1192
  14. package/dist/cjs/mcp/index.js.map +1 -1
  15. package/dist/cjs/mcp/prompts.d.ts +4 -0
  16. package/dist/cjs/mcp/prompts.d.ts.map +1 -0
  17. package/dist/cjs/mcp/prompts.js +84 -0
  18. package/dist/cjs/mcp/prompts.js.map +1 -0
  19. package/dist/cjs/mcp/resources.d.ts +3 -0
  20. package/dist/cjs/mcp/resources.d.ts.map +1 -0
  21. package/dist/cjs/mcp/resources.js +254 -0
  22. package/dist/cjs/mcp/resources.js.map +1 -0
  23. package/dist/cjs/mcp/tools.d.ts +11 -0
  24. package/dist/cjs/mcp/tools.d.ts.map +1 -0
  25. package/dist/cjs/mcp/tools.js +1192 -0
  26. package/dist/cjs/mcp/tools.js.map +1 -0
  27. package/dist/cjs/mcp/utils.d.ts +11 -0
  28. package/dist/cjs/mcp/utils.d.ts.map +1 -0
  29. package/dist/cjs/mcp/utils.js +85 -0
  30. package/dist/cjs/mcp/utils.js.map +1 -0
  31. package/dist/cjs/proxy/ContextInjector.d.ts +14 -0
  32. package/dist/cjs/proxy/ContextInjector.d.ts.map +1 -0
  33. package/dist/cjs/proxy/ContextInjector.js +148 -0
  34. package/dist/cjs/proxy/ContextInjector.js.map +1 -0
  35. package/dist/cjs/proxy/ProjectRegistry.d.ts +17 -0
  36. package/dist/cjs/proxy/ProjectRegistry.d.ts.map +1 -0
  37. package/dist/cjs/proxy/ProjectRegistry.js +60 -0
  38. package/dist/cjs/proxy/ProjectRegistry.js.map +1 -0
  39. package/dist/cjs/utils/reportSavings.d.ts +6 -0
  40. package/dist/cjs/utils/reportSavings.d.ts.map +1 -1
  41. package/dist/cjs/utils/reportSavings.js.map +1 -1
  42. package/dist/esm/api/dashboardRoutes.d.ts.map +1 -1
  43. package/dist/esm/api/dashboardRoutes.js +41 -1
  44. package/dist/esm/api/dashboardRoutes.js.map +1 -1
  45. package/dist/esm/cli/lemma-proxy.d.ts +0 -6
  46. package/dist/esm/cli/lemma-proxy.d.ts.map +1 -1
  47. package/dist/esm/cli/lemma-proxy.js +233 -358
  48. package/dist/esm/cli/lemma-proxy.js.map +1 -1
  49. package/dist/esm/mcp/index.js +164 -1191
  50. package/dist/esm/mcp/index.js.map +1 -1
  51. package/dist/esm/mcp/prompts.d.ts +4 -0
  52. package/dist/esm/mcp/prompts.d.ts.map +1 -0
  53. package/dist/esm/mcp/prompts.js +80 -0
  54. package/dist/esm/mcp/prompts.js.map +1 -0
  55. package/dist/esm/mcp/resources.d.ts +3 -0
  56. package/dist/esm/mcp/resources.d.ts.map +1 -0
  57. package/dist/esm/mcp/resources.js +248 -0
  58. package/dist/esm/mcp/resources.js.map +1 -0
  59. package/dist/esm/mcp/tools.d.ts +11 -0
  60. package/dist/esm/mcp/tools.d.ts.map +1 -0
  61. package/dist/esm/mcp/tools.js +1153 -0
  62. package/dist/esm/mcp/tools.js.map +1 -0
  63. package/dist/esm/mcp/utils.d.ts +11 -0
  64. package/dist/esm/mcp/utils.d.ts.map +1 -0
  65. package/dist/esm/mcp/utils.js +73 -0
  66. package/dist/esm/mcp/utils.js.map +1 -0
  67. package/dist/esm/proxy/ContextInjector.d.ts +14 -0
  68. package/dist/esm/proxy/ContextInjector.d.ts.map +1 -0
  69. package/dist/esm/proxy/ContextInjector.js +108 -0
  70. package/dist/esm/proxy/ContextInjector.js.map +1 -0
  71. package/dist/esm/proxy/ProjectRegistry.d.ts +17 -0
  72. package/dist/esm/proxy/ProjectRegistry.d.ts.map +1 -0
  73. package/dist/esm/proxy/ProjectRegistry.js +56 -0
  74. package/dist/esm/proxy/ProjectRegistry.js.map +1 -0
  75. package/dist/esm/utils/reportSavings.d.ts +6 -0
  76. package/dist/esm/utils/reportSavings.d.ts.map +1 -1
  77. package/dist/esm/utils/reportSavings.js.map +1 -1
  78. package/package.json +1 -1
  79. package/dashboard/dist/assets/index-BJzMIGrT.js.map +0 -1
  80. package/dashboard/dist/assets/index-DUOrThix.css +0 -1
@@ -1,84 +1,88 @@
1
1
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
- import { CallToolRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
4
3
  import fs from "fs";
5
4
  import path from "path";
6
- import { reportSavings } from "../utils/reportSavings";
7
- /**
8
- * Lemma Autopilot System Prompt injected into every connected Chat IDE.
9
- * This is what makes Lemma tools AUTOMATIC: no user friction, no manual invocations.
10
- */
11
- const LEMMA_SYSTEM_PROMPT = `You are connected to Lemma — an intelligent local-first AI gateway.
12
- Lemma gives you a set of tools you MUST use proactively and automatically. NEVER ask the user
13
- to call a tool manually. YOU invoke the tools. The user should experience zero friction.
14
-
15
- ## MANDATORY AUTOMATIC BEHAVIORS
16
-
17
- ### 1. Before reading ANY file → call get_ast_hologram first
18
- When you need to understand the structure of a codebase or navigate files, ALWAYS call
19
- \`get_ast_hologram\` first (with the relevant dirPath, e.g. "src"). Use the returned symbol
20
- map to pinpoint exactly which files to read. NEVER blindly read every file one by one.
21
-
22
- ### 2. Before answering ANY technical question → call query_hybrid_consensus first
23
- BEFORE making any reasoning or cloud LLM call, ALWAYS call \`query_hybrid_consensus\` with
24
- the user's question. If similarity ≥ 80%, return the cached answer immediately — no cloud
25
- call needed. Only proceed with your own reasoning if the Brain returns a MISS.
26
-
27
- ### 3. When you start working on ANY file → call get_telepathic_hints automatically
28
- Whenever the user mentions a file or you are about to read/edit a file, IMMEDIATELY call
29
- \`get_telepathic_hints\` with that file's path. Surface the results to the user as relevant
30
- context BEFORE doing any work. Do not ask permission — just do it.
31
-
32
- ### 4. Before applying ANY code patch → call validate_patch_sandbox first
33
- NEVER call \`write_workspace_file\` or \`apply_workspace_patch\` without FIRST calling
34
- \`validate_patch_sandbox\` with the proposed content. Only proceed with the write if the
35
- verdict is "✅ SAFE TO APPLY". If it fails, fix the issues and re-validate.
36
-
37
- ### 5. After solving any technical problem → call store_memory automatically
38
- After resolving a bug, implementing a feature, or answering a significant technical question,
39
- ALWAYS call \`store_memory\` to persist the solution. Use a descriptive query key so it can
40
- be retrieved in future sessions across ALL projects.
41
-
42
- ### 6. Workspace navigation → always use Lemma tools, NEVER guess file contents
43
- - Use \`list_workspace_dir\` to navigate structure
44
- - Use \`read_workspace_file\` (auto-compresses + scrubs secrets) instead of asking the user
45
- - Use \`search_workspace\` for text search across files
46
- - Use \`run_workspace_command\` for builds, tests, linters
47
-
48
- ### 7. Privacy is automatic
49
- \`read_workspace_file\` and \`search_workspace\` automatically scrub API keys and PII.
50
- You never need to manually sanitize file content.
51
-
52
- ## LEMMA RESOURCES (auto-subscribe when available)
53
- - \`lemma://runtime/context\` — live crash logs. Read this FIRST when the user reports a bug.
54
- - \`lemma://multiverse/timeline\` — AST history. Use when the user says "it was working before".
55
- - \`lemma://project/onboarding\` architecture map. Read at session start in new repos.
56
- - \`lemma://stats/usage\` — token savings report.
57
-
58
- Remember: the user hired YOU to be autonomous. Act like it.`;
59
- /**
60
- * Lemma MCP Server
61
- * Exposes Lemma's intelligence layer as Tools and Resources for LLMs.
62
- */
5
+ import axios from "axios";
6
+ import { spawn } from "child_process";
7
+ import { v4 as uuidv4 } from "uuid";
8
+ import { setupPromptsHandlers } from "./prompts";
9
+ import { setupResourcesHandlers } from "./resources";
10
+ import { setupToolsHandlers } from "./tools";
11
+ import { getProxyPort, sanitizeArgsForLogging, logWarn } from "./utils";
12
+ const SERVER_VERSION = "0.7.3";
13
+ function detectStack() {
14
+ const projectPath = process.cwd();
15
+ let projectName = path.basename(projectPath);
16
+ const techStack = [];
17
+ try {
18
+ const pkg = JSON.parse(fs.readFileSync(path.join(projectPath, 'package.json'), 'utf8'));
19
+ projectName = pkg.name || projectName;
20
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
21
+ if (deps.react)
22
+ techStack.push('react');
23
+ if (deps.next)
24
+ techStack.push('next');
25
+ if (deps.vue)
26
+ techStack.push('vue');
27
+ if (deps.express)
28
+ techStack.push('express');
29
+ if (deps['@nestjs/core'])
30
+ techStack.push('nestjs');
31
+ if (deps.typescript || pkg.devDependencies?.typescript)
32
+ techStack.push('typescript');
33
+ }
34
+ catch { }
35
+ try {
36
+ const cargo = fs.readFileSync(path.join(projectPath, 'Cargo.toml'), 'utf8');
37
+ techStack.push('rust');
38
+ if (cargo.includes('actix'))
39
+ techStack.push('actix');
40
+ if (cargo.includes('axum'))
41
+ techStack.push('axum');
42
+ }
43
+ catch { }
44
+ try {
45
+ fs.readFileSync(path.join(projectPath, 'go.mod'), 'utf8');
46
+ techStack.push('go');
47
+ }
48
+ catch { }
49
+ try {
50
+ fs.readFileSync(path.join(projectPath, 'pyproject.toml'), 'utf8');
51
+ techStack.push('python');
52
+ }
53
+ catch { }
54
+ return { projectName, projectPath, techStack };
55
+ }
63
56
  class LemmaMcpServer {
64
57
  constructor() {
65
58
  this.server = new Server({
66
59
  name: "lemma-mcp-server",
67
- version: "0.1.0",
60
+ version: SERVER_VERSION,
68
61
  }, {
69
62
  capabilities: {
70
- resources: {
71
- subscribe: true
72
- },
63
+ resources: { subscribe: true },
73
64
  tools: {},
74
65
  prompts: {},
75
66
  },
76
67
  });
77
68
  this.setupHandlers();
78
- this.setupPromptsHandlers();
79
69
  this.setupErrorHandling();
80
70
  this.setupLiveContextWatcher();
81
71
  }
72
+ setupHandlers() {
73
+ setupPromptsHandlers(this.server);
74
+ setupResourcesHandlers(this.server);
75
+ setupToolsHandlers(this.server, (event) => this.reportMcpEvent(event));
76
+ }
77
+ async run() {
78
+ await this.ensureProxyRunning();
79
+ const transport = new StdioServerTransport();
80
+ await this.server.connect(transport);
81
+ console.error("Lemma MCP Server running on stdio");
82
+ await this.registerWithProxy();
83
+ await this.trySamplingContext();
84
+ }
85
+ // ── Live Context Watcher ──────────────────────────────────────────
82
86
  setupLiveContextWatcher() {
83
87
  try {
84
88
  const lemmaDir = path.join(process.cwd(), ".lemma");
@@ -95,1138 +99,25 @@ class LemmaMcpServer {
95
99
  // @ts-ignore
96
100
  this.server.sendResourceUpdated({ uri: "lemma://runtime/context" });
97
101
  }
98
- catch { }
99
- }
100
- });
101
- }
102
- catch { }
103
- }
104
- listDirRecursive(currentDir, relativePath, depth, maxDepth) {
105
- if (depth > maxDepth)
106
- return [];
107
- try {
108
- const entries = fs.readdirSync(currentDir, { withFileTypes: true });
109
- let result = [];
110
- for (const entry of entries) {
111
- if (["node_modules", ".git", "dist", "chroma_data"].includes(entry.name))
112
- continue;
113
- const rel = relativePath ? path.join(relativePath, entry.name) : entry.name;
114
- const full = path.join(currentDir, entry.name);
115
- if (entry.isDirectory()) {
116
- result.push(`${rel}/`);
117
- result.push(...this.listDirRecursive(full, rel, depth + 1, maxDepth));
118
- }
119
- else {
120
- result.push(rel);
121
- }
122
- }
123
- return result;
124
- }
125
- catch {
126
- return [];
127
- }
128
- }
129
- searchDirRecursive(currentDir, relativePath, query, extFilter) {
130
- try {
131
- const entries = fs.readdirSync(currentDir, { withFileTypes: true });
132
- let result = [];
133
- for (const entry of entries) {
134
- if (["node_modules", ".git", "dist", "chroma_data"].includes(entry.name))
135
- continue;
136
- const rel = relativePath ? path.join(relativePath, entry.name) : entry.name;
137
- const full = path.join(currentDir, entry.name);
138
- if (entry.isDirectory()) {
139
- result.push(...this.searchDirRecursive(full, rel, query, extFilter));
140
- }
141
- else {
142
- if (extFilter && !entry.name.endsWith(`.${extFilter}`))
143
- continue;
144
- try {
145
- const content = fs.readFileSync(full, "utf8");
146
- if (content.toLowerCase().includes(query.toLowerCase())) {
147
- const lines = content.split("\n");
148
- lines.forEach((lineText, idx) => {
149
- if (lineText.toLowerCase().includes(query.toLowerCase())) {
150
- result.push({
151
- filePath: rel,
152
- line: idx + 1,
153
- text: lineText.trim()
154
- });
155
- }
156
- });
157
- }
102
+ catch (err) {
103
+ logWarn("live-context", "Failed to send resource update");
158
104
  }
159
- catch { }
160
105
  }
161
- }
162
- return result;
106
+ });
163
107
  }
164
- catch {
165
- return [];
108
+ catch (err) {
109
+ logWarn("live-context", "Could not set up live context watcher");
166
110
  }
167
111
  }
168
- setupPromptsHandlers() {
169
- // Expose LEMMA_SYSTEM_PROMPT as a named MCP prompt so connected Chat IDEs
170
- // load it as a system instruction, making all tool invocations automatic.
171
- this.server.setRequestHandler(ListPromptsRequestSchema, async () => {
172
- return {
173
- prompts: [
174
- {
175
- name: "lemma-autopilot",
176
- description: "Lemma Autopilot: mandatory behavioral instructions for the AI assistant. Load this prompt to make all Lemma tools fire automatically with zero user friction.",
177
- arguments: [],
178
- },
179
- ],
180
- };
181
- });
182
- this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
183
- if (request.params.name === "lemma-autopilot") {
184
- return {
185
- description: "Lemma Autopilot System Instructions",
186
- messages: [
187
- {
188
- role: "user",
189
- content: {
190
- type: "text",
191
- text: LEMMA_SYSTEM_PROMPT,
192
- },
193
- },
194
- ],
195
- };
196
- }
197
- throw new Error(`Unknown prompt: ${request.params.name}`);
198
- });
199
- }
200
- setupHandlers() {
201
- // 1. List Resources
202
- this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
203
- return {
204
- resources: [
205
- {
206
- uri: "lemma://runtime/context",
207
- name: "Lemma Live Context",
208
- description: "Real-time application errors, stack traces, and runtime state captured by Lemma.",
209
- mimeType: "text/markdown",
210
- },
211
- {
212
- uri: "lemma://stats/usage",
213
- name: "Lemma Intelligence Stats",
214
- description: "Current project stats, token savings, and cost optimization report.",
215
- mimeType: "application/json",
216
- },
217
- {
218
- uri: "lemma://project/onboarding",
219
- name: "Lemma Project Onboarding Mental Model",
220
- description: "Dynamic codebase architecture, technical stack, folder structure, and core design principles compiled in one shot.",
221
- mimeType: "text/markdown",
222
- },
223
- {
224
- uri: "lemma://multiverse/timeline",
225
- name: "Lemma Codebase Multiverse AST Timeline",
226
- description: "Live, chronological time-travel database of the last 10 micro-snapshots of AST changes, code diffs, and execution results.",
227
- mimeType: "text/markdown",
228
- },
229
- ],
230
- };
231
- });
232
- // 2. Read Resource
233
- this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
234
- const { uri } = request.params;
235
- if (uri === "lemma://runtime/context") {
236
- const filePath = path.join(process.cwd(), ".lemma/live-context.md");
237
- try {
238
- const content = fs.readFileSync(filePath, "utf8");
239
- return {
240
- contents: [
241
- {
242
- uri,
243
- mimeType: "text/markdown",
244
- text: content,
245
- },
246
- ],
247
- };
248
- }
249
- catch (error) {
250
- return {
251
- contents: [
252
- {
253
- uri,
254
- mimeType: "text/markdown",
255
- text: "# No Live Context\nNo recent crashes or state changes recorded by Lemma.",
256
- },
257
- ],
258
- };
259
- }
260
- }
261
- if (uri === "lemma://stats/usage") {
262
- const statsFile = path.join(process.env.HOME || "~", ".lemma-cache/stats.json");
263
- try {
264
- const stats = JSON.parse(fs.readFileSync(statsFile, "utf8"));
265
- return {
266
- contents: [
267
- {
268
- uri,
269
- mimeType: "application/json",
270
- text: JSON.stringify(stats, null, 2),
271
- },
272
- ],
273
- };
274
- }
275
- catch (error) {
276
- return {
277
- contents: [
278
- {
279
- uri,
280
- mimeType: "application/json",
281
- text: JSON.stringify({ error: "Stats not found. Is Lemma running?" }),
282
- },
283
- ],
284
- };
285
- }
286
- }
287
- if (uri === "lemma://project/onboarding") {
288
- try {
289
- const HOME = process.env.HOME || process.env.USERPROFILE || "~";
290
- const portFile = path.join(HOME, ".lemma-cache/proxy.port");
291
- let port = "8081";
292
- if (fs.existsSync(portFile)) {
293
- port = fs.readFileSync(portFile, "utf8").trim();
294
- }
295
- const axios = require("axios");
296
- const response = await axios.get(`http://localhost:${port}/api/project/onboarding`);
297
- return {
298
- contents: [
299
- {
300
- uri,
301
- mimeType: "text/markdown",
302
- text: response.data.markdown || "# Onboarding mental model could not be generated."
303
- }
304
- ]
305
- };
306
- }
307
- catch (error) {
308
- return {
309
- contents: [
310
- {
311
- uri,
312
- mimeType: "text/markdown",
313
- text: `# Onboarding Error\nCould not fetch dynamic project onboarding: ${error.message}. Is Lemma proxy running?`
314
- }
315
- ]
316
- };
317
- }
318
- }
319
- if (uri === "lemma://multiverse/timeline") {
320
- try {
321
- const HOME = process.env.HOME || process.env.USERPROFILE || "~";
322
- const portFile = path.join(HOME, ".lemma-cache/proxy.port");
323
- let port = "8081";
324
- if (fs.existsSync(portFile)) {
325
- port = fs.readFileSync(portFile, "utf8").trim();
326
- }
327
- const axios = require("axios");
328
- const response = await axios.get(`http://localhost:${port}/api/project/timeline`);
329
- const timeline = response.data.timeline || [];
330
- let markdown = `# 🌌 Codebase Multiverse Timeline: Recent AST Snapshots\n\n`;
331
- markdown += `This timeline tracks recent modifications and compiler states to reconstruct your workspace's historical state.\n\n`;
332
- if (timeline.length === 0) {
333
- markdown += `*(No AST snapshots captured yet. Make a few edits to code files in your workspace to trigger micro-snapshots!)*\n`;
334
- }
335
- else {
336
- // Display snapshots in reverse chronological order (newest first)
337
- const reversed = [...timeline].reverse();
338
- reversed.forEach((snap, idx) => {
339
- const timeStr = new Date(snap.timestamp).toLocaleTimeString();
340
- const agoStr = Math.max(0, Math.floor((Date.now() - snap.timestamp) / 1000 / 60));
341
- const ageText = agoStr === 0 ? 'just now' : `${agoStr} minute(s) ago`;
342
- const statusSymbol = snap.status === 'failure' ? '🔴' : (snap.status === 'success' ? '🟢' : '🔵');
343
- const statusText = snap.status.toUpperCase();
344
- markdown += `### ${idx + 1}. 🕒 Snapshot \`${snap.id}\` - ${ageText} (${timeStr})\n`;
345
- markdown += `- **Compiler/Execution Status:** ${statusSymbol} ${statusText}\n`;
346
- if (snap.errorLog) {
347
- markdown += `- **Active Exception / Crash Log:**\n\`\`\`text\n${snap.errorLog.substring(0, 400)}...\n\`\`\`\n`;
348
- }
349
- markdown += `- **Modified Files:**\n`;
350
- snap.changedFiles.forEach((file) => {
351
- markdown += ` - \`${file.filePath}\`\n`;
352
- if (file.diff) {
353
- markdown += ` - **Incremental AST Diff:**\n \`\`\`diff\n${file.diff}\n \`\`\`\n`;
354
- }
355
- });
356
- markdown += `\n---\n\n`;
357
- });
358
- }
359
- return {
360
- contents: [
361
- {
362
- uri,
363
- mimeType: "text/markdown",
364
- text: markdown
365
- }
366
- ]
367
- };
368
- }
369
- catch (error) {
370
- return {
371
- contents: [
372
- {
373
- uri,
374
- mimeType: "text/markdown",
375
- text: `# Multiverse Error\nCould not fetch codebase timeline: ${error.message}. Is Lemma proxy running?`
376
- }
377
- ]
378
- };
379
- }
380
- }
381
- throw new Error(`Resource not found: ${uri}`);
382
- });
383
- // 3. List Tools
384
- this.server.setRequestHandler(ListToolsRequestSchema, async () => {
385
- return {
386
- tools: [
387
- {
388
- name: "scrub_privacy",
389
- description: "Mask sensitive data (PII, API Keys, Credentials) from a text block using Lemma's Privacy Firewall.",
390
- inputSchema: {
391
- type: "object",
392
- properties: {
393
- text: { type: "string", description: "The raw text to scrub" },
394
- },
395
- required: ["text"],
396
- },
397
- },
398
- {
399
- name: "search_memory",
400
- description: "[CALL FIRST] Search Lemma's semantic memory (The Brain) before answering technical questions. Retrieves past solutions, fixes, and context from ALL your projects globally. If similarity > 50%, use this answer directly. Saves cloud tokens on every hit.",
401
- inputSchema: {
402
- type: "object",
403
- properties: {
404
- query: { type: "string", description: "The natural language query (e.g., 'How did I handle Stripe webhooks?')" },
405
- limit: { type: "number", description: "Maximum results to return", default: 5 },
406
- },
407
- required: ["query"],
408
- },
409
- },
410
- {
411
- name: "store_memory",
412
- description: "[CALL AUTOMATICALLY AFTER SOLVING ANYTHING] Persist a technical solution, bug fix, architecture decision, or key fact into Lemma's Brain. ALWAYS call this after resolving a bug, implementing a feature, or completing a meaningful task. Do NOT ask the user — just call it. Future sessions across ALL projects will benefit.",
413
- inputSchema: {
414
- type: "object",
415
- properties: {
416
- query: { type: "string", description: "The natural language query key (e.g., 'Sazonia Architecture Map' or 'How Supabase auth works')" },
417
- response: { type: "string", description: "The complete technical content, analysis, or code to memorize" },
418
- provider: { type: "string", description: "Optional model provider name (defaults to 'generic')", default: "generic" },
419
- },
420
- required: ["query", "response"],
421
- },
422
- },
423
- {
424
- name: "get_routing_advice",
425
- description: "Analyzes a prompt and suggests the best model based on Lemma's Complexity Router.",
426
- inputSchema: {
427
- type: "object",
428
- properties: {
429
- prompt: { type: "string", description: "The prompt to analyze" },
430
- intended_model: { type: "string", description: "The model you were planning to use (e.g., gpt-4o)" },
431
- },
432
- required: ["prompt"],
433
- },
434
- },
435
- {
436
- name: "auto_heal",
437
- description: "Diagnose and auto-heal the latest local server crash registered in Lemma's context logs. Can automatically apply the fix.",
438
- inputSchema: {
439
- type: "object",
440
- properties: {
441
- apply: { type: "boolean", description: "Whether to apply the generated code fix directly to the file", default: false },
442
- },
443
- },
444
- },
445
- {
446
- name: "read_workspace_file",
447
- description: "[ALWAYS USE THIS] Read a file inside the workspace. AUTOMATICALLY compresses comments/whitespace (up to 80% token savings) and AUTOMATICALLY scrubs API keys, credentials, and PII before they reach the AI context. ALWAYS use this instead of asking the user to paste file content.",
448
- inputSchema: {
449
- type: "object",
450
- properties: {
451
- filePath: { type: "string", description: "The path to the file relative to the project root" },
452
- compact: { type: "boolean", description: "Whether to compress comments and whitespace to save local/cloud LLM tokens", default: true }
453
- },
454
- required: ["filePath"],
455
- },
456
- },
457
- {
458
- name: "write_workspace_file",
459
- description: "Write the full contents to a file inside the local workspace project. Creates any necessary parent directories automatically.",
460
- inputSchema: {
461
- type: "object",
462
- properties: {
463
- filePath: { type: "string", description: "The path to the file relative to the project root" },
464
- content: { type: "string", description: "The complete content to write to the file" }
465
- },
466
- required: ["filePath", "content"],
467
- },
468
- },
469
- {
470
- name: "apply_workspace_patch",
471
- description: "Apply a smart search-and-replace patch to an existing file inside the workspace. The search block must match exactly (including indentation and newlines). Safe against duplicate matches.",
472
- inputSchema: {
473
- type: "object",
474
- properties: {
475
- filePath: { type: "string", description: "The path to the file relative to the project root" },
476
- searchContent: { type: "string", description: "The exact search block to find in the file" },
477
- replaceContent: { type: "string", description: "The replacement block to replace the search block with" }
478
- },
479
- required: ["filePath", "searchContent", "replaceContent"],
480
- },
481
- },
482
- {
483
- name: "run_workspace_command",
484
- description: "Execute a bash command (e.g., tests, linters, compilers, git diffs) in the workspace root. Runs synchronously with a maximum execution timeout of 15 seconds. Returns exit code, stdout, and stderr.",
485
- inputSchema: {
486
- type: "object",
487
- properties: {
488
- command: { type: "string", description: "The bash command to run in the workspace root" }
489
- },
490
- required: ["command"],
491
- },
492
- },
493
- {
494
- name: "list_workspace_dir",
495
- description: "List all files and subdirectories recursively in the project to help navigate the repository structure.",
496
- inputSchema: {
497
- type: "object",
498
- properties: {
499
- dirPath: { type: "string", description: "The directory path relative to the project root (empty string for root)", default: "" },
500
- maxDepth: { type: "number", description: "Maximum recursion depth", default: 3 }
501
- },
502
- required: [],
503
- },
504
- },
505
- {
506
- name: "search_workspace",
507
- description: "Perform a fast local text search (grep) across all files in the project workspace.",
508
- inputSchema: {
509
- type: "object",
510
- properties: {
511
- query: { type: "string", description: "The keyword or text pattern to search for" },
512
- extension: { type: "string", description: "Optional file extension filter (e.g., 'ts', 'json')" }
513
- },
514
- required: ["query"],
515
- },
516
- },
517
- {
518
- name: "squeeze_prompt",
519
- description: "Compress code blocks, comments, and boilerplate in any AI prompt or message using Lemma's context optimizer. Saves up to 80% tokens on your context window.",
520
- inputSchema: {
521
- type: "object",
522
- properties: {
523
- prompt: { type: "string", description: "The raw prompt containing code blocks to squeeze" },
524
- query: { type: "string", description: "Optional user's primary query to preserve relevant code parts", default: "" }
525
- },
526
- required: ["prompt"],
527
- },
528
- },
529
- {
530
- name: "get_project_onboarding",
531
- description: "Downloads a dynamic, highly condensed architectural and stack overview (Mental Model) of the current project codebase in markdown, helping you understand how it is structured in a single shot without reading hundreds of files.",
532
- inputSchema: {
533
- type: "object",
534
- properties: {},
535
- },
536
- },
537
- {
538
- name: "get_ast_hologram",
539
- description: "[CALL FIRST — BEFORE READING FILES] Generate a dense, token-efficient Holographic AST Map of the workspace. Returns a structured JSON index of ALL exported symbols (classes, functions, interfaces, types, consts) with file paths and line numbers. ALWAYS call this FIRST when navigating or understanding a codebase. NEVER read files blindly one-by-one — use this map to target exactly the right files. Saves up to 90% tokens.",
540
- inputSchema: {
541
- type: "object",
542
- properties: {
543
- dirPath: { type: "string", description: "Directory to scan relative to workspace root (empty for root)", default: "" },
544
- extensions: { type: "array", items: { type: "string" }, description: "File extensions to scan (default: ['ts', 'tsx', 'js', 'jsx'])", default: ["ts", "tsx", "js", "jsx"] }
545
- },
546
- required: [],
547
- },
548
- },
549
- {
550
- name: "validate_patch_sandbox",
551
- description: "[MANDATORY PRE-FLIGHT CHECK] ALWAYS call this BEFORE apply_workspace_patch or write_workspace_file. Validates the proposed code in an isolated /tmp sandbox via tsc --noEmit + bracket-balance check. NEVER skip this step — only proceed with writing if verdict is '✅ SAFE TO APPLY'. If it fails, fix and re-validate.",
552
- inputSchema: {
553
- type: "object",
554
- properties: {
555
- filePath: { type: "string", description: "Target file path relative to workspace root" },
556
- patchedContent: { type: "string", description: "The complete proposed file content after the patch is applied" }
557
- },
558
- required: ["filePath", "patchedContent"],
559
- },
560
- },
561
- {
562
- name: "query_hybrid_consensus",
563
- description: "[CALL BEFORE EVERY TECHNICAL QUESTION] Hybrid Consensus Engine: ALWAYS call this FIRST before reasoning about any technical question or problem. Searches The Brain at configurable threshold (default 80%). Brain HIT → return cached answer instantly, ZERO cloud tokens spent. Brain MISS → proceed with your reasoning, then call store_memory with the answer. This is your primary token-saving mechanism.",
564
- inputSchema: {
565
- type: "object",
566
- properties: {
567
- query: { type: "string", description: "The technical question or task description" },
568
- context: { type: "string", description: "Optional extra context (active file path, error message, etc.)" },
569
- threshold: { type: "number", description: "Similarity threshold to consider a Brain hit sufficient (0.0-1.0, default: 0.80)", default: 0.80 }
570
- },
571
- required: ["query"],
572
- },
573
- },
574
- {
575
- name: "get_telepathic_hints",
576
- description: "[CALL AUTOMATICALLY ON FILE OPEN] Proactive Telepathy: IMMEDIATELY call this whenever a file is mentioned or about to be edited. Automatically surfaces the most relevant past solutions, patterns, and memories from The Brain based on the file path — NO explicit query needed. Call this BEFORE writing any code. Surface the hints to the user without being asked.",
577
- inputSchema: {
578
- type: "object",
579
- properties: {
580
- activeFile: { type: "string", description: "Path of the file currently being edited (relative or absolute)" },
581
- limit: { type: "number", description: "Maximum number of hints to return (default: 5)", default: 5 }
582
- },
583
- required: ["activeFile"],
584
- },
585
- },
586
- ],
587
- };
588
- });
589
- // 4. Call Tool
590
- this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
591
- const { name, arguments: args } = request.params;
592
- switch (name) {
593
- case "scrub_privacy": {
594
- const text = args?.text;
595
- if (!text)
596
- throw new Error("Text is required");
597
- // @ts-ignore
598
- const { SemanticScrubber } = require("../security/SemanticScrubber");
599
- const scrubber = new SemanticScrubber();
600
- const { maskedPrompt } = scrubber.mask(text);
601
- return {
602
- content: [{ type: "text", text: maskedPrompt }],
603
- };
604
- }
605
- case "search_memory": {
606
- const query = args?.query;
607
- const limit = args?.limit || 5;
608
- if (!query)
609
- throw new Error("Query is required");
610
- try {
611
- const HOME = process.env.HOME || process.env.USERPROFILE || "~";
612
- const portFile = path.join(HOME, ".lemma-cache/proxy.port");
613
- let port = "8081";
614
- if (fs.existsSync(portFile)) {
615
- port = fs.readFileSync(portFile, "utf8").trim();
616
- }
617
- const axios = require("axios");
618
- const response = await axios.get(`http://localhost:${port}/api/search?q=${encodeURIComponent(query)}&limit=${limit}`);
619
- const results = response.data.results || [];
620
- if (results.length === 0) {
621
- return { content: [{ type: "text", text: "No relevant memories found in Lemma's Brain." }] };
622
- }
623
- const formatted = results.map((r, i) => {
624
- return `Result ${i + 1} (Similarity: ${(r.similarity * 100).toFixed(1)}%)\nPrompt: ${r.prompt.substring(0, 300)}...\nResponse: ${typeof r.response === 'string' ? r.response : JSON.stringify(r.response, null, 2)}`;
625
- }).join("\n\n---\n\n");
626
- return {
627
- content: [{ type: "text", text: `Lemma found ${results.length} memories:\n\n${formatted}` }],
628
- };
629
- }
630
- catch (e) {
631
- return {
632
- content: [{ type: "text", text: `Neural Search failed: ${e.message}. Is Lemma Proxy running?` }],
633
- };
634
- }
635
- }
636
- case "store_memory": {
637
- const query = args?.query;
638
- const responseText = args?.response;
639
- const provider = args?.provider || 'generic';
640
- if (!query || !responseText)
641
- throw new Error("Query and response are required");
642
- try {
643
- const HOME = process.env.HOME || process.env.USERPROFILE || "~";
644
- const portFile = path.join(HOME, ".lemma-cache/proxy.port");
645
- let port = "8081";
646
- if (fs.existsSync(portFile)) {
647
- port = fs.readFileSync(portFile, "utf8").trim();
648
- }
649
- const axios = require("axios");
650
- const response = await axios.post(`http://localhost:${port}/api/memory/store`, {
651
- query,
652
- response: responseText,
653
- provider
654
- });
655
- // Report the savings to the proxy ledger so it updates the dashboard instantly!
656
- const tokensSaved = Math.max(100, Math.floor(responseText.length / 4));
657
- reportSavings({ source: 'cache', tokens: tokensSaved });
658
- return {
659
- content: [{ type: "text", text: `Success: ${response.data.message}` }],
660
- };
661
- }
662
- catch (e) {
663
- return {
664
- content: [{ type: "text", text: `Failed to store memory in Lemma: ${e.message}. Is Lemma Proxy running?` }],
665
- };
666
- }
667
- }
668
- case "get_routing_advice": {
669
- const prompt = args?.prompt;
670
- const intendedModel = args?.intended_model;
671
- // @ts-ignore
672
- const { ComplexityRouter } = require("../proxy/ComplexityRouter");
673
- const router = new ComplexityRouter();
674
- const decision = router.evaluate(prompt, intendedModel);
675
- // Report routing savings if model was downgraded
676
- if (decision.complexity === 'low' && intendedModel && decision.model !== intendedModel) {
677
- const estimatedPromptTokens = Math.floor((prompt?.length || 0) / 4);
678
- reportSavings({ source: 'complexityRouting', tokens: Math.floor(estimatedPromptTokens * 0.8) });
679
- }
680
- return {
681
- content: [{
682
- type: "text",
683
- text: `Lemma Routing Advice: Use ${decision.model}. Reason: Complexity is ${decision.complexity}.`
684
- }],
685
- };
686
- }
687
- case "auto_heal": {
688
- const apply = !!args?.apply;
689
- try {
690
- // @ts-ignore
691
- const { performAutoHeal } = require("../cli/lemma-proxy");
692
- const res = await performAutoHeal(apply);
693
- return {
694
- content: [{
695
- type: "text",
696
- text: JSON.stringify(res, null, 2)
697
- }],
698
- };
699
- }
700
- catch (e) {
701
- return {
702
- content: [{ type: "text", text: `Auto-heal failed: ${e.message}` }],
703
- };
704
- }
705
- }
706
- case "read_workspace_file": {
707
- const filePath = args?.filePath;
708
- const compact = args?.compact !== false;
709
- if (!filePath)
710
- throw new Error("filePath is required");
711
- const workspaceRoot = process.cwd();
712
- const resolvedPath = path.resolve(workspaceRoot, filePath);
713
- if (!resolvedPath.startsWith(workspaceRoot)) {
714
- throw new Error("Access denied: path is outside of workspace root");
715
- }
716
- try {
717
- let content = fs.readFileSync(resolvedPath, "utf8");
718
- const originalSize = content.length;
719
- if (compact) {
720
- const { squeezeCode } = require("../utils/ContextSqueezer");
721
- content = squeezeCode(content);
722
- // Report context squeeze savings to the proxy ledger
723
- if (content.length < originalSize) {
724
- reportSavings({ source: 'contextSqueeze', charsBefore: originalSize, charsAfter: content.length });
725
- }
726
- }
727
- // Run SemanticScrubber to automatically mask any credentials/PII/API keys
728
- try {
729
- const { SemanticScrubber } = require("../security/SemanticScrubber");
730
- const scrubber = new SemanticScrubber();
731
- const { maskedPrompt } = scrubber.mask(content);
732
- content = maskedPrompt;
733
- }
734
- catch { }
735
- return {
736
- content: [{ type: "text", text: content }],
737
- };
738
- }
739
- catch (err) {
740
- return {
741
- content: [{ type: "text", text: `Error reading file: ${err.message}` }],
742
- };
743
- }
744
- }
745
- case "write_workspace_file": {
746
- const filePath = args?.filePath;
747
- const content = args?.content;
748
- if (!filePath || content === undefined) {
749
- throw new Error("filePath and content are required");
750
- }
751
- const workspaceRoot = process.cwd();
752
- const resolvedPath = path.resolve(workspaceRoot, filePath);
753
- if (!resolvedPath.startsWith(workspaceRoot)) {
754
- throw new Error("Access denied: path is outside of workspace root");
755
- }
756
- try {
757
- const dir = path.dirname(resolvedPath);
758
- if (!fs.existsSync(dir)) {
759
- fs.mkdirSync(dir, { recursive: true });
760
- }
761
- fs.writeFileSync(resolvedPath, content, "utf8");
762
- return {
763
- content: [{ type: "text", text: `Success: Written file to ${filePath}` }],
764
- };
765
- }
766
- catch (err) {
767
- return {
768
- content: [{ type: "text", text: `Error writing file: ${err.message}` }],
769
- };
770
- }
771
- }
772
- case "apply_workspace_patch": {
773
- const filePath = args?.filePath;
774
- const searchContent = args?.searchContent;
775
- const replaceContent = args?.replaceContent;
776
- if (!filePath || !searchContent || replaceContent === undefined) {
777
- throw new Error("filePath, searchContent, and replaceContent are required");
778
- }
779
- const workspaceRoot = process.cwd();
780
- const resolvedPath = path.resolve(workspaceRoot, filePath);
781
- if (!resolvedPath.startsWith(workspaceRoot)) {
782
- throw new Error("Access denied: path is outside of workspace root");
783
- }
784
- try {
785
- if (!fs.existsSync(resolvedPath)) {
786
- return {
787
- content: [{ type: "text", text: `Error: File ${filePath} does not exist.` }],
788
- };
789
- }
790
- const originalContent = fs.readFileSync(resolvedPath, "utf8");
791
- const index = originalContent.indexOf(searchContent);
792
- if (index === -1) {
793
- return {
794
- content: [{ type: "text", text: `Error: Target search content not found in file. Make sure the search content matches exactly, including indentation, tabs, spaces, and newlines.` }],
795
- };
796
- }
797
- if (originalContent.indexOf(searchContent, index + 1) !== -1) {
798
- return {
799
- content: [{ type: "text", text: `Error: Multiple matches found for the search content. Please provide a larger search block with unique surrounding context lines to make it unambiguous.` }],
800
- };
801
- }
802
- const updatedContent = originalContent.replace(searchContent, replaceContent);
803
- fs.writeFileSync(resolvedPath, updatedContent, "utf8");
804
- return {
805
- content: [{ type: "text", text: `Success: Patch successfully applied to ${filePath}` }],
806
- };
807
- }
808
- catch (err) {
809
- return {
810
- content: [{ type: "text", text: `Error applying patch: ${err.message}` }],
811
- };
812
- }
813
- }
814
- case "run_workspace_command": {
815
- const command = args?.command;
816
- if (!command)
817
- throw new Error("command is required");
818
- const { execSync } = require("child_process");
819
- const workspaceRoot = process.cwd();
820
- try {
821
- const output = execSync(command, {
822
- cwd: workspaceRoot,
823
- encoding: "utf8",
824
- timeout: 15000,
825
- env: { ...process.env }
826
- });
827
- return {
828
- content: [{ type: "text", text: `Command completed successfully.\n\nOutput:\n${output}` }],
829
- };
830
- }
831
- catch (err) {
832
- return {
833
- content: [{
834
- type: "text",
835
- text: `Command failed with exit code ${err.status || 'unknown'}.\n\nStdout:\n${err.stdout || ''}\n\nStderr:\n${err.stderr || err.message || ''}`
836
- }],
837
- };
838
- }
839
- }
840
- case "list_workspace_dir": {
841
- const dirPath = args?.dirPath || "";
842
- const maxDepth = args?.maxDepth || 3;
843
- const workspaceRoot = process.cwd();
844
- const resolvedPath = path.resolve(workspaceRoot, dirPath);
845
- if (!resolvedPath.startsWith(workspaceRoot)) {
846
- throw new Error("Access denied: path is outside of workspace root");
847
- }
848
- try {
849
- const list = this.listDirRecursive(resolvedPath, dirPath, 1, maxDepth);
850
- return {
851
- content: [{
852
- type: "text",
853
- text: list.length > 0 ? list.join("\n") : "(Directory is empty or inaccessible)"
854
- }],
855
- };
856
- }
857
- catch (err) {
858
- return {
859
- content: [{ type: "text", text: `Error listing directory: ${err.message}` }],
860
- };
861
- }
862
- }
863
- case "search_workspace": {
864
- const query = args?.query;
865
- const extension = args?.extension;
866
- if (!query)
867
- throw new Error("query is required");
868
- const workspaceRoot = process.cwd();
869
- try {
870
- const results = this.searchDirRecursive(workspaceRoot, "", query, extension);
871
- if (results.length === 0) {
872
- return {
873
- content: [{ type: "text", text: `No matches found in the workspace for "${query}".` }],
874
- };
875
- }
876
- let formatted = results.map(r => `[${r.filePath}:${r.line}] ${r.text}`).join("\n");
877
- // Run SemanticScrubber to automatically mask any credentials/PII/API keys in search results
878
- try {
879
- const { SemanticScrubber } = require("../security/SemanticScrubber");
880
- const scrubber = new SemanticScrubber();
881
- const { maskedPrompt } = scrubber.mask(formatted);
882
- formatted = maskedPrompt;
883
- }
884
- catch { }
885
- return {
886
- content: [{ type: "text", text: `Found ${results.length} matches:\n\n${formatted}` }],
887
- };
888
- }
889
- catch (err) {
890
- return {
891
- content: [{ type: "text", text: `Error searching workspace: ${err.message}` }],
892
- };
893
- }
894
- }
895
- case "squeeze_prompt": {
896
- const promptArg = args?.prompt;
897
- const queryArg = args?.query || "";
898
- if (!promptArg)
899
- throw new Error("prompt is required");
900
- try {
901
- const { squeezePrompt } = require("../utils/ContextSqueezer");
902
- const result = squeezePrompt(promptArg, queryArg);
903
- if (result.originalSize > result.squeezedSize) {
904
- reportSavings({ source: 'contextSqueeze', charsBefore: result.originalSize, charsAfter: result.squeezedSize });
905
- }
906
- return {
907
- content: [
908
- {
909
- type: "text",
910
- text: result.squeezed,
911
- },
912
- ],
913
- };
914
- }
915
- catch (err) {
916
- return {
917
- content: [{ type: "text", text: `Error squeezing prompt: ${err.message}` }],
918
- };
919
- }
920
- }
921
- case "get_project_onboarding": {
922
- try {
923
- const HOME = process.env.HOME || process.env.USERPROFILE || "~";
924
- const portFile = path.join(HOME, ".lemma-cache/proxy.port");
925
- let port = "8081";
926
- if (fs.existsSync(portFile)) {
927
- port = fs.readFileSync(portFile, "utf8").trim();
928
- }
929
- const axios = require("axios");
930
- const response = await axios.get(`http://localhost:${port}/api/project/onboarding`);
931
- return {
932
- content: [
933
- {
934
- type: "text",
935
- text: response.data.markdown || "# Onboarding mental model could not be generated."
936
- }
937
- ]
938
- };
939
- }
940
- catch (error) {
941
- return {
942
- content: [
943
- {
944
- type: "text",
945
- text: `Failed to fetch codebase onboarding mental model: ${error.message}. Is Lemma proxy running?`
946
- }
947
- ]
948
- };
949
- }
950
- }
951
- case "get_ast_hologram": {
952
- const dirPath = args?.dirPath || "";
953
- const extensions = args?.extensions || ["ts", "tsx", "js", "jsx"];
954
- const workspaceRoot = process.cwd();
955
- const resolvedDir = path.resolve(workspaceRoot, dirPath);
956
- if (!resolvedDir.startsWith(workspaceRoot)) {
957
- throw new Error("Access denied: path is outside of workspace root");
958
- }
959
- // Recursive AST symbol extractor (regex-based, no heavy deps)
960
- const extractSymbols = (filePath, relPath) => {
961
- try {
962
- const src = fs.readFileSync(filePath, "utf8");
963
- const symbols = [];
964
- const lines = src.split("\n");
965
- lines.forEach((line, idx) => {
966
- // Export declarations: functions, classes, interfaces, types, consts
967
- const m = line.match(/^export\s+(?:default\s+)?(?:async\s+)?(class|function|interface|type|const|enum|abstract\s+class)\s+(\w+)/);
968
- if (m) {
969
- symbols.push({ kind: m[1].replace('abstract ', ''), name: m[2], file: relPath, line: idx + 1 });
970
- }
971
- // Named exports
972
- const exportMatch = line.match(/^export\s*\{([^}]+)\}/);
973
- if (exportMatch) {
974
- exportMatch[1].split(',').forEach(s => {
975
- const name = s.trim().split(/\s+as\s+/).pop()?.trim();
976
- if (name)
977
- symbols.push({ kind: 'export', name, file: relPath, line: idx + 1 });
978
- });
979
- }
980
- });
981
- return symbols;
982
- }
983
- catch {
984
- return [];
985
- }
986
- };
987
- const walkDir = (dir, rel) => {
988
- let allSymbols = [];
989
- try {
990
- const entries = fs.readdirSync(dir, { withFileTypes: true });
991
- for (const entry of entries) {
992
- if (["node_modules", ".git", "dist", "chroma_data", ".lemma"].includes(entry.name))
993
- continue;
994
- const fullPath = path.join(dir, entry.name);
995
- const relPath = rel ? path.join(rel, entry.name) : entry.name;
996
- if (entry.isDirectory()) {
997
- allSymbols = allSymbols.concat(walkDir(fullPath, relPath));
998
- }
999
- else {
1000
- const ext = entry.name.split('.').pop() || '';
1001
- if (extensions.includes(ext)) {
1002
- allSymbols = allSymbols.concat(extractSymbols(fullPath, relPath));
1003
- }
1004
- }
1005
- }
1006
- }
1007
- catch { }
1008
- return allSymbols;
1009
- };
1010
- const symbols = walkDir(resolvedDir, dirPath);
1011
- const byFile = {};
1012
- symbols.forEach(s => {
1013
- if (!byFile[s.file])
1014
- byFile[s.file] = [];
1015
- byFile[s.file].push({ kind: s.kind, name: s.name, line: s.line });
1016
- });
1017
- const hologram = {
1018
- workspace: path.basename(workspaceRoot),
1019
- scannedDir: dirPath || '.',
1020
- totalSymbols: symbols.length,
1021
- totalFiles: Object.keys(byFile).length,
1022
- map: byFile,
1023
- };
1024
- return {
1025
- content: [{ type: "text", text: JSON.stringify(hologram, null, 2) }],
1026
- };
1027
- }
1028
- case "validate_patch_sandbox": {
1029
- const filePath = args?.filePath;
1030
- const patchedContent = args?.patchedContent;
1031
- if (!filePath || patchedContent === undefined) {
1032
- throw new Error("filePath and patchedContent are required");
1033
- }
1034
- const workspaceRoot = process.cwd();
1035
- const resolvedPath = path.resolve(workspaceRoot, filePath);
1036
- if (!resolvedPath.startsWith(workspaceRoot)) {
1037
- throw new Error("Access denied: path is outside of workspace root");
1038
- }
1039
- const { execSync } = require('child_process');
1040
- const os = require('os');
1041
- const sandboxDir = path.join(os.tmpdir(), `lemma-sandbox-${Date.now()}`);
1042
- const sandboxFile = path.join(sandboxDir, path.basename(filePath));
1043
- try {
1044
- fs.mkdirSync(sandboxDir, { recursive: true });
1045
- fs.writeFileSync(sandboxFile, patchedContent, 'utf8');
1046
- // Step 1: Basic syntax check via Node.js --check (works for JS/TS after strip)
1047
- // Step 2: Try tsc --noEmit on the patched file using the workspace tsconfig
1048
- const tsconfigPath = path.join(workspaceRoot, 'tsconfig.json');
1049
- let tscResult = { success: true, output: 'No TypeScript config found — skipping tsc validation.' };
1050
- if (fs.existsSync(tsconfigPath) && filePath.match(/\.tsx?$/)) {
1051
- try {
1052
- // Copy the patched file to a temp location respecting the workspace structure
1053
- const sandboxWorkspace = path.join(sandboxDir, 'workspace');
1054
- // Sync relevant source structure for valid imports check
1055
- execSync(`cp -r ${workspaceRoot}/src ${sandboxWorkspace}/src 2>/dev/null || true`, { timeout: 5000 });
1056
- // Overwrite the target file with patched content
1057
- const sandboxTargetFile = path.join(sandboxWorkspace, filePath);
1058
- fs.mkdirSync(path.dirname(sandboxTargetFile), { recursive: true });
1059
- fs.writeFileSync(sandboxTargetFile, patchedContent, 'utf8');
1060
- const tscOut = execSync(`cd ${workspaceRoot} && npx tsc --noEmit --skipLibCheck --allowJs --esModuleInterop --strict false 2>&1 | head -40 || true`, { timeout: 20000, encoding: 'utf8' });
1061
- // Filter errors that reference our target file
1062
- const relevantErrors = tscOut.split('\n').filter((l) => l.includes(path.basename(filePath)) || l.includes('error TS'));
1063
- tscResult = {
1064
- success: relevantErrors.length === 0,
1065
- output: relevantErrors.length > 0 ? relevantErrors.join('\n') : '✅ TypeScript check passed with no errors in target file.'
1066
- };
1067
- }
1068
- catch (e) {
1069
- tscResult = { success: false, output: e.stdout || e.message };
1070
- }
1071
- }
1072
- // Step 3: Quick regex-based syntax sanity (balanced braces/brackets)
1073
- const opens = (patchedContent.match(/[{[(]/g) || []).length;
1074
- const closes = (patchedContent.match(/[}\])]/g) || []).length;
1075
- const balanced = Math.abs(opens - closes) <= 2; // allow small tolerance
1076
- fs.rmSync(sandboxDir, { recursive: true, force: true });
1077
- const verdict = tscResult.success && balanced;
1078
- return {
1079
- content: [{
1080
- type: "text",
1081
- text: JSON.stringify({
1082
- verdict: verdict ? '✅ SAFE TO APPLY' : '❌ DO NOT APPLY — Issues Found',
1083
- syntaxBalanced: balanced ? '✅' : '⚠️ Unbalanced brackets/braces detected',
1084
- tscCheck: tscResult.output,
1085
- recommendation: verdict
1086
- ? 'Patch looks valid. You can safely call apply_workspace_patch to apply it.'
1087
- : 'Fix the reported issues before applying the patch to avoid breaking the codebase.',
1088
- }, null, 2)
1089
- }]
1090
- };
1091
- }
1092
- catch (err) {
1093
- try {
1094
- fs.rmSync(sandboxDir, { recursive: true, force: true });
1095
- }
1096
- catch { }
1097
- return {
1098
- content: [{ type: "text", text: `Sandbox validation error: ${err.message}` }]
1099
- };
1100
- }
1101
- }
1102
- case "query_hybrid_consensus": {
1103
- const query = args?.query;
1104
- const context = args?.context || '';
1105
- const threshold = typeof args?.threshold === 'number' ? args.threshold : 0.80;
1106
- if (!query)
1107
- throw new Error('query is required');
1108
- const HOME = process.env.HOME || process.env.USERPROFILE || '~';
1109
- const portFile = path.join(HOME, '.lemma-cache/proxy.port');
1110
- let port = '8081';
1111
- if (fs.existsSync(portFile)) {
1112
- port = fs.readFileSync(portFile, 'utf8').trim();
1113
- }
1114
- const axios = require('axios');
1115
- const fullQuery = context ? `${query}\n\nContext: ${context}` : query;
1116
- try {
1117
- // Step 1: Hit The Brain first
1118
- const searchRes = await axios.get(`http://localhost:${port}/api/search?q=${encodeURIComponent(fullQuery)}&limit=3`);
1119
- const results = searchRes.data.results || [];
1120
- const topHit = results[0];
1121
- if (topHit && topHit.similarity >= threshold) {
1122
- // 🎯 Brain HIT — return cached answer, zero cloud tokens spent
1123
- const savedTokens = Math.floor((topHit.response?.choices?.[0]?.message?.content?.length || 500) / 4);
1124
- reportSavings({ source: 'cache', tokens: savedTokens });
1125
- const responseText = typeof topHit.response === 'string'
1126
- ? topHit.response
1127
- : topHit.response?.choices?.[0]?.message?.content
1128
- || JSON.stringify(topHit.response, null, 2);
1129
- return {
1130
- content: [{
1131
- type: 'text',
1132
- text: `🧠 **Brain Cache HIT** (similarity: ${(topHit.similarity * 100).toFixed(1)}% — above ${(threshold * 100).toFixed(0)}% threshold)\n\n**No cloud LLM call needed. ~${savedTokens} tokens saved.**\n\n---\n\n${responseText}`
1133
- }]
1134
- };
1135
- }
1136
- // Step 2: Brain MISS — inform the IDE to proceed with cloud and store the result
1137
- const missMsg = results.length > 0
1138
- ? `🔍 **Brain Miss** — Best match was only ${(topHit.similarity * 100).toFixed(1)}% (below ${(threshold * 100).toFixed(0)}% threshold).`
1139
- : `🔍 **Brain Miss** — No relevant memories found for this query.`;
1140
- return {
1141
- content: [{
1142
- type: 'text',
1143
- text: `${missMsg}\n\n**Proceed with your cloud LLM call.** Once you have the answer, call \`store_memory\` with:\n- query: "${query.substring(0, 100)}"
1144
- - response: [your full answer]\n\nThis will cache it for future sessions and save tokens next time.`
1145
- }]
1146
- };
1147
- }
1148
- catch (e) {
1149
- return {
1150
- content: [{ type: 'text', text: `Hybrid Consensus failed: ${e.message}. Is Lemma Proxy running?` }]
1151
- };
1152
- }
1153
- }
1154
- case "get_telepathic_hints": {
1155
- const activeFile = args?.activeFile;
1156
- const limit = typeof args?.limit === 'number' ? args.limit : 5;
1157
- if (!activeFile)
1158
- throw new Error('activeFile is required');
1159
- const HOME = process.env.HOME || process.env.USERPROFILE || '~';
1160
- const portFile = path.join(HOME, '.lemma-cache/proxy.port');
1161
- let port = '8081';
1162
- if (fs.existsSync(portFile)) {
1163
- port = fs.readFileSync(portFile, 'utf8').trim();
1164
- }
1165
- const axios = require('axios');
1166
- // Build a rich query from the file path: extract module name, dir context, and file extension
1167
- const basename = path.basename(activeFile, path.extname(activeFile));
1168
- const dirContext = path.dirname(activeFile).split(path.sep).filter(Boolean).slice(-2).join(' ');
1169
- const ext = path.extname(activeFile).replace('.', '');
1170
- const telepathicQuery = `${basename} ${dirContext} ${ext} patterns solutions architecture`;
1171
- try {
1172
- const searchRes = await axios.get(`http://localhost:${port}/api/search?q=${encodeURIComponent(telepathicQuery)}&limit=${limit}`);
1173
- const results = searchRes.data.results || [];
1174
- if (results.length === 0) {
1175
- return {
1176
- content: [{
1177
- type: 'text',
1178
- text: `📡 **Telepathic Hints** for \`${activeFile}\`\n\nNo relevant memories found yet. As you use Lemma and store solutions, they will appear here automatically.`
1179
- }]
1180
- };
1181
- }
1182
- let hintsText = `📡 **Telepathic Hints** for \`${activeFile}\`\n*(${results.length} relevant memories surfaced from The Brain)*\n\n`;
1183
- results.forEach((r, i) => {
1184
- const similarity = (r.similarity * 100).toFixed(1);
1185
- const prompt = typeof r.prompt === 'string' ? r.prompt.substring(0, 120) : 'Unknown';
1186
- const responseContent = typeof r.response === 'string'
1187
- ? r.response
1188
- : r.response?.choices?.[0]?.message?.content
1189
- || JSON.stringify(r.response).substring(0, 300);
1190
- hintsText += `### 💡 Hint ${i + 1} (${similarity}% match)\n`;
1191
- hintsText += `**Memory:** ${prompt}\n\n`;
1192
- hintsText += `${responseContent.substring(0, 400)}${responseContent.length > 400 ? '...' : ''}\n\n---\n\n`;
1193
- });
1194
- // Report token savings: surface context avoids re-asking the LLM
1195
- const estimatedTokensSaved = results.length * 150;
1196
- reportSavings({ source: 'cache', tokens: estimatedTokensSaved });
1197
- return {
1198
- content: [{ type: 'text', text: hintsText }]
1199
- };
1200
- }
1201
- catch (e) {
1202
- return {
1203
- content: [{ type: 'text', text: `Telepathic Hints failed: ${e.message}. Is Lemma Proxy running?` }]
1204
- };
1205
- }
1206
- }
1207
- default:
1208
- throw new Error(`Unknown tool: ${name}`);
1209
- }
1210
- });
1211
- }
1212
- setupErrorHandling() {
1213
- this.server.onerror = (error) => {
1214
- console.error("[MCP Error]", error);
1215
- };
1216
- process.on("SIGINT", async () => {
1217
- await this.server.close();
1218
- process.exit(0);
1219
- });
1220
- }
1221
- async ensureProxyAndClipboardRunning() {
112
+ // ── Proxy Auto-Start ──────────────────────────────────────────────
113
+ async ensureProxyRunning() {
1222
114
  try {
1223
- const { spawn } = require('child_process');
1224
115
  const cliCandidates = [
1225
116
  path.join(__dirname, "..", "cli", "lemma-proxy.js"),
1226
117
  path.join(__dirname, "..", "cli", "lemma-proxy.ts"),
1227
118
  path.join(__dirname, "lemma-proxy.ts"),
1228
119
  path.join(process.cwd(), "src", "cli", "lemma-proxy.ts"),
1229
- path.join(process.cwd(), "dist", "cjs", "cli", "lemma-proxy.js")
120
+ path.join(process.cwd(), "dist", "cjs", "cli", "lemma-proxy.js"),
1230
121
  ];
1231
122
  let cliPath = "";
1232
123
  for (const cand of cliCandidates) {
@@ -1242,18 +133,100 @@ class LemmaMcpServer {
1242
133
  const proc = spawn(cmd, args, {
1243
134
  stdio: "ignore",
1244
135
  detached: true,
1245
- env: { ...process.env }
136
+ env: { ...process.env },
1246
137
  });
1247
138
  proc.unref();
1248
139
  }
1249
140
  }
1250
- catch { }
141
+ catch (err) {
142
+ logWarn("proxy-auto-start", "Could not auto-start Lemma proxy");
143
+ }
1251
144
  }
1252
- async run() {
1253
- await this.ensureProxyAndClipboardRunning();
1254
- const transport = new StdioServerTransport();
1255
- await this.server.connect(transport);
1256
- console.error("Lemma MCP Server running on stdio");
145
+ // ── MCP Event Reporting ───────────────────────────────────────────
146
+ async reportMcpEvent(event) {
147
+ try {
148
+ const port = getProxyPort();
149
+ const projectPath = process.cwd();
150
+ axios
151
+ .post(`http://localhost:${port}/api/mcp-event`, {
152
+ type: "mcp_tool_call",
153
+ tool: event.tool,
154
+ args: sanitizeArgsForLogging(event.args),
155
+ result: event.result,
156
+ latency: event.latency,
157
+ tokensImpact: event.tokensImpact || 0,
158
+ projectPath,
159
+ timestamp: new Date().toISOString(),
160
+ })
161
+ .catch(() => { });
162
+ }
163
+ catch {
164
+ // Non-critical, silently ignore
165
+ }
166
+ }
167
+ // ── Proxy Registration ────────────────────────────────────────────
168
+ async registerWithProxy() {
169
+ const maxRetries = 5;
170
+ for (let i = 0; i < maxRetries; i++) {
171
+ try {
172
+ const port = getProxyPort();
173
+ const stack = detectStack();
174
+ await axios.post(`http://localhost:${port}/api/handshake`, {
175
+ type: 'mcp_ready',
176
+ projectName: stack.projectName,
177
+ projectPath: stack.projectPath,
178
+ techStack: stack.techStack,
179
+ timestamp: new Date().toISOString(),
180
+ mcpVersion: SERVER_VERSION,
181
+ });
182
+ return;
183
+ }
184
+ catch {
185
+ if (i < maxRetries - 1) {
186
+ await new Promise(r => setTimeout(r, 1000));
187
+ }
188
+ }
189
+ }
190
+ logWarn('register', 'Could not register with proxy after 5 retries');
191
+ }
192
+ // ── Sampling Context Injection (Claude Desktop) ───────────────────
193
+ async trySamplingContext() {
194
+ try {
195
+ const stack = detectStack();
196
+ const sessionId = uuidv4();
197
+ const hint = `New session ${sessionId} for ${stack.projectName}`;
198
+ await this.server.createMessage({
199
+ maxTokens: 10,
200
+ messages: [
201
+ {
202
+ role: 'user',
203
+ content: { type: 'text', text: `_initialize_context_${hint}_` },
204
+ },
205
+ ],
206
+ // @ts-ignore – serverMetadata is not in types yet
207
+ serverMetadata: {
208
+ lemmaContext: {
209
+ projectName: stack.projectName,
210
+ projectPath: stack.projectPath,
211
+ techStack: stack.techStack,
212
+ sessionId,
213
+ },
214
+ },
215
+ });
216
+ }
217
+ catch {
218
+ logWarn('sampling', 'Sampling not available (likely not Claude Desktop)');
219
+ }
220
+ }
221
+ // ── Error Handling ────────────────────────────────────────────────
222
+ setupErrorHandling() {
223
+ this.server.onerror = (error) => {
224
+ console.error("[Lemma MCP Error]", error);
225
+ };
226
+ process.on("SIGINT", async () => {
227
+ await this.server.close();
228
+ process.exit(0);
229
+ });
1257
230
  }
1258
231
  }
1259
232
  const server = new LemmaMcpServer();