@kya-os/mcp-i-runtime 1.3.1 → 1.3.3

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 (122) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/auth/handshake.d.ts +23 -43
  3. package/dist/auth/handshake.d.ts.map +1 -1
  4. package/dist/auth/handshake.js +51 -82
  5. package/dist/auth/handshake.js.map +1 -1
  6. package/dist/auth/index.d.ts +1 -1
  7. package/dist/auth/index.d.ts.map +1 -1
  8. package/dist/auth/index.js.map +1 -1
  9. package/dist/auth/resume-token.d.ts +52 -0
  10. package/dist/auth/resume-token.d.ts.map +1 -0
  11. package/dist/auth/resume-token.js +89 -0
  12. package/dist/auth/resume-token.js.map +1 -0
  13. package/dist/auth/types.d.ts +15 -0
  14. package/dist/auth/types.d.ts.map +1 -1
  15. package/dist/index.d.ts +7 -3
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +25 -3
  18. package/dist/index.js.map +1 -1
  19. package/dist/proof/companion.d.ts +25 -0
  20. package/dist/proof/companion.d.ts.map +1 -0
  21. package/dist/proof/companion.js +14 -0
  22. package/dist/proof/companion.js.map +1 -0
  23. package/dist/proof/generator.d.ts +22 -9
  24. package/dist/proof/generator.d.ts.map +1 -1
  25. package/dist/proof/generator.js +20 -27
  26. package/dist/proof/generator.js.map +1 -1
  27. package/dist/proof/index.d.ts +2 -1
  28. package/dist/proof/index.d.ts.map +1 -1
  29. package/dist/proof/index.js +3 -1
  30. package/dist/proof/index.js.map +1 -1
  31. package/dist/runtime/audit.d.ts.map +1 -1
  32. package/dist/runtime/audit.js +78 -18
  33. package/dist/runtime/audit.js.map +1 -1
  34. package/dist/runtime/base.d.ts +6 -1
  35. package/dist/runtime/base.d.ts.map +1 -1
  36. package/dist/runtime/base.js +65 -17
  37. package/dist/runtime/base.js.map +1 -1
  38. package/dist/runtime/dif-core.d.ts +8 -0
  39. package/dist/runtime/dif-core.d.ts.map +1 -1
  40. package/dist/runtime/dif-core.js +10 -0
  41. package/dist/runtime/dif-core.js.map +1 -1
  42. package/dist/services/access-control.service.d.ts.map +1 -1
  43. package/dist/services/access-control.service.js +12 -5
  44. package/dist/services/access-control.service.js.map +1 -1
  45. package/dist/services/claims-first-guard.d.ts +33 -0
  46. package/dist/services/claims-first-guard.d.ts.map +1 -0
  47. package/dist/services/claims-first-guard.js +77 -0
  48. package/dist/services/claims-first-guard.js.map +1 -0
  49. package/dist/services/holder-keys.d.ts +95 -0
  50. package/dist/services/holder-keys.d.ts.map +1 -0
  51. package/dist/services/holder-keys.js +281 -0
  52. package/dist/services/holder-keys.js.map +1 -0
  53. package/dist/services/holder-read-slots.d.ts +42 -0
  54. package/dist/services/holder-read-slots.d.ts.map +1 -0
  55. package/dist/services/holder-read-slots.js +82 -0
  56. package/dist/services/holder-read-slots.js.map +1 -0
  57. package/dist/services/proof-verifier.d.ts +13 -35
  58. package/dist/services/proof-verifier.d.ts.map +1 -1
  59. package/dist/services/proof-verifier.js +16 -74
  60. package/dist/services/proof-verifier.js.map +1 -1
  61. package/dist/services/request-holder.d.ts +78 -0
  62. package/dist/services/request-holder.d.ts.map +1 -0
  63. package/dist/services/request-holder.js +81 -0
  64. package/dist/services/request-holder.js.map +1 -0
  65. package/dist/services/tool-context-builder.d.ts.map +1 -1
  66. package/dist/services/tool-context-builder.js +16 -4
  67. package/dist/services/tool-context-builder.js.map +1 -1
  68. package/dist/services/tool-protection.service.d.ts +7 -0
  69. package/dist/services/tool-protection.service.d.ts.map +1 -1
  70. package/dist/services/tool-protection.service.js +34 -15
  71. package/dist/services/tool-protection.service.js.map +1 -1
  72. package/dist/types/tool-protection.d.ts +94 -0
  73. package/dist/types/tool-protection.d.ts.map +1 -1
  74. package/dist/types/tool-protection.js +113 -1
  75. package/dist/types/tool-protection.js.map +1 -1
  76. package/eslint.config.js +20 -0
  77. package/package.json +8 -2
  78. package/src/__tests__/runtime/amount-limit-enforcement.test.ts +269 -0
  79. package/src/__tests__/runtime/amount-limit-result.test.ts +61 -0
  80. package/src/__tests__/runtime/audit-contracts-compat.test.ts +20 -5
  81. package/src/__tests__/runtime/audit.test.ts +363 -53
  82. package/src/__tests__/runtime/process-tool-call-security.test.ts +97 -13
  83. package/src/__tests__/runtime/provider-selection.test.ts +4 -6
  84. package/src/__tests__/runtime/route-interception.test.ts +215 -214
  85. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +89 -6
  86. package/src/__tests__/services/tool-protection-amount.test.ts +107 -0
  87. package/src/__tests__/services/tool-protection-failsafe.test.ts +71 -4
  88. package/src/__tests__/utils/tool-protection-runtime.ts +3 -0
  89. package/src/auth/__tests__/verify-or-hints-presented.test.ts +155 -0
  90. package/src/auth/handshake.ts +80 -125
  91. package/src/auth/index.ts +1 -0
  92. package/src/auth/resume-token.ts +134 -0
  93. package/src/auth/types.ts +20 -2
  94. package/src/index.ts +40 -1
  95. package/src/proof/__tests__/proof-generator.test.ts +80 -13
  96. package/src/proof/companion.ts +35 -0
  97. package/src/proof/generator.ts +51 -33
  98. package/src/proof/index.ts +3 -0
  99. package/src/runtime/__tests__/ext-apps-consent.test.ts +87 -2
  100. package/src/runtime/audit.ts +170 -65
  101. package/src/runtime/base.ts +95 -31
  102. package/src/runtime/dif-core.ts +16 -0
  103. package/src/services/__tests__/access-control.service.test.ts +44 -0
  104. package/src/services/__tests__/claims-first-guard.test.ts +93 -0
  105. package/src/services/__tests__/holder-fixtures.ts +135 -0
  106. package/src/services/__tests__/holder-keys.test.ts +257 -0
  107. package/src/services/__tests__/holder-read-slots.test.ts +117 -0
  108. package/src/services/__tests__/holder-reads.test.ts +284 -0
  109. package/src/services/__tests__/proof-verifier.test.ts +286 -195
  110. package/src/services/__tests__/request-holder.test.ts +210 -0
  111. package/src/services/__tests__/tool-context-builder-authtype.test.ts +79 -0
  112. package/src/services/__tests__/tool-context-builder.test.ts +4 -7
  113. package/src/services/__tests__/tool-protection-served-revision.test.ts +102 -0
  114. package/src/services/access-control.service.ts +11 -5
  115. package/src/services/claims-first-guard.ts +89 -0
  116. package/src/services/holder-keys.ts +379 -0
  117. package/src/services/holder-read-slots.ts +85 -0
  118. package/src/services/proof-verifier.ts +18 -79
  119. package/src/services/request-holder.ts +146 -0
  120. package/src/services/tool-context-builder.ts +19 -4
  121. package/src/services/tool-protection.service.ts +62 -19
  122. package/src/types/tool-protection.ts +161 -0
