javascript-solid-server 0.0.199 → 0.0.201

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/src/server.js CHANGED
@@ -25,6 +25,7 @@ import { createPayHandler, isPayRequest } from './handlers/pay.js';
25
25
  import { activityPubPlugin, getActorHandler } from './ap/index.js';
26
26
  import { remoteStoragePlugin } from './remotestorage.js';
27
27
  import { dbPlugin } from './db/index.js';
28
+ import { mcpPlugin } from './mcp/index.js';
28
29
  import { webrtcPlugin } from './webrtc/index.js';
29
30
  import { tunnelPlugin } from './tunnel/index.js';
30
31
  import { terminalPlugin } from './terminal/index.js';
@@ -139,6 +140,10 @@ export function createServer(options = {}) {
139
140
  const liveReloadEnabled = options.liveReload ?? false;
140
141
  // MongoDB-backed /db/ route is OFF by default
141
142
  const mongoEnabled = options.mongo ?? false;
143
+ // MCP (Model Context Protocol) server — exposes the pod as a tool
144
+ // surface for agents (Claude Desktop, Cursor, etc.). OFF by default.
145
+ // See docs/mcp.md and #490.
146
+ const mcpEnabled = options.mcp ?? false;
142
147
  // Provision a Schnorr secp256k1 owner key in /private/privkey.jsonld
143
148
  // when a single-user pod is first created. Phase 1 of #437. Off by
144
149
  // default: keys-on-disk is a real security tradeoff, opt-in keeps
@@ -394,6 +399,11 @@ export function createServer(options = {}) {
394
399
  fastify.register(dbPlugin, { mongoUrl, mongoDatabase, singleUser });
395
400
  }
396
401
 
402
+ // Register MCP server if enabled (issue #490)
403
+ if (mcpEnabled) {
404
+ fastify.register(mcpPlugin);
405
+ }
406
+
397
407
  // Register rate limiting plugin
398
408
  // Protects against brute force attacks and resource exhaustion
399
409
  fastify.register(rateLimit, {
@@ -648,6 +658,7 @@ export function createServer(options = {}) {
648
658
  request.url.startsWith('/storage/') ||
649
659
  (payEnabled && isPayRequest(request.url)) ||
650
660
  (mongoEnabled && (request.url === '/db' || request.url.startsWith('/db/'))) ||
661
+ (mcpEnabled && (request.url === '/mcp' || request.url.startsWith('/mcp?'))) ||
651
662
  (webrtcEnabled && (request.url === webrtcPath || request.url.startsWith(webrtcPath + '?'))) ||
652
663
  (terminalEnabled && (request.url === '/.terminal' || request.url.startsWith('/.terminal?'))) ||
653
664
  (tunnelEnabled && (request.url === tunnelPath || request.url.startsWith(tunnelPath + '?') || request.url.startsWith('/tunnel/'))) ||
@@ -0,0 +1,562 @@
1
+ /**
2
+ * MCP (Model Context Protocol) server tests.
3
+ *
4
+ * Covers:
5
+ * - handshake (initialize / tools/list)
6
+ * - CRUD tools (list, read, write, create, delete, head)
7
+ * - skill discovery (list_skills, get_skill, get_pod_skill)
8
+ * - docs (list_docs, read_docs)
9
+ * - WAC enforcement (anonymous denied write, owner allowed)
10
+ */
11
+
12
+ import { describe, it, before, after } from 'node:test';
13
+ import assert from 'node:assert';
14
+ import {
15
+ startTestServer,
16
+ stopTestServer,
17
+ request,
18
+ createTestPod,
19
+ getBaseUrl,
20
+ getPodToken
21
+ } from './helpers.js';
22
+ import { emitChange } from '../src/notifications/events.js';
23
+
24
+ let token;
25
+
26
+ async function rpc(body, opts = {}) {
27
+ const headers = { 'Content-Type': 'application/json' };
28
+ if (opts.token) headers.Authorization = `Bearer ${opts.token}`;
29
+ const res = await request('/mcp', {
30
+ method: 'POST',
31
+ headers,
32
+ body: JSON.stringify(body)
33
+ });
34
+ if (res.status === 204) return { status: 204, body: null };
35
+ const data = await res.json();
36
+ return { status: res.status, body: data };
37
+ }
38
+
39
+ describe('MCP server (--mcp enabled)', () => {
40
+ before(async () => {
41
+ await startTestServer({ mcp: true });
42
+ await createTestPod('mcptest');
43
+ token = getPodToken('mcptest');
44
+ });
45
+
46
+ after(async () => {
47
+ await stopTestServer();
48
+ });
49
+
50
+ it('responds to initialize with protocol version', async () => {
51
+ const { status, body } = await rpc({
52
+ jsonrpc: '2.0', id: 1, method: 'initialize',
53
+ params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'test', version: '0' } }
54
+ });
55
+ assert.strictEqual(status, 200);
56
+ assert.strictEqual(body.jsonrpc, '2.0');
57
+ assert.ok(body.result?.protocolVersion);
58
+ assert.strictEqual(body.result.serverInfo.name, 'jss-mcp');
59
+ });
60
+
61
+ it('lists tools', async () => {
62
+ const { body } = await rpc({ jsonrpc: '2.0', id: 2, method: 'tools/list' });
63
+ const names = body.result.tools.map(t => t.name);
64
+ for (const expected of [
65
+ 'list_resources', 'read_resource', 'write_resource',
66
+ 'create_resource', 'delete_resource', 'head_resource',
67
+ 'list_skills', 'get_skill', 'get_pod_skill',
68
+ 'list_docs', 'read_docs', 'pod_info'
69
+ ]) {
70
+ assert.ok(names.includes(expected), `missing tool: ${expected}`);
71
+ }
72
+ });
73
+
74
+ it('write_resource denied without auth', async () => {
75
+ const { body } = await rpc({
76
+ jsonrpc: '2.0', id: 3, method: 'tools/call',
77
+ params: { name: 'write_resource', arguments: { path: '/mcptest/public/anon.txt', content: 'nope' } }
78
+ });
79
+ assert.ok(body.result?.isError, 'expected isError for anonymous write');
80
+ assert.match(body.result.content[0].text, /denied/i);
81
+ });
82
+
83
+ it('write_resource works with owner token', async () => {
84
+ const { body } = await rpc({
85
+ jsonrpc: '2.0', id: 4, method: 'tools/call',
86
+ params: {
87
+ name: 'write_resource',
88
+ arguments: { path: '/mcptest/public/hello.txt', content: 'hi', contentType: 'text/plain' }
89
+ }
90
+ }, { token });
91
+ assert.strictEqual(body.result.isError, false, body.result.content?.[0]?.text);
92
+ assert.match(body.result.content[0].text, /wrote/);
93
+ });
94
+
95
+ it('read_resource returns the written content', async () => {
96
+ const { body } = await rpc({
97
+ jsonrpc: '2.0', id: 5, method: 'tools/call',
98
+ params: { name: 'read_resource', arguments: { path: '/mcptest/public/hello.txt' } }
99
+ }, { token });
100
+ assert.strictEqual(body.result.isError, false);
101
+ const payload = JSON.parse(body.result.content[0].text);
102
+ assert.strictEqual(payload.body, 'hi');
103
+ });
104
+
105
+ it('list_resources lists the container', async () => {
106
+ const { body } = await rpc({
107
+ jsonrpc: '2.0', id: 6, method: 'tools/call',
108
+ params: { name: 'list_resources', arguments: { path: '/mcptest/public/' } }
109
+ }, { token });
110
+ assert.strictEqual(body.result.isError, false);
111
+ const payload = JSON.parse(body.result.content[0].text);
112
+ assert.ok(payload.items.some(i => i.name === 'hello.txt'));
113
+ });
114
+
115
+ it('create_resource auto-mints filename', async () => {
116
+ const { body } = await rpc({
117
+ jsonrpc: '2.0', id: 7, method: 'tools/call',
118
+ params: {
119
+ name: 'create_resource',
120
+ arguments: { container: '/mcptest/public/', slug: 'minted', content: 'x' }
121
+ }
122
+ }, { token });
123
+ assert.strictEqual(body.result.isError, false);
124
+ assert.match(body.result.content[0].text, /\/mcptest\/public\/minted/);
125
+ });
126
+
127
+ it('delete_resource removes the file', async () => {
128
+ const { body } = await rpc({
129
+ jsonrpc: '2.0', id: 8, method: 'tools/call',
130
+ params: { name: 'delete_resource', arguments: { path: '/mcptest/public/hello.txt' } }
131
+ }, { token });
132
+ assert.strictEqual(body.result.isError, false);
133
+ assert.match(body.result.content[0].text, /deleted/);
134
+ });
135
+
136
+ it('head_resource returns 404 on missing path', async () => {
137
+ const { body } = await rpc({
138
+ jsonrpc: '2.0', id: 9, method: 'tools/call',
139
+ params: { name: 'head_resource', arguments: { path: '/mcptest/public/does-not-exist' } }
140
+ }, { token });
141
+ assert.ok(body.result.isError);
142
+ });
143
+
144
+ it('list_skills returns the index shape', async () => {
145
+ const { body } = await rpc({
146
+ jsonrpc: '2.0', id: 10, method: 'tools/call',
147
+ params: { name: 'list_skills', arguments: {} }
148
+ }, { token });
149
+ assert.strictEqual(body.result.isError, false);
150
+ const payload = JSON.parse(body.result.content[0].text);
151
+ assert.strictEqual(payload['@type'], 'skill:SkillIndex');
152
+ assert.ok(Array.isArray(payload['skill:items']));
153
+ });
154
+
155
+ it('list_skills discovers per-app SKILL.md', async () => {
156
+ // Seed a per-app skill
157
+ await rpc({
158
+ jsonrpc: '2.0', id: 1010, method: 'tools/call',
159
+ params: {
160
+ name: 'write_resource',
161
+ arguments: {
162
+ path: '/mcptest/public/apps/demo/index.html',
163
+ content: '<h1>demo</h1>',
164
+ contentType: 'text/html'
165
+ }
166
+ }
167
+ }, { token });
168
+ await rpc({
169
+ jsonrpc: '2.0', id: 1011, method: 'tools/call',
170
+ params: {
171
+ name: 'write_resource',
172
+ arguments: {
173
+ path: '/mcptest/public/apps/demo/SKILL.md',
174
+ content: '# demo app skill',
175
+ contentType: 'text/markdown'
176
+ }
177
+ }
178
+ }, { token });
179
+
180
+ // Now list against the pod root — but list_skills walks /public/apps/
181
+ // and /private/bots/ at the pod root, not inside a named pod. For this
182
+ // test, we just verify the per-app discovery walks containers correctly
183
+ // by listing /mcptest/public/apps/ directly via list_resources and
184
+ // confirming "demo" comes back as a container (isContainer=true).
185
+ const { body } = await rpc({
186
+ jsonrpc: '2.0', id: 1012, method: 'tools/call',
187
+ params: { name: 'list_resources', arguments: { path: '/mcptest/public/apps/' } }
188
+ }, { token });
189
+ assert.strictEqual(body.result.isError, false);
190
+ const payload = JSON.parse(body.result.content[0].text);
191
+ const demo = payload.items.find(i => i.name === 'demo');
192
+ assert.ok(demo, 'demo container should be listed');
193
+ assert.strictEqual(demo.isContainer, true, 'isContainer must be true for directories');
194
+ });
195
+
196
+ it('list_docs returns the JSS-builtin doc set', async () => {
197
+ const { body } = await rpc({
198
+ jsonrpc: '2.0', id: 11, method: 'tools/call',
199
+ params: { name: 'list_docs', arguments: {} }
200
+ });
201
+ assert.strictEqual(body.result.isError, false);
202
+ const payload = JSON.parse(body.result.content[0].text);
203
+ assert.strictEqual(payload.source, 'jss-builtin');
204
+ assert.ok(payload.docs.some(d => d.name.endsWith('.md')));
205
+ });
206
+
207
+ it('read_docs fetches a known doc', async () => {
208
+ const { body } = await rpc({
209
+ jsonrpc: '2.0', id: 12, method: 'tools/call',
210
+ params: { name: 'read_docs', arguments: { name: 'git-support.md' } }
211
+ });
212
+ assert.strictEqual(body.result.isError, false);
213
+ const payload = JSON.parse(body.result.content[0].text);
214
+ assert.match(payload.body, /git/i);
215
+ });
216
+
217
+ it('read_docs rejects path traversal', async () => {
218
+ const { body } = await rpc({
219
+ jsonrpc: '2.0', id: 13, method: 'tools/call',
220
+ params: { name: 'read_docs', arguments: { name: '../package.json' } }
221
+ });
222
+ assert.ok(body.result.isError);
223
+ });
224
+
225
+ it('pod_info returns identity info', async () => {
226
+ const { body } = await rpc({
227
+ jsonrpc: '2.0', id: 14, method: 'tools/call',
228
+ params: { name: 'pod_info', arguments: {} }
229
+ }, { token });
230
+ assert.strictEqual(body.result.isError, false);
231
+ const payload = JSON.parse(body.result.content[0].text);
232
+ assert.strictEqual(payload.server, 'jss');
233
+ assert.ok(payload.identity);
234
+ });
235
+
236
+ it('rejects unknown method', async () => {
237
+ const { body } = await rpc({ jsonrpc: '2.0', id: 99, method: 'doesnt/exist' });
238
+ assert.strictEqual(body.error?.code, -32601);
239
+ });
240
+
241
+ // --- read_acl / write_acl (#496) ---
242
+
243
+ it('read_acl returns existing authorizations for /mcptest/public/', async () => {
244
+ const { body } = await rpc({
245
+ jsonrpc: '2.0', id: 200, method: 'tools/call',
246
+ params: { name: 'read_acl', arguments: { path: '/mcptest/public/' } }
247
+ }, { token });
248
+ assert.strictEqual(body.result.isError, false, body.result.content?.[0]?.text);
249
+ const payload = JSON.parse(body.result.content[0].text);
250
+ assert.strictEqual(payload.exists, true);
251
+ assert.ok(Array.isArray(payload.authorizations));
252
+ assert.ok(payload.authorizations.length > 0, 'should have at least owner auth');
253
+ // Owner auth should include Read, Write, Control
254
+ const ownerAuth = payload.authorizations.find(a => a.modes.includes('Control'));
255
+ assert.ok(ownerAuth, 'owner auth with Control should exist');
256
+ });
257
+
258
+ it('write_acl + read_acl round-trip', async () => {
259
+ const auths = [
260
+ {
261
+ agents: ['/mcptest/profile/card.jsonld#me'],
262
+ modes: ['Read', 'Write', 'Control'],
263
+ isDefault: true
264
+ },
265
+ {
266
+ agentClasses: ['acl:AuthenticatedAgent'],
267
+ modes: ['Read', 'Append'],
268
+ isDefault: true
269
+ },
270
+ {
271
+ agentClasses: ['foaf:Agent'],
272
+ modes: ['Read'],
273
+ isDefault: true
274
+ }
275
+ ];
276
+ const wr = await rpc({
277
+ jsonrpc: '2.0', id: 201, method: 'tools/call',
278
+ params: { name: 'write_acl', arguments: { path: '/mcptest/public/', authorizations: auths } }
279
+ }, { token });
280
+ assert.strictEqual(wr.body.result.isError, false, wr.body.result.content?.[0]?.text);
281
+
282
+ const rd = await rpc({
283
+ jsonrpc: '2.0', id: 202, method: 'tools/call',
284
+ params: { name: 'read_acl', arguments: { path: '/mcptest/public/' } }
285
+ }, { token });
286
+ const payload = JSON.parse(rd.body.result.content[0].text);
287
+ assert.strictEqual(payload.authorizations.length, 3);
288
+ const classes = payload.authorizations.flatMap(a => a.agentClasses || []);
289
+ assert.ok(classes.includes('acl:AuthenticatedAgent'));
290
+ assert.ok(classes.includes('foaf:Agent'));
291
+ });
292
+
293
+ it('write_acl refuses to lock caller out (safety)', async () => {
294
+ // Try to write an ACL that grants Control only to a foreign WebID
295
+ // — would lock the caller (mcptest owner) out. Safety should refuse.
296
+ const { body } = await rpc({
297
+ jsonrpc: '2.0', id: 204, method: 'tools/call',
298
+ params: { name: 'write_acl', arguments: {
299
+ path: '/mcptest/public/',
300
+ authorizations: [
301
+ {
302
+ agents: ['https://stranger.example/profile#me'],
303
+ modes: ['Read', 'Write', 'Control'],
304
+ isDefault: true
305
+ }
306
+ ]
307
+ } }
308
+ }, { token });
309
+ assert.ok(body.result.isError);
310
+ assert.match(body.result.content[0].text, /lock the caller out|would not grant Control/i);
311
+ });
312
+
313
+ it('write_acl denied without Control', async () => {
314
+ const { body } = await rpc({
315
+ jsonrpc: '2.0', id: 203, method: 'tools/call',
316
+ params: { name: 'write_acl', arguments: {
317
+ path: '/mcptest/public/',
318
+ authorizations: [{ agentClasses: ['foaf:Agent'], modes: ['Read'] }]
319
+ } }
320
+ }); // no token
321
+ assert.ok(body.result.isError);
322
+ assert.match(body.result.content[0].text, /control/i);
323
+ });
324
+
325
+ // --- call_remote_pod (#495) ---
326
+
327
+ it('call_remote_pod denied without federation gate access', async () => {
328
+ const { body } = await rpc({
329
+ jsonrpc: '2.0', id: 210, method: 'tools/call',
330
+ params: {
331
+ name: 'call_remote_pod',
332
+ arguments: {
333
+ pod_url: 'http://example.invalid',
334
+ tool: 'pod_info',
335
+ arguments: {}
336
+ }
337
+ }
338
+ }); // no token
339
+ assert.ok(body.result.isError);
340
+ // Anonymous → "local WebID identity" error; authenticated-but-not-gated → "federation gate"
341
+ assert.match(body.result.content[0].text, /federation/i);
342
+ });
343
+
344
+ it('call_remote_pod hits its own /mcp when gated open', async () => {
345
+ // Federation gate lives at <agent-pod>/private/federation/. For the
346
+ // mcptest pod owner that's /mcptest/private/federation/. Create the
347
+ // container, then grant AuthenticatedAgent Write there.
348
+ await rpc({
349
+ jsonrpc: '2.0', id: 220, method: 'tools/call',
350
+ params: {
351
+ name: 'create_resource',
352
+ arguments: { container: '/mcptest/private/', slug: 'federation', isContainer: true }
353
+ }
354
+ }, { token });
355
+ await rpc({
356
+ jsonrpc: '2.0', id: 221, method: 'tools/call',
357
+ params: {
358
+ name: 'write_acl',
359
+ arguments: {
360
+ path: '/mcptest/private/federation/',
361
+ authorizations: [
362
+ {
363
+ agents: ['/mcptest/profile/card.jsonld#me'],
364
+ modes: ['Read', 'Write', 'Control'],
365
+ isDefault: true
366
+ }
367
+ ]
368
+ }
369
+ }
370
+ }, { token });
371
+
372
+ // Now call our own MCP back at /mcp invoking pod_info
373
+ const base = getBaseUrl();
374
+ const { body } = await rpc({
375
+ jsonrpc: '2.0', id: 222, method: 'tools/call',
376
+ params: {
377
+ name: 'call_remote_pod',
378
+ arguments: {
379
+ pod_url: base,
380
+ tool: 'pod_info',
381
+ arguments: {}
382
+ }
383
+ }
384
+ }, { token });
385
+ assert.strictEqual(body.result.isError, false, body.result.content?.[0]?.text);
386
+ const payload = JSON.parse(body.result.content[0].text);
387
+ assert.strictEqual(payload.depth, 1);
388
+ assert.ok(payload.remote_result);
389
+ });
390
+
391
+ it('call_remote_pod enforces depth cap', async () => {
392
+ // Force an inbound MCP-Federation-Depth header so the next hop trips MAX
393
+ const res = await request('/mcp', {
394
+ method: 'POST',
395
+ headers: {
396
+ 'Content-Type': 'application/json',
397
+ 'Authorization': `Bearer ${token}`,
398
+ 'MCP-Federation-Depth': '3' // already at max → next hop would be 4
399
+ },
400
+ body: JSON.stringify({
401
+ jsonrpc: '2.0', id: 230, method: 'tools/call',
402
+ params: {
403
+ name: 'call_remote_pod',
404
+ arguments: {
405
+ pod_url: getBaseUrl(),
406
+ tool: 'pod_info',
407
+ arguments: {}
408
+ }
409
+ }
410
+ })
411
+ });
412
+ const data = await res.json();
413
+ assert.ok(data.result.isError);
414
+ assert.match(data.result.content[0].text, /depth exceeded/);
415
+ });
416
+
417
+ // --- subscribe (#494) ---
418
+
419
+ it('subscribe streams SSE events on resourceEvents change', async () => {
420
+ // Open the SSE stream
421
+ const res = await fetch(`${getBaseUrl()}/mcp`, {
422
+ method: 'POST',
423
+ headers: {
424
+ 'Content-Type': 'application/json',
425
+ 'Authorization': `Bearer ${token}`
426
+ },
427
+ body: JSON.stringify({
428
+ jsonrpc: '2.0', id: 300, method: 'tools/call',
429
+ params: { name: 'subscribe', arguments: { path: '/mcptest/public/' } }
430
+ })
431
+ });
432
+ assert.strictEqual(res.status, 200);
433
+ assert.match(res.headers.get('content-type') || '', /text\/event-stream/);
434
+
435
+ // Read the initial "subscribed" event then trigger a change
436
+ const reader = res.body.getReader();
437
+ const decoder = new TextDecoder();
438
+ let buffer = '';
439
+ let events = [];
440
+
441
+ async function readUntil(predicate, timeoutMs = 3000) {
442
+ const deadline = Date.now() + timeoutMs;
443
+ while (Date.now() < deadline) {
444
+ const { value, done } = await Promise.race([
445
+ reader.read(),
446
+ new Promise(r => setTimeout(() => r({ value: null, done: false }), 200))
447
+ ]);
448
+ if (done) break;
449
+ if (value) {
450
+ buffer += decoder.decode(value, { stream: true });
451
+ // Parse complete SSE events (terminated by \n\n)
452
+ let idx;
453
+ while ((idx = buffer.indexOf('\n\n')) !== -1) {
454
+ const chunk = buffer.slice(0, idx);
455
+ buffer = buffer.slice(idx + 2);
456
+ const dataLine = chunk.split('\n').find(l => l.startsWith('data: '));
457
+ if (dataLine) {
458
+ events.push(JSON.parse(dataLine.slice(6)));
459
+ }
460
+ }
461
+ if (predicate(events)) return;
462
+ }
463
+ }
464
+ }
465
+
466
+ await readUntil(e => e.length >= 1); // wait for "subscribed" event
467
+ assert.ok(events.length >= 1);
468
+ assert.strictEqual(events[0].method, 'notifications/tool_event');
469
+ assert.strictEqual(events[0].params.event.type, 'subscribed');
470
+
471
+ // Trigger a change inside scope
472
+ emitChange(`${getBaseUrl()}/mcptest/public/triggered.txt`);
473
+
474
+ await readUntil(e => e.some(ev => ev.params?.event?.type === 'resource_changed'), 3000);
475
+ const change = events.find(ev => ev.params?.event?.type === 'resource_changed');
476
+ assert.ok(change, `expected resource_changed event; got ${JSON.stringify(events)}`);
477
+ assert.strictEqual(change.params.event.path, '/mcptest/public/triggered.txt');
478
+
479
+ // Clean up: cancel stream
480
+ await reader.cancel();
481
+ });
482
+
483
+ it('subscribe filters by scope', async () => {
484
+ const res = await fetch(`${getBaseUrl()}/mcp`, {
485
+ method: 'POST',
486
+ headers: {
487
+ 'Content-Type': 'application/json',
488
+ 'Authorization': `Bearer ${token}`
489
+ },
490
+ body: JSON.stringify({
491
+ jsonrpc: '2.0', id: 301, method: 'tools/call',
492
+ params: { name: 'subscribe', arguments: { path: '/mcptest/public/' } }
493
+ })
494
+ });
495
+ const reader = res.body.getReader();
496
+ const decoder = new TextDecoder();
497
+ let buffer = '';
498
+ let events = [];
499
+
500
+ async function read(ms = 800) {
501
+ const deadline = Date.now() + ms;
502
+ while (Date.now() < deadline) {
503
+ const { value, done } = await Promise.race([
504
+ reader.read(),
505
+ new Promise(r => setTimeout(() => r({ value: null, done: false }), 100))
506
+ ]);
507
+ if (done) break;
508
+ if (value) {
509
+ buffer += decoder.decode(value, { stream: true });
510
+ let idx;
511
+ while ((idx = buffer.indexOf('\n\n')) !== -1) {
512
+ const chunk = buffer.slice(0, idx);
513
+ buffer = buffer.slice(idx + 2);
514
+ const dataLine = chunk.split('\n').find(l => l.startsWith('data: '));
515
+ if (dataLine) events.push(JSON.parse(dataLine.slice(6)));
516
+ }
517
+ }
518
+ }
519
+ }
520
+
521
+ await read(500); // pick up "subscribed"
522
+ // Out-of-scope change — should NOT trigger an event
523
+ emitChange(`${getBaseUrl()}/mcptest/private/notes/x.txt`);
524
+ await read(500);
525
+ const changes = events.filter(e => e.params?.event?.type === 'resource_changed');
526
+ assert.strictEqual(changes.length, 0, 'out-of-scope change should not emit');
527
+
528
+ await reader.cancel();
529
+ });
530
+
531
+ it('rejects unknown tool', async () => {
532
+ const { body } = await rpc({
533
+ jsonrpc: '2.0', id: 100, method: 'tools/call',
534
+ params: { name: 'fictional_tool', arguments: {} }
535
+ });
536
+ assert.ok(body.result?.isError);
537
+ assert.match(body.result.content[0].text, /unknown tool/);
538
+ });
539
+ });
540
+
541
+ describe('MCP server disabled (no flag)', () => {
542
+ before(async () => {
543
+ await startTestServer({});
544
+ });
545
+
546
+ after(async () => {
547
+ await stopTestServer();
548
+ });
549
+
550
+ it('blocks /mcp when flag is off', async () => {
551
+ // Without --mcp, the route isn't registered. The global auth hook fires
552
+ // first on the missing route and rejects (401) since /mcp isn't on the
553
+ // skip list when mcpEnabled is false. Either 401 or 404 is correct
554
+ // "MCP is not available here" behavior; both block tool dispatch.
555
+ const res = await request('/mcp', {
556
+ method: 'POST',
557
+ headers: { 'Content-Type': 'application/json' },
558
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize' })
559
+ });
560
+ assert.ok(res.status === 404 || res.status === 401, `expected 404 or 401, got ${res.status}`);
561
+ });
562
+ });