@kya-os/mcp-i-cloudflare 1.17.0 → 1.18.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.
Files changed (268) hide show
  1. package/README.md +273 -54
  2. package/dist/adapter.d.ts +3 -17
  3. package/dist/adapter.d.ts.map +1 -1
  4. package/dist/adapter.js +39 -477
  5. package/dist/adapter.js.map +1 -1
  6. package/dist/agent.d.ts +59 -35
  7. package/dist/agent.d.ts.map +1 -1
  8. package/dist/agent.js +386 -404
  9. package/dist/agent.js.map +1 -1
  10. package/dist/app.d.ts.map +1 -1
  11. package/dist/app.js +150 -94
  12. package/dist/app.js.map +1 -1
  13. package/dist/audit/deployment-binding.d.ts +16 -16
  14. package/dist/authority-outcome.d.ts +110 -0
  15. package/dist/authority-outcome.d.ts.map +1 -0
  16. package/dist/authority-outcome.js +154 -0
  17. package/dist/authority-outcome.js.map +1 -0
  18. package/dist/config.d.ts +8 -77
  19. package/dist/config.d.ts.map +1 -1
  20. package/dist/config.js +0 -83
  21. package/dist/config.js.map +1 -1
  22. package/dist/delegation-http/bearer-retry.d.ts +84 -32
  23. package/dist/delegation-http/bearer-retry.d.ts.map +1 -1
  24. package/dist/delegation-http/bearer-retry.js +124 -139
  25. package/dist/delegation-http/bearer-retry.js.map +1 -1
  26. package/dist/delegation-http/connect-gate.d.ts +47 -0
  27. package/dist/delegation-http/connect-gate.d.ts.map +1 -0
  28. package/dist/delegation-http/connect-gate.js +104 -0
  29. package/dist/delegation-http/connect-gate.js.map +1 -0
  30. package/dist/delegation-http/constants.d.ts +4 -49
  31. package/dist/delegation-http/constants.d.ts.map +1 -1
  32. package/dist/delegation-http/constants.js +4 -58
  33. package/dist/delegation-http/constants.js.map +1 -1
  34. package/dist/delegation-http/issuer-binding.d.ts +26 -0
  35. package/dist/delegation-http/issuer-binding.d.ts.map +1 -0
  36. package/dist/delegation-http/issuer-binding.js +51 -0
  37. package/dist/delegation-http/issuer-binding.js.map +1 -0
  38. package/dist/delegation-http/lazy-auth-gate.d.ts +88 -0
  39. package/dist/delegation-http/lazy-auth-gate.d.ts.map +1 -0
  40. package/dist/delegation-http/lazy-auth-gate.js +203 -0
  41. package/dist/delegation-http/lazy-auth-gate.js.map +1 -0
  42. package/dist/delegation-http/native-challenge.d.ts +52 -0
  43. package/dist/delegation-http/native-challenge.d.ts.map +1 -0
  44. package/dist/delegation-http/native-challenge.js +124 -0
  45. package/dist/delegation-http/native-challenge.js.map +1 -0
  46. package/dist/delegation-http/native-consent-redirect.d.ts +21 -0
  47. package/dist/delegation-http/native-consent-redirect.d.ts.map +1 -0
  48. package/dist/delegation-http/native-consent-redirect.js +43 -0
  49. package/dist/delegation-http/native-consent-redirect.js.map +1 -0
  50. package/dist/delegation-http/native-http.d.ts +1 -86
  51. package/dist/delegation-http/native-http.d.ts.map +1 -1
  52. package/dist/delegation-http/native-http.js +2 -130
  53. package/dist/delegation-http/native-http.js.map +1 -1
  54. package/dist/delegation-http/native-oauth-state-do.d.ts +13 -35
  55. package/dist/delegation-http/native-oauth-state-do.d.ts.map +1 -1
  56. package/dist/delegation-http/native-oauth-state-do.js +10 -165
  57. package/dist/delegation-http/native-oauth-state-do.js.map +1 -1
  58. package/dist/delegation-http/protected-resource.d.ts +37 -0
  59. package/dist/delegation-http/protected-resource.d.ts.map +1 -0
  60. package/dist/delegation-http/protected-resource.js +43 -0
  61. package/dist/delegation-http/protected-resource.js.map +1 -0
  62. package/dist/delegation-http/request-proof.d.ts +20 -0
  63. package/dist/delegation-http/request-proof.d.ts.map +1 -0
  64. package/dist/delegation-http/request-proof.js +29 -0
  65. package/dist/delegation-http/request-proof.js.map +1 -0
  66. package/dist/delegation-http/sid.d.ts +4 -12
  67. package/dist/delegation-http/sid.d.ts.map +1 -1
  68. package/dist/delegation-http/sid.js +4 -19
  69. package/dist/delegation-http/sid.js.map +1 -1
  70. package/dist/delegation-http/well-known-capability.d.ts +8 -12
  71. package/dist/delegation-http/well-known-capability.d.ts.map +1 -1
  72. package/dist/delegation-http/well-known-capability.js +9 -18
  73. package/dist/delegation-http/well-known-capability.js.map +1 -1
  74. package/dist/helpers/env-mapper.d.ts.map +1 -1
  75. package/dist/helpers/env-mapper.js +7 -29
  76. package/dist/helpers/env-mapper.js.map +1 -1
  77. package/dist/index.d.ts +2 -4
  78. package/dist/index.d.ts.map +1 -1
  79. package/dist/index.js +11 -8
  80. package/dist/index.js.map +1 -1
  81. package/dist/proof-generator.d.ts +24 -17
  82. package/dist/proof-generator.d.ts.map +1 -1
  83. package/dist/proof-generator.js +42 -56
  84. package/dist/proof-generator.js.map +1 -1
  85. package/dist/runtime/amount-limit-refusal.d.ts +3 -0
  86. package/dist/runtime/amount-limit-refusal.d.ts.map +1 -0
  87. package/dist/runtime/amount-limit-refusal.js +7 -0
  88. package/dist/runtime/amount-limit-refusal.js.map +1 -0
  89. package/dist/runtime/oauth-handler.d.ts +1 -1
  90. package/dist/runtime/oauth-handler.d.ts.map +1 -1
  91. package/dist/runtime/oauth-handler.js +31 -34
  92. package/dist/runtime/oauth-handler.js.map +1 -1
  93. package/dist/runtime.d.ts +34 -10
  94. package/dist/runtime.d.ts.map +1 -1
  95. package/dist/runtime.js +65 -16
  96. package/dist/runtime.js.map +1 -1
  97. package/dist/security/admission-refusal.d.ts +3 -3
  98. package/dist/security/admission-refusal.d.ts.map +1 -1
  99. package/dist/security/admission-refusal.js +14 -6
  100. package/dist/security/admission-refusal.js.map +1 -1
  101. package/dist/security/holder-binding.d.ts +34 -0
  102. package/dist/security/holder-binding.d.ts.map +1 -0
  103. package/dist/security/holder-binding.js +75 -0
  104. package/dist/security/holder-binding.js.map +1 -0
  105. package/dist/security/mcp-admission.d.ts +29 -1
  106. package/dist/security/mcp-admission.d.ts.map +1 -1
  107. package/dist/security/mcp-admission.js +78 -12
  108. package/dist/security/mcp-admission.js.map +1 -1
  109. package/dist/security/native-holder-admission.d.ts +39 -0
  110. package/dist/security/native-holder-admission.d.ts.map +1 -0
  111. package/dist/security/native-holder-admission.js +65 -0
  112. package/dist/security/native-holder-admission.js.map +1 -0
  113. package/dist/security/outcome-proof.d.ts +39 -0
  114. package/dist/security/outcome-proof.d.ts.map +1 -0
  115. package/dist/security/outcome-proof.js +54 -0
  116. package/dist/security/outcome-proof.js.map +1 -0
  117. package/dist/security/request-nonce-store.d.ts +43 -0
  118. package/dist/security/request-nonce-store.d.ts.map +1 -0
  119. package/dist/security/request-nonce-store.js +129 -0
  120. package/dist/security/request-nonce-store.js.map +1 -0
  121. package/dist/security/routed-request.d.ts +41 -0
  122. package/dist/security/routed-request.d.ts.map +1 -0
  123. package/dist/security/routed-request.js +86 -0
  124. package/dist/security/routed-request.js.map +1 -0
  125. package/dist/security/sign-in-amr.d.ts +23 -0
  126. package/dist/security/sign-in-amr.d.ts.map +1 -0
  127. package/dist/security/sign-in-amr.js +44 -0
  128. package/dist/security/sign-in-amr.js.map +1 -0
  129. package/dist/services/approval-route.d.ts +3 -2
  130. package/dist/services/approval-route.d.ts.map +1 -1
  131. package/dist/services/approval-route.js.map +1 -1
  132. package/dist/services/checkpoint-decision.d.ts +56 -0
  133. package/dist/services/checkpoint-decision.d.ts.map +1 -0
  134. package/dist/services/checkpoint-decision.js +109 -0
  135. package/dist/services/checkpoint-decision.js.map +1 -0
  136. package/dist/services/consent-page-renderer.d.ts.map +1 -1
  137. package/dist/services/consent-page-renderer.js +2 -3
  138. package/dist/services/consent-page-renderer.js.map +1 -1
  139. package/dist/services/consent.service.d.ts +11 -49
  140. package/dist/services/consent.service.d.ts.map +1 -1
  141. package/dist/services/consent.service.js +81 -307
  142. package/dist/services/consent.service.js.map +1 -1
  143. package/dist/services/credential-auth.handler.d.ts.map +1 -1
  144. package/dist/services/credential-auth.handler.js +2 -8
  145. package/dist/services/credential-auth.handler.js.map +1 -1
  146. package/dist/services/delegation-authority.d.ts +53 -0
  147. package/dist/services/delegation-authority.d.ts.map +1 -0
  148. package/dist/services/delegation-authority.js +130 -0
  149. package/dist/services/delegation-authority.js.map +1 -0
  150. package/dist/services/delegation-trust.d.ts +35 -64
  151. package/dist/services/delegation-trust.d.ts.map +1 -1
  152. package/dist/services/delegation-trust.js +98 -279
  153. package/dist/services/delegation-trust.js.map +1 -1
  154. package/dist/services/delegation.service.d.ts +83 -105
  155. package/dist/services/delegation.service.d.ts.map +1 -1
  156. package/dist/services/delegation.service.js +166 -518
  157. package/dist/services/delegation.service.js.map +1 -1
  158. package/dist/services/idp-token-storage.d.ts +32 -12
  159. package/dist/services/idp-token-storage.d.ts.map +1 -1
  160. package/dist/services/idp-token-storage.js +79 -36
  161. package/dist/services/idp-token-storage.js.map +1 -1
  162. package/dist/services/issuer-keys.d.ts +55 -0
  163. package/dist/services/issuer-keys.d.ts.map +1 -0
  164. package/dist/services/issuer-keys.js +184 -0
  165. package/dist/services/issuer-keys.js.map +1 -0
  166. package/dist/services/oauth-security.service.d.ts +17 -1
  167. package/dist/services/oauth-security.service.d.ts.map +1 -1
  168. package/dist/services/oauth-security.service.js +29 -10
  169. package/dist/services/oauth-security.service.js.map +1 -1
  170. package/dist/services/proof.service.d.ts +10 -0
  171. package/dist/services/proof.service.d.ts.map +1 -1
  172. package/dist/services/proof.service.js +28 -6
  173. package/dist/services/proof.service.js.map +1 -1
  174. package/dist/services/resource-audience.d.ts +12 -9
  175. package/dist/services/resource-audience.d.ts.map +1 -1
  176. package/dist/services/resource-audience.js +12 -9
  177. package/dist/services/resource-audience.js.map +1 -1
  178. package/dist/services/unenforceable-tool-protection.d.ts +32 -0
  179. package/dist/services/unenforceable-tool-protection.d.ts.map +1 -0
  180. package/dist/services/unenforceable-tool-protection.js +90 -0
  181. package/dist/services/unenforceable-tool-protection.js.map +1 -0
  182. package/dist/services/upstream-fetch.d.ts +14 -0
  183. package/dist/services/upstream-fetch.d.ts.map +1 -0
  184. package/dist/services/upstream-fetch.js +56 -0
  185. package/dist/services/upstream-fetch.js.map +1 -0
  186. package/dist/types.d.ts +5 -18
  187. package/dist/types.d.ts.map +1 -1
  188. package/dist/utils/oauth-profile.d.ts +19 -0
  189. package/dist/utils/oauth-profile.d.ts.map +1 -1
  190. package/dist/utils/oauth-profile.js +54 -1
  191. package/dist/utils/oauth-profile.js.map +1 -1
  192. package/dist/utils/tool-security-schemes.d.ts +65 -0
  193. package/dist/utils/tool-security-schemes.d.ts.map +1 -0
  194. package/dist/utils/tool-security-schemes.js +168 -0
  195. package/dist/utils/tool-security-schemes.js.map +1 -0
  196. package/package.json +5 -6
  197. package/dist/delegation-http/anchor-do.d.ts +0 -84
  198. package/dist/delegation-http/anchor-do.d.ts.map +0 -1
  199. package/dist/delegation-http/anchor-do.js +0 -412
  200. package/dist/delegation-http/anchor-do.js.map +0 -1
  201. package/dist/delegation-http/anchor-registration-validate.d.ts +0 -61
  202. package/dist/delegation-http/anchor-registration-validate.d.ts.map +0 -1
  203. package/dist/delegation-http/anchor-registration-validate.js +0 -191
  204. package/dist/delegation-http/anchor-registration-validate.js.map +0 -1
  205. package/dist/delegation-http/anchor-registration.d.ts +0 -62
  206. package/dist/delegation-http/anchor-registration.d.ts.map +0 -1
  207. package/dist/delegation-http/anchor-registration.js +0 -337
  208. package/dist/delegation-http/anchor-registration.js.map +0 -1
  209. package/dist/delegation-http/anchor-routing.d.ts +0 -20
  210. package/dist/delegation-http/anchor-routing.d.ts.map +0 -1
  211. package/dist/delegation-http/anchor-routing.js +0 -27
  212. package/dist/delegation-http/anchor-routing.js.map +0 -1
  213. package/dist/delegation-http/challenge-middleware.d.ts +0 -28
  214. package/dist/delegation-http/challenge-middleware.d.ts.map +0 -1
  215. package/dist/delegation-http/challenge-middleware.js +0 -190
  216. package/dist/delegation-http/challenge-middleware.js.map +0 -1
  217. package/dist/delegation-http/challenge.d.ts +0 -102
  218. package/dist/delegation-http/challenge.d.ts.map +0 -1
  219. package/dist/delegation-http/challenge.js +0 -223
  220. package/dist/delegation-http/challenge.js.map +0 -1
  221. package/dist/delegation-http/consent-anchor-bridge.d.ts +0 -70
  222. package/dist/delegation-http/consent-anchor-bridge.d.ts.map +0 -1
  223. package/dist/delegation-http/consent-anchor-bridge.js +0 -1130
  224. package/dist/delegation-http/consent-anchor-bridge.js.map +0 -1
  225. package/dist/delegation-http/consent-preparation-page.d.ts +0 -18
  226. package/dist/delegation-http/consent-preparation-page.d.ts.map +0 -1
  227. package/dist/delegation-http/consent-preparation-page.js +0 -172
  228. package/dist/delegation-http/consent-preparation-page.js.map +0 -1
  229. package/dist/delegation-http/credential-consent.d.ts +0 -149
  230. package/dist/delegation-http/credential-consent.d.ts.map +0 -1
  231. package/dist/delegation-http/credential-consent.js +0 -338
  232. package/dist/delegation-http/credential-consent.js.map +0 -1
  233. package/dist/delegation-http/native-capabilities.d.ts +0 -4
  234. package/dist/delegation-http/native-capabilities.d.ts.map +0 -1
  235. package/dist/delegation-http/native-capabilities.js +0 -53
  236. package/dist/delegation-http/native-capabilities.js.map +0 -1
  237. package/dist/delegation-http/native-oauth-state.d.ts +0 -28
  238. package/dist/delegation-http/native-oauth-state.d.ts.map +0 -1
  239. package/dist/delegation-http/native-oauth-state.js +0 -146
  240. package/dist/delegation-http/native-oauth-state.js.map +0 -1
  241. package/dist/delegation-http/native-oauth.d.ts +0 -26
  242. package/dist/delegation-http/native-oauth.d.ts.map +0 -1
  243. package/dist/delegation-http/native-oauth.js +0 -393
  244. package/dist/delegation-http/native-oauth.js.map +0 -1
  245. package/dist/delegation-http/native-pickup.d.ts +0 -20
  246. package/dist/delegation-http/native-pickup.d.ts.map +0 -1
  247. package/dist/delegation-http/native-pickup.js +0 -227
  248. package/dist/delegation-http/native-pickup.js.map +0 -1
  249. package/dist/delegation-http/pickup-routes.d.ts +0 -43
  250. package/dist/delegation-http/pickup-routes.d.ts.map +0 -1
  251. package/dist/delegation-http/pickup-routes.js +0 -166
  252. package/dist/delegation-http/pickup-routes.js.map +0 -1
  253. package/dist/delegation-http/register.d.ts +0 -26
  254. package/dist/delegation-http/register.d.ts.map +0 -1
  255. package/dist/delegation-http/register.js +0 -95
  256. package/dist/delegation-http/register.js.map +0 -1
  257. package/dist/delegation-http/registrar-auth.d.ts +0 -24
  258. package/dist/delegation-http/registrar-auth.d.ts.map +0 -1
  259. package/dist/delegation-http/registrar-auth.js +0 -61
  260. package/dist/delegation-http/registrar-auth.js.map +0 -1
  261. package/dist/delegation-http/remote-issuer.d.ts +0 -52
  262. package/dist/delegation-http/remote-issuer.d.ts.map +0 -1
  263. package/dist/delegation-http/remote-issuer.js +0 -324
  264. package/dist/delegation-http/remote-issuer.js.map +0 -1
  265. package/dist/delegation-http/types.d.ts +0 -116
  266. package/dist/delegation-http/types.d.ts.map +0 -1
  267. package/dist/delegation-http/types.js +0 -11
  268. package/dist/delegation-http/types.js.map +0 -1
