@kya-os/mcp-i-runtime 1.1.0 → 1.2.1

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 (63) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/config.d.ts +5 -7
  3. package/dist/config.d.ts.map +1 -1
  4. package/dist/config.js +4 -6
  5. package/dist/config.js.map +1 -1
  6. package/dist/index.d.ts +3 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +20 -2
  9. package/dist/index.js.map +1 -1
  10. package/dist/runtime/audit-logger.d.ts +6 -28
  11. package/dist/runtime/audit-logger.d.ts.map +1 -1
  12. package/dist/runtime/audit-logger.js +5 -3
  13. package/dist/runtime/audit-logger.js.map +1 -1
  14. package/dist/runtime/audit.d.ts +132 -0
  15. package/dist/runtime/audit.d.ts.map +1 -0
  16. package/dist/runtime/audit.js +424 -0
  17. package/dist/runtime/audit.js.map +1 -0
  18. package/dist/runtime/base.d.ts +9 -48
  19. package/dist/runtime/base.d.ts.map +1 -1
  20. package/dist/runtime/base.js +109 -89
  21. package/dist/runtime/base.js.map +1 -1
  22. package/dist/services/auth-type-satisfies.d.ts +93 -0
  23. package/dist/services/auth-type-satisfies.d.ts.map +1 -0
  24. package/dist/services/auth-type-satisfies.js +127 -0
  25. package/dist/services/auth-type-satisfies.js.map +1 -0
  26. package/dist/services/oauth-config.service.d.ts.map +1 -1
  27. package/dist/services/oauth-config.service.js +29 -0
  28. package/dist/services/oauth-config.service.js.map +1 -1
  29. package/dist/services/tool-context-builder.d.ts +6 -1
  30. package/dist/services/tool-context-builder.d.ts.map +1 -1
  31. package/dist/services/tool-context-builder.js +35 -3
  32. package/dist/services/tool-context-builder.js.map +1 -1
  33. package/package.json +7 -3
  34. package/src/__tests__/config/provider-runtime-config.test.ts +2 -9
  35. package/src/__tests__/config.test.ts +12 -11
  36. package/src/__tests__/integration/full-flow.test.ts +0 -5
  37. package/src/__tests__/integration.test.ts +2 -6
  38. package/src/__tests__/runtime/audit.test.ts +327 -0
  39. package/src/__tests__/runtime/base-extensions.test.ts +0 -46
  40. package/src/__tests__/runtime/base.test.ts +71 -102
  41. package/src/__tests__/runtime/delegation-flow.test.ts +0 -4
  42. package/src/__tests__/runtime/process-tool-call-security.test.ts +5 -11
  43. package/src/__tests__/runtime/proof-client-did.test.ts +0 -4
  44. package/src/__tests__/runtime/provider-selection.test.ts +0 -2
  45. package/src/__tests__/runtime/route-interception.test.ts +7 -4
  46. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +23 -31
  47. package/src/__tests__/services/tool-protection-merged-config.test.ts +0 -40
  48. package/src/config/__tests__/merged-config.spec.ts +0 -26
  49. package/src/config.ts +9 -10
  50. package/src/index.ts +32 -2
  51. package/src/runtime/__tests__/audit-logger-compat.test.ts +15 -0
  52. package/src/runtime/audit-logger.ts +6 -29
  53. package/src/runtime/audit.ts +598 -0
  54. package/src/runtime/base.ts +154 -99
  55. package/src/services/__tests__/auth-type-satisfies.test.ts +232 -0
  56. package/src/services/__tests__/oauth-config.service.test.ts +66 -0
  57. package/src/services/__tests__/proof-verifier.integration.test.ts +1 -1
  58. package/src/services/__tests__/proof-verifier.test.ts +6 -3
  59. package/src/services/__tests__/tool-context-builder-authtype.test.ts +167 -0
  60. package/src/services/auth-type-satisfies.ts +134 -0
  61. package/src/services/oauth-config.service.ts +44 -1
  62. package/src/services/tool-context-builder.ts +64 -18
  63. package/src/__tests__/runtime/audit-logger.test.ts +0 -154
