heurchain 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/AGENT_CONFIG.json +361 -0
- package/README.md +388 -0
- package/package.json +37 -0
- package/server.js +601 -0
package/server.js
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
const express = require("express");
|
|
2
|
+
const { createClient } = require("redis");
|
|
3
|
+
const cors = require("cors");
|
|
4
|
+
const fs = require("fs").promises;
|
|
5
|
+
const path = require("path");
|
|
6
|
+
const { McpServer } = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
7
|
+
const { SSEServerTransport } = require("@modelcontextprotocol/sdk/server/sse.js");
|
|
8
|
+
const { z } = require("zod");
|
|
9
|
+
|
|
10
|
+
const app = express();
|
|
11
|
+
app.use(cors());
|
|
12
|
+
|
|
13
|
+
const redis = createClient({ url: process.env.REDIS_URL || "redis://localhost:6379" });
|
|
14
|
+
redis.on("error", (err) => console.error("Redis error:", err));
|
|
15
|
+
|
|
16
|
+
const OBSIDIAN_VAULT_PATH = process.env.OBSIDIAN_VAULT_PATH || "/opt/obsidian-vault";
|
|
17
|
+
const HEURCHAIN_URL = process.env.HEURCHAIN_URL || "http://host.docker.internal:3012";
|
|
18
|
+
|
|
19
|
+
(async () => {
|
|
20
|
+
await redis.connect();
|
|
21
|
+
const port = parseInt(process.env.MCP_PORT, 10) || 3010;
|
|
22
|
+
app.listen(port, () => console.log("MCP server listening on port " + port));
|
|
23
|
+
})();
|
|
24
|
+
|
|
25
|
+
// ---------------------------------------------------------------------------
|
|
26
|
+
// Obsidian Vault Helpers
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
function keyToObsidianPath(key) {
|
|
30
|
+
const relativePath = key.replace(/:/g, "/") + ".md";
|
|
31
|
+
return path.join(OBSIDIAN_VAULT_PATH, relativePath);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function saveToObsidian(key, content, metadata) {
|
|
35
|
+
const filePath = keyToObsidianPath(key);
|
|
36
|
+
await fs.mkdir(path.dirname(filePath), { recursive: true });
|
|
37
|
+
let output = content;
|
|
38
|
+
if (metadata && Object.keys(metadata).length > 0) {
|
|
39
|
+
const frontmatter = ["---"];
|
|
40
|
+
for (const [k, v] of Object.entries(metadata)) {
|
|
41
|
+
frontmatter.push(`${k}: ${Array.isArray(v) ? `[${v.join(", ")}]` : v}`);
|
|
42
|
+
}
|
|
43
|
+
frontmatter.push("---", "");
|
|
44
|
+
output = frontmatter.join("\n") + content;
|
|
45
|
+
}
|
|
46
|
+
await fs.writeFile(filePath, output, "utf-8");
|
|
47
|
+
return filePath;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function readFromObsidian(key) {
|
|
51
|
+
const filePath = keyToObsidianPath(key);
|
|
52
|
+
try {
|
|
53
|
+
return await fs.readFile(filePath, "utf-8");
|
|
54
|
+
} catch (e) {
|
|
55
|
+
if (e.code === "ENOENT") return null;
|
|
56
|
+
throw e;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function deleteFromObsidian(key) {
|
|
61
|
+
const filePath = keyToObsidianPath(key);
|
|
62
|
+
try {
|
|
63
|
+
await fs.unlink(filePath);
|
|
64
|
+
return true;
|
|
65
|
+
} catch (e) {
|
|
66
|
+
if (e.code === "ENOENT") return false;
|
|
67
|
+
throw e;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function searchObsidian(query) {
|
|
72
|
+
const results = [];
|
|
73
|
+
async function walk(dir) {
|
|
74
|
+
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
75
|
+
for (const entry of entries) {
|
|
76
|
+
const fullPath = path.join(dir, entry.name);
|
|
77
|
+
if (entry.isDirectory()) {
|
|
78
|
+
await walk(fullPath);
|
|
79
|
+
} else if (entry.name.endsWith(".md")) {
|
|
80
|
+
const content = await fs.readFile(fullPath, "utf-8");
|
|
81
|
+
if (content.toLowerCase().includes(query.toLowerCase())) {
|
|
82
|
+
const relative = path.relative(OBSIDIAN_VAULT_PATH, fullPath);
|
|
83
|
+
const key = relative.replace(/\//g, ":").replace(/\.md$/, "");
|
|
84
|
+
results.push({ key, content, path: relative });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
await walk(OBSIDIAN_VAULT_PATH);
|
|
91
|
+
} catch (e) {
|
|
92
|
+
if (e.code !== "ENOENT") throw e;
|
|
93
|
+
}
|
|
94
|
+
return results;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function listObsidian(prefix) {
|
|
98
|
+
const results = [];
|
|
99
|
+
async function walk(dir) {
|
|
100
|
+
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
101
|
+
for (const entry of entries) {
|
|
102
|
+
const fullPath = path.join(dir, entry.name);
|
|
103
|
+
if (entry.isDirectory()) {
|
|
104
|
+
await walk(fullPath);
|
|
105
|
+
} else if (entry.name.endsWith(".md")) {
|
|
106
|
+
const relative = path.relative(OBSIDIAN_VAULT_PATH, fullPath);
|
|
107
|
+
const key = relative.replace(/\//g, ":").replace(/\.md$/, "");
|
|
108
|
+
if (!prefix || key.startsWith(prefix)) {
|
|
109
|
+
results.push({ key, path: relative });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
await walk(OBSIDIAN_VAULT_PATH);
|
|
116
|
+
} catch (e) {
|
|
117
|
+
if (e.code !== "ENOENT") throw e;
|
|
118
|
+
}
|
|
119
|
+
return results;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ---------------------------------------------------------------------------
|
|
123
|
+
// MCP Server Factory
|
|
124
|
+
// ---------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
function createMcpServerInstance() {
|
|
127
|
+
const server = new McpServer({
|
|
128
|
+
name: "heurchain-mcp",
|
|
129
|
+
version: "1.1.0"
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
// --- Cache Tools ---
|
|
133
|
+
|
|
134
|
+
server.tool("cache_set", "Store a key-value pair in Redis cache with optional TTL", {
|
|
135
|
+
key: z.string().describe("Cache key"),
|
|
136
|
+
value: z.string().describe("Value to cache"),
|
|
137
|
+
ttl: z.number().optional().describe("Time-to-live in seconds")
|
|
138
|
+
}, async ({ key, value, ttl }) => {
|
|
139
|
+
if (ttl) await redis.setEx(key, ttl, value);
|
|
140
|
+
else await redis.set(key, value);
|
|
141
|
+
return { content: [{ type: "text", text: JSON.stringify({ cached: true, key }) }] };
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
server.tool("cache_get", "Retrieve a cached value from Redis by key", {
|
|
145
|
+
key: z.string().describe("Cache key to retrieve")
|
|
146
|
+
}, async ({ key }) => {
|
|
147
|
+
const val = await redis.get(key);
|
|
148
|
+
if (val) return { content: [{ type: "text", text: val }] };
|
|
149
|
+
return { content: [{ type: "text", text: JSON.stringify({ hit: false }) }] };
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
server.tool("cache_delete", "Delete a cached key from Redis", {
|
|
153
|
+
key: z.string().describe("Cache key to delete")
|
|
154
|
+
}, async ({ key }) => {
|
|
155
|
+
const deleted = await redis.del(key);
|
|
156
|
+
return { content: [{ type: "text", text: JSON.stringify({ deleted: deleted > 0, key }) }] };
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
server.tool("redis_stats", "Get Redis server statistics and memory info", {}, async () => {
|
|
160
|
+
const info = await redis.info("stats");
|
|
161
|
+
return { content: [{ type: "text", text: info }] };
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
server.tool("health_check", "Check the health of the MCP server, Redis, and Obsidian vault", {}, async () => {
|
|
165
|
+
const redisOk = redis.isReady;
|
|
166
|
+
let obsidianOk = false;
|
|
167
|
+
try {
|
|
168
|
+
await fs.access(OBSIDIAN_VAULT_PATH);
|
|
169
|
+
obsidianOk = true;
|
|
170
|
+
} catch {}
|
|
171
|
+
return {
|
|
172
|
+
content: [{
|
|
173
|
+
type: "text",
|
|
174
|
+
text: JSON.stringify({
|
|
175
|
+
status: (redisOk && obsidianOk) ? "healthy" : "degraded",
|
|
176
|
+
redis: redisOk,
|
|
177
|
+
obsidian: obsidianOk,
|
|
178
|
+
vault_path: OBSIDIAN_VAULT_PATH,
|
|
179
|
+
uptime: process.uptime()
|
|
180
|
+
})
|
|
181
|
+
}]
|
|
182
|
+
};
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
// --- Obsidian Vault Tools (Long-Term MD Storage) ---
|
|
186
|
+
|
|
187
|
+
server.tool("obsidian_write_note", "Write or overwrite a markdown note in the Obsidian vault for long-term storage", {
|
|
188
|
+
key: z.string().describe("Note key (colons become folder separators, e.g., doc:proxmox:setup)"),
|
|
189
|
+
content: z.string().describe("Markdown body"),
|
|
190
|
+
metadata: z.record(z.string()).optional().describe("Optional frontmatter metadata (key-value pairs)")
|
|
191
|
+
}, async ({ key, content, metadata }) => {
|
|
192
|
+
try {
|
|
193
|
+
const filePath = await saveToObsidian(key, content, metadata);
|
|
194
|
+
return { content: [{ type: "text", text: JSON.stringify({ stored: true, key, path: filePath, tier: "reference" }) }] };
|
|
195
|
+
} catch (e) {
|
|
196
|
+
return { content: [{ type: "text", text: JSON.stringify({ stored: false, key, error: e.message }) }] };
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
server.tool("obsidian_read_note", "Read a markdown note from the Obsidian vault by key", {
|
|
201
|
+
key: z.string().describe("Note key")
|
|
202
|
+
}, async ({ key }) => {
|
|
203
|
+
try {
|
|
204
|
+
const content = await readFromObsidian(key);
|
|
205
|
+
if (content === null) {
|
|
206
|
+
return { content: [{ type: "text", text: JSON.stringify({ found: false, key }) }] };
|
|
207
|
+
}
|
|
208
|
+
return { content: [{ type: "text", text: JSON.stringify({ found: true, key, content }) }] };
|
|
209
|
+
} catch (e) {
|
|
210
|
+
return { content: [{ type: "text", text: JSON.stringify({ found: false, key, error: e.message }) }] };
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
server.tool("obsidian_delete_note", "Delete a markdown note from the Obsidian vault by key", {
|
|
215
|
+
key: z.string().describe("Note key to delete")
|
|
216
|
+
}, async ({ key }) => {
|
|
217
|
+
try {
|
|
218
|
+
const deleted = await deleteFromObsidian(key);
|
|
219
|
+
return { content: [{ type: "text", text: JSON.stringify({ deleted, key }) }] };
|
|
220
|
+
} catch (e) {
|
|
221
|
+
return { content: [{ type: "text", text: JSON.stringify({ deleted: false, key, error: e.message }) }] };
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
server.tool("obsidian_search_notes", "Search all markdown notes in the Obsidian vault by keyword", {
|
|
226
|
+
query: z.string().describe("Search term"),
|
|
227
|
+
limit: z.number().optional().describe("Max results to return").default(10)
|
|
228
|
+
}, async ({ query, limit }) => {
|
|
229
|
+
try {
|
|
230
|
+
const results = await searchObsidian(query);
|
|
231
|
+
const sliced = results.slice(0, limit);
|
|
232
|
+
return { content: [{ type: "text", text: JSON.stringify({ count: results.length, results: sliced.map(r => ({ key: r.key, preview: r.content.substring(0, 200) })) }) }] };
|
|
233
|
+
} catch (e) {
|
|
234
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: e.message }) }] };
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
server.tool("obsidian_list_notes", "List all markdown notes in the Obsidian vault, optionally filtered by prefix", {
|
|
239
|
+
prefix: z.string().optional().describe("Key prefix filter, e.g., doc:proxmox:")
|
|
240
|
+
}, async ({ prefix }) => {
|
|
241
|
+
try {
|
|
242
|
+
const results = await listObsidian(prefix);
|
|
243
|
+
return { content: [{ type: "text", text: JSON.stringify({ count: results.length, notes: results }) }] };
|
|
244
|
+
} catch (e) {
|
|
245
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: e.message }) }] };
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
// --- HeurChain BM25 Search ---
|
|
250
|
+
|
|
251
|
+
server.tool("heurchain_search", "Search the full knowledge base using HeurChain's BM25 ranked index (preferred over obsidian_search_notes — covers all 460+ Redis keys with relevance scoring)", {
|
|
252
|
+
query: z.string().describe("Search query"),
|
|
253
|
+
limit: z.number().optional().describe("Max results (default 10, max 50)").default(10),
|
|
254
|
+
tier: z.string().optional().describe("'all' | 'longterm' | 'working' (default: all)").default("all")
|
|
255
|
+
}, async ({ query, limit, tier }) => {
|
|
256
|
+
try {
|
|
257
|
+
const url = `${HEURCHAIN_URL}/search?q=${encodeURIComponent(query)}&limit=${limit}&tier=${tier}`;
|
|
258
|
+
const response = await fetch(url);
|
|
259
|
+
if (!response.ok) {
|
|
260
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: `HeurChain returned HTTP ${response.status}` }) }] };
|
|
261
|
+
}
|
|
262
|
+
const results = await response.json();
|
|
263
|
+
return { content: [{ type: "text", text: JSON.stringify({ count: results.length, results: results.map(r => ({ key: r.key, score: r.score, tier: r.tier, preview: (r.content || "").substring(0, 300), updated_at: r.updated_at })) }) }] };
|
|
264
|
+
} catch (e) {
|
|
265
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: e.message }) }] };
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
// --- Prometheus Monitoring Tools ---
|
|
270
|
+
|
|
271
|
+
server.tool("prometheus_get_targets", "Returns the status of all targets Prometheus is currently scraping", {}, async () => {
|
|
272
|
+
try {
|
|
273
|
+
const response = await fetch("http://prometheus:9090/api/v1/targets");
|
|
274
|
+
if (!response.ok) return { content: [{ type: "text", text: JSON.stringify({ error: `HTTP ${response.status}` }) }] };
|
|
275
|
+
const data = await response.json();
|
|
276
|
+
const targets = data.data.activeTargets.map(t => ({
|
|
277
|
+
job: t.labels.job,
|
|
278
|
+
instance: t.labels.instance,
|
|
279
|
+
health: t.health,
|
|
280
|
+
last_scrape: t.lastScrape
|
|
281
|
+
}));
|
|
282
|
+
return { content: [{ type: "text", text: JSON.stringify({ targets }) }] };
|
|
283
|
+
} catch (e) {
|
|
284
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: e.message }) }] };
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
server.tool("prometheus_get_alerts", "Returns any currently firing or pending Prometheus alerts", {}, async () => {
|
|
289
|
+
try {
|
|
290
|
+
const response = await fetch("http://prometheus:9090/api/v1/alerts");
|
|
291
|
+
if (!response.ok) return { content: [{ type: "text", text: JSON.stringify({ error: `HTTP ${response.status}` }) }] };
|
|
292
|
+
const data = await response.json();
|
|
293
|
+
return { content: [{ type: "text", text: JSON.stringify({ alerts: data.data.alerts }) }] };
|
|
294
|
+
} catch (e) {
|
|
295
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: e.message }) }] };
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
server.tool("prometheus_query", "Execute a PromQL query against Prometheus", {
|
|
300
|
+
promql_query: z.string().describe("The PromQL query string to execute")
|
|
301
|
+
}, async ({ promql_query }) => {
|
|
302
|
+
try {
|
|
303
|
+
const response = await fetch(`http://prometheus:9090/api/v1/query?query=${encodeURIComponent(promql_query)}`);
|
|
304
|
+
if (!response.ok) return { content: [{ type: "text", text: JSON.stringify({ error: `HTTP ${response.status}` }) }] };
|
|
305
|
+
const data = await response.json();
|
|
306
|
+
return { content: [{ type: "text", text: JSON.stringify(data.data) }] };
|
|
307
|
+
} catch (e) {
|
|
308
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: e.message }) }] };
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
// --- Grafana Monitoring Tools ---
|
|
313
|
+
|
|
314
|
+
const grafanaAuth = "Basic " + Buffer.from(`${process.env.GRAFANA_USER || "admin"}:${process.env.GRAFANA_PASSWORD || "admin"}`).toString("base64");
|
|
315
|
+
|
|
316
|
+
server.tool("grafana_get_health", "Check the health status of the Grafana server", {}, async () => {
|
|
317
|
+
try {
|
|
318
|
+
const response = await fetch("http://grafana:3000/api/health", {
|
|
319
|
+
headers: { "Authorization": grafanaAuth }
|
|
320
|
+
});
|
|
321
|
+
if (!response.ok) return { content: [{ type: "text", text: JSON.stringify({ error: `HTTP ${response.status}` }) }] };
|
|
322
|
+
const data = await response.json();
|
|
323
|
+
return { content: [{ type: "text", text: JSON.stringify(data) }] };
|
|
324
|
+
} catch (e) {
|
|
325
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: e.message }) }] };
|
|
326
|
+
}
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
server.tool("grafana_list_dashboards", "List all available dashboards in Grafana", {}, async () => {
|
|
330
|
+
try {
|
|
331
|
+
const response = await fetch("http://grafana:3000/api/search?type=dash-db", {
|
|
332
|
+
headers: { "Authorization": grafanaAuth }
|
|
333
|
+
});
|
|
334
|
+
if (!response.ok) return { content: [{ type: "text", text: JSON.stringify({ error: `HTTP ${response.status}` }) }] };
|
|
335
|
+
const dashboards = await response.json();
|
|
336
|
+
return { content: [{ type: "text", text: JSON.stringify({ dashboards: dashboards.map(d => ({ title: d.title, url: d.url })) }) }] };
|
|
337
|
+
} catch (e) {
|
|
338
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: e.message }) }] };
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
// --- Proxmox Documentation Tools (Redis-backed) ---
|
|
343
|
+
|
|
344
|
+
async function searchDocs(keyPattern, contentFilter) {
|
|
345
|
+
const keys = [];
|
|
346
|
+
for await (const key of redis.scanIterator({ MATCH: keyPattern, COUNT: 100 })) {
|
|
347
|
+
keys.push(key);
|
|
348
|
+
}
|
|
349
|
+
if (keys.length === 0) return [];
|
|
350
|
+
const results = [];
|
|
351
|
+
for (const key of keys) {
|
|
352
|
+
const val = await redis.get(key);
|
|
353
|
+
if (val && (!contentFilter || val.toLowerCase().includes(contentFilter.toLowerCase()))) {
|
|
354
|
+
results.push({ key, content: val });
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
return results;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
server.tool("proxmox_get_cluster_status", "Retrieve the Proxmox cluster status document from the knowledge base", {}, async () => {
|
|
361
|
+
const results = await searchDocs("doc:proxmox:cluster-status*", null);
|
|
362
|
+
if (results.length === 0) {
|
|
363
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: "No cluster status document found. Store one with key 'doc:proxmox:cluster-status' using cache_set." }) }] };
|
|
364
|
+
}
|
|
365
|
+
return { content: [{ type: "text", text: results[0].content }] };
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
server.tool("proxmox_list_nodes", "List all Proxmox nodes documented in the knowledge base", {}, async () => {
|
|
369
|
+
const results = await searchDocs("doc:proxmox:node:*", null);
|
|
370
|
+
if (results.length === 0) {
|
|
371
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: "No node documents found. Store them with keys like 'doc:proxmox:node:pver430' using cache_set." }) }] };
|
|
372
|
+
}
|
|
373
|
+
return { content: [{ type: "text", text: JSON.stringify({ nodes: results.map(r => ({ key: r.key, title: r.key.split(":").pop() })) }) }] };
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
server.tool("proxmox_find_vm", "Search for a specific VM or container by ID or name in the knowledge base", {
|
|
377
|
+
vm_id_or_name: z.string().describe("VM ID or name to search for")
|
|
378
|
+
}, async ({ vm_id_or_name }) => {
|
|
379
|
+
let results = await searchDocs("doc:proxmox:vm:*", vm_id_or_name);
|
|
380
|
+
if (results.length === 0) results = await searchDocs("doc:proxmox:ct:*", vm_id_or_name);
|
|
381
|
+
if (results.length === 0) results = await searchDocs("doc:proxmox:*", vm_id_or_name);
|
|
382
|
+
if (results.length === 0) {
|
|
383
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: `No VM or CT found matching "${vm_id_or_name}".` }) }] };
|
|
384
|
+
}
|
|
385
|
+
return { content: [{ type: "text", text: results[0].content }] };
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
// --- Ceph Documentation Tools (Redis-backed) ---
|
|
389
|
+
|
|
390
|
+
server.tool("ceph_get_health_status", "Retrieve the latest Ceph cluster health status from the knowledge base", {}, async () => {
|
|
391
|
+
const results = await searchDocs("doc:ceph:cluster-status*", null);
|
|
392
|
+
if (results.length === 0) {
|
|
393
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: "No Ceph status document found. Store one with key 'doc:ceph:cluster-status' using cache_set." }) }] };
|
|
394
|
+
}
|
|
395
|
+
return { content: [{ type: "text", text: results[0].content }] };
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
server.tool("ceph_list_osd_notes", "List all Ceph OSD documentation notes from the knowledge base", {}, async () => {
|
|
399
|
+
const results = await searchDocs("doc:ceph:osd:*", null);
|
|
400
|
+
if (results.length === 0) {
|
|
401
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: "No OSD documents found. Store them with keys like 'doc:ceph:osd:0' using cache_set." }) }] };
|
|
402
|
+
}
|
|
403
|
+
return { content: [{ type: "text", text: JSON.stringify({ osd_notes: results.map(r => r.key) }) }] };
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
// --- Network Documentation Tools (Redis-backed) ---
|
|
407
|
+
|
|
408
|
+
server.tool("network_search_docs", "Search across network and infrastructure documentation in the knowledge base", {
|
|
409
|
+
search_query: z.string().describe("Search query to find relevant documentation")
|
|
410
|
+
}, async ({ search_query }) => {
|
|
411
|
+
const results = await searchDocs("doc:network:*", search_query);
|
|
412
|
+
const infraResults = await searchDocs("doc:infrastructure:*", search_query);
|
|
413
|
+
const all = [...results, ...infraResults];
|
|
414
|
+
if (all.length === 0) {
|
|
415
|
+
return { content: [{ type: "text", text: JSON.stringify({ status: "No relevant documents found." }) }] };
|
|
416
|
+
}
|
|
417
|
+
return { content: [{ type: "text", text: JSON.stringify({ results: all.slice(0, 5).map(r => ({ key: r.key, preview: r.content.substring(0, 200) })) }) }] };
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
server.tool("network_get_runbook", "Retrieve a specific network runbook by topic from the knowledge base", {
|
|
421
|
+
topic: z.string().describe("Runbook topic to search for")
|
|
422
|
+
}, async ({ topic }) => {
|
|
423
|
+
const results = await searchDocs("doc:runbook:*", topic);
|
|
424
|
+
if (results.length === 0) {
|
|
425
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: `No runbook found for topic: "${topic}". Store runbooks with keys like 'doc:runbook:topic-name' using cache_set.` }) }] };
|
|
426
|
+
}
|
|
427
|
+
return { content: [{ type: "text", text: results[0].content }] };
|
|
428
|
+
});
|
|
429
|
+
|
|
430
|
+
// --- User Context Tools (Redis-backed) ---
|
|
431
|
+
|
|
432
|
+
const USER_HISTORY_TTL = 90 * 24 * 60 * 60; // 90 days
|
|
433
|
+
|
|
434
|
+
server.tool("user_context_add_entry", "Add an entry to a user's daily interaction history log", {
|
|
435
|
+
user_id: z.string().describe("User identifier"),
|
|
436
|
+
content: z.string().describe("Content to log")
|
|
437
|
+
}, async ({ user_id, content }) => {
|
|
438
|
+
const today = new Date().toISOString().split("T")[0];
|
|
439
|
+
const key = `doc:users:${user_id}:history:${today}`;
|
|
440
|
+
let existing = await redis.get(key);
|
|
441
|
+
if (!existing) existing = `## User History for ${user_id} - ${today}\n\n`;
|
|
442
|
+
const timestamp = new Date().toLocaleTimeString();
|
|
443
|
+
const entry = `**[${timestamp}]**\n${content}\n\n---\n\n`;
|
|
444
|
+
await redis.setEx(key, USER_HISTORY_TTL, existing + entry);
|
|
445
|
+
return { content: [{ type: "text", text: JSON.stringify({ success: true, key, entry_added: entry }) }] };
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
server.tool("user_context_get_history", "Retrieve the full interaction history for a user on a specific date", {
|
|
449
|
+
user_id: z.string().describe("User identifier"),
|
|
450
|
+
date: z.string().describe("Date in YYYY-MM-DD format")
|
|
451
|
+
}, async ({ user_id, date }) => {
|
|
452
|
+
const key = `doc:users:${user_id}:history:${date}`;
|
|
453
|
+
const val = await redis.get(key);
|
|
454
|
+
if (!val) {
|
|
455
|
+
return { content: [{ type: "text", text: JSON.stringify({ status: "Not Found", message: `No history found for user '${user_id}' on date '${date}'.` }) }] };
|
|
456
|
+
}
|
|
457
|
+
return { content: [{ type: "text", text: JSON.stringify({ user_id, date, history: val }) }] };
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
server.tool("user_context_search_history", "Search across all of a user's history documents by keyword", {
|
|
461
|
+
user_id: z.string().describe("User identifier"),
|
|
462
|
+
query: z.string().describe("Search query")
|
|
463
|
+
}, async ({ user_id, query }) => {
|
|
464
|
+
const results = await searchDocs(`doc:users:${user_id}:history:*`, query);
|
|
465
|
+
if (results.length === 0) {
|
|
466
|
+
return { content: [{ type: "text", text: JSON.stringify({ status: "No matches found." }) }] };
|
|
467
|
+
}
|
|
468
|
+
return { content: [{ type: "text", text: JSON.stringify({
|
|
469
|
+
results: results.map(r => ({
|
|
470
|
+
date: r.key.split(":").pop(),
|
|
471
|
+
match_preview: r.content.substring(0, 200) + "..."
|
|
472
|
+
}))
|
|
473
|
+
}) }] };
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
return server;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// SSE transport management
|
|
480
|
+
const transports = {};
|
|
481
|
+
|
|
482
|
+
app.get("/sse", async (req, res) => {
|
|
483
|
+
const transport = new SSEServerTransport("/messages", res);
|
|
484
|
+
const mcpServer = createMcpServerInstance();
|
|
485
|
+
transports[transport.sessionId] = { transport, server: mcpServer };
|
|
486
|
+
res.on("close", () => {
|
|
487
|
+
mcpServer.close();
|
|
488
|
+
delete transports[transport.sessionId];
|
|
489
|
+
});
|
|
490
|
+
await mcpServer.connect(transport);
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
app.post("/messages", async (req, res) => {
|
|
494
|
+
const sessionId = req.query.sessionId;
|
|
495
|
+
const entry = transports[sessionId];
|
|
496
|
+
if (entry) {
|
|
497
|
+
await entry.transport.handlePostMessage(req, res);
|
|
498
|
+
} else {
|
|
499
|
+
res.status(400).json({ error: "No transport found for sessionId" });
|
|
500
|
+
}
|
|
501
|
+
});
|
|
502
|
+
|
|
503
|
+
// --- REST API (backwards compatibility) ---
|
|
504
|
+
const jsonParser = express.json();
|
|
505
|
+
|
|
506
|
+
app.get("/health", async (req, res) => {
|
|
507
|
+
const redisOk = redis.isReady;
|
|
508
|
+
let obsidianOk = false;
|
|
509
|
+
try {
|
|
510
|
+
await fs.access(OBSIDIAN_VAULT_PATH);
|
|
511
|
+
obsidianOk = true;
|
|
512
|
+
} catch {}
|
|
513
|
+
res.json({
|
|
514
|
+
status: (redisOk && obsidianOk) ? "healthy" : "degraded",
|
|
515
|
+
redis: redisOk,
|
|
516
|
+
obsidian: obsidianOk,
|
|
517
|
+
vault_path: OBSIDIAN_VAULT_PATH,
|
|
518
|
+
uptime: process.uptime()
|
|
519
|
+
});
|
|
520
|
+
});
|
|
521
|
+
|
|
522
|
+
app.get("/api/tools", (req, res) => {
|
|
523
|
+
res.json({ tools: [
|
|
524
|
+
"cache_set", "cache_get", "cache_delete", "redis_stats", "health_check",
|
|
525
|
+
"obsidian_write_note", "obsidian_read_note", "obsidian_delete_note",
|
|
526
|
+
"obsidian_search_notes", "obsidian_list_notes",
|
|
527
|
+
"heurchain_search",
|
|
528
|
+
"prometheus_get_targets", "prometheus_get_alerts", "prometheus_query",
|
|
529
|
+
"grafana_get_health", "grafana_list_dashboards",
|
|
530
|
+
"proxmox_get_cluster_status", "proxmox_list_nodes", "proxmox_find_vm",
|
|
531
|
+
"ceph_get_health_status", "ceph_list_osd_notes",
|
|
532
|
+
"network_search_docs", "network_get_runbook",
|
|
533
|
+
"user_context_add_entry", "user_context_get_history", "user_context_search_history"
|
|
534
|
+
]});
|
|
535
|
+
});
|
|
536
|
+
|
|
537
|
+
app.post("/api/cache", jsonParser, async (req, res) => {
|
|
538
|
+
const { key, value, ttl } = req.body;
|
|
539
|
+
const stored = typeof value === "string" ? value : JSON.stringify(value);
|
|
540
|
+
if (ttl) await redis.setEx(key, ttl, stored);
|
|
541
|
+
else await redis.set(key, stored);
|
|
542
|
+
res.json({ cached: true });
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
app.get("/api/cache/:key", async (req, res) => {
|
|
546
|
+
const val = await redis.get(req.params.key);
|
|
547
|
+
if (val) res.json({ hit: true, data: val });
|
|
548
|
+
else res.json({ hit: false });
|
|
549
|
+
});
|
|
550
|
+
|
|
551
|
+
app.get("/api/stats", async (req, res) => {
|
|
552
|
+
const info = await redis.info("stats");
|
|
553
|
+
res.json({ redis_info: info });
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
// --- Obsidian REST Endpoints ---
|
|
557
|
+
|
|
558
|
+
app.get("/api/obsidian/notes", async (req, res) => {
|
|
559
|
+
const { key, prefix } = req.query;
|
|
560
|
+
if (key) {
|
|
561
|
+
const content = await readFromObsidian(key);
|
|
562
|
+
if (content === null) return res.status(404).json({ found: false, key });
|
|
563
|
+
return res.json({ found: true, key, content });
|
|
564
|
+
}
|
|
565
|
+
const notes = await listObsidian(prefix);
|
|
566
|
+
res.json({ count: notes.length, notes });
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
app.post("/api/obsidian/notes", jsonParser, async (req, res) => {
|
|
570
|
+
const { key, content, metadata } = req.body;
|
|
571
|
+
if (!key || content === undefined) return res.status(400).json({ error: "key and content required" });
|
|
572
|
+
try {
|
|
573
|
+
const filePath = await saveToObsidian(key, content, metadata);
|
|
574
|
+
res.json({ stored: true, key, path: filePath });
|
|
575
|
+
} catch (e) {
|
|
576
|
+
res.status(500).json({ stored: false, error: e.message });
|
|
577
|
+
}
|
|
578
|
+
});
|
|
579
|
+
|
|
580
|
+
app.delete("/api/obsidian/notes", async (req, res) => {
|
|
581
|
+
const { key } = req.query;
|
|
582
|
+
if (!key) return res.status(400).json({ error: "key required" });
|
|
583
|
+
const deleted = await deleteFromObsidian(key);
|
|
584
|
+
res.json({ deleted, key });
|
|
585
|
+
});
|
|
586
|
+
|
|
587
|
+
app.get("/api/obsidian/search", async (req, res) => {
|
|
588
|
+
const { q, limit } = req.query;
|
|
589
|
+
if (!q) return res.status(400).json({ error: "q required" });
|
|
590
|
+
const results = await searchObsidian(q);
|
|
591
|
+
const max = parseInt(limit) || 10;
|
|
592
|
+
res.json({
|
|
593
|
+
count: results.length,
|
|
594
|
+
results: results.slice(0, max).map(r => ({
|
|
595
|
+
key: r.key,
|
|
596
|
+
path: r.path,
|
|
597
|
+
preview: r.content.substring(0, 200)
|
|
598
|
+
}))
|
|
599
|
+
});
|
|
600
|
+
});
|
|
601
|
+
|