@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/index.js CHANGED
@@ -69,7 +69,8 @@ var TOOL_NAMES = [
69
69
  function invocationTargetForMcp(selection) {
70
70
  return {
71
71
  profile: selection.profile,
72
- ...selection.explicitProfile && selection.allowOwnerProfile ? { allowOwnerProfile: true } : {}
72
+ ...selection.explicitProfile && selection.allowOwnerProfile ? { allowOwnerProfile: true } : {},
73
+ ...selection.stateRoot === void 0 ? {} : { stateRoot: selection.stateRoot }
73
74
  };
74
75
  }
75
76
  var packageRequire = createRequire(
@@ -271,7 +272,8 @@ function registerTinyCloudTools(server, selection, validator) {
271
272
  invocationTargetForMcp(selection),
272
273
  input
273
274
  );
274
- return toMcpToolResult(result);
275
+ const projected = selection.transformOperationResult === void 0 ? result : await selection.transformOperationResult(result);
276
+ return toMcpToolResult(projected);
275
277
  }
276
278
  );
277
279
  }
@@ -280,7 +282,7 @@ function registerTinyCloudTools(server, selection, validator) {
280
282
  // package.json
281
283
  var package_default = {
282
284
  name: "@tinycloud/mcp",
283
- version: "0.2.2-beta.0",
285
+ version: "0.3.0-beta.0",
284
286
  description: "TinyCloud delegated operations MCP server",
285
287
  keywords: [
286
288
  "tinycloud",
@@ -299,7 +301,8 @@ var package_default = {
299
301
  module: "dist/index.js",
300
302
  types: "dist/index.d.ts",
301
303
  bin: {
302
- "tinycloud-mcp": "./bin/tinycloud-mcp"
304
+ "tinycloud-mcp": "./bin/tinycloud-mcp",
305
+ "tinycloud-mcp-http": "./bin/tinycloud-mcp-http"
303
306
  },
304
307
  exports: {
305
308
  ".": {
@@ -321,6 +324,11 @@ var package_default = {
321
324
  types: "./dist/results.d.ts",
322
325
  import: "./dist/results.js",
323
326
  require: "./dist/results.cjs"
327
+ },
328
+ "./http": {
329
+ types: "./dist/http.d.ts",
330
+ import: "./dist/http.js",
331
+ require: "./dist/http.cjs"
324
332
  }
325
333
  },
326
334
  files: [
@@ -338,12 +346,17 @@ var package_default = {
338
346
  test: "bun run build && bun scripts/test.ts && bun run check:generated",
339
347
  "test:stdio": "bun run build && bun test src/stdio.test.ts",
340
348
  typecheck: "tsc -p tsconfig.json",
349
+ "start:http": "node dist/http-cli.js",
341
350
  generate: "bun scripts/generate.ts",
342
351
  "check:generated": "bun scripts/generate.ts --check"
343
352
  },
344
353
  dependencies: {
354
+ "@modelcontextprotocol/node": "2.0.0-beta.4",
345
355
  "@modelcontextprotocol/server": "2.0.0-beta.4",
346
- "@tinycloud/operations": "0.2.1-beta.0"
356
+ "@tinycloud/node-sdk": "2.9.0",
357
+ "@tinycloud/node-sdk-wasm": "1.7.5",
358
+ "@tinycloud/operations": "0.3.0-beta.0",
359
+ jose: "6.1.3"
347
360
  },
348
361
  devDependencies: {
349
362
  "@modelcontextprotocol/client": "2.0.0-beta.4",
@@ -479,11 +492,736 @@ if (isDirectInvocation()) {
479
492
  process.exitCode = 1;
480
493
  });
481
494
  }
495
+
496
+ // src/http.ts
497
+ import {
498
+ McpServer as McpServer2,
499
+ createMcpHandler,
500
+ fromJsonSchema as fromJsonSchema2,
501
+ getOAuthProtectedResourceMetadataUrl,
502
+ hostHeaderValidationResponse,
503
+ oauthMetadataResponse,
504
+ requireBearerAuth
505
+ } from "@modelcontextprotocol/server";
506
+
507
+ // src/oauth.ts
508
+ import {
509
+ OAuthError,
510
+ OAuthErrorCode
511
+ } from "@modelcontextprotocol/server";
512
+ import { createRemoteJWKSet, errors, jwtVerify } from "jose";
513
+ var OWNER_DIDS_CLAIM = "https://tinycloud.xyz/owner_dids";
514
+ function createOpenKeyTokenVerifier(config) {
515
+ const jwks = createRemoteJWKSet(new URL(config.jwksUri));
516
+ return {
517
+ async verifyAccessToken(token) {
518
+ try {
519
+ const { payload } = await jwtVerify(token, jwks, {
520
+ issuer: config.issuer,
521
+ audience: config.audience
522
+ });
523
+ return authInfo(token, payload, config);
524
+ } catch (error) {
525
+ if (error instanceof errors.JOSEError) {
526
+ throw new OAuthError(OAuthErrorCode.InvalidToken, "The OpenKey access token is invalid.");
527
+ }
528
+ throw error;
529
+ }
530
+ }
531
+ };
532
+ }
533
+ function authInfo(token, payload, config) {
534
+ if (typeof payload.sub !== "string" || payload.sub.length === 0) {
535
+ throw new OAuthError(OAuthErrorCode.InvalidToken, "The OpenKey access token does not identify a subject.");
536
+ }
537
+ if (typeof payload.exp !== "number") {
538
+ throw new OAuthError(OAuthErrorCode.InvalidToken, "The OpenKey access token has no expiry.");
539
+ }
540
+ const scopes = typeof payload.scope === "string" ? payload.scope.split(/\s+/).filter(Boolean) : [];
541
+ if (config.requiredScope !== void 0 && !scopes.includes(config.requiredScope)) {
542
+ throw new OAuthError(
543
+ OAuthErrorCode.InsufficientScope,
544
+ "The OpenKey access token is missing the TinyCloud MCP scope."
545
+ );
546
+ }
547
+ const clientId = firstString(payload.azp, payload.client_id) ?? "unknown";
548
+ const ownerDids = Array.isArray(payload[OWNER_DIDS_CLAIM]) ? payload[OWNER_DIDS_CLAIM].filter((value) => typeof value === "string") : [];
549
+ if (ownerDids.length === 0) {
550
+ throw new OAuthError(
551
+ OAuthErrorCode.InvalidToken,
552
+ "The OpenKey access token has no TinyCloud owner identity."
553
+ );
554
+ }
555
+ return {
556
+ token,
557
+ clientId,
558
+ scopes,
559
+ expiresAt: payload.exp,
560
+ resource: new URL(config.audience),
561
+ extra: {
562
+ subject: payload.sub,
563
+ ownerDids
564
+ }
565
+ };
566
+ }
567
+ function firstString(...values) {
568
+ return values.find((value) => typeof value === "string" && value.length > 0);
569
+ }
570
+
571
+ // src/remote-store.ts
572
+ import { createHmac, randomBytes, timingSafeEqual } from "crypto";
573
+ import { chmod, mkdir, readFile, readdir, rename, rm, writeFile } from "fs/promises";
574
+ import { dirname, join as join2 } from "path";
575
+ import {
576
+ TinyCloudNode,
577
+ principalDidEquals
578
+ } from "@tinycloud/node-sdk";
579
+ import { TCWSessionManager, importKey, initPanicHook } from "@tinycloud/node-sdk-wasm";
580
+ import { invokeOperation as invokeOperation2 } from "@tinycloud/operations";
581
+ var PROFILE = "agent";
582
+ var MAX_CALLBACK_BYTES = 256 * 1024;
583
+ var BOOTSTRAP_PERMISSIONS = [
584
+ {
585
+ service: "tinycloud.kv",
586
+ space: "account",
587
+ path: "spaces/",
588
+ actions: ["tinycloud.kv/get", "tinycloud.kv/list"]
589
+ },
590
+ {
591
+ service: "tinycloud.kv",
592
+ space: "account",
593
+ path: "applications/",
594
+ actions: ["tinycloud.kv/get", "tinycloud.kv/list"]
595
+ }
596
+ ];
597
+ var RemoteTenantStore = class {
598
+ #config;
599
+ #initializing = /* @__PURE__ */ new Map();
600
+ constructor(config) {
601
+ this.#config = config;
602
+ }
603
+ tenantStateRoot(subject) {
604
+ return join2(this.#config.stateDir, "tenants", this.#tenantId(subject));
605
+ }
606
+ async connectStatus(subject, ownerDids = []) {
607
+ const tenant = await this.#ensureTenant(subject);
608
+ if (await this.#hasValidSession(tenant, ownerDids)) {
609
+ return { connected: true, sessionDid: tenant.sessionDid };
610
+ }
611
+ const pending = await this.#createPending(subject, ownerDids, "bootstrap", BOOTSTRAP_PERMISSIONS);
612
+ return {
613
+ connected: false,
614
+ sessionDid: tenant.sessionDid,
615
+ approvalUrl: this.#connectUrl(pending),
616
+ expiresAt: pending.expiresAt
617
+ };
618
+ }
619
+ async decorateAuthorityResult(subject, ownerDids, result) {
620
+ if (!isRecord(result) || result.status !== "authority_required") return result;
621
+ const request = isRecord(result.request) ? result.request : void 0;
622
+ const requestId = typeof request?.requestId === "string" ? request.requestId : void 0;
623
+ const requested = Array.isArray(request?.requested) ? request.requested.filter(isPermissionEntry) : [];
624
+ if (requestId === void 0 || requested.length === 0) return result;
625
+ const pending = await this.#createPending(subject, ownerDids, "delegation", requested, requestId);
626
+ return {
627
+ ...result,
628
+ approval: {
629
+ ...isRecord(result.approval) ? result.approval : {},
630
+ kind: "openkey",
631
+ requestId,
632
+ url: this.#connectUrl(pending),
633
+ fallback: "Open the approval URL, then retry the same MCP tool."
634
+ }
635
+ };
636
+ }
637
+ async approvalRedirect(state) {
638
+ const pending = await this.#readPending(state, false);
639
+ const tenant = await this.#readTenant(pending.tenantId);
640
+ const callback = new URL("/connect/callback", this.#config.publicUrl);
641
+ callback.searchParams.set("state", state);
642
+ const params = new URLSearchParams({
643
+ did: tenant.sessionDid,
644
+ callback: callback.toString(),
645
+ host: this.#config.nodeHost,
646
+ jwk: Buffer.from(JSON.stringify(publicJwk(tenant.jwk))).toString("base64url"),
647
+ permissions: Buffer.from(JSON.stringify({
648
+ permissions: pending.permissions,
649
+ reason: pending.kind === "bootstrap" ? "Connect this TinyCloud account to the hosted MCP delegate." : "Approve the exact capabilities requested by the TinyCloud MCP operation."
650
+ })).toString("base64url"),
651
+ expiry: this.#config.delegationExpiry
652
+ });
653
+ return `${this.#config.openkeyHost.replace(/\/+$/, "")}/delegate?${params.toString()}`;
654
+ }
655
+ async completeApproval(state, request) {
656
+ const length = Number(request.headers.get("content-length") ?? "0");
657
+ if (Number.isFinite(length) && length > MAX_CALLBACK_BYTES) throw new Error("Callback body is too large.");
658
+ const text = await request.text();
659
+ if (Buffer.byteLength(text) > MAX_CALLBACK_BYTES) throw new Error("Callback body is too large.");
660
+ const data = JSON.parse(text);
661
+ if (!isRecord(data)) throw new Error("Callback body is invalid.");
662
+ const pending = await this.#readPending(state, true);
663
+ try {
664
+ const tenant = await this.#readTenant(pending.tenantId);
665
+ if (pending.kind === "bootstrap") {
666
+ await this.#storeBootstrap(tenant, pending, data);
667
+ } else {
668
+ await this.#storeDelegation(tenant, pending, data);
669
+ }
670
+ await rm(this.#pendingPath(tenant.stateRoot, pending.nonce) + ".processing", { force: true });
671
+ } catch (error) {
672
+ await this.#restorePending(pending).catch(() => void 0);
673
+ throw error;
674
+ }
675
+ }
676
+ async #storeBootstrap(tenant, pending, data) {
677
+ const session = sessionFromCallback(data, tenant.jwk);
678
+ const node = new TinyCloudNode({ host: this.#config.nodeHost });
679
+ await node.restoreSession(session);
680
+ if (!samePrincipal(node.sessionDid, tenant.sessionDid)) {
681
+ throw new Error("The approved delegation targets a different session.");
682
+ }
683
+ if (pending.ownerDids.length > 0 && !pending.ownerDids.some((did) => samePrincipal(node.did, did))) {
684
+ throw new Error("The approved delegation belongs to a different OpenKey user.");
685
+ }
686
+ const granted = [...node.getVerifiedSessionCapabilities()];
687
+ if (!permissionsCover(pending.permissions, granted)) {
688
+ throw new Error("The approved delegation does not cover the requested account access.");
689
+ }
690
+ const profile = await readJson(this.#profilePath(tenant.stateRoot));
691
+ await secureWrite(this.#profilePath(tenant.stateRoot), {
692
+ ...profile,
693
+ ownerDid: normalizeDid(node.did),
694
+ spaceId: session.spaceId
695
+ });
696
+ await secureWrite(this.#sessionPath(tenant.stateRoot), {
697
+ authMethod: "openkey",
698
+ ...session
699
+ });
700
+ }
701
+ async #storeDelegation(tenant, pending, data) {
702
+ if (pending.requestId === void 0) throw new Error("Authority request is missing.");
703
+ const delegation = portableFromCallback(data, pending.permissions, this.#config.nodeHost);
704
+ const result = await invokeOperation2(
705
+ "tinycloud.auth.import",
706
+ 1,
707
+ { profile: PROFILE, stateRoot: tenant.stateRoot },
708
+ {
709
+ requestId: pending.requestId,
710
+ delegationCid: delegation.cid,
711
+ delegation
712
+ }
713
+ );
714
+ if (result.status !== "ok") throw new Error("TinyCloud rejected the approved delegation.");
715
+ }
716
+ async #ensureTenant(subject) {
717
+ const tenantId = this.#tenantId(subject);
718
+ const current = this.#initializing.get(tenantId);
719
+ if (current !== void 0) return current;
720
+ const initializing = this.#initializeTenant(tenantId).finally(() => {
721
+ this.#initializing.delete(tenantId);
722
+ });
723
+ this.#initializing.set(tenantId, initializing);
724
+ return initializing;
725
+ }
726
+ async #hasValidSession(tenant, ownerDids) {
727
+ const raw = await readJson(this.#sessionPath(tenant.stateRoot));
728
+ if (raw === null) return false;
729
+ try {
730
+ const node = new TinyCloudNode({ host: this.#config.nodeHost });
731
+ await node.restoreSession(raw);
732
+ return samePrincipal(node.sessionDid, tenant.sessionDid) && ownerDids.some((did) => samePrincipal(node.did, did));
733
+ } catch {
734
+ await rm(this.#sessionPath(tenant.stateRoot), { force: true });
735
+ return false;
736
+ }
737
+ }
738
+ async #initializeTenant(tenantId) {
739
+ const stateRoot = join2(this.#config.stateDir, "tenants", tenantId);
740
+ const keyPath = this.#keyPath(stateRoot);
741
+ await secureDirectory(join2(stateRoot, ".tinycloud", "profiles", PROFILE));
742
+ let jwk = await readJson(keyPath);
743
+ let sessionDid;
744
+ if (jwk === null) {
745
+ const generated = generateSessionKey();
746
+ jwk = generated.jwk;
747
+ sessionDid = generated.did;
748
+ await secureWrite(keyPath, jwk);
749
+ } else {
750
+ sessionDid = didFromJwk(jwk);
751
+ }
752
+ const profilePath = this.#profilePath(stateRoot);
753
+ if (!await fileExists(profilePath)) {
754
+ await secureWrite(profilePath, {
755
+ name: PROFILE,
756
+ host: this.#config.nodeHost,
757
+ chainId: 1,
758
+ spaceName: "default",
759
+ did: sessionDid,
760
+ sessionDid,
761
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
762
+ posture: "delegate-session",
763
+ operatorType: "agent",
764
+ authMethod: "openkey",
765
+ openkeyHost: this.#config.openkeyHost
766
+ });
767
+ }
768
+ return { stateRoot, sessionDid, jwk };
769
+ }
770
+ async #readTenant(tenantId) {
771
+ if (!/^[a-f0-9]{64}$/.test(tenantId)) throw new Error("Approval state is invalid.");
772
+ const stateRoot = join2(this.#config.stateDir, "tenants", tenantId);
773
+ const jwk = await readJson(this.#keyPath(stateRoot));
774
+ if (jwk === null) throw new Error("The TinyCloud delegate no longer exists.");
775
+ return { stateRoot, jwk, sessionDid: didFromJwk(jwk) };
776
+ }
777
+ async #createPending(subject, ownerDids, kind, permissions, requestId) {
778
+ const tenant = await this.#ensureTenant(subject);
779
+ const tenantId = this.#tenantId(subject);
780
+ const reusable = await reusablePending(
781
+ this.#pendingDirectory(tenant.stateRoot),
782
+ { tenantId, kind, requestId, permissions, ownerDids: ownerDids.map(normalizeDid) }
783
+ );
784
+ if (reusable !== void 0) return reusable;
785
+ const nonce = randomBytes(24).toString("base64url");
786
+ const created = Date.now();
787
+ const pending = {
788
+ version: 1,
789
+ nonce,
790
+ tenantId,
791
+ kind,
792
+ ...requestId === void 0 ? {} : { requestId },
793
+ permissions,
794
+ ownerDids: ownerDids.map(normalizeDid),
795
+ createdAt: new Date(created).toISOString(),
796
+ expiresAt: new Date(created + this.#config.approvalTtlSeconds * 1e3).toISOString()
797
+ };
798
+ await secureWrite(this.#pendingPath(tenant.stateRoot, nonce), pending);
799
+ return pending;
800
+ }
801
+ async #readPending(state, consume) {
802
+ const [tenantId, nonce, signature] = state.split(".");
803
+ if (tenantId === void 0 || nonce === void 0 || signature === void 0) {
804
+ throw new Error("Approval state is invalid.");
805
+ }
806
+ const expected = this.#signState(tenantId, nonce);
807
+ const supplied = Buffer.from(signature, "base64url");
808
+ const expectedBytes = Buffer.from(expected, "base64url");
809
+ if (supplied.length !== expectedBytes.length || !timingSafeEqual(supplied, expectedBytes)) {
810
+ throw new Error("Approval state is invalid.");
811
+ }
812
+ const stateRoot = join2(this.#config.stateDir, "tenants", tenantId);
813
+ const path = this.#pendingPath(stateRoot, nonce);
814
+ const claimed = `${path}.processing`;
815
+ if (consume) await rename(path, claimed);
816
+ try {
817
+ const pending = await readJson(consume ? claimed : path);
818
+ if (pending === null || pending.version !== 1 || pending.tenantId !== tenantId || pending.nonce !== nonce) {
819
+ throw new Error("Approval state is invalid or already used.");
820
+ }
821
+ if (new Date(pending.expiresAt).getTime() <= Date.now()) {
822
+ await rm(consume ? claimed : path, { force: true });
823
+ throw new Error("Approval state has expired.");
824
+ }
825
+ return pending;
826
+ } catch (error) {
827
+ if (consume) await rename(claimed, path).catch(() => void 0);
828
+ throw error;
829
+ }
830
+ }
831
+ async #restorePending(pending) {
832
+ const stateRoot = join2(this.#config.stateDir, "tenants", pending.tenantId);
833
+ const path = this.#pendingPath(stateRoot, pending.nonce);
834
+ await rename(`${path}.processing`, path);
835
+ }
836
+ #connectUrl(pending) {
837
+ const url = new URL("/connect", this.#config.publicUrl);
838
+ url.searchParams.set("state", `${pending.tenantId}.${pending.nonce}.${this.#signState(pending.tenantId, pending.nonce)}`);
839
+ return url.toString();
840
+ }
841
+ #tenantId(subject) {
842
+ return createHmac("sha256", this.#config.stateSecret).update(`tenant:${subject}`).digest("hex");
843
+ }
844
+ #signState(tenantId, nonce) {
845
+ return createHmac("sha256", this.#config.stateSecret).update(`approval:${tenantId}:${nonce}`).digest("base64url");
846
+ }
847
+ #profilePath(stateRoot) {
848
+ return join2(stateRoot, ".tinycloud", "profiles", PROFILE, "profile.json");
849
+ }
850
+ #keyPath(stateRoot) {
851
+ return join2(stateRoot, ".tinycloud", "profiles", PROFILE, "key.json");
852
+ }
853
+ #sessionPath(stateRoot) {
854
+ return join2(stateRoot, ".tinycloud", "profiles", PROFILE, "session.json");
855
+ }
856
+ #pendingPath(stateRoot, nonce) {
857
+ return join2(this.#pendingDirectory(stateRoot), `${nonce}.json`);
858
+ }
859
+ #pendingDirectory(stateRoot) {
860
+ return join2(stateRoot, ".tinycloud", "profiles", PROFILE, "pending");
861
+ }
862
+ };
863
+ var wasmInitialized = false;
864
+ function generateSessionKey() {
865
+ ensureWasm();
866
+ const manager = new TCWSessionManager();
867
+ const keyId = manager.createSessionKey("hosted-mcp");
868
+ const serialized = manager.jwk(keyId);
869
+ if (!serialized) throw new Error("Could not generate the hosted delegate key.");
870
+ return { jwk: JSON.parse(serialized), did: manager.getDID(keyId) };
871
+ }
872
+ function didFromJwk(jwk) {
873
+ ensureWasm();
874
+ const manager = new TCWSessionManager();
875
+ const keyId = importKey(manager, JSON.stringify(jwk), "hosted-mcp");
876
+ return manager.getDID(keyId);
877
+ }
878
+ function ensureWasm() {
879
+ if (wasmInitialized) return;
880
+ initPanicHook();
881
+ wasmInitialized = true;
882
+ }
883
+ function sessionFromCallback(data, privateJwk) {
884
+ const delegationHeader = data.delegationHeader;
885
+ if (!isRecord(delegationHeader) || typeof delegationHeader.Authorization !== "string" || typeof data.delegationCid !== "string" || typeof data.spaceId !== "string" || typeof data.verificationMethod !== "string") {
886
+ throw new Error("OpenKey returned an incomplete delegation.");
887
+ }
888
+ return {
889
+ delegationHeader: { Authorization: delegationHeader.Authorization },
890
+ delegationCid: data.delegationCid,
891
+ spaceId: data.spaceId,
892
+ jwk: privateJwk,
893
+ verificationMethod: data.verificationMethod,
894
+ ...typeof data.address === "string" ? { address: data.address } : {},
895
+ ...typeof data.chainId === "number" ? { chainId: data.chainId } : {},
896
+ ...typeof data.siwe === "string" ? { siwe: data.siwe } : {},
897
+ ...typeof data.signature === "string" ? { signature: data.signature } : {}
898
+ };
899
+ }
900
+ function portableFromCallback(data, permissions, host) {
901
+ const primary = permissions.find((permission) => permission.service !== "tinycloud.encryption") ?? permissions[0];
902
+ if (primary === void 0) throw new Error("The authority request has no permissions.");
903
+ const session = sessionFromCallback(data, {});
904
+ const expiry = delegationExpiry(data);
905
+ return {
906
+ cid: session.delegationCid,
907
+ delegationHeader: session.delegationHeader,
908
+ spaceId: session.spaceId,
909
+ path: primary.path,
910
+ actions: [...primary.actions],
911
+ resources: permissions.map((permission) => ({
912
+ service: permission.service.startsWith("tinycloud.") ? permission.service.slice("tinycloud.".length) : permission.service,
913
+ space: permission.service === "tinycloud.encryption" ? requiredPermissionSpace(permission) : session.spaceId,
914
+ path: permission.path,
915
+ actions: [...permission.actions]
916
+ })),
917
+ expiry,
918
+ delegateDID: session.verificationMethod,
919
+ ownerAddress: typeof data.address === "string" ? data.address : "",
920
+ chainId: typeof data.chainId === "number" ? data.chainId : 1,
921
+ host
922
+ };
923
+ }
924
+ function delegationExpiry(data) {
925
+ for (const key of ["expiry", "expiresAt", "expirationTime"]) {
926
+ const parsed = parseDate(data[key]);
927
+ if (parsed !== void 0) return parsed;
928
+ }
929
+ if (typeof data.siwe === "string") {
930
+ const match = data.siwe.match(/^Expiration Time:\s*(.+)$/im);
931
+ const parsed = parseDate(match?.[1]?.trim());
932
+ if (parsed !== void 0) return parsed;
933
+ }
934
+ throw new Error("OpenKey did not return a delegation expiry.");
935
+ }
936
+ function permissionsCover(requested, granted) {
937
+ return requested.every((request) => granted.some(
938
+ (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))
939
+ ));
940
+ }
941
+ function sameSpace(granted, requested) {
942
+ return granted === requested || granted.endsWith(`:${requested}`);
943
+ }
944
+ function normalizeService(service) {
945
+ return service.startsWith("tinycloud.") ? service : `tinycloud.${service}`;
946
+ }
947
+ function requiredPermissionSpace(permission) {
948
+ if (typeof permission.space !== "string") throw new Error("The authority request has no space.");
949
+ return permission.space;
950
+ }
951
+ function publicJwk(jwk) {
952
+ const copy = { ...jwk };
953
+ for (const field of ["d", "p", "q", "dp", "dq", "qi", "oth", "k"]) delete copy[field];
954
+ return copy;
955
+ }
956
+ function samePrincipal(left, right) {
957
+ if (typeof left !== "string") return false;
958
+ try {
959
+ return principalDidEquals(left, right);
960
+ } catch {
961
+ return false;
962
+ }
963
+ }
964
+ function normalizeDid(value) {
965
+ return value.split("#", 1)[0];
966
+ }
967
+ function isPermissionEntry(value) {
968
+ 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");
969
+ }
970
+ function isRecord(value) {
971
+ return typeof value === "object" && value !== null && !Array.isArray(value);
972
+ }
973
+ function parseDate(value) {
974
+ if (typeof value !== "string" && typeof value !== "number") return void 0;
975
+ const date = new Date(typeof value === "number" && value < 1e10 ? value * 1e3 : value);
976
+ return Number.isNaN(date.getTime()) ? void 0 : date;
977
+ }
978
+ async function secureDirectory(path) {
979
+ await mkdir(path, { recursive: true, mode: 448 });
980
+ await chmod(path, 448);
981
+ }
982
+ async function secureWrite(path, value) {
983
+ const directory = dirname(path);
984
+ await secureDirectory(directory);
985
+ const temporary = `${path}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
986
+ await writeFile(temporary, `${JSON.stringify(value, jsonReplacer, 2)}
987
+ `, { mode: 384 });
988
+ await rename(temporary, path);
989
+ await chmod(path, 384);
990
+ }
991
+ function jsonReplacer(_key, value) {
992
+ return value instanceof Date ? value.toISOString() : value;
993
+ }
994
+ async function readJson(path) {
995
+ try {
996
+ return JSON.parse(await readFile(path, "utf8"));
997
+ } catch (error) {
998
+ if (isRecord(error) && error.code === "ENOENT") return null;
999
+ throw error;
1000
+ }
1001
+ }
1002
+ async function fileExists(path) {
1003
+ return await readJson(path) !== null;
1004
+ }
1005
+ async function reusablePending(directory, expected) {
1006
+ let names;
1007
+ try {
1008
+ names = await readdir(directory);
1009
+ } catch (error) {
1010
+ if (isRecord(error) && error.code === "ENOENT") return void 0;
1011
+ throw error;
1012
+ }
1013
+ const active = [];
1014
+ for (const name of names) {
1015
+ if (!name.endsWith(".json")) continue;
1016
+ const path = join2(directory, name);
1017
+ const pending = await readJson(path).catch(() => null);
1018
+ if (pending === null || new Date(pending.expiresAt).getTime() <= Date.now()) {
1019
+ await rm(path, { force: true });
1020
+ continue;
1021
+ }
1022
+ active.push(pending);
1023
+ if (samePendingRequest(pending, expected)) return pending;
1024
+ }
1025
+ if (active.length >= 64) {
1026
+ active.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt));
1027
+ await rm(join2(directory, `${active[0].nonce}.json`), { force: true });
1028
+ }
1029
+ return void 0;
1030
+ }
1031
+ function samePendingRequest(pending, expected) {
1032
+ 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);
1033
+ }
1034
+
1035
+ // src/http.ts
1036
+ var REQUIRED_SCOPE = "tinycloud:mcp";
1037
+ function createHostedMcpApp(config) {
1038
+ const resourceUrl = canonicalResourceUrl(config.publicUrl);
1039
+ const issuer = String(config.oauthMetadata.issuer);
1040
+ const jwksUri = String(config.oauthMetadata.jwks_uri);
1041
+ const verifier = createOpenKeyTokenVerifier({
1042
+ issuer,
1043
+ audience: resourceUrl.toString(),
1044
+ jwksUri,
1045
+ requiredScope: REQUIRED_SCOPE
1046
+ });
1047
+ const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(resourceUrl);
1048
+ const authenticate = requireBearerAuth({
1049
+ verifier,
1050
+ requiredScopes: [REQUIRED_SCOPE],
1051
+ resourceMetadataUrl
1052
+ });
1053
+ const store = new RemoteTenantStore({ ...config, publicUrl: resourceUrl });
1054
+ const handler = createMcpHandler(async ({ authInfo: authInfo2 }) => {
1055
+ const identity = oauthIdentity(authInfo2);
1056
+ const { subject, ownerDids } = identity;
1057
+ const stateRoot = store.tenantStateRoot(subject);
1058
+ const validator = createJsonSchemaValidator();
1059
+ const server = new McpServer2(
1060
+ { name: MCP_SERVER_NAME, version: MCP_VERSION },
1061
+ {
1062
+ jsonSchemaValidator: validator,
1063
+ instructions: "Call tinycloud_connect first. If an operation returns authority_required, open approval.url, then retry that operation unchanged."
1064
+ }
1065
+ );
1066
+ registerTinyCloudTools(server, {
1067
+ profile: "agent",
1068
+ explicitProfile: true,
1069
+ allowOwnerProfile: false,
1070
+ stateRoot,
1071
+ transformOperationResult: (result) => store.decorateAuthorityResult(subject, ownerDids, result)
1072
+ }, validator);
1073
+ registerConnectTool(server, validator, store, identity);
1074
+ return server;
1075
+ }, {
1076
+ legacy: "stateless",
1077
+ onerror: () => writeDiagnostic("MCP request failed")
1078
+ });
1079
+ const metadataOptions = {
1080
+ oauthMetadata: config.oauthMetadata,
1081
+ resourceServerUrl: resourceUrl,
1082
+ serviceDocumentationUrl: new URL("https://docs.tinycloud.xyz/cli/mcp"),
1083
+ scopesSupported: [REQUIRED_SCOPE],
1084
+ resourceName: "TinyCloud hosted MCP"
1085
+ };
1086
+ const allowedHosts = [resourceUrl.hostname];
1087
+ return {
1088
+ async fetch(request) {
1089
+ const metadata = oauthMetadataResponse(request, metadataOptions);
1090
+ if (metadata !== void 0) return metadata;
1091
+ const url = new URL(request.url);
1092
+ if (url.pathname === "/healthz") {
1093
+ return request.method === "GET" ? json({ ok: true }) : methodNotAllowed("GET");
1094
+ }
1095
+ const hostFailure = hostHeaderValidationResponse(request, allowedHosts);
1096
+ if (hostFailure !== void 0) return hostFailure;
1097
+ if (url.pathname === "/connect") {
1098
+ if (request.method !== "GET") return methodNotAllowed("GET");
1099
+ try {
1100
+ const destination = await store.approvalRedirect(requiredState(url));
1101
+ return Response.redirect(destination, 302);
1102
+ } catch {
1103
+ return json({ error: "The approval link is invalid or expired." }, 400);
1104
+ }
1105
+ }
1106
+ if (url.pathname === "/connect/callback") {
1107
+ if (request.method === "OPTIONS") return callbackCors(new Response(null, { status: 204 }), config.openkeyHost);
1108
+ if (request.method !== "POST") return methodNotAllowed("POST");
1109
+ const originFailure2 = validateCallbackOrigin(request, config.openkeyHost);
1110
+ if (originFailure2 !== void 0) return callbackCors(originFailure2, config.openkeyHost);
1111
+ try {
1112
+ await store.completeApproval(requiredState(url), request);
1113
+ return callbackCors(json({ success: true }), config.openkeyHost);
1114
+ } catch {
1115
+ return callbackCors(json({ error: "TinyCloud could not accept this delegation." }, 400), config.openkeyHost);
1116
+ }
1117
+ }
1118
+ if (url.pathname !== resourceUrl.pathname) return json({ error: "Not found" }, 404);
1119
+ const originFailure = validateOrigin(request, config.allowedOrigins);
1120
+ if (originFailure !== void 0) return originFailure;
1121
+ const auth = await authenticate(request);
1122
+ if (auth instanceof Response) return auth;
1123
+ return handler.fetch(request, { authInfo: auth });
1124
+ },
1125
+ close: () => handler.close()
1126
+ };
1127
+ }
1128
+ function registerConnectTool(server, validator, store, identity) {
1129
+ const inputSchema = fromJsonSchema2({ type: "object", properties: {}, additionalProperties: false }, validator);
1130
+ const outputSchema = fromJsonSchema2({
1131
+ type: "object",
1132
+ properties: {
1133
+ connected: { type: "boolean" },
1134
+ sessionDid: { type: "string" },
1135
+ approvalUrl: { type: "string", format: "uri" },
1136
+ expiresAt: { type: "string", format: "date-time" }
1137
+ },
1138
+ required: ["connected", "sessionDid"],
1139
+ additionalProperties: false
1140
+ }, validator);
1141
+ server.registerTool(
1142
+ "tinycloud_connect",
1143
+ {
1144
+ title: "Connect TinyCloud",
1145
+ description: "Check the hosted delegate connection and return a one-time OpenKey approval URL when setup is required.",
1146
+ inputSchema,
1147
+ outputSchema,
1148
+ annotations: {
1149
+ readOnlyHint: false,
1150
+ idempotentHint: true,
1151
+ destructiveHint: false,
1152
+ openWorldHint: true
1153
+ }
1154
+ },
1155
+ async () => {
1156
+ const status = await store.connectStatus(identity.subject, identity.ownerDids);
1157
+ return {
1158
+ content: [{
1159
+ type: "text",
1160
+ text: status.connected ? "TinyCloud is connected." : "TinyCloud approval is required; open approvalUrl, then call this tool again."
1161
+ }],
1162
+ structuredContent: status
1163
+ };
1164
+ }
1165
+ );
1166
+ }
1167
+ function oauthIdentity(authInfo2) {
1168
+ const subject = authInfo2?.extra?.subject;
1169
+ if (typeof subject !== "string" || subject.length === 0) {
1170
+ throw new Error("The authenticated MCP request has no OpenKey subject.");
1171
+ }
1172
+ const ownerDids = authInfo2?.extra?.ownerDids;
1173
+ if (!Array.isArray(ownerDids) || ownerDids.length === 0 || !ownerDids.every((did) => typeof did === "string")) {
1174
+ throw new Error("The authenticated MCP request has no OpenKey owner identity.");
1175
+ }
1176
+ return { subject, ownerDids };
1177
+ }
1178
+ function canonicalResourceUrl(url) {
1179
+ const resource = new URL(url);
1180
+ resource.hash = "";
1181
+ resource.search = "";
1182
+ resource.pathname = resource.pathname.replace(/\/+$/, "") || "/mcp";
1183
+ if (resource.pathname === "/") resource.pathname = "/mcp";
1184
+ return resource;
1185
+ }
1186
+ function requiredState(url) {
1187
+ const state = url.searchParams.get("state");
1188
+ if (state === null || state.length > 512) throw new Error("Missing approval state.");
1189
+ return state;
1190
+ }
1191
+ function validateOrigin(request, allowed) {
1192
+ const origin = request.headers.get("origin");
1193
+ if (origin === null) return void 0;
1194
+ const allowlist = allowed ?? [];
1195
+ return allowlist.includes(origin) ? void 0 : json({ error: "Origin is not allowed." }, 403);
1196
+ }
1197
+ function validateCallbackOrigin(request, openkeyHost) {
1198
+ const origin = request.headers.get("origin");
1199
+ return origin === null || origin === new URL(openkeyHost).origin ? void 0 : json({ error: "Origin is not allowed." }, 403);
1200
+ }
1201
+ function callbackCors(response, openkeyHost) {
1202
+ const headers = new Headers(response.headers);
1203
+ headers.set("access-control-allow-origin", new URL(openkeyHost).origin);
1204
+ headers.set("access-control-allow-methods", "POST, OPTIONS");
1205
+ headers.set("access-control-allow-headers", "content-type");
1206
+ headers.set("vary", "Origin");
1207
+ return new Response(response.body, { status: response.status, headers });
1208
+ }
1209
+ function json(value, status = 200) {
1210
+ return Response.json(value, { status, headers: { "cache-control": "no-store" } });
1211
+ }
1212
+ function methodNotAllowed(allow) {
1213
+ return new Response("Method not allowed", { status: 405, headers: { allow } });
1214
+ }
1215
+ function writeDiagnostic(message) {
1216
+ process.stderr.write(`[tinycloud-mcp-http] ${message}
1217
+ `);
1218
+ }
482
1219
  export {
483
1220
  MCP_SERVER_NAME,
484
1221
  MCP_VERSION,
485
1222
  TOOL_NAMES,
486
1223
  canonicalMcpAdapterResult,
1224
+ createHostedMcpApp,
487
1225
  createTinyCloudMcpServer,
488
1226
  main,
489
1227
  parseCliOptions,