@tinycloud/mcp 0.5.2 → 0.5.3-beta.1

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/http-cli.ts","../src/http.ts","../src/oauth.ts","../src/remote-store.ts","../src/server.ts","../src/tools.ts","../src/results.ts","../package.json","../src/version.ts"],"sourcesContent":["import { createServer } from \"node:http\";\nimport { isAbsolute, resolve } from \"node:path\";\n\nimport { toNodeHandler } from \"@modelcontextprotocol/node\";\n\nimport { createHostedMcpApp } from \"./http.js\";\nimport { loadOAuthMetadata } from \"./oauth.js\";\n\nexport async function main(): Promise<void> {\n process.umask(0o077);\n const publicUrl = requiredUrl(\"TC_MCP_PUBLIC_URL\");\n const stateDir = requiredAbsolutePath(\"TC_MCP_STATE_DIR\");\n const stateSecret = requiredString(\"TC_MCP_STATE_SECRET\");\n if (Buffer.byteLength(stateSecret) < 32) throw new Error(\"TC_MCP_STATE_SECRET must contain at least 32 bytes.\");\n const openkeyHost = process.env.TC_OPENKEY_HOST ?? \"https://openkey.so\";\n const oauthMetadataUrl = new URL(\n process.env.TC_MCP_OAUTH_METADATA_URL ??\n \"https://api.openkey.so/.well-known/oauth-authorization-server/api/auth\",\n );\n const oauthMetadata = await loadOAuthMetadata(oauthMetadataUrl);\n const app = createHostedMcpApp({\n publicUrl,\n stateDir,\n stateSecret,\n nodeHost: process.env.TC_HOST ?? \"https://tee.node.tinycloud.xyz\",\n openkeyHost,\n approvalTtlSeconds: positiveInteger(process.env.TC_MCP_APPROVAL_TTL_SECONDS, 300),\n delegationExpiry: process.env.TC_MCP_DELEGATION_EXPIRY ?? \"1h\",\n allowedOrigins: commaList(process.env.TC_MCP_ALLOWED_ORIGINS),\n oauthMetadata,\n });\n const nodeHandler = toNodeHandler(app);\n const server = createServer(nodeHandler);\n const host = process.env.HOST ?? \"0.0.0.0\";\n const port = positiveInteger(process.env.PORT, 3000);\n server.listen(port, host, () => {\n process.stderr.write(`[tinycloud-mcp-http] listening on ${host}:${port}\\n`);\n });\n const shutdown = () => {\n server.close(() => void app.close());\n };\n process.once(\"SIGINT\", shutdown);\n process.once(\"SIGTERM\", shutdown);\n}\n\nfunction requiredString(name: string): string {\n const value = process.env[name]?.trim();\n if (!value) throw new Error(`${name} is required.`);\n return value;\n}\n\nfunction requiredUrl(name: string): URL {\n const url = new URL(requiredString(name));\n if (url.protocol !== \"https:\" && url.hostname !== \"localhost\" && url.hostname !== \"127.0.0.1\") {\n throw new Error(`${name} must use HTTPS outside localhost.`);\n }\n return url;\n}\n\nfunction requiredAbsolutePath(name: string): string {\n const value = requiredString(name);\n if (!isAbsolute(value)) throw new Error(`${name} must be an absolute path.`);\n return resolve(value);\n}\n\nfunction positiveInteger(value: string | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed <= 0) throw new Error(\"Expected a positive integer environment value.\");\n return parsed;\n}\n\nfunction commaList(value: string | undefined): string[] | undefined {\n if (value === undefined) return undefined;\n return value.split(\",\").map((entry) => entry.trim()).filter(Boolean);\n}\n\nvoid main().catch(() => {\n process.stderr.write(\"[tinycloud-mcp-http] Startup failed.\\n\");\n process.exitCode = 1;\n});\n","import {\n McpServer,\n createMcpHandler,\n fromJsonSchema,\n getOAuthProtectedResourceMetadataUrl,\n hostHeaderValidationResponse,\n oauthMetadataResponse,\n requireBearerAuth,\n type AuthInfo,\n type OAuthMetadata,\n} from \"@modelcontextprotocol/server\";\n\nimport { createOpenKeyTokenVerifier } from \"./oauth.js\";\nimport { ApprovalOwnerMismatchError, RemoteTenantStore, type RemoteStoreConfig } from \"./remote-store.js\";\nimport { MCP_SERVER_NAME } from \"./server.js\";\nimport { createJsonSchemaValidator, registerTinyCloudTools } from \"./tools.js\";\nimport { MCP_VERSION } from \"./version.js\";\n\nconst REQUIRED_SCOPE = \"tinycloud:mcp\";\n\nexport interface HostedMcpConfig extends RemoteStoreConfig {\n readonly oauthMetadata: OAuthMetadata;\n readonly allowedOrigins?: readonly string[];\n}\n\nexport interface HostedMcpApp {\n readonly fetch: (request: Request) => Promise<Response>;\n readonly close: () => Promise<void>;\n}\n\nexport function createHostedMcpApp(config: HostedMcpConfig): HostedMcpApp {\n const resourceUrl = canonicalResourceUrl(config.publicUrl);\n const issuer = String(config.oauthMetadata.issuer);\n const jwksUri = String(config.oauthMetadata.jwks_uri);\n const verifier = createOpenKeyTokenVerifier({\n issuer,\n audience: resourceUrl.toString(),\n jwksUri,\n requiredScope: REQUIRED_SCOPE,\n });\n const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(resourceUrl);\n const authenticate = requireBearerAuth({\n verifier,\n requiredScopes: [REQUIRED_SCOPE],\n resourceMetadataUrl,\n });\n const store = new RemoteTenantStore({ ...config, publicUrl: resourceUrl });\n const handler = createMcpHandler(async ({ authInfo }) => {\n const identity = oauthIdentity(authInfo);\n const { subject, ownerDids } = identity;\n const stateRoot = store.tenantStateRoot(subject);\n const validator = createJsonSchemaValidator();\n const server = new McpServer(\n { name: MCP_SERVER_NAME, version: MCP_VERSION },\n {\n jsonSchemaValidator: validator,\n instructions: \"Call tinycloud_connect first. If an operation returns authority_required, open approval.url, then retry that operation unchanged.\",\n },\n );\n registerTinyCloudTools(server, {\n surface: \"hosted\",\n profile: \"agent\",\n explicitProfile: true,\n allowOwnerProfile: false,\n stateRoot,\n transformOperationResult: (result) => store.decorateAuthorityResult(subject, ownerDids, result),\n }, validator);\n registerConnectTool(server, validator, store, identity);\n return server;\n }, {\n legacy: \"stateless\",\n onerror: () => writeDiagnostic(\"MCP request failed\"),\n });\n\n const metadataOptions = {\n oauthMetadata: config.oauthMetadata,\n resourceServerUrl: resourceUrl,\n serviceDocumentationUrl: new URL(\"https://docs.tinycloud.xyz/cli/mcp\"),\n scopesSupported: [REQUIRED_SCOPE],\n resourceName: \"TinyCloud hosted MCP\",\n };\n const allowedHosts = [resourceUrl.hostname];\n\n return {\n async fetch(request: Request): Promise<Response> {\n const metadata = oauthMetadataResponse(request, metadataOptions);\n if (metadata !== undefined) return metadata;\n const url = new URL(request.url);\n if (url.pathname === \"/healthz\") {\n return request.method === \"GET\"\n ? json({ ok: true })\n : methodNotAllowed(\"GET\");\n }\n const hostFailure = hostHeaderValidationResponse(request, allowedHosts);\n if (hostFailure !== undefined) return hostFailure;\n\n if (url.pathname === \"/connect\") {\n if (request.method !== \"GET\") return methodNotAllowed(\"GET\");\n try {\n const destination = await store.approvalRedirect(requiredState(url));\n return Response.redirect(destination, 302);\n } catch {\n return json({ error: \"The approval link is invalid or expired.\" }, 400);\n }\n }\n if (url.pathname === \"/connect/callback\") {\n if (request.method === \"OPTIONS\") return callbackCors(new Response(null, { status: 204 }), config.openkeyHost);\n if (request.method !== \"POST\") return methodNotAllowed(\"POST\");\n const originFailure = validateCallbackOrigin(request, config.openkeyHost);\n if (originFailure !== undefined) return callbackCors(originFailure, config.openkeyHost);\n try {\n await store.completeApproval(requiredState(url), request);\n return callbackCors(json({ success: true }), config.openkeyHost);\n } catch (error) {\n // Only fixed server-authored text reaches OpenKey; callback input is never echoed.\n return callbackCors(\n error instanceof ApprovalOwnerMismatchError\n ? json({ error: error.message, code: \"approval_owner_mismatch\" }, 403)\n : json({ error: \"TinyCloud could not accept this delegation.\" }, 400),\n config.openkeyHost,\n );\n }\n }\n if (url.pathname !== resourceUrl.pathname) return json({ error: \"Not found\" }, 404);\n const originFailure = validateOrigin(request, config.allowedOrigins);\n if (originFailure !== undefined) return originFailure;\n const auth = await authenticate(request);\n if (auth instanceof Response) return auth;\n return handler.fetch(request, { authInfo: auth });\n },\n close: () => handler.close(),\n };\n}\n\nfunction registerConnectTool(\n server: McpServer,\n validator: ReturnType<typeof createJsonSchemaValidator>,\n store: RemoteTenantStore,\n identity: OAuthIdentity,\n): void {\n const inputSchema = fromJsonSchema({ type: \"object\", properties: {}, additionalProperties: false }, validator);\n const outputSchema = fromJsonSchema({\n type: \"object\",\n properties: {\n connected: { type: \"boolean\" },\n sessionDid: { type: \"string\" },\n approvalUrl: { type: \"string\", format: \"uri\" },\n expiresAt: { type: \"string\", format: \"date-time\" },\n },\n required: [\"connected\", \"sessionDid\"],\n additionalProperties: false,\n }, validator);\n server.registerTool(\n \"tinycloud_connect\",\n {\n title: \"Connect TinyCloud\",\n description: \"Check the hosted delegate connection and return a one-time OpenKey approval URL when setup is required.\",\n inputSchema,\n outputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n },\n async () => {\n const status = await store.connectStatus(identity.subject, identity.ownerDids);\n return {\n content: [{\n type: \"text\" as const,\n text: status.connected\n ? \"TinyCloud is connected.\"\n : \"TinyCloud approval is required; open approvalUrl, then call this tool again.\",\n }],\n structuredContent: status,\n };\n },\n );\n}\n\ninterface OAuthIdentity {\n readonly subject: string;\n readonly ownerDids: string[];\n}\n\nfunction oauthIdentity(authInfo: AuthInfo | undefined): OAuthIdentity {\n const subject = authInfo?.extra?.subject;\n if (typeof subject !== \"string\" || subject.length === 0) {\n throw new Error(\"The authenticated MCP request has no OpenKey subject.\");\n }\n const ownerDids = authInfo?.extra?.ownerDids;\n if (!Array.isArray(ownerDids) || ownerDids.length === 0 ||\n !ownerDids.every((did) => typeof did === \"string\")) {\n throw new Error(\"The authenticated MCP request has no OpenKey owner identity.\");\n }\n return { subject, ownerDids };\n}\n\nfunction canonicalResourceUrl(url: URL): URL {\n const resource = new URL(url);\n resource.hash = \"\";\n resource.search = \"\";\n resource.pathname = resource.pathname.replace(/\\/+$/, \"\") || \"/mcp\";\n if (resource.pathname === \"/\") resource.pathname = \"/mcp\";\n return resource;\n}\n\nfunction requiredState(url: URL): string {\n const state = url.searchParams.get(\"state\");\n if (state === null || state.length > 512) throw new Error(\"Missing approval state.\");\n return state;\n}\n\nfunction validateOrigin(request: Request, allowed: readonly string[] | undefined): Response | undefined {\n const origin = request.headers.get(\"origin\");\n if (origin === null) return undefined;\n const allowlist = allowed ?? [];\n return allowlist.includes(origin) ? undefined : json({ error: \"Origin is not allowed.\" }, 403);\n}\n\nfunction validateCallbackOrigin(request: Request, openkeyHost: string): Response | undefined {\n const origin = request.headers.get(\"origin\");\n return origin === null || origin === new URL(openkeyHost).origin\n ? undefined\n : json({ error: \"Origin is not allowed.\" }, 403);\n}\n\nfunction callbackCors(response: Response, openkeyHost: string): Response {\n const headers = new Headers(response.headers);\n headers.set(\"access-control-allow-origin\", new URL(openkeyHost).origin);\n headers.set(\"access-control-allow-methods\", \"POST, OPTIONS\");\n headers.set(\"access-control-allow-headers\", \"content-type\");\n headers.set(\"vary\", \"Origin\");\n return new Response(response.body, { status: response.status, headers });\n}\n\nfunction json(value: unknown, status = 200): Response {\n return Response.json(value, { status, headers: { \"cache-control\": \"no-store\" } });\n}\n\nfunction methodNotAllowed(allow: string): Response {\n return new Response(\"Method not allowed\", { status: 405, headers: { allow } });\n}\n\nfunction writeDiagnostic(message: string): void {\n process.stderr.write(`[tinycloud-mcp-http] ${message}\\n`);\n}\n","import {\n OAuthError,\n OAuthErrorCode,\n type AuthInfo,\n type OAuthMetadata,\n type OAuthTokenVerifier,\n} from \"@modelcontextprotocol/server\";\nimport { pkhDid } from \"@tinycloud/node-sdk\";\nimport { createRemoteJWKSet, errors, jwtVerify, type JWTPayload } from \"jose\";\n\nconst OWNER_DIDS_CLAIM = \"https://tinycloud.xyz/owner_dids\";\n\nexport interface OpenKeyOAuthConfig {\n readonly issuer: string;\n readonly audience: string;\n readonly jwksUri: string;\n readonly requiredScope?: string;\n}\n\nexport function createOpenKeyTokenVerifier(config: OpenKeyOAuthConfig): OAuthTokenVerifier {\n const jwks = createRemoteJWKSet(new URL(config.jwksUri));\n return {\n async verifyAccessToken(token: string): Promise<AuthInfo> {\n try {\n const { payload } = await jwtVerify(token, jwks, {\n issuer: config.issuer,\n audience: config.audience,\n });\n return authInfo(token, payload, config);\n } catch (error) {\n if (error instanceof errors.JOSEError) {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token is invalid.\");\n }\n throw error;\n }\n },\n };\n}\n\nexport async function loadOAuthMetadata(metadataUrl: URL): Promise<OAuthMetadata> {\n const response = await fetch(metadataUrl, {\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) throw new Error(\"OpenKey OAuth discovery failed.\");\n const metadata = await response.json() as OAuthMetadata;\n if (typeof metadata.issuer !== \"string\" || typeof metadata.jwks_uri !== \"string\") {\n throw new Error(\"OpenKey OAuth metadata is incomplete.\");\n }\n return metadata;\n}\n\nfunction authInfo(\n token: string,\n payload: JWTPayload,\n config: OpenKeyOAuthConfig,\n): AuthInfo {\n if (typeof payload.sub !== \"string\" || payload.sub.length === 0) {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token does not identify a subject.\");\n }\n if (typeof payload.exp !== \"number\") {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token has no expiry.\");\n }\n const scopes = typeof payload.scope === \"string\"\n ? payload.scope.split(/\\s+/).filter(Boolean)\n : [];\n if (config.requiredScope !== undefined && !scopes.includes(config.requiredScope)) {\n throw new OAuthError(\n OAuthErrorCode.InsufficientScope,\n \"The OpenKey access token is missing the TinyCloud MCP scope.\",\n );\n }\n const clientId = firstString(payload.azp, payload.client_id) ?? \"unknown\";\n const ownerDids = canonicalOwnerDids(payload[OWNER_DIDS_CLAIM]);\n if (ownerDids === undefined) {\n throw new OAuthError(\n OAuthErrorCode.InvalidToken,\n \"The OpenKey access token has no valid TinyCloud owner identity.\",\n );\n }\n return {\n token,\n clientId,\n scopes,\n expiresAt: payload.exp,\n resource: new URL(config.audience),\n extra: {\n subject: payload.sub,\n ownerDids,\n },\n };\n}\n\n/**\n * OpenKey issues owner DIDs as `did:pkh:eip155:<chain>:<address>`. Only that\n * exact syntax is accepted, canonicalised, and passed on to owner comparison\n * and the approval text. One malformed value refuses the whole claim rather\n * than being skipped.\n */\nconst OWNER_DID = /^did:pkh:eip155:([1-9][0-9]{0,15}):(0x[0-9a-fA-F]{40})$/;\n\nfunction canonicalOwnerDids(claim: unknown): string[] | undefined {\n if (!Array.isArray(claim) || claim.length === 0) return undefined;\n const ownerDids: string[] = [];\n for (const value of claim) {\n const match = typeof value === \"string\" ? OWNER_DID.exec(value) : null;\n if (match === null) return undefined;\n try {\n ownerDids.push(pkhDid(match[2]!, Number(match[1])));\n } catch {\n return undefined;\n }\n }\n return [...new Set(ownerDids)];\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n return values.find((value): value is string => typeof value === \"string\" && value.length > 0);\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { chmod, mkdir, readFile, readdir, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\nimport {\n TinyCloudNode,\n isCapabilitySubset,\n principalDidEquals,\n siweRuntimeDelegation,\n type PermissionEntry,\n type TinyCloudSession,\n} from \"@tinycloud/node-sdk\";\nimport { TCWSessionManager, importKey, initPanicHook } from \"@tinycloud/node-sdk-wasm\";\nimport { invokeOperation } from \"@tinycloud/operations\";\n\nconst PROFILE = \"agent\";\nconst MAX_CALLBACK_BYTES = 256 * 1024;\nconst BOOTSTRAP_PERMISSIONS: PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: \"account\",\n path: \"spaces/\",\n actions: [\"tinycloud.kv/get\", \"tinycloud.kv/list\"],\n },\n {\n service: \"tinycloud.kv\",\n space: \"account\",\n path: \"applications/\",\n actions: [\"tinycloud.kv/get\", \"tinycloud.kv/list\"],\n },\n];\n\nexport interface RemoteStoreConfig {\n readonly stateDir: string;\n readonly stateSecret: string;\n readonly publicUrl: URL;\n readonly nodeHost: string;\n readonly openkeyHost: string;\n readonly approvalTtlSeconds: number;\n readonly delegationExpiry: string;\n}\n\ninterface TenantProfile {\n readonly stateRoot: string;\n readonly sessionDid: string;\n readonly jwk: Record<string, unknown>;\n}\n\ninterface PendingApproval {\n readonly version: 1;\n readonly nonce: string;\n readonly tenantId: string;\n readonly kind: \"bootstrap\" | \"delegation\";\n readonly requestId?: string;\n readonly permissions: PermissionEntry[];\n readonly ownerDids: string[];\n readonly createdAt: string;\n readonly expiresAt: string;\n}\n\nexport interface ConnectStatus {\n readonly connected: boolean;\n readonly sessionDid: string;\n readonly approvalUrl?: string;\n readonly expiresAt?: string;\n}\n\ninterface CallbackSession {\n readonly delegationHeader: { Authorization: string };\n readonly delegationCid: string;\n readonly spaceId: string;\n readonly jwk: Record<string, unknown>;\n readonly verificationMethod: string;\n readonly address: string;\n readonly chainId: number;\n readonly siwe: string;\n readonly signature: string;\n}\n\n/**\n * The approving wallet is not the OpenKey principal whose MCP request created\n * the approval link. The message is static so callers may show it verbatim.\n */\nexport class ApprovalOwnerMismatchError extends Error {\n constructor() {\n super(\"This approval link was requested by a different TinyCloud account, so the delegation was not stored.\");\n this.name = \"ApprovalOwnerMismatchError\";\n }\n}\n\nexport class RemoteTenantStore {\n readonly #config: RemoteStoreConfig;\n readonly #initializing = new Map<string, Promise<TenantProfile>>();\n\n constructor(config: RemoteStoreConfig) {\n this.#config = config;\n }\n\n tenantStateRoot(subject: string): string {\n return join(this.#config.stateDir, \"tenants\", this.#tenantId(subject));\n }\n\n async connectStatus(subject: string, ownerDids: readonly string[] = []): Promise<ConnectStatus> {\n const tenant = await this.#ensureTenant(subject);\n if (await this.#hasValidSession(tenant, ownerDids)) {\n return { connected: true, sessionDid: tenant.sessionDid };\n }\n const pending = await this.#createPending(subject, ownerDids, \"bootstrap\", BOOTSTRAP_PERMISSIONS);\n return {\n connected: false,\n sessionDid: tenant.sessionDid,\n approvalUrl: this.#connectUrl(pending),\n expiresAt: pending.expiresAt,\n };\n }\n\n async decorateAuthorityResult(\n subject: string,\n ownerDids: readonly string[],\n result: unknown,\n ): Promise<unknown> {\n if (!isRecord(result) || result.status !== \"authority_required\") return result;\n const request = isRecord(result.request) ? result.request : undefined;\n const requestId = typeof request?.requestId === \"string\" ? request.requestId : undefined;\n const requested = Array.isArray(request?.requested)\n ? request.requested.filter(isPermissionEntry)\n : [];\n if (requestId === undefined || requested.length === 0) return result;\n const pending = await this.#createPending(subject, ownerDids, \"delegation\", requested, requestId);\n return {\n ...result,\n approval: {\n ...(isRecord(result.approval) ? result.approval : {}),\n kind: \"openkey\",\n requestId,\n url: this.#connectUrl(pending),\n fallback: \"Open the approval URL, then retry the same MCP tool.\",\n },\n };\n }\n\n async approvalRedirect(state: string): Promise<string> {\n const pending = await this.#readPending(state, false);\n const tenant = await this.#readTenant(pending.tenantId);\n const callback = new URL(\"/connect/callback\", this.#config.publicUrl);\n callback.searchParams.set(\"state\", state);\n const params = new URLSearchParams({\n did: tenant.sessionDid,\n callback: callback.toString(),\n host: this.#config.nodeHost,\n jwk: Buffer.from(JSON.stringify(publicJwk(tenant.jwk))).toString(\"base64url\"),\n permissions: Buffer.from(JSON.stringify({\n permissions: pending.permissions,\n reason: [\n pending.kind === \"bootstrap\"\n ? \"Connect this TinyCloud account to the hosted MCP delegate.\"\n : \"Approve the exact capabilities requested by the TinyCloud MCP operation.\",\n // Owner DIDs come from the verified OpenKey access token of the MCP\n // client that created this link, never from the link itself.\n ...(pending.ownerDids.length === 0\n ? []\n : [`Requested by TinyCloud account ${pending.ownerDids.join(\", \")}; approve only if that is you.`]),\n ].join(\" \"),\n })).toString(\"base64url\"),\n expiry: this.#config.delegationExpiry,\n });\n return `${this.#config.openkeyHost.replace(/\\/+$/, \"\")}/delegate?${params.toString()}`;\n }\n\n async completeApproval(state: string, request: Request): Promise<void> {\n const length = Number(request.headers.get(\"content-length\") ?? \"0\");\n if (Number.isFinite(length) && length > MAX_CALLBACK_BYTES) throw new Error(\"Callback body is too large.\");\n const text = await request.text();\n if (Buffer.byteLength(text) > MAX_CALLBACK_BYTES) throw new Error(\"Callback body is too large.\");\n const data = JSON.parse(text) as unknown;\n if (!isRecord(data)) throw new Error(\"Callback body is invalid.\");\n\n const pending = await this.#readPending(state, true);\n try {\n const tenant = await this.#readTenant(pending.tenantId);\n if (pending.kind === \"bootstrap\") {\n await this.#storeBootstrap(tenant, pending, data);\n } else {\n await this.#storeDelegation(tenant, pending, data);\n }\n await rm(this.#pendingPath(tenant.stateRoot, pending.nonce) + \".processing\", { force: true });\n } catch (error) {\n await this.#restorePending(pending).catch(() => undefined);\n throw error;\n }\n }\n\n async #storeBootstrap(\n tenant: TenantProfile,\n pending: PendingApproval,\n data: Record<string, unknown>,\n ): Promise<void> {\n const { node, session } = await this.#restoreApproval(tenant, data);\n if (pending.ownerDids.length > 0 && !pending.ownerDids.some((did) => samePrincipal(node.did, did))) {\n throw new ApprovalOwnerMismatchError();\n }\n // The verifier reports one entry per signed action; the SDK subset check\n // judges each requested entry against every matching grant together.\n if (!isCapabilitySubset(pending.permissions, node.getVerifiedSessionCapabilities()).subset) {\n throw new Error(\"The approved delegation does not cover the requested account access.\");\n }\n const profile = await readJson<Record<string, unknown>>(this.#profilePath(tenant.stateRoot));\n await secureWrite(this.#profilePath(tenant.stateRoot), {\n ...profile,\n ownerDid: normalizeDid(node.did),\n spaceId: session.spaceId,\n });\n await secureWrite(this.#sessionPath(tenant.stateRoot), {\n authMethod: \"openkey\",\n ...session,\n });\n }\n\n async #storeDelegation(\n tenant: TenantProfile,\n pending: PendingApproval,\n data: Record<string, unknown>,\n ): Promise<void> {\n if (pending.requestId === undefined) throw new Error(\"Authority request is missing.\");\n // Unlike bootstrap there is no empty-list exemption: a delegation is only\n // imported when its verified signer is the OAuth principal that asked.\n const { node, session } = await this.#restoreApproval(tenant, data);\n if (!pending.ownerDids.some((did) => samePrincipal(node.did, did))) throw new ApprovalOwnerMismatchError();\n // OpenKey returns a signed-login (CACAO) delegation. Every field is\n // projected from the verified SIWE; `tinycloud.auth.import` verifies it\n // again and checks it stays within the stored request.\n const delegation = siweRuntimeDelegation(node, {\n authorization: session.delegationHeader.Authorization,\n cid: session.delegationCid,\n spaceId: session.spaceId,\n ownerAddress: session.address,\n chainId: session.chainId,\n siwe: session.siwe,\n signature: session.signature,\n host: this.#config.nodeHost,\n });\n const result = await invokeOperation(\n \"tinycloud.auth.import\",\n 1,\n { profile: PROFILE, stateRoot: tenant.stateRoot },\n {\n kind: \"tinycloud.auth.delegation\",\n version: 1,\n requestId: pending.requestId,\n delegationCid: delegation.cid,\n delegation,\n },\n );\n if (result.status !== \"ok\") throw new Error(\"TinyCloud rejected the approved delegation.\");\n }\n\n /**\n * Verify the OpenKey callback as a SIWE session for this tenant's key. The\n * callback must carry the full signed proof (SIWE, signature, address and\n * chain), so the WASM verifier always runs: it binds the authorization bytes\n * and CID to the signed SIWE, and `node.did` is the wallet that signed\n * exactly the delegation being stored.\n */\n async #restoreApproval(\n tenant: TenantProfile,\n data: Record<string, unknown>,\n ): Promise<{ node: TinyCloudNode; session: CallbackSession }> {\n const session = sessionFromCallback(data, tenant.jwk);\n const node = new TinyCloudNode({ host: this.#config.nodeHost });\n await node.restoreSession(session);\n if (!samePrincipal(node.sessionDid, tenant.sessionDid)) {\n throw new Error(\"The approved delegation targets a different session.\");\n }\n return { node, session };\n }\n\n async #ensureTenant(subject: string): Promise<TenantProfile> {\n const tenantId = this.#tenantId(subject);\n const current = this.#initializing.get(tenantId);\n if (current !== undefined) return current;\n const initializing = this.#initializeTenant(tenantId).finally(() => {\n this.#initializing.delete(tenantId);\n });\n this.#initializing.set(tenantId, initializing);\n return initializing;\n }\n\n async #hasValidSession(tenant: TenantProfile, ownerDids: readonly string[]): Promise<boolean> {\n const raw = await readJson<Record<string, unknown>>(this.#sessionPath(tenant.stateRoot));\n if (raw === null) return false;\n try {\n const node = new TinyCloudNode({ host: this.#config.nodeHost });\n await node.restoreSession(raw as unknown as TinyCloudSession);\n return samePrincipal(node.sessionDid, tenant.sessionDid) &&\n ownerDids.some((did) => samePrincipal(node.did, did));\n } catch {\n await rm(this.#sessionPath(tenant.stateRoot), { force: true });\n return false;\n }\n }\n\n async #initializeTenant(tenantId: string): Promise<TenantProfile> {\n const stateRoot = join(this.#config.stateDir, \"tenants\", tenantId);\n const keyPath = this.#keyPath(stateRoot);\n await secureDirectory(join(stateRoot, \".tinycloud\", \"profiles\", PROFILE));\n let jwk = await readJson<Record<string, unknown>>(keyPath);\n let sessionDid: string;\n if (jwk === null) {\n const generated = generateSessionKey();\n jwk = generated.jwk;\n sessionDid = generated.did;\n await secureWrite(keyPath, jwk);\n } else {\n sessionDid = didFromJwk(jwk);\n }\n const profilePath = this.#profilePath(stateRoot);\n if (!(await fileExists(profilePath))) {\n await secureWrite(profilePath, {\n name: PROFILE,\n host: this.#config.nodeHost,\n chainId: 1,\n spaceName: \"default\",\n did: sessionDid,\n sessionDid,\n createdAt: new Date().toISOString(),\n posture: \"delegate-session\",\n operatorType: \"agent\",\n authMethod: \"openkey\",\n openkeyHost: this.#config.openkeyHost,\n });\n }\n return { stateRoot, sessionDid, jwk };\n }\n\n async #readTenant(tenantId: string): Promise<TenantProfile> {\n if (!/^[a-f0-9]{64}$/.test(tenantId)) throw new Error(\"Approval state is invalid.\");\n const stateRoot = join(this.#config.stateDir, \"tenants\", tenantId);\n const jwk = await readJson<Record<string, unknown>>(this.#keyPath(stateRoot));\n if (jwk === null) throw new Error(\"The TinyCloud delegate no longer exists.\");\n return { stateRoot, jwk, sessionDid: didFromJwk(jwk) };\n }\n\n async #createPending(\n subject: string,\n ownerDids: readonly string[],\n kind: PendingApproval[\"kind\"],\n permissions: PermissionEntry[],\n requestId?: string,\n ): Promise<PendingApproval> {\n const tenant = await this.#ensureTenant(subject);\n const tenantId = this.#tenantId(subject);\n const reusable = await reusablePending(\n this.#pendingDirectory(tenant.stateRoot),\n { tenantId, kind, requestId, permissions, ownerDids: ownerDids.map(normalizeDid) },\n );\n if (reusable !== undefined) return reusable;\n const nonce = randomBytes(24).toString(\"base64url\");\n const created = Date.now();\n const pending: PendingApproval = {\n version: 1,\n nonce,\n tenantId,\n kind,\n ...(requestId === undefined ? {} : { requestId }),\n permissions,\n ownerDids: ownerDids.map(normalizeDid),\n createdAt: new Date(created).toISOString(),\n expiresAt: new Date(created + this.#config.approvalTtlSeconds * 1000).toISOString(),\n };\n await secureWrite(this.#pendingPath(tenant.stateRoot, nonce), pending);\n return pending;\n }\n\n async #readPending(state: string, consume: boolean): Promise<PendingApproval> {\n const [tenantId, nonce, signature] = state.split(\".\");\n if (tenantId === undefined || nonce === undefined || signature === undefined) {\n throw new Error(\"Approval state is invalid.\");\n }\n const expected = this.#signState(tenantId, nonce);\n const supplied = Buffer.from(signature, \"base64url\");\n const expectedBytes = Buffer.from(expected, \"base64url\");\n if (supplied.length !== expectedBytes.length || !timingSafeEqual(supplied, expectedBytes)) {\n throw new Error(\"Approval state is invalid.\");\n }\n const stateRoot = join(this.#config.stateDir, \"tenants\", tenantId);\n const path = this.#pendingPath(stateRoot, nonce);\n const claimed = `${path}.processing`;\n if (consume) await rename(path, claimed);\n try {\n const pending = await readJson<PendingApproval>(consume ? claimed : path);\n if (pending === null || pending.version !== 1 || pending.tenantId !== tenantId || pending.nonce !== nonce) {\n throw new Error(\"Approval state is invalid or already used.\");\n }\n if (new Date(pending.expiresAt).getTime() <= Date.now()) {\n await rm(consume ? claimed : path, { force: true });\n throw new Error(\"Approval state has expired.\");\n }\n return pending;\n } catch (error) {\n if (consume) await rename(claimed, path).catch(() => undefined);\n throw error;\n }\n }\n\n async #restorePending(pending: PendingApproval): Promise<void> {\n const stateRoot = join(this.#config.stateDir, \"tenants\", pending.tenantId);\n const path = this.#pendingPath(stateRoot, pending.nonce);\n await rename(`${path}.processing`, path);\n }\n\n #connectUrl(pending: PendingApproval): string {\n const url = new URL(\"/connect\", this.#config.publicUrl);\n url.searchParams.set(\"state\", `${pending.tenantId}.${pending.nonce}.${this.#signState(pending.tenantId, pending.nonce)}`);\n return url.toString();\n }\n\n #tenantId(subject: string): string {\n return createHmac(\"sha256\", this.#config.stateSecret).update(`tenant:${subject}`).digest(\"hex\");\n }\n\n #signState(tenantId: string, nonce: string): string {\n return createHmac(\"sha256\", this.#config.stateSecret)\n .update(`approval:${tenantId}:${nonce}`)\n .digest(\"base64url\");\n }\n\n #profilePath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"profile.json\");\n }\n\n #keyPath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"key.json\");\n }\n\n #sessionPath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"session.json\");\n }\n\n #pendingPath(stateRoot: string, nonce: string): string {\n return join(this.#pendingDirectory(stateRoot), `${nonce}.json`);\n }\n\n #pendingDirectory(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"pending\");\n }\n}\n\nlet wasmInitialized = false;\n\nfunction generateSessionKey(): { jwk: Record<string, unknown>; did: string } {\n ensureWasm();\n const manager = new TCWSessionManager();\n const keyId = manager.createSessionKey(\"hosted-mcp\");\n const serialized = manager.jwk(keyId);\n if (!serialized) throw new Error(\"Could not generate the hosted delegate key.\");\n return { jwk: JSON.parse(serialized) as Record<string, unknown>, did: manager.getDID(keyId) };\n}\n\nfunction didFromJwk(jwk: Record<string, unknown>): string {\n ensureWasm();\n const manager = new TCWSessionManager();\n const keyId = importKey(manager, JSON.stringify(jwk), \"hosted-mcp\");\n return manager.getDID(keyId);\n}\n\nfunction ensureWasm(): void {\n if (wasmInitialized) return;\n initPanicHook();\n wasmInitialized = true;\n}\n\n/**\n * Parse the OpenKey callback. Every signed-proof field is required: without\n * them `restoreSession` verifies nothing and `node.did` would fall back to the\n * tenant's own key.\n */\nfunction sessionFromCallback(data: Record<string, unknown>, privateJwk: Record<string, unknown>): CallbackSession {\n const delegationHeader = data.delegationHeader;\n if (!isRecord(delegationHeader) || typeof delegationHeader.Authorization !== \"string\" ||\n typeof data.delegationCid !== \"string\" || typeof data.spaceId !== \"string\" ||\n typeof data.verificationMethod !== \"string\" || typeof data.address !== \"string\" ||\n typeof data.chainId !== \"number\" || typeof data.siwe !== \"string\" ||\n typeof data.signature !== \"string\") {\n throw new Error(\"OpenKey returned an incomplete delegation.\");\n }\n return {\n delegationHeader: { Authorization: delegationHeader.Authorization },\n delegationCid: data.delegationCid,\n spaceId: data.spaceId,\n jwk: privateJwk,\n verificationMethod: data.verificationMethod,\n address: data.address,\n chainId: data.chainId,\n siwe: data.siwe,\n signature: data.signature,\n };\n}\n\nfunction publicJwk(jwk: Record<string, unknown>): Record<string, unknown> {\n const copy = { ...jwk };\n for (const field of [\"d\", \"p\", \"q\", \"dp\", \"dq\", \"qi\", \"oth\", \"k\"]) delete copy[field];\n return copy;\n}\n\nfunction samePrincipal(left: string | undefined, right: string): boolean {\n if (typeof left !== \"string\") return false;\n try {\n return principalDidEquals(left, right);\n } catch {\n return false;\n }\n}\n\nfunction normalizeDid(value: string): string {\n return value.split(\"#\", 1)[0]!;\n}\n\nfunction isPermissionEntry(value: unknown): value is PermissionEntry {\n return isRecord(value) && typeof value.service === \"string\" && typeof value.space === \"string\" &&\n typeof value.path === \"string\" && Array.isArray(value.actions) &&\n value.actions.every((action) => typeof action === \"string\");\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nasync function secureDirectory(path: string): Promise<void> {\n await mkdir(path, { recursive: true, mode: 0o700 });\n await chmod(path, 0o700);\n}\n\nasync function secureWrite(path: string, value: unknown): Promise<void> {\n const directory = dirname(path);\n await secureDirectory(directory);\n const temporary = `${path}.${process.pid}.${randomBytes(8).toString(\"hex\")}.tmp`;\n await writeFile(temporary, `${JSON.stringify(value, jsonReplacer, 2)}\\n`, { mode: 0o600 });\n await rename(temporary, path);\n await chmod(path, 0o600);\n}\n\nfunction jsonReplacer(_key: string, value: unknown): unknown {\n return value instanceof Date ? value.toISOString() : value;\n}\n\nasync function readJson<T>(path: string): Promise<T | null> {\n try {\n return JSON.parse(await readFile(path, \"utf8\")) as T;\n } catch (error) {\n if (isRecord(error) && error.code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nasync function fileExists(path: string): Promise<boolean> {\n return (await readJson<unknown>(path)) !== null;\n}\n\nasync function reusablePending(\n directory: string,\n expected: Pick<PendingApproval, \"tenantId\" | \"kind\" | \"requestId\" | \"permissions\" | \"ownerDids\">,\n): Promise<PendingApproval | undefined> {\n let names: string[];\n try {\n names = await readdir(directory);\n } catch (error) {\n if (isRecord(error) && error.code === \"ENOENT\") return undefined;\n throw error;\n }\n const active: PendingApproval[] = [];\n for (const name of names) {\n if (!name.endsWith(\".json\")) continue;\n const path = join(directory, name);\n const pending = await readJson<PendingApproval>(path).catch(() => null);\n if (pending === null || new Date(pending.expiresAt).getTime() <= Date.now()) {\n await rm(path, { force: true });\n continue;\n }\n active.push(pending);\n if (samePendingRequest(pending, expected)) return pending;\n }\n if (active.length >= 64) {\n active.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt));\n await rm(join(directory, `${active[0]!.nonce}.json`), { force: true });\n }\n return undefined;\n}\n\nfunction samePendingRequest(\n pending: PendingApproval,\n expected: Pick<PendingApproval, \"tenantId\" | \"kind\" | \"requestId\" | \"permissions\" | \"ownerDids\">,\n): boolean {\n return pending.version === 1 && pending.tenantId === expected.tenantId &&\n pending.kind === expected.kind && pending.requestId === expected.requestId &&\n JSON.stringify(pending.permissions) === JSON.stringify(expected.permissions) &&\n JSON.stringify(pending.ownerDids) === JSON.stringify(expected.ownerDids);\n}\n","import { McpServer } from \"@modelcontextprotocol/server\";\nimport { serveStdio, type StdioServerHandle } from \"@modelcontextprotocol/server/stdio\";\n\nimport { createJsonSchemaValidator, registerTinyCloudTools, type McpStartupSelection } from \"./tools.js\";\nimport { MCP_VERSION } from \"./version.js\";\n\nexport const MCP_SERVER_NAME = \"tinycloud-mcp\";\nexport { MCP_VERSION } from \"./version.js\";\n/** The stdio server is always the local surface. */\nexport type LocalMcpSelection = Omit<McpStartupSelection, \"surface\">;\n\nexport function createTinyCloudMcpServer(selection: LocalMcpSelection): McpServer {\n const validator = createJsonSchemaValidator();\n const server = new McpServer(\n { name: MCP_SERVER_NAME, version: MCP_VERSION },\n { jsonSchemaValidator: validator },\n );\n registerTinyCloudTools(server, { ...selection, surface: \"local\" }, validator);\n return server;\n}\n\n/** Start the only supported MCP transport: local stdio. */\nexport function serveTinyCloudMcp(selection: LocalMcpSelection): StdioServerHandle {\n return serveStdio(\n () => createTinyCloudMcpServer(selection),\n { onerror: () => writeBoundedDiagnostic(\"MCP transport error\") },\n );\n}\n\nfunction writeBoundedDiagnostic(message: string): void {\n process.stderr.write(`[tinycloud-mcp] ${message}\\n`);\n}\n","import { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\n\nimport { fromJsonSchema, type McpServer, type ToolAnnotations } from \"@modelcontextprotocol/server\";\nimport { addFormats, Ajv, AjvJsonSchemaValidator } from \"@modelcontextprotocol/server/validators/ajv\";\nimport { invokeOperation } from \"@tinycloud/operations\";\n\nimport { toMcpToolResult, type McpToolResult } from \"./results.js\";\n\nexport const TOOL_NAMES = [\n \"tinycloud_status\",\n \"tinycloud_auth_status\",\n \"tinycloud_auth_capabilities\",\n \"tinycloud_auth_request\",\n \"tinycloud_auth_import\",\n \"tinycloud_account_spaces_list\",\n \"tinycloud_account_applications_list\",\n \"tinycloud_kv_list\",\n \"tinycloud_kv_get\",\n \"tinycloud_kv_head\",\n \"tinycloud_kv_put\",\n \"tinycloud_kv_delete\",\n \"tinycloud_sql_schema_inspect\",\n \"tinycloud_sql_query\",\n \"tinycloud_sql_execute\",\n \"tinycloud_secrets_get\",\n \"tinycloud_secrets_status\",\n] as const;\n\nexport type ToolName = (typeof TOOL_NAMES)[number];\n\n/** MCP server surfaces: local stdio and the hosted OAuth HTTP server. */\nexport type McpSurface = \"local\" | \"hosted\";\n\nexport interface McpStartupSelection {\n /** Which server registers the tools; bindings not on this surface are skipped. */\n readonly surface: McpSurface;\n readonly profile: string;\n readonly explicitProfile: boolean;\n readonly allowOwnerProfile: boolean;\n /** Absolute TinyCloud home used to isolate one hosted OAuth principal. */\n readonly stateRoot?: string;\n /** Hosted transports may attach a browser approval URL to canonical results. */\n readonly transformOperationResult?: (result: unknown) => Promise<unknown>;\n}\n\nexport interface McpInvocationTarget {\n readonly profile: string;\n readonly allowOwnerProfile?: true;\n readonly stateRoot?: string;\n}\n\n/** Project one startup selection into the only owner-sensitive target shape. */\nexport function invocationTargetForMcp(\n selection: Omit<McpStartupSelection, \"surface\">,\n): McpInvocationTarget {\n return {\n profile: selection.profile,\n ...(selection.explicitProfile && selection.allowOwnerProfile\n ? { allowOwnerProfile: true }\n : {}),\n ...(selection.stateRoot === undefined ? {} : { stateRoot: selection.stateRoot }),\n };\n}\n\ninterface CatalogOperation {\n readonly id: string;\n readonly version: number;\n readonly title: string;\n readonly description: string;\n readonly input: Record<string, unknown>;\n readonly result: Record<string, unknown>;\n}\n\ninterface OperationsCatalog {\n readonly operations: readonly CatalogOperation[];\n}\n\n// The require anchor is this module, never the consumer entrypoint. In ESM\n// tsup preserves import.meta.url; in CJS it rewrites the same module-relative\n// anchor to the generated __filename, so both formats stay in MCP's package\n// dependency boundary.\nconst packageRequire = createRequire(\n typeof __dirname === \"string\" ? join(__dirname, \"tools.cjs\") : import.meta.url,\n);\nconst generatedCatalog = packageRequire(\n \"@tinycloud/operations/operations.json\",\n) as OperationsCatalog;\n\nexport interface ToolBinding {\n readonly name: ToolName;\n readonly operationId: string;\n readonly operationVersion: number;\n readonly readOnlyHint: boolean;\n readonly idempotentHint: boolean;\n readonly destructiveHint: boolean;\n readonly openWorldHint: boolean;\n /** Surfaces that register this tool; omitted means every surface. */\n readonly surfaces?: readonly McpSurface[];\n}\n\nconst ALL_SURFACES: readonly McpSurface[] = [\"local\", \"hosted\"];\n\n/** The surfaces a binding is registered on. */\nexport function bindingSurfaces(binding: ToolBinding): readonly McpSurface[] {\n return binding.surfaces ?? ALL_SURFACES;\n}\n\nexport const TOOL_BINDINGS: readonly ToolBinding[] = [\n {\n name: \"tinycloud_status\",\n operationId: \"tinycloud.status.get\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_status\",\n operationId: \"tinycloud.auth.status\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_capabilities\",\n operationId: \"tinycloud.auth.capabilities\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_request\",\n operationId: \"tinycloud.auth.request\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_import\",\n operationId: \"tinycloud.auth.import\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n // Hosted delegations must arrive through the owner/request-bound OpenKey callback,\n // not a caller-supplied import artifact.\n surfaces: [\"local\"],\n },\n {\n name: \"tinycloud_account_spaces_list\",\n operationId: \"tinycloud.account.spaces.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_account_applications_list\",\n operationId: \"tinycloud.account.applications.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_list\",\n operationId: \"tinycloud.kv.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_get\",\n operationId: \"tinycloud.kv.get\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_head\",\n operationId: \"tinycloud.kv.head\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_put\",\n operationId: \"tinycloud.kv.put\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: true,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_delete\",\n operationId: \"tinycloud.kv.delete\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: true,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_sql_schema_inspect\",\n operationId: \"tinycloud.sql.schema.inspect\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_sql_query\",\n operationId: \"tinycloud.sql.query\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_sql_execute\",\n operationId: \"tinycloud.sql.execute\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_secrets_get\",\n operationId: \"tinycloud.secrets.get\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_secrets_status\",\n operationId: \"tinycloud.secrets.status\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n // Hosted has no persistent reauthorization path for a revoked session\n // yet (TC-896), so status is local/stdio only.\n surfaces: [\"local\"],\n },\n] as const;\n\nexport function createJsonSchemaValidator(): AjvJsonSchemaValidator {\n const ajv = new Ajv({ strict: false });\n addFormats(ajv);\n return new AjvJsonSchemaValidator(ajv);\n}\n\nexport function registerTinyCloudTools(\n server: McpServer,\n selection: McpStartupSelection,\n validator: AjvJsonSchemaValidator,\n): void {\n const definitions = new Map(\n generatedCatalog.operations.map((operation) => [\n `${operation.id}@${operation.version}`,\n operation,\n ]),\n );\n\n for (const binding of TOOL_BINDINGS) {\n if (!bindingSurfaces(binding).includes(selection.surface)) continue;\n const operation = definitions.get(`${binding.operationId}@${binding.operationVersion}`);\n if (operation === undefined) {\n throw new Error(`Generated operations catalog is missing ${binding.operationId}@${binding.operationVersion}.`);\n }\n\n const inputSchema = fromJsonSchema(\n operation.input as Parameters<typeof fromJsonSchema>[0],\n validator,\n );\n const outputSchema = fromJsonSchema(\n operation.result as unknown as Parameters<typeof fromJsonSchema>[0],\n validator,\n );\n const annotations: ToolAnnotations = {\n readOnlyHint: binding.readOnlyHint,\n idempotentHint: binding.idempotentHint,\n destructiveHint: binding.destructiveHint,\n openWorldHint: binding.openWorldHint,\n };\n\n server.registerTool(\n binding.name,\n {\n title: operation.title,\n description: operation.description,\n inputSchema,\n outputSchema,\n annotations,\n },\n async (input: unknown): Promise<McpToolResult> => {\n const result = await invokeOperation(\n binding.operationId,\n binding.operationVersion,\n invocationTargetForMcp(selection),\n input,\n );\n const projected = selection.transformOperationResult === undefined\n ? result\n : await selection.transformOperationResult(result);\n return toMcpToolResult(projected, TOOL_BINDINGS);\n },\n );\n }\n}\n\nexport function toolBindingsForTest(): readonly ToolBinding[] {\n return TOOL_BINDINGS;\n}\n","/**\n * MCP has one structured result channel for a TinyCloud operation. Text is a\n * fixed, non-sensitive status line; it never serializes the operation result.\n */\nexport interface CanonicalOperationResult {\n readonly status: \"ok\" | \"authority_required\" | \"setup_required\" | \"error\";\n readonly [key: string]: unknown;\n}\n\nexport interface McpToolResult extends CallToolResult {\n readonly content: [{ readonly type: \"text\"; readonly text: string }];\n readonly structuredContent: CanonicalOperationResult;\n}\n\n/** The binding fields needed to name the tool that runs an operation. */\nexport interface RecoveryToolBinding {\n readonly name: string;\n readonly operationId: string;\n}\n\nexport function toMcpToolResult(\n result: unknown,\n bindings: readonly RecoveryToolBinding[] = [],\n): McpToolResult {\n const canonical: CanonicalOperationResult = isCanonicalOperationResult(result)\n ? withRecoveryTool(result, bindings)\n : {\n status: \"error\",\n operation: {},\n context: {},\n error: { code: \"INTERNAL_ERROR\" },\n };\n\n return {\n content: [{ type: \"text\", text: resultSummary(canonical.status) }],\n structuredContent: canonical,\n };\n}\n\n/**\n * A redacted `complete_migration` recovery names an operation; MCP clients\n * call tools, so name the bound tool. `tool` comes from the code-owned binding\n * table only, never from operation data, and is added after redaction. An\n * operationId with no binding gets no `tool`.\n */\nfunction withRecoveryTool(\n result: CanonicalOperationResult,\n bindings: readonly RecoveryToolBinding[],\n): CanonicalOperationResult {\n if (result.status !== \"error\") return result;\n // The kernel's redaction already constrained `error.details.recovery` to a\n // safe recovery object; only its discriminant and operationId are read here.\n const error = result.error as\n | { readonly details?: { readonly recovery?: { readonly action?: unknown; readonly operationId?: unknown } } }\n | undefined;\n const recovery = error?.details?.recovery;\n if (recovery?.action !== \"complete_migration\") return result;\n const binding = bindings.find((candidate) => candidate.operationId === recovery.operationId);\n if (binding === undefined) return result;\n return {\n ...result,\n error: { ...error, details: { ...error?.details, recovery: { ...recovery, tool: binding.name } } },\n };\n}\n\n/** The canonical envelope immediately before MCP protocol serialization. */\nexport function canonicalMcpAdapterResult(result: unknown): CanonicalOperationResult {\n return toMcpToolResult(result).structuredContent;\n}\n\nfunction isCanonicalOperationResult(value: unknown): value is CanonicalOperationResult {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n const status = (value as { status?: unknown }).status;\n return status === \"ok\" ||\n status === \"authority_required\" ||\n status === \"setup_required\" ||\n status === \"error\";\n}\n\nfunction resultSummary(status: CanonicalOperationResult[\"status\"]): string {\n switch (status) {\n case \"ok\":\n return \"TinyCloud operation completed; use the structured result.\";\n case \"authority_required\":\n return \"TinyCloud authority is required; use the structured request and approval action.\";\n case \"setup_required\":\n return \"TinyCloud setup is required; use the structured setup action.\";\n case \"error\":\n return \"TinyCloud operation failed; use the structured error.\";\n }\n}\nimport type { CallToolResult } from \"@modelcontextprotocol/server\";\n","{\n \"name\": \"@tinycloud/mcp\",\n \"version\": \"0.5.2\",\n \"description\": \"TinyCloud delegated operations MCP server\",\n \"keywords\": [\n \"tinycloud\",\n \"mcp\",\n \"model-context-protocol\",\n \"agents\",\n \"delegation\",\n \"ucan\",\n \"kv\",\n \"sqlite\"\n ],\n \"author\": \"TinyCloud, Inc.\",\n \"license\": \"EGPL\",\n \"type\": \"module\",\n \"main\": \"dist/index.cjs\",\n \"module\": \"dist/index.js\",\n \"types\": \"dist/index.d.ts\",\n \"bin\": {\n \"tinycloud-mcp\": \"./bin/tinycloud-mcp\",\n \"tinycloud-mcp-http\": \"./bin/tinycloud-mcp-http\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./server\": {\n \"types\": \"./dist/server.d.ts\",\n \"import\": \"./dist/server.js\",\n \"require\": \"./dist/server.cjs\"\n },\n \"./tools\": {\n \"types\": \"./dist/tools.d.ts\",\n \"import\": \"./dist/tools.js\",\n \"require\": \"./dist/tools.cjs\"\n },\n \"./results\": {\n \"types\": \"./dist/results.d.ts\",\n \"import\": \"./dist/results.js\",\n \"require\": \"./dist/results.cjs\"\n },\n \"./http\": {\n \"types\": \"./dist/http.d.ts\",\n \"import\": \"./dist/http.js\",\n \"require\": \"./dist/http.cjs\"\n }\n },\n \"files\": [\n \"dist\",\n \"bin\",\n \"generated\",\n \"skills\"\n ],\n \"engines\": {\n \"node\": \">=20\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"clean\": \"rm -rf dist\",\n \"test\": \"bun run build && bun scripts/test.ts && bun run check:generated\",\n \"test:stdio\": \"bun run build && bun test src/stdio.test.ts\",\n \"typecheck\": \"tsc -p tsconfig.json\",\n \"start:http\": \"node dist/http-cli.js\",\n \"generate\": \"bun scripts/generate.ts\",\n \"check:generated\": \"bun scripts/generate.ts --check\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/node\": \"2.0.0-beta.4\",\n \"@modelcontextprotocol/server\": \"2.0.0-beta.4\",\n \"@tinycloud/node-sdk\": \"3.2.2\",\n \"@tinycloud/node-sdk-wasm\": \"1.7.7\",\n \"@tinycloud/operations\": \"0.5.2\",\n \"jose\": \"6.1.3\"\n },\n \"devDependencies\": {\n \"@modelcontextprotocol/client\": \"2.0.0-beta.4\",\n \"@types/node\": \"^20\",\n \"tsup\": \"^8.0.0\",\n \"typescript\": \"^5.9.3\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/TinyCloudLabs/js-sdk\"\n },\n \"homepage\": \"https://docs.tinycloud.xyz/cli/mcp\"\n}\n","import packageMetadata from \"../package.json\";\n\nexport const MCP_VERSION = packageMetadata.version;\n"],"mappings":";AAAA,SAAS,oBAAoB;AAC7B,SAAS,YAAY,eAAe;AAEpC,SAAS,qBAAqB;;;ACH9B;AAAA,EACE,aAAAA;AAAA,EACA;AAAA,EACA,kBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;;;ACVP;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AACP,SAAS,cAAc;AACvB,SAAS,oBAAoB,QAAQ,iBAAkC;AAEvE,IAAM,mBAAmB;AASlB,SAAS,2BAA2B,QAAgD;AACzF,QAAM,OAAO,mBAAmB,IAAI,IAAI,OAAO,OAAO,CAAC;AACvD,SAAO;AAAA,IACL,MAAM,kBAAkB,OAAkC;AACxD,UAAI;AACF,cAAM,EAAE,QAAQ,IAAI,MAAM,UAAU,OAAO,MAAM;AAAA,UAC/C,QAAQ,OAAO;AAAA,UACf,UAAU,OAAO;AAAA,QACnB,CAAC;AACD,eAAO,SAAS,OAAO,SAAS,MAAM;AAAA,MACxC,SAAS,OAAO;AACd,YAAI,iBAAiB,OAAO,WAAW;AACrC,gBAAM,IAAI,WAAW,eAAe,cAAc,sCAAsC;AAAA,QAC1F;AACA,cAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;AAEA,eAAsB,kBAAkB,aAA0C;AAChF,QAAM,WAAW,MAAM,MAAM,aAAa;AAAA,IACxC,SAAS,EAAE,QAAQ,mBAA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,OAAM,IAAI,MAAM,gDAAgD;AAC9G,SAAO;AACT;AAEA,SAAS,UAAU,OAAiD;AAClE,MAAI,UAAU,OAAW,QAAO;AAChC,SAAO,MAAM,MAAM,GAAG,EAAE,IAAI,CAAC,UAAU,MAAM,KAAK,CAAC,EAAE,OAAO,OAAO;AACrE;AAEA,KAAK,KAAK,EAAE,MAAM,MAAM;AACtB,UAAQ,OAAO,MAAM,wCAAwC;AAC7D,UAAQ,WAAW;AACrB,CAAC;","names":["McpServer","fromJsonSchema","join","invokeOperation","join","invokeOperation","authInfo","McpServer","originFailure","fromJsonSchema"]}
1
+ {"version":3,"sources":["../src/http-cli.ts","../src/http.ts","../src/oauth.ts","../src/remote-store.ts","../src/server.ts","../src/tools.ts","../src/results.ts","../package.json","../src/version.ts"],"sourcesContent":["import { createServer } from \"node:http\";\nimport { isAbsolute, resolve } from \"node:path\";\n\nimport { toNodeHandler } from \"@modelcontextprotocol/node\";\n\nimport { createHostedMcpApp } from \"./http.js\";\nimport { loadOAuthMetadata } from \"./oauth.js\";\n\nexport async function main(): Promise<void> {\n process.umask(0o077);\n const publicUrl = requiredUrl(\"TC_MCP_PUBLIC_URL\");\n const stateDir = requiredAbsolutePath(\"TC_MCP_STATE_DIR\");\n const stateSecret = requiredString(\"TC_MCP_STATE_SECRET\");\n if (Buffer.byteLength(stateSecret) < 32) throw new Error(\"TC_MCP_STATE_SECRET must contain at least 32 bytes.\");\n const openkeyHost = process.env.TC_OPENKEY_HOST ?? \"https://openkey.so\";\n const oauthMetadataUrl = new URL(\n process.env.TC_MCP_OAUTH_METADATA_URL ??\n \"https://api.openkey.so/.well-known/oauth-authorization-server/api/auth\",\n );\n const oauthMetadata = await loadOAuthMetadata(oauthMetadataUrl);\n const app = createHostedMcpApp({\n publicUrl,\n stateDir,\n stateSecret,\n nodeHost: process.env.TC_HOST ?? \"https://tee.node.tinycloud.xyz\",\n openkeyHost,\n approvalTtlSeconds: positiveInteger(process.env.TC_MCP_APPROVAL_TTL_SECONDS, 300),\n delegationExpiry: process.env.TC_MCP_DELEGATION_EXPIRY ?? \"1h\",\n allowedOrigins: commaList(process.env.TC_MCP_ALLOWED_ORIGINS),\n oauthMetadata,\n });\n const nodeHandler = toNodeHandler(app);\n const server = createServer(nodeHandler);\n const host = process.env.HOST ?? \"0.0.0.0\";\n const port = positiveInteger(process.env.PORT, 3000);\n server.listen(port, host, () => {\n process.stderr.write(`[tinycloud-mcp-http] listening on ${host}:${port}\\n`);\n });\n const shutdown = () => {\n server.close(() => void app.close());\n };\n process.once(\"SIGINT\", shutdown);\n process.once(\"SIGTERM\", shutdown);\n}\n\nfunction requiredString(name: string): string {\n const value = process.env[name]?.trim();\n if (!value) throw new Error(`${name} is required.`);\n return value;\n}\n\nfunction requiredUrl(name: string): URL {\n const url = new URL(requiredString(name));\n if (url.protocol !== \"https:\" && url.hostname !== \"localhost\" && url.hostname !== \"127.0.0.1\") {\n throw new Error(`${name} must use HTTPS outside localhost.`);\n }\n return url;\n}\n\nfunction requiredAbsolutePath(name: string): string {\n const value = requiredString(name);\n if (!isAbsolute(value)) throw new Error(`${name} must be an absolute path.`);\n return resolve(value);\n}\n\nfunction positiveInteger(value: string | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed <= 0) throw new Error(\"Expected a positive integer environment value.\");\n return parsed;\n}\n\nfunction commaList(value: string | undefined): string[] | undefined {\n if (value === undefined) return undefined;\n return value.split(\",\").map((entry) => entry.trim()).filter(Boolean);\n}\n\nvoid main().catch(() => {\n process.stderr.write(\"[tinycloud-mcp-http] Startup failed.\\n\");\n process.exitCode = 1;\n});\n","import {\n McpServer,\n createMcpHandler,\n fromJsonSchema,\n getOAuthProtectedResourceMetadataUrl,\n hostHeaderValidationResponse,\n oauthMetadataResponse,\n requireBearerAuth,\n type AuthInfo,\n type OAuthMetadata,\n} from \"@modelcontextprotocol/server\";\n\nimport { createOpenKeyTokenVerifier } from \"./oauth.js\";\nimport { ApprovalOwnerMismatchError, RemoteTenantStore, type RemoteStoreConfig } from \"./remote-store.js\";\nimport { MCP_SERVER_NAME } from \"./server.js\";\nimport { createJsonSchemaValidator, registerTinyCloudTools } from \"./tools.js\";\nimport { MCP_VERSION } from \"./version.js\";\n\nconst REQUIRED_SCOPE = \"tinycloud:mcp\";\n\nexport interface HostedMcpConfig extends RemoteStoreConfig {\n readonly oauthMetadata: OAuthMetadata;\n readonly allowedOrigins?: readonly string[];\n}\n\nexport interface HostedMcpApp {\n readonly fetch: (request: Request) => Promise<Response>;\n readonly close: () => Promise<void>;\n}\n\nexport function createHostedMcpApp(config: HostedMcpConfig): HostedMcpApp {\n const resourceUrl = canonicalResourceUrl(config.publicUrl);\n const issuer = String(config.oauthMetadata.issuer);\n const jwksUri = String(config.oauthMetadata.jwks_uri);\n const verifier = createOpenKeyTokenVerifier({\n issuer,\n audience: resourceUrl.toString(),\n jwksUri,\n requiredScope: REQUIRED_SCOPE,\n });\n const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(resourceUrl);\n const authenticate = requireBearerAuth({\n verifier,\n requiredScopes: [REQUIRED_SCOPE],\n resourceMetadataUrl,\n });\n const store = new RemoteTenantStore({ ...config, publicUrl: resourceUrl });\n const handler = createMcpHandler(async ({ authInfo }) => {\n const identity = oauthIdentity(authInfo);\n const { subject, ownerDids } = identity;\n const stateRoot = store.tenantStateRoot(subject);\n const validator = createJsonSchemaValidator();\n const server = new McpServer(\n { name: MCP_SERVER_NAME, version: MCP_VERSION },\n {\n jsonSchemaValidator: validator,\n instructions: \"Call tinycloud_connect first. If an operation returns authority_required, open approval.url, then retry that operation unchanged.\",\n },\n );\n registerTinyCloudTools(server, {\n surface: \"hosted\",\n profile: \"agent\",\n explicitProfile: true,\n allowOwnerProfile: false,\n stateRoot,\n transformOperationResult: (result) => store.decorateAuthorityResult(subject, ownerDids, result),\n }, validator);\n registerConnectTool(server, validator, store, identity);\n return server;\n }, {\n legacy: \"stateless\",\n onerror: () => writeDiagnostic(\"MCP request failed\"),\n });\n\n const metadataOptions = {\n oauthMetadata: config.oauthMetadata,\n resourceServerUrl: resourceUrl,\n serviceDocumentationUrl: new URL(\"https://docs.tinycloud.xyz/cli/mcp\"),\n scopesSupported: [REQUIRED_SCOPE],\n resourceName: \"TinyCloud hosted MCP\",\n };\n const allowedHosts = [resourceUrl.hostname];\n\n return {\n async fetch(request: Request): Promise<Response> {\n const metadata = oauthMetadataResponse(request, metadataOptions);\n if (metadata !== undefined) return metadata;\n const url = new URL(request.url);\n if (url.pathname === \"/healthz\") {\n return request.method === \"GET\"\n ? json({ ok: true })\n : methodNotAllowed(\"GET\");\n }\n const hostFailure = hostHeaderValidationResponse(request, allowedHosts);\n if (hostFailure !== undefined) return hostFailure;\n\n if (url.pathname === \"/connect\") {\n if (request.method !== \"GET\") return methodNotAllowed(\"GET\");\n try {\n const destination = await store.approvalRedirect(requiredState(url));\n return Response.redirect(destination, 302);\n } catch {\n return json({ error: \"The approval link is invalid or expired.\" }, 400);\n }\n }\n if (url.pathname === \"/connect/callback\") {\n if (request.method === \"OPTIONS\") return callbackCors(new Response(null, { status: 204 }), config.openkeyHost);\n if (request.method !== \"POST\") return methodNotAllowed(\"POST\");\n const originFailure = validateCallbackOrigin(request, config.openkeyHost);\n if (originFailure !== undefined) return callbackCors(originFailure, config.openkeyHost);\n try {\n await store.completeApproval(requiredState(url), request);\n return callbackCors(json({ success: true }), config.openkeyHost);\n } catch (error) {\n // Only fixed server-authored text reaches OpenKey; callback input is never echoed.\n return callbackCors(\n error instanceof ApprovalOwnerMismatchError\n ? json({ error: error.message, code: \"approval_owner_mismatch\" }, 403)\n : json({ error: \"TinyCloud could not accept this delegation.\" }, 400),\n config.openkeyHost,\n );\n }\n }\n if (url.pathname !== resourceUrl.pathname) return json({ error: \"Not found\" }, 404);\n const originFailure = validateOrigin(request, config.allowedOrigins);\n if (originFailure !== undefined) return originFailure;\n const auth = await authenticate(request);\n if (auth instanceof Response) return auth;\n return handler.fetch(request, { authInfo: auth });\n },\n close: () => handler.close(),\n };\n}\n\nfunction registerConnectTool(\n server: McpServer,\n validator: ReturnType<typeof createJsonSchemaValidator>,\n store: RemoteTenantStore,\n identity: OAuthIdentity,\n): void {\n const inputSchema = fromJsonSchema({ type: \"object\", properties: {}, additionalProperties: false }, validator);\n const outputSchema = fromJsonSchema({\n type: \"object\",\n properties: {\n connected: { type: \"boolean\" },\n sessionDid: { type: \"string\" },\n approvalUrl: { type: \"string\", format: \"uri\" },\n expiresAt: { type: \"string\", format: \"date-time\" },\n },\n required: [\"connected\", \"sessionDid\"],\n additionalProperties: false,\n }, validator);\n server.registerTool(\n \"tinycloud_connect\",\n {\n title: \"Connect TinyCloud\",\n description: \"Check the hosted delegate connection and return a one-time OpenKey approval URL when setup is required.\",\n inputSchema,\n outputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n },\n async () => {\n const status = await store.connectStatus(identity.subject, identity.ownerDids);\n return {\n content: [{\n type: \"text\" as const,\n text: status.connected\n ? \"TinyCloud is connected.\"\n : \"TinyCloud approval is required; open approvalUrl, then call this tool again.\",\n }],\n structuredContent: status,\n };\n },\n );\n}\n\ninterface OAuthIdentity {\n readonly subject: string;\n readonly ownerDids: string[];\n}\n\nfunction oauthIdentity(authInfo: AuthInfo | undefined): OAuthIdentity {\n const subject = authInfo?.extra?.subject;\n if (typeof subject !== \"string\" || subject.length === 0) {\n throw new Error(\"The authenticated MCP request has no OpenKey subject.\");\n }\n const ownerDids = authInfo?.extra?.ownerDids;\n if (!Array.isArray(ownerDids) || ownerDids.length === 0 ||\n !ownerDids.every((did) => typeof did === \"string\")) {\n throw new Error(\"The authenticated MCP request has no OpenKey owner identity.\");\n }\n return { subject, ownerDids };\n}\n\nfunction canonicalResourceUrl(url: URL): URL {\n const resource = new URL(url);\n resource.hash = \"\";\n resource.search = \"\";\n resource.pathname = resource.pathname.replace(/\\/+$/, \"\") || \"/mcp\";\n if (resource.pathname === \"/\") resource.pathname = \"/mcp\";\n return resource;\n}\n\nfunction requiredState(url: URL): string {\n const state = url.searchParams.get(\"state\");\n if (state === null || state.length > 512) throw new Error(\"Missing approval state.\");\n return state;\n}\n\nfunction validateOrigin(request: Request, allowed: readonly string[] | undefined): Response | undefined {\n const origin = request.headers.get(\"origin\");\n if (origin === null) return undefined;\n const allowlist = allowed ?? [];\n return allowlist.includes(origin) ? undefined : json({ error: \"Origin is not allowed.\" }, 403);\n}\n\nfunction validateCallbackOrigin(request: Request, openkeyHost: string): Response | undefined {\n const origin = request.headers.get(\"origin\");\n return origin === null || origin === new URL(openkeyHost).origin\n ? undefined\n : json({ error: \"Origin is not allowed.\" }, 403);\n}\n\nfunction callbackCors(response: Response, openkeyHost: string): Response {\n const headers = new Headers(response.headers);\n headers.set(\"access-control-allow-origin\", new URL(openkeyHost).origin);\n headers.set(\"access-control-allow-methods\", \"POST, OPTIONS\");\n headers.set(\"access-control-allow-headers\", \"content-type\");\n headers.set(\"vary\", \"Origin\");\n return new Response(response.body, { status: response.status, headers });\n}\n\nfunction json(value: unknown, status = 200): Response {\n return Response.json(value, { status, headers: { \"cache-control\": \"no-store\" } });\n}\n\nfunction methodNotAllowed(allow: string): Response {\n return new Response(\"Method not allowed\", { status: 405, headers: { allow } });\n}\n\nfunction writeDiagnostic(message: string): void {\n process.stderr.write(`[tinycloud-mcp-http] ${message}\\n`);\n}\n","import {\n OAuthError,\n OAuthErrorCode,\n type AuthInfo,\n type OAuthMetadata,\n type OAuthTokenVerifier,\n} from \"@modelcontextprotocol/server\";\nimport { pkhDid } from \"@tinycloud/node-sdk\";\nimport { createRemoteJWKSet, errors, jwtVerify, type JWTPayload } from \"jose\";\n\nconst OWNER_DIDS_CLAIM = \"https://tinycloud.xyz/owner_dids\";\n\nexport interface OpenKeyOAuthConfig {\n readonly issuer: string;\n readonly audience: string;\n readonly jwksUri: string;\n readonly requiredScope?: string;\n}\n\nexport function createOpenKeyTokenVerifier(config: OpenKeyOAuthConfig): OAuthTokenVerifier {\n const jwks = createRemoteJWKSet(new URL(config.jwksUri));\n return {\n async verifyAccessToken(token: string): Promise<AuthInfo> {\n try {\n const { payload } = await jwtVerify(token, jwks, {\n issuer: config.issuer,\n audience: config.audience,\n });\n return authInfo(token, payload, config);\n } catch (error) {\n if (error instanceof errors.JOSEError) {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token is invalid.\");\n }\n throw error;\n }\n },\n };\n}\n\nexport async function loadOAuthMetadata(metadataUrl: URL): Promise<OAuthMetadata> {\n const response = await fetch(metadataUrl, {\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) throw new Error(\"OpenKey OAuth discovery failed.\");\n const metadata = await response.json() as OAuthMetadata;\n if (typeof metadata.issuer !== \"string\" || typeof metadata.jwks_uri !== \"string\") {\n throw new Error(\"OpenKey OAuth metadata is incomplete.\");\n }\n return metadata;\n}\n\nfunction authInfo(\n token: string,\n payload: JWTPayload,\n config: OpenKeyOAuthConfig,\n): AuthInfo {\n if (typeof payload.sub !== \"string\" || payload.sub.length === 0) {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token does not identify a subject.\");\n }\n if (typeof payload.exp !== \"number\") {\n throw new OAuthError(OAuthErrorCode.InvalidToken, \"The OpenKey access token has no expiry.\");\n }\n const scopes = typeof payload.scope === \"string\"\n ? payload.scope.split(/\\s+/).filter(Boolean)\n : [];\n if (config.requiredScope !== undefined && !scopes.includes(config.requiredScope)) {\n throw new OAuthError(\n OAuthErrorCode.InsufficientScope,\n \"The OpenKey access token is missing the TinyCloud MCP scope.\",\n );\n }\n const clientId = firstString(payload.azp, payload.client_id) ?? \"unknown\";\n const ownerDids = canonicalOwnerDids(payload[OWNER_DIDS_CLAIM]);\n if (ownerDids === undefined) {\n throw new OAuthError(\n OAuthErrorCode.InvalidToken,\n \"The OpenKey access token has no valid TinyCloud owner identity.\",\n );\n }\n return {\n token,\n clientId,\n scopes,\n expiresAt: payload.exp,\n resource: new URL(config.audience),\n extra: {\n subject: payload.sub,\n ownerDids,\n },\n };\n}\n\n/**\n * OpenKey issues owner DIDs as `did:pkh:eip155:<chain>:<address>`. Only that\n * exact syntax is accepted, canonicalised, and passed on to owner comparison\n * and the approval text. One malformed value refuses the whole claim rather\n * than being skipped.\n */\nconst OWNER_DID = /^did:pkh:eip155:([1-9][0-9]{0,15}):(0x[0-9a-fA-F]{40})$/;\n\nfunction canonicalOwnerDids(claim: unknown): string[] | undefined {\n if (!Array.isArray(claim) || claim.length === 0) return undefined;\n const ownerDids: string[] = [];\n for (const value of claim) {\n const match = typeof value === \"string\" ? OWNER_DID.exec(value) : null;\n if (match === null) return undefined;\n try {\n ownerDids.push(pkhDid(match[2]!, Number(match[1])));\n } catch {\n return undefined;\n }\n }\n return [...new Set(ownerDids)];\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n return values.find((value): value is string => typeof value === \"string\" && value.length > 0);\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { chmod, mkdir, readFile, readdir, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\nimport {\n TinyCloudNode,\n isCapabilitySubset,\n principalDidEquals,\n siweRuntimeDelegation,\n type PermissionEntry,\n type TinyCloudSession,\n} from \"@tinycloud/node-sdk\";\nimport { TCWSessionManager, importKey, initPanicHook } from \"@tinycloud/node-sdk-wasm\";\nimport { invokeOperation } from \"@tinycloud/operations\";\n\nconst PROFILE = \"agent\";\nconst MAX_CALLBACK_BYTES = 256 * 1024;\nconst BOOTSTRAP_PERMISSIONS: PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: \"account\",\n path: \"spaces/\",\n actions: [\"tinycloud.kv/get\", \"tinycloud.kv/list\"],\n },\n {\n service: \"tinycloud.kv\",\n space: \"account\",\n path: \"applications/\",\n actions: [\"tinycloud.kv/get\", \"tinycloud.kv/list\"],\n },\n];\n\nexport interface RemoteStoreConfig {\n readonly stateDir: string;\n readonly stateSecret: string;\n readonly publicUrl: URL;\n readonly nodeHost: string;\n readonly openkeyHost: string;\n readonly approvalTtlSeconds: number;\n readonly delegationExpiry: string;\n}\n\ninterface TenantProfile {\n readonly stateRoot: string;\n readonly sessionDid: string;\n readonly jwk: Record<string, unknown>;\n}\n\ninterface PendingApproval {\n readonly version: 1;\n readonly nonce: string;\n readonly tenantId: string;\n readonly kind: \"bootstrap\" | \"delegation\";\n readonly requestId?: string;\n readonly permissions: PermissionEntry[];\n readonly ownerDids: string[];\n readonly createdAt: string;\n readonly expiresAt: string;\n}\n\nexport interface ConnectStatus {\n readonly connected: boolean;\n readonly sessionDid: string;\n readonly approvalUrl?: string;\n readonly expiresAt?: string;\n}\n\ninterface CallbackSession {\n readonly delegationHeader: { Authorization: string };\n readonly delegationCid: string;\n readonly spaceId: string;\n readonly jwk: Record<string, unknown>;\n readonly verificationMethod: string;\n readonly address: string;\n readonly chainId: number;\n readonly siwe: string;\n readonly signature: string;\n}\n\n/**\n * The approving wallet is not the OpenKey principal whose MCP request created\n * the approval link. The message is static so callers may show it verbatim.\n */\nexport class ApprovalOwnerMismatchError extends Error {\n constructor() {\n super(\"This approval link was requested by a different TinyCloud account, so the delegation was not stored.\");\n this.name = \"ApprovalOwnerMismatchError\";\n }\n}\n\nexport class RemoteTenantStore {\n readonly #config: RemoteStoreConfig;\n readonly #initializing = new Map<string, Promise<TenantProfile>>();\n\n constructor(config: RemoteStoreConfig) {\n this.#config = config;\n }\n\n tenantStateRoot(subject: string): string {\n return join(this.#config.stateDir, \"tenants\", this.#tenantId(subject));\n }\n\n async connectStatus(subject: string, ownerDids: readonly string[] = []): Promise<ConnectStatus> {\n const tenant = await this.#ensureTenant(subject);\n if (await this.#hasValidSession(tenant, ownerDids)) {\n return { connected: true, sessionDid: tenant.sessionDid };\n }\n const pending = await this.#createPending(subject, ownerDids, \"bootstrap\", BOOTSTRAP_PERMISSIONS);\n return {\n connected: false,\n sessionDid: tenant.sessionDid,\n approvalUrl: this.#connectUrl(pending),\n expiresAt: pending.expiresAt,\n };\n }\n\n async decorateAuthorityResult(\n subject: string,\n ownerDids: readonly string[],\n result: unknown,\n ): Promise<unknown> {\n if (!isRecord(result) || result.status !== \"authority_required\") return result;\n const request = isRecord(result.request) ? result.request : undefined;\n const requestId = typeof request?.requestId === \"string\" ? request.requestId : undefined;\n const requested = Array.isArray(request?.requested)\n ? request.requested.filter(isPermissionEntry)\n : [];\n if (requestId === undefined || requested.length === 0) return result;\n const pending = await this.#createPending(subject, ownerDids, \"delegation\", requested, requestId);\n return {\n ...result,\n approval: {\n ...(isRecord(result.approval) ? result.approval : {}),\n kind: \"openkey\",\n requestId,\n url: this.#connectUrl(pending),\n fallback: \"Open the approval URL, then retry the same MCP tool.\",\n },\n };\n }\n\n async approvalRedirect(state: string): Promise<string> {\n const pending = await this.#readPending(state, false);\n const tenant = await this.#readTenant(pending.tenantId);\n const callback = new URL(\"/connect/callback\", this.#config.publicUrl);\n callback.searchParams.set(\"state\", state);\n const params = new URLSearchParams({\n did: tenant.sessionDid,\n callback: callback.toString(),\n host: this.#config.nodeHost,\n jwk: Buffer.from(JSON.stringify(publicJwk(tenant.jwk))).toString(\"base64url\"),\n permissions: Buffer.from(JSON.stringify({\n permissions: pending.permissions,\n reason: [\n pending.kind === \"bootstrap\"\n ? \"Connect this TinyCloud account to the hosted MCP delegate.\"\n : \"Approve the exact capabilities requested by the TinyCloud MCP operation.\",\n // Owner DIDs come from the verified OpenKey access token of the MCP\n // client that created this link, never from the link itself.\n ...(pending.ownerDids.length === 0\n ? []\n : [`Requested by TinyCloud account ${pending.ownerDids.join(\", \")}; approve only if that is you.`]),\n ].join(\" \"),\n })).toString(\"base64url\"),\n expiry: this.#config.delegationExpiry,\n });\n return `${this.#config.openkeyHost.replace(/\\/+$/, \"\")}/delegate?${params.toString()}`;\n }\n\n async completeApproval(state: string, request: Request): Promise<void> {\n const length = Number(request.headers.get(\"content-length\") ?? \"0\");\n if (Number.isFinite(length) && length > MAX_CALLBACK_BYTES) throw new Error(\"Callback body is too large.\");\n const text = await request.text();\n if (Buffer.byteLength(text) > MAX_CALLBACK_BYTES) throw new Error(\"Callback body is too large.\");\n const data = JSON.parse(text) as unknown;\n if (!isRecord(data)) throw new Error(\"Callback body is invalid.\");\n\n const pending = await this.#readPending(state, true);\n try {\n const tenant = await this.#readTenant(pending.tenantId);\n if (pending.kind === \"bootstrap\") {\n await this.#storeBootstrap(tenant, pending, data);\n } else {\n await this.#storeDelegation(tenant, pending, data);\n }\n await rm(this.#pendingPath(tenant.stateRoot, pending.nonce) + \".processing\", { force: true });\n } catch (error) {\n await this.#restorePending(pending).catch(() => undefined);\n throw error;\n }\n }\n\n async #storeBootstrap(\n tenant: TenantProfile,\n pending: PendingApproval,\n data: Record<string, unknown>,\n ): Promise<void> {\n const { node, session } = await this.#restoreApproval(tenant, data);\n if (pending.ownerDids.length > 0 && !pending.ownerDids.some((did) => samePrincipal(node.did, did))) {\n throw new ApprovalOwnerMismatchError();\n }\n // The verifier reports one entry per signed action; the SDK subset check\n // judges each requested entry against every matching grant together.\n if (!isCapabilitySubset(pending.permissions, node.getVerifiedSessionCapabilities()).subset) {\n throw new Error(\"The approved delegation does not cover the requested account access.\");\n }\n const profile = await readJson<Record<string, unknown>>(this.#profilePath(tenant.stateRoot));\n await secureWrite(this.#profilePath(tenant.stateRoot), {\n ...profile,\n ownerDid: normalizeDid(node.did),\n spaceId: session.spaceId,\n });\n await secureWrite(this.#sessionPath(tenant.stateRoot), {\n authMethod: \"openkey\",\n ...session,\n });\n }\n\n async #storeDelegation(\n tenant: TenantProfile,\n pending: PendingApproval,\n data: Record<string, unknown>,\n ): Promise<void> {\n if (pending.requestId === undefined) throw new Error(\"Authority request is missing.\");\n // Unlike bootstrap there is no empty-list exemption: a delegation is only\n // imported when its verified signer is the OAuth principal that asked.\n const { node, session } = await this.#restoreApproval(tenant, data);\n if (!pending.ownerDids.some((did) => samePrincipal(node.did, did))) throw new ApprovalOwnerMismatchError();\n // OpenKey returns a signed-login (CACAO) delegation. Every field is\n // projected from the verified SIWE; `tinycloud.auth.import` verifies it\n // again and checks it stays within the stored request.\n const delegation = siweRuntimeDelegation(node, {\n authorization: session.delegationHeader.Authorization,\n cid: session.delegationCid,\n spaceId: session.spaceId,\n ownerAddress: session.address,\n chainId: session.chainId,\n siwe: session.siwe,\n signature: session.signature,\n host: this.#config.nodeHost,\n });\n const result = await invokeOperation(\n \"tinycloud.auth.import\",\n 1,\n { profile: PROFILE, stateRoot: tenant.stateRoot },\n {\n kind: \"tinycloud.auth.delegation\",\n version: 1,\n requestId: pending.requestId,\n delegationCid: delegation.cid,\n delegation,\n },\n );\n if (result.status !== \"ok\") throw new Error(\"TinyCloud rejected the approved delegation.\");\n }\n\n /**\n * Verify the OpenKey callback as a SIWE session for this tenant's key. The\n * callback must carry the full signed proof (SIWE, signature, address and\n * chain), so the WASM verifier always runs: it binds the authorization bytes\n * and CID to the signed SIWE, and `node.did` is the wallet that signed\n * exactly the delegation being stored.\n */\n async #restoreApproval(\n tenant: TenantProfile,\n data: Record<string, unknown>,\n ): Promise<{ node: TinyCloudNode; session: CallbackSession }> {\n const session = sessionFromCallback(data, tenant.jwk);\n const node = new TinyCloudNode({ host: this.#config.nodeHost });\n await node.restoreSession(session);\n if (!samePrincipal(node.sessionDid, tenant.sessionDid)) {\n throw new Error(\"The approved delegation targets a different session.\");\n }\n return { node, session };\n }\n\n async #ensureTenant(subject: string): Promise<TenantProfile> {\n const tenantId = this.#tenantId(subject);\n const current = this.#initializing.get(tenantId);\n if (current !== undefined) return current;\n const initializing = this.#initializeTenant(tenantId).finally(() => {\n this.#initializing.delete(tenantId);\n });\n this.#initializing.set(tenantId, initializing);\n return initializing;\n }\n\n async #hasValidSession(tenant: TenantProfile, ownerDids: readonly string[]): Promise<boolean> {\n const raw = await readJson<Record<string, unknown>>(this.#sessionPath(tenant.stateRoot));\n if (raw === null) return false;\n try {\n const node = new TinyCloudNode({ host: this.#config.nodeHost });\n await node.restoreSession(raw as unknown as TinyCloudSession);\n return samePrincipal(node.sessionDid, tenant.sessionDid) &&\n ownerDids.some((did) => samePrincipal(node.did, did));\n } catch {\n await rm(this.#sessionPath(tenant.stateRoot), { force: true });\n return false;\n }\n }\n\n async #initializeTenant(tenantId: string): Promise<TenantProfile> {\n const stateRoot = join(this.#config.stateDir, \"tenants\", tenantId);\n const keyPath = this.#keyPath(stateRoot);\n await secureDirectory(join(stateRoot, \".tinycloud\", \"profiles\", PROFILE));\n let jwk = await readJson<Record<string, unknown>>(keyPath);\n let sessionDid: string;\n if (jwk === null) {\n const generated = generateSessionKey();\n jwk = generated.jwk;\n sessionDid = generated.did;\n await secureWrite(keyPath, jwk);\n } else {\n sessionDid = didFromJwk(jwk);\n }\n const profilePath = this.#profilePath(stateRoot);\n if (!(await fileExists(profilePath))) {\n await secureWrite(profilePath, {\n name: PROFILE,\n host: this.#config.nodeHost,\n chainId: 1,\n spaceName: \"default\",\n did: sessionDid,\n sessionDid,\n createdAt: new Date().toISOString(),\n posture: \"delegate-session\",\n operatorType: \"agent\",\n authMethod: \"openkey\",\n openkeyHost: this.#config.openkeyHost,\n });\n }\n return { stateRoot, sessionDid, jwk };\n }\n\n async #readTenant(tenantId: string): Promise<TenantProfile> {\n if (!/^[a-f0-9]{64}$/.test(tenantId)) throw new Error(\"Approval state is invalid.\");\n const stateRoot = join(this.#config.stateDir, \"tenants\", tenantId);\n const jwk = await readJson<Record<string, unknown>>(this.#keyPath(stateRoot));\n if (jwk === null) throw new Error(\"The TinyCloud delegate no longer exists.\");\n return { stateRoot, jwk, sessionDid: didFromJwk(jwk) };\n }\n\n async #createPending(\n subject: string,\n ownerDids: readonly string[],\n kind: PendingApproval[\"kind\"],\n permissions: PermissionEntry[],\n requestId?: string,\n ): Promise<PendingApproval> {\n const tenant = await this.#ensureTenant(subject);\n const tenantId = this.#tenantId(subject);\n const reusable = await reusablePending(\n this.#pendingDirectory(tenant.stateRoot),\n { tenantId, kind, requestId, permissions, ownerDids: ownerDids.map(normalizeDid) },\n );\n if (reusable !== undefined) return reusable;\n const nonce = randomBytes(24).toString(\"base64url\");\n const created = Date.now();\n const pending: PendingApproval = {\n version: 1,\n nonce,\n tenantId,\n kind,\n ...(requestId === undefined ? {} : { requestId }),\n permissions,\n ownerDids: ownerDids.map(normalizeDid),\n createdAt: new Date(created).toISOString(),\n expiresAt: new Date(created + this.#config.approvalTtlSeconds * 1000).toISOString(),\n };\n await secureWrite(this.#pendingPath(tenant.stateRoot, nonce), pending);\n return pending;\n }\n\n async #readPending(state: string, consume: boolean): Promise<PendingApproval> {\n const [tenantId, nonce, signature] = state.split(\".\");\n if (tenantId === undefined || nonce === undefined || signature === undefined) {\n throw new Error(\"Approval state is invalid.\");\n }\n const expected = this.#signState(tenantId, nonce);\n const supplied = Buffer.from(signature, \"base64url\");\n const expectedBytes = Buffer.from(expected, \"base64url\");\n if (supplied.length !== expectedBytes.length || !timingSafeEqual(supplied, expectedBytes)) {\n throw new Error(\"Approval state is invalid.\");\n }\n const stateRoot = join(this.#config.stateDir, \"tenants\", tenantId);\n const path = this.#pendingPath(stateRoot, nonce);\n const claimed = `${path}.processing`;\n if (consume) await rename(path, claimed);\n try {\n const pending = await readJson<PendingApproval>(consume ? claimed : path);\n if (pending === null || pending.version !== 1 || pending.tenantId !== tenantId || pending.nonce !== nonce) {\n throw new Error(\"Approval state is invalid or already used.\");\n }\n if (new Date(pending.expiresAt).getTime() <= Date.now()) {\n await rm(consume ? claimed : path, { force: true });\n throw new Error(\"Approval state has expired.\");\n }\n return pending;\n } catch (error) {\n if (consume) await rename(claimed, path).catch(() => undefined);\n throw error;\n }\n }\n\n async #restorePending(pending: PendingApproval): Promise<void> {\n const stateRoot = join(this.#config.stateDir, \"tenants\", pending.tenantId);\n const path = this.#pendingPath(stateRoot, pending.nonce);\n await rename(`${path}.processing`, path);\n }\n\n #connectUrl(pending: PendingApproval): string {\n const url = new URL(\"/connect\", this.#config.publicUrl);\n url.searchParams.set(\"state\", `${pending.tenantId}.${pending.nonce}.${this.#signState(pending.tenantId, pending.nonce)}`);\n return url.toString();\n }\n\n #tenantId(subject: string): string {\n return createHmac(\"sha256\", this.#config.stateSecret).update(`tenant:${subject}`).digest(\"hex\");\n }\n\n #signState(tenantId: string, nonce: string): string {\n return createHmac(\"sha256\", this.#config.stateSecret)\n .update(`approval:${tenantId}:${nonce}`)\n .digest(\"base64url\");\n }\n\n #profilePath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"profile.json\");\n }\n\n #keyPath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"key.json\");\n }\n\n #sessionPath(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"session.json\");\n }\n\n #pendingPath(stateRoot: string, nonce: string): string {\n return join(this.#pendingDirectory(stateRoot), `${nonce}.json`);\n }\n\n #pendingDirectory(stateRoot: string): string {\n return join(stateRoot, \".tinycloud\", \"profiles\", PROFILE, \"pending\");\n }\n}\n\nlet wasmInitialized = false;\n\nfunction generateSessionKey(): { jwk: Record<string, unknown>; did: string } {\n ensureWasm();\n const manager = new TCWSessionManager();\n const keyId = manager.createSessionKey(\"hosted-mcp\");\n const serialized = manager.jwk(keyId);\n if (!serialized) throw new Error(\"Could not generate the hosted delegate key.\");\n return { jwk: JSON.parse(serialized) as Record<string, unknown>, did: manager.getDID(keyId) };\n}\n\nfunction didFromJwk(jwk: Record<string, unknown>): string {\n ensureWasm();\n const manager = new TCWSessionManager();\n const keyId = importKey(manager, JSON.stringify(jwk), \"hosted-mcp\");\n return manager.getDID(keyId);\n}\n\nfunction ensureWasm(): void {\n if (wasmInitialized) return;\n initPanicHook();\n wasmInitialized = true;\n}\n\n/**\n * Parse the OpenKey callback. Every signed-proof field is required: without\n * them `restoreSession` verifies nothing and `node.did` would fall back to the\n * tenant's own key.\n */\nfunction sessionFromCallback(data: Record<string, unknown>, privateJwk: Record<string, unknown>): CallbackSession {\n const delegationHeader = data.delegationHeader;\n if (!isRecord(delegationHeader) || typeof delegationHeader.Authorization !== \"string\" ||\n typeof data.delegationCid !== \"string\" || typeof data.spaceId !== \"string\" ||\n typeof data.verificationMethod !== \"string\" || typeof data.address !== \"string\" ||\n typeof data.chainId !== \"number\" || typeof data.siwe !== \"string\" ||\n typeof data.signature !== \"string\") {\n throw new Error(\"OpenKey returned an incomplete delegation.\");\n }\n return {\n delegationHeader: { Authorization: delegationHeader.Authorization },\n delegationCid: data.delegationCid,\n spaceId: data.spaceId,\n jwk: privateJwk,\n verificationMethod: data.verificationMethod,\n address: data.address,\n chainId: data.chainId,\n siwe: data.siwe,\n signature: data.signature,\n };\n}\n\nfunction publicJwk(jwk: Record<string, unknown>): Record<string, unknown> {\n const copy = { ...jwk };\n for (const field of [\"d\", \"p\", \"q\", \"dp\", \"dq\", \"qi\", \"oth\", \"k\"]) delete copy[field];\n return copy;\n}\n\nfunction samePrincipal(left: string | undefined, right: string): boolean {\n if (typeof left !== \"string\") return false;\n try {\n return principalDidEquals(left, right);\n } catch {\n return false;\n }\n}\n\nfunction normalizeDid(value: string): string {\n return value.split(\"#\", 1)[0]!;\n}\n\nfunction isPermissionEntry(value: unknown): value is PermissionEntry {\n return isRecord(value) && typeof value.service === \"string\" && typeof value.space === \"string\" &&\n typeof value.path === \"string\" && Array.isArray(value.actions) &&\n value.actions.every((action) => typeof action === \"string\");\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nasync function secureDirectory(path: string): Promise<void> {\n await mkdir(path, { recursive: true, mode: 0o700 });\n await chmod(path, 0o700);\n}\n\nasync function secureWrite(path: string, value: unknown): Promise<void> {\n const directory = dirname(path);\n await secureDirectory(directory);\n const temporary = `${path}.${process.pid}.${randomBytes(8).toString(\"hex\")}.tmp`;\n await writeFile(temporary, `${JSON.stringify(value, jsonReplacer, 2)}\\n`, { mode: 0o600 });\n await rename(temporary, path);\n await chmod(path, 0o600);\n}\n\nfunction jsonReplacer(_key: string, value: unknown): unknown {\n return value instanceof Date ? value.toISOString() : value;\n}\n\nasync function readJson<T>(path: string): Promise<T | null> {\n try {\n return JSON.parse(await readFile(path, \"utf8\")) as T;\n } catch (error) {\n if (isRecord(error) && error.code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nasync function fileExists(path: string): Promise<boolean> {\n return (await readJson<unknown>(path)) !== null;\n}\n\nasync function reusablePending(\n directory: string,\n expected: Pick<PendingApproval, \"tenantId\" | \"kind\" | \"requestId\" | \"permissions\" | \"ownerDids\">,\n): Promise<PendingApproval | undefined> {\n let names: string[];\n try {\n names = await readdir(directory);\n } catch (error) {\n if (isRecord(error) && error.code === \"ENOENT\") return undefined;\n throw error;\n }\n const active: PendingApproval[] = [];\n for (const name of names) {\n if (!name.endsWith(\".json\")) continue;\n const path = join(directory, name);\n const pending = await readJson<PendingApproval>(path).catch(() => null);\n if (pending === null || new Date(pending.expiresAt).getTime() <= Date.now()) {\n await rm(path, { force: true });\n continue;\n }\n active.push(pending);\n if (samePendingRequest(pending, expected)) return pending;\n }\n if (active.length >= 64) {\n active.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt));\n await rm(join(directory, `${active[0]!.nonce}.json`), { force: true });\n }\n return undefined;\n}\n\nfunction samePendingRequest(\n pending: PendingApproval,\n expected: Pick<PendingApproval, \"tenantId\" | \"kind\" | \"requestId\" | \"permissions\" | \"ownerDids\">,\n): boolean {\n return pending.version === 1 && pending.tenantId === expected.tenantId &&\n pending.kind === expected.kind && pending.requestId === expected.requestId &&\n JSON.stringify(pending.permissions) === JSON.stringify(expected.permissions) &&\n JSON.stringify(pending.ownerDids) === JSON.stringify(expected.ownerDids);\n}\n","import { McpServer } from \"@modelcontextprotocol/server\";\nimport { serveStdio, type StdioServerHandle } from \"@modelcontextprotocol/server/stdio\";\n\nimport { createJsonSchemaValidator, registerTinyCloudTools, type McpStartupSelection } from \"./tools.js\";\nimport { MCP_VERSION } from \"./version.js\";\n\nexport const MCP_SERVER_NAME = \"tinycloud-mcp\";\nexport { MCP_VERSION } from \"./version.js\";\n/** The stdio server is always the local surface. */\nexport type LocalMcpSelection = Omit<McpStartupSelection, \"surface\">;\n\nexport function createTinyCloudMcpServer(selection: LocalMcpSelection): McpServer {\n const validator = createJsonSchemaValidator();\n const server = new McpServer(\n { name: MCP_SERVER_NAME, version: MCP_VERSION },\n { jsonSchemaValidator: validator },\n );\n registerTinyCloudTools(server, { ...selection, surface: \"local\" }, validator);\n return server;\n}\n\n/** Start the only supported MCP transport: local stdio. */\nexport function serveTinyCloudMcp(selection: LocalMcpSelection): StdioServerHandle {\n return serveStdio(\n () => createTinyCloudMcpServer(selection),\n { onerror: () => writeBoundedDiagnostic(\"MCP transport error\") },\n );\n}\n\nfunction writeBoundedDiagnostic(message: string): void {\n process.stderr.write(`[tinycloud-mcp] ${message}\\n`);\n}\n","import { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\n\nimport { fromJsonSchema, type McpServer, type ToolAnnotations } from \"@modelcontextprotocol/server\";\nimport { addFormats, Ajv, AjvJsonSchemaValidator } from \"@modelcontextprotocol/server/validators/ajv\";\nimport { invokeOperation } from \"@tinycloud/operations\";\n\nimport { toMcpToolResult, type McpToolResult } from \"./results.js\";\n\nexport const TOOL_NAMES = [\n \"tinycloud_status\",\n \"tinycloud_auth_status\",\n \"tinycloud_auth_capabilities\",\n \"tinycloud_auth_request\",\n \"tinycloud_auth_import\",\n \"tinycloud_account_spaces_list\",\n \"tinycloud_account_applications_list\",\n \"tinycloud_kv_list\",\n \"tinycloud_kv_get\",\n \"tinycloud_kv_head\",\n \"tinycloud_kv_put\",\n \"tinycloud_kv_delete\",\n \"tinycloud_sql_schema_inspect\",\n \"tinycloud_sql_query\",\n \"tinycloud_sql_execute\",\n \"tinycloud_secrets_get\",\n \"tinycloud_secrets_status\",\n] as const;\n\nexport type ToolName = (typeof TOOL_NAMES)[number];\n\n/** MCP server surfaces: local stdio and the hosted OAuth HTTP server. */\nexport type McpSurface = \"local\" | \"hosted\";\n\nexport interface McpStartupSelection {\n /** Which server registers the tools; bindings not on this surface are skipped. */\n readonly surface: McpSurface;\n readonly profile: string;\n readonly explicitProfile: boolean;\n readonly allowOwnerProfile: boolean;\n /** Absolute TinyCloud home used to isolate one hosted OAuth principal. */\n readonly stateRoot?: string;\n /** Hosted transports may attach a browser approval URL to canonical results. */\n readonly transformOperationResult?: (result: unknown) => Promise<unknown>;\n}\n\nexport interface McpInvocationTarget {\n readonly profile: string;\n readonly allowOwnerProfile?: true;\n readonly stateRoot?: string;\n}\n\n/** Project one startup selection into the only owner-sensitive target shape. */\nexport function invocationTargetForMcp(\n selection: Omit<McpStartupSelection, \"surface\">,\n): McpInvocationTarget {\n return {\n profile: selection.profile,\n ...(selection.explicitProfile && selection.allowOwnerProfile\n ? { allowOwnerProfile: true }\n : {}),\n ...(selection.stateRoot === undefined ? {} : { stateRoot: selection.stateRoot }),\n };\n}\n\ninterface CatalogOperation {\n readonly id: string;\n readonly version: number;\n readonly title: string;\n readonly description: string;\n readonly input: Record<string, unknown>;\n readonly result: Record<string, unknown>;\n}\n\ninterface OperationsCatalog {\n readonly operations: readonly CatalogOperation[];\n}\n\n// The require anchor is this module, never the consumer entrypoint. In ESM\n// tsup preserves import.meta.url; in CJS it rewrites the same module-relative\n// anchor to the generated __filename, so both formats stay in MCP's package\n// dependency boundary.\nconst packageRequire = createRequire(\n typeof __dirname === \"string\" ? join(__dirname, \"tools.cjs\") : import.meta.url,\n);\nconst generatedCatalog = packageRequire(\n \"@tinycloud/operations/operations.json\",\n) as OperationsCatalog;\n\nexport interface ToolBinding {\n readonly name: ToolName;\n readonly operationId: string;\n readonly operationVersion: number;\n readonly readOnlyHint: boolean;\n readonly idempotentHint: boolean;\n readonly destructiveHint: boolean;\n readonly openWorldHint: boolean;\n /** Surfaces that register this tool; omitted means every surface. */\n readonly surfaces?: readonly McpSurface[];\n}\n\nconst ALL_SURFACES: readonly McpSurface[] = [\"local\", \"hosted\"];\n\n/** The surfaces a binding is registered on. */\nexport function bindingSurfaces(binding: ToolBinding): readonly McpSurface[] {\n return binding.surfaces ?? ALL_SURFACES;\n}\n\nexport const TOOL_BINDINGS: readonly ToolBinding[] = [\n {\n name: \"tinycloud_status\",\n operationId: \"tinycloud.status.get\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_status\",\n operationId: \"tinycloud.auth.status\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_capabilities\",\n operationId: \"tinycloud.auth.capabilities\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_request\",\n operationId: \"tinycloud.auth.request\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n {\n name: \"tinycloud_auth_import\",\n operationId: \"tinycloud.auth.import\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n // Hosted delegations must arrive through the owner/request-bound OpenKey callback,\n // not a caller-supplied import artifact.\n surfaces: [\"local\"],\n },\n {\n name: \"tinycloud_account_spaces_list\",\n operationId: \"tinycloud.account.spaces.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_account_applications_list\",\n operationId: \"tinycloud.account.applications.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_list\",\n operationId: \"tinycloud.kv.list\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_get\",\n operationId: \"tinycloud.kv.get\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_head\",\n operationId: \"tinycloud.kv.head\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_put\",\n operationId: \"tinycloud.kv.put\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: true,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_kv_delete\",\n operationId: \"tinycloud.kv.delete\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: true,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_sql_schema_inspect\",\n operationId: \"tinycloud.sql.schema.inspect\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_sql_query\",\n operationId: \"tinycloud.sql.query\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_sql_execute\",\n operationId: \"tinycloud.sql.execute\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_secrets_get\",\n operationId: \"tinycloud.secrets.get\",\n operationVersion: 1,\n readOnlyHint: false,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n },\n {\n name: \"tinycloud_secrets_status\",\n operationId: \"tinycloud.secrets.status\",\n operationVersion: 1,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: true,\n // Hosted has no persistent reauthorization path for a revoked session\n // yet (TC-896), so status is local/stdio only.\n surfaces: [\"local\"],\n },\n] as const;\n\nexport function createJsonSchemaValidator(): AjvJsonSchemaValidator {\n const ajv = new Ajv({ strict: false });\n addFormats(ajv);\n return new AjvJsonSchemaValidator(ajv);\n}\n\nexport function registerTinyCloudTools(\n server: McpServer,\n selection: McpStartupSelection,\n validator: AjvJsonSchemaValidator,\n): void {\n const definitions = new Map(\n generatedCatalog.operations.map((operation) => [\n `${operation.id}@${operation.version}`,\n operation,\n ]),\n );\n\n for (const binding of TOOL_BINDINGS) {\n if (!bindingSurfaces(binding).includes(selection.surface)) continue;\n const operation = definitions.get(`${binding.operationId}@${binding.operationVersion}`);\n if (operation === undefined) {\n throw new Error(`Generated operations catalog is missing ${binding.operationId}@${binding.operationVersion}.`);\n }\n\n const inputSchema = fromJsonSchema(\n operation.input as Parameters<typeof fromJsonSchema>[0],\n validator,\n );\n const outputSchema = fromJsonSchema(\n operation.result as unknown as Parameters<typeof fromJsonSchema>[0],\n validator,\n );\n const annotations: ToolAnnotations = {\n readOnlyHint: binding.readOnlyHint,\n idempotentHint: binding.idempotentHint,\n destructiveHint: binding.destructiveHint,\n openWorldHint: binding.openWorldHint,\n };\n\n server.registerTool(\n binding.name,\n {\n title: operation.title,\n description: operation.description,\n inputSchema,\n outputSchema,\n annotations,\n },\n async (input: unknown): Promise<McpToolResult> => {\n const result = await invokeOperation(\n binding.operationId,\n binding.operationVersion,\n invocationTargetForMcp(selection),\n input,\n );\n const projected = selection.transformOperationResult === undefined\n ? result\n : await selection.transformOperationResult(result);\n return toMcpToolResult(projected, TOOL_BINDINGS);\n },\n );\n }\n}\n\nexport function toolBindingsForTest(): readonly ToolBinding[] {\n return TOOL_BINDINGS;\n}\n","/**\n * MCP has one structured result channel for a TinyCloud operation. Text is a\n * fixed, non-sensitive status line; it never serializes the operation result.\n */\nexport interface CanonicalOperationResult {\n readonly status: \"ok\" | \"authority_required\" | \"setup_required\" | \"error\";\n readonly [key: string]: unknown;\n}\n\nexport interface McpToolResult extends CallToolResult {\n readonly content: [{ readonly type: \"text\"; readonly text: string }];\n readonly structuredContent: CanonicalOperationResult;\n}\n\n/** The binding fields needed to name the tool that runs an operation. */\nexport interface RecoveryToolBinding {\n readonly name: string;\n readonly operationId: string;\n}\n\nexport function toMcpToolResult(\n result: unknown,\n bindings: readonly RecoveryToolBinding[] = [],\n): McpToolResult {\n const canonical: CanonicalOperationResult = isCanonicalOperationResult(result)\n ? withRecoveryTool(result, bindings)\n : {\n status: \"error\",\n operation: {},\n context: {},\n error: { code: \"INTERNAL_ERROR\" },\n };\n\n return {\n content: [{ type: \"text\", text: resultSummary(canonical.status) }],\n structuredContent: canonical,\n };\n}\n\n/**\n * A redacted `complete_migration` recovery names an operation; MCP clients\n * call tools, so name the bound tool. `tool` comes from the code-owned binding\n * table only, never from operation data, and is added after redaction. An\n * operationId with no binding gets no `tool`.\n */\nfunction withRecoveryTool(\n result: CanonicalOperationResult,\n bindings: readonly RecoveryToolBinding[],\n): CanonicalOperationResult {\n if (result.status !== \"error\") return result;\n // The kernel's redaction already constrained `error.details.recovery` to a\n // safe recovery object; only its discriminant and operationId are read here.\n const error = result.error as\n | { readonly details?: { readonly recovery?: { readonly action?: unknown; readonly operationId?: unknown } } }\n | undefined;\n const recovery = error?.details?.recovery;\n if (recovery?.action !== \"complete_migration\") return result;\n const binding = bindings.find((candidate) => candidate.operationId === recovery.operationId);\n if (binding === undefined) return result;\n return {\n ...result,\n error: { ...error, details: { ...error?.details, recovery: { ...recovery, tool: binding.name } } },\n };\n}\n\n/** The canonical envelope immediately before MCP protocol serialization. */\nexport function canonicalMcpAdapterResult(result: unknown): CanonicalOperationResult {\n return toMcpToolResult(result).structuredContent;\n}\n\nfunction isCanonicalOperationResult(value: unknown): value is CanonicalOperationResult {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n const status = (value as { status?: unknown }).status;\n return status === \"ok\" ||\n status === \"authority_required\" ||\n status === \"setup_required\" ||\n status === \"error\";\n}\n\nfunction resultSummary(status: CanonicalOperationResult[\"status\"]): string {\n switch (status) {\n case \"ok\":\n return \"TinyCloud operation completed; use the structured result.\";\n case \"authority_required\":\n return \"TinyCloud authority is required; use the structured request and approval action.\";\n case \"setup_required\":\n return \"TinyCloud setup is required; use the structured setup action.\";\n case \"error\":\n return \"TinyCloud operation failed; use the structured error.\";\n }\n}\nimport type { CallToolResult } from \"@modelcontextprotocol/server\";\n","{\n \"name\": \"@tinycloud/mcp\",\n \"version\": \"0.5.3-beta.1\",\n \"description\": \"TinyCloud delegated operations MCP server\",\n \"keywords\": [\n \"tinycloud\",\n \"mcp\",\n \"model-context-protocol\",\n \"agents\",\n \"delegation\",\n \"ucan\",\n \"kv\",\n \"sqlite\"\n ],\n \"author\": \"TinyCloud, Inc.\",\n \"license\": \"EGPL\",\n \"type\": \"module\",\n \"main\": \"dist/index.cjs\",\n \"module\": \"dist/index.js\",\n \"types\": \"dist/index.d.ts\",\n \"bin\": {\n \"tinycloud-mcp\": \"./bin/tinycloud-mcp\",\n \"tinycloud-mcp-http\": \"./bin/tinycloud-mcp-http\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./server\": {\n \"types\": \"./dist/server.d.ts\",\n \"import\": \"./dist/server.js\",\n \"require\": \"./dist/server.cjs\"\n },\n \"./tools\": {\n \"types\": \"./dist/tools.d.ts\",\n \"import\": \"./dist/tools.js\",\n \"require\": \"./dist/tools.cjs\"\n },\n \"./results\": {\n \"types\": \"./dist/results.d.ts\",\n \"import\": \"./dist/results.js\",\n \"require\": \"./dist/results.cjs\"\n },\n \"./http\": {\n \"types\": \"./dist/http.d.ts\",\n \"import\": \"./dist/http.js\",\n \"require\": \"./dist/http.cjs\"\n }\n },\n \"files\": [\n \"dist\",\n \"bin\",\n \"generated\",\n \"skills\"\n ],\n \"engines\": {\n \"node\": \">=20\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"clean\": \"rm -rf dist\",\n \"test\": \"bun run build && bun scripts/test.ts && bun run check:generated\",\n \"test:stdio\": \"bun run build && bun test src/stdio.test.ts\",\n \"typecheck\": \"tsc -p tsconfig.json\",\n \"start:http\": \"node dist/http-cli.js\",\n \"generate\": \"bun scripts/generate.ts\",\n \"check:generated\": \"bun scripts/generate.ts --check\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/node\": \"2.0.0-beta.4\",\n \"@modelcontextprotocol/server\": \"2.0.0-beta.4\",\n \"@tinycloud/node-sdk\": \"3.2.3-beta.0\",\n \"@tinycloud/node-sdk-wasm\": \"1.7.7\",\n \"@tinycloud/operations\": \"0.5.3-beta.1\",\n \"jose\": \"6.1.3\"\n },\n \"devDependencies\": {\n \"@modelcontextprotocol/client\": \"2.0.0-beta.4\",\n \"@types/node\": \"^20\",\n \"tsup\": \"^8.0.0\",\n \"typescript\": \"^5.9.3\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/TinyCloudLabs/js-sdk\"\n },\n \"homepage\": \"https://docs.tinycloud.xyz/cli/mcp\"\n}\n","import packageMetadata from \"../package.json\";\n\nexport const MCP_VERSION = packageMetadata.version;\n"],"mappings":";AAAA,SAAS,oBAAoB;AAC7B,SAAS,YAAY,eAAe;AAEpC,SAAS,qBAAqB;;;ACH9B;AAAA,EACE,aAAAA;AAAA,EACA;AAAA,EACA,kBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;;;ACVP;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AACP,SAAS,cAAc;AACvB,SAAS,oBAAoB,QAAQ,iBAAkC;AAEvE,IAAM,mBAAmB;AASlB,SAAS,2BAA2B,QAAgD;AACzF,QAAM,OAAO,mBAAmB,IAAI,IAAI,OAAO,OAAO,CAAC;AACvD,SAAO;AAAA,IACL,MAAM,kBAAkB,OAAkC;AACxD,UAAI;AACF,cAAM,EAAE,QAAQ,IAAI,MAAM,UAAU,OAAO,MAAM;AAAA,UAC/C,QAAQ,OAAO;AAAA,UACf,UAAU,OAAO;AAAA,QACnB,CAAC;AACD,eAAO,SAAS,OAAO,SAAS,MAAM;AA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AI;AACjC,MAAI,CAAC,WAAW,KAAK,EAAG,OAAM,IAAI,MAAM,GAAG,IAAI,4BAA4B;AAC3E,SAAO,QAAQ,KAAK;AACtB;AAEA,SAAS,gBAAgB,OAA2B,UAA0B;AAC5E,MAAI,UAAU,OAAW,QAAO;AAChC,QAAM,SAAS,OAAO,KAAK;AAC3B,MAAI,CAAC,OAAO,UAAU,MAAM,KAAK,UAAU,EAAG,OAAM,IAAI,MAAM,gDAAgD;AAC9G,SAAO;AACT;AAEA,SAAS,UAAU,OAAiD;AAClE,MAAI,UAAU,OAAW,QAAO;AAChC,SAAO,MAAM,MAAM,GAAG,EAAE,IAAI,CAAC,UAAU,MAAM,KAAK,CAAC,EAAE,OAAO,OAAO;AACrE;AAEA,KAAK,KAAK,EAAE,MAAM,MAAM;AACtB,UAAQ,OAAO,MAAM,wCAAwC;AAC7D,UAAQ,WAAW;AACrB,CAAC;","names":["McpServer","fromJsonSchema","join","invokeOperation","join","invokeOperation","authInfo","McpServer","originFailure","fromJsonSchema"]}
package/dist/http.cjs CHANGED
@@ -833,7 +833,7 @@ function registerTinyCloudTools(server, selection, validator) {
833
833
  // package.json
834
834
  var package_default = {
835
835
  name: "@tinycloud/mcp",
836
- version: "0.5.2",
836
+ version: "0.5.3-beta.1",
837
837
  description: "TinyCloud delegated operations MCP server",
838
838
  keywords: [
839
839
  "tinycloud",
@@ -904,9 +904,9 @@ var package_default = {
904
904
  dependencies: {
905
905
  "@modelcontextprotocol/node": "2.0.0-beta.4",
906
906
  "@modelcontextprotocol/server": "2.0.0-beta.4",
907
- "@tinycloud/node-sdk": "3.2.2",
907
+ "@tinycloud/node-sdk": "3.2.3-beta.0",
908
908
  "@tinycloud/node-sdk-wasm": "1.7.7",
909
- "@tinycloud/operations": "0.5.2",
909
+ "@tinycloud/operations": "0.5.3-beta.1",
910
910
  jose: "6.1.3"
911
911
  },
912
912
  devDependencies: {