@skedulo/memory-hub-mcp 0.2.1 → 0.2.3
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/assets/session-start.sh +59 -22
- package/assets/user-prompt-submit.sh +124 -0
- package/dist/cli.js +7 -0
- package/dist/embed-cli.js +41 -0
- package/dist/embeddings.js +6 -1
- package/dist/guide-check.js +24 -0
- package/dist/index.js +4 -1
- package/dist/recall.js +26 -6
- package/dist/setup.js +20 -10
- package/package.json +2 -2
- package/skill-guide.md +13 -5
package/assets/session-start.sh
CHANGED
|
@@ -185,16 +185,21 @@ ELIDE="if length >= $ITEM_CAP then . + \"…\" else . end"
|
|
|
185
185
|
# Without this a stored "## heading" renders at the level of the hook's own section headings.
|
|
186
186
|
INDENT='gsub("\n"; "\n ")'
|
|
187
187
|
|
|
188
|
+
# The function flags a cut item; an older one sends no flag and keeps just the "…" above.
|
|
189
|
+
cut_pointer() {
|
|
190
|
+
printf '(if .truncated then " [cut at \\(.content | length) of \\(.fullLength) — memory_get type=%s uid=\\(.uid)]" else "" end)' "$1"
|
|
191
|
+
}
|
|
192
|
+
|
|
188
193
|
extract_facts() {
|
|
189
|
-
jq -c ".facts[]? | (\"- \" + (.content | $ELIDE) + $STAMP) | $CLOSE_FENCE | $INDENT" "$1" 2>/dev/null || true
|
|
194
|
+
jq -c ".facts[]? | (\"- \" + (.content | $ELIDE) + $(cut_pointer Fact) + $STAMP) | $CLOSE_FENCE | $INDENT" "$1" 2>/dev/null || true
|
|
190
195
|
}
|
|
191
196
|
|
|
192
197
|
extract_skills() {
|
|
193
|
-
jq -c ".skills[]? | (\"- \" + .title + \": \" + (.content | $ELIDE) + $STAMP) | $CLOSE_FENCE | $INDENT" "$1" 2>/dev/null || true
|
|
198
|
+
jq -c ".skills[]? | (\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Skill) + $STAMP) | $CLOSE_FENCE | $INDENT" "$1" 2>/dev/null || true
|
|
194
199
|
}
|
|
195
200
|
|
|
196
201
|
extract_wiki() {
|
|
197
|
-
jq -c ".pages[]? | (\"- \" + .title + \": \" + (.content | $ELIDE) + $STAMP) | $CLOSE_FENCE | $INDENT" "$1" 2>/dev/null || true
|
|
202
|
+
jq -c ".pages[]? | (\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Wiki) + $STAMP) | $CLOSE_FENCE | $INDENT" "$1" 2>/dev/null || true
|
|
198
203
|
}
|
|
199
204
|
|
|
200
205
|
# Absent on functions deployed before the field existed; fall back to what arrived rather than inventing a number.
|
|
@@ -217,8 +222,14 @@ count_items() {
|
|
|
217
222
|
NL=$'\n'
|
|
218
223
|
CONTEXT=""
|
|
219
224
|
|
|
220
|
-
|
|
221
|
-
|
|
225
|
+
omission_footer() {
|
|
226
|
+
printf '_Omitted for space: %s. Ask memory_recall with a query._' "$1"
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
# Sized for every section being skipped, so the footer can never itself be the thing squeezed out.
|
|
230
|
+
FOOTER_NAMES="Your memory-hub facts, Team memory-hub facts, Your memory-hub skills, Team memory-hub skills"
|
|
231
|
+
[ -n "$REPO_UID" ] && FOOTER_NAMES="Team knowledge for ${REPO_NAME}, ${FOOTER_NAMES}"
|
|
232
|
+
FOOTER_RESERVE=$(($(omission_footer "$FOOTER_NAMES" | wc -m) + 2))
|
|
222
233
|
REMAINING=$((BUDGET - FOOTER_RESERVE))
|
|
223
234
|
SKIPPED=""
|
|
224
235
|
|
|
@@ -228,24 +239,31 @@ SECTIONS_LEFT=4
|
|
|
228
239
|
|
|
229
240
|
# Emits at most $1 chars of $2, whole items only. $3 is what the server holds — its cap has usually dropped items already.
|
|
230
241
|
clip_to_budget() {
|
|
231
|
-
local budget="$1" text="$2" avail="$3" out="" line used
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
seen
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
shown
|
|
242
|
+
local budget="$1" text="$2" avail="$3" out="" line used shown seen marker attempt
|
|
243
|
+
# The "showing N of M" marker is part of what the section costs, so a second pass leaves room for it.
|
|
244
|
+
for attempt in 1 2; do
|
|
245
|
+
out="" used=0 shown=0 seen=0 marker=""
|
|
246
|
+
while IFS= read -r line; do
|
|
247
|
+
[ -n "$line" ] || continue
|
|
248
|
+
seen=$((seen + 1))
|
|
249
|
+
if [ "$shown" -eq "$((seen - 1))" ] && [ $((used + ${#line} + 1)) -le "$budget" ]; then
|
|
250
|
+
out="${out}${line}${NL}"
|
|
251
|
+
used=$((used + ${#line} + 1))
|
|
252
|
+
shown=$((shown + 1))
|
|
253
|
+
fi
|
|
254
|
+
done <<< "$text"
|
|
255
|
+
[ "$shown" -gt 0 ] || return 0
|
|
256
|
+
# Pre-dedup, so team counts can overstate by items also shown under self/repo.
|
|
257
|
+
[ "$avail" -ge "$seen" ] 2>/dev/null || avail="$seen"
|
|
258
|
+
# A bare memory_recall returns newest-first — the same items already above.
|
|
259
|
+
[ "$avail" -gt "$shown" ] && marker=$(printf '_showing %d of %d — ask memory_recall with a query for the rest._' "$shown" "$avail" | jq -R .)
|
|
260
|
+
if [ -z "$marker" ] || [ $((used + ${#marker} + 1)) -le "$budget" ]; then
|
|
261
|
+
break
|
|
239
262
|
fi
|
|
240
|
-
|
|
263
|
+
budget=$((budget - ${#marker} - 1))
|
|
264
|
+
done
|
|
241
265
|
printf '%s' "$out"
|
|
242
|
-
[ "$
|
|
243
|
-
# Pre-dedup, so team counts can overstate by items also shown under self/repo.
|
|
244
|
-
[ "$avail" -ge "$seen" ] 2>/dev/null || avail="$seen"
|
|
245
|
-
if [ "$avail" -gt "$shown" ]; then
|
|
246
|
-
# A bare memory_recall returns newest-first — the same items already above.
|
|
247
|
-
printf '_showing %d of %d — ask memory_recall with a query for the rest._' "$shown" "$avail" | jq -R .
|
|
248
|
-
fi
|
|
266
|
+
[ -z "$marker" ] || printf '%s\n' "$marker"
|
|
249
267
|
}
|
|
250
268
|
|
|
251
269
|
add_section() {
|
|
@@ -352,12 +370,31 @@ DIAG="${DIAG}_"
|
|
|
352
370
|
#
|
|
353
371
|
# First, not last: it is the only part that asks for an action, so it has to survive the
|
|
354
372
|
# budget even when nothing else does.
|
|
373
|
+
# A stale build cannot warn about itself, so the hook, which a git pull does refresh, has to.
|
|
374
|
+
MCP_DIR="${MEMORY_HUB_MCP_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../memory-hub-mcp" 2>/dev/null && pwd)}"
|
|
375
|
+
# Content, not mtimes: a branch switch or pull rewrites files without changing what they say.
|
|
376
|
+
mcp_build_is_stale() {
|
|
377
|
+
local dir="$1" current
|
|
378
|
+
[ -f "$dir/dist/index.js" ] || return 1
|
|
379
|
+
if [ -f "$dir/dist/.source-hash" ] && [ -f "$dir/scripts/source-hash.sh" ]; then
|
|
380
|
+
current=$(bash "$dir/scripts/source-hash.sh" 2>/dev/null)
|
|
381
|
+
[ -z "$current" ] || { [ "$current" != "$(cat "$dir/dist/.source-hash" 2>/dev/null)" ]; return; }
|
|
382
|
+
fi
|
|
383
|
+
[ -n "$(find "$dir/src" "$dir/skill-guide.md" -type f \( -name '*.ts' -o -name '*.md' \) ! -name '*.test.ts' -newer "$dir/dist/index.js" 2>/dev/null | head -1)" ]
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
STALE_MCP=""
|
|
387
|
+
if [ -n "$MCP_DIR" ] && mcp_build_is_stale "$MCP_DIR"; then
|
|
388
|
+
STALE_MCP="WARNING: the memory-hub MCP build in this checkout is older than its source, so tools the guide names (memory_get) may be missing and recalled items cut at 500 chars cannot be fetched whole. Tell the user to run ./scripts/setup-dev.sh (or cd memory-hub-mcp && yarn build) and restart the session.${NL}${NL}"
|
|
389
|
+
fi
|
|
390
|
+
|
|
355
391
|
REMINDER="## Reminder${NL}"
|
|
356
392
|
REMINDER="${REMINDER}What follows is an automatic recall only - it never saves anything new.${NL}"
|
|
357
393
|
REMINDER="${REMINDER}Invoke the se-ai-memory-hub skill during this session: memory_recall before${NL}"
|
|
358
394
|
REMINDER="${REMINDER}investigating something that smells like prior context, and memory_save${NL}"
|
|
359
395
|
REMINDER="${REMINDER}(type \"Fact\" or \"Scenario\") once a task produces a durable decision, root${NL}"
|
|
360
396
|
REMINDER="${REMINDER}cause, or fix worth keeping for next time.${NL}${NL}"
|
|
397
|
+
REMINDER="${REMINDER}${STALE_MCP}"
|
|
361
398
|
CONTEXT="$REMINDER"
|
|
362
399
|
REMAINING=$((REMAINING - ${#REMINDER} - ${#DIAG}))
|
|
363
400
|
|
|
@@ -373,7 +410,7 @@ add_section "Team memory-hub skills" "$SKILLS_TEAM" "$SKILLS_TEAM_N"
|
|
|
373
410
|
|
|
374
411
|
# A section that never fit is the omission most likely to be read as "there is nothing there".
|
|
375
412
|
if [ -n "$SKIPPED" ]; then
|
|
376
|
-
CONTEXT="${CONTEXT}
|
|
413
|
+
CONTEXT="${CONTEXT}$(omission_footer "$SKIPPED")${NL}${NL}"
|
|
377
414
|
fi
|
|
378
415
|
|
|
379
416
|
CONTEXT="${CONTEXT}${DIAG}${NL}"
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# UserPromptSubmit hook: on the first substantive prompt of a session, recalls the memories most
|
|
3
|
+
# relevant to that prompt and injects them. Must never block or crash a prompt — every failure
|
|
4
|
+
# degrades to injecting nothing.
|
|
5
|
+
set -u
|
|
6
|
+
|
|
7
|
+
TOKEN="${MEMORY_HUB_MCP_TOKEN:-}"
|
|
8
|
+
[ -n "$TOKEN" ] || exit 0
|
|
9
|
+
command -v jq >/dev/null 2>&1 || exit 0
|
|
10
|
+
|
|
11
|
+
# Same default as session-start.sh; change both together.
|
|
12
|
+
FUNCTION_URL="${MEMORY_HUB_FUNCTION_URL:-https://dev-api.test.skl.io/function/memory-hub/memory-hub}"
|
|
13
|
+
BUDGET="${MEMORY_HUB_PROMPT_MAX_CHARS:-6000}"
|
|
14
|
+
[ "$BUDGET" -gt 9000 ] && BUDGET=9000
|
|
15
|
+
FACTS_N="${MEMORY_HUB_PROMPT_FACTS:-5}"
|
|
16
|
+
# Scores in this corpus are compressed: relevant items land near 0.4-0.7, unrelated ones near 0.3-0.4,
|
|
17
|
+
# so an item must clear a floor and stay close to the best match across both lists.
|
|
18
|
+
MIN_SIMILARITY="${MEMORY_HUB_PROMPT_MIN_SIMILARITY:-0.35}"
|
|
19
|
+
SIMILARITY_BAND="${MEMORY_HUB_PROMPT_SIMILARITY_BAND:-0.25}"
|
|
20
|
+
SKILLS_N="${MEMORY_HUB_PROMPT_SKILLS:-3}"
|
|
21
|
+
ITEM_CAP=500
|
|
22
|
+
NL=$'\n'
|
|
23
|
+
|
|
24
|
+
INPUT=$(cat)
|
|
25
|
+
SESSION_ID=$(printf '%s' "$INPUT" | jq -r '.session_id // empty' 2>/dev/null | tr -cd 'A-Za-z0-9_-')
|
|
26
|
+
PROMPT=$(printf '%s' "$INPUT" | jq -r '.prompt // empty' 2>/dev/null)
|
|
27
|
+
[ -n "$SESSION_ID" ] && [ -n "$PROMPT" ] || exit 0
|
|
28
|
+
|
|
29
|
+
# A slash command or a one-line reply has nothing to match on, and must not use up the session's one shot.
|
|
30
|
+
case "$PROMPT" in /*) exit 0 ;; esac
|
|
31
|
+
[ "$(printf '%s' "$PROMPT" | wc -w)" -ge "${MEMORY_HUB_MIN_PROMPT_WORDS:-4}" ] || exit 0
|
|
32
|
+
|
|
33
|
+
STATE_DIR="${MEMORY_HUB_STATE_DIR:-$HOME/.claude/memory-hub-hook/state}"
|
|
34
|
+
mkdir -p "$STATE_DIR" 2>/dev/null || exit 0
|
|
35
|
+
find "$STATE_DIR" -type f -mtime +7 -delete 2>/dev/null || true
|
|
36
|
+
MARKER="$STATE_DIR/$SESSION_ID"
|
|
37
|
+
[ -e "$MARKER" ] && exit 0
|
|
38
|
+
# Marked before any work, so a slow or failing function costs one prompt, not every prompt.
|
|
39
|
+
: > "$MARKER" 2>/dev/null || exit 0
|
|
40
|
+
|
|
41
|
+
TMP_DIR=$(mktemp -d)
|
|
42
|
+
trap 'rm -rf "$TMP_DIR"' EXIT
|
|
43
|
+
|
|
44
|
+
HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)"
|
|
45
|
+
EMBED=()
|
|
46
|
+
if [ -n "${MEMORY_HUB_EMBED_CMD:-}" ]; then
|
|
47
|
+
EMBED=("$MEMORY_HUB_EMBED_CMD")
|
|
48
|
+
elif [ -f "$HOOK_DIR/../memory-hub-mcp/dist/cli.js" ] && command -v node >/dev/null 2>&1; then
|
|
49
|
+
EMBED=(node "$HOOK_DIR/../memory-hub-mcp/dist/cli.js" embed)
|
|
50
|
+
elif command -v memory-hub-mcp >/dev/null 2>&1; then
|
|
51
|
+
EMBED=(memory-hub-mcp embed)
|
|
52
|
+
else
|
|
53
|
+
SERVER_CMD=$(jq -r '.mcpServers["memory-hub"].command // empty' "$HOME/.claude.json" 2>/dev/null)
|
|
54
|
+
[ -n "$SERVER_CMD" ] && [ -x "$SERVER_CMD" ] && EMBED=("$SERVER_CMD" embed)
|
|
55
|
+
fi
|
|
56
|
+
|
|
57
|
+
VECTOR=""
|
|
58
|
+
if [ "${#EMBED[@]}" -gt 0 ]; then
|
|
59
|
+
VECTOR=$(printf '%s' "$PROMPT" | MEMORY_HUB_EMBED_TIMEOUT_MS=4000 "${EMBED[@]}" 2>/dev/null) || VECTOR=""
|
|
60
|
+
printf '%s' "$VECTOR" | jq -e 'type == "array" and length > 0' >/dev/null 2>&1 || VECTOR=""
|
|
61
|
+
fi
|
|
62
|
+
|
|
63
|
+
QUERY=$(printf '%s' "$PROMPT" | head -c 300)
|
|
64
|
+
body() {
|
|
65
|
+
jq -nc --arg q "$QUERY" --arg v "${VECTOR:-null}" --argjson cap "$((BUDGET / 2))" \
|
|
66
|
+
--argjson min "$MIN_SIMILARITY" '
|
|
67
|
+
{scope: "team", query: $q, diverse: true, maxCharsPerItem: 500, maxTotalChars: $cap}
|
|
68
|
+
+ (if $v == "null" then {} else {queryEmbedding: ($v | fromjson), minSimilarity: $min} end)'
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
call() {
|
|
72
|
+
local path="$1" out_file="$2"
|
|
73
|
+
if [ -n "${MEMORY_HUB_FIXTURE_DIR:-}" ]; then
|
|
74
|
+
mkdir -p "$MEMORY_HUB_FIXTURE_DIR/requests"
|
|
75
|
+
body > "$MEMORY_HUB_FIXTURE_DIR/requests/$(basename "$out_file")" 2>/dev/null
|
|
76
|
+
cp "$MEMORY_HUB_FIXTURE_DIR/$(basename "$out_file")" "$out_file" 2>/dev/null || true
|
|
77
|
+
return 0
|
|
78
|
+
fi
|
|
79
|
+
curl -sS --connect-timeout 3 --max-time 7 \
|
|
80
|
+
-X POST "${FUNCTION_URL}${path}" \
|
|
81
|
+
-H "Authorization: Bearer ${TOKEN}" \
|
|
82
|
+
-H "Content-Type: application/json" \
|
|
83
|
+
-d "$(body)" \
|
|
84
|
+
-o "$out_file" 2>/dev/null || true
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
call "/memory/recall" "$TMP_DIR/facts.json" &
|
|
88
|
+
call "/memory/list-skills" "$TMP_DIR/skills.json" &
|
|
89
|
+
wait
|
|
90
|
+
|
|
91
|
+
CLOSE_FENCE='if ([match("```"; "g")] | length) % 2 == 1 then . + "\n```" else . end'
|
|
92
|
+
INDENT='gsub("\n"; "\n ")'
|
|
93
|
+
STAMP='(if .lastModifiedDate then " (updated " + .lastModifiedDate[0:10] + ")" else "" end)'
|
|
94
|
+
ELIDE="if length >= $ITEM_CAP then . + \"…\" else . end"
|
|
95
|
+
cut_pointer() {
|
|
96
|
+
printf '(if .truncated then " [cut at \\(.content | length) of \\(.fullLength) — memory_get type=%s uid=\\(.uid)]" else "" end)' "$1"
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
# Judged across both lists: one list alone may have no strong match, and would keep its weak ones.
|
|
100
|
+
BEST=$(jq -rs '[.[] | ((.facts // []) + (.skills // []))[] | .similarity // empty] | max // empty' "$TMP_DIR/facts.json" "$TMP_DIR/skills.json" 2>/dev/null)
|
|
101
|
+
FLOOR=-1
|
|
102
|
+
[ -n "$BEST" ] && FLOOR=$(jq -n --argjson best "$BEST" --argjson band "$SIMILARITY_BAND" '$best - $band')
|
|
103
|
+
KEEP='select(.similarity == null or .similarity >= $floor)'
|
|
104
|
+
|
|
105
|
+
HEADING="## Memory relevant to this prompt"
|
|
106
|
+
FOOTER="_Matched to your prompt, not newest-first. memory_recall with a query finds more; memory_get fetches a cut item._"
|
|
107
|
+
room=$((BUDGET - ${#HEADING} - ${#FOOTER} - 4))
|
|
108
|
+
BODY=""
|
|
109
|
+
used=0
|
|
110
|
+
# Whole items only: each item is one logical record, so it is shown entirely or not at all.
|
|
111
|
+
while IFS= read -r -d $'\x1e' item; do
|
|
112
|
+
[ -n "$item" ] || continue
|
|
113
|
+
if [ $((used + ${#item} + 1)) -le "$room" ]; then
|
|
114
|
+
BODY="${BODY}${item}${NL}"
|
|
115
|
+
used=$((used + ${#item} + 1))
|
|
116
|
+
fi
|
|
117
|
+
done < <(
|
|
118
|
+
jq -j --argjson floor "$FLOOR" "[.facts[]? | $KEEP][:$FACTS_N][] | ((\"- \" + (.content | $ELIDE) + $(cut_pointer Fact) + $STAMP) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/facts.json" 2>/dev/null
|
|
119
|
+
jq -j --argjson floor "$FLOOR" "[.skills[]? | $KEEP][:$SKILLS_N][] | ((\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Skill) + $STAMP) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/skills.json" 2>/dev/null
|
|
120
|
+
)
|
|
121
|
+
[ -n "$BODY" ] || exit 0
|
|
122
|
+
|
|
123
|
+
CONTEXT="${HEADING}${NL}${BODY}${NL}${FOOTER}${NL}"
|
|
124
|
+
jq -nc --arg c "$CONTEXT" '{hookSpecificOutput: {hookEventName: "UserPromptSubmit", additionalContext: $c}}'
|
package/dist/cli.js
CHANGED
|
@@ -12,12 +12,19 @@ if (command === 'setup') {
|
|
|
12
12
|
process.exit(1);
|
|
13
13
|
});
|
|
14
14
|
}
|
|
15
|
+
else if (command === 'embed') {
|
|
16
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
17
|
+
const { runEmbed, readProcessStdin } = require('./embed-cli');
|
|
18
|
+
runEmbed(process.argv.slice(3), { readStdin: readProcessStdin, write: (line) => console.log(line) }).then((code) => process.exit(code));
|
|
19
|
+
}
|
|
15
20
|
else if (command === '--help' || command === '-h') {
|
|
16
21
|
console.log(`memory-hub-mcp — MCP server for the SE AI Memory Hub
|
|
17
22
|
|
|
18
23
|
memory-hub-mcp setup log in, then wire up Claude Code (MCP server + SessionStart
|
|
19
24
|
hook + skill) and/or Claude Desktop (MCP server), and verify
|
|
20
25
|
the token. Pass --code, --desktop or --both to skip the prompt.
|
|
26
|
+
memory-hub-mcp embed print the embedding of the text on stdin (or the arguments) as JSON;
|
|
27
|
+
used by the UserPromptSubmit hook. Exits non-zero if it cannot.
|
|
21
28
|
memory-hub-mcp run the MCP server on stdio (how a host launches it)
|
|
22
29
|
`);
|
|
23
30
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readProcessStdin = exports.runEmbed = void 0;
|
|
4
|
+
const embeddings_1 = require("./embeddings");
|
|
5
|
+
const MAX_TEXT_CHARS = 2000;
|
|
6
|
+
const DEFAULT_TIMEOUT_MS = 8000;
|
|
7
|
+
// Exit code, not process.exit, so a hook can treat any non-zero as "no embedding" and carry on.
|
|
8
|
+
async function runEmbed(args, deps) {
|
|
9
|
+
const text = (args.length > 0 ? args.join(' ') : await deps.readStdin()).trim().slice(0, MAX_TEXT_CHARS);
|
|
10
|
+
if (!text) {
|
|
11
|
+
return 1;
|
|
12
|
+
}
|
|
13
|
+
let timer;
|
|
14
|
+
const timeout = new Promise((_, reject) => {
|
|
15
|
+
timer = setTimeout(() => reject(new Error('embed timed out')), deps.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
16
|
+
});
|
|
17
|
+
try {
|
|
18
|
+
const vector = await Promise.race([(deps.embedText ?? embeddings_1.embed)(text), timeout]);
|
|
19
|
+
deps.write(JSON.stringify(vector));
|
|
20
|
+
return 0;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return 2;
|
|
24
|
+
}
|
|
25
|
+
finally {
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
exports.runEmbed = runEmbed;
|
|
30
|
+
function readProcessStdin() {
|
|
31
|
+
if (process.stdin.isTTY) {
|
|
32
|
+
return Promise.resolve('');
|
|
33
|
+
}
|
|
34
|
+
return new Promise((resolve) => {
|
|
35
|
+
let data = '';
|
|
36
|
+
process.stdin.setEncoding('utf8');
|
|
37
|
+
process.stdin.on('data', (chunk) => (data += chunk));
|
|
38
|
+
process.stdin.on('end', () => resolve(data));
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
exports.readProcessStdin = readProcessStdin;
|
package/dist/embeddings.js
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.embed = void 0;
|
|
3
|
+
exports.embed = exports.MODEL_CACHE_DIR = void 0;
|
|
4
|
+
const os_1 = require("os");
|
|
5
|
+
const path_1 = require("path");
|
|
4
6
|
const transformers_1 = require("@xenova/transformers");
|
|
7
|
+
// Not under node_modules: a global `npm i -g` update wipes that, and a slow network can then miss the load timeout.
|
|
8
|
+
exports.MODEL_CACHE_DIR = process.env.MEMORY_HUB_MODEL_CACHE || (0, path_1.join)((0, os_1.homedir)(), '.cache', 'memory-hub', 'models');
|
|
9
|
+
transformers_1.env.cacheDir = exports.MODEL_CACHE_DIR;
|
|
5
10
|
// Loaded lazily, once per process, on the first embed() call — a session that
|
|
6
11
|
// never saves or recalls anything pays zero cost, and every call after the
|
|
7
12
|
// first reuses the same loaded model instead of reloading it. The model's
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.staleBuildNotice = exports.toolsMentioned = void 0;
|
|
4
|
+
// The guide is read from disk, so a pull without a rebuild pairs a new guide with an old build.
|
|
5
|
+
function toolsMentioned(guide) {
|
|
6
|
+
return [...new Set(guide.match(/\bmemory_[A-Za-z]+\b/g) ?? [])].sort();
|
|
7
|
+
}
|
|
8
|
+
exports.toolsMentioned = toolsMentioned;
|
|
9
|
+
function staleBuildNotice(guide, registered) {
|
|
10
|
+
// Fail open: with no registry to compare against, a warning would be noise.
|
|
11
|
+
if (registered.length === 0) {
|
|
12
|
+
return '';
|
|
13
|
+
}
|
|
14
|
+
const have = new Set(registered);
|
|
15
|
+
const missing = toolsMentioned(guide).filter((name) => !have.has(name));
|
|
16
|
+
if (missing.length === 0) {
|
|
17
|
+
return '';
|
|
18
|
+
}
|
|
19
|
+
return (`WARNING: this memory-hub-mcp build is older than its guide. The guide below refers to ` +
|
|
20
|
+
`${missing.join(', ')}, which this build does not expose, so those steps will fail. ` +
|
|
21
|
+
`Tell the user to rebuild (\`cd memory-hub-mcp && yarn build\`, or rerun ./scripts/setup-dev.sh) ` +
|
|
22
|
+
`and restart the session.\n\n---\n\n`);
|
|
23
|
+
}
|
|
24
|
+
exports.staleBuildNotice = staleBuildNotice;
|
package/dist/index.js
CHANGED
|
@@ -13,6 +13,7 @@ const git_remote_1 = require("./git-remote");
|
|
|
13
13
|
const embeddings_1 = require("./embeddings");
|
|
14
14
|
const save_1 = require("./save");
|
|
15
15
|
const recall_1 = require("./recall");
|
|
16
|
+
const guide_check_1 = require("./guide-check");
|
|
16
17
|
const session_context_1 = require("./session-context");
|
|
17
18
|
// Must match the AgentFacts/AgentSkills/AgentWikiPages Tags custom field's Picklist
|
|
18
19
|
// allowedValues (src/object-model/custom-fields/{AgentFacts,AgentSkills,AgentWikiPages}/*-Tags.custom-field.json)
|
|
@@ -106,7 +107,9 @@ server.tool('memory_getSkillGuide', 'Get the current SE AI Memory Hub usage guid
|
|
|
106
107
|
// itself and updates on every `yarn build`, not via a separate manual `cp` step.
|
|
107
108
|
const guidePath = (0, path_1.join)(__dirname, '..', 'skill-guide.md');
|
|
108
109
|
const guide = (0, fs_1.readFileSync)(guidePath, 'utf-8');
|
|
109
|
-
|
|
110
|
+
// The SDK has no public tool list; if this internal moves, the check just goes silent.
|
|
111
|
+
const registered = Object.keys(server._registeredTools ?? {});
|
|
112
|
+
return { content: [{ type: 'text', text: (0, guide_check_1.staleBuildNotice)(guide, registered) + guide }] };
|
|
110
113
|
});
|
|
111
114
|
server.tool('memory_recall', "Recall this developer's (or their team's) Facts, Skills, Scenarios, or Wiki pages. See memory_getSkillGuide for when to use each type.", {
|
|
112
115
|
type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
|
package/dist/recall.js
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.performRecall = void 0;
|
|
4
|
+
// In-band, not just a JSON field: an agent skimming the text must still see the cut and the uid.
|
|
5
|
+
function markCuts(type, listKey, textKey, result) {
|
|
6
|
+
const items = result?.[listKey];
|
|
7
|
+
if (!Array.isArray(items)) {
|
|
8
|
+
return result;
|
|
9
|
+
}
|
|
10
|
+
const marked = items.map((item) => {
|
|
11
|
+
if (!item.truncated) {
|
|
12
|
+
return item;
|
|
13
|
+
}
|
|
14
|
+
const { truncated: _truncated, fullLength, ...rest } = item;
|
|
15
|
+
const text = typeof rest[textKey] === 'string' ? rest[textKey] : '';
|
|
16
|
+
const of = typeof fullLength === 'number' ? ` of ${fullLength.toLocaleString('en-US')}` : '';
|
|
17
|
+
return {
|
|
18
|
+
...rest,
|
|
19
|
+
[textKey]: `${text}\n[cut at ${text.length}${of} chars — memory_get type=${type} uid=${rest.uid}]`,
|
|
20
|
+
};
|
|
21
|
+
});
|
|
22
|
+
return { ...result, [listKey]: marked };
|
|
23
|
+
}
|
|
4
24
|
// Extracted from four near-identical memory_recall/listSkills/recallScenarios/
|
|
5
25
|
// recallWiki tool handlers — see save.ts's comment for why (index.ts's module-scope
|
|
6
26
|
// side effects make it untestable directly).
|
|
@@ -10,26 +30,26 @@ async function performRecall(deps, input) {
|
|
|
10
30
|
const caps = { maxCharsPerItem: input.maxCharsPerItem, maxTotalChars: input.maxTotalChars };
|
|
11
31
|
switch (input.type) {
|
|
12
32
|
case 'Fact':
|
|
13
|
-
return client.recall({
|
|
33
|
+
return markCuts('Fact', 'facts', 'content', await client.recall({
|
|
14
34
|
scope: input.scope,
|
|
15
35
|
query: input.query,
|
|
16
36
|
tags: input.tags,
|
|
17
37
|
externalRef: input.externalRef,
|
|
18
38
|
queryEmbedding,
|
|
19
39
|
...caps,
|
|
20
|
-
});
|
|
40
|
+
}));
|
|
21
41
|
case 'Skill':
|
|
22
|
-
return client.listSkills({ scope: input.scope, query: input.query, queryEmbedding, ...caps });
|
|
42
|
+
return markCuts('Skill', 'skills', 'content', await client.listSkills({ scope: input.scope, query: input.query, queryEmbedding, ...caps }));
|
|
23
43
|
case 'Scenario':
|
|
24
|
-
return client.recallScenarios({
|
|
44
|
+
return markCuts('Scenario', 'scenarios', 'summary', await client.recallScenarios({
|
|
25
45
|
scope: input.scope,
|
|
26
46
|
query: input.query,
|
|
27
47
|
externalRef: input.externalRef,
|
|
28
48
|
queryEmbedding,
|
|
29
49
|
...caps,
|
|
30
|
-
});
|
|
50
|
+
}));
|
|
31
51
|
case 'Wiki':
|
|
32
|
-
return client.recallWiki({ scope: input.scope, query: input.query, queryEmbedding, ...caps });
|
|
52
|
+
return markCuts('Wiki', 'pages', 'content', await client.recallWiki({ scope: input.scope, query: input.query, queryEmbedding, ...caps }));
|
|
33
53
|
}
|
|
34
54
|
}
|
|
35
55
|
exports.performRecall = performRecall;
|
package/dist/setup.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.runSetup = exports.registerSessionStartHook = exports.writeUserEnv = exports.writeDesktopConfig = exports.writeMcpServer = exports.functionUrl = exports.desktopConfigPath = void 0;
|
|
3
|
+
exports.runSetup = exports.registerPromptHook = exports.registerSessionStartHook = exports.writeUserEnv = exports.writeDesktopConfig = exports.writeMcpServer = exports.functionUrl = exports.desktopConfigPath = void 0;
|
|
4
4
|
const child_process_1 = require("child_process");
|
|
5
5
|
const fs_1 = require("fs");
|
|
6
6
|
const os_1 = require("os");
|
|
@@ -135,36 +135,44 @@ exports.writeUserEnv = writeUserEnv;
|
|
|
135
135
|
// "Ours" is the script's identity, not its exact path: setup-dev.sh registers the repo
|
|
136
136
|
// checkout and this installer ~/.claude/memory-hub-hook, so matching the exact string
|
|
137
137
|
// lets both stack copies of the same script. Replaces, keeping any timeout it carried.
|
|
138
|
-
function
|
|
138
|
+
function registerHook(path, event, hookPath, script, timeout) {
|
|
139
139
|
const settings = readJson(path);
|
|
140
140
|
const hooks = (settings.hooks ||= {});
|
|
141
|
-
const entries = (hooks
|
|
141
|
+
const entries = (hooks[event] ||= []);
|
|
142
142
|
const isOurs = (command) => typeof command === 'string' &&
|
|
143
|
-
(command.trim() === hookPath || command.trim().endsWith(
|
|
143
|
+
(command.trim() === hookPath || command.trim().endsWith(`memory-hub-hook/${script}`));
|
|
144
144
|
const ours = entries.flatMap((entry) => (entry.hooks || []).filter((h) => isOurs(h.command)));
|
|
145
145
|
const already = ours.length === 1 && ours[0].command === hookPath;
|
|
146
|
-
const kept = { type: 'command', ...ours[0], command: hookPath };
|
|
146
|
+
const kept = { type: 'command', ...(timeout ? { timeout } : {}), ...ours[0], command: hookPath };
|
|
147
147
|
for (const entry of entries) {
|
|
148
148
|
entry.hooks = (entry.hooks || []).filter((h) => !isOurs(h.command));
|
|
149
149
|
}
|
|
150
|
-
hooks
|
|
151
|
-
hooks.
|
|
150
|
+
hooks[event] = entries.filter((entry) => entry.hooks.length > 0);
|
|
151
|
+
hooks[event].push({ hooks: [kept] });
|
|
152
152
|
writeJson(path, settings);
|
|
153
153
|
return { already, replaced: already ? 0 : ours.length };
|
|
154
154
|
}
|
|
155
|
+
function registerSessionStartHook(path, hookPath) {
|
|
156
|
+
return registerHook(path, 'SessionStart', hookPath, 'session-start.sh');
|
|
157
|
+
}
|
|
155
158
|
exports.registerSessionStartHook = registerSessionStartHook;
|
|
159
|
+
// This one is on the critical path of every prompt, so it carries an explicit timeout.
|
|
160
|
+
function registerPromptHook(path, hookPath) {
|
|
161
|
+
return registerHook(path, 'UserPromptSubmit', hookPath, 'user-prompt-submit.sh', 15);
|
|
162
|
+
}
|
|
163
|
+
exports.registerPromptHook = registerPromptHook;
|
|
156
164
|
function installAssets() {
|
|
157
165
|
const hookDir = (0, path_1.join)((0, os_1.homedir)(), '.claude', 'memory-hub-hook');
|
|
158
166
|
const skillDir = (0, path_1.join)((0, os_1.homedir)(), '.claude', 'skills', 'se-ai-memory-hub');
|
|
159
167
|
(0, fs_1.mkdirSync)(hookDir, { recursive: true });
|
|
160
168
|
(0, fs_1.mkdirSync)(skillDir, { recursive: true });
|
|
161
|
-
for (const name of ['session-start.sh', 'session-stop.sh']) {
|
|
169
|
+
for (const name of ['session-start.sh', 'session-stop.sh', 'user-prompt-submit.sh']) {
|
|
162
170
|
const dest = (0, path_1.join)(hookDir, name);
|
|
163
171
|
(0, fs_1.copyFileSync)((0, path_1.join)(ASSETS, name), dest);
|
|
164
172
|
(0, fs_1.chmodSync)(dest, 0o755);
|
|
165
173
|
}
|
|
166
174
|
(0, fs_1.copyFileSync)((0, path_1.join)(ASSETS, 'SKILL.md'), (0, path_1.join)(skillDir, 'SKILL.md'));
|
|
167
|
-
return { hookPath: (0, path_1.join)(hookDir, 'session-start.sh') };
|
|
175
|
+
return { hookPath: (0, path_1.join)(hookDir, 'session-start.sh'), promptHookPath: (0, path_1.join)(hookDir, 'user-prompt-submit.sh') };
|
|
168
176
|
}
|
|
169
177
|
// A wrong token does not make the server fail loudly — every recall degrades to
|
|
170
178
|
// empty — so the only honest confirmation is one real call before declaring done.
|
|
@@ -268,7 +276,7 @@ async function runSetup(argv = []) {
|
|
|
268
276
|
// The hook is a shell script, so it reads the token from the environment Claude
|
|
269
277
|
// Code gives it, not from the MCP server's env block.
|
|
270
278
|
writeUserEnv((0, path_1.join)((0, os_1.homedir)(), '.claude', 'settings.json'), env);
|
|
271
|
-
const { hookPath } = installAssets();
|
|
279
|
+
const { hookPath, promptHookPath } = installAssets();
|
|
272
280
|
const { already, replaced } = registerSessionStartHook((0, path_1.join)((0, os_1.homedir)(), '.claude', 'settings.json'), hookPath);
|
|
273
281
|
const note = already
|
|
274
282
|
? ' (already registered)'
|
|
@@ -276,6 +284,8 @@ async function runSetup(argv = []) {
|
|
|
276
284
|
? ` (replaced ${replaced} earlier registration${replaced > 1 ? 's' : ''})`
|
|
277
285
|
: '';
|
|
278
286
|
console.log(` SessionStart hook -> ${hookPath}${note}`);
|
|
287
|
+
const prompt = registerPromptHook((0, path_1.join)((0, os_1.homedir)(), '.claude', 'settings.json'), promptHookPath);
|
|
288
|
+
console.log(` UserPromptSubmit hook -> ${promptHookPath}${prompt.already ? ' (already registered)' : ''}`);
|
|
279
289
|
console.log(' skill -> ~/.claude/skills/se-ai-memory-hub/SKILL.md');
|
|
280
290
|
for (const tool of ['curl', 'jq']) {
|
|
281
291
|
if ((0, child_process_1.spawnSync)('which', [tool]).status !== 0) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skedulo/memory-hub-mcp",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
4
4
|
"description": "MCP server for the SE AI Memory Hub: recall and save developer memory from Claude Code and Claude Desktop.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"repository": {
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"access": "public"
|
|
26
26
|
},
|
|
27
27
|
"scripts": {
|
|
28
|
-
"build": "tsc",
|
|
28
|
+
"build": "tsc && ./scripts/source-hash.sh > dist/.source-hash",
|
|
29
29
|
"start": "node dist/index.js",
|
|
30
30
|
"test": "jest",
|
|
31
31
|
"prepack": "./scripts/copy-assets.sh"
|
package/skill-guide.md
CHANGED
|
@@ -27,10 +27,16 @@ filters to facts/scenarios linked to that ticket, and returns nothing (not
|
|
|
27
27
|
everything) if the ref was never used before.
|
|
28
28
|
|
|
29
29
|
Recall truncates every item it lists — 500 characters each, 6000 across the
|
|
30
|
-
result — so a Skill long enough to be worth writing down is
|
|
31
|
-
readable from a recall.
|
|
32
|
-
`
|
|
33
|
-
|
|
30
|
+
result — so a Skill long enough to be worth writing down is rarely fully
|
|
31
|
+
readable from a recall. A cut item ends with a marker such as
|
|
32
|
+
`[cut at 500 of 3,412 chars — memory_get type=Skill uid=<uid>]`; call
|
|
33
|
+
`memory_get` with that `type` and `uid` for the whole thing. No marker means
|
|
34
|
+
the item is complete. A query that is exactly a Skill's or Wiki page's title
|
|
35
|
+
returns that item whole (up to the 6000 total), so use the exact title when you
|
|
36
|
+
know it. Raise `maxCharsPerItem` / `maxTotalChars` instead only when you need
|
|
37
|
+
several long items at once. If `memory_get` or those parameters are missing
|
|
38
|
+
from your tools, your memory-hub-mcp build is stale: tell the user to rerun
|
|
39
|
+
`./scripts/setup-dev.sh` (or `cd memory-hub-mcp && yarn build`) and restart.
|
|
34
40
|
|
|
35
41
|
## Save at the end of a task
|
|
36
42
|
|
|
@@ -51,7 +57,9 @@ Call `memory_save` with a `type` of `'Fact'`, `'Skill'`, `'Scenario'`, or
|
|
|
51
57
|
different repo explicitly" below).
|
|
52
58
|
- **`type: 'Skill'`** — a reusable procedure or fix you'd want to reach
|
|
53
59
|
for again. Pass `title` and `content` (the actual steps/code), and
|
|
54
|
-
optionally `tags`. The repo is attached automatically, as above.
|
|
60
|
+
optionally `tags`. The repo is attached automatically, as above. Recall
|
|
61
|
+
shows only the first 500 characters, so put the answer — the exact
|
|
62
|
+
endpoint, command, or rule — in the first ~400 and the background after it.
|
|
55
63
|
|
|
56
64
|
`tags` (on Fact/Skill/Wiki saves, and on `memory_recall`) is a fixed
|
|
57
65
|
picklist, not a free-form string — pick from `ConnectedFunction`,
|