@kya-os/mcp-i-runtime 1.2.4 → 1.2.6

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 (103) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/auth/types.d.ts +1 -1
  3. package/dist/auth/types.d.ts.map +1 -1
  4. package/dist/config/remote-config.d.ts +3 -3
  5. package/dist/config/remote-config.js +4 -4
  6. package/dist/config/remote-config.js.map +1 -1
  7. package/dist/identity/user-did-manager.d.ts +4 -4
  8. package/dist/identity/user-did-manager.js +5 -5
  9. package/dist/identity/user-did-manager.js.map +1 -1
  10. package/dist/index.d.ts +4 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +11 -3
  13. package/dist/index.js.map +1 -1
  14. package/dist/runtime/audit.d.ts.map +1 -1
  15. package/dist/runtime/audit.js +22 -0
  16. package/dist/runtime/audit.js.map +1 -1
  17. package/dist/runtime/base.d.ts +17 -11
  18. package/dist/runtime/base.d.ts.map +1 -1
  19. package/dist/runtime/base.js +58 -28
  20. package/dist/runtime/base.js.map +1 -1
  21. package/dist/runtime/delegation-denial.d.ts +43 -0
  22. package/dist/runtime/delegation-denial.d.ts.map +1 -0
  23. package/dist/runtime/delegation-denial.js +83 -0
  24. package/dist/runtime/delegation-denial.js.map +1 -0
  25. package/dist/runtime/verified-delegation.d.ts +30 -0
  26. package/dist/runtime/verified-delegation.d.ts.map +1 -0
  27. package/dist/runtime/verified-delegation.js +62 -0
  28. package/dist/runtime/verified-delegation.js.map +1 -0
  29. package/dist/services/access-control.service.d.ts +2 -2
  30. package/dist/services/access-control.service.js +4 -4
  31. package/dist/services/access-control.service.js.map +1 -1
  32. package/dist/services/delegation-error-formatter.d.ts +15 -0
  33. package/dist/services/delegation-error-formatter.d.ts.map +1 -1
  34. package/dist/services/delegation-error-formatter.js +27 -1
  35. package/dist/services/delegation-error-formatter.js.map +1 -1
  36. package/dist/services/oauth-config.service.d.ts +4 -4
  37. package/dist/services/oauth-config.service.d.ts.map +1 -1
  38. package/dist/services/oauth-config.service.js +8 -8
  39. package/dist/services/oauth-config.service.js.map +1 -1
  40. package/dist/services/oauth-provider-registry.d.ts +3 -3
  41. package/dist/services/oauth-provider-registry.js +4 -4
  42. package/dist/services/oauth-provider-registry.js.map +1 -1
  43. package/dist/services/oauth-service.d.ts +8 -8
  44. package/dist/services/oauth-service.d.ts.map +1 -1
  45. package/dist/services/oauth-service.js +8 -8
  46. package/dist/services/oauth-service.js.map +1 -1
  47. package/dist/services/oauth-token-retrieval.service.d.ts +6 -6
  48. package/dist/services/oauth-token-retrieval.service.d.ts.map +1 -1
  49. package/dist/services/oauth-token-retrieval.service.js +5 -5
  50. package/dist/services/provider-resolver.d.ts +1 -1
  51. package/dist/services/provider-resolver.js +4 -4
  52. package/dist/services/provider-resolver.js.map +1 -1
  53. package/dist/services/session-registration.service.d.ts +4 -4
  54. package/dist/services/session-registration.service.d.ts.map +1 -1
  55. package/dist/services/session-registration.service.js +5 -5
  56. package/dist/services/session-registration.service.js.map +1 -1
  57. package/dist/services/tool-protection.service.d.ts +13 -13
  58. package/dist/services/tool-protection.service.js +16 -16
  59. package/dist/services/tool-protection.service.js.map +1 -1
  60. package/dist/types/tool-protection.d.ts +11 -4
  61. package/dist/types/tool-protection.d.ts.map +1 -1
  62. package/dist/types/tool-protection.js +8 -1
  63. package/dist/types/tool-protection.js.map +1 -1
  64. package/package.json +3 -3
  65. package/src/__tests__/index.test.ts +12 -0
  66. package/src/__tests__/integration/full-flow.test.ts +3 -3
  67. package/src/__tests__/runtime/audit-contracts-compat.test.ts +54 -0
  68. package/src/__tests__/runtime/audit.test.ts +172 -0
  69. package/src/__tests__/runtime/delegation-denial.test.ts +115 -0
  70. package/src/__tests__/runtime/native-holder-enforcement.test.ts +107 -0
  71. package/src/__tests__/runtime/process-tool-call-security.test.ts +323 -6
  72. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +40 -42
  73. package/src/__tests__/runtime/verified-delegation.test.ts +129 -0
  74. package/src/__tests__/services/agentshield-integration.test.ts +3 -3
  75. package/src/__tests__/services/oauth-service-secret-resolution.test.ts +1 -1
  76. package/src/__tests__/services/provider-resolver-edge-cases.test.ts +2 -2
  77. package/src/__tests__/services/tool-protection.service.test.ts +1 -1
  78. package/src/__tests__/utils/tool-protection-runtime.ts +25 -0
  79. package/src/auth/types.ts +1 -1
  80. package/src/config/remote-config.ts +4 -4
  81. package/src/identity/user-did-manager.ts +5 -5
  82. package/src/index.ts +15 -0
  83. package/src/runtime/audit.ts +26 -0
  84. package/src/runtime/base.ts +76 -31
  85. package/src/runtime/delegation-denial.ts +107 -0
  86. package/src/runtime/verified-delegation.ts +66 -0
  87. package/src/services/__tests__/access-control.proof-response-validation.test.ts +8 -8
  88. package/src/services/__tests__/delegation-error-formatter.test.ts +156 -0
  89. package/src/services/__tests__/oauth-config.service.test.ts +2 -2
  90. package/src/services/__tests__/oauth-provider-registry.test.ts +1 -1
  91. package/src/services/__tests__/storage.service.test.ts +21 -16
  92. package/src/services/access-control.service.ts +4 -4
  93. package/src/services/delegation-error-formatter.ts +42 -1
  94. package/src/services/oauth-config.service.d.ts +4 -4
  95. package/src/services/oauth-config.service.ts +9 -9
  96. package/src/services/oauth-provider-registry.d.ts +2 -2
  97. package/src/services/oauth-provider-registry.ts +4 -4
  98. package/src/services/oauth-service.ts +10 -10
  99. package/src/services/oauth-token-retrieval.service.ts +8 -8
  100. package/src/services/provider-resolver.ts +4 -4
  101. package/src/services/session-registration.service.ts +6 -6
  102. package/src/services/tool-protection.service.ts +17 -17
  103. package/src/types/tool-protection.ts +13 -4
