@kya-os/mcp-i-runtime 1.3.1 → 1.3.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 (62) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +13 -2
  5. package/dist/index.js.map +1 -1
  6. package/dist/proof/generator.d.ts +8 -6
  7. package/dist/proof/generator.d.ts.map +1 -1
  8. package/dist/proof/generator.js +7 -24
  9. package/dist/proof/generator.js.map +1 -1
  10. package/dist/runtime/audit.d.ts.map +1 -1
  11. package/dist/runtime/audit.js +66 -18
  12. package/dist/runtime/audit.js.map +1 -1
  13. package/dist/runtime/base.d.ts +6 -1
  14. package/dist/runtime/base.d.ts.map +1 -1
  15. package/dist/runtime/base.js +65 -17
  16. package/dist/runtime/base.js.map +1 -1
  17. package/dist/services/access-control.service.d.ts.map +1 -1
  18. package/dist/services/access-control.service.js +12 -5
  19. package/dist/services/access-control.service.js.map +1 -1
  20. package/dist/services/proof-verifier.d.ts +13 -35
  21. package/dist/services/proof-verifier.d.ts.map +1 -1
  22. package/dist/services/proof-verifier.js +16 -74
  23. package/dist/services/proof-verifier.js.map +1 -1
  24. package/dist/services/tool-context-builder.d.ts.map +1 -1
  25. package/dist/services/tool-context-builder.js +16 -4
  26. package/dist/services/tool-context-builder.js.map +1 -1
  27. package/dist/services/tool-protection.service.d.ts +7 -0
  28. package/dist/services/tool-protection.service.d.ts.map +1 -1
  29. package/dist/services/tool-protection.service.js +34 -15
  30. package/dist/services/tool-protection.service.js.map +1 -1
  31. package/dist/types/tool-protection.d.ts +94 -0
  32. package/dist/types/tool-protection.d.ts.map +1 -1
  33. package/dist/types/tool-protection.js +113 -1
  34. package/dist/types/tool-protection.js.map +1 -1
  35. package/package.json +2 -2
  36. package/src/__tests__/runtime/amount-limit-enforcement.test.ts +269 -0
  37. package/src/__tests__/runtime/amount-limit-result.test.ts +61 -0
  38. package/src/__tests__/runtime/audit-contracts-compat.test.ts +20 -5
  39. package/src/__tests__/runtime/audit.test.ts +255 -53
  40. package/src/__tests__/runtime/process-tool-call-security.test.ts +97 -13
  41. package/src/__tests__/runtime/provider-selection.test.ts +4 -6
  42. package/src/__tests__/runtime/route-interception.test.ts +215 -214
  43. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +89 -6
  44. package/src/__tests__/services/tool-protection-amount.test.ts +107 -0
  45. package/src/__tests__/services/tool-protection-failsafe.test.ts +71 -4
  46. package/src/__tests__/utils/tool-protection-runtime.ts +3 -0
  47. package/src/index.ts +15 -1
  48. package/src/proof/__tests__/proof-generator.test.ts +35 -12
  49. package/src/proof/generator.ts +18 -27
  50. package/src/runtime/__tests__/ext-apps-consent.test.ts +87 -2
  51. package/src/runtime/audit.ts +155 -62
  52. package/src/runtime/base.ts +95 -31
  53. package/src/services/__tests__/access-control.service.test.ts +44 -0
  54. package/src/services/__tests__/proof-verifier.test.ts +283 -195
  55. package/src/services/__tests__/tool-context-builder-authtype.test.ts +79 -0
  56. package/src/services/__tests__/tool-context-builder.test.ts +4 -7
  57. package/src/services/__tests__/tool-protection-served-revision.test.ts +102 -0
  58. package/src/services/access-control.service.ts +11 -5
  59. package/src/services/proof-verifier.ts +18 -79
  60. package/src/services/tool-context-builder.ts +19 -4
  61. package/src/services/tool-protection.service.ts +62 -19
  62. package/src/types/tool-protection.ts +161 -0
@@ -240,3 +240,82 @@ describe("ToolContextBuilder — delegation auth-type enforcement (B3)", () => {
240
240
  });
241
241
  });
242
242
  });