@@ -0,0 +1,327 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import type { AuditTrailEventInput } from "@kya-os/mcp/audit";
3
+ import type { ProviderRuntimeConfig } from "../../config";
4
+ import { MCPIRuntimeBase } from "../../runtime/base";
5
+ import {
6
+ createHmacRuntimeAuditContextFactory,
7
+ recordRuntimeConsentAudit,
8
+ recordRuntimeDelegationAudit,
9
+ type RuntimeAuditConfig,
10
+ } from "../../runtime/audit";
11
+ import { createMockProviders } from "../utils/mock-providers";
12
+
13
+ function auditConfig(record: (event: AuditTrailEventInput) => Promise<unknown>): RuntimeAuditConfig {
14
+ return {
15
+ sourceId: "deployment:test:mcp:0",
16
+ context: {
17
+ create: async () => ({
18
+ invocationId: "invocation-1",
19
+ correlationId: "correlation-1",
20
+ session: {
21
+ ref: {
22
+ kind: "keyed_commitment",
23
+ value: `sha256:${"a".repeat(64)}`,
24
+ keyId: "session-key-1",
25
+ },
26
+ },
27
+ }),
28
+ },
29
+ trail: { record: record as RuntimeAuditConfig["trail"]["record"] },
30
+ includeToolNames: true,
31
+ };
32
+ }
33
+
34
+ function runtimeWithAudit(record: (event: AuditTrailEventInput) => Promise<unknown>): MCPIRuntimeBase {
35
+ const config: ProviderRuntimeConfig = {
36
+ ...createMockProviders(),
37
+ environment: "development",
38
+ auditTrail: auditConfig(record),
39
+ };
40
+ return new MCPIRuntimeBase(config);
41
+ }
42
+
43
+ function pendingResult(event: AuditTrailEventInput, sourceSequence = "1") {
44
+ return {
45
+ status: "pending",
46
+ event: {
47
+ ...event,
48
+ source: {
49
+ producer: { kind: "pairwise_did", did: "did:key:zProducer" },
50
+ sourceId: "deployment:test:mcp:0",
51
+ sourceSequence,
52
+ },
53
+ },
54
+ };
55
+ }
56
+
57
+ describe("canonical runtime audit lifecycle", () => {
58
+ it("records exactly one started and one completed event", async () => {
59
+ const events: AuditTrailEventInput[] = [];
60
+ const runtime = runtimeWithAudit(async (event) => {
61
+ events.push(event);
62
+ return pendingResult(event, String(events.length));
63
+ });
64
+ const handler = vi.fn(async () => ({ ok: true }));
65
+
66
+ const result = await runtime.processToolCall(
67
+ "payments.send",
68
+ { secret: "never-audited" },
69
+ handler,
70
+ { id: "raw-session", nonce: "nonce", audience: "client" },
71
+ );
72
+
73
+ expect(result).toMatchObject({
74
+ ok: true,
75
+ _meta: {
76
+ "org.kya-os/audit": {
77
+ status: "pending",
78
+ sourceId: "deployment:test:mcp:0",
79
+ invocationId: "invocation-1",
80
+ },
81
+ },
82
+ });
83
+
84
+ expect(handler).toHaveBeenCalledTimes(1);
85
+ expect(events.map((event) => event.eventType)).toEqual([
86
+ "tool.call.started",
87
+ "tool.call.completed",
88
+ ]);
89
+ expect(events.map((event) => event.eventId)).toEqual([
90
+ "invocation-1:started",
91
+ "invocation-1:completed",
92
+ ]);
93
+ expect(events.every((event) => event.correlationId === "correlation-1")).toBe(true);
94
+ expect(JSON.stringify(events)).not.toContain("never-audited");
95
+ expect(JSON.stringify(events)).not.toContain("raw-session");
96
+ });
97
+
98
+ it("records one failed terminal event and never re-runs a throwing handler", async () => {
99
+ const events: AuditTrailEventInput[] = [];
100
+ const runtime = runtimeWithAudit(async (event) => {
101
+ events.push(event);
102
+ return pendingResult(event, String(events.length));
103
+ });
104
+ const handler = vi.fn(async () => {
105
+ throw new Error("side effect failed");
106
+ });
107
+
108
+ await expect(runtime.processToolCall(
109
+ "payments.send",
110
+ {},
111
+ handler,
112
+ { id: "session", nonce: "nonce", audience: "client" },
113
+ )).rejects.toThrow("side effect failed");
114
+
115
+ expect(handler).toHaveBeenCalledTimes(1);
116
+ expect(events.map((event) => event.eventType)).toEqual([
117
+ "tool.call.started",
118
+ "tool.call.failed",
119
+ ]);
120
+ });
121
+
122
+ it("keeps long started and terminal event IDs distinct", async () => {
123
+ const events: AuditTrailEventInput[] = [];
124
+ const config = auditConfig(async (event) => {
125
+ events.push(event);
126
+ return pendingResult(event, String(events.length));
127
+ });
128
+ config.context = {
129
+ create: async () => ({
130
+ invocationId: "i".repeat(256),
131
+ correlationId: "correlation-1",
132
+ }),
133
+ };
134
+ const runtime = new MCPIRuntimeBase({
135
+ ...createMockProviders(),
136
+ environment: "development",
137
+ auditTrail: config,
138
+ });
139
+
140
+ await runtime.processToolCall("payments.send", {}, async () => ({ ok: true }));
141
+
142
+ expect(events.map((event) => event.eventId)).toHaveLength(2);
143
+ expect(events[0].eventId).not.toBe(events[1].eventId);
144
+ expect(events[0].eventId).toHaveLength(256);
145
+ expect(events[1].eventId).toHaveLength(256);
146
+ expect(events[0].eventId).toMatch(/:started$/);
147
+ expect(events[1].eventId).toMatch(/:completed$/);
148
+ });
149
+
150
+ it("does not execute the handler when required intent delivery rejects", async () => {
151
+ const runtime = runtimeWithAudit(async () => {
152
+ throw new Error("recorder unavailable");
153
+ });
154
+ const handler = vi.fn(async () => ({ ok: true }));
155
+
156
+ await expect(runtime.processToolCall("dangerous", {}, handler, {
157
+ id: "session",
158
+ nonce: "nonce",
159
+ audience: "client",
160
+ })).rejects.toThrow("recorder unavailable");
161
+ expect(handler).not.toHaveBeenCalled();
162
+ });
163
+
164
+ it("classifies inline consent as a challenged terminal event", async () => {
165
+ const events: AuditTrailEventInput[] = [];
166
+ const runtime = runtimeWithAudit(async (event) => {
167
+ events.push(event);
168
+ return pendingResult(event, String(events.length));
169
+ });
170
+
171
+ await runtime.processToolCall("protected", {}, async () => ({
172
+ structuredContent: { type: "consent_required" },
173
+ _meta: { ui: { resourceUri: "ui://kya-os-consent/authorize" } },
174
+ }), { id: "session", nonce: "nonce", audience: "client" });
175
+
176
+ expect(events.map((event) => event.eventType)).toEqual([
177
+ "tool.call.started",
178
+ "tool.call.challenged",
179
+ ]);
180
+ });
181
+
182
+ it("does not emit twice or rerun the handler when successful terminal delivery throws", async () => {
183
+ const events: AuditTrailEventInput[] = [];
184
+ const runtime = runtimeWithAudit(async (event) => {
185
+ events.push(event);
186
+ if (event.eventType === "tool.call.completed") {
187
+ throw new Error("required recorder unavailable");
188
+ }
189
+ return pendingResult(event);
190
+ });
191
+ const handler = vi.fn(async () => ({
192
+ content: [{ type: "text", text: "paid" }],
193
+ _meta: {
194
+ proof: { jws: "proof-is-preserved" },
195
+ foreignExtension: { enabled: true },
196
+ },
197
+ }));
198
+
199
+ const result = await runtime.processToolCall("payments.send", {}, handler, {
200
+ id: "session",
201
+ nonce: "nonce",
202
+ audience: "client",
203
+ });
204
+
205
+ expect(handler).toHaveBeenCalledTimes(1);
206
+ expect(events.map((event) => event.eventType)).toEqual([
207
+ "tool.call.started",
208
+ "tool.call.completed",
209
+ ]);
210
+ expect(result).toMatchObject({
211
+ isError: true,
212
+ _meta: {
213
+ proof: { jws: "proof-is-preserved" },
214
+ foreignExtension: { enabled: true },
215
+ "org.kya-os/audit": {
216
+ status: "degraded",
217
+ reason: "AUDIT_TERMINAL_DELIVERY_FAILED",
218
+ events: [{ eventType: "tool.call.started" }],
219
+ },
220
+ },
221
+ });
222
+ });
223
+
224
+ it("fails closed for primitive results after required terminal delivery failure", async () => {
225
+ const events: AuditTrailEventInput[] = [];
226
+ const runtime = runtimeWithAudit(async (event) => {
227
+ events.push(event);
228
+ if (event.eventType === "tool.call.completed") throw new Error("offline");
229
+ return pendingResult(event);
230
+ });
231
+ const handler = vi.fn(async () => "side-effect-complete");
232
+
233
+ await expect(runtime.processToolCall("payments.send", {}, handler)).rejects.toThrow(
234
+ "Required terminal audit delivery failed after tool execution",
235
+ );
236
+ expect(handler).toHaveBeenCalledTimes(1);
237
+ expect(events.map((event) => event.eventType)).toEqual([
238
+ "tool.call.started",
239
+ "tool.call.completed",
240
+ ]);
241
+ });
242
+ });
243
+
244
+ describe("HMAC audit references", () => {
245
+ it("is deterministic and does not expose capability-bearing identifiers", async () => {
246
+ const factory = createHmacRuntimeAuditContextFactory({
247
+ secret: "0123456789abcdef0123456789abcdef",
248
+ keyId: "audit-ref-2026-01",
249
+ randomUUID: () => "fallback-invocation",
250
+ });
251
+ const input = {
252
+ toolName: "payments.send",
253
+ args: {},
254
+ session: {
255
+ id: "session-secret",
256
+ clientDid: "did:key:zClient",
257
+ auditInvocationId: "request-secret",
258
+ auditCorrelationId: "flow-secret",
259
+ },
260
+ };
261
+
262
+ const first = await factory.create(input);
263
+ const second = await factory.create(input);
264
+
265
+ expect(second).toEqual(first);
266
+ expect(first.session?.ref.kind).toBe("keyed_commitment");
267
+ expect(first.actor).toEqual({ kind: "public_did", did: "did:key:zClient" });
268
+ const serialized = JSON.stringify(first);
269
+ expect(serialized).not.toContain("session-secret");
270
+ expect(serialized).not.toContain("request-secret");
271
+ expect(serialized).not.toContain("flow-secret");
272
+ });
273
+ });
274
+
275
+ describe("canonical consent and delegation events", () => {
276
+ it("records consent without copying request payload fields", async () => {
277
+ const events: AuditTrailEventInput[] = [];
278
+ await recordRuntimeConsentAudit(auditConfig(async (event) => {
279
+ events.push(event);
280
+ return pendingResult(event);
281
+ }), {
282
+ phase: "credential_failed",
283
+ outcome: "failed",
284
+ sessionId: "raw-session-secret",
285
+ userDid: "did:key:zUser",
286
+ reasonCode: "CREDENTIAL_AUTH_FAILED",
287
+ consentRef: "consent-reference",
288
+ });
289
+
290
+ expect(events).toHaveLength(1);
291
+ expect(events[0]).toMatchObject({
292
+ eventType: "credential.failed",
293
+ action: { category: "consent" },
294
+ outcome: "failed",
295
+ reason: { code: "CREDENTIAL_AUTH_FAILED" },
296
+ details: {
297
+ family: "consent",
298
+ phase: "credential_failed",
299
+ consentRef: "consent-reference",
300
+ },
301
+ });
302
+ expect(JSON.stringify(events[0])).not.toContain("raw-session-secret");
303
+ });
304
+
305
+ it("records delegation issuance as a separate event family", async () => {
306
+ const events: AuditTrailEventInput[] = [];
307
+ await recordRuntimeDelegationAudit(auditConfig(async (event) => {
308
+ events.push(event);
309
+ return pendingResult(event);
310
+ }), {
311
+ phase: "issued",
312
+ outcome: "succeeded",
313
+ sessionId: "session-secret",
314
+ delegationRef: "delegation-123",
315
+ });
316
+
317
+ expect(events[0]).toMatchObject({
318
+ eventType: "delegation.issued",
319
+ action: { category: "delegation" },
320
+ details: {
321
+ family: "delegation",
322
+ phase: "issued",
323
+ delegationRef: "delegation-123",
324
+ },
325
+ });
326
+ });
327
+ });
@@ -25,9 +25,6 @@ describe('MCPIRuntimeBase - Base Extensions', () => {
25
25
  session: {
26
26
  timestampSkewSeconds: 120,
27
27
  ttlMinutes: 30
28
- },
29
- audit: {
30
- enabled: false
31
28
  }
32
29
  };
33
30
  runtime = new MCPIRuntimeBase(config);
@@ -304,48 +301,6 @@ describe('MCPIRuntimeBase - Base Extensions', () => {
304
301
  });
305
302
  });
