antigravity-plugin-context-mode 0.0.0-stage → 1.0.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.
package/lib/tools.js ADDED
@@ -0,0 +1,339 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import http from "node:http";
4
+ import https from "node:https";
5
+ import { executeCode, runProcess, OUTPUT_CAP } from "./executor.js";
6
+ import { SNIPPET_MAX_BYTES } from "./store.js";
7
+
8
+ const EXEC_PREVIEW_BYTES = 4096;
9
+
10
+ /** Fetch URL text content */
11
+ function fetchUrlText(urlStr, timeoutMs = 15000) {
12
+ return new Promise((resolve, reject) => {
13
+ try {
14
+ const parsed = new URL(urlStr);
15
+ const client = parsed.protocol === "https:" ? https : http;
16
+ const req = client.get(parsed, { timeout: timeoutMs }, (res) => {
17
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
18
+ return fetchUrlText(res.headers.location, timeoutMs).then(resolve, reject);
19
+ }
20
+ if (res.statusCode && res.statusCode >= 400) {
21
+ return reject(new Error(`HTTP ${res.statusCode} ${res.statusMessage}`));
22
+ }
23
+ const chunks = [];
24
+ let total = 0;
25
+ res.on("data", (c) => {
26
+ total += c.byteLength;
27
+ if (total <= 10 * 1024 * 1024) {
28
+ chunks.push(c);
29
+ }
30
+ });
31
+ res.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
32
+ });
33
+ req.on("error", reject);
34
+ req.on("timeout", () => {
35
+ req.destroy();
36
+ reject(new Error("Request timed out"));
37
+ });
38
+ } catch (e) {
39
+ reject(e);
40
+ }
41
+ });
42
+ }
43
+
44
+ /** Render helper for ASCII bar chart */
45
+ function renderBar(ratio, width = 28) {
46
+ const filled = Math.min(width, Math.max(0, Math.round(ratio * width)));
47
+ const empty = width - filled;
48
+ return `[${"=".repeat(filled)}${" ".repeat(empty)}]`;
49
+ }
50
+
51
+ /** Format size nicely */
52
+ export function formatBytes(bytes) {
53
+ if (bytes < 1024) return `${bytes} B`;
54
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
55
+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
56
+ }
57
+
58
+ /** Build tools registry bound to store and active context */
59
+ export function createTools({ store, getCwd = () => process.cwd(), getSessionId = () => "default" }) {
60
+ return {
61
+ // 1. ctx_execute
62
+ async ctx_execute({ language = "shell", code = "", file = "", args = [], intent = "" } = {}) {
63
+ const startTime = Date.now();
64
+ const cwd = getCwd();
65
+ const sessionId = getSessionId();
66
+
67
+ const result = await executeCode({
68
+ language,
69
+ code,
70
+ file,
71
+ args,
72
+ cwd
73
+ });
74
+
75
+ const elapsedMs = Date.now() - startTime;
76
+ const fullOutput = (result.stdout ? result.stdout : "") + (result.stderr ? "\n" + result.stderr : "");
77
+ const fullBytes = Buffer.byteLength(fullOutput, "utf8");
78
+
79
+ let sourceId = null;
80
+ if (fullBytes > 0) {
81
+ const indexed = store.indexContent({
82
+ sessionId,
83
+ worktree: cwd,
84
+ agent: "antigravity",
85
+ kind: "execution",
86
+ label: intent || `${language} script (${elapsedMs}ms)`,
87
+ content: fullOutput
88
+ });
89
+ sourceId = indexed.sourceId;
90
+ }
91
+
92
+ let returnedText = fullOutput;
93
+ let truncated = false;
94
+ if (fullBytes > EXEC_PREVIEW_BYTES) {
95
+ returnedText = fullOutput.slice(0, EXEC_PREVIEW_BYTES);
96
+ truncated = true;
97
+ }
98
+
99
+ const returnedBytes = Buffer.byteLength(returnedText, "utf8");
100
+
101
+ store.recordEvent({
102
+ sessionId,
103
+ worktree: cwd,
104
+ agent: "antigravity",
105
+ kind: "execution",
106
+ tool: "ctx_execute",
107
+ key: language,
108
+ path: file || null,
109
+ ok: result.ok ? 1 : 0,
110
+ exitCode: result.exitCode,
111
+ bytes: fullBytes,
112
+ body: returnedText,
113
+ sandboxBytes: fullBytes,
114
+ returnedBytes
115
+ });
116
+
117
+ let responseText = returnedText;
118
+ if (truncated) {
119
+ responseText += `\n\n... [${formatBytes(fullBytes - returnedBytes)} truncated to protect context window; full output indexed into ${sourceId}. Use ctx_search(queries: [...], sourceId: "${sourceId}") to query it]`;
120
+ }
121
+
122
+ return {
123
+ ok: result.ok,
124
+ exitCode: result.exitCode,
125
+ elapsedMs,
126
+ language,
127
+ intent: intent || null,
128
+ sourceId,
129
+ rawBytes: fullBytes,
130
+ returnedBytes,
131
+ output: responseText
132
+ };
133
+ },
134
+
135
+ // 2. ctx_batch
136
+ async ctx_batch({ commands = [], queries = [] } = {}) {
137
+ const cwd = getCwd();
138
+ const sessionId = getSessionId();
139
+ const cmdList = Array.isArray(commands) ? commands : [commands];
140
+ const outputs = [];
141
+ let totalRawBytes = 0;
142
+
143
+ for (const cmd of cmdList) {
144
+ if (!cmd) continue;
145
+ const res = await executeCode({ language: "shell", code: cmd, cwd });
146
+ const text = `=== Command: ${cmd} (exit: ${res.exitCode}) ===\n${res.stdout || ""}${res.stderr ? "\n[stderr]\n" + res.stderr : ""}\n`;
147
+ totalRawBytes += Buffer.byteLength(text, "utf8");
148
+ outputs.push(text);
149
+ }
150
+
151
+ const combined = outputs.join("\n");
152
+ const indexed = store.indexContent({
153
+ sessionId,
154
+ worktree: cwd,
155
+ agent: "antigravity",
156
+ kind: "batch",
157
+ label: `batch: ${cmdList.length} commands`,
158
+ content: combined
159
+ });
160
+
161
+ let returnedContent = "";
162
+ if (queries && queries.length > 0) {
163
+ const searchRes = store.search({
164
+ queries,
165
+ sourceId: indexed.sourceId,
166
+ sessionId,
167
+ limit: 10
168
+ });
169
+ returnedContent = searchRes.hits.map((h) => `[ord ${h.ord}] ${h.snippet}`).join("\n\n---\n\n");
170
+ } else {
171
+ returnedContent = combined.slice(0, EXEC_PREVIEW_BYTES);
172
+ if (totalRawBytes > EXEC_PREVIEW_BYTES) {
173
+ returnedContent += `\n\n... [truncated. Use ctx_search(queries: [...], sourceId: "${indexed.sourceId}") to search full batch output]`;
174
+ }
175
+ }
176
+
177
+ const returnedBytes = Buffer.byteLength(returnedContent, "utf8");
178
+ store.recordEvent({
179
+ sessionId,
180
+ worktree: cwd,
181
+ agent: "antigravity",
182
+ kind: "batch",
183
+ tool: "ctx_batch",
184
+ ok: 1,
185
+ bytes: totalRawBytes,
186
+ body: returnedContent,
187
+ sandboxBytes: totalRawBytes,
188
+ returnedBytes
189
+ });
190
+
191
+ return {
192
+ commandsRun: cmdList.length,
193
+ sourceId: indexed.sourceId,
194
+ rawBytes: totalRawBytes,
195
+ returnedBytes,
196
+ content: returnedContent
197
+ };
198
+ },
199
+
200
+ // 3. ctx_index
201
+ async ctx_index({ path: filePath = "", url = "", content = "", label = "" } = {}) {
202
+ const cwd = getCwd();
203
+ const sessionId = getSessionId();
204
+ let rawText = content || "";
205
+ let resolvedLabel = label;
206
+
207
+ if (url) {
208
+ resolvedLabel = resolvedLabel || url;
209
+ rawText = await fetchUrlText(url);
210
+ } else if (filePath) {
211
+ resolvedLabel = resolvedLabel || filePath;
212
+ const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
213
+ if (!fs.existsSync(absPath)) {
214
+ throw new Error(`File not found: ${filePath}`);
215
+ }
216
+ rawText = fs.readFileSync(absPath, "utf8");
217
+ }
218
+
219
+ if (!rawText) {
220
+ throw new Error("No content, file path, or url provided to index");
221
+ }
222
+
223
+ const indexed = store.indexContent({
224
+ sessionId,
225
+ worktree: cwd,
226
+ agent: "antigravity",
227
+ kind: url ? "web" : filePath ? "file" : "text",
228
+ label: resolvedLabel || "manual_index",
229
+ content: rawText
230
+ });
231
+
232
+ return {
233
+ sourceId: indexed.sourceId,
234
+ label: indexed.label,
235
+ bytesTotal: indexed.bytesTotal,
236
+ chunkCount: indexed.chunkCount,
237
+ message: `Indexed ${formatBytes(indexed.bytesTotal)} into ${indexed.chunkCount} chunks. Query with ctx_search.`
238
+ };
239
+ },
240
+
241
+ // 4. ctx_search
242
+ async ctx_search({ queries = [], sourceId = null, scope = "session", limit = 5, offset = 0 } = {}) {
243
+ const cwd = getCwd();
244
+ const sessionId = getSessionId();
245
+
246
+ const res = store.search({
247
+ queries,
248
+ sourceId,
249
+ sessionId,
250
+ worktree: cwd,
251
+ scope,
252
+ limit,
253
+ offset
254
+ });
255
+
256
+ return {
257
+ queries,
258
+ totalMatches: res.totalMatches,
259
+ returned: res.returned,
260
+ offset: res.offset,
261
+ hits: res.hits
262
+ };
263
+ },
264
+
265
+ // 5. ctx_resume
266
+ async ctx_resume({ seq = null } = {}) {
267
+ const sessionId = getSessionId();
268
+ if (seq !== null && seq !== undefined) {
269
+ const ev = store.getEventBySeq(seq);
270
+ if (!ev) throw new Error(`Event sequence #${seq} not found`);
271
+ return { event: ev };
272
+ }
273
+
274
+ const state = store.getResumeState(sessionId, 5);
275
+ const stats = store.getStats(sessionId);
276
+
277
+ return {
278
+ sessionId,
279
+ stats: {
280
+ calls: stats.calls,
281
+ savedBytes: formatBytes(stats.keptOutBytes),
282
+ savingsPercent: `${stats.savingsPercent}%`,
283
+ tokensSaved: stats.tokensKeptOut
284
+ },
285
+ recentSources: state.recentSources,
286
+ recentEvents: state.recentEvents
287
+ };
288
+ },
289
+
290
+ // 6. ctx_stats
291
+ async ctx_stats({ reset = false } = {}) {
292
+ const sessionId = getSessionId();
293
+ if (reset) {
294
+ store.purge({ scope: "session", sessionId });
295
+ }
296
+
297
+ const s = store.getStats(sessionId);
298
+ const report = [
299
+ "────────────────────────────────────────────────────────────────────────────────",
300
+ ` Antigravity context-mode stats [session: ${sessionId}]`,
301
+ "────────────────────────────────────────────────────────────────────────────────",
302
+ ` Total Operations: ${s.calls}`,
303
+ ` Raw Data Handled: ${formatBytes(s.totalRawBytes)}`,
304
+ ` Data Fed into LLM: ${formatBytes(s.totalReturnedBytes)}`,
305
+ ` Tokens Kept Out: ~${s.tokensKeptOut.toLocaleString()} tokens (${formatBytes(s.keptOutBytes)})`,
306
+ ` Reduction Rate: ${s.savingsPercent}% saved`,
307
+ "",
308
+ ` Without context-mode ${renderBar(1.0)} ${formatBytes(s.totalRawBytes)}`,
309
+ ` With context-mode ${renderBar(s.totalRawBytes > 0 ? s.totalReturnedBytes / s.totalRawBytes : 0)} ${formatBytes(s.totalReturnedBytes)}`,
310
+ "────────────────────────────────────────────────────────────────────────────────"
311
+ ].join("\n");
312
+
313
+ return {
314
+ stats: s,
315
+ report
316
+ };
317
+ },
318
+
319
+ // 7. ctx_doctor
320
+ async ctx_doctor() {
321
+ const doc = store.doctor();
322
+ return {
323
+ doctor: doc,
324
+ runtimes: {
325
+ node: process.version,
326
+ platform: process.platform,
327
+ arch: process.arch
328
+ }
329
+ };
330
+ },
331
+
332
+ // 8. ctx_purge
333
+ async ctx_purge({ scope = "session" } = {}) {
334
+ const sessionId = getSessionId();
335
+ const cwd = getCwd();
336
+ return store.purge({ scope, sessionId, worktree: cwd });
337
+ }
338
+ };
339
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "mcpServers": {
3
+ "context-mode": {
4
+ "command": "node",
5
+ "args": ["./server.js"]
6
+ }
7
+ }
8
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "antigravity-plugin-context-mode",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Native Antigravity plugin for context-mode: SQLite FTS5 indexing, sandboxed execution, and lifecycle hook protection against context window bloat",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Phillip Webber <github@webbsense.com>",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Domush/antigravity-plugin-context-mode.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/Domush/antigravity-plugin-context-mode/issues"
14
+ },
15
+ "homepage": "https://github.com/Domush/antigravity-plugin-context-mode#readme",
16
+ "keywords": [
17
+ "antigravity",
18
+ "antigravity-plugin",
19
+ "gemini",
20
+ "context-mode",
21
+ "context-window",
22
+ "fts5",
23
+ "bm25",
24
+ "rrf",
25
+ "mcp",
26
+ "model-context-protocol",
27
+ "lifecycle-hooks"
28
+ ],
29
+ "engines": {
30
+ "node": ">=22.0.0"
31
+ },
32
+ "scripts": {
33
+ "start": "node server.js",
34
+ "test": "node --test tests/test_store.js tests/test_executor.js tests/test_tools.js tests/test_hooks.js tests/test_mcp.js"
35
+ },
36
+ "bin": {
37
+ "antigravity-context-mode": "server.js"
38
+ },
39
+ "main": "./server.js",
40
+ "files": [
41
+ "server.js",
42
+ "plugin.json",
43
+ "hooks.json",
44
+ "mcp_config.json",
45
+ "lib",
46
+ "hooks",
47
+ "skills",
48
+ "rules",
49
+ "assets",
50
+ "README.md",
51
+ "LICENSE",
52
+ "CHANGELOG.md"
53
+ ],
54
+ "publishConfig": {
55
+ "access": "public"
56
+ }
57
+ }
package/plugin.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "antigravity-plugin-context-mode",
3
+ "displayName": "Context Mode",
4
+ "description": "Context window protection for Antigravity: local SQLite FTS5 search, sandboxed execution, and lifecycle hook gating against token bloat.",
5
+ "version": "1.0.0",
6
+ "author": "Phillip Webber <github@webbsense.com>",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/Domush/antigravity-plugin-context-mode.git"
10
+ },
11
+ "homepage": "https://github.com/Domush/antigravity-plugin-context-mode#readme",
12
+ "logo": "assets/icon.svg",
13
+ "suggestedPrompts": [
14
+ "Search indexed logs for error and warning patterns",
15
+ "Run analytical script in the context-mode sandbox",
16
+ "Show context-mode token savings and database stats"
17
+ ]
18
+ }
@@ -0,0 +1,8 @@
1
+ # Context Mode Behavioral Standards
2
+
3
+ When `antigravity-plugin-context-mode` is active, agents MUST adhere to context budgeting laws:
4
+
5
+ 1. **Zero Raw Log Dumps**: Never run unbounded log commands (`cat`, `Get-Content`, `type`) or read files exceeding 400 lines without pagination or line ranges.
6
+ 2. **Thinking in Code**: When analyzing large files (>32 KB), parse and filter the data inside a `ctx_execute` script (Node.js, Python, or PowerShell) instead of bringing the raw file content into context.
7
+ 3. **FTS5 Search Over Brute Force**: Index reference documents or massive outputs with `ctx_index` and query them with `ctx_search` using precise BM25/Trigram keywords.
8
+ 4. **Token Verification**: Verify token savings and database health using `ctx_stats` and `ctx_doctor`.
package/server.js ADDED
@@ -0,0 +1,262 @@
1
+ #!/usr/bin/env node
2
+ import readline from "node:readline";
3
+ import { ContextModeStore } from "./lib/store.js";
4
+ import { createTools } from "./lib/tools.js";
5
+
6
+ const store = new ContextModeStore();
7
+ let currentCwd = process.cwd();
8
+ let currentSessionId = "default";
9
+
10
+ const tools = createTools({
11
+ store,
12
+ getCwd: () => currentCwd,
13
+ getSessionId: () => currentSessionId
14
+ });
15
+
16
+ const TOOL_DEFINITIONS = [
17
+ {
18
+ name: "ctx_execute",
19
+ description:
20
+ "Execute JavaScript, Python, PowerShell, or Shell code in a local sandbox to process large logs, filter data, or compute results without dumping raw output into the context window.",
21
+ inputSchema: {
22
+ type: "object",
23
+ properties: {
24
+ language: {
25
+ type: "string",
26
+ enum: ["javascript", "nodejs", "python", "shell", "powershell", "cmd"],
27
+ description: "Runtime language"
28
+ },
29
+ code: { type: "string", description: "Source code snippet to execute" },
30
+ file: { type: "string", description: "Optional script file path to execute" },
31
+ args: { type: "array", items: { type: "string" }, description: "Optional command-line arguments" },
32
+ intent: { type: "string", description: "One-line explanation of what this script analyzes" }
33
+ }
34
+ }
35
+ },
36
+ {
37
+ name: "ctx_batch",
38
+ description:
39
+ "Execute multiple shell commands in batch, indexing all outputs and returning only matching search snippets to preserve tokens.",
40
+ inputSchema: {
41
+ type: "object",
42
+ properties: {
43
+ commands: { type: "array", items: { type: "string" }, description: "List of shell commands to execute" },
44
+ queries: {
45
+ type: "array",
46
+ items: { type: "string" },
47
+ description: "Search queries to filter and extract from the combined output"
48
+ }
49
+ },
50
+ required: ["commands"]
51
+ }
52
+ },
53
+ {
54
+ name: "ctx_index",
55
+ description: "Index a file, URL, or raw text into SQLite FTS5 for fast BM25/trigram searching.",
56
+ inputSchema: {
57
+ type: "object",
58
+ properties: {
59
+ path: { type: "string", description: "Path to local file to index" },
60
+ url: { type: "string", description: "HTTP/HTTPS URL to fetch and index" },
61
+ content: { type: "string", description: "Raw string content to index" },
62
+ label: { type: "string", description: "Descriptive label for this source" }
63
+ }
64
+ }
65
+ },
66
+ {
67
+ name: "ctx_search",
68
+ description:
69
+ "Search the local SQLite FTS5 database across indexed logs, tool outputs, and documentation using Reciprocal Rank Fusion (Porter BM25 + Trigram).",
70
+ inputSchema: {
71
+ type: "object",
72
+ properties: {
73
+ queries: { type: "array", items: { type: "string" }, description: "Search queries or tokens to match" },
74
+ sourceId: { type: "string", description: "Optional sourceId to restrict search" },
75
+ scope: {
76
+ type: "string",
77
+ enum: ["session", "worktree", "all"],
78
+ description: "Search scope (default: session)"
79
+ },
80
+ limit: { type: "integer", description: "Max number of snippets to return (default 5)" },
81
+ offset: { type: "integer", description: "Offset for pagination" }
82
+ },
83
+ required: ["queries"]
84
+ }
85
+ },
86
+ {
87
+ name: "ctx_resume",
88
+ description: "Retrieve current session state, active sources, indexed items, and compaction pointers.",
89
+ inputSchema: {
90
+ type: "object",
91
+ properties: {
92
+ seq: { type: "integer", description: "Optional journal event sequence to retrieve" }
93
+ }
94
+ }
95
+ },
96
+ {
97
+ name: "ctx_stats",
98
+ description:
99
+ "Show context window savings report (raw bytes vs tokens returned to LLM, savings percentage, and database metrics).",
100
+ inputSchema: {
101
+ type: "object",
102
+ properties: {
103
+ reset: { type: "boolean", description: "Reset session statistics" }
104
+ }
105
+ }
106
+ },
107
+ {
108
+ name: "ctx_doctor",
109
+ description: "Check database health, FTS5 availability, SQLite schema, and active sandbox runtimes.",
110
+ inputSchema: {
111
+ type: "object",
112
+ properties: {}
113
+ }
114
+ },
115
+ {
116
+ name: "ctx_purge",
117
+ description: "Purge indexed sources and journal records for this session, worktree, or entire database.",
118
+ inputSchema: {
119
+ type: "object",
120
+ properties: {
121
+ scope: { type: "string", enum: ["session", "worktree", "all"], description: "Purge scope" }
122
+ }
123
+ }
124
+ }
125
+ ];
126
+
127
+ function sendJsonRpc(obj) {
128
+ process.stdout.write(JSON.stringify(obj) + "\n");
129
+ }
130
+
131
+ function sendResponse(id, result) {
132
+ sendJsonRpc({
133
+ jsonrpc: "2.0",
134
+ id,
135
+ result
136
+ });
137
+ }
138
+
139
+ function sendError(id, code, message, data) {
140
+ sendJsonRpc({
141
+ jsonrpc: "2.0",
142
+ id,
143
+ error: {
144
+ code,
145
+ message,
146
+ ...(data !== undefined ? { data } : {})
147
+ }
148
+ });
149
+ }
150
+
151
+ const rl = readline.createInterface({
152
+ input: process.stdin,
153
+ output: process.stdout,
154
+ terminal: false
155
+ });
156
+
157
+ rl.on("line", async (line) => {
158
+ const trimmed = line.trim();
159
+ if (!trimmed) return;
160
+
161
+ let msg;
162
+ try {
163
+ msg = JSON.parse(trimmed);
164
+ } catch (err) {
165
+ sendError(null, -32700, "Parse error", String(err));
166
+ return;
167
+ }
168
+
169
+ const { id, method, params } = msg;
170
+
171
+ // Notifications (no id)
172
+ if (id === undefined || id === null) {
173
+ if (method === "notifications/initialized") {
174
+ // client initialized confirmation
175
+ }
176
+ return;
177
+ }
178
+
179
+ // Handle requests
180
+ try {
181
+ switch (method) {
182
+ case "initialize": {
183
+ if (params?.rootPath) currentCwd = params.rootPath;
184
+ if (params?.sessionId) currentSessionId = params.sessionId;
185
+ sendResponse(id, {
186
+ protocolVersion: "2024-11-05",
187
+ capabilities: {
188
+ tools: {}
189
+ },
190
+ serverInfo: {
191
+ name: "antigravity-plugin-context-mode",
192
+ version: "1.0.0"
193
+ }
194
+ });
195
+ break;
196
+ }
197
+
198
+ case "ping": {
199
+ sendResponse(id, {});
200
+ break;
201
+ }
202
+
203
+ case "tools/list": {
204
+ sendResponse(id, {
205
+ tools: TOOL_DEFINITIONS
206
+ });
207
+ break;
208
+ }
209
+
210
+ case "tools/call": {
211
+ const toolName = params?.name;
212
+ const toolArgs = params?.arguments || {};
213
+
214
+ if (!tools[toolName]) {
215
+ sendError(id, -32601, `Unknown tool: ${toolName}`);
216
+ break;
217
+ }
218
+
219
+ try {
220
+ const result = await tools[toolName](toolArgs);
221
+ sendResponse(id, {
222
+ content: [
223
+ {
224
+ type: "text",
225
+ text: typeof result === "string" ? result : JSON.stringify(result, null, 2)
226
+ }
227
+ ],
228
+ isError: false
229
+ });
230
+ } catch (toolErr) {
231
+ sendResponse(id, {
232
+ content: [
233
+ {
234
+ type: "text",
235
+ text: `Tool error (${toolName}): ${toolErr.message || String(toolErr)}`
236
+ }
237
+ ],
238
+ isError: true
239
+ });
240
+ }
241
+ break;
242
+ }
243
+
244
+ default: {
245
+ sendError(id, -32601, `Method not found: ${method}`);
246
+ break;
247
+ }
248
+ }
249
+ } catch (handlerErr) {
250
+ sendError(id, -32603, "Internal server error", String(handlerErr));
251
+ }
252
+ });
253
+
254
+ process.on("SIGINT", () => {
255
+ store.close();
256
+ process.exit(0);
257
+ });
258
+
259
+ process.on("SIGTERM", () => {
260
+ store.close();
261
+ process.exit(0);
262
+ });