@lexapi/mcp 0.2.0 → 0.5.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 +110 -0
- package/LICENSE +1 -1
- package/README.md +128 -35
- package/dist/client.d.ts +125 -21
- package/dist/client.js +442 -97
- package/dist/credentials.d.ts +67 -0
- package/dist/credentials.js +118 -0
- package/dist/errors.d.ts +53 -0
- package/dist/errors.js +313 -0
- package/dist/http-entry.js +19 -2
- package/dist/http-server.d.ts +48 -2
- package/dist/http-server.js +544 -111
- package/dist/index.js +18 -60
- package/dist/oauth/body.d.ts +5 -0
- package/dist/oauth/body.js +35 -0
- package/dist/oauth/config.d.ts +59 -0
- package/dist/oauth/config.js +149 -0
- package/dist/oauth/exchange.d.ts +196 -0
- package/dist/oauth/exchange.js +573 -0
- package/dist/oauth/jwt.d.ts +124 -0
- package/dist/oauth/jwt.js +352 -0
- package/dist/oauth/redact.d.ts +1 -0
- package/dist/oauth/redact.js +23 -0
- package/dist/oauth/upstream.d.ts +41 -0
- package/dist/oauth/upstream.js +95 -0
- package/dist/server.d.ts +62 -0
- package/dist/server.js +100 -0
- package/dist/shape.d.ts +115 -0
- package/dist/shape.js +1043 -0
- package/dist/tools.d.ts +29 -8
- package/dist/tools.js +1071 -216
- package/dist/webhookUrl.d.ts +4 -0
- package/dist/webhookUrl.js +114 -0
- package/package.json +23 -15
- package/dist/types.d.ts +0 -43
- package/dist/types.js +0 -7
package/dist/client.js
CHANGED
|
@@ -1,133 +1,478 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
1
|
+
import { LexAPIError, LexAPITransportError, parseErrorBody } from './errors.js';
|
|
2
|
+
import { PACKAGE_VERSION } from './version.js';
|
|
3
|
+
export const DEFAULT_BASE_URL = 'https://lex-api.com/api/v1';
|
|
4
|
+
/**
|
|
5
|
+
* Deadline for one tool call (all attempts, backoff and 429 sleeps included).
|
|
6
|
+
* MCP clients give up after their own request timeout (the TypeScript SDK
|
|
7
|
+
* default is 60 s; Claude Code: MCP_TOOL_TIMEOUT), so stop a few seconds
|
|
8
|
+
* earlier and return an actionable message instead of the client's generic
|
|
9
|
+
* -32001. LexAPI's own upstream budgets (EUR-Lex fetch 90 s, semantic
|
|
10
|
+
* legislation 45 s, citation network 30 s) can exceed this on a cold live
|
|
11
|
+
* fetch; users who raise their client's timeout raise LEXAPI_TIMEOUT_MS too.
|
|
12
|
+
*/
|
|
13
|
+
export const DEFAULT_TIMEOUT_MS = 55_000;
|
|
14
|
+
/** Printable ASCII, no spaces — anything else cannot be a LexAPI key (and would end up in an undici error message). */
|
|
15
|
+
const KEY_RE = /^[\x21-\x7e]+$/;
|
|
16
|
+
export function isWellFormedKey(key) {
|
|
17
|
+
return KEY_RE.test(key);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* A 429 (or an incomplete national search 503) whose Retry-After is longer
|
|
21
|
+
* than this is returned to the model instead of slept on. Waits up to and
|
|
22
|
+
* including this value are slept on.
|
|
23
|
+
*/
|
|
24
|
+
const MAX_RETRY_AFTER_SLEEP_S = 10;
|
|
25
|
+
/**
|
|
26
|
+
* An incomplete national search 503 is retried only when at least this much
|
|
27
|
+
* of the call's deadline is left after the wait: a search that could not
|
|
28
|
+
* complete needs a full attempt, not the minimum one.
|
|
29
|
+
*/
|
|
30
|
+
const MIN_INCOMPLETE_RETRY_REMAINING_MS = 15_000;
|
|
31
|
+
/** Response headers worth surfacing to a model; everything else is dropped. */
|
|
32
|
+
const KEPT_HEADERS = [
|
|
33
|
+
'x-source',
|
|
34
|
+
'x-language',
|
|
35
|
+
'x-language-fallback',
|
|
36
|
+
'x-text-available',
|
|
37
|
+
'x-warning',
|
|
38
|
+
'x-search-source',
|
|
39
|
+
'x-search-cache',
|
|
40
|
+
'x-ignored-documenttypes',
|
|
41
|
+
'x-corpus-version',
|
|
42
|
+
'x-export-total',
|
|
43
|
+
'x-export-truncated',
|
|
44
|
+
// National-law monthly allowance for FREE/STARTER/PROFESSIONAL accounts;
|
|
45
|
+
// absent for BUSINESS and higher (no separate limit).
|
|
46
|
+
'x-national-limit',
|
|
47
|
+
'x-national-remaining',
|
|
48
|
+
'x-national-reset',
|
|
49
|
+
];
|
|
50
|
+
/** No retry or 429 sleep is started unless at least this much of the call's deadline would remain. */
|
|
51
|
+
const MIN_ATTEMPT_MS = 2000;
|
|
52
|
+
function apiKeyAuth(key) {
|
|
53
|
+
const headers = { 'x-api-key': key };
|
|
54
|
+
return { headers: () => headers };
|
|
11
55
|
}
|
|
12
56
|
export class LexAPIClient {
|
|
13
|
-
|
|
57
|
+
auth;
|
|
14
58
|
baseUrl;
|
|
15
59
|
maxRetries;
|
|
60
|
+
timeoutMs;
|
|
61
|
+
fetchImpl;
|
|
62
|
+
sleep;
|
|
63
|
+
signal;
|
|
64
|
+
now;
|
|
65
|
+
opts;
|
|
16
66
|
constructor(opts) {
|
|
17
|
-
if (
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
67
|
+
if (opts.auth) {
|
|
68
|
+
this.auth = opts.auth;
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
const key = (opts.apiKey ?? '').trim();
|
|
72
|
+
if (!key)
|
|
73
|
+
throw new Error('LexAPI API key is missing.');
|
|
74
|
+
// Never include the key itself in this message.
|
|
75
|
+
if (!isWellFormedKey(key))
|
|
76
|
+
throw new Error('LexAPI API key contains whitespace or control characters — paste it again as a single line.');
|
|
77
|
+
this.auth = apiKeyAuth(key);
|
|
78
|
+
}
|
|
79
|
+
this.opts = opts;
|
|
80
|
+
this.signal = opts.signal;
|
|
81
|
+
this.now = opts.now ?? Date.now;
|
|
82
|
+
this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
83
|
+
this.maxRetries = opts.maxRetries ?? 1;
|
|
84
|
+
this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
85
|
+
this.fetchImpl = opts.fetch ?? fetch;
|
|
86
|
+
this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
87
|
+
}
|
|
88
|
+
/** A client for one MCP request: its cancellation signal and timeout. */
|
|
89
|
+
forCall(call) {
|
|
90
|
+
return new LexAPIClient({
|
|
91
|
+
...this.opts,
|
|
92
|
+
...(call.signal ? { signal: call.signal } : {}),
|
|
93
|
+
...(call.timeoutMs ? { timeoutMs: call.timeoutMs } : {}),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
get timeout() {
|
|
97
|
+
return this.timeoutMs;
|
|
98
|
+
}
|
|
99
|
+
credentialHeaders() {
|
|
100
|
+
if (this.signal?.aborted)
|
|
101
|
+
throw new LexAPITransportError('the request was cancelled by the client', false, true);
|
|
102
|
+
const h = this.auth.headers({ signal: this.signal });
|
|
103
|
+
if (!(h instanceof Promise))
|
|
104
|
+
return h;
|
|
105
|
+
return h.catch((err) => {
|
|
106
|
+
if (this.signal?.aborted)
|
|
107
|
+
throw new LexAPITransportError('the request was cancelled by the client', false, true);
|
|
108
|
+
throw err;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/** Low-level request. Throws LexAPIError (HTTP error) or LexAPITransportError. */
|
|
112
|
+
async request(method, path, opts = {}) {
|
|
25
113
|
const url = new URL(this.baseUrl + path);
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
114
|
+
for (const [k, v] of Object.entries(opts.query ?? {})) {
|
|
115
|
+
if (v === undefined || v === null || v === '')
|
|
116
|
+
continue;
|
|
117
|
+
if (Array.isArray(v)) {
|
|
118
|
+
if (v.length)
|
|
119
|
+
url.searchParams.set(k, v.join(','));
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
30
122
|
url.searchParams.set(k, String(v));
|
|
31
123
|
}
|
|
32
124
|
}
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
'x-api-key': this.apiKey,
|
|
37
|
-
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
|
|
38
|
-
},
|
|
39
|
-
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
125
|
+
const baseHeaders = {
|
|
126
|
+
accept: opts.ndjson ? 'application/x-ndjson, application/json' : 'application/json',
|
|
127
|
+
'user-agent': `lexapi-mcp/${PACKAGE_VERSION}`,
|
|
40
128
|
};
|
|
129
|
+
if (opts.body !== undefined)
|
|
130
|
+
baseHeaders['content-type'] = 'application/json';
|
|
131
|
+
const canRetry = opts.retry !== false;
|
|
132
|
+
// ONE deadline for the whole call — attempts, backoff and 429 sleeps all
|
|
133
|
+
// come out of it, so retries can never push a call past the timeout the
|
|
134
|
+
// MCP client is waiting on.
|
|
135
|
+
const deadline = this.now() + this.timeoutMs;
|
|
136
|
+
const remaining = () => deadline - this.now();
|
|
137
|
+
const canWait = (ms) => remaining() - ms >= MIN_ATTEMPT_MS;
|
|
41
138
|
let attempt = 0;
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
if (
|
|
46
|
-
|
|
47
|
-
await sleep(Math.max(1, retryAfter) * 1000);
|
|
48
|
-
attempt++;
|
|
49
|
-
continue;
|
|
139
|
+
let authRetried = false;
|
|
140
|
+
let incompleteRetried = false;
|
|
141
|
+
for (;;) {
|
|
142
|
+
if (remaining() <= 0) {
|
|
143
|
+
throw new LexAPITransportError(`no response within ${Math.round(this.timeoutMs / 1000)} s`, true);
|
|
50
144
|
}
|
|
51
|
-
//
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
145
|
+
// Per attempt: an OAuth credential re-exchanges after a 401. Its errors
|
|
146
|
+
// (exchange refused, AS unreachable) propagate as they are.
|
|
147
|
+
// An API key resolves synchronously (no extra tick before fetch).
|
|
148
|
+
const pending = this.credentialHeaders();
|
|
149
|
+
const credential = pending instanceof Promise ? await pending : pending;
|
|
150
|
+
if (this.signal?.aborted)
|
|
151
|
+
throw new LexAPITransportError('the request was cancelled by the client', false, true);
|
|
152
|
+
const headers = { ...baseHeaders, ...credential };
|
|
153
|
+
let res;
|
|
154
|
+
const attemptSignal = combineSignals(this.signal, AbortSignal.timeout(Math.max(1, remaining())));
|
|
155
|
+
try {
|
|
156
|
+
res = await this.fetchImpl(url, {
|
|
157
|
+
method,
|
|
158
|
+
headers,
|
|
159
|
+
...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),
|
|
160
|
+
signal: attemptSignal.signal,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
catch (err) {
|
|
164
|
+
attemptSignal.dispose();
|
|
165
|
+
if (this.signal?.aborted)
|
|
166
|
+
throw new LexAPITransportError('the request was cancelled by the client', false, true);
|
|
167
|
+
const timedOut = err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError');
|
|
168
|
+
const backoff = 500 * 2 ** (attempt + 1);
|
|
169
|
+
if (!timedOut && canRetry && attempt < this.maxRetries && canWait(backoff)) {
|
|
170
|
+
attempt++;
|
|
171
|
+
await this.sleep(backoff);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
// Never forward the runtime's message: undici quotes header values
|
|
175
|
+
// (the key) in some of them. Report only the error class / errno.
|
|
176
|
+
const reason = timedOut
|
|
177
|
+
? `no response within ${Math.round(this.timeoutMs / 1000)} s`
|
|
178
|
+
: networkReason(err);
|
|
179
|
+
throw new LexAPITransportError(reason, timedOut);
|
|
180
|
+
}
|
|
181
|
+
if (this.signal?.aborted) {
|
|
182
|
+
attemptSignal.dispose();
|
|
183
|
+
await discard(res);
|
|
184
|
+
throw new LexAPITransportError('the request was cancelled by the client', false, true);
|
|
185
|
+
}
|
|
186
|
+
if (res.status === 401 && this.auth.onUnauthorized) {
|
|
187
|
+
let peek = '';
|
|
188
|
+
try {
|
|
189
|
+
peek = await res.clone().text();
|
|
190
|
+
}
|
|
191
|
+
catch { /* unreadable body */ }
|
|
192
|
+
const verdict = await this.auth.onUnauthorized({ wwwAuthenticate: res.headers.get('www-authenticate'), body: peek });
|
|
193
|
+
// At most one credential retry per call, whatever the credential says.
|
|
194
|
+
if (verdict === 'retry' && !authRetried) {
|
|
195
|
+
attemptSignal.dispose();
|
|
196
|
+
await discard(res);
|
|
197
|
+
authRetried = true;
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (verdict instanceof Error) {
|
|
201
|
+
attemptSignal.dispose();
|
|
202
|
+
await discard(res);
|
|
203
|
+
throw verdict;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
// A used-up legacy quota (QUOTA_EXHAUSTED) cannot succeed
|
|
207
|
+
// before it refills, whatever its Retry-After says: never retried.
|
|
208
|
+
if (res.status === 429 && canRetry && attempt < this.maxRetries && !(await isQuotaExhausted(res))) {
|
|
209
|
+
const wait = retryAfterSeconds(res);
|
|
210
|
+
const waitMs = wait === undefined ? Infinity : Math.max(1, wait) * 1000;
|
|
211
|
+
if (wait !== undefined && wait <= MAX_RETRY_AFTER_SLEEP_S && canWait(waitMs)) {
|
|
212
|
+
attemptSignal.dispose();
|
|
213
|
+
await discard(res);
|
|
214
|
+
attempt++;
|
|
215
|
+
await this.sleep(waitMs);
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
// An incomplete national semantic search (503, partialReason
|
|
220
|
+
// SEARCH_INCOMPLETE) is retried at most once per call, only after the
|
|
221
|
+
// wait it names (Retry-After header, else the body's retryAfter) and
|
|
222
|
+
// only with enough of the deadline left; without a wait the same
|
|
223
|
+
// search has repeatedly come back incomplete, so it is not retried.
|
|
224
|
+
const incomplete = res.status === 503 ? await incompleteSearch(res) : undefined;
|
|
225
|
+
if (incomplete) {
|
|
226
|
+
const wait = retryAfterSeconds(res) ?? incomplete.retryAfter;
|
|
227
|
+
const waitMs = wait === undefined ? Infinity : Math.max(1, wait) * 1000;
|
|
228
|
+
if (canRetry && !incompleteRetried && attempt < this.maxRetries && wait !== undefined
|
|
229
|
+
&& wait <= MAX_RETRY_AFTER_SLEEP_S && remaining() - waitMs >= MIN_INCOMPLETE_RETRY_REMAINING_MS) {
|
|
230
|
+
attemptSignal.dispose();
|
|
231
|
+
await discard(res);
|
|
232
|
+
attempt++;
|
|
233
|
+
incompleteRetried = true;
|
|
234
|
+
await this.sleep(waitMs);
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
// 500/502/503 are transient and refunded in full on credit plans.
|
|
240
|
+
// 504 is NOT retried: it already means a 90 s upstream budget ran out.
|
|
241
|
+
// Nor is a 503 TIMEOUT: a server-side time budget ran out, and the
|
|
242
|
+
// same request would run out of it again.
|
|
243
|
+
const backoff = 500 * 2 ** (attempt + 1);
|
|
244
|
+
if ((res.status === 500 || res.status === 502 || res.status === 503) && canRetry && attempt < this.maxRetries && canWait(backoff)
|
|
245
|
+
&& !(res.status === 503 && await isServerTimeout(res))) {
|
|
246
|
+
attemptSignal.dispose();
|
|
247
|
+
await discard(res);
|
|
248
|
+
attempt++;
|
|
249
|
+
await this.sleep(backoff);
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
let text;
|
|
254
|
+
try {
|
|
255
|
+
text = res.status === 204 ? '' : await res.text();
|
|
256
|
+
}
|
|
257
|
+
catch (err) {
|
|
258
|
+
if (this.signal?.aborted)
|
|
259
|
+
throw new LexAPITransportError('the request was cancelled by the client', false, true);
|
|
260
|
+
const timedOut = err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError');
|
|
261
|
+
throw new LexAPITransportError(timedOut ? `no response within ${Math.round(this.timeoutMs / 1000)} s` : networkReason(err), timedOut);
|
|
262
|
+
}
|
|
263
|
+
finally {
|
|
264
|
+
attemptSignal.dispose();
|
|
265
|
+
}
|
|
266
|
+
const kept = {};
|
|
267
|
+
for (const h of KEPT_HEADERS) {
|
|
268
|
+
const v = res.headers.get(h);
|
|
269
|
+
if (v !== null)
|
|
270
|
+
kept[h] = v;
|
|
56
271
|
}
|
|
57
|
-
const text = await res.text();
|
|
58
|
-
const json = text ? safeJson(text) : {};
|
|
59
272
|
if (!res.ok) {
|
|
60
|
-
const
|
|
61
|
-
|
|
273
|
+
const parsed = parseErrorBody(safeJson(text), text, res.status);
|
|
274
|
+
const quota = parsed.code === 'QUOTA_EXHAUSTED';
|
|
275
|
+
throw new LexAPIError(res.status, parsed.code, parsed.message, parsed.details,
|
|
276
|
+
// A quota 429 has no meaningful retry-after.
|
|
277
|
+
quota ? undefined : (retryAfterSeconds(res) ?? parsed.retryAfter), parsed.resetsAt);
|
|
278
|
+
}
|
|
279
|
+
let body;
|
|
280
|
+
if (opts.ndjson && !(res.headers.get('content-type') ?? '').includes('application/json')) {
|
|
281
|
+
body = {
|
|
282
|
+
lines: text
|
|
283
|
+
.split('\n')
|
|
284
|
+
.filter((l) => l.trim())
|
|
285
|
+
.map((l) => safeJson(l) ?? { _unparsed: l.slice(0, 200) }),
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
body = text ? (safeJson(text) ?? { _unparsed: text.slice(0, 500) }) : {};
|
|
62
290
|
}
|
|
63
|
-
return
|
|
291
|
+
return { status: res.status, body: body, headers: kept };
|
|
64
292
|
}
|
|
65
293
|
}
|
|
66
|
-
// ──
|
|
67
|
-
|
|
68
|
-
|
|
294
|
+
// ── Meta ─────────────────────────────────────────────────────────
|
|
295
|
+
info() { return this.request('GET', '/info'); }
|
|
296
|
+
// ── Search & documents ───────────────────────────────────────────
|
|
297
|
+
search(body) { return this.request('POST', '/search', { body }); }
|
|
298
|
+
getDocument(body) { return this.request('POST', '/documentContent', { body }); }
|
|
299
|
+
getDocumentsBatch(body) { return this.request('POST', '/documentContent/batch', { body }); }
|
|
300
|
+
getMetadata(body) { return this.request('POST', '/documents/metadata', { body }); }
|
|
301
|
+
getDocumentByUrl(body) { return this.request('POST', '/documents/url', { body }); }
|
|
302
|
+
recentDocuments(query) { return this.request('GET', '/documents/recent', { query }); }
|
|
303
|
+
resolve(body) { return this.request('POST', '/resolve', { body }); }
|
|
304
|
+
// ── Version history (observation snapshots) ──────────────────────
|
|
305
|
+
listVersions(celex, query) {
|
|
306
|
+
return this.request('GET', `/documents/${enc(celex)}/versions`, { query });
|
|
69
307
|
}
|
|
70
|
-
|
|
71
|
-
return this.request('
|
|
308
|
+
getVersion(celex, version, query) {
|
|
309
|
+
return this.request('GET', `/documents/${enc(celex)}/versions/${version}`, { query });
|
|
72
310
|
}
|
|
73
|
-
|
|
74
|
-
return this.request('
|
|
311
|
+
getAtDate(celex, date, query) {
|
|
312
|
+
return this.request('GET', `/documents/${enc(celex)}/at/${enc(date)}`, { query });
|
|
75
313
|
}
|
|
76
|
-
|
|
77
|
-
|
|
314
|
+
// ── Export (NDJSON) ──────────────────────────────────────────────
|
|
315
|
+
exportCorpus(query) {
|
|
316
|
+
return this.request('GET', '/export', { query, ndjson: true });
|
|
78
317
|
}
|
|
79
|
-
|
|
80
|
-
|
|
318
|
+
// ── Semantic ─────────────────────────────────────────────────────
|
|
319
|
+
semanticCaseLaw(body) { return this.request('POST', '/search/semantic', { body }); }
|
|
320
|
+
semanticLegislation(body) { return this.request('POST', '/legislation/semantic', { body }); }
|
|
321
|
+
// ── Citations ────────────────────────────────────────────────────
|
|
322
|
+
extractCitations(body) { return this.request('POST', '/citations/extract', { body }); }
|
|
323
|
+
citedBy(celex, query) { return this.request('GET', `/citations/cited-by/${enc(celex)}`, { query }); }
|
|
324
|
+
cites(celex, query) { return this.request('GET', `/citations/cites/${enc(celex)}`, { query }); }
|
|
325
|
+
citationNetwork(celex, query) {
|
|
326
|
+
return this.request('GET', `/citations/network/${enc(celex)}`, { query });
|
|
81
327
|
}
|
|
82
|
-
|
|
83
|
-
return this.request('GET', `/citations/
|
|
328
|
+
citationPath(from, to, query) {
|
|
329
|
+
return this.request('GET', `/citations/path/${enc(from)}/${enc(to)}`, { query });
|
|
84
330
|
}
|
|
85
|
-
|
|
86
|
-
|
|
331
|
+
related(celex, query) { return this.request('GET', `/citations/related/${enc(celex)}`, { query }); }
|
|
332
|
+
citationStats(query = {}) { return this.request('GET', '/citations/stats', { query }); }
|
|
333
|
+
transposition(celex, query = {}) {
|
|
334
|
+
return this.request('GET', `/citations/transposition/${enc(celex)}`, { query });
|
|
87
335
|
}
|
|
88
|
-
|
|
89
|
-
return this.request('GET', `/citations/
|
|
336
|
+
counterparts(id, query = {}) {
|
|
337
|
+
return this.request('GET', `/citations/counterparts/${enc(id)}`, { query });
|
|
90
338
|
}
|
|
91
|
-
|
|
92
|
-
|
|
339
|
+
// ── National law ─────────────────────────────────────────────────
|
|
340
|
+
// Jurisdiction codes are lower-cased on the wire (route pattern is
|
|
341
|
+
// registry-generated from lower-case codes).
|
|
342
|
+
nationalCoverage() { return this.request('GET', '/national/coverage'); }
|
|
343
|
+
getNationalDocument(jurisdiction, id, query) {
|
|
344
|
+
return this.request('GET', `/${jurisdiction.toLowerCase()}/documents/${enc(id)}`, { query });
|
|
93
345
|
}
|
|
94
|
-
|
|
95
|
-
return this.request('
|
|
346
|
+
listNationalDocuments(jurisdiction, query) {
|
|
347
|
+
return this.request('GET', `/${jurisdiction.toLowerCase()}/documents`, { query });
|
|
96
348
|
}
|
|
349
|
+
nationalSemanticCaseLaw(jurisdiction, body) {
|
|
350
|
+
return this.request('POST', `/${jurisdiction.toLowerCase()}/search/semantic`, { body });
|
|
351
|
+
}
|
|
352
|
+
nationalSemanticLegislation(jurisdiction, body) {
|
|
353
|
+
return this.request('POST', `/${jurisdiction.toLowerCase()}/legislation/semantic`, { body });
|
|
354
|
+
}
|
|
355
|
+
// ── Webhooks ─────────────────────────────────────────────────────
|
|
356
|
+
listWebhooks() { return this.request('GET', '/webhooks'); }
|
|
357
|
+
getWebhook(id) { return this.request('GET', `/webhooks/${enc(id)}`); }
|
|
358
|
+
webhookDeliveries(id, query) {
|
|
359
|
+
return this.request('GET', `/webhooks/${enc(id)}/deliveries`, { query });
|
|
360
|
+
}
|
|
361
|
+
// A retried create would make a second webhook — never auto-retried.
|
|
362
|
+
createWebhook(body) { return this.request('POST', '/webhooks', { body, retry: false }); }
|
|
363
|
+
updateWebhook(id, body) { return this.request('PUT', `/webhooks/${enc(id)}`, { body }); }
|
|
364
|
+
// A lost response + retry would turn a successful delete into a confusing 404.
|
|
365
|
+
deleteWebhook(id) { return this.request('DELETE', `/webhooks/${enc(id)}`, { retry: false }); }
|
|
366
|
+
// A retried test would POST to the user's endpoint twice.
|
|
367
|
+
testWebhook(id) { return this.request('POST', `/webhooks/${enc(id)}/test`, { retry: false }); }
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* The call's cancellation signal combined with this attempt's timeout.
|
|
371
|
+
* `dispose()` detaches the listeners of the pre-20.3 fallback (no
|
|
372
|
+
* AbortSignal.any), so long-lived call signals don't accumulate them.
|
|
373
|
+
*/
|
|
374
|
+
export function combineSignals(a, b) {
|
|
375
|
+
if (!a)
|
|
376
|
+
return { signal: b, dispose: () => { } };
|
|
377
|
+
if (typeof AbortSignal.any === 'function')
|
|
378
|
+
return { signal: AbortSignal.any([a, b]), dispose: () => { } };
|
|
379
|
+
const c = new AbortController();
|
|
380
|
+
const dispose = () => {
|
|
381
|
+
a.removeEventListener('abort', abort);
|
|
382
|
+
b.removeEventListener('abort', abort);
|
|
383
|
+
};
|
|
384
|
+
function abort() {
|
|
385
|
+
dispose();
|
|
386
|
+
c.abort();
|
|
387
|
+
}
|
|
388
|
+
if (a.aborted || b.aborted) {
|
|
389
|
+
c.abort();
|
|
390
|
+
return { signal: c.signal, dispose: () => { } };
|
|
391
|
+
}
|
|
392
|
+
a.addEventListener('abort', abort, { once: true });
|
|
393
|
+
b.addEventListener('abort', abort, { once: true });
|
|
394
|
+
return { signal: c.signal, dispose };
|
|
97
395
|
}
|
|
98
|
-
|
|
99
|
-
|
|
396
|
+
/** A key-free description of a network failure: errno code if there is one, else the error class. */
|
|
397
|
+
function networkReason(err) {
|
|
398
|
+
const cause = err instanceof Error ? err.cause : undefined;
|
|
399
|
+
const code = cause && typeof cause === 'object' && typeof cause.code === 'string'
|
|
400
|
+
? cause.code
|
|
401
|
+
: undefined;
|
|
402
|
+
if (code && /^[A-Z_]+$/.test(code))
|
|
403
|
+
return `network error ${code}`;
|
|
404
|
+
if (err instanceof TypeError && /invalid header/i.test(err.message))
|
|
405
|
+
return 'invalid request header (check the API key)';
|
|
406
|
+
return `network error (${err instanceof Error ? err.name : 'unknown'})`;
|
|
407
|
+
}
|
|
408
|
+
function enc(s) {
|
|
409
|
+
return encodeURIComponent(s);
|
|
410
|
+
}
|
|
411
|
+
async function discard(res) {
|
|
412
|
+
try {
|
|
413
|
+
await res.body?.cancel();
|
|
414
|
+
}
|
|
415
|
+
catch {
|
|
416
|
+
/* already consumed */
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
/** Peeks a 429 body (on a clone) for `code: "QUOTA_EXHAUSTED"`. */
|
|
420
|
+
async function isQuotaExhausted(res) {
|
|
421
|
+
try {
|
|
422
|
+
const j = safeJson(await res.clone().text());
|
|
423
|
+
return !!j && typeof j === 'object' && j.code === 'QUOTA_EXHAUSTED';
|
|
424
|
+
}
|
|
425
|
+
catch {
|
|
426
|
+
return false;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
/** Peeks a 503 body for `partialReason: "SEARCH_INCOMPLETE"`; returns its `retryAfter` (seconds) when set. */
|
|
430
|
+
async function incompleteSearch(res) {
|
|
431
|
+
try {
|
|
432
|
+
const j = safeJson(await res.clone().text());
|
|
433
|
+
if (!j || typeof j !== 'object')
|
|
434
|
+
return undefined;
|
|
435
|
+
const o = j;
|
|
436
|
+
if (o.partialReason !== 'SEARCH_INCOMPLETE')
|
|
437
|
+
return undefined;
|
|
438
|
+
const ra = o.retryAfter;
|
|
439
|
+
return typeof ra === 'number' && Number.isFinite(ra) && ra >= 0 ? { retryAfter: Math.ceil(ra) } : {};
|
|
440
|
+
}
|
|
441
|
+
catch {
|
|
442
|
+
return undefined;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
async function isServerTimeout(res) {
|
|
446
|
+
try {
|
|
447
|
+
const j = safeJson(await res.clone().text());
|
|
448
|
+
if (!j || typeof j !== 'object')
|
|
449
|
+
return false;
|
|
450
|
+
const o = j;
|
|
451
|
+
return o.code === 'TIMEOUT' || o.partialReason === 'TIMEOUT';
|
|
452
|
+
}
|
|
453
|
+
catch {
|
|
454
|
+
return false;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
function retryAfterSeconds(res) {
|
|
458
|
+
const raw = res.headers.get('retry-after');
|
|
459
|
+
if (!raw)
|
|
460
|
+
return undefined;
|
|
461
|
+
const n = Number(raw);
|
|
462
|
+
if (Number.isFinite(n) && n >= 0)
|
|
463
|
+
return Math.ceil(n);
|
|
464
|
+
const date = Date.parse(raw);
|
|
465
|
+
if (!Number.isNaN(date))
|
|
466
|
+
return Math.max(0, Math.ceil((date - Date.now()) / 1000));
|
|
467
|
+
return undefined;
|
|
100
468
|
}
|
|
101
469
|
function safeJson(text) {
|
|
470
|
+
if (!text)
|
|
471
|
+
return undefined;
|
|
102
472
|
try {
|
|
103
473
|
return JSON.parse(text);
|
|
104
474
|
}
|
|
105
475
|
catch {
|
|
106
|
-
return
|
|
476
|
+
return undefined;
|
|
107
477
|
}
|
|
108
478
|
}
|
|
109
|
-
// Gateway returns either the typed envelope { error: { code, message } } or
|
|
110
|
-
// the legacy flat shape { error: "slug", message: "..." }. Handle both;
|
|
111
|
-
// fall back to HTTP status when neither is present.
|
|
112
|
-
function extractError(json, text, status) {
|
|
113
|
-
const fallbackMessage = text || `HTTP ${status}`;
|
|
114
|
-
const fallbackSlug = `http_${status}`;
|
|
115
|
-
if (!json || typeof json !== 'object') {
|
|
116
|
-
return { slug: fallbackSlug, message: fallbackMessage };
|
|
117
|
-
}
|
|
118
|
-
const j = json;
|
|
119
|
-
const e = j.error;
|
|
120
|
-
if (e && typeof e === 'object') {
|
|
121
|
-
const eo = e;
|
|
122
|
-
const slug = typeof eo.code === 'string' ? eo.code : fallbackSlug;
|
|
123
|
-
const message = typeof eo.message === 'string'
|
|
124
|
-
? eo.message
|
|
125
|
-
: typeof j.message === 'string'
|
|
126
|
-
? j.message
|
|
127
|
-
: fallbackMessage;
|
|
128
|
-
return { slug, message };
|
|
129
|
-
}
|
|
130
|
-
const slug = typeof e === 'string' ? e : fallbackSlug;
|
|
131
|
-
const message = typeof j.message === 'string' ? j.message : fallbackMessage;
|
|
132
|
-
return { slug, message };
|
|
133
|
-
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { IncomingMessage } from 'node:http';
|
|
2
|
+
/**
|
|
3
|
+
* Longest credential value considered at all. Checked on the value as soon
|
|
4
|
+
* as it is read from its header, BEFORE any routing, so an oversized token can
|
|
5
|
+
* never fall through to the API-key path (both API keys and access tokens
|
|
6
|
+
* are far shorter).
|
|
7
|
+
*/
|
|
8
|
+
export declare const MAX_CREDENTIAL_LENGTH = 8192;
|
|
9
|
+
export declare function isApiKeyShaped(value: string): boolean;
|
|
10
|
+
/** Could be a JWT / JWS (or a fragment of one): API keys never contain a '.'. */
|
|
11
|
+
export declare function isTokenShaped(value: string): boolean;
|
|
12
|
+
export type RejectReason = 'too_long' | 'token_as_api_key' | 'not_an_api_key';
|
|
13
|
+
/** The credential an MCP request carries. */
|
|
14
|
+
export type Credential = {
|
|
15
|
+
kind: 'none';
|
|
16
|
+
} | {
|
|
17
|
+
kind: 'apiKey';
|
|
18
|
+
key: string;
|
|
19
|
+
} | {
|
|
20
|
+
kind: 'oauth';
|
|
21
|
+
token: string;
|
|
22
|
+
}
|
|
23
|
+
/** A value that must not be used at all — answered 401 locally, never forwarded. */
|
|
24
|
+
| {
|
|
25
|
+
kind: 'rejected';
|
|
26
|
+
header: 'authorization' | 'x-api-key';
|
|
27
|
+
reason: RejectReason;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* The caller's LexAPI key as 0.3.0 read it: `Authorization: Bearer <key>`,
|
|
31
|
+
* else `x-api-key: <key>`. A value with inner whitespace is returned as-is
|
|
32
|
+
* so it is reported as malformed, not as missing.
|
|
33
|
+
*/
|
|
34
|
+
export declare function extractApiKey(req: IncomingMessage): string | null;
|
|
35
|
+
/**
|
|
36
|
+
* OAuth off: 0.3.0's precedence and key handling, except that a value which
|
|
37
|
+
* is too long or token-shaped is refused instead of being forwarded.
|
|
38
|
+
*
|
|
39
|
+
* OAuth on:
|
|
40
|
+
* - `x-api-key` wins when present; it must be API-key shaped — a JWT (or
|
|
41
|
+
* anything else) there is refused, never forwarded and never exchanged;
|
|
42
|
+
* - `Authorization: Bearer <lex_…>` is an API key;
|
|
43
|
+
* - any other Bearer value is an OAuth access token (garbage is then
|
|
44
|
+
* refused by validation with 401 invalid_token);
|
|
45
|
+
* - the length cap applies before any of this.
|
|
46
|
+
*/
|
|
47
|
+
export declare function classifyCredential(req: IncomingMessage, oauthEnabled: boolean): Credential;
|
|
48
|
+
/** How the client address was derived for one request. */
|
|
49
|
+
export interface ClientAddress {
|
|
50
|
+
ip: string;
|
|
51
|
+
/** Entries in X-Forwarded-For (0 when absent). */
|
|
52
|
+
xffEntries: number;
|
|
53
|
+
/**
|
|
54
|
+
* LEXAPI_MCP_TRUST_PROXY_HOPS > 0 but X-Forwarded-For has fewer entries:
|
|
55
|
+
* the hop count is too high for this path (or a proxy replaces the header),
|
|
56
|
+
* so the socket peer — a proxy — is used instead. Warn; never silent.
|
|
57
|
+
*/
|
|
58
|
+
short: boolean;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The client address used for per-IP limits. With LEXAPI_MCP_TRUST_PROXY_HOPS
|
|
62
|
+
* = N > 0 the server sits behind N reverse proxies that each append to
|
|
63
|
+
* X-Forwarded-For, so the client is the N-th entry from the right (entries
|
|
64
|
+
* further left are client-controlled and ignored). N = 0: the socket peer.
|
|
65
|
+
*/
|
|
66
|
+
export declare function deriveClientAddress(req: IncomingMessage, trustProxyHops: number): ClientAddress;
|
|
67
|
+
export declare function clientIp(req: IncomingMessage, trustProxyHops: number): string;
|