audit-ledger-mcp 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,192 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ Copyright 2026 Shahid (https://github.com/shahidh68)
181
+
182
+ Licensed under the Apache License, Version 2.0 (the "License");
183
+ you may not use this file except in compliance with the License.
184
+ You may obtain a copy of the License at
185
+
186
+ http://www.apache.org/licenses/LICENSE-2.0
187
+
188
+ Unless required by applicable law or agreed to in writing, software
189
+ distributed under the License is distributed on an "AS IS" BASIS,
190
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
191
+ implied. See the License for the specific language governing
192
+ permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,265 @@
1
+ # audit-ledger-mcp
2
+
3
+ **MCP server for the [AI Audit Ledger](https://github.com/shahidh68/audit-ledger).** Lets any AI agent — Claude Desktop, Cursor, LangGraph, custom — record decisions to a tamper-evident audit trail with one line of config.
4
+
5
+ Built for teams shipping AI in regulated contexts: EU AI Act Article 12 logging, FCA SS1/23 model risk evidence, GDPR data minimisation. Personal data is hashed locally before any payload leaves the server — the ledger only ever sees fingerprints.
6
+
7
+ [![npm](https://img.shields.io/npm/v/audit-ledger-mcp.svg)](https://www.npmjs.com/package/audit-ledger-mcp) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](./LICENSE) [![MCP](https://img.shields.io/badge/MCP-compatible-7c3aed.svg)](https://modelcontextprotocol.io)
8
+
9
+ **[Try the live dashboard →](https://d2pfirb2397ixy.cloudfront.net/?demo=1)**  ·  30 synthetic decisions written via this MCP server, queryable and verifiable.
10
+
11
+ <p align="center">
12
+ <img src="./demo.gif" alt="LangGraph agents using audit-ledger-mcp — triage, risk, and human-in-the-loop each calling record_decision" />
13
+ </p>
14
+
15
+ > A LangGraph workflow calls `record_decision` after each agent step. Three audit events written to the live ledger; every one independently verifiable.
16
+
17
+ ---
18
+
19
+ ## What it does
20
+
21
+ Exposes three tools to any MCP-compatible agent:
22
+
23
+ | Tool | What it does |
24
+ |---|---|
25
+ | `record_decision` | Log an AI decision. Hashes inputs locally, then writes through to the ledger. Returns an event ID. |
26
+ | `verify_decision` | Cross-check a stored record against the immutable S3 Object Lock copy. Returns `integrity_verified: true/false`. |
27
+ | `list_decisions` | Query recent decisions, optionally filtered by time window. Tenant-scoped by API key. |
28
+
29
+ Each call ends up as a regulator-grade audit record in your deployed ledger — DynamoDB for query, S3 Object Lock COMPLIANCE mode for the immutable copy, 7-year retention by default.
30
+
31
+ ---
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ npm install -g audit-ledger-mcp
37
+ ```
38
+
39
+ Or run on demand without installing:
40
+
41
+ ```bash
42
+ npx -y audit-ledger-mcp
43
+ ```
44
+
45
+ ---
46
+
47
+ ## Configure
48
+
49
+ The server reads its configuration from environment variables. You need a deployed [AI Audit Ledger](https://github.com/shahidh68/audit-ledger) (or access to one) with at least one tenant write key and read key provisioned in Secrets Manager.
50
+
51
+ ```bash
52
+ # Required
53
+ export AUDIT_API_URL="https://<api-id>.execute-api.<region>.amazonaws.com/prod"
54
+ export AUDIT_WRITE_KEY="<your-tenant-write-key>"
55
+ export AUDIT_READ_KEY="<your-tenant-read-key>"
56
+
57
+ # Optional
58
+ export AUDIT_TIMEOUT_MS=5000 # default 5000
59
+ export AUDIT_RETRY_ATTEMPTS=3 # default 3
60
+ ```
61
+
62
+ The full template lives in [`.env.example`](./.env.example).
63
+
64
+ ---
65
+
66
+ ## Wire it into an agent
67
+
68
+ ### Claude Desktop
69
+
70
+ Edit your `claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`, Windows: `%APPDATA%\Claude\claude_desktop_config.json`):
71
+
72
+ ```json
73
+ {
74
+ "mcpServers": {
75
+ "audit-ledger": {
76
+ "command": "npx",
77
+ "args": ["-y", "audit-ledger-mcp"],
78
+ "env": {
79
+ "AUDIT_API_URL": "https://<api-id>.execute-api.<region>.amazonaws.com/prod",
80
+ "AUDIT_WRITE_KEY": "<your-tenant-write-key>",
81
+ "AUDIT_READ_KEY": "<your-tenant-read-key>"
82
+ }
83
+ }
84
+ }
85
+ }
86
+ ```
87
+
88
+ Restart Claude Desktop. You'll see "audit-ledger" in the MCP tools menu. Ask Claude something like *"Record this decision: I declined the application because…"* and watch it call `record_decision` automatically.
89
+
90
+ ### Cursor
91
+
92
+ In Cursor settings → MCP → add server:
93
+
94
+ ```json
95
+ {
96
+ "mcpServers": {
97
+ "audit-ledger": {
98
+ "command": "npx",
99
+ "args": ["-y", "audit-ledger-mcp"],
100
+ "env": {
101
+ "AUDIT_API_URL": "https://<api-id>.execute-api.<region>.amazonaws.com/prod",
102
+ "AUDIT_WRITE_KEY": "<your-tenant-write-key>",
103
+ "AUDIT_READ_KEY": "<your-tenant-read-key>"
104
+ }
105
+ }
106
+ }
107
+ }
108
+ ```
109
+
110
+ ### LangGraph (Python)
111
+
112
+ Using [`langchain-mcp-adapters`](https://github.com/langchain-ai/langchain-mcp-adapters):
113
+
114
+ ```python
115
+ from langchain_mcp_adapters.client import MultiServerMCPClient
116
+ from langgraph.prebuilt import create_react_agent
117
+ from langchain_anthropic import ChatAnthropic
118
+ import os
119
+
120
+ client = MultiServerMCPClient({
121
+ "audit-ledger": {
122
+ "command": "npx",
123
+ "args": ["-y", "audit-ledger-mcp"],
124
+ "transport": "stdio",
125
+ "env": {
126
+ "AUDIT_API_URL": os.environ["AUDIT_API_URL"],
127
+ "AUDIT_WRITE_KEY": os.environ["AUDIT_WRITE_KEY"],
128
+ "AUDIT_READ_KEY": os.environ["AUDIT_READ_KEY"],
129
+ },
130
+ }
131
+ })
132
+
133
+ tools = await client.get_tools()
134
+ agent = create_react_agent(
135
+ ChatAnthropic(model="claude-sonnet-4-7-20251022"),
136
+ tools,
137
+ )
138
+
139
+ # The agent can now call record_decision, verify_decision, list_decisions
140
+ result = await agent.ainvoke({
141
+ "messages": [{"role": "user", "content": "Triage this loan application…"}]
142
+ })
143
+ ```
144
+
145
+ ### Custom client (raw MCP)
146
+
147
+ ```bash
148
+ AUDIT_API_URL=... AUDIT_WRITE_KEY=... npx -y audit-ledger-mcp
149
+ ```
150
+
151
+ The server speaks MCP over stdio. Send `initialize`, `tools/list`, and `tools/call` requests per the [MCP specification](https://modelcontextprotocol.io/specification).
152
+
153
+ ---
154
+
155
+ ## How a `record_decision` call flows
156
+
157
+ ```
158
+ Agent audit-ledger-mcp AWS (your ledger)
159
+ | | |
160
+ |--- record_decision ----->| |
161
+ | raw_user_input | (hash locally — no PII over |
162
+ | raw_system_prompt | the wire from this point) |
163
+ | decision_output | |
164
+ | human_in_loop | |
165
+ | |--- HTTPS POST /audit/events --->|
166
+ | | {hashes + decision + |
167
+ | | x-api-key} |
168
+ | | |
169
+ | |<--- 202 Accepted ---------------|
170
+ | | { event_id, ... } |
171
+ |<--- event_id ------------| |
172
+ | recorded_at | |
173
+ | note | |
174
+ ```
175
+
176
+ Storage on the AWS side happens asynchronously through SQS → Processor Lambda → DynamoDB + S3 Object Lock. See the [main repo's ARCHITECTURE.md](https://github.com/shahidh68/audit-ledger/blob/main/ARCHITECTURE.md) for the full path.
177
+
178
+ ---
179
+
180
+ ## Tool reference
181
+
182
+ ### `record_decision`
183
+
184
+ Record an AI decision to the ledger.
185
+
186
+ | Parameter | Type | Required | Notes |
187
+ |---|---|---|---|
188
+ | `model_version` | string | Yes | e.g. `"claude-sonnet-4-7-20251022"` |
189
+ | `raw_system_prompt` | string | Yes | Hashed locally |
190
+ | `raw_user_input` | string | Yes | Hashed locally |
191
+ | `ai_decision_output` | object | Yes | Stored verbatim — must not contain raw PII |
192
+ | `human_in_loop` | boolean | Yes | Critical for EU AI Act Article 14 |
193
+ | `event_id` | uuid v4 | No | Auto-generated if omitted |
194
+ | `timestamp` | ISO 8601 | No | Defaults to now |
195
+
196
+ ### `verify_decision`
197
+
198
+ Tamper-check a stored record.
199
+
200
+ | Parameter | Type | Required | Notes |
201
+ |---|---|---|---|
202
+ | `event_id` | uuid v4 | Yes | The ID of the record to verify |
203
+
204
+ Returns the DynamoDB record, the S3 record, and `integrity_verified: true/false`.
205
+
206
+ ### `list_decisions`
207
+
208
+ List recent decisions for the calling tenant.
209
+
210
+ | Parameter | Type | Required | Notes |
211
+ |---|---|---|---|
212
+ | `from` | ISO 8601 | No | Defaults to 7 days ago |
213
+ | `to` | ISO 8601 | No | Defaults to now |
214
+ | `limit` | integer 1–500 | No | Defaults to 100 |
215
+
216
+ ---
217
+
218
+ ## Security
219
+
220
+ - **PII hashing happens in this process, not in the ledger.** SHA-256 over UTF-8. The ledger only ever stores hashes, the structured decision, and metadata.
221
+ - **API keys are never logged.** They come from environment variables, are passed in the `x-api-key` header, and are never echoed back to the agent or written to disk.
222
+ - **Two key namespaces.** Write keys cannot read; read keys cannot write. A leaked write key cannot exfiltrate data; a leaked read key cannot plant fake records.
223
+ - **Errors are propagated with HTTP status passthrough.** Rate limit, invalid key, and validation errors surface to the agent so it can react appropriately rather than retry blindly.
224
+
225
+ ---
226
+
227
+ ## What this is not
228
+
229
+ - **Not legal advice.** This is infrastructure that produces audit evidence. Whether that evidence satisfies any specific regulatory obligation is a question for your legal team.
230
+ - **Not a substitute for a model risk audit.** It records what the AI did, not whether it was right.
231
+ - **Not a bias or fairness testing tool.** It is the audit layer underneath whatever testing you already do.
232
+
233
+ ---
234
+
235
+ ## Development
236
+
237
+ ```bash
238
+ git clone https://github.com/shahidh68/audit-ledger-mcp.git
239
+ cd audit-ledger-mcp
240
+ npm install
241
+ npm run build
242
+ npm test
243
+ ```
244
+
245
+ The server is TypeScript on Node 20+, ESM, stdio transport, using `@modelcontextprotocol/sdk`.
246
+
247
+ ---
248
+
249
+ ## Related
250
+
251
+ - **[shahidh68/audit-ledger](https://github.com/shahidh68/audit-ledger)** — the AWS infrastructure this server talks to. CDK stack, Python and Node SDKs, compliance dashboard, full architecture documentation.
252
+
253
+ ---
254
+
255
+ ## License
256
+
257
+ Apache License 2.0 — see [LICENSE](./LICENSE).
258
+
259
+ The patent grant is intentional. Compliance infrastructure sits adjacent to enterprise legal review and the explicit grant matters there.
260
+
261
+ ---
262
+
263
+ ## Author
264
+
265
+ Built by [Shahid](https://github.com/shahidh68). Available for Principal AI Engineering and Head of AI Engineering roles, and fractional advisory engagements, in UK regulated fintech.
@@ -0,0 +1,58 @@
1
+ /**
2
+ * HTTP client for the AI Audit Ledger API.
3
+ *
4
+ * Mirrors the retry behaviour of the Python SDK in the main repo: exponential
5
+ * backoff with full jitter, retry on network errors and 5xx only. 4xx (including
6
+ * 429) returns immediately because retrying a rate-limited or auth-failed
7
+ * request just burns quota.
8
+ */
9
+ export interface ClientConfig {
10
+ apiUrl: string;
11
+ writeKey?: string;
12
+ readKey?: string;
13
+ timeoutMs?: number;
14
+ retryAttempts?: number;
15
+ }
16
+ export declare class AuditLedgerError extends Error {
17
+ readonly status?: number | undefined;
18
+ readonly body?: string | undefined;
19
+ constructor(message: string, status?: number | undefined, body?: string | undefined);
20
+ }
21
+ export interface DecisionRecord {
22
+ event_id: string;
23
+ timestamp: string;
24
+ tenant_id?: string;
25
+ model_version: string;
26
+ system_prompt_hash: string;
27
+ input_data_hash: string;
28
+ ai_decision_output: Record<string, unknown>;
29
+ human_in_loop: boolean;
30
+ }
31
+ export interface TamperCheckResult {
32
+ integrity_verified: boolean;
33
+ note: string;
34
+ dynamodb_record: DecisionRecord;
35
+ s3_record: DecisionRecord;
36
+ }
37
+ export declare class AuditLedgerClient {
38
+ private readonly apiUrl;
39
+ private readonly writeKey?;
40
+ private readonly readKey?;
41
+ private readonly timeoutMs;
42
+ private readonly retryAttempts;
43
+ constructor(config: ClientConfig);
44
+ recordDecision(payload: Omit<DecisionRecord, "tenant_id">): Promise<{
45
+ event_id: string;
46
+ }>;
47
+ verifyDecision(eventId: string): Promise<TamperCheckResult>;
48
+ listDecisions(opts: {
49
+ from?: string;
50
+ to?: string;
51
+ }): Promise<DecisionRecord[]>;
52
+ /**
53
+ * Exponential backoff with full jitter. Retries network errors and 5xx only.
54
+ * 4xx is returned to the caller immediately.
55
+ */
56
+ private fetchWithRetry;
57
+ }
58
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,qBAAa,gBAAiB,SAAQ,KAAK;aAGvB,MAAM,CAAC,EAAE,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C;IA2BpF;;;OAGG;YACW,cAAc;CA0B7B"}
package/dist/client.js ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * HTTP client for the AI Audit Ledger API.
3
+ *
4
+ * Mirrors the retry behaviour of the Python SDK in the main repo: exponential
5
+ * backoff with full jitter, retry on network errors and 5xx only. 4xx (including
6
+ * 429) returns immediately because retrying a rate-limited or auth-failed
7
+ * request just burns quota.
8
+ */
9
+ export class AuditLedgerError extends Error {
10
+ status;
11
+ body;
12
+ constructor(message, status, body) {
13
+ super(`[audit-ledger] ${message}`);
14
+ this.status = status;
15
+ this.body = body;
16
+ this.name = "AuditLedgerError";
17
+ }
18
+ }
19
+ export class AuditLedgerClient {
20
+ apiUrl;
21
+ writeKey;
22
+ readKey;
23
+ timeoutMs;
24
+ retryAttempts;
25
+ constructor(config) {
26
+ this.apiUrl = config.apiUrl.replace(/\/+$/, "");
27
+ this.writeKey = config.writeKey;
28
+ this.readKey = config.readKey;
29
+ this.timeoutMs = config.timeoutMs ?? 5000;
30
+ this.retryAttempts = config.retryAttempts ?? 3;
31
+ }
32
+ async recordDecision(payload) {
33
+ if (!this.writeKey) {
34
+ throw new AuditLedgerError("AUDIT_WRITE_KEY is not set — record_decision unavailable");
35
+ }
36
+ const res = await this.fetchWithRetry(`${this.apiUrl}/audit/events`, {
37
+ method: "POST",
38
+ headers: {
39
+ "Content-Type": "application/json",
40
+ "Accept": "application/json",
41
+ "x-api-key": this.writeKey,
42
+ },
43
+ body: JSON.stringify(payload),
44
+ });
45
+ if (res.status !== 200 && res.status !== 202) {
46
+ throw new AuditLedgerError(`record_decision failed: HTTP ${res.status}`, res.status, await safeText(res));
47
+ }
48
+ const data = await safeJson(res);
49
+ return { event_id: data?.event_id ?? payload.event_id };
50
+ }
51
+ async verifyDecision(eventId) {
52
+ if (!this.readKey) {
53
+ throw new AuditLedgerError("AUDIT_READ_KEY is not set — verify_decision unavailable");
54
+ }
55
+ const url = `${this.apiUrl}/audit/events/${encodeURIComponent(eventId)}/history`;
56
+ const res = await this.fetchWithRetry(url, {
57
+ method: "GET",
58
+ headers: { "Accept": "application/json", "x-api-key": this.readKey },
59
+ });
60
+ if (res.status !== 200) {
61
+ throw new AuditLedgerError(`verify_decision failed: HTTP ${res.status}`, res.status, await safeText(res));
62
+ }
63
+ return (await res.json());
64
+ }
65
+ async listDecisions(opts) {
66
+ if (!this.readKey) {
67
+ throw new AuditLedgerError("AUDIT_READ_KEY is not set — list_decisions unavailable");
68
+ }
69
+ const params = new URLSearchParams();
70
+ if (opts.from)
71
+ params.set("from", opts.from);
72
+ if (opts.to)
73
+ params.set("to", opts.to);
74
+ const url = `${this.apiUrl}/audit/logs${params.toString() ? `?${params}` : ""}`;
75
+ const res = await this.fetchWithRetry(url, {
76
+ method: "GET",
77
+ headers: { "Accept": "application/json", "x-api-key": this.readKey },
78
+ });
79
+ if (res.status !== 200) {
80
+ throw new AuditLedgerError(`list_decisions failed: HTTP ${res.status}`, res.status, await safeText(res));
81
+ }
82
+ const data = await res.json();
83
+ if (Array.isArray(data))
84
+ return data;
85
+ if (data && typeof data === "object" && "items" in data && Array.isArray(data.items)) {
86
+ return data.items;
87
+ }
88
+ return [];
89
+ }
90
+ /**
91
+ * Exponential backoff with full jitter. Retries network errors and 5xx only.
92
+ * 4xx is returned to the caller immediately.
93
+ */
94
+ async fetchWithRetry(url, init) {
95
+ let lastErr;
96
+ for (let attempt = 0; attempt < this.retryAttempts; attempt++) {
97
+ try {
98
+ const controller = new AbortController();
99
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
100
+ try {
101
+ const res = await fetch(url, { ...init, signal: controller.signal });
102
+ if (res.status < 500)
103
+ return res;
104
+ lastErr = new AuditLedgerError(`HTTP ${res.status}`, res.status, await safeText(res));
105
+ }
106
+ finally {
107
+ clearTimeout(timer);
108
+ }
109
+ }
110
+ catch (err) {
111
+ lastErr = err;
112
+ }
113
+ if (attempt < this.retryAttempts - 1) {
114
+ const baseMs = 200;
115
+ const jitter = Math.random() * baseMs;
116
+ const delay = baseMs * 2 ** attempt + jitter;
117
+ await new Promise((r) => setTimeout(r, delay));
118
+ }
119
+ }
120
+ if (lastErr instanceof Error)
121
+ throw lastErr;
122
+ throw new AuditLedgerError("retry attempts exhausted");
123
+ }
124
+ }
125
+ async function safeText(res) {
126
+ try {
127
+ return await res.text();
128
+ }
129
+ catch {
130
+ return "";
131
+ }
132
+ }
133
+ async function safeJson(res) {
134
+ try {
135
+ return (await res.json());
136
+ }
137
+ catch {
138
+ return null;
139
+ }
140
+ }
141
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAUH,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IAGvB;IACA;IAHlB,YACE,OAAe,EACC,MAAe,EACf,IAAa;QAE7B,KAAK,CAAC,kBAAkB,OAAO,EAAE,CAAC,CAAC;QAHnB,WAAM,GAAN,MAAM,CAAS;QACf,SAAI,GAAJ,IAAI,CAAS;QAG7B,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;IACjC,CAAC;CACF;AAoBD,MAAM,OAAO,iBAAiB;IACX,MAAM,CAAS;IACf,QAAQ,CAAU;IAClB,OAAO,CAAU;IACjB,SAAS,CAAS;IAClB,aAAa,CAAS;IAEvC,YAAY,MAAoB;QAC9B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QAChD,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;QAChC,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;QAC9B,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS,IAAI,IAAI,CAAC;QAC1C,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC,aAAa,IAAI,CAAC,CAAC;IACjD,CAAC;IAED,KAAK,CAAC,cAAc,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