@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,129 @@
1
+ /**
2
+ * Tests for toVerifiedDelegation: the pure mapping from a verify response to
3
+ * the VerifiedDelegation that protected tool handlers receive.
4
+ */
5
+
6
+ import { describe, it, expect } from "vitest";
7
+ import type { VerifyDelegationResponse } from "@kya-os/contracts/agentshield-api";
8
+ import { toVerifiedDelegation } from "../../runtime/verified-delegation";
9
+
10
+ const NOT_AFTER_SECONDS = 1_900_000_000;
11
+
12
+ function checkpointVerifyResponse(
13
+ overrides: Partial<VerifyDelegationResponse> = {}
14
+ ): VerifyDelegationResponse {
15
+ return {
16
+ valid: true,
17
+ delegation_id: "0d6f4c1e-2b1a-4d8e-9a57-5b2f1c7e9d10",
18
+ credential: {
19
+ agent_did: "did:web:knowthat.ai:agents:kya-commerce",
20
+ user_did: "did:key:zUser",
21
+ scopes: ["place_order:execute"],
22
+ constraints: {
23
+ not_before: 0,
24
+ not_after: NOT_AFTER_SECONDS,
25
+ crisp: {
26
+ units: "CHF",
27
+ max_amount: "50.00",
28
+ product_class: ["https://id.gs1.org/01/09506000134352"],
29
+ },
30
+ },
31
+ issued_at: 1_800_000_000,
32
+ created_at: 1_800_000_000,
33
+ authorization: { type: "none" },
34
+ },
35
+ ...overrides,
36
+ };
37
+ }
38
+
39
+ describe("toVerifiedDelegation", () => {
40
+ it("maps a valid verify response, including nested crisp constraints", () => {
41
+ const verified = toVerifiedDelegation(checkpointVerifyResponse());
42
+
43
+ expect(verified).toEqual({
44
+ id: "0d6f4c1e-2b1a-4d8e-9a57-5b2f1c7e9d10",
45
+ agentDid: "did:web:knowthat.ai:agents:kya-commerce",
46
+ userDid: "did:key:zUser",
47
+ scopes: ["place_order:execute"],
48
+ constraints: {
49
+ not_before: 0,
50
+ not_after: NOT_AFTER_SECONDS,
51
+ crisp: {
52
+ units: "CHF",
53
+ max_amount: "50.00",
54
+ product_class: ["https://id.gs1.org/01/09506000134352"],
55
+ },
56
+ },
57
+ authorizationType: "none",
58
+ expiresAt: NOT_AFTER_SECONDS,
59
+ });
60
+ });
61
+
62
+ it("returns undefined when the verifier did not accept the delegation", () => {
63
+ expect(
64
+ toVerifiedDelegation(checkpointVerifyResponse({ valid: false }))
65
+ ).toBeUndefined();
66
+ });
67
+
68
+ it("returns undefined when the verifier returned no credential (KV and memory verifiers)", () => {
69
+ expect(
70
+ toVerifiedDelegation({ valid: true, delegation_id: "kv-delegation" })
71
+ ).toBeUndefined();
72
+ });
73
+
74
+ it.each([
75
+ ["zero", 0],
76
+ ["negative", -1],
77
+ ["a string", "1900000000"],
78
+ ])("sets no expiresAt when not_after is %s", (_label, notAfter) => {
79
+ const response = checkpointVerifyResponse();
80
+ response.credential!.constraints = { not_after: notAfter };
81
+
82
+ const verified = toVerifiedDelegation(response);
83
+
84
+ expect(verified).toBeDefined();
85
+ expect(verified).not.toHaveProperty("expiresAt");
86
+ });
87
+
88
+ it("sets no expiresAt and no constraints when the credential has none", () => {
89
+ const response = checkpointVerifyResponse();
90
+ delete response.credential!.constraints;
91
+
92
+ const verified = toVerifiedDelegation(response);
93
+
94
+ expect(verified).not.toHaveProperty("expiresAt");
95
+ expect(verified).not.toHaveProperty("constraints");
96
+ });
97
+
98
+ it("omits id when the response carries no delegation_id", () => {
99
+ const verified = toVerifiedDelegation(
100
+ checkpointVerifyResponse({ delegation_id: undefined })
101
+ );
102
+
103
+ expect(verified).not.toHaveProperty("id");
104
+ expect(verified?.scopes).toEqual(["place_order:execute"]);
105
+ });
106
+
107
+ it("copies scopes and constraints, so mutating the output leaves the input unchanged", () => {
108
+ const response = checkpointVerifyResponse();
109
+ const verified = toVerifiedDelegation(response)!;
110
+
111
+ verified.scopes.push("admin:everything");
112
+ (verified.constraints!.crisp as Record<string, unknown>).max_amount =
113
+ "999999.00";
114
+
115
+ expect(response.credential!.scopes).toEqual(["place_order:execute"]);
116
+ expect(
117
+ (response.credential!.constraints!.crisp as Record<string, unknown>)
118
+ .max_amount
119
+ ).toBe("50.00");
120
+ });
121
+
122
+ it("treats a non-array scopes field as no scopes rather than trusting it", () => {
123
+ const response = checkpointVerifyResponse();
124
+ (response.credential as unknown as Record<string, unknown>).scopes =
125
+ "place_order:execute";
126
+
127
+ expect(toVerifiedDelegation(response)?.scopes).toEqual([]);
128
+ });
129
+ });
@@ -1,7 +1,7 @@
1
1
  /**
2
- * AgentShield Integration Tests
2
+ * Checkpoint Integration Tests
3
3
  *
4
- * Tests for AgentShield API integration including:
4
+ * Tests for Checkpoint API integration including:
5
5
  * - Tool protection config fetching
6
6
  * - API authentication
7
7
  * - Error handling
@@ -47,7 +47,7 @@ function mockFetchWithTools(tools: Record<string, Partial<ToolProtection>>) {
47
47
  });
48
48
  }
49
49
 
50
- describe("AgentShield Integration", () => {
50
+ describe("Checkpoint Integration", () => {
51
51
  let service: ToolProtectionService;
52
52
  let cache: InMemoryToolProtectionCache;
53
53
  let config: ToolProtectionServiceConfig;
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Tests the MCP-I provider-registry model where:
5
5
  * - Client secrets are NOT sent via the API response
6
- * - Agents receive metadata.clientSecretName from AgentShield
6
+ * - Agents receive metadata.clientSecretName from Checkpoint
7
7
  * - Secrets are resolved at runtime from secure storage
8
8
  *
9
9
  * @package @kya-os/mcp-i-core
@@ -416,7 +416,7 @@ describe("ProviderResolver - Edge Cases", () => {
416
416
  await resolver.resolveProvider(toolProtection, "test-project");
417
417
  } catch (error) {
418
418
  const message = (error as Error).message;
419
- expect(message).toContain("AgentShield dashboard");
419
+ expect(message).toContain("Checkpoint dashboard");
420
420
  expect(message).toContain("Configure");
421
421
  }
422
422
  });
@@ -526,7 +526,7 @@ describe("ProviderResolver - Edge Cases", () => {
526
526
  };
527
527
 
528
528
  // Registry has providers but configuredProvider is null
529
- // This simulates AgentShield returning all providers but none configured
529
+ // This simulates Checkpoint returning all providers but none configured
530
530
  (mockRegistry.hasProvider as any).mockReturnValue(false);
531
531
  (mockRegistry.getConfiguredProvider as any).mockReturnValue(null);
532
532
  (mockRegistry.getAllProviders as any).mockReturnValue([
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Tool Protection Service Tests
3
3
  *
4
- * Tests for fetching and caching tool protection configurations from AgentShield API
4
+ * Tests for fetching and caching tool protection configurations from Checkpoint API
5
5
  */
