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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +13 -2
  5. package/dist/index.js.map +1 -1
  6. package/dist/proof/generator.d.ts +8 -6
  7. package/dist/proof/generator.d.ts.map +1 -1
  8. package/dist/proof/generator.js +7 -24
  9. package/dist/proof/generator.js.map +1 -1
  10. package/dist/runtime/audit.d.ts.map +1 -1
  11. package/dist/runtime/audit.js +66 -18
  12. package/dist/runtime/audit.js.map +1 -1
  13. package/dist/runtime/base.d.ts +6 -1
  14. package/dist/runtime/base.d.ts.map +1 -1
  15. package/dist/runtime/base.js +65 -17
  16. package/dist/runtime/base.js.map +1 -1
  17. package/dist/services/access-control.service.d.ts.map +1 -1
  18. package/dist/services/access-control.service.js +12 -5
  19. package/dist/services/access-control.service.js.map +1 -1
  20. package/dist/services/proof-verifier.d.ts +13 -35
  21. package/dist/services/proof-verifier.d.ts.map +1 -1
  22. package/dist/services/proof-verifier.js +16 -74
  23. package/dist/services/proof-verifier.js.map +1 -1
  24. package/dist/services/tool-context-builder.d.ts.map +1 -1
  25. package/dist/services/tool-context-builder.js +16 -4
  26. package/dist/services/tool-context-builder.js.map +1 -1
  27. package/dist/services/tool-protection.service.d.ts +7 -0
  28. package/dist/services/tool-protection.service.d.ts.map +1 -1
  29. package/dist/services/tool-protection.service.js +34 -15
  30. package/dist/services/tool-protection.service.js.map +1 -1
  31. package/dist/types/tool-protection.d.ts +94 -0
  32. package/dist/types/tool-protection.d.ts.map +1 -1
  33. package/dist/types/tool-protection.js +113 -1
  34. package/dist/types/tool-protection.js.map +1 -1
  35. package/package.json +2 -2
  36. package/src/__tests__/runtime/amount-limit-enforcement.test.ts +269 -0
  37. package/src/__tests__/runtime/amount-limit-result.test.ts +61 -0
  38. package/src/__tests__/runtime/audit-contracts-compat.test.ts +20 -5
  39. package/src/__tests__/runtime/audit.test.ts +255 -53
  40. package/src/__tests__/runtime/process-tool-call-security.test.ts +97 -13
  41. package/src/__tests__/runtime/provider-selection.test.ts +4 -6
  42. package/src/__tests__/runtime/route-interception.test.ts +215 -214
  43. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +89 -6
  44. package/src/__tests__/services/tool-protection-amount.test.ts +107 -0
  45. package/src/__tests__/services/tool-protection-failsafe.test.ts +71 -4
  46. package/src/__tests__/utils/tool-protection-runtime.ts +3 -0
  47. package/src/index.ts +15 -1
  48. package/src/proof/__tests__/proof-generator.test.ts +35 -12
  49. package/src/proof/generator.ts +18 -27
  50. package/src/runtime/__tests__/ext-apps-consent.test.ts +87 -2
  51. package/src/runtime/audit.ts +155 -62
  52. package/src/runtime/base.ts +95 -31
  53. package/src/services/__tests__/access-control.service.test.ts +44 -0
  54. package/src/services/__tests__/proof-verifier.test.ts +283 -195
  55. package/src/services/__tests__/tool-context-builder-authtype.test.ts +79 -0
  56. package/src/services/__tests__/tool-context-builder.test.ts +4 -7
  57. package/src/services/__tests__/tool-protection-served-revision.test.ts +102 -0
  58. package/src/services/access-control.service.ts +11 -5
  59. package/src/services/proof-verifier.ts +18 -79
  60. package/src/services/tool-context-builder.ts +19 -4
  61. package/src/services/tool-protection.service.ts +62 -19
  62. package/src/types/tool-protection.ts +161 -0
@@ -15,7 +15,14 @@ import {
15
15
  IdentityProvider,
16
16
  AgentIdentity,
17
17
  } from "../providers/base";
18
- import { DelegationRequiredError } from "../types/tool-protection.js";
18
+ import {
19
+ AmountLimitError,
20
+ DelegationRequiredError,
21
+ isUnavailableToolProtection,
22
+ namesRequiredScope,
23
+ unavailableToolProtectionError,
24
+ unscopedToolProtectionError,
25
+ } from "../types/tool-protection.js";
19
26
  import { CryptoService, type Ed25519JWK } from "../services/crypto.service.js";
20
27
  import { ProofVerifier } from "../services/proof-verifier.js";
21
28
  import type { DetachedProof } from "@kya-os/contracts/proof";
