@agledger/mcp-server 2.10.1 → 3.0.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/dist/index.js CHANGED
@@ -1,8 +1,11 @@
1
1
  #!/usr/bin/env node
2
+ import { accessSync, constants as fsConstants } from 'node:fs';
2
3
  import { parseArgs } from 'node:util';
3
4
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
5
  import { AgledgerMcpServer, SERVER_VERSION } from './server.js';
5
6
  import { resolveZodCopies, zodSplitWarning } from './zod-integrity.js';
7
+ import { OIDC_ENV, oidcTokenFromCommand, oidcTokenFromFile } from './credentials.js';
8
+ import { ON_BEHALF_OF_ENV } from './delegation.js';
6
9
  /**
7
10
  * Exit codes. A launcher that supervises this process, or a shell wrapping it,
8
11
  * has only the code to go on: stderr is where the MCP client's own diagnostics
@@ -22,6 +25,31 @@ process.on('unhandledRejection', (reason) => {
22
25
  process.stderr.write(`Fatal: unhandled rejection: ${reason instanceof Error ? reason.message : String(reason)}\n`);
23
26
  process.exit(EXIT_RUNTIME_FAILURE);
24
27
  });
28
+ /** Why an API URL cannot be used, or undefined when it can. */
29
+ function apiUrlProblem(url) {
30
+ let parsed;
31
+ try {
32
+ parsed = new URL(url);
33
+ }
34
+ catch {
35
+ return 'is not a URL';
36
+ }
37
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
38
+ return `has scheme '${parsed.protocol}', and only http: and https: are supported`;
39
+ }
40
+ return undefined;
41
+ }
42
+ /** The longest delay setTimeout takes; a larger one fires at once, which would time every call out. */
43
+ const MAX_TIMEOUT_SECONDS = 2_147_483;
44
+ /** Why a timeout in seconds cannot be used, or undefined when it can. */
45
+ function timeoutProblem(raw) {
46
+ const seconds = raw.trim() === '' ? NaN : Number(raw);
47
+ if (!Number.isFinite(seconds) || seconds <= 0)
48
+ return 'is not a positive number of seconds';
49
+ if (seconds > MAX_TIMEOUT_SECONDS)
50
+ return `is more than ${MAX_TIMEOUT_SECONDS} seconds`;
51
+ return undefined;
52
+ }
25
53
  function main() {
26
54
  let values;
27
55
  try {
@@ -29,6 +57,7 @@ function main() {
29
57
  options: {
30
58
  'api-key': { type: 'string', short: 'k' },
31
59
  'api-url': { type: 'string', short: 'u' },
60
+ timeout: { type: 'string' },
32
61
  help: { type: 'boolean', short: 'h' },
33
62
  },
34
63
  strict: true,
@@ -45,14 +74,46 @@ function main() {
45
74
  process.stderr.write(`AGLedger MCP Server v${SERVER_VERSION}
46
75
 
47
76
  Usage: agledger-mcp --api-key <key> --api-url <url>
77
+ AGLEDGER_OIDC_TOKEN_FILE=<path> agledger-mcp --api-url <url>
48
78
 
49
79
  Options:
50
- --api-key, -k AGLedger API key (or AGLEDGER_API_KEY env var). Required.
80
+ --api-key, -k AGLedger API key (or AGLEDGER_API_KEY env var).
51
81
  --api-url, -u Base URL of your AGLedger instance (or AGLEDGER_API_URL env
52
82
  var). Required: AGLedger is self-hosted, so there is no
53
83
  default server to call.
84
+ --timeout Seconds to wait for each API response (or AGLEDGER_TIMEOUT
85
+ env var). Default 30, at most 2147483. A call that times
86
+ out may still have been applied: retry a POST with the
87
+ idempotencyKey the timeout error names, never a new one.
54
88
  --help, -h Show this help message
55
89
 
90
+ Credentials: one is required. An API key wins when set; otherwise an OIDC
91
+ token source is exchanged for a short-lived cert (POST /v1/auth/oidc/cert),
92
+ re-exchanged at half its lifetime and on a 401, and the cert's key signs
93
+ request bodies. Nothing is written to disk.
94
+ AGLEDGER_API_KEY API key (same as --api-key)
95
+ AGLEDGER_OIDC_TOKEN_CMD Shell command whose stdout is an OIDC JWT; run on
96
+ every exchange. Wins over the token file.
97
+ AGLEDGER_OIDC_TOKEN_FILE File holding an OIDC JWT; read on every exchange,
98
+ so a rotated Kubernetes projected token is picked
99
+ up.
100
+ AGLEDGER_OIDC_AGENT_ID Optional assertion of the agent id the token
101
+ binds to. The token decides the agent; a
102
+ different id, or any id on a token bound to
103
+ no agent, is 403 CERT_AGENT_BINDING_MISMATCH.
104
+ Bind an agent with PATCH /v1/agents/{id}
105
+ (oidcIss, oidcSub) or claimMapping.agent_id
106
+ on the trusted issuer.
107
+
108
+ Delegation (optional): when the agent acts for a person or another party, an
109
+ RFC 8693 token-exchange result token is sent as AGLedger-On-Behalf-Of on every
110
+ POST. It comes from the process, never from a tool argument.
111
+ AGLEDGER_ON_BEHALF_OF_CMD Shell command whose stdout is the token. Wins over
112
+ the file.
113
+ AGLEDGER_ON_BEHALF_OF_FILE File holding the token.
114
+ Either is read again once the token's exp has passed, or when the Server
115
+ refuses the delegation with a 401.
116
+
56
117
  Tools:
57
118
  agledger_discover Returns API health, your identity, and available scopes
58
119
  agledger_api Make any AGLedger API call; the API guides you via nextSteps
@@ -62,12 +123,49 @@ Exit codes: 0 clean, 1 runtime failure, 2 usage or configuration error.
62
123
  `);
63
124
  process.exit(0);
64
125
  }
65
- const apiKey = values['api-key'] ?? process.env.AGLEDGER_API_KEY;
126
+ const apiKey = values['api-key'] || process.env.AGLEDGER_API_KEY || undefined;
66
127
  const apiUrl = values['api-url'] ?? process.env.AGLEDGER_API_URL;
67
- if (!apiKey) {
68
- process.stderr.write('Error: --api-key or AGLEDGER_API_KEY environment variable is required.\n');
128
+ const tokenCmd = process.env[OIDC_ENV.TOKEN_CMD] || undefined;
129
+ const tokenFile = process.env[OIDC_ENV.TOKEN_FILE] || undefined;
130
+ const agentId = process.env[OIDC_ENV.AGENT_ID] || undefined;
131
+ if (!apiKey && !tokenCmd && !tokenFile) {
132
+ process.stderr.write('Error: no credential configured. Set one of:\n' +
133
+ ' --api-key <key> or AGLEDGER_API_KEY an AGLedger API key\n' +
134
+ ` ${OIDC_ENV.TOKEN_CMD} a shell command that prints an OIDC JWT\n` +
135
+ ` ${OIDC_ENV.TOKEN_FILE} a file holding an OIDC JWT (e.g. a projected token)\n` +
136
+ 'Run `agledger-mcp --help` for details.\n');
69
137
  process.exit(EXIT_USAGE_ERROR);
70
138
  }
139
+ // Precedence: API key, then command, then file. Say which one lost, so a
140
+ // leftover variable is not silently ignored.
141
+ const ignored = [
142
+ apiKey && tokenCmd ? OIDC_ENV.TOKEN_CMD : undefined,
143
+ (apiKey || tokenCmd) && tokenFile ? OIDC_ENV.TOKEN_FILE : undefined,
144
+ ].filter(Boolean);
145
+ if (ignored.length) {
146
+ process.stderr.write(`Note: ${ignored.join(' and ')} ${ignored.length === 1 ? 'is' : 'are'} set but not used: ` +
147
+ `${apiKey ? 'the API key' : OIDC_ENV.TOKEN_CMD} takes precedence.\n`);
148
+ }
149
+ let oidc;
150
+ if (!apiKey) {
151
+ if (!tokenCmd && tokenFile) {
152
+ // Caught here rather than on the first tool call: a wrong path is a
153
+ // configuration error, and the MCP client may not call a tool for hours.
154
+ try {
155
+ accessSync(tokenFile, fsConstants.R_OK);
156
+ }
157
+ catch {
158
+ process.stderr.write(`Error: ${OIDC_ENV.TOKEN_FILE} names a file that cannot be read: ${tokenFile}\n`);
159
+ process.exit(EXIT_USAGE_ERROR);
160
+ }
161
+ }
162
+ oidc = {
163
+ getOidcToken: tokenCmd ? oidcTokenFromCommand(tokenCmd) : oidcTokenFromFile(tokenFile),
164
+ origin: tokenCmd ? OIDC_ENV.TOKEN_CMD : OIDC_ENV.TOKEN_FILE,
165
+ ...(agentId ? { agentId } : {}),
166
+ onWarning: (message) => process.stderr.write(`Warning: ${message}\n`),
167
+ };
168
+ }
71
169
  // Checked here, alongside the key, rather than left to throw out of the
72
170
  // server constructor: the two are the same class of mistake and deserve the
73
171
  // same treatment. Letting one exit 2 with a plain message while the other
@@ -78,7 +176,51 @@ Exit codes: 0 clean, 1 runtime failure, 2 usage or configuration error.
78
176
  'AGLedger is self-hosted, so the MCP server cannot guess your Server.\n');
79
177
  process.exit(EXIT_USAGE_ERROR);
80
178
  }
81
- const server = new AgledgerMcpServer({ apiKey, apiUrl });
179
+ // A URL that does not parse used to start the server, which then failed
180
+ // every tool call; `localhost:3000` parses, with `localhost:` as its scheme.
181
+ // Only an absolute http(s) URL can reach a Server.
182
+ const urlProblem = apiUrlProblem(apiUrl);
183
+ if (urlProblem) {
184
+ const origin = values['api-url'] !== undefined ? '--api-url' : 'AGLEDGER_API_URL';
185
+ process.stderr.write(`Error: the API URL from ${origin} (${JSON.stringify(apiUrl)}) ${urlProblem}. ` +
186
+ 'Give the full base URL of your AGLedger Server, scheme included, for example https://agledger.internal.\n');
187
+ process.exit(EXIT_USAGE_ERROR);
188
+ }
189
+ const timeoutRaw = values.timeout ?? process.env.AGLEDGER_TIMEOUT;
190
+ if (timeoutRaw !== undefined) {
191
+ const problem = timeoutProblem(timeoutRaw);
192
+ if (problem) {
193
+ const origin = values.timeout !== undefined ? '--timeout' : 'AGLEDGER_TIMEOUT';
194
+ process.stderr.write(`Error: the timeout from ${origin} (${JSON.stringify(timeoutRaw)}) ${problem}. ` +
195
+ 'Give the seconds to wait for each API response, for example 60.\n');
196
+ process.exit(EXIT_USAGE_ERROR);
197
+ }
198
+ }
199
+ const oboCmd = process.env[ON_BEHALF_OF_ENV.CMD] || undefined;
200
+ const oboFile = process.env[ON_BEHALF_OF_ENV.FILE] || undefined;
201
+ let onBehalfOf;
202
+ if (oboCmd) {
203
+ if (oboFile) {
204
+ process.stderr.write(`Note: ${ON_BEHALF_OF_ENV.FILE} is set but not used: ${ON_BEHALF_OF_ENV.CMD} takes precedence.\n`);
205
+ }
206
+ onBehalfOf = { getToken: oidcTokenFromCommand(oboCmd, ON_BEHALF_OF_ENV.CMD), origin: ON_BEHALF_OF_ENV.CMD };
207
+ }
208
+ else if (oboFile) {
209
+ try {
210
+ accessSync(oboFile, fsConstants.R_OK);
211
+ }
212
+ catch {
213
+ process.stderr.write(`Error: ${ON_BEHALF_OF_ENV.FILE} names a file that cannot be read: ${oboFile}\n`);
214
+ process.exit(EXIT_USAGE_ERROR);
215
+ }
216
+ onBehalfOf = { getToken: oidcTokenFromFile(oboFile, ON_BEHALF_OF_ENV.FILE), origin: ON_BEHALF_OF_ENV.FILE };
217
+ }
218
+ const server = new AgledgerMcpServer({
219
+ ...(apiKey ? { apiKey } : { oidc }),
220
+ apiUrl,
221
+ ...(timeoutRaw !== undefined ? { timeoutMs: Math.round(Number(timeoutRaw) * 1000) } : {}),
222
+ ...(onBehalfOf ? { onBehalfOf } : {}),
223
+ });
82
224
  // A version-skewed zod resolution strips every argument description and the
83
225
  // type of every JSON-string argument out of the published tool contract, and
84
226
  // throws nothing while doing it. Two copies of the SAME version render fine,
package/dist/server.d.ts CHANGED
@@ -1,9 +1,25 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { ApiClient } from './api-client.js';
3
+ import { type OidcCertCredentialOptions } from './credentials.js';
4
+ import { type DelegationSourceOptions } from './delegation.js';
3
5
  import { SERVER_VERSION } from './version.js';
4
6
  export { SERVER_VERSION };
5
7
  export interface AgledgerMcpServerOptions {
6
- apiKey: string;
8
+ /** An AGLedger API key. Exactly one of `apiKey` and `oidc` is required. */
9
+ apiKey?: string;
10
+ /**
11
+ * Authenticate with a short-lived cert exchanged for a customer IdP token
12
+ * (`POST /v1/auth/oidc/cert`). `getOidcToken` is called for every exchange
13
+ * and must return a fresh token each time. Exactly one of `apiKey` and
14
+ * `oidc` is required.
15
+ */
16
+ oidc?: OidcCertCredentialOptions;
17
+ /**
18
+ * The source of an RFC 8693 delegation token, sent as `AGLedger-On-Behalf-Of`
19
+ * on every POST when the agent acts for a person or another party. Never a
20
+ * tool argument: the model can neither read nor choose it.
21
+ */
22
+ onBehalfOf?: DelegationSourceOptions;
7
23
  apiUrl?: string;
8
24
  /** Request timeout in milliseconds. Default 30000. */
9
25
  timeoutMs?: number;