@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,79 @@
|
|
|
1
|
+
import { exactKeys, isHexId, isToken, isUint, unbase64url } from "./encoding.js";
|
|
2
|
+
import { canonicalBytes, isObject } from "./json.js";
|
|
3
|
+
import { isNamespace } from "./names.js";
|
|
4
|
+
import { WireError } from "./errors.js";
|
|
5
|
+
const common = ["id", "iss", "aud", "origin", "actions", "instance", "epoch", "nbf", "exp", "sig"];
|
|
6
|
+
export function isOrigin(value) {
|
|
7
|
+
if (typeof value !== "string")
|
|
8
|
+
return false;
|
|
9
|
+
try {
|
|
10
|
+
const u = new URL(value);
|
|
11
|
+
return /^(https?:)$/.test(u.protocol) && u.origin === value;
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function signature(v) {
|
|
18
|
+
try {
|
|
19
|
+
return typeof v === "string" && unbase64url(v).length === 64;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function base(v) {
|
|
26
|
+
return isHexId(v.id) && isToken(v.iss) && isToken(v.aud) && isOrigin(v.origin) &&
|
|
27
|
+
isToken(v.instance) && isUint(v.epoch) && isUint(v.nbf) && isUint(v.exp) &&
|
|
28
|
+
v.nbf < v.exp && signature(v.sig);
|
|
29
|
+
}
|
|
30
|
+
export function isProviderTicket(v) {
|
|
31
|
+
return isObject(v) && exactKeys(v, common) && base(v) &&
|
|
32
|
+
Array.isArray(v.actions) && v.actions.length === 1 && v.actions[0] === "register";
|
|
33
|
+
}
|
|
34
|
+
export function isNamespaceGrant(v) {
|
|
35
|
+
return isObject(v) && exactKeys(v, [...common, "namespace", "ticketId", "catalogDigest", "localAgentAllowed"]) &&
|
|
36
|
+
base(v) && isNamespace(v.namespace) && isHexId(v.ticketId) &&
|
|
37
|
+
typeof v.catalogDigest === "string" && /^[0-9a-f]{64}$/.test(v.catalogDigest) &&
|
|
38
|
+
typeof v.localAgentAllowed === "boolean" && Array.isArray(v.actions) &&
|
|
39
|
+
v.actions.length > 0 && v.actions.length <= 3 && new Set(v.actions).size === v.actions.length &&
|
|
40
|
+
v.actions.every(x => x === "read" || x === "write" || x === "destructive");
|
|
41
|
+
}
|
|
42
|
+
export function ticketSigningBytes(ticket) {
|
|
43
|
+
const { sig: _, ...body } = ticket;
|
|
44
|
+
return canonicalBytes(["mist-mcp/provider/v1", body]);
|
|
45
|
+
}
|
|
46
|
+
export function grantSigningBytes(grant) {
|
|
47
|
+
const { sig: _, ...body } = grant;
|
|
48
|
+
return canonicalBytes(["mist-mcp/namespace-grant/v1", body]);
|
|
49
|
+
}
|
|
50
|
+
function check(v, ctx, bytes) {
|
|
51
|
+
if (!isUint(ctx.now) || v.nbf > ctx.now || ctx.now >= v.exp)
|
|
52
|
+
throw new WireError("EXPIRED");
|
|
53
|
+
if (v.iss !== ctx.iss || v.aud !== ctx.aud || v.origin !== ctx.origin || v.instance !== ctx.instance ||
|
|
54
|
+
v.epoch !== ctx.epoch || ctx.isRevoked?.(v.id) || ctx.publicKey.length !== 32)
|
|
55
|
+
throw new WireError("AUTH_FAILED");
|
|
56
|
+
try {
|
|
57
|
+
if (ctx.verify(ctx.publicKey, bytes, unbase64url(v.sig)) !== true)
|
|
58
|
+
throw new Error();
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
throw new WireError("AUTH_FAILED");
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export function verifyTicket(v, ctx) {
|
|
65
|
+
if (!isProviderTicket(v))
|
|
66
|
+
throw new WireError("INVALID_MESSAGE");
|
|
67
|
+
check(v, ctx, ticketSigningBytes(v));
|
|
68
|
+
return v;
|
|
69
|
+
}
|
|
70
|
+
export function verifyGrant(v, ticket, ctx) {
|
|
71
|
+
const t = verifyTicket(ticket, ctx);
|
|
72
|
+
if (!isNamespaceGrant(v))
|
|
73
|
+
throw new WireError("INVALID_MESSAGE");
|
|
74
|
+
if (v.namespace !== ctx.namespace || v.catalogDigest !== ctx.catalogDigest || v.ticketId !== t.id ||
|
|
75
|
+
!v.localAgentAllowed)
|
|
76
|
+
throw new WireError("AUTH_FAILED");
|
|
77
|
+
check(v, ctx, grantSigningBytes(v));
|
|
78
|
+
return v;
|
|
79
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare function base64url(bytes: Uint8Array): string;
|
|
2
|
+
export declare function unbase64url(s: string): Uint8Array;
|
|
3
|
+
export declare const isHexId: (v: unknown) => v is string;
|
|
4
|
+
export declare function randomId(): string;
|
|
5
|
+
export declare const isToken: (v: unknown) => v is string;
|
|
6
|
+
export declare const isUint: (v: unknown) => v is number;
|
|
7
|
+
export declare function exactKeys(v: Record<string, unknown>, keys: readonly string[]): boolean;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export function base64url(bytes) {
|
|
2
|
+
let s = "";
|
|
3
|
+
for (let i = 0; i < bytes.length; i++)
|
|
4
|
+
s += String.fromCharCode(bytes[i]);
|
|
5
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
6
|
+
}
|
|
7
|
+
export function unbase64url(s) {
|
|
8
|
+
if (!/^[A-Za-z0-9_-]*$/.test(s) || s.length % 4 === 1)
|
|
9
|
+
throw new TypeError("Invalid base64url");
|
|
10
|
+
const bytes = Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), c => c.charCodeAt(0));
|
|
11
|
+
if (base64url(bytes) !== s)
|
|
12
|
+
throw new TypeError("Non-canonical base64url");
|
|
13
|
+
return bytes;
|
|
14
|
+
}
|
|
15
|
+
export const isHexId = (v) => typeof v === "string" && /^[0-9a-f]{32}$/.test(v);
|
|
16
|
+
export function randomId() {
|
|
17
|
+
return Array.from(crypto.getRandomValues(new Uint8Array(16)), x => x.toString(16).padStart(2, "0")).join("");
|
|
18
|
+
}
|
|
19
|
+
export const isToken = (v) => typeof v === "string" && v.length > 0 && v.length <= 512 && !/[\s\u0000-\u001f\u007f]/.test(v);
|
|
20
|
+
export const isUint = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
|
|
21
|
+
export function exactKeys(v, keys) {
|
|
22
|
+
return Object.keys(v).length === keys.length && keys.every(k => Object.hasOwn(v, k));
|
|
23
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export declare const WIRE_CODES: {
|
|
2
|
+
readonly INVALID_MESSAGE: "INVALID_MESSAGE";
|
|
3
|
+
readonly LIMIT: "LIMIT";
|
|
4
|
+
readonly AUTH_FAILED: "AUTH_FAILED";
|
|
5
|
+
readonly EXPIRED: "EXPIRED";
|
|
6
|
+
readonly REPLAY: "REPLAY";
|
|
7
|
+
readonly FRAME_CONFLICT: "FRAME_CONFLICT";
|
|
8
|
+
readonly SESSION_CLOSED: "SESSION_CLOSED";
|
|
9
|
+
};
|
|
10
|
+
export type WireErrorCode = typeof WIRE_CODES[keyof typeof WIRE_CODES];
|
|
11
|
+
export declare class WireError extends Error {
|
|
12
|
+
readonly code: WireErrorCode;
|
|
13
|
+
constructor(code: WireErrorCode, message?: string);
|
|
14
|
+
}
|
|
15
|
+
export declare const RPC_CODES: {
|
|
16
|
+
readonly PARSE_ERROR: -32700;
|
|
17
|
+
readonly INVALID_REQUEST: -32600;
|
|
18
|
+
readonly METHOD_NOT_FOUND: -32601;
|
|
19
|
+
readonly INVALID_PARAMS: -32602;
|
|
20
|
+
readonly INTERNAL_ERROR: -32603;
|
|
21
|
+
readonly DENIED: -32001;
|
|
22
|
+
readonly BUSY: -32002;
|
|
23
|
+
readonly TIMEOUT: -32003;
|
|
24
|
+
readonly CANCELLED: -32004;
|
|
25
|
+
readonly RESULT_UNKNOWN: -32005;
|
|
26
|
+
readonly SESSION_EXHAUSTED: -32006;
|
|
27
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export const WIRE_CODES = {
|
|
2
|
+
INVALID_MESSAGE: "INVALID_MESSAGE", LIMIT: "LIMIT", AUTH_FAILED: "AUTH_FAILED",
|
|
3
|
+
EXPIRED: "EXPIRED", REPLAY: "REPLAY", FRAME_CONFLICT: "FRAME_CONFLICT",
|
|
4
|
+
SESSION_CLOSED: "SESSION_CLOSED",
|
|
5
|
+
};
|
|
6
|
+
export class WireError extends Error {
|
|
7
|
+
code;
|
|
8
|
+
constructor(code, message = code) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.name = "WireError";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export const RPC_CODES = {
|
|
15
|
+
PARSE_ERROR: -32700, INVALID_REQUEST: -32600, METHOD_NOT_FOUND: -32601,
|
|
16
|
+
INVALID_PARAMS: -32602, INTERNAL_ERROR: -32603, DENIED: -32001,
|
|
17
|
+
BUSY: -32002, TIMEOUT: -32003, CANCELLED: -32004, RESULT_UNKNOWN: -32005,
|
|
18
|
+
SESSION_EXHAUSTED: -32006,
|
|
19
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Frame } from "./messages.js";
|
|
2
|
+
/** A session-bound authenticated cipher. Errors are fatal to that session. */
|
|
3
|
+
export interface FrameCipher {
|
|
4
|
+
seal(plain: Uint8Array): Uint8Array;
|
|
5
|
+
open(sealed: Uint8Array): Uint8Array;
|
|
6
|
+
}
|
|
7
|
+
export interface FrameLimits {
|
|
8
|
+
chunkSize: number;
|
|
9
|
+
messageSize: number;
|
|
10
|
+
maxChunks: number;
|
|
11
|
+
frameSize: number;
|
|
12
|
+
}
|
|
13
|
+
export declare const DEFAULT_FRAME_LIMITS: Readonly<FrameLimits>;
|
|
14
|
+
export declare function splitFrames(bytes: Uint8Array, sid: string, cipher: FrameCipher, options?: Partial<FrameLimits> & {
|
|
15
|
+
mid?: string;
|
|
16
|
+
}): Frame[];
|
|
17
|
+
/** Share this budget across all simultaneous authenticated peer sessions. */
|
|
18
|
+
export declare class ReassemblyBudget {
|
|
19
|
+
readonly maxBytes: number;
|
|
20
|
+
private allocated;
|
|
21
|
+
constructor(maxBytes?: number);
|
|
22
|
+
get usedBytes(): number;
|
|
23
|
+
reserve(n: number): boolean;
|
|
24
|
+
release(n: number): void;
|
|
25
|
+
}
|
|
26
|
+
export declare class FrameReassembler {
|
|
27
|
+
readonly sid: string;
|
|
28
|
+
private readonly cipher;
|
|
29
|
+
private readonly budget;
|
|
30
|
+
private readonly now;
|
|
31
|
+
private readonly pending;
|
|
32
|
+
private readonly seen;
|
|
33
|
+
private closed;
|
|
34
|
+
private readonly l;
|
|
35
|
+
constructor(sid: string, cipher: FrameCipher, budget?: ReassemblyBudget, config?: Partial<FrameLimits>, now?: () => number);
|
|
36
|
+
private discard;
|
|
37
|
+
expire(): number;
|
|
38
|
+
close(): void;
|
|
39
|
+
accept(frame: Frame): Uint8Array | undefined;
|
|
40
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { base64url, isHexId, randomId, unbase64url } from "./encoding.js";
|
|
2
|
+
import { WireError } from "./errors.js";
|
|
3
|
+
import { canonicalBytes } from "./json.js";
|
|
4
|
+
import { CHUNK_SIZE, MAX_CHUNKS, MAX_FRAME_SIZE, MAX_INCOMPLETE, MAX_MESSAGE_SIZE, MAX_REASSEMBLY_BYTES, MAX_SESSION_MESSAGES, REASSEMBLY_TIMEOUT_MS, encodeWire, validateFrameShape } from "./messages.js";
|
|
5
|
+
export const DEFAULT_FRAME_LIMITS = Object.freeze({
|
|
6
|
+
chunkSize: CHUNK_SIZE, messageSize: MAX_MESSAGE_SIZE, maxChunks: MAX_CHUNKS, frameSize: MAX_FRAME_SIZE,
|
|
7
|
+
});
|
|
8
|
+
function limits(input) {
|
|
9
|
+
const l = { ...DEFAULT_FRAME_LIMITS, ...input };
|
|
10
|
+
for (const k of ["chunkSize", "messageSize", "maxChunks", "frameSize"]) {
|
|
11
|
+
if (!Number.isSafeInteger(l[k]) || l[k] <= 0 || l[k] > DEFAULT_FRAME_LIMITS[k])
|
|
12
|
+
throw new WireError("LIMIT");
|
|
13
|
+
}
|
|
14
|
+
l.messageSize = Math.min(l.messageSize, l.chunkSize * l.maxChunks);
|
|
15
|
+
return l;
|
|
16
|
+
}
|
|
17
|
+
function header(f) {
|
|
18
|
+
const { data: _, ...rest } = f;
|
|
19
|
+
const bytes = canonicalBytes(rest);
|
|
20
|
+
const result = new Uint8Array(bytes.length + 1);
|
|
21
|
+
result.set(bytes);
|
|
22
|
+
result[bytes.length] = 10;
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
function concat(a, b) {
|
|
26
|
+
const result = new Uint8Array(a.length + b.length);
|
|
27
|
+
result.set(a);
|
|
28
|
+
result.set(b, a.length);
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
export function splitFrames(bytes, sid, cipher, options = {}) {
|
|
32
|
+
const { mid = randomId(), ...config } = options;
|
|
33
|
+
const l = limits(config);
|
|
34
|
+
if (!isHexId(sid) || !isHexId(mid))
|
|
35
|
+
throw new WireError("INVALID_MESSAGE");
|
|
36
|
+
if (bytes.length === 0 || bytes.length > l.messageSize)
|
|
37
|
+
throw new WireError("LIMIT");
|
|
38
|
+
const count = Math.ceil(bytes.length / l.chunkSize);
|
|
39
|
+
const frames = [];
|
|
40
|
+
for (let seq = 0; seq < count; seq++) {
|
|
41
|
+
const h = { v: 1, type: "mcp.frame", sid, mid, seq, count, size: bytes.length };
|
|
42
|
+
const plain = concat(header(h), bytes.subarray(seq * l.chunkSize, (seq + 1) * l.chunkSize));
|
|
43
|
+
const frame = { ...h, data: base64url(cipher.seal(plain)) };
|
|
44
|
+
if (encodeWire(frame).length > l.frameSize)
|
|
45
|
+
throw new WireError("LIMIT");
|
|
46
|
+
frames.push(frame);
|
|
47
|
+
}
|
|
48
|
+
return frames;
|
|
49
|
+
}
|
|
50
|
+
/** Share this budget across all simultaneous authenticated peer sessions. */
|
|
51
|
+
export class ReassemblyBudget {
|
|
52
|
+
maxBytes;
|
|
53
|
+
allocated = 0;
|
|
54
|
+
constructor(maxBytes = MAX_REASSEMBLY_BYTES) {
|
|
55
|
+
this.maxBytes = maxBytes;
|
|
56
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0 || maxBytes > MAX_REASSEMBLY_BYTES)
|
|
57
|
+
throw new WireError("LIMIT");
|
|
58
|
+
}
|
|
59
|
+
get usedBytes() { return this.allocated; }
|
|
60
|
+
reserve(n) {
|
|
61
|
+
if (!Number.isSafeInteger(n) || n <= 0 || this.allocated + n > this.maxBytes)
|
|
62
|
+
return false;
|
|
63
|
+
this.allocated += n;
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
release(n) {
|
|
67
|
+
if (!Number.isSafeInteger(n) || n < 0 || n > this.allocated)
|
|
68
|
+
throw new WireError("INVALID_MESSAGE");
|
|
69
|
+
this.allocated -= n;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
export class FrameReassembler {
|
|
73
|
+
sid;
|
|
74
|
+
cipher;
|
|
75
|
+
budget;
|
|
76
|
+
now;
|
|
77
|
+
pending = new Map();
|
|
78
|
+
seen = new Set();
|
|
79
|
+
closed = false;
|
|
80
|
+
l;
|
|
81
|
+
constructor(sid, cipher, budget = new ReassemblyBudget(), config = {}, now = () => performance.now()) {
|
|
82
|
+
this.sid = sid;
|
|
83
|
+
this.cipher = cipher;
|
|
84
|
+
this.budget = budget;
|
|
85
|
+
this.now = now;
|
|
86
|
+
if (!isHexId(sid))
|
|
87
|
+
throw new WireError("INVALID_MESSAGE");
|
|
88
|
+
this.l = limits(config);
|
|
89
|
+
}
|
|
90
|
+
discard(mid) {
|
|
91
|
+
const p = this.pending.get(mid);
|
|
92
|
+
if (p) {
|
|
93
|
+
this.budget.release(p.reserved);
|
|
94
|
+
this.pending.delete(mid);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
expire() {
|
|
98
|
+
const now = this.now();
|
|
99
|
+
let expired = 0;
|
|
100
|
+
for (const [mid, p] of this.pending)
|
|
101
|
+
if (now >= p.deadline) {
|
|
102
|
+
this.discard(mid);
|
|
103
|
+
expired++;
|
|
104
|
+
}
|
|
105
|
+
return expired;
|
|
106
|
+
}
|
|
107
|
+
close() {
|
|
108
|
+
this.closed = true;
|
|
109
|
+
for (const mid of this.pending.keys())
|
|
110
|
+
this.discard(mid);
|
|
111
|
+
this.seen.clear();
|
|
112
|
+
}
|
|
113
|
+
accept(frame) {
|
|
114
|
+
if (this.closed)
|
|
115
|
+
throw new WireError("SESSION_CLOSED");
|
|
116
|
+
this.expire();
|
|
117
|
+
if (!validateFrameShape(frame) || frame.sid !== this.sid || encodeWire(frame).length > this.l.frameSize ||
|
|
118
|
+
frame.size > this.l.messageSize || frame.count !== Math.ceil(frame.size / this.l.chunkSize) ||
|
|
119
|
+
frame.count > this.l.maxChunks)
|
|
120
|
+
throw new WireError("INVALID_MESSAGE");
|
|
121
|
+
let p = this.pending.get(frame.mid);
|
|
122
|
+
if (!p && this.seen.has(frame.mid))
|
|
123
|
+
return undefined;
|
|
124
|
+
const old = p?.parts.get(frame.seq);
|
|
125
|
+
if (old?.data === frame.data && p?.size === frame.size && p.count === frame.count)
|
|
126
|
+
return undefined;
|
|
127
|
+
try {
|
|
128
|
+
const h = header(frame);
|
|
129
|
+
const plain = this.cipher.open(unbase64url(frame.data));
|
|
130
|
+
const size = Math.min(this.l.chunkSize, frame.size - frame.seq * this.l.chunkSize);
|
|
131
|
+
if (plain.length !== h.length + size || !h.every((b, i) => b === plain[i]))
|
|
132
|
+
throw new WireError("AUTH_FAILED");
|
|
133
|
+
if (p && (p.count !== frame.count || p.size !== frame.size))
|
|
134
|
+
throw new WireError("FRAME_CONFLICT");
|
|
135
|
+
const chunk = plain.slice(h.length);
|
|
136
|
+
if (old) {
|
|
137
|
+
if (!old.bytes.every((b, i) => b === chunk[i]))
|
|
138
|
+
throw new WireError("FRAME_CONFLICT");
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
if (!p) {
|
|
142
|
+
if (this.seen.size >= MAX_SESSION_MESSAGES || this.pending.size >= MAX_INCOMPLETE)
|
|
143
|
+
throw new WireError("LIMIT");
|
|
144
|
+
// Reserve the worst-case retained base64 strings (UTF-16) plus plaintext.
|
|
145
|
+
const reserved = frame.size + frame.count * this.l.frameSize * 2;
|
|
146
|
+
if (!this.budget.reserve(reserved))
|
|
147
|
+
throw new WireError("LIMIT");
|
|
148
|
+
p = { count: frame.count, size: frame.size, deadline: this.now() + REASSEMBLY_TIMEOUT_MS, reserved, parts: new Map() };
|
|
149
|
+
this.pending.set(frame.mid, p);
|
|
150
|
+
this.seen.add(frame.mid);
|
|
151
|
+
}
|
|
152
|
+
p.parts.set(frame.seq, { bytes: chunk, data: frame.data });
|
|
153
|
+
if (p.parts.size !== p.count)
|
|
154
|
+
return undefined;
|
|
155
|
+
const result = new Uint8Array(p.size);
|
|
156
|
+
for (let i = 0; i < p.count; i++)
|
|
157
|
+
result.set(p.parts.get(i).bytes, i * this.l.chunkSize);
|
|
158
|
+
this.discard(frame.mid);
|
|
159
|
+
return result;
|
|
160
|
+
}
|
|
161
|
+
catch (e) {
|
|
162
|
+
this.close();
|
|
163
|
+
throw e instanceof WireError ? e : new WireError("AUTH_FAILED");
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export type Json = null | boolean | number | string | Json[] | {
|
|
2
|
+
[key: string]: Json;
|
|
3
|
+
};
|
|
4
|
+
export type JsonObject = {
|
|
5
|
+
[key: string]: Json;
|
|
6
|
+
};
|
|
7
|
+
export declare const MAX_DEPTH = 32;
|
|
8
|
+
export declare const utf8: (text: string) => Uint8Array;
|
|
9
|
+
export declare const decodeUtf8: (bytes: Uint8Array) => string;
|
|
10
|
+
export declare function isObject(value: unknown): value is Record<string, unknown>;
|
|
11
|
+
export declare function canonicalJson(value: unknown): string;
|
|
12
|
+
export declare const canonicalBytes: (value: unknown) => Uint8Array;
|
|
13
|
+
export declare function parseJson(bytes: Uint8Array): Json;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
export const MAX_DEPTH = 32;
|
|
2
|
+
export const utf8 = (text) => new TextEncoder().encode(text);
|
|
3
|
+
export const decodeUtf8 = (bytes) => new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
4
|
+
export function isObject(value) {
|
|
5
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) &&
|
|
6
|
+
(Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
7
|
+
}
|
|
8
|
+
function string(value) {
|
|
9
|
+
if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value))
|
|
10
|
+
throw new TypeError("Unpaired surrogate");
|
|
11
|
+
return JSON.stringify(value);
|
|
12
|
+
}
|
|
13
|
+
export function canonicalJson(value) {
|
|
14
|
+
function visit(v, depth) {
|
|
15
|
+
if (depth > MAX_DEPTH)
|
|
16
|
+
throw new TypeError("JSON nesting limit");
|
|
17
|
+
if (v === null || typeof v === "boolean")
|
|
18
|
+
return String(v);
|
|
19
|
+
if (typeof v === "string")
|
|
20
|
+
return string(v);
|
|
21
|
+
if (typeof v === "number" && Number.isFinite(v))
|
|
22
|
+
return JSON.stringify(v);
|
|
23
|
+
if (Array.isArray(v)) {
|
|
24
|
+
if (Object.keys(v).length !== v.length)
|
|
25
|
+
throw new TypeError("Invalid JSON array");
|
|
26
|
+
return "[" + Array.from(v, x => visit(x, depth + 1)).join(",") + "]";
|
|
27
|
+
}
|
|
28
|
+
if (isObject(v))
|
|
29
|
+
return "{" + Object.keys(v).sort().map(k => string(k) + ":" + visit(v[k], depth + 1)).join(",") + "}";
|
|
30
|
+
throw new TypeError("Not a JSON value");
|
|
31
|
+
}
|
|
32
|
+
return visit(value, 0);
|
|
33
|
+
}
|
|
34
|
+
export const canonicalBytes = (value) => utf8(canonicalJson(value));
|
|
35
|
+
export function parseJson(bytes) {
|
|
36
|
+
const text = decodeUtf8(bytes);
|
|
37
|
+
// JSON.parse validates syntax but silently overwrites duplicate members.
|
|
38
|
+
const value = JSON.parse(text);
|
|
39
|
+
const tokens = /"(?:[^"\\]|\\.)*"|[{}\[\]:,]|[^\s{}\[\]:,]+/gy;
|
|
40
|
+
let pos = 0;
|
|
41
|
+
const stack = [];
|
|
42
|
+
let previous = "";
|
|
43
|
+
while (pos < text.length) {
|
|
44
|
+
if (/\s/.test(text[pos])) {
|
|
45
|
+
pos++;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
tokens.lastIndex = pos;
|
|
49
|
+
const match = tokens.exec(text);
|
|
50
|
+
if (!match)
|
|
51
|
+
throw new TypeError("Invalid JSON token");
|
|
52
|
+
const token = match[0];
|
|
53
|
+
pos = tokens.lastIndex;
|
|
54
|
+
const object = stack[stack.length - 1];
|
|
55
|
+
if (object && (previous === "{" || previous === ",") && token.startsWith('"')) {
|
|
56
|
+
const key = JSON.parse(token);
|
|
57
|
+
if (object.has(key))
|
|
58
|
+
throw new TypeError("Duplicate JSON member");
|
|
59
|
+
object.add(key);
|
|
60
|
+
}
|
|
61
|
+
if (token === "{")
|
|
62
|
+
stack.push(new Set());
|
|
63
|
+
else if (token === "[")
|
|
64
|
+
stack.push(null);
|
|
65
|
+
else if (token === "}" || token === "]")
|
|
66
|
+
stack.pop();
|
|
67
|
+
if (stack.length > MAX_DEPTH + 1)
|
|
68
|
+
throw new TypeError("JSON nesting limit");
|
|
69
|
+
previous = token;
|
|
70
|
+
}
|
|
71
|
+
canonicalJson(value);
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
export declare const MCP_VERSION = "2025-11-25";
|
|
2
|
+
export declare const CHUNK_SIZE: number;
|
|
3
|
+
/** Max plaintext sealed per frame: one chunk plus its canonical frame header (spec/wire-v1.md). */
|
|
4
|
+
export declare const FRAME_HEADER_ALLOWANCE = 512;
|
|
5
|
+
export declare const MAX_SEALED_PLAINTEXT: number;
|
|
6
|
+
/** Maximum canonical frame header (without data), including the LF separator. */
|
|
7
|
+
export declare const MAX_FRAME_HEADER_SIZE = 143;
|
|
8
|
+
/** FrameCipher must support this many plaintext bytes, inclusive. */
|
|
9
|
+
export declare const MAX_FRAME_PLAIN_SIZE: number;
|
|
10
|
+
export declare const MAX_MESSAGE_SIZE: number;
|
|
11
|
+
export declare const MAX_FRAME_SIZE: number;
|
|
12
|
+
export declare const MAX_CONTROL_SIZE: number;
|
|
13
|
+
export declare const MAX_CHUNKS = 43;
|
|
14
|
+
export declare const MAX_INCOMPLETE = 4;
|
|
15
|
+
export declare const MAX_REASSEMBLY_BYTES: number;
|
|
16
|
+
export declare const REASSEMBLY_TIMEOUT_MS = 10000;
|
|
17
|
+
export declare const MAX_SESSION_MESSAGES = 4096;
|
|
18
|
+
export declare const MAX_PEER_CALLS = 4;
|
|
19
|
+
export declare const MAX_TOTAL_CALLS = 32;
|
|
20
|
+
export declare const MAX_TOOLS = 64;
|
|
21
|
+
export declare const MAX_TOOL_BYTES: number;
|
|
22
|
+
export declare const INIT_TIMEOUT_MS = 15000;
|
|
23
|
+
export declare const CALL_TIMEOUT_MS = 30000;
|
|
24
|
+
export declare const MAX_CALL_TIMEOUT_MS = 120000;
|
|
25
|
+
export interface Hello {
|
|
26
|
+
v: 1;
|
|
27
|
+
type: "mcp.hello";
|
|
28
|
+
gatewayDid: string;
|
|
29
|
+
instance: string;
|
|
30
|
+
bootNonce: string;
|
|
31
|
+
mcpVersions: string[];
|
|
32
|
+
limits: {
|
|
33
|
+
chunkSize: number;
|
|
34
|
+
messageSize: number;
|
|
35
|
+
frameSize: number;
|
|
36
|
+
maxChunks: number;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export declare const HANDSHAKE_TYPES: readonly ["mcp.pair.challenge", "mcp.pair.proof", "mcp.pair.grant", "mcp.auth.challenge", "mcp.auth.proof", "mcp.auth.grant", "mcp.auth.accept"];
|
|
40
|
+
export type HandshakeType = typeof HANDSHAKE_TYPES[number];
|
|
41
|
+
/** Opaque secure-channel payload. No credentials may appear in the outer envelope. */
|
|
42
|
+
export interface HandshakeMessage {
|
|
43
|
+
v: 1;
|
|
44
|
+
type: HandshakeType;
|
|
45
|
+
sid: string;
|
|
46
|
+
data: string;
|
|
47
|
+
}
|
|
48
|
+
export interface Frame {
|
|
49
|
+
v: 1;
|
|
50
|
+
type: "mcp.frame";
|
|
51
|
+
sid: string;
|
|
52
|
+
mid: string;
|
|
53
|
+
seq: number;
|
|
54
|
+
count: number;
|
|
55
|
+
size: number;
|
|
56
|
+
data: string;
|
|
57
|
+
}
|
|
58
|
+
export interface Close {
|
|
59
|
+
v: 1;
|
|
60
|
+
type: "mcp.close";
|
|
61
|
+
sid: string;
|
|
62
|
+
data: string;
|
|
63
|
+
}
|
|
64
|
+
export type WireMessage = Hello | HandshakeMessage | Frame | Close;
|
|
65
|
+
export declare function validateFrameShape(v: unknown): v is Frame;
|
|
66
|
+
export declare function isWireMessage(v: unknown): v is WireMessage;
|
|
67
|
+
export declare function encodeWire(message: WireMessage): Uint8Array;
|
|
68
|
+
export declare function decodeWire(bytes: Uint8Array): WireMessage;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { exactKeys, isHexId, isToken, isUint, unbase64url } from "./encoding.js";
|
|
2
|
+
import { canonicalBytes, isObject, parseJson } from "./json.js";
|
|
3
|
+
import { WireError } from "./errors.js";
|
|
4
|
+
export const MCP_VERSION = "2025-11-25";
|
|
5
|
+
export const CHUNK_SIZE = 12 * 1024;
|
|
6
|
+
/** Max plaintext sealed per frame: one chunk plus its canonical frame header (spec/wire-v1.md). */
|
|
7
|
+
export const FRAME_HEADER_ALLOWANCE = 512;
|
|
8
|
+
export const MAX_SEALED_PLAINTEXT = CHUNK_SIZE + FRAME_HEADER_ALLOWANCE;
|
|
9
|
+
/** Maximum canonical frame header (without data), including the LF separator. */
|
|
10
|
+
export const MAX_FRAME_HEADER_SIZE = 143;
|
|
11
|
+
/** FrameCipher must support this many plaintext bytes, inclusive. */
|
|
12
|
+
export const MAX_FRAME_PLAIN_SIZE = CHUNK_SIZE + MAX_FRAME_HEADER_SIZE;
|
|
13
|
+
export const MAX_MESSAGE_SIZE = 512 * 1024;
|
|
14
|
+
export const MAX_FRAME_SIZE = 18 * 1024;
|
|
15
|
+
export const MAX_CONTROL_SIZE = 8 * 1024;
|
|
16
|
+
export const MAX_CHUNKS = 43;
|
|
17
|
+
export const MAX_INCOMPLETE = 4;
|
|
18
|
+
export const MAX_REASSEMBLY_BYTES = 16 * 1024 * 1024;
|
|
19
|
+
export const REASSEMBLY_TIMEOUT_MS = 10_000;
|
|
20
|
+
export const MAX_SESSION_MESSAGES = 4096;
|
|
21
|
+
export const MAX_PEER_CALLS = 4;
|
|
22
|
+
export const MAX_TOTAL_CALLS = 32;
|
|
23
|
+
export const MAX_TOOLS = 64;
|
|
24
|
+
export const MAX_TOOL_BYTES = 16 * 1024;
|
|
25
|
+
export const INIT_TIMEOUT_MS = 15_000;
|
|
26
|
+
export const CALL_TIMEOUT_MS = 30_000;
|
|
27
|
+
export const MAX_CALL_TIMEOUT_MS = 120_000;
|
|
28
|
+
export const HANDSHAKE_TYPES = ["mcp.pair.challenge", "mcp.pair.proof", "mcp.pair.grant",
|
|
29
|
+
"mcp.auth.challenge", "mcp.auth.proof", "mcp.auth.grant", "mcp.auth.accept"];
|
|
30
|
+
const bounded = (v, max) => isUint(v) && v > 0 && v <= max;
|
|
31
|
+
const payload = (v) => {
|
|
32
|
+
try {
|
|
33
|
+
return typeof v === "string" && v.length > 0 && v.length <= MAX_FRAME_SIZE && unbase64url(v).length > 0;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
export function validateFrameShape(v) {
|
|
40
|
+
return isObject(v) && exactKeys(v, ["v", "type", "sid", "mid", "seq", "count", "size", "data"]) &&
|
|
41
|
+
v.v === 1 && v.type === "mcp.frame" && isHexId(v.sid) && isHexId(v.mid) &&
|
|
42
|
+
isUint(v.seq) && isUint(v.count) && v.count >= 1 && v.count <= MAX_CHUNKS && v.seq < v.count &&
|
|
43
|
+
bounded(v.size, MAX_MESSAGE_SIZE) && payload(v.data);
|
|
44
|
+
}
|
|
45
|
+
export function isWireMessage(v) {
|
|
46
|
+
if (!isObject(v) || v.v !== 1)
|
|
47
|
+
return false;
|
|
48
|
+
if (v.type === "mcp.frame")
|
|
49
|
+
return validateFrameShape(v);
|
|
50
|
+
if (v.type === "mcp.hello") {
|
|
51
|
+
const l = v.limits;
|
|
52
|
+
return exactKeys(v, ["v", "type", "gatewayDid", "instance", "bootNonce", "mcpVersions", "limits"]) &&
|
|
53
|
+
isToken(v.gatewayDid) && isToken(v.instance) && isHexId(v.bootNonce) &&
|
|
54
|
+
Array.isArray(v.mcpVersions) && v.mcpVersions.length > 0 && v.mcpVersions.length <= 8 &&
|
|
55
|
+
v.mcpVersions.every(x => typeof x === "string" && /^\d{4}-\d{2}-\d{2}$/.test(x)) &&
|
|
56
|
+
new Set(v.mcpVersions).size === v.mcpVersions.length &&
|
|
57
|
+
isObject(l) && exactKeys(l, ["chunkSize", "messageSize", "frameSize", "maxChunks"]) &&
|
|
58
|
+
bounded(l.chunkSize, CHUNK_SIZE) && bounded(l.messageSize, MAX_MESSAGE_SIZE) &&
|
|
59
|
+
bounded(l.frameSize, MAX_FRAME_SIZE) && bounded(l.maxChunks, MAX_CHUNKS) &&
|
|
60
|
+
l.messageSize <= l.chunkSize * l.maxChunks;
|
|
61
|
+
}
|
|
62
|
+
return (v.type === "mcp.close" || HANDSHAKE_TYPES.some(t => t === v.type)) &&
|
|
63
|
+
exactKeys(v, ["v", "type", "sid", "data"]) && isHexId(v.sid) && payload(v.data);
|
|
64
|
+
}
|
|
65
|
+
export function encodeWire(message) {
|
|
66
|
+
if (!isWireMessage(message))
|
|
67
|
+
throw new WireError("INVALID_MESSAGE");
|
|
68
|
+
const bytes = canonicalBytes(message);
|
|
69
|
+
if (bytes.length > (message.type === "mcp.frame" ? MAX_FRAME_SIZE : MAX_CONTROL_SIZE))
|
|
70
|
+
throw new WireError("LIMIT");
|
|
71
|
+
return bytes;
|
|
72
|
+
}
|
|
73
|
+
export function decodeWire(bytes) {
|
|
74
|
+
if (bytes.length > MAX_FRAME_SIZE)
|
|
75
|
+
throw new WireError("LIMIT");
|
|
76
|
+
try {
|
|
77
|
+
const v = parseJson(bytes);
|
|
78
|
+
if (!isWireMessage(v))
|
|
79
|
+
throw new WireError("INVALID_MESSAGE");
|
|
80
|
+
if (v.type !== "mcp.frame" && bytes.length > MAX_CONTROL_SIZE)
|
|
81
|
+
throw new WireError("LIMIT");
|
|
82
|
+
return v;
|
|
83
|
+
}
|
|
84
|
+
catch (e) {
|
|
85
|
+
if (e instanceof WireError)
|
|
86
|
+
throw e;
|
|
87
|
+
throw new WireError("INVALID_MESSAGE");
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare const isNamespace: (v: unknown) => v is string;
|
|
2
|
+
export declare const isLocalName: (v: unknown) => v is string;
|
|
3
|
+
export declare function publicToolName(namespace: string, localName: string): string;
|
|
4
|
+
export declare function isPublicToolName(v: unknown): v is string;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
const part = /^[A-Za-z0-9_.-]+$/;
|
|
2
|
+
export const isNamespace = (v) => typeof v === "string" && /^[a-z0-9-]{1,48}$/.test(v);
|
|
3
|
+
export const isLocalName = (v) => typeof v === "string" && v.length <= 45 && part.test(v) && !v.includes("__");
|
|
4
|
+
export function publicToolName(namespace, localName) {
|
|
5
|
+
if (!isNamespace(namespace) || !isLocalName(localName))
|
|
6
|
+
throw new TypeError("Invalid tool name");
|
|
7
|
+
return namespace + "__" + localName;
|
|
8
|
+
}
|
|
9
|
+
export function isPublicToolName(v) {
|
|
10
|
+
if (typeof v !== "string" || v.length > 128)
|
|
11
|
+
return false;
|
|
12
|
+
const i = v.indexOf("__");
|
|
13
|
+
return i > 0 && isNamespace(v.slice(0, i)) && isLocalName(v.slice(i + 2));
|
|
14
|
+
}
|