@kya-os/mcp-i-cloudflare 1.18.0 → 1.18.2

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 (256) 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 +30 -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 +383 -406
  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/oauth-handler.d.ts +1 -1
  86. package/dist/runtime/oauth-handler.d.ts.map +1 -1
  87. package/dist/runtime/oauth-handler.js +15 -30
  88. package/dist/runtime/oauth-handler.js.map +1 -1
  89. package/dist/runtime.d.ts +34 -10
  90. package/dist/runtime.d.ts.map +1 -1
  91. package/dist/runtime.js +54 -12
  92. package/dist/runtime.js.map +1 -1
  93. package/dist/security/admission-refusal.d.ts +3 -3
  94. package/dist/security/admission-refusal.d.ts.map +1 -1
  95. package/dist/security/admission-refusal.js +14 -6
  96. package/dist/security/admission-refusal.js.map +1 -1
  97. package/dist/security/holder-binding.d.ts +34 -0
  98. package/dist/security/holder-binding.d.ts.map +1 -0
  99. package/dist/security/holder-binding.js +75 -0
  100. package/dist/security/holder-binding.js.map +1 -0
  101. package/dist/security/mcp-admission.d.ts +29 -1
  102. package/dist/security/mcp-admission.d.ts.map +1 -1
  103. package/dist/security/mcp-admission.js +78 -12
  104. package/dist/security/mcp-admission.js.map +1 -1
  105. package/dist/security/native-holder-admission.d.ts +39 -0
  106. package/dist/security/native-holder-admission.d.ts.map +1 -0
  107. package/dist/security/native-holder-admission.js +65 -0
  108. package/dist/security/native-holder-admission.js.map +1 -0
  109. package/dist/security/outcome-proof.d.ts +39 -0
  110. package/dist/security/outcome-proof.d.ts.map +1 -0
  111. package/dist/security/outcome-proof.js +54 -0
  112. package/dist/security/outcome-proof.js.map +1 -0
  113. package/dist/security/request-nonce-store.d.ts +43 -0
  114. package/dist/security/request-nonce-store.d.ts.map +1 -0
  115. package/dist/security/request-nonce-store.js +129 -0
  116. package/dist/security/request-nonce-store.js.map +1 -0
  117. package/dist/security/routed-request.d.ts +41 -0
  118. package/dist/security/routed-request.d.ts.map +1 -0
  119. package/dist/security/routed-request.js +86 -0
  120. package/dist/security/routed-request.js.map +1 -0
  121. package/dist/security/sign-in-amr.d.ts +23 -0
  122. package/dist/security/sign-in-amr.d.ts.map +1 -0
  123. package/dist/security/sign-in-amr.js +44 -0
  124. package/dist/security/sign-in-amr.js.map +1 -0
  125. package/dist/services/approval-route.d.ts +3 -2
  126. package/dist/services/approval-route.d.ts.map +1 -1
  127. package/dist/services/approval-route.js.map +1 -1
  128. package/dist/services/checkpoint-decision.d.ts +56 -0
  129. package/dist/services/checkpoint-decision.d.ts.map +1 -0
  130. package/dist/services/checkpoint-decision.js +109 -0
  131. package/dist/services/checkpoint-decision.js.map +1 -0
  132. package/dist/services/consent-page-renderer.d.ts.map +1 -1
  133. package/dist/services/consent-page-renderer.js +2 -3
  134. package/dist/services/consent-page-renderer.js.map +1 -1
  135. package/dist/services/consent.service.d.ts +11 -49
  136. package/dist/services/consent.service.d.ts.map +1 -1
  137. package/dist/services/consent.service.js +81 -307
  138. package/dist/services/consent.service.js.map +1 -1
  139. package/dist/services/credential-auth.handler.d.ts.map +1 -1
  140. package/dist/services/credential-auth.handler.js +2 -8
  141. package/dist/services/credential-auth.handler.js.map +1 -1
  142. package/dist/services/delegation-authority.d.ts +53 -0
  143. package/dist/services/delegation-authority.d.ts.map +1 -0
  144. package/dist/services/delegation-authority.js +130 -0
  145. package/dist/services/delegation-authority.js.map +1 -0
  146. package/dist/services/delegation-trust.d.ts +35 -64
  147. package/dist/services/delegation-trust.d.ts.map +1 -1
  148. package/dist/services/delegation-trust.js +98 -279
  149. package/dist/services/delegation-trust.js.map +1 -1
  150. package/dist/services/delegation.service.d.ts +83 -105
  151. package/dist/services/delegation.service.d.ts.map +1 -1
  152. package/dist/services/delegation.service.js +166 -518
  153. package/dist/services/delegation.service.js.map +1 -1
  154. package/dist/services/idp-token-storage.d.ts +32 -12
  155. package/dist/services/idp-token-storage.d.ts.map +1 -1
  156. package/dist/services/idp-token-storage.js +79 -36
  157. package/dist/services/idp-token-storage.js.map +1 -1
  158. package/dist/services/issuer-keys.d.ts +55 -0
  159. package/dist/services/issuer-keys.d.ts.map +1 -0
  160. package/dist/services/issuer-keys.js +184 -0
  161. package/dist/services/issuer-keys.js.map +1 -0
  162. package/dist/services/oauth-security.service.d.ts +17 -1
  163. package/dist/services/oauth-security.service.d.ts.map +1 -1
  164. package/dist/services/oauth-security.service.js +29 -10
  165. package/dist/services/oauth-security.service.js.map +1 -1
  166. package/dist/services/resource-audience.d.ts +12 -9
  167. package/dist/services/resource-audience.d.ts.map +1 -1
  168. package/dist/services/resource-audience.js +12 -9
  169. package/dist/services/resource-audience.js.map +1 -1
  170. package/dist/services/unenforceable-tool-protection.d.ts +32 -0
  171. package/dist/services/unenforceable-tool-protection.d.ts.map +1 -0
  172. package/dist/services/unenforceable-tool-protection.js +90 -0
  173. package/dist/services/unenforceable-tool-protection.js.map +1 -0
  174. package/dist/services/upstream-fetch.d.ts +14 -0
  175. package/dist/services/upstream-fetch.d.ts.map +1 -0
  176. package/dist/services/upstream-fetch.js +56 -0
  177. package/dist/services/upstream-fetch.js.map +1 -0
  178. package/dist/types.d.ts +5 -18
  179. package/dist/types.d.ts.map +1 -1
  180. package/dist/utils/tool-security-schemes.d.ts +65 -0
  181. package/dist/utils/tool-security-schemes.d.ts.map +1 -0
  182. package/dist/utils/tool-security-schemes.js +168 -0
  183. package/dist/utils/tool-security-schemes.js.map +1 -0
  184. package/package.json +4 -5
  185. package/dist/delegation-http/anchor-do.d.ts +0 -84
  186. package/dist/delegation-http/anchor-do.d.ts.map +0 -1
  187. package/dist/delegation-http/anchor-do.js +0 -412
  188. package/dist/delegation-http/anchor-do.js.map +0 -1
  189. package/dist/delegation-http/anchor-registration-validate.d.ts +0 -61
  190. package/dist/delegation-http/anchor-registration-validate.d.ts.map +0 -1
  191. package/dist/delegation-http/anchor-registration-validate.js +0 -191
  192. package/dist/delegation-http/anchor-registration-validate.js.map +0 -1
  193. package/dist/delegation-http/anchor-registration.d.ts +0 -62
  194. package/dist/delegation-http/anchor-registration.d.ts.map +0 -1
  195. package/dist/delegation-http/anchor-registration.js +0 -337
  196. package/dist/delegation-http/anchor-registration.js.map +0 -1
  197. package/dist/delegation-http/anchor-routing.d.ts +0 -20
  198. package/dist/delegation-http/anchor-routing.d.ts.map +0 -1
  199. package/dist/delegation-http/anchor-routing.js +0 -27
  200. package/dist/delegation-http/anchor-routing.js.map +0 -1
  201. package/dist/delegation-http/challenge-middleware.d.ts +0 -28
  202. package/dist/delegation-http/challenge-middleware.d.ts.map +0 -1
  203. package/dist/delegation-http/challenge-middleware.js +0 -190
  204. package/dist/delegation-http/challenge-middleware.js.map +0 -1
  205. package/dist/delegation-http/challenge.d.ts +0 -102
  206. package/dist/delegation-http/challenge.d.ts.map +0 -1
  207. package/dist/delegation-http/challenge.js +0 -223
  208. package/dist/delegation-http/challenge.js.map +0 -1
  209. package/dist/delegation-http/consent-anchor-bridge.d.ts +0 -70
  210. package/dist/delegation-http/consent-anchor-bridge.d.ts.map +0 -1
  211. package/dist/delegation-http/consent-anchor-bridge.js +0 -1130
  212. package/dist/delegation-http/consent-anchor-bridge.js.map +0 -1
  213. package/dist/delegation-http/consent-preparation-page.d.ts +0 -18
  214. package/dist/delegation-http/consent-preparation-page.d.ts.map +0 -1
  215. package/dist/delegation-http/consent-preparation-page.js +0 -172
  216. package/dist/delegation-http/consent-preparation-page.js.map +0 -1
  217. package/dist/delegation-http/credential-consent.d.ts +0 -149
  218. package/dist/delegation-http/credential-consent.d.ts.map +0 -1
  219. package/dist/delegation-http/credential-consent.js +0 -338
  220. package/dist/delegation-http/credential-consent.js.map +0 -1
  221. package/dist/delegation-http/native-capabilities.d.ts +0 -4
  222. package/dist/delegation-http/native-capabilities.d.ts.map +0 -1
  223. package/dist/delegation-http/native-capabilities.js +0 -53
  224. package/dist/delegation-http/native-capabilities.js.map +0 -1
  225. package/dist/delegation-http/native-oauth-state.d.ts +0 -28
  226. package/dist/delegation-http/native-oauth-state.d.ts.map +0 -1
  227. package/dist/delegation-http/native-oauth-state.js +0 -146
  228. package/dist/delegation-http/native-oauth-state.js.map +0 -1
  229. package/dist/delegation-http/native-oauth.d.ts +0 -26
  230. package/dist/delegation-http/native-oauth.d.ts.map +0 -1
  231. package/dist/delegation-http/native-oauth.js +0 -401
  232. package/dist/delegation-http/native-oauth.js.map +0 -1
  233. package/dist/delegation-http/native-pickup.d.ts +0 -20
  234. package/dist/delegation-http/native-pickup.d.ts.map +0 -1
  235. package/dist/delegation-http/native-pickup.js +0 -227
  236. package/dist/delegation-http/native-pickup.js.map +0 -1
  237. package/dist/delegation-http/pickup-routes.d.ts +0 -43
  238. package/dist/delegation-http/pickup-routes.d.ts.map +0 -1
  239. package/dist/delegation-http/pickup-routes.js +0 -166
  240. package/dist/delegation-http/pickup-routes.js.map +0 -1
  241. package/dist/delegation-http/register.d.ts +0 -26
  242. package/dist/delegation-http/register.d.ts.map +0 -1
  243. package/dist/delegation-http/register.js +0 -95
  244. package/dist/delegation-http/register.js.map +0 -1
  245. package/dist/delegation-http/registrar-auth.d.ts +0 -24
  246. package/dist/delegation-http/registrar-auth.d.ts.map +0 -1
  247. package/dist/delegation-http/registrar-auth.js +0 -61
  248. package/dist/delegation-http/registrar-auth.js.map +0 -1
  249. package/dist/delegation-http/remote-issuer.d.ts +0 -52
  250. package/dist/delegation-http/remote-issuer.d.ts.map +0 -1
  251. package/dist/delegation-http/remote-issuer.js +0 -324
  252. package/dist/delegation-http/remote-issuer.js.map +0 -1
  253. package/dist/delegation-http/types.d.ts +0 -116
  254. package/dist/delegation-http/types.d.ts.map +0 -1
  255. package/dist/delegation-http/types.js +0 -11
  256. package/dist/delegation-http/types.js.map +0 -1
