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