package/dist/agent.js CHANGED
@@ -8,24 +8,35 @@
8
8
  import { McpAgent } from "agents/mcp";
9
9
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
10
10
  import { AdmissionMcpServer, getMcpRequestHolder, getMcpPresentedDelegation, } from "./security/mcp-admission";
11
- import { localToolProtectionConfig, resolveHttpChallengeConfig, } from "./config";
11
+ import { WWW_AUTHENTICATE_META_KEY, buildDeniedResult, buildNeedsAuthorizationResult, deniedText, isStatefulDenial, orgConnectUrl, } from "./authority-outcome";
12
+ import { registerNativeChallenge } from "./delegation-http/native-challenge";
13
+ import { parseNativeIssuerBinding } from "./delegation-http/issuer-binding";
14
+ import { addSecuritySchemesToListing, kvLastKnownGoodProtections, } from "./utils/tool-security-schemes";
15
+ import { nativeRailHolderAdmission } from "./security/native-holder-admission";
16
+ import { REQUEST_NONCE_CONSUME_PATH, handleRequestNonceConsume, } from "./security/request-nonce-store";
17
+ import { localToolProtectionConfig } from "./config";
18
+ import { isToolProtectionUnenforceableError, unenforceableToolProtectionService, } from "./services/unenforceable-tool-protection";
12
19
  import { CloudflareRuntime } from "./runtime";
