@agledger/mcp-server 3.0.0 → 3.2.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 +130 -170
- package/README.md +24 -21
- package/dist/api-client.d.ts +18 -0
- package/dist/api-client.js +80 -20
- package/dist/credentials.d.ts +52 -1
- package/dist/credentials.js +184 -10
- package/dist/delegation.js +2 -1
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +18 -0
- package/dist/index.js +66 -17
- package/dist/server.d.ts +35 -1
- package/dist/server.js +310 -136
- package/dist/zod-integrity.d.ts +7 -7
- package/dist/zod-integrity.js +11 -9
- package/package.json +12 -10
package/dist/credentials.js
CHANGED
|
@@ -18,12 +18,16 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import { spawn } from 'node:child_process';
|
|
20
20
|
import { createHash, generateKeyPairSync, sign } from 'node:crypto';
|
|
21
|
-
import { readFile } from 'node:fs/promises';
|
|
22
|
-
|
|
21
|
+
import { link, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
22
|
+
import { dirname, join } from 'node:path';
|
|
23
|
+
import { errorMessage } from './errors.js';
|
|
24
|
+
/** The env vars the server reads a token source from. */
|
|
23
25
|
export const OIDC_ENV = {
|
|
24
26
|
TOKEN_CMD: 'AGLEDGER_OIDC_TOKEN_CMD',
|
|
25
27
|
TOKEN_FILE: 'AGLEDGER_OIDC_TOKEN_FILE',
|
|
26
28
|
AGENT_ID: 'AGLEDGER_OIDC_AGENT_ID',
|
|
29
|
+
/** A JWK Set file each cert exchange adds the server's public key to, for agledger_verify's agentKeys. */
|
|
30
|
+
AGENT_KEYS_FILE: 'AGLEDGER_AGENT_KEYS_FILE',
|
|
27
31
|
};
|
|
28
32
|
const EXCHANGE_PATH = '/v1/auth/oidc/cert';
|
|
29
33
|
const POP_CONTEXT = 'agledger.oidc.cert.v1\n';
|
|
@@ -36,7 +40,7 @@ const JWT_PATTERN = /eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g;
|
|
|
36
40
|
const REDACTED = '<redacted-token>';
|
|
37
41
|
/** Replace anything shaped like a JWT with a placeholder. */
|
|
38
42
|
export function redactTokens(text) {
|
|
39
|
-
return text.
|
|
43
|
+
return text.replaceAll(JWT_PATTERN, REDACTED);
|
|
40
44
|
}
|
|
41
45
|
/**
|
|
42
46
|
* Deep-copy a JSON value with every string passed through `redactTokens`, and
|
|
@@ -75,6 +79,139 @@ export class OidcTokenSourceError extends Error {
|
|
|
75
79
|
this.name = 'OidcTokenSourceError';
|
|
76
80
|
}
|
|
77
81
|
}
|
|
82
|
+
/** The agent keys file could not be read or written; nothing was signed under the new cert. */
|
|
83
|
+
export class AgentKeysFileError extends Error {
|
|
84
|
+
path;
|
|
85
|
+
code = 'AGENT_KEYS_FILE_FAILED';
|
|
86
|
+
constructor(message, path) {
|
|
87
|
+
super(message);
|
|
88
|
+
this.path = path;
|
|
89
|
+
this.name = 'AgentKeysFileError';
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Add one exchanged cert's public key to the JWK Set at `path`, creating it if
|
|
94
|
+
* needed: `{ keys: [{ publicKeyJwk, certId, agentId, issuedAt, expiresAt }] }`,
|
|
95
|
+
* the shape every AGLedger verifier's agent keys input reads. A key already
|
|
96
|
+
* listed is not added twice. Written through a temp file and a rename; a file
|
|
97
|
+
* that does not hold a `keys` list is refused, never overwritten. The read and
|
|
98
|
+
* the write happen under `<path>.lock`, the same lock the agledger CLI takes,
|
|
99
|
+
* so processes sharing one file each add their key. The same format and rules
|
|
100
|
+
* as the CLI's `--agent-keys-file`.
|
|
101
|
+
*/
|
|
102
|
+
export async function recordAgentKey(path, entry) {
|
|
103
|
+
await withKeysFileLock(path, () => appendAgentKey(path, entry));
|
|
104
|
+
}
|
|
105
|
+
/** Bounds on the agent keys file lock. Mutable so tests can shorten them. */
|
|
106
|
+
export const KEYS_FILE_LOCK = {
|
|
107
|
+
/** How long to wait for another process to release the lock. */
|
|
108
|
+
waitMs: 15_000,
|
|
109
|
+
/** A lock older than this was left by a process that died holding it. */
|
|
110
|
+
staleMs: 10_000,
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Run `fn` holding `<path>.lock`, an exclusively created file the holder
|
|
114
|
+
* deletes when done. A lock older than `KEYS_FILE_LOCK.staleMs` is taken over:
|
|
115
|
+
* renamed aside (atomic, so one waiter wins), and put back if what moved was a
|
|
116
|
+
* fresh lock rather than the stale one. Matches the agledger CLI's lock.
|
|
117
|
+
*/
|
|
118
|
+
async function withKeysFileLock(path, fn) {
|
|
119
|
+
const lock = `${path}.lock`;
|
|
120
|
+
const deadline = Date.now() + KEYS_FILE_LOCK.waitMs;
|
|
121
|
+
for (let delay = 5;; delay = Math.min(delay * 2, 100)) {
|
|
122
|
+
try {
|
|
123
|
+
await (await open(lock, 'wx')).close();
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
catch (err) {
|
|
127
|
+
const code = err.code;
|
|
128
|
+
if (code !== 'EEXIST') {
|
|
129
|
+
throw new AgentKeysFileError(`Cannot create the agent keys file lock ${lock} (${code ?? errorMessage(err)}).`, path);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (await breakStaleLock(lock))
|
|
133
|
+
continue;
|
|
134
|
+
if (Date.now() >= deadline) {
|
|
135
|
+
throw new AgentKeysFileError(`The agent keys file ${path} stayed locked by another process for ${KEYS_FILE_LOCK.waitMs / 1000}s. If no agledger process is running, delete ${lock}.`, path);
|
|
136
|
+
}
|
|
137
|
+
await new Promise((r) => setTimeout(r, delay + Math.random() * delay));
|
|
138
|
+
}
|
|
139
|
+
try {
|
|
140
|
+
return await fn();
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
await rm(lock, { force: true });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** Remove `lock` if it is stale. True when the caller should try to take it again. */
|
|
147
|
+
async function breakStaleLock(lock) {
|
|
148
|
+
let seen;
|
|
149
|
+
try {
|
|
150
|
+
seen = await stat(lock);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return true; // Released between our open and stat.
|
|
154
|
+
}
|
|
155
|
+
if (Date.now() - seen.mtimeMs <= KEYS_FILE_LOCK.staleMs)
|
|
156
|
+
return false;
|
|
157
|
+
const aside = `${lock}.${process.pid}.${Date.now()}.stale`;
|
|
158
|
+
try {
|
|
159
|
+
await rename(lock, aside);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return true; // Another waiter moved it first.
|
|
163
|
+
}
|
|
164
|
+
const moved = await stat(aside).catch(() => null);
|
|
165
|
+
if (moved !== null && moved.ino !== seen.ino) {
|
|
166
|
+
// A waiter replaced the stale lock between our stat and rename: put its
|
|
167
|
+
// lock back. If the path was taken again meanwhile, that holder keeps it.
|
|
168
|
+
await link(aside, lock).catch(() => { });
|
|
169
|
+
}
|
|
170
|
+
await rm(aside, { force: true });
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
async function appendAgentKey(path, entry) {
|
|
174
|
+
let doc = { keys: [] };
|
|
175
|
+
let text = null;
|
|
176
|
+
try {
|
|
177
|
+
text = await readFile(path, 'utf8');
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
if (err.code !== 'ENOENT') {
|
|
181
|
+
throw new AgentKeysFileError(`Cannot read the agent keys file ${path} (${err.code ?? errorMessage(err)}).`, path);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (text !== null && text.trim() !== '') {
|
|
185
|
+
let parsed;
|
|
186
|
+
try {
|
|
187
|
+
parsed = JSON.parse(text);
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
throw new AgentKeysFileError(`The agent keys file ${path} is not JSON; it was left as it is.`, path);
|
|
191
|
+
}
|
|
192
|
+
if (parsed === null || typeof parsed !== 'object' || !Array.isArray(parsed.keys)) {
|
|
193
|
+
throw new AgentKeysFileError(`The agent keys file ${path} does not hold a {"keys": [...]} JWK Set; it was left as it is.`, path);
|
|
194
|
+
}
|
|
195
|
+
doc = parsed;
|
|
196
|
+
}
|
|
197
|
+
const x = entry.publicKeyJwk.x;
|
|
198
|
+
const listed = doc.keys.some((k) => {
|
|
199
|
+
const jwk = k !== null && typeof k === 'object' && 'publicKeyJwk' in k ? k.publicKeyJwk : k;
|
|
200
|
+
return jwk !== null && typeof jwk === 'object' && jwk.x === x;
|
|
201
|
+
});
|
|
202
|
+
if (listed)
|
|
203
|
+
return;
|
|
204
|
+
doc.keys.push(entry);
|
|
205
|
+
const temp = join(dirname(path), `.${process.pid}.${Date.now()}.agent-keys.tmp`);
|
|
206
|
+
try {
|
|
207
|
+
await writeFile(temp, JSON.stringify(doc, null, 2) + '\n');
|
|
208
|
+
await rename(temp, path);
|
|
209
|
+
}
|
|
210
|
+
catch (err) {
|
|
211
|
+
await rm(temp, { force: true });
|
|
212
|
+
throw new AgentKeysFileError(`Cannot write the agent keys file ${path} (${err.code ?? errorMessage(err)}).`, path);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
78
215
|
/** The Server refused the exchange. `body` is its error response, scrubbed. */
|
|
79
216
|
export class OidcExchangeError extends Error {
|
|
80
217
|
status;
|
|
@@ -129,6 +266,14 @@ function killTree(pid) {
|
|
|
129
266
|
// Already gone.
|
|
130
267
|
}
|
|
131
268
|
}
|
|
269
|
+
/** Process groups of token commands that are running now, so a shutdown can end them. */
|
|
270
|
+
const runningCommands = new Set();
|
|
271
|
+
/** Kill every token command still running. For a signal handler: the commands run detached, so they would outlive this process. */
|
|
272
|
+
export function killRunningTokenCommands() {
|
|
273
|
+
for (const pid of runningCommands)
|
|
274
|
+
killTree(pid);
|
|
275
|
+
runningCommands.clear();
|
|
276
|
+
}
|
|
132
277
|
/**
|
|
133
278
|
* Runs a shell command on every call; its stdout is the token. The command
|
|
134
279
|
* runs in its own process group, which is killed on timeout, on oversized
|
|
@@ -150,9 +295,12 @@ export function oidcTokenFromCommand(command, origin = OIDC_ENV.TOKEN_CMD, optio
|
|
|
150
295
|
});
|
|
151
296
|
}
|
|
152
297
|
catch (err) {
|
|
153
|
-
reject(new OidcTokenSourceError(`${origin}: could not run the token command: ${
|
|
298
|
+
reject(new OidcTokenSourceError(`${origin}: could not run the token command: ${errorMessage(err)}`));
|
|
154
299
|
return;
|
|
155
300
|
}
|
|
301
|
+
const pid = child.pid;
|
|
302
|
+
if (pid !== undefined)
|
|
303
|
+
runningCommands.add(pid);
|
|
156
304
|
const out = [];
|
|
157
305
|
let outBytes = 0;
|
|
158
306
|
let stderr = '';
|
|
@@ -163,10 +311,12 @@ export function oidcTokenFromCommand(command, origin = OIDC_ENV.TOKEN_CMD, optio
|
|
|
163
311
|
settled = true;
|
|
164
312
|
clearTimeout(timer);
|
|
165
313
|
killTree(child.pid);
|
|
314
|
+
if (pid !== undefined)
|
|
315
|
+
runningCommands.delete(pid);
|
|
166
316
|
reject(new OidcTokenSourceError(`${origin}: ${message}`));
|
|
167
317
|
};
|
|
168
318
|
const timer = setTimeout(() => fail(`the token command did not finish within ${timeoutMs / 1000}s and was killed.`), timeoutMs);
|
|
169
|
-
child.stdout
|
|
319
|
+
child.stdout?.on('data', (d) => {
|
|
170
320
|
outBytes += d.length;
|
|
171
321
|
if (outBytes > maxStdout) {
|
|
172
322
|
fail(`the token command printed more than ${maxStdout} bytes, which is not a token; it was killed.`);
|
|
@@ -174,7 +324,7 @@ export function oidcTokenFromCommand(command, origin = OIDC_ENV.TOKEN_CMD, optio
|
|
|
174
324
|
}
|
|
175
325
|
out.push(d);
|
|
176
326
|
});
|
|
177
|
-
child.stderr
|
|
327
|
+
child.stderr?.setEncoding('utf8').on('data', (d) => {
|
|
178
328
|
if (stderr.length < STDERR_LIMIT * 2)
|
|
179
329
|
stderr += d;
|
|
180
330
|
});
|
|
@@ -186,6 +336,8 @@ export function oidcTokenFromCommand(command, origin = OIDC_ENV.TOKEN_CMD, optio
|
|
|
186
336
|
clearTimeout(timer);
|
|
187
337
|
// Anything it left running in the background goes with it.
|
|
188
338
|
killTree(child.pid);
|
|
339
|
+
if (pid !== undefined)
|
|
340
|
+
runningCommands.delete(pid);
|
|
189
341
|
if (code === 0) {
|
|
190
342
|
resolve(Buffer.concat(out).toString('utf8'));
|
|
191
343
|
return;
|
|
@@ -239,6 +391,7 @@ export class OidcCertCredential {
|
|
|
239
391
|
renewable = true;
|
|
240
392
|
getOidcToken;
|
|
241
393
|
agentId;
|
|
394
|
+
agentKeysFile;
|
|
242
395
|
refreshFraction;
|
|
243
396
|
origin;
|
|
244
397
|
onWarning;
|
|
@@ -257,6 +410,7 @@ export class OidcCertCredential {
|
|
|
257
410
|
}
|
|
258
411
|
this.getOidcToken = options.getOidcToken;
|
|
259
412
|
this.agentId = options.agentId;
|
|
413
|
+
this.agentKeysFile = options.agentKeysFile || undefined;
|
|
260
414
|
this.refreshFraction = fraction;
|
|
261
415
|
this.origin = options.origin ?? 'OIDC token source';
|
|
262
416
|
this.onWarning = options.onWarning;
|
|
@@ -268,6 +422,14 @@ export class OidcCertCredential {
|
|
|
268
422
|
throw new Error('Ed25519 public key export carried no x coordinate.');
|
|
269
423
|
this.publicX = jwk.x;
|
|
270
424
|
}
|
|
425
|
+
/**
|
|
426
|
+
* The public half of this server's key pair, as sent at every exchange. The
|
|
427
|
+
* cert carries only its thumbprint; this is the key agledger_verify's
|
|
428
|
+
* agentKeys needs to re-verify what this server signed. One per process.
|
|
429
|
+
*/
|
|
430
|
+
get publicKeyJwk() {
|
|
431
|
+
return { kty: 'OKP', crv: 'Ed25519', x: this.publicX };
|
|
432
|
+
}
|
|
271
433
|
async bearer(ctx) {
|
|
272
434
|
const current = this.cert;
|
|
273
435
|
const t = this.now();
|
|
@@ -292,7 +454,7 @@ export class OidcCertCredential {
|
|
|
292
454
|
// has not rotated yet fails the same way on every call until it does.
|
|
293
455
|
// An unrotated token file is the normal state between rotations, not a
|
|
294
456
|
// failure worth a line on stderr.
|
|
295
|
-
const message =
|
|
457
|
+
const message = errorMessage(err);
|
|
296
458
|
const expected = err instanceof OidcTokenSourceError && err.unrotated;
|
|
297
459
|
if (!expected && this.lastWarned !== message) {
|
|
298
460
|
this.lastWarned = message;
|
|
@@ -328,7 +490,7 @@ export class OidcCertCredential {
|
|
|
328
490
|
catch (err) {
|
|
329
491
|
if (err instanceof OidcTokenSourceError)
|
|
330
492
|
throw err;
|
|
331
|
-
throw new OidcTokenSourceError(`${this.origin}: ${redactTokens(
|
|
493
|
+
throw new OidcTokenSourceError(`${this.origin}: ${redactTokens(errorMessage(err))}`);
|
|
332
494
|
}
|
|
333
495
|
if (!token)
|
|
334
496
|
throw new OidcTokenSourceError(`${this.origin}: the token source returned nothing.`);
|
|
@@ -346,7 +508,7 @@ export class OidcCertCredential {
|
|
|
346
508
|
const proofOfPossession = sign(null, Buffer.from(`${POP_CONTEXT}${sub}`, 'utf8'), this.privateKey).toString('base64');
|
|
347
509
|
const body = {
|
|
348
510
|
oidcToken: token,
|
|
349
|
-
publicKeyJwk:
|
|
511
|
+
publicKeyJwk: this.publicKeyJwk,
|
|
350
512
|
proofOfPossession,
|
|
351
513
|
};
|
|
352
514
|
if (this.agentId)
|
|
@@ -356,7 +518,7 @@ export class OidcCertCredential {
|
|
|
356
518
|
res = await ctx.postAnonymous(EXCHANGE_PATH, body);
|
|
357
519
|
}
|
|
358
520
|
catch (err) {
|
|
359
|
-
throw new OidcExchangeError(`OIDC cert exchange failed: ${redactTokens(
|
|
521
|
+
throw new OidcExchangeError(`OIDC cert exchange failed: ${redactTokens(errorMessage(err))}`, 0, null);
|
|
360
522
|
}
|
|
361
523
|
if (res.status !== 201) {
|
|
362
524
|
const scrubbed = scrub(res.body, token);
|
|
@@ -370,6 +532,18 @@ export class OidcCertCredential {
|
|
|
370
532
|
if (typeof out?.certJws !== 'string' || !Number.isFinite(lifetime) || lifetime <= 0) {
|
|
371
533
|
throw new OidcExchangeError(`OIDC cert exchange failed: POST ${EXCHANGE_PATH} returned 201 without a certJws and a valid cert.issuedAt/expiresAt.`, res.status, null);
|
|
372
534
|
}
|
|
535
|
+
// Recorded before the cert is used, so nothing is signed under a key the
|
|
536
|
+
// file does not list.
|
|
537
|
+
if (this.agentKeysFile !== undefined) {
|
|
538
|
+
const certInfo = out.cert ?? {};
|
|
539
|
+
await recordAgentKey(this.agentKeysFile, {
|
|
540
|
+
publicKeyJwk: this.publicKeyJwk,
|
|
541
|
+
certId: certInfo.id,
|
|
542
|
+
agentId: certInfo.agentId,
|
|
543
|
+
issuedAt: certInfo.issuedAt,
|
|
544
|
+
expiresAt: certInfo.expiresAt,
|
|
545
|
+
});
|
|
546
|
+
}
|
|
373
547
|
this.lastExchangedToken = token;
|
|
374
548
|
this.lastWarned = undefined;
|
|
375
549
|
const receivedAt = this.now();
|
package/dist/delegation.js
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* refuses it with a 401 that names the delegation.
|
|
14
14
|
*/
|
|
15
15
|
import { jwtPayloadOf, OidcTokenSourceError, redactTokens } from './credentials.js';
|
|
16
|
+
import { errorMessage } from './errors.js';
|
|
16
17
|
export const ON_BEHALF_OF_ENV = {
|
|
17
18
|
CMD: 'AGLEDGER_ON_BEHALF_OF_CMD',
|
|
18
19
|
FILE: 'AGLEDGER_ON_BEHALF_OF_FILE',
|
|
@@ -82,7 +83,7 @@ export class DelegationSource {
|
|
|
82
83
|
}
|
|
83
84
|
catch (err) {
|
|
84
85
|
this.cached = undefined;
|
|
85
|
-
const message = redactTokens(
|
|
86
|
+
const message = redactTokens(errorMessage(err));
|
|
86
87
|
throw new DelegationSourceError(message.startsWith(this.origin) ? message : `${this.origin}: ${message}`);
|
|
87
88
|
}
|
|
88
89
|
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** An error's message, or the text of a thrown value that is not an Error. */
|
|
2
|
+
export declare function errorMessage(err: unknown): string;
|
|
3
|
+
/** An error as text. `fetch failed` says nothing on its own; the cause (ECONNREFUSED, ENOTFOUND, a certificate error) says why. */
|
|
4
|
+
export declare function describeError(err: unknown): string;
|
|
5
|
+
/** The code, else the message, of what a failed fetch was caused by. */
|
|
6
|
+
export declare function fetchCause(err: Error): string | undefined;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** An error's message, or the text of a thrown value that is not an Error. */
|
|
2
|
+
export function errorMessage(err) {
|
|
3
|
+
return err instanceof Error ? err.message : String(err);
|
|
4
|
+
}
|
|
5
|
+
/** An error as text. `fetch failed` says nothing on its own; the cause (ECONNREFUSED, ENOTFOUND, a certificate error) says why. */
|
|
6
|
+
export function describeError(err) {
|
|
7
|
+
if (!(err instanceof Error))
|
|
8
|
+
return String(err);
|
|
9
|
+
const detail = fetchCause(err);
|
|
10
|
+
return detail && !err.message.includes(detail) ? `${err.message} (${detail})` : err.message;
|
|
11
|
+
}
|
|
12
|
+
/** The code, else the message, of what a failed fetch was caused by. */
|
|
13
|
+
export function fetchCause(err) {
|
|
14
|
+
const cause = err.cause;
|
|
15
|
+
if (typeof cause?.code === 'string')
|
|
16
|
+
return cause.code;
|
|
17
|
+
return typeof cause?.message === 'string' ? cause.message : undefined;
|
|
18
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { accessSync, constants as fsConstants } from 'node:fs';
|
|
3
|
+
import { resolve as resolvePath } from 'node:path';
|
|
3
4
|
import { parseArgs } from 'node:util';
|
|
4
|
-
import { StdioServerTransport } from '@modelcontextprotocol/
|
|
5
|
+
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
|
|
5
6
|
import { AgledgerMcpServer, SERVER_VERSION } from './server.js';
|
|
6
7
|
import { resolveZodCopies, zodSplitWarning } from './zod-integrity.js';
|
|
7
|
-
import { OIDC_ENV, oidcTokenFromCommand, oidcTokenFromFile } from './credentials.js';
|
|
8
|
+
import { OIDC_ENV, killRunningTokenCommands, oidcTokenFromCommand, oidcTokenFromFile } from './credentials.js';
|
|
8
9
|
import { ON_BEHALF_OF_ENV } from './delegation.js';
|
|
10
|
+
import { errorMessage } from './errors.js';
|
|
9
11
|
/**
|
|
10
12
|
* Exit codes. A launcher that supervises this process, or a shell wrapping it,
|
|
11
13
|
* has only the code to go on: stderr is where the MCP client's own diagnostics
|
|
@@ -14,17 +16,37 @@ import { ON_BEHALF_OF_ENV } from './delegation.js';
|
|
|
14
16
|
*/
|
|
15
17
|
const EXIT_RUNTIME_FAILURE = 1;
|
|
16
18
|
const EXIT_USAGE_ERROR = 2;
|
|
17
|
-
// These handlers
|
|
18
|
-
//
|
|
19
|
-
//
|
|
19
|
+
// These handlers print the error and then exit non-zero explicitly: returning
|
|
20
|
+
// from an uncaughtException handler suppresses Node's default non-zero exit,
|
|
21
|
+
// so an unstartable server would otherwise report its fatal error and exit 0.
|
|
20
22
|
process.on('uncaughtException', (err) => {
|
|
21
|
-
process.stderr.write(`Fatal: ${err
|
|
23
|
+
process.stderr.write(`Fatal: ${fatalText(err)}\n`);
|
|
22
24
|
process.exit(EXIT_RUNTIME_FAILURE);
|
|
23
25
|
});
|
|
24
26
|
process.on('unhandledRejection', (reason) => {
|
|
25
|
-
process.stderr.write(`Fatal: unhandled rejection: ${
|
|
27
|
+
process.stderr.write(`Fatal: unhandled rejection: ${fatalText(reason)}\n`);
|
|
26
28
|
process.exit(EXIT_RUNTIME_FAILURE);
|
|
27
29
|
});
|
|
30
|
+
// A token command runs in its own process group, so it would outlive a server
|
|
31
|
+
// that is told to stop. End it first, then exit with the conventional code.
|
|
32
|
+
for (const [signal, code] of [['SIGINT', 130], ['SIGTERM', 143]]) {
|
|
33
|
+
process.on(signal, () => {
|
|
34
|
+
killRunningTokenCommands();
|
|
35
|
+
process.exit(code);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* A fatal error as text: the message and its cause, or with DEBUG set the
|
|
40
|
+
* whole stack (which carries the message and, for a cause, the cause's).
|
|
41
|
+
*/
|
|
42
|
+
function fatalText(err) {
|
|
43
|
+
if (!(err instanceof Error))
|
|
44
|
+
return String(err);
|
|
45
|
+
if (process.env.DEBUG)
|
|
46
|
+
return err.stack ?? err.message;
|
|
47
|
+
const cause = err.cause instanceof Error ? err.cause.message : typeof err.cause === 'string' ? err.cause : undefined;
|
|
48
|
+
return cause && !err.message.includes(cause) ? `${err.message} (${cause})` : err.message;
|
|
49
|
+
}
|
|
28
50
|
/** Why an API URL cannot be used, or undefined when it can. */
|
|
29
51
|
function apiUrlProblem(url) {
|
|
30
52
|
let parsed;
|
|
@@ -46,6 +68,9 @@ function timeoutProblem(raw) {
|
|
|
46
68
|
const seconds = raw.trim() === '' ? NaN : Number(raw);
|
|
47
69
|
if (!Number.isFinite(seconds) || seconds <= 0)
|
|
48
70
|
return 'is not a positive number of seconds';
|
|
71
|
+
// The wait is whole milliseconds; anything that rounds to 0 would time every call out at once.
|
|
72
|
+
if (Math.round(seconds * 1000) < 1)
|
|
73
|
+
return 'is less than 1 millisecond';
|
|
49
74
|
if (seconds > MAX_TIMEOUT_SECONDS)
|
|
50
75
|
return `is more than ${MAX_TIMEOUT_SECONDS} seconds`;
|
|
51
76
|
return undefined;
|
|
@@ -59,6 +84,7 @@ function main() {
|
|
|
59
84
|
'api-url': { type: 'string', short: 'u' },
|
|
60
85
|
timeout: { type: 'string' },
|
|
61
86
|
help: { type: 'boolean', short: 'h' },
|
|
87
|
+
version: { type: 'boolean', short: 'V' },
|
|
62
88
|
},
|
|
63
89
|
strict: true,
|
|
64
90
|
}));
|
|
@@ -67,11 +93,18 @@ function main() {
|
|
|
67
93
|
// strict parseArgs throws on an unknown flag. That is a usage error the
|
|
68
94
|
// caller can fix, not a crash, so say so and point at --help rather than
|
|
69
95
|
// letting it surface as an uncaught exception.
|
|
70
|
-
process.stderr.write(`Error: ${
|
|
96
|
+
process.stderr.write(`Error: ${errorMessage(err)}\nRun \`agledger-mcp --help\` for usage.\n`);
|
|
71
97
|
process.exit(EXIT_USAGE_ERROR);
|
|
72
98
|
}
|
|
99
|
+
if (values.version) {
|
|
100
|
+
// Nothing has been connected yet, so stdout is still free for a caller to
|
|
101
|
+
// capture; once the server starts it belongs to the MCP transport.
|
|
102
|
+
process.stdout.write(`agledger-mcp ${SERVER_VERSION}\n`);
|
|
103
|
+
process.exit(0);
|
|
104
|
+
}
|
|
73
105
|
if (values.help) {
|
|
74
|
-
|
|
106
|
+
// stdout, like --version: nothing has been connected yet, so it is still free.
|
|
107
|
+
process.stdout.write(`AGLedger MCP Server v${SERVER_VERSION}
|
|
75
108
|
|
|
76
109
|
Usage: agledger-mcp --api-key <key> --api-url <url>
|
|
77
110
|
AGLEDGER_OIDC_TOKEN_FILE=<path> agledger-mcp --api-url <url>
|
|
@@ -86,6 +119,7 @@ Options:
|
|
|
86
119
|
out may still have been applied: retry a POST with the
|
|
87
120
|
idempotencyKey the timeout error names, never a new one.
|
|
88
121
|
--help, -h Show this help message
|
|
122
|
+
--version, -V Print the version and exit
|
|
89
123
|
|
|
90
124
|
Credentials: one is required. An API key wins when set; otherwise an OIDC
|
|
91
125
|
token source is exchanged for a short-lived cert (POST /v1/auth/oidc/cert),
|
|
@@ -104,6 +138,12 @@ request bodies. Nothing is written to disk.
|
|
|
104
138
|
Bind an agent with PATCH /v1/agents/{id}
|
|
105
139
|
(oidcIss, oidcSub) or claimMapping.agent_id
|
|
106
140
|
on the trusted issuer.
|
|
141
|
+
AGLEDGER_AGENT_KEYS_FILE Optional. A JWK Set file the server's cert public
|
|
142
|
+
key is added to on each exchange, before the cert
|
|
143
|
+
is used, so its agent signatures can be
|
|
144
|
+
re-verified offline (agledger_verify agentKeys,
|
|
145
|
+
or --agent-keys on a verifier). Public keys only.
|
|
146
|
+
agledger_discover also shows the key.
|
|
107
147
|
|
|
108
148
|
Delegation (optional): when the agent acts for a person or another party, an
|
|
109
149
|
RFC 8693 token-exchange result token is sent as AGLedger-On-Behalf-Of on every
|
|
@@ -116,7 +156,7 @@ POST. It comes from the process, never from a tool argument.
|
|
|
116
156
|
|
|
117
157
|
Tools:
|
|
118
158
|
agledger_discover Returns API health, your identity, and available scopes
|
|
119
|
-
agledger_api Make any AGLedger API call;
|
|
159
|
+
agledger_api Make any AGLedger API call; most responses carry nextSteps
|
|
120
160
|
agledger_verify Verify an audit export offline (hash chain + signatures)
|
|
121
161
|
|
|
122
162
|
Exit codes: 0 clean, 1 runtime failure, 2 usage or configuration error.
|
|
@@ -128,6 +168,8 @@ Exit codes: 0 clean, 1 runtime failure, 2 usage or configuration error.
|
|
|
128
168
|
const tokenCmd = process.env[OIDC_ENV.TOKEN_CMD] || undefined;
|
|
129
169
|
const tokenFile = process.env[OIDC_ENV.TOKEN_FILE] || undefined;
|
|
130
170
|
const agentId = process.env[OIDC_ENV.AGENT_ID] || undefined;
|
|
171
|
+
const agentKeysPath = process.env[OIDC_ENV.AGENT_KEYS_FILE];
|
|
172
|
+
const agentKeysFile = agentKeysPath ? resolvePath(agentKeysPath) : undefined;
|
|
131
173
|
if (!apiKey && !tokenCmd && !tokenFile) {
|
|
132
174
|
process.stderr.write('Error: no credential configured. Set one of:\n' +
|
|
133
175
|
' --api-key <key> or AGLEDGER_API_KEY an AGLedger API key\n' +
|
|
@@ -159,10 +201,16 @@ Exit codes: 0 clean, 1 runtime failure, 2 usage or configuration error.
|
|
|
159
201
|
process.exit(EXIT_USAGE_ERROR);
|
|
160
202
|
}
|
|
161
203
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
204
|
+
// The checks above leave one of the two set; the command wins.
|
|
205
|
+
const source = tokenCmd
|
|
206
|
+
? { getOidcToken: oidcTokenFromCommand(tokenCmd), origin: OIDC_ENV.TOKEN_CMD }
|
|
207
|
+
: tokenFile
|
|
208
|
+
? { getOidcToken: oidcTokenFromFile(tokenFile), origin: OIDC_ENV.TOKEN_FILE }
|
|
209
|
+
: undefined;
|
|
210
|
+
oidc = source && {
|
|
211
|
+
...source,
|
|
165
212
|
...(agentId ? { agentId } : {}),
|
|
213
|
+
...(agentKeysFile ? { agentKeysFile } : {}),
|
|
166
214
|
onWarning: (message) => process.stderr.write(`Warning: ${message}\n`),
|
|
167
215
|
};
|
|
168
216
|
}
|
|
@@ -176,9 +224,10 @@ Exit codes: 0 clean, 1 runtime failure, 2 usage or configuration error.
|
|
|
176
224
|
'AGLedger is self-hosted, so the MCP server cannot guess your Server.\n');
|
|
177
225
|
process.exit(EXIT_USAGE_ERROR);
|
|
178
226
|
}
|
|
179
|
-
//
|
|
180
|
-
//
|
|
181
|
-
//
|
|
227
|
+
// Refuse a URL that does not parse, or that parses with another scheme:
|
|
228
|
+
// `localhost:3000` parses, with `localhost:` as its scheme. Only an absolute
|
|
229
|
+
// http(s) URL can reach a Server, so starting with anything else would fail
|
|
230
|
+
// every tool call.
|
|
182
231
|
const urlProblem = apiUrlProblem(apiUrl);
|
|
183
232
|
if (urlProblem) {
|
|
184
233
|
const origin = values['api-url'] !== undefined ? '--api-url' : 'AGLEDGER_API_URL';
|
|
@@ -232,7 +281,7 @@ Exit codes: 0 clean, 1 runtime failure, 2 usage or configuration error.
|
|
|
232
281
|
process.stderr.write(zodSplitWarning(zod));
|
|
233
282
|
const transport = new StdioServerTransport();
|
|
234
283
|
server.mcp.connect(transport).catch((err) => {
|
|
235
|
-
process.stderr.write(`Fatal: failed to start MCP server: ${
|
|
284
|
+
process.stderr.write(`Fatal: failed to start MCP server: ${fatalText(err)}\n`);
|
|
236
285
|
process.exit(EXIT_RUNTIME_FAILURE);
|
|
237
286
|
});
|
|
238
287
|
}
|
package/dist/server.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { McpServer } from '@modelcontextprotocol/
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/server';
|
|
2
2
|
import { ApiClient } from './api-client.js';
|
|
3
3
|
import { type OidcCertCredentialOptions } from './credentials.js';
|
|
4
4
|
import { type DelegationSourceOptions } from './delegation.js';
|
|
@@ -24,9 +24,43 @@ export interface AgledgerMcpServerOptions {
|
|
|
24
24
|
/** Request timeout in milliseconds. Default 30000. */
|
|
25
25
|
timeoutMs?: number;
|
|
26
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* What the export's entry count was held to. A chain cut from the end still
|
|
29
|
+
* verifies entry by entry, so the report names the stated count, if any, that
|
|
30
|
+
* stood behind the number of entries it verified.
|
|
31
|
+
*/
|
|
32
|
+
export declare function entryCountLine(count: {
|
|
33
|
+
expectedEntries: number | null;
|
|
34
|
+
statedEntries: number | null;
|
|
35
|
+
}): string;
|
|
36
|
+
/**
|
|
37
|
+
* The summary lines on the evidence bodies an `?evidence=true` export
|
|
38
|
+
* inlines, each re-bound to the hash its entry signs. Silent when every one
|
|
39
|
+
* re-bound, or when the export carries none.
|
|
40
|
+
*/
|
|
41
|
+
export declare function evidenceLines(counts: {
|
|
42
|
+
present: number;
|
|
43
|
+
verified: number;
|
|
44
|
+
clientHashed: number;
|
|
45
|
+
failed: number;
|
|
46
|
+
}): string[];
|
|
47
|
+
/**
|
|
48
|
+
* The summary lines on the sealed federation messages. `failed` ones failed a
|
|
49
|
+
* check (a key given for the hub that did not match among them); the rest of
|
|
50
|
+
* the unverified ones came from a hub no key was given for.
|
|
51
|
+
*/
|
|
52
|
+
export declare function peerMessageLines(wire: {
|
|
53
|
+
present: number;
|
|
54
|
+
verified: number;
|
|
55
|
+
failed: number;
|
|
56
|
+
afterRetirement: number;
|
|
57
|
+
}): string[];
|
|
27
58
|
export declare class AgledgerMcpServer {
|
|
28
59
|
readonly mcp: McpServer;
|
|
29
60
|
readonly client: ApiClient;
|
|
61
|
+
/** The cert credential, when the server authenticates with an OIDC token source. */
|
|
62
|
+
private readonly oidcCredential;
|
|
63
|
+
private readonly agentKeysFile;
|
|
30
64
|
constructor(options: AgledgerMcpServerOptions);
|
|
31
65
|
private registerTools;
|
|
32
66
|
private registerResources;
|