knowmind 0.1.21 → 0.1.23

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/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # Knowmind CLI — Änderungen
2
2
 
3
+ ## 0.1.23 (2026-06-20)
4
+
5
+ **Neuer Befehl `knowmind install <ide>`**
6
+ - Trägt knowmind als MCP-Server in die richtige Config-Datei einer IDE ein.
7
+ - Unterstützt drei Schema-Familien: `mcpServers` (Cursor, Windsurf, Antigravity,
8
+ Claude Desktop, Claude Code-Projekt), `servers`+`inputs` (VS Code) und
9
+ `context_servers` (Zed); JetBrains und Claude-Code-User-Scope geben ein
10
+ Snippet bzw. den `claude mcp add`-Befehl aus.
11
+ - Flags: `--project`, `--print`, `--dry-run`, `--token`, `--api`.
12
+ - Token wird per Default nie im Klartext geschrieben (Env-/Input-Referenz oder
13
+ Platzhalter mit Warnung); Schreibvorgänge sind ein idempotenter JSON-Merge,
14
+ der vorhandene Fremd-Server erhält.
15
+
16
+ ## 0.1.22 (2026-06-11)
17
+
18
+ **Discovery-Modus ohne Token (Introspection-fähig)**
19
+ - Ist KEIN Token konfiguriert, beantwortet `knowmind mcp` jetzt `initialize`,
20
+ `tools/list` und `prompts/list` über die ÖFFENTLICHE Server-Discovery
21
+ (`GET /api/mcp/v1` — liefert Name, Version und alle Tool-Definitionen ohne
22
+ Auth). Vorher schlugen ohne Token ALLE Requests inkl. `initialize` mit
23
+ `-32001` fehl — Verzeichnis-Crawler (z. B. Glama) konnten den Server nicht
24
+ inspizieren.
25
+ - `tools/call` verlangt weiterhin einen Token und verweist klar auf
26
+ `knowmind login`. Ein konfigurierter, aber ungültiger Token führt unverändert
27
+ zum harten Verbindungsfehler (kein falsches „connected ✓").
28
+ - Neu: `Dockerfile` im Repo (node:20-alpine, `knowmind mcp` als Entrypoint) —
29
+ für Container-basierte Inspection/Nutzung.
30
+
3
31
  ## 0.1.21 (2026-06-10)
4
32
 
5
33
  **Bugfix: `knowmind init`-Recall-Hook funktioniert jetzt auf Windows**
@@ -41,7 +69,7 @@
41
69
  gegen lokale `.md`-Dateien.
42
70
  - **Cursor:** schreibt `.cursor/rules/knowmind.mdc` (Memory-First-Regel, `alwaysApply`).
43
71
  - **Claude Desktop / Codex / generisch:** kein Hook-Mechanismus — zeigt den
44
- Memory-First-Text zum manuellen Einfügen und benennt die ehrliche Grenze (nur
72
+ Memory-First-Text zum manuellen Einfügen und benennt die Grenze (nur
45
73
  MCP-instructions + MCP-prompts wirken, keine harte Erzwingung).
46
74
  - **Idempotent & nicht-destruktiv:** marker-/befehls-basierte Ersetzung
47
75
  (`<!-- BEGIN/END knowmind -->`); zweiter Lauf erzeugt keine Duplikate, fremde Dateien
package/README.md CHANGED
@@ -73,11 +73,11 @@ knowmind init --dry-run # zeigt nur, was geschähe (schreibt nich
73
73
  (marker-/befehls-basierte Ersetzung); bestehende fremde Dateien und Hooks bleiben
74
74
  unangetastet. Mit `--dry-run` sehen Sie jede Aktion vorab.
75
75
 
76
- > **Ehrliche Grenze:** Eine *harte* Erzwingung der Pflege gibt es nur in Clients mit
76
+ > **Grenze der Automatik:** Eine *harte* Erzwingung der Pflege gibt es nur in Clients mit
77
77
  > Hook-/Rule-Mechanismus (Claude Code, Cursor). In Clients ohne solchen Mechanismus
78
- > (z. B. Claude Desktop, Codex CLI) wirken nur die **MCP-instructions** (werden beim
79
- > Verbinden gelesen) und die **MCP-prompts** — das ist eine weiche, modellabhängige
80
- > Steuerung, keine technische Garantie.
78
+ > (z. B. Claude Desktop, Codex CLI) greifen die **MCP-instructions** (werden beim
79
+ > Verbinden gelesen) und die **MCP-prompts** — eine modellabhängige Steuerung ohne
80
+ > technische Garantie.
81
81
 
82
82
  ## MCP-Server einrichten
83
83
 
package/bin/knowmind.js CHANGED
@@ -1,241 +1,260 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Knowmind CLI Entry-Point.
4
- *
5
- * Verfügbare Befehle:
6
- * knowmind login [--token kmt_…] — API-Token speichern
7
- * knowmind config — aktuelle Config anzeigen
8
- * knowmind search "Frage" [-k 5] — Recall
9
- * knowmind upload <file> [--title] — Dokument-Ingestion
10
- * knowmind stats — Korpus-Statistik
11
- * knowmind health — Service-Health
12
- * knowmind mcp — Stdio-MCP-Server
13
- */
14
- import { readFileSync } from "node:fs";
15
- import { basename } from "node:path";
16
- import { stdin as input } from "node:process";
17
- import {
18
- recall,
19
- uploadDocument,
20
- stats,
21
- health,
22
- } from "../src/client.js";
23
- import { loadConfig, saveConfig, configPath, VERSION } from "../src/config.js";
24
- import { runStdioServer } from "../src/mcp-stdio.js";
25
- import { syncDirectory } from "../src/sync.js";
26
- import { runInit } from "../src/init.js";
27
-
28
- const args = process.argv.slice(2);
29
- const cmd = args[0];
30
-
31
- function parseFlag(name, fallback) {
32
- const i = args.indexOf(name);
33
- if (i < 0) return fallback;
34
- return args[i + 1] ?? fallback;
35
- }
36
-
37
- async function readStdin() {
38
- return await new Promise((resolve) => {
39
- let data = "";
40
- input.setEncoding("utf-8");
41
- input.on("data", (c) => (data += c));
42
- input.on("end", () => resolve(data));
43
- });
44
- }
45
-
46
- function help() {
47
- console.log(`
48
- Knowmind ${VERSION} — Das Gedächtnis für Ihre KI
49
-
50
- Befehle:
51
- knowmind login [--token kmt_TOKEN] [--api https://knowmind.de]
52
- Token speichern
53
- knowmind init [--client claude-code|cursor|auto] [--dry-run]
54
- Automatische Gedächtnis-Pflege im KI-Client einrichten
55
- (Hooks/Regeln + Memory-First-Block). Idempotent.
56
- knowmind config Aktuelle Konfiguration anzeigen
57
- knowmind search "Frage" [-k 5] [--hops 2]
58
- Hybrid-Recall gegen den Tenant-Korpus
59
- knowmind upload <file> [--title "..."]
60
- Markdown-/Text-Datei indexieren (stdin: knowmind upload -)
61
- knowmind sync <dir> [--ext .md,.txt] [--verbose] [--title-from-content]
62
- Ordner mit dem Korpus abgleichen. Idempotent über
63
- Content-Hash, Manifest in <dir>/.knowmind-manifest.json.
64
- knowmind stats Memory- und Edge-Counter des Tenants
65
- knowmind health Health-Check der Plattform
66
- knowmind mcp Stdio-MCP-Server für lokale AI-Clients
67
-
68
- ENV-Override:
69
- KNOWMIND_API_URL z. B. https://knowmind.de
70
- KNOWMIND_TOKEN Bearer-Token (überschreibt Config-File)
71
- `);
72
- }
73
-
74
- async function runLogin() {
75
- let token = parseFlag("--token", null);
76
- const api = parseFlag("--api", null);
77
- if (!token) {
78
- // Interaktiv von stdin lesen
79
- process.stdout.write("API-Token (kmt_…): ");
80
- const line = await new Promise((resolve) => {
81
- input.once("data", (d) => resolve(d.toString().trim()));
82
- });
83
- token = line;
84
- }
85
- if (!token || !token.startsWith("kmt_"))
86
- throw new Error("Token muss mit kmt_ beginnen.");
87
-
88
- // Vor dem Speichern: Token gegen Server verifizieren. Sonst wäre jeder
89
- // Phantasie-String akzeptiert und alle späteren Aufrufe scheitern erst
90
- // beim ersten echten Call — das ist verwirrend.
91
- const apiUrl = api || process.env.KNOWMIND_API_URL || loadConfig().apiUrl;
92
- process.stdout.write("Token wird gegen Server verifiziert … ");
93
- const r = await fetch(`${apiUrl}/api/mcp/v1`, {
94
- method: "POST",
95
- headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
96
- body: JSON.stringify({
97
- jsonrpc: "2.0",
98
- id: 1,
99
- method: "tools/call",
100
- params: { name: "knowmind_health", arguments: {} },
101
- }),
102
- }).catch((e) => ({ ok: false, _netError: e.message }));
103
- if (r._netError) {
104
- process.stdout.write("FEHLER\n");
105
- throw new Error(`Server nicht erreichbar (${apiUrl}): ${r._netError}`);
106
- }
107
- const data = await r.json().catch(() => ({}));
108
- if (!r.ok || data.error) {
109
- process.stdout.write("ABGELEHNT\n");
110
- const code = data.error?.code ?? r.status;
111
- const msg = data.error?.message ?? `HTTP ${r.status}`;
112
- throw new Error(`Token ungültig: ${code} — ${msg}`);
113
- }
114
- process.stdout.write("ok\n");
115
- const where = saveConfig({ token, ...(api ? { apiUrl: api } : {}) });
116
- console.log(`Token gespeichert in ${where}.`);
117
- }
118
-
119
- async function runSearch() {
120
- const query = args.slice(1).filter((a) => !a.startsWith("-")).join(" ");
121
- if (!query) throw new Error('Usage: knowmind search "Ihre Frage"');
122
- const k = Number(parseFlag("-k", parseFlag("--k", 5)));
123
- const hops = Number(parseFlag("--hops", 2));
124
- const result = await recall(query, { k, hops });
125
- if (!result?.hits?.length) {
126
- console.log("Keine Treffer.");
127
- return;
128
- }
129
- for (const [i, hit] of result.hits.entries()) {
130
- const src = hit.metadata?.source_id ?? hit.chunk_id;
131
- const name = hit.metadata?.name ?? src;
132
- console.log(`\n#${i + 1} ${name} (score ${hit.score.toFixed(3)})`);
133
- console.log(" " + hit.content.slice(0, 280).replace(/\n/g, "\n "));
134
- }
135
- console.log(`\n${result.hits.length} Treffer in ${result.latency_ms} ms.`);
136
- }
137
-
138
- async function runUpload() {
139
- const path = args[1];
140
- if (!path) throw new Error("Usage: knowmind upload <file> (oder `-` für stdin)");
141
- let content;
142
- let title = parseFlag("--title", null);
143
- if (path === "-") {
144
- content = await readStdin();
145
- title = title ?? "stdin";
146
- } else {
147
- content = readFileSync(path, "utf-8");
148
- title = title ?? basename(path);
149
- }
150
- const data = await uploadDocument(title, content);
151
- if (data.unchanged || data.duplicate) {
152
- console.log(`Unverändert/Duplikat: Inhalt liegt bereits indexiert vor (Doc ${data.id ?? "?"}).`);
153
- } else {
154
- console.log(`Indexiert: ${data.chunksWritten} Chunks (Provider ${data.embeddingProvider}).`);
155
- }
156
- }
157
-
158
- async function runSync() {
159
- const dir = args[1];
160
- if (!dir) throw new Error("Usage: knowmind sync <directory>");
161
- const extFlag = parseFlag("--ext", null);
162
- const options = {
163
- extensions: extFlag ? extFlag.split(",").map((e) => (e.startsWith(".") ? e : `.${e}`)) : undefined,
164
- verbose: args.includes("--verbose"),
165
- titleFromContent: args.includes("--title-from-content"),
166
- };
167
- const result = await syncDirectory(dir, options);
168
- if (result.failed > 0) process.exitCode = 3;
169
- }
170
-
171
-
172
- async function runStats() {
173
- console.log(JSON.stringify(await stats(), null, 2));
174
- }
175
-
176
- async function runHealth() {
177
- console.log(JSON.stringify(await health(), null, 2));
178
- }
179
-
180
- async function runConfig() {
181
- const c = loadConfig();
182
- console.log(`Config-Datei: ${configPath()}`);
183
- console.log(`API-URL: ${c.apiUrl}`);
184
- console.log(`Token: ${c.token ? c.token.slice(0, 12) + "…" : "(keiner)"}`);
185
- }
186
-
187
- async function runInitCmd() {
188
- const client = parseFlag("--client", "auto");
189
- const dryRun = args.includes("--dry-run");
190
- console.log(await runInit({ client, dryRun }));
191
- }
192
-
193
- // Wichtig: `process.exit(N)` reißt offene Sockets/fetch-Verbindungen mit
194
- // rein und triggert auf Windows/Node 22 die libuv-Assertion
195
- // `!(handle->flags & UV_HANDLE_CLOSING)`. Stattdessen `exitCode` setzen
196
- // und sauber zurückkehren — Node beendet sich von selbst, sobald keine
197
- // offenen Handles mehr da sind.
198
- try {
199
- switch (cmd) {
200
- case "login":
201
- await runLogin();
202
- break;
203
- case "config":
204
- await runConfig();
205
- break;
206
- case "search":
207
- await runSearch();
208
- break;
209
- case "upload":
210
- await runUpload();
211
- break;
212
- case "sync":
213
- await runSync();
214
- break;
215
- case "stats":
216
- await runStats();
217
- break;
218
- case "health":
219
- await runHealth();
220
- break;
221
- case "mcp":
222
- await runStdioServer();
223
- break;
224
- case "init":
225
- await runInitCmd();
226
- break;
227
- case "--help":
228
- case "-h":
229
- case "help":
230
- case undefined:
231
- help();
232
- break;
233
- default:
234
- console.error(`Unbekannter Befehl: ${cmd}`);
235
- help();
236
- process.exitCode = 1;
237
- }
238
- } catch (e) {
239
- console.error(`Fehler: ${e.message}`);
240
- process.exitCode = 2;
241
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Knowmind CLI Entry-Point.
4
+ *
5
+ * Verfügbare Befehle:
6
+ * knowmind login [--token kmt_…] — API-Token speichern
7
+ * knowmind config — aktuelle Config anzeigen
8
+ * knowmind search "Frage" [-k 5] — Recall
9
+ * knowmind upload <file> [--title] — Dokument-Ingestion
10
+ * knowmind stats — Korpus-Statistik
11
+ * knowmind health — Service-Health
12
+ * knowmind mcp — Stdio-MCP-Server
13
+ */
14
+ import { readFileSync } from "node:fs";
15
+ import { basename } from "node:path";
16
+ import { stdin as input } from "node:process";
17
+ import {
18
+ recall,
19
+ uploadDocument,
20
+ stats,
21
+ health,
22
+ } from "../src/client.js";
23
+ import { loadConfig, saveConfig, configPath, VERSION } from "../src/config.js";
24
+ import { runStdioServer } from "../src/mcp-stdio.js";
25
+ import { syncDirectory } from "../src/sync.js";
26
+ import { runInit } from "../src/init.js";
27
+ import { runInstall } from "../src/install.js";
28
+
29
+ const args = process.argv.slice(2);
30
+ const cmd = args[0];
31
+
32
+ function parseFlag(name, fallback) {
33
+ const i = args.indexOf(name);
34
+ if (i < 0) return fallback;
35
+ return args[i + 1] ?? fallback;
36
+ }
37
+
38
+ async function readStdin() {
39
+ return await new Promise((resolve) => {
40
+ let data = "";
41
+ input.setEncoding("utf-8");
42
+ input.on("data", (c) => (data += c));
43
+ input.on("end", () => resolve(data));
44
+ });
45
+ }
46
+
47
+ function help() {
48
+ console.log(`
49
+ Knowmind ${VERSION} — Das Gedächtnis für Ihre KI
50
+
51
+ Befehle:
52
+ knowmind login [--token kmt_TOKEN] [--api https://knowmind.de]
53
+ Token speichern
54
+ knowmind init [--client claude-code|cursor|auto] [--dry-run]
55
+ Automatische Gedächtnis-Pflege im KI-Client einrichten
56
+ (Hooks/Regeln + Memory-First-Block). Idempotent.
57
+ knowmind config Aktuelle Konfiguration anzeigen
58
+ knowmind search "Frage" [-k 5] [--hops 2]
59
+ Hybrid-Recall gegen den Tenant-Korpus
60
+ knowmind upload <file> [--title "..."]
61
+ Markdown-/Text-Datei indexieren (stdin: knowmind upload -)
62
+ knowmind sync <dir> [--ext .md,.txt] [--verbose] [--title-from-content]
63
+ Ordner mit dem Korpus abgleichen. Idempotent über
64
+ Content-Hash, Manifest in <dir>/.knowmind-manifest.json.
65
+ knowmind stats Memory- und Edge-Counter des Tenants
66
+ knowmind health Health-Check der Plattform
67
+ knowmind mcp Stdio-MCP-Server für lokale AI-Clients
68
+ knowmind install <ide> [--project] [--print] [--token T] [--api URL]
69
+ knowmind als MCP-Server in eine IDE eintragen
70
+ (cursor, vscode, windsurf, antigravity, zed, jetbrains,
71
+ claude-code, claude-desktop, all). 'install list' zeigt alle.
72
+
73
+ ENV-Override:
74
+ KNOWMIND_API_URL z. B. https://knowmind.de
75
+ KNOWMIND_TOKEN Bearer-Token (überschreibt Config-File)
76
+ `);
77
+ }
78
+
79
+ async function runLogin() {
80
+ let token = parseFlag("--token", null);
81
+ const api = parseFlag("--api", null);
82
+ if (!token) {
83
+ // Interaktiv von stdin lesen
84
+ process.stdout.write("API-Token (kmt_…): ");
85
+ const line = await new Promise((resolve) => {
86
+ input.once("data", (d) => resolve(d.toString().trim()));
87
+ });
88
+ token = line;
89
+ }
90
+ if (!token || !token.startsWith("kmt_"))
91
+ throw new Error("Token muss mit kmt_ beginnen.");
92
+
93
+ // Vor dem Speichern: Token gegen Server verifizieren. Sonst wäre jeder
94
+ // Phantasie-String akzeptiert und alle späteren Aufrufe scheitern erst
95
+ // beim ersten echten Call — das ist verwirrend.
96
+ const apiUrl = api || process.env.KNOWMIND_API_URL || loadConfig().apiUrl;
97
+ process.stdout.write("Token wird gegen Server verifiziert … ");
98
+ const r = await fetch(`${apiUrl}/api/mcp/v1`, {
99
+ method: "POST",
100
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
101
+ body: JSON.stringify({
102
+ jsonrpc: "2.0",
103
+ id: 1,
104
+ method: "tools/call",
105
+ params: { name: "knowmind_health", arguments: {} },
106
+ }),
107
+ }).catch((e) => ({ ok: false, _netError: e.message }));
108
+ if (r._netError) {
109
+ process.stdout.write("FEHLER\n");
110
+ throw new Error(`Server nicht erreichbar (${apiUrl}): ${r._netError}`);
111
+ }
112
+ const data = await r.json().catch(() => ({}));
113
+ if (!r.ok || data.error) {
114
+ process.stdout.write("ABGELEHNT\n");
115
+ const code = data.error?.code ?? r.status;
116
+ const msg = data.error?.message ?? `HTTP ${r.status}`;
117
+ throw new Error(`Token ungültig: ${code} — ${msg}`);
118
+ }
119
+ process.stdout.write("ok\n");
120
+ const where = saveConfig({ token, ...(api ? { apiUrl: api } : {}) });
121
+ console.log(`Token gespeichert in ${where}.`);
122
+ }
123
+
124
+ async function runSearch() {
125
+ const query = args.slice(1).filter((a) => !a.startsWith("-")).join(" ");
126
+ if (!query) throw new Error('Usage: knowmind search "Ihre Frage"');
127
+ const k = Number(parseFlag("-k", parseFlag("--k", 5)));
128
+ const hops = Number(parseFlag("--hops", 2));
129
+ const result = await recall(query, { k, hops });
130
+ if (!result?.hits?.length) {
131
+ console.log("Keine Treffer.");
132
+ return;
133
+ }
134
+ for (const [i, hit] of result.hits.entries()) {
135
+ const src = hit.metadata?.source_id ?? hit.chunk_id;
136
+ const name = hit.metadata?.name ?? src;
137
+ console.log(`\n#${i + 1} ${name} (score ${hit.score.toFixed(3)})`);
138
+ console.log(" " + hit.content.slice(0, 280).replace(/\n/g, "\n "));
139
+ }
140
+ console.log(`\n${result.hits.length} Treffer in ${result.latency_ms} ms.`);
141
+ }
142
+
143
+ async function runUpload() {
144
+ const path = args[1];
145
+ if (!path) throw new Error("Usage: knowmind upload <file> (oder `-` für stdin)");
146
+ let content;
147
+ let title = parseFlag("--title", null);
148
+ if (path === "-") {
149
+ content = await readStdin();
150
+ title = title ?? "stdin";
151
+ } else {
152
+ content = readFileSync(path, "utf-8");
153
+ title = title ?? basename(path);
154
+ }
155
+ const data = await uploadDocument(title, content);
156
+ if (data.unchanged || data.duplicate) {
157
+ console.log(`Unverändert/Duplikat: Inhalt liegt bereits indexiert vor (Doc ${data.id ?? "?"}).`);
158
+ } else {
159
+ console.log(`Indexiert: ${data.chunksWritten} Chunks (Provider ${data.embeddingProvider}).`);
160
+ }
161
+ }
162
+
163
+ async function runSync() {
164
+ const dir = args[1];
165
+ if (!dir) throw new Error("Usage: knowmind sync <directory>");
166
+ const extFlag = parseFlag("--ext", null);
167
+ const options = {
168
+ extensions: extFlag ? extFlag.split(",").map((e) => (e.startsWith(".") ? e : `.${e}`)) : undefined,
169
+ verbose: args.includes("--verbose"),
170
+ titleFromContent: args.includes("--title-from-content"),
171
+ };
172
+ const result = await syncDirectory(dir, options);
173
+ if (result.failed > 0) process.exitCode = 3;
174
+ }
175
+
176
+
177
+ async function runStats() {
178
+ console.log(JSON.stringify(await stats(), null, 2));
179
+ }
180
+
181
+ async function runHealth() {
182
+ console.log(JSON.stringify(await health(), null, 2));
183
+ }
184
+
185
+ async function runConfig() {
186
+ const c = loadConfig();
187
+ console.log(`Config-Datei: ${configPath()}`);
188
+ console.log(`API-URL: ${c.apiUrl}`);
189
+ console.log(`Token: ${c.token ? c.token.slice(0, 12) + "…" : "(keiner)"}`);
190
+ }
191
+
192
+ async function runInitCmd() {
193
+ const client = parseFlag("--client", "auto");
194
+ const dryRun = args.includes("--dry-run");
195
+ console.log(await runInit({ client, dryRun }));
196
+ }
197
+
198
+ async function runInstallCmd() {
199
+ runInstall({
200
+ ideKey: args[1] && !args[1].startsWith("-") ? args[1] : null,
201
+ project: args.includes("--project"),
202
+ dryRun: args.includes("--dry-run"),
203
+ printOnly: args.includes("--print"),
204
+ apiUrl: parseFlag("--api", null),
205
+ literalToken: parseFlag("--token", null),
206
+ });
207
+ }
208
+
209
+ // Wichtig: `process.exit(N)` reißt offene Sockets/fetch-Verbindungen mit
210
+ // rein und triggert auf Windows/Node 22 die libuv-Assertion
211
+ // `!(handle->flags & UV_HANDLE_CLOSING)`. Stattdessen `exitCode` setzen
212
+ // und sauber zurückkehren — Node beendet sich von selbst, sobald keine
213
+ // offenen Handles mehr da sind.
214
+ try {
215
+ switch (cmd) {
216
+ case "login":
217
+ await runLogin();
218
+ break;
219
+ case "config":
220
+ await runConfig();
221
+ break;
222
+ case "search":
223
+ await runSearch();
224
+ break;
225
+ case "upload":
226
+ await runUpload();
227
+ break;
228
+ case "sync":
229
+ await runSync();
230
+ break;
231
+ case "stats":
232
+ await runStats();
233
+ break;
234
+ case "health":
235
+ await runHealth();
236
+ break;
237
+ case "mcp":
238
+ await runStdioServer();
239
+ break;
240
+ case "install":
241
+ await runInstallCmd();
242
+ break;
243
+ case "init":
244
+ await runInitCmd();
245
+ break;
246
+ case "--help":
247
+ case "-h":
248
+ case "help":
249
+ case undefined:
250
+ help();
251
+ break;
252
+ default:
253
+ console.error(`Unbekannter Befehl: ${cmd}`);
254
+ help();
255
+ process.exitCode = 1;
256
+ }
257
+ } catch (e) {
258
+ console.error(`Fehler: ${e.message}`);
259
+ process.exitCode = 2;
260
+ }
package/package.json CHANGED
@@ -1,61 +1,61 @@
1
- {
2
- "name": "knowmind",
3
- "version": "0.1.21",
4
- "mcpName": "io.github.Schubeler-Consulting/knowmind",
5
- "description": "Knowmind — das Agentengehirn aus Deutschland: CLI + MCP-Server (Langzeitgedächtnis & Wissensgraph für Ihre KI, Server in Deutschland).",
6
- "type": "module",
7
- "license": "Apache-2.0",
8
- "homepage": "https://knowmind.de",
9
- "repository": {
10
- "type": "git",
11
- "url": "git+https://github.com/Schubeler-Consulting/knowmind.git"
12
- },
13
- "bugs": {
14
- "url": "https://knowmind.de/support",
15
- "email": "info@schuebeler-consulting.de"
16
- },
17
- "author": {
18
- "name": "Knowmind",
19
- "email": "info@schuebeler-consulting.de",
20
- "url": "https://knowmind.de"
21
- },
22
- "engines": {
23
- "node": ">=20"
24
- },
25
- "bin": {
26
- "knowmind": "bin/knowmind.js"
27
- },
28
- "files": [
29
- "bin",
30
- "src",
31
- "!src/*.test.js",
32
- "README.md",
33
- "CHANGELOG.md",
34
- "LICENSE"
35
- ],
36
- "scripts": {
37
- "test": "node --test src/*.test.js"
38
- },
39
- "dependencies": {
40
- "@huggingface/transformers": "^3.5.0"
41
- },
42
- "overrides": {
43
- "global-agent": "^4.1.3"
44
- },
45
- "keywords": [
46
- "knowmind",
47
- "mcp",
48
- "model-context-protocol",
49
- "knowledge-graph",
50
- "recall",
51
- "memory",
52
- "rag",
53
- "claude",
54
- "openai",
55
- "anthropic",
56
- "ai"
57
- ],
58
- "publishConfig": {
59
- "access": "public"
60
- }
61
- }
1
+ {
2
+ "name": "knowmind",
3
+ "version": "0.1.23",
4
+ "mcpName": "io.github.Schubeler-Consulting/knowmind",
5
+ "description": "Knowmind — das Agentengehirn aus Deutschland: CLI + MCP-Server (Langzeitgedächtnis & Wissensgraph für Ihre KI, Server in Deutschland).",
6
+ "type": "module",
7
+ "license": "Apache-2.0",
8
+ "homepage": "https://knowmind.de",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/Schubeler-Consulting/knowmind.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://knowmind.de/support",
15
+ "email": "info@schuebeler-consulting.de"
16
+ },
17
+ "author": {
18
+ "name": "Knowmind",
19
+ "email": "info@schuebeler-consulting.de",
20
+ "url": "https://knowmind.de"
21
+ },
22
+ "engines": {
23
+ "node": ">=20"
24
+ },
25
+ "bin": {
26
+ "knowmind": "bin/knowmind.js"
27
+ },
28
+ "files": [
29
+ "bin",
30
+ "src",
31
+ "!src/*.test.js",
32
+ "README.md",
33
+ "CHANGELOG.md",
34
+ "LICENSE"
35
+ ],
36
+ "scripts": {
37
+ "test": "node --test src/*.test.js"
38
+ },
39
+ "dependencies": {
40
+ "@huggingface/transformers": "^3.5.0"
41
+ },
42
+ "overrides": {
43
+ "global-agent": "^4.1.3"
44
+ },
45
+ "keywords": [
46
+ "knowmind",
47
+ "mcp",
48
+ "model-context-protocol",
49
+ "knowledge-graph",
50
+ "recall",
51
+ "memory",
52
+ "rag",
53
+ "claude",
54
+ "openai",
55
+ "anthropic",
56
+ "ai"
57
+ ],
58
+ "publishConfig": {
59
+ "access": "public"
60
+ }
61
+ }
package/src/install.js ADDED
@@ -0,0 +1,255 @@
1
+ // `knowmind install <ide>` — schreibt die MCP-Server-Konfiguration für knowmind
2
+ // in die richtige Datei der jeweiligen IDE. Drei Schema-Familien decken alle
3
+ // gängigen Clients ab:
4
+ //
5
+ // 1. `mcpServers` → Cursor, Windsurf, Antigravity, Claude Desktop, Claude Code (Projekt)
6
+ // 2. `servers`+inputs → VS Code (eigener Secret-Prompt)
7
+ // 3. `context_servers`→ Zed
8
+ //
9
+ // Secret-Politik (R5): das Token wird NICHT im Klartext in Config-Dateien
10
+ // geschrieben. Wo die IDE Interpolation kann, verweisen wir auf die Umgebung
11
+ // (`${env:KNOWMIND_TOKEN}` / `${input:…}` / `${KNOWMIND_TOKEN}`); wo nicht, steht
12
+ // ein Platzhalter mit Warnung. Nur mit ausdrücklichem `--token <wert>` wird ein
13
+ // literaler Wert geschrieben (dann mit Klartext-Warnung).
14
+
15
+ import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";
16
+ import { homedir, platform } from "node:os";
17
+ import { dirname, join } from "node:path";
18
+
19
+ const DEFAULT_API = "https://knowmind.de";
20
+ const NPX = "npx";
21
+ const NPX_ARGS = ["-y", "knowmind", "mcp"];
22
+
23
+ function home(...p) {
24
+ return join(homedir(), ...p);
25
+ }
26
+
27
+ // OS-abhängiger App-Daten-Pfad (Windows APPDATA, macOS Application Support, sonst ~/.config).
28
+ function appData(...p) {
29
+ if (platform() === "win32") {
30
+ return join(process.env.APPDATA || home("AppData", "Roaming"), ...p);
31
+ }
32
+ if (platform() === "darwin") {
33
+ return home("Library", "Application Support", ...p);
34
+ }
35
+ return join(process.env.XDG_CONFIG_HOME || home(".config"), ...p);
36
+ }
37
+
38
+ // ── IDE-Registry ──────────────────────────────────────────────────────────
39
+ // family: "mcpServers" | "servers" | "context_servers" | "command"
40
+ // secret: "env" | "input" | "shell" | "literal-only" (Default-Referenzstil)
41
+ const IDES = {
42
+ cursor: {
43
+ label: "Cursor",
44
+ family: "mcpServers",
45
+ secret: "env",
46
+ globalPath: () => home(".cursor", "mcp.json"),
47
+ projectPath: (cwd) => join(cwd, ".cursor", "mcp.json"),
48
+ },
49
+ vscode: {
50
+ label: "VS Code",
51
+ family: "servers",
52
+ secret: "input",
53
+ globalPath: () => appData("Code", "User", "mcp.json"),
54
+ projectPath: (cwd) => join(cwd, ".vscode", "mcp.json"),
55
+ },
56
+ windsurf: {
57
+ label: "Windsurf",
58
+ family: "mcpServers",
59
+ secret: "env",
60
+ globalPath: () => home(".codeium", "windsurf", "mcp_config.json"),
61
+ projectPath: null,
62
+ },
63
+ antigravity: {
64
+ label: "Google Antigravity",
65
+ family: "mcpServers",
66
+ secret: "literal-only",
67
+ globalPath: () => home(".gemini", "config", "mcp_config.json"),
68
+ projectPath: null,
69
+ },
70
+ zed: {
71
+ label: "Zed",
72
+ family: "context_servers",
73
+ secret: "literal-only",
74
+ globalPath: () => (platform() === "win32" ? appData("Zed", "settings.json") : home(".config", "zed", "settings.json")),
75
+ projectPath: (cwd) => join(cwd, ".zed", "settings.json"),
76
+ },
77
+ "claude-desktop": {
78
+ label: "Claude Desktop",
79
+ family: "mcpServers",
80
+ secret: "literal-only",
81
+ globalPath: () => appData("Claude", "claude_desktop_config.json"),
82
+ projectPath: null,
83
+ },
84
+ "claude-code": {
85
+ label: "Claude Code",
86
+ family: "mcpServers",
87
+ secret: "shell",
88
+ globalPath: null, // user-scope: via `claude mcp add` (siehe printClaudeCode)
89
+ projectPath: (cwd) => join(cwd, ".mcp.json"),
90
+ },
91
+ jetbrains: {
92
+ label: "JetBrains (IntelliJ/PyCharm)",
93
+ family: "mcpServers",
94
+ secret: "literal-only",
95
+ globalPath: null, // GUI-basiert: Snippet ausgeben
96
+ projectPath: null,
97
+ },
98
+ };
99
+
100
+ // Token-Referenz je Secret-Stil. literalToken überschreibt (nur mit --token).
101
+ function tokenRef(secretStyle, literalToken) {
102
+ if (literalToken) return literalToken;
103
+ switch (secretStyle) {
104
+ case "env":
105
+ return "${env:KNOWMIND_TOKEN}";
106
+ case "shell":
107
+ return "${KNOWMIND_TOKEN}";
108
+ case "input":
109
+ return "${input:knowmind-token}";
110
+ default:
111
+ return "<KNOWMIND_TOKEN — siehe `knowmind login`>";
112
+ }
113
+ }
114
+
115
+ // Server-Eintrag im Schema der Familie.
116
+ function serverEntry(ide, { apiUrl, literalToken }) {
117
+ const env = {
118
+ KNOWMIND_TOKEN: tokenRef(ide.secret, literalToken),
119
+ KNOWMIND_API_URL: apiUrl,
120
+ };
121
+ if (ide.family === "servers") {
122
+ // VS Code verlangt einen Transport-Typ.
123
+ return { type: "stdio", command: NPX, args: NPX_ARGS, env };
124
+ }
125
+ return { command: NPX, args: NPX_ARGS, env };
126
+ }
127
+
128
+ // Vollständiges Snippet (für --print / GUI-IDEs).
129
+ function snippet(ide, opts) {
130
+ const entry = serverEntry(ide, opts);
131
+ if (ide.family === "servers") {
132
+ return {
133
+ inputs: [{ type: "promptString", id: "knowmind-token", description: "KNOWMIND_TOKEN", password: true }],
134
+ servers: { knowmind: entry },
135
+ };
136
+ }
137
+ return { [ide.family]: { knowmind: entry } };
138
+ }
139
+
140
+ function readJsonSafe(path) {
141
+ if (!existsSync(path)) return {};
142
+ try {
143
+ return JSON.parse(readFileSync(path, "utf-8"));
144
+ } catch {
145
+ return null; // signalisiert: vorhandene Datei ist kaputt → nicht blind überschreiben
146
+ }
147
+ }
148
+
149
+ function writeJson(path, obj) {
150
+ mkdirSync(dirname(path), { recursive: true });
151
+ writeFileSync(path, JSON.stringify(obj, null, 2) + "\n", "utf-8");
152
+ }
153
+
154
+ // Merged knowmind in eine bestehende Config, ohne Fremd-Server zu verlieren.
155
+ function mergeInto(existing, ide, opts) {
156
+ const cfg = existing && typeof existing === "object" ? { ...existing } : {};
157
+ const entry = serverEntry(ide, opts);
158
+ if (ide.family === "servers") {
159
+ cfg.servers = { ...(cfg.servers || {}), knowmind: entry };
160
+ const inputs = Array.isArray(cfg.inputs) ? cfg.inputs.slice() : [];
161
+ if (!inputs.some((i) => i && i.id === "knowmind-token")) {
162
+ inputs.push({ type: "promptString", id: "knowmind-token", description: "KNOWMIND_TOKEN", password: true });
163
+ }
164
+ cfg.inputs = inputs;
165
+ } else {
166
+ cfg[ide.family] = { ...(cfg[ide.family] || {}), knowmind: entry };
167
+ }
168
+ return cfg;
169
+ }
170
+
171
+ function printClaudeCodeCommand(opts) {
172
+ const tokenArg = opts.literalToken ? opts.literalToken : "$KNOWMIND_TOKEN";
173
+ console.log("Claude Code (User-Scope, alle Projekte) — diesen Befehl ausführen:\n");
174
+ console.log(
175
+ ` claude mcp add --scope user --transport stdio \\\n` +
176
+ ` --env KNOWMIND_TOKEN=${tokenArg} \\\n` +
177
+ ` --env KNOWMIND_API_URL=${opts.apiUrl} \\\n` +
178
+ ` knowmind -- npx -y knowmind mcp\n`,
179
+ );
180
+ console.log("Für ein einzelnes Projekt stattdessen: knowmind install claude-code --project\n");
181
+ }
182
+
183
+ // ── Hauptbefehl ─────────────────────────────────────────────────────────────
184
+ export function runInstall(opts) {
185
+ const { ideKey, project, dryRun, printOnly, apiUrl, literalToken } = opts;
186
+
187
+ if (!ideKey || ideKey === "list") {
188
+ console.log("knowmind install <ide> [--project] [--print] [--token <wert>] [--api <url>]\n");
189
+ console.log("Unterstützte IDEs:");
190
+ for (const [key, ide] of Object.entries(IDES)) console.log(` ${key.padEnd(16)} ${ide.label}`);
191
+ console.log(" all alle dateibasierten IDEs auf einmal");
192
+ console.log("\nStandard: globale Config, Token als Referenz (kein Klartext). --project schreibt projektlokal.");
193
+ return;
194
+ }
195
+
196
+ const targets = ideKey === "all" ? Object.keys(IDES) : [ideKey];
197
+ if (ideKey !== "all" && !IDES[ideKey]) {
198
+ throw new Error(`Unbekannte IDE: ${ideKey}. \`knowmind install list\` zeigt alle.`);
199
+ }
200
+ if (literalToken) {
201
+ console.warn("WARNUNG: --token schreibt das Token im KLARTEXT in die Config-Datei(en).\n");
202
+ }
203
+
204
+ const cwd = process.cwd();
205
+ const entryOpts = { apiUrl: apiUrl || DEFAULT_API, literalToken };
206
+
207
+ for (const key of targets) {
208
+ const ide = IDES[key];
209
+
210
+ // Reine Snippet-/GUI-Fälle.
211
+ if (printOnly || (key === "jetbrains") || (key === "claude-code" && !project)) {
212
+ if (key === "claude-code" && !project) {
213
+ printClaudeCodeCommand(entryOpts);
214
+ continue;
215
+ }
216
+ console.log(`# ${ide.label} — Snippet (manuell einfügen):`);
217
+ console.log(JSON.stringify(snippet(ide, entryOpts), null, 2));
218
+ console.log("");
219
+ continue;
220
+ }
221
+
222
+ const path = project ? (ide.projectPath && ide.projectPath(cwd)) : (ide.globalPath && ide.globalPath());
223
+ if (!path) {
224
+ // Kein Datei-Ziel für diesen Scope → Snippet zeigen.
225
+ console.log(`# ${ide.label}: kein ${project ? "Projekt" : "globaler"}-Dateipfad bekannt — Snippet:`);
226
+ console.log(JSON.stringify(snippet(ide, entryOpts), null, 2));
227
+ console.log("");
228
+ continue;
229
+ }
230
+
231
+ const existing = readJsonSafe(path);
232
+ if (existing === null) {
233
+ console.error(`! ${ide.label}: ${path} ist kein gültiges JSON — übersprungen (nicht überschrieben).`);
234
+ continue;
235
+ }
236
+ const merged = mergeInto(existing, ide, entryOpts);
237
+
238
+ if (dryRun) {
239
+ console.log(`# ${ide.label} — DRY RUN → ${path}`);
240
+ console.log(JSON.stringify(merged, null, 2));
241
+ console.log("");
242
+ continue;
243
+ }
244
+
245
+ writeJson(path, merged);
246
+ console.log(`✓ ${ide.label}: knowmind eingetragen in ${path}`);
247
+ if (ide.secret === "env") {
248
+ console.log(` → setze KNOWMIND_TOKEN in deiner Umgebung (oder nutze --token).`);
249
+ } else if (ide.secret === "literal-only" && !literalToken) {
250
+ console.log(` → Platzhalter gesetzt: KNOWMIND_TOKEN in ${path} durch dein Token ersetzen.`);
251
+ } else if (ide.secret === "shell") {
252
+ console.log(` → ${path} nutzt \${KNOWMIND_TOKEN} aus der Umgebung (git-sicher).`);
253
+ }
254
+ }
255
+ }
package/src/mcp-stdio.js CHANGED
@@ -19,6 +19,15 @@
19
19
  * tatsächlichen serverInfo/capabilities den Client erreichen. Bei Server-
20
20
  * Fehler/Offline fällt der Proxy auf einen lokalen Default zurück.
21
21
  *
22
+ * Seit 0.1.22 gibt es einen DISCOVERY-MODUS: Ist KEIN Token konfiguriert,
23
+ * beantwortet der Proxy `initialize`, `tools/list` und `prompts/list` über die
24
+ * ÖFFENTLICHE Server-Discovery (GET {apiUrl}/api/mcp/v1 — liefert Name, Version
25
+ * und alle Tool-Definitionen ohne Auth). Damit funktioniert Introspection
26
+ * (z. B. Verzeichnis-Crawler wie Glama) ohne Account; erst `tools/call`
27
+ * verlangt einen Token und verweist klar auf `knowmind login`. Ein
28
+ * konfigurierter, aber UNGÜLTIGER Token führt weiterhin zum harten
29
+ * Verbindungsfehler, damit MCP-Clients nicht fälschlich „connected" anzeigen.
30
+ *
22
31
  * Protokoll: stdio mit zeilenweise JSON (NDJSON-Style). Jedes Frame ist ein
23
32
  * vollständiges JSON-RPC-Objekt.
24
33
  */
@@ -75,6 +84,20 @@ function write(obj) {
75
84
  process.stdout.write(JSON.stringify(obj) + "\n");
76
85
  }
77
86
 
87
+ /**
88
+ * Öffentliche Server-Discovery (kein Auth nötig): GET {apiUrl}/api/mcp/v1
89
+ * liefert { name, version, protocolVersion, tools: [...] }. Grundlage des
90
+ * Discovery-Modus ohne Token.
91
+ */
92
+ async function fetchPublicDiscovery() {
93
+ const { apiUrl } = loadConfig();
94
+ const r = await fetch(`${apiUrl}/api/mcp/v1`, {
95
+ headers: { accept: "application/json" },
96
+ });
97
+ if (!r.ok) throw new Error(`Knowmind-Server: HTTP ${r.status}`);
98
+ return await r.json();
99
+ }
100
+
78
101
  /**
79
102
  * Probiert den konfigurierten Token gegen den Server. Liefert
80
103
  * { ok: true } oder { ok: false, reason: "..." }. Wird in der
@@ -142,10 +165,30 @@ async function probeAuth() {
142
165
  }
143
166
 
144
167
  export async function runStdioServer() {
145
- // Auth einmal am Start prüfen. Das Ergebnis cachen — der MCP-Client
146
- // soll sofort beim initialize wissen, ob die Verbindung wirklich steht.
147
- const auth = await probeAuth();
148
- if (!auth.ok) {
168
+ // Kein Token konfiguriert → Discovery-Modus: initialize/tools/list laufen
169
+ // über die öffentliche Server-Discovery, tools/call verlangt Login.
170
+ let discoveryMode = false;
171
+ try {
172
+ discoveryMode = !loadConfig().token;
173
+ } catch {
174
+ discoveryMode = true;
175
+ }
176
+
177
+ // Auth einmal am Start prüfen (nur wenn ein Token vorhanden ist). Das
178
+ // Ergebnis cachen — der MCP-Client soll sofort beim initialize wissen,
179
+ // ob die Verbindung wirklich steht.
180
+ const auth = discoveryMode
181
+ ? {
182
+ ok: false,
183
+ reason:
184
+ "Kein Knowmind-Token konfiguriert. Bitte `knowmind login` im Terminal ausführen.",
185
+ }
186
+ : await probeAuth();
187
+ if (discoveryMode) {
188
+ process.stderr.write(
189
+ "[knowmind] Kein Token — Discovery-Modus: initialize/tools/list öffentlich, tools/call erfordert `knowmind login`.\n",
190
+ );
191
+ } else if (!auth.ok) {
149
192
  process.stderr.write(`[knowmind] AUTH-FEHLER: ${auth.reason}\n`);
150
193
  }
151
194
 
@@ -169,6 +212,65 @@ export async function runStdioServer() {
169
212
  const isNotification = req.id === undefined && typeof req.method === "string" && req.method.startsWith("notifications/");
170
213
  if (isNotification) continue;
171
214
 
215
+ if (discoveryMode) {
216
+ if (req.method === "ping") {
217
+ write({ jsonrpc: "2.0", id: req.id ?? null, result: {} });
218
+ continue;
219
+ }
220
+ if (req.method === "initialize") {
221
+ // serverInfo/protocolVersion möglichst aus der öffentlichen
222
+ // Discovery übernehmen; bei Fehler lokaler Default.
223
+ const initResult = localInitializeResult();
224
+ try {
225
+ const pub = await fetchPublicDiscovery();
226
+ if (pub && typeof pub === "object") {
227
+ if (typeof pub.protocolVersion === "string")
228
+ initResult.protocolVersion = pub.protocolVersion;
229
+ initResult.serverInfo = {
230
+ name: "knowmind",
231
+ version:
232
+ typeof pub.version === "string" ? pub.version : VERSION,
233
+ };
234
+ }
235
+ } catch {
236
+ // offline → lokaler Default reicht für initialize.
237
+ }
238
+ write({ jsonrpc: "2.0", id: req.id ?? null, result: initResult });
239
+ continue;
240
+ }
241
+ if (req.method === "tools/list") {
242
+ try {
243
+ const pub = await fetchPublicDiscovery();
244
+ const tools = Array.isArray(pub?.tools) ? pub.tools : [];
245
+ write({ jsonrpc: "2.0", id: req.id ?? null, result: { tools } });
246
+ } catch (e) {
247
+ write({
248
+ jsonrpc: "2.0",
249
+ id: req.id ?? null,
250
+ error: {
251
+ code: -32000,
252
+ message: `Knowmind-Discovery nicht erreichbar: ${e instanceof Error ? e.message : String(e)}`,
253
+ },
254
+ });
255
+ }
256
+ continue;
257
+ }
258
+ if (req.method === "prompts/list") {
259
+ write({ jsonrpc: "2.0", id: req.id ?? null, result: { prompts: [] } });
260
+ continue;
261
+ }
262
+ // tools/call & Co. brauchen einen Token → klare Fehlermeldung.
263
+ write({
264
+ jsonrpc: "2.0",
265
+ id: req.id ?? null,
266
+ error: {
267
+ code: -32001,
268
+ message: `Knowmind: ${auth.reason}`,
269
+ },
270
+ });
271
+ continue;
272
+ }
273
+
172
274
  if (!auth.ok && req.method !== "ping") {
173
275
  // Initialize (und alles weitere) FEHLSCHLAGEN lassen, damit der
174
276
  // MCP-Client „connected" nicht fälschlich anzeigt. Claude Code,