243
+
244
+ describe("ToolContextBuilder — stored IdP token needs a satisfying delegation (finding A)", () => {
245
+ // Defence in depth: a delegation minted under the user's DID without their
246
+ // sign-in must not unlock the IdP token stored for that DID.
247
+ const oauthTool: ToolProtection = {
248
+ requiresDelegation: true,
249
+ requiredScopes: ["read:user"],
250
+ authorization: { type: "oauth2", provider: "github" },
251
+ };
252
+
253
+ let builder: ToolContextBuilder;
254
+
255
+ beforeEach(() => {
256
+ builder = new ToolContextBuilder({
257
+ tokenResolver: {
258
+ resolveTokenDataFromDid: vi.fn().mockResolvedValue({
259
+ access_token: "victim-idp-token",
260
+ tokenUsage: "bearer",
261
+ }),
262
+ } as unknown as IdpTokenResolver,
263
+ configService: {
264
+ getOAuthConfig: vi.fn(),
265
+ } as unknown as OAuthConfigService,
266
+ providerResolver: {
267
+ resolveProvider: vi.fn().mockResolvedValue("github"),
268
+ } as unknown as ProviderResolver,
269
+ projectId: "proj-123",
270
+ });
271
+ });
272
+
273
+ it.each([
274
+ ["a none delegation", "none"],
275
+ ["a password delegation", "password"],
276
+ ["a legacy delegation with no type", undefined],
277
+ ])(
278
+ "re-challenges instead of handing out the token for %s",
279
+ async (_label, delegationType) => {
280
+ await expect(
281
+ builder.buildContext(
282
+ "gated-tool",
283
+ "did:key:z6MkVictim",
284
+ "session-123",
285
+ "delegation-token",
286
+ oauthTool,
287
+ delegationType
288
+ )
289
+ ).rejects.toThrow(OAuthRequiredError);
290
+ }
291
+ );
292
+
293
+ it("hands out the token for an oauth2 delegation", async () => {
294
+ const result = await builder.buildContext(
295
+ "gated-tool",
296
+ "did:key:z6MkUser",
297
+ "session-123",
298
+ "delegation-token",
299
+ oauthTool,
300
+ "oauth2"
301
+ );
302
+
303
+ expect(result?.idpToken).toBe("victim-idp-token");
304
+ expect(result?.idpHeaders).toEqual({
305
+ Authorization: "Bearer victim-idp-token",
306
+ });
307
+ });
308
+
309
+ it("keeps the existing behaviour when no delegation is presented", async () => {
310
+ const result = await builder.buildContext(
311
+ "gated-tool",
312
+ "did:key:z6MkUser",
313
+ "session-123",
314
+ undefined,
315
+ oauthTool,
316
+ undefined
317
+ );
318
+
319
+ expect(result?.idpToken).toBe("victim-idp-token");
320
+ });
321
+ });
@@ -114,7 +114,10 @@ describe("ToolContextBuilder", () => {
114
114
  "did:key:z6MkUser123",
115
115
  "session-123",
116
116
  "delegation-token",
117
- toolProtection
117
+ toolProtection,
118
+ // A presented delegation must satisfy the tool's type before the
119
+ // stored IdP token is handed out (finding A defence in depth).
120
+ "oauth2"
118
121
  );
119
122
 
120
123
  expect(result).toBeDefined();
@@ -430,9 +433,3 @@ describe("ToolContextBuilder", () => {
430
433
  });
431
434
  });
432
435
  });