306
303
 
307
- describe('getAuditLogger', () => {
308
- it('should return logger with log method', () => {
309
- const logger = runtime.getAuditLogger();
310
- expect(logger).toBeDefined();
311
- expect(typeof logger.log).toBe('function');
312
- });
313
-
314
- it('should log through runtime audit system', async () => {
315
- const auditConfig = {
316
- ...config,
317
- audit: {
318
- enabled: true,
319
- logFunction: vi.fn(),
320
- includePayloads: true
321
- }
322
- };
323
- const auditRuntime = new MCPIRuntimeBase(auditConfig);
324
- await auditRuntime.initialize();
325
-
326
- const logger = auditRuntime.getAuditLogger();
327
- logger.log('test_event', { test: 'data' });
328
-
329
- expect(auditConfig.audit!.logFunction).toHaveBeenCalledWith(
330
- expect.stringContaining('test_event')
331
- );
332
- });
333
-
334
- it('should handle audit disabled', () => {
335
- const noAuditConfig = {
336
- ...config,
337
- audit: {
338
- enabled: false
339
- }
340
- };
341
- const noAuditRuntime = new MCPIRuntimeBase(noAuditConfig);
342
- const logger = noAuditRuntime.getAuditLogger();
343
-
344
- // Should not throw
345
- logger.log('test_event', { test: 'data' });
346
- });
347
- });
348
-
349
304
  describe('rotateKeys', () => {
350
305
  beforeEach(async () => {
351
306
  await runtime.initialize();
@@ -592,4 +547,3 @@ describe('MCPIRuntimeBase - Base Extensions', () => {
592
547
  });
593
548
  });
594
549
  });