package/dist/agent.js CHANGED
@@ -8,26 +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";
25
30
  import { isAmountLimitError } from "./runtime/amount-limit-refusal";
26
- import { amountLimitToolResult } from "@kya-os/mcp-i-runtime";
31
+ import { amrSatisfiesAuthType } from "./security/sign-in-amr";
32
+ import { amountLimitToolResult, terminalForToolError, } from "@kya-os/mcp-i-runtime";
27
33
  import { z } from "zod";
28
34
  import { generateDidKeyFromBase64, logger } from "@kya-os/mcp";
29
- 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)
30
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";
31
40
  // CRITICAL: Import the OAuth service registry - this triggers globalThis registration
32
41
  // at module load time, preventing esbuild from tree-shaking the OAuth services
33
42
  import { getOAuthServices, isOAuthServicesAvailable, } from "./utils/oauth-service-registry";
@@ -51,6 +60,8 @@ import { withCheckpointNames } from "@kya-os/contracts/config";
51
60
  // Without this, esbuild may eliminate oauth-service-registry.ts entirely
52
61
  // because the exports are only used inside conditional async code
53
62
  const _oauthRegistryLoaded = isOAuthServicesAvailable();
63
+ /** The audience of every proof a call's session signs. */
64
+ const PROOF_AUDIENCE = "https://kya.vouched.id";
54
65
  if (!_oauthRegistryLoaded) {
55
66
  // Logger not yet configured at module init, use console.warn as fallback
56
67
  console.warn("[MCPICloudflareAgent] OAuth service registry not loaded at module init - services may be unavailable");
@@ -132,12 +143,16 @@ export class MCPICloudflareAgent extends McpAgent {
132
143
  mappedEnv._durableObjectState = state;
133
144
  // Load runtime configuration from subclass
134
145
  const runtimeConfig = this.getRuntimeConfigInternal(mappedEnv);
135
- if (runtimeConfig.requestAdmission) {
136
- 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, {
137
151
  // Read at report time: mcpiRuntime is created further down.
138
152
  reportRefusal: async (report) => {
139
153
  await this.mcpiRuntime?.reportAdmissionRefusal(report);
140
154
  },
155
+ onRefusal: (refusal) => this.signAdmissionRefusal(refusal),
141
156
  });
142
157
  }
143
158
  const managedAudit = createCloudflareAuditRuntimeFromEnv(mappedEnv);
@@ -158,7 +173,8 @@ export class MCPICloudflareAgent extends McpAgent {
158
173
  // Discovery must use the same effective audit trail as the initialized
159
174
  // runtime, including managed bindings absent from the template defaults.
160
175
  this._runtimeConfig = runtimeConfig;
161
- // 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.
162
178
  const toolProtectionService = runtimeConfig.toolProtection &&
163
179
  mappedEnv.TOOL_PROTECTION_KV &&
164
180
  mappedEnv.CHECKPOINT_API_KEY
@@ -184,7 +200,9 @@ export class MCPICloudflareAgent extends McpAgent {
184
200
  }
185
201
  : undefined,
186
202
  })