@@ -0,0 +1,107 @@
1
+ import { describe, it, expect, beforeEach, vi } from "vitest";
2
+ import type { MCPIRuntimeBase } from "../../runtime/base";
3
+ import { createToolProtectionRuntime } from "../utils/tool-protection-runtime";
4
+ import { DelegationRequiredError } from "../../types/tool-protection";
5
+
6
+ describe("native holder tool enforcement", () => {
7
+ let runtime: MCPIRuntimeBase;
8
+ let mockToolProtectionService: {
9
+ checkToolProtection: ReturnType<typeof vi.fn>;
10
+ };
11
+ let mockAccessControlService: { verifyDelegation: ReturnType<typeof vi.fn> };
12
+ const mockHandler = vi.fn().mockResolvedValue({ result: "success" });
13
+ const session = {
14
+ id: "session123",
15
+ audience: "https://client.example.com",
16
+ nonce: "test-nonce",
17
+ };
18
+ beforeEach(async () => {
19
+ vi.clearAllMocks();
20
+ ({ runtime, mockToolProtectionService, mockAccessControlService } =
21
+ await createToolProtectionRuntime());
22
+ });
23
+
24
+ it.each([true, false])(
25
+ "uses the proved invoker and rejects a foreign verified grant (matching=%s)",
26
+ async (matching) => {
27
+ mockToolProtectionService.checkToolProtection.mockResolvedValue({
28
+ requiresDelegation: true,
29
+ requiredScopes: ["files:write"],
30
+ });
31
+ const holder = "did:web:native-agent.example";
32
+ mockAccessControlService.verifyDelegation.mockResolvedValue({
33
+ success: true,
34
+ data: {
35
+ valid: true,
36
+ credential: {
37
+ agent_did: matching ? holder : "did:key:zmock123",
38
+ scopes: ["files:write"],
39
+ },
40
+ },
41
+ });
42
+ const call = runtime.processToolCall("protectedTool", {}, mockHandler, {
43
+ ...session,
44
+ agentDid: holder,
45
+ verifiedInvokerDid: holder,
46
+ delegationToken: "delegation-for-native-holder",
47
+ });
48
+ if (matching) {
49
+ await expect(call).resolves.toEqual({ result: "success" });
50
+ expect(mockHandler).toHaveBeenCalledTimes(1);
51
+ } else {
52
+ await expect(call).rejects.toThrow(DelegationRequiredError);
53
+ expect(mockHandler).not.toHaveBeenCalled();
54
+ }
55
+ expect(mockAccessControlService.verifyDelegation).toHaveBeenCalledWith(
56
+ expect.objectContaining({ agent_did: holder }),
57
+ expect.any(Object)
58
+ );
59
+ // Configuration belongs to the serving deployment, while authority names
60
+ // the invoker. Response signing must still use the serving identity.
61
+ expect(
62
+ mockToolProtectionService.checkToolProtection
63
+ ).toHaveBeenCalledWith("protectedTool", "did:key:zmock123");
64
+ expect((await runtime.getIdentity()).did).toBe("did:key:zmock123");
65
+ }
66
+ );
67
+
68
+ it("does not promote a handshake agent label to a proved invoker", async () => {
69
+ mockToolProtectionService.checkToolProtection.mockResolvedValue({
70
+ requiresDelegation: true,
71
+ requiredScopes: ["files:write"],
72
+ });
73
+ mockAccessControlService.verifyDelegation.mockResolvedValue({
74
+ success: true,
75
+ data: { valid: true },
76
+ });
77
+ await runtime.processToolCall("protectedTool", {}, mockHandler, {
78
+ ...session,
79
+ agentDid: "did:web:unproved.example",
80
+ delegationToken: "runtime-grant",
81
+ });
82
+ expect(mockAccessControlService.verifyDelegation).toHaveBeenCalledWith(
83
+ expect.objectContaining({ agent_did: "did:key:zmock123" }),
84
+ expect.any(Object)
85
+ );
86
+ });
87
+
88
+ it("keeps the proved holder in the existing consent challenge when authority is missing", async () => {
89
+ mockToolProtectionService.checkToolProtection.mockResolvedValue({
90
+ requiresDelegation: true,
91
+ requiredScopes: ["files:write"],
92
+ });
93
+ const holder = "did:web:native-agent.example";
94
+ const failure = await runtime
95
+ .processToolCall("protectedTool", {}, mockHandler, {
96
+ ...session,
97
+ agentDid: holder,
98
+ verifiedInvokerDid: holder,
99
+ })
100
+ .catch((error: unknown) => error);
101
+ expect(failure).toBeInstanceOf(DelegationRequiredError);
102
+ const url = new URL((failure as DelegationRequiredError).consentUrl!);
103
+ expect(url.searchParams.get("agent_did")).toBe(holder);
104
+ expect(url.searchParams.get("scopes")).toBe("files:write");
105
+ expect(mockHandler).not.toHaveBeenCalled();
106
+ });
107
+ });
@@ -165,13 +165,19 @@ describe("processToolCall Security", () => {
165
165
  session
166
166
  );
167
167
 
168
- // Tool handler SHOULD be called
169
- expect(toolHandler).toHaveBeenCalledWith({ arg: "value" });
168
+ // Tool handler SHOULD be called, with the verified delegation second
169
+ expect(toolHandler).toHaveBeenCalledWith(
170
+ { arg: "value" },
171
+ expect.objectContaining({
172
+ id: "test-delegation",
173
+ scopes: ["tool:execute"],
174
+ })
175
+ );
170
176
  expect(result).toEqual({ result: "success" });
171
177
  });