433
-
434
-
435
-
436
-
437
-
438
-
@@ -0,0 +1,102 @@
1
+ /**
2
+ * The served tool-protection revision: the hash of exactly what Checkpoint
3
+ * served, which a native challenge registration reports and Checkpoint
4
+ * recomputes. It is computed from the served `tools` object as received,
5
+ * before any local config is merged in.
6
+ */
7
+ import { createHash } from "node:crypto";
8
+ import { afterEach, describe, expect, it, vi } from "vitest";
9
+ import { canonicalize } from "json-canonicalize";
10
+
11
+ import { InMemoryToolProtectionCache } from "../../cache/tool-protection-cache.js";
12
+ import {
13
+ ToolProtectionService,
14
+ servedToolProtectionRevision,
15
+ } from "../tool-protection.service.js";
16
+
17
+ const SERVED_TOOLS = {
18
+ place_order: {
19
+ requiresDelegation: true,
20
+ requiredScopes: ["orders:write"],
21
+ authorization: { type: "none" },
22
+ },
23
+ browse_catalog: { requiresDelegation: false, requiredScopes: [] },
24
+ };
25
+
26
+ afterEach(() => {
27
+ vi.unstubAllGlobals();
28
+ });
29
+
30
+ describe("servedToolProtectionRevision", () => {
31
+ it("is the SHA-256 hex of the RFC 8785 canonical JSON", async () => {
32
+ const expected = createHash("sha256")
33
+ .update(canonicalize(SERVED_TOOLS))
34
+ .digest("hex");
35
+ expect(await servedToolProtectionRevision(SERVED_TOOLS)).toBe(expected);
36
+ });
37
+
38
+ it("does not depend on key order", async () => {
39
+ const reordered = {
40
+ browse_catalog: { requiredScopes: [], requiresDelegation: false },
41
+ place_order: {
42
+ authorization: { type: "none" },
43
+ requiredScopes: ["orders:write"],
44
+ requiresDelegation: true,
45
+ },
46
+ };
47
+ expect(await servedToolProtectionRevision(reordered)).toBe(
48
+ await servedToolProtectionRevision(SERVED_TOOLS)
49
+ );
50
+ });
51
+ });
52
+
53
+ describe("ToolProtectionService.getToolProtectionConfig", () => {
54
+ function service(localConfig?: Record<string, unknown>) {
55
+ return new ToolProtectionService(
56
+ {
57
+ apiUrl: "https://checkpoint.test",
58
+ apiKey: "sk_test_key",
59
+ projectId: "project-1",
60
+ failSafeBehavior: "deny-all",
61
+ ...(localConfig
62
+ ? { localConfig: { toolProtections: localConfig as never } }
63
+ : {}),
64
+ },
65
+ new InMemoryToolProtectionCache()
66
+ );
67
+ }
68
+
69
+ it("records the revision of the served tools, as received, before the local merge", async () => {
70
+ vi.stubGlobal(
71
+ "fetch",
72
+ vi.fn(async () =>
73
+ Response.json({
74
+ success: true,
75
+ data: { config: { toolProtection: { tools: SERVED_TOOLS } } },
76
+ })
77
+ )
78
+ );
79
+ const config = await service({
80
+ local_only: { requiresDelegation: true, requiredScopes: ["x:y"] },
81
+ }).getToolProtectionConfig("did:key:z6MkAgent");
82
+
83
+ expect(config.servedRevision).toBe(
84
+ await servedToolProtectionRevision(SERVED_TOOLS)
85
+ );
86
+ // The local tool is evaluated, but it is not part of what Checkpoint served.
87
+ expect(Object.keys(config.toolProtections)).toContain("local_only");
88
+ });
89
+
90
+ it("records no revision for a config Checkpoint did not serve", async () => {
91
+ // A network failure falls back to the fail-safe deny-all config.
92
+ vi.stubGlobal(
93
+ "fetch",
94
+ vi.fn(async () => {
95
+ throw new TypeError("network down");
96
+ })
97
+ );
98
+ vi.spyOn(console, "error").mockImplementation(() => {});
99
+ const config = await service().getToolProtectionConfig("did:key:z6MkAgent");
100
+ expect(config.servedRevision).toBeUndefined();
101
+ });
102
+ });
@@ -28,6 +28,7 @@ import {
28
28
  } from "@kya-os/contracts/checkpoint-api";
29
29
  import { CheckpointAPIError } from "@kya-os/contracts/checkpoint-api";
30
30
  import type { FetchProvider } from "../providers/base";
31
+ import { normalizeAuthType } from "./auth-type-satisfies.js";
31
32
 
32
33
  // Type for error response
33
34
  type CheckpointAPIErrorResponse = {
@@ -1026,16 +1027,21 @@ export function authorizationMatches(
1026
1027
  return true;
1027
1028
  }
1028
1029
 
1029
- // Compare type (strict match for other cases)
1030
- if (delegationAuth.type !== toolAuth.type) return false;
1031
-
1032
- // For OAuth, compare provider (undefined in toolAuth means "any provider is acceptable")
1033
- if (delegationAuth.type === "oauth") {
1030
+ // Checkpoint grants can use the legacy `oauth` spelling while current tool
1031
+ // configuration uses `oauth2`. Both must enforce the same provider boundary;
1032
+ // checking only `oauth` would also let two `oauth2` values skip that check.
1033
+ const delegationIsOAuth = normalizeAuthType(delegationAuth.type) === "oauth2";
1034
+ const toolRequiresOAuth = normalizeAuthType(toolAuth.type) === "oauth2";
1035
+ if (delegationIsOAuth || toolRequiresOAuth) {
1036
+ if (!delegationIsOAuth || !toolRequiresOAuth) return false;
1034
1037
  // If tool doesn't specify a provider, any provider is acceptable
1035
1038
  if (!toolAuth.provider) return true;
1036
1039
  return delegationAuth.provider === toolAuth.provider;
1037
1040
  }
1038
1041
 
1042
+ // Preserve the existing comparison for non-OAuth authorization types.
1043
+ if (delegationAuth.type !== toolAuth.type) return false;
1044
+
1039
1045
  // For verifiable_credential, compare credentialType
1040
1046
  if (delegationAuth.type === "verifiable_credential") {
1041
1047
  // If tool doesn't specify a credential type, any type is acceptable
@@ -14,19 +14,11 @@
14
14
  * `runtime/base.ts` and the runtime subclasses that inject a `ProofVerifier` —
15
15
  * are unchanged.
16
16
  *
17
- * `verifyProof` calls DIF's `verifyProofDetached` (not DIF's `verifyProof`),
18
- * passing a canonical payload built by this façade's own
19
- * `buildCanonicalPayload` rather than letting DIF reconstruct it internally.
20
- * `@kya-os/mcp` is a separately-versioned, externally-published dependency,
21
- * so its own reconstruction does not know about fields this repo's signers
22
- * add to the payload (see `buildCanonicalPayload`'s doc comment) — supplying
23
- * the payload ourselves keeps the crypto/replay/skew pipeline delegated to
24
- * DIF while staying correct regardless of DIF's release cadence. One
25
- * consequence: the content-binding fail-closed check (DIF's `verifyProof`
26
- * third `expected` argument) is not reachable through `verifyProofDetached`,
27
- * but this façade never passed that argument through anyway. The one
28
- * pre-C2 default that differs (local timestamp skew defaulted to 300s vs
29
- * DIF's 120s) is preserved explicitly when composing the DIF verifier.
17
+ * `verifyProof` calls DIF's `verifyProof`, which rebuilds the signed payload
18
+ * from `proof.meta` with the same `buildProofJwsPayload` the signers use, so
19
+ * nothing in this repo reconstructs the payload itself. The one pre-C2
20
+ * default that differs (local timestamp skew defaulted to 300s vs DIF's
21
+ * 120s) is preserved explicitly when composing the DIF verifier.
30
22
  */
31
23
 
32
24
  import { type Ed25519JWK } from "./crypto.service.js";
@@ -113,17 +105,9 @@ export class ProofVerifier {
113
105
  * Verify a DetachedProof. Checks the JWS signature, nonce replay, and
114
106
  * timestamp skew via the DIF `ProofVerifier` pipeline.
115
107
  *
116
- * Deliberately calls the DIF verifier's `verifyProofDetached()` with a
117
- * canonical payload built by this class's own `buildCanonicalPayload()`,
118
- * rather than the DIF verifier's `verifyProof()` (which would reconstruct
119
- * the payload using ITS OWN internal builder). `@kya-os/mcp` is a
120
- * separately-versioned, externally-published dependency; its internal
121
- * builder does not know about the literal did/kid/audience/toolName/
122
- * outcome fields this repo's signers add to the payload, so proofs signed
123
- * here would fail `@kya-os/mcp`'s own reconstruction even though the
124
- * signature is genuinely valid. Supplying the payload ourselves keeps the
125
- * nonce-replay/timestamp-skew/signature pipeline delegated to DIF while
126
- * sidestepping its stale reconstruction.
108
+ * Calls the DIF verifier's `verifyProof()`, which rebuilds the signed
109
+ * payload from `proof.meta` (the shared `buildProofJwsPayload`, RFC 8785)
110
+ * and checks the signature over it.
127
111
  *
128
112
  * @param proof - The proof to verify
129
113
  * @param publicKeyJwk - Ed25519 public key in JWK format (from DID document)
@@ -134,10 +118,8 @@ export class ProofVerifier {
134
118
  publicKeyJwk: Ed25519JWK
135
119
  ): Promise<ProofVerificationResult> {
136
120
  const verifier = await this.getDifVerifier();
137
- const canonicalPayload = this.buildCanonicalPayload(proof.meta);
138
- return verifier.verifyProofDetached(
121
+ return verifier.verifyProof(
139
122
  proof,
140
- canonicalPayload,
141
123
  publicKeyJwk
142
124
  ) as Promise<ProofVerificationResult>;
143
125
  }
@@ -271,60 +253,17 @@ export class ProofVerifier {
271
253
  }
272
254
 
273
255
  /**
274
- * Build canonical payload from proof meta
275
- *
276
- * CRITICAL: This must reconstruct the exact JWS payload structure that was originally signed.
277
- * The original JWS payload uses standard JWT claims (aud, sub, iss) plus custom proof claims,
278
- * NOT the proof.meta structure directly.
279
- *
280
- * Kept local (not delegated): callers invoke this synchronously, while the DIF
281
- * verifier is only reachable through the async seam. The reconstruction is
282
- * byte-identical to DIF's `buildCanonicalPayload`.
256
+ * The canonical (RFC 8785) JWS payload for `meta`, for detached-JWS
257
+ * consumers. Delegates to `@kya-os/mcp`'s `buildProofJwsPayload`; async
258
+ * because that module is reached through the ESM-bridge seam.
283
259
  *
284
260
  * @param meta - Proof metadata
285
- * @returns Canonical JSON string matching the original JWS payload structure
261
+ * @returns Canonical JSON string identical to the payload a signer signs
286
262
  */
287
- buildCanonicalPayload(meta: DetachedProof["meta"]): string {
288
- // Reconstruct the original JWS payload structure that was signed
289
- // This matches the structure used in proof generation (proof.ts, proof-generator.ts)
290
- const payload = {
291
- // Standard JWT claims (RFC 7519) - these are what was actually signed
292
- aud: meta.audience, // Audience (who the token is for)
293
- sub: meta.did, // Subject (agent DID)
294
- iss: meta.did, // Issuer (agent DID - self-issued)
295
-
296
- // Literal field names some verifiers (e.g. knowthat.ai) check by
297
- // exact property, rather than the JWT-standard aliases above -- must
298
- // stay in lockstep with generator.ts's payload, or reconstruction
299
- // here will byte-diverge from what was actually signed.
300
- did: meta.did,
301
- kid: meta.kid,
302
- audience: meta.audience,
303
-
304
- // Custom MCP-I proof claims
305
- requestHash: meta.requestHash,
306
- responseHash: meta.responseHash,
307
- ts: meta.ts,
308
- nonce: meta.nonce,
309
- sessionId: meta.sessionId,
310
-
311
- // Optional claims (only include if present)
312
- ...(meta.scopeId && { scopeId: meta.scopeId }),
313
- ...(meta.delegationRef && { delegationRef: meta.delegationRef }),
314
- ...(meta.clientDid && { clientDid: meta.clientDid }),
315
- ...(meta.toolName && { toolName: meta.toolName }),
316
- ...(meta.submissionOutcome && { outcome: meta.submissionOutcome }),
317
- };
318
-
319
- // generator.ts signs this payload via jose's SignJWT, which serializes
320
- // with a plain JSON.stringify() in object-insertion order (see
321
- // JWTClaimsBuilder.data() in the jose source) -- NOT RFC 8785 JCS.
322
- // canonicalize() sorts keys alphabetically, which byte-diverges from
323
- // what was actually signed even when every field VALUE matches (this
324
- // silently broke DIF-delegated verification: see the regression tests
325
- // above). The object literal above already mirrors generator.ts's
326
- // field order exactly, so a plain JSON.stringify() here reproduces the
327
- // exact bytes that were signed.
328
- return JSON.stringify(payload);
263
+ async buildCanonicalPayload(meta: DetachedProof["meta"]): Promise<string> {
264
+ const { buildProofJwsPayload, canonicalizeJSON } = await loadDifCore();
265
+ return canonicalizeJSON(
266
+ buildProofJwsPayload(meta as Parameters<typeof buildProofJwsPayload>[0])
267
+ );
329
268
  }
330
269
  }
@@ -134,8 +134,23 @@ export class ToolContextBuilder {
134
134
  toolProtection.requiredScopes
135
135
  );
136
136
 
137
- if (!tokenData) {
138
- // IDP token not available - check if delegation token exists
137
+ // Reaching this OAuth context builder means the tool is neither
138
+ // consent-only (`none`) nor password (see the comment below), so the
139
+ // effective requirement is OAuth.
140
+ const requiredAuthType = toolProtection.authorization?.type ?? "oauth2";
141
+
142
+ // SECURITY (defence in depth): a presented delegation must satisfy the
143
+ // tool's required type before the user's stored IdP token is handed to the
144
+ // tool, the same rule as the delegation-only path below. Otherwise a
145
+ // delegation minted under the user's DID without their sign-in (an
146
+ // anonymous `none` one, say) would unlock their token. Not presenting a
147
+ // delegation keeps the existing behaviour.
148
+ const presentedDelegationAllowed =
149
+ !delegationToken ||
150
+ authTypeSatisfies(delegationAuthorizationType, requiredAuthType);
151
+
152
+ if (!tokenData || !presentedDelegationAllowed) {
153
+ // No usable IDP token - check if delegation token exists
139
154
  // If delegation exists, tool can still execute without IDP token
140
155
  // (the tool handler should check for idpToken if it needs external API access)
141
156
  //
@@ -150,8 +165,8 @@ export class ToolContextBuilder {
150
165
  // mismatched delegation (e.g. an anonymous `none` consent-only delegation,
151
166
  // or a legacy record with no persisted type → undefined) is rejected. On
152
167
  // mismatch we do NOT return the delegation-only context; we fall through
153
- // to OAuthRequiredError so the tool re-challenges.
154
- const requiredAuthType = toolProtection.authorization?.type ?? "oauth2";
168
+ // to OAuthRequiredError so the tool re-challenges. `requiredAuthType`
169
+ // is computed above.
155
170
  if (
156
171
  delegationToken &&
157
172
  authTypeSatisfies(delegationAuthorizationType, requiredAuthType)
@@ -106,10 +106,36 @@
106
106
  * @package @kya-os/mcp-i-core
107
107
  */
108
108
 
109
- import type { ToolProtection, ToolProtectionConfig, ToolProtectionServiceConfig } from "../types/tool-protection.js";
110
- import type { AuthorizationRequirement } from "@kya-os/contracts/tool-protection";
109
+ import type {
110
+ ToolProtection,
111
+ ToolProtectionConfig,
112
+ ToolProtectionServiceConfig,
113
+ } from "../types/tool-protection.js";
114
+ import { unavailableToolProtection } from "../types/tool-protection.js";
115
+ import type {
116
+ AuthorizationRequirement,
117
+ ToolAmountConfig,
118
+ } from "@kya-os/contracts/tool-protection";
111
119
  import type { ToolProtectionCache } from "../cache/tool-protection-cache.js";
112
120
  import { InMemoryToolProtectionCache } from "../cache/tool-protection-cache.js";
121
+ import { canonicalize } from "json-canonicalize";
122
+
123
+ /**
124
+ * The revision of the tool protection Checkpoint served: SHA-256 (lowercase
125
+ * hex) of the RFC 8785 canonical JSON of `config.toolProtection.tools`,
126
+ * exactly as received. Checkpoint recomputes the same from what it serves.
127
+ */
128
+ export async function servedToolProtectionRevision(
129
+ tools: unknown
130
+ ): Promise<string> {
131
+ const digest = await crypto.subtle.digest(
132
+ "SHA-256",
133
+ new TextEncoder().encode(canonicalize(tools))
134
+ );
135
+ return [...new Uint8Array(digest)]
136
+ .map((byte) => byte.toString(16).padStart(2, "0"))
137
+ .join("");
138
+ }
113
139
 
114
140
  /**
115
141
  * Tool protection data structure in API responses
@@ -130,6 +156,7 @@ interface ToolProtectionData {
130
156
  issuer?: string;
131
157
  credentialType?: string;
132
158
  };
159
+ amount?: ToolAmountConfig;
133
160
  }
134
161
 
135
162
  /**
@@ -235,6 +262,17 @@ export class ToolProtectionService {
235
262
  return null;
236
263
  }
237
264
 
265
+ private keepLocalAmount(
266
+ toolName: string,
267
+ apiConfig: ToolProtection
268
+ ): ToolProtection {
269
+ const localAmount =
270
+ this.config.localConfig?.toolProtections?.[toolName]?.amount;
271
+ return apiConfig.amount || !localAmount
272
+ ? apiConfig
273
+ : { ...apiConfig, amount: localAmount };
274
+ }
275
+
238
276
  /**
239
277
  * Get tool protection configuration for the agent
240
278
  *
@@ -370,6 +408,9 @@ export class ToolProtectionService {
370
408
  ...((localConfig as ToolProtection).authorization && {
371
409
  authorization: (localConfig as ToolProtection).authorization,
372
410
  }),
411
+ ...((localConfig as ToolProtection).amount && {
412
+ amount: (localConfig as ToolProtection).amount,
413
+ }),
373
414
  };
374
415
 
375
416
  mergedToolProtections[toolName] = validConfig;
@@ -387,7 +428,10 @@ export class ToolProtectionService {
387
428
 
388
429
  // Step 2: Apply API config (OVERWRITES local config - remote wins)
389
430
  for (const [toolName, apiConfig] of Object.entries(toolProtections)) {
390
- mergedToolProtections[toolName] = apiConfig;
431
+ mergedToolProtections[toolName] = this.keepLocalAmount(
432
+ toolName,
433
+ apiConfig
434
+ );
391
435
  if (
392
436
  this.config.debug &&
393
437
  this.config.localConfig?.toolProtections?.[toolName]
@@ -404,6 +448,9 @@ export class ToolProtectionService {
404
448
 
405
449
  const config: ToolProtectionConfig = {
406
450
  toolProtections: mergedToolProtections,
451
+ servedRevision: await servedToolProtectionRevision(
452
+ response.data?.config?.toolProtection?.tools ?? {}
453
+ ),
407
454
  };
408
455
 
409
456
  // 3. Cache the response
@@ -543,21 +590,10 @@ export class ToolProtectionService {
543
590
  }
544
591
  );
545
592
 
546
- // Create deny-all config (wildcard requires delegation for all tools)
547
- const denyAllConfig: ToolProtectionConfig = {
548
- toolProtections: {
549
- "*": {
550
- requiresDelegation: true,
551
- requiredScopes: [],
552
- },
553
- },
554
- };
555
-
556
- // Cache deny-all config to avoid repeated API calls
557
- const ttl = this.config.cacheTtl ?? 300000; // Default 5 minutes
558
- await this.cache.set(cacheKey, denyAllConfig, ttl);
559
-
560
- return denyAllConfig;
593
+ // Protection is unavailable: every tool resolves to the stand-in,
594
+ // which the runtime refuses. It isn't cached, so the next lookup
595
+ // reads the API again and the first config that arrives replaces it.
596
+ return { toolProtections: { "*": unavailableToolProtection() } };
561
597
  } else {
562
598
  // failSafeBehavior === 'allow-all' (insecure, not recommended)
563
599
  console.warn(
@@ -810,6 +846,7 @@ export class ToolProtectionService {
810
846
  ...(oauthProvider && { oauthProvider }),
811
847
  ...(riskLevel && { riskLevel }),
812
848
  ...(authorization && { authorization }),
849
+ ...(toolConfig.amount && { amount: toolConfig.amount }),
813
850
  };
814
851
  }
815
852
 
@@ -920,6 +957,9 @@ export class ToolProtectionService {
920
957
  ...((localConfig as ToolProtection).authorization && {
921
958
  authorization: (localConfig as ToolProtection).authorization,
922
959
  }),
960
+ ...((localConfig as ToolProtection).amount && {
961
+ amount: (localConfig as ToolProtection).amount,
962
+ }),
923
963
  };
924
964
  mergedToolProtections[toolName] = validConfig;
925
965
  }
@@ -928,7 +968,10 @@ export class ToolProtectionService {
928
968
 
929
969
  // Step 2: Apply API config (OVERWRITES local config - remote wins)
930
970
  for (const [toolName, apiConfig] of Object.entries(toolProtections)) {
931
- mergedToolProtections[toolName] = apiConfig;
971
+ mergedToolProtections[toolName] = this.keepLocalAmount(
972
+ toolName,
973
+ apiConfig
974
+ );
932
975
  }
933
976
 
934
977
  // Construct fresh config (ToolProtectionConfig type)