javascript-solid-server 0.0.200 → 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/docs/mcp.md CHANGED
@@ -82,6 +82,79 @@ Both `SKILL.md` (Anthropic markdown format) and `SKILL.jsonld` (typed JSON-LD de
82
82
 
83
83
  Pod-resident docs (`/docs/`, `/public/apps/<name>/docs/`) are reachable via the regular CRUD tools — no separate surface.
84
84
 
85
+ ### ACL editing (#496)
86
+
87
+ The most common owner operation is delegating an agent access to a resource. The MCP server exposes ACL editing as first-class tools so bots don't need to hand-roll JSON-LD.
88
+
89
+ | Tool | Effect | WAC check |
90
+ |---|---|---|
91
+ | `read_acl` | Return the ACL for a resource as a structured list (agents, agentClasses, modes, isDefault) | Control on resource |
92
+ | `write_acl` | Persist a structured ACL to the resource's `.acl` file | Control on resource |
93
+
94
+ ```json
95
+ // write_acl arguments
96
+ {
97
+ "path": "/private/notes/",
98
+ "authorizations": [
99
+ {
100
+ "agents": ["did:nostr:abc...", "https://alice.example.com/profile#me"],
101
+ "modes": ["Read", "Append"],
102
+ "isDefault": true
103
+ },
104
+ {
105
+ "agentClasses": ["acl:AuthenticatedAgent"],
106
+ "modes": ["Read"]
107
+ }
108
+ ]
109
+ }
110
+ ```
111
+
112
+ The structured form abstracts away JSON-LD shape (`acl:agent` vs `acl:agentClass`, mode URI prefixes, `acl:default` propagation). New WAC vocabulary additions extend the structure without breaking existing bots.
113
+
114
+ ### Subscribe — live change notifications (#494)
115
+
116
+ `subscribe` is a streaming tool. The response switches to SSE (`text/event-stream`) and emits MCP notifications as resources change. WAC-filtered per event so subscribers only see resources they have Read access to.
117
+
118
+ | Tool | Effect |
119
+ |---|---|
120
+ | `subscribe` | Stream resource_changed events for a container subtree or specific path |
121
+
122
+ ```bash
123
+ curl -N http://localhost:4443/mcp \
124
+ -H "Content-Type: application/json" \
125
+ -H "Authorization: Bearer $TOKEN" \
126
+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"subscribe","arguments":{"path":"/forum/channels/general/"}}}'
127
+ ```
128
+
129
+ Events arrive as:
130
+ ```
131
+ event: notification
132
+ data: {"jsonrpc":"2.0","method":"notifications/tool_event","params":{"tool":"subscribe","event":{"type":"resource_changed","path":"/forum/channels/general/abc.jsonld"}}}
133
+ ```
134
+
135
+ For chat-style bots, replace polling with `subscribe` and react to events as they land.
136
+
137
+ ### Federation — bot-to-bot (#495)
138
+
139
+ `call_remote_pod` lets a bot on this pod invoke MCP tools on another pod. WAC-gated on both ends; depth-capped at 3 hops.
140
+
141
+ | Tool | Effect | Gating |
142
+ |---|---|---|
143
+ | `call_remote_pod` | Forward an MCP `tools/call` to another pod | Caller needs acl:Write on `<their-pod>/private/federation/` on this pod |
144
+
145
+ ```json
146
+ {
147
+ "pod_url": "https://alice.example.com",
148
+ "tool": "read_resource",
149
+ "arguments": { "path": "/public/notes/shared.md" },
150
+ "auth": { "type": "bearer", "token": "..." }
151
+ }
152
+ ```
153
+
154
+ To delegate outbound federation to a specific agent, grant them `acl:Write` on your `/private/federation/` container. Owners control which agents can initiate calls; remote pods control what they expose.
155
+
156
+ Foreign WebIDs (identities hosted on other pods) cannot initiate federation from this pod — there's no local path for the gate to live at. Multi-pod federation chains compose by hopping between pods, each gated locally.
157
+
85
158
  ### Introspection
86
159
 
87
160
  | Tool | Returns |
@@ -98,13 +171,47 @@ http://localhost:4443/mcp
98
171
 
99
172
  For authenticated access, configure the client to send `Authorization: Bearer <token>`. Tokens come from `POST /idp/credentials` (username/password) or from any compatible OIDC/DPoP flow.
100
173
 
174
+ ## Footguns
175
+
176
+ A short list of real gotchas to know about, learned from live-fire use:
177
+
178
+ ### Use absolute WebIDs in `write_acl` agents
179
+
180
+ The `agents` array in a `write_acl` authorization is interpreted as a list of URIs. Relative paths (e.g. `../profile/card.jsonld#me`) resolve against the **.acl file's URL**, not the pod root — and the .acl URL changes depending on which resource the ACL applies to. Two pitfalls:
181
+
182
+ ```json
183
+ // Pod owner WebID: http://example.com/profile/card.jsonld#me
184
+ // Writing this ACL to /public/forum/.acl:
185
+ {
186
+ "agents": ["../profile/card.jsonld#me"], // wrong — resolves to /public/profile/card.jsonld#me
187
+ "agents": ["./profile/card.jsonld#me"], // wrong — resolves to /public/forum/profile/card.jsonld#me
188
+ "agents": ["/profile/card.jsonld#me"], // right — absolute path, resolves to /profile/card.jsonld#me
189
+ "agents": ["http://example.com/profile/card.jsonld#me"] // right — absolute URL, host-portable
190
+ }
191
+ ```
192
+
193
+ **Always use absolute WebID URLs unless you know exactly what relative-URL resolution will give you.** Absolute URLs also make the ACL portable across hostnames.
194
+
195
+ ### `write_acl` will refuse if you'd lock yourself out
196
+
197
+ If the proposed ACL doesn't grant `Control` to the caller (typically a relative-URL mistake), `write_acl` refuses with an explanatory error. This is a safety, not a permission check — it's stopping you from breaking your own access.
198
+
199
+ If you really want to transfer ownership (remove your own access), do it in two steps:
200
+
201
+ 1. First `write_acl` granting Control to the new owner *in addition to* yourself
202
+ 2. Then the new owner calls `write_acl` removing you
203
+
204
+ ### Subscribe over long-running connections needs a keep-alive client
205
+
206
+ The `subscribe` tool keeps an HTTP+SSE connection open indefinitely. Some HTTP clients, proxies, or load balancers will time out idle streams. If you're subscribing for hours, ensure your client handles SSE reconnect (most do; raw `curl` does not).
207
+
101
208
  ## What's not included (yet)
102
209
 
103
- The first cut ships CRUD, ACL-as-resource (you can read/write `.acl` files via the regular tools), skills, docs, and introspection. Deferred:
210
+ The current cut ships CRUD, structured ACL editing, subscribe, federation, skills, docs, and introspection. Deferred:
104
211
 
105
212
  - **`update_resource` (PATCH)** — SPARQL Update / N3 patches. Read-modify-write through the CRUD tools is the workaround.
106
- - **`subscribe`** — wrap JSS's WebSocket notifications as MCP events over SSE. Today, agents can `read_resource` + poll.
107
- - **`call_remote_pod`** — federation primitive for bot-to-bot. Today, an agent can talk to two pods by registering both as MCP servers in its client.
213
+ - **Discovery layer** — no DNS SRV / Solid Type Index entry for "this pod offers MCP". Owners share URLs explicitly today.
214
+ - **Pod-resident federation credentials** — every `call_remote_pod` carries its own auth. A vault for storing remote-pod credentials is a separate security surface worth its own design pass.
108
215
 
109
216
  These are tracked as follow-ups on issue #490.
110
217
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "javascript-solid-server",
3
- "version": "0.0.200",
3
+ "version": "0.0.201",
4
4
  "description": "A minimal, fast Solid server",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
package/src/mcp/index.js CHANGED
@@ -23,7 +23,7 @@ import {
23
23
  rpcResult,
24
24
  rpcError
25
25
  } from './protocol.js';
26
- import { listToolsForRpc, callTool } from './tools.js';
26
+ import { listToolsForRpc, callTool, TOOLS } from './tools.js';
27
27
  import { getWebIdFromRequestAsync } from '../auth/token.js';
28
28
 
29
29
  const ALLOWED_METHODS = new Set([
@@ -84,6 +84,75 @@ async function dispatch(msg, ctx) {
84
84
  return rpcError(id, RPC_ERRORS.METHOD_NOT_FOUND, `unhandled method: ${method}`);
85
85
  }
86
86
 
87
+ function isStreamingToolCall(body) {
88
+ return body
89
+ && body.method === 'tools/call'
90
+ && body.params?.name
91
+ && TOOLS[body.params.name]
92
+ // Sniff: invoke the handler synchronously so we can detect the
93
+ // `{ stream: true, init, run }` shape. Streaming tools must be
94
+ // pure-synchronous in their shape-decision (no awaits before
95
+ // returning the stream descriptor).
96
+ && (() => {
97
+ try {
98
+ // We can't safely call the handler without a ctx, so we just
99
+ // rely on the tool name being in our streaming-tools set.
100
+ return STREAMING_TOOLS.has(body.params.name);
101
+ } catch { return false; }
102
+ })();
103
+ }
104
+
105
+ const STREAMING_TOOLS = new Set(['subscribe']);
106
+
107
+ async function handleStreamingTool(request, reply, body, ctx) {
108
+ const tool = TOOLS[body.params.name];
109
+ let descriptor;
110
+ try {
111
+ descriptor = tool.handler(body.params.arguments || {}, ctx);
112
+ } catch (e) {
113
+ reply.code(500);
114
+ reply.header('Content-Type', 'application/json');
115
+ return rpcError(body.id, RPC_ERRORS.INTERNAL_ERROR, e.message);
116
+ }
117
+ if (!descriptor || descriptor.stream !== true) {
118
+ // Tool decided not to stream after all — emit single-shot response
119
+ reply.header('Content-Type', 'application/json');
120
+ return rpcResult(body.id, descriptor);
121
+ }
122
+
123
+ // Switch to SSE
124
+ reply.raw.writeHead(200, {
125
+ 'Content-Type': 'text/event-stream',
126
+ 'Cache-Control': 'no-cache, no-transform',
127
+ 'Connection': 'keep-alive',
128
+ 'X-Accel-Buffering': 'no'
129
+ });
130
+
131
+ const controller = new AbortController();
132
+ request.raw.on('close', () => controller.abort());
133
+
134
+ const sendEvent = (payload) => {
135
+ if (controller.signal.aborted) return;
136
+ const note = {
137
+ jsonrpc: '2.0',
138
+ method: 'notifications/tool_event',
139
+ params: { tool: body.params.name, event: payload }
140
+ };
141
+ reply.raw.write(`event: notification\ndata: ${JSON.stringify(note)}\n\n`);
142
+ };
143
+
144
+ try {
145
+ const initial = await descriptor.init();
146
+ if (initial) sendEvent(initial);
147
+ await descriptor.run(sendEvent, controller.signal);
148
+ } catch (e) {
149
+ sendEvent({ type: 'error', message: e.message });
150
+ } finally {
151
+ if (!controller.signal.aborted) reply.raw.end();
152
+ }
153
+ return reply;
154
+ }
155
+
87
156
  /**
88
157
  * Register the MCP plugin with Fastify.
89
158
  */
@@ -99,11 +168,21 @@ export async function mcpPlugin(fastify, _options) {
99
168
  // null webId means "anonymous"; WAC will treat it accordingly.
100
169
  const { webId } = await getWebIdFromRequestAsync(request).catch(() => ({ webId: null }));
101
170
 
171
+ // Federation depth (used by call_remote_pod to enforce the cap)
172
+ const depthHdr = request.headers['mcp-federation-depth'];
173
+ const federationDepth = depthHdr ? parseInt(depthHdr, 10) || 0 : 0;
174
+
102
175
  const ctx = {
103
176
  webId: webId || null,
104
- origin: originOf(request)
177
+ origin: originOf(request),
178
+ federationDepth
105
179
  };
106
180
 
181
+ // Streaming tool? Hand off to SSE handler.
182
+ if (!Array.isArray(body) && isStreamingToolCall(body)) {
183
+ return handleStreamingTool(request, reply, body, ctx);
184
+ }
185
+
107
186
  // Batch support (array of requests)
108
187
  if (Array.isArray(body)) {
109
188
  const out = [];
package/src/mcp/tools.js CHANGED
@@ -11,13 +11,38 @@
11
11
 
12
12
  import * as storage from '../storage/filesystem.js';
13
13
  import { checkAccess } from '../wac/checker.js';
14
- import { AccessMode } from '../wac/parser.js';
14
+ import { AccessMode, parseAcl, serializeAcl } from '../wac/parser.js';
15
+ import { resourceEvents, emitChange } from '../notifications/events.js';
15
16
  import { toolText, toolError, toolJson } from './protocol.js';
16
17
  import { discoverSkills, readSkill, readPodSkill } from './skills.js';
17
18
  import { readFile, readdir, stat as fsStat } from 'fs/promises';
18
19
  import { join, dirname, resolve as pathResolve } from 'path';
19
20
  import { fileURLToPath } from 'url';
20
21
 
22
+ const ACL_NS = 'http://www.w3.org/ns/auth/acl#';
23
+ const FOAF_AGENT = 'http://xmlns.com/foaf/0.1/Agent';
24
+ const ACL_AUTH_AGENT = 'http://www.w3.org/ns/auth/acl#AuthenticatedAgent';
25
+ const SHORT_MODE = {
26
+ [`${ACL_NS}Read`]: 'Read',
27
+ [`${ACL_NS}Write`]: 'Write',
28
+ [`${ACL_NS}Append`]: 'Append',
29
+ [`${ACL_NS}Control`]: 'Control'
30
+ };
31
+ const SHORT_AGENT_CLASS = {
32
+ [FOAF_AGENT]: 'foaf:Agent',
33
+ [ACL_AUTH_AGENT]: 'acl:AuthenticatedAgent'
34
+ };
35
+ const FULL_MODE = {
36
+ Read: `${ACL_NS}Read`,
37
+ Write: `${ACL_NS}Write`,
38
+ Append: `${ACL_NS}Append`,
39
+ Control: `${ACL_NS}Control`
40
+ };
41
+ const FULL_AGENT_CLASS = {
42
+ 'foaf:Agent': FOAF_AGENT,
43
+ 'acl:AuthenticatedAgent': ACL_AUTH_AGENT
44
+ };
45
+
21
46
  const __dirname = dirname(fileURLToPath(import.meta.url));
22
47
  const JSS_DOCS_DIR = pathResolve(__dirname, '..', '..', 'docs');
23
48
 
@@ -114,6 +139,7 @@ async function write_resource({ path, content, contentType }, ctx) {
114
139
  await storage.write(path, Buffer.from(content, 'utf8'), {
115
140
  contentType: contentType || 'text/plain'
116
141
  });
142
+ emitChange(buildUrl(ctx, path));
117
143
  return toolText(`wrote ${path} (${Buffer.byteLength(content, 'utf8')} bytes)`);
118
144
  }
119
145
 
@@ -131,11 +157,13 @@ async function create_resource({ container, slug, content, contentType, isContai
131
157
  const childPath = `${container}${name}${isContainer ? '/' : ''}`;
132
158
  if (isContainer) {
133
159
  await storage.createContainer(childPath);
160
+ emitChange(buildUrl(ctx, childPath));
134
161
  return toolText(`created container ${childPath}`);
135
162
  }
136
163
  await storage.write(childPath, Buffer.from(content || '', 'utf8'), {
137
164
  contentType: contentType || 'text/plain'
138
165
  });
166
+ emitChange(buildUrl(ctx, childPath));
139
167
  return toolText(`created ${childPath}`);
140
168
  }
141
169
 
@@ -148,6 +176,7 @@ async function delete_resource({ path }, ctx) {
148
176
  return toolError(`not found: ${path}`);
149
177
  }
150
178
  await storage.remove(path);
179
+ emitChange(buildUrl(ctx, path));
151
180
  return toolText(`deleted ${path}`);
152
181
  }
153
182
 
@@ -220,6 +249,296 @@ async function read_docs({ name }, _ctx) {
220
249
  }
221
250
  }
222
251
 
252
+ // --- ACL tools (#496) ---
253
+
254
+ function aclUrlFor(path) {
255
+ // For containers, ACL is <container>.acl
256
+ // For resources, ACL is <resource>.acl
257
+ if (path.endsWith('/')) return path + '.acl';
258
+ return path + '.acl';
259
+ }
260
+
261
+ function shortMode(mode) {
262
+ return SHORT_MODE[mode] || mode;
263
+ }
264
+
265
+ function shortAgentClass(uri) {
266
+ return SHORT_AGENT_CLASS[uri] || uri;
267
+ }
268
+
269
+ function fullMode(mode) {
270
+ return FULL_MODE[mode] || mode;
271
+ }
272
+
273
+ function fullAgentClass(value) {
274
+ return FULL_AGENT_CLASS[value] || value;
275
+ }
276
+
277
+ async function read_acl({ path }, ctx) {
278
+ if (!path) return toolError('path required');
279
+ // Reading the ACL document itself requires Control on the resource.
280
+ if (!(await wac(ctx, path, AccessMode.CONTROL))) {
281
+ return toolError(`access denied: control ${path}`);
282
+ }
283
+ const aclPath = aclUrlFor(path);
284
+ if (!(await storage.exists(aclPath))) {
285
+ return toolJson({ path, aclPath, exists: false, authorizations: [] });
286
+ }
287
+ const content = await storage.read(aclPath);
288
+ const aclUrl = buildUrl(ctx, aclPath);
289
+ const auths = await parseAcl(content.toString('utf8'), aclUrl);
290
+ return toolJson({
291
+ path,
292
+ aclPath,
293
+ exists: true,
294
+ authorizations: auths.map(a => ({
295
+ agents: a.agents || [],
296
+ agentClasses: (a.agentClasses || []).map(shortAgentClass),
297
+ modes: (a.modes || []).map(shortMode),
298
+ isDefault: !!a.default
299
+ }))
300
+ });
301
+ }
302
+
303
+ function buildAclDoc(structured) {
304
+ const graph = structured.authorizations.map((auth, i) => {
305
+ const node = {
306
+ '@id': `#auth${i}`,
307
+ '@type': 'acl:Authorization',
308
+ 'acl:accessTo': { '@id': './' },
309
+ 'acl:mode': (auth.modes || []).map(m => ({ '@id': `acl:${m}` }))
310
+ };
311
+ if (auth.agents && auth.agents.length) {
312
+ node['acl:agent'] = auth.agents.map(a => ({ '@id': a }));
313
+ }
314
+ if (auth.agentClasses && auth.agentClasses.length) {
315
+ node['acl:agentClass'] = auth.agentClasses.map(c => ({
316
+ '@id': fullAgentClass(c)
317
+ }));
318
+ }
319
+ if (auth.isDefault) {
320
+ node['acl:default'] = { '@id': './' };
321
+ }
322
+ return node;
323
+ });
324
+ return {
325
+ '@context': {
326
+ acl: ACL_NS,
327
+ foaf: 'http://xmlns.com/foaf/0.1/'
328
+ },
329
+ '@graph': graph
330
+ };
331
+ }
332
+
333
+ async function write_acl({ path, authorizations }, ctx) {
334
+ if (!path) return toolError('path required');
335
+ if (!Array.isArray(authorizations)) {
336
+ return toolError('authorizations must be an array');
337
+ }
338
+ // Writing the ACL document requires Control on the resource.
339
+ if (!(await wac(ctx, path, AccessMode.CONTROL))) {
340
+ return toolError(`access denied: control ${path}`);
341
+ }
342
+ const aclPath = aclUrlFor(path);
343
+ const doc = buildAclDoc({ authorizations });
344
+ const serialized = serializeAcl(doc);
345
+
346
+ // Safety: refuse to write an ACL that would lock the caller out of
347
+ // future Control. This is the most common write_acl footgun —
348
+ // typically caused by relative WebID paths in `agents` resolving
349
+ // against the .acl URL to a different absolute URI than the caller's
350
+ // actual WebID. Parse the proposed ACL with its real URL so relative
351
+ // agents resolve correctly, then check whether any authorization
352
+ // grants Control to the caller.
353
+ const aclAbsUrl = buildUrl(ctx, aclPath);
354
+ const proposed = await parseAcl(serialized, aclAbsUrl);
355
+ const callerHasControl = proposed.some(auth => {
356
+ if (!(auth.modes || []).includes(AccessMode.CONTROL)) return false;
357
+ if (ctx.webId && (auth.agents || []).includes(ctx.webId)) return true;
358
+ if ((auth.agentClasses || []).includes(FOAF_AGENT)) return true;
359
+ if (ctx.webId && (auth.agentClasses || []).includes(ACL_AUTH_AGENT)) return true;
360
+ return false;
361
+ });
362
+ if (!callerHasControl) {
363
+ return toolError(
364
+ `write_acl refused: the proposed ACL would not grant Control to the caller (${ctx.webId || 'anonymous'}). ` +
365
+ 'This is typically caused by relative WebID paths in agents resolving against the .acl URL — use absolute WebIDs. ' +
366
+ 'If you really want to remove your own access (e.g. transferring ownership), do it in two steps: ' +
367
+ 'first grant Control to the new owner, then have the new owner write_acl without you.'
368
+ );
369
+ }
370
+
371
+ await storage.write(aclPath, Buffer.from(serialized, 'utf8'), {
372
+ contentType: 'application/ld+json'
373
+ });
374
+ emitChange(buildUrl(ctx, aclPath));
375
+ return toolText(`wrote ${aclPath} (${authorizations.length} authorization${authorizations.length === 1 ? '' : 's'})`);
376
+ }
377
+
378
+ // --- subscribe (#494) ---
379
+ //
380
+ // `subscribe` is a streaming tool. The handler signals its streaming
381
+ // shape by returning { stream: true, init, run }. The MCP plugin
382
+ // switches the HTTP response to SSE when it sees this shape and calls
383
+ // `init` first (for the initial event) then `run(send, signal)` to push
384
+ // notifications until the client disconnects.
385
+
386
+ function pathMatchesScope(eventUrl, scopePath, origin) {
387
+ if (!eventUrl.startsWith(origin)) return false;
388
+ const eventPath = eventUrl.slice(origin.length);
389
+ if (scopePath === '/') return true;
390
+ if (scopePath.endsWith('/')) return eventPath.startsWith(scopePath);
391
+ return eventPath === scopePath;
392
+ }
393
+
394
+ function subscribe({ path }, ctx) {
395
+ const scope = path || '/';
396
+ return {
397
+ stream: true,
398
+ async init() {
399
+ return {
400
+ type: 'subscribed',
401
+ scope,
402
+ origin: ctx.origin,
403
+ identity: ctx.webId || null
404
+ };
405
+ },
406
+ async run(send, signal) {
407
+ const onChange = async (eventUrl) => {
408
+ if (signal.aborted) return;
409
+ if (!pathMatchesScope(eventUrl, scope, ctx.origin)) return;
410
+
411
+ // Per-event WAC filter — don't leak resources the subscriber
412
+ // can't see. The check is best-effort: if the resource was just
413
+ // deleted we may not have storage to read its ACL from, so we
414
+ // err on the side of not emitting.
415
+ const eventPath = eventUrl.slice(ctx.origin.length);
416
+ try {
417
+ const allowed = await wac(ctx, eventPath, AccessMode.READ);
418
+ if (!allowed) return;
419
+ } catch {
420
+ return;
421
+ }
422
+ send({
423
+ type: 'resource_changed',
424
+ path: eventPath,
425
+ url: eventUrl
426
+ });
427
+ };
428
+ resourceEvents.on('change', onChange);
429
+ const cleanup = () => resourceEvents.off('change', onChange);
430
+ signal.addEventListener('abort', cleanup, { once: true });
431
+ // Resolve when aborted — keeps the stream open until client disconnect
432
+ await new Promise(resolve => signal.addEventListener('abort', resolve, { once: true }));
433
+ cleanup();
434
+ }
435
+ };
436
+ }
437
+
438
+ // --- federation (#495) ---
439
+
440
+ // Conservative defaults locked in for v1. Future PRs may add more flexibility.
441
+ //
442
+ // 1. Federation gate is `<agent-pod>/private/federation/` — caller must
443
+ // have acl:Write there to initiate outbound federation. The agent's
444
+ // pod is derived from their WebID. Foreign WebIDs are denied (no
445
+ // local path to gate against).
446
+ // 2. No pod-resident credential storage — every call carries its own
447
+ // credentials in the `auth` argument (or none for anonymous reads).
448
+ // 3. Depth cap via MCP-Federation-Depth header, max 3.
449
+ const MAX_FEDERATION_DEPTH = 3;
450
+
451
+ function federationGatePathFor(webId, origin) {
452
+ if (!webId || !origin) return null;
453
+ if (!webId.startsWith(origin)) return null; // foreign WebID — deny
454
+ const localPath = webId.slice(origin.length);
455
+ // Extract pod root: everything up to and including the segment before /profile/
456
+ const profileIdx = localPath.indexOf('/profile/');
457
+ const podPath = profileIdx > 0 ? localPath.slice(0, profileIdx + 1) : '/';
458
+ return podPath + 'private/federation/';
459
+ }
460
+
461
+ async function call_remote_pod({ pod_url, tool, arguments: remoteArgs, auth }, ctx) {
462
+ if (!pod_url || typeof pod_url !== 'string') {
463
+ return toolError('pod_url required');
464
+ }
465
+ if (!tool || typeof tool !== 'string') {
466
+ return toolError('tool required');
467
+ }
468
+ try {
469
+ new URL(pod_url);
470
+ } catch {
471
+ return toolError(`pod_url is not a valid URL: ${pod_url}`);
472
+ }
473
+
474
+ // Local WAC gate — derived from the agent's WebID. Foreign or
475
+ // anonymous identities can't federate.
476
+ const gatePath = federationGatePathFor(ctx.webId, ctx.origin);
477
+ if (!gatePath) {
478
+ return toolError(
479
+ 'access denied: federation requires a local WebID identity (anonymous and foreign identities cannot initiate outbound federation)'
480
+ );
481
+ }
482
+ if (!(await wac(ctx, gatePath, AccessMode.WRITE))) {
483
+ return toolError(
484
+ `access denied: write ${gatePath} (federation gate). Owner must grant acl:Write at this path to delegate outbound federation.`
485
+ );
486
+ }
487
+
488
+ // Depth cap
489
+ const depth = (ctx.federationDepth ?? 0) + 1;
490
+ if (depth > MAX_FEDERATION_DEPTH) {
491
+ return toolError(`federation depth exceeded (max ${MAX_FEDERATION_DEPTH})`);
492
+ }
493
+
494
+ // Build remote MCP request
495
+ const remoteEndpoint = pod_url.replace(/\/+$/, '') + '/mcp';
496
+ const body = {
497
+ jsonrpc: '2.0',
498
+ id: 1,
499
+ method: 'tools/call',
500
+ params: { name: tool, arguments: remoteArgs || {} }
501
+ };
502
+
503
+ const headers = {
504
+ 'Content-Type': 'application/json',
505
+ 'MCP-Federation-Depth': String(depth)
506
+ };
507
+ if (auth && typeof auth === 'object') {
508
+ if (auth.type === 'bearer' && auth.token) {
509
+ headers.Authorization = `Bearer ${auth.token}`;
510
+ } else if (auth.type === 'header' && auth.name && auth.value) {
511
+ headers[auth.name] = auth.value;
512
+ }
513
+ }
514
+
515
+ let response, payload;
516
+ try {
517
+ response = await fetch(remoteEndpoint, {
518
+ method: 'POST',
519
+ headers,
520
+ body: JSON.stringify(body),
521
+ signal: AbortSignal.timeout(30_000)
522
+ });
523
+ } catch (e) {
524
+ return toolError(`remote pod unreachable: ${e.message}`);
525
+ }
526
+ try {
527
+ payload = await response.json();
528
+ } catch (e) {
529
+ return toolError(`remote response not JSON (${response.status}): ${e.message}`);
530
+ }
531
+ if (payload.error) {
532
+ return toolError(`remote MCP error ${payload.error.code}: ${payload.error.message}`);
533
+ }
534
+ return toolJson({
535
+ pod_url,
536
+ tool,
537
+ depth,
538
+ remote_result: payload.result || null
539
+ });
540
+ }
541
+
223
542
  // --- pod info ---
224
543
 
225
544
  async function pod_info(_args, ctx) {
@@ -345,6 +664,72 @@ export const TOOLS = {
345
664
  description: 'Basic pod identity and MCP capabilities.',
346
665
  inputSchema: { type: 'object', properties: {} },
347
666
  handler: pod_info
667
+ },
668
+ read_acl: {
669
+ description: 'Read the WAC ACL for a resource as a structured list of authorizations. Requires acl:Control.',
670
+ inputSchema: {
671
+ type: 'object',
672
+ properties: { path: { type: 'string' } },
673
+ required: ['path']
674
+ },
675
+ handler: read_acl
676
+ },
677
+ write_acl: {
678
+ description: 'Write a structured ACL for a resource. authorizations: [{ agents?, agentClasses?, modes, isDefault? }]. Requires acl:Control.',
679
+ inputSchema: {
680
+ type: 'object',
681
+ properties: {
682
+ path: { type: 'string' },
683
+ authorizations: {
684
+ type: 'array',
685
+ items: {
686
+ type: 'object',
687
+ properties: {
688
+ agents: { type: 'array', items: { type: 'string' } },
689
+ agentClasses: { type: 'array', items: { type: 'string', enum: ['foaf:Agent', 'acl:AuthenticatedAgent'] } },
690
+ modes: { type: 'array', items: { type: 'string', enum: ['Read', 'Write', 'Append', 'Control'] } },
691
+ isDefault: { type: 'boolean' }
692
+ },
693
+ required: ['modes']
694
+ }
695
+ }
696
+ },
697
+ required: ['path', 'authorizations']
698
+ },
699
+ handler: write_acl
700
+ },
701
+ subscribe: {
702
+ description: 'Subscribe to change events on a resource or container subtree. Returns an SSE stream of MCP notifications as resources change. WAC-filtered per event.',
703
+ inputSchema: {
704
+ type: 'object',
705
+ properties: {
706
+ path: { type: 'string', description: 'Container path (with trailing /) to watch a subtree, or exact resource path. Default: / (whole pod, filtered by Read access).' }
707
+ }
708
+ },
709
+ handler: subscribe
710
+ },
711
+ call_remote_pod: {
712
+ description: 'Invoke an MCP tool on another pod. Caller must have acl:Write on /private/federation/ on this pod. Depth-capped at 3.',
713
+ inputSchema: {
714
+ type: 'object',
715
+ properties: {
716
+ pod_url: { type: 'string', description: 'Origin of the remote pod (e.g. https://alice.example.com)' },
717
+ tool: { type: 'string', description: 'Tool name to invoke on the remote' },
718
+ arguments: { type: 'object', description: 'Arguments to pass to the remote tool' },
719
+ auth: {
720
+ type: 'object',
721
+ description: 'Auth for the remote call. Currently { type: "bearer", token } or { type: "header", name, value }. Omit for anonymous.',
722
+ properties: {
723
+ type: { type: 'string', enum: ['bearer', 'header'] },
724
+ token: { type: 'string' },
725
+ name: { type: 'string' },
726
+ value: { type: 'string' }
727
+ }
728
+ }
729
+ },
730
+ required: ['pod_url', 'tool']
731
+ },
732
+ handler: call_remote_pod
348
733
  }
349
734
  };
350
735
 
package/test/mcp.test.js CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  getBaseUrl,
20
20
  getPodToken
21
21
  } from './helpers.js';
22
+ import { emitChange } from '../src/notifications/events.js';
22
23
 
23
24
  let token;
24
25
 
@@ -237,6 +238,296 @@ describe('MCP server (--mcp enabled)', () => {
237
238
  assert.strictEqual(body.error?.code, -32601);
238
239
  });
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
+
240
531
  it('rejects unknown tool', async () => {
241
532
  const { body } = await rpc({
242
533
  jsonrpc: '2.0', id: 100, method: 'tools/call',