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