@kolivri/memoreal-mcp 1.0.2 → 1.1.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.
@@ -1,31 +1,48 @@
1
1
  import {
2
+ MEMOREAL_CLIENT_VERSION,
3
+ ONBOARDING_WIZARD_PROMPT,
4
+ PLACEHOLDER_KEY_REGEX,
5
+ isPlaceholderApiKey,
6
+ isUnregisteredApiKey,
7
+ isSecondaryHookSilenced,
8
+ buildSetupWizardPrompt,
9
+ isChildSession,
10
+ isChildSubagentSession,
11
+ derivePathNamespace,
12
+ sanitizeLogicalNamespace,
13
+ resolveOpenCodeNamespaceInfo,
2
14
  deriveNamespace,
3
15
  resolveCloudConfig,
4
- isPlaceholderApiKey,
5
- ONBOARDING_WIZARD_PROMPT,
6
16
  fetchSessionStartContext,
7
17
  buildReadSuffix,
8
18
  buildWriteSuffix,
9
19
  buildEditSuffix,
10
- isChildSession,
11
- isChildSubagentSession,
12
20
  MemorealHooksPlugin,
21
+ MemoriaHooksPlugin,
13
22
  setup,
14
23
  } from "./memoreal-hooks.js"
15
24
 
16
25
  export {
26
+ MEMOREAL_CLIENT_VERSION,
27
+ ONBOARDING_WIZARD_PROMPT,
28
+ PLACEHOLDER_KEY_REGEX,
29
+ isPlaceholderApiKey,
30
+ isUnregisteredApiKey,
31
+ isSecondaryHookSilenced,
32
+ buildSetupWizardPrompt,
33
+ isChildSession,
34
+ isChildSubagentSession,
35
+ derivePathNamespace,
36
+ sanitizeLogicalNamespace,
37
+ resolveOpenCodeNamespaceInfo,
17
38
  deriveNamespace,
18
39
  resolveCloudConfig,
19
- isPlaceholderApiKey,
20
- ONBOARDING_WIZARD_PROMPT,
21
40
  fetchSessionStartContext,
22
41
  buildReadSuffix,
23
42
  buildWriteSuffix,
24
43
  buildEditSuffix,
25
- isChildSession,
26
- isChildSubagentSession,
27
44
  MemorealHooksPlugin,
28
- MemorealHooksPlugin as MemoriaHooksPlugin,
45
+ MemoriaHooksPlugin,
29
46
  setup,
30
47
  }
31
48
 
@@ -33,6 +50,24 @@ export default {
33
50
  id: "memoria-hooks",
34
51
  server: MemorealHooksPlugin,
35
52
  setup,
53
+ MEMOREAL_CLIENT_VERSION,
54
+ ONBOARDING_WIZARD_PROMPT,
55
+ PLACEHOLDER_KEY_REGEX,
56
+ isPlaceholderApiKey,
57
+ isUnregisteredApiKey,
58
+ isSecondaryHookSilenced,
59
+ buildSetupWizardPrompt,
36
60
  isChildSession,
37
61
  isChildSubagentSession,
38
- }
62
+ derivePathNamespace,
63
+ sanitizeLogicalNamespace,
64
+ resolveOpenCodeNamespaceInfo,
65
+ deriveNamespace,
66
+ resolveCloudConfig,
67
+ fetchSessionStartContext,
68
+ buildReadSuffix,
69
+ buildWriteSuffix,
70
+ buildEditSuffix,
71
+ MemorealHooksPlugin,
72
+ MemoriaHooksPlugin,
73
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kolivri/memoreal-mcp",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "mcpName": "io.github.kolivritech/memoreal-mcp",
5
5
  "description": "Official Node.js MCP connector for Memoreal Cloud (https://memoreal.kolivri.com) — deterministic long-term memory and code intelligence for AI coding agents.",
6
6
  "type": "module",
@@ -9,6 +9,28 @@
9
9
  "memoria-mcp": "src/server.mjs"
10
10
  },
11
11
  "main": "./src/server.mjs",
12
+ "files": [
13
+ "src/",
14
+ "bin/",
15
+ "hooks/",
16
+ "opencode/",
17
+ "rules/",
18
+ "skills/",
19
+ "agents/",
20
+ "assets/",
21
+ ".cursor-plugin/",
22
+ ".claude-plugin/",
23
+ ".mcp.json",
24
+ "CLAUDE.md",
25
+ "README.md",
26
+ "LICENSE",
27
+ "install.sh",
28
+ "manifest.json",
29
+ "mcp.json",
30
+ "server.json",
31
+ "glama.json",
32
+ "smithery.yaml"
33
+ ],
12
34
  "scripts": {
13
35
  "start": "node ./src/server.mjs",
14
36
  "test": "node --test ./test/*.test.mjs"
@@ -31,6 +53,9 @@
31
53
  ],
