@skedulo/memory-hub-mcp 0.2.24 → 0.2.26

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.
@@ -0,0 +1,168 @@
1
+ ---
2
+ name: setup
3
+ description: Use when someone wants to set up Memory Hub, sign in to it, or fix it, e.g. "set up memory hub", "sign in to memory hub", "memory hub isn't working", "memory hub says I'm not signed in", "install the memory hub desktop extension". It checks what this computer is missing, signs the person in through their browser, switches on auto-capture where it can, and installs the desktop extension when asked.
4
+ # prettier-ignore
5
+ argument-hint: "[desktop]"
6
+ ---
7
+
8
+ # Set up Memory Hub
9
+
10
+ Get the person from "installed" to "working". They may not be a developer: use plain words, no
11
+ jargon they did not use, and run the checks yourself instead of asking them to.
12
+
13
+ - **Never ask for a token in chat**, and never print one. Report only whether a token source is set.
14
+ - **Never run an install command for them** (Node, `jq`). Explain what to install and why, then let them do it.
15
+ - **One step at a time.** Do the step, say in one sentence what happened, then go on.
16
+
17
+ ## 1. Check this computer
18
+
19
+ Run this one command and read the result. It prints no token values.
20
+
21
+ ```bash
22
+ bash <<'CHECK'
23
+ for dir in /opt/homebrew/bin /usr/local/bin "$HOME/.volta/bin" $(ls -d "$HOME"/.nvm/versions/node/*/bin 2>/dev/null | sort -rV); do
24
+ if [ -x "$dir/npx" ]; then PATH="$dir:$PATH"; break; fi
25
+ done
26
+ echo "os: $(uname -s)"
27
+ for tool in node npx jq curl claude; do
28
+ if command -v "$tool" >/dev/null 2>&1; then echo "$tool: yes"; else echo "$tool: no"; fi
29
+ done
30
+ real() { [ -n "$1" ] && [ "${1#\$\{}" = "$1" ]; }
31
+ if real "${MEMORY_HUB_MCP_TOKEN:-}"; then echo "env token: set"; else echo "env token: not set"; fi
32
+ if real "${CLAUDE_PLUGIN_OPTION_TOKEN:-}"; then echo "plugin option token: set"; else echo "plugin option token: not set"; fi
33
+ file="${MEMORY_HUB_TOKEN_FILE:-${XDG_CONFIG_HOME:-$HOME/.config}/memory-hub/token.json}"
34
+ if grep -Eq '"token"[[:space:]]*:[[:space:]]*"[^"]' "$file" 2>/dev/null; then echo "token file: has a token"; else echo "token file: none"; fi
35
+ CHECK
36
+ ```
37
+
38
+ A token in any of the three places means the person is already signed in: skip to step 4, and only
39
+ go back to step 3 if the hub says the token was rejected. "Not set" for the plugin option proves
40
+ nothing, because only hooks see it; step 3's `memory_login` says whether the person is signed in.
41
+
42
+ ## 2. Fix what is missing
43
+
44
+ - **No `node` or `npx`:** the plugin needs Node. Tell them to install the LTS version from
45
+ [nodejs.org](https://nodejs.org) (the installer for macOS or Windows), then quit and reopen
46
+ Claude and run `/memory-hub:setup` again. Stop here.
47
+ - **No `jq`:** the memory hooks need it. On macOS they run `brew install jq` in a terminal; on
48
+ Debian or Ubuntu, `sudo apt install jq`. Say what it is for ("it lets the hooks read Memory Hub's
49
+ answers") and carry on while they do it. Sign-in does not need it.
50
+ - **No `curl`:** same, through their package manager.
51
+ - **Windows without bash** (the check cannot run, or the OS is not macOS, Linux, or a Git Bash that
52
+ reports `MINGW` or `MSYS`): the plugin's hooks and server launcher need Git Bash or WSL. Say so,
53
+ and point to the desktop extension (`/memory-hub:setup desktop`), which needs neither.
54
+
55
+ ## 3. Sign in
56
+
57
+ 1. Call the `memory_login` tool. It opens a browser tab on the Skedulo sign-in page and returns at
58
+ once. Tell the person to sign in there, then say when they are done. Call `memory_login` again
59
+ to confirm.
60
+ 2. If the memory tools are not available in this session, run the sign-in from the command line,
61
+ with the Bash tool's `run_in_background` set: it opens the same tab and then waits up to 5
62
+ minutes for the sign-in, longer than a normal Bash call lasts. Run
63
+ `"${CLAUDE_PLUGIN_ROOT}/memory-hub-hook/mcp-server.sh" login`, or, when `${CLAUDE_PLUGIN_ROOT}`
64
+ is empty (a `--no-plugin` install), `npx -y @skedulo/memory-hub-mcp@latest login`. Tell the
65
+ person to finish signing in in the browser, and once they say they have, call `memory_login`
66
+ once more, or ask them to restart Claude, to confirm.
67
+ 3. If the browser says they have no login, they need an invite: ask the Memory Hub admin.
68
+ 4. If they would rather paste a token than use the browser, give them these two steps and leave the
69
+ pasting to them: copy a token from Pulse Web → their profile → Settings → Developer tools → API
70
+ tokens, then run `/plugin configure memory-hub@memory-hub` in a terminal and restart Claude.
71
+
72
+ ## 4. Stop approval prompts (optional)
73
+
74
+ Skip this if you already offered it in this session.
75
+
76
+ Claude asks before each Memory Hub tool unless it is allowed. Ask the person once, in one
77
+ sentence, whether Memory Hub's tools should stop asking. Say that this covers
78
+ every Memory Hub tool, including deleting and sharing memories. Do nothing without a yes.
79
+
80
+ - **Claude Code, on yes:** merge the rule into `permissions.allow` in `~/.claude/settings.json`.
81
+ The rule is `mcp__plugin_memory-hub_memory-hub__*` when `${CLAUDE_PLUGIN_ROOT}` is set, and
82
+ `mcp__memory-hub__*` otherwise (a `--no-plugin` install). It keeps everything else in the file,
83
+ writes a timestamped backup first, replaces the file only if `jq` succeeds, and does nothing when
84
+ the rule is already there:
85
+
86
+ ```bash
87
+ bash -c 'settings="$HOME/.claude/settings.json"
88
+ [ -f "$settings" ] || echo "{}" > "$settings"
89
+ jq -e --arg rule "$1" "(.permissions.allow // []) | index(\$rule) != null" "$settings" >/dev/null 2>&1 && { echo "already allowed"; exit 0; }
90
+ cp "$settings" "$settings.bak-$(date +%Y%m%d%H%M%S)" \
91
+ && jq --arg rule "$1" ".permissions.allow = ((.permissions.allow // []) + [\$rule])" "$settings" > "$settings.new" \
92
+ && mv "$settings.new" "$settings"' _ "<the rule>"
93
+ ```
94
+
95
+ Say it applies from their next session. If `jq` is missing, skip this and say so.
96
+
97
+ - **Desktop chat:** there is no settings file to edit. Tell them to choose **Always allow** the
98
+ first time Claude asks before a Memory Hub tool, or to change it later in the Claude app's
99
+ settings for the Memory Hub extension.
100
+
101
+ ## 5. Auto-capture (Claude Code only)
102
+
103
+ Auto-capture saves what a session learned when it ends, by running `claude` in the background.
104
+
105
+ - If `claude` is on the PATH, nothing to do.
106
+ - If not (common when only the desktop app is installed), find the app's own copy. This prints the
107
+ newest one, or nothing:
108
+
109
+ ```bash
110
+ bash -c 'ls -d "$HOME/Library/Application Support/Claude/claude-code/"*/claude.app/Contents/MacOS/claude 2>/dev/null | sort -V | tail -1'
111
+ ```
112
+
113
+ - If it prints a path, merge it into `~/.claude/settings.json` as `env.MEMORY_HUB_CLAUDE_BIN`. Keep
114
+ everything else in the file. Write a timestamped backup first, and replace the file only if `jq`
115
+ succeeds, so a failure leaves it untouched:
116
+
117
+ ```bash
118
+ settings="$HOME/.claude/settings.json"
119
+ [ -f "$settings" ] || echo '{}' > "$settings"
120
+ cp "$settings" "$settings.bak-$(date +%Y%m%d%H%M%S)"
121
+ jq --arg bin "<the path>" '.env = ((.env // {}) + {MEMORY_HUB_CLAUDE_BIN: $bin})' "$settings" > "$settings.new" \
122
+ && mv "$settings.new" "$settings"
123
+ ```
124
+
125
+ If `jq` is missing, skip this and say so.
126
+
127
+ - If nothing is found (or this is not a Mac), say auto-capture is off on this machine and that
128
+ recall and saving by request still work.
129
+
130
+ ## 6. The `desktop` argument
131
+
132
+ Only when the person typed `desktop` or asked for the desktop extension:
133
+
134
+ 1. Mark the time, then open the extension link in their browser (`open` on macOS, `start` on
135
+ Windows, `xdg-open` on Linux):
136
+ `https://github.com/Skedulo/se-ai-memory-hub/releases/latest/download/memory-hub.mcpb`.
137
+ The repo is internal, so the browser must be signed in to GitHub. If the page says "not found",
138
+ that is the cause.
139
+
140
+ ```bash
141
+ touch "${TMPDIR:-/tmp}/memory-hub-link-opened"
142
+ ```
143
+
144
+ 2. Wait up to 2 minutes for the download (check every few seconds). Browsers may save
145
+ `memory-hub (1).mcpb`, and an old download may be sitting there, so take the newest
146
+ `~/Downloads/memory-hub*.mcpb` modified after the mark. This prints it, or nothing:
147
+
148
+ ```bash
149
+ bash -c 'find "$HOME/Downloads" -maxdepth 1 -name "memory-hub*.mcpb" -newer "${TMPDIR:-/tmp}/memory-hub-link-opened" -exec ls -t {} + | head -1'
150
+ ```
151
+
152
+ If it never prints anything, ask where the browser saved it.
153
+
154
+ 3. Open the file that step 2 found (`open` it on macOS). The Claude desktop app shows its install
155
+ screen. Tell them to click **Install** and to leave the token field empty.
156
+ 4. Say that the next time they ask Claude something about their work, Claude will offer to sign
157
+ them in through the browser. The desktop chat has no hooks, so it does not capture anything by
158
+ itself: Claude saves only when asked.
159
+
160
+ ## 7. Finish
161
+
162
+ Say what working looks like: in Claude Code, a line starting `memory-hub:` at the start of a new
163
+ session; anywhere, Claude answering from memory when asked what the hub knows. Offer to try it now
164
+ by calling `memory_sessionContext`.
165
+
166
+ Then end with this sentence, word for word, spoken to the person:
167
+
168
+ > If you'd rather not use Memory Hub, you can turn it off: in a terminal, /plugin → Installed → memory-hub → Disable; in the desktop app, + → Plugins → Manage plugins → memory-hub off.
@@ -143,11 +143,6 @@ Take the items in order. Before reading anything, skip and list:
143
143
  - `diffLines` of -1: the diff failed; flag it as not checked.
144
144
  - `editedByOtherWithin7Days`: someone else is working on it; never rewrite it. Count it as "already swept by a teammate" in the digest, not as waiting.
145
145
  - `editable: false`: flag it (the "Stale memories" rule on edits you cannot make).
146
- - an item whose text starts with an `UPDATE <date> (said in session)` line that its changed code now
147
- disagrees with: never rewrite it, and never move its `source`. A spoken correction can run ahead of
148
- the code, so leave it as it is and list it under "Said in session, but the code disagrees" in the
149
- digest. Only verifying shows the disagreement (the "Other items" step below); once it does, stop
150
- there and spend no update on it.
151
146
  - tagged `Superseded`: a newer memory replaced it; report it, do not update it.
152
147
 
153
148
  In `dry-run` mode, read nothing more. Count as `apply` would, with each project handed over counted
@@ -179,7 +174,9 @@ In `apply` mode:
179
174
  2. Verify: read each path in `changed` at `target`, and its change with
180
175
  `git -C <clone> diff <source.commit> <target> -- <paths>`.
181
176
  3. If the item starts with an `UPDATE <date> (said in session)` line and the code disagrees with
182
- it, change nothing and list it, as above. When the code agrees with it, the line stays.
177
+ it, never rewrite it and never move its `source`: a spoken correction can run ahead of the
178
+ code. List it under "Said in session, but the code disagrees" in the digest and spend no
179
+ update on it. When the code agrees with it, the line stays.
183
180
  Otherwise apply the section's "still true", "clearly wrong" or "unclear" step, with
184
181
  `source: {repo: "<owner/name>", commit: "<target>"}` and `expectedLastModified` on every
185
182
  `memory_update`, keeping the item's visibility.
@@ -215,10 +212,10 @@ One digest for the whole run, headed with the mode and the date:
215
212
  3. Flagged and skipped items with why: too big, diff failed, not editable,
216
213
  superseded, unclear after verifying, not reached. Items edited by someone else in the last 7
217
214
  days are counted as already swept by a teammate.
218
- Then a list headed "Said in session, but the code disagrees": for each item, the memory (by
219
- title; by uid only when Private, with nothing else about it), what was said and when (the date on
220
- its `UPDATE` line), and what the code shows. Nothing was rewritten; the person decides which side
221
- is right.
215
+ Then a list headed "Said in session, but the code disagrees": for each item, the memory by
216
+ title, what was said and when (the date on its `UPDATE` line), and what the code shows. For a
217
+ Private memory, show only its uid and that date. Nothing was rewritten; the person decides which
218
+ side is right.
222
219
  4. Per project: what the targeted updates and sources-only refreshes changed, by page title and
223
220
  entry ID, the core changes waiting ("run project-knowledge on <Project> to decide them"), and
224
221
  anything "Worth a look", such as new modules.
@@ -6,12 +6,25 @@ set -u
6
6
 
7
7
  [ -n "${MEMORY_HUB_STOP_HOOK_ACTIVE:-}" ] && exit 0
8
8
 
9
- TOKEN="${MEMORY_HUB_MCP_TOKEN:-${CLAUDE_PLUGIN_OPTION_TOKEN:-}}"
9
+ # >>> token lookup: keep identical in session-start.sh, user-prompt-submit.sh, session-stop.sh
10
+ TOKEN="" TOKEN_SOURCE="" FILE_API_BASE=""
11
+ for pair in "env:${MEMORY_HUB_MCP_TOKEN:-}" "option:${CLAUDE_PLUGIN_OPTION_TOKEN:-}"; do
12
+ value="${pair#*:}"
13
+ case "$value" in '' | '${'*) continue ;; esac
14
+ TOKEN="$value" TOKEN_SOURCE="${pair%%:*}"
15
+ break
16
+ done
17
+ TOKEN_FILE="${MEMORY_HUB_TOKEN_FILE:-${XDG_CONFIG_HOME:-$HOME/.config}/memory-hub/token.json}"
18
+ if [ -z "$TOKEN" ] && [ -r "$TOKEN_FILE" ] && command -v jq >/dev/null 2>&1; then
19
+ TOKEN=$(jq -r '.token // empty' "$TOKEN_FILE" 2>/dev/null || true)
20
+ FILE_API_BASE=$(jq -r '.apiBase // empty' "$TOKEN_FILE" 2>/dev/null || true)
21
+ [ -n "$TOKEN" ] && TOKEN_SOURCE=file
22
+ fi
23
+ FUNCTION_URL="${MEMORY_HUB_FUNCTION_URL:-${FILE_API_BASE:-https://dev-api.test.skl.io}/function/memory-hub/memory-hub}"
24
+ # <<< token lookup
10
25
  [ -n "$TOKEN" ] || exit 0
11
26
  command -v jq >/dev/null 2>&1 || exit 0
12
27
 
13
- # Same default as session-start.sh; change both together.
14
- FUNCTION_URL="${MEMORY_HUB_FUNCTION_URL:-https://dev-api.test.skl.io/function/memory-hub/memory-hub}"
15
28
  BUDGET="${MEMORY_HUB_PROMPT_MAX_CHARS:-6000}"
16
29
  [ "$BUDGET" -gt 9000 ] && BUDGET=9000
17
30
  FACTS_N="${MEMORY_HUB_PROMPT_FACTS:-5}"
@@ -273,7 +286,7 @@ QUERY=$(printf '%s' "$PROMPT" | head -c 300)
273
286
  body() {
274
287
  jq -nc --arg q "$QUERY" --arg v "${VECTOR:-null}" --argjson cap "$((BUDGET / 2))" \
275
288
  --argjson min "$MIN_SIMILARITY" --arg repo "$REPO" --argjson other "$OTHER_REPO_MIN" --argjson band "$SIMILARITY_BAND" '
276
- {query: $q, diverse: true, maxCharsPerItem: 500, maxTotalChars: $cap}
289
+ {query: $q, diverse: true, withRelated: true, maxCharsPerItem: 500, maxTotalChars: $cap}
277
290
  + (if $v == "null" then {scope: "team"}
278
291
  else {scope: "all", queryEmbedding: ($v | fromjson), minSimilarity: $min}
279
292
  + (if $repo == "" then {} else {homeRepo: $repo, otherRepoMinSimilarity: $other, similarityBand: $band} end)
@@ -330,6 +343,11 @@ ORIGIN_DEF='def origin:
330
343
  then " · from " + (.repoName | gsub("[[:cntrl:]]"; " ")) + (if (.teamName | type) == "string" and .teamName != "" then " (" + (.teamName | gsub("[[:cntrl:]]"; " ")) + ")" else "" end)
331
344
  else "" end;'
332
345
 
346
+ RELATED_DEF='def related($kind):
347
+ if (.related | type) == "number" and .related > 0 and .related == (.related | floor) and (.uid | type) == "string"
348
+ then " · related: " + (.related | tostring) + " — memory_related type=" + $kind + " uid=" + (.uid | gsub("[[:cntrl:]]"; " "))
349
+ else "" end;'
350
+
333
351
  HEADING="## Memory relevant to this prompt"
334
352
  FOOTER="_Matched to your prompt, not newest-first. memory_recall with a query finds more; memory_get fetches a cut item._"
335
353
  PRECEDENT_NOTE="_An item marked \"from\" another project is precedent: check it against this code, and keep that customer's names, data and terms out of this work._"
@@ -344,10 +362,10 @@ while IFS= read -r -d $'\x1e' item; do
344
362
  used=$((used + ${#item} + 1))
345
363
  fi
346
364
  done < <(
347
- jq -j "${KEEP_ARGS[@]}" "$EXTRAS_DEF $ORIGIN_DEF [.facts[]? | $KEEP][:$FACTS_N][] | ((\"- \" + (.content | $ELIDE) + $(cut_pointer Fact) + $STAMP + extras(\"\"; .content) + origin) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/facts.json" 2>/dev/null
348
- jq -j "${KEEP_ARGS[@]}" "$EXTRAS_DEF $ORIGIN_DEF [.skills[]? | $KEEP][:$SKILLS_N][] | ((\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Skill) + $STAMP + extras(\"\"; .content) + origin) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/skills.json" 2>/dev/null
349
- jq -j "${KEEP_ARGS[@]}" "$EXTRAS_DEF $ORIGIN_DEF [.pages[]? | $KEEP][:$WIKI_N][] | ((\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Wiki) + $STAMP + extras(\"\"; .content) + origin) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/wiki.json" 2>/dev/null
350
- jq -j "${KEEP_ARGS[@]}" "$EXTRAS_DEF $ORIGIN_DEF [.scenarios[]? | $KEEP][:$SCENARIOS_N][] | ((\"- \" + (.summary | $ELIDE) + $(cut_pointer Scenario summary) + $STAMP + extras(\"\"; .summary) + origin) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/scenarios.json" 2>/dev/null
365
+ jq -j "${KEEP_ARGS[@]}" "$EXTRAS_DEF $ORIGIN_DEF $RELATED_DEF [.facts[]? | $KEEP][:$FACTS_N][] | ((\"- \" + (.content | $ELIDE) + $(cut_pointer Fact) + $STAMP + extras(\"\"; .content) + origin + related(\"Fact\")) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/facts.json" 2>/dev/null
366
+ jq -j "${KEEP_ARGS[@]}" "$EXTRAS_DEF $ORIGIN_DEF $RELATED_DEF [.skills[]? | $KEEP][:$SKILLS_N][] | ((\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Skill) + $STAMP + extras(\"\"; .content) + origin + related(\"Skill\")) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/skills.json" 2>/dev/null
367
+ jq -j "${KEEP_ARGS[@]}" "$EXTRAS_DEF $ORIGIN_DEF $RELATED_DEF [.pages[]? | $KEEP][:$WIKI_N][] | ((\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Wiki) + $STAMP + extras(\"\"; .content) + origin + related(\"Wiki\")) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/wiki.json" 2>/dev/null
368
+ jq -j "${KEEP_ARGS[@]}" "$EXTRAS_DEF $ORIGIN_DEF $RELATED_DEF [.scenarios[]? | $KEEP][:$SCENARIOS_N][] | ((\"- \" + (.summary | $ELIDE) + $(cut_pointer Scenario summary) + $STAMP + extras(\"\"; .summary) + origin + related(\"Scenario\")) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/scenarios.json" 2>/dev/null
351
369
  )
352
370
  [ -n "$BODY" ] || finish_with_notices
353
371
  case "$BODY" in
package/dist/capture.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.logCapture = exports.captureVisibility = exports.captureUpdateRefusal = exports.captureUpsert = exports.isCaptureMode = void 0;
3
+ exports.logCapture = exports.captureVisibility = exports.captureSourceRefusal = exports.captureUpdateRefusal = exports.captureUpsert = exports.isCaptureMode = void 0;
4
4
  const fs_1 = require("fs");
5
5
  const SIMILAR_OWN_FACT_FLOOR = 0.86;
6
6
  function isCaptureMode(env = process.env) {
@@ -90,6 +90,16 @@ function captureUpdateRefusal(type, env = process.env) {
90
90
  };
91
91
  }
92
92
  exports.captureUpdateRefusal = captureUpdateRefusal;
93
+ function captureSourceRefusal(source, env = process.env) {
94
+ if (!isCaptureMode(env) || source === undefined) {
95
+ return undefined;
96
+ }
97
+ return {
98
+ message: 'Not updated: capture mode never changes source, so nothing was changed. ' +
99
+ 'Update again without source; only a human or the sweep re-checks an item against the code.',
100
+ };
101
+ }
102
+ exports.captureSourceRefusal = captureSourceRefusal;
93
103
  // An auto-capture is never reviewed before it is saved, so it stays with its author until they share it.
94
104
  function captureVisibility(requested, env = process.env) {
95
105
  return isCaptureMode(env) ? 'Private' : requested;
package/dist/cli.js CHANGED
@@ -1,8 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
- // Dispatch happens here rather than in index.ts because index.ts throws at module
4
- // load when MEMORY_HUB_MCP_TOKEN is unset — which is exactly the state `setup` exists
5
- // to fix, so it can never be reached from there.
3
+ // Dispatch happens here rather than in index.ts, which starts the MCP server as soon as it loads.
6
4
  const command = process.argv[2];
7
5
  if (command === '--version' || command === '-v') {
8
6
  // eslint-disable-next-line @typescript-eslint/no-var-requires
@@ -17,6 +15,16 @@ else if (command === 'setup') {
17
15
  process.exit(1);
18
16
  });
19
17
  }
18
+ else if (command === 'login') {
19
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
20
+ const { runLogin } = require('./login-tool');
21
+ runLogin(process.argv.slice(3)).then((code) => {
22
+ process.exitCode = code;
23
+ }, (error) => {
24
+ console.error(error instanceof Error ? error.message : String(error));
25
+ process.exitCode = 1;
26
+ });
27
+ }
20
28
  else if (command === 'capture') {
21
29
  // eslint-disable-next-line @typescript-eslint/no-var-requires
22
30
  const { runCapture } = require('./setup');
@@ -109,10 +117,13 @@ else if (command === '--help' || command === '-h') {
109
117
  questions; auto-capture is on unless you pass --no-capture.
110
118
  For Claude Code it installs the memory-hub plugin with auto-update
111
119
  on (needs the claude CLI and GitHub access; --no-plugin installs
112
- the hooks and skill directly instead). The server runs as
120
+ the hooks and skill directly instead). It also allows all Memory Hub
121
+ tools (including delete and share) without approval prompts in
122
+ ~/.claude/settings.json; pass --no-allow to skip that. The server runs as
113
123
  npx ...@latest, so each start picks up the newest release;
114
124
  --no-auto-update pins this install instead. On macOS it offers to
115
125
  restart Claude Desktop at the end.
126
+ memory-hub-mcp login sign in to Memory Hub in the browser and save the token on this machine
116
127
  memory-hub-mcp capture on|off
117
128
  turn auto-capture on or off (on by default). In the background,
118
129
  Claude saves what each session learns and fixes hub memories you
package/dist/client.js CHANGED
@@ -3,9 +3,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.MemoryHubClient = void 0;
6
+ exports.MemoryHubClient = exports.NotSignedInError = exports.NOT_SIGNED_IN = void 0;
7
7
  // memory-hub-mcp/src/client.ts
8
8
  const axios_1 = __importDefault(require("axios"));
9
+ exports.NOT_SIGNED_IN = "Memory Hub isn't signed in yet. Call memory_login: it opens a Skedulo sign-in in the user's browser.";
10
+ class NotSignedInError extends Error {
11
+ constructor() {
12
+ super(exports.NOT_SIGNED_IN);
13
+ this.name = 'NotSignedInError';
14
+ }
15
+ }
16
+ exports.NotSignedInError = NotSignedInError;
9
17
  // axios only says "status code 400"; the function puts the reason in { error } on the body.
10
18
  function withServerMessage(err) {
11
19
  const response = err?.response;
@@ -21,10 +29,17 @@ class MemoryHubClient {
21
29
  constructor(config) {
22
30
  this.config = config;
23
31
  }
32
+ resolveCredentials() {
33
+ const credentials = 'credentials' in this.config ? this.config.credentials() : this.config;
34
+ if (!credentials)
35
+ throw new NotSignedInError();
36
+ return credentials;
37
+ }
24
38
  async post(path, body) {
39
+ const { baseUrl, apiToken } = this.resolveCredentials();
25
40
  try {
26
- const res = await axios_1.default.post(`${this.config.baseUrl}${path}`, body, {
27
- headers: { Authorization: `Bearer ${this.config.apiToken}`, 'Content-Type': 'application/json' },
41
+ const res = await axios_1.default.post(`${baseUrl}${path}`, body, {
42
+ headers: { Authorization: `Bearer ${apiToken}`, 'Content-Type': 'application/json' },
28
43
  });
29
44
  return res.data;
30
45
  }
@@ -142,6 +157,9 @@ class MemoryHubClient {
142
157
  getWikiPage(input) {
143
158
  return this.post('/memory/get-wiki-page', input);
144
159
  }
160
+ related(input) {
161
+ return this.post('/memory/related', input);
162
+ }
145
163
  saveWikiPage(input) {
146
164
  return this.post('/memory/save-wiki-page', input);
147
165
  }
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveFunctionUrl = exports.resolveCredentials = exports.writeTokenFile = exports.readTokenFile = exports.tokenFilePath = exports.DEFAULT_API_BASE = void 0;
4
+ const fs_1 = require("fs");
5
+ const os_1 = require("os");
6
+ const path_1 = require("path");
7
+ const setup_1 = require("./setup");
8
+ exports.DEFAULT_API_BASE = 'https://dev-api.test.skl.io';
9
+ // `||`, not `??`: an empty XDG_CONFIG_HOME means unset.
10
+ function tokenFilePath(env = process.env, home = (0, os_1.homedir)()) {
11
+ if (env.MEMORY_HUB_TOKEN_FILE)
12
+ return env.MEMORY_HUB_TOKEN_FILE;
13
+ return (0, path_1.join)(env.XDG_CONFIG_HOME || (0, path_1.join)(home, '.config'), 'memory-hub', 'token.json');
14
+ }
15
+ exports.tokenFilePath = tokenFilePath;
16
+ function readTokenFile(path = tokenFilePath()) {
17
+ try {
18
+ const parsed = JSON.parse((0, fs_1.readFileSync)(path, 'utf8'));
19
+ if (typeof parsed?.token !== 'string' || !parsed.token)
20
+ return undefined;
21
+ const apiBase = typeof parsed.apiBase === 'string' && parsed.apiBase ? parsed.apiBase : exports.DEFAULT_API_BASE;
22
+ return { token: parsed.token, apiBase };
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ }
28
+ exports.readTokenFile = readTokenFile;
29
+ function writeTokenFile(creds, path = tokenFilePath()) {
30
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(path), { recursive: true, mode: 0o700 });
31
+ const temp = `${path}.tmp`;
32
+ (0, fs_1.writeFileSync)(temp, `${JSON.stringify({ token: creds.token, apiBase: creds.apiBase }, null, 2)}\n`, { mode: 0o600 });
33
+ (0, fs_1.renameSync)(temp, path);
34
+ }
35
+ exports.writeTokenFile = writeTokenFile;
36
+ // An unexpanded `${user_config.token}` placeholder arrives when the plugin option was left empty.
37
+ function usableToken(value) {
38
+ return value && !value.startsWith('${') ? value : undefined;
39
+ }
40
+ function resolveCredentials(env = process.env, path) {
41
+ const fromEnv = usableToken(env.MEMORY_HUB_MCP_TOKEN);
42
+ if (fromEnv)
43
+ return { token: fromEnv, apiBase: exports.DEFAULT_API_BASE, source: 'env' };
44
+ const fromFile = readTokenFile(path);
45
+ return fromFile ? { ...fromFile, source: 'file' } : undefined;
46
+ }
47
+ exports.resolveCredentials = resolveCredentials;
48
+ function resolveFunctionUrl(env, creds) {
49
+ return env.MEMORY_HUB_FUNCTION_URL || (0, setup_1.functionUrl)(creds?.apiBase);
50
+ }
51
+ exports.resolveFunctionUrl = resolveFunctionUrl;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.extensionUpdateNotice = void 0;
4
+ const LATEST_URL = 'https://registry.npmjs.org/@skedulo/memory-hub-mcp/latest';
5
+ const DOWNLOAD_URL = 'https://github.com/Skedulo/se-ai-memory-hub/releases/latest/download/memory-hub.mcpb';
6
+ const TIMEOUT_MS = 3000;
7
+ function parts(version) {
8
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
9
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : undefined;
10
+ }
11
+ function isNewer(latest, current) {
12
+ for (let i = 0; i < 3; i++) {
13
+ if (latest[i] !== current[i])
14
+ return latest[i] > current[i];
15
+ }
16
+ return false;
17
+ }
18
+ async function extensionUpdateNotice(current, fetchFn = fetch) {
19
+ try {
20
+ const response = await fetchFn(LATEST_URL, { signal: AbortSignal.timeout(TIMEOUT_MS) });
21
+ if (!response.ok)
22
+ return undefined;
23
+ const latest = (await response.json()).version ?? '';
24
+ const latestParts = parts(latest);
25
+ const currentParts = parts(current);
26
+ if (!latestParts || !currentParts || !isNewer(latestParts, currentParts))
27
+ return undefined;
28
+ return `A newer Memory Hub desktop extension (${latest}) is available: ${DOWNLOAD_URL}. Download it and double-click it to update.`;
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ }
34
+ exports.extensionUpdateNotice = extensionUpdateNotice;
package/dist/index.js CHANGED
@@ -6,6 +6,9 @@ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
6
6
  const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
7
7
  const zod_1 = require("zod");
8
8
  const client_1 = require("./client");
9
+ const credentials_1 = require("./credentials");
10
+ const login_1 = require("./login");
11
+ const login_tool_1 = require("./login-tool");
9
12
  const list_repos_1 = require("./list-repos");
10
13
  const check_sources_1 = require("./check-sources");
11
14
  const annotate_1 = require("./annotate");
@@ -23,21 +26,16 @@ const revise_1 = require("./revise");
23
26
  const similar_notice_1 = require("./similar-notice");
24
27
  const session_context_1 = require("./session-context");
25
28
  const version_1 = require("./version");
29
+ const extension_update_1 = require("./extension-update");
26
30
  const asset_sync_1 = require("./asset-sync");
27
31
  const tags_1 = require("./tags");
28
32
  const ask_prompt_1 = require("./ask-prompt");
29
- // The team's one deployed memory-hub function. MEMORY_HUB_FUNCTION_URL only needs to
30
- // be set to override this (e.g. pointing at a local `sked function dev` instance).
31
- const DEFAULT_FUNCTION_URL = 'https://dev-api.test.skl.io/function/memory-hub/memory-hub';
32
- const baseUrl = process.env.MEMORY_HUB_FUNCTION_URL || DEFAULT_FUNCTION_URL;
33
- // This developer's personal identity token, forwarded as the caller's own
34
- // Authorization header — the connected function now runs under this same
35
- // forwarded token rather than a separate service-account ConfigVariable.
36
- const apiToken = process.env.MEMORY_HUB_MCP_TOKEN;
37
- if (!apiToken) {
38
- throw new Error('MEMORY_HUB_MCP_TOKEN must be set');
39
- }
40
- const client = new client_1.MemoryHubClient({ baseUrl, apiToken });
33
+ const client = new client_1.MemoryHubClient({
34
+ credentials: () => {
35
+ const creds = (0, credentials_1.resolveCredentials)();
36
+ return creds && { baseUrl: (0, credentials_1.resolveFunctionUrl)(process.env, creds), apiToken: creds.token };
37
+ },
38
+ });
41
39
  // Claude Code gets its startup recall from memory-hub-hook's SessionStart hook. Claude
42
40
  // Desktop has no hook system, so these instructions (surfaced by the host at connect
43
41
  // time) plus memory_sessionContext are the only equivalent available there.
@@ -58,8 +56,10 @@ const INSTRUCTIONS = [
58
56
  'even from here, passing only a repo that memory_listRepos lists; Org for customer-free',
59
57
  'knowledge about Skedulo\'s platform, products, tools or practices; Private only with a',
60
58
  'stated reason. Unsure between Org and Team: Team. Say the choice and the reason.',
59
+ "If a memory tool says Memory Hub isn't signed in, offer once to sign in and call memory_login.",
61
60
  ].join(' ');
62
61
  const server = new mcp_js_1.McpServer({ name: 'memory-hub-mcp', version: (0, version_1.packageVersion)() }, { instructions: INSTRUCTIONS });
62
+ (0, login_tool_1.guardTools)(server, { signedIn: () => (0, credentials_1.resolveCredentials)() !== undefined, exempt: ['memory_login', 'memory_getSkillGuide'] });
63
63
  // Detected from this process's own working directory, not from anything the model
64
64
  // types. Resolved lazily on the first save so startup never blocks on git or the
65
65
  // network, and degrades to undefined (an unscoped save) on any failure.
@@ -101,6 +101,16 @@ server.registerPrompt('ask', {
101
101
  }, ({ question }) => ({
102
102
  messages: [{ role: 'user', content: { type: 'text', text: (0, ask_prompt_1.askPromptText)(question) } }],
103
103
  }));
104
+ const loginAttempt = (0, login_tool_1.loginStarter)();
105
+ const login = (0, login_tool_1.createLoginTool)({
106
+ start: loginAttempt.start,
107
+ url: loginAttempt.url,
108
+ current: () => (0, credentials_1.resolveCredentials)(),
109
+ status: creds => (0, login_1.tokenStatus)((0, credentials_1.resolveFunctionUrl)(process.env, creds), creds.token),
110
+ extension: process.env.MEMORY_HUB_EXTENSION === '1',
111
+ viaPlugin: process.env.MEMORY_HUB_VIA_PLUGIN === '1',
112
+ });
113
+ server.tool('memory_login', "Sign in to Memory Hub: opens a Skedulo sign-in in the user's browser and saves the token on this machine. Call it when another memory tool says it isn't signed in, or when the user asks to sign in. Call it again to check whether the sign-in finished.", {}, async () => ({ content: [{ type: 'text', text: await login() }] }));
104
114
  server.tool('memory_getSkillGuide', 'Get the current Memory Hub usage guide — when to recall, what to save where, sharing rules, repo linking. Call this first when the memory-hub skill triggers. Pass section to read one part only (for example "Stale memories"), which costs far fewer tokens.', {
105
115
  section: zod_1.z.string().min(1).optional().describe('A "## " heading of the guide, matched without regard to case. Returns only that part; an unknown name returns the list of sections.'),
106
116
  }, async ({ section }) => {
@@ -140,6 +150,13 @@ server.tool('memory_get', "Fetch one Fact/Skill/Scenario/Wiki page in full by it
140
150
  const annotated = await (0, annotate_1.annotateItemCapped)(result, currentStaleness(), { entries: input.type === 'Wiki' });
141
151
  return { content: [{ type: 'text', text: JSON.stringify(annotated) }] };
142
152
  });
153
+ server.tool('memory_related', "List one memory's neighbours as pointers (uid, type, title, why) without their content. `why` is one of: linked page, backlink, scenario fact, supersedes, superseded by, same ticket, cites the same file. Fetch any neighbour with memory_get. It respects the same visibility as memory_get, so a neighbour you cannot read is not listed.", {
154
+ type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
155
+ uid: zod_1.z.string().min(1).describe('The uid from a memory_recall or memory_get result.'),
156
+ }, async (input) => {
157
+ const result = await client.related({ uid: input.uid, type: input.type });
158
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
159
+ });
143
160
  const saveShape = {
144
161
  type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
145
162
  content: zod_1.z.string().optional().describe('Required for Fact, Skill, Wiki.'),
@@ -295,7 +312,7 @@ server.tool('memory_update', "Revise a memory (yours, or a Team item on your tea
295
312
  source: source_1.sourceSchema.nullable().optional().describe(`${source_1.SOURCE_DESCRIPTION} Pass it after re-checking the item against the repo; null clears the source.`),
296
313
  expectedLastModified: zod_1.z.string().min(1).optional().describe('The lastModifiedDate memory_get returned. Required when you are not the author. The update is refused if the item changed since.'),
297
314
  }, async (input) => {
298
- const refused = (0, capture_1.captureUpdateRefusal)(input.type);
315
+ const refused = (0, capture_1.captureUpdateRefusal)(input.type) ?? (0, capture_1.captureSourceRefusal)(input.source);
299
316
  if (refused) {
300
317
  return { content: [{ type: 'text', text: refused.message }] };
301
318
  }
@@ -355,8 +372,17 @@ server.tool('memory_sessionContext', "Load this developer's saved memory-hub con
355
372
  staleness: currentStaleness(),
356
373
  serverVersion: (0, version_1.packageVersion)(),
357
374
  });
358
- return { content: [...embeddingNoticeBlocks(), { type: 'text', text: JSON.stringify(context) }] };
375
+ const update = process.env.MEMORY_HUB_EXTENSION === '1' ? await (0, extension_update_1.extensionUpdateNotice)((0, version_1.packageVersion)()) : undefined;
376
+ return {
377
+ content: [
378
+ ...embeddingNoticeBlocks(),
379
+ ...(update ? [{ type: 'text', text: update }] : []),
380
+ { type: 'text', text: JSON.stringify(context) },
381
+ ],
382
+ };
359
383
  });
360
- (0, asset_sync_1.refreshInstalledAssets)();
384
+ if (process.env.MEMORY_HUB_EXTENSION !== '1') {
385
+ (0, asset_sync_1.refreshInstalledAssets)();
386
+ }
361
387
  const transport = new stdio_js_1.StdioServerTransport();
362
388
  server.connect(transport);