@happyvertical/smrt-app-mcp 0.60.18 → 0.61.0

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 (38) hide show
  1. package/AGENTS.md +12 -0
  2. package/README.md +40 -0
  3. package/agents/runtime-loading.md +21 -0
  4. package/dist/__smrt-register__.d.ts +2 -0
  5. package/dist/__smrt-register__.d.ts.map +1 -0
  6. package/dist/audit-store.d.ts +53 -0
  7. package/dist/audit-store.d.ts.map +1 -0
  8. package/dist/audit-store.js +149 -0
  9. package/dist/audit-store.js.map +1 -0
  10. package/dist/audit.d.ts +59 -0
  11. package/dist/audit.d.ts.map +1 -0
  12. package/dist/chunks/{protocol-BRQji5k_.js → defaults-i3kpRFpB.js} +190 -149
  13. package/dist/chunks/defaults-i3kpRFpB.js.map +1 -0
  14. package/dist/chunks/{errors-XG_zn1pP.js → errors-C704k8Mv.js} +3 -2
  15. package/dist/chunks/errors-C704k8Mv.js.map +1 -0
  16. package/dist/chunks/protocol-D_O2WaCO.js +153 -0
  17. package/dist/chunks/protocol-D_O2WaCO.js.map +1 -0
  18. package/dist/errors.d.ts +2 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/host-operations.js +1 -1
  21. package/dist/index.d.ts +2 -1
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +4 -3
  24. package/dist/index.js.map +1 -1
  25. package/dist/manifest.json +435 -3
  26. package/dist/server.d.ts +39 -0
  27. package/dist/server.d.ts.map +1 -1
  28. package/dist/smrt-knowledge.json +174 -8
  29. package/dist/smrt-knowledge.okf.md +17 -4
  30. package/dist/sveltekit.d.ts +1 -1
  31. package/dist/sveltekit.d.ts.map +1 -1
  32. package/dist/sveltekit.js +4 -3
  33. package/dist/sveltekit.js.map +1 -1
  34. package/dist/workflow-tools.d.ts +14 -0
  35. package/dist/workflow-tools.d.ts.map +1 -1
  36. package/package.json +14 -6
  37. package/dist/chunks/errors-XG_zn1pP.js.map +0 -1
  38. package/dist/chunks/protocol-BRQji5k_.js.map +0 -1
package/AGENTS.md CHANGED
@@ -13,6 +13,16 @@ tool policy; `./sveltekit` owns the stateless Streamable HTTP transport.
13
13
 
14
14
  ## Patterns
15
15
 
