@skedulo/memory-hub-mcp 0.2.25 → 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.
package/dist/login.js ADDED
@@ -0,0 +1,309 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.performLogin = exports.tokenStatus = exports.authorizeUrl = exports.pkcePair = exports.defaultLoginDeps = exports.LOGIN_MESSAGES = exports.SIGNED_IN_PAGE = void 0;
4
+ const child_process_1 = require("child_process");
5
+ const crypto_1 = require("crypto");
6
+ const http_1 = require("http");
7
+ const net_1 = require("net");
8
+ const credentials_1 = require("./credentials");
9
+ const setup_1 = require("./setup");
10
+ exports.SIGNED_IN_PAGE = '<p style="margin:4em;font-family:sans-serif">Signed in to Memory Hub. You can close this tab.</p>';
11
+ exports.LOGIN_MESSAGES = {
12
+ 'port-busy': "A Memory Hub sign-in is already waiting on port 8888, probably in a browser tab that's already open. Finish signing in there, or wait up to five minutes and try again. If you started a sked login, close it first.",
13
+ timeout: "No sign-in arrived within five minutes. Run the sign-in again when you're ready. If you couldn't sign in to the memory-hub tenant, ask the hub admin for an invite.",
14
+ refused: "The Skedulo sign-in was refused ({detail}). If you can't sign in to the memory-hub tenant, ask the hub admin for an invite.",
15
+ rejected: "You signed in, but the hub didn't accept the token (HTTP {detail}). Ask the hub admin to check your access.",
16
+ network: "Couldn't reach Skedulo ({detail}). Check your network and try again.",
17
+ 'save-failed': "You signed in, but the token couldn't be saved ({detail}). Check that the folder is writable, then sign in again.",
18
+ };
19
+ const CALLBACK_PATH = '/authorize.html';
20
+ const REQUEST_TIMEOUT_MS = 30_000;
21
+ const RECALL_TIMEOUT_MS = 10_000;
22
+ const CLOSE_GRACE_MS = 1000;
23
+ class LoginError extends Error {
24
+ reason;
25
+ detail;
26
+ constructor(reason, detail = '') {
27
+ super(detail);
28
+ this.reason = reason;
29
+ this.detail = detail;
30
+ }
31
+ }
32
+ function openWithOs(url) {
33
+ const [command, args, options] = process.platform === 'darwin'
34
+ ? ['open', [url], {}]
35
+ : process.platform === 'win32'
36
+ ? ['cmd', ['/c', 'start', '""', `"${url}"`], { windowsVerbatimArguments: true }]
37
+ : ['xdg-open', [url], {}];
38
+ const child = (0, child_process_1.spawn)(command, args, { ...options, detached: true, stdio: 'ignore' });
39
+ child.on('error', () => undefined);
40
+ child.unref();
41
+ }
42
+ function defaultLoginDeps() {
43
+ return {
44
+ apiBase: credentials_1.DEFAULT_API_BASE,
45
+ tenant: 'memory-hub',
46
+ port: 8888,
47
+ timeoutMs: 300_000,
48
+ openBrowser: openWithOs,
49
+ fetch,
50
+ save: credentials_1.writeTokenFile,
51
+ };
52
+ }
53
+ exports.defaultLoginDeps = defaultLoginDeps;
54
+ const base64Url = (buffer) => buffer.toString('base64url');
55
+ function pkcePair() {
56
+ const verifier = base64Url((0, crypto_1.randomBytes)(32));
57
+ return { verifier, challenge: base64Url((0, crypto_1.createHash)('sha256').update(verifier).digest()) };
58
+ }
59
+ exports.pkcePair = pkcePair;
60
+ function authorizeUrl(config, challenge, port) {
61
+ const provider = config.authenticationProvider;
62
+ const params = new URLSearchParams({
63
+ response_type: 'code',
64
+ code_challenge: challenge,
65
+ code_challenge_method: 'S256',
66
+ audience: provider.audience,
67
+ client_id: provider.clientId,
68
+ redirect_uri: redirectUri(port),
69
+ response_mode: 'query',
70
+ connection: provider.connections?.[0]?.connection ?? '',
71
+ prompt: 'login',
72
+ });
73
+ if (config.tenantId)
74
+ params.append('tenant_id', config.tenantId);
75
+ return `${provider.issuer}authorize?${params}`;
76
+ }
77
+ exports.authorizeUrl = authorizeUrl;
78
+ const redirectUri = (port) => `http://localhost:${port}${CALLBACK_PATH}`;
79
+ async function tokenStatus(url, token, fetchFn = fetch) {
80
+ try {
81
+ const res = await fetchFn(`${url}/memory/recall`, {
82
+ method: 'POST',
83
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
84
+ body: JSON.stringify({ scope: 'self' }),
85
+ signal: AbortSignal.timeout(RECALL_TIMEOUT_MS),
86
+ });
87
+ return res.status;
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ }
93
+ exports.tokenStatus = tokenStatus;
94
+ function describe(error) {
95
+ const e = error;
96
+ return e?.cause?.code || e?.cause?.message || e?.code || e?.message || String(error);
97
+ }
98
+ function failure(reason, detail = '') {
99
+ return { ok: false, reason, message: exports.LOGIN_MESSAGES[reason].replace('{detail}', () => detail) };
100
+ }
101
+ function escapeHtml(text) {
102
+ return text.replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`);
103
+ }
104
+ async function send(deps, url, init = {}) {
105
+ try {
106
+ return await deps.fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
107
+ }
108
+ catch (error) {
109
+ throw new LoginError('network', describe(error));
110
+ }
111
+ }
112
+ async function readJson(res) {
113
+ try {
114
+ return await res.json();
115
+ }
116
+ catch {
117
+ return undefined;
118
+ }
119
+ }
120
+ async function fetchLoginConfig(deps) {
121
+ const res = await send(deps, `${deps.apiBase}/customer/login/config/team?type=web&name=${encodeURIComponent(deps.tenant)}`);
122
+ if (!res.ok)
123
+ throw new LoginError('network', `HTTP ${res.status}`);
124
+ const config = (await readJson(res))?.result;
125
+ const provider = config?.authenticationProvider;
126
+ if (!config || !provider?.issuer || !provider.clientId)
127
+ throw new LoginError('network', 'unexpected sign-in settings');
128
+ if (provider.name !== 'auth0')
129
+ throw new LoginError('refused', `sign-in provider ${provider.name} is not supported`);
130
+ if (!provider.connections?.length)
131
+ throw new LoginError('refused', 'no sign-in options for this tenant');
132
+ return config;
133
+ }
134
+ function listenOn(server, host, port) {
135
+ return new Promise((resolve, reject) => {
136
+ const onError = (error) => reject(error);
137
+ server.once('error', onError);
138
+ server.listen(port, host, () => {
139
+ server.off('error', onError);
140
+ server.on('error', () => undefined);
141
+ resolve();
142
+ });
143
+ });
144
+ }
145
+ // macOS lets a loopback bind succeed next to a wildcard listener (sked's own login), so bind errors alone miss it.
146
+ function answers(host, port) {
147
+ return new Promise(resolve => {
148
+ const socket = (0, net_1.createConnection)({ host, port, timeout: 500 });
149
+ const done = (busy) => {
150
+ socket.destroy();
151
+ resolve(busy);
152
+ };
153
+ socket.once('connect', () => done(true));
154
+ socket.once('error', () => done(false));
155
+ socket.once('timeout', () => done(false));
156
+ });
157
+ }
158
+ const BUSY = new Set(['EADDRINUSE', 'EACCES']);
159
+ const NO_IPV6 = new Set(['EADDRNOTAVAIL', 'EAFNOSUPPORT', 'EINVAL']);
160
+ // Loopback only, and both families: `localhost` in the browser may resolve to either.
161
+ async function listenLoopback(handler, port) {
162
+ const servers = [];
163
+ if ((await answers('127.0.0.1', port)) || (await answers('::1', port)))
164
+ throw new LoginError('port-busy');
165
+ try {
166
+ const v4 = (0, http_1.createServer)(handler);
167
+ servers.push(v4);
168
+ await listenOn(v4, '127.0.0.1', port);
169
+ const bound = v4.address().port;
170
+ const v6 = (0, http_1.createServer)(handler);
171
+ servers.push(v6);
172
+ try {
173
+ await listenOn(v6, '::1', bound);
174
+ }
175
+ catch (error) {
176
+ const code = error.code ?? '';
177
+ if (!NO_IPV6.has(code))
178
+ throw error;
179
+ servers.pop();
180
+ }
181
+ return servers;
182
+ }
183
+ catch (error) {
184
+ await closeAll(servers);
185
+ const code = error.code ?? '';
186
+ throw BUSY.has(code) ? new LoginError('port-busy') : new LoginError('network', describe(error));
187
+ }
188
+ }
189
+ async function closeAll(servers) {
190
+ await Promise.all(servers.map(server => new Promise(resolve => {
191
+ if (!server.listening)
192
+ return resolve();
193
+ const timer = setTimeout(() => server.closeAllConnections(), CLOSE_GRACE_MS);
194
+ server.close(() => {
195
+ clearTimeout(timer);
196
+ resolve();
197
+ });
198
+ server.closeIdleConnections();
199
+ })));
200
+ }
201
+ async function exchangeCode(deps, config, code, verifier, port) {
202
+ const provider = config.authenticationProvider;
203
+ const form = new URLSearchParams({
204
+ grant_type: 'authorization_code',
205
+ client_id: provider.clientId,
206
+ code_verifier: verifier,
207
+ code,
208
+ redirect_uri: redirectUri(port),
209
+ scope: 'offline_access',
210
+ });
211
+ if (config.tenantId)
212
+ form.append('tenant_id', config.tenantId);
213
+ const res = await send(deps, `${provider.issuer}oauth/token`, {
214
+ method: 'POST',
215
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
216
+ body: form.toString(),
217
+ });
218
+ const body = await readJson(res);
219
+ if (!res.ok || typeof body?.access_token !== 'string') {
220
+ throw new LoginError('refused', body?.error_description || body?.error || `HTTP ${res.status}`);
221
+ }
222
+ return body.access_token;
223
+ }
224
+ async function mintToken(deps, accessToken) {
225
+ const res = await send(deps, `${deps.apiBase}/auth/token`, {
226
+ method: 'POST',
227
+ headers: { authorization: `Bearer ${accessToken}`, 'content-type': 'application/json' },
228
+ body: '{}',
229
+ });
230
+ const token = (await readJson(res))?.result?.token;
231
+ if (!res.ok || typeof token !== 'string' || !token)
232
+ throw new LoginError('refused', `HTTP ${res.status}`);
233
+ return token;
234
+ }
235
+ function reply(res, status, html) {
236
+ res.writeHead(status, { 'content-type': 'text/html; charset=utf-8', connection: 'close' });
237
+ res.end(html);
238
+ }
239
+ async function performLogin(deps = defaultLoginDeps()) {
240
+ let servers = [];
241
+ let timer;
242
+ try {
243
+ const config = await fetchLoginConfig(deps);
244
+ const { verifier, challenge } = pkcePair();
245
+ let resolveCode;
246
+ let rejectCode;
247
+ const codePromise = new Promise((resolve, reject) => {
248
+ resolveCode = resolve;
249
+ rejectCode = reject;
250
+ });
251
+ codePromise.catch(() => undefined);
252
+ servers = await listenLoopback((req, res) => {
253
+ let url;
254
+ try {
255
+ url = new URL(req.url ?? '/', 'http://localhost');
256
+ }
257
+ catch {
258
+ return reply(res, 400, 'Bad request');
259
+ }
260
+ if (req.method !== 'GET' || url.pathname !== CALLBACK_PATH)
261
+ return reply(res, 404, 'Not found');
262
+ const error = url.searchParams.get('error');
263
+ if (error) {
264
+ const detail = url.searchParams.get('error_description') || error;
265
+ reply(res, 400, `<p style="margin:4em;font-family:sans-serif">Sign-in failed: ${escapeHtml(detail)}</p>`);
266
+ return rejectCode(new LoginError('refused', detail));
267
+ }
268
+ const code = url.searchParams.get('code');
269
+ if (!code)
270
+ return reply(res, 400, 'Missing code');
271
+ reply(res, 200, exports.SIGNED_IN_PAGE);
272
+ resolveCode(code);
273
+ }, deps.port);
274
+ const port = servers[0].address().port;
275
+ const url = authorizeUrl(config, challenge, port);
276
+ timer = setTimeout(() => rejectCode(new LoginError('timeout')), deps.timeoutMs);
277
+ try {
278
+ deps.openBrowser(url);
279
+ }
280
+ catch { }
281
+ deps.onUrl?.(url);
282
+ const code = await codePromise;
283
+ const accessToken = await exchangeCode(deps, config, code, verifier, port);
284
+ const token = await mintToken(deps, accessToken);
285
+ const status = await tokenStatus((0, setup_1.functionUrl)(deps.apiBase), token, deps.fetch);
286
+ if (status === undefined)
287
+ throw new LoginError('network', 'the hub did not answer');
288
+ if (status < 200 || status >= 300)
289
+ throw new LoginError('rejected', String(status));
290
+ try {
291
+ deps.save({ token, apiBase: deps.apiBase });
292
+ }
293
+ catch (error) {
294
+ throw new LoginError('save-failed', error?.code || describe(error));
295
+ }
296
+ return { ok: true, apiBase: deps.apiBase };
297
+ }
298
+ catch (error) {
299
+ if (error instanceof LoginError)
300
+ return failure(error.reason, error.detail);
301
+ return failure('network', describe(error));
302
+ }
303
+ finally {
304
+ if (timer)
305
+ clearTimeout(timer);
306
+ await closeAll(servers);
307
+ }
308
+ }
309
+ exports.performLogin = performLogin;
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.runCapture = exports.captureMessage = exports.processAncestors = exports.doneLine = exports.desktopRestartOffer = exports.insideClaudeDesktop = exports.chooseSetup = exports.registerPromptHook = exports.registerSessionStartHook = exports.removeMcpServer = exports.removeCopiedAssets = exports.setCapture = exports.captureOn = exports.CAPTURE_FLAG = exports.unregisterHooks = exports.claudeRunner = exports.installPlugin = exports.enableMarketplaceAutoUpdate = exports.removeUserEnv = exports.writeUserEnv = exports.writeDesktopConfig = exports.writeMcpServer = exports.functionUrl = exports.writeJson = exports.readJson = exports.desktopConfigPath = exports.mcpLaunch = exports.lastLine = exports.isHubSource = exports.pluginInstalled = exports.installedPluginId = exports.installedPluginIds = exports.claudeConfigDir = exports.LEGACY_PLUGIN_ID = exports.PLUGIN_ID = exports.MARKETPLACE_REF = exports.MARKETPLACE_GIT_URL = exports.MARKETPLACE_REPO = exports.LEGACY_MARKETPLACE_NAME = exports.MARKETPLACE_NAME = exports.launchPath = exports.PACKAGE_SPEC = void 0;
3
+ exports.runSetup = exports.runCapture = exports.captureMessage = exports.processAncestors = exports.doneLine = exports.desktopRestartOffer = exports.insideClaudeDesktop = exports.chooseSetup = exports.registerPromptHook = exports.registerSessionStartHook = exports.removeMcpServer = exports.removeCopiedAssets = exports.setCapture = exports.captureOn = exports.CAPTURE_FLAG = exports.unregisterHooks = exports.claudeRunner = exports.installPlugin = exports.enableMarketplaceAutoUpdate = exports.removeUserEnv = exports.allowMemoryHubTools = exports.writeUserEnv = exports.writeDesktopConfig = exports.writeMcpServer = exports.functionUrl = exports.writeJson = exports.readJson = exports.desktopConfigPath = exports.mcpLaunch = exports.lastLine = exports.isHubSource = exports.pluginInstalled = exports.installedPluginId = exports.installedPluginIds = exports.claudeConfigDir = exports.LEGACY_PLUGIN_ID = exports.PLUGIN_ID = exports.DIRECT_ALLOW_RULE = exports.PLUGIN_ALLOW_RULE = exports.MARKETPLACE_REF = exports.MARKETPLACE_GIT_URL = exports.MARKETPLACE_REPO = exports.LEGACY_MARKETPLACE_NAME = exports.MARKETPLACE_NAME = exports.launchPath = exports.PACKAGE_SPEC = 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");
@@ -27,6 +27,8 @@ exports.MARKETPLACE_REPO = 'Skedulo/se-ai-memory-hub';
27
27
  exports.MARKETPLACE_GIT_URL = `https://github.com/${exports.MARKETPLACE_REPO}.git`;
28
28
  // main only moves when a release is merged into it, so installs and updates both get released hooks.
29
29
  exports.MARKETPLACE_REF = 'main';
30
+ exports.PLUGIN_ALLOW_RULE = 'mcp__plugin_memory-hub_memory-hub__*';
31
+ exports.DIRECT_ALLOW_RULE = 'mcp__memory-hub__*';
30
32
  exports.PLUGIN_ID = `memory-hub@${exports.MARKETPLACE_NAME}`;
31
33
  exports.LEGACY_PLUGIN_ID = `memory-hub@${exports.LEGACY_MARKETPLACE_NAME}`;
32
34
  // `||`, not `??`: Claude Code treats an empty CLAUDE_CONFIG_DIR as the current directory.
@@ -194,6 +196,19 @@ function writeUserEnv(path, env) {
194
196
  writeJson(path, settings);
195
197
  }
196
198
  exports.writeUserEnv = writeUserEnv;
199
+ function allowMemoryHubTools(path, rule) {
200
+ const settings = readJson(path);
201
+ const permissions = settings.permissions || {};
202
+ if (permissions.allow !== undefined && !Array.isArray(permissions.allow))
203
+ return false;
204
+ const allow = permissions.allow || [];
205
+ if (allow.includes(rule))
206
+ return true;
207
+ settings.permissions = { ...permissions, allow: [...allow, rule] };
208
+ writeJson(path, settings);
209
+ return true;
210
+ }
211
+ exports.allowMemoryHubTools = allowMemoryHubTools;
197
212
  function removeUserEnv(path, key) {
198
213
  const settings = readJson(path);
199
214
  if (!settings.env || !(key in settings.env))
@@ -752,6 +767,11 @@ async function runSetup(argv = []) {
752
767
  console.log(` UserPromptSubmit hook -> ${promptHookPath}${prompt.already ? ' (already registered)' : ''}`);
753
768
  console.log(` skills -> ~/.claude/skills/ (${(0, asset_sync_1.packagedSkills)(ASSETS).join(', ')})`);
754
769
  }
770
+ if (!argv.includes('--no-allow')) {
771
+ console.log(allowMemoryHubTools(settingsPath, plugin ? exports.PLUGIN_ALLOW_RULE : exports.DIRECT_ALLOW_RULE)
772
+ ? ' Allowed all Memory Hub tools without approval prompts, including delete and share (rerun with --no-allow to skip).'
773
+ : " Couldn't add the Memory Hub allow rule: permissions.allow in settings.json isn't a list.");
774
+ }
755
775
  warnHookTools();
756
776
  console.log();
757
777
  console.log('==> Auto-capture');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skedulo/memory-hub-mcp",
3
- "version": "0.2.25",
3
+ "version": "0.2.26",
4
4
  "description": "MCP server for the Memory Hub: recall and save developer memory from Claude Code and Claude Desktop.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
package/skill-guide.md CHANGED
@@ -62,6 +62,10 @@ several long items at once. If `memory_get` or those parameters are missing
62
62
  from your tools, your memory-hub-mcp build is stale: tell the user to rerun
63
63
  `./scripts/setup-dev.sh` (or `cd memory-hub-mcp && yarn build`) and restart.
64
64
 
65
+ Before relying on a recalled item, `memory_related` lists its linked pages,
66
+ backlinks, Scenario facts, a `superseded by` candidate, same-ticket and same-file items.
67
+ Read only those that bear on the task, at most about 5.
68
+
65
69
  ## Save at the end of a task
66
70
 
67
71
  When you finish a task that produced something durable and worth keeping
@@ -614,7 +618,8 @@ when a file it cites changed since it was verified:
614
618
 
615
619
  No `staleness` field means no change was found, not that the item was verified: an item that cites
616
620
  no file is never marked. `superseded: true` means a newer memory replaced it (tag `Superseded`);
617
- prefer the newer one.
621
+ prefer the newer one, found with `memory_recall` or as a `superseded by` candidate from
622
+ `memory_related`.
618
623
 
619
624
  Before relying on a stale item, verify, then flag, then fix:
620
625