172
178
 
173
- it("should allow delegation when user_identifier is email and AgentShield verifies it", async () => {
174
- // AgentShield may return email as user_identifier but internally link it to DID
179
+ it("should allow delegation when user_identifier is email and Checkpoint verifies it", async () => {
180
+ // Checkpoint may return email as user_identifier but internally link it to DID
175
181
  mockAccessControlService.verifyDelegation = vi.fn().mockResolvedValue({
176
182
  data: {
177
183
  valid: true,
@@ -179,7 +185,7 @@ describe("processToolCall Security", () => {
179
185
  credential: {
180
186
  scopes: ["tool:execute"],
181
187
  user_identifier: "user@example.com", // Email, not DID
182
- // No user_id field - AgentShield verified internally
188
+ // No user_id field - Checkpoint verified internally
183
189
  },
184
190
  },
185
191
  });
@@ -193,7 +199,7 @@ describe("processToolCall Security", () => {
193
199
 
194
200
  const toolHandler = vi.fn().mockResolvedValue({ result: "success" });
195
201
 
196
- // Should allow because email doesn't start with "did:" - trusted AgentShield verification
202
+ // Should allow because email doesn't start with "did:" - trusted Checkpoint verification
197
203
  const result = await runtime.processToolCall(
198
204
  "protected-tool",
199
205
  { arg: "value" },
@@ -1015,4 +1021,315 @@ describe("processToolCall Security", () => {
1015
1021
  );
1016
1022
  });
1017
1023
  });
1024
+
1025
+ describe("Verified Delegation Handoff", () => {
1026
+ const crisp = {
1027
+ units: "CHF",
1028
+ max_amount: "50.00",
1029
+ product_class: ["https://id.gs1.org/01/09506000134352"],
1030
+ };
1031
+
1032
+ function verifiedResponse(delegationId: string, scopes: string[]) {
1033
+ return {
1034
+ data: {
1035
+ valid: true,
1036
+ delegation_id: delegationId,
1037
+ credential: {
1038
+ agent_did: "did:key:zmock123",
1039
+ user_did: "did:key:zUser123",
1040
+ scopes,
1041
+ constraints: { not_after: 1_900_000_000, crisp },
1042
+ issued_at: 1_800_000_000,
1043
+ created_at: 1_800_000_000,
1044
+ authorization: { type: "none" },
1045
+ },
1046
+ },
1047
+ };
1048
+ }
1049
+
1050
+ const session = {
1051
+ id: "test-session",
1052
+ userDid: "did:key:zUser123",
1053
+ agentDid: "did:key:zmock123",
1054
+ delegationToken: "valid-token",
1055
+ };
1056
+
1057
+ it("passes the verifier's answer to the handler as the second argument", async () => {
1058
+ mockAccessControlService.verifyDelegation = vi
1059
+ .fn()
1060
+ .mockResolvedValue(
1061
+ verifiedResponse("delegation-1", ["tool:execute", "tool:read"])
1062
+ );
1063
+ const toolHandler = vi.fn().mockResolvedValue({ result: "success" });
1064
+
1065
+ await runtime.processToolCall(
1066
+ "protected-tool",
1067
+ { arg: "value" },
1068
+ toolHandler,
1069
+ session
1070
+ );
1071
+
1072
+ expect(toolHandler).toHaveBeenCalledTimes(1);
1073
+ expect(toolHandler).toHaveBeenCalledWith(
1074
+ { arg: "value" },
1075
+ {
1076
+ id: "delegation-1",
1077
+ agentDid: "did:key:zmock123",
1078
+ userDid: "did:key:zUser123",
1079
+ // Scopes come from the verifier, not from the tool's requiredScopes.
1080
+ scopes: ["tool:execute", "tool:read"],
1081
+ constraints: { not_after: 1_900_000_000, crisp },
1082
+ authorizationType: "none",
1083
+ expiresAt: 1_900_000_000,
1084
+ }
1085
+ );
1086
+ });
1087
+
1088
+ it("calls an unprotected tool's handler with exactly one argument", async () => {
1089
+ mockToolProtectionService.checkToolProtection = vi
1090
+ .fn()
1091
+ .mockResolvedValue(null);
1092
+ const toolHandler = vi.fn().mockResolvedValue({ result: "success" });
1093
+
1094
+ await runtime.processToolCall(
1095
+ "public-tool",
1096
+ { arg: "value" },
1097
+ toolHandler,
1098
+ session
1099
+ );
1100
+
1101
+ expect(toolHandler.mock.calls).toEqual([[{ arg: "value" }]]);
1102
+ });
1103
+
1104
+ it("calls the handler with exactly one argument when the verifier returns no credential", async () => {
1105
+ mockAccessControlService.verifyDelegation = vi.fn().mockResolvedValue({
1106
+ data: { valid: true, delegation_id: "kv-delegation" },
1107
+ });
1108
+ const toolHandler = vi.fn().mockResolvedValue({ result: "success" });
1109
+
1110
+ await runtime.processToolCall(
1111
+ "protected-tool",
1112
+ { arg: "value" },
1113
+ toolHandler,
1114
+ session
1115
+ );
1116
+
1117
+ expect(toolHandler.mock.calls).toEqual([[{ arg: "value" }]]);
1118
+ });
1119
+
1120
+ it("gives each of two interleaved calls its own verified delegation", async () => {
1121
+ const releaseFirstVerify: Array<() => void> = [];
1122
+ mockAccessControlService.verifyDelegation = vi
1123
+ .fn()
1124
+ .mockImplementationOnce(
1125
+ () =>
1126
+ new Promise((resolve) => {
1127
+ releaseFirstVerify.push(() =>
1128
+ resolve(verifiedResponse("delegation-first", ["tool:execute"]))
1129
+ );
1130
+ })
1131
+ )
1132
+ .mockResolvedValueOnce(
1133
+ verifiedResponse("delegation-second", ["tool:execute"])
1134
+ );
1135
+ const firstHandler = vi.fn().mockResolvedValue({ result: "first" });
1136
+ const secondHandler = vi.fn().mockResolvedValue({ result: "second" });
1137
+
1138
+ const firstCall = runtime.processToolCall(
1139
+ "protected-tool",
1140
+ { call: 1 },
1141
+ firstHandler,
1142
+ { ...session, delegationToken: "first-token" }
1143
+ );
1144
+ // Let the first call reach its (still pending) verify before starting the second.
1145
+ await vi.waitFor(() => expect(releaseFirstVerify).toHaveLength(1));
1146
+ await runtime.processToolCall(
1147
+ "protected-tool",
1148
+ { call: 2 },
1149
+ secondHandler,
1150
+ { ...session, delegationToken: "second-token" }
1151
+ );
1152
+ releaseFirstVerify[0]();
1153
+ await firstCall;
1154
+
1155
+ expect(firstHandler).toHaveBeenCalledWith(
1156
+ { call: 1 },
1157
+ expect.objectContaining({ id: "delegation-first" })
1158
+ );
1159
+ expect(secondHandler).toHaveBeenCalledWith(
1160
+ { call: 2 },
1161
+ expect.objectContaining({ id: "delegation-second" })
1162
+ );
1163
+ });
1164
+
1165
+ it("does not call the handler when verification fails", async () => {
1166
+ mockAccessControlService.verifyDelegation = vi.fn().mockResolvedValue({
1167
+ data: { valid: false, reason: "revoked" },
1168
+ });
1169
+ const toolHandler = vi.fn().mockResolvedValue({ result: "success" });
1170
+
1171
+ await expect(
1172
+ runtime.processToolCall(
1173
+ "protected-tool",
1174
+ { arg: "value" },
1175
+ toolHandler,
1176
+ session
1177
+ )
1178
+ ).rejects.toThrow(DelegationRequiredError);
1179
+ expect(toolHandler).not.toHaveBeenCalled();
1180
+ });
1181
+ });
1182
+
1183
+ describe("Verifier Denial Codes", () => {
1184
+ const session = {
1185
+ id: "test-session",
1186
+ userDid: "did:key:zUser123",
1187
+ agentDid: "did:key:zmock123",
1188
+ delegationToken: "presented-token",
1189
+ };
1190
+
1191
+ async function denialFor(
1192
+ verifyData: Record<string, unknown>,
1193
+ sessionOverrides: Record<string, unknown> = {}
1194
+ ) {
1195
+ mockAccessControlService.verifyDelegation = vi
1196
+ .fn()
1197
+ .mockResolvedValue({ data: verifyData });
1198
+ const toolHandler = vi.fn().mockResolvedValue({ result: "success" });
1199
+
1200
+ const error = await runtime
1201
+ .processToolCall(
1202
+ "protected-tool",
1203
+ { arg: "value" },
1204
+ toolHandler,
1205
+ { ...session, ...sessionOverrides }
1206
+ )
1207
+ .then(
1208
+ () => undefined,
1209
+ (thrown: unknown) => thrown
1210
+ );
1211
+
1212
+ expect(error).toBeInstanceOf(DelegationRequiredError);
1213
+ expect(toolHandler).not.toHaveBeenCalled();
1214
+ return error as DelegationRequiredError;
1215
+ }
1216
+
1217
+ it("reports a revoked grant without leaking the upstream message or details", async () => {
1218
+ const error = await denialFor({
1219
+ valid: false,
1220
+ error: {
1221
+ code: "delegation_revoked",
1222
+ message: "secret: revoked by admin",
1223
+ details: { reason: "secret fraud case 4411" },
1224
+ },
1225
+ });
1226
+
1227
+ expect(error.denial).toEqual({
1228
+ code: "delegation_revoked",
1229
+ message: "This authorization was revoked. Nothing was executed.",
1230
+ });
1231
+ expect(error.consentUrl).toBeTruthy();
1232
+ expect(error.resumeToken).toBeTruthy();
1233
+ expect(
1234
+ JSON.stringify({ message: error.message, denial: error.denial })
1235
+ ).not.toContain("secret");
1236
+ });
1237
+
1238
+ it("keeps agent_mismatch distinct from user_mismatch", async () => {
1239
+ const agentError = await denialFor({
1240
+ valid: false,
1241
+ error: { code: "agent_mismatch", message: "Agent DID mismatch" },
1242
+ });
1243
+ const userError = await denialFor({
1244
+ valid: false,
1245
+ error: { code: "user_mismatch", message: "User DID mismatch" },
1246
+ });
1247
+
1248
+ expect(agentError.denial?.code).toBe("agent_mismatch");
1249
+ expect(userError.denial?.code).toBe("user_mismatch");
1250
+ });
1251
+
1252
+ it("falls back to a legacy top-level reason only when it is an allowlisted code", async () => {
1253
+ const legacyError = await denialFor({
1254
+ valid: false,
1255
+ reason: "delegation_expired",
1256
+ });
1257
+ const freeTextError = await denialFor({
1258
+ valid: false,
1259
+ reason: "Delegation token invalid or expired",
1260
+ });
1261
+
1262
+ expect(legacyError.denial?.code).toBe("delegation_expired");
1263
+ expect(freeTextError.denial).toBeUndefined();
1264
+ });
1265
+
1266
+ it("reports a native holder binding mismatch from the runtime's own comparison", async () => {
1267
+ const error = await denialFor(
1268
+ {
1269
+ valid: true,
1270
+ delegation_id: "delegation-for-another-holder",
1271
+ credential: {
1272
+ agent_did: "did:key:zSomeoneElse",
1273
+ user_did: "did:key:zUser123",
1274
+ scopes: ["tool:execute"],
1275
+ issued_at: 1,
1276
+ created_at: 1,
1277
+ authorization: { type: "none" },
1278
+ },
1279
+ },
1280
+ { verifiedInvokerDid: "did:key:zAdmittedHolder" }
1281
+ );
1282
+
1283
+ expect(error.denial?.code).toBe("native_binding_mismatch");
1284
+ });
1285
+
1286
+ it("keeps the verifier's own denial code on the native rail", async () => {
1287
+ // A refused grant carries no credential, so a holder comparison against
1288
+ // it is meaningless and must not mask why Checkpoint refused it.
1289
+ const revokedError = await denialFor(
1290
+ {
1291
+ valid: false,
1292
+ error: { code: "delegation_revoked", message: "Revoked" },
1293
+ },
1294
+ { verifiedInvokerDid: "did:key:zAdmittedHolder" }
1295
+ );
1296
+ const unknownCodeError = await denialFor(
1297
+ {
1298
+ valid: false,
1299
+ error: { code: "project_not_found", message: "Project not found" },
1300
+ },
1301
+ { verifiedInvokerDid: "did:key:zAdmittedHolder" }
1302
+ );
1303
+
1304
+ expect(revokedError.denial?.code).toBe("delegation_revoked");
1305
+ expect(unknownCodeError.denial).toBeUndefined();
1306
+ });
1307
+
1308
+ it("leaves the denial undefined for a code outside the allowlist", async () => {
1309
+ const error = await denialFor({
1310
+ valid: false,
1311
+ error: { code: "project_not_found", message: "Project not found" },
1312
+ });
1313
+
1314
+ expect(error.denial).toBeUndefined();
1315
+ expect(error.consentUrl).toBeTruthy();
1316
+ });
1317
+
1318
+ it("leaves the denial undefined when no delegation was presented", async () => {
1319
+ const toolHandler = vi.fn();
1320
+
1321
+ const error = await runtime
1322
+ .processToolCall("protected-tool", {}, toolHandler, {
1323
+ id: "test-session",
1324
+ })
1325
+ .then(
1326
+ () => undefined,
1327
+ (thrown: unknown) => thrown
1328
+ );
1329
+
1330
+ expect(error).toBeInstanceOf(DelegationRequiredError);
1331
+ expect((error as DelegationRequiredError).denial).toBeUndefined();
1332
+ expect(mockAccessControlService.verifyDelegation).not.toHaveBeenCalled();
1333
+ });
1334
+ });
1018
1335
  });
@@ -7,14 +7,13 @@
7
7
  import { describe, it, expect, beforeEach, vi } from "vitest";
8
8
  import { MCPIRuntimeBase } from "../../runtime/base";
9
9
  import { ProviderRuntimeConfig } from "../../config";
10
- import { createMockProviders } from "../utils/mock-providers";
10
+ import { createToolProtectionRuntime } from "../utils/tool-protection-runtime";
11
11
  import { DelegationRequiredError } from "../../types/tool-protection";
12
12
  import type { VerifyDelegationAPIResponse } from "@kya-os/contracts/agentshield-api";
13
13
 
14
14
  describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
15
15
  let runtime: MCPIRuntimeBase;
16
16
  let config: ProviderRuntimeConfig;
17
- let mockProviders: ReturnType<typeof createMockProviders>;
18
17
  let mockToolProtectionService: {
19
18
  checkToolProtection: ReturnType<typeof vi.fn>;
20
19
  };
@@ -24,31 +23,8 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
24
23
 
25
24
  beforeEach(async () => {
26
25
  vi.clearAllMocks();
27
- mockProviders = createMockProviders();
28
-
29
- // Create mock tool protection service
30
- mockToolProtectionService = {
31
- checkToolProtection: vi.fn(),
32
- };
33
-
34
- // Create mock access control service
35
- mockAccessControlService = {
36
- verifyDelegation: vi.fn(),
37
- };
38
-
39
- config = {
40
- ...mockProviders,
41
- environment: "development",
42
- session: {
43
- timestampSkewSeconds: 120,
44
- ttlMinutes: 30,
45
- },
46
- toolProtectionService: mockToolProtectionService as any,
47
- };
48
- runtime = new MCPIRuntimeBase(config);
49
- // Inject mock access control service
50
- (runtime as any).accessControlService = mockAccessControlService as any;
51
- await runtime.initialize();
26
+ ({ runtime, config, mockToolProtectionService, mockAccessControlService } =
27
+ await createToolProtectionRuntime());
52
28
  });
53
29
 
54
30
  describe("processToolCall with tool protection", () => {
@@ -139,7 +115,10 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
139
115
  })
140
116
  );
141
117
 
142
- expect(mockHandler).toHaveBeenCalledWith({ arg: "value" });
118
+ expect(mockHandler).toHaveBeenCalledWith(
119
+ { arg: "value" },
120
+ expect.objectContaining({ id: "test-delegation-id" })
121
+ );
143
122
  expect(result).toEqual({ result: "success" });
144
123
  });
145
124
 
@@ -188,7 +167,10 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
188
167
  })