13
20
  import { createCloudflareRuntime } from "./index";
14
21
  import { mapPrefixedEnv } from "./helpers/env-mapper";
15
22
  import { makeEnvSecretResolver } from "./utils/env-secret-resolver.js";
16
- import { handlePickupInternal } from "./delegation-http/anchor-do";
17
23
  import { NATIVE_OAUTH_INTERNAL_PREFIX } from "./delegation-http/native-oauth-state-do";
18
24
  import { augmentKyaOsIdentityWellKnown } from "./delegation-http/well-known-capability";
19
25
  import { resolveCloudflareAuditAssurance } from "./audit/assurance";
20
26
  import { createCloudflareAuditRuntimeFromEnv } from "./audit/deployment-binding";
21
- import { isAnchorRegistrationEnabled } from "./delegation-http/anchor-registration";
22
27
  import { STORAGE_KEYS } from "./constants/storage-keys";
23
28
  import { DEFAULT_SESSION_TTL } from "./constants";
24
29
  import { buildNeedsAuthorizationMeta } from "./needs-authorization-meta";
30
+ import { isAmountLimitError } from "./runtime/amount-limit-refusal";
31
+ import { amrSatisfiesAuthType } from "./security/sign-in-amr";
32
+ import { amountLimitToolResult, terminalForToolError, } from "@kya-os/mcp-i-runtime";
25
33
  import { z } from "zod";
26
34
  import { generateDidKeyFromBase64, logger } from "@kya-os/mcp";
27
- import { OAuthService, IdpTokenResolver, ToolContextBuilder, OAuthRequiredError, DelegationRequiredError, DelegationErrorFormatter, SessionRegistrationService, SESSION_ID_PREFIX, recordWireForm, generateResumeToken, authTypeSatisfies, isUnsatisfiableAuthType, MINTABLE_AUTH_TYPES, } from "@kya-os/mcp-i-runtime"; // product layer — stays (C2/C3)
35
+ import { OAuthService, IdpTokenResolver, ToolContextBuilder, OAuthRequiredError, DelegationRequiredError, DelegationErrorFormatter, SessionRegistrationService, SESSION_ID_PREFIX, recordWireForm, generateResumeToken, } from "@kya-os/mcp-i-runtime"; // product layer — stays (C2/C3)
28
36
  import { WebCryptoProvider } from "./providers/crypto";
37
+ import { createDeploymentDelegationService } from "./services/delegation.service";
38
+ import { collectNarrowGrant, } from "./services/delegation-authority";
39
+ import { getRoutedHeaderDelegation, getRoutedHost, runInRoutedRequest, } from "./security/routed-request";
29
40
  // CRITICAL: Import the OAuth service registry - this triggers globalThis registration
30
41
  // at module load time, preventing esbuild from tree-shaking the OAuth services
31
42
  import { getOAuthServices, isOAuthServicesAvailable, } from "./utils/oauth-service-registry";
@@ -49,6 +60,8 @@ import { withCheckpointNames } from "@kya-os/contracts/config";
49
60
  // Without this, esbuild may eliminate oauth-service-registry.ts entirely
50
61
  // because the exports are only used inside conditional async code
51
62
  const _oauthRegistryLoaded = isOAuthServicesAvailable();