6
6
 
7
7
  import { describe, test, expect, beforeEach, vi, afterEach } from "vitest";
@@ -0,0 +1,25 @@
1
+ import { vi } from "vitest";
2
+ import { MCPIRuntimeBase } from "../../runtime/base";
3
+ import type { ProviderRuntimeConfig } from "../../config";
4
+ import { createMockProviders } from "./mock-providers";
5
+
6
+ /** Shared initialized runtime for delegation enforcement tests. */
7
+ export async function createToolProtectionRuntime() {
8
+ const mockToolProtectionService = { checkToolProtection: vi.fn() };
9
+ const mockAccessControlService = { verifyDelegation: vi.fn() };
10
+ const config: ProviderRuntimeConfig = {
11
+ ...createMockProviders(),
12
+ environment: "development",
13
+ session: { timestampSkewSeconds: 120, ttlMinutes: 30 },
14
+ toolProtectionService: mockToolProtectionService as any,
15
+ };
16
+ const runtime = new MCPIRuntimeBase(config);
17
+ (runtime as any).accessControlService = mockAccessControlService;
18
+ await runtime.initialize();
19
+ return {
20
+ runtime,
21
+ config,
22
+ mockToolProtectionService,
23
+ mockAccessControlService,
24
+ };
25
+ }
package/src/auth/types.ts CHANGED
@@ -19,7 +19,7 @@ export interface VerifyDelegationResult {
19
19
  /** The delegation record (if found) */
20
20
  delegation?: DelegationRecord;
21
21
 
22
- /** Credential from AgentShield API (includes authorization method) */
22
+ /** Credential from Checkpoint API (includes authorization method) */
23
23
  credential?: {
24
24
  agent_did: string;
25
25
  user_did: string;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Remote Configuration Fetching
3
3
  *
4
- * Service for fetching configuration from remote APIs (AgentShield dashboard)
4
+ * Service for fetching configuration from remote APIs (Checkpoint dashboard)
5
5
  * with caching support for performance optimization.
6
6
  *
7
7
  * C2 (#2916) classification: **product-layer, no DIF equivalent.** These are
@@ -85,9 +85,9 @@ export interface RemoteConfigCache {
85
85
  }
86
86
 
87
87
  /**
88
- * Fetch configuration from remote API (AgentShield dashboard)
88
+ * Fetch configuration from remote API (Checkpoint dashboard)
89
89
  *
90
- * Attempts to fetch configuration from the AgentShield API with caching support.
90
+ * Attempts to fetch configuration from the Checkpoint API with caching support.
91
91
  * Falls back gracefully if remote fetch fails.
92
92
  *
93
93
  * @param options - Remote config options
@@ -136,7 +136,7 @@ export async function fetchRemoteConfig(
136
136
  console.error(
137
137
  '[RemoteConfig] projectId is required for user-scoped delegation. ' +
138
138
  'Agent-only scoping has been deprecated due to security concerns (cross-user delegation leakage). ' +
139
- 'Please configure AGENTSHIELD_PROJECT_ID environment variable.'
139
+ 'Please configure CHECKPOINT_PROJECT_ID environment variable.'
140
140
  );
141
141
  return null;
142
142
  }
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * Phase 5: Anonymous Sessions Until OAuth
7
7
  * - Sessions start anonymous (no userDid) until OAuth completes
8
- * - User DIDs are resolved via AgentShield identity/resolve after OAuth
8
+ * - User DIDs are resolved via Checkpoint identity/resolve after OAuth
9
9
  * - Eliminates DID fragmentation (same user = same DID across sessions)
10
10
  *
11
11
  * DID Resolution Priority:
@@ -253,7 +253,7 @@ export class UserDidManager {
253
253
  *
254
254
  * @remarks
255
255
  * - Phase 5: Sessions start anonymous, no ephemeral DID generation
256
- * - User DIDs are resolved via AgentShield after OAuth completes
256
+ * - User DIDs are resolved via Checkpoint after OAuth completes
257
257
  * - Returns null if no existing DID found (instead of generating ephemeral)
258
258
  */
259
259
  async getOrCreateUserDid(
@@ -354,18 +354,18 @@ export class UserDidManager {
354
354
  }
355
355
 
356
356
  // PHASE 5: No ephemeral DID generation - session stays anonymous
357
- // User DID will be resolved via AgentShield after OAuth completes
357
+ // User DID will be resolved via Checkpoint after OAuth completes
358
358
  return null;
359
359
  }
360
360
 
361
361
  /**
362
362
  * Set user DID for a session (Phase 5: After OAuth resolution)
363
363
  *
364
- * Called after AgentShield identity/resolve returns a persistent user DID.
364
+ * Called after Checkpoint identity/resolve returns a persistent user DID.
365
365
  * Caches the DID and optionally stores in session storage.
366
366
  *
367
367
  * @param sessionId - MCP session ID
368
- * @param userDid - Persistent user DID from AgentShield
368
+ * @param userDid - Persistent user DID from Checkpoint
369
369
  * @param oauthIdentity - OAuth identity for creating persistent mappings
370
370
  */
371
371
  async setUserDidForSession(
package/src/index.ts CHANGED
@@ -48,6 +48,21 @@ export {
48
48
  // C4 (#2918) 3c envelope flip — DelegationRequiredError → needs_authorization mapper.
49
49
  export { toNeedsAuthorization } from "./runtime/needs-authorization";
50
50
 
51
+ // Verified delegation handed to protected tool handlers
52
+ export { toVerifiedDelegation } from "./runtime/verified-delegation";
53
+ export type { VerifiedDelegation } from "@kya-os/contracts/config";
54
+
55
+ // Verifier denial codes surfaced to clients and the audit ledger
56
+ export {
57
+ DEFAULT_DENIAL_MESSAGES,
58
+ nativeBindingDenial,
59
+ toDelegationDenial,
60
+ } from "./runtime/delegation-denial";
61
+ export type {
62
+ DelegationDenial,
63
+ DelegationDenialCode,
64
+ } from "./runtime/delegation-denial";
65
+
51
66
  // Canonical KYA-OS audit trail integration
52
67
  export {
53
68
  RuntimeToolAuditInvocation,
@@ -6,6 +6,10 @@ import type {
6
6
  AuthorizationEvidence,
7
7
  PartyRef,
8
8
  } from "@kya-os/mcp/audit" with { "resolution-mode": "import" };
9
+ // Type-only on purpose: package.json accepts contracts releases that predate
10
+ // the denial code list, so the known codes come from this package instead.
11
+ import type { DelegationDenialCode } from "@kya-os/contracts/config";
12
+ import { DEFAULT_DENIAL_MESSAGES } from "./delegation-denial.js";
9
13
 
10
14
  const encoder = new TextEncoder();
11
15
  const MAX_REFERENCE_LENGTH = 256;
@@ -584,8 +588,30 @@ export function terminalForToolResult(result: unknown): RuntimeToolTerminal {
584
588
  return { phase: "failed", outcome: "failed", reasonCode: "HANDLER_ERROR_RESULT" };
585
589
  }
586
590
 
591
+ // Read by shape, like the name checks below, because the error may come from
592
+ // another copy of this package. Only a known code counts as a denial.
593
+ function delegationDenialCode(error: unknown): DelegationDenialCode | undefined {
594
+ if (!isRecord(error) || !isRecord(error.denial)) return undefined;
595
+ const code = error.denial.code;
596
+ // Own keys only, so an inherited name such as "constructor" never matches.
597
+ return typeof code === "string" &&
598
+ Object.prototype.hasOwnProperty.call(DEFAULT_DENIAL_MESSAGES, code)
599
+ ? (code as DelegationDenialCode)
600
+ : undefined;
601
+ }
602
+
587
603
  export function terminalForToolError(error: unknown): RuntimeToolTerminal {
588
604
  const name = error instanceof Error ? error.name : "UnknownError";
605
+ const denialCode =
606
+ name === "DelegationRequiredError" ? delegationDenialCode(error) : undefined;
607
+ if (denialCode !== undefined) {
608
+ // The verifier refused a presented grant: a denial, not a request for consent.
609
+ return {
610
+ phase: "denied",
611
+ outcome: "denied",
612
+ reasonCode: denialCode.toUpperCase(),
613
+ };
614
+ }
589
615
  if (name === "DelegationRequiredError" || name === "OAuthRequiredError" ||
590
616
  name === "AuthRequiredError") {
591
617
  return {
@@ -31,6 +31,12 @@ import type { AccessControlApiService } from "../services/access-control.service
31
31
  import { authorizationMatches } from "../services/access-control.service.js";
32
32
  import type { VerifyDelegationRequest } from "@kya-os/contracts/agentshield-api";
33
33
  import { AgentShieldAPIError } from "@kya-os/contracts/agentshield-api";
34
+ import type { VerifiedDelegation } from "@kya-os/contracts/config";
35
+ import { toVerifiedDelegation } from "./verified-delegation.js";
36
+ import {
37
+ nativeBindingDenial,
38
+ toDelegationDenial,
39
+ } from "./delegation-denial.js";
34
40
 
35
41
  // Import the new provider runtime config
36
42
  import type { ProviderRuntimeConfig } from "../config";
@@ -98,6 +104,9 @@ interface RuntimeSessionContext {
98
104
  clientDid?: string;
99
105
  userDid?: string;
100
106
  agentDid?: string;
107
+ /** Trusted adapter fact from verification of THIS request's holder proof.
108
+ * Never populate from JSON params, decoded credentials, or handshake labels. */
109
+ verifiedInvokerDid?: string;
101
110
  serverDid?: string;
102
111
  nonce?: string;
103
112
  delegationToken?: string;
@@ -245,7 +254,7 @@ export class MCPIRuntimeBase {
245
254
  *
246
255
  * Phase 5: Anonymous Sessions Until OAuth
247
256
  * - Sessions start anonymous (no userDid) unless OAuth identity provided
248
- * - User DID is resolved via AgentShield after OAuth completes
257
+ * - User DID is resolved via Checkpoint after OAuth completes
249
258
  * - Eliminates DID fragmentation (same user = same DID across sessions)
250
259
  *
251
260
  * @param request - Handshake request object (may include oauthIdentity for persistent user DID lookup)
@@ -383,11 +392,11 @@ export class MCPIRuntimeBase {
383
392
  /**
384
393
  * Update session identity after OAuth resolution (Phase 5)
385
394
  *
386
- * Called after AgentShield identity/resolve returns a persistent user DID.
395
+ * Called after Checkpoint identity/resolve returns a persistent user DID.
387
396
  * Updates the session to authenticated state with the resolved DID.
388
397
  *
389
398
  * @param sessionId - MCP session ID
390
- * @param userDid - Persistent user DID from AgentShield
399
+ * @param userDid - Persistent user DID from Checkpoint
391
400
  * @param oauthIdentity - OAuth identity information
392
401
  * @throws Error if session not found
393
402
  */
@@ -481,13 +490,15 @@ export class MCPIRuntimeBase {
481
490
  *
482
491
  * @param toolName - Name of the tool being called
483
492
  * @param args - Tool arguments
484
- * @param handler - Tool execution handler
493
+ * @param handler - Tool execution handler. A protected tool whose verifier
494
+ * returned a credential also receives the verified delegation for THIS
495
+ * call as a second argument; every other call passes `args` only.
485
496
  * @param session - Session context (expected fields: id, audience, nonce?, delegationToken?, consentProof?)
486
497
  */
487
498
  async processToolCall<TArgs = unknown, TResult = unknown>(
488
499
  toolName: string,
489
500
  args: TArgs,
490
- handler: (args: TArgs) => Promise<TResult>,
501
+ handler: (args: TArgs, verified?: VerifiedDelegation) => Promise<TResult>,
491
502
  session?: RuntimeSessionContext
492
503
  ): Promise<TResult | RuntimeRecord> {
493
504
  const auditInvocation = this.config.auditTrail
@@ -552,9 +563,13 @@ export class MCPIRuntimeBase {
552
563
  private async processToolCallInternal<TArgs = unknown, TResult = unknown>(
553
564
  toolName: string,
554
565
  args: TArgs,
555
- handler: (args: TArgs) => Promise<TResult>,
566
+ handler: (args: TArgs, verified?: VerifiedDelegation) => Promise<TResult>,
556
567
  session?: RuntimeSessionContext
557
568
  ): Promise<TResult | RuntimeRecord> {
569
+ // Set only after every check below passes. Local to this call, so
570
+ // concurrent calls on the same runtime never see each other's grant.
571
+ let verifiedDelegation: VerifiedDelegation | undefined;
572
+
558
573
  // Check tool protection (delegation requirement)
559
574
  if (this.config.toolProtectionService) {
560
575
  // Get agent identity to check protection
@@ -715,13 +730,13 @@ export class MCPIRuntimeBase {
715
730
 
716
731
  // Build verification request
717
732
  const verifyRequest: VerifyDelegationRequest = {
718
- agent_did: identity.did,
733
+ agent_did: session?.verifiedInvokerDid ?? identity.did,
719
734
  scopes: protection.requiredScopes,
720
735
  };
721
736
 
722
737
  // ✅ CRITICAL: Include user_did for user-scoped delegation verification
723
738
  // This prevents cross-user delegation leakage (Priority 3 fallback issue)
724
- // Without user_did, AgentShield cannot validate user isolation
739
+ // Without user_did, Checkpoint cannot validate user isolation
725
740
  if (session?.userDid) {
726
741
  verifyRequest.user_did = session.userDid;
727
742
  if (this.config.environment === "development") {
@@ -760,13 +775,34 @@ export class MCPIRuntimeBase {
760
775
  credentialJwt: consentProof || undefined,
761
776
  });
762
777
 
763
- // Check verification result
764
- if (!verificationResult.data.valid) {
778
+ // A native admission binds this exact request to a holder. Recheck
779
+ // the returned authority rather than accepting a valid response for
780
+ // another principal or a weaker scope set from a stale adapter.
781
+ // Only an accepted grant carries a credential to compare. A refused
782
+ // grant has none, so it keeps the verifier's own denial code.
783
+ const nativeBindingMismatch =
784
+ verificationResult.data.valid === true &&
785
+ session?.verifiedInvokerDid !== undefined &&
786
+ (verificationResult.data.credential?.agent_did !==
787
+ session.verifiedInvokerDid ||
788
+ !protection.requiredScopes.every((scope) =>
789
+ verificationResult.data.credential?.scopes?.includes(scope)
790
+ ));
791
+ if (!verificationResult.data.valid || nativeBindingMismatch) {
765
792
  // Delegation verification failed
766
793
  const reason =
767
- verificationResult.data.reason ||
794
+ (nativeBindingMismatch
795
+ ? "Native holder or scope binding mismatch"
796
+ : verificationResult.data.reason) ||
768
797
  "Delegation token invalid or expired";
769
798
  const errorDetails = verificationResult.data.error;
799
+ // Machine-readable reason from the allowlist only. Upstream
800
+ // message and details never reach the client or the ledger.
801
+ const denial = nativeBindingMismatch
802
+ ? nativeBindingDenial()
803
+ : toDelegationDenial(
804
+ errorDetails?.code ?? verificationResult.data.reason
805
+ );
770
806
 
771
807
  if (this.config.environment === "development") {
772
808
  console.error("[MCP-I] ❌ Delegation verification FAILED", {
@@ -775,6 +811,7 @@ export class MCPIRuntimeBase {
775
811
  reason,
776
812
  errorCode: errorDetails?.code,
777
813
  errorMessage: errorDetails?.message,
814
+ denialCode: denial?.code,
778
815
  requiredScopes: protection.requiredScopes,
779
816
  });
780
817
  }
@@ -807,7 +844,8 @@ export class MCPIRuntimeBase {
807
844
  protection.requiredScopes,
808
845
  consentUrl,
809
846
  interceptedCall,
810
- resumeToken
847
+ resumeToken,
848
+ denial
811
849
  );
812
850
  }
813
851
 
@@ -815,7 +853,7 @@ export class MCPIRuntimeBase {
815
853
  // This ensures delegations are user-specific and prevents user isolation bypass
816
854
  const credential = verificationResult.data.credential;
817
855
  const delegationUserIdentifier = credential?.user_identifier;
818
- // Also check for user_id field (AgentShield may return DID or ID directly)
856
+ // Also check for user_id field (Checkpoint may return DID or ID directly)
819
857
  const delegationUserId = credential?.user_id;
820
858
  const sessionUserDid = session?.userDid;
821
859
 
@@ -826,8 +864,8 @@ export class MCPIRuntimeBase {
826
864
  delegationUserId === sessionUserDid;
827
865
 
828
866
  // Special case: If delegationUserIdentifier is NOT a DID (e.g., email),
829
- // but AgentShield verified the delegation, trust it.
830
- // AgentShield internally links email → DID, so the verification is valid.
867
+ // but Checkpoint verified the delegation, trust it.
868
+ // Checkpoint internally links email → DID, so the verification is valid.
831
869
  // Only fail if BOTH are DIDs and they don't match.
832
870
  const isDelegationIdentifierDid =
833
871
  delegationUserIdentifier.startsWith("did:");
@@ -889,7 +927,7 @@ export class MCPIRuntimeBase {
889
927
  );
890
928
  }
891
929
 
892
- // User identifier validation passed (direct match or trusted AgentShield verification)
930
+ // User identifier validation passed (direct match or trusted Checkpoint verification)
893
931
  if (this.config.environment === "development") {
894
932
  console.error("[MCP-I] ✅ User identifier validation PASSED", {
895
933
  tool: toolName,
@@ -922,7 +960,7 @@ export class MCPIRuntimeBase {
922
960
 
923
961
  // ✅ SECURITY: Validate authorization method matches tool requirements
924
962
  // This prevents stale delegations from working after tool auth method changes
925
- // NOTE: Authorization validation only applies when credential is present (AgentShield API verifier).
963
+ // NOTE: Authorization validation only applies when credential is present (Checkpoint API verifier).
926
964
  // KV/Memory verifiers don't return credential data, so we skip auth method validation for them.
927
965
  const toolAuth = protection.authorization;
928
966
  const delegationAuth = credential?.authorization as
@@ -931,7 +969,7 @@ export class MCPIRuntimeBase {
931
969
 
932
970
  // Only validate when:
933
971
  // 1. Tool has authorization requirement defined
934
- // 2. Credential is present (AgentShield API verifier)
972
+ // 2. Credential is present (Checkpoint API verifier)
935
973
  if (toolAuth && credential) {
936
974
  // If tool requires authorization but credential doesn't have auth data, reject
937
975
  // This prevents bypassing auth checks with incomplete credential data
@@ -1053,6 +1091,10 @@ export class MCPIRuntimeBase {
1053
1091
  }
1054
1092
  // If credential is missing entirely (KV/Memory verifiers), skip validation for backward compatibility
1055
1093
 
1094
+ // Every check passed: hand the verifier's answer to the handler so
1095
+ // it can enforce grant constraints from what was verified just now.
1096
+ verifiedDelegation = toVerifiedDelegation(verificationResult.data);
1097
+
1056
1098
  // Verification succeeded
1057
1099
  if (this.config.environment === "development") {
1058
1100
  console.error("[MCP-I] ✅ Delegation verification SUCCEEDED", {
@@ -1177,8 +1219,11 @@ export class MCPIRuntimeBase {
1177
1219
  }
1178
1220
  }
1179
1221
 
1180
- // Execute the tool
1181
- const result = await handler(args);
1222
+ // Execute the tool. One-argument call when nothing was verified, so
1223
+ // handlers that inspect their arity or `arguments` see today's call.
1224
+ const result = verifiedDelegation
1225
+ ? await handler(args, verifiedDelegation)
1226
+ : await handler(args);
1182
1227
 
1183
1228
  // Create proof
1184
1229
  const proof = await this.createProof(result, session);
@@ -1209,7 +1254,7 @@ export class MCPIRuntimeBase {
1209
1254
  */
1210
1255
  async resumeToolCall(
1211
1256
  resumeToken: string,
1212
- handler: (args: unknown) => Promise<unknown>,
1257
+ handler: (args: unknown, verified?: VerifiedDelegation) => Promise<unknown>,
1213
1258
  delegationToken?: string
1214
1259
  ): Promise<unknown> {
1215
1260
  const interceptedCall = this.interceptedCalls.get(resumeToken);
@@ -1278,12 +1323,12 @@ export class MCPIRuntimeBase {
1278
1323
  }
1279
1324
 
1280
1325
  /**
1281
- * Build consent URL for AgentShield delegation flow
1326
+ * Build consent URL for Checkpoint delegation flow
1282
1327
  *
1283
- * Note: Parameter names use snake_case for AgentShield API compatibility.
1328
+ * Note: Parameter names use snake_case for Checkpoint API compatibility.
1284
1329
  * This is documented in docs/API_PARITY_GUIDE.md under "Field Naming Conventions".
1285
1330
  *
1286
- * AgentShield API requires snake_case in URL parameters:
1331
+ * Checkpoint API requires snake_case in URL parameters:
1287
1332
  * - session_id (not sessionId)
1288
1333
  * - agent_did (not agentDid)
1289
1334
  * - resume_token (not resumeToken)
@@ -1293,7 +1338,7 @@ export class MCPIRuntimeBase {
1293
1338
  * @param scopes - Required scopes for the tool
1294
1339
  * @param session - Current session context
1295
1340
  * @param resumeToken - Token to resume after delegation
1296
- * @param projectId - Project ID for AgentShield API
1341
+ * @param projectId - Project ID for Checkpoint API
1297
1342
  * @param provider - Provider name (e.g., "github", "credentials") to select specific auth method
1298
1343
  * @returns Full consent URL with snake_case parameters
1299
1344
  */
@@ -1377,7 +1422,7 @@ export class MCPIRuntimeBase {
1377
1422
  * @param scopes - Required scopes
1378
1423
  * @param session - Current session context
1379
1424
  * @param resumeToken - Token to resume after delegation
1380
- * @param projectId - AgentShield project ID
1425
+ * @param projectId - Checkpoint project ID
1381
1426
  * @param serverUrl - Server URL for consent approval POST
1382
1427
  * @param clientCapabilities - MCP client capabilities from the session
1383
1428
  */
@@ -1448,8 +1493,8 @@ export class MCPIRuntimeBase {
1448
1493
  provider?: string
1449
1494
  ): string {
1450
1495
  // Default implementation - override in subclasses
1451
- // This URL should point to AgentShield's consent page
1452
- // Parameter names use snake_case for AgentShield API compatibility
1496
+ // This URL should point to Checkpoint's consent page
1497
+ // Parameter names use snake_case for Checkpoint API compatibility
1453
1498
  const params = new URLSearchParams({
1454
1499
  tool: toolName,
1455
1500
  scopes: scopes.join(","),
@@ -1457,14 +1502,14 @@ export class MCPIRuntimeBase {
1457
1502
  agent_did: session?.agentDid || "",
1458
1503
  });
1459
1504
 
1460
- // Add agent_name for AgentShield dashboard display
1505
+ // Add agent_name for Checkpoint dashboard display
1461
1506
  // Priority: session.agentName > "Unknown Agent"
1462
1507
  const agentName = session?.agentName;
1463
1508
  if (agentName) {
1464
1509
  params.set("agent_name", agentName);
1465
1510
  }
1466
1511
 
1467
- // Add project_id if provided (required for AgentShield consent endpoint)
1512
+ // Add project_id if provided (required for Checkpoint consent endpoint)
1468
1513
  if (projectId) {
1469
1514
  params.set("project_id", projectId);
1470
1515
  }
@@ -1480,7 +1525,7 @@ export class MCPIRuntimeBase {
1480
1525
  params.set("provider", provider);
1481
1526
  }
1482
1527
 
1483
- // Use AgentShield consent endpoint
1528
+ // Use Checkpoint consent endpoint
1484
1529
  return `https://kya.vouched.id/bouncer/consent?${params.toString()}`;
1485
1530
  }
1486
1531