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/README.md
CHANGED
|
@@ -34,6 +34,7 @@ A minimal, fast, JSON-LD native Solid server.
|
|
|
34
34
|
- **Tunnel Proxy** — Decentralized ngrok through your pod
|
|
35
35
|
- **Terminal** — WebSocket shell access via `--terminal`
|
|
36
36
|
- **Password CLI** — `jss passwd` for user password management
|
|
37
|
+
- **MCP Server** — Expose the pod as a tool surface for agents (Claude Desktop, Cursor, custom bots) via `--mcp` ([docs](docs/mcp.md))
|
|
37
38
|
- **HTTP 402 Payments** — Monetize endpoints with per-request sat payments
|
|
38
39
|
- **Mashlib / SolidOS UI** — Optional data browser (CDN, local, or ES module)
|
|
39
40
|
- **Storage Quotas** — Per-user limits with CLI management
|
|
@@ -92,7 +93,7 @@ jss quota <cmd> # Manage storage quotas
|
|
|
92
93
|
jss passwd <username> # Manage user passwords
|
|
93
94
|
```
|
|
94
95
|
|
|
95
|
-
Key options: `--port`, `--idp`, `--conneg`, `--mashlib`, `--git`, `--nostr`, `--activitypub`, `--webrtc`, `--tunnel`, `--terminal`, `--mongo`, `--pay`, `--public`, `--single-user`
|
|
96
|
+
Key options: `--port`, `--idp`, `--conneg`, `--mashlib`, `--git`, `--nostr`, `--mcp`, `--activitypub`, `--webrtc`, `--tunnel`, `--terminal`, `--mongo`, `--pay`, `--public`, `--single-user`
|
|
96
97
|
|
|
97
98
|
Full options: [docs/configuration.md](docs/configuration.md)
|
|
98
99
|
|
|
@@ -106,6 +107,7 @@ Full options: [docs/configuration.md](docs/configuration.md)
|
|
|
106
107
|
| WebSocket Notifications | [docs/notifications.md](docs/notifications.md) |
|
|
107
108
|
| Git Support | [docs/git-support.md](docs/git-support.md) |
|
|
108
109
|
| Installing Apps | [docs/app-install.md](docs/app-install.md) |
|
|
110
|
+
| MCP (pod as agent tool surface) | [docs/mcp.md](docs/mcp.md) |
|
|
109
111
|
| Nostr Relay | [docs/nostr.md](docs/nostr.md) |
|
|
110
112
|
| ActivityPub & Mastodon API | [docs/activitypub.md](docs/activitypub.md) |
|
|
111
113
|
| remoteStorage | [docs/remotestorage.md](docs/remotestorage.md) |
|
package/bin/jss.js
CHANGED
|
@@ -152,6 +152,8 @@ program
|
|
|
152
152
|
.option('--no-mongo', 'Disable MongoDB-backed /db/ route')
|
|
153
153
|
.option('--mongo-url <url>', 'MongoDB connection URL (default: mongodb://localhost:27017)')
|
|
154
154
|
.option('--mongo-database <name>', 'MongoDB database name (default: solid)')
|
|
155
|
+
.option('--mcp', 'Enable MCP (Model Context Protocol) server at /mcp — pod as a tool surface for agents (#490)')
|
|
156
|
+
.option('--no-mcp', 'Disable MCP server')
|
|
155
157
|
.option('-q, --quiet', 'Suppress log output')
|
|
156
158
|
.option('--log-level <level>', 'Log level: error, warn, info, debug (default: info)')
|
|
157
159
|
.option('--print-config', 'Print configuration and exit')
|
|
@@ -234,6 +236,7 @@ program
|
|
|
234
236
|
mongo: config.mongo,
|
|
235
237
|
mongoUrl: config.mongoUrl,
|
|
236
238
|
mongoDatabase: config.mongoDatabase,
|
|
239
|
+
mcp: config.mcp,
|
|
237
240
|
});
|
|
238
241
|
|
|
239
242
|
await server.listen({ port: config.port, host: config.host });
|
package/docs/mcp.md
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
# MCP — pod as a tool surface for agents
|
|
2
|
+
|
|
3
|
+
JSS speaks the [Model Context Protocol](https://modelcontextprotocol.io). Once `--mcp` is enabled, any MCP-compatible client — Claude Desktop, Cursor, custom agents, or `solid-apps/charlie` — can register your pod as a tool surface and read/write resources under the same WAC rules as any HTTP client.
|
|
4
|
+
|
|
5
|
+
> **Thesis**: MCP needs a backend. Solid is the backend.
|
|
6
|
+
|
|
7
|
+
## Quick start
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
jss start --idp --mcp
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
The MCP endpoint is `POST /mcp` on your pod, speaking JSON-RPC 2.0 over MCP's Streamable HTTP transport (protocol version `2025-03-26`).
|
|
14
|
+
|
|
15
|
+
### Smoke test
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
# Handshake
|
|
19
|
+
curl -s http://localhost:4443/mcp \
|
|
20
|
+
-H "Content-Type: application/json" \
|
|
21
|
+
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}' | jq
|
|
22
|
+
|
|
23
|
+
# List the tools the server offers
|
|
24
|
+
curl -s http://localhost:4443/mcp \
|
|
25
|
+
-H "Content-Type: application/json" \
|
|
26
|
+
-d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | jq '.result.tools[].name'
|
|
27
|
+
|
|
28
|
+
# Call a tool (anonymous read of /public/)
|
|
29
|
+
curl -s http://localhost:4443/mcp \
|
|
30
|
+
-H "Content-Type: application/json" \
|
|
31
|
+
-d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_resources","arguments":{"path":"/public/"}}}' | jq
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Auth
|
|
35
|
+
|
|
36
|
+
The MCP endpoint reuses JSS's existing auth chain. Any token format JSS accepts on regular HTTP endpoints works here:
|
|
37
|
+
|
|
38
|
+
- **Bearer** — simple HMAC tokens from `POST /idp/credentials`
|
|
39
|
+
- **Solid-OIDC + DPoP** — for federated WebID identities
|
|
40
|
+
- **LWS-CID JWTs** — kid resolution via WebID profile
|
|
41
|
+
- **NIP-98** — Schnorr-signed Nostr events with `did:nostr:<pubkey>` identity
|
|
42
|
+
|
|
43
|
+
The MCP server extracts the WebID from the inbound request to `/mcp` itself. Every tool call is then WAC-checked against that WebID, on the resource path the tool touches. **There is no separate MCP auth layer** — granting an agent access to `/private/notes/` is the same operation as granting a human: edit the ACL.
|
|
44
|
+
|
|
45
|
+
Anonymous requests get the same WAC treatment as any other anonymous request — public resources are reachable, private ones aren't.
|
|
46
|
+
|
|
47
|
+
## Tools
|
|
48
|
+
|
|
49
|
+
### Resource CRUD
|
|
50
|
+
|
|
51
|
+
| Tool | Effect | WAC check |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| `list_resources` | List a container's contents (`ldp:contains`) | Read on container |
|
|
54
|
+
| `read_resource` | Return resource body (UTF-8) | Read on resource |
|
|
55
|
+
| `write_resource` | PUT resource (overwrites) | Write on resource (parent fallback for new resources) |
|
|
56
|
+
| `create_resource` | POST to container (server mints name unless `slug` given) | Append on container |
|
|
57
|
+
| `delete_resource` | DELETE resource | Write on resource |
|
|
58
|
+
| `head_resource` | Return size/modified without body | Read on resource |
|
|
59
|
+
|
|
60
|
+
### Skill discovery
|
|
61
|
+
|
|
62
|
+
Skills live at conventional paths the MCP server walks:
|
|
63
|
+
|
|
64
|
+
- `<pod>/SKILL.md` — pod-wide (owner's instructions to any bot)
|
|
65
|
+
- `<pod>/public/apps/<name>/SKILL.md` — per-app
|
|
66
|
+
- `<pod>/private/bots/<name>/SKILL.md` — per-bot
|
|
67
|
+
|
|
68
|
+
| Tool | Returns |
|
|
69
|
+
|---|---|
|
|
70
|
+
| `list_skills` | `skill:SkillIndex` listing every discovered skill with `skill:format`, `skill:scope`, `skill:source` |
|
|
71
|
+
| `get_skill` | Body of a specific skill file |
|
|
72
|
+
| `get_pod_skill` | Pod-wide SKILL.md (convenience) |
|
|
73
|
+
|
|
74
|
+
Both `SKILL.md` (Anthropic markdown format) and `SKILL.jsonld` (typed JSON-LD descriptor) are first-class. The discovery channel stays stable; new formats plug in via the `skill:format` declaration.
|
|
75
|
+
|
|
76
|
+
### Docs
|
|
77
|
+
|
|
78
|
+
| Tool | Returns |
|
|
79
|
+
|---|---|
|
|
80
|
+
| `list_docs` | JSS's own built-in docs (the markdown files shipped with the server) |
|
|
81
|
+
| `read_docs` | Markdown body of a doc by filename |
|
|
82
|
+
|
|
83
|
+
Pod-resident docs (`/docs/`, `/public/apps/<name>/docs/`) are reachable via the regular CRUD tools — no separate surface.
|
|
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
|
+
|
|
158
|
+
### Introspection
|
|
159
|
+
|
|
160
|
+
| Tool | Returns |
|
|
161
|
+
|---|---|
|
|
162
|
+
| `pod_info` | Origin, server, MCP protocol version, authenticated identity, capability flags |
|
|
163
|
+
|
|
164
|
+
## Wiring Claude Desktop
|
|
165
|
+
|
|
166
|
+
In your Claude Desktop MCP settings, add an HTTP MCP server pointing at:
|
|
167
|
+
|
|
168
|
+
```
|
|
169
|
+
http://localhost:4443/mcp
|
|
170
|
+
```
|
|
171
|
+
|
|
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.
|
|
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
|
+
|
|
208
|
+
## What's not included (yet)
|
|
209
|
+
|
|
210
|
+
The current cut ships CRUD, structured ACL editing, subscribe, federation, skills, docs, and introspection. Deferred:
|
|
211
|
+
|
|
212
|
+
- **`update_resource` (PATCH)** — SPARQL Update / N3 patches. Read-modify-write through the CRUD tools is the workaround.
|
|
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.
|
|
215
|
+
|
|
216
|
+
These are tracked as follow-ups on issue #490.
|
|
217
|
+
|
|
218
|
+
## Why this exists
|
|
219
|
+
|
|
220
|
+
The agent ecosystem has no shared answer for sovereign, ACL-gated storage. Every agent today bolts on its own DB, vector store, or secrets vault. Solid's pitch — user-owned data, queryable, access-controlled — is exactly what agents need. MCP is the wire that connects them.
|
|
221
|
+
|
|
222
|
+
When JSS exposes `/mcp`:
|
|
223
|
+
|
|
224
|
+
- **Agent identity becomes a first-class WAC subject.** `acl:agent <did:nostr:...>` for a bot is the same operation as for a human.
|
|
225
|
+
- **The pod is the bot's world.** A bot reads its instructions from `SKILL.md` on the pod, discovers tools as URL-addressable resources, and (with the owner's permission) writes back. No backend, no API key store, no secrets vault — just the pod.
|
|
226
|
+
- **Bot-to-bot falls out of the protocol.** Two pods running JSS can have their bots call each other's MCP endpoints, gated by WAC on both ends. No new federation wire.
|
|
227
|
+
|
|
228
|
+
See [#490](https://github.com/JavaScriptSolidServer/JavaScriptSolidServer/issues/490) for the design discussion and roadmap.
|
package/package.json
CHANGED
package/src/config.js
CHANGED
|
@@ -127,6 +127,9 @@ export const defaults = {
|
|
|
127
127
|
mongoUrl: 'mongodb://localhost:27017',
|
|
128
128
|
mongoDatabase: 'solid',
|
|
129
129
|
|
|
130
|
+
// MCP (Model Context Protocol) server — pod as a tool surface for agents (#490)
|
|
131
|
+
mcp: false,
|
|
132
|
+
|
|
130
133
|
// Logging
|
|
131
134
|
logger: true,
|
|
132
135
|
quiet: false,
|
|
@@ -197,6 +200,7 @@ const envMap = {
|
|
|
197
200
|
JSS_MONGO: 'mongo',
|
|
198
201
|
JSS_MONGO_URL: 'mongoUrl',
|
|
199
202
|
JSS_MONGO_DATABASE: 'mongoDatabase',
|
|
203
|
+
JSS_MCP: 'mcp',
|
|
200
204
|
};
|
|
201
205
|
|
|
202
206
|
/**
|
|
@@ -242,6 +246,7 @@ const BOOLEAN_KEYS = new Set([
|
|
|
242
246
|
'liveReload',
|
|
243
247
|
'pay',
|
|
244
248
|
'mongo',
|
|
249
|
+
'mcp',
|
|
245
250
|
'idp',
|
|
246
251
|
'notifications',
|
|
247
252
|
'logger',
|
package/src/mcp/index.js
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP (Model Context Protocol) plugin.
|
|
3
|
+
*
|
|
4
|
+
* Usage:
|
|
5
|
+
* createServer({ mcp: true })
|
|
6
|
+
*
|
|
7
|
+
* Endpoint:
|
|
8
|
+
* POST /mcp (JSON-RPC 2.0, MCP Streamable HTTP transport)
|
|
9
|
+
*
|
|
10
|
+
* Auth:
|
|
11
|
+
* Reuses JSS's existing auth chain — Bearer / DPoP / NIP-98 — so
|
|
12
|
+
* the same WAC rules that gate /public, /private, etc. also gate
|
|
13
|
+
* tool calls. Anonymous requests get the same WAC treatment as
|
|
14
|
+
* any other anonymous request.
|
|
15
|
+
*
|
|
16
|
+
* Spec: https://spec.modelcontextprotocol.io/specification/2025-03-26/
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import {
|
|
20
|
+
PROTOCOL_VERSION,
|
|
21
|
+
SERVER_INFO,
|
|
22
|
+
RPC_ERRORS,
|
|
23
|
+
rpcResult,
|
|
24
|
+
rpcError
|
|
25
|
+
} from './protocol.js';
|
|
26
|
+
import { listToolsForRpc, callTool, TOOLS } from './tools.js';
|
|
27
|
+
import { getWebIdFromRequestAsync } from '../auth/token.js';
|
|
28
|
+
|
|
29
|
+
const ALLOWED_METHODS = new Set([
|
|
30
|
+
'initialize',
|
|
31
|
+
'initialized',
|
|
32
|
+
'notifications/initialized',
|
|
33
|
+
'tools/list',
|
|
34
|
+
'tools/call',
|
|
35
|
+
'ping'
|
|
36
|
+
]);
|
|
37
|
+
|
|
38
|
+
function originOf(request) {
|
|
39
|
+
const host = request.headers.host || request.hostname;
|
|
40
|
+
const proto = request.protocol || 'http';
|
|
41
|
+
return `${proto}://${host}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function dispatch(msg, ctx) {
|
|
45
|
+
const { id, method, params } = msg;
|
|
46
|
+
|
|
47
|
+
if (!ALLOWED_METHODS.has(method)) {
|
|
48
|
+
return rpcError(id, RPC_ERRORS.METHOD_NOT_FOUND, `unknown method: ${method}`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (method === 'ping') {
|
|
52
|
+
return rpcResult(id, {});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (method === 'initialize') {
|
|
56
|
+
return rpcResult(id, {
|
|
57
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
58
|
+
serverInfo: SERVER_INFO,
|
|
59
|
+
capabilities: {
|
|
60
|
+
tools: { listChanged: false }
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (method === 'initialized' || method === 'notifications/initialized') {
|
|
66
|
+
// Notifications carry no id; nothing to return
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (method === 'tools/list') {
|
|
71
|
+
return rpcResult(id, { tools: listToolsForRpc() });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (method === 'tools/call') {
|
|
75
|
+
const toolName = params?.name;
|
|
76
|
+
const toolArgs = params?.arguments || {};
|
|
77
|
+
if (!toolName) {
|
|
78
|
+
return rpcError(id, RPC_ERRORS.INVALID_PARAMS, 'tool name required');
|
|
79
|
+
}
|
|
80
|
+
const result = await callTool(toolName, toolArgs, ctx);
|
|
81
|
+
return rpcResult(id, result);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return rpcError(id, RPC_ERRORS.METHOD_NOT_FOUND, `unhandled method: ${method}`);
|
|
85
|
+
}
|
|
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
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Register the MCP plugin with Fastify.
|
|
158
|
+
*/
|
|
159
|
+
export async function mcpPlugin(fastify, _options) {
|
|
160
|
+
fastify.post('/mcp', async (request, reply) => {
|
|
161
|
+
const body = request.body;
|
|
162
|
+
if (!body || typeof body !== 'object') {
|
|
163
|
+
reply.code(400);
|
|
164
|
+
return rpcError(null, RPC_ERRORS.INVALID_REQUEST, 'expected JSON-RPC body');
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Identity for tool calls — pulled from the inbound auth on /mcp itself.
|
|
168
|
+
// null webId means "anonymous"; WAC will treat it accordingly.
|
|
169
|
+
const { webId } = await getWebIdFromRequestAsync(request).catch(() => ({ webId: null }));
|
|
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
|
+
|
|
175
|
+
const ctx = {
|
|
176
|
+
webId: webId || null,
|
|
177
|
+
origin: originOf(request),
|
|
178
|
+
federationDepth
|
|
179
|
+
};
|
|
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
|
+
|
|
186
|
+
// Batch support (array of requests)
|
|
187
|
+
if (Array.isArray(body)) {
|
|
188
|
+
const out = [];
|
|
189
|
+
for (const msg of body) {
|
|
190
|
+
const r = await dispatch(msg, ctx);
|
|
191
|
+
if (r) out.push(r);
|
|
192
|
+
}
|
|
193
|
+
reply.header('Content-Type', 'application/json');
|
|
194
|
+
return out;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const result = await dispatch(body, ctx);
|
|
198
|
+
if (result === null) {
|
|
199
|
+
// Notification (no response body)
|
|
200
|
+
reply.code(204);
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
reply.header('Content-Type', 'application/json');
|
|
204
|
+
return result;
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
fastify.options('/mcp', async (_request, reply) => {
|
|
208
|
+
reply.header('Allow', 'POST, OPTIONS');
|
|
209
|
+
reply.code(204);
|
|
210
|
+
return null;
|
|
211
|
+
});
|
|
212
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP (Model Context Protocol) protocol envelope.
|
|
3
|
+
*
|
|
4
|
+
* Implements the Streamable HTTP transport for MCP 2025-03-26.
|
|
5
|
+
* Single endpoint (POST /mcp). Client sends JSON-RPC 2.0 requests.
|
|
6
|
+
* Server responds with JSON-RPC 2.0 responses (single-shot JSON for now;
|
|
7
|
+
* SSE streaming can be added later for subscribe-style tools).
|
|
8
|
+
*
|
|
9
|
+
* Spec: https://spec.modelcontextprotocol.io/specification/2025-03-26/
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export const PROTOCOL_VERSION = '2025-03-26';
|
|
13
|
+
|
|
14
|
+
export const SERVER_INFO = {
|
|
15
|
+
name: 'jss-mcp',
|
|
16
|
+
version: '0.1.0'
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
// JSON-RPC error codes
|
|
20
|
+
export const RPC_ERRORS = {
|
|
21
|
+
PARSE_ERROR: -32700,
|
|
22
|
+
INVALID_REQUEST: -32600,
|
|
23
|
+
METHOD_NOT_FOUND: -32601,
|
|
24
|
+
INVALID_PARAMS: -32602,
|
|
25
|
+
INTERNAL_ERROR: -32603,
|
|
26
|
+
// MCP-specific
|
|
27
|
+
TOOL_ERROR: -32000,
|
|
28
|
+
AUTH_REQUIRED: -32001,
|
|
29
|
+
ACCESS_DENIED: -32002
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export function rpcResult(id, result) {
|
|
33
|
+
return { jsonrpc: '2.0', id, result };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function rpcError(id, code, message, data) {
|
|
37
|
+
const err = { code, message };
|
|
38
|
+
if (data !== undefined) err.data = data;
|
|
39
|
+
return { jsonrpc: '2.0', id, error: err };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function toolText(text) {
|
|
43
|
+
return { content: [{ type: 'text', text }], isError: false };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function toolError(message) {
|
|
47
|
+
return { content: [{ type: 'text', text: message }], isError: true };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function toolJson(value) {
|
|
51
|
+
return toolText(JSON.stringify(value, null, 2));
|
|
52
|
+
}
|