16
+ - Scopes, confirm and audit are server options (`toolScopes`, workflow
17
+ `requiredScopes`/`requiresConfirm`, `confirmTools`, `auditSink`,
18
+ `auditTenantId`). The scope check lives inside `passesToolPolicy` so tools and
19
+ resources share it and an anonymous caller never passes a scoped tool; the
20
+ confirm gate runs in `authorizeCall` before assertions and handlers and
21
+ answers as an `isError` result (`confirm_required`, audited `denied`). Audit
22
+ records hold argument KEY names only. `audit.ts` is model-free; the
23
+ `@smrt()` `McpCallAudit` model lives only behind the `./audit-store` subpath
24
+ (smrt#4957), never in the main entry.
25
+
16
26
  - Generate tools from core scoped to the allow-list (`MCPConfig.classNames`),
17
27
  then filter by allowed class names: a duplicate tool name among registered
18
28
  classes the app never publishes must not fail its catalog or calls (#3490).
@@ -80,3 +90,5 @@ tool policy; `./sveltekit` owns the stateless Streamable HTTP transport.
80
90
  - `mountMcpToolsRoute` and `mountMcpCallRoute` are deprecated REST-shaped
81
91
  compatibility aliases, not MCP transports.
82
92
  - This package is runtime app infrastructure, not the development MCP. Use `@happyvertical/smrt-dev-mcp` for agentic development knowledge, review, and architecture tooling.
93
+
94
+ HTTP transport loading: [agents/runtime-loading.md](agents/runtime-loading.md).
package/README.md CHANGED
@@ -268,6 +268,46 @@ workflowTools: [{
268
268
  }],
269
269
  ```
270
270
 
271
+ ### Tool scopes, confirm gate and persistent audit
272
+
273
+ Scoped credentials for external agents need no app-local policy parsing:
274
+
275
+ ```ts
276
+ createDefaultMcpAppServer({
277
+ models, requiredScopes: [], principalKinds: ['agent', 'owner'],
278
+ // glob pattern -> scopes the principal must hold (all of them)
279
+ toolScopes: { 'crm_*': ['crm.read'], mail_send: ['mail.send'] },
280
+ // refuse unless arguments.confirm === true (also: workflowTool.requiresConfirm)
281
+ confirmTools: ['*_send', '*_publish', '*_pay', '*_delete'],
282
+ auditSink: createSmrtMcpAuditStore({ smrtOptions }), // from '@happyvertical/smrt-app-mcp/audit-store'
283
+ auditTenantId: ({ principal }) => principal?.tenantId, // host-supplied; the default
284
+ });
285
+ ```
286
+
287
+ - **Scopes.** A workflow tool declares `requiredScopes`; the host may also map
288
+ patterns with `toolScopes`. A tool whose scopes the principal (`principal.scopes`)
289
+ does not hold is hidden from `tools/list` and denied (403) on call; this is
290
+ ANDed with `toolPolicy`. An anonymous caller holds none, so a scoped tool is
291
+ never public.
292
+ - **Confirm.** A gated tool is refused before any `workflowAssertions` or
293
+ handler runs unless `arguments.confirm === true`: the result is `isError` with
294
+ `structuredContent.error.code === 'confirm_required'`, audited `denied`.
295
+ Discovery advertises a boolean `confirm` property. For generated tools the
296
+ `confirm` flag is consumed by the gate and not forwarded.
297
+ - **Audit.** `onToolCall` events now also carry `tenantId`, `argumentKeys`
298
+ and `occurredAt`; `auditSink.record(record)` receives the persistable
299
+ `McpAuditRecord` (`principalId`, `principalKind`, `tool`, `tenantId`,
300
+ `outcome: 'allowed' | 'denied' | 'error'`, `errorCode?`, `argumentKeys`,
301
+ `occurredAt`, plus `identityIssuer`/`identitySubject`/`identityClientId` when the adapter stamped a verified identity): argument key names only, never values. Anonymous unknown-tool denials reach `onToolCall` but are not persisted to the sink. A throwing `auditTenantId` falls back to `principal.tenantId`. Task lifecycle calls re-check the originating tool's scopes. Patterns in `toolScopes`/`confirmTools` that match no tool log a one-time warning. A tool result with
302
+ `isError` records `error`, or `denied` for `forbidden`, `confirm_required` and
303
+ access-denial codes. Sink failures go to `onToolCallHookError`. Anonymous 401 calls are always persisted when a sink is configured, so hosts should rate-limit the endpoint; anonymous unknown-tool (404) denials go to `onToolCall` only. Scopes make `tools/list` principal-dependent, so its cache hint is forced `private` whenever any scope is declared.
304
+ - **Persistent store.** `createSmrtMcpAuditStore({ smrtOptions })` (subpath
305
+ `./audit-store`, registers the tenant-scoped `McpCallAudit` model, table
306
+ `smrt_mcp_call_audits`) is a sink with `list({ tenantId, principalId?, tool?,
307
+ outcome?, limit? })`; `tenantId` is mandatory (`null` lists global rows).
308
+ Run your schema bootstrap/migrations so the table exists. Implement
309
+ `McpAuditSink` for any other store; `createInMemoryMcpAuditSink()` suits tests.
310
+
271
311
  ### Host operations, audit and typed errors
272
312
 
273
313
  `@happyvertical/smrt-app-mcp/host-operations` (browser-safe, dependency-free)
@@ -0,0 +1,21 @@
1
+ # HTTP transport loading
2
+
3
+ The `sveltekit` entry imports the MCP SDK and its protocol adapter at the existing
4
+ async request dispatch boundary. Task interception loads the same SDK classifier
5
+ and the same protocol extension constant only when a task envelope needs them.
6
+ Route construction, runtime-binding validation and `.server` remain synchronous;
7
+ public `createMcpProtocolServer` remains synchronous on its existing entry.
8
+ Origin/auth checks still precede dispatch and an SDK load failure still rejects
9
+ with its original cause at first use. No auth or task policy is duplicated.
10
+
11
+ The fresh-Node published-entry regression refuses SDK resolution, mounts the
12
+ route, proves a cross-origin denial still returns 403, then proves an eligible
13
+ request gets that exact SDK load error. It fails against the eager build. The
14
+ full package suite retains the SDK wire, effects, actor × tenant, binding,
15
+ extension, async Tasks and revision/header refusal tests (359 tests including the startup guard). Runtime: Node 26, existing SQLite/injected executors;
16
+ no persistence, transaction or dialect behavior changes.
17
+
18
+ Reuse inspection: MCP package review, intent index and searches for
19
+ `mountMcpAppRoute`, `createMcpHandler`, SDK imports, `maybeHandleTaskRequest` and
20
+ protocol request factories found these existing seams. Only their import timing
21
+ changes; no new production component, helper, model, route or type is added.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=__smrt-register__.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"__smrt-register__.d.ts","sourceRoot":"","sources":["../src/__smrt-register__.ts"],"names":[],"mappings":""}
@@ -0,0 +1,53 @@
1
+ import './__smrt-register__.js';
2
+ import { SmrtCollection, SmrtObject } from '@happyvertical/smrt-core';
3
+ import type { McpAuditOutcome, McpAuditQuery, McpAuditRecord, McpAuditSink } from './audit.js';
4
+ /**
5
+ * One persisted MCP tool call. Stores identity, tool, tenant, outcome and
6
+ * argument KEY names only: never argument values or response bodies.
7
+ */
8
+ export declare class McpCallAudit extends SmrtObject {
9
+ /** The tenant the call ran for; `null` for a global/anonymous call. */
10
+ tenantId: string | null | undefined;
11
+ /** The principal id (credential id); `null` for an anonymous call. */
12
+ principalId: string | null;
13
+ /** The principal kind (agent, owner, user, ...); `null` when unknown. */
14
+ principalKind: string | null;
15
+ identityIssuer: string | null;
16
+ identitySubject: string | null;
17
+ identityClientId: string | null;
18
+ tool: string;
19
+ outcome: McpAuditOutcome;
20
+ errorCode: string | null;
21
+ argumentKeys: string[];
22
+ occurredAt: Date;
23
+ }
24
+ /** Tenant-aware persistence and queries for {@link McpCallAudit}. */
25
+ export declare class McpCallAuditCollection extends SmrtCollection<McpCallAudit> {
26
+ static readonly _itemClass: typeof McpCallAudit;
27
+ /** Persist one record under its own tenant (or the global scope). */
28
+ append(record: McpAuditRecord): Promise<McpCallAudit>;
29
+ /**
30
+ * Newest-first records for one tenant, optionally narrowed by principal,
31
+ * tool or outcome. `tenantId` is mandatory: `null` lists global rows.
32
+ */
33
+ listAudits(query: McpAuditQuery & {
34
+ tenantId: string | null;
35
+ }): Promise<(McpAuditRecord & {
36
+ id: string;
37
+ })[]>;
38
+ }
39
+ /** Options for {@link createSmrtMcpAuditStore}. */
40
+ export interface SmrtMcpAuditStoreOptions {
41
+ /** SMRT options bag (`{ db }`), the same one `smrtOptions` supplies. */
42
+ smrtOptions: () => Record<string, unknown>;
43
+ }
44
+ /**
45
+ * The default persistent audit sink: a SMRT-model-backed, tenant-aware store.
46
+ * Pass it as `auditSink` and read it back with `list`.
47
+ */
48
+ export declare function createSmrtMcpAuditStore(options: SmrtMcpAuditStoreOptions): McpAuditSink & {
49
+ list(query: McpAuditQuery & {
50
+ tenantId: string | null;
51
+ }): ReturnType<McpCallAuditCollection['listAudits']>;
52
+ };
53
+ //# s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AM,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC5C;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,wBAAwB,GAChC,YAAY,GAAG;IAChB,IAAI,CACF,KAAK,EAAE,aAAa,GAAG;QAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,GACjD,UAAU,CAAC,sBAAsB,CAAC,YAAY,CAAC,CAAC,CAAC;CACrD,CAeA"}
@@ -0,0 +1,149 @@
1
+ import { ObjectRegistry, SmrtCollection, SmrtObject, field, smrt } from "@happyvertical/smrt-core";
2
+ import { TenantScoped, tenantId, withSystemContext, withTenant } from "@happyvertical/smrt-tenancy";
3
+ //#region src/__smrt-register__.ts
4
+ ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-app-mcp","packageVersion":"0.61.0","objects":{"@happyvertical/smrt-app-mcp:McpCallAudit":{"name":"mcpcallaudit","className":"McpCallAudit","qualifiedName":"@happyvertical/smrt-app-mcp:McpCallAudit","collection":"mcpcallaudits","description":"One persisted MCP tool call. Stores identity, tool, tenant, outcome and argument KEY names only: never argument values or response bodies.","filePath":"/home/runner/work/smrt/smrt/packages/smrt-app-mcp/src/audit-store.ts","packageName":"@happyvertical/smrt-app-mcp","fields":{"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"principalId":{"type":"text","required":false,"_meta":{"nullable":true}},"principalKind":{"type":"text","required":false,"_meta":{"nullable":true}},"identityIssuer":{"type":"text","required":false,"_meta":{"nullable":true}},"identitySubject":{"type":"text","required":false,"_meta":{"nullable":true}},"identityClientId":{"type":"text","required":false,"_meta":{"nullable":true}},"tool":{"type":"text","required":true,"default":"","_meta":{"required":true,"default":""}},"outcome":{"type":"text","required":true,"default":"allowed","_meta":{"required":true,"default":"allowed"},"enum":["allowed","denied","error"]},"errorCode":{"type":"text","required":false,"_meta":{"nullable":true}},"argumentKeys":{"type":"json","required":false,"_meta":{}},"occurredAt":{"type":"datetime","required":true,"_meta":{"required":true}}},"methods":{},"decoratorConfig":{"tableName":"smrt_mcp_call_audits","api":false,"mcp":false,"cli":false,"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"McpCallAudit","collectionExportName":"McpCallAuditCollection","validationRules":[{"field":"tool","rule":"required","fieldType":"text"},{"field":"outcome","rule":"required","fieldType":"text"},{"field":"occurredAt","rule":"required","fieldType":"datetime"}],"schema":{"tableName":"smrt_mcp_call_audits","ddl":"CREATE TABLE IF NOT EXISTS \\"smrt_mcp_call_audits\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"principal_id\\" TEXT,\\n \\"principal_kind\\" TEXT,\\n \\"identity_issuer\\" TEXT,\\n \\"identity_subject\\" TEXT,\\n \\"identity_client_id\\" TEXT,\\n \\"tool\\" TEXT NOT NULL DEFAULT '',\\n \\"outcome\\" TEXT NOT NULL DEFAULT 'allowed',\\n \\"error_code\\" TEXT,\\n \\"argument_keys\\" JSON,\\n \\"occurred_at\\" TIMESTAMP NOT NULL\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"principal_id":{"type":"TEXT","notNull":false,"unique":false},"principal_kind":{"type":"TEXT","notNull":false,"unique":false},"identity_issuer":{"type":"TEXT","notNull":false,"unique":false},"identity_subject":{"type":"TEXT","notNull":false,"unique":false},"identity_client_id":{"type":"TEXT","notNull":false,"unique":false},"tool":{"type":"TEXT","notNull":true,"unique":false,"default":""},"outcome":{"type":"TEXT","notNull":true,"unique":false,"default":"allowed"},"error_code":{"type":"TEXT","notNull":false,"unique":false},"argument_keys":{"type":"JSON","notNull":false,"unique":false},"occurred_at":{"type":"TIMESTAMP","notNull":true,"unique":false}},"indexes":[{"name":"smrt_mcp_call_audits_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"smrt_mcp_call_audits_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"e0a722bb"},"importPath":"@happyvertical/smrt-app-mcp/audit-store"},"@happyvertical/smrt-app-mcp:McpCallAuditCollection":{"name":"mcpcallauditcollection","className":"McpCallAuditCollection","qualifiedName":"@happyvertical/smrt-app-mcp:McpCallAuditCollection","collection":"mcpcallaudits","description":"Tenant-aware persistence and queries for McpCallAudit.","filePath":"/home/runner/work/smrt/smrt/packages/smrt-app-mcp/src/audit-store.ts","packageName":"@happyvertical/smrt-app-mcp","fields":{},"methods":{"append":{"name":"append","async":true,"parameters":[{"name":"record","type":"McpAuditRecord","optional":false}],"returnType":"Promise<McpCallAudit>","isStatic":false,"isPublic":true},"listAudits":{"name":"listAudits","async":true,"parameters":[{"name":"query","type":"any","optional":false,"typeUnresolved":true}],"returnType":"any","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"smrt_mcp_call_audits","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"McpCallAudit","exportName":"McpCallAuditCollection","collectionExportName":"McpCallAuditCollectionCollection","collectionOf":"@happyvertical/smrt-app-mcp:McpCallAudit","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"smrt_mcp_call_audits","ddl":"CREATE TABLE IF NOT EXISTS \\"smrt_mcp_call_audits\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"principal_id\\" TEXT,\\n \\"principal_kind\\" TEXT,\\n \\"identity_issuer\\" TEXT,\\n \\"identity_subject\\" TEXT,\\n \\"identity_client_id\\" TEXT,\\n \\"tool\\" TEXT NOT NULL DEFAULT '',\\n \\"outcome\\" TEXT NOT NULL DEFAULT 'allowed',\\n \\"error_code\\" TEXT,\\n \\"argument_keys\\" JSON,\\n \\"occurred_at\\" TIMESTAMP NOT NULL\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"principal_id":{"type":"TEXT","notNull":false,"unique":false},"principal_kind":{"type":"TEXT","notNull":false,"unique":false},"identity_issuer":{"type":"TEXT","notNull":false,"unique":false},"identity_subject":{"type":"TEXT","notNull":false,"unique":false},"identity_client_id":{"type":"TEXT","notNull":false,"unique":false},"tool":{"type":"TEXT","notNull":true,"unique":false,"default":""},"outcome":{"type":"TEXT","notNull":true,"unique":false,"default":"allowed"},"error_code":{"type":"TEXT","notNull":false,"unique":false},"argument_keys":{"type":"JSON","notNull":false,"unique":false},"occurred_at":{"type":"TIMESTAMP","notNull":true,"unique":false}},"indexes":[{"name":"smrt_mcp_call_audits_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"smrt_mcp_call_audits_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"e0a722bb"},"importPath":"@happyvertical/smrt-app-mcp/audit-store"}},"moduleType":"smrt","smrtDependencies":["@happyvertical/smrt-core","@happyvertical/smrt-jobs","@happyvertical/smrt-tenancy"],"stampsConstructors":true}`));
5
+ //#endregion
6
+ //#region src/audit-store.ts
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
10
+ enumerable: true,
11
+ configurable: true,
12
+ writable: true,
13
+ value
14
+ }) : obj[key] = value;
15
+ var __decorateClass = (decorators, target, key, kind) => {
16
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
17
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
18
+ if (kind && result) __defProp(target, key, result);
19
+ return result;
20
+ };
21
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
+ var McpCallAudit = class extends SmrtObject {
23
+ tenantId = void 0;
24
+ principalId = null;
25
+ principalKind = null;
26
+ identityIssuer = null;
27
+ identitySubject = null;
28
+ identityClientId = null;
29
+ tool = "";
30
+ outcome = "allowed";
31
+ errorCode = null;
32
+ argumentKeys = [];
33
+ occurredAt = /* @__PURE__ */ new Date();
34
+ };
35
+ __publicField(McpCallAudit, "__smrtPackage__", "@happyvertical/smrt-app-mcp");
36
+ __decorateClass([tenantId({ nullable: true })], McpCallAudit.prototype, "tenantId", 2);
37
+ __decorateClass([field({
38
+ type: "text",
39
+ nullable: true
40
+ })], McpCallAudit.prototype, "principalId", 2);
41
+ __decorateClass([field({
42
+ type: "text",
43
+ nullable: true
44
+ })], McpCallAudit.prototype, "principalKind", 2);
45
+ __decorateClass([field({
46
+ type: "text",
47
+ nullable: true
48
+ })], McpCallAudit.prototype, "identityIssuer", 2);
49
+ __decorateClass([field({
50
+ type: "text",
51
+ nullable: true
52
+ })], McpCallAudit.prototype, "identitySubject", 2);
53
+ __decorateClass([field({
54
+ type: "text",
55
+ nullable: true
56
+ })], McpCallAudit.prototype, "identityClientId", 2);
57
+ __decorateClass([field({
58
+ type: "text",
59
+ required: true,
60
+ default: ""
61
+ })], McpCallAudit.prototype, "tool", 2);
62
+ __decorateClass([field({
63
+ type: "text",
64
+ required: true,
65
+ default: "allowed"
66
+ })], McpCallAudit.prototype, "outcome", 2);
67
+ __decorateClass([field({
68
+ type: "text",
69
+ nullable: true
70
+ })], McpCallAudit.prototype, "errorCode", 2);
71
+ __decorateClass([field({ type: "json" })], McpCallAudit.prototype, "argumentKeys", 2);
72
+ __decorateClass([field({
73
+ type: "datetime",
74
+ required: true
75
+ })], McpCallAudit.prototype, "occurredAt", 2);
76
+ McpCallAudit = __decorateClass([smrt({
77
+ tableName: "smrt_mcp_call_audits",
78
+ api: false,
79
+ mcp: false,
80
+ cli: false
81
+ }), TenantScoped({ mode: "optional" })], McpCallAudit);
82
+ var DEFAULT_LIMIT = 100;
83
+ var MAX_LIMIT = 500;
84
+ var McpCallAuditCollection = class extends SmrtCollection {
85
+ static _itemClass = McpCallAudit;
86
+ /** Persist one record under its own tenant (or the global scope). */
87
+ async append(record) {
88
+ const write = () => this.create({
89
+ tenantId: record.tenantId,
90
+ principalId: record.principalId,
91
+ principalKind: record.principalKind,
92
+ identityIssuer: record.identityIssuer ?? null,
93
+ identitySubject: record.identitySubject ?? null,
94
+ identityClientId: record.identityClientId ?? null,
95
+ tool: record.tool,
96
+ outcome: record.outcome,
97
+ errorCode: record.errorCode ?? null,
98
+ argumentKeys: [...record.argumentKeys],
99
+ occurredAt: record.occurredAt
100
+ });
101
+ return record.tenantId ? withTenant({ tenantId: record.tenantId }, write) : withSystemContext(write);
102
+ }
103
+ /**
104
+ * Newest-first records for one tenant, optionally narrowed by principal,
105
+ * tool or outcome. `tenantId` is mandatory: `null` lists global rows.
106
+ */
107
+ async listAudits(query) {
108
+ if (query.tenantId === void 0) throw new TypeError("listAudits requires an explicit tenantId.");
109
+ const limit = Math.min(Math.max(Math.trunc(query.limit ?? DEFAULT_LIMIT), 1), MAX_LIMIT);
110
+ const where = { tenantId: query.tenantId };
111
+ if (query.principalId !== void 0) where.principalId = query.principalId;
112
+ if (query.tool !== void 0) where.tool = query.tool;
113
+ if (query.outcome !== void 0) where.outcome = query.outcome;
114
+ const read = () => this.list({
115
+ where,
116
+ orderBy: "occurred_at DESC",
117
+ limit
118
+ });
119
+ return (query.tenantId ? await withTenant({ tenantId: query.tenantId }, read) : await withSystemContext(read)).map((row) => ({
120
+ id: String(row.id),
121
+ principalId: row.principalId ?? null,
122
+ principalKind: row.principalKind ?? null,
123
+ tool: row.tool,
124
+ tenantId: row.tenantId ?? null,
125
+ outcome: row.outcome,
126
+ ...row.errorCode ? { errorCode: row.errorCode } : {},
127
+ ...row.identityIssuer ? { identityIssuer: row.identityIssuer } : {},
128
+ ...row.identitySubject ? { identitySubject: row.identitySubject } : {},
129
+ ...row.identityClientId ? { identityClientId: row.identityClientId } : {},
130
+ argumentKeys: Array.isArray(row.argumentKeys) ? row.argumentKeys : [],
131
+ occurredAt: new Date(row.occurredAt)
132
+ }));
133
+ }
134
+ };
135
+ function createSmrtMcpAuditStore(options) {
136
+ const get = () => McpCallAuditCollection.create(options.smrtOptions());
137
+ return {
138
+ async record(record) {
139
+ await (await get()).append(record);
140
+ },
141
+ async list(query) {
142
+ return (await get()).listAudits(query);
143
+ }
144
+ };
145
+ }
146
+ //#endregion
147
+ export { McpCallAudit, McpCallAuditCollection, createSmrtMcpAuditStore };
148
+
149
+ //# sourceMappingURL=audit-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit-store.js","names":[],"sources":["../src/__smrt-register__.ts","../src/audit-store.ts"],"sourcesContent":["// Generated by @happyvertical/smrt-core smrtPlugin at library build time.\n// The package manifest is inlined so self-registration cannot miss when a\n// downstream bundler relocates this module away from dist/manifest.json\n// (https://github.com/happyvertical/smrt/issues/1506,\n// https://github.com/happyvertical/smrt/issues/1507).\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\nObjectRegistry.registerPackageManifest(JSON.parse(\"{\\\"version\\\":\\\"1.0.0\\\",\\\"timestamp\\\":0,\\\"packageName\\\":\\\"@happyvertical/smrt-app-mcp\\\",\\\"packageVersion\\\":\\\"0.61.0\\\",\\\"objects\\\":{\\\"@happyvertical/smrt-app-mcp:McpCallAudit\\\":{\\\"name\\\":\\\"mcpcallaudit\\\",\\\"className\\\":\\\"McpCallAudit\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-app-mcp:McpCallAudit\\\",\\\"collection\\\":\\\"mcpcallaudits\\\",\\\"description\\\":\\\"One persisted MCP tool call. Stores identity, tool, tenant, outcome and argument KEY names only: never argument values or response bodies.\\\",\\\"filePath\\\":\\\"/home/runner/work/smrt/smrt/packages/smrt-app-mcp/src/audit-store.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-app-mcp\\\",\\\"fields\\\":{\\\"tenantId\\\":{\\\"type\\\":\\\"text\\\",\\\"required\\\":false,\\\"_meta\\\":{\\\"sqlType\\\":\\\"UUID\\\",\\\"nullable\\\":true,\\\"__tenancy\\\":{\\\"isTenantIdField\\\":true,\\\"autoFilter\\\":true,\\\"required\\\":false,\\\"autoPopulate\\\":true,\\\"nullable\\\":true,\\\"mode\\\":\\\"optional\\\",\\\"field\\\":\\\"tenantId\\\",\\\"allowSuperAdminBypass\\\":false}}},\\\"principalId\\\":{\\\"type\\\":\\\"text\\\",\\\"required\\\":false,\\\"_meta\\\":{\\\"nullable\\\":true}},\\\"principalKind\\\":{\\\"type\\\":\\\"text\\\",\\\"required\\\":false,\\\"_meta\\\":{\\\"nullable\\\":true}},\\\"identityIssuer\\\":{\\\"type\\\":\\\"text\\\",\\\"required\\\":false,\\\"_meta\\\":{\\\"nullable\\\":true}},\\\"identitySubject\\\":{\\\"type\\\":\\\"text\\\",\\\"required\\\":false,\\\"_meta\\\":{\\\"nullable\\\":true}},\\\"identityClientId\\\":{\\\"type\\\":\\\"text\\\",\\\"required\\\":false,\\\"_meta\\\":{\\\"nullable\\\":true}},\\\"tool\\\":{\\\"type\\\":\\\"text\\\",\\\"required\\\":true,\\\"default\\\":\\\"\\\",\\\"_meta\\\":{\\\"required\\\":true,\\\"default\\\":\\\"\\\"}},\\\"outcome\\\":{\\\"type\\\":\\\"text\\\",\\\"required\\\":true,\\\"default\\\":\\\"allowed\\\",\\\"_meta\\\":{\\\"required\\\":true,\\\"default\\\":\\\"allowed\\\"},\\\"enum\\\":[\\\"allowed\\\",\\\"denied\\\",\\\"error\\\"]},\\\"errorCode\\\":{\\\"type\\\":\\\"text\\\",\\\"required\\\":false,\\\"_meta\\\":{\\\"nullable\\\":true}},\\\"argumentKeys\\\":{\\\"type\\\":\\\"json\\\",\\\"required\\\":false,\\\"_meta\\\":{}},\\\"occurredAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"required\\\":true,\\\"_meta\\\":{\\\"required\\\":true}}},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"smrt_mcp_call_audits\\\",\\\"api\\\":false,\\\"mcp\\\":false,\\\"cli\\\":false,\\\"tenantScoped\\\":{\\\"mode\\\":\\\"optional\\\"},\\\"conflictColumns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"]},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"McpCallAudit\\\",\\\"collectionExportName\\\":\\\"McpCallAuditCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"tool\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"outcome\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"occurredAt\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"datetime\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"smrt_mcp_call_audits\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"smrt_mcp_call_audits\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID,\\\\n \\\\\\\"principal_id\\\\\\\" TEXT,\\\\n \\\\\\\"principal_kind\\\\\\\" TEXT,\\\\n \\\\\\\"identity_issuer\\\\\\\" TEXT,\\\\n \\\\\\\"identity_subject\\\\\\\" TEXT,\\\\n \\\\\\\"identity_client_id\\\\\\\" TEXT,\\\\n \\\\\\\"tool\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"outcome\\\\\\\" TEXT NOT NULL DEFAULT 'allowed',\\\\n \\\\\\\"error_code\\\\\\\" TEXT,\\\\n \\\\\\\"argument_keys\\\\\\\" JSON,\\\\n \\\\\\\"occurred_at\\\\\\\" TIMESTAMP NOT NULL\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"principal_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"principal_kind\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"identity_issuer\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"identity_subject\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"identity_client_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"tool\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"\\\"},\\\"outcome\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"allowed\\\"},\\\"error_code\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"argument_keys\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"occurred_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"smrt_mcp_call_audits_slug_context_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true,\\\"nullsNotDistinct\\\":true},{\\\"name\\\":\\\"smrt_mcp_call_audits_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]}],\\\"version\\\":\\\"e0a722bb\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-app-mcp/audit-store\\\"},\\\"@happyvertical/smrt-app-mcp:McpCallAuditCollection\\\":{\\\"name\\\":\\\"mcpcallauditcollection\\\",\\\"className\\\":\\\"McpCallAuditCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-app-mcp:McpCallAuditCollection\\\",\\\"collection\\\":\\\"mcpcallaudits\\\",\\\"description\\\":\\\"Tenant-aware persistence and queries for McpCallAudit.\\\",\\\"filePath\\\":\\\"/home/runner/work/smrt/smrt/packages/smrt-app-mcp/src/audit-store.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-app-mcp\\\",\\\"fields\\\":{},\\\"methods\\\":{\\\"append\\\":{\\\"name\\\":\\\"append\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"record\\\",\\\"type\\\":\\\"McpAuditRecord\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<McpCallAudit>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"listAudits\\\":{\\\"name\\\":\\\"listAudits\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"query\\\",\\\"type\\\":\\\"any\\\",\\\"optional\\\":false,\\\"typeUnresolved\\\":true}],\\\"returnType\\\":\\\"any\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true}},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"smrt_mcp_call_audits\\\",\\\"api\\\":false,\\\"mcp\\\":false,\\\"cli\\\":false},\\\"extends\\\":\\\"SmrtCollection\\\",\\\"extendsTypeArg\\\":\\\"McpCallAudit\\\",\\\"exportName\\\":\\\"McpCallAuditCollection\\\",\\\"collectionExportName\\\":\\\"McpCallAuditCollectionCollection\\\",\\\"collectionOf\\\":\\\"@happyvertical/smrt-app-mcp:McpCallAudit\\\",\\\"inheritedExposure\\\":[\\\"api\\\",\\\"mcp\\\",\\\"cli\\\"],\\\"schema\\\":{\\\"tableName\\\":\\\"smrt_mcp_call_audits\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"smrt_mcp_call_audits\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID,\\\\n \\\\\\\"principal_id\\\\\\\" TEXT,\\\\n \\\\\\\"principal_kind\\\\\\\" TEXT,\\\\n \\\\\\\"identity_issuer\\\\\\\" TEXT,\\\\n \\\\\\\"identity_subject\\\\\\\" TEXT,\\\\n \\\\\\\"identity_client_id\\\\\\\" TEXT,\\\\n \\\\\\\"tool\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"outcome\\\\\\\" TEXT NOT NULL DEFAULT 'allowed',\\\\n \\\\\\\"error_code\\\\\\\" TEXT,\\\\n \\\\\\\"argument_keys\\\\\\\" JSON,\\\\n \\\\\\\"occurred_at\\\\\\\" TIMESTAMP NOT NULL\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"principal_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"principal_kind\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"identity_issuer\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"identity_subject\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"identity_client_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"tool\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"\\\"},\\\"outcome\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"allowed\\\"},\\\"error_code\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"argument_keys\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"occurred_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"smrt_mcp_call_audits_slug_context_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true,\\\"nullsNotDistinct\\\":true},{\\\"name\\\":\\\"smrt_mcp_call_audits_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]}],\\\"version\\\":\\\"e0a722bb\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-app-mcp/audit-store\\\"}},\\\"moduleType\\\":\\\"smrt\\\",\\\"smrtDependencies\\\":[\\\"@happyvertical/smrt-core\\\",\\\"@happyvertical/smrt-jobs\\\",\\\"@happyvertical/smrt-tenancy\\\"],\\\"stampsConstructors\\\":true}\"));\n","// Self-register this package's manifest for consumers that import via this\n// subpath without the main entry (smrt#1132).\nimport './__smrt-register__.js';\n\nimport {\n field,\n SmrtCollection,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport {\n TenantScoped,\n tenantId,\n withSystemContext,\n withTenant,\n} from '@happyvertical/smrt-tenancy';\nimport type {\n McpAuditOutcome,\n McpAuditQuery,\n McpAuditRecord,\n McpAuditSink,\n} from './audit.js';\n\n/**\n * One persisted MCP tool call. Stores identity, tool, tenant, outcome and\n * argument KEY names only: never argument values or response bodies.\n */\n@smrt({\n tableName: 'smrt_mcp_call_audits',\n // Audit rows are read through `McpCallAuditCollection.listAudits`, which\n // requires an explicit tenant; no generated read surface (fail closed).\n api: false,\n mcp: false,\n cli: false,\n})\n@TenantScoped({ mode: 'optional' })\nexport class McpCallAudit extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-app-mcp\";\n /** The tenant the call ran for; `null` for a global/anonymous call. */\n @tenantId({ nullable: true })\n tenantId: string | null | undefined = undefined;\n\n /** The principal id (credential id); `null` for an anonymous call. */\n @field({ type: 'text', nullable: true })\n principalId: string | null = null;\n\n /** The principal kind (agent, owner, user, ...); `null` when unknown. */\n @field({ type: 'text', nullable: true })\n principalKind: string | null = null;\n\n @field({ type: 'text', nullable: true })\n identityIssuer: string | null = null;\n\n @field({ type: 'text', nullable: true })\n identitySubject: string | null = null;\n\n @field({ type: 'text', nullable: true })\n identityClientId: string | null = null;\n\n @field({ type: 'text', required: true, default: '' })\n tool = '';\n\n @field({ type: 'text', required: true, default: 'allowed' })\n outcome: McpAuditOutcome = 'allowed';\n\n @field({ type: 'text', nullable: true })\n errorCode: string | null = null;\n\n @field({ type: 'json' })\n argumentKeys: string[] = [];\n\n @field({ type: 'datetime', required: true })\n occurredAt: Date = new Date();\n}\n\nconst DEFAULT_LIMIT = 100;\nconst MAX_LIMIT = 500;\n\n/** Tenant-aware persistence and queries for {@link McpCallAudit}. */\nexport class McpCallAuditCollection extends SmrtCollection<McpCallAudit> {\n static readonly _itemClass = McpCallAudit;\n\n /** Persist one record under its own tenant (or the global scope). */\n async append(record: McpAuditRecord): Promise<McpCallAudit> {\n const write = () =>\n this.create({\n tenantId: record.tenantId,\n principalId: record.principalId,\n principalKind: record.principalKind,\n identityIssuer: record.identityIssuer ?? null,\n identitySubject: record.identitySubject ?? null,\n identityClientId: record.identityClientId ?? null,\n tool: record.tool,\n outcome: record.outcome,\n errorCode: record.errorCode ?? null,\n argumentKeys: [...record.argumentKeys],\n occurredAt: record.occurredAt,\n });\n return record.tenantId\n ? withTenant({ tenantId: record.tenantId }, write)\n : withSystemContext(write);\n }\n\n /**\n * Newest-first records for one tenant, optionally narrowed by principal,\n * tool or outcome. `tenantId` is mandatory: `null` lists global rows.\n */\n async listAudits(query: McpAuditQuery & { tenantId: string | null }) {\n if (query.tenantId === undefined) {\n throw new TypeError('listAudits requires an explicit tenantId.');\n }\n const limit = Math.min(\n Math.max(Math.trunc(query.limit ?? DEFAULT_LIMIT), 1),\n MAX_LIMIT,\n );\n const where: Record<string, unknown> = { tenantId: query.tenantId };\n if (query.principalId !== undefined) where.principalId = query.principalId;\n if (query.tool !== undefined) where.tool = query.tool;\n if (query.outcome !== undefined) where.outcome = query.outcome;\n const read = () => this.list({ where, orderBy: 'occurred_at DESC', limit });\n const rows = query.tenantId\n ? await withTenant({ tenantId: query.tenantId }, read)\n : await withSystemContext(read);\n return rows.map((row): McpAuditRecord & { id: string } => ({\n id: String(row.id),\n principalId: row.principalId ?? null,\n principalKind: row.principalKind ?? null,\n tool: row.tool,\n tenantId: row.tenantId ?? null,\n outcome: row.outcome,\n ...(row.errorCode ? { errorCode: row.errorCode } : {}),\n ...(row.identityIssuer ? { identityIssuer: row.identityIssuer } : {}),\n ...(row.identitySubject ? { identitySubject: row.identitySubject } : {}),\n ...(row.identityClientId\n ? { identityClientId: row.identityClientId }\n : {}),\n argumentKeys: Array.isArray(row.argumentKeys) ? row.argumentKeys : [],\n occurredAt: new Date(row.occurredAt),\n }));\n }\n}\n\n/** Options for {@link createSmrtMcpAuditStore}. */\nexport interface SmrtMcpAuditStoreOptions {\n /** SMRT options bag (`{ db }`), the same one `smrtOptions` supplies. */\n smrtOptions: () => Record<string, unknown>;\n}\n\n/**\n * The default persistent audit sink: a SMRT-model-backed, tenant-aware store.\n * Pass it as `auditSink` and read it back with `list`.\n */\nexport function createSmrtMcpAuditStore(\n options: SmrtMcpAuditStoreOptions,\n): McpAuditSink & {\n list(\n query: McpAuditQuery & { tenantId: string | null },\n ): ReturnType<McpCallAuditCollection['listAudits']>;\n} {\n // Resolved per operation: `smrtOptions()` may return request-scoped state\n // (e.g. a transaction-bound db under RLS) that must not outlive its request.\n const get = () =>\n McpCallAuditCollection.create(\n options.smrtOptions() as never,\n ) as Promise<McpCallAuditCollection>;\n return {\n async record(record) {\n await (await get()).append(record);\n },\n async list(query) {\n return (await get()).listAudits(query);\n },\n };\n}\n"],"mappings":";;;AAOA,eAAe,wBAAwB,KAAK,MAAM,80PAA8zR,C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AAK,KAAK;GAAE;GAAO,SAAS;GAAoB;EAAM,CAAC;EAI1E,QAHa,MAAM,WACf,MAAM,WAAW,EAAE,UAAU,MAAM,SAAS,GAAG,IAAI,IACnD,MAAM,kBAAkB,IAAI,EAAA,CACpB,KAAK,SAA0C;GACzD,IAAI,OAAO,IAAI,EAAE;GACjB,aAAa,IAAI,eAAe;GAChC,eAAe,IAAI,iBAAiB;GACpC,MAAM,IAAI;GACV,UAAU,IAAI,YAAY;GAC1B,SAAS,IAAI;GACb,GAAI,IAAI,YAAY,EAAE,WAAW,IAAI,UAAU,IAAI,CAAC;GACpD,GAAI,IAAI,iBAAiB,EAAE,gBAAgB,IAAI,eAAe,IAAI,CAAC;GACnE,GAAI,IAAI,kBAAkB,EAAE,iBAAiB,IAAI,gBAAgB,IAAI,CAAC;GACtE,GAAI,IAAI,mBACJ,EAAE,kBAAkB,IAAI,iBAAiB,IACzC,CAAC;GACL,cAAc,MAAM,QAAQ,IAAI,YAAY,IAAI,IAAI,eAAe,CAAC;GACpE,YAAY,IAAI,KAAK,IAAI,UAAU;EACrC,EAAE;CACJ;AACF;AAYO,SAAS,wBACd,SAKA;CAGA,MAAM,YACJ,uBAAuB,OACrB,QAAQ,YAAY,CACtB;CACF,OAAO;EACL,MAAM,OAAO,QAAQ;GACnB,OAAO,MAAM,IAAI,EAAA,CAAG,OAAO,MAAM;EACnC;EACA,MAAM,KAAK,OAAO;GAChB,QAAQ,MAAM,IAAI,EAAA,CAAG,WAAW,KAAK;EACvC;CACF;AACF"}
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Persistable per-call audit records for the app-MCP server.
3
+ *
4
+ * The server builds one {@link McpAuditRecord} per tool call from the same
5
+ * event `onToolCall` receives (#4520) and hands it to an {@link McpAuditSink}.
6
+ * A record carries identity, tool, tenant, outcome and argument KEY names only:
7
+ * never argument values, tokens or response bodies, so the log cannot hold
8
+ * secrets or PII. The default persistent sink lives in `./audit` (a SMRT
9
+ * model); this module has no model or database dependency.
10
+ *
11
+ * @packageDocumentation
12
+ */
13
+ import type { McpToolCallAuditEvent } from './server.js';
14
+ /** Outcome vocabulary of a persisted audit record. */
15
+ export type McpAuditOutcome = 'allowed' | 'denied' | 'error';
16
+ /** One persisted-shape audit record. */
17
+ export interface McpAuditRecord {
18
+ /** The authenticated principal's id (credential id), or `null` when anonymous. */
19
+ principalId: string | null;
20
+ /** The principal's `kind` (for example `agent`, `owner`, `user`), or `null`. */
21
+ principalKind: string | null;
22
+ tool: string;
23
+ /** Host-supplied tenant (defaults to `principal.tenantId`), or `null`. */
24
+ tenantId: string | null;
25
+ outcome: McpAuditOutcome;
26
+ /** Stable safe code of a denial or failure, when there was one. */
27
+ errorCode?: string;
28
+ /** Verified credential identity (issuer, subject, client id), when the adapter stamped one. */
29
+ identityIssuer?: string;
30
+ identitySubject?: string;
31
+ identityClientId?: string;
32
+ /** Sorted argument key names. Values are never recorded. */
33
+ argumentKeys: readonly string[];
34
+ occurredAt: Date;
35
+ }
36
+ /** Destination for audit records. A failure is reported, never rethrown. */
37
+ export interface McpAuditSink {
38
+ record(record: McpAuditRecord): void | Promise<void>;
39
+ }
40
+ /** Key names only, sorted and bounded; values never leave this function. */
41
+ export declare function mcpArgumentKeyNames(args: unknown): string[];
42
+ /** Build the record for an audited call event. */
43
+ export declare function mcpAuditRecordFromEvent(event: McpToolCallAuditEvent): McpAuditRecord;
44
+ /** An in-memory sink for tests and local development. */
45
+ export declare function createInMemoryMcpAuditSink(): McpAuditSink & {
46
+ readonly records: readonly McpAuditRecord[];
47
+ list(query?: McpAuditQuery): McpAuditRecord[];
48
+ };
49
+ /** Filter for listing audit records. `tenantId` is the isolation boundary. */
50
+ export interface McpAuditQuery {
51
+ /** Required by persistent stores; `null` selects global (no-tenant) rows. */
52
+ tenantId?: string | null;
53
+ principalId?: string;
54
+ tool?: string;
55
+ outcome?: McpAuditOutcome;
56
+ /** 1..500, default 100. */
57
+ limit?: number;
58
+ }
59
+ //# sourceMappingURL=audit.d.ts.map
@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