63
+ /** The audience of every proof a call's session signs. */
64
+ const PROOF_AUDIENCE = "https://kya.vouched.id";
52
65
  if (!_oauthRegistryLoaded) {
53
66
  // Logger not yet configured at module init, use console.warn as fallback
54
67
  console.warn("[MCPICloudflareAgent] OAuth service registry not loaded at module init - services may be unavailable");
@@ -130,12 +143,16 @@ export class MCPICloudflareAgent extends McpAgent {
130
143
  mappedEnv._durableObjectState = state;
131
144
  // Load runtime configuration from subclass
132
145
  const runtimeConfig = this.getRuntimeConfigInternal(mappedEnv);
133
- if (runtimeConfig.requestAdmission) {
134
- this.server = new AdmissionMcpServer({ name: agentName, version: agentVersion || "1.0.0" }, runtimeConfig.requestAdmission, {
146
+ // A native-rail deployment with no admission of its own gets the one that
147
+ // proves a key-bound credential's holder (security/native-holder-admission).
148
+ const requestAdmission = runtimeConfig.requestAdmission ?? nativeRailHolderAdmission(mappedEnv);
149
+ if (requestAdmission) {
150
+ this.server = new AdmissionMcpServer({ name: agentName, version: agentVersion || "1.0.0" }, requestAdmission, {
135
151
  // Read at report time: mcpiRuntime is created further down.
136
152
  reportRefusal: async (report) => {
137
153
  await this.mcpiRuntime?.reportAdmissionRefusal(report);
138
154
  },
155
+ onRefusal: (refusal) => this.signAdmissionRefusal(refusal),
139
156
  });
140
157
  }
141
158
  const managedAudit = createCloudflareAuditRuntimeFromEnv(mappedEnv);
@@ -156,7 +173,8 @@ export class MCPICloudflareAgent extends McpAgent {
156
173
  // Discovery must use the same effective audit trail as the initialized
157
174
  // runtime, including managed bindings absent from the template defaults.
158
175
  this._runtimeConfig = runtimeConfig;
159
- // Create tool protection service if configured
176
+ // Create tool protection service if configured. Configured protection the
177
+ // deployment can't enforce (no API key or no cache binding) fails closed.
160
178
  const toolProtectionService = runtimeConfig.toolProtection &&
161
179
  mappedEnv.TOOL_PROTECTION_KV &&
162
180
  mappedEnv.CHECKPOINT_API_KEY
@@ -182,7 +200,9 @@ export class MCPICloudflareAgent extends McpAgent {
182
200
  }
183
201
  : undefined,
184
202
  })
185
- : undefined;
203
+ : runtimeConfig.toolProtection
204
+ ? unenforceableToolProtectionService(runtimeConfig.toolProtection, mappedEnv)
205
+ : undefined;
186
206
  // Initialize MCP-I runtime
187
207
  this.mcpiRuntime = createCloudflareRuntime({
188
208
  env: mappedEnv,
@@ -565,10 +585,13 @@ export class MCPICloudflareAgent extends McpAgent {
565
585
  /**
566
586
  * The delegation verifier the runtime uses for protected tool calls.
567
587
  *
568
- * Subclasses can ask the same verifier a question the runtime would ask,
569
- * with the same credentials and base URL, instead of building their own
570
- * client. Undefined when no CHECKPOINT_API_KEY is configured (the runtime
571
- * then has no remote verifier either).
588
+ * Subclasses can ask the same verifier a question the runtime would ask
589
+ * instead of building their own client. It verifies the presented
590
+ * credential locally (org issuer, kid-named key, this worker's resource DID
591
+ * as audience, the issuer's signed status list), then consults Checkpoint
592
+ * as a decision hook, never as the authority. Undefined when no
593
+ * CHECKPOINT_API_KEY is configured (the runtime then has no verifier, and a
594
+ * protected tool fails closed).
572
595
  *
573
596
  * @example
574
597
  * ```typescript
@@ -608,12 +631,42 @@ export class MCPICloudflareAgent extends McpAgent {
608
631
  await this.registerConsentUIResource();
609
632
  // Register tools (implemented by subclasses)
610
633
  await this.registerTools();
634
+ // Per-tool securitySchemes on tools/list, from the served protection.
635
+ // Wrapped after registration, once the SDK has installed its handler.
636
+ if (!addSecuritySchemesToListing(this.server, () => this.servedToolProtections(), this.lastKnownGoodSecuritySchemes())) {
637
+ logger.warn("[MCPICloudflareAgent] No tools/list handler found; securitySchemes not added");
638
+ }
611
639
  }
612
640
  catch (error) {
613
641
  logger.error("[MCPICloudflareAgent] Initialization failed:", error);
614
642
  throw error;
615
643
  }
616
644
  }
645
+ /**
646
+ * Last-known-good store for the tools/list securitySchemes, keyed by the
647
+ * agent DID. The key resolves lazily so init does not wait on it. Undefined
648
+ * without the KV binding; the listing then keeps an in-memory copy only.
649
+ */
650
+ lastKnownGoodSecuritySchemes() {
651
+ // The same binding the tool protection service caches in, prefix included.
652
+ const envPrefix = this.getEnvPrefix();
653
+ const mappedEnv = envPrefix
654
+ ? mapPrefixedEnv(this.env, envPrefix)
655
+ : this.env;
656
+ const kv = mappedEnv.TOOL_PROTECTION_KV;
657
+ if (!kv)
658
+ return undefined;
659
+ const store = async () => {
660
+ const did = (await this.mcpiRuntime?.getIdentity())?.did;
661
+ if (!did)
662
+ throw new Error("agent identity unavailable");
663
+ return kvLastKnownGoodProtections(kv, `security-schemes:last-known-good:${did}`);
664
+ };
665
+ return {
666
+ get: async () => (await store()).get(),
667
+ put: async (protections) => (await store()).put(protections),
668
+ };
669
+ }
617
670
  /**
618
671
  * Register the MCP Apps consent UI resource.
619
672
  *
@@ -1000,72 +1053,20 @@ export class MCPICloudflareAgent extends McpAgent {
1000
1053
  project_id: z.string(),
1001
1054
  resume_token: z.string(),
1002
1055
  };
1003
- const approveConsentHandler = async (args) => {
1004
- const envPrefix = this.getEnvPrefix();
1005
- const mappedEnv = envPrefix
1006
- ? mapPrefixedEnv(this.env, envPrefix)
1007
- : this.env;
1008
- const serverUrl = mappedEnv.MCP_SERVER_URL ??
1009
- this._autoDetectedOrigin;
1010
- if (!serverUrl) {
1011
- return {
1012
- content: [
1013
- {
1014
- type: "text",
1015
- text: JSON.stringify({
1016
- success: false,
1017
- error: "No server URL configured",
1018
- }),
1019
- },
1020
- ],
1021
- };
1022
- }
1023
- try {
1024
- const resp = await fetch(`${serverUrl}/consent/approve`, {
1025
- method: "POST",
1026
- headers: { "Content-Type": "application/json" },
1027
- body: JSON.stringify({
1028
- tool: args.tool,
1029
- scopes: args.scopes,
1030
- session_id: args.session_id,
1031
- agent_did: args.agent_did,
1032
- project_id: args.project_id,
1033
- resume_token: args.resume_token,
1034
- termsAccepted: true,
1035
- approved: true,
1036
- // The iframe's consent-only approval. /consent/approve refuses
1037
- // a missing provider_type.
1038
- provider_type: "none",
1056
+ // The iframe's approval carries no completed sign-in: approval happens
1057
+ // at the organization's authorization service, so nothing is minted here.
1058
+ const approveConsentHandler = async (_args) => ({
1059
+ content: [
1060
+ {
1061
+ type: "text",
1062
+ text: JSON.stringify({
1063
+ success: false,
1064
+ error: "This approval happens at the organization's authorization service",
1065
+ error_code: "consent_at_authorization_service",
1039
1066
  }),
1040
- });
1041
- if (!resp.ok) {
1042
- return {
1043
- content: [
1044
- {
1045
- type: "text",
1046
- text: JSON.stringify({
1047
- success: false,
1048
- error: `Server error: ${resp.status}`,
1049
- }),
1050
- },
1051
- ],
1052
- };
1053
- }
1054
- const data = await resp.json();
1055
- return { content: [{ type: "text", text: JSON.stringify(data) }] };
1056
- }
1057
- catch (err) {
1058
- const msg = err instanceof Error ? err.message : "Unknown error";
1059
- return {
1060
- content: [
1061
- {
1062
- type: "text",
1063
- text: JSON.stringify({ success: false, error: msg }),
1064
- },
1065
- ],
1066
- };
1067
- }
1068
- };
1067
+ },
1068
+ ],
1069
+ });
1069
1070
  this.server.tool("_kyaos_approve_consent", approveConsentDescription, approveConsentSchema, approveConsentHandler);
1070
1071
  this.server.tool("_mcpi_approve_consent", approveConsentDescription, approveConsentSchema, async (args) => {
1071
1072
  recordWireForm("tool_name", "old", {
@@ -1272,12 +1273,13 @@ export class MCPICloudflareAgent extends McpAgent {
1272
1273
  }
1273
1274
  // Use registerTool (not deprecated server.tool) to support _meta.ui for MCP Apps
1274
1275
  const toolCallback = async (args, extra) => {
1275
- // ✅ Automatically extract sessionId from ToolExtraArguments
1276
- // This ensures delegation tokens stored with the original session ID
1277
- // can be retrieved on subsequent tool calls
1276
+ // The transport session attributes the call; it never selects a grant.
1278
1277
  const sessionId = extra
1279
1278
  ?.sessionId;
1280
- return this.executeToolWithProof(name, args, handler, sessionId);
1279
+ // Scope this call to the request the worker forwarded: its routed host
1280
+ // (the worker-set X-MCP-Original-Origin) and its header credential.
1281
+ const headers = extra?.requestInfo?.headers;
1282
+ return runInRoutedRequest(headers, () => this.executeToolWithProof(name, args, handler, sessionId));
1281
1283
  };
1282
1284
  // Build tool config with optional MCP Apps UI metadata
1283
1285
  // When ext-apps consent UI is registered, include _meta.ui.resourceUri
@@ -1315,7 +1317,7 @@ export class MCPICloudflareAgent extends McpAgent {
1315
1317
  * @param args - Tool arguments
1316
1318
  * @param handler - Tool handler function
1317
1319
  * @param providedSessionId - Optional session ID from MCP request (extracted from ToolExtraArguments.sessionId)
1318
- * If provided, uses this session ID for delegation token lookup.
1320
+ * Attributes the call to that session; it never selects a delegation.
1319
1321
  * If not provided, falls back to getSessionId() or generates ephemeral ID.
1320
1322
  */
1321
1323
  async executeToolWithProof(toolName, args, handler, providedSessionId) {
@@ -1459,134 +1461,38 @@ export class MCPICloudflareAgent extends McpAgent {
1459
1461
  serverUrl: serverUrl?.slice(0, 50) || "undefined",
1460
1462
  });
1461
1463
  }
1462
- // ✅ Look up delegation token from DO storage (strongly consistent)
1463
- // Using DO internal storage eliminates KV eventual consistency issues.
1464
- // No retry mechanism needed - storage and retrieval happen on the same DO instance.
1465
- let delegationToken;
1464
+ // The client presents its delegation on every call: Authorization: Bearer
1465
+ // or the KYA-OS header. Admission reads it (with any body carrier) before
1466
+ // the SDK sees the request; without admission it comes from the forwarded
1467
+ // request's headers. Nothing is looked up by session id, user DID or agent
1468
+ // DID, so a grant is never resolved from a session. Account identity comes
1469
+ // only from a credential that verifies locally, for the host this request
1470
+ // was routed for; a refused one is still handed to the runtime, whose
1471
+ // verifier refuses it again and reports why.
1472
+ const delegationToken = getMcpPresentedDelegation() ?? getRoutedHeaderDelegation();
1466
1473
  let delegationId;
1467
1474
  let userDid;
1468
- let clientDid;
1469
- // SECURITY (consent-approve auth-gate, Task B2/B3): the presented
1470
- // delegation's own authorization type, surfaced from storage so the gate in
1471
- // buildToolContext can require it to satisfy the tool's required type.
1472
- // Remains undefined for the KV-legacy / JWT-extraction fallbacks below (no
1473
- // stored type) → fail-safe re-challenge on typed tools.
1474
- let delegationAuthorizationType;
1475
- try {
1476
- const agentDid = getMcpRequestHolder()?.did ??
1477
- (await this.mcpiRuntime.getIdentity()).did;
1478
- logger.debug("[MCPICloudflareAgent] 🔍 Starting delegation lookup (DO storage):", {
1479
- sessionId: sessionId.slice(0, 20) + "...",
1480
- agentDid: agentDid.slice(0, 20) + "...",
1475
+ // How the account's person signed in, from the same verified credential.
1476
+ let delegationAmr;
1477
+ if (delegationToken) {
1478
+ const verified = await createDeploymentDelegationService(mappedEnv, getRoutedHost()).verifyLocally(delegationToken, {
1479
+ holderDid: getMcpRequestHolder()?.did,
1481
1480
  });
1482
- // Get userDid and clientDid from KV session data (still needed for identity context)
1483
- const delegationStorage = mappedEnv.DELEGATION_STORAGE;
1484
- if (delegationStorage) {
1485
- const identityKey = STORAGE_KEYS.sessionIdentity(sessionId);
1486
- const sessionKey = STORAGE_KEYS.session(sessionId);
1487
- const identityData = (await delegationStorage.get(identityKey, "json"));
1488
- const sessionData = (await delegationStorage.get(sessionKey, "json"));
1489
- userDid = identityData?.userDid || sessionData?.userDid;
1490
- clientDid = sessionData?.clientDid;
1491
- }
1492
- // Look up delegation from DO storage (strongly consistent - no retries needed)
1493
- const doData = await this.getDelegationFromStorage(sessionId, userDid, agentDid);
1494
- if (doData) {
1495
- delegationToken = doData.delegationToken;
1496
- delegationId = doData.delegationId;
1497
- // Task B2: surface the stored delegation auth type for the call-time gate
1498
- delegationAuthorizationType = doData.authorizationType;
1499
- // Prefer userDid from DO storage if available
1500
- if (doData.userDid) {
1501
- userDid = doData.userDid;
1502
- }
1503
- logger.debug("[MCPICloudflareAgent] ✅ Delegation found in DO storage:", {
1504
- sessionId: sessionId.slice(0, 20) + "...",
1505
- delegationId,
1506
- hasUserDid: !!userDid,
1507
- });
1508
- }
1509
- else {
1510
- // Fallback: Check KV for backward compatibility with existing delegations
1511
- // This handles delegations created before the DO storage migration
1512
- if (delegationStorage && userDid) {
1513
- const userAgentKey = STORAGE_KEYS.delegation(userDid, agentDid);
1514
- const kvToken = await delegationStorage.get(userAgentKey, "text");
1515
- if (kvToken) {
1516
- delegationToken = kvToken;
1517
- // Recover the delegation's auth type from its sidecar key so this
1518
- // fallback can satisfy a typed tool. Records written before the
1519
- // sidecar existed have none — that stays undefined and the gate
1520
- // fails safe (re-challenge), which is the pre-existing behaviour
1521
- // for legacy records, not a new rejection.
1522
- delegationAuthorizationType =
1523
- (await delegationStorage.get(STORAGE_KEYS.delegationAuthType(userDid, agentDid), "text")) ?? undefined;
1524
- logger.debug("[MCPICloudflareAgent] ✅ Delegation found in KV (legacy):", {
1525
- sessionId: sessionId.slice(0, 20) + "...",
1526
- source: "kv-fallback",
1527
- hasAuthorizationType: !!delegationAuthorizationType,
1528
- });
1529
- }
1530
- }
1531
- if (!delegationToken) {
1532
- logger.debug("[MCPICloudflareAgent] ℹ️ No delegation found:", {
1533
- sessionId: sessionId.slice(0, 20) + "...",
1534
- hasUserDid: !!userDid,
1535
- note: "Delegation only required for tools with 'requiresDelegation: true'",
1536
- });
1537
- }
1538
- }
1539
- }
1540
- catch (error) {
1541
- logger.warn("[MCPICloudflareAgent] Failed to retrieve delegation:", error);
1542
- }
1543
- // A retry's explicit credential takes precedence over a cached grant. Keep
1544
- // the authenticated session account, but never borrow another grant's ID or
1545
- // authorization type. The existing runtime verifier still checks this token.
1546
- const presentedDelegation = getMcpPresentedDelegation();
1547
- if (presentedDelegation !== undefined &&
1548
- presentedDelegation !== delegationToken) {
1549
- delegationToken = presentedDelegation;
1550
- delegationId = undefined;
1551
- delegationAuthorizationType = undefined;
1552
- }
1553
- // ✅ FIX: Extract userDid from delegation token if not available from session storage
1554
- // This handles KV eventual consistency issues where session cache is stale but delegation exists
1555
- // For proved native callers, account identity must come from authenticated
1556
- // session/grant storage, never an unverified JWT payload or its agent sub.
1557
- if (delegationToken && !userDid && !getMcpRequestHolder()) {
1558
- try {
1559
- // Decode JWT payload (delegation tokens are JWTs with vc.credentialSubject.user_identifier)
1560
- const parts = delegationToken.split(".");
1561
- if (parts.length >= 2) {
1562
- const payload = JSON.parse(atob(parts[1]));
1563
- const extractedUserDid = payload.vc?.credentialSubject?.user_identifier ||
1564
- payload.user_identifier ||
1565
- payload.sub;
1566
- if (extractedUserDid && extractedUserDid.startsWith("did:")) {
1567
- userDid = extractedUserDid;
1568
- logger.debug("[MCPICloudflareAgent] ✅ Extracted userDid from delegation token:", {
1569
- userDid: extractedUserDid.slice(0, 20) + "...",
1570
- source: "delegation-token-jwt",
1571
- });
1572
- }
1573
- }
1574
- }
1575
- catch (extractError) {
1576
- logger.warn("[MCPICloudflareAgent] Failed to extract userDid from delegation token:", extractError);
1481
+ if (verified.valid) {
1482
+ delegationId = verified.delegationId;
1483
+ userDid = verified.userDid;
1484
+ delegationAmr = verified.amr;
1577
1485
  }
1578
1486
  }
1579
- // ✅ SECURITY: Use validatedClientDid from server-side session validation
1580
- // This is the authoritative clientDid - it was verified to exist in our KV store
1581
- // Only falls back to clientDid from session lookup if no validated session
1582
- const finalClientDid = validatedClientDid || clientDid;
1487
+ // ✅ SECURITY: clientDid only from server-side handshake validation.
1488
+ const finalClientDid = validatedClientDid;
1583
1489
  // Request-scoped identifiers are threaded through the runtime instead of
1584
1490
  // being stored on the Durable Object instance. Concurrent calls can then
1585
1491
  // never borrow each other's proof or audit correlation state.
1586
1492
  const auditInvocationId = crypto.randomUUID();
1587
1493
  const session = {
1588
1494
  id: sessionId,
1589
- audience: "https://kya.vouched.id",
1495
+ audience: PROOF_AUDIENCE,
1590
1496
  agentDid: getMcpRequestHolder()?.did ??
1591
1497
  (await this.mcpiRuntime.getIdentity()).did,
1592
1498
  // Trusted per-request proof result; never a client-supplied DID label.
@@ -1629,7 +1535,7 @@ export class MCPICloudflareAgent extends McpAgent {
1629
1535
  // Store AuthRequiredError to throw inside the inner try block where its handler lives
1630
1536
  let pendingAuthRequiredError = null;
1631
1537
  try {
1632
- toolContext = await this.buildToolContext(toolName, userDid, sessionId, delegationToken, delegationAuthorizationType, mappedEnv);
1538
+ toolContext = await this.buildToolContext(toolName, userDid, sessionId, delegationToken, delegationAmr, delegationId, mappedEnv);
1633
1539
  }
1634
1540
  catch (error) {
1635
1541
  // Handle CredentialAuthModeError - build consent page URL (not OAuth URL)
@@ -1830,6 +1736,11 @@ export class MCPICloudflareAgent extends McpAgent {
1830
1736
  return pendingInlineResult;
1831
1737
  }
1832
1738
  // Wrap in try-catch to handle DelegationRequiredError and format for MCP clients
1739
+ // Whether the runtime's audit has seen this call. A refusal thrown before
1740
+ // processToolCall never reaches it, so its terminal event is recorded here.
1741
+ let runtimeAudited = false;
1742
+ // The scopes of a presented grant the verifier finds too narrow, if any.
1743
+ const narrowGrant = {};
1833
1744
  try {
1834
1745
  // ✅ FIX: Throw pending errors INSIDE the try block
1835
1746
  // This ensures they're caught by the formatters below
@@ -1839,7 +1750,9 @@ export class MCPICloudflareAgent extends McpAgent {
1839
1750
  if (pendingAuthRequiredError) {
1840
1751
  throw pendingAuthRequiredError;
1841
1752
  }
1842
- const result = await this.mcpiRuntime.processToolCall(toolName, args, handlerWithContext, session);
1753
+ runtimeAudited = true;
1754
+ const runtime = this.mcpiRuntime;
1755
+ const result = await collectNarrowGrant(narrowGrant, () => runtime.processToolCall(toolName, args, handlerWithContext, session));
1843
1756
  // NOTE: Proof submission is now awaited directly in CloudflareRuntime.processToolCall()
1844
1757
  // This ensures reliable submission without relying on ctx.waitUntil() which is unreliable
1845
1758
  // in Durable Objects (McpAgent). The tradeoff is ~200-400ms additional latency per tool call.
@@ -1867,45 +1780,115 @@ export class MCPICloudflareAgent extends McpAgent {
1867
1780
  hasResumeToken: !!resumeToken,
1868
1781
  clientId: clientId || "unknown",
1869
1782
  });
1783
+ // A refused call that never reached the runtime still leaves exactly
1784
+ // one terminal event in the audit trail.
1785
+ if (!runtimeAudited) {
1786
+ await this.mcpiRuntime.recordRefusedToolCallAudit(toolNameForError, session, terminalForToolError(delegationError));
1787
+ }
1788
+ // Outcome proofs hash the request the way success proofs do.
1789
+ const callRequest = this.outcomeCall(toolNameForError, args);
1790
+ // A stateful policy refusal (a spent budget, an origin or IP rule)
1791
+ // is a signed `denied`: a new grant would not change the answer, so
1792
+ // the result carries no link.
1793
+ const denial = delegationError.denial;
1794
+ if (denial && isStatefulDenial(denial)) {
1795
+ return (await this.mcpiRuntime.signOutcomeResult(buildDeniedResult([
1796
+ {
1797
+ type: "text",
1798
+ text: deniedText(denial, toolNameForError, clientId, this.getClientMessagesConfig()),
1799
+ },
1800
+ ], denial.code), { outcome: "denied", reason: denial.code }, callRequest, session));
1801
+ }
1802
+ // Everything else a new grant could fix is a signed
1803
+ // `needs_authorization`. A native caller is a tools/call whose request
1804
+ // proof admission verified (a proved holder): the org authorization
1805
+ // service registers its challenge, and the result carries it.
1806
+ const routedHost = getRoutedHost();
1807
+ const binding = parseNativeIssuerBinding(mappedEnv.MCPI_NATIVE_HTTP_ISSUER_CONFIG);
1808
+ // The revision of the tool protection Checkpoint served for this
1809
+ // evaluation. A native challenge registration reports it, and
1810
+ // Checkpoint recomputes it (delegation-http/native-challenge).
1811
+ const policyRevision = await this.servedToolProtectionRevision();
1812
+ // A tool whose authorization needs an IdP sign-in on the worker
1813
+ // (credentials, password or oauth2) keeps the worker's own consent
1814
+ // page; only a pure delegation follows the org rules below.
1815
+ const workerSignIn = await this.requiresWorkerSignIn(toolNameForError);
1816
+ const orgRules = binding !== null && !workerSignIn;
1817
+ const nativeCaller = orgRules && !!getMcpRequestHolder();
1818
+ const nativeChallenge = nativeCaller && routedHost
1819
+ ? await registerNativeChallenge(routedHost, mappedEnv, {
1820
+ requiredScopes: scopes,
1821
+ policyRevision,
1822
+ })
1823
+ : null;
1824
+ // Where the person goes, and never the worker on the native rail: the
1825
+ // registered challenge's consent page, else the org's connect page
1826
+ // for the project. Off the rail the deployment keeps its consent URL.
1827
+ const preferredUrl = nativeChallenge
1828
+ ? nativeChallenge.http.consent_uri
1829
+ : orgRules && binding
1830
+ ? orgConnectUrl(binding)
1831
+ : delegationError.consentUrl;
1870
1832
  // Use DelegationErrorFormatter for consistent message formatting
1871
1833
  // Supports client-specific messages via getClientMessagesConfig()
1872
1834
  const formatter = new DelegationErrorFormatter(this.getClientMessagesConfig());
1873
- const { message: displayMessage, consentUrl } = formatter.format({
1835
+ const { message: displayMessage, consentUrl: formattedUrl } = formatter.format({
1874
1836
  toolName: toolNameForError,
1875
- consentUrl: delegationError.consentUrl,
1837
+ consentUrl: preferredUrl,
1876
1838
  scopes,
1877
1839
  clientId,
1878
1840
  // A verifier refusal (revoked, expired, wrong agent) gets its
1879
1841
  // configured per-code line; without one the text stays as today.
1880
- denial: delegationError.denial,
1842
+ denial,
1881
1843
  });
1844
+ // The org's URLs are signed or fixed, so they are used as given.
1845
+ const authorizationUrl = orgRules
1846
+ ? (preferredUrl ?? "")
1847
+ : (formattedUrl ?? "");
1882
1848
  // Popup launch — only attached as a hint in `_meta` so popup-aware
1883
1849
  // clients (today: `.mcpb`-installed Claude Desktop) can open the
1884
1850
  // consent URL in a stripped-chrome window. Standard clients ignore
1885
1851
  // the hint and surface the markdown link as before. The popup hint
1886
1852
  // is gated on `popupEnabled` from the resolved consent config so
1887
- // operators can opt out per-deployment.
1888
- const popupEligible = consentUrl && shouldUsePopup(clientId, this.popupEnabledForClient);
1853
+ // operators can opt out per-deployment. The connect page is not a
1854
+ // consent page, so it gets none.
1855
+ const popupEligible = authorizationUrl &&
1856
+ (nativeChallenge || !orgRules) &&
1857
+ shouldUsePopup(clientId, this.popupEnabledForClient);
1889
1858
  const popupResource = popupEligible
1890
- ? buildPopupResource(consentUrl)
1859
+ ? buildPopupResource(authorizationUrl)
1891
1860
  : undefined;
1861
+ // The legacy `_meta` keys carry milliseconds; the needs_authorization
1862
+ // envelope carries seconds, as @kya-os/mcp's own gates emit it.
1863
+ const expiresAtMs = delegationError.interceptedCall?.expiresAt ?? Date.now() + 1_800_000;
1864
+ const { result, wwwAuthenticate } = buildNeedsAuthorizationResult({
1865
+ message: displayMessage,
1866
+ authorizationUrl,
1867
+ resumeToken,
1868
+ expiresAt: Math.floor(expiresAtMs / 1000),
1869
+ scopes,
1870
+ ...(narrowGrant.scopes ? { grantedScopes: narrowGrant.scopes } : {}),
1871
+ denial,
1872
+ routedHost,
1873
+ ...(nativeChallenge ? { nativeChallenge } : {}),
1874
+ hostUnavailable: nativeCaller && !nativeChallenge,
1875
+ });
1892
1876
  // Return tool result with isError: true so MCP clients (Claude Desktop, Inspector)
1893
1877
  // surface the consent URL to users and trigger browser popup for authorization.
1894
- return {
1895
- content: [
1896
- {
1897
- type: "text",
1898
- text: displayMessage,
1899
- },
1900
- ],
1901
- isError: true,
1878
+ return (await this.mcpiRuntime.signOutcomeResult({
1879
+ ...result,
1902
1880
  // C4 (#2918) 3c dual-emit: carry BOTH the ratified DIF
1903
1881
  // needs_authorization envelope AND the legacy proprietary keys
1904
1882
  // (`errorType: "authorization_required"` — the kya-http §8.1
1905
1883
  // challenge trigger). See buildNeedsAuthorizationMeta.
1906
- _meta: buildNeedsAuthorizationMeta(delegationError, consentUrl, delegationError.interceptedCall?.expiresAt ??
1907
- Date.now() + 1_800_000, popupResource ? { popupResource } : {}),
1908
- };
1884
+ _meta: {
1885
+ ...buildNeedsAuthorizationMeta(delegationError, authorizationUrl, expiresAtMs, {
1886
+ ...(popupResource ? { popupResource } : {}),
1887
+ ...(policyRevision ? { policyRevision } : {}),
1888
+ }),
1889
+ [WWW_AUTHENTICATE_META_KEY]: wwwAuthenticate,
1890
+ },
1891
+ }, { outcome: "needs_authorization" }, callRequest, session));
1909
1892
  }
1910
1893
  // Handle OAuthRequiredError - use formatOAuth() to preserve provider name
1911
1894
  // This ensures the message says "Sign in with GitHub" instead of generic "Authorize"
@@ -1986,21 +1969,136 @@ export class MCPICloudflareAgent extends McpAgent {
1986
1969
  isError: true,
1987
1970
  };
1988
1971
  }
1972
+ if (isAmountLimitError(error)) {
1973
+ // A policy decision: a signed `denied` with the amount code as its
1974
+ // reason. The runtime already audited the refusal as denied.
1975
+ return (await this.mcpiRuntime.signOutcomeResult({
1976
+ ...amountLimitToolResult(error),
1977
+ structuredContent: { error: "denied", reason: error.code },
1978
+ }, { outcome: "denied", reason: error.code }, this.outcomeCall(error.toolName || toolName, args), session));
1979
+ }
1980
+ // Configured tool protection the deployment can't enforce: a
1981
+ // configuration error, refused before the handler ran. Human-readable
1982
+ // text plus the machine-readable JSON, as for AuthRequiredError.
1983
+ if (isToolProtectionUnenforceableError(error)) {
1984
+ return {
1985
+ content: [
1986
+ { type: "text", text: error.message },
1987
+ { type: "text", text: JSON.stringify(error.toJSON()) },
1988
+ ],
1989
+ isError: true,
1990
+ };
1991
+ }
1989
1992
  // Re-throw other errors to be handled by MCP SDK
1990
1993
  throw error;
1991
1994
  }
1992
1995
  }
1996
+ /**
1997
+ * The revision of the tool protection Checkpoint served, from the cached
1998
+ * config the runtime evaluates (same service, same cache key), or undefined
1999
+ * when the config was not served (local, fallback) or cannot be read.
2000
+ */
2001
+ async servedToolProtectionRevision() {
2002
+ return (await this.servedToolProtectionConfig())?.servedRevision;
2003
+ }
2004
+ /**
2005
+ * The served protection of every tool, from the same cached config, or
2006
+ * undefined when it cannot be resolved (the listing then omits schemes).
2007
+ */
2008
+ async servedToolProtections() {
2009
+ return (await this.servedToolProtectionConfig())?.toolProtections;
2010
+ }
2011
+ async servedToolProtectionConfig() {
2012
+ try {
2013
+ const service = this.mcpiRuntime?.config?.toolProtectionService;
2014
+ if (!service?.getToolProtectionConfig || !this.mcpiRuntime)
2015
+ return undefined;
2016
+ const agentDid = (await this.mcpiRuntime.getIdentity()).did;
2017
+ return await service.getToolProtectionConfig(agentDid);
2018
+ }
2019
+ catch {
2020
+ return undefined;
2021
+ }
2022
+ }
2023
+ /**
2024
+ * The request an outcome proof hashes: the tool name as the method and the
2025
+ * arguments as the params, as success proofs build it.
2026
+ */
2027
+ outcomeCall(toolName, args) {
2028
+ return {
2029
+ toolName,
2030
+ params: args && typeof args === "object"
2031
+ ? { ...args }
2032
+ : {},
2033
+ };
2034
+ }
2035
+ /**
2036
+ * Whether the tool's authorization needs an IdP sign-in on the worker
2037
+ * (credentials, password or oauth2), which keeps the worker's consent page.
2038
+ * A pure delegation (`none` or absent) does not. When the served protection
2039
+ * cannot be read, the answer is yes: the worker's page still sends a pure
2040
+ * delegation on to the org, while the org's link cannot sign anyone in.
2041
+ */
2042
+ async requiresWorkerSignIn(toolName) {
2043
+ try {
2044
+ const service = this.mcpiRuntime?.config?.toolProtectionService;
2045
+ // An unknown protection keeps the worker's sign-in link: only a served
2046
+ // protection that names a pure delegation goes to the org.
2047
+ if (!service?.checkToolProtection || !this.mcpiRuntime)
2048
+ return true;
2049
+ const agentDid = (await this.mcpiRuntime.getIdentity()).did;
2050
+ const protection = await service.checkToolProtection(toolName, agentDid);
2051
+ if (!protection)
2052
+ return true;
2053
+ const type = protection.authorization?.type;
2054
+ if (type === undefined)
2055
+ return Boolean(protection.oauthProvider);
2056
+ return ["credentials", "password", "oauth", "oauth2"].includes(type);
2057
+ }
2058
+ catch {
2059
+ return true;
2060
+ }
2061
+ }
2062
+ /**
2063
+ * Sign and record a tools/call that request admission refused. The reply
2064
+ * keeps its wire text and gains a `denied` outcome proof; the refusal also
2065
+ * leaves one terminal `denied` event in the audit trail. The request hash
2066
+ * covers the refused call's method and params, the only input read from the
2067
+ * unproven request. Returns nothing, so the original reply goes out, when
2068
+ * the runtime is not ready.
2069
+ */
2070
+ async signAdmissionRefusal(refusal) {
2071
+ const runtime = this.mcpiRuntime;
2072
+ if (!runtime)
2073
+ return undefined;
2074
+ const sessionId = refusal.sessionId || this.ctx.id.toString();
2075
+ const [signed] = await Promise.all([
2076
+ runtime.signOutcomeResult(buildDeniedResult(refusal.result.content, refusal.code), { outcome: "denied", reason: refusal.code }, this.outcomeCall(refusal.toolName, refusal.params.arguments), { id: sessionId, audience: PROOF_AUDIENCE }),
2077
+ runtime.recordRefusedToolCallAudit(refusal.toolName, { id: sessionId }, {
2078
+ phase: "denied",
2079
+ outcome: "denied",
2080
+ reasonCode: (refusal.refusal?.code ?? refusal.code).toUpperCase(),
2081
+ }),
2082
+ ]);
2083
+ return signed;
2084
+ }
1993
2085
  /**
1994
2086
  * Build tool execution context with IDP token (Phase 1 - MH-7)
1995
2087
  *
1996
- * @param delegationAuthorizationType - The stored authorization type of the
1997
- * presented delegation (from `getDelegationFromStorage`), or undefined for
1998
- * legacy records. Used by the delegation-only fallbacks below to reject a
1999
- * delegation whose type does not satisfy the tool's required type (security
2000
- * fix: consent-approve auth-gate, Task B3).
2088
+ * `userDid` comes only from a locally verified, presented credential. A
2089
+ * delegation never stands in for a typed tool's own credential
2090
+ * (consent-approve auth-gate, Task B3): without the stored IdP credential
2091
+ * the tool re-challenges. The stored credential is handed out only when that
2092
+ * same credential's verified `amr` shows its person signed in the way the
2093
+ * tool requires (./security/sign-in-amr), and only to the delegation that
2094
+ * claimed it (./services/idp-token-storage): a revoked or replaced
2095
+ * delegation's token is never released to another.
2096
+ *
2097
+ * @param delegationAmr - The verified credential's `amr`, or undefined.
2098
+ * @param delegationId - The verified credential's id, or undefined.
2001
2099
  * @private
2002
2100
  */
2003
- async buildToolContext(toolName, userDid, sessionId, delegationToken, delegationAuthorizationType, env) {
2101
+ async buildToolContext(toolName, userDid, sessionId, delegationToken, delegationAmr, delegationId, env) {
2004
2102
  // Only build context if userDid is available and Checkpoint API is configured.
2005
2103
  // Note: DELEGATION_STORAGE is only required for password/OAuth paths, not apikey vault.
2006
2104
  if (!userDid || !env.CHECKPOINT_API_KEY) {
@@ -2043,21 +2141,25 @@ export class MCPICloudflareAgent extends McpAgent {
2043
2141
  }
2044
2142
  // Create IdpTokenStorage to retrieve credential token
2045
2143
  const oauthSecurityService = new OAuthSecurityService(env.DELEGATION_STORAGE, env.OAUTH_ENCRYPTION_SECRET);
2144
+ // SECURITY (defence in depth): a presented delegation unlocks the
2145
+ // user's stored credential token only when its verified `amr` shows
2146
+ // the person signed in the way this tool requires. Otherwise a
2147
+ // delegation minted under the user's DID without their sign-in
2148
+ // would unlock their token. A missing or insufficient `amr` fails
2149
+ // closed. Not presenting a delegation keeps the existing behaviour.
2150
+ const presentedDelegationAllowed = !delegationToken ||
2151
+ amrSatisfiesAuthType(delegationAmr, protection.authorization?.type ?? "password");
2152
+ // Reading claims an unclaimed sign-in for the delegation the storage
2153
+ // acts for, so the check above comes first: a delegation that fails
2154
+ // it gets a storage acting for none, which reads and claims nothing.
2046
2155
  const idpTokenStorage = new IdpTokenStorage({
2047
2156
  storage: env.DELEGATION_STORAGE,
2048
2157
  oauthSecurityService,
2158
+ delegationId: presentedDelegationAllowed ? delegationId : undefined,
2049
2159
  });
2050
2160
  try {
2051
2161
  // Retrieve password auth token - getToken handles scope hashing internally
2052
2162
  const storedToken = await idpTokenStorage.getToken(userDid, provider, protection.requiredScopes || []);
2053
- // SECURITY (defence in depth): a presented delegation must satisfy
2054
- // the tool's required type before the user's stored credential token
2055
- // is handed to the tool, the same rule as the delegation-only path
2056
- // below. Otherwise a delegation minted under the user's DID without
2057
- // their sign-in would unlock their token. Not presenting a
2058
- // delegation keeps the existing behaviour.
2059
- const presentedDelegationAllowed = !delegationToken ||
2060
- authTypeSatisfies(delegationAuthorizationType, protection.authorization?.type ?? "password");
2061
2163
  if (storedToken && presentedDelegationAllowed) {
2062
2164
  // Build headers based on token usage metadata
2063
2165
  const tokenWithMeta = storedToken;
@@ -2098,66 +2200,19 @@ export class MCPICloudflareAgent extends McpAgent {
2098
2200
  return context;
2099
2201
  }
2100
2202
  else {
2101
- // No usable password auth token - check if delegation exists
2102
- // If delegation exists, tool can still execute without credential token
2103
- //
2104
- // SECURITY (consent-approve auth-gate, Task B3): the delegation only
2105
- // authorizes this tool if its OWN authorization type satisfies the
2106
- // requirement. We are provably in the password branch (isPasswordAuth
2107
- // above), so the effective requirement is "password" — fall back to it
2108
- // when the tool uses the legacy `oauthProvider: "credentials"` shape
2109
- // (authorization.type undefined). A mismatched delegation (e.g. an
2110
- // anonymous `none` consent-only delegation — the demonstrated exploit
2111
- // — or a legacy record with no persisted type → undefined) does NOT
2112
- // satisfy it; fall through to OAuthRequiredError so the tool
2113
- // re-challenges instead of executing on mere delegation presence.
2114
- const requiredAuthType = protection.authorization?.type ?? "password";
2115
- if (delegationToken &&
2116
- authTypeSatisfies(delegationAuthorizationType, requiredAuthType)) {
2117
- if (this._environment === "development") {
2118
- logger.debug("[MCPICloudflareAgent] No credential token found, but delegation exists - returning minimal context:", {
2119
- tool: toolName,
2120
- userDid: userDid?.slice(0, 20) + "...",
2121
- provider,
2122
- authType: "password",
2123
- scopes: protection.requiredScopes,
2124
- note: "Tool can execute with delegation-only authorization",
2125
- });
2126
- }
2127
- // Return minimal context with delegation info
2128
- return {
2129
- provider,
2130
- scopes: protection.requiredScopes,
2131
- userDid,
2132
- sessionId,
2133
- delegationToken,
2134
- };
2135
- }
2203
+ // No usable stored password credential: none is stored, or the
2204
+ // presented delegation's `amr` doesn't satisfy this tool. A
2205
+ // delegation never stands in for this tool's own credential
2206
+ // (consent-approve auth-gate, Task B3): the tool re-challenges.
2207
+ // Logged outside development, because it is the only signal that
2208
+ // explains the re-challenge.
2136
2209
  if (delegationToken) {
2137
- // A delegation WAS presented but its type does not satisfy the
2138
- // password requirement — log the rejection before re-challenging.
2139
- // NOT gated on development: this fires only on a rejection (so it
2140
- // is low volume), and it is the only signal that explains why a
2141
- // user is being re-challenged. Hiding it in production made the
2142
- // exact loop this follow-up addresses undiagnosable.
2143
- logger.warn("[MCPICloudflareAgent] Delegation present but auth-type does not satisfy password requirement - re-challenging:", {
2210
+ logger.warn("[MCPICloudflareAgent] Delegation present but no usable stored password credential - re-challenging:", {
2144
2211
  tool: toolName,
2145
- requiredAuthType,
2146
- delegationAuthorizationType: delegationAuthorizationType ?? null,
2212
+ requiredAuthType: protection.authorization?.type ?? "password",
2147
2213
  });
2148
- // Distinguish "re-authenticate and this resolves" from "no mint
2149
- // can ever satisfy this". Diagnostic only — the authorization
2150
- // decision above is unchanged.
2151
- if (isUnsatisfiableAuthType(requiredAuthType)) {
2152
- logger.warn("[MCPICloudflareAgent] MISCONFIGURATION: tool requires an authorization type no delegation mint can produce - this tool will re-challenge forever:", {
2153
- tool: toolName,
2154
- requiredAuthType,
2155
- mintableAuthTypes: [...MINTABLE_AUTH_TYPES],
2156
- hint: "Set the tool's authorization.type to one of the mintable types, or add mint support for the required type.",
2157
- });
2158
- }
2159
2214
  }
2160
- // No (satisfying) delegation token - throw OAuthRequiredError to trigger auth flow
2215
+ // No stored credential - throw OAuthRequiredError to trigger auth flow
2161
2216
  if (this._environment === "development") {
2162
2217
  logger.warn("[MCPICloudflareAgent] No password auth token found, throwing OAuthRequiredError:", {
2163
2218
  tool: toolName,
@@ -2358,9 +2413,21 @@ export class MCPICloudflareAgent extends McpAgent {
2358
2413
  logger.warn("[MCPICloudflareAgent] DELEGATION_STORAGE not configured, skipping IDP token storage");
2359
2414
  return undefined;
2360
2415
  }
2416
+ // The sign-in the presented credential's verified `amr` proves for
2417
+ // this tool, under the same table as the password branch: the
2418
+ // required type when it shows that sign-in, else none, and a missing
2419
+ // or insufficient `amr` re-challenges.
2420
+ const requiredAuthType = protection.authorization?.type ?? "oauth2";
2421
+ const presentedSignInType = amrSatisfiesAuthType(delegationAmr, requiredAuthType)
2422
+ ? requiredAuthType
2423
+ : undefined;
2424
+ // Reading claims an unclaimed sign-in for the delegation the storage
2425
+ // acts for, so only a delegation whose `amr` proves the sign-in reads:
2426
+ // one that doesn't gets a storage acting for none, which claims nothing.
2361
2427
  const idpTokenStorage = new IdpTokenStorage({
2362
2428
  storage: env.DELEGATION_STORAGE,
2363
2429
  oauthSecurityService,
2430
+ delegationId: presentedSignInType ? delegationId : undefined,
2364
2431
  });
2365
2432
  const tokenResolver = new IdpTokenResolver({
2366
2433
  tokenStorage: idpTokenStorage,
@@ -2372,8 +2439,20 @@ export class MCPICloudflareAgent extends McpAgent {
2372
2439
  providerResolver: providerResolver, // Phase 2: Pass ProviderResolver (type assertion for dist/src compatibility)
2373
2440
  projectId,
2374
2441
  });
2375
- // Build context
2376
- return await contextBuilder.buildContext(toolName, userDid, sessionId, delegationToken, protection, delegationAuthorizationType);
2442
+ const context = await contextBuilder.buildContext(toolName, userDid, sessionId, delegationToken, protection, presentedSignInType);
2443
+ // A delegation never stands in for the tool's own sign-in: without a
2444
+ // stored token for this delegation, the tool re-challenges.
2445
+ if (context && !context.idpToken) {
2446
+ throw new OAuthRequiredError({
2447
+ toolName,
2448
+ requiredScopes: protection.requiredScopes || [],
2449
+ provider: context.provider ?? "",
2450
+ oauthUrl: "", // Will be populated by buildOAuthUrlForError
2451
+ userDid,
2452
+ sessionId,
2453
+ });
2454
+ }
2455
+ return context;
2377
2456
  }
2378
2457
  catch (error) {
2379
2458
  // Re-throw OAuthRequiredError so it can be handled by executeToolWithProof
@@ -2582,20 +2661,18 @@ export class MCPICloudflareAgent extends McpAgent {
2582
2661
  */
2583
2662
  async fetch(request) {
2584
2663
  const url = new URL(request.url);
2585
- // Native state moved to its own binding/class. Refuse obsolete internal
2586
- // dispatch without initializing MCP or touching the shared Agent scheduler.
2587
- if (url.pathname.startsWith(NATIVE_OAUTH_INTERNAL_PREFIX)) {
2664
+ // Native sign-in, consent and pickup are the org authorization service's.
2665
+ // Obsolete internal dispatch is refused without initialising MCP or
2666
+ // touching the shared Agent scheduler.
2667
+ if (url.pathname.startsWith(NATIVE_OAUTH_INTERNAL_PREFIX) ||
2668
+ url.pathname.startsWith("/_internal/pickup/")) {
2588
2669
  return new Response(null, { status: 404 });
2589
2670
  }
2590
- // draft-kya-http-02 §13 pickup-anchor dispatch.
2591
- // These requests target dedicated `pickup:<sid>` durable-object instances and
2592
- // must run BEFORE any origin detection, handshake-session side effects, or
2593
- // super/PartyServer routing — a pickup-anchor instance must never trip agent
2594
- // init. Precedent: the `/_internal/delegation/*` routes handled further below.
2595
- if (url.pathname.startsWith("/_internal/pickup/")) {
2596
- // `this.ctx` is the McpAgent base's DurableObjectState, typed against the
2597
- // SDK's bundled @cloudflare/workers-types; bridge it to this package's copy.
2598
- return handlePickupInternal(this.ctx, request);
2671
+ // The deployment's request-proof nonce instance must never initialise an
2672
+ // MCP session either.
2673
+ if (url.pathname === REQUEST_NONCE_CONSUME_PATH &&
2674
+ request.method === "POST") {
2675
+ return handleRequestNonceConsume(this.ctx.storage, request);
2599
2676
  }
2600
2677
  // Auto-detect and store server origin for consent URL building.
2601
2678
  // CRITICAL: When requests are routed through Cloudflare DO routing, the URL is
@@ -2775,16 +2852,9 @@ export class MCPICloudflareAgent extends McpAgent {
2775
2852
  if (result) {
2776
2853
  // Handler returned MCPIdentity or other data directly. For the
2777
2854
  // kya-os-identity path specifically, merge in the delegation-http
2778
- // capability advertisement (checkpoint's authorization-host picker
2779
- // probes this before trusting a deployment) — a no-op for every
2780
- // other well-known path.
2781
- const envPrefix = this.getEnvPrefix();
2782
- const mappedEnv = envPrefix
2783
- ? mapPrefixedEnv(this.env, envPrefix)
2784
- : this.env;
2785
- const runtimeConfig = this.getRuntimeConfigInternal(mappedEnv);
2786
- const httpChallengeCfg = resolveHttpChallengeConfig(runtimeConfig, mappedEnv);
2787
- const augmented = augmentKyaOsIdentityWellKnown(wellKnownPath, result, httpChallengeCfg, isAnchorRegistrationEnabled(httpChallengeCfg, mappedEnv), resolveCloudflareAuditAssurance(this._runtimeConfig));
2855
+ // capability advertisement — a no-op for every other well-known
2856
+ // path.
2857
+ const augmented = augmentKyaOsIdentityWellKnown(wellKnownPath, result, resolveCloudflareAuditAssurance(this._runtimeConfig));
2788
2858
  return new Response(JSON.stringify(augmented), {
2789
2859
  status: 200,
2790
2860
  headers: { "Content-Type": "application/json" },
@@ -2875,10 +2945,10 @@ export class MCPICloudflareAgent extends McpAgent {
2875
2945
  }), { status: 500, headers: { "Content-Type": "application/json" } });
2876
2946
  }
2877
2947
  }
2878
- // Handle internal delegation retrieval request
2879
- // This is called by getDelegationFromStorage() to read from singleton DO
2880
- // when using singleton routing strategy. This ensures the agent reads from
2881
- // the same DO that consent.service.ts wrote to.
2948
+ // Handle internal delegation retrieval request.
2949
+ // Nothing in this package reads it any more: grants are never resolved
2950
+ // from a session, the client presents its credential on every call. The
2951
+ // route goes with the worker's own consent store (task D2).
2882
2952
  if (url.pathname === "/_internal/delegation/get" &&
2883
2953
  request.method === "POST") {
2884
2954
  logger.debug("[MCPICloudflareAgent] Handling internal delegation get request");
@@ -3194,94 +3264,6 @@ export class MCPICloudflareAgent extends McpAgent {
3194
3264
  delegationId,
3195
3265
  });
3196
3266
  }
3197
- /**
3198
- * Retrieve delegation from DO internal storage
3199
- *
3200
- * CRITICAL: When using singleton routing, this method fetches from the singleton DO
3201
- * via HTTP to ensure consistency with where consent.service.ts stored the delegation.
3202
- * The partyserver library routes MCP requests to connection-based DOs, not singleton,
3203
- * so we must explicitly read from singleton to get the stored delegation.
3204
- *
3205
- * Looks up in priority order:
3206
- * 1. Session key (primary)
3207
- * 2. User+agent key (if userDid available)
3208
- *
3209
- * @param sessionId - Session ID
3210
- * @param userDid - Optional user DID for secondary lookup
3211
- * @param agentDid - Agent DID for secondary lookup
3212
- * @returns Delegation data or undefined if not found
3213
- */
3214
- async getDelegationFromStorage(sessionId, userDid, agentDid) {
3215
- const strategy = parseDORoutingStrategy(this.env.DO_ROUTING_STRATEGY);
3216
- const shardCount = parseDOShardCount(this.env.DO_SHARD_COUNT);
3217
- // PRIORITY 0: Fetch from the correct DO via HTTP (matches consent.service write path)
3218
- // consent.service stores delegations to DO for ALL strategies, so we must read from
3219
- // DO for all strategies too — not just singleton.
3220
- try {
3221
- const doNamespace = this.env.MCP_OBJECT;
3222
- if (doNamespace) {
3223
- const doInstanceId = calculateDOInstanceId(sessionId, strategy, shardCount);
3224
- const doId = doNamespace.idFromName(doInstanceId);
3225
- const doStub = doNamespace.get(doId);
3226
- // Get server origin for the request
3227
- const serverOrigin = this.env.MCP_SERVER_URL || "https://localhost";
3228
- logger.debug("[MCPICloudflareAgent] Fetching delegation from DO:", {
3229
- sessionId: sessionId.slice(0, 20) + "...",
3230
- strategy,
3231
- doInstanceId,
3232
- });
3233
- const response = await doStub.fetch(new URL("/_internal/delegation/get", serverOrigin).toString(), {
3234
- method: "POST",
3235
- headers: { "Content-Type": "application/json" },
3236
- body: JSON.stringify({ sessionId, userDid, agentDid }),
3237
- });
3238
- if (response.ok) {
3239
- const result = (await response.json());
3240
- if (result.success && result.data) {
3241
- logger.debug("[MCPICloudflareAgent] ✅ Delegation found via DO:", {
3242
- sessionId: sessionId.slice(0, 20) + "...",
3243
- strategy,
3244
- doInstanceId,
3245
- delegationId: result.data.delegationId,
3246
- });
3247
- return result.data;
3248
- }
3249
- }
3250
- }
3251
- }
3252
- catch (error) {
3253
- logger.warn("[MCPICloudflareAgent] Failed to fetch from DO, falling back to local:", error);
3254
- }
3255
- // Fallback: Try local DO storage (if MCP_OBJECT unavailable or HTTP fetch failed)
3256
- const sessionKey = `delegation:session:${sessionId}`;
3257
- const sessionData = await this.ctx.storage.get(sessionKey);
3258
- if (sessionData) {
3259
- logger.debug("[MCPICloudflareAgent] Delegation found via local session key:", {
3260
- sessionId: sessionId.slice(0, 20) + "...",
3261
- delegationId: sessionData.delegationId,
3262
- });
3263
- return sessionData;
3264
- }
3265
- // Try user+agent key if we have userDid
3266
- if (userDid && agentDid) {
3267
- const userAgentKey = `delegation:user:${userDid}:agent:${agentDid}`;
3268
- const userAgentData = await this.ctx.storage.get(userAgentKey);
3269
- if (userAgentData) {
3270
- logger.debug("[MCPICloudflareAgent] Delegation found via local user+agent key:", {
3271
- userDid: userDid.slice(0, 20) + "...",
3272
- agentDid: agentDid.slice(0, 20) + "...",
3273
- delegationId: userAgentData.delegationId,
3274
- });
3275
- return userAgentData;
3276
- }
3277
- }
3278
- logger.debug("[MCPICloudflareAgent] No delegation found in DO storage:", {
3279
- sessionId: sessionId.slice(0, 20) + "...",
3280
- hasUserDid: !!userDid,
3281
- hasAgentDid: !!agentDid,
3282
- });
3283
- return undefined;
3284
- }
3285
3267
  /**
3286
3268
  * Handle MCP-I handshake JSON-RPC request
3287
3269
  *