@agledger/mcp-server 2.10.0 → 2.11.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/CHANGELOG.md CHANGED
@@ -4,6 +4,45 @@ All notable changes to the AGLedger MCP Server will be documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [2.11.0] - 2026-09-21
8
+
9
+ ### Added
10
+
11
+ - **`agledger_verify` refuses a re-attributed export.** The `actorId`, `actorRole` and `actorOwnerId` an export displays are signature-covered, and they are now cross-checked against the signed actor claim, so an export re-attributed to another actor fails with the new `CHAIN_ACTOR_ATTRIBUTION_MISMATCH` instead of verifying. Requires `@agledger/verify-core` 1.5.0.
12
+ - **The server can authenticate with an OIDC token instead of an API key** (#30). Set `AGLEDGER_OIDC_TOKEN_FILE` (a file holding the token, such as a Kubernetes projected service-account token) or `AGLEDGER_OIDC_TOKEN_CMD` (a shell command that prints one), plus `AGLEDGER_OIDC_AGENT_ID` if the cert should bind to a specific agent. The server generates an Ed25519 key pair in memory, exchanges the token for a short-lived cert signed by the Server (`POST /v1/auth/oidc/cert`) and presents the cert as its bearer. No long-lived secret sits in the MCP client configuration, and nothing is written to disk. An API key still wins when one is set, then the command, then the file; the server prints a note naming any source it ignores.
13
+
14
+ - The token source is consulted on every exchange: the file is re-read and the command re-run, because the Server exchanges a given token id (`jti`) only once and a projected token is rotated on disk under a running process. A file that still holds the token already exchanged is recognised locally and not sent, so an unrotated file costs no request and no warning while the current cert is valid, and produces an error naming the rotation interval once the cert has expired.
15
+ - The cert is re-exchanged once half its lifetime has passed, measured from when it was received so clock skew cannot shorten or stretch it. Concurrent tool calls share one exchange. A refresh that fails while the current cert is still valid keeps it and prints one warning on stderr.
16
+ - A 401 on a cert bearer (a revoked cert) forces exactly one re-exchange and one retry of the request, with the same body bytes and the same `Idempotency-Key`. A second 401 is returned as the answer.
17
+ - Every request body is signed with the key bound to the cert (`X-Agent-Signature-Content-Hash` and `X-Agent-Signature`), so the Server records the agent's own signature in the chain entry (`predicate.on_behalf_of.agent_signature`) on the routes that accept one.
18
+ - A failed exchange reaches the tool result as `code: OIDC_EXCHANGE_FAILED` with the Server's status, error body and `recoveryHint`; a token source that cannot produce a token is `OIDC_TOKEN_SOURCE_FAILED`. Tokens are scrubbed from both, and a failing command's stderr is included with anything shaped like a JWT removed. The command text itself is never echoed, since it can carry a secret of its own.
19
+ - A token command (`AGLEDGER_OIDC_TOKEN_CMD`, and `AGLEDGER_ON_BEHALF_OF_CMD` below) runs in its own process group, and the whole group is killed when the command times out after 60 seconds, prints more than 64 KiB, or exits, so a pipeline or a helper it forks cannot outlive the call and pile up across refreshes in a long-running server.
20
+ - `agledger_discover` fetches `/health` without a credential, so "is the Server up" stays answerable when the credential is what is broken.
21
+ - `--help` and the no-credential startup error list all three credential sources. A token file that cannot be read exits 2 at startup rather than failing on the first tool call.
22
+
23
+ - **The server can act on behalf of a person or another party.** `AGLEDGER_ON_BEHALF_OF_CMD` (a shell command) or `AGLEDGER_ON_BEHALF_OF_FILE` names an RFC 8693 delegation token, which the server sends as `AGLedger-On-Behalf-Of` on every POST; every route that declares the header is a POST. The token comes from the process and never from a tool argument, so a model can neither read nor forge it, and `agledger_discover` reports only whether a delegation is configured and its source. The command wins over the file. A delegation token is not single use, so it is kept until its `exp` (less 30 seconds) and read again after that, or once when the Server answers 401 about the delegation, after which the request is retried a single time; an already-expired token is refused before anything is sent. It is scrubbed from every error and tool result, including a Server response that echoes it. With the OIDC cert credential the Server records the delegation `bound` to the agent's own identity; with an API key, `unbound`.
24
+
25
+ - **`agledger_verify` takes `agentKeys`**, the Ed25519 public keys (JWKs) of agent certs. An entry whose sealed agent signature names one of them by thumbprint has that signature re-verified offline, and a failure is the new `CHAIN_AGENT_SIGNATURE_INVALID`. Without it, the result counts agent signatures in `agentSignatures` without checking them. Requires `@agledger/verify-core` 1.5.0.
26
+
27
+ ### Fixed
28
+
29
+ - **An argument a tool does not declare is refused instead of dropped** (#29). `agledger_api` called with `body` in place of `params` sent the request with no payload, and the agent read the Server's `body must be object` as a problem with its payload rather than with the argument name. Each tool now answers an undeclared argument with `code: UNKNOWN_ARGUMENT`, naming the argument and the ones it accepts, before anything is sent. The published tool schemas are unchanged: required arguments stay required, every description is intact, and no `additionalProperties` keyword appears, which `tests/tool-schema.test.ts` asserts on the `tools/list` document.
30
+
31
+ - **The `agledger_api` description pointed agents at a field the Server does not send.** It said to read `suggestion` on a failed call; the Server's error bodies carry `recoveryHint`. The description and the README now name `recoveryHint` for Server errors and `suggestion` for errors the tool raises itself.
32
+
33
+ - **The `agledger_verify` description listed 16 of the 19 failure codes an audit export can produce.** `CHAIN_OIDC_ACTOR_MISMATCH`, `CHAIN_KEY_EXPIRED` and `CHAIN_KEY_NOT_YET_ACTIVE` were missing. The list is now checked against `@agledger/verify-core`'s `FailureCode` union at compile time, so a new code there fails the build here until the description carries it.
34
+
35
+ ### Changed
36
+
37
+ - `LICENSE` follows SDK License Template 1.9: section 1 says AGLedger LLC does not receive, inspect or use the data you process through your deployment and collects no product usage information from it; section 7 names AGLedger and Settlement Signal as trademarks of AGLedger LLC; section 8 refers to issued or pending U.S. patents.
38
+ - The README states what AGLedger is in current terms: agent memory, approvals, audit trail and notifications on one API and one signed ledger, self-hosted.
39
+
40
+ ## [2.10.1] - 2026-09-10
41
+
42
+ ### Changed
43
+
44
+ - **LICENSE section 6 names the ciphers this package line ships**: Ed25519 (EdDSA), ECDSA P-256 with SHA-256, HMAC-SHA-256, AES-256-GCM, HKDF-SHA-256 and SHA-256. X25519 is gone from the list with the federation encryption key the engine no longer has. The LICENSE file is the only shipped byte that moved.
45
+
7
46
  ## [2.10.0] - 2026-08-21
8
47
 
9
48
  ### Added
package/LICENSE CHANGED
@@ -17,16 +17,13 @@ Licensor grants you a limited, non-exclusive, non-transferable, revocable
17
17
  license to install and use the Software solely for the purpose of integrating
18
18
  with a self-hosted AGLedger deployment operated by you or your organization, or
19
19
  by a third party on your behalf with your authorization. The Software is not
20
- designed for, and is not licensed for use with, any AGLedger-hosted service.
21
- AGLedger operates the AGLedger software on a self-hosted model; there is no
22
- hosted AGLedger API.
20
+ licensed for use with any AGLedger-hosted service.
23
21
 
24
- AGLedger LLC operates no service in your data path. AGLedger LLC does not
25
- receive, access, inspect, or judge the records, completions, or deliverable
26
- content you process through your self-hosted deployment, and does not use any
27
- such data to train, fine-tune, evaluate, or benchmark any machine-learning or
28
- artificial-intelligence model, or to develop any product or service. AGLedger
29
- LLC receives no usage data or other data from your self-hosted deployment.
22
+ AGLedger LLC does not receive, access, inspect, or judge the data you process
23
+ through your self-hosted deployment, and does not use any such data to train,
24
+ fine-tune, evaluate, or benchmark any machine-learning or artificial-
25
+ intelligence model, or to develop any product or service. AGLedger LLC does not
26
+ collect product usage information from your self-hosted deployment.
30
27
 
31
28
  2. RESTRICTIONS
32
29
 
@@ -84,8 +81,9 @@ cause of action accrues, to the maximum extent permitted by applicable law.
84
81
 
85
82
  6. EXPORT COMPLIANCE
86
83
 
87
- The Software may include cryptographic functionality (including Ed25519, AES-
88
- 256-GCM, SHA-256, and X25519). AGLedger LLC classifies the Software under
84
+ The Software may include cryptographic functionality, including Ed25519
85
+ (EdDSA), ECDSA using curve P-256 with SHA-256, HMAC-SHA-256, AES-256-GCM,
86
+ HKDF-SHA-256, and SHA-256. AGLedger LLC classifies the Software under
89
87
  ECCN 5D002 in good faith. To the extent AGLedger LLC makes the source code of
90
88
  the Software publicly available through a public repository, that source code
91
89
  is subject to the treatment afforded under 15 CFR § 742.15(b) of the U.S.
@@ -102,14 +100,13 @@ or trade-control laws.
102
100
 
103
101
  7. TRADEMARKS
104
102
 
105
- AGLedger is a trademark of AGLedger LLC, and Settlement Signal is a pending
106
- trademark of AGLedger LLC. All other trademarks are the property of their
107
- respective owners.
103
+ AGLedger and Settlement Signal are trademarks of AGLedger LLC. All other
104
+ trademarks are the property of their respective owners.
108
105
 
109
106
  8. PATENTS
110
107
 
111
- The Software is covered by one or more U.S. patent applications pending before
112
- the U.S. Patent and Trademark Office in AGLedger LLC's patent portfolio.
108
+ The Software is covered by one or more issued or pending U.S. patents in
109
+ AGLedger LLC's patent portfolio.
113
110
 
114
111
  9. RELATIONSHIP TO OTHER AGLEDGER AGREEMENTS
115
112
 
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @agledger/mcp-server
2
2
 
3
- The official [MCP](https://modelcontextprotocol.io) server for the [AGLedger](https://agledger.ai) API: change control for AI agents. A self-hosted notary that records every change an agent makes, signed and hash-chained, and gates the ones that matter.
3
+ The official [MCP](https://modelcontextprotocol.io) server for the [AGLedger](https://agledger.ai) API: change control for AI agents. Agent memory, approvals, audit trail, and notifications: one API, one signed ledger, self-hosted.
4
4
 
5
5
  Connects any MCP-compatible AI agent (Claude, Cursor, Windsurf, etc.) to the AGLedger API with 2 universal API-pass-through tools plus an offline audit verifier. No SDK code required. Just point your agent at this server.
6
6
 
@@ -35,8 +35,10 @@ Add to your MCP client configuration (e.g. `claude_desktop_config.json`):
35
35
  }
36
36
  ```
37
37
 
38
- Both flags are required. AGLedger is self-hosted, so there is no default server
39
- to call: without `--api-url` the server exits before it accepts a connection.
38
+ Both flags are required, unless an OIDC token source stands in for the key (see
39
+ [below](#authenticating-with-oidc-instead-of-an-api-key)). AGLedger is
40
+ self-hosted, so there is no default server to call: without `--api-url` the
41
+ server exits before it accepts a connection.
40
42
 
41
43
  Or run directly:
42
44
 
@@ -48,13 +50,108 @@ Exit codes: `0` clean, `1` runtime failure, `2` usage or configuration error
48
50
  (missing flag, unknown flag), so a launcher can tell a misconfiguration from a
49
51
  crash.
50
52
 
53
+ ## Authenticating with OIDC instead of an API key
54
+
55
+ When the operator of your AGLedger Server has registered your identity
56
+ provider as a trusted issuer for agents, the MCP server can run with no API key
57
+ at all. Give it a source of OIDC tokens instead. It exchanges a token for a
58
+ short-lived cert signed by the Server (`POST /v1/auth/oidc/cert`), presents the
59
+ cert as its bearer, and signs each request body with an Ed25519 key that exists
60
+ only in its own memory. The Server records that signature in the signed chain
61
+ entry of every record the agent writes (`predicate.on_behalf_of.agent_signature`).
62
+ Nothing is written to disk.
63
+
64
+ | Env var | Description |
65
+ |---------|-------------|
66
+ | `AGLEDGER_OIDC_TOKEN_FILE` | A file holding an OIDC JWT, such as a Kubernetes projected service-account token. Read on every exchange, so a token rotated on disk is picked up. |
67
+ | `AGLEDGER_OIDC_TOKEN_CMD` | A shell command whose stdout is an OIDC JWT. Run on every exchange. |
68
+ | `AGLEDGER_OIDC_AGENT_ID` | Optional. The agent id to bind the cert to, when the issuer does not map one from the token. |
69
+
70
+ An API key wins when one is set, then the command, then the file.
71
+
72
+ ```bash
73
+ AGLEDGER_OIDC_TOKEN_FILE=/var/run/secrets/agledger/token \
74
+ agledger-mcp --api-url https://your-agledger-instance
75
+ ```
76
+
77
+ In an MCP client configuration, the token source goes in `env`:
78
+
79
+ ```json
80
+ {
81
+ "mcpServers": {
82
+ "agledger": {
83
+ "command": "agledger-mcp",
84
+ "args": ["--api-url", "https://your-agledger-instance"],
85
+ "env": { "AGLEDGER_OIDC_TOKEN_FILE": "/var/run/secrets/agledger/token" }
86
+ }
87
+ }
88
+ }
89
+ ```
90
+
91
+ The cert is re-exchanged once half its lifetime has passed, and once more if
92
+ the Server answers 401 (a revoked cert), after which the request is retried a
93
+ single time. A refresh that fails while the current cert is still valid keeps
94
+ the current cert and prints one warning on stderr. When the exchange itself is
95
+ refused, the tool result carries `code: OIDC_EXCHANGE_FAILED`, the Server's
96
+ status and error body, and its `recoveryHint`.
97
+
98
+ The Server exchanges a token id (`jti`) only once, so every exchange needs a
99
+ new token. A command runs on every exchange; a file is read on every exchange,
100
+ and while it still holds the token already exchanged, the server keeps using
101
+ the current cert rather than asking. The kubelet rewrites a projected token at
102
+ 80% of `expirationSeconds`, so keep that interval shorter than the trusted
103
+ issuer's `maxCredentialTtlSeconds`, or the cert expires before a new token
104
+ appears:
105
+
106
+ ```yaml
107
+ volumes:
108
+ - name: agledger-token
109
+ projected:
110
+ sources:
111
+ - serviceAccountToken:
112
+ audience: agledger
113
+ expirationSeconds: 600
114
+ path: token
115
+ ```
116
+
117
+ ## Acting on behalf of someone
118
+
119
+ When the agent does work for a person or another party rather than for
120
+ itself, the operator can give the server an RFC 8693 delegation token: the
121
+ token-exchange result your IdP issues, whose `act` claim names the agent. The
122
+ server sends it as the `AGLedger-On-Behalf-Of` header on every POST, and the
123
+ Server validates it against a trusted issuer registered with
124
+ `appliesTo: principal` and seals it into the chain entry as
125
+ `predicate.on_behalf_of`. The token comes from the process, never from a tool
126
+ argument, so the model can neither read nor choose it; `agledger_discover`
127
+ reports only whether a delegation is configured and where it comes from.
128
+
129
+ | Env var | Description |
130
+ |---------|-------------|
131
+ | `AGLEDGER_ON_BEHALF_OF_CMD` | A shell command whose stdout is the delegation token. Wins over the file. |
132
+ | `AGLEDGER_ON_BEHALF_OF_FILE` | A file holding the delegation token. |
133
+
134
+ ```bash
135
+ AGLEDGER_OIDC_TOKEN_FILE=/var/run/secrets/agledger/token \
136
+ AGLEDGER_ON_BEHALF_OF_FILE=/var/run/secrets/agledger/on-behalf-of \
137
+ agledger-mcp --api-url https://your-agledger-instance
138
+ ```
139
+
140
+ A delegation token is not single use, so it is kept until its `exp` and read
141
+ again after that, or when the Server refuses it with a 401 that names the
142
+ delegation (the request is then retried once). With the OIDC cert credential
143
+ the delegation is recorded `bound`: the token's `act.sub` and actor issuer must
144
+ be the cert's own subject and issuer, or the Server answers 403
145
+ `ACTOR_BINDING_MISMATCH`. With an API key there is no validated caller identity
146
+ to compare, and it is recorded `unbound`.
147
+
51
148
  ## Tools
52
149
 
53
150
  | Tool | Description |
54
151
  |------|-------------|
55
152
  | `agledger_discover` | Returns API health, your identity, available scopes, and a quickstart workflow. Call this first. |
56
153
  | `agledger_api` | Make any AGLedger API call (method, path, params). Every POST carries a generated `Idempotency-Key`; pass `idempotencyKey` to reuse the first attempt's key when retrying a call that may already have landed. The API returns `nextSteps` on every response for self-guided workflow discovery. |
57
- | `agledger_verify` | Verify a record audit export offline (COSE_Sign1 envelopes per RFC 9052, hash chain + envelope signatures, Ed25519 or ES256). No network calls. Returns `valid`, `verifiedEntries`, and a `brokenAt` pointer with a canonical failure `code` on failure. Pass `publicKeys` to supply keys out of band and `requireOutOfBandKeys` for an independent audit that refuses the export's embedded keys. Built on the shared `@agledger/verify-core`. |
154
+ | `agledger_verify` | Verify a record audit export offline (COSE_Sign1 envelopes per RFC 9052, hash chain + envelope signatures, Ed25519 or ES256). No network calls. Returns `valid`, `verifiedEntries`, and a `brokenAt` pointer with a canonical failure `code` on failure. Pass `publicKeys` to supply keys out of band and `requireOutOfBandKeys` for an independent audit that refuses the export's embedded keys. Pass `agentKeys` (the agents' cert public keys as JWKs) to re-verify the agent signatures sealed in the chain; without them those signatures are counted but not checked. Built on the shared `@agledger/verify-core`. |
58
155
 
59
156
  ## Resources
60
157
 
@@ -74,18 +171,18 @@ The `agledger_discover` tool returns a quickstart workflow that guides agents th
74
171
  3. `POST /v1/records` -- create a record
75
172
  4. `POST /v1/records/{id}/completions` -- submit a completion (evidence) when done
76
173
 
77
- Every API error response includes a `suggestion` field with actionable recovery guidance -- agents can self-correct without human intervention.
174
+ Every API error response includes a `recoveryHint` naming the fix, so an agent can correct itself without a human. Errors raised by the MCP server itself (an argument the tool does not declare, a timeout, a credential failure) carry a `code` and a `suggestion` instead.
78
175
 
79
176
  ## Configuration
80
177
 
81
178
  | Flag | Env Var | Description |
82
179
  |------|---------|-------------|
83
- | `--api-key` | `AGLEDGER_API_KEY` | AGLedger API key (required) |
180
+ | `--api-key` | `AGLEDGER_API_KEY` | AGLedger API key. Required unless an OIDC token source is set (see above). |
84
181
  | `--api-url` | `AGLEDGER_API_URL` | API base URL of your instance (required). AGLedger is self-hosted, so there is no default; the server refuses to start without it. |
85
182
 
86
183
  ## What is AGLedger?
87
184
 
88
- AGLedger is the accountability layer for automated operations. It notarizes what was agreed to, by whom, and when, and tracks the delegation of that agreement through other systems.
185
+ AGLedger is change control for AI agents, delivered as a signed ledger for agentic work. Agents notarize what they intended and what they did, principals approve the work that needs a decision, and every entry is signed, hash-chained and verifiable offline.
89
186
 
90
187
  - **Records** -- structured commitments with acceptance criteria and tolerance bands
91
188
  - **Completions** -- performer evidence recording what was reported to be done
@@ -99,7 +196,7 @@ Each self-hosted AGLedger instance also serves interactive Swagger UI at `{AGLED
99
196
  ## Requirements
100
197
 
101
198
  - Node.js >= 24
102
- - A running self-hosted AGLedger API instance and an API key (see the self-hosted install guide at [agledger.ai](https://www.agledger.ai))
199
+ - A running self-hosted AGLedger API instance, and an API key or a trusted OIDC issuer (see the self-hosted install guide at [agledger.ai](https://www.agledger.ai))
103
200
 
104
201
  ## License
105
202
 
@@ -1,16 +1,33 @@
1
+ import { type Credential } from './credentials.js';
2
+ import { type DelegationSource } from './delegation.js';
1
3
  export interface ApiResponse {
2
4
  status: number;
3
5
  body: unknown;
4
6
  ok: boolean;
5
7
  }
8
+ export interface RequestOptions {
9
+ query?: Record<string, unknown>;
10
+ body?: unknown;
11
+ idempotencyKey?: string;
12
+ /** Send no credential. For public routes whose answer must not depend on the credential working (`/health`). */
13
+ anonymous?: boolean;
14
+ }
6
15
  export declare class ApiClient {
7
16
  private readonly apiUrl;
8
- private readonly apiKey;
17
+ private readonly credential;
9
18
  private readonly timeoutMs;
10
- constructor(apiUrl: string, apiKey: string, timeoutMs?: number);
11
- request(method: string, path: string, options?: {
12
- query?: Record<string, unknown>;
13
- body?: unknown;
14
- idempotencyKey?: string;
15
- }): Promise<ApiResponse>;
19
+ private readonly delegation;
20
+ /**
21
+ * `credential` is an API key string or a {@link Credential} (e.g. an OIDC
22
+ * cert credential). `delegation`, when set, supplies the
23
+ * `AGLedger-On-Behalf-Of` token attached to every POST.
24
+ */
25
+ constructor(apiUrl: string, credential: string | Credential, timeoutMs?: number, delegation?: DelegationSource);
26
+ /** Where the delegation token comes from, or undefined when none is configured. Never the token. */
27
+ get delegationOrigin(): string | undefined;
28
+ request(method: string, path: string, options?: RequestOptions): Promise<ApiResponse>;
29
+ /** The delegation token never comes back to a tool, even if the Server echoes it. */
30
+ private scrubbed;
31
+ private postAnonymous;
32
+ private send;
16
33
  }
@@ -1,4 +1,7 @@
1
+ import { ApiKeyCredential, cutSecret } from './credentials.js';
2
+ import { namesDelegation, ON_BEHALF_OF_HEADER } from './delegation.js';
1
3
  import { SERVER_VERSION } from './version.js';
4
+ const USER_AGENT = `agledger-mcp-server/${SERVER_VERSION}`;
2
5
  // Strip trailing slashes with a single linear scan. A regex like /\/+$/ is
3
6
  // O(n^2) on inputs of many slashes (CodeQL js/polynomial-redos); this is O(n).
4
7
  function stripTrailingSlashes(s) {
@@ -43,19 +46,30 @@ function appendQueryParam(search, key, value) {
43
46
  }
44
47
  export class ApiClient {
45
48
  apiUrl;
46
- apiKey;
49
+ credential;
47
50
  timeoutMs;
48
- constructor(apiUrl, apiKey, timeoutMs = 30_000) {
51
+ delegation;
52
+ /**
53
+ * `credential` is an API key string or a {@link Credential} (e.g. an OIDC
54
+ * cert credential). `delegation`, when set, supplies the
55
+ * `AGLedger-On-Behalf-Of` token attached to every POST.
56
+ */
57
+ constructor(apiUrl, credential, timeoutMs = 30_000, delegation) {
49
58
  this.apiUrl = stripTrailingSlashes(apiUrl);
50
- this.apiKey = apiKey;
59
+ this.credential = typeof credential === 'string' ? new ApiKeyCredential(credential) : credential;
51
60
  this.timeoutMs = timeoutMs;
61
+ this.delegation = delegation;
62
+ }
63
+ /** Where the delegation token comes from, or undefined when none is configured. Never the token. */
64
+ get delegationOrigin() {
65
+ return this.delegation?.origin;
52
66
  }
53
67
  async request(method, path, options) {
54
68
  const url = new URL(path, this.apiUrl);
55
69
  // Defense-in-depth: pin every request to the configured API origin. A
56
70
  // protocol-relative or absolute `path` (e.g. `//evil.com/x`,
57
71
  // `https://evil.com`) resolves against the base to a different origin, which
58
- // would leak the `Authorization: Bearer <apiKey>` header off-host. No caller
72
+ // would leak the `Authorization: Bearer` header off-host. No caller
59
73
  // may steer the client off-origin.
60
74
  if (url.origin !== new URL(this.apiUrl).origin) {
61
75
  throw new Error(`Refusing to send request off-origin: path "${path}" resolves to ${url.origin}, expected ${new URL(this.apiUrl).origin}.`);
@@ -68,40 +82,88 @@ export class ApiClient {
68
82
  }
69
83
  }
70
84
  const headers = {
71
- Authorization: `Bearer ${this.apiKey}`,
72
85
  Accept: 'application/json',
73
- 'User-Agent': `agledger-mcp-server/${SERVER_VERSION}`,
86
+ 'User-Agent': USER_AGENT,
74
87
  };
75
- if (options?.body !== undefined) {
88
+ // Serialized once. The agent signature covers these exact bytes, and a
89
+ // 401 retry resends them, so the body must never be re-stringified.
90
+ const body = options?.body !== undefined ? JSON.stringify(options.body) : undefined;
91
+ if (body !== undefined) {
76
92
  headers['Content-Type'] = 'application/json';
77
93
  }
78
94
  // POST is the only method the API arms for idempotency: all 18 routes that
79
95
  // declare `idempotent: true` are POST, and on any other method the header is
80
96
  // ignored. A generated key makes each write replay-safe by default. An agent
81
97
  // that retries a tool call after a timeout passes the key it used the first
82
- // time, so the retry dedups instead of notarizing the same work twice.
98
+ // time, so the retry dedups instead of notarizing the same work twice. The
99
+ // 401 retry below reuses the same key for the same reason.
83
100
  if (method.toUpperCase() === 'POST') {
84
101
  headers['Idempotency-Key'] = options?.idempotencyKey ?? crypto.randomUUID();
85
102
  }
103
+ if (options?.anonymous) {
104
+ return this.send(url, method, headers, body);
105
+ }
106
+ // A cert credential signs the body with the key bound to its cert. The
107
+ // Server records the signature in the chain entry on the routes that
108
+ // accept one and ignores the headers elsewhere.
109
+ if (body !== undefined && this.credential.signBody) {
110
+ Object.assign(headers, this.credential.signBody(body));
111
+ }
112
+ // Every route that declares AGLedger-On-Behalf-Of is a POST.
113
+ let onBehalfOf = this.delegation && method.toUpperCase() === 'POST' ? await this.delegation.token() : undefined;
114
+ const withDelegation = (h) => onBehalfOf ? { ...h, [ON_BEHALF_OF_HEADER]: onBehalfOf } : h;
115
+ const ctx = { postAnonymous: (p, b) => this.postAnonymous(p, b) };
116
+ let bearer = await this.credential.bearer(ctx);
117
+ const first = await this.send(url, method, withDelegation({ ...headers, Authorization: `Bearer ${bearer}` }), body);
118
+ if (first.status !== 401)
119
+ return this.scrubbed(first, onBehalfOf);
120
+ // At most one retry, renewing whichever credential the 401 is about. A
121
+ // delegation token is re-read only when the Server names it; otherwise a
122
+ // cert can be revoked or expire server-side before our clock says so, and
123
+ // gets exactly one re-exchange. A second 401 is the answer.
124
+ if (onBehalfOf && namesDelegation(first.body)) {
125
+ const refused = onBehalfOf;
126
+ onBehalfOf = await this.delegation.token(refused);
127
+ if (onBehalfOf === refused)
128
+ return this.scrubbed(first, refused);
129
+ }
130
+ else if (this.credential.renewable) {
131
+ bearer = await this.credential.bearer({ ...ctx, rejected: bearer });
132
+ }
133
+ else {
134
+ return this.scrubbed(first, onBehalfOf);
135
+ }
136
+ const second = await this.send(url, method, withDelegation({ ...headers, Authorization: `Bearer ${bearer}` }), body);
137
+ return this.scrubbed(second, onBehalfOf);
138
+ }
139
+ /** The delegation token never comes back to a tool, even if the Server echoes it. */
140
+ scrubbed(res, onBehalfOf) {
141
+ return onBehalfOf ? { ...res, body: cutSecret(res.body, onBehalfOf) } : res;
142
+ }
143
+ async postAnonymous(path, payload) {
144
+ const res = await this.send(new URL(path, this.apiUrl), 'POST', { Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': USER_AGENT }, JSON.stringify(payload));
145
+ return { status: res.status, body: res.body };
146
+ }
147
+ async send(url, method, headers, body) {
86
148
  const controller = new AbortController();
87
149
  const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
88
150
  try {
89
151
  const res = await fetch(url.toString(), {
90
152
  method,
91
153
  headers,
92
- body: options?.body !== undefined ? JSON.stringify(options.body) : undefined,
154
+ body,
93
155
  signal: controller.signal,
94
156
  });
95
157
  const contentType = res.headers.get('content-type') ?? '';
96
- let body;
158
+ let parsed;
97
159
  if (contentType.includes('json')) {
98
- body = await res.json();
160
+ parsed = await res.json();
99
161
  }
100
162
  else {
101
163
  const text = await res.text();
102
- body = { _raw: text, _contentType: contentType };
164
+ parsed = { _raw: text, _contentType: contentType };
103
165
  }
104
- return { status: res.status, body, ok: res.ok };
166
+ return { status: res.status, body: parsed, ok: res.ok };
105
167
  }
106
168
  finally {
107
169
  clearTimeout(timeout);
@@ -0,0 +1,140 @@
1
+ /**
2
+ * How the server authenticates to the AGLedger API.
3
+ *
4
+ * Two shapes. An API key is a static bearer. An OIDC cert credential exchanges
5
+ * a customer IdP token for a short-lived, Server-signed cert
6
+ * (`POST /v1/auth/oidc/cert`), re-exchanges before the cert runs out, and signs
7
+ * request bodies with the key bound to it.
8
+ *
9
+ * Nothing here writes to disk. The Ed25519 key pair lives in memory for the
10
+ * life of one credential (one server process) and the cert is cached in memory
11
+ * only. The token source is called for EVERY exchange: the Server refuses a
12
+ * token id it has already exchanged (409), and a projected Kubernetes token is
13
+ * rotated on disk underneath a running process, so a token is never reused.
14
+ *
15
+ * No token, cert or key ever reaches an error message, a log line or tool
16
+ * output. Server error bodies and token-command stderr are scrubbed before
17
+ * they are surfaced, because either can echo a token back.
18
+ */
19
+ /** The env vars the server reads a token source from. The CLI reads the same names. */
20
+ export declare const OIDC_ENV: {
21
+ readonly TOKEN_CMD: 'AGLEDGER_OIDC_TOKEN_CMD';
22
+ readonly TOKEN_FILE: 'AGLEDGER_OIDC_TOKEN_FILE';
23
+ readonly AGENT_ID: 'AGLEDGER_OIDC_AGENT_ID';
24
+ };
25
+ /** Replace anything shaped like a JWT with a placeholder. */
26
+ export declare function redactTokens(text: string): string;
27
+ /**
28
+ * Deep-copy a JSON value with every string passed through `redactTokens`, and
29
+ * any occurrence of `secret` cut out. The Server's validation errors echo the
30
+ * offending input back, which on the exchange route is the OIDC token.
31
+ */
32
+ export declare function scrub(value: unknown, secret?: string): unknown;
33
+ /**
34
+ * Deep-copy a JSON value with every occurrence of `secret` cut out, and
35
+ * nothing else touched. For API responses, which may legitimately carry other
36
+ * JWT-shaped values (an agent can call the exchange route itself).
37
+ */
38
+ export declare function cutSecret(value: unknown, secret: string): unknown;
39
+ /** The token source could not produce a usable token. */
40
+ export declare class OidcTokenSourceError extends Error {
41
+ readonly unrotated: boolean;
42
+ readonly code = "OIDC_TOKEN_SOURCE_FAILED";
43
+ /** @param unrotated the source returned the token it returned last time, which is expected for a file between rotations */
44
+ constructor(message: string, unrotated?: boolean);
45
+ }
46
+ /** The Server refused the exchange. `body` is its error response, scrubbed. */
47
+ export declare class OidcExchangeError extends Error {
48
+ readonly status: number;
49
+ readonly body: unknown;
50
+ readonly code = "OIDC_EXCHANGE_FAILED";
51
+ constructor(message: string, status: number, body: unknown);
52
+ /** The Server's own recovery guidance, when its error body carries one. */
53
+ get recoveryHint(): string | undefined;
54
+ }
55
+ /** A function returning a fresh compact OIDC JWT. Called once per exchange. */
56
+ export type OidcTokenGetter = () => string | Promise<string>;
57
+ /** Reads a token file on every call. Kubernetes rotates projected tokens on disk. */
58
+ export declare function oidcTokenFromFile(path: string, origin?: string): OidcTokenGetter;
59
+ export interface TokenCommandOptions {
60
+ /** Kill the command after this long. Default 60s. */
61
+ timeoutMs?: number;
62
+ /** Refuse more stdout than this. Default 64 KiB; a JWT is a few KiB at most. */
63
+ maxStdoutBytes?: number;
64
+ }
65
+ /**
66
+ * Runs a shell command on every call; its stdout is the token. The command
67
+ * runs in its own process group, which is killed on timeout, on oversized
68
+ * output, and after it exits, so nothing it started outlives the call. The
69
+ * command text is never echoed back, since it can carry a secret of its own.
70
+ */
71
+ export declare function oidcTokenFromCommand(command: string, origin?: string, options?: TokenCommandOptions): OidcTokenGetter;
72
+ /**
73
+ * Validate a compact JWT's shape and return its unverified payload. The Server
74
+ * verifies the signature. Errors never quote the token.
75
+ */
76
+ export declare function jwtPayloadOf(token: string, origin: string): Record<string, unknown>;
77
+ /** What the API client hands a credential when it needs a bearer. */
78
+ export interface CredentialContext {
79
+ /** POST a JSON body without any credential attached. Used for the exchange. */
80
+ postAnonymous(path: string, body: unknown): Promise<{
81
+ status: number;
82
+ body: unknown;
83
+ }>;
84
+ /**
85
+ * The bearer that just drew a 401, when this call is the retry. A credential
86
+ * that has already moved past it returns the newer bearer instead of
87
+ * exchanging again, so concurrent 401s cost one exchange, not one each.
88
+ */
89
+ rejected?: string;
90
+ }
91
+ export interface Credential {
92
+ /** Bearer value for the next request. */
93
+ bearer(ctx: CredentialContext): Promise<string>;
94
+ /** True when a 401 should force a re-exchange and one retry. */
95
+ readonly renewable: boolean;
96
+ /** Extra headers that attest to a request body, exactly as it will be sent. */
97
+ signBody?(body: string): Record<string, string>;
98
+ }
99
+ export declare class ApiKeyCredential implements Credential {
100
+ private readonly apiKey;
101
+ readonly renewable = false;
102
+ constructor(apiKey: string);
103
+ bearer(): Promise<string>;
104
+ }
105
+ export interface OidcCertCredentialOptions {
106
+ /** Returns a fresh OIDC JWT. Called once per exchange, never cached. */
107
+ getOidcToken: OidcTokenGetter;
108
+ /** Optional agent binding sent on the exchange (a UUID in the issuer's org). */
109
+ agentId?: string;
110
+ /** Re-exchange once this fraction of the cert's lifetime has passed. Default 0.5. */
111
+ refreshFraction?: number;
112
+ /** Names the token source in errors, e.g. `AGLEDGER_OIDC_TOKEN_FILE`. */
113
+ origin?: string;
114
+ /** Receives one line when a refresh fails while the current cert is still valid. Never a token. */
115
+ onWarning?: (message: string) => void;
116
+ /** Injectable clock, for tests. */
117
+ now?: () => number;
118
+ }
119
+ export declare class OidcCertCredential implements Credential {
120
+ readonly renewable = true;
121
+ private readonly getOidcToken;
122
+ private readonly agentId;
123
+ private readonly refreshFraction;
124
+ private readonly origin;
125
+ private readonly onWarning;
126
+ private readonly now;
127
+ private readonly privateKey;
128
+ private readonly publicX;
129
+ private cert;
130
+ private inflight;
131
+ private lastWarned;
132
+ /** The last token the Server accepted. A token carrying a `jti` is exchangeable once. */
133
+ private lastExchangedToken;
134
+ constructor(options: OidcCertCredentialOptions);
135
+ bearer(ctx: CredentialContext): Promise<string>;
136
+ signBody(body: string): Record<string, string>;
137
+ /** Single-flight: concurrent callers share one exchange. */
138
+ private exchange;
139
+ private runExchange;
140
+ }