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/README.md +3 -1
- package/bin/jss.js +3 -0
- package/docs/mcp.md +228 -0
- package/package.json +1 -1
- package/src/config.js +5 -0
- package/src/mcp/index.js +212 -0
- package/src/mcp/protocol.js +52 -0
- package/src/mcp/skills.js +138 -0
- package/src/mcp/tools.js +760 -0
- package/src/server.js +11 -0
- package/test/mcp.test.js +562 -0
package/src/mcp/tools.js
ADDED
|
@@ -0,0 +1,760 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP tool definitions and dispatch.
|
|
3
|
+
*
|
|
4
|
+
* Each tool is a function: (args, ctx) -> Promise<MCPToolResult>
|
|
5
|
+
* ctx.webId — authenticated identity (null = anonymous)
|
|
6
|
+
* ctx.origin — request origin for building absolute URLs
|
|
7
|
+
*
|
|
8
|
+
* All WAC checks delegate to src/wac/checker.js so MCP tools have
|
|
9
|
+
* the same access semantics as the HTTP endpoints.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import * as storage from '../storage/filesystem.js';
|
|
13
|
+
import { checkAccess } from '../wac/checker.js';
|
|
14
|
+
import { AccessMode, parseAcl, serializeAcl } from '../wac/parser.js';
|
|
15
|
+
import { resourceEvents, emitChange } from '../notifications/events.js';
|
|
16
|
+
import { toolText, toolError, toolJson } from './protocol.js';
|
|
17
|
+
import { discoverSkills, readSkill, readPodSkill } from './skills.js';
|
|
18
|
+
import { readFile, readdir, stat as fsStat } from 'fs/promises';
|
|
19
|
+
import { join, dirname, resolve as pathResolve } from 'path';
|
|
20
|
+
import { fileURLToPath } from 'url';
|
|
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
|
+
|
|
46
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
47
|
+
const JSS_DOCS_DIR = pathResolve(__dirname, '..', '..', 'docs');
|
|
48
|
+
|
|
49
|
+
function buildUrl(ctx, path) {
|
|
50
|
+
if (!path.startsWith('/')) path = '/' + path;
|
|
51
|
+
return `${ctx.origin}${path}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function parentPath(p) {
|
|
55
|
+
if (p === '/' || p === '') return '/';
|
|
56
|
+
const trimmed = p.endsWith('/') ? p.slice(0, -1) : p;
|
|
57
|
+
const idx = trimmed.lastIndexOf('/');
|
|
58
|
+
return idx <= 0 ? '/' : trimmed.slice(0, idx + 1);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function wac(ctx, path, mode) {
|
|
62
|
+
// For writes against a non-existent resource, fall back to checking
|
|
63
|
+
// the parent container — same pattern as src/auth/middleware.js so MCP
|
|
64
|
+
// tools have identical WAC semantics to the HTTP endpoints.
|
|
65
|
+
const isWrite = mode === AccessMode.WRITE || mode === AccessMode.APPEND;
|
|
66
|
+
let checkPath = path;
|
|
67
|
+
let checkIsContainer = path.endsWith('/');
|
|
68
|
+
if (isWrite && !path.endsWith('/') && !(await storage.exists(path))) {
|
|
69
|
+
checkPath = parentPath(path);
|
|
70
|
+
checkIsContainer = true;
|
|
71
|
+
}
|
|
72
|
+
const { allowed } = await checkAccess({
|
|
73
|
+
resourceUrl: buildUrl(ctx, checkPath),
|
|
74
|
+
resourcePath: checkPath,
|
|
75
|
+
isContainer: checkIsContainer,
|
|
76
|
+
agentWebId: ctx.webId,
|
|
77
|
+
requiredMode: mode
|
|
78
|
+
});
|
|
79
|
+
return allowed;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// --- CRUD tools ---
|
|
83
|
+
|
|
84
|
+
async function list_resources({ path }, ctx) {
|
|
85
|
+
if (!path || !path.endsWith('/')) {
|
|
86
|
+
return toolError('path must be a container (ending in /)');
|
|
87
|
+
}
|
|
88
|
+
if (!(await wac(ctx, path, AccessMode.READ))) {
|
|
89
|
+
return toolError(`access denied: read ${path}`);
|
|
90
|
+
}
|
|
91
|
+
if (!(await storage.exists(path))) {
|
|
92
|
+
return toolError(`not found: ${path}`);
|
|
93
|
+
}
|
|
94
|
+
const entries = await storage.listContainer(path);
|
|
95
|
+
return toolJson({
|
|
96
|
+
container: path,
|
|
97
|
+
items: (entries || []).map(e => ({
|
|
98
|
+
name: e.name,
|
|
99
|
+
path: `${path}${e.name}${e.isDirectory ? '/' : ''}`,
|
|
100
|
+
isContainer: e.isDirectory,
|
|
101
|
+
size: e.size ?? null,
|
|
102
|
+
modified: e.modified ?? null
|
|
103
|
+
}))
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function read_resource({ path }, ctx) {
|
|
108
|
+
if (!path) return toolError('path required');
|
|
109
|
+
if (!(await wac(ctx, path, AccessMode.READ))) {
|
|
110
|
+
return toolError(`access denied: read ${path}`);
|
|
111
|
+
}
|
|
112
|
+
if (!(await storage.exists(path))) {
|
|
113
|
+
return toolError(`not found: ${path}`);
|
|
114
|
+
}
|
|
115
|
+
if (path.endsWith('/')) {
|
|
116
|
+
return toolError('use list_resources for containers');
|
|
117
|
+
}
|
|
118
|
+
const content = await storage.read(path);
|
|
119
|
+
let body = content.toString('utf8');
|
|
120
|
+
// Truncate very large reads
|
|
121
|
+
const MAX = 200_000;
|
|
122
|
+
let truncated = false;
|
|
123
|
+
if (body.length > MAX) {
|
|
124
|
+
body = body.slice(0, MAX);
|
|
125
|
+
truncated = true;
|
|
126
|
+
}
|
|
127
|
+
const result = { path, body };
|
|
128
|
+
if (truncated) result.truncated = true;
|
|
129
|
+
return toolJson(result);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function write_resource({ path, content, contentType }, ctx) {
|
|
133
|
+
if (!path) return toolError('path required');
|
|
134
|
+
if (path.endsWith('/')) return toolError('cannot PUT a container; use create_resource');
|
|
135
|
+
if (content == null) return toolError('content required');
|
|
136
|
+
if (!(await wac(ctx, path, AccessMode.WRITE))) {
|
|
137
|
+
return toolError(`access denied: write ${path}`);
|
|
138
|
+
}
|
|
139
|
+
await storage.write(path, Buffer.from(content, 'utf8'), {
|
|
140
|
+
contentType: contentType || 'text/plain'
|
|
141
|
+
});
|
|
142
|
+
emitChange(buildUrl(ctx, path));
|
|
143
|
+
return toolText(`wrote ${path} (${Buffer.byteLength(content, 'utf8')} bytes)`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function create_resource({ container, slug, content, contentType, isContainer }, ctx) {
|
|
147
|
+
if (!container || !container.endsWith('/')) {
|
|
148
|
+
return toolError('container path required (must end in /)');
|
|
149
|
+
}
|
|
150
|
+
if (!(await wac(ctx, container, AccessMode.APPEND))) {
|
|
151
|
+
return toolError(`access denied: append ${container}`);
|
|
152
|
+
}
|
|
153
|
+
if (!(await storage.exists(container))) {
|
|
154
|
+
return toolError(`container not found: ${container}`);
|
|
155
|
+
}
|
|
156
|
+
const name = await storage.generateUniqueFilename(container, slug || null, !!isContainer);
|
|
157
|
+
const childPath = `${container}${name}${isContainer ? '/' : ''}`;
|
|
158
|
+
if (isContainer) {
|
|
159
|
+
await storage.createContainer(childPath);
|
|
160
|
+
emitChange(buildUrl(ctx, childPath));
|
|
161
|
+
return toolText(`created container ${childPath}`);
|
|
162
|
+
}
|
|
163
|
+
await storage.write(childPath, Buffer.from(content || '', 'utf8'), {
|
|
164
|
+
contentType: contentType || 'text/plain'
|
|
165
|
+
});
|
|
166
|
+
emitChange(buildUrl(ctx, childPath));
|
|
167
|
+
return toolText(`created ${childPath}`);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function delete_resource({ path }, ctx) {
|
|
171
|
+
if (!path) return toolError('path required');
|
|
172
|
+
if (!(await wac(ctx, path, AccessMode.WRITE))) {
|
|
173
|
+
return toolError(`access denied: delete ${path}`);
|
|
174
|
+
}
|
|
175
|
+
if (!(await storage.exists(path))) {
|
|
176
|
+
return toolError(`not found: ${path}`);
|
|
177
|
+
}
|
|
178
|
+
await storage.remove(path);
|
|
179
|
+
emitChange(buildUrl(ctx, path));
|
|
180
|
+
return toolText(`deleted ${path}`);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function head_resource({ path }, ctx) {
|
|
184
|
+
if (!path) return toolError('path required');
|
|
185
|
+
if (!(await wac(ctx, path, AccessMode.READ))) {
|
|
186
|
+
return toolError(`access denied: read ${path}`);
|
|
187
|
+
}
|
|
188
|
+
if (!(await storage.exists(path))) {
|
|
189
|
+
return toolError(`not found: ${path}`);
|
|
190
|
+
}
|
|
191
|
+
const s = await storage.stat(path);
|
|
192
|
+
return toolJson({
|
|
193
|
+
path,
|
|
194
|
+
isContainer: path.endsWith('/'),
|
|
195
|
+
size: s?.size ?? null,
|
|
196
|
+
modified: s?.mtime ?? null
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// --- skill tools ---
|
|
201
|
+
|
|
202
|
+
async function list_skills(_args, _ctx) {
|
|
203
|
+
const idx = await discoverSkills();
|
|
204
|
+
return toolJson(idx);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function get_skill({ path }, _ctx) {
|
|
208
|
+
if (!path) return toolError('path required');
|
|
209
|
+
try {
|
|
210
|
+
const skill = await readSkill(path);
|
|
211
|
+
return toolJson(skill);
|
|
212
|
+
} catch (e) {
|
|
213
|
+
return toolError(e.message);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function get_pod_skill(_args, _ctx) {
|
|
218
|
+
const skill = await readPodSkill();
|
|
219
|
+
if (!skill) return toolText('no pod-wide SKILL.md or SKILL.jsonld');
|
|
220
|
+
return toolJson(skill);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// --- docs tools ---
|
|
224
|
+
|
|
225
|
+
async function list_docs(_args, _ctx) {
|
|
226
|
+
try {
|
|
227
|
+
const entries = await readdir(JSS_DOCS_DIR);
|
|
228
|
+
const md = entries.filter(n => n.endsWith('.md'));
|
|
229
|
+
const docs = await Promise.all(md.map(async name => {
|
|
230
|
+
const fullPath = join(JSS_DOCS_DIR, name);
|
|
231
|
+
const s = await fsStat(fullPath).catch(() => null);
|
|
232
|
+
return { name, size: s?.size ?? null };
|
|
233
|
+
}));
|
|
234
|
+
return toolJson({ source: 'jss-builtin', docs });
|
|
235
|
+
} catch {
|
|
236
|
+
return toolJson({ source: 'jss-builtin', docs: [] });
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function read_docs({ name }, _ctx) {
|
|
241
|
+
if (!name) return toolError('name required (e.g. "git-support.md")');
|
|
242
|
+
if (name.includes('..') || name.includes('/')) return toolError('name must be a bare filename');
|
|
243
|
+
if (!name.endsWith('.md')) name = name + '.md';
|
|
244
|
+
try {
|
|
245
|
+
const body = await readFile(join(JSS_DOCS_DIR, name), 'utf8');
|
|
246
|
+
return toolJson({ name, body });
|
|
247
|
+
} catch (e) {
|
|
248
|
+
return toolError(`doc not found: ${name}`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
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
|
+
|
|
542
|
+
// --- pod info ---
|
|
543
|
+
|
|
544
|
+
async function pod_info(_args, ctx) {
|
|
545
|
+
const skill = await readPodSkill().catch(() => null);
|
|
546
|
+
return toolJson({
|
|
547
|
+
pod: ctx.origin,
|
|
548
|
+
server: 'jss',
|
|
549
|
+
protocolVersion: '2025-03-26',
|
|
550
|
+
identity: ctx.webId || null,
|
|
551
|
+
capabilities: {
|
|
552
|
+
crud: true,
|
|
553
|
+
acl: true,
|
|
554
|
+
skills: true,
|
|
555
|
+
docs: true
|
|
556
|
+
},
|
|
557
|
+
skill: skill ? { path: skill.path, format: skill.format } : null
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// --- registry ---
|
|
562
|
+
|
|
563
|
+
export const TOOLS = {
|
|
564
|
+
list_resources: {
|
|
565
|
+
description: 'List contents of an LDP container. Returns child resources and sub-containers.',
|
|
566
|
+
inputSchema: {
|
|
567
|
+
type: 'object',
|
|
568
|
+
properties: {
|
|
569
|
+
path: { type: 'string', description: 'Container path, must end in /' }
|
|
570
|
+
},
|
|
571
|
+
required: ['path']
|
|
572
|
+
},
|
|
573
|
+
handler: list_resources
|
|
574
|
+
},
|
|
575
|
+
read_resource: {
|
|
576
|
+
description: 'Read the body of a non-container resource (any content type). Returns UTF-8.',
|
|
577
|
+
inputSchema: {
|
|
578
|
+
type: 'object',
|
|
579
|
+
properties: { path: { type: 'string' } },
|
|
580
|
+
required: ['path']
|
|
581
|
+
},
|
|
582
|
+
handler: read_resource
|
|
583
|
+
},
|
|
584
|
+
write_resource: {
|
|
585
|
+
description: 'Write (PUT) a resource at the given path. Overwrites if exists.',
|
|
586
|
+
inputSchema: {
|
|
587
|
+
type: 'object',
|
|
588
|
+
properties: {
|
|
589
|
+
path: { type: 'string' },
|
|
590
|
+
content: { type: 'string' },
|
|
591
|
+
contentType: { type: 'string', description: 'MIME type (default text/plain)' }
|
|
592
|
+
},
|
|
593
|
+
required: ['path', 'content']
|
|
594
|
+
},
|
|
595
|
+
handler: write_resource
|
|
596
|
+
},
|
|
597
|
+
create_resource: {
|
|
598
|
+
description: 'Create a child resource in a container (LDP POST). Server mints the name unless slug is provided.',
|
|
599
|
+
inputSchema: {
|
|
600
|
+
type: 'object',
|
|
601
|
+
properties: {
|
|
602
|
+
container: { type: 'string', description: 'Parent container path, must end in /' },
|
|
603
|
+
slug: { type: 'string', description: 'Optional filename hint' },
|
|
604
|
+
content: { type: 'string' },
|
|
605
|
+
contentType: { type: 'string' },
|
|
606
|
+
isContainer: { type: 'boolean', description: 'Create a child container instead of a resource' }
|
|
607
|
+
},
|
|
608
|
+
required: ['container']
|
|
609
|
+
},
|
|
610
|
+
handler: create_resource
|
|
611
|
+
},
|
|
612
|
+
delete_resource: {
|
|
613
|
+
description: 'Delete a resource or empty container.',
|
|
614
|
+
inputSchema: {
|
|
615
|
+
type: 'object',
|
|
616
|
+
properties: { path: { type: 'string' } },
|
|
617
|
+
required: ['path']
|
|
618
|
+
},
|
|
619
|
+
handler: delete_resource
|
|
620
|
+
},
|
|
621
|
+
head_resource: {
|
|
622
|
+
description: 'Return metadata (size, modified) for a resource without reading the body.',
|
|
623
|
+
inputSchema: {
|
|
624
|
+
type: 'object',
|
|
625
|
+
properties: { path: { type: 'string' } },
|
|
626
|
+
required: ['path']
|
|
627
|
+
},
|
|
628
|
+
handler: head_resource
|
|
629
|
+
},
|
|
630
|
+
list_skills: {
|
|
631
|
+
description: 'List SKILL.md / SKILL.jsonld files at conventional paths (pod-wide, per-app, per-bot).',
|
|
632
|
+
inputSchema: { type: 'object', properties: {} },
|
|
633
|
+
handler: list_skills
|
|
634
|
+
},
|
|
635
|
+
get_skill: {
|
|
636
|
+
description: 'Read a specific skill file by pod path.',
|
|
637
|
+
inputSchema: {
|
|
638
|
+
type: 'object',
|
|
639
|
+
properties: { path: { type: 'string' } },
|
|
640
|
+
required: ['path']
|
|
641
|
+
},
|
|
642
|
+
handler: get_skill
|
|
643
|
+
},
|
|
644
|
+
get_pod_skill: {
|
|
645
|
+
description: 'Read the pod-wide SKILL.md (the owner\'s instructions to bots).',
|
|
646
|
+
inputSchema: { type: 'object', properties: {} },
|
|
647
|
+
handler: get_pod_skill
|
|
648
|
+
},
|
|
649
|
+
list_docs: {
|
|
650
|
+
description: 'List JSS\'s built-in docs (markdown files shipped with the server).',
|
|
651
|
+
inputSchema: { type: 'object', properties: {} },
|
|
652
|
+
handler: list_docs
|
|
653
|
+
},
|
|
654
|
+
read_docs: {
|
|
655
|
+
description: 'Read a JSS doc by filename (e.g. "git-support.md", "app-install.md").',
|
|
656
|
+
inputSchema: {
|
|
657
|
+
type: 'object',
|
|
658
|
+
properties: { name: { type: 'string' } },
|
|
659
|
+
required: ['name']
|
|
660
|
+
},
|
|
661
|
+
handler: read_docs
|
|
662
|
+
},
|
|
663
|
+
pod_info: {
|
|
664
|
+
description: 'Basic pod identity and MCP capabilities.',
|
|
665
|
+
inputSchema: { type: 'object', properties: {} },
|
|
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
|
|
733
|
+
}
|
|
734
|
+
};
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* Return the list of tools in MCP tools/list shape.
|
|
738
|
+
*/
|
|
739
|
+
export function listToolsForRpc() {
|
|
740
|
+
return Object.entries(TOOLS).map(([name, t]) => ({
|
|
741
|
+
name,
|
|
742
|
+
description: t.description,
|
|
743
|
+
inputSchema: t.inputSchema
|
|
744
|
+
}));
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/**
|
|
748
|
+
* Dispatch a tools/call request.
|
|
749
|
+
*/
|
|
750
|
+
export async function callTool(name, args, ctx) {
|
|
751
|
+
const tool = TOOLS[name];
|
|
752
|
+
if (!tool) {
|
|
753
|
+
return toolError(`unknown tool: ${name}`);
|
|
754
|
+
}
|
|
755
|
+
try {
|
|
756
|
+
return await tool.handler(args || {}, ctx);
|
|
757
|
+
} catch (e) {
|
|
758
|
+
return toolError(`tool ${name} threw: ${e.message}`);
|
|
759
|
+
}
|
|
760
|
+
}
|