@@ -1,5 +1,6 @@
1
1
  import { describe, expect, it, vi } from "vitest";
2
2
  import type { AuditTrailEventInput } from "@kya-os/mcp/audit";
3
+ import { markToolRefusal } from "@kya-os/contracts/config";
3
4
  import type { ProviderRuntimeConfig } from "../../config";
4
5
  import { MCPIRuntimeBase } from "../../runtime/base";
5
6
  import {
@@ -15,7 +16,9 @@ import { toDelegationDenial } from "../../runtime/delegation-denial";
15
16
  import type { AccessControlApiService } from "../../services/access-control.service";
16
17
  import type { ToolProtectionService } from "../../services/tool-protection.service";
17
18
 
18
- function auditConfig(record: (event: AuditTrailEventInput) => Promise<unknown>): RuntimeAuditConfig {
19
+ function auditConfig(
20
+ record: (event: AuditTrailEventInput) => Promise<unknown>
21
+ ): RuntimeAuditConfig {
19
22
  return {
20
23
  sourceId: "deployment:test:mcp:0",
21
24
  context: {
@@ -36,7 +39,9 @@ function auditConfig(record: (event: AuditTrailEventInput) => Promise<unknown>):
36
39
  };
37
40
  }
38
41
 
39
- function runtimeWithAudit(record: (event: AuditTrailEventInput) => Promise<unknown>): MCPIRuntimeBase {
42
+ function runtimeWithAudit(
43
+ record: (event: AuditTrailEventInput) => Promise<unknown>
44
+ ): MCPIRuntimeBase {
40
45
  const config: ProviderRuntimeConfig = {
41
46
  ...createMockProviders(),
42
47
  environment: "development",
@@ -72,7 +77,7 @@ describe("canonical runtime audit lifecycle", () => {
72
77
  "payments.send",
73
78
  { secret: "never-audited" },
74
79
  handler,
75
- { id: "raw-session", nonce: "nonce", audience: "client" },
80
+ { id: "raw-session", nonce: "nonce", audience: "client" }
76
81
  );
77
82
 
78
83
  expect(result).toMatchObject({
@@ -95,7 +100,9 @@ describe("canonical runtime audit lifecycle", () => {
95
100
  "invocation-1:started",
96
101
  "invocation-1:completed",
97
102
  ]);
98
- expect(events.every((event) => event.correlationId === "correlation-1")).toBe(true);
103
+ expect(
104
+ events.every((event) => event.correlationId === "correlation-1")
105
+ ).toBe(true);
99
106
  expect(JSON.stringify(events)).not.toContain("never-audited");
100
107
  expect(JSON.stringify(events)).not.toContain("raw-session");
101
108
  });
@@ -110,12 +117,13 @@ describe("canonical runtime audit lifecycle", () => {
110
117
  throw new Error("side effect failed");
111
118
  });
112
119
 
113
- await expect(runtime.processToolCall(
114
- "payments.send",
115
- {},
116
- handler,
117
- { id: "session", nonce: "nonce", audience: "client" },
118
- )).rejects.toThrow("side effect failed");
120
+ await expect(
121
+ runtime.processToolCall("payments.send", {}, handler, {
122
+ id: "session",
123
+ nonce: "nonce",
124
+ audience: "client",
125
+ })
126
+ ).rejects.toThrow("side effect failed");
119
127
 
120
128
  expect(handler).toHaveBeenCalledTimes(1);
121
129
  expect(events.map((event) => event.eventType)).toEqual([
@@ -142,7 +150,9 @@ describe("canonical runtime audit lifecycle", () => {
142
150
  auditTrail: config,
143
151
  });
144
152
 
145
- await runtime.processToolCall("payments.send", {}, async () => ({ ok: true }));
153
+ await runtime.processToolCall("payments.send", {}, async () => ({
154
+ ok: true,
155
+ }));
146
156
 
147
157
  expect(events.map((event) => event.eventId)).toHaveLength(2);
148
158
  expect(events[0].eventId).not.toBe(events[1].eventId);
@@ -158,11 +168,13 @@ describe("canonical runtime audit lifecycle", () => {
158
168
  });
159
169
  const handler = vi.fn(async () => ({ ok: true }));
160
170
 
161
- await expect(runtime.processToolCall("dangerous", {}, handler, {
162
- id: "session",
163
- nonce: "nonce",
164
- audience: "client",
165
- })).rejects.toThrow("recorder unavailable");
171
+ await expect(
172
+ runtime.processToolCall("dangerous", {}, handler, {
173
+ id: "session",
174
+ nonce: "nonce",
175
+ audience: "client",
176
+ })
177
+ ).rejects.toThrow("recorder unavailable");
166
178
  expect(handler).not.toHaveBeenCalled();
167
179
  });
168
180
 
@@ -173,10 +185,15 @@ describe("canonical runtime audit lifecycle", () => {
173
185
  return pendingResult(event, String(events.length));
174
186
  });
175
187
 
176
- await runtime.processToolCall("protected", {}, async () => ({
177
- structuredContent: { type: "consent_required" },
178
- _meta: { ui: { resourceUri: "ui://kya-os-consent/authorize" } },
179
- }), { id: "session", nonce: "nonce", audience: "client" });
188
+ await runtime.processToolCall(
189
+ "protected",
190
+ {},
191
+ async () => ({
192
+ structuredContent: { type: "consent_required" },
193
+ _meta: { ui: { resourceUri: "ui://kya-os-consent/authorize" } },
194
+ }),
195
+ { id: "session", nonce: "nonce", audience: "client" }
196
+ );
180
197
 
181
198
  expect(events.map((event) => event.eventType)).toEqual([
182
199
  "tool.call.started",
@@ -235,8 +252,10 @@ describe("canonical runtime audit lifecycle", () => {
235
252
  });
236
253
  const handler = vi.fn(async () => "side-effect-complete");
237
254
 
238
- await expect(runtime.processToolCall("payments.send", {}, handler)).rejects.toThrow(
239
- "Required terminal audit delivery failed after tool execution",
255
+ await expect(
256
+ runtime.processToolCall("payments.send", {}, handler)
257
+ ).rejects.toThrow(
258
+ "Required terminal audit delivery failed after tool execution"
240
259
  );
241
260
  expect(handler).toHaveBeenCalledTimes(1);
242
261
  expect(events.map((event) => event.eventType)).toEqual([
@@ -246,6 +265,113 @@ describe("canonical runtime audit lifecycle", () => {
246
265
  });
247
266
  });
248
267
 
268
+ describe("tool refusals in the audit ledger", () => {
269
+ async function terminalEventFor(
270
+ result: Record<string, unknown>
271
+ ): Promise<AuditTrailEventInput> {
272
+ const events: AuditTrailEventInput[] = [];
273
+ const runtime = runtimeWithAudit(async (event) => {
274
+ events.push(event);
275
+ return pendingResult(event, String(events.length));
276
+ });
277
+ await runtime.processToolCall("place_order", {}, async () => result, {
278
+ id: "session",
279
+ nonce: "nonce",
280
+ audience: "client",
281
+ });
282
+ expect(events).toHaveLength(2);
283
+ expect(events[0]!.eventType).toBe("tool.call.started");
284
+ return events[1]!;
285
+ }
286
+
287
+ it.each(["SPEND_CAP_EXCEEDED", "PRODUCT_OUT_OF_SCOPE"])(
288
+ "records a marked %s refusal as tool.call.denied with its code",
289
+ async (code) => {
290
+ const terminal = await terminalEventFor({
291
+ isError: true,
292
+ content: [
293
+ { type: "text", text: "Order refused. Nothing was ordered." },
294
+ ],
295
+ _meta: { ...markToolRefusal(code) },
296
+ });
297
+
298
+ expect(terminal).toMatchObject({
299
+ eventType: "tool.call.denied",
300
+ outcome: "denied",
301
+ reason: { code },
302
+ details: { phase: "denied" },
303
+ });
304
+ expect(JSON.stringify(terminal)).not.toContain("Nothing was ordered");
305
+ }
306
+ );
307
+
308
+ it("records a marked refusal as denied even without isError, like Checkpoint and activity do", async () => {
309
+ const terminal = await terminalEventFor({
310
+ content: [{ type: "text", text: "Refused." }],
311
+ _meta: { ...markToolRefusal("SPEND_CAP_EXCEEDED") },
312
+ });
313
+
314
+ expect(terminal).toMatchObject({
315
+ eventType: "tool.call.denied",
316
+ reason: { code: "SPEND_CAP_EXCEEDED" },
317
+ });
318
+ });
319
+
320
+ it("keeps an inline consent challenge challenged even when it also carries a marker", async () => {
321
+ const terminal = await terminalEventFor({
322
+ structuredContent: { type: "consent_required" },
323
+ _meta: { ...markToolRefusal("SPEND_CAP_EXCEEDED") },
324
+ });
325
+
326
+ expect(terminal).toMatchObject({
327
+ eventType: "tool.call.challenged",
328
+ outcome: "challenged",
329
+ reason: { code: "AUTHORIZATION_REQUIRED" },
330
+ });
331
+ });
332
+
333
+ it("keeps an unmarked isError result a failed tool error, even when its text looks like a code", async () => {
334
+ const terminal = await terminalEventFor({
335
+ isError: true,
336
+ content: [{ type: "text", text: "SPEND_CAP_EXCEEDED" }],
337
+ structuredContent: { ok: false, code: "SPEND_CAP_EXCEEDED" },
338
+ });
339
+
340
+ expect(terminal).toMatchObject({
341
+ eventType: "tool.call.failed",
342
+ outcome: "failed",
343
+ reason: { code: "HANDLER_ERROR_RESULT" },
344
+ });
345
+ });
346
+
347
+ it("keeps a malformed marker a failed tool error", async () => {
348
+ const terminal = await terminalEventFor({
349
+ isError: true,
350
+ content: [],
351
+ _meta: {
352
+ "ai.kya-os/refusal": { code: "over the cap: alice@example.com" },
353
+ },
354
+ });
355
+
356
+ expect(terminal).toMatchObject({
357
+ eventType: "tool.call.failed",
358
+ reason: { code: "HANDLER_ERROR_RESULT" },
359
+ });
360
+ expect(JSON.stringify(terminal)).not.toContain("alice@example.com");
361
+ });
362
+
363
+ it("keeps an allowed order completed", async () => {
364
+ const terminal = await terminalEventFor({
365
+ content: [{ type: "text", text: "Order placed." }],
366
+ });
367
+
368
+ expect(terminal).toMatchObject({
369
+ eventType: "tool.call.completed",
370
+ outcome: "succeeded",
371
+ });
372
+ });
373
+ });
374
+
249
375
  describe("verifier denials in the audit ledger", () => {
250
376
  async function protectedRuntimeWithAudit(
251
377
  record: (event: AuditTrailEventInput) => Promise<unknown>,
@@ -266,13 +392,14 @@ describe("verifier denials in the audit ledger", () => {
266
392
  auditTrail: auditConfig(record),
267
393
  toolProtectionService,
268
394
  });
269
- (runtime as unknown as { accessControlService: AccessControlApiService })
270
- .accessControlService = accessControlService;
395
+ (
396
+ runtime as unknown as { accessControlService: AccessControlApiService }
397
+ ).accessControlService = accessControlService;
271
398
  await runtime.initialize();
272
399
  return runtime;
273
400
  }
274
401
 
275
- it("records a revoked grant as tool.call.denied with DELEGATION_REVOKED", async () => {
402
+ it("records a revoked grant as tool.call.challenged with DELEGATION_REVOKED", async () => {
276
403
  const events: AuditTrailEventInput[] = [];
277
404
  const runtime = await protectedRuntimeWithAudit(
278
405
  async (event) => {
@@ -298,12 +425,12 @@ describe("verifier denials in the audit ledger", () => {
298
425
  expect(handler).not.toHaveBeenCalled();
299
426
  expect(events.map((event) => event.eventType)).toEqual([
300
427
  "tool.call.started",
301
- "tool.call.denied",
428
+ "tool.call.challenged",
302
429
  ]);
303
430
  expect(events[1]).toMatchObject({
304
- outcome: "denied",
431
+ outcome: "challenged",
305
432
  reason: { code: "DELEGATION_REVOKED" },
306
- details: { phase: "denied" },
433
+ details: { phase: "challenged" },
307
434
  });
308
435
  expect(JSON.stringify(events)).not.toContain("secret");
309
436
  });
@@ -335,10 +462,10 @@ describe("verifier denials in the audit ledger", () => {
335
462
  expect(handler).not.toHaveBeenCalled();
336
463
  expect(events.map((event) => event.eventType)).toEqual([
337
464
  "tool.call.started",
338
- "tool.call.denied",
465
+ "tool.call.challenged",
339
466
  ]);
340
467
  expect(events[1]).toMatchObject({
341
- outcome: "denied",
468
+ outcome: "challenged",
342
469
  reason: { code: "DELEGATION_REVOKED" },
343
470
  });
344
471
  expect(JSON.stringify(events)).not.toContain("NATIVE_BINDING_MISMATCH");
@@ -372,7 +499,7 @@ describe("verifier denials in the audit ledger", () => {
372
499
  });
373
500
  });
374
501
 
375
- it("maps a denial to the denied phase", () => {
502
+ it("maps a refused grant a new grant could fix to the challenged phase", () => {
376
503
  const error = new DelegationRequiredError(
377
504
  "orders.place",
378
505
  ["orders:place"],
@@ -383,8 +510,8 @@ describe("verifier denials in the audit ledger", () => {
383
510
  );
384
511
 
385
512
  expect(terminalForToolError(error)).toEqual({
386
- phase: "denied",
387
- outcome: "denied",
513
+ phase: "challenged",
514
+ outcome: "challenged",
388
515
  reasonCode: "AGENT_MISMATCH",
389
516
  });
390
517
  });
@@ -442,22 +569,202 @@ describe("HMAC audit references", () => {
442
569
  expect(serialized).not.toContain("request-secret");
443
570
  expect(serialized).not.toContain("flow-secret");
444
571
  });
572
+
573
+ describe("actor attribution", () => {
574
+ const PROVED_HOLDER = "did:key:zProvedHolder";
575
+
576
+ function hmacFactory() {
577
+ return createHmacRuntimeAuditContextFactory({
578
+ secret: "0123456789abcdef0123456789abcdef",
579
+ keyId: "audit-ref-2026-01",
580
+ randomUUID: () => "fallback-invocation",
581
+ });
582
+ }
583
+
584
+ // Captured from the factory before the proved holder was considered, so
585
+ // a session without one must keep producing exactly these contexts.
586
+ const BASELINE_REFS = {
587
+ invocationId:
588
+ "invocation:3d83efbffba8e7e6d16375f1bca7769a995ec6d534250b35d1674e22e326600d",
589
+ correlationId:
590
+ "correlation:f91d71e462c8ce56c29ad3f285063e76df2417a55678720d62f33c5e52bb846c",
591
+ session: {
592
+ ref: {
593
+ kind: "keyed_commitment",
594
+ value:
595
+ "sha256:170dd72f62ad13ec4a1a3535afaa1b09f0ba8d8d00c9fd874455c5da67713fe0",
596
+ keyId: "audit-ref-2026-01",
597
+ },
598
+ },
599
+ };
600
+
601
+ function callWith(session: Record<string, unknown>) {
602
+ return {
603
+ toolName: "payments.send",
604
+ args: {},
605
+ session: {
606
+ id: "session-secret",
607
+ auditInvocationId: "request-secret",
608
+ ...session,
609
+ },
610
+ };
611
+ }
612
+
613
+ it("attributes the call to the proved holder over caller-asserted DIDs", async () => {
614
+ const context = await hmacFactory().create(
615
+ callWith({
616
+ verifiedInvokerDid: PROVED_HOLDER,
617
+ clientDid: "did:key:zClient",
618
+ userDid: "did:key:zUser",
619
+ })
620
+ );
621
+
622
+ expect(context.actor).toEqual({ kind: "public_did", did: PROVED_HOLDER });
623
+ expect(JSON.stringify(context)).not.toContain("zClient");
624
+ expect(JSON.stringify(context)).not.toContain("zUser");
625
+ });
626
+
627
+ it("without a proved holder, keeps today's context with clientDid as the actor", async () => {
628
+ const context = await hmacFactory().create(
629
+ callWith({ clientDid: "did:key:zClient", userDid: "did:key:zUser" })
630
+ );
631
+
632
+ expect(context).toEqual({
633
+ ...BASELINE_REFS,
634
+ actor: { kind: "public_did", did: "did:key:zClient" },
635
+ });
636
+ });
637
+
638
+ it("without a proved holder or clientDid, keeps today's context with userDid as the actor", async () => {
639
+ const context = await hmacFactory().create(
640
+ callWith({ userDid: "did:key:zUser" })
641
+ );
642
+
643
+ expect(context).toEqual({
644
+ ...BASELINE_REFS,
645
+ actor: { kind: "public_did", did: "did:key:zUser" },
646
+ });
647
+ });
648
+
649
+ it("never takes the actor from a caller-asserted agentDid", async () => {
650
+ const context = await hmacFactory().create(
651
+ callWith({ agentDid: "did:key:zAsserted" })
652
+ );
653
+
654
+ expect(context).toEqual(BASELINE_REFS);
655
+ expect(context).not.toHaveProperty("actor");
656
+ });
657
+
658
+ it("keeps the did: prefix check for the proved holder", async () => {
659
+ const context = await hmacFactory().create(
660
+ callWith({
661
+ verifiedInvokerDid: "not-a-did",
662
+ clientDid: "did:key:zClient",
663
+ })
664
+ );
665
+
666
+ // A malformed holder never falls back to the caller-asserted clientDid.
667
+ expect(context).not.toHaveProperty("actor");
668
+ });
669
+
670
+ it("ignores a blank proved holder like any other blank reference", async () => {
671
+ const context = await hmacFactory().create(
672
+ callWith({ verifiedInvokerDid: " ", clientDid: "did:key:zClient" })
673
+ );
674
+
675
+ expect(context.actor).toEqual({
676
+ kind: "public_did",
677
+ did: "did:key:zClient",
678
+ });
679
+ });
680
+
681
+ it("records the presenter, not the grant's agent, when a holder presents another agent's grant", async () => {
682
+ const grantAgent = "did:key:zGrantAgentA";
683
+ const presenter = "did:key:zPresenterB";
684
+ const events: AuditTrailEventInput[] = [];
685
+ const verifyDelegation = vi.fn().mockResolvedValue({
686
+ data: {
687
+ valid: false,
688
+ error: {
689
+ code: "agent_mismatch",
690
+ message: "grant belongs to another agent",
691
+ },
692
+ },
693
+ });
694
+ const runtime = new MCPIRuntimeBase({
695
+ ...createMockProviders(),
696
+ environment: "production",
697
+ auditTrail: {
698
+ ...auditConfig(async (event) => {
699
+ events.push(event);
700
+ return pendingResult(event, String(events.length));
701
+ }),
702
+ context: hmacFactory(),
703
+ },
704
+ toolProtectionService: {
705
+ checkToolProtection: vi.fn().mockResolvedValue({
706
+ requiresDelegation: true,
707
+ requiredScopes: ["orders:place"],
708
+ }),
709
+ } as unknown as ToolProtectionService,
710
+ });
711
+ (
712
+ runtime as unknown as { accessControlService: AccessControlApiService }
713
+ ).accessControlService = {
714
+ verifyDelegation,
715
+ } as unknown as AccessControlApiService;
716
+ await runtime.initialize();
717
+ const handler = vi.fn(async () => ({ ok: true }));
718
+
719
+ await expect(
720
+ runtime.processToolCall("orders.place", {}, handler, {
721
+ id: "session",
722
+ nonce: "nonce",
723
+ audience: "client",
724
+ delegationToken: "grant-for-agent-a",
725
+ verifiedInvokerDid: presenter,
726
+ // What a caller can assert on its own; none of it is proved.
727
+ clientDid: grantAgent,
728
+ agentDid: grantAgent,
729
+ })
730
+ ).rejects.toThrow(DelegationRequiredError);
731
+
732
+ expect(handler).not.toHaveBeenCalled();
733
+ expect(verifyDelegation.mock.calls[0][0]).toMatchObject({
734
+ agent_did: presenter,
735
+ });
736
+ expect(events.map((event) => event.eventType)).toEqual([
737
+ "tool.call.started",
738
+ "tool.call.challenged",
739
+ ]);
740
+ expect(events[1]).toMatchObject({
741
+ outcome: "challenged",
742
+ reason: { code: "AGENT_MISMATCH" },
743
+ actor: { kind: "public_did", did: presenter },
744
+ });
745
+ expect(events[0].actor).toEqual({ kind: "public_did", did: presenter });
746
+ expect(JSON.stringify(events)).not.toContain(grantAgent);
747
+ });
748
+ });
445
749
  });
446
750
 
447
751
  describe("canonical consent and delegation events", () => {
448
752
  it("records consent without copying request payload fields", async () => {
449
753
  const events: AuditTrailEventInput[] = [];
450
- await recordRuntimeConsentAudit(auditConfig(async (event) => {
451
- events.push(event);
452
- return pendingResult(event);
453
- }), {
454
- phase: "credential_failed",
455
- outcome: "failed",
456
- sessionId: "raw-session-secret",
457
- userDid: "did:key:zUser",
458
- reasonCode: "CREDENTIAL_AUTH_FAILED",
459
- consentRef: "consent-reference",
460
- });
754
+ await recordRuntimeConsentAudit(
755
+ auditConfig(async (event) => {
756
+ events.push(event);
757
+ return pendingResult(event);
758
+ }),
759
+ {
760
+ phase: "credential_failed",
761
+ outcome: "failed",
762
+ sessionId: "raw-session-secret",
763
+ userDid: "did:key:zUser",
764
+ reasonCode: "CREDENTIAL_AUTH_FAILED",
765
+ consentRef: "consent-reference",
766
+ }
767
+ );
461
768
 
462
769
  expect(events).toHaveLength(1);
463
770
  expect(events[0]).toMatchObject({
@@ -476,15 +783,18 @@ describe("canonical consent and delegation events", () => {
476
783
 
477
784
  it("records delegation issuance as a separate event family", async () => {
478
785
  const events: AuditTrailEventInput[] = [];
479
- await recordRuntimeDelegationAudit(auditConfig(async (event) => {
480
- events.push(event);
481
- return pendingResult(event);
482
- }), {
483
- phase: "issued",
484
- outcome: "succeeded",
485
- sessionId: "session-secret",
486
- delegationRef: "delegation-123",
487
- });
786
+ await recordRuntimeDelegationAudit(
787
+ auditConfig(async (event) => {
788
+ events.push(event);
789
+ return pendingResult(event);
790
+ }),
791
+ {
792
+ phase: "issued",
793
+ outcome: "succeeded",
794
+ sessionId: "session-secret",
795
+ delegationRef: "delegation-123",
796
+ }
797
+ );
488
798
 
489
799
  expect(events[0]).toMatchObject({
490
800
  eventType: "delegation.issued",
@@ -90,6 +90,9 @@ describe("processToolCall Security", () => {
90
90
  ttlMinutes: 30,
91
91
  },
92
92
  toolProtectionService: mockToolProtectionService,
93
+ delegation: {
94
+ authorization: { authorizationUrl: "https://auth.example.com/consent" },
95
+ } as any,
93
96
  };
94
97
 
95
98
  runtime = new MCPIRuntimeBase(config);
@@ -292,6 +295,87 @@ describe("processToolCall Security", () => {
292
295
  expect(toolHandler).toHaveBeenCalled();
293
296
  expect(result).toEqual({ result: "success" });
294
297
  });
298
+
299
+ it("logs a refused identifier's shape, never the email or customer id", async () => {
300
+ const consoleSpy = vi
301
+ .spyOn(console, "error")
302
+ .mockImplementation(() => {});
303
+ mockAccessControlService.verifyDelegation = vi.fn().mockResolvedValue({
304
+ data: {
305
+ valid: true,
306
+ delegation_id: "test-delegation",
307
+ credential: {
308
+ scopes: ["tool:execute"],
309
+ user_identifier: "shopper@merchant.test",
310
+ user_id: "cust-1001",
311
+ },
312
+ },
313
+ });
314
+ const session = {
315
+ id: "test-session",
316
+ userDid: "did:key:zSessionUser123",
317
+ agentDid: "did:key:zmock123",
318
+ delegationToken: "valid-token",
319
+ };
320
+
321
+ await expect(
322
+ runtime.processToolCall(
323
+ "protected-tool",
324
+ { arg: "value" },
325
+ vi.fn(),
326
+ session
327
+ )
328
+ ).rejects.toThrow(DelegationRequiredError);
329
+
330
+ expect(consoleSpy).toHaveBeenCalledWith(
331
+ expect.stringContaining("User identifier validation FAILED"),
332
+ expect.objectContaining({
333
+ delegationIdentifierFormat: "email_or_other",
334
+ hasDelegationUserId: true,
335
+ })
336
+ );
337
+ const logged = JSON.stringify(consoleSpy.mock.calls);
338
+ expect(logged).not.toContain("shopper@");
339
+ expect(logged).not.toContain("cust-1001");
340
+ consoleSpy.mockRestore();
341
+ });
342
+
343
+ it("logs an identifier without a session user by its shape, never its value", async () => {
344
+ const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
345
+ mockAccessControlService.verifyDelegation = vi.fn().mockResolvedValue({
346
+ data: {
347
+ valid: true,
348
+ delegation_id: "test-delegation",
349
+ credential: {
350
+ scopes: ["tool:execute"],
351
+ user_identifier: "shopper@merchant.test",
352
+ },
353
+ },
354
+ });
355
+ const session = {
356
+ id: "test-session",
357
+ agentDid: "did:key:zmock123",
358
+ delegationToken: "valid-token",
359
+ };
360
+
361
+ await runtime.processToolCall(
362
+ "protected-tool",
363
+ { arg: "value" },
364
+ vi.fn().mockResolvedValue({ result: "success" }),
365
+ session
366
+ );
367
+
368
+ expect(consoleSpy).toHaveBeenCalledWith(
369
+ expect.stringContaining(
370
+ "Delegation has user_identifier but session missing userDid"
371
+ ),
372
+ expect.objectContaining({
373
+ delegationIdentifierFormat: "email_or_other",
374
+ })
375
+ );
376
+ expect(JSON.stringify(consoleSpy.mock.calls)).not.toContain("shopper@");
377
+ consoleSpy.mockRestore();
378
+ });
295
379
  });
296
380
 
297
381
  describe("Missing Delegation Handling", () => {
@@ -339,7 +423,7 @@ describe("processToolCall Security", () => {
339
423
  const delegationError = error as DelegationRequiredError;
340
424
  expect(delegationError.consentUrl).toBeDefined();
341
425
  expect(delegationError.consentUrl).toContain(
342
- "kya.vouched.id/bouncer/consent"
426
+ "https://auth.example.com/consent?"
343
427
  );
344
428
  expect(delegationError.resumeToken).toBeDefined();
345
429
  expect(delegationError.resumeToken).toMatch(/^resume_/);
@@ -526,12 +610,14 @@ describe("processToolCall Security", () => {
526
610
 
527
611
  const toolHandler = vi.fn().mockResolvedValue({ result: "success" });
528
612
 
529
- await expect(runtime.processToolCall(
530
- "protected-tool",
531
- { arg: "value" },
532
- toolHandler,
533
- session
534
- )).rejects.toThrow(DelegationRequiredError);
613
+ await expect(
614
+ runtime.processToolCall(
615
+ "protected-tool",
616
+ { arg: "value" },
617
+ toolHandler,
618
+ session
619
+ )
620
+ ).rejects.toThrow(DelegationRequiredError);
535
621
 
536
622
  expect(toolHandler).not.toHaveBeenCalled();
537
623
  expect(consoleSpy).toHaveBeenCalledWith(
@@ -1198,12 +1284,10 @@ describe("processToolCall Security", () => {
1198
1284
  const toolHandler = vi.fn().mockResolvedValue({ result: "success" });
1199
1285
 
1200
1286
  const error = await runtime
1201
- .processToolCall(
1202
- "protected-tool",
1203
- { arg: "value" },
1204
- toolHandler,
1205
- { ...session, ...sessionOverrides }
1206
- )
1287
+ .processToolCall("protected-tool", { arg: "value" }, toolHandler, {
1288
+ ...session,
1289
+ ...sessionOverrides,
1290
+ })
1207
1291
  .then(
1208
1292
  () => undefined,
1209
1293
  (thrown: unknown) => thrown