knowmind 0.1.19 → 0.1.20
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 +32 -0
- package/README.md +38 -0
- package/bin/knowmind.js +13 -0
- package/package.json +2 -1
- package/src/init.js +564 -0
- package/src/mcp-stdio.js +52 -10
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,37 @@
|
|
|
1
1
|
# Knowmind CLI — Änderungen
|
|
2
2
|
|
|
3
|
+
## 0.1.20 (2026-06-10)
|
|
4
|
+
|
|
5
|
+
**MCP-`instructions` erreichen jetzt den Client (initialize wird durchgereicht)**
|
|
6
|
+
- `knowmind mcp` beantwortete `initialize` bisher lokal und unterschlug damit das
|
|
7
|
+
serverseitige `instructions`-Feld. Der Proxy fragt `initialize` nun beim Server an und
|
|
8
|
+
übernimmt `serverInfo` (Name/Version aus zentraler Quelle), `capabilities` und
|
|
9
|
+
`instructions` aus der Server-Antwort. Damit liest jeder MCP-Client beim Verbinden die
|
|
10
|
+
Memory-First-Betriebsanweisung des Servers — der client-übergreifende Pflege-Hebel
|
|
11
|
+
OHNE manuelles Setup. Bei Server-Fehler/Offline fällt der Proxy auf den lokalen Default
|
|
12
|
+
zurück (Proxy-Charakter + Offline-Robustheit bleiben).
|
|
13
|
+
- Serverseitig (knowmind.de) liefert das `initialize`-Result jetzt ein `instructions`-Feld
|
|
14
|
+
(Recall-First + proaktives Speichern) sowie `serverInfo.version` aus einer einzigen Quelle.
|
|
15
|
+
|
|
16
|
+
**Neuer Befehl: `knowmind init` — automatische Gedächtnis-Pflege einrichten**
|
|
17
|
+
- `knowmind init [--client claude-code|cursor|auto] [--dry-run]` richtet die
|
|
18
|
+
Memory-First-Automatik im KI-Client des Nutzers ein, ohne manuelles Hook-Gefrickel.
|
|
19
|
+
Client wird am Projekt-/Home-Verzeichnis erkannt (`.claude/`, `.cursor/`, `~/.codex/`)
|
|
20
|
+
oder explizit gewählt.
|
|
21
|
+
- **Claude Code:** schreibt projektlokale Hooks (`UserPromptSubmit` → `knowmind_recall`
|
|
22
|
+
vor jeder Frage; `Stop` → Capture-Reminder, der an `knowmind_store_memory` erinnert,
|
|
23
|
+
wenn die Runde Sicherungswürdiges enthielt) + einen Memory-First-Block in `./CLAUDE.md`.
|
|
24
|
+
Die Hooks reden gegen die Plattform (`npx knowmind search` / die MCP-Tools), nicht
|
|
25
|
+
gegen lokale `.md`-Dateien.
|
|
26
|
+
- **Cursor:** schreibt `.cursor/rules/knowmind.mdc` (Memory-First-Regel, `alwaysApply`).
|
|
27
|
+
- **Claude Desktop / Codex / generisch:** kein Hook-Mechanismus — zeigt den
|
|
28
|
+
Memory-First-Text zum manuellen Einfügen und benennt die ehrliche Grenze (nur
|
|
29
|
+
MCP-instructions + MCP-prompts wirken, keine harte Erzwingung).
|
|
30
|
+
- **Idempotent & nicht-destruktiv:** marker-/befehls-basierte Ersetzung
|
|
31
|
+
(`<!-- BEGIN/END knowmind -->`); zweiter Lauf erzeugt keine Duplikate, fremde Dateien
|
|
32
|
+
und Hooks bleiben unangetastet. `--dry-run` zeigt jede Aktion ohne zu schreiben.
|
|
33
|
+
- Tests in `src/init.test.js` (Idempotenz, Client-Erkennung, dry-run, Marker-Upsert).
|
|
34
|
+
|
|
3
35
|
## 0.1.19 (2026-06-10)
|
|
4
36
|
|
|
5
37
|
**CLI-Befehle repariert (search/stats/health/login)**
|
package/README.md
CHANGED
|
@@ -34,6 +34,7 @@ export KNOWMIND_API_URL=https://knowmind.de
|
|
|
34
34
|
## Befehle
|
|
35
35
|
|
|
36
36
|
```
|
|
37
|
+
knowmind init Automatische Gedächtnis-Pflege im KI-Client einrichten
|
|
37
38
|
knowmind search "Wo läuft die OKR-App?"
|
|
38
39
|
knowmind upload notizen.md --title "Meeting Notizen 2026-05-12"
|
|
39
40
|
knowmind stats
|
|
@@ -41,6 +42,43 @@ knowmind health
|
|
|
41
42
|
knowmind config
|
|
42
43
|
```
|
|
43
44
|
|
|
45
|
+
## Automatische Pflege einrichten (`knowmind init`)
|
|
46
|
+
|
|
47
|
+
Damit Ihre KI knowmind selbsttätig pflegt — **Recall vor jeder Aufgabe**, **Sichern nach
|
|
48
|
+
jeder sicherungswürdigen Runde** — richtet `knowmind init` die passenden Mechanismen für
|
|
49
|
+
Ihren Client ein. Der Befehl erkennt den Client am Projekt- und Home-Verzeichnis
|
|
50
|
+
(`.claude/`, `.cursor/`, `~/.codex/`) oder Sie wählen ihn explizit.
|
|
51
|
+
|
|
52
|
+
```
|
|
53
|
+
knowmind init # Client automatisch erkennen
|
|
54
|
+
knowmind init --client claude-code # gezielt für Claude Code
|
|
55
|
+
knowmind init --client cursor # gezielt für Cursor
|
|
56
|
+
knowmind init --dry-run # zeigt nur, was geschähe (schreibt nichts)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
**Was eingerichtet wird:**
|
|
60
|
+
|
|
61
|
+
- **Claude Code** — projektlokale Hooks in `.claude/`:
|
|
62
|
+
- *UserPromptSubmit* → ruft vor jeder echten Frage `knowmind_recall` auf und reicht die
|
|
63
|
+
Top-Treffer als Kontext nach (Memory-First, automatisch).
|
|
64
|
+
- *Stop* → erinnert die KI daran, mit `knowmind_store_memory` zu sichern, wenn die Runde
|
|
65
|
+
Sicherungswürdiges enthielt (Deploy/Commit, neue Regel, Entscheidung) und noch nichts
|
|
66
|
+
gespeichert wurde.
|
|
67
|
+
- ein **Memory-First-Block** in `./CLAUDE.md` (mit `<!-- BEGIN/END knowmind -->`-Markern).
|
|
68
|
+
- **Cursor** — `.cursor/rules/knowmind.mdc` mit der Memory-First-Regel (`alwaysApply`).
|
|
69
|
+
- **Claude Desktop / Codex / generisch** — kein automatischer Hook-Mechanismus vorhanden;
|
|
70
|
+
der Befehl zeigt den Memory-First-Text zum manuellen Einfügen (siehe Grenze unten).
|
|
71
|
+
|
|
72
|
+
**Idempotent & nicht-destruktiv:** Ein zweiter Lauf erzeugt keine Duplikate
|
|
73
|
+
(marker-/befehls-basierte Ersetzung); bestehende fremde Dateien und Hooks bleiben
|
|
74
|
+
unangetastet. Mit `--dry-run` sehen Sie jede Aktion vorab.
|
|
75
|
+
|
|
76
|
+
> **Ehrliche Grenze:** Eine *harte* Erzwingung der Pflege gibt es nur in Clients mit
|
|
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.
|
|
81
|
+
|
|
44
82
|
## MCP-Server einrichten
|
|
45
83
|
|
|
46
84
|
knowmind ist ein MCP-Server (`npx -y knowmind mcp`, stdio). Token aus dem knowmind.de-Dashboard
|
package/bin/knowmind.js
CHANGED
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
import { loadConfig, saveConfig, configPath, VERSION } from "../src/config.js";
|
|
24
24
|
import { runStdioServer } from "../src/mcp-stdio.js";
|
|
25
25
|
import { syncDirectory } from "../src/sync.js";
|
|
26
|
+
import { runInit } from "../src/init.js";
|
|
26
27
|
|
|
27
28
|
const args = process.argv.slice(2);
|
|
28
29
|
const cmd = args[0];
|
|
@@ -49,6 +50,9 @@ Knowmind ${VERSION} — Das Gedächtnis für Ihre KI
|
|
|
49
50
|
Befehle:
|
|
50
51
|
knowmind login [--token kmt_TOKEN] [--api https://knowmind.de]
|
|
51
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.
|
|
52
56
|
knowmind config Aktuelle Konfiguration anzeigen
|
|
53
57
|
knowmind search "Frage" [-k 5] [--hops 2]
|
|
54
58
|
Hybrid-Recall gegen den Tenant-Korpus
|
|
@@ -180,6 +184,12 @@ async function runConfig() {
|
|
|
180
184
|
console.log(`Token: ${c.token ? c.token.slice(0, 12) + "…" : "(keiner)"}`);
|
|
181
185
|
}
|
|
182
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
|
+
|
|
183
193
|
// Wichtig: `process.exit(N)` reißt offene Sockets/fetch-Verbindungen mit
|
|
184
194
|
// rein und triggert auf Windows/Node 22 die libuv-Assertion
|
|
185
195
|
// `!(handle->flags & UV_HANDLE_CLOSING)`. Stattdessen `exitCode` setzen
|
|
@@ -211,6 +221,9 @@ try {
|
|
|
211
221
|
case "mcp":
|
|
212
222
|
await runStdioServer();
|
|
213
223
|
break;
|
|
224
|
+
case "init":
|
|
225
|
+
await runInitCmd();
|
|
226
|
+
break;
|
|
214
227
|
case "--help":
|
|
215
228
|
case "-h":
|
|
216
229
|
case "help":
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "knowmind",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.20",
|
|
4
4
|
"mcpName": "io.github.Schubeler-Consulting/knowmind",
|
|
5
5
|
"description": "Knowmind — das Agentengehirn aus Deutschland: CLI + MCP-Server (Langzeitgedächtnis & Wissensgraph für Ihre KI, Server in Deutschland).",
|
|
6
6
|
"type": "module",
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
"files": [
|
|
29
29
|
"bin",
|
|
30
30
|
"src",
|
|
31
|
+
"!src/*.test.js",
|
|
31
32
|
"README.md",
|
|
32
33
|
"CHANGELOG.md",
|
|
33
34
|
"LICENSE"
|
package/src/init.js
ADDED
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `knowmind init` — client-aware Onboarding.
|
|
3
|
+
*
|
|
4
|
+
* Richtet die AUTOMATISCHE Gedächtnis-Pflege im erkannten KI-Client ein, damit
|
|
5
|
+
* die Kunden-KI knowmind ohne manuelles Hook-Gefrickel pflegt:
|
|
6
|
+
*
|
|
7
|
+
* - Claude Code: schreibt projektlokale Hooks (UserPromptSubmit -> Recall-Hint
|
|
8
|
+
* via knowmind_recall; Stop -> Capture-Reminder, der an knowmind_store_memory
|
|
9
|
+
* erinnert, wenn die Runde Sicherungswürdiges enthielt) und einen
|
|
10
|
+
* Memory-First-Block in ./CLAUDE.md (idempotent, BEGIN/END-Marker).
|
|
11
|
+
* - Cursor: schreibt .cursor/rules/knowmind.mdc mit der Memory-First-Regel.
|
|
12
|
+
* - generisch / Claude Desktop: erklärt, dass die MCP-instructions automatisch
|
|
13
|
+
* wirken, und zeigt den manuellen Memory-First-Text zum Einfügen.
|
|
14
|
+
*
|
|
15
|
+
* Garantien:
|
|
16
|
+
* - IDEMPOTENT: zweiter Lauf erzeugt keine Duplikate. Eingefügte Blöcke werden
|
|
17
|
+
* mit BEGIN/END-knowmind-Markern umschlossen und beim erneuten Lauf ersetzt,
|
|
18
|
+
* nie ein zweites Mal angehängt.
|
|
19
|
+
* - NICHT-DESTRUKTIV: ohne Marker wird keine fremde Datei überschrieben; eigene
|
|
20
|
+
* Dateien (Hook-Skripte, .mdc) werden nur ge-/überschrieben, wenn sie einen
|
|
21
|
+
* knowmind-Marker tragen ODER neu sind.
|
|
22
|
+
* - --dry-run zeigt jede Aktion, schreibt aber nichts.
|
|
23
|
+
*
|
|
24
|
+
* Die Hooks rufen NICHT lokale .md-Dateien an (das ist der interne SC-Weg),
|
|
25
|
+
* sondern reden gegen die Plattform: `npx knowmind search` für Recall.
|
|
26
|
+
* Token/apiUrl kommen aus der knowmind-Config (~/.knowmind/config.json) bzw. ENV.
|
|
27
|
+
*/
|
|
28
|
+
import {
|
|
29
|
+
existsSync,
|
|
30
|
+
readFileSync,
|
|
31
|
+
writeFileSync,
|
|
32
|
+
mkdirSync,
|
|
33
|
+
chmodSync,
|
|
34
|
+
} from "node:fs";
|
|
35
|
+
import { homedir, platform } from "node:os";
|
|
36
|
+
import { join, resolve, dirname } from "node:path";
|
|
37
|
+
import { loadConfig, VERSION } from "./config.js";
|
|
38
|
+
|
|
39
|
+
// ─── Marker (für idempotente Block-Ersetzung) ────────────────────────
|
|
40
|
+
const BEGIN = "<!-- BEGIN knowmind -->";
|
|
41
|
+
const END = "<!-- END knowmind -->";
|
|
42
|
+
const BEGIN_HASH = "# >>> BEGIN knowmind >>>";
|
|
43
|
+
const END_HASH = "# <<< END knowmind <<<";
|
|
44
|
+
|
|
45
|
+
// ─── Memory-First-Text (Kunden-Variante, gegen die Plattform) ────────
|
|
46
|
+
// Bewusst kurz und client-neutral. Verweist auf die MCP-Tools, die der
|
|
47
|
+
// knowmind-MCP-Server bereitstellt (knowmind_recall / knowmind_store_memory).
|
|
48
|
+
function memoryFirstBlock() {
|
|
49
|
+
return [
|
|
50
|
+
BEGIN,
|
|
51
|
+
"## knowmind — automatische Gedächtnis-Pflege",
|
|
52
|
+
"",
|
|
53
|
+
"Dieses Projekt nutzt **knowmind** (Langzeitgedächtnis & Wissensgraph) als MCP-Server.",
|
|
54
|
+
"Halte dich an die Memory-First-Regel:",
|
|
55
|
+
"",
|
|
56
|
+
"1. **Recall zuerst.** Bevor du eine inhaltliche Frage beantwortest oder eine",
|
|
57
|
+
" Aufgabe planst, rufe `knowmind_recall` (oder `knowmind search`) auf und prüfe,",
|
|
58
|
+
" ob es bereits relevantes Wissen gibt. Erst danach Dateien lesen/Web suchen.",
|
|
59
|
+
"2. **Wissen sichern.** Wenn eine Runde etwas Sicherungswürdiges hervorbringt —",
|
|
60
|
+
" eine Entscheidung, eine neue Regel, ein Ergebnis, ein Fakt über Personen/",
|
|
61
|
+
" Projekte/Systeme — lege es mit `knowmind_store_memory` (Titel + Inhalt) ab,",
|
|
62
|
+
" bevor du fortfährst. Reine Recherche oder Wegwerf-Tests müssen nicht gesichert werden.",
|
|
63
|
+
"3. **Beziehungen pflegen.** Verknüpfe zusammengehörige Erinnerungen mit",
|
|
64
|
+
" `knowmind_link`, damit der Graph nutzbar bleibt.",
|
|
65
|
+
"",
|
|
66
|
+
"Das Gedächtnis lebt auf der knowmind-Plattform (Server in Deutschland), nicht in",
|
|
67
|
+
"lokalen Dateien. Es ist über Sessions und Clients hinweg dasselbe Gehirn.",
|
|
68
|
+
END,
|
|
69
|
+
].join("\n");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ─── Generischer Hinweis-Text (manuell einfügbar) ────────────────────
|
|
73
|
+
function manualSnippet() {
|
|
74
|
+
return memoryFirstBlock();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ─── Datei-Helfer ────────────────────────────────────────────────────
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Fügt einen marker-umschlossenen Block in eine Textdatei ein bzw. ersetzt
|
|
81
|
+
* einen bereits vorhandenen. Liefert { action, content } ohne zu schreiben.
|
|
82
|
+
* action: "create" | "replace" | "append" | "unchanged"
|
|
83
|
+
*/
|
|
84
|
+
function upsertMarkedBlock(filePath, block, { begin = BEGIN, end = END } = {}) {
|
|
85
|
+
const existed = existsSync(filePath);
|
|
86
|
+
const current = existed ? readFileSync(filePath, "utf-8") : "";
|
|
87
|
+
|
|
88
|
+
// Bereits ein Block vorhanden? -> ersetzen.
|
|
89
|
+
const bi = current.indexOf(begin);
|
|
90
|
+
const ei = current.indexOf(end);
|
|
91
|
+
if (bi !== -1 && ei !== -1 && ei > bi) {
|
|
92
|
+
const before = current.slice(0, bi);
|
|
93
|
+
const after = current.slice(ei + end.length);
|
|
94
|
+
const next = (before + block + after).replace(/\n{3,}/g, "\n\n");
|
|
95
|
+
if (next === current) return { action: "unchanged", content: current };
|
|
96
|
+
return { action: "replace", content: next };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Kein Block -> anhängen (oder Datei neu).
|
|
100
|
+
if (!existed) {
|
|
101
|
+
return { action: "create", content: block + "\n" };
|
|
102
|
+
}
|
|
103
|
+
const sep = current.endsWith("\n") ? "\n" : "\n\n";
|
|
104
|
+
return { action: "append", content: current + sep + block + "\n" };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Schreibt eine eigene knowmind-Datei nur, wenn neu ODER marker-getragen. */
|
|
108
|
+
function writeOwnFile(filePath, content, marker) {
|
|
109
|
+
if (existsSync(filePath)) {
|
|
110
|
+
const cur = readFileSync(filePath, "utf-8");
|
|
111
|
+
if (!cur.includes(marker)) {
|
|
112
|
+
return { action: "skip-foreign", reason: "Datei existiert ohne knowmind-Marker" };
|
|
113
|
+
}
|
|
114
|
+
if (cur === content) return { action: "unchanged" };
|
|
115
|
+
return { action: "overwrite", content };
|
|
116
|
+
}
|
|
117
|
+
return { action: "create", content };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ─── Client-Erkennung ────────────────────────────────────────────────
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Erkennt den/die wahrscheinlichen Client(s) anhand von Projekt- und
|
|
124
|
+
* Home-Verzeichnis. Liefert eine Liste, weil mehrere zugleich plausibel sind.
|
|
125
|
+
*/
|
|
126
|
+
export function detectClients(cwd, home) {
|
|
127
|
+
const found = new Set();
|
|
128
|
+
// Claude Code: projektlokales .claude/ ODER globale ~/.claude.json / ~/.claude
|
|
129
|
+
if (existsSync(join(cwd, ".claude"))) found.add("claude-code");
|
|
130
|
+
if (existsSync(join(home, ".claude.json")) || existsSync(join(home, ".claude")))
|
|
131
|
+
found.add("claude-code");
|
|
132
|
+
// Cursor: projektlokales .cursor/ ODER globale ~/.cursor
|
|
133
|
+
if (existsSync(join(cwd, ".cursor"))) found.add("cursor");
|
|
134
|
+
if (existsSync(join(home, ".cursor"))) found.add("cursor");
|
|
135
|
+
// Codex CLI
|
|
136
|
+
if (existsSync(join(home, ".codex", "config.toml"))) found.add("codex");
|
|
137
|
+
return [...found];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ─── Hook-Skripte (Claude-Code-Vorlage, gegen die Plattform) ─────────
|
|
141
|
+
// Reines Node, keine externen Deps — laufen über `node`. Sie rufen die CLI
|
|
142
|
+
// per `npx -y knowmind ...` bzw. direkt die Bearer-API, ohne SC-spezifische
|
|
143
|
+
// Pfade. Token/apiUrl über ENV oder ~/.knowmind/config.json.
|
|
144
|
+
|
|
145
|
+
function autoRecallHookSource() {
|
|
146
|
+
return `#!/usr/bin/env node
|
|
147
|
+
// >>> knowmind auto-recall hook (UserPromptSubmit)
|
|
148
|
+
// Erzeugt von: knowmind init. Idempotent ersetzbar (trägt diesen Marker).
|
|
149
|
+
//
|
|
150
|
+
// Ruft vor jeder echten Frage knowmind_recall auf und injiziert die Top-Treffer
|
|
151
|
+
// als zusätzlichen Kontext (stdout). Fail-open: jeder Fehler -> exit 0 ohne Block.
|
|
152
|
+
import { spawnSync } from "node:child_process";
|
|
153
|
+
|
|
154
|
+
const TRIVIAL = new Set([
|
|
155
|
+
"ok","okay","go","ja","nein","weiter","stop","danke","thanks","thx",
|
|
156
|
+
"yes","no","yep","nope","perfekt","passt","super","gut",
|
|
157
|
+
]);
|
|
158
|
+
const TRIGGER = [
|
|
159
|
+
"kunde","kunden","projekt","tool","server","domain","wer ist","was ist",
|
|
160
|
+
"welche","liste","übersicht","status","wo ","wann","wieso","warum",
|
|
161
|
+
"recherche","research","info zu","infos zu","memory","graph","datenbank",
|
|
162
|
+
];
|
|
163
|
+
|
|
164
|
+
function shouldRecall(p) {
|
|
165
|
+
const s = (p || "").trim().toLowerCase();
|
|
166
|
+
if (s.length < 8) return false;
|
|
167
|
+
if (TRIVIAL.has(s)) return false;
|
|
168
|
+
if (s.startsWith("/")) return false;
|
|
169
|
+
if (TRIGGER.some((k) => s.includes(k))) return true;
|
|
170
|
+
if (s.endsWith("?")) return true;
|
|
171
|
+
return s.length >= 40;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function main() {
|
|
175
|
+
let raw = "";
|
|
176
|
+
process.stdin.setEncoding("utf-8");
|
|
177
|
+
for await (const c of process.stdin) raw += c;
|
|
178
|
+
let prompt = "";
|
|
179
|
+
try {
|
|
180
|
+
const data = raw ? JSON.parse(raw) : {};
|
|
181
|
+
prompt = data.prompt || data.user_prompt || data.user_message || "";
|
|
182
|
+
} catch { return; }
|
|
183
|
+
if (!shouldRecall(prompt)) return;
|
|
184
|
+
|
|
185
|
+
const query = prompt.trim().slice(0, 500);
|
|
186
|
+
const r = spawnSync(
|
|
187
|
+
process.platform === "win32" ? "npx.cmd" : "npx",
|
|
188
|
+
["-y", "knowmind", "search", query, "-k", "5", "--hops", "2"],
|
|
189
|
+
{ encoding: "utf-8", timeout: 8000, env: process.env }
|
|
190
|
+
);
|
|
191
|
+
const out = (r.stdout || "").trim();
|
|
192
|
+
if (!out || /Keine Treffer/.test(out)) return;
|
|
193
|
+
|
|
194
|
+
process.stdout.write(
|
|
195
|
+
"═════════ knowmind RECALL (auto) ═════════\\n" +
|
|
196
|
+
out + "\\n" +
|
|
197
|
+
"Diese Treffer wurden automatisch vor deiner Antwort abgerufen.\\n" +
|
|
198
|
+
"Erst hier prüfen, dann Dateien lesen / Web suchen.\\n" +
|
|
199
|
+
"══════════════════════════════════════════\\n"
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
main().catch(() => process.exit(0));
|
|
204
|
+
// <<< knowmind auto-recall hook
|
|
205
|
+
`;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function captureGateHookSource() {
|
|
209
|
+
return `#!/usr/bin/env node
|
|
210
|
+
// >>> knowmind capture-gate hook (Stop)
|
|
211
|
+
// Erzeugt von: knowmind init. Idempotent ersetzbar (trägt diesen Marker).
|
|
212
|
+
//
|
|
213
|
+
// Prüft nach jeder Antwort, ob die Runde Sicherungswürdiges enthielt
|
|
214
|
+
// (Code-/Config-Änderung, Deploy/Commit, neue Regel/Entscheidung) UND ob ein
|
|
215
|
+
// knowmind_store_memory aufgerufen wurde. Wenn nicht -> {"decision":"block"},
|
|
216
|
+
// damit die KI vor dem Stoppen eine Erinnerung ablegt.
|
|
217
|
+
// Rein heuristisch (kein LLM). Loop-Schutz via stop_hook_active. Fail-open.
|
|
218
|
+
import { readFileSync } from "node:fs";
|
|
219
|
+
|
|
220
|
+
const DEPLOY = /\\b(git\\s+commit|git\\s+push|docker\\s+compose[^\\n]*\\bup\\b|docker\\s+build|deploy|scp|rsync|npm\\s+publish|kubectl\\s+apply)\\b/i;
|
|
221
|
+
const RULE = /(ab sofort|ab jetzt|von nun an|merk(e)? dir|neue regel|regel:|harte regel|standing order|niemals wieder|nie wieder)/i;
|
|
222
|
+
const ARCH = /(architektur-?entscheid|\\bADR\\b|wir stellen um|grundsatzentscheidung|wir migrieren auf|umstellung auf|wir setzen auf)/i;
|
|
223
|
+
const CODE_EXT = [".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".php",".go",".rs",".java",".rb",".css",".scss",".html",".vue",".svelte",".json",".yml",".yaml",".toml",".prisma",".sql",".sh",".ps1"];
|
|
224
|
+
const STORE_HINTS = ["knowmind_store","store_memory","update_fact","knowmind_update_fact"];
|
|
225
|
+
|
|
226
|
+
function isUserMsg(e) {
|
|
227
|
+
if (e.type !== "user") return false;
|
|
228
|
+
const c = e.message?.content;
|
|
229
|
+
if (typeof c === "string") return !!c.trim();
|
|
230
|
+
if (Array.isArray(c)) {
|
|
231
|
+
const text = c.some((b) => b?.type === "text");
|
|
232
|
+
const tr = c.some((b) => b?.type === "tool_result");
|
|
233
|
+
return text && !tr;
|
|
234
|
+
}
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
function userText(e) {
|
|
238
|
+
const c = e.message?.content;
|
|
239
|
+
if (typeof c === "string") return c;
|
|
240
|
+
if (Array.isArray(c)) return c.filter((b) => b?.type === "text").map((b) => b.text || "").join(" ");
|
|
241
|
+
return "";
|
|
242
|
+
}
|
|
243
|
+
function collectRound(path) {
|
|
244
|
+
const lines = readFileSync(path, "utf-8").split(/\\r?\\n/).filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
|
|
245
|
+
let start = 0;
|
|
246
|
+
for (let i = lines.length - 1; i >= 0; i--) if (isUserMsg(lines[i])) { start = i; break; }
|
|
247
|
+
const utext = lines.length ? userText(lines[start]) : "";
|
|
248
|
+
const tools = [];
|
|
249
|
+
for (const e of lines.slice(start)) {
|
|
250
|
+
if (e.type !== "assistant") continue;
|
|
251
|
+
const c = e.message?.content;
|
|
252
|
+
if (Array.isArray(c)) for (const b of c) if (b?.type === "tool_use") tools.push(b);
|
|
253
|
+
}
|
|
254
|
+
return { utext, tools };
|
|
255
|
+
}
|
|
256
|
+
function hasStore(tools) {
|
|
257
|
+
for (const t of tools) {
|
|
258
|
+
const n = (t.name || "").toLowerCase();
|
|
259
|
+
if (STORE_HINTS.some((h) => n.includes(h))) return true;
|
|
260
|
+
}
|
|
261
|
+
return false;
|
|
262
|
+
}
|
|
263
|
+
function detect(utext, tools) {
|
|
264
|
+
const sig = [];
|
|
265
|
+
for (const t of tools) if (t.name === "Bash" && DEPLOY.test((t.input?.command) || "")) { sig.push("Deploy/Commit"); break; }
|
|
266
|
+
for (const t of tools) {
|
|
267
|
+
if (["Write","Edit","MultiEdit"].includes(t.name)) {
|
|
268
|
+
const fp = (t.input?.file_path || "").toLowerCase();
|
|
269
|
+
if (fp && CODE_EXT.some((x) => fp.endsWith(x))) { sig.push("Code-/Config-Änderung"); break; }
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (RULE.test(utext)) sig.push("neue Regel/Standing Order");
|
|
273
|
+
if (ARCH.test(utext)) sig.push("Architektur-Entscheidung");
|
|
274
|
+
return [...new Set(sig)];
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function main() {
|
|
278
|
+
let raw = "";
|
|
279
|
+
process.stdin.setEncoding("utf-8");
|
|
280
|
+
for await (const c of process.stdin) raw += c;
|
|
281
|
+
let data = {};
|
|
282
|
+
try { data = raw ? JSON.parse(raw) : {}; } catch { return; }
|
|
283
|
+
if (data.stop_hook_active) return; // Loop-Schutz
|
|
284
|
+
const tp = data.transcript_path;
|
|
285
|
+
if (!tp) return;
|
|
286
|
+
let round;
|
|
287
|
+
try { round = collectRound(tp); } catch { return; }
|
|
288
|
+
if (hasStore(round.tools)) return; // schon gesichert
|
|
289
|
+
const sig = detect(round.utext, round.tools);
|
|
290
|
+
if (!sig.length) return; // nichts Sicherungswürdiges
|
|
291
|
+
|
|
292
|
+
const reason =
|
|
293
|
+
"STOP-GATE (knowmind): Diese Runde enthielt Sicherungswürdiges (" + sig.join(", ") + "), " +
|
|
294
|
+
"aber es wurde kein knowmind_store_memory aufgerufen.\\n" +
|
|
295
|
+
"Bevor du stoppst: lege das Ergebnis mit knowmind_store_memory ab (Titel + Inhalt) " +
|
|
296
|
+
"und verknüpfe es ggf. mit knowmind_link. Ist der Vorgang wirklich nicht " +
|
|
297
|
+
"sicherungswürdig (reine Recherche, Wegwerf-Test), begründe es in einem Satz, dann stoppe.";
|
|
298
|
+
process.stdout.write(JSON.stringify({ decision: "block", reason }));
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
main().catch(() => process.exit(0));
|
|
302
|
+
// <<< knowmind capture-gate hook
|
|
303
|
+
`;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// ─── Cursor-Rule (.mdc) ──────────────────────────────────────────────
|
|
307
|
+
function cursorRuleSource() {
|
|
308
|
+
return `---
|
|
309
|
+
description: knowmind — Memory-First-Regel (automatisches Langzeitgedächtnis)
|
|
310
|
+
alwaysApply: true
|
|
311
|
+
---
|
|
312
|
+
${BEGIN}
|
|
313
|
+
# knowmind — automatische Gedächtnis-Pflege
|
|
314
|
+
|
|
315
|
+
Dieses Projekt nutzt **knowmind** (Langzeitgedächtnis & Wissensgraph) als MCP-Server.
|
|
316
|
+
|
|
317
|
+
1. **Recall zuerst.** Bevor du eine inhaltliche Frage beantwortest oder eine Aufgabe
|
|
318
|
+
planst, rufe \`knowmind_recall\` auf und prüfe, ob bereits relevantes Wissen vorliegt.
|
|
319
|
+
Erst danach Dateien lesen / Web suchen.
|
|
320
|
+
2. **Wissen sichern.** Bringt eine Runde Sicherungswürdiges hervor (Entscheidung, neue
|
|
321
|
+
Regel, Ergebnis, Fakt über Personen/Projekte/Systeme), lege es mit
|
|
322
|
+
\`knowmind_store_memory\` ab, bevor du fortfährst.
|
|
323
|
+
3. **Beziehungen pflegen.** Verknüpfe zusammengehörige Erinnerungen mit \`knowmind_link\`.
|
|
324
|
+
|
|
325
|
+
Das Gedächtnis lebt auf der knowmind-Plattform (Server in Deutschland), nicht in lokalen
|
|
326
|
+
Dateien — über Sessions und Clients hinweg dasselbe Gehirn.
|
|
327
|
+
${END}
|
|
328
|
+
`;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// ─── Claude-settings.json: Hook-Registrierung (idempotent) ───────────
|
|
332
|
+
|
|
333
|
+
function ensureClaudeHookEntry(settings, eventName, scriptRel) {
|
|
334
|
+
// settings.hooks[eventName] ist ein Array von { matcher?, hooks: [{type,command}] }.
|
|
335
|
+
// Wir registrieren genau EINEN knowmind-Eintrag pro Event, marker-erkennbar am command.
|
|
336
|
+
const cmd = `node "${scriptRel}"`;
|
|
337
|
+
settings.hooks = settings.hooks || {};
|
|
338
|
+
const arr = settings.hooks[eventName] || [];
|
|
339
|
+
// Existierenden knowmind-Eintrag finden (command enthält den Skriptnamen).
|
|
340
|
+
const scriptName = scriptRel.split(/[\\/]/).pop();
|
|
341
|
+
let mutated = false;
|
|
342
|
+
let present = false;
|
|
343
|
+
for (const group of arr) {
|
|
344
|
+
for (const h of group.hooks || []) {
|
|
345
|
+
if (typeof h.command === "string" && h.command.includes(scriptName)) {
|
|
346
|
+
present = true;
|
|
347
|
+
if (h.command !== cmd) {
|
|
348
|
+
h.command = cmd;
|
|
349
|
+
mutated = true;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
if (!present) {
|
|
355
|
+
arr.push({ hooks: [{ type: "command", command: cmd }] });
|
|
356
|
+
mutated = true;
|
|
357
|
+
}
|
|
358
|
+
settings.hooks[eventName] = arr;
|
|
359
|
+
return mutated;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// ─── Plan-Bauer pro Client ───────────────────────────────────────────
|
|
363
|
+
// Jeder Eintrag: { path, kind, render() -> {action, content?} oder Info }
|
|
364
|
+
|
|
365
|
+
function planClaudeCode(cwd) {
|
|
366
|
+
const actions = [];
|
|
367
|
+
const hooksDir = join(cwd, ".claude", "hooks");
|
|
368
|
+
const recallPath = join(hooksDir, "knowmind_recall.mjs");
|
|
369
|
+
const capturePath = join(hooksDir, "knowmind_capture.mjs");
|
|
370
|
+
const settingsPath = join(cwd, ".claude", "settings.json");
|
|
371
|
+
const claudeMdPath = join(cwd, "CLAUDE.md");
|
|
372
|
+
|
|
373
|
+
// 1) Recall-Hook
|
|
374
|
+
const recallSrc = autoRecallHookSource();
|
|
375
|
+
actions.push({
|
|
376
|
+
label: "Claude-Code Recall-Hook",
|
|
377
|
+
path: recallPath,
|
|
378
|
+
...writeOwnFile(recallPath, recallSrc, ">>> knowmind auto-recall hook"),
|
|
379
|
+
content: recallSrc,
|
|
380
|
+
_own: true,
|
|
381
|
+
_exec: true,
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
// 2) Capture-Gate-Hook
|
|
385
|
+
const captureSrc = captureGateHookSource();
|
|
386
|
+
actions.push({
|
|
387
|
+
label: "Claude-Code Capture-Gate-Hook",
|
|
388
|
+
path: capturePath,
|
|
389
|
+
...writeOwnFile(capturePath, captureSrc, ">>> knowmind capture-gate hook"),
|
|
390
|
+
content: captureSrc,
|
|
391
|
+
_own: true,
|
|
392
|
+
_exec: true,
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
// 3) settings.json — Hooks registrieren
|
|
396
|
+
let settings = {};
|
|
397
|
+
if (existsSync(settingsPath)) {
|
|
398
|
+
try {
|
|
399
|
+
settings = JSON.parse(readFileSync(settingsPath, "utf-8"));
|
|
400
|
+
} catch {
|
|
401
|
+
settings = { _parseError: true };
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
if (settings._parseError) {
|
|
405
|
+
actions.push({
|
|
406
|
+
label: "Claude-Code settings.json",
|
|
407
|
+
path: settingsPath,
|
|
408
|
+
action: "skip-foreign",
|
|
409
|
+
reason: "settings.json ist kein gültiges JSON — bitte Hooks manuell eintragen",
|
|
410
|
+
});
|
|
411
|
+
} else {
|
|
412
|
+
const relRecall = ".claude/hooks/knowmind_recall.mjs";
|
|
413
|
+
const relCapture = ".claude/hooks/knowmind_capture.mjs";
|
|
414
|
+
const m1 = ensureClaudeHookEntry(settings, "UserPromptSubmit", relRecall);
|
|
415
|
+
const m2 = ensureClaudeHookEntry(settings, "Stop", relCapture);
|
|
416
|
+
actions.push({
|
|
417
|
+
label: "Claude-Code settings.json (Hook-Registrierung)",
|
|
418
|
+
path: settingsPath,
|
|
419
|
+
action: m1 || m2 ? (existsSync(settingsPath) ? "patch" : "create") : "unchanged",
|
|
420
|
+
content: JSON.stringify(settings, null, 2) + "\n",
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// 4) CLAUDE.md — Memory-First-Block
|
|
425
|
+
const md = upsertMarkedBlock(claudeMdPath, memoryFirstBlock());
|
|
426
|
+
actions.push({
|
|
427
|
+
label: "CLAUDE.md (Memory-First-Block)",
|
|
428
|
+
path: claudeMdPath,
|
|
429
|
+
action: md.action,
|
|
430
|
+
content: md.content,
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
return actions;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function planCursor(cwd) {
|
|
437
|
+
const rulePath = join(cwd, ".cursor", "rules", "knowmind.mdc");
|
|
438
|
+
const src = cursorRuleSource();
|
|
439
|
+
return [
|
|
440
|
+
{
|
|
441
|
+
label: "Cursor-Rule .cursor/rules/knowmind.mdc",
|
|
442
|
+
path: rulePath,
|
|
443
|
+
...writeOwnFile(rulePath, src, BEGIN),
|
|
444
|
+
content: src,
|
|
445
|
+
_own: true,
|
|
446
|
+
},
|
|
447
|
+
];
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// ─── Ausführung ──────────────────────────────────────────────────────
|
|
451
|
+
|
|
452
|
+
function applyAction(a) {
|
|
453
|
+
if (!a.action || ["unchanged", "skip-foreign"].includes(a.action)) return;
|
|
454
|
+
if (a.content == null) return;
|
|
455
|
+
mkdirSync(dirname(a.path), { recursive: true });
|
|
456
|
+
writeFileSync(a.path, a.content, "utf-8");
|
|
457
|
+
if (a._exec && platform() !== "win32") {
|
|
458
|
+
try {
|
|
459
|
+
chmodSync(a.path, 0o755);
|
|
460
|
+
} catch {
|
|
461
|
+
/* best effort */
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const ICON = {
|
|
467
|
+
create: "+",
|
|
468
|
+
replace: "~",
|
|
469
|
+
overwrite: "~",
|
|
470
|
+
patch: "~",
|
|
471
|
+
append: "~",
|
|
472
|
+
unchanged: "=",
|
|
473
|
+
"skip-foreign": "!",
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Haupteinstieg. options: { client, dryRun, cwd, home }
|
|
478
|
+
*/
|
|
479
|
+
export async function runInit({ client = "auto", dryRun = false, cwd = process.cwd(), home = homedir() } = {}) {
|
|
480
|
+
const cfg = loadConfig();
|
|
481
|
+
const lines = [];
|
|
482
|
+
lines.push(`knowmind init ${VERSION}${dryRun ? " (dry-run — es wird NICHTS geschrieben)" : ""}`);
|
|
483
|
+
lines.push(`Projekt: ${resolve(cwd)}`);
|
|
484
|
+
lines.push(`Plattform: ${cfg.apiUrl}${cfg.token ? " (Token konfiguriert)" : " (KEIN Token — `knowmind login` zuerst!)"}`);
|
|
485
|
+
lines.push("");
|
|
486
|
+
|
|
487
|
+
// Client wählen
|
|
488
|
+
let target = client;
|
|
489
|
+
if (client === "auto") {
|
|
490
|
+
const detected = detectClients(cwd, home);
|
|
491
|
+
if (detected.length === 0) {
|
|
492
|
+
target = "generic";
|
|
493
|
+
lines.push("Kein Client automatisch erkannt — generische Anleitung.");
|
|
494
|
+
} else if (detected.length === 1) {
|
|
495
|
+
target = detected[0];
|
|
496
|
+
lines.push(`Erkannter Client: ${target}`);
|
|
497
|
+
} else {
|
|
498
|
+
// Mehrere -> alle einrichten, klar ausweisen.
|
|
499
|
+
target = detected;
|
|
500
|
+
lines.push(`Erkannte Clients: ${detected.join(", ")} — alle werden eingerichtet.`);
|
|
501
|
+
}
|
|
502
|
+
} else {
|
|
503
|
+
lines.push(`Client (explizit): ${client}`);
|
|
504
|
+
}
|
|
505
|
+
lines.push("");
|
|
506
|
+
|
|
507
|
+
const targets = Array.isArray(target) ? target : [target];
|
|
508
|
+
const allActions = [];
|
|
509
|
+
for (const t of targets) {
|
|
510
|
+
if (t === "claude-code") allActions.push(...planClaudeCode(cwd));
|
|
511
|
+
else if (t === "cursor") allActions.push(...planCursor(cwd));
|
|
512
|
+
else {
|
|
513
|
+
// generic / claude-desktop / codex und alles ohne Hook-Mechanismus.
|
|
514
|
+
const heading =
|
|
515
|
+
t === "codex"
|
|
516
|
+
? "Codex CLI:"
|
|
517
|
+
: t === "claude-desktop"
|
|
518
|
+
? "Claude Desktop:"
|
|
519
|
+
: "Generischer Client:";
|
|
520
|
+
lines.push(heading);
|
|
521
|
+
lines.push(" Dieser Client kennt keinen Hook-Mechanismus, der die Pflege HART erzwingt.");
|
|
522
|
+
lines.push(" Es wirken automatisch: die MCP-instructions (werden beim Verbinden gelesen)");
|
|
523
|
+
lines.push(" und die MCP-prompts. Für eine zusätzliche, weiche Memory-First-Regel den");
|
|
524
|
+
lines.push(" folgenden Block in deine System-/Projekt-Anweisung (z. B. AGENTS.md, CLAUDE.md,");
|
|
525
|
+
lines.push(" Custom Instructions) einfügen:");
|
|
526
|
+
lines.push("");
|
|
527
|
+
lines.push(manualSnippet().split("\n").map((l) => " " + l).join("\n"));
|
|
528
|
+
lines.push("");
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// Plan ausgeben + ggf. anwenden
|
|
533
|
+
if (allActions.length) {
|
|
534
|
+
lines.push("Aktionen:");
|
|
535
|
+
for (const a of allActions) {
|
|
536
|
+
const icon = ICON[a.action] || "?";
|
|
537
|
+
let note = "";
|
|
538
|
+
if (a.action === "skip-foreign") note = ` (übersprungen: ${a.reason})`;
|
|
539
|
+
if (a.action === "unchanged") note = " (bereits aktuell)";
|
|
540
|
+
lines.push(` [${icon}] ${a.label}`);
|
|
541
|
+
lines.push(` ${a.path}${note}`);
|
|
542
|
+
}
|
|
543
|
+
lines.push("");
|
|
544
|
+
if (!dryRun) {
|
|
545
|
+
for (const a of allActions) applyAction(a);
|
|
546
|
+
lines.push("Eingerichtet. Starte deinen KI-Client neu, damit Hooks/Regeln greifen.");
|
|
547
|
+
} else {
|
|
548
|
+
lines.push("Dry-Run: keine Datei wurde geändert. Ohne --dry-run erneut ausführen.");
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
return lines.join("\n");
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// Für Tests exportiert.
|
|
556
|
+
export const _internals = {
|
|
557
|
+
upsertMarkedBlock,
|
|
558
|
+
writeOwnFile,
|
|
559
|
+
ensureClaudeHookEntry,
|
|
560
|
+
detectClients,
|
|
561
|
+
memoryFirstBlock,
|
|
562
|
+
BEGIN,
|
|
563
|
+
END,
|
|
564
|
+
};
|
package/src/mcp-stdio.js
CHANGED
|
@@ -14,6 +14,11 @@
|
|
|
14
14
|
* genau diese Abweichung (Punkt- vs. Unterstrich-Namen) hatte 0.1.17 unbrauchbar
|
|
15
15
|
* gemacht, nachdem die Plattform auf das MCP-Namensschema umgestellt wurde.
|
|
16
16
|
*
|
|
17
|
+
* Seit 0.1.20 wird auch `initialize` an den Server durchgereicht, damit die
|
|
18
|
+
* serverseitigen `instructions` (der client-übergreifende Pflege-Hebel) und die
|
|
19
|
+
* tatsächlichen serverInfo/capabilities den Client erreichen. Bei Server-
|
|
20
|
+
* Fehler/Offline fällt der Proxy auf einen lokalen Default zurück.
|
|
21
|
+
*
|
|
17
22
|
* Protokoll: stdio mit zeilenweise JSON (NDJSON-Style). Jedes Frame ist ein
|
|
18
23
|
* vollständiges JSON-RPC-Objekt.
|
|
19
24
|
*/
|
|
@@ -23,6 +28,19 @@ import { createInterface } from "node:readline";
|
|
|
23
28
|
/** Methoden, die lokal beantwortet werden (alles andere geht an den Server). */
|
|
24
29
|
const LOCAL_METHODS = new Set(["initialize", "ping"]);
|
|
25
30
|
|
|
31
|
+
/**
|
|
32
|
+
* Lokaler Fallback-result für `initialize`, falls der Server nicht erreichbar
|
|
33
|
+
* ist oder keine verwertbare Antwort liefert. Hält den Proxy offline-robust.
|
|
34
|
+
* Die serverInfo.version stammt aus der package.json (VERSION).
|
|
35
|
+
*/
|
|
36
|
+
function localInitializeResult() {
|
|
37
|
+
return {
|
|
38
|
+
protocolVersion: "2025-06-18",
|
|
39
|
+
serverInfo: { name: "knowmind", version: VERSION },
|
|
40
|
+
capabilities: { tools: {}, prompts: {} },
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
26
44
|
async function forwardToServer(method, params) {
|
|
27
45
|
const { apiUrl, token } = loadConfig();
|
|
28
46
|
if (!token)
|
|
@@ -171,16 +189,40 @@ export async function runStdioServer() {
|
|
|
171
189
|
write({ jsonrpc: "2.0", id: req.id ?? null, result: {} });
|
|
172
190
|
continue;
|
|
173
191
|
}
|
|
174
|
-
// initialize
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
192
|
+
// initialize: An den Server durchreichen und serverInfo / instructions /
|
|
193
|
+
// capabilities aus der Server-Antwort übernehmen. Nur so erreichen die
|
|
194
|
+
// serverseitigen `instructions` (der automatische Pflege-Hebel) den
|
|
195
|
+
// MCP-Client. Bei Server-Fehler/Offline auf den lokalen Default
|
|
196
|
+
// zurückfallen — Proxy-Charakter und Offline-Robustheit bleiben.
|
|
197
|
+
let initResult = localInitializeResult();
|
|
198
|
+
try {
|
|
199
|
+
const upstreamInit = await forwardToServer("initialize", req.params);
|
|
200
|
+
const serverResult =
|
|
201
|
+
upstreamInit && typeof upstreamInit === "object" && "result" in upstreamInit
|
|
202
|
+
? upstreamInit.result
|
|
203
|
+
: null;
|
|
204
|
+
if (serverResult && typeof serverResult === "object") {
|
|
205
|
+
initResult = {
|
|
206
|
+
// protocolVersion vom Server, sonst lokaler Default.
|
|
207
|
+
protocolVersion: serverResult.protocolVersion ?? initResult.protocolVersion,
|
|
208
|
+
// serverInfo vom Server (Name/Version aus zentraler Quelle), sonst lokal.
|
|
209
|
+
serverInfo: serverResult.serverInfo ?? initResult.serverInfo,
|
|
210
|
+
// capabilities vom Server, sonst lokal.
|
|
211
|
+
capabilities: serverResult.capabilities ?? initResult.capabilities,
|
|
212
|
+
// instructions NUR übernehmen, wenn der Server sie liefert.
|
|
213
|
+
...(typeof serverResult.instructions === "string"
|
|
214
|
+
? { instructions: serverResult.instructions }
|
|
215
|
+
: {}),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
} catch (e) {
|
|
219
|
+
// Server nicht erreichbar o.Ä. → lokaler Default. Der Client soll trotzdem
|
|
220
|
+
// initialisieren können; Tool-Calls scheitern dann ohnehin mit klarer Meldung.
|
|
221
|
+
process.stderr.write(
|
|
222
|
+
`[knowmind] initialize-Forward fehlgeschlagen, lokaler Default: ${e instanceof Error ? e.message : String(e)}\n`,
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
write({ jsonrpc: "2.0", id: req.id ?? null, result: initResult });
|
|
184
226
|
continue;
|
|
185
227
|
}
|
|
186
228
|
|