187
- : undefined;
203
+ : runtimeConfig.toolProtection
204
+ ? unenforceableToolProtectionService(runtimeConfig.toolProtection, mappedEnv)
205
+ : undefined;
188
206
  // Initialize MCP-I runtime
189
207
  this.mcpiRuntime = createCloudflareRuntime({
190
208
  env: mappedEnv,
@@ -567,10 +585,13 @@ export class MCPICloudflareAgent extends McpAgent {
567
585
  /**
568
586
  * The delegation verifier the runtime uses for protected tool calls.
569
587
  *
570
- * Subclasses can ask the same verifier a question the runtime would ask,
571
- * with the same credentials and base URL, instead of building their own
572
- * client. Undefined when no CHECKPOINT_API_KEY is configured (the runtime
573
- * 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).
574
595
  *
575
596
  * @example
576
597
  * ```typescript
@@ -610,12 +631,42 @@ export class MCPICloudflareAgent extends McpAgent {
610
631
  await this.registerConsentUIResource();
611
632
  // Register tools (implemented by subclasses)
612
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
+ }
613
639
  }
614
640
  catch (error) {
615
641
  logger.error("[MCPICloudflareAgent] Initialization failed:", error);
616
642
  throw error;
617
643
  }
618
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
+ }
619
670
  /**
620
671
  * Register the MCP Apps consent UI resource.
621
672
  *
@@ -1002,72 +1053,20 @@ export class MCPICloudflareAgent extends McpAgent {
1002
1053
  project_id: z.string(),
1003
1054
  resume_token: z.string(),
1004
1055
  };
1005
- const approveConsentHandler = async (args) => {
1006
- const envPrefix = this.getEnvPrefix();
1007
- const mappedEnv = envPrefix
1008
- ? mapPrefixedEnv(this.env, envPrefix)
1009
- : this.env;
1010
- const serverUrl = mappedEnv.MCP_SERVER_URL ??
1011
- this._autoDetectedOrigin;
1012
- if (!serverUrl) {
1013
- return {
1014
- content: [
1015
- {
1016
- type: "text",
1017
- text: JSON.stringify({
1018
- success: false,
1019
- error: "No server URL configured",
1020
- }),
1021
- },
1022
- ],
1023
- };
1024
- }
1025
- try {
1026
- const resp = await fetch(`${serverUrl}/consent/approve`, {
1027
- method: "POST",
1028
- headers: { "Content-Type": "application/json" },
1029
- body: JSON.stringify({
1030
- tool: args.tool,
1031
- scopes: args.scopes,
1032
- session_id: args.session_id,
1033
- agent_did: args.agent_did,
1034
- project_id: args.project_id,
1035
- resume_token: args.resume_token,
1036
- termsAccepted: true,
1037
- approved: true,
1038
- // The iframe's consent-only approval. /consent/approve refuses
1039
- // a missing provider_type.
1040
- 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",
1041
1066
  }),
1042
- });
1043
- if (!resp.ok) {
1044
- return {
1045
- content: [
1046
- {
1047
- type: "text",
1048
- text: JSON.stringify({
1049
- success: false,
1050
- error: `Server error: ${resp.status}`,
1051
- }),
1052
- },
1053
- ],
1054
- };
1055
- }
1056
- const data = await resp.json();
1057
- return { content: [{ type: "text", text: JSON.stringify(data) }] };
1058
- }
1059
- catch (err) {
1060
- const msg = err instanceof Error ? err.message : "Unknown error";
1061
- return {
1062
- content: [
1063
- {
1064
- type: "text",
1065
- text: JSON.stringify({ success: false, error: msg }),
1066
- },
1067
- ],
1068
- };
1069
- }
1070
- };
1067
+ },
1068
+ ],
1069
+ });
1071
1070
  this.server.tool("_kyaos_approve_consent", approveConsentDescription, approveConsentSchema, approveConsentHandler);
1072
1071
  this.server.tool("_mcpi_approve_consent", approveConsentDescription, approveConsentSchema, async (args) => {
1073
1072
  recordWireForm("tool_name", "old", {
@@ -1274,12 +1273,13 @@ export class MCPICloudflareAgent extends McpAgent {
1274
1273
  }
1275
1274
  // Use registerTool (not deprecated server.tool) to support _meta.ui for MCP Apps
1276
1275
  const toolCallback = async (args, extra) => {
1277
- // ✅ Automatically extract sessionId from ToolExtraArguments
1278
- // This ensures delegation tokens stored with the original session ID
1279
- // can be retrieved on subsequent tool calls
1276
+ // The transport session attributes the call; it never selects a grant.
1280
1277
  const sessionId = extra
1281
1278
  ?.sessionId;
1282
- 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));
1283
1283
  };
1284
1284
  // Build tool config with optional MCP Apps UI metadata
1285
1285
  // When ext-apps consent UI is registered, include _meta.ui.resourceUri
@@ -1317,7 +1317,7 @@ export class MCPICloudflareAgent extends McpAgent {
1317
1317
  * @param args - Tool arguments
1318
1318
  * @param handler - Tool handler function
1319
1319
  * @param providedSessionId - Optional session ID from MCP request (extracted from ToolExtraArguments.sessionId)
1320
- * If provided, uses this session ID for delegation token lookup.
1320
+ * Attributes the call to that session; it never selects a delegation.
1321
1321
  * If not provided, falls back to getSessionId() or generates ephemeral ID.
1322
1322
  */
1323
1323
  async executeToolWithProof(toolName, args, handler, providedSessionId) {
@@ -1461,134 +1461,38 @@ export class MCPICloudflareAgent extends McpAgent {
1461
1461
  serverUrl: serverUrl?.slice(0, 50) || "undefined",
1462
1462
  });
1463
1463
  }
1464
- // ✅ Look up delegation token from DO storage (strongly consistent)
1465
- // Using DO internal storage eliminates KV eventual consistency issues.
1466
- // No retry mechanism needed - storage and retrieval happen on the same DO instance.
1467
- 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();
1468
1473
  let delegationId;
1469
1474
  let userDid;
1470
- let clientDid;
1471
- // SECURITY (consent-approve auth-gate, Task B2/B3): the presented
1472
- // delegation's own authorization type, surfaced from storage so the gate in
1473
- // buildToolContext can require it to satisfy the tool's required type.
1474
- // Remains undefined for the KV-legacy / JWT-extraction fallbacks below (no
1475
- // stored type) → fail-safe re-challenge on typed tools.
1476
- let delegationAuthorizationType;
1477
- try {
1478
- const agentDid = getMcpRequestHolder()?.did ??
1479
- (await this.mcpiRuntime.getIdentity()).did;
1480
- logger.debug("[MCPICloudflareAgent] 🔍 Starting delegation lookup (DO storage):", {
1481
- sessionId: sessionId.slice(0, 20) + "...",
1482
- 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,
1483
1480
  });
1484
- // Get userDid and clientDid from KV session data (still needed for identity context)
1485
- const delegationStorage = mappedEnv.DELEGATION_STORAGE;
1486
- if (delegationStorage) {
1487
- const identityKey = STORAGE_KEYS.sessionIdentity(sessionId);
1488
- const sessionKey = STORAGE_KEYS.session(sessionId);
1489
- const identityData = (await delegationStorage.get(identityKey, "json"));
1490
- const sessionData = (await delegationStorage.get(sessionKey, "json"));
1491
- userDid = identityData?.userDid || sessionData?.userDid;
1492
- clientDid = sessionData?.clientDid;
1493
- }
1494
- // Look up delegation from DO storage (strongly consistent - no retries needed)
1495
- const doData = await this.getDelegationFromStorage(sessionId, userDid, agentDid);
1496
- if (doData) {
1497
- delegationToken = doData.delegationToken;
1498
- delegationId = doData.delegationId;
1499
- // Task B2: surface the stored delegation auth type for the call-time gate
1500
- delegationAuthorizationType = doData.authorizationType;
1501
- // Prefer userDid from DO storage if available
1502
- if (doData.userDid) {
1503
- userDid = doData.userDid;
1504
- }
1505
- logger.debug("[MCPICloudflareAgent] ✅ Delegation found in DO storage:", {
1506
- sessionId: sessionId.slice(0, 20) + "...",
1507
- delegationId,
1508
- hasUserDid: !!userDid,
1509
- });
1510
- }
1511
- else {
1512
- // Fallback: Check KV for backward compatibility with existing delegations
1513
- // This handles delegations created before the DO storage migration
1514
- if (delegationStorage && userDid) {
1515
- const userAgentKey = STORAGE_KEYS.delegation(userDid, agentDid);
1516
- const kvToken = await delegationStorage.get(userAgentKey, "text");
1517
- if (kvToken) {
1518
- delegationToken = kvToken;
1519
- // Recover the delegation's auth type from its sidecar key so this
1520
- // fallback can satisfy a typed tool. Records written before the
1521
- // sidecar existed have none — that stays undefined and the gate
1522
- // fails safe (re-challenge), which is the pre-existing behaviour
1523
- // for legacy records, not a new rejection.
1524
- delegationAuthorizationType =
1525
- (await delegationStorage.get(STORAGE_KEYS.delegationAuthType(userDid, agentDid), "text")) ?? undefined;
1526
- logger.debug("[MCPICloudflareAgent] ✅ Delegation found in KV (legacy):", {
1527
- sessionId: sessionId.slice(0, 20) + "...",
1528
- source: "kv-fallback",
1529
- hasAuthorizationType: !!delegationAuthorizationType,
1530
- });
1531
- }
1532
- }
1533
- if (!delegationToken) {
1534
- logger.debug("[MCPICloudflareAgent] ℹ️ No delegation found:", {
1535
- sessionId: sessionId.slice(0, 20) + "...",
1536
- hasUserDid: !!userDid,
1537
- note: "Delegation only required for tools with 'requiresDelegation: true'",
1538
- });
1539
- }
1540
- }
1541
- }
1542
- catch (error) {
1543
- logger.warn("[MCPICloudflareAgent] Failed to retrieve delegation:", error);
1544
- }
1545
- // A retry's explicit credential takes precedence over a cached grant. Keep
1546
- // the authenticated session account, but never borrow another grant's ID or
1547
- // authorization type. The existing runtime verifier still checks this token.
1548
- const presentedDelegation = getMcpPresentedDelegation();
1549
- if (presentedDelegation !== undefined &&
1550
- presentedDelegation !== delegationToken) {
1551
- delegationToken = presentedDelegation;
1552
- delegationId = undefined;
1553
- delegationAuthorizationType = undefined;
1554
- }
1555
- // ✅ FIX: Extract userDid from delegation token if not available from session storage
1556
- // This handles KV eventual consistency issues where session cache is stale but delegation exists
1557
- // For proved native callers, account identity must come from authenticated
1558
- // session/grant storage, never an unverified JWT payload or its agent sub.
1559
- if (delegationToken && !userDid && !getMcpRequestHolder()) {
1560
- try {
1561
- // Decode JWT payload (delegation tokens are JWTs with vc.credentialSubject.user_identifier)
1562
- const parts = delegationToken.split(".");
1563
- if (parts.length >= 2) {
1564
- const payload = JSON.parse(atob(parts[1]));
1565
- const extractedUserDid = payload.vc?.credentialSubject?.user_identifier ||
1566
- payload.user_identifier ||
1567
- payload.sub;
1568
- if (extractedUserDid && extractedUserDid.startsWith("did:")) {
1569
- userDid = extractedUserDid;
1570
- logger.debug("[MCPICloudflareAgent] ✅ Extracted userDid from delegation token:", {
1571
- userDid: extractedUserDid.slice(0, 20) + "...",
1572
- source: "delegation-token-jwt",
1573
- });
1574
- }
1575
- }
1576
- }
1577
- catch (extractError) {
1578
- 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;
1579
1485
  }
1580
1486
  }
1581
- // ✅ SECURITY: Use validatedClientDid from server-side session validation
1582
- // This is the authoritative clientDid - it was verified to exist in our KV store
1583
- // Only falls back to clientDid from session lookup if no validated session
1584
- const finalClientDid = validatedClientDid || clientDid;
1487
+ // ✅ SECURITY: clientDid only from server-side handshake validation.
1488
+ const finalClientDid = validatedClientDid;
1585
1489
  // Request-scoped identifiers are threaded through the runtime instead of
1586
1490
  // being stored on the Durable Object instance. Concurrent calls can then
1587
1491
  // never borrow each other's proof or audit correlation state.
1588
1492
  const auditInvocationId = crypto.randomUUID();
1589
1493
  const session = {
1590
1494
  id: sessionId,
1591
- audience: "https://kya.vouched.id",
1495
+ audience: PROOF_AUDIENCE,
1592
1496
  agentDid: getMcpRequestHolder()?.did ??
1593
1497
  (await this.mcpiRuntime.getIdentity()).did,
1594
1498
  // Trusted per-request proof result; never a client-supplied DID label.
@@ -1631,7 +1535,7 @@ export class MCPICloudflareAgent extends McpAgent {
1631
1535
  // Store AuthRequiredError to throw inside the inner try block where its handler lives
1632
1536
  let pendingAuthRequiredError = null;
1633
1537
  try {
1634
- toolContext = await this.buildToolContext(toolName, userDid, sessionId, delegationToken, delegationAuthorizationType, mappedEnv);
1538
+ toolContext = await this.buildToolContext(toolName, userDid, sessionId, delegationToken, delegationAmr, delegationId, mappedEnv);
1635
1539
  }
1636
1540
  catch (error) {
1637
1541
  // Handle CredentialAuthModeError - build consent page URL (not OAuth URL)
@@ -1832,6 +1736,11 @@ export class MCPICloudflareAgent extends McpAgent {
1832
1736
  return pendingInlineResult;
1833
1737
  }
1834
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 = {};
1835
1744
  try {
1836
1745
  // ✅ FIX: Throw pending errors INSIDE the try block
1837
1746
  // This ensures they're caught by the formatters below
@@ -1841,7 +1750,9 @@ export class MCPICloudflareAgent extends McpAgent {
1841
1750
  if (pendingAuthRequiredError) {
1842
1751
  throw pendingAuthRequiredError;
1843
1752
  }
1844
- 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));
1845
1756
  // NOTE: Proof submission is now awaited directly in CloudflareRuntime.processToolCall()
1846
1757
  // This ensures reliable submission without relying on ctx.waitUntil() which is unreliable
1847
1758
  // in Durable Objects (McpAgent). The tradeoff is ~200-400ms additional latency per tool call.
@@ -1869,45 +1780,115 @@ export class MCPICloudflareAgent extends McpAgent {
1869
1780
  hasResumeToken: !!resumeToken,
1870
1781
  clientId: clientId || "unknown",
1871
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;
1872
1832
  // Use DelegationErrorFormatter for consistent message formatting
1873
1833
  // Supports client-specific messages via getClientMessagesConfig()
1874
1834
  const formatter = new DelegationErrorFormatter(this.getClientMessagesConfig());
1875
- const { message: displayMessage, consentUrl } = formatter.format({
1835
+ const { message: displayMessage, consentUrl: formattedUrl } = formatter.format({
1876
1836
  toolName: toolNameForError,
1877
- consentUrl: delegationError.consentUrl,
1837
+ consentUrl: preferredUrl,
1878
1838
  scopes,
1879
1839
  clientId,
1880
1840
  // A verifier refusal (revoked, expired, wrong agent) gets its
1881
1841
  // configured per-code line; without one the text stays as today.
1882
- denial: delegationError.denial,
1842
+ denial,
1883
1843
  });
1844
+ // The org's URLs are signed or fixed, so they are used as given.
1845
+ const authorizationUrl = orgRules
1846
+ ? (preferredUrl ?? "")
1847
+ : (formattedUrl ?? "");
1884
1848
  // Popup launch — only attached as a hint in `_meta` so popup-aware
1885
1849
  // clients (today: `.mcpb`-installed Claude Desktop) can open the
1886
1850
  // consent URL in a stripped-chrome window. Standard clients ignore
1887
1851
  // the hint and surface the markdown link as before. The popup hint
1888
1852
  // is gated on `popupEnabled` from the resolved consent config so
1889
- // operators can opt out per-deployment.
1890
- 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);
1891
1858
  const popupResource = popupEligible
1892
- ? buildPopupResource(consentUrl)
1859
+ ? buildPopupResource(authorizationUrl)
1893
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
+ });
1894
1876
  // Return tool result with isError: true so MCP clients (Claude Desktop, Inspector)
1895
1877
  // surface the consent URL to users and trigger browser popup for authorization.
1896
- return {
1897
- content: [
1898
- {
1899
- type: "text",
1900
- text: displayMessage,
1901
- },
1902
- ],
1903
- isError: true,
1878
+ return (await this.mcpiRuntime.signOutcomeResult({
1879
+ ...result,
1904
1880
  // C4 (#2918) 3c dual-emit: carry BOTH the ratified DIF
1905
1881
  // needs_authorization envelope AND the legacy proprietary keys
1906
1882
  // (`errorType: "authorization_required"` — the kya-http §8.1
1907
1883
  // challenge trigger). See buildNeedsAuthorizationMeta.
1908
- _meta: buildNeedsAuthorizationMeta(delegationError, consentUrl, delegationError.interceptedCall?.expiresAt ??
1909
- Date.now() + 1_800_000, popupResource ? { popupResource } : {}),
1910
- };
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));
1911
1892
  }
1912
1893
  // Handle OAuthRequiredError - use formatOAuth() to preserve provider name
1913
1894
  // This ensures the message says "Sign in with GitHub" instead of generic "Authorize"
@@ -1989,23 +1970,135 @@ export class MCPICloudflareAgent extends McpAgent {
1989
1970
  };
1990
1971
  }
1991
1972
  if (isAmountLimitError(error)) {
1992
- return amountLimitToolResult(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
+ };
1993
1991
  }
1994
1992
  // Re-throw other errors to be handled by MCP SDK
1995
1993
  throw error;
1996
1994
  }
1997
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
+ }
1998
2085
  /**
1999
2086
  * Build tool execution context with IDP token (Phase 1 - MH-7)
2000
2087
  *
2001
- * @param delegationAuthorizationType - The stored authorization type of the
2002
- * presented delegation (from `getDelegationFromStorage`), or undefined for
2003
- * legacy records. Used by the delegation-only fallbacks below to reject a
2004
- * delegation whose type does not satisfy the tool's required type (security
2005
- * 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.
2006
2099
  * @private
2007
2100
  */
2008
- async buildToolContext(toolName, userDid, sessionId, delegationToken, delegationAuthorizationType, env) {
2101
+ async buildToolContext(toolName, userDid, sessionId, delegationToken, delegationAmr, delegationId, env) {
2009
2102
  // Only build context if userDid is available and Checkpoint API is configured.
2010
2103
  // Note: DELEGATION_STORAGE is only required for password/OAuth paths, not apikey vault.
2011
2104
  if (!userDid || !env.CHECKPOINT_API_KEY) {
@@ -2048,21 +2141,25 @@ export class MCPICloudflareAgent extends McpAgent {
2048
2141
  }
2049
2142
  // Create IdpTokenStorage to retrieve credential token
2050
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.
2051
2155
  const idpTokenStorage = new IdpTokenStorage({
2052
2156
  storage: env.DELEGATION_STORAGE,
2053
2157
  oauthSecurityService,
2158
+ delegationId: presentedDelegationAllowed ? delegationId : undefined,
2054
2159
  });
2055
2160
  try {
2056
2161
  // Retrieve password auth token - getToken handles scope hashing internally
2057
2162
  const storedToken = await idpTokenStorage.getToken(userDid, provider, protection.requiredScopes || []);
2058
- // SECURITY (defence in depth): a presented delegation must satisfy
2059
- // the tool's required type before the user's stored credential token
2060
- // is handed to the tool, the same rule as the delegation-only path
2061
- // below. Otherwise a delegation minted under the user's DID without
2062
- // their sign-in would unlock their token. Not presenting a
2063
- // delegation keeps the existing behaviour.
2064
- const presentedDelegationAllowed = !delegationToken ||
2065
- authTypeSatisfies(delegationAuthorizationType, protection.authorization?.type ?? "password");
2066
2163
  if (storedToken && presentedDelegationAllowed) {
2067
2164
  // Build headers based on token usage metadata
2068
2165
  const tokenWithMeta = storedToken;
@@ -2103,66 +2200,19 @@ export class MCPICloudflareAgent extends McpAgent {
2103
2200
  return context;
2104
2201
  }
2105
2202
  else {
2106
- // No usable password auth token - check if delegation exists
2107
- // If delegation exists, tool can still execute without credential token
2108
- //
2109
- // SECURITY (consent-approve auth-gate, Task B3): the delegation only
2110
- // authorizes this tool if its OWN authorization type satisfies the
2111
- // requirement. We are provably in the password branch (isPasswordAuth
2112
- // above), so the effective requirement is "password" — fall back to it
2113
- // when the tool uses the legacy `oauthProvider: "credentials"` shape
2114
- // (authorization.type undefined). A mismatched delegation (e.g. an
2115
- // anonymous `none` consent-only delegation — the demonstrated exploit
2116
- // — or a legacy record with no persisted type → undefined) does NOT
2117
- // satisfy it; fall through to OAuthRequiredError so the tool
2118
- // re-challenges instead of executing on mere delegation presence.
2119
- const requiredAuthType = protection.authorization?.type ?? "password";
2120
- if (delegationToken &&
2121
- authTypeSatisfies(delegationAuthorizationType, requiredAuthType)) {
2122
- if (this._environment === "development") {
2123
- logger.debug("[MCPICloudflareAgent] No credential token found, but delegation exists - returning minimal context:", {
2124
- tool: toolName,
2125
- userDid: userDid?.slice(0, 20) + "...",
2126
- provider,
2127
- authType: "password",
2128
- scopes: protection.requiredScopes,
2129
- note: "Tool can execute with delegation-only authorization",
2130
- });
2131
- }
2132
- // Return minimal context with delegation info
2133
- return {
2134
- provider,
2135
- scopes: protection.requiredScopes,
2136
- userDid,
2137
- sessionId,
2138
- delegationToken,
2139
- };
2140
- }
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.
2141
2209
  if (delegationToken) {
2142
- // A delegation WAS presented but its type does not satisfy the
2143
- // password requirement — log the rejection before re-challenging.
2144
- // NOT gated on development: this fires only on a rejection (so it
2145
- // is low volume), and it is the only signal that explains why a
2146
- // user is being re-challenged. Hiding it in production made the
2147
- // exact loop this follow-up addresses undiagnosable.
2148
- 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:", {
2149
2211
  tool: toolName,
2150
- requiredAuthType,
2151
- delegationAuthorizationType: delegationAuthorizationType ?? null,
2212
+ requiredAuthType: protection.authorization?.type ?? "password",
2152
2213
  });
2153
- // Distinguish "re-authenticate and this resolves" from "no mint
2154
- // can ever satisfy this". Diagnostic only — the authorization
2155
- // decision above is unchanged.
2156
- if (isUnsatisfiableAuthType(requiredAuthType)) {
2157
- logger.warn("[MCPICloudflareAgent] MISCONFIGURATION: tool requires an authorization type no delegation mint can produce - this tool will re-challenge forever:", {
2158
- tool: toolName,
2159
- requiredAuthType,
2160
- mintableAuthTypes: [...MINTABLE_AUTH_TYPES],
2161
- hint: "Set the tool's authorization.type to one of the mintable types, or add mint support for the required type.",
2162
- });
2163
- }
2164
2214
  }
2165
- // No (satisfying) delegation token - throw OAuthRequiredError to trigger auth flow
2215
+ // No stored credential - throw OAuthRequiredError to trigger auth flow
2166
2216
  if (this._environment === "development") {
2167
2217
  logger.warn("[MCPICloudflareAgent] No password auth token found, throwing OAuthRequiredError:", {
2168
2218
  tool: toolName,
@@ -2363,9 +2413,21 @@ export class MCPICloudflareAgent extends McpAgent {
2363
2413
  logger.warn("[MCPICloudflareAgent] DELEGATION_STORAGE not configured, skipping IDP token storage");
2364
2414
  return undefined;
2365
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.
2366
2427
  const idpTokenStorage = new IdpTokenStorage({
2367
2428
  storage: env.DELEGATION_STORAGE,
2368
2429
  oauthSecurityService,
2430
+ delegationId: presentedSignInType ? delegationId : undefined,
2369
2431
  });
2370
2432
  const tokenResolver = new IdpTokenResolver({
2371
2433
  tokenStorage: idpTokenStorage,
@@ -2377,8 +2439,20 @@ export class MCPICloudflareAgent extends McpAgent {
2377
2439
  providerResolver: providerResolver, // Phase 2: Pass ProviderResolver (type assertion for dist/src compatibility)
2378
2440
  projectId,
2379
2441
  });
2380
- // Build context
2381
- 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;
2382
2456
  }
2383
2457
  catch (error) {
2384
2458
  // Re-throw OAuthRequiredError so it can be handled by executeToolWithProof
@@ -2587,20 +2661,18 @@ export class MCPICloudflareAgent extends McpAgent {
2587
2661
  */
2588
2662
  async fetch(request) {
2589
2663
  const url = new URL(request.url);
2590
- // Native state moved to its own binding/class. Refuse obsolete internal
2591
- // dispatch without initializing MCP or touching the shared Agent scheduler.
2592
- 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/")) {
2593
2669
  return new Response(null, { status: 404 });
2594
2670
  }
2595
- // draft-kya-http-02 §13 pickup-anchor dispatch.
2596
- // These requests target dedicated `pickup:<sid>` durable-object instances and
2597
- // must run BEFORE any origin detection, handshake-session side effects, or
2598
- // super/PartyServer routing — a pickup-anchor instance must never trip agent
2599
- // init. Precedent: the `/_internal/delegation/*` routes handled further below.
2600
- if (url.pathname.startsWith("/_internal/pickup/")) {
2601
- // `this.ctx` is the McpAgent base's DurableObjectState, typed against the
2602
- // SDK's bundled @cloudflare/workers-types; bridge it to this package's copy.
2603
- 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);
2604
2676
  }
2605
2677
  // Auto-detect and store server origin for consent URL building.
2606
2678
  // CRITICAL: When requests are routed through Cloudflare DO routing, the URL is
@@ -2780,16 +2852,9 @@ export class MCPICloudflareAgent extends McpAgent {
2780
2852
  if (result) {
2781
2853
  // Handler returned MCPIdentity or other data directly. For the
2782
2854
  // kya-os-identity path specifically, merge in the delegation-http
2783
- // capability advertisement (checkpoint's authorization-host picker
2784
- // probes this before trusting a deployment) — a no-op for every
2785
- // other well-known path.
2786
- const envPrefix = this.getEnvPrefix();
2787
- const mappedEnv = envPrefix
2788
- ? mapPrefixedEnv(this.env, envPrefix)
2789
- : this.env;
2790
- const runtimeConfig = this.getRuntimeConfigInternal(mappedEnv);
2791
- const httpChallengeCfg = resolveHttpChallengeConfig(runtimeConfig, mappedEnv);
2792
- 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));
2793
2858
  return new Response(JSON.stringify(augmented), {
2794
2859
  status: 200,
2795
2860
  headers: { "Content-Type": "application/json" },
@@ -2880,10 +2945,10 @@ export class MCPICloudflareAgent extends McpAgent {
2880
2945
  }), { status: 500, headers: { "Content-Type": "application/json" } });
2881
2946
  }
2882
2947
  }
2883
- // Handle internal delegation retrieval request
2884
- // This is called by getDelegationFromStorage() to read from singleton DO
2885
- // when using singleton routing strategy. This ensures the agent reads from
2886
- // 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).
2887
2952
  if (url.pathname === "/_internal/delegation/get" &&
2888
2953
  request.method === "POST") {
2889
2954
  logger.debug("[MCPICloudflareAgent] Handling internal delegation get request");
@@ -3199,94 +3264,6 @@ export class MCPICloudflareAgent extends McpAgent {
3199
3264
  delegationId,
3200
3265
  });
3201
3266
  }
3202
- /**
3203
- * Retrieve delegation from DO internal storage
3204
- *
3205
- * CRITICAL: When using singleton routing, this method fetches from the singleton DO
3206
- * via HTTP to ensure consistency with where consent.service.ts stored the delegation.
3207
- * The partyserver library routes MCP requests to connection-based DOs, not singleton,
3208
- * so we must explicitly read from singleton to get the stored delegation.
3209
- *
3210
- * Looks up in priority order:
3211
- * 1. Session key (primary)
3212
- * 2. User+agent key (if userDid available)
3213
- *
3214
- * @param sessionId - Session ID
3215
- * @param userDid - Optional user DID for secondary lookup
3216
- * @param agentDid - Agent DID for secondary lookup
3217
- * @returns Delegation data or undefined if not found
3218
- */
3219
- async getDelegationFromStorage(sessionId, userDid, agentDid) {
3220
- const strategy = parseDORoutingStrategy(this.env.DO_ROUTING_STRATEGY);
3221
- const shardCount = parseDOShardCount(this.env.DO_SHARD_COUNT);
3222
- // PRIORITY 0: Fetch from the correct DO via HTTP (matches consent.service write path)
3223
- // consent.service stores delegations to DO for ALL strategies, so we must read from
3224
- // DO for all strategies too — not just singleton.
3225
- try {
3226
- const doNamespace = this.env.MCP_OBJECT;
3227
- if (doNamespace) {
3228
- const doInstanceId = calculateDOInstanceId(sessionId, strategy, shardCount);
3229
- const doId = doNamespace.idFromName(doInstanceId);
3230
- const doStub = doNamespace.get(doId);
3231
- // Get server origin for the request
3232
- const serverOrigin = this.env.MCP_SERVER_URL || "https://localhost";
3233
- logger.debug("[MCPICloudflareAgent] Fetching delegation from DO:", {
3234
- sessionId: sessionId.slice(0, 20) + "...",
3235
- strategy,
3236
- doInstanceId,
3237
- });
3238
- const response = await doStub.fetch(new URL("/_internal/delegation/get", serverOrigin).toString(), {
3239
- method: "POST",
3240
- headers: { "Content-Type": "application/json" },
3241
- body: JSON.stringify({ sessionId, userDid, agentDid }),
3242
- });
3243
- if (response.ok) {
3244
- const result = (await response.json());
3245
- if (result.success && result.data) {
3246
- logger.debug("[MCPICloudflareAgent] ✅ Delegation found via DO:", {
3247
- sessionId: sessionId.slice(0, 20) + "...",
3248
- strategy,
3249
- doInstanceId,
3250
- delegationId: result.data.delegationId,
3251
- });
3252
- return result.data;
3253
- }
3254
- }
3255
- }
3256
- }
3257
- catch (error) {
3258
- logger.warn("[MCPICloudflareAgent] Failed to fetch from DO, falling back to local:", error);
3259
- }
3260
- // Fallback: Try local DO storage (if MCP_OBJECT unavailable or HTTP fetch failed)
3261
- const sessionKey = `delegation:session:${sessionId}`;
3262
- const sessionData = await this.ctx.storage.get(sessionKey);
3263
- if (sessionData) {
3264
- logger.debug("[MCPICloudflareAgent] Delegation found via local session key:", {
3265
- sessionId: sessionId.slice(0, 20) + "...",
3266
- delegationId: sessionData.delegationId,
3267
- });
3268
- return sessionData;
3269
- }
3270
- // Try user+agent key if we have userDid
3271
- if (userDid && agentDid) {
3272
- const userAgentKey = `delegation:user:${userDid}:agent:${agentDid}`;
3273
- const userAgentData = await this.ctx.storage.get(userAgentKey);
3274
- if (userAgentData) {
3275
- logger.debug("[MCPICloudflareAgent] Delegation found via local user+agent key:", {
3276
- userDid: userDid.slice(0, 20) + "...",
3277
- agentDid: agentDid.slice(0, 20) + "...",
3278
- delegationId: userAgentData.delegationId,
3279
- });
3280
- return userAgentData;
3281
- }
3282
- }
3283
- logger.debug("[MCPICloudflareAgent] No delegation found in DO storage:", {
3284
- sessionId: sessionId.slice(0, 20) + "...",
3285
- hasUserDid: !!userDid,
3286
- hasAgentDid: !!agentDid,
3287
- });
3288
- return undefined;
3289
- }
3290
3267
  /**
3291
3268
  * Handle MCP-I handshake JSON-RPC request
3292
3269
  *