-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathlistChanged.ts
More file actions
346 lines (323 loc) · 12.8 KB
/
Copy pathlistChanged.ts
File metadata and controls
346 lines (323 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/**
* MCP server-push notification dispatcher (#619). Subscribes to Harper's
* existing role-cache-invalidation + schema-reload event channels and
* emits per-session `notifications/tools/list_changed` /
* `notifications/resources/list_changed` frames over the registered
* SSE streams.
*
* Per-session computation only — never broadcast. For each event, we
* walk the per-worker session registry, re-resolve the session's user
* (so the diff sees the freshly-mutated permission set, not the snapshot
* captured at GET-stream open), recompute that session's tools/list (or
* resources/list) under the fresh user, diff against the snapshot from
* the prior emission, and push a notification iff the visible set
* actually changed. Sessions whose visible surface is unchanged see
* nothing.
*/
import harperLogger from '../../utility/logging/harper_logger.ts';
import { listResources, listResourceTemplates } from './resources.ts';
import {
type RegisteredSession,
forEachSessionByProfile,
getRegisteredSession,
pushSessionFrame,
} from './sessionRegistry.ts';
import { listTools, type AuthedUser } from './toolRegistry.ts';
import { refreshApplicationTools } from './tools/application.ts';
import type { McpProfile } from './transport.ts';
const MAX_TOOLS_PAGE = 1000;
const MAX_RESOURCES_PAGE = 1000;
let initialized = false;
let onUserChangeBound: (() => void) | undefined;
let onSchemaChangeBound: (() => void) | undefined;
// Test seams: avoid importing the real ITC handler from unit tests.
let _itcHandlersOverride:
| {
userHandler?: { addListener?: (fn: () => void) => void };
schemaHandler?: { addListener?: (fn: () => void) => void };
}
| undefined;
export function _setItcHandlersForTest(
h:
| {
userHandler?: { addListener?: (fn: () => void) => void };
schemaHandler?: { addListener?: (fn: () => void) => void };
}
| undefined
): void {
_itcHandlersOverride = h;
}
export function _resetListChangedForTest(): void {
initialized = false;
onUserChangeBound = undefined;
onSchemaChangeBound = undefined;
}
function loadItcHandlers():
| {
userHandler?: { addListener?: (fn: () => void) => void };
schemaHandler?: { addListener?: (fn: () => void) => void };
}
| undefined {
if (_itcHandlersOverride) return _itcHandlersOverride;
try {
return require('../../server/itc/serverHandlers');
} catch (err) {
harperLogger.trace(`MCP listChanged: ITC handlers unavailable (${(err as Error).message})`);
return undefined;
}
}
// Test seam: lets unit tests stub the user re-resolution without pulling in
// security/user.ts (which initializes the system catalogs at module-load).
let _userResolverOverride: ((username: string) => Promise<AuthedUser | undefined>) | undefined;
export function _setUserResolverForTest(fn: ((username: string) => Promise<AuthedUser | undefined>) | undefined): void {
_userResolverOverride = fn;
}
async function resolveUser(username: string | undefined): Promise<AuthedUser | undefined> {
if (!username) return undefined;
if (_userResolverOverride) return _userResolverOverride(username);
try {
const { findAndValidateUser } = require('../../security/user');
const fresh = await findAndValidateUser(username, null, false);
return fresh as AuthedUser;
} catch (err) {
harperLogger.trace(`MCP listChanged: user re-resolve failed for ${username}: ${(err as Error).message}`);
return undefined;
}
}
function toolsListNames(profile: McpProfile, session: RegisteredSession): Array<{ name: string }> {
const { tools } = listTools({
user: session.user,
profile,
sessionId: session.sessionId,
limit: MAX_TOOLS_PAGE,
});
return tools.map((t) => ({ name: t.name }));
}
function resourcesListUris(profile: McpProfile, session: RegisteredSession): Array<{ uri: string }> {
const result = listResources({ user: session.user, profile, limit: MAX_RESOURCES_PAGE });
const uris = result.resources.map((r) => ({ uri: r.uri }));
// Templates are part of the advertised resource surface too: a rebuild can
// add/remove a custom mcpResources uriTemplate while the fixed-URI set stays
// identical (#1609). Fold them into the diffed snapshot (prefixed so a
// template can't collide with a fixed URI of the same spelling).
const templates = listResourceTemplates(profile, undefined, MAX_RESOURCES_PAGE);
for (const t of templates.resourceTemplates) {
uris.push({ uri: `template:${t.uriTemplate}` });
}
return uris;
}
function sameSet(
a: ReadonlyArray<{ name?: string; uri?: string }> | undefined,
b: ReadonlyArray<{ name?: string; uri?: string }>
): boolean {
if (!a) return false;
if (a.length !== b.length) return false;
const aKeys = new Set(a.map((x) => x.name ?? x.uri));
for (const x of b) {
if (!aKeys.has(x.name ?? x.uri)) return false;
}
return true;
}
/**
* Re-emit `notifications/tools/list_changed` for one session iff its
* visible tools list has changed since the last snapshot. Wrapped in
* try/catch so a single failing session never breaks the loop.
*/
function maybeNotifyToolsChanged(record: RegisteredSession): void {
try {
const current = toolsListNames(record.profile, record);
if (sameSet(record.lastTools, current)) return;
record.lastTools = current;
pushSessionFrame(record, {
event: 'message',
data: { jsonrpc: '2.0', method: 'notifications/tools/list_changed' },
});
} catch (err) {
harperLogger.trace(`MCP listChanged tools/* for session ${record.sessionId}: ${(err as Error).message}`);
}
}
function maybeNotifyResourcesChanged(record: RegisteredSession): void {
try {
const current = resourcesListUris(record.profile, record);
if (sameSet(record.lastResources, current)) return;
record.lastResources = current;
pushSessionFrame(record, {
event: 'message',
data: { jsonrpc: '2.0', method: 'notifications/resources/list_changed' },
});
} catch (err) {
harperLogger.trace(`MCP listChanged resources/* for session ${record.sessionId}: ${(err as Error).message}`);
}
}
/**
* Re-diff every session's visible resource list on a profile and push
* `notifications/resources/list_changed` to the sessions whose list actually
* changed. Called by the application registration after a rebuild so custom
* `mcpResources` additions/removals propagate (#1609); the per-session diff in
* `maybeNotifyResourcesChanged` keeps no-op rebuilds silent.
*/
export function notifyResourcesListChanged(profile: McpProfile): void {
for (const record of snapshotSessions(profile)) {
maybeNotifyResourcesChanged(record);
}
}
/**
* Re-diff every session's visible tool list on a profile and push
* `notifications/tools/list_changed` to the sessions whose list actually
* changed. The schema-change handler already does this, but the lazy
* per-request rebuild (`ensureApplicationToolsFresh`, #1609) can add/remove
* custom `mcpTools` outside any schema event — without this, a session that
* initialized before a tableless component registered keeps a stale tool
* list until it happens to re-poll `tools/list`.
*/
export function notifyToolsListChanged(profile: McpProfile): void {
for (const record of snapshotSessions(profile)) {
maybeNotifyToolsChanged(record);
}
}
/**
* Push `notifications/prompts/list_changed` to every session on a profile.
* Prompts carry no per-user RBAC (they're generic templates, §3.5), so unlike
* tools/resources this is a flat per-profile fan-out rather than a per-session
* user-diff. Called by the application registration when the prompt set actually
* changes (added/removed) — not on every rebuild.
*/
export function notifyPromptsListChanged(profile: McpProfile): void {
forEachSessionByProfile(profile, (record) => {
try {
pushSessionFrame(record, {
event: 'message',
data: { jsonrpc: '2.0', method: 'notifications/prompts/list_changed' },
});
} catch (err) {
harperLogger.trace(`MCP listChanged prompts/* for session ${record.sessionId}: ${(err as Error).message}`);
}
});
}
/**
* Snapshot the current registry as a flat list so re-resolves can happen
* sequentially without re-walking the live map (which a concurrent
* registerSession could mutate mid-iteration).
*/
function snapshotSessions(profile: McpProfile): RegisteredSession[] {
const out: RegisteredSession[] = [];
forEachSessionByProfile(profile, (r) => out.push(r));
return out;
}
async function refreshSessionUser(record: RegisteredSession): Promise<void> {
const fresh = await resolveUser(record.user?.username);
if (fresh) record.user = fresh;
}
/**
* Fan out a user/role change: for each session on either profile,
* re-resolve the user (so a role-perm mutation is visible to the diff —
* the captured `record.user` at GET-stream open is otherwise frozen),
* recompute the tools list and notify if changed. Resources may also
* change visibility (table-perm-gated schema URIs), so we re-check
* those too.
*/
async function onUserChange(): Promise<void> {
for (const r of snapshotSessions('operations')) {
await refreshSessionUser(r);
maybeNotifyToolsChanged(r);
maybeNotifyResourcesChanged(r);
}
for (const r of snapshotSessions('application')) {
await refreshSessionUser(r);
maybeNotifyToolsChanged(r);
maybeNotifyResourcesChanged(r);
}
}
/**
* Schema changes touch both surfaces — application-profile tools are
* generated from the Resources registry, and operations-profile
* resources include the OPERATION list (unchanged) plus harper://schema
* URIs (changed). Application sessions need the bigger refresh. We also
* re-resolve the user here in case the schema change coincided with a
* role mutation (Harper sometimes fires both channels on database-level
* grants).
*/
async function onSchemaChange(): Promise<void> {
// Rebuild the application tool registry first so `tools/list` reflects the
// current schema graph (a table may have been added/removed after the MCP
// component loaded). No-op when the application profile isn't enabled.
// Guarded: a throw here (e.g. an unexpected Resource shape during schema
// iteration) must not abort the session-notification loops below.
try {
refreshApplicationTools();
} catch (err) {
// warn, not trace: a tool-rebuild failure leaves `tools/list` stale, which
// is invisible at default log levels if only traced. The notification loops
// below still run.
harperLogger.warn(`MCP listChanged refreshApplicationTools failed: ${(err as Error).message}`);
}
for (const r of snapshotSessions('application')) {
await refreshSessionUser(r);
maybeNotifyToolsChanged(r);
maybeNotifyResourcesChanged(r);
}
// Operations sessions only need resources/list refresh — there are no
// schema-derived operations tools, but `harper://schema/...` URIs may
// shift if a new table appears under a database the user can describe.
for (const r of snapshotSessions('operations')) {
await refreshSessionUser(r);
maybeNotifyResourcesChanged(r);
}
}
/**
* Idempotent: subscribe once at component boot. Repeated calls are
* no-ops. Returns true if subscriptions were actually installed (false
* if Harper's ITC handlers aren't available in this process).
*/
export function initListChanged(): boolean {
if (initialized) return true;
const handlers = loadItcHandlers();
if (!handlers) return false;
let installed = 0;
if (handlers.userHandler?.addListener) {
// Harper's ITC handler treats listeners as `() => void`. Our handler is
// async (re-resolves users); fire-and-forget with a swallow so a rejection
// can never escape the event emitter as an UnhandledPromiseRejection.
onUserChangeBound = () => {
onUserChange().catch((err) => harperLogger.trace(`MCP listChanged onUserChange: ${(err as Error).message}`));
};
handlers.userHandler.addListener(onUserChangeBound);
installed++;
}
if (handlers.schemaHandler?.addListener) {
onSchemaChangeBound = () => {
onSchemaChange().catch((err) => harperLogger.trace(`MCP listChanged onSchemaChange: ${(err as Error).message}`));
};
handlers.schemaHandler.addListener(onSchemaChangeBound);
installed++;
}
initialized = installed > 0;
if (initialized) {
harperLogger.info(`MCP listChanged: subscribed to ${installed} event channel(s)`);
} else {
harperLogger.warn(
'MCP listChanged: ITC handlers do not expose addListener; list_changed notifications will not fire'
);
}
return initialized;
}
/**
* Compute and stash the initial tools/resources snapshot for a session
* that just opened its GET stream. Without this seed, the first event
* would always be a "changed" because `lastTools === undefined !==
* current`. Call right after registerSession.
*/
export function seedSessionSnapshot(sessionId: string): void {
const record = getRegisteredSession(sessionId);
if (!record) return;
try {
record.lastTools = toolsListNames(record.profile, record);
} catch (err) {
harperLogger.trace(`MCP seed tools list for ${sessionId}: ${(err as Error).message}`);
}
try {
record.lastResources = resourcesListUris(record.profile, record);
} catch (err) {
harperLogger.trace(`MCP seed resources list for ${sessionId}: ${(err as Error).message}`);
}
}