32
54
  "author": "Kolivri",
33
55
  "license": "MIT",
56
+ "publishConfig": {
57
+ "access": "public"
58
+ },
34
59
  "repository": {
35
60
  "type": "git",
36
61
  "url": "git+https://github.com/kolivritech/memoreal-mcp.git"
@@ -1,11 +1,27 @@
1
1
  ---
2
2
  name: memoreal-workflow
3
- description: Use Memoreal MCP tools for deterministic cross-session memory, belief revision, and code intelligence before grepping files blind
3
+ description: Use 32 Memoreal MCP tools for deterministic cross-session memory, belief revision, and code intelligence before grepping files blind
4
4
  alwaysApply: true
5
5
  ---
6
6
 
7
7
  memoreal-workflow:
8
8
 
9
- - At the start of a coding session, call `build_context` with your project `namespace` and a concise task query (and `health` in parallel) to load prior architectural decisions, user rules, and active tasks into Memoreal.
10
- - Before grepping blind or assuming missing context, call `recall_memories`, `search_code`, or `explain_code`.
11
- - Persist durable architectural decisions, bug root causes, and user corrections with `encode_memory` (or `batch_encode` for multiple facts), rate recalled memories with `feedback`, and run `consolidate` at session wrap-up.
9
+ - **Turn-1 Cold Start & Session Initialization**:
10
+ - On Turn 1 of a newly checked-out or unindexed project, call `bootstrap_project` to index project markdown instructions (`CLAUDE.md`, `AGENTS.md`, `README.md`) and top-level code symbols into Memoreal Cloud.
11
+ - At the start of every session, call `build_context` with a concise task query (and `health` in parallel) to load prior architectural decisions, user rules, and active tasks.
12
+ - The Memoreal MCP plugin automatically resolves canonical project `namespace` from repository manifests (`package.json`, `Cargo.toml`, `pyproject.toml`, `go.mod`, `pom.xml`, etc., across 32 ecosystems), `.memoreal-namespace`, git remotes, and git worktrees (stripping `/.worktrees/*`, `/.claude/worktrees/*`, `/.opencode/worktrees/*`, `/.codex/worktrees/*`, `/.cursor/worktrees/*`) without `org:` prefix — agents can omit `namespace` to let the MCP server resolve it automatically or pass the canonical project slug from `memoreal-ns`, guaranteeing all git worktrees share canonical project memories.
13
+
14
+ - **Deterministic Code Intelligence & Graph Navigation (16 Tools)**:
15
+ - Locating files & symbols: call `find_file` and `search_code` instead of filesystem directory scans.
16
+ - Before modifying a shared symbol: call `find_references` for all workspace usages, `impact` for blast radius, and `call_tree` (`direction: 'in' | 'out'`) to trace call hierarchy.
17
+ - Structural navigation: use `navigate` (cursor walk) and `get_hierarchy` (ancestor & descendant subtrees) to explore project structure coarse-to-fine before bulk file reads.
18
+ - Implementations & code hygiene: inspect `implementors` for interface implementors, detect `dead_code`, and analyze `test_gaps`.
19
+ - Risk & diagnostics: evaluate `diff_risk` for pull requests, determine `downstream_effects`, identify `root_cause` for errors, inspect `trace_provenance` for symbol origin, review git diffs with `explain_diff`, and diagnose runtime/compiler errors with `explain_error`.
20
+ - Refactoring: execute safe symbol renames with `rename`.
21
+
22
+ - **Memory Lifecycle, Hygiene & Multi-Agent Coordination**:
23
+ - Before assuming missing context, call `recall_memories`, `search_code`, or `explain_code`.
24
+ - Persist durable architectural decisions, bug root causes, and user corrections with `encode_memory` (or `batch_encode`), rate recalled memories with `feedback`, and remove obsolete memories with `forget_memory` or `delete_by_context`.
25
+ - Multi-agent workflows: coordinate specialist wings with `list_agent_wings` and `handoff_to_agent`.
26
+ - Interactive onboarding: call `connect_account` for in-chat credential setup.
27
+ - At session wrap-up, run `consolidate` and verify memory counts with `stats`.
package/rules/memoria.mdc CHANGED
@@ -1,11 +1,14 @@
1
1
  ---
2
2
  name: memoria-workflow
3
- description: Backward-compatible alias for Memoreal workflow rules. Use Memoreal MCP tools for deterministic cross-session memory, belief revision, and code intelligence before grepping files blind
3
+ description: Backward-compatible alias for Memoreal workflow rules. Use Memoreal MCP tools (32 deterministic tools) for cross-session memory, belief revision, code intelligence, and cold-start repository bootstrapping before grepping files blind
4
4
  alwaysApply: true
5
5
  ---
6
6
 
7
7
  memoria-workflow (canonical: memoreal-workflow):
8
8
 
9
- - At the start of a coding session, call `build_context` with your project `namespace` and a concise task query (and `health` in parallel) to load prior architectural decisions, user rules, and active tasks into Memoreal.
10
- - Before grepping blind or assuming missing context, call `recall_memories`, `search_code`, or `explain_code`.
9
+ - On Turn-1 cold-start in a repository, call `bootstrap_project` to index project documentation (`CLAUDE.md`, `AGENTS.md`, etc.) and batch-extract up to 150 symbol definitions from source files into Memoreal.
10
+ - The Memoreal MCP plugin automatically resolves the canonical project namespace from repository manifests (`package.json`, `Cargo.toml`, `pyproject.toml`, `go.mod`, etc., across 32 ecosystems), `.memoreal-namespace`, git remotes, and git worktrees (stripping `/.worktrees/*`, `/.claude/worktrees/*`, `/.opencode/worktrees/*`, `/.codex/worktrees/*`, `/.cursor/worktrees/*`), omitting any `org:` prefix — agents can omit `namespace` to let the MCP server resolve it automatically.
11
+ - At the start of a coding session, call `build_context` with a concise task query (and `health` in parallel) to load prior architectural decisions, user rules, and active tasks into Memoreal.
12
+ - Before grepping blind or bulk-reading files, use the 32 deterministic Memoreal tools: locate files with `find_file`, inspect callers/call-sites with `find_references`, explore containment maps with `navigate` and `get_hierarchy`, analyze call chains with `call_tree`, check blast radius with `impact` and `downstream_effects`, and query symbols with `search_code` and `explain_code`.
13
+ - For changes and diagnostics, use `diff_risk`, `explain_diff`, `root_cause`, `explain_error`, `test_gaps`, `dead_code`, and `trace_provenance`.
11
14
  - Persist durable architectural decisions, bug root causes, and user corrections with `encode_memory` (or `batch_encode` for multiple facts), rate recalled memories with `feedback`, and run `consolidate` at session wrap-up.
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "io.github.kolivritech/memoreal-mcp",
4
4
  "title": "Memoreal — Deterministic AI Memory & Code Intelligence MCP",
5
5
  "description": "Official Node.js MCP connector for Memoreal Cloud (https://memoreal.kolivri.com).",
6
- "version": "1.0.2",
6
+ "version": "1.1.0",
7
7
  "websiteUrl": "https://memoreal.kolivri.com",
8
8
  "repository": {
9
9
  "url": "https://github.com/kolivritech/memoreal-mcp",
@@ -14,7 +14,7 @@
14
14
  "registryType": "npm",
15
15
  "registryBaseUrl": "https://registry.npmjs.org",
16
16
  "identifier": "@kolivri/memoreal-mcp",
17
- "version": "1.0.2",
17
+ "version": "1.1.0",
18
18
  "runtimeHint": "npx",
19
19
  "transport": {
20
20
  "type": "stdio"
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: memoreal-connect
3
3
  description: Connect this workspace to Memoreal Cloud via the 3-Click Interactive In-Chat Wizard (legacy alias: /memoria-connect).
4
+ allowed-tools: Bash, AskUserQuestion
4
5
  ---
5
6
 
6
7
  # /memoreal-connect — 3-Click Interactive In-Chat Wizard
@@ -30,7 +31,7 @@ If the user chooses `Skip for this session`, acknowledge politely and continue t
30
31
 
31
32
  ---
32
33
 
33
- ### Step 2: Device Pairing & Verification Card
34
+ ### Step 2: Device Pairing & Verification Card (Primary MCP Path)
34
35
 
35
36
  When the user chooses `Connect in 1 Click via Google / Browser (Recommended)`:
36
37
 
@@ -38,6 +39,8 @@ When the user chooses `Connect in 1 Click via Google / Browser (Recommended)`:
38
39
  ```json
39
40
  {
40
41
  "action": "start",
42
+ "tool": "claude-code",
43
+ "client_name": "Claude Code",
41
44
  "open_browser": true
42
45
  }
43
46
  ```
@@ -68,4 +71,177 @@ Once connected, prompt the user to initialize code-graph intelligence:
68
71
  - `Yes — Index repo now (Recommended)`
69
72
  - `Later`
70
73
 
71
- If the user chooses `Yes — Index repo now (Recommended)`, run `/memoreal-sync-code` to build the semantic code graph. If `Later`, confirm that `build_context`, `encode_memory`, and `recall_memories` are immediately available without restarting the IDE.
74
+ If the user chooses `Yes — Index repo now (Recommended)`, run `bootstrap_project` (or `/memoreal-sync-code`) to build the semantic code graph. If `Later`, confirm that `build_context`, `encode_memory`, and `recall_memories` are immediately available without restarting the IDE.
75
+
76
+ ---
77
+
78
+ ### Safe Bash Device-Pairing Fallback (When connect_account MCP Tool Is Unavailable)
79
+
80
+ If the `connect_account` MCP tool is not yet loaded in the current environment or returns a tool lookup error, execute this zero-stdout-secret fallback via `Bash`. It performs RFC 8628 device authorization using pure `node -e` and `curl --proto =https --tlsv1.2` (no `jq` required), opens the browser, polls until authorized, persists credentials to `0600` config files, and emits ONLY `CONNECTED=true` without leaking secrets to stdout:
81
+
82
+ ```bash
83
+ #!/usr/bin/env bash
84
+ set -euo pipefail
85
+
86
+ API_URL="${MEMOREAL_API_URL:-${MEMORIA_API_URL:-https://memoreal.kolivri.com}}"
87
+ MEMOREAL_DIR="$HOME/.memoreal"
88
+ MEMORIA_DIR="$HOME/.memoria"
89
+ mkdir -p -m 0700 "$MEMOREAL_DIR" "$MEMORIA_DIR"
90
+ AUTH_FILE="$MEMOREAL_DIR/.device_auth.json"
91
+ touch "$AUTH_FILE" && chmod 0600 "$AUTH_FILE"
92
+
93
+ # 1. Start device authorization
94
+ START_PAYLOAD=$(curl -sS --proto =https --tlsv1.2 --max-time 15 -X POST "$API_URL/v1/auth/device/start" \
95
+ -H "Content-Type: application/json" \
96
+ -d '{"client_name":"Claude Code","tool":"claude-code"}')
97
+
98
+ PARSED=$(node -e '
99
+ const p = JSON.parse(process.argv[1]);
100
+ if (!p.device_code || !p.verification_uri) {
101
+ console.error("Device auth initialization failed:", p.error || "unknown response");
102
+ process.exit(1);
103
+ }
104
+ if (!/^[A-Za-z0-9_.-]+$/.test(p.device_code)) {
105
+ console.error("Invalid device_code format received");
106
+ process.exit(1);
107
+ }
108
+ const rawUri = p.verification_uri_complete || (p.user_code ? (p.verification_uri + (p.verification_uri.includes("?") ? "&" : "?") + "user_code=" + encodeURIComponent(p.user_code)) : p.verification_uri);
109
+ if (!rawUri || !/^(https:\/\/|http:\/\/(localhost|127\.0\.0\.1)(:|\/|$))/i.test(rawUri) || /[\s"'\`;&|\\<>]/.test(rawUri)) {
110
+ console.error("Invalid or unsafe verification URI received");
111
+ process.exit(1);
112
+ }
113
+ const vComplete = rawUri;
114
+ console.log([
115
+ p.device_code,
116
+ p.user_code || "",
117
+ p.verification_uri,
118
+ vComplete,
119
+ p.interval || 5,
120
+ p.expires_in || 900
121
+ ].join("\t"));
122
+ ' "$START_PAYLOAD")
123
+
124
+ IFS=$'\t' read -r DEVICE_CODE USER_CODE VERIFY_URI VERIFY_COMPLETE INTERVAL EXPIRES_IN <<< "$PARSED"
125
+
126
+ # Save temporary session metadata (mode 0600)
127
+ node -e '
128
+ const fs = require("fs");
129
+ const deviceCode = process.argv[2];
130
+ const vComplete = process.argv[5];
131
+ if (!/^[A-Za-z0-9_.-]+$/.test(deviceCode) || !/^(https:\/\/|http:\/\/(localhost|127\.0\.0\.1)(:|\/|$))/i.test(vComplete) || /[\s"'\`;&|\\<>]/.test(vComplete)) {
132
+ process.exit(1);
133
+ }
134
+ fs.writeFileSync(process.argv[1], JSON.stringify({
135
+ device_code: deviceCode,
136
+ user_code: process.argv[3],
137
+ verification_uri: process.argv[4],
138
+ verification_uri_complete: vComplete,
139
+ started_at: Date.now()
140
+ }), { mode: 0o600 });
141
+ ' "$AUTH_FILE" "$DEVICE_CODE" "$USER_CODE" "$VERIFY_URI" "$VERIFY_COMPLETE"
142
+
143
+ echo "Open your browser to authorize:"
144
+ echo "$VERIFY_COMPLETE"
145
+ if [ -n "$USER_CODE" ]; then
146
+ echo "Confirmation Code: $USER_CODE"
147
+ fi
148
+
149
+ # 2. Attempt to open system browser
150
+ if command -v open >/dev/null 2>&1; then
151
+ open "$VERIFY_COMPLETE" >/dev/null 2>&1 || true
152
+ elif command -v xdg-open >/dev/null 2>&1; then
153
+ xdg-open "$VERIFY_COMPLETE" >/dev/null 2>&1 || true
154
+ elif command -v rundll32 >/dev/null 2>&1; then
155
+ rundll32 url.dll,FileProtocolHandler "$VERIFY_COMPLETE" >/dev/null 2>&1 || true
156
+ fi
157
+
158
+ # 3. Poll for authorization
159
+ START_TIME=$(date +%s)
160
+ EXPIRES_AT=$((START_TIME + EXPIRES_IN))
161
+ POLL_INTERVAL="${INTERVAL:-5}"
162
+ [ "$POLL_INTERVAL" -lt 2 ] && POLL_INTERVAL=2
163
+
164
+ while [ "$(date +%s)" -lt "$EXPIRES_AT" ]; do
165
+ sleep "$POLL_INTERVAL"
166
+
167
+ POLL_RES=$(curl -sS --proto =https --tlsv1.2 --max-time 15 -X POST "$API_URL/v1/auth/device/poll" \
168
+ -H "Content-Type: application/json" \
169
+ -d "{\"device_code\":\"$DEVICE_CODE\"}")
170
+
171
+ STATUS=$(node -e '
172
+ try {
173
+ const p = JSON.parse(process.argv[1]);
174
+ const key = p.api_key || p.key;
175
+ const isPlaceholder = (k) => !k || /^mem_dev_your_key_here$|^mem_dev_\.\.\.$|^your_api_key/i.test(k) || /^<.*>$/.test(k);
176
+ const isValidKey = (k) => typeof k === "string" && /^[A-Za-z0-9_.-]+$/.test(k) && !isPlaceholder(k);
177
+ if ((p.status === "connected" || p.status === "authorized" || key) && isValidKey(key)) {
178
+ process.stdout.write("SUCCESS");
179
+ } else if (p.status === "slow_down") {
180
+ process.stdout.write("SLOW_DOWN");
181
+ } else if (p.status === "waiting_for_browser" || p.status === "authorization_pending") {
182
+ process.stdout.write("PENDING");
183
+ } else {
184
+ process.stdout.write("ERROR:" + (p.error || p.status || "failed"));
185
+ }
186
+ } catch (e) {
187
+ process.stdout.write("ERROR:" + e.message);
188
+ }
189
+ ' "$POLL_RES")
190
+
191
+ if [ "$STATUS" = "SUCCESS" ]; then
192
+ # Securely persist API key to config files (mode 0600) without stdout echo
193
+ node -e '
194
+ const fs = require("fs");
195
+ const path = require("path");
196
+ const p = JSON.parse(process.argv[1]);
197
+ const key = p.api_key || p.key;
198
+ const isPlaceholder = (k) => !k || /^mem_dev_your_key_here$|^mem_dev_\.\.\.$|^your_api_key/i.test(k) || /^<.*>$/.test(k);
199
+ if (!key || typeof key !== "string" || !/^[A-Za-z0-9_.-]+$/.test(key) || isPlaceholder(key)) {
200
+ console.error("Invalid or placeholder API key received");
201
+ process.exit(1);
202
+ }
203
+ const apiUrl = process.argv[2];
204
+ const memorealDir = process.argv[3];
205
+ const memoriaDir = process.argv[4];
206
+
207
+ const content = `MEMOREAL_API_URL=${apiUrl}\nMEMOREAL_API_KEY=${key}\nMEMORIA_API_URL=${apiUrl}\nMEMORIA_API_KEY=${key}\n`;
208
+
209
+ for (const dir of [memorealDir, memoriaDir]) {
210
+ try {
211
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
212
+ const envPath = path.join(dir, "config.env");
213
+ fs.writeFileSync(envPath, content, { mode: 0o600 });
214
+ fs.chmodSync(envPath, 0o600);
215
+ } catch (_) {}
216
+ }
217
+ ' "$POLL_RES" "$API_URL" "$MEMOREAL_DIR" "$MEMORIA_DIR"
218
+
219
+ # Also register with MCP if npx is available
220
+ node -e '
221
+ const { execSync } = require("child_process");
222
+ const p = JSON.parse(process.argv[1]);
223
+ const key = p.api_key || p.key;
224
+ const isPlaceholder = (k) => !k || /^mem_dev_your_key_here$|^mem_dev_\.\.\.$|^your_api_key/i.test(k) || /^<.*>$/.test(k);
225
+ if (key && typeof key === "string" && /^[A-Za-z0-9_.-]+$/.test(key) && !isPlaceholder(key)) {
226
+ try {
227
+ execSync("npx -y @kolivri/memoreal-mcp setup --key " + JSON.stringify(key) + " --no-bootstrap", { stdio: "ignore" });
228
+ } catch (_) {}
229
+ }
230
+ ' "$POLL_RES" >/dev/null 2>&1 || true
231
+
232
+ rm -f "$AUTH_FILE"
233
+ echo "CONNECTED=true"
234
+ exit 0
235
+ elif [ "$STATUS" = "SLOW_DOWN" ]; then
236
+ POLL_INTERVAL=$((POLL_INTERVAL + 5))
237
+ elif [[ "$STATUS" == ERROR:* ]]; then
238
+ echo "Pairing failed: ${STATUS#ERROR:}" >&2
239
+ rm -f "$AUTH_FILE"
240
+ exit 1
241
+ fi
242
+ done
243
+
244
+ echo "Pairing timed out." >&2
245
+ rm -f "$AUTH_FILE"
246
+ exit 1
247
+ ```
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: memoria-connect
3
3
  description: Connect this workspace to Memoreal Cloud via the 3-Click Interactive In-Chat Wizard (canonical: /memoreal-connect).
4
+ allowed-tools: Bash, AskUserQuestion
4
5
  ---
5
6
 
6
7
  # /memoria-connect — 3-Click Interactive In-Chat Wizard
@@ -30,7 +31,7 @@ If the user chooses `Skip for this session`, acknowledge politely and continue t
30
31
 
31
32
  ---
32
33
 
33
- ### Step 2: Device Pairing & Verification Card
34
+ ### Step 2: Device Pairing & Verification Card (Primary MCP Path)
34
35
 
35
36
  When the user chooses `Connect in 1 Click via Google / Browser (Recommended)`:
36
37
 
@@ -38,6 +39,8 @@ When the user chooses `Connect in 1 Click via Google / Browser (Recommended)`:
38
39
  ```json
39
40
  {
40
41
  "action": "start",
42
+ "tool": "claude-code",
43
+ "client_name": "Claude Code",
41
44
  "open_browser": true
42
45
  }
43
46
  ```
@@ -68,4 +71,177 @@ Once connected, prompt the user to initialize code-graph intelligence:
68
71
  - `Yes — Index repo now (Recommended)`
69
72
  - `Later`
70
73
 
71
- If the user chooses `Yes — Index repo now (Recommended)`, run `/memoreal-sync-code` to build the semantic code graph. If `Later`, confirm that `build_context`, `encode_memory`, and `recall_memories` are immediately available without restarting the IDE.
74
+ If the user chooses `Yes — Index repo now (Recommended)`, run `bootstrap_project` (or `/memoreal-sync-code`) to build the semantic code graph. If `Later`, confirm that `build_context`, `encode_memory`, and `recall_memories` are immediately available without restarting the IDE.
75
+
76
+ ---
77
+
78
+ ### Safe Bash Device-Pairing Fallback (When connect_account MCP Tool Is Unavailable)
79
+
80
+ If the `connect_account` MCP tool is not yet loaded in the current environment or returns a tool lookup error, execute this zero-stdout-secret fallback via `Bash`. It performs RFC 8628 device authorization using pure `node -e` and `curl --proto =https --tlsv1.2` (no `jq` required), opens the browser, polls until authorized, persists credentials to `0600` config files, and emits ONLY `CONNECTED=true` without leaking secrets to stdout:
81
+
82
+ ```bash
83
+ #!/usr/bin/env bash
84
+ set -euo pipefail
85
+
86
+ API_URL="${MEMOREAL_API_URL:-${MEMORIA_API_URL:-https://memoreal.kolivri.com}}"
87
+ MEMOREAL_DIR="$HOME/.memoreal"
88
+ MEMORIA_DIR="$HOME/.memoria"
89
+ mkdir -p -m 0700 "$MEMOREAL_DIR" "$MEMORIA_DIR"
90
+ AUTH_FILE="$MEMOREAL_DIR/.device_auth.json"
91
+ touch "$AUTH_FILE" && chmod 0600 "$AUTH_FILE"
92
+
93
+ # 1. Start device authorization
94
+ START_PAYLOAD=$(curl -sS --proto =https --tlsv1.2 --max-time 15 -X POST "$API_URL/v1/auth/device/start" \
95
+ -H "Content-Type: application/json" \
96
+ -d '{"client_name":"Claude Code","tool":"claude-code"}')
97
+
98
+ PARSED=$(node -e '
99
+ const p = JSON.parse(process.argv[1]);
100
+ if (!p.device_code || !p.verification_uri) {
101
+ console.error("Device auth initialization failed:", p.error || "unknown response");
102
+ process.exit(1);
103
+ }
104
+ if (!/^[A-Za-z0-9_.-]+$/.test(p.device_code)) {
105
+ console.error("Invalid device_code format received");
106
+ process.exit(1);
107
+ }
108
+ const rawUri = p.verification_uri_complete || (p.user_code ? (p.verification_uri + (p.verification_uri.includes("?") ? "&" : "?") + "user_code=" + encodeURIComponent(p.user_code)) : p.verification_uri);
109
+ if (!rawUri || !/^(https:\/\/|http:\/\/(localhost|127\.0\.0\.1)(:|\/|$))/i.test(rawUri) || /[\s"'\`;&|\\<>]/.test(rawUri)) {
110
+ console.error("Invalid or unsafe verification URI received");
111
+ process.exit(1);
112
+ }
113
+ const vComplete = rawUri;
114
+ console.log([
115
+ p.device_code,
116
+ p.user_code || "",
117
+ p.verification_uri,
118
+ vComplete,
119
+ p.interval || 5,
120
+ p.expires_in || 900
121
+ ].join("\t"));
122
+ ' "$START_PAYLOAD")
123
+
124
+ IFS=$'\t' read -r DEVICE_CODE USER_CODE VERIFY_URI VERIFY_COMPLETE INTERVAL EXPIRES_IN <<< "$PARSED"
125
+
126
+ # Save temporary session metadata (mode 0600)
127
+ node -e '
128
+ const fs = require("fs");
129
+ const deviceCode = process.argv[2];
130
+ const vComplete = process.argv[5];
131
+ if (!/^[A-Za-z0-9_.-]+$/.test(deviceCode) || !/^(https:\/\/|http:\/\/(localhost|127\.0\.0\.1)(:|\/|$))/i.test(vComplete) || /[\s"'\`;&|\\<>]/.test(vComplete)) {
132
+ process.exit(1);
133
+ }
134
+ fs.writeFileSync(process.argv[1], JSON.stringify({
135
+ device_code: deviceCode,
136
+ user_code: process.argv[3],
137
+ verification_uri: process.argv[4],
138
+ verification_uri_complete: vComplete,
139
+ started_at: Date.now()
140
+ }), { mode: 0o600 });
141
+ ' "$AUTH_FILE" "$DEVICE_CODE" "$USER_CODE" "$VERIFY_URI" "$VERIFY_COMPLETE"
142
+
143
+ echo "Open your browser to authorize:"
144
+ echo "$VERIFY_COMPLETE"
145
+ if [ -n "$USER_CODE" ]; then
146
+ echo "Confirmation Code: $USER_CODE"
147
+ fi
148
+
149
+ # 2. Attempt to open system browser
150
+ if command -v open >/dev/null 2>&1; then
151
+ open "$VERIFY_COMPLETE" >/dev/null 2>&1 || true
152
+ elif command -v xdg-open >/dev/null 2>&1; then
153
+ xdg-open "$VERIFY_COMPLETE" >/dev/null 2>&1 || true
154
+ elif command -v rundll32 >/dev/null 2>&1; then
155
+ rundll32 url.dll,FileProtocolHandler "$VERIFY_COMPLETE" >/dev/null 2>&1 || true
156
+ fi
157
+
158
+ # 3. Poll for authorization
159
+ START_TIME=$(date +%s)
160
+ EXPIRES_AT=$((START_TIME + EXPIRES_IN))
161
+ POLL_INTERVAL="${INTERVAL:-5}"
162
+ [ "$POLL_INTERVAL" -lt 2 ] && POLL_INTERVAL=2
163
+
164
+ while [ "$(date +%s)" -lt "$EXPIRES_AT" ]; do
165
+ sleep "$POLL_INTERVAL"
166
+
167
+ POLL_RES=$(curl -sS --proto =https --tlsv1.2 --max-time 15 -X POST "$API_URL/v1/auth/device/poll" \
168
+ -H "Content-Type: application/json" \
169
+ -d "{\"device_code\":\"$DEVICE_CODE\"}")
170
+
171
+ STATUS=$(node -e '
172
+ try {
173
+ const p = JSON.parse(process.argv[1]);
174
+ const key = p.api_key || p.key;
175
+ const isPlaceholder = (k) => !k || /^mem_dev_your_key_here$|^mem_dev_\.\.\.$|^your_api_key/i.test(k) || /^<.*>$/.test(k);
176
+ const isValidKey = (k) => typeof k === "string" && /^[A-Za-z0-9_.-]+$/.test(k) && !isPlaceholder(k);
177
+ if ((p.status === "connected" || p.status === "authorized" || key) && isValidKey(key)) {
178
+ process.stdout.write("SUCCESS");
179
+ } else if (p.status === "slow_down") {
180
+ process.stdout.write("SLOW_DOWN");
181
+ } else if (p.status === "waiting_for_browser" || p.status === "authorization_pending") {
182
+ process.stdout.write("PENDING");
183
+ } else {
184
+ process.stdout.write("ERROR:" + (p.error || p.status || "failed"));
185
+ }
186
+ } catch (e) {
187
+ process.stdout.write("ERROR:" + e.message);
188
+ }
189
+ ' "$POLL_RES")
190
+
191
+ if [ "$STATUS" = "SUCCESS" ]; then
192
+ # Securely persist API key to config files (mode 0600) without stdout echo
193
+ node -e '
194
+ const fs = require("fs");
195
+ const path = require("path");
196
+ const p = JSON.parse(process.argv[1]);
197
+ const key = p.api_key || p.key;
198
+ const isPlaceholder = (k) => !k || /^mem_dev_your_key_here$|^mem_dev_\.\.\.$|^your_api_key/i.test(k) || /^<.*>$/.test(k);
199
+ if (!key || typeof key !== "string" || !/^[A-Za-z0-9_.-]+$/.test(key) || isPlaceholder(key)) {
200
+ console.error("Invalid or placeholder API key received");
201
+ process.exit(1);
202
+ }
203
+ const apiUrl = process.argv[2];
204
+ const memorealDir = process.argv[3];
205
+ const memoriaDir = process.argv[4];
206
+
207
+ const content = `MEMOREAL_API_URL=${apiUrl}\nMEMOREAL_API_KEY=${key}\nMEMORIA_API_URL=${apiUrl}\nMEMORIA_API_KEY=${key}\n`;
208
+
209
+ for (const dir of [memorealDir, memoriaDir]) {
210
+ try {
211
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
212
+ const envPath = path.join(dir, "config.env");
213
+ fs.writeFileSync(envPath, content, { mode: 0o600 });
214
+ fs.chmodSync(envPath, 0o600);
215
+ } catch (_) {}
216
+ }
217
+ ' "$POLL_RES" "$API_URL" "$MEMOREAL_DIR" "$MEMORIA_DIR"
218
+
219
+ # Also register with MCP if npx is available
220
+ node -e '
221
+ const { execSync } = require("child_process");
222
+ const p = JSON.parse(process.argv[1]);
223
+ const key = p.api_key || p.key;
224
+ const isPlaceholder = (k) => !k || /^mem_dev_your_key_here$|^mem_dev_\.\.\.$|^your_api_key/i.test(k) || /^<.*>$/.test(k);
225
+ if (key && typeof key === "string" && /^[A-Za-z0-9_.-]+$/.test(key) && !isPlaceholder(key)) {
226
+ try {
227
+ execSync("npx -y @kolivri/memoreal-mcp setup --key " + JSON.stringify(key) + " --no-bootstrap", { stdio: "ignore" });
228
+ } catch (_) {}
229
+ }
230
+ ' "$POLL_RES" >/dev/null 2>&1 || true
231
+
232
+ rm -f "$AUTH_FILE"
233
+ echo "CONNECTED=true"
234
+ exit 0
235
+ elif [ "$STATUS" = "SLOW_DOWN" ]; then
236
+ POLL_INTERVAL=$((POLL_INTERVAL + 5))
237
+ elif [[ "$STATUS" == ERROR:* ]]; then
238
+ echo "Pairing failed: ${STATUS#ERROR:}" >&2
239
+ rm -f "$AUTH_FILE"
240
+ exit 1
241
+ fi
242
+ done
243
+
244
+ echo "Pairing timed out." >&2
245
+ rm -f "$AUTH_FILE"
246
+ exit 1
247
+ ```