@@ -31,6 +38,7 @@ import type { AccessControlApiService } from "../services/access-control.service
31
38
  import { authorizationMatches } from "../services/access-control.service.js";
32
39
  import type { VerifyDelegationRequest } from "@kya-os/contracts/checkpoint-api";
33
40
  import { CheckpointAPIError } from "@kya-os/contracts/checkpoint-api";
41
+ import { findAmountLimitViolation } from "@kya-os/contracts/delegation";
34
42
  import type { VerifiedDelegation } from "@kya-os/contracts/config";
35
43
  import { toVerifiedDelegation } from "./verified-delegation.js";
36
44
  import {
@@ -525,7 +533,10 @@ export class MCPIRuntimeBase {
525
533
  // A tool failure is the primary error. Do not replace it with a
526
534
  // terminal-delivery error and accidentally make retries ambiguous.
527
535
  console.error("[MCP-I] Failed to record terminal tool audit event", {
528
- error: auditError instanceof Error ? auditError.message : String(auditError),
536
+ error:
537
+ auditError instanceof Error
538
+ ? auditError.message
539
+ : String(auditError),
529
540
  });
530
541
  }
531
542
  }
@@ -535,7 +546,9 @@ export class MCPIRuntimeBase {
535
546
  if (!auditInvocation || !this.config.auditTrail) return result;
536
547
 
537
548
  try {
538
- const terminal = await auditInvocation.terminal(terminalForToolResult(result));
549
+ const terminal = await auditInvocation.terminal(
550
+ terminalForToolResult(result)
551
+ );
539
552
  return attachRuntimeAuditMetadata(
540
553
  result,
541
554
  this.config.auditTrail.sourceId,
@@ -548,7 +561,8 @@ export class MCPIRuntimeBase {
548
561
  // an explicit degraded/error marker; primitives fail closed because they
549
562
  // cannot carry trustworthy delivery metadata.
550
563
  console.error("[MCP-I] Failed to record successful tool audit terminal", {
551
- error: auditError instanceof Error ? auditError.message : String(auditError),
564
+ error:
565
+ auditError instanceof Error ? auditError.message : String(auditError),
552
566
  });
553
567
  return attachRuntimeAuditMetadata(
554
568
  result,
@@ -569,6 +583,7 @@ export class MCPIRuntimeBase {
569
583
  // Set only after every check below passes. Local to this call, so
570
584
  // concurrent calls on the same runtime never see each other's grant.
571
585
  let verifiedDelegation: VerifiedDelegation | undefined;
586
+ let grantConstraints: unknown;
572
587
 
573
588
  // Check tool protection (delegation requirement)
574
589
  if (this.config.toolProtectionService) {
@@ -590,6 +605,18 @@ export class MCPIRuntimeBase {
590
605
  );
591
606
 
592
607
  if (protection) {
608
+ // No config could be read and none is cached: the service's stand-in.
609
+ // Refused until a config arrives.
610
+ if (isUnavailableToolProtection(protection)) {
611
+ throw unavailableToolProtectionError(toolName);
612
+ }
613
+ // A protection that names no scope has nothing to check a delegation
614
+ // against, so it can't be enforced: refused before consent or
615
+ // verification, never passed as satisfied.
616
+ if (!namesRequiredScope(protection.requiredScopes)) {
617
+ throw unscopedToolProtectionError(toolName);
618
+ }
619
+
593
620
  // Tool requires delegation
594
621
  const hasDelegation = session?.delegationToken || session?.consentProof;
595
622
 
@@ -874,19 +901,18 @@ export class MCPIRuntimeBase {
874
901
 
875
902
  if (shouldEnforceMatch && !identifiersMatch) {
876
903
  // User identifier mismatch - potential security issue
877
- const securityError = `Delegation user_identifier mismatch: delegation has "${delegationUserIdentifier.substring(0, 20)}..." but session has "${sessionUserDid.substring(0, 20)}..."`;
878
-
879
904
  if (this.config.environment === "development") {
880
905
  console.error(
881
906
  "[MCP-I] 🔒 SECURITY: User identifier validation FAILED",
882
907
  {
883
908
  tool: toolName,
884
909
  agentDid: identity.did.slice(0, 20) + "...",
885
- delegationUserIdentifier:
886
- delegationUserIdentifier.substring(0, 20) + "...",
887
- delegationUserId: delegationUserId
888
- ? delegationUserId.substring(0, 20) + "..."
889
- : "N/A",
910
+ // The identifier can be an email and the id a
911
+ // customer number: log their shape, never the values.
912
+ delegationIdentifierFormat: isDelegationIdentifierDid
913
+ ? "did"
914
+ : "email_or_other",
915
+ hasDelegationUserId: !!delegationUserId,
890
916
  sessionUserDid: sessionUserDid.substring(0, 20) + "...",
891
917
  sessionId: session?.id?.substring(0, 20) + "...",
892
918
  reason: "user_identifier_mismatch",
@@ -950,8 +976,10 @@ export class MCPIRuntimeBase {
950
976
  {
951
977
  tool: toolName,
952
978
  agentDid: identity.did.slice(0, 20) + "...",
953
- delegationUserIdentifier:
954
- delegationUserIdentifier.substring(0, 20) + "...",
979
+ delegationIdentifierFormat:
980
+ delegationUserIdentifier.startsWith("did:")
981
+ ? "did"
982
+ : "email_or_other",
955
983
  sessionId: session?.id?.substring(0, 20) + "...",
956
984
  }
957
985
  );
@@ -1094,6 +1122,9 @@ export class MCPIRuntimeBase {
1094
1122
  // Every check passed: hand the verifier's answer to the handler so
1095
1123
  // it can enforce grant constraints from what was verified just now.
1096
1124
  verifiedDelegation = toVerifiedDelegation(verificationResult.data);
1125
+ grantConstraints =
1126
+ verifiedDelegation?.constraints ??
1127
+ verificationResult.data.delegation?.constraints;
1097
1128
 
1098
1129
  // Verification succeeded
1099
1130
  if (this.config.environment === "development") {
@@ -1204,6 +1235,18 @@ export class MCPIRuntimeBase {
1204
1235
  );
1205
1236
  }
1206
1237
  }
1238
+
1239
+ if (protection.amount) {
1240
+ const amountViolation = findAmountLimitViolation({
1241
+ args,
1242
+ amountConfig: protection.amount,
1243
+ requiredScopes: protection.requiredScopes,
1244
+ constraints: grantConstraints,
1245
+ });
1246
+ if (amountViolation) {
1247
+ throw new AmountLimitError(toolName, amountViolation);
1248
+ }
1249
+ }
1207
1250
  } else {
1208
1251
  // No protection required - tool can be executed freely
1209
1252
  if (this.config.environment === "development") {
@@ -1457,7 +1500,11 @@ export class MCPIRuntimeBase {
1457
1500
  content: [
1458
1501
  {
1459
1502
  type: "text",
1460
- text: `Authorization required for tool "${toolName}". Please approve in the consent form below, or open this link to authorize in your browser: ${consentUrl}`,
1503
+ text: `Authorization required for tool "${toolName}". Please approve in the consent form below.${
1504
+ consentUrl
1505
+ ? ` Or open this link to authorize in your browser: ${consentUrl}`
1506
+ : ""
1507
+ }`,
1461
1508
  },
1462
1509
  ],
1463
1510
  structuredContent: {
@@ -1471,7 +1518,7 @@ export class MCPIRuntimeBase {
1471
1518
  projectId: projectId || "",
1472
1519
  resumeToken: resumeToken || "",
1473
1520
  serverUrl: serverUrl || "",
1474
- consentUrl,
1521
+ ...(consentUrl ? { consentUrl } : {}),
1475
1522
  ...(provider ? { provider } : {}),
1476
1523
  },
1477
1524
  _meta: {
@@ -1484,6 +1531,11 @@ export class MCPIRuntimeBase {
1484
1531
  };
1485
1532
  }
1486
1533
 
1534
+ /**
1535
+ * The configured authorization URL with this request's parameters, or
1536
+ * undefined when none is configured. Runtimes that serve their own consent
1537
+ * page override this.
1538
+ */
1487
1539
  protected buildConsentUrl(
1488
1540
  toolName: string,
1489
1541
  scopes: string[],
@@ -1491,10 +1543,16 @@ export class MCPIRuntimeBase {
1491
1543
  resumeToken?: string,
1492
1544
  projectId?: string,
1493
1545
  provider?: string
1494
- ): string {
1495
- // Default implementation - override in subclasses
1496
- // This URL should point to Checkpoint's consent page
1497
- // Parameter names use snake_case for Checkpoint API compatibility
1546
+ ): string | undefined {
1547
+ const configured = this.config.delegation?.authorization?.authorizationUrl;
1548
+ if (!configured) return undefined;
1549
+ let url: URL;
1550
+ try {
1551
+ url = new URL(configured);
1552
+ } catch {
1553
+ return undefined;
1554
+ }
1555
+
1498
1556
  const params = new URLSearchParams({
1499
1557
  tool: toolName,
1500
1558
  scopes: scopes.join(","),
@@ -1502,14 +1560,14 @@ export class MCPIRuntimeBase {
1502
1560
  agent_did: session?.agentDid || "",
1503
1561
  });
1504
1562
 
1505
- // Add agent_name for Checkpoint dashboard display
1563
+ // Add agent_name for display
1506
1564
  // Priority: session.agentName > "Unknown Agent"
1507
1565
  const agentName = session?.agentName;
1508
1566
  if (agentName) {
1509
1567
  params.set("agent_name", agentName);
1510
1568
  }
1511
1569
 
1512
- // Add project_id if provided (required for Checkpoint consent endpoint)
1570
+ // Add project_id if provided
1513
1571
  if (projectId) {
1514
1572
  params.set("project_id", projectId);
1515
1573
  }
@@ -1525,8 +1583,10 @@ export class MCPIRuntimeBase {
1525
1583
  params.set("provider", provider);
1526
1584
  }
1527
1585
 
1528
- // Use Checkpoint consent endpoint
1529
- return `https://kya.vouched.id/bouncer/consent?${params.toString()}`;
1586
+ for (const [key, value] of params) {
1587
+ url.searchParams.set(key, value);
1588
+ }
1589
+ return url.toString();
1530
1590
  }
1531
1591
 
1532
1592
  /**
@@ -1643,9 +1703,10 @@ export class MCPIRuntimeBase {
1643
1703
 
1644
1704
  if (result.valid && session) {
1645
1705
  // Store canonical payload in session for detached JWS consumers
1646
- const canonicalPayload = this.proofVerifier.buildCanonicalPayload(
1647
- detachedProof.meta
1648
- );
1706
+ const canonicalPayload =
1707
+ await this.proofVerifier.buildCanonicalPayload(
1708
+ detachedProof.meta
1709
+ );
1649
1710
  session.canonicalPayload = canonicalPayload;
1650
1711
  }
1651
1712
 
@@ -2097,11 +2158,14 @@ export class MCPIRuntimeBase {
2097
2158
  /** Development-only diagnostics. These records make no audit assurance claim. */
2098
2159
  private emitDiagnostic(event: string, data: unknown): void {
2099
2160
  if (this.config.environment !== "development") return;
2100
- console.error("[MCP-I diagnostic]", JSON.stringify({
2101
- event,
2102
- data,
2103
- timestamp: this.clock.now(),
2104
- }));
2161
+ console.error(
2162
+ "[MCP-I diagnostic]",
2163
+ JSON.stringify({
2164
+ event,
2165
+ data,
2166
+ timestamp: this.clock.now(),
2167
+ })
2168
+ );
2105
2169
  }
2106
2170
 
2107
2171
  private createDIDDocument(identity: AgentIdentity): DIDDocument {
@@ -1046,6 +1046,50 @@ describe("authorizationMatches", () => {
1046
1046
  });
1047
1047
  });
1048
1048
 
1049
+ describe.each([
1050
+ ["oauth", "oauth2"],
1051
+ ["oauth2", "oauth"],
1052
+ ["oauth2", "oauth2"],
1053
+ ])("OAuth aliases (%s delegation, %s requirement)", (delegationType, requiredType) => {
1054
+ it("accepts the same provider across supported OAuth aliases", () => {
1055
+ expect(authorizationMatches(
1056
+ { type: delegationType, provider: "github" },
1057
+ { type: requiredType, provider: "github" }
1058
+ )).toBe(true);
1059
+ });
1060
+
1061
+ it.each(["custom", "google", "GitHub", undefined])(
1062
+ "rejects a delegation provider of %s when GitHub is required",
1063
+ (provider) => {
1064
+ expect(authorizationMatches(
1065
+ { type: delegationType, provider },
1066
+ { type: requiredType, provider: "github" }
1067
+ )).toBe(false);
1068
+ }
1069
+ );
1070
+
1071
+ it("allows any provider only when the tool has no provider requirement", () => {
1072
+ expect(authorizationMatches(
1073
+ { type: delegationType, provider: "github" },
1074
+ { type: requiredType }
1075
+ )).toBe(true);
1076
+ });
1077
+ });
1078
+
1079
+ it.each(["password", "none", "apikey", "verifiable_credential"])(
1080
+ "does not make %s authorization interchangeable with OAuth",
1081
+ (type) => {
1082
+ expect(authorizationMatches(
1083
+ { type, provider: "github" },
1084
+ { type: "oauth2", provider: "github" }
1085
+ )).toBe(false);
1086
+ expect(authorizationMatches(
1087
+ { type: "oauth2", provider: "github" },
1088
+ { type, provider: "github" }
1089
+ )).toBe(false);
1090
+ }
1091
+ );
1092
+
1049
1093
  describe("verifiable_credential type matching", () => {
1050
1094
  it("should return true when credentialTypes match", () => {
1051
1095
  const delegationAuth = { type: "verifiable_credential", credentialType: "api-key" };