595
-
@@ -28,11 +28,6 @@ describe("MCPIRuntimeBase", () => {
28
28
  timestampSkewSeconds: 120,
29
29
  ttlMinutes: 30,
30
30
  },
31
- audit: {
32
- enabled: true,
33
- logFunction: vi.fn(),
34
- includePayloads: true,
35
- },
36
31
  wellKnown: {
37
32
  enabled: true,
38
33
  serviceName: "Test Service",
@@ -75,24 +70,29 @@ describe("MCPIRuntimeBase", () => {
75
70
  expect(initializeFn).toHaveBeenCalled();
76
71
  });
77
72
 
78
- it("should log audit event on initialization", async () => {
73
+ it("should emit explicitly-labelled development diagnostics", async () => {
74
+ const diagnostic = vi.spyOn(console, "error").mockImplementation(() => {});
79
75
  await runtime.initialize();
80
-
81
- expect(config.audit!.logFunction).toHaveBeenCalledWith(
82
- expect.stringContaining("runtime_initialized")
76
+ expect(diagnostic).toHaveBeenCalledWith(
77
+ "[MCP-I diagnostic]",
78
+ expect.stringContaining("runtime_initialized"),
83
79
  );
84
-
85
- const logCall = (config.audit!.logFunction as any).mock.calls[0][0];
86
- const logData = JSON.parse(logCall);
80
+ const logData = JSON.parse(diagnostic.mock.calls[0][1] as string);
87
81
  expect(logData.event).toBe("runtime_initialized");
88
82
  expect(logData.data.did).toBe("did:key:zmock123");
89
83
  expect(logData.data.environment).toBe("development");
84
+ diagnostic.mockRestore();
90
85
  });
91
86
 
92
- it("should not log audit if disabled", async () => {
93
- config.audit!.enabled = false;
94
- await runtime.initialize();
95
- expect(config.audit!.logFunction).not.toHaveBeenCalled();
87
+ it("should suppress diagnostics in production", async () => {
88
+ const diagnostic = vi.spyOn(console, "error").mockImplementation(() => {});
89
+ const production = new MCPIRuntimeBase({ ...config, environment: "production" });
90
+ await production.initialize();
91
+ expect(diagnostic).not.toHaveBeenCalledWith(
92
+ "[MCP-I diagnostic]",
93
+ expect.any(String),
94
+ );
95
+ diagnostic.mockRestore();
96
96
  });
97
97
  });
98
98
 
@@ -131,10 +131,50 @@ describe("MCPIRuntimeBase", () => {
131
131
  expect(response.timestamp).toBe(
132
132
  (mockProviders.clockProvider as MockClockProvider).now()
133
133
  );
134
- expect(response.capabilities).toEqual(["identity", "proof", "audit"]);
134
+ expect(response.capabilities).toEqual(["identity", "proof"]);
135
+ expect(response.auditAssurance).toEqual({
136
+ enabled: false,
137
+ profile: "AAP-0",
138
+ });
135
139
  expect(response.signature).toBeDefined();
136
140
  });
137
141
 
142
+ it("should advertise only mechanically reported canonical audit assurance", async () => {
143
+ const capabilities = {
144
+ profile: "AAP-2" as const,
145
+ recorderTopology: "managed" as const,
146
+ delivery: "buffered" as const,
147
+ journalDurability: "durable" as const,
148
+ atomicAppend: true,
149
+ sourceHighWater: false,
150
+ merkleCheckpoints: false,
151
+ independentObservation: false,
152
+ supportingAnchors: [] as const,
153
+ evidenceRetention: "separate" as const,
154
+ };
155
+ config.auditTrail = {
156
+ sourceId: "source:test",
157
+ context: { create: vi.fn() },
158
+ trail: {
159
+ capabilities,
160
+ record: vi.fn(),
161
+ },
162
+ };
163
+
164
+ const response = await runtime.handleHandshake(handshakeRequest);
165
+
166
+ expect(response.capabilities).toEqual([
167
+ "identity",
168
+ "proof",
169
+ "audit-trail",
170
+ ]);
171
+ expect(response.auditAssurance).toEqual({
172
+ enabled: true,
173
+ profile: "AAP-2",
174
+ capabilities,
175
+ });
176
+ });
177
+
138
178
  it("should store session internally", async () => {
139
179
  const response = await runtime.handleHandshake(handshakeRequest);
140
180
  const session = await runtime.getCurrentSession();
@@ -296,10 +336,11 @@ describe("MCPIRuntimeBase", () => {
296
336
  expect(proof.audience).toBe("https://client.example.com");
297
337
  });
298
338
 
299
- it("should log audit event", async () => {
339
+ it("should label tool execution output as a diagnostic, not an audit record", async () => {
300
340
  const clock = mockProviders.clockProvider as MockClockProvider;
301
341
  const currentTime = Date.now();
302
342
  clock.setTime(currentTime);
343
+ const diagnostic = vi.spyOn(console, "error").mockImplementation(() => {});
303
344
 
304
345
  await runtime.processToolCall(
305
346
  "testTool",
@@ -308,21 +349,19 @@ describe("MCPIRuntimeBase", () => {
308
349
  session
309
350
  );
310
351
 
311
- expect(config.audit!.logFunction).toHaveBeenCalled();
312
-
313
- // Find the tool_executed log entry (might not be the first one)
314
- const logCalls = (config.audit!.logFunction as any).mock.calls;
315
- const toolLogCall = logCalls.find((call: any[]) => {
316
- const log = JSON.parse(call[0]);
352
+ const toolLogCall = diagnostic.mock.calls.find((call: any[]) => {
353
+ if (call[0] !== "[MCP-I diagnostic]") return false;
354
+ const log = JSON.parse(call[1]);
317
355
  return log.event === "tool_executed";
318
356
  });
319
357
 
320
358
  expect(toolLogCall).toBeDefined();
321
- const logData = JSON.parse(toolLogCall[0]);
359
+ const logData = JSON.parse(toolLogCall![1]);
322
360
  expect(logData.event).toBe("tool_executed");
323
361
  expect(logData.data.tool).toBe("testTool");
324
362
  expect(logData.data.sessionId).toBe("session123");
325
363
  expect(logData.data.timestamp).toBe(currentTime);
364
+ diagnostic.mockRestore();
326
365
  });
327
366
 
328
367
  it("should handle tool handler errors", async () => {
@@ -879,25 +918,6 @@ describe("MCPIRuntimeBase", () => {
879
918
  });
880
919
  });
881
920
 
882
- describe("getAuditLogger", () => {
883
- it("should return audit logger", () => {
884
- const logger = runtime.getAuditLogger();
885
- expect(logger).toBeDefined();
886
- expect(logger.log).toBeDefined();
887
- });
888
-
889
- it("should log through runtime audit", async () => {
890
- await runtime.initialize();
891
- const logger = runtime.getAuditLogger();
892
-
893
- logger.log("test_event", { test: "data" });
894
-
895
- expect(config.audit!.logFunction).toHaveBeenCalledWith(
896
- expect.stringContaining("test_event")
897
- );
898
- });
899
- });
900
-
901
921
  describe("rotateKeys", () => {
902
922
  beforeEach(async () => {
903
923
  await runtime.initialize();
@@ -915,78 +935,30 @@ describe("MCPIRuntimeBase", () => {
915
935
  expect(currentIdentity).toEqual(newIdentity);
916
936
  });
917
937
 
918
- it("should log audit event", async () => {
938
+ it("should emit key rotation only as a development diagnostic", async () => {
919
939
  const clock = mockProviders.clockProvider as MockClockProvider;
920
940
  const currentTime = Date.now();
921
941
  clock.setTime(currentTime);
942
+ const diagnostic = vi.spyOn(console, "error").mockImplementation(() => {});
922
943
 
923
944
  // Get the old identity first
924
945
  const oldIdentity = await runtime.getIdentity();
925
946
 
926
947
  await runtime.rotateKeys();
927
948
 
928
- expect(config.audit!.logFunction).toHaveBeenCalled();
929
-
930
- // Find the keys_rotated log entry
931
- const logCalls = (config.audit!.logFunction as any).mock.calls;
932
- const rotateLogCall = logCalls.find((call: any[]) => {
933
- const log = JSON.parse(call[0]);
949
+ const rotateLogCall = diagnostic.mock.calls.find((call: any[]) => {
950
+ if (call[0] !== "[MCP-I diagnostic]") return false;
951
+ const log = JSON.parse(call[1]);
934
952
  return log.event === "keys_rotated";
935
953
  });
936
954
 
937
955
  expect(rotateLogCall).toBeDefined();
938
- const logData = JSON.parse(rotateLogCall[0]);
956
+ const logData = JSON.parse(rotateLogCall![1]);
939
957
  expect(logData.event).toBe("keys_rotated");
940
958
  expect(logData.data.oldDid).toBe(oldIdentity.did);
941
959
  expect(logData.data.newDid).toBe("did:key:zmock456-1");
942
960
  expect(logData.data.timestamp).toBe(currentTime);
943
- });
944
- });
945
-
946
- describe("audit logging", () => {
947
- it("should use custom log function if provided", async () => {
948
- await runtime.initialize();
949
- expect(config.audit!.logFunction).toHaveBeenCalled();
950
- });
951
-
952
- it("should console.error if no custom function", async () => {
953
- const consoleErrorSpy = vi
954
- .spyOn(console, "error")
955
- .mockImplementation(() => {});
956
-
957
- config.audit!.logFunction = undefined;
958
- const runtimeNoLogFn = new MCPIRuntimeBase(config);
959
- await runtimeNoLogFn.initialize();
960
-
961
- expect(consoleErrorSpy).toHaveBeenCalledWith(
962
- "[AUDIT]",
963
- expect.any(String)
964
- );
965
- consoleErrorSpy.mockRestore();
966
- });
967
-
968
- it("should exclude payloads if configured", async () => {
969
- config.audit!.includePayloads = false;
970
- const runtimeNoPayloads = new MCPIRuntimeBase(config);
971
- await runtimeNoPayloads.initialize();
972
-
973
- const logCall = (config.audit!.logFunction as any).mock.calls[0][0];
974
- const logData = JSON.parse(logCall);
975
- expect(logData.data).toBeUndefined();
976
- });
977
-
978
- it("should include formatted timestamp", async () => {
979
- const clock = mockProviders.clockProvider as MockClockProvider;
980
- const currentTime = Date.now();
981
- clock.setTime(currentTime);
982
-
983
- await runtime.initialize();
984
-
985
- const logCall = (config.audit!.logFunction as any).mock.calls[0][0];
986
- const logData = JSON.parse(logCall);
987
- expect(logData.timestampFormatted).toBe(
988
- new Date(currentTime).toISOString()
989
- );
961
+ diagnostic.mockRestore();
990
962
  });
991
963
  });
992
964
 
@@ -1050,9 +1022,6 @@ describe("MCPIRuntimeBase", () => {
1050
1022
  timestampSkewSeconds: 120,
1051
1023
  ttlMinutes: 30,
1052
1024
  },
1053
- audit: {
1054
- enabled: false, // Disable audit for cleaner tests
1055
- },
1056
1025
  toolProtectionService: mockToolProtectionService,
1057
1026
  };
1058
1027
 
@@ -27,9 +27,6 @@ describe("Delegation Verification Flow", () => {
27
27
  timestampSkewSeconds: 120,
28
28
  ttlMinutes: 30,
29
29
  },
30
- audit: {
31
- enabled: false, // Disable audit for cleaner test output
32
- },
33
30
  };
34
31
  runtime = new MCPIRuntimeBase(config);
35
32
  await runtime.initialize();
@@ -156,4 +153,3 @@ describe("Delegation Verification Flow", () => {
156
153
  expect(session?.serverDid).not.toBe(agentDid); // ✅ Should NOT match agent DID
157
154
  });
158
155
  });
159
-