mcp-basic-memory 0.1.1 → 0.1.2

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/README.md CHANGED
@@ -16,7 +16,11 @@ args = ["-y", "--prefer-online", "mcp-basic-memory@latest"]
16
16
  startup_timeout_sec = 180
17
17
  ```
18
18
 
19
- The proxy forwards Basic Memory's MCP messages. It keeps the client connection open when the upstream exits and repeats the MCP handshake on the next request. The latest request selects the idle timeout: one minute for initialization and tool discovery, or thirty minutes for other requests. Outstanding requests keep the upstream running.
19
+ The proxy forwards Basic Memory's MCP messages. It keeps the client connection open when the upstream exits and repeats the legacy MCP handshake when needed. Requests forwarded upstream set the idle timeout to one minute for initialization and tool discovery, or thirty minutes for other requests. Outstanding requests keep the upstream running.
20
+
21
+ Proxy instances share eligible discovery responses in `basic-memory/discovery` under the OS temporary directory. On a cache hit, initialization and tool discovery can complete without starting Basic Memory. The default lifetime is 10 minutes from the last successful write. Set `MCP_BASIC_MEMORY_DISCOVERY_TTL_MS` to change it or set it to `0` to disable caching. For modern MCP, the proxy also respects the server's cache hints. A cache hit or a legacy MCP `ping` leaves the idle deadline unchanged.
22
+
23
+ Cache entries are keyed by the upstream command, arguments, working directory and environment. `CODEX_TOOL_CALL_ID` is excluded by default. Set `MCP_BASIC_MEMORY_CACHE_IGNORE_ENV` to a comma-separated list of additional variable names to exclude from the key. The upstream still receives those variables. The cache holds discovery metadata and tool schemas. It does not hold tool results or environment values.
20
24
 
21
25
  At shutdown, the proxy closes upstream stdin and gives Basic Memory up to one minute to finish cleanup. If the launcher remains running, the proxy terminates its process tree. The same shutdown applies when the client disconnects.
22
26
 
package/cli.js CHANGED
@@ -3,6 +3,7 @@ import { readFile } from 'node:fs/promises';
3
3
  import { homedir } from 'node:os';
4
4
  import { isAbsolute, join } from 'node:path';
5
5
  import { StdioProxy } from './proxy.js';
6
+ import { DiscoveryCache } from './discovery-cache.js';
6
7
 
7
8
  const args = process.argv.slice(2);
8
9
  if (args.length === 1 && ['--version', '-v'].includes(args[0])) {
@@ -23,7 +24,12 @@ if (args.length === 1 && ['--version', '-v'].includes(args[0])) {
23
24
  env.FASTEMBED_CACHE_PATH = join(cache, 'basic-memory', 'fastembed');
24
25
  }
25
26
 
26
- const proxy = new StdioProxy({ command: 'uvx', args: ['basic-memory@latest', 'mcp'], env });
27
+ const launch = { command: 'uvx', args: ['basic-memory@latest', 'mcp'], env };
28
+ const settings = process.platform === 'win32' ? process.env : env;
29
+ const excludeEnv = (settings.MCP_BASIC_MEMORY_CACHE_IGNORE_ENV ?? '').split(',').map(name => name.trim()).filter(Boolean);
30
+ const ttl = settings.MCP_BASIC_MEMORY_DISCOVERY_TTL_MS;
31
+ const ttlMs = ttl && /^\d+$/.test(ttl) ? Number(ttl) : undefined;
32
+ const proxy = new StdioProxy({ ...launch, cache: new DiscoveryCache(launch, { excludeEnv, ttlMs }) });
27
33
  proxy.connect(process.stdin, process.stdout);
28
34
  for (const signal of ['SIGINT', 'SIGTERM']) {
29
35
  process.once(signal, () => { process.stdin.destroy(); void proxy.close(); });
@@ -0,0 +1,169 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { lstatSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+
6
+ export const legacyVersions = new Set(['2024-10-07', '2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25']);
7
+ export const protocolKey = 'io.modelcontextprotocol/protocolVersion';
8
+ const serverInfoKey = 'io.modelcontextprotocol/serverInfo';
9
+ const defaultTtl = 600_000;
10
+ const maxBytes = 4 * 1024 * 1024;
11
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
12
+ const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
13
+ const ordered = value => Array.isArray(value) ? value.map(ordered) : object(value)
14
+ ? Object.fromEntries(Object.keys(value).sort().map(key => [key, ordered(value[key])])) : value;
15
+
16
+ export function launchKey({ command, args, cwd, env, excludeEnv = [], platform = process.platform }) {
17
+ const name = key => platform === 'win32' ? key.toUpperCase() : key;
18
+ const excluded = new Set([name('CODEX_TOOL_CALL_ID'), ...excludeEnv.map(name)]);
19
+ const variables = new Map();
20
+ for (const key of Object.keys(env).sort()) {
21
+ const normalized = name(key);
22
+ if (!excluded.has(normalized) && !variables.has(normalized) && env[key] !== undefined) {
23
+ variables.set(normalized, String(env[key]));
24
+ }
25
+ }
26
+ return digest([command, args, resolve(cwd ?? process.cwd()), [...variables.keys()].sort().map(key => [key, variables.get(key)])]);
27
+ }
28
+
29
+ export function discoveryKey(message, legacy) {
30
+ const { method, params = {} } = message;
31
+ if (!object(params) || params.cursor != null || params.inputResponses != null || params.requestState != null) return null;
32
+ if (method === 'initialize' && legacyVersions.has(params.protocolVersion)) return digest([method, ordered(params)]);
33
+ if ((method === 'tools/list' || method === 'server/discover') && typeof params._meta?.[protocolKey] === 'string') {
34
+ return digest([method, ordered(params)]);
35
+ }
36
+ if (method === 'tools/list' && legacy) return digest([method, legacy, ordered(params)]);
37
+ return null;
38
+ }
39
+
40
+ export const legacyContext = (request, result) => digest([ordered(request.params), result.protocolVersion, ordered(result.capabilities)]);
41
+
42
+ function implementation(info) {
43
+ return object(info) && typeof info.name === 'string' && info.name.length > 0 &&
44
+ typeof info.version === 'string' && info.version.length > 0;
45
+ }
46
+
47
+ export function backendIdentity(result, initializing) {
48
+ const info = initializing ? result?.serverInfo : result?._meta?.[serverInfoKey];
49
+ return implementation(info) ? digest([info.name, info.version]) : null;
50
+ }
51
+
52
+ export function legacyHandshake(result) {
53
+ return object(result) && typeof result.protocolVersion === 'string' && object(result.capabilities) && implementation(result.serverInfo);
54
+ }
55
+
56
+ function sessionMetadata(value) {
57
+ return Array.isArray(value) ? value.some(sessionMetadata) : object(value) &&
58
+ Object.entries(value).some(([key, item]) => /session[_-]?id$/i.test(key) || sessionMetadata(item));
59
+ }
60
+
61
+ function cacheable(method, payload, modern) {
62
+ if (Object.keys(payload).length !== 1) return false;
63
+ if (payload.error) {
64
+ return method === 'server/discover' && payload.error.code === -32601 && typeof payload.error.message === 'string' &&
65
+ Object.keys(payload.error).every(key => key === 'code' || key === 'message');
66
+ }
67
+ const result = payload.result;
68
+ if (!object(result)) return false;
69
+ const common = modern ? ['resultType', 'ttlMs', 'cacheScope', '_meta'] : ['_meta'];
70
+ if (modern && (result.resultType !== 'complete' || !Number.isSafeInteger(result.ttlMs) || result.ttlMs <= 0 ||
71
+ !['public', 'private'].includes(result.cacheScope) || (result._meta !== undefined &&
72
+ (!object(result._meta) || Object.keys(result._meta).some(key => key !== serverInfoKey))))) return false;
73
+ if (result.instructions !== undefined && typeof result.instructions !== 'string') return false;
74
+ if (method === 'initialize') {
75
+ return !modern && legacyHandshake(result) && legacyVersions.has(result.protocolVersion) && !sessionMetadata(result) &&
76
+ Object.keys(result).every(key => ['protocolVersion', 'capabilities', 'serverInfo', 'instructions'].includes(key));
77
+ }
78
+ if (method === 'server/discover') {
79
+ return modern && object(result.capabilities) && Array.isArray(result.supportedVersions) && result.supportedVersions.length > 0 &&
80
+ result.supportedVersions.every(version => typeof version === 'string') && !sessionMetadata(result) &&
81
+ Object.keys(result).every(key => [...common, 'supportedVersions', 'capabilities', 'instructions'].includes(key));
82
+ }
83
+ return method === 'tools/list' && !sessionMetadata(result._meta) && result.nextCursor === undefined &&
84
+ Object.keys(result).every(key => [...common, 'tools'].includes(key)) && Array.isArray(result.tools) &&
85
+ result.tools.every(tool => object(tool) && typeof tool.name === 'string' && tool.name.length > 0 &&
86
+ object(tool.inputSchema) && tool.inputSchema.type === 'object' &&
87
+ !sessionMetadata(Object.fromEntries(Object.entries(tool).filter(([key]) => key !== 'inputSchema' && key !== 'outputSchema'))));
88
+ }
89
+
90
+ export class DiscoveryCache {
91
+ constructor(launch, { directory = join(tmpdir(), 'basic-memory', 'discovery'), ttlMs = defaultTtl,
92
+ excludeEnv = [] } = {}) {
93
+ this.directory = directory;
94
+ this.ttlMs = Number.isSafeInteger(ttlMs) && ttlMs >= 0 ? ttlMs : defaultTtl;
95
+ const key = launchKey({ ...launch, excludeEnv });
96
+ this.file = join(directory, `${key}.json`);
97
+ this.generationFile = join(directory, `${key}.generation`);
98
+ }
99
+
100
+ generation() {
101
+ if (!this.ttlMs) return null;
102
+ try {
103
+ // TEMP may be shared between OS users. Only trust a private directory.
104
+ mkdirSync(this.directory, { recursive: true, mode: 0o700 });
105
+ const directory = lstatSync(this.directory);
106
+ if (!directory.isDirectory() || (process.getuid && (directory.uid !== process.getuid() || (directory.mode & 0o077)))) return null;
107
+ const marker = statSync(this.generationFile, { throwIfNoEntry: false });
108
+ if (!marker) return '';
109
+ if (!marker.isFile() || marker.size !== 36) return 'invalid';
110
+ const generation = readFileSync(this.generationFile, 'utf8');
111
+ return /^[a-f0-9-]{36}$/.test(generation) ? generation : 'invalid';
112
+ } catch { return null; }
113
+ }
114
+
115
+ replace(file, content) {
116
+ const temporary = `${file}.${randomUUID()}.tmp`;
117
+ try {
118
+ writeFileSync(temporary, content, { mode: 0o600, flag: 'wx' });
119
+ renameSync(temporary, file);
120
+ return true;
121
+ } catch { return false; }
122
+ finally { try { rmSync(temporary, { force: true }); } catch { /* cache is optional */ } }
123
+ }
124
+
125
+ read(generation) {
126
+ try {
127
+ if (generation === null || statSync(this.file).size > maxBytes) return null;
128
+ const data = JSON.parse(readFileSync(this.file, 'utf8'));
129
+ return data.schema === 1 && data.generation === generation && object(data.entries) &&
130
+ (data.identity === null || /^[a-f0-9]{64}$/.test(data.identity)) ? data : null;
131
+ } catch { return null; }
132
+ }
133
+
134
+ invalidate() {
135
+ if (this.generation() === null) return null;
136
+ // Readers reject old writes even if a replica was writing when invalidation arrived.
137
+ const generation = randomUUID();
138
+ if (this.replace(this.generationFile, generation)) return generation;
139
+ try { rmSync(this.file, { force: true }); } catch { /* cache is optional */ }
140
+ return null;
141
+ }
142
+
143
+ get(key, method) {
144
+ const generation = this.generation();
145
+ const entry = this.read(generation)?.entries[key];
146
+ const now = Date.now();
147
+ if (!object(entry) || entry.method !== method || typeof entry.modern !== 'boolean' || !object(entry.payload) ||
148
+ !Number.isSafeInteger(entry.createdAt) || entry.createdAt > now || !Number.isSafeInteger(entry.expiresAt) ||
149
+ now >= Math.min(entry.expiresAt, entry.createdAt + this.ttlMs) ||
150
+ !cacheable(method, entry.payload, entry.modern) || this.generation() !== generation) return null;
151
+ if (entry.modern && entry.payload.result) {
152
+ entry.payload.result.ttlMs = Math.min(entry.expiresAt, entry.createdAt + this.ttlMs) - now;
153
+ }
154
+ return entry.payload;
155
+ }
156
+
157
+ save({ key, method, modern, generation }, payload, identity = null) {
158
+ if (!this.ttlMs || generation === null || this.generation() !== generation || !cacheable(method, payload, modern)) return;
159
+ const data = this.read(generation) ?? { schema: 1, generation, identity: null, entries: {} };
160
+ if (identity && data.identity && identity !== data.identity) return;
161
+ if (identity) data.identity = identity;
162
+ const createdAt = Date.now();
163
+ const expiresAt = createdAt + Math.min(this.ttlMs, payload.result?.ttlMs ?? this.ttlMs);
164
+ const entries = Object.entries(data.entries).filter(([id, value]) => id !== key && value?.expiresAt > createdAt).slice(-15);
165
+ data.entries = Object.fromEntries([...entries, [key, { method, modern, createdAt, expiresAt, payload }]]);
166
+ const content = JSON.stringify(data);
167
+ if (Buffer.byteLength(content) <= maxBytes && this.generation() === generation) this.replace(this.file, content);
168
+ }
169
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-basic-memory",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "On-demand stdio proxy for Basic Memory with idle shutdown.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -18,6 +18,7 @@
18
18
  "files": [
19
19
  "cli.js",
20
20
  "proxy.js",
21
+ "discovery-cache.js",
21
22
  "README.md",
22
23
  "LICENSE"
23
24
  ],
@@ -25,7 +26,7 @@
25
26
  "node": ">=22"
26
27
  },
27
28
  "scripts": {
28
- "check": "node --check cli.js && node --check proxy.js && node --test test/*.test.js",
29
+ "check": "node --check cli.js && node --check proxy.js && node --check discovery-cache.js && node --test test/*.test.js",
29
30
  "release:prepare": "npm run check && node scripts/prepare-release.mjs",
30
31
  "release:publish": "node scripts/publish-release.mjs"
31
32
  },
package/proxy.js CHANGED
@@ -2,8 +2,10 @@ import { spawn } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { once } from 'node:events';
4
4
  import { createInterface } from 'node:readline';
5
+ import { backendIdentity, discoveryKey, legacyContext, legacyHandshake, legacyVersions, protocolKey } from './discovery-cache.js';
5
6
 
6
- const discoveryMethods = new Set(['initialize', 'tools/list']);
7
+ const discoveryMethods = new Set(['initialize', 'server/discover', 'tools/list']);
8
+ const listChanged = /^notifications\/(tools|resources|prompts)\/list_changed$/;
7
9
  const report = message => process.stderr.write(`mcp-basic-memory: ${message}\n`);
8
10
 
9
11
  function killTree(child) {
@@ -30,9 +32,9 @@ function killTree(child) {
30
32
 
31
33
  export class StdioProxy {
32
34
  constructor({ command, args = [], env = process.env, cwd, discoveryMs = 60_000,
33
- idleMs = 1_800_000, startupMs = 120_000, shutdownMs = 60_000 }) {
34
- Object.assign(this, { command, args, env, cwd, discoveryMs, idleMs, startupMs, shutdownMs });
35
- this.pending = new Set();
35
+ idleMs = 1_800_000, startupMs = 120_000, shutdownMs = 60_000, cache }) {
36
+ Object.assign(this, { command, args, env, cwd, discoveryMs, idleMs, startupMs, shutdownMs, cache });
37
+ this.pending = new Map();
36
38
  this.serverPending = new Set();
37
39
  this.delay = discoveryMs;
38
40
  this.queued = 0;
@@ -52,7 +54,11 @@ export class StdioProxy {
52
54
  }
53
55
 
54
56
  sendError(id, code, message) {
55
- if (!this.closed) this.output.write(JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } }) + '\n');
57
+ this.reply(id, { error: { code, message } });
58
+ }
59
+
60
+ reply(id, payload) {
61
+ if (!this.closed) this.output.write(JSON.stringify({ jsonrpc: '2.0', id, ...payload }) + '\n');
56
62
  }
57
63
 
58
64
  async receive(line) {
@@ -66,21 +72,49 @@ export class StdioProxy {
66
72
  }
67
73
  const hasId = Object.hasOwn(message, 'id');
68
74
  const request = message.method && hasId;
75
+ const version = message.params?._meta?.[protocolKey];
76
+ const modern = typeof version === 'string' && !legacyVersions.has(version);
77
+ if (message.method === 'ping' && request) {
78
+ if (modern || (!version && this.modern)) this.sendError(message.id, -32601, 'Method not found');
79
+ else this.reply(message.id, { result: {} });
80
+ return;
81
+ }
82
+ const key = request && this.cache ? discoveryKey(message, this.legacyContext) : null;
69
83
  if (request) {
84
+ if (message.method === 'initialize') {
85
+ this.initialize = message;
86
+ this.initialized = null;
87
+ this.modern = false;
88
+ this.legacyResult = null;
89
+ this.legacyContext = null;
90
+ } else if (modern && message.method !== 'server/discover') this.modern = true;
91
+ const cached = key && this.cache.get(key, message.method);
92
+ if (cached) {
93
+ this.acceptDiscovery(message, cached);
94
+ this.reply(message.id, cached);
95
+ return;
96
+ }
70
97
  clearTimeout(this.timer);
71
98
  this.timer = null;
72
99
  this.delay = discoveryMethods.has(message.method) ? this.discoveryMs : this.idleMs;
73
- if (message.method === 'initialize') this.initialize = message;
74
100
  }
75
- if (message.method === 'notifications/initialized') this.initialized = line;
101
+ if (message.method === 'notifications/initialized') {
102
+ this.initialized = line;
103
+ if (!this.upstreamInitialized) return;
104
+ }
76
105
  if (!request && (!this.child || this.stopping)) return;
77
106
  try {
78
- await this.ensureStarted(message.method === 'initialize');
107
+ await this.ensureStarted(modern || message.method === 'initialize' || message.method === 'server/discover');
79
108
  if (this.closed) return;
80
109
  if (!this.child) throw new Error('Basic Memory exited before accepting the request');
81
- if (request) this.pending.add(message.id);
110
+ if (request) this.pending.set(message.id, { message, key, modern, generation: this.childGeneration });
82
111
  else if (hasId) this.serverPending.delete(message.id);
83
112
  this.child.stdin.write(line + '\n');
113
+ if (!hasId && message.method === 'notifications/cancelled') {
114
+ const id = message.params?.requestId;
115
+ const cancelled = this.pending.get(id);
116
+ if (cancelled && cancelled.message.method !== 'initialize') this.pending.delete(id);
117
+ }
84
118
  } catch (error) {
85
119
  if (request) {
86
120
  this.pending.delete(message.id);
@@ -91,32 +125,43 @@ export class StdioProxy {
91
125
 
92
126
  async ensureStarted(initializing) {
93
127
  if (this.stopping) await this.stopping;
94
- if (this.closed || this.child) return;
95
- const child = spawn(this.command, this.args, {
96
- cwd: this.cwd, env: this.env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true,
97
- detached: process.platform !== 'win32',
98
- });
99
- this.child = child;
100
- child.stdin.on('error', () => {});
101
- child.stderr.pipe(process.stderr, { end: false });
102
- let failure;
103
- child.on('error', error => { failure = error.message; });
104
- child.once('close', (code, signal) => this.disconnected(child, failure || `Basic Memory exited (${signal ?? code})`));
105
- const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
106
- lines.on('line', line => this.fromUpstream(line));
107
- await once(child, 'spawn');
108
-
109
- if (initializing || !this.initialize) return;
110
- if (this.closed || this.child !== child) throw new Error('Basic Memory exited during startup');
128
+ if (this.closed) return;
129
+ if (!this.child) {
130
+ this.childGeneration = this.cache?.generation();
131
+ const child = spawn(this.command, this.args, {
132
+ cwd: this.cwd, env: this.env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true,
133
+ detached: process.platform !== 'win32',
134
+ });
135
+ this.child = child;
136
+ child.stdin.on('error', () => {});
137
+ child.stderr.pipe(process.stderr, { end: false });
138
+ let failure;
139
+ child.on('error', error => { failure = error.message; });
140
+ child.once('close', (code, signal) => this.disconnected(child, failure || `Basic Memory exited (${signal ?? code})`));
141
+ const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
142
+ lines.on('line', line => this.fromUpstream(line));
143
+ await once(child, 'spawn');
144
+ }
145
+
146
+ if (initializing || !this.legacyResult || this.upstreamInitialized) return;
147
+ const child = this.child;
148
+ if (this.closed || !child) throw new Error('Basic Memory exited during startup');
111
149
  const id = `proxy-initialize-${randomUUID()}`;
112
150
  this.bootstrapId = id;
113
151
  let timer;
114
152
  try {
115
- await new Promise((resolve, reject) => {
153
+ const result = await new Promise((resolve, reject) => {
116
154
  timer = setTimeout(() => reject(new Error('Basic Memory initialization timed out')), this.startupMs);
117
155
  this.bootstrap = { id, resolve, reject };
118
156
  child.stdin.write(JSON.stringify({ ...this.initialize, id }) + '\n');
119
157
  });
158
+ if (!legacyHandshake(result) || legacyContext(this.initialize, result) !== this.legacyContext) {
159
+ this.invalidateDiscovery();
160
+ throw new Error('Basic Memory protocol or capabilities changed. Reconnect the MCP client.');
161
+ }
162
+ this.upstreamInitialized = true;
163
+ const key = this.cache && discoveryKey(this.initialize);
164
+ if (key) this.cache.save({ key, method: 'initialize', modern: false, generation: this.childGeneration }, { result }, this.childIdentity);
120
165
  if (this.initialized) child.stdin.write(this.initialized + '\n');
121
166
  } catch (error) {
122
167
  void this.stop();
@@ -132,27 +177,66 @@ export class StdioProxy {
132
177
  try { message = JSON.parse(line); }
133
178
  catch { report('discarded non-JSON upstream output'); return; }
134
179
  if (!message || typeof message !== 'object' || Array.isArray(message)) return;
135
- if (!message.method && message.id === this.bootstrapId && this.bootstrapId) {
136
- if (message.error) this.bootstrap?.reject(new Error(message.error.message));
137
- else this.bootstrap?.resolve();
180
+ if (listChanged.test(message.method)) this.invalidateDiscovery();
181
+ if (message.method === 'notifications/cancelled') this.serverPending.delete(message.params?.requestId);
182
+ const response = !message.method && Object.hasOwn(message, 'id');
183
+ const bootstrap = response && this.bootstrapId && message.id === this.bootstrapId;
184
+ const entry = response && this.pending.get(message.id);
185
+ const previousGeneration = this.childGeneration;
186
+ if (bootstrap || entry) this.observeIdentity(backendIdentity(message.result, bootstrap || entry.message.method === 'initialize'));
187
+ if (bootstrap) {
188
+ if (message.error) {
189
+ if ([-32601, -32602].includes(message.error.code)) this.invalidateDiscovery();
190
+ this.bootstrap?.reject(new Error(message.error.message));
191
+ } else this.bootstrap?.resolve(message.result);
138
192
  return;
139
193
  }
140
194
  if (Object.hasOwn(message, 'id')) {
141
195
  if (message.method) this.serverPending.add(message.id);
142
- else this.pending.delete(message.id);
196
+ else {
197
+ this.pending.delete(message.id);
198
+ if (entry) {
199
+ const payload = message.error ? { error: message.error } : { result: message.result };
200
+ this.acceptDiscovery(entry.message, payload);
201
+ if (entry.message.method === 'initialize' && legacyHandshake(message.result)) this.upstreamInitialized = true;
202
+ if (entry.key && entry.generation === previousGeneration) {
203
+ this.cache.save({ ...entry, method: entry.message.method, generation: this.childGeneration }, payload, this.childIdentity);
204
+ }
205
+ }
206
+ }
143
207
  }
144
208
  if (!this.closed) this.output.write(line + '\n');
145
209
  this.arm();
146
210
  }
147
211
 
212
+ acceptDiscovery(request, { result }) {
213
+ if (request.method === 'initialize' && legacyHandshake(result)) {
214
+ this.legacyResult = result;
215
+ this.legacyContext = legacyContext(request, result);
216
+ } else if (request.method === 'server/discover' && Array.isArray(result?.supportedVersions)) this.modern = true;
217
+ }
218
+
219
+ observeIdentity(identity) {
220
+ if (!identity || identity === this.childIdentity) return;
221
+ const previous = this.childIdentity ?? this.cache?.read(this.childGeneration)?.identity;
222
+ this.childIdentity = identity;
223
+ if (previous && previous !== identity && this.cache?.generation() === this.childGeneration) this.invalidateDiscovery();
224
+ }
225
+
226
+ invalidateDiscovery() {
227
+ if (this.cache) this.childGeneration = this.cache.invalidate();
228
+ }
229
+
148
230
  disconnected(child, reason) {
149
231
  if (child !== this.child) return;
150
232
  this.child = null;
233
+ this.childIdentity = null;
234
+ this.upstreamInitialized = false;
151
235
  clearTimeout(this.timer);
152
236
  this.timer = null;
153
237
  this.bootstrap?.reject(new Error(reason));
154
238
  this.bootstrapId = null;
155
- for (const id of this.pending) this.sendError(id, -32603, reason);
239
+ for (const id of this.pending.keys()) this.sendError(id, -32603, reason);
156
240
  this.pending.clear();
157
241
  this.serverPending.clear();
158
242
  }