189
168
  );
190
169
 
191
- expect(mockHandler).toHaveBeenCalledWith({ arg: "value" });
170
+ expect(mockHandler).toHaveBeenCalledWith(
171
+ { arg: "value" },
172
+ expect.objectContaining({ id: "test-delegation-id" })
173
+ );
192
174
  expect(result).toEqual({ result: "success" });
193
175
  });
194
176
 
@@ -315,12 +297,14 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
315
297
  delegationToken: "valid-delegation-token",
316
298
  };
317
299
 
318
- await expect(runtime.processToolCall(
319
- "protectedTool",
320
- { arg: "value" },
321
- mockHandler,
322
- sessionWithDelegation
323
- )).rejects.toThrow(DelegationRequiredError);
300
+ await expect(
301
+ runtime.processToolCall(
302
+ "protectedTool",
303
+ { arg: "value" },
304
+ mockHandler,
305
+ sessionWithDelegation
306
+ )
307
+ ).rejects.toThrow(DelegationRequiredError);
324
308
 
325
309
  expect(mockHandler).not.toHaveBeenCalled();
326
310
  });
@@ -410,7 +394,10 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
410
394
  );
411
395
 
412
396
  expect(mockAccessControlService.verifyDelegation).toHaveBeenCalled();
413
- expect(mockHandler).toHaveBeenCalledWith({ arg: "value" });
397
+ expect(mockHandler).toHaveBeenCalledWith(
398
+ { arg: "value" },
399
+ expect.objectContaining({ id: "test-delegation-id" })
400
+ );
414
401
  expect(result).toEqual({ result: "success" });
415
402
  });
416
403
 
@@ -450,7 +437,10 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
450
437
  sessionWithUserA
451
438
  );
452
439
 
453
- expect(mockHandler).toHaveBeenCalledWith({ arg: "value" });
440
+ expect(mockHandler).toHaveBeenCalledWith(
441
+ { arg: "value" },
442
+ expect.objectContaining({ id: "test-delegation-id" })
443
+ );
454
444
  expect(result).toEqual({ result: "success" });
455
445
  });
456
446
 
@@ -491,12 +481,15 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
491
481
  sessionWithoutUserDid
492
482
  );
493
483
 
494
- expect(mockHandler).toHaveBeenCalledWith({ arg: "value" });
484
+ expect(mockHandler).toHaveBeenCalledWith(
485
+ { arg: "value" },
486
+ expect.objectContaining({ id: "test-delegation-id" })
487
+ );
495
488
  expect(result).toEqual({ result: "success" });
496
489
  });
497
490
 
498
491
  it("should include user_did in verification request when session.userDid is set", async () => {
499
- // ✅ SECURITY: Verify user_did is sent to AgentShield for user-scoped verification
492
+ // ✅ SECURITY: Verify user_did is sent to Checkpoint for user-scoped verification
500
493
  // This prevents cross-user delegation leakage (Priority 3 fallback issue)
501
494
  mockToolProtectionService.checkToolProtection.mockResolvedValue({
502
495
  requiresDelegation: true,
@@ -577,7 +570,8 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
577
570
  );
578
571
 
579
572
  // Verify that user_did was NOT included (backward compatibility)
580
- const verifyCall = mockAccessControlService.verifyDelegation.mock.calls[0][0];
573
+ const verifyCall =
574
+ mockAccessControlService.verifyDelegation.mock.calls[0][0];
581
575
  expect(verifyCall.user_did).toBeUndefined();
582
576
  });
583
577
  });
@@ -751,7 +745,9 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
751
745
 
752
746
  it("should label tool execution as a diagnostic", async () => {
753
747
  mockToolProtectionService.checkToolProtection.mockResolvedValue(null);
754
- const diagnostic = vi.spyOn(console, "error").mockImplementation(() => {});
748
+ const diagnostic = vi
749
+ .spyOn(console, "error")
750
+ .mockImplementation(() => {});
755
751
 
756
752
  await runtime.processToolCall(
757
753
  "testTool",
@@ -803,7 +799,9 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
803
799
  });
804
800
 
805
801
  it("should suppress diagnostic tool output in production", async () => {
806
- const diagnostic = vi.spyOn(console, "error").mockImplementation(() => {});
802
+ const diagnostic = vi
803
+ .spyOn(console, "error")
804
+ .mockImplementation(() => {});
807
805
  const productionConfig = {
808
806
  ...config,
809
807
  environment: "production" as const,