@tinycloud/mcp 0.2.2-beta.0 → 0.3.0-beta.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/dist/http.js ADDED
@@ -0,0 +1,1081 @@
1
+ // src/http.ts
2
+ import {
3
+ McpServer as McpServer2,
4
+ createMcpHandler,
5
+ fromJsonSchema as fromJsonSchema2,
6
+ getOAuthProtectedResourceMetadataUrl,
7
+ hostHeaderValidationResponse,
8
+ oauthMetadataResponse,
9
+ requireBearerAuth
10
+ } from "@modelcontextprotocol/server";
11
+
12
+ // src/oauth.ts
13
+ import {
14
+ OAuthError,
15
+ OAuthErrorCode
16
+ } from "@modelcontextprotocol/server";
17
+ import { createRemoteJWKSet, errors, jwtVerify } from "jose";
18
+ var OWNER_DIDS_CLAIM = "https://tinycloud.xyz/owner_dids";
19
+ function createOpenKeyTokenVerifier(config) {
20
+ const jwks = createRemoteJWKSet(new URL(config.jwksUri));
21
+ return {
22
+ async verifyAccessToken(token) {
23
+ try {
24
+ const { payload } = await jwtVerify(token, jwks, {
25
+ issuer: config.issuer,
26
+ audience: config.audience
27
+ });
28
+ return authInfo(token, payload, config);
29
+ } catch (error) {
30
+ if (error instanceof errors.JOSEError) {
31
+ throw new OAuthError(OAuthErrorCode.InvalidToken, "The OpenKey access token is invalid.");
32
+ }
33
+ throw error;
34
+ }
35
+ }
36
+ };
37
+ }
38
+ function authInfo(token, payload, config) {
39
+ if (typeof payload.sub !== "string" || payload.sub.length === 0) {
40
+ throw new OAuthError(OAuthErrorCode.InvalidToken, "The OpenKey access token does not identify a subject.");
41
+ }
42
+ if (typeof payload.exp !== "number") {
43
+ throw new OAuthError(OAuthErrorCode.InvalidToken, "The OpenKey access token has no expiry.");
44
+ }
45
+ const scopes = typeof payload.scope === "string" ? payload.scope.split(/\s+/).filter(Boolean) : [];
46
+ if (config.requiredScope !== void 0 && !scopes.includes(config.requiredScope)) {
47
+ throw new OAuthError(
48
+ OAuthErrorCode.InsufficientScope,
49
+ "The OpenKey access token is missing the TinyCloud MCP scope."
50
+ );
51
+ }
52
+ const clientId = firstString(payload.azp, payload.client_id) ?? "unknown";
53
+ const ownerDids = Array.isArray(payload[OWNER_DIDS_CLAIM]) ? payload[OWNER_DIDS_CLAIM].filter((value) => typeof value === "string") : [];
54
+ if (ownerDids.length === 0) {
55
+ throw new OAuthError(
56
+ OAuthErrorCode.InvalidToken,
57
+ "The OpenKey access token has no TinyCloud owner identity."
58
+ );
59
+ }
60
+ return {
61
+ token,
62
+ clientId,
63
+ scopes,
64
+ expiresAt: payload.exp,
65
+ resource: new URL(config.audience),
66
+ extra: {
67
+ subject: payload.sub,
68
+ ownerDids
69
+ }
70
+ };
71
+ }
72
+ function firstString(...values) {
73
+ return values.find((value) => typeof value === "string" && value.length > 0);
74
+ }
75
+
76
+ // src/remote-store.ts
77
+ import { createHmac, randomBytes, timingSafeEqual } from "crypto";
78
+ import { chmod, mkdir, readFile, readdir, rename, rm, writeFile } from "fs/promises";
79
+ import { dirname, join } from "path";
80
+ import {
81
+ TinyCloudNode,
82
+ principalDidEquals
83
+ } from "@tinycloud/node-sdk";
84
+ import { TCWSessionManager, importKey, initPanicHook } from "@tinycloud/node-sdk-wasm";
85
+ import { invokeOperation } from "@tinycloud/operations";
86
+ var PROFILE = "agent";
87
+ var MAX_CALLBACK_BYTES = 256 * 1024;
88
+ var BOOTSTRAP_PERMISSIONS = [
89
+ {
90
+ service: "tinycloud.kv",
91
+ space: "account",
92
+ path: "spaces/",
93
+ actions: ["tinycloud.kv/get", "tinycloud.kv/list"]
94
+ },
95
+ {
96
+ service: "tinycloud.kv",
97
+ space: "account",
98
+ path: "applications/",
99
+ actions: ["tinycloud.kv/get", "tinycloud.kv/list"]
100
+ }
101
+ ];
102
+ var RemoteTenantStore = class {
103
+ #config;
104
+ #initializing = /* @__PURE__ */ new Map();
105
+ constructor(config) {
106
+ this.#config = config;
107
+ }
108
+ tenantStateRoot(subject) {
109
+ return join(this.#config.stateDir, "tenants", this.#tenantId(subject));
110
+ }
111
+ async connectStatus(subject, ownerDids = []) {
112
+ const tenant = await this.#ensureTenant(subject);
113
+ if (await this.#hasValidSession(tenant, ownerDids)) {
114
+ return { connected: true, sessionDid: tenant.sessionDid };
115
+ }
116
+ const pending = await this.#createPending(subject, ownerDids, "bootstrap", BOOTSTRAP_PERMISSIONS);
117
+ return {
118
+ connected: false,
119
+ sessionDid: tenant.sessionDid,
120
+ approvalUrl: this.#connectUrl(pending),
121
+ expiresAt: pending.expiresAt
122
+ };
123
+ }
124
+ async decorateAuthorityResult(subject, ownerDids, result) {
125
+ if (!isRecord(result) || result.status !== "authority_required") return result;
126
+ const request = isRecord(result.request) ? result.request : void 0;
127
+ const requestId = typeof request?.requestId === "string" ? request.requestId : void 0;
128
+ const requested = Array.isArray(request?.requested) ? request.requested.filter(isPermissionEntry) : [];
129
+ if (requestId === void 0 || requested.length === 0) return result;
130
+ const pending = await this.#createPending(subject, ownerDids, "delegation", requested, requestId);
131
+ return {
132
+ ...result,
133
+ approval: {
134
+ ...isRecord(result.approval) ? result.approval : {},
135
+ kind: "openkey",
136
+ requestId,
137
+ url: this.#connectUrl(pending),
138
+ fallback: "Open the approval URL, then retry the same MCP tool."
139
+ }
140
+ };
141
+ }
142
+ async approvalRedirect(state) {
143
+ const pending = await this.#readPending(state, false);
144
+ const tenant = await this.#readTenant(pending.tenantId);
145
+ const callback = new URL("/connect/callback", this.#config.publicUrl);
146
+ callback.searchParams.set("state", state);
147
+ const params = new URLSearchParams({
148
+ did: tenant.sessionDid,
149
+ callback: callback.toString(),
150
+ host: this.#config.nodeHost,
151
+ jwk: Buffer.from(JSON.stringify(publicJwk(tenant.jwk))).toString("base64url"),
152
+ permissions: Buffer.from(JSON.stringify({
153
+ permissions: pending.permissions,
154
+ reason: pending.kind === "bootstrap" ? "Connect this TinyCloud account to the hosted MCP delegate." : "Approve the exact capabilities requested by the TinyCloud MCP operation."
155
+ })).toString("base64url"),
156
+ expiry: this.#config.delegationExpiry
157
+ });
158
+ return `${this.#config.openkeyHost.replace(/\/+$/, "")}/delegate?${params.toString()}`;
159
+ }
160
+ async completeApproval(state, request) {
161
+ const length = Number(request.headers.get("content-length") ?? "0");
162
+ if (Number.isFinite(length) && length > MAX_CALLBACK_BYTES) throw new Error("Callback body is too large.");
163
+ const text = await request.text();
164
+ if (Buffer.byteLength(text) > MAX_CALLBACK_BYTES) throw new Error("Callback body is too large.");
165
+ const data = JSON.parse(text);
166
+ if (!isRecord(data)) throw new Error("Callback body is invalid.");
167
+ const pending = await this.#readPending(state, true);
168
+ try {
169
+ const tenant = await this.#readTenant(pending.tenantId);
170
+ if (pending.kind === "bootstrap") {
171
+ await this.#storeBootstrap(tenant, pending, data);
172
+ } else {
173
+ await this.#storeDelegation(tenant, pending, data);
174
+ }
175
+ await rm(this.#pendingPath(tenant.stateRoot, pending.nonce) + ".processing", { force: true });
176
+ } catch (error) {
177
+ await this.#restorePending(pending).catch(() => void 0);
178
+ throw error;
179
+ }
180
+ }
181
+ async #storeBootstrap(tenant, pending, data) {
182
+ const session = sessionFromCallback(data, tenant.jwk);
183
+ const node = new TinyCloudNode({ host: this.#config.nodeHost });
184
+ await node.restoreSession(session);
185
+ if (!samePrincipal(node.sessionDid, tenant.sessionDid)) {
186
+ throw new Error("The approved delegation targets a different session.");
187
+ }
188
+ if (pending.ownerDids.length > 0 && !pending.ownerDids.some((did) => samePrincipal(node.did, did))) {
189
+ throw new Error("The approved delegation belongs to a different OpenKey user.");
190
+ }
191
+ const granted = [...node.getVerifiedSessionCapabilities()];
192
+ if (!permissionsCover(pending.permissions, granted)) {
193
+ throw new Error("The approved delegation does not cover the requested account access.");
194
+ }
195
+ const profile = await readJson(this.#profilePath(tenant.stateRoot));
196
+ await secureWrite(this.#profilePath(tenant.stateRoot), {
197
+ ...profile,
198
+ ownerDid: normalizeDid(node.did),
199
+ spaceId: session.spaceId
200
+ });
201
+ await secureWrite(this.#sessionPath(tenant.stateRoot), {
202
+ authMethod: "openkey",
203
+ ...session
204
+ });
205
+ }
206
+ async #storeDelegation(tenant, pending, data) {
207
+ if (pending.requestId === void 0) throw new Error("Authority request is missing.");
208
+ const delegation = portableFromCallback(data, pending.permissions, this.#config.nodeHost);
209
+ const result = await invokeOperation(
210
+ "tinycloud.auth.import",
211
+ 1,
212
+ { profile: PROFILE, stateRoot: tenant.stateRoot },
213
+ {
214
+ requestId: pending.requestId,
215
+ delegationCid: delegation.cid,
216
+ delegation
217
+ }
218
+ );
219
+ if (result.status !== "ok") throw new Error("TinyCloud rejected the approved delegation.");
220
+ }
221
+ async #ensureTenant(subject) {
222
+ const tenantId = this.#tenantId(subject);
223
+ const current = this.#initializing.get(tenantId);
224
+ if (current !== void 0) return current;
225
+ const initializing = this.#initializeTenant(tenantId).finally(() => {
226
+ this.#initializing.delete(tenantId);
227
+ });
228
+ this.#initializing.set(tenantId, initializing);
229
+ return initializing;
230
+ }
231
+ async #hasValidSession(tenant, ownerDids) {
232
+ const raw = await readJson(this.#sessionPath(tenant.stateRoot));
233
+ if (raw === null) return false;
234
+ try {
235
+ const node = new TinyCloudNode({ host: this.#config.nodeHost });
236
+ await node.restoreSession(raw);
237
+ return samePrincipal(node.sessionDid, tenant.sessionDid) && ownerDids.some((did) => samePrincipal(node.did, did));
238
+ } catch {
239
+ await rm(this.#sessionPath(tenant.stateRoot), { force: true });
240
+ return false;
241
+ }
242
+ }
243
+ async #initializeTenant(tenantId) {
244
+ const stateRoot = join(this.#config.stateDir, "tenants", tenantId);
245
+ const keyPath = this.#keyPath(stateRoot);
246
+ await secureDirectory(join(stateRoot, ".tinycloud", "profiles", PROFILE));
247
+ let jwk = await readJson(keyPath);
248
+ let sessionDid;
249
+ if (jwk === null) {
250
+ const generated = generateSessionKey();
251
+ jwk = generated.jwk;
252
+ sessionDid = generated.did;
253
+ await secureWrite(keyPath, jwk);
254
+ } else {
255
+ sessionDid = didFromJwk(jwk);
256
+ }
257
+ const profilePath = this.#profilePath(stateRoot);
258
+ if (!await fileExists(profilePath)) {
259
+ await secureWrite(profilePath, {
260
+ name: PROFILE,
261
+ host: this.#config.nodeHost,
262
+ chainId: 1,
263
+ spaceName: "default",
264
+ did: sessionDid,
265
+ sessionDid,
266
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
267
+ posture: "delegate-session",
268
+ operatorType: "agent",
269
+ authMethod: "openkey",
270
+ openkeyHost: this.#config.openkeyHost
271
+ });
272
+ }
273
+ return { stateRoot, sessionDid, jwk };
274
+ }
275
+ async #readTenant(tenantId) {
276
+ if (!/^[a-f0-9]{64}$/.test(tenantId)) throw new Error("Approval state is invalid.");
277
+ const stateRoot = join(this.#config.stateDir, "tenants", tenantId);
278
+ const jwk = await readJson(this.#keyPath(stateRoot));
279
+ if (jwk === null) throw new Error("The TinyCloud delegate no longer exists.");
280
+ return { stateRoot, jwk, sessionDid: didFromJwk(jwk) };
281
+ }
282
+ async #createPending(subject, ownerDids, kind, permissions, requestId) {
283
+ const tenant = await this.#ensureTenant(subject);
284
+ const tenantId = this.#tenantId(subject);
285
+ const reusable = await reusablePending(
286
+ this.#pendingDirectory(tenant.stateRoot),
287
+ { tenantId, kind, requestId, permissions, ownerDids: ownerDids.map(normalizeDid) }
288
+ );
289
+ if (reusable !== void 0) return reusable;
290
+ const nonce = randomBytes(24).toString("base64url");
291
+ const created = Date.now();
292
+ const pending = {
293
+ version: 1,
294
+ nonce,
295
+ tenantId,
296
+ kind,
297
+ ...requestId === void 0 ? {} : { requestId },
298
+ permissions,
299
+ ownerDids: ownerDids.map(normalizeDid),
300
+ createdAt: new Date(created).toISOString(),
301
+ expiresAt: new Date(created + this.#config.approvalTtlSeconds * 1e3).toISOString()
302
+ };
303
+ await secureWrite(this.#pendingPath(tenant.stateRoot, nonce), pending);
304
+ return pending;
305
+ }
306
+ async #readPending(state, consume) {
307
+ const [tenantId, nonce, signature] = state.split(".");
308
+ if (tenantId === void 0 || nonce === void 0 || signature === void 0) {
309
+ throw new Error("Approval state is invalid.");
310
+ }
311
+ const expected = this.#signState(tenantId, nonce);
312
+ const supplied = Buffer.from(signature, "base64url");
313
+ const expectedBytes = Buffer.from(expected, "base64url");
314
+ if (supplied.length !== expectedBytes.length || !timingSafeEqual(supplied, expectedBytes)) {
315
+ throw new Error("Approval state is invalid.");
316
+ }
317
+ const stateRoot = join(this.#config.stateDir, "tenants", tenantId);
318
+ const path = this.#pendingPath(stateRoot, nonce);
319
+ const claimed = `${path}.processing`;
320
+ if (consume) await rename(path, claimed);
321
+ try {
322
+ const pending = await readJson(consume ? claimed : path);
323
+ if (pending === null || pending.version !== 1 || pending.tenantId !== tenantId || pending.nonce !== nonce) {
324
+ throw new Error("Approval state is invalid or already used.");
325
+ }
326
+ if (new Date(pending.expiresAt).getTime() <= Date.now()) {
327
+ await rm(consume ? claimed : path, { force: true });
328
+ throw new Error("Approval state has expired.");
329
+ }
330
+ return pending;
331
+ } catch (error) {
332
+ if (consume) await rename(claimed, path).catch(() => void 0);
333
+ throw error;
334
+ }
335
+ }
336
+ async #restorePending(pending) {
337
+ const stateRoot = join(this.#config.stateDir, "tenants", pending.tenantId);
338
+ const path = this.#pendingPath(stateRoot, pending.nonce);
339
+ await rename(`${path}.processing`, path);
340
+ }
341
+ #connectUrl(pending) {
342
+ const url = new URL("/connect", this.#config.publicUrl);
343
+ url.searchParams.set("state", `${pending.tenantId}.${pending.nonce}.${this.#signState(pending.tenantId, pending.nonce)}`);
344
+ return url.toString();
345
+ }
346
+ #tenantId(subject) {
347
+ return createHmac("sha256", this.#config.stateSecret).update(`tenant:${subject}`).digest("hex");
348
+ }
349
+ #signState(tenantId, nonce) {
350
+ return createHmac("sha256", this.#config.stateSecret).update(`approval:${tenantId}:${nonce}`).digest("base64url");
351
+ }
352
+ #profilePath(stateRoot) {
353
+ return join(stateRoot, ".tinycloud", "profiles", PROFILE, "profile.json");
354
+ }
355
+ #keyPath(stateRoot) {
356
+ return join(stateRoot, ".tinycloud", "profiles", PROFILE, "key.json");
357
+ }
358
+ #sessionPath(stateRoot) {
359
+ return join(stateRoot, ".tinycloud", "profiles", PROFILE, "session.json");
360
+ }
361
+ #pendingPath(stateRoot, nonce) {
362
+ return join(this.#pendingDirectory(stateRoot), `${nonce}.json`);
363
+ }
364
+ #pendingDirectory(stateRoot) {
365
+ return join(stateRoot, ".tinycloud", "profiles", PROFILE, "pending");
366
+ }
367
+ };
368
+ var wasmInitialized = false;
369
+ function generateSessionKey() {
370
+ ensureWasm();
371
+ const manager = new TCWSessionManager();
372
+ const keyId = manager.createSessionKey("hosted-mcp");
373
+ const serialized = manager.jwk(keyId);
374
+ if (!serialized) throw new Error("Could not generate the hosted delegate key.");
375
+ return { jwk: JSON.parse(serialized), did: manager.getDID(keyId) };
376
+ }
377
+ function didFromJwk(jwk) {
378
+ ensureWasm();
379
+ const manager = new TCWSessionManager();
380
+ const keyId = importKey(manager, JSON.stringify(jwk), "hosted-mcp");
381
+ return manager.getDID(keyId);
382
+ }
383
+ function ensureWasm() {
384
+ if (wasmInitialized) return;
385
+ initPanicHook();
386
+ wasmInitialized = true;
387
+ }
388
+ function sessionFromCallback(data, privateJwk) {
389
+ const delegationHeader = data.delegationHeader;
390
+ if (!isRecord(delegationHeader) || typeof delegationHeader.Authorization !== "string" || typeof data.delegationCid !== "string" || typeof data.spaceId !== "string" || typeof data.verificationMethod !== "string") {
391
+ throw new Error("OpenKey returned an incomplete delegation.");
392
+ }
393
+ return {
394
+ delegationHeader: { Authorization: delegationHeader.Authorization },
395
+ delegationCid: data.delegationCid,
396
+ spaceId: data.spaceId,
397
+ jwk: privateJwk,
398
+ verificationMethod: data.verificationMethod,
399
+ ...typeof data.address === "string" ? { address: data.address } : {},
400
+ ...typeof data.chainId === "number" ? { chainId: data.chainId } : {},
401
+ ...typeof data.siwe === "string" ? { siwe: data.siwe } : {},
402
+ ...typeof data.signature === "string" ? { signature: data.signature } : {}
403
+ };
404
+ }
405
+ function portableFromCallback(data, permissions, host) {
406
+ const primary = permissions.find((permission) => permission.service !== "tinycloud.encryption") ?? permissions[0];
407
+ if (primary === void 0) throw new Error("The authority request has no permissions.");
408
+ const session = sessionFromCallback(data, {});
409
+ const expiry = delegationExpiry(data);
410
+ return {
411
+ cid: session.delegationCid,
412
+ delegationHeader: session.delegationHeader,
413
+ spaceId: session.spaceId,
414
+ path: primary.path,
415
+ actions: [...primary.actions],
416
+ resources: permissions.map((permission) => ({
417
+ service: permission.service.startsWith("tinycloud.") ? permission.service.slice("tinycloud.".length) : permission.service,
418
+ space: permission.service === "tinycloud.encryption" ? requiredPermissionSpace(permission) : session.spaceId,
419
+ path: permission.path,
420
+ actions: [...permission.actions]
421
+ })),
422
+ expiry,
423
+ delegateDID: session.verificationMethod,
424
+ ownerAddress: typeof data.address === "string" ? data.address : "",
425
+ chainId: typeof data.chainId === "number" ? data.chainId : 1,
426
+ host
427
+ };
428
+ }
429
+ function delegationExpiry(data) {
430
+ for (const key of ["expiry", "expiresAt", "expirationTime"]) {
431
+ const parsed = parseDate(data[key]);
432
+ if (parsed !== void 0) return parsed;
433
+ }
434
+ if (typeof data.siwe === "string") {
435
+ const match = data.siwe.match(/^Expiration Time:\s*(.+)$/im);
436
+ const parsed = parseDate(match?.[1]?.trim());
437
+ if (parsed !== void 0) return parsed;
438
+ }
439
+ throw new Error("OpenKey did not return a delegation expiry.");
440
+ }
441
+ function permissionsCover(requested, granted) {
442
+ return requested.every((request) => granted.some(
443
+ (grant) => normalizeService(grant.service) === normalizeService(request.service) && typeof grant.space === "string" && typeof request.space === "string" && sameSpace(grant.space, request.space) && grant.path === request.path && request.actions.every((action) => grant.actions.includes(action))
444
+ ));
445
+ }
446
+ function sameSpace(granted, requested) {
447
+ return granted === requested || granted.endsWith(`:${requested}`);
448
+ }
449
+ function normalizeService(service) {
450
+ return service.startsWith("tinycloud.") ? service : `tinycloud.${service}`;
451
+ }
452
+ function requiredPermissionSpace(permission) {
453
+ if (typeof permission.space !== "string") throw new Error("The authority request has no space.");
454
+ return permission.space;
455
+ }
456
+ function publicJwk(jwk) {
457
+ const copy = { ...jwk };
458
+ for (const field of ["d", "p", "q", "dp", "dq", "qi", "oth", "k"]) delete copy[field];
459
+ return copy;
460
+ }
461
+ function samePrincipal(left, right) {
462
+ if (typeof left !== "string") return false;
463
+ try {
464
+ return principalDidEquals(left, right);
465
+ } catch {
466
+ return false;
467
+ }
468
+ }
469
+ function normalizeDid(value) {
470
+ return value.split("#", 1)[0];
471
+ }
472
+ function isPermissionEntry(value) {
473
+ return isRecord(value) && typeof value.service === "string" && typeof value.space === "string" && typeof value.path === "string" && Array.isArray(value.actions) && value.actions.every((action) => typeof action === "string");
474
+ }
475
+ function isRecord(value) {
476
+ return typeof value === "object" && value !== null && !Array.isArray(value);
477
+ }
478
+ function parseDate(value) {
479
+ if (typeof value !== "string" && typeof value !== "number") return void 0;
480
+ const date = new Date(typeof value === "number" && value < 1e10 ? value * 1e3 : value);
481
+ return Number.isNaN(date.getTime()) ? void 0 : date;
482
+ }
483
+ async function secureDirectory(path) {
484
+ await mkdir(path, { recursive: true, mode: 448 });
485
+ await chmod(path, 448);
486
+ }
487
+ async function secureWrite(path, value) {
488
+ const directory = dirname(path);
489
+ await secureDirectory(directory);
490
+ const temporary = `${path}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
491
+ await writeFile(temporary, `${JSON.stringify(value, jsonReplacer, 2)}
492
+ `, { mode: 384 });
493
+ await rename(temporary, path);
494
+ await chmod(path, 384);
495
+ }
496
+ function jsonReplacer(_key, value) {
497
+ return value instanceof Date ? value.toISOString() : value;
498
+ }
499
+ async function readJson(path) {
500
+ try {
501
+ return JSON.parse(await readFile(path, "utf8"));
502
+ } catch (error) {
503
+ if (isRecord(error) && error.code === "ENOENT") return null;
504
+ throw error;
505
+ }
506
+ }
507
+ async function fileExists(path) {
508
+ return await readJson(path) !== null;
509
+ }
510
+ async function reusablePending(directory, expected) {
511
+ let names;
512
+ try {
513
+ names = await readdir(directory);
514
+ } catch (error) {
515
+ if (isRecord(error) && error.code === "ENOENT") return void 0;
516
+ throw error;
517
+ }
518
+ const active = [];
519
+ for (const name of names) {
520
+ if (!name.endsWith(".json")) continue;
521
+ const path = join(directory, name);
522
+ const pending = await readJson(path).catch(() => null);
523
+ if (pending === null || new Date(pending.expiresAt).getTime() <= Date.now()) {
524
+ await rm(path, { force: true });
525
+ continue;
526
+ }
527
+ active.push(pending);
528
+ if (samePendingRequest(pending, expected)) return pending;
529
+ }
530
+ if (active.length >= 64) {
531
+ active.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt));
532
+ await rm(join(directory, `${active[0].nonce}.json`), { force: true });
533
+ }
534
+ return void 0;
535
+ }
536
+ function samePendingRequest(pending, expected) {
537
+ return pending.version === 1 && pending.tenantId === expected.tenantId && pending.kind === expected.kind && pending.requestId === expected.requestId && JSON.stringify(pending.permissions) === JSON.stringify(expected.permissions) && JSON.stringify(pending.ownerDids) === JSON.stringify(expected.ownerDids);
538
+ }
539
+
540
+ // src/server.ts
541
+ import { McpServer } from "@modelcontextprotocol/server";
542
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
543
+
544
+ // src/tools.ts
545
+ import { createRequire } from "module";
546
+ import { join as join2 } from "path";
547
+ import { fromJsonSchema } from "@modelcontextprotocol/server";
548
+ import { addFormats, Ajv, AjvJsonSchemaValidator } from "@modelcontextprotocol/server/validators/ajv";
549
+ import { invokeOperation as invokeOperation2 } from "@tinycloud/operations";
550
+
551
+ // src/results.ts
552
+ function toMcpToolResult(result) {
553
+ const canonical = isCanonicalOperationResult(result) ? result : {
554
+ status: "error",
555
+ operation: {},
556
+ context: {},
557
+ error: { code: "INTERNAL_ERROR" }
558
+ };
559
+ return {
560
+ content: [{ type: "text", text: resultSummary(canonical.status) }],
561
+ structuredContent: canonical
562
+ };
563
+ }
564
+ function isCanonicalOperationResult(value) {
565
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
566
+ const status = value.status;
567
+ return status === "ok" || status === "authority_required" || status === "setup_required" || status === "error";
568
+ }
569
+ function resultSummary(status) {
570
+ switch (status) {
571
+ case "ok":
572
+ return "TinyCloud operation completed; use the structured result.";
573
+ case "authority_required":
574
+ return "TinyCloud authority is required; use the structured request and approval action.";
575
+ case "setup_required":
576
+ return "TinyCloud setup is required; use the structured setup action.";
577
+ case "error":
578
+ return "TinyCloud operation failed; use the structured error.";
579
+ }
580
+ }
581
+
582
+ // src/tools.ts
583
+ function invocationTargetForMcp(selection) {
584
+ return {
585
+ profile: selection.profile,
586
+ ...selection.explicitProfile && selection.allowOwnerProfile ? { allowOwnerProfile: true } : {},
587
+ ...selection.stateRoot === void 0 ? {} : { stateRoot: selection.stateRoot }
588
+ };
589
+ }
590
+ var packageRequire = createRequire(
591
+ typeof __dirname === "string" ? join2(__dirname, "tools.cjs") : import.meta.url
592
+ );
593
+ var generatedCatalog = packageRequire(
594
+ "@tinycloud/operations/operations.json"
595
+ );
596
+ var TOOL_BINDINGS = [
597
+ {
598
+ name: "tinycloud_status",
599
+ operationId: "tinycloud.status.get",
600
+ operationVersion: 1,
601
+ readOnlyHint: true,
602
+ idempotentHint: true,
603
+ destructiveHint: false,
604
+ openWorldHint: false
605
+ },
606
+ {
607
+ name: "tinycloud_auth_status",
608
+ operationId: "tinycloud.auth.status",
609
+ operationVersion: 1,
610
+ readOnlyHint: true,
611
+ idempotentHint: true,
612
+ destructiveHint: false,
613
+ openWorldHint: false
614
+ },
615
+ {
616
+ name: "tinycloud_auth_capabilities",
617
+ operationId: "tinycloud.auth.capabilities",
618
+ operationVersion: 1,
619
+ readOnlyHint: true,
620
+ idempotentHint: true,
621
+ destructiveHint: false,
622
+ openWorldHint: false
623
+ },
624
+ {
625
+ name: "tinycloud_auth_request",
626
+ operationId: "tinycloud.auth.request",
627
+ operationVersion: 1,
628
+ readOnlyHint: false,
629
+ idempotentHint: true,
630
+ destructiveHint: false,
631
+ openWorldHint: false
632
+ },
633
+ {
634
+ name: "tinycloud_auth_import",
635
+ operationId: "tinycloud.auth.import",
636
+ operationVersion: 1,
637
+ readOnlyHint: false,
638
+ idempotentHint: true,
639
+ destructiveHint: false,
640
+ openWorldHint: false
641
+ },
642
+ {
643
+ name: "tinycloud_account_spaces_list",
644
+ operationId: "tinycloud.account.spaces.list",
645
+ operationVersion: 1,
646
+ readOnlyHint: true,
647
+ idempotentHint: true,
648
+ destructiveHint: false,
649
+ openWorldHint: true
650
+ },
651
+ {
652
+ name: "tinycloud_account_applications_list",
653
+ operationId: "tinycloud.account.applications.list",
654
+ operationVersion: 1,
655
+ readOnlyHint: true,
656
+ idempotentHint: true,
657
+ destructiveHint: false,
658
+ openWorldHint: true
659
+ },
660
+ {
661
+ name: "tinycloud_kv_list",
662
+ operationId: "tinycloud.kv.list",
663
+ operationVersion: 1,
664
+ readOnlyHint: true,
665
+ idempotentHint: true,
666
+ destructiveHint: false,
667
+ openWorldHint: true
668
+ },
669
+ {
670
+ name: "tinycloud_kv_get",
671
+ operationId: "tinycloud.kv.get",
672
+ operationVersion: 1,
673
+ readOnlyHint: true,
674
+ idempotentHint: true,
675
+ destructiveHint: false,
676
+ openWorldHint: true
677
+ },
678
+ {
679
+ name: "tinycloud_kv_head",
680
+ operationId: "tinycloud.kv.head",
681
+ operationVersion: 1,
682
+ readOnlyHint: true,
683
+ idempotentHint: true,
684
+ destructiveHint: false,
685
+ openWorldHint: true
686
+ },
687
+ {
688
+ name: "tinycloud_kv_put",
689
+ operationId: "tinycloud.kv.put",
690
+ operationVersion: 1,
691
+ readOnlyHint: false,
692
+ idempotentHint: true,
693
+ destructiveHint: true,
694
+ openWorldHint: true
695
+ },
696
+ {
697
+ name: "tinycloud_kv_delete",
698
+ operationId: "tinycloud.kv.delete",
699
+ operationVersion: 1,
700
+ readOnlyHint: false,
701
+ idempotentHint: true,
702
+ destructiveHint: true,
703
+ openWorldHint: true
704
+ },
705
+ {
706
+ name: "tinycloud_sql_schema_inspect",
707
+ operationId: "tinycloud.sql.schema.inspect",
708
+ operationVersion: 1,
709
+ readOnlyHint: true,
710
+ idempotentHint: true,
711
+ destructiveHint: false,
712
+ openWorldHint: true
713
+ },
714
+ {
715
+ name: "tinycloud_sql_query",
716
+ operationId: "tinycloud.sql.query",
717
+ operationVersion: 1,
718
+ readOnlyHint: true,
719
+ idempotentHint: true,
720
+ destructiveHint: false,
721
+ openWorldHint: true
722
+ },
723
+ {
724
+ name: "tinycloud_sql_execute",
725
+ operationId: "tinycloud.sql.execute",
726
+ operationVersion: 1,
727
+ readOnlyHint: false,
728
+ idempotentHint: false,
729
+ destructiveHint: true,
730
+ openWorldHint: true
731
+ },
732
+ {
733
+ name: "tinycloud_secrets_get",
734
+ operationId: "tinycloud.secrets.get",
735
+ operationVersion: 1,
736
+ readOnlyHint: false,
737
+ idempotentHint: true,
738
+ destructiveHint: false,
739
+ openWorldHint: true
740
+ }
741
+ ];
742
+ function createJsonSchemaValidator() {
743
+ const ajv = new Ajv({ strict: false });
744
+ addFormats(ajv);
745
+ return new AjvJsonSchemaValidator(ajv);
746
+ }
747
+ function registerTinyCloudTools(server, selection, validator) {
748
+ const definitions = new Map(
749
+ generatedCatalog.operations.map((operation) => [
750
+ `${operation.id}@${operation.version}`,
751
+ operation
752
+ ])
753
+ );
754
+ for (const binding of TOOL_BINDINGS) {
755
+ const operation = definitions.get(`${binding.operationId}@${binding.operationVersion}`);
756
+ if (operation === void 0) {
757
+ throw new Error(`Generated operations catalog is missing ${binding.operationId}@${binding.operationVersion}.`);
758
+ }
759
+ const inputSchema = fromJsonSchema(
760
+ operation.input,
761
+ validator
762
+ );
763
+ const outputSchema = fromJsonSchema(
764
+ operation.result,
765
+ validator
766
+ );
767
+ const annotations = {
768
+ readOnlyHint: binding.readOnlyHint,
769
+ idempotentHint: binding.idempotentHint,
770
+ destructiveHint: binding.destructiveHint,
771
+ openWorldHint: binding.openWorldHint
772
+ };
773
+ server.registerTool(
774
+ binding.name,
775
+ {
776
+ title: operation.title,
777
+ description: operation.description,
778
+ inputSchema,
779
+ outputSchema,
780
+ annotations
781
+ },
782
+ async (input) => {
783
+ const result = await invokeOperation2(
784
+ binding.operationId,
785
+ binding.operationVersion,
786
+ invocationTargetForMcp(selection),
787
+ input
788
+ );
789
+ const projected = selection.transformOperationResult === void 0 ? result : await selection.transformOperationResult(result);
790
+ return toMcpToolResult(projected);
791
+ }
792
+ );
793
+ }
794
+ }
795
+
796
+ // package.json
797
+ var package_default = {
798
+ name: "@tinycloud/mcp",
799
+ version: "0.3.0-beta.0",
800
+ description: "TinyCloud delegated operations MCP server",
801
+ keywords: [
802
+ "tinycloud",
803
+ "mcp",
804
+ "model-context-protocol",
805
+ "agents",
806
+ "delegation",
807
+ "ucan",
808
+ "kv",
809
+ "sqlite"
810
+ ],
811
+ author: "TinyCloud, Inc.",
812
+ license: "EGPL",
813
+ type: "module",
814
+ main: "dist/index.cjs",
815
+ module: "dist/index.js",
816
+ types: "dist/index.d.ts",
817
+ bin: {
818
+ "tinycloud-mcp": "./bin/tinycloud-mcp",
819
+ "tinycloud-mcp-http": "./bin/tinycloud-mcp-http"
820
+ },
821
+ exports: {
822
+ ".": {
823
+ types: "./dist/index.d.ts",
824
+ import: "./dist/index.js",
825
+ require: "./dist/index.cjs"
826
+ },
827
+ "./server": {
828
+ types: "./dist/server.d.ts",
829
+ import: "./dist/server.js",
830
+ require: "./dist/server.cjs"
831
+ },
832
+ "./tools": {
833
+ types: "./dist/tools.d.ts",
834
+ import: "./dist/tools.js",
835
+ require: "./dist/tools.cjs"
836
+ },
837
+ "./results": {
838
+ types: "./dist/results.d.ts",
839
+ import: "./dist/results.js",
840
+ require: "./dist/results.cjs"
841
+ },
842
+ "./http": {
843
+ types: "./dist/http.d.ts",
844
+ import: "./dist/http.js",
845
+ require: "./dist/http.cjs"
846
+ }
847
+ },
848
+ files: [
849
+ "dist",
850
+ "bin",
851
+ "generated",
852
+ "skills"
853
+ ],
854
+ engines: {
855
+ node: ">=20"
856
+ },
857
+ scripts: {
858
+ build: "tsup",
859
+ clean: "rm -rf dist",
860
+ test: "bun run build && bun scripts/test.ts && bun run check:generated",
861
+ "test:stdio": "bun run build && bun test src/stdio.test.ts",
862
+ typecheck: "tsc -p tsconfig.json",
863
+ "start:http": "node dist/http-cli.js",
864
+ generate: "bun scripts/generate.ts",
865
+ "check:generated": "bun scripts/generate.ts --check"
866
+ },
867
+ dependencies: {
868
+ "@modelcontextprotocol/node": "2.0.0-beta.4",
869
+ "@modelcontextprotocol/server": "2.0.0-beta.4",
870
+ "@tinycloud/node-sdk": "2.9.0",
871
+ "@tinycloud/node-sdk-wasm": "1.7.5",
872
+ "@tinycloud/operations": "0.3.0-beta.0",
873
+ jose: "6.1.3"
874
+ },
875
+ devDependencies: {
876
+ "@modelcontextprotocol/client": "2.0.0-beta.4",
877
+ "@types/node": "^20",
878
+ tsup: "^8.0.0",
879
+ typescript: "^5.9.3"
880
+ },
881
+ repository: {
882
+ type: "git",
883
+ url: "https://github.com/TinyCloudLabs/js-sdk"
884
+ },
885
+ homepage: "https://docs.tinycloud.xyz/cli/mcp"
886
+ };
887
+
888
+ // src/version.ts
889
+ var MCP_VERSION = package_default.version;
890
+
891
+ // src/server.ts
892
+ var MCP_SERVER_NAME = "tinycloud-mcp";
893
+
894
+ // src/http.ts
895
+ var REQUIRED_SCOPE = "tinycloud:mcp";
896
+ function createHostedMcpApp(config) {
897
+ const resourceUrl = canonicalResourceUrl(config.publicUrl);
898
+ const issuer = String(config.oauthMetadata.issuer);
899
+ const jwksUri = String(config.oauthMetadata.jwks_uri);
900
+ const verifier = createOpenKeyTokenVerifier({
901
+ issuer,
902
+ audience: resourceUrl.toString(),
903
+ jwksUri,
904
+ requiredScope: REQUIRED_SCOPE
905
+ });
906
+ const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(resourceUrl);
907
+ const authenticate = requireBearerAuth({
908
+ verifier,
909
+ requiredScopes: [REQUIRED_SCOPE],
910
+ resourceMetadataUrl
911
+ });
912
+ const store = new RemoteTenantStore({ ...config, publicUrl: resourceUrl });
913
+ const handler = createMcpHandler(async ({ authInfo: authInfo2 }) => {
914
+ const identity = oauthIdentity(authInfo2);
915
+ const { subject, ownerDids } = identity;
916
+ const stateRoot = store.tenantStateRoot(subject);
917
+ const validator = createJsonSchemaValidator();
918
+ const server = new McpServer2(
919
+ { name: MCP_SERVER_NAME, version: MCP_VERSION },
920
+ {
921
+ jsonSchemaValidator: validator,
922
+ instructions: "Call tinycloud_connect first. If an operation returns authority_required, open approval.url, then retry that operation unchanged."
923
+ }
924
+ );
925
+ registerTinyCloudTools(server, {
926
+ profile: "agent",
927
+ explicitProfile: true,
928
+ allowOwnerProfile: false,
929
+ stateRoot,
930
+ transformOperationResult: (result) => store.decorateAuthorityResult(subject, ownerDids, result)
931
+ }, validator);
932
+ registerConnectTool(server, validator, store, identity);
933
+ return server;
934
+ }, {
935
+ legacy: "stateless",
936
+ onerror: () => writeDiagnostic("MCP request failed")
937
+ });
938
+ const metadataOptions = {
939
+ oauthMetadata: config.oauthMetadata,
940
+ resourceServerUrl: resourceUrl,
941
+ serviceDocumentationUrl: new URL("https://docs.tinycloud.xyz/cli/mcp"),
942
+ scopesSupported: [REQUIRED_SCOPE],
943
+ resourceName: "TinyCloud hosted MCP"
944
+ };
945
+ const allowedHosts = [resourceUrl.hostname];
946
+ return {
947
+ async fetch(request) {
948
+ const metadata = oauthMetadataResponse(request, metadataOptions);
949
+ if (metadata !== void 0) return metadata;
950
+ const url = new URL(request.url);
951
+ if (url.pathname === "/healthz") {
952
+ return request.method === "GET" ? json({ ok: true }) : methodNotAllowed("GET");
953
+ }
954
+ const hostFailure = hostHeaderValidationResponse(request, allowedHosts);
955
+ if (hostFailure !== void 0) return hostFailure;
956
+ if (url.pathname === "/connect") {
957
+ if (request.method !== "GET") return methodNotAllowed("GET");
958
+ try {
959
+ const destination = await store.approvalRedirect(requiredState(url));
960
+ return Response.redirect(destination, 302);
961
+ } catch {
962
+ return json({ error: "The approval link is invalid or expired." }, 400);
963
+ }
964
+ }
965
+ if (url.pathname === "/connect/callback") {
966
+ if (request.method === "OPTIONS") return callbackCors(new Response(null, { status: 204 }), config.openkeyHost);
967
+ if (request.method !== "POST") return methodNotAllowed("POST");
968
+ const originFailure2 = validateCallbackOrigin(request, config.openkeyHost);
969
+ if (originFailure2 !== void 0) return callbackCors(originFailure2, config.openkeyHost);
970
+ try {
971
+ await store.completeApproval(requiredState(url), request);
972
+ return callbackCors(json({ success: true }), config.openkeyHost);
973
+ } catch {
974
+ return callbackCors(json({ error: "TinyCloud could not accept this delegation." }, 400), config.openkeyHost);
975
+ }
976
+ }
977
+ if (url.pathname !== resourceUrl.pathname) return json({ error: "Not found" }, 404);
978
+ const originFailure = validateOrigin(request, config.allowedOrigins);
979
+ if (originFailure !== void 0) return originFailure;
980
+ const auth = await authenticate(request);
981
+ if (auth instanceof Response) return auth;
982
+ return handler.fetch(request, { authInfo: auth });
983
+ },
984
+ close: () => handler.close()
985
+ };
986
+ }
987
+ function registerConnectTool(server, validator, store, identity) {
988
+ const inputSchema = fromJsonSchema2({ type: "object", properties: {}, additionalProperties: false }, validator);
989
+ const outputSchema = fromJsonSchema2({
990
+ type: "object",
991
+ properties: {
992
+ connected: { type: "boolean" },
993
+ sessionDid: { type: "string" },
994
+ approvalUrl: { type: "string", format: "uri" },
995
+ expiresAt: { type: "string", format: "date-time" }
996
+ },
997
+ required: ["connected", "sessionDid"],
998
+ additionalProperties: false
999
+ }, validator);
1000
+ server.registerTool(
1001
+ "tinycloud_connect",
1002
+ {
1003
+ title: "Connect TinyCloud",
1004
+ description: "Check the hosted delegate connection and return a one-time OpenKey approval URL when setup is required.",
1005
+ inputSchema,
1006
+ outputSchema,
1007
+ annotations: {
1008
+ readOnlyHint: false,
1009
+ idempotentHint: true,
1010
+ destructiveHint: false,
1011
+ openWorldHint: true
1012
+ }
1013
+ },
1014
+ async () => {
1015
+ const status = await store.connectStatus(identity.subject, identity.ownerDids);
1016
+ return {
1017
+ content: [{
1018
+ type: "text",
1019
+ text: status.connected ? "TinyCloud is connected." : "TinyCloud approval is required; open approvalUrl, then call this tool again."
1020
+ }],
1021
+ structuredContent: status
1022
+ };
1023
+ }
1024
+ );
1025
+ }
1026
+ function oauthIdentity(authInfo2) {
1027
+ const subject = authInfo2?.extra?.subject;
1028
+ if (typeof subject !== "string" || subject.length === 0) {
1029
+ throw new Error("The authenticated MCP request has no OpenKey subject.");
1030
+ }
1031
+ const ownerDids = authInfo2?.extra?.ownerDids;
1032
+ if (!Array.isArray(ownerDids) || ownerDids.length === 0 || !ownerDids.every((did) => typeof did === "string")) {
1033
+ throw new Error("The authenticated MCP request has no OpenKey owner identity.");
1034
+ }
1035
+ return { subject, ownerDids };
1036
+ }
1037
+ function canonicalResourceUrl(url) {
1038
+ const resource = new URL(url);
1039
+ resource.hash = "";
1040
+ resource.search = "";
1041
+ resource.pathname = resource.pathname.replace(/\/+$/, "") || "/mcp";
1042
+ if (resource.pathname === "/") resource.pathname = "/mcp";
1043
+ return resource;
1044
+ }
1045
+ function requiredState(url) {
1046
+ const state = url.searchParams.get("state");
1047
+ if (state === null || state.length > 512) throw new Error("Missing approval state.");
1048
+ return state;
1049
+ }
1050
+ function validateOrigin(request, allowed) {
1051
+ const origin = request.headers.get("origin");
1052
+ if (origin === null) return void 0;
1053
+ const allowlist = allowed ?? [];
1054
+ return allowlist.includes(origin) ? void 0 : json({ error: "Origin is not allowed." }, 403);
1055
+ }
1056
+ function validateCallbackOrigin(request, openkeyHost) {
1057
+ const origin = request.headers.get("origin");
1058
+ return origin === null || origin === new URL(openkeyHost).origin ? void 0 : json({ error: "Origin is not allowed." }, 403);
1059
+ }
1060
+ function callbackCors(response, openkeyHost) {
1061
+ const headers = new Headers(response.headers);
1062
+ headers.set("access-control-allow-origin", new URL(openkeyHost).origin);
1063
+ headers.set("access-control-allow-methods", "POST, OPTIONS");
1064
+ headers.set("access-control-allow-headers", "content-type");
1065
+ headers.set("vary", "Origin");
1066
+ return new Response(response.body, { status: response.status, headers });
1067
+ }
1068
+ function json(value, status = 200) {
1069
+ return Response.json(value, { status, headers: { "cache-control": "no-store" } });
1070
+ }
1071
+ function methodNotAllowed(allow) {
1072
+ return new Response("Method not allowed", { status: 405, headers: { allow } });
1073
+ }
1074
+ function writeDiagnostic(message) {
1075
+ process.stderr.write(`[tinycloud-mcp-http] ${message}
1076
+ `);
1077
+ }
1078
+ export {
1079
+ createHostedMcpApp
1080
+ };
1081
+ //# sourceMappingURL=http.js.map