@tik-choco/mistlib-mcp 0.0.0-stage → 0.1.0
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/LICENSE +373 -0
- package/README.md +128 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/mcp/index.d.ts +3 -0
- package/dist/mcp/index.js +1 -0
- package/dist/mcp/schema.d.ts +6 -0
- package/dist/mcp/schema.js +29 -0
- package/dist/mcp/server.d.ts +100 -0
- package/dist/mcp/server.js +303 -0
- package/dist/provider/identity.d.ts +4 -0
- package/dist/provider/identity.js +57 -0
- package/dist/provider/index.d.ts +4 -0
- package/dist/provider/index.js +3 -0
- package/dist/provider/mistseed.d.ts +16 -0
- package/dist/provider/mistseed.js +91 -0
- package/dist/provider/protocol.d.ts +49 -0
- package/dist/provider/protocol.js +139 -0
- package/dist/provider/provider.d.ts +3 -0
- package/dist/provider/provider.js +430 -0
- package/dist/provider/shared-node.d.ts +23 -0
- package/dist/provider/shared-node.js +78 -0
- package/dist/provider/types.d.ts +31 -0
- package/dist/provider/types.js +1 -0
- package/dist/wire/credentials.d.ts +47 -0
- package/dist/wire/credentials.js +79 -0
- package/dist/wire/encoding.d.ts +7 -0
- package/dist/wire/encoding.js +23 -0
- package/dist/wire/errors.d.ts +27 -0
- package/dist/wire/errors.js +19 -0
- package/dist/wire/framing.d.ts +40 -0
- package/dist/wire/framing.js +166 -0
- package/dist/wire/index.d.ts +8 -0
- package/dist/wire/index.js +8 -0
- package/dist/wire/json.d.ts +13 -0
- package/dist/wire/json.js +73 -0
- package/dist/wire/messages.d.ts +68 -0
- package/dist/wire/messages.js +89 -0
- package/dist/wire/names.d.ts +4 -0
- package/dist/wire/names.js +14 -0
- package/dist/wire/noise-session.d.ts +135 -0
- package/dist/wire/noise-session.js +432 -0
- package/noise-wasm/README.md +59 -0
- package/noise-wasm/pkg/noise_wasm.d.ts +101 -0
- package/noise-wasm/pkg/noise_wasm.js +699 -0
- package/noise-wasm/pkg/noise_wasm_bg.wasm +0 -0
- package/noise-wasm/pkg/noise_wasm_bg.wasm.d.ts +30 -0
- package/package.json +70 -4
- package/spec/provider-runtime-v1.md +100 -0
- package/spec/secure-channel-v1.md +213 -0
- package/spec/wire-v1.md +355 -0
- package/vectors/wire-v1.json +117 -0
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { canonicalBytes, canonicalJson, isObject, parseJson } from "../wire/json.js";
|
|
2
|
+
import { isLocalName, isNamespace } from "../wire/names.js";
|
|
3
|
+
import { RPC_CODES as C } from "../wire/errors.js";
|
|
4
|
+
import { MCP_VERSION, MAX_MESSAGE_SIZE, MAX_PEER_CALLS, MAX_TOOLS, MAX_TOOL_BYTES, CALL_TIMEOUT_MS, INIT_TIMEOUT_MS, MAX_CALL_TIMEOUT_MS, MAX_SESSION_MESSAGES } from "../wire/messages.js";
|
|
5
|
+
import { compileSchema } from "./schema.js";
|
|
6
|
+
/** An explicit MCP tool result. Return it from a handler to control `content` / `isError` directly. */
|
|
7
|
+
export class ToolResult {
|
|
8
|
+
content;
|
|
9
|
+
structuredContent;
|
|
10
|
+
isError;
|
|
11
|
+
constructor(content, structuredContent, isError = false) {
|
|
12
|
+
this.content = content;
|
|
13
|
+
this.structuredContent = structuredContent;
|
|
14
|
+
this.isError = isError;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function toolResult(r) {
|
|
18
|
+
return new ToolResult(r.content, r.structuredContent, r.isError === true);
|
|
19
|
+
}
|
|
20
|
+
class RpcError extends Error {
|
|
21
|
+
code;
|
|
22
|
+
constructor(code, message) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.code = code;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const idValid = (id) => typeof id === "string" || (typeof id === "number" && Number.isSafeInteger(id));
|
|
28
|
+
const clone = (v) => JSON.parse(canonicalJson(v));
|
|
29
|
+
const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
30
|
+
/** @internal Shared validation for the persistent provider catalog and session catalogs. */
|
|
31
|
+
export function prepareTool(name, definition, handler) {
|
|
32
|
+
if (!isLocalName(name) || typeof handler !== "function")
|
|
33
|
+
throw new TypeError("Invalid tool");
|
|
34
|
+
const d = clone(definition);
|
|
35
|
+
if (!isObject(d) || Object.keys(d).some(k => !["title", "description", "inputSchema", "annotations"].includes(k)) ||
|
|
36
|
+
(d.title !== undefined && typeof d.title !== "string") || (d.description !== undefined && typeof d.description !== "string") ||
|
|
37
|
+
(d.annotations !== undefined && (!isObject(d.annotations) || Object.entries(d.annotations).some(([k, v]) => k === "title" ? typeof v !== "string" : !["readOnlyHint", "destructiveHint", "idempotentHint", "openWorldHint"].includes(k) || typeof v !== "boolean"))) ||
|
|
38
|
+
canonicalBytes({ name, ...d }).length > MAX_TOOL_BYTES)
|
|
39
|
+
throw new TypeError("Invalid tool definition");
|
|
40
|
+
return { definition: d, validate: compileSchema(d.inputSchema), handler };
|
|
41
|
+
}
|
|
42
|
+
export class McpServer {
|
|
43
|
+
options;
|
|
44
|
+
tools = new Map();
|
|
45
|
+
ledger = new Map();
|
|
46
|
+
unsubscribe;
|
|
47
|
+
phase = "new";
|
|
48
|
+
revision = 0;
|
|
49
|
+
active = 0;
|
|
50
|
+
writing = false;
|
|
51
|
+
pageSize;
|
|
52
|
+
timeout;
|
|
53
|
+
ledgerBytes = 0;
|
|
54
|
+
sendQueue = Promise.resolve();
|
|
55
|
+
queuedBytes = 0;
|
|
56
|
+
initTimer;
|
|
57
|
+
constructor(options) {
|
|
58
|
+
this.options = options;
|
|
59
|
+
if (!isNamespace(options.namespace))
|
|
60
|
+
throw new TypeError("Invalid namespace");
|
|
61
|
+
this.pageSize = options.pageSize ?? 16;
|
|
62
|
+
this.timeout = options.callTimeoutMs ?? CALL_TIMEOUT_MS;
|
|
63
|
+
if (!Number.isSafeInteger(this.pageSize) || this.pageSize < 1 || this.pageSize > MAX_TOOLS ||
|
|
64
|
+
!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > MAX_CALL_TIMEOUT_MS)
|
|
65
|
+
throw new TypeError("Invalid server limits");
|
|
66
|
+
this.unsubscribe = options.transport.onMessage(bytes => { void this.receive(bytes); });
|
|
67
|
+
this.initTimer = setTimeout(() => this.fail(new Error("Initialize deadline exceeded")), INIT_TIMEOUT_MS);
|
|
68
|
+
}
|
|
69
|
+
registerTool(name, definition, handler) {
|
|
70
|
+
if (this.phase === "closed" || this.tools.has(name) || this.tools.size >= MAX_TOOLS)
|
|
71
|
+
throw new TypeError("Invalid or duplicate tool");
|
|
72
|
+
const tool = prepareTool(name, definition, handler);
|
|
73
|
+
if (tool.definition.annotations?.readOnlyHint !== true && !this.options.confirm)
|
|
74
|
+
throw new TypeError("Confirmation hook required");
|
|
75
|
+
this.tools.set(name, tool);
|
|
76
|
+
this.changed();
|
|
77
|
+
return () => { if (this.tools.get(name) === tool) {
|
|
78
|
+
this.tools.delete(name);
|
|
79
|
+
this.changed();
|
|
80
|
+
} };
|
|
81
|
+
}
|
|
82
|
+
/** Sorted immutable-by-copy catalog for digesting and approval. */
|
|
83
|
+
catalog() {
|
|
84
|
+
return [...this.tools].sort(([a], [b]) => compare(a, b)).map(([name, t]) => ({ name, ...clone(t.definition) }));
|
|
85
|
+
}
|
|
86
|
+
changed() {
|
|
87
|
+
this.revision++;
|
|
88
|
+
if (this.phase === "ready")
|
|
89
|
+
this.send({ jsonrpc: "2.0", method: "notifications/tools/list_changed" });
|
|
90
|
+
}
|
|
91
|
+
send(message) {
|
|
92
|
+
if (this.phase === "closed")
|
|
93
|
+
return;
|
|
94
|
+
const bytes = canonicalBytes(message);
|
|
95
|
+
if (bytes.length > MAX_MESSAGE_SIZE || this.queuedBytes + bytes.length > 4 * 1024 * 1024) {
|
|
96
|
+
this.fail(new Error("Outbound queue exhausted"));
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
this.queuedBytes += bytes.length;
|
|
100
|
+
this.sendQueue = this.sendQueue.then(async () => {
|
|
101
|
+
if (this.phase !== "closed")
|
|
102
|
+
await this.options.transport.send(bytes);
|
|
103
|
+
}).catch(e => this.fail(e)).finally(() => { this.queuedBytes -= bytes.length; });
|
|
104
|
+
}
|
|
105
|
+
fail(e) {
|
|
106
|
+
this.dispose();
|
|
107
|
+
this.options.onSessionError?.(e);
|
|
108
|
+
}
|
|
109
|
+
dispose() {
|
|
110
|
+
if (this.phase === "closed")
|
|
111
|
+
return;
|
|
112
|
+
this.phase = "closed";
|
|
113
|
+
clearTimeout(this.initTimer);
|
|
114
|
+
this.unsubscribe?.();
|
|
115
|
+
for (const entry of this.ledger.values()) {
|
|
116
|
+
clearTimeout(entry.timer);
|
|
117
|
+
entry.controller?.abort();
|
|
118
|
+
}
|
|
119
|
+
this.ledger.clear();
|
|
120
|
+
this.tools.clear();
|
|
121
|
+
this.ledgerBytes = 0;
|
|
122
|
+
}
|
|
123
|
+
error(id, code, message) {
|
|
124
|
+
return { jsonrpc: "2.0", id, error: { code, message } };
|
|
125
|
+
}
|
|
126
|
+
finish(id, entry, response) {
|
|
127
|
+
if (this.phase === "closed" || entry.response)
|
|
128
|
+
return;
|
|
129
|
+
clearTimeout(entry.timer);
|
|
130
|
+
let size;
|
|
131
|
+
try {
|
|
132
|
+
size = canonicalBytes(response).length;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
size = Infinity;
|
|
136
|
+
}
|
|
137
|
+
if (size > MAX_MESSAGE_SIZE) {
|
|
138
|
+
response = this.error(id, C.INTERNAL_ERROR, "Invalid or oversized result");
|
|
139
|
+
size = canonicalBytes(response).length;
|
|
140
|
+
}
|
|
141
|
+
if (this.ledgerBytes + size > 16 * 1024 * 1024) {
|
|
142
|
+
this.fail(new Error("Request ledger exhausted"));
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
entry.response = response;
|
|
146
|
+
this.ledgerBytes += size;
|
|
147
|
+
this.send(response);
|
|
148
|
+
}
|
|
149
|
+
cancel(id, code) {
|
|
150
|
+
const entry = this.ledger.get(id);
|
|
151
|
+
if (!entry?.controller || entry.response)
|
|
152
|
+
return;
|
|
153
|
+
entry.controller.abort();
|
|
154
|
+
const unknown = entry.started;
|
|
155
|
+
this.finish(id, entry, this.error(id, unknown ? C.RESULT_UNKNOWN : code, unknown ? "Execution started; result unknown" : code === C.TIMEOUT ? "Deadline exceeded" : "Cancelled"));
|
|
156
|
+
}
|
|
157
|
+
async receive(bytes) {
|
|
158
|
+
if (this.phase === "closed")
|
|
159
|
+
return;
|
|
160
|
+
let request;
|
|
161
|
+
try {
|
|
162
|
+
if (bytes.length > MAX_MESSAGE_SIZE)
|
|
163
|
+
throw new Error("Size limit");
|
|
164
|
+
request = parseJson(bytes);
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
this.send(this.error(null, C.PARSE_ERROR, "Invalid JSON"));
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (!isObject(request) || request.jsonrpc !== "2.0" || typeof request.method !== "string" ||
|
|
171
|
+
Object.keys(request).some(k => !["jsonrpc", "method", "id", "params"].includes(k)) ||
|
|
172
|
+
(Object.hasOwn(request, "id") && !idValid(request.id))) {
|
|
173
|
+
this.send(this.error(null, C.INVALID_REQUEST, "Invalid request"));
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const { method, id, params } = request;
|
|
177
|
+
if (id === undefined) {
|
|
178
|
+
if (method === "notifications/initialized" && this.phase === "initializing" && (params === undefined || isObject(params))) {
|
|
179
|
+
this.phase = "ready";
|
|
180
|
+
clearTimeout(this.initTimer);
|
|
181
|
+
}
|
|
182
|
+
if (method === "notifications/cancelled" && this.phase === "ready" && isObject(params) &&
|
|
183
|
+
idValid(params.requestId) && (params.reason === undefined || typeof params.reason === "string"))
|
|
184
|
+
this.cancel(params.requestId, C.CANCELLED);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const rid = id;
|
|
188
|
+
if (method.startsWith("notifications/")) {
|
|
189
|
+
this.send(this.error(rid, C.INVALID_REQUEST, "Notification cannot have id"));
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
const key = canonicalJson(request);
|
|
193
|
+
const old = this.ledger.get(rid);
|
|
194
|
+
if (old) {
|
|
195
|
+
if (old.request !== key)
|
|
196
|
+
this.send(this.error(rid, C.INVALID_REQUEST, "Conflicting request id"));
|
|
197
|
+
else if (old.response)
|
|
198
|
+
this.send(old.response);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const recordedBytes = key.length * 2;
|
|
202
|
+
if (this.ledger.size >= MAX_SESSION_MESSAGES || this.ledgerBytes + recordedBytes > 16 * 1024 * 1024) {
|
|
203
|
+
this.fail(new Error("Request ledger exhausted"));
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const entry = { request: key };
|
|
207
|
+
this.ledger.set(rid, entry);
|
|
208
|
+
this.ledgerBytes += recordedBytes;
|
|
209
|
+
try {
|
|
210
|
+
if (params !== undefined && !isObject(params))
|
|
211
|
+
throw new RpcError(C.INVALID_PARAMS, "Expected object params");
|
|
212
|
+
const p = (params ?? {});
|
|
213
|
+
let result;
|
|
214
|
+
if (method === "ping")
|
|
215
|
+
result = {};
|
|
216
|
+
else if (method === "initialize") {
|
|
217
|
+
if (this.phase !== "new" || typeof p.protocolVersion !== "string" || !isObject(p.capabilities) ||
|
|
218
|
+
!isObject(p.clientInfo) || typeof p.clientInfo.name !== "string" || typeof p.clientInfo.version !== "string")
|
|
219
|
+
throw new RpcError(C.INVALID_PARAMS, "Invalid initialize");
|
|
220
|
+
this.phase = "initializing";
|
|
221
|
+
result = { protocolVersion: MCP_VERSION, capabilities: { tools: { listChanged: true } },
|
|
222
|
+
serverInfo: { name: this.options.namespace, version: "0.1.0" } };
|
|
223
|
+
}
|
|
224
|
+
else {
|
|
225
|
+
if (this.phase !== "ready")
|
|
226
|
+
throw new RpcError(C.INVALID_REQUEST, "Not initialized");
|
|
227
|
+
if (method === "tools/list")
|
|
228
|
+
result = this.list(p);
|
|
229
|
+
else if (method === "tools/call")
|
|
230
|
+
result = await this.call(rid, p, entry);
|
|
231
|
+
else
|
|
232
|
+
throw new RpcError(C.METHOD_NOT_FOUND, "Unknown method");
|
|
233
|
+
}
|
|
234
|
+
this.finish(rid, entry, { jsonrpc: "2.0", id: rid, result });
|
|
235
|
+
}
|
|
236
|
+
catch (e) {
|
|
237
|
+
this.finish(rid, entry, this.error(rid, e instanceof RpcError ? e.code : C.INTERNAL_ERROR, e instanceof RpcError ? e.message : "Internal error"));
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
list(p) {
|
|
241
|
+
let index = 0;
|
|
242
|
+
if (p.cursor !== undefined) {
|
|
243
|
+
if (typeof p.cursor !== "string" || !/^\d+:\d+$/.test(p.cursor))
|
|
244
|
+
throw new RpcError(C.INVALID_PARAMS, "Invalid cursor");
|
|
245
|
+
const [revision, offset] = p.cursor.split(":").map(Number);
|
|
246
|
+
if (revision !== this.revision || !Number.isSafeInteger(offset) || offset < 1 || offset >= this.tools.size)
|
|
247
|
+
throw new RpcError(C.INVALID_PARAMS, "Stale cursor");
|
|
248
|
+
index = offset;
|
|
249
|
+
}
|
|
250
|
+
const catalog = this.catalog();
|
|
251
|
+
// Keep the response safely below the transport limit even with large schemas.
|
|
252
|
+
const tools = catalog.slice(index, index + Math.min(this.pageSize, 30));
|
|
253
|
+
const next = index + tools.length;
|
|
254
|
+
return { tools: tools, ...(next < catalog.length ? { nextCursor: this.revision + ":" + next } : {}) };
|
|
255
|
+
}
|
|
256
|
+
async call(id, p, entry) {
|
|
257
|
+
const tool = typeof p.name === "string" ? this.tools.get(p.name) : undefined;
|
|
258
|
+
const args = p.arguments === undefined ? {} : p.arguments;
|
|
259
|
+
if (!tool || !isObject(args) || !tool.validate(args))
|
|
260
|
+
throw new RpcError(C.INVALID_PARAMS, "Unknown tool or invalid arguments");
|
|
261
|
+
const write = tool.definition.annotations?.readOnlyHint !== true;
|
|
262
|
+
if (this.active >= MAX_PEER_CALLS || (write && this.writing))
|
|
263
|
+
throw new RpcError(C.BUSY, "Call limit");
|
|
264
|
+
this.active++;
|
|
265
|
+
if (write)
|
|
266
|
+
this.writing = true;
|
|
267
|
+
const controller = new AbortController();
|
|
268
|
+
entry.controller = controller;
|
|
269
|
+
entry.timer = setTimeout(() => this.cancel(id, C.TIMEOUT), this.timeout);
|
|
270
|
+
try {
|
|
271
|
+
const context = { signal: controller.signal, requestId: id };
|
|
272
|
+
if (write && await this.options.confirm?.({ ...context, name: p.name, arguments: clone(args),
|
|
273
|
+
definition: clone(tool.definition) }) !== true)
|
|
274
|
+
throw new RpcError(C.DENIED, "Confirmation denied");
|
|
275
|
+
if (controller.signal.aborted || this.tools.get(p.name) !== tool)
|
|
276
|
+
throw new RpcError(C.CANCELLED, "Call cancelled or definition changed");
|
|
277
|
+
entry.started = true;
|
|
278
|
+
let value;
|
|
279
|
+
try {
|
|
280
|
+
value = await tool.handler(clone(args), context);
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
return { isError: true, content: [{ type: "text", text: "Tool execution failed" }] };
|
|
284
|
+
}
|
|
285
|
+
if (value instanceof ToolResult) {
|
|
286
|
+
const content = value.content.filter(c => c && c.type === "text" && typeof c.text === "string").map(c => ({ type: "text", text: c.text }));
|
|
287
|
+
const out = { content: content.length ? content : [{ type: "text", text: "" }] };
|
|
288
|
+
if (isObject(value.structuredContent))
|
|
289
|
+
out.structuredContent = clone(value.structuredContent);
|
|
290
|
+
if (value.isError)
|
|
291
|
+
out.isError = true;
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
const text = canonicalJson(value);
|
|
295
|
+
return { content: [{ type: "text", text }], structuredContent: isObject(value) ? clone(value) : { value } };
|
|
296
|
+
}
|
|
297
|
+
finally {
|
|
298
|
+
this.active--;
|
|
299
|
+
if (write)
|
|
300
|
+
this.writing = false;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { BindingSigner } from "../wire/noise-session.js";
|
|
2
|
+
export declare function ed25519DidKey(raw: Uint8Array): string;
|
|
3
|
+
/** Origin-scoped Ed25519 leaf; the private CryptoKey is never exported. */
|
|
4
|
+
export declare function createOriginSigner(): Promise<BindingSigner>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { ed25519PublicKeyFromDidKey, webCryptoBindingSigner } from "../wire/noise-session.js";
|
|
2
|
+
const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
3
|
+
export function ed25519DidKey(raw) {
|
|
4
|
+
if (raw.length !== 32)
|
|
5
|
+
throw new TypeError("Invalid Ed25519 public key");
|
|
6
|
+
let n = 0n;
|
|
7
|
+
for (const b of [0xed, 1, ...raw])
|
|
8
|
+
n = (n << 8n) | BigInt(b);
|
|
9
|
+
let encoded = "";
|
|
10
|
+
while (n) {
|
|
11
|
+
encoded = ALPHABET[Number(n % 58n)] + encoded;
|
|
12
|
+
n /= 58n;
|
|
13
|
+
}
|
|
14
|
+
return "did:key:z" + encoded;
|
|
15
|
+
}
|
|
16
|
+
function openDatabase() {
|
|
17
|
+
return new Promise((resolve, reject) => {
|
|
18
|
+
const req = indexedDB.open("mist-mcp-provider-v1", 1);
|
|
19
|
+
req.onupgradeneeded = () => req.result.createObjectStore("identity");
|
|
20
|
+
req.onsuccess = () => resolve(req.result);
|
|
21
|
+
req.onerror = () => reject(req.error);
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
// Read then conditionally insert in one readwrite transaction. Concurrent tabs
|
|
25
|
+
// may generate candidates, but only the first committed leaf is ever returned.
|
|
26
|
+
function loadOrInsert(db, candidate) {
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
const tx = db.transaction("identity", "readwrite");
|
|
29
|
+
const store = tx.objectStore("identity");
|
|
30
|
+
const req = store.get("leaf");
|
|
31
|
+
let leaf;
|
|
32
|
+
req.onsuccess = () => {
|
|
33
|
+
leaf = req.result ?? candidate;
|
|
34
|
+
if (req.result === undefined)
|
|
35
|
+
store.add(candidate, "leaf");
|
|
36
|
+
};
|
|
37
|
+
tx.oncomplete = () => resolve(leaf);
|
|
38
|
+
tx.onabort = () => reject(tx.error ?? new Error("Identity transaction aborted"));
|
|
39
|
+
tx.onerror = () => reject(tx.error);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/** Origin-scoped Ed25519 leaf; the private CryptoKey is never exported. */
|
|
43
|
+
export async function createOriginSigner() {
|
|
44
|
+
const db = await openDatabase();
|
|
45
|
+
try {
|
|
46
|
+
const keys = await crypto.subtle.generateKey({ name: "Ed25519" }, false, ["sign", "verify"]);
|
|
47
|
+
const did = ed25519DidKey(new Uint8Array(await crypto.subtle.exportKey("raw", keys.publicKey)));
|
|
48
|
+
const leaf = await loadOrInsert(db, { did, privateKey: keys.privateKey });
|
|
49
|
+
if (!ed25519PublicKeyFromDidKey(leaf.did) || leaf.privateKey.extractable ||
|
|
50
|
+
leaf.privateKey.type !== "private" || leaf.privateKey.algorithm.name !== "Ed25519" || !leaf.privateKey.usages.includes("sign"))
|
|
51
|
+
throw new Error("Invalid stored provider identity");
|
|
52
|
+
return webCryptoBindingSigner(leaf.did, leaf.privateKey);
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
db.close();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { MistTransport } from "./types.js";
|
|
2
|
+
/** Structural subset of @tik-choco/mistseed/node; no runtime dependency on it. */
|
|
3
|
+
export interface MistseedNode {
|
|
4
|
+
currentNodeId(): string;
|
|
5
|
+
ensureNode(): Promise<{
|
|
6
|
+
sendMessage(to: string, bytes: Uint8Array, delivery: 0, room: string): void;
|
|
7
|
+
}>;
|
|
8
|
+
acquireRoom(room: string): {
|
|
9
|
+
ready: Promise<void> | null;
|
|
10
|
+
release(): void;
|
|
11
|
+
};
|
|
12
|
+
subscribeRoom(room: string, cb: (event: number, from: string, payload: unknown) => void): () => void;
|
|
13
|
+
onNetworkDisabled?(cb: () => void): () => void;
|
|
14
|
+
}
|
|
15
|
+
/** Adapt the shared node facade (e.g. import * as node from '@tik-choco/mistseed/node'). */
|
|
16
|
+
export declare function fromMistseed(node: MistseedNode): MistTransport;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
function toBytes(value) {
|
|
2
|
+
if (value instanceof Uint8Array)
|
|
3
|
+
return value;
|
|
4
|
+
if (value instanceof ArrayBuffer)
|
|
5
|
+
return new Uint8Array(value);
|
|
6
|
+
if (ArrayBuffer.isView(value))
|
|
7
|
+
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
8
|
+
if (Array.isArray(value) && value.every(x => Number.isInteger(x) && x >= 0 && x <= 255))
|
|
9
|
+
return Uint8Array.from(value);
|
|
10
|
+
}
|
|
11
|
+
/** Adapt the shared node facade (e.g. import * as node from '@tik-choco/mistseed/node'). */
|
|
12
|
+
export function fromMistseed(node) {
|
|
13
|
+
const rooms = new Map();
|
|
14
|
+
const messages = new Set();
|
|
15
|
+
const peers = new Set();
|
|
16
|
+
const stop = (room, entry) => {
|
|
17
|
+
if (entry.stopped)
|
|
18
|
+
return;
|
|
19
|
+
entry.stopped = true;
|
|
20
|
+
entry.send = undefined;
|
|
21
|
+
if (rooms.get(room) === entry)
|
|
22
|
+
rooms.delete(room);
|
|
23
|
+
for (const from of entry.peers)
|
|
24
|
+
for (const cb of peers)
|
|
25
|
+
cb(room, from, false);
|
|
26
|
+
entry.release?.();
|
|
27
|
+
};
|
|
28
|
+
return {
|
|
29
|
+
get selfNodeId() { return node.currentNodeId(); },
|
|
30
|
+
async join(room) {
|
|
31
|
+
const existing = rooms.get(room);
|
|
32
|
+
if (existing) {
|
|
33
|
+
existing.refs++;
|
|
34
|
+
return existing.ready;
|
|
35
|
+
}
|
|
36
|
+
const entry = { refs: 1, ready: Promise.resolve(), peers: new Set(), stopped: false };
|
|
37
|
+
rooms.set(room, entry);
|
|
38
|
+
entry.ready = (async () => {
|
|
39
|
+
const shared = await node.ensureNode();
|
|
40
|
+
if (entry.stopped)
|
|
41
|
+
throw new Error("Room lease released");
|
|
42
|
+
const unsubscribe = node.subscribeRoom(room, (event, from, payload) => {
|
|
43
|
+
if (entry.stopped || !from)
|
|
44
|
+
return;
|
|
45
|
+
if (event === 0) {
|
|
46
|
+
const bytes = toBytes(payload);
|
|
47
|
+
if (bytes) {
|
|
48
|
+
entry.peers.add(from);
|
|
49
|
+
for (const cb of messages)
|
|
50
|
+
cb(room, from, bytes);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
else if (event === 2 || event === 3) {
|
|
54
|
+
if (event === 2)
|
|
55
|
+
entry.peers.add(from);
|
|
56
|
+
else
|
|
57
|
+
entry.peers.delete(from);
|
|
58
|
+
for (const cb of peers)
|
|
59
|
+
cb(room, from, event === 2);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
let lease;
|
|
63
|
+
let disabled;
|
|
64
|
+
entry.release = () => { unsubscribe(); disabled?.(); lease?.release(); };
|
|
65
|
+
try {
|
|
66
|
+
lease = node.acquireRoom(room);
|
|
67
|
+
disabled = node.onNetworkDisabled?.(() => stop(room, entry));
|
|
68
|
+
await lease.ready;
|
|
69
|
+
if (entry.stopped)
|
|
70
|
+
throw new Error("Room lease released");
|
|
71
|
+
entry.send = (to, bytes) => shared.sendMessage(to, bytes, 0, room);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
stop(room, entry);
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
})().catch(error => { stop(room, entry); throw error; });
|
|
78
|
+
return entry.ready;
|
|
79
|
+
},
|
|
80
|
+
leave(room) { const entry = rooms.get(room); if (entry && --entry.refs === 0)
|
|
81
|
+
stop(room, entry); },
|
|
82
|
+
send(room, toNodeId, bytes) {
|
|
83
|
+
const send = rooms.get(room)?.send;
|
|
84
|
+
if (!send || !toNodeId)
|
|
85
|
+
throw new Error("Room not ready or missing destination");
|
|
86
|
+
send(toNodeId, bytes);
|
|
87
|
+
},
|
|
88
|
+
onMessage(cb) { messages.add(cb); return () => { messages.delete(cb); }; },
|
|
89
|
+
onPeer(cb) { peers.add(cb); return () => { peers.delete(cb); }; },
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { JsonObject } from "../wire/json.js";
|
|
2
|
+
import type { HandshakeType, Hello, WireMessage } from "../wire/messages.js";
|
|
3
|
+
import type { ClosableFrameCipher } from "../wire/noise-session.js";
|
|
4
|
+
import type { ProviderTicket } from "../wire/credentials.js";
|
|
5
|
+
import type { MistTransport } from "./types.js";
|
|
6
|
+
export declare const PAIRING_KEY = "mist-mcp:v1:pairing";
|
|
7
|
+
export declare const SESSION_TIMEOUT = 15000;
|
|
8
|
+
export declare const LIVENESS_TIMEOUT = 45000;
|
|
9
|
+
export declare const PAIR_TIMEOUT = 120000;
|
|
10
|
+
export declare const hex: (bytes: Uint8Array) => string;
|
|
11
|
+
export declare function sha256(bytes: Uint8Array): Promise<string>;
|
|
12
|
+
export declare function pairingRoom(code: string): Promise<string>;
|
|
13
|
+
export declare const isPermanentRoom: (room: unknown) => room is string;
|
|
14
|
+
export declare const cancelled: () => Error;
|
|
15
|
+
export declare function check(signal: AbortSignal): void;
|
|
16
|
+
export declare function abortable<T>(value: T | Promise<T>, signal: AbortSignal): Promise<T>;
|
|
17
|
+
export declare function delay(ms: number, signal: AbortSignal): Promise<void>;
|
|
18
|
+
type Received = {
|
|
19
|
+
from: string;
|
|
20
|
+
message: WireMessage;
|
|
21
|
+
};
|
|
22
|
+
/** One bounded, ordered inbox for a room. Select a single directed peer and sid
|
|
23
|
+
* before processing any handshake or application records. */
|
|
24
|
+
export declare class Inbox {
|
|
25
|
+
private readonly transport;
|
|
26
|
+
readonly room: string;
|
|
27
|
+
private readonly controller;
|
|
28
|
+
private queue;
|
|
29
|
+
private wake?;
|
|
30
|
+
private peer?;
|
|
31
|
+
private sid?;
|
|
32
|
+
private readonly off;
|
|
33
|
+
constructor(transport: MistTransport, room: string, controller: AbortController);
|
|
34
|
+
select(peer: string, sid: string): void;
|
|
35
|
+
next(): Promise<Received>;
|
|
36
|
+
hello(predicate: (hello: Hello) => boolean): Promise<{
|
|
37
|
+
from: string;
|
|
38
|
+
hello: Hello;
|
|
39
|
+
}>;
|
|
40
|
+
send(message: WireMessage): Promise<void>;
|
|
41
|
+
sendData(type: HandshakeType | "mcp.close", data: Uint8Array): Promise<void>;
|
|
42
|
+
receiveData(type: HandshakeType): Promise<Uint8Array>;
|
|
43
|
+
close(): void;
|
|
44
|
+
}
|
|
45
|
+
/** Bind protected control payloads to their outer type and exchange ID. */
|
|
46
|
+
export declare function sealControl(cipher: ClosableFrameCipher, type: HandshakeType | "mcp.close", sid: string, body: JsonObject): Uint8Array;
|
|
47
|
+
export declare function openControl(cipher: ClosableFrameCipher, type: HandshakeType | "mcp.close", sid: string, data: Uint8Array): JsonObject;
|
|
48
|
+
export declare function validateTicket(value: unknown, did: string, leaf: string, origin: string, instance: string): Promise<ProviderTicket>;
|
|
49
|
+
export {};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { base64url, exactKeys, unbase64url } from "../wire/encoding.js";
|
|
2
|
+
import { canonicalBytes, isObject, parseJson } from "../wire/json.js";
|
|
3
|
+
import { decodeWire, encodeWire, MAX_FRAME_SIZE } from "../wire/messages.js";
|
|
4
|
+
import { normalizePairingCode, ed25519PublicKeyFromDidKey } from "../wire/noise-session.js";
|
|
5
|
+
import { isProviderTicket, ticketSigningBytes } from "../wire/credentials.js";
|
|
6
|
+
export const PAIRING_KEY = "mist-mcp:v1:pairing";
|
|
7
|
+
export const SESSION_TIMEOUT = 15_000;
|
|
8
|
+
export const LIVENESS_TIMEOUT = 45_000;
|
|
9
|
+
export const PAIR_TIMEOUT = 120_000;
|
|
10
|
+
export const hex = (bytes) => Array.from(bytes, b => b.toString(16).padStart(2, "0")).join("");
|
|
11
|
+
export async function sha256(bytes) {
|
|
12
|
+
return hex(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)));
|
|
13
|
+
}
|
|
14
|
+
export async function pairingRoom(code) {
|
|
15
|
+
return "mcp-pair-v1-" + (await sha256(new TextEncoder().encode("mist-mcp/v1/pair-room|" + normalizePairingCode(code)))).slice(0, 32);
|
|
16
|
+
}
|
|
17
|
+
export const isPermanentRoom = (room) => typeof room === "string" && /^mcp-v1-[0-9a-f]{32}$/.test(room);
|
|
18
|
+
export const cancelled = () => new Error("Provider operation cancelled");
|
|
19
|
+
export function check(signal) { if (signal.aborted)
|
|
20
|
+
throw cancelled(); }
|
|
21
|
+
export function abortable(value, signal) {
|
|
22
|
+
return new Promise((resolve, reject) => {
|
|
23
|
+
const abort = () => reject(cancelled());
|
|
24
|
+
if (signal.aborted)
|
|
25
|
+
abort();
|
|
26
|
+
else
|
|
27
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
28
|
+
Promise.resolve(value).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
export function delay(ms, signal) {
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
if (signal.aborted) {
|
|
34
|
+
reject(cancelled());
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const abort = () => { clearTimeout(timer); reject(cancelled()); };
|
|
38
|
+
const timer = setTimeout(() => { signal.removeEventListener("abort", abort); resolve(); }, ms);
|
|
39
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/** One bounded, ordered inbox for a room. Select a single directed peer and sid
|
|
43
|
+
* before processing any handshake or application records. */
|
|
44
|
+
export class Inbox {
|
|
45
|
+
transport;
|
|
46
|
+
room;
|
|
47
|
+
controller;
|
|
48
|
+
queue = [];
|
|
49
|
+
wake;
|
|
50
|
+
peer;
|
|
51
|
+
sid;
|
|
52
|
+
off;
|
|
53
|
+
constructor(transport, room, controller) {
|
|
54
|
+
this.transport = transport;
|
|
55
|
+
this.room = room;
|
|
56
|
+
this.controller = controller;
|
|
57
|
+
this.off = [transport.onMessage((r, from, bytes) => {
|
|
58
|
+
if (controller.signal.aborted || r !== room || from === transport.selfNodeId || (this.peer && from !== this.peer))
|
|
59
|
+
return;
|
|
60
|
+
if (bytes.byteLength > MAX_FRAME_SIZE)
|
|
61
|
+
return;
|
|
62
|
+
let message;
|
|
63
|
+
try {
|
|
64
|
+
message = decodeWire(bytes);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (this.sid ? (message.type === "mcp.hello" || message.sid !== this.sid) : message.type !== "mcp.hello")
|
|
70
|
+
return;
|
|
71
|
+
if (this.queue.length >= 128) {
|
|
72
|
+
controller.abort();
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
this.queue.push({ from, message });
|
|
76
|
+
this.wake?.();
|
|
77
|
+
}), transport.onPeer((r, from, connected) => {
|
|
78
|
+
if (r === room && this.peer === from && !connected)
|
|
79
|
+
controller.abort();
|
|
80
|
+
})];
|
|
81
|
+
}
|
|
82
|
+
select(peer, sid) { this.peer = peer; this.sid = sid; this.queue = []; }
|
|
83
|
+
async next() {
|
|
84
|
+
const signal = this.controller.signal;
|
|
85
|
+
while (!this.queue.length) {
|
|
86
|
+
check(signal);
|
|
87
|
+
await abortable(new Promise(resolve => { this.wake = resolve; }), signal);
|
|
88
|
+
this.wake = undefined;
|
|
89
|
+
}
|
|
90
|
+
check(signal);
|
|
91
|
+
return this.queue.shift();
|
|
92
|
+
}
|
|
93
|
+
async hello(predicate) {
|
|
94
|
+
while (true) {
|
|
95
|
+
const { from, message } = await this.next();
|
|
96
|
+
if (message.type === "mcp.hello" && predicate(message))
|
|
97
|
+
return { from, hello: message };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
async send(message) {
|
|
101
|
+
check(this.controller.signal);
|
|
102
|
+
if (!this.peer)
|
|
103
|
+
throw new Error("No selected peer");
|
|
104
|
+
await abortable(this.transport.send(this.room, this.peer, encodeWire(message)), this.controller.signal);
|
|
105
|
+
}
|
|
106
|
+
async sendData(type, data) {
|
|
107
|
+
await this.send({ v: 1, type, sid: this.sid, data: base64url(data) });
|
|
108
|
+
}
|
|
109
|
+
async receiveData(type) {
|
|
110
|
+
const { message } = await this.next();
|
|
111
|
+
if (message.type !== type)
|
|
112
|
+
throw new Error("Unexpected handshake record");
|
|
113
|
+
return unbase64url(message.data);
|
|
114
|
+
}
|
|
115
|
+
close() { this.controller.abort(); this.off.forEach(off => off()); this.queue = []; this.wake = undefined; }
|
|
116
|
+
}
|
|
117
|
+
/** Bind protected control payloads to their outer type and exchange ID. */
|
|
118
|
+
export function sealControl(cipher, type, sid, body) {
|
|
119
|
+
return cipher.seal(canonicalBytes({ v: 1, type, sid, body }));
|
|
120
|
+
}
|
|
121
|
+
export function openControl(cipher, type, sid, data) {
|
|
122
|
+
const message = parseJson(cipher.open(data));
|
|
123
|
+
if (!isObject(message) || !exactKeys(message, ["v", "type", "sid", "body"]) || message.v !== 1 ||
|
|
124
|
+
message.type !== type || message.sid !== sid || !isObject(message.body))
|
|
125
|
+
throw new Error("Invalid protected control record");
|
|
126
|
+
return message.body;
|
|
127
|
+
}
|
|
128
|
+
export async function validateTicket(value, did, leaf, origin, instance) {
|
|
129
|
+
const key = ed25519PublicKeyFromDidKey(did);
|
|
130
|
+
if (!key || !isProviderTicket(value) || value.iss !== did || value.aud !== leaf || value.origin !== origin || value.instance !== instance)
|
|
131
|
+
throw new Error("Invalid provider ticket");
|
|
132
|
+
const now = Math.floor(Date.now() / 1000);
|
|
133
|
+
if (value.nbf > now || now >= value.exp)
|
|
134
|
+
throw new Error("Provider ticket expired");
|
|
135
|
+
const publicKey = await crypto.subtle.importKey("raw", key, "Ed25519", false, ["verify"]);
|
|
136
|
+
if (!await crypto.subtle.verify("Ed25519", publicKey, unbase64url(value.sig), ticketSigningBytes(value)))
|
|
137
|
+
throw new Error("Invalid provider ticket signature");
|
|
138
|
+
return value;
|
|
139
|
+
}
|