@lexapi/mcp 0.2.0 → 0.3.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/client.js CHANGED
@@ -1,133 +1,339 @@
1
- const DEFAULT_BASE_URL = 'https://lex-api.com/api/v1';
2
- export class LexAPIError extends Error {
3
- status;
4
- slug;
5
- constructor(status, slug, message) {
6
- super(message);
7
- this.status = status;
8
- this.slug = slug;
9
- this.name = 'LexAPIError';
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);
11
18
  }
19
+ /** A 429 whose Retry-After is longer than this is returned to the model instead of slept on. */
20
+ const MAX_RETRY_AFTER_SLEEP_S = 10;
21
+ /** Response headers worth surfacing to a model; everything else is dropped. */
22
+ const KEPT_HEADERS = [
23
+ 'x-source',
24
+ 'x-language',
25
+ 'x-language-fallback',
26
+ 'x-text-available',
27
+ 'x-warning',
28
+ 'x-search-source',
29
+ 'x-search-cache',
30
+ 'x-ignored-documenttypes',
31
+ 'x-corpus-version',
32
+ 'x-export-total',
33
+ 'x-export-truncated',
34
+ ];
35
+ /** No retry or 429 sleep is started unless at least this much of the call's deadline would remain. */
36
+ const MIN_ATTEMPT_MS = 2000;
12
37
  export class LexAPIClient {
13
38
  apiKey;
14
39
  baseUrl;
15
40
  maxRetries;
41
+ timeoutMs;
42
+ fetchImpl;
43
+ sleep;
44
+ signal;
45
+ now;
46
+ opts;
16
47
  constructor(opts) {
17
- if (!opts.apiKey)
18
- throw new Error('LexAPIClient: apiKey is required');
19
- this.apiKey = opts.apiKey;
20
- this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, '');
21
- this.maxRetries = opts.maxRetries ?? 2;
22
- }
23
- // ── HTTP ──────────────────────────────────────────────────────────
24
- async request(method, path, body, query) {
48
+ const key = (opts.apiKey ?? '').trim();
49
+ if (!key)
50
+ throw new Error('LexAPI API key is missing.');
51
+ // Never include the key itself in this message.
52
+ if (!isWellFormedKey(key))
53
+ throw new Error('LexAPI API key contains whitespace or control characters — paste it again as a single line.');
54
+ this.opts = opts;
55
+ this.apiKey = key;
56
+ this.signal = opts.signal;
57
+ this.now = opts.now ?? Date.now;
58
+ this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
59
+ this.maxRetries = opts.maxRetries ?? 1;
60
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
61
+ this.fetchImpl = opts.fetch ?? fetch;
62
+ this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
63
+ }
64
+ /** A client for one MCP request: its cancellation signal and timeout. */
65
+ forCall(call) {
66
+ return new LexAPIClient({
67
+ ...this.opts,
68
+ ...(call.signal ? { signal: call.signal } : {}),
69
+ ...(call.timeoutMs ? { timeoutMs: call.timeoutMs } : {}),
70
+ });
71
+ }
72
+ get timeout() {
73
+ return this.timeoutMs;
74
+ }
75
+ /** Low-level request. Throws LexAPIError (HTTP error) or LexAPITransportError. */
76
+ async request(method, path, opts = {}) {
25
77
  const url = new URL(this.baseUrl + path);
26
- if (query) {
27
- for (const [k, v] of Object.entries(query)) {
28
- if (v === undefined || v === null)
29
- continue;
78
+ for (const [k, v] of Object.entries(opts.query ?? {})) {
79
+ if (v === undefined || v === null || v === '')
80
+ continue;
81
+ if (Array.isArray(v)) {
82
+ if (v.length)
83
+ url.searchParams.set(k, v.join(','));
84
+ }
85
+ else {
30
86
  url.searchParams.set(k, String(v));
31
87
  }
32
88
  }
33
- const init = {
34
- method,
35
- headers: {
36
- 'x-api-key': this.apiKey,
37
- ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
38
- },
39
- ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
89
+ const headers = {
90
+ 'x-api-key': this.apiKey,
91
+ accept: opts.ndjson ? 'application/x-ndjson, application/json' : 'application/json',
92
+ 'user-agent': `lexapi-mcp/${PACKAGE_VERSION}`,
40
93
  };
94
+ if (opts.body !== undefined)
95
+ headers['content-type'] = 'application/json';
96
+ const canRetry = opts.retry !== false;
97
+ // ONE deadline for the whole call — attempts, backoff and 429 sleeps all
98
+ // come out of it, so retries can never push a call past the timeout the
99
+ // MCP client is waiting on.
100
+ const deadline = this.now() + this.timeoutMs;
101
+ const remaining = () => deadline - this.now();
102
+ const canWait = (ms) => remaining() - ms >= MIN_ATTEMPT_MS;
41
103
  let attempt = 0;
42
- while (true) {
43
- const res = await fetch(url, init);
44
- // Honor 429 Retry-After once before giving up.
45
- if (res.status === 429 && attempt < this.maxRetries) {
46
- const retryAfter = parseInt(res.headers.get('Retry-After') ?? '1', 10);
47
- await sleep(Math.max(1, retryAfter) * 1000);
48
- attempt++;
49
- continue;
104
+ for (;;) {
105
+ if (remaining() <= 0) {
106
+ throw new LexAPITransportError(`no response within ${Math.round(this.timeoutMs / 1000)} s`, true);
50
107
  }
51
- // Retry on transient 5xx with exponential backoff.
52
- if (res.status >= 500 && res.status < 600 && attempt < this.maxRetries) {
53
- await sleep(500 * Math.pow(2, attempt));
108
+ let res;
109
+ const attemptSignal = combineSignals(this.signal, AbortSignal.timeout(Math.max(1, remaining())));
110
+ try {
111
+ res = await this.fetchImpl(url, {
112
+ method,
113
+ headers,
114
+ ...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),
115
+ signal: attemptSignal.signal,
116
+ });
117
+ }
118
+ catch (err) {
119
+ attemptSignal.dispose();
120
+ if (this.signal?.aborted)
121
+ throw new LexAPITransportError('the request was cancelled by the client', false, true);
122
+ const timedOut = err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError');
123
+ const backoff = 500 * 2 ** (attempt + 1);
124
+ if (!timedOut && canRetry && attempt < this.maxRetries && canWait(backoff)) {
125
+ attempt++;
126
+ await this.sleep(backoff);
127
+ continue;
128
+ }
129
+ // Never forward the runtime's message: undici quotes header values
130
+ // (the key) in some of them. Report only the error class / errno.
131
+ const reason = timedOut
132
+ ? `no response within ${Math.round(this.timeoutMs / 1000)} s`
133
+ : networkReason(err);
134
+ throw new LexAPITransportError(reason, timedOut);
135
+ }
136
+ if (this.signal?.aborted) {
137
+ attemptSignal.dispose();
138
+ await discard(res);
139
+ throw new LexAPITransportError('the request was cancelled by the client', false, true);
140
+ }
141
+ // A used-up legacy quota (QUOTA_EXHAUSTED, lex-api #304) cannot succeed
142
+ // before it refills, whatever its Retry-After says: never retried.
143
+ if (res.status === 429 && canRetry && attempt < this.maxRetries && !(await isQuotaExhausted(res))) {
144
+ const wait = retryAfterSeconds(res);
145
+ const waitMs = wait === undefined ? Infinity : Math.max(1, wait) * 1000;
146
+ if (wait !== undefined && wait <= MAX_RETRY_AFTER_SLEEP_S && canWait(waitMs)) {
147
+ attemptSignal.dispose();
148
+ await discard(res);
149
+ attempt++;
150
+ await this.sleep(waitMs);
151
+ continue;
152
+ }
153
+ }
154
+ // 500/502/503 are transient and refunded in full on credit plans.
155
+ // 504 is NOT retried: it already means a 90 s upstream budget ran out.
156
+ const backoff = 500 * 2 ** (attempt + 1);
157
+ if ((res.status === 500 || res.status === 502 || res.status === 503) && canRetry && attempt < this.maxRetries && canWait(backoff)) {
158
+ attemptSignal.dispose();
159
+ await discard(res);
54
160
  attempt++;
161
+ await this.sleep(backoff);
55
162
  continue;
56
163
  }
57
- const text = await res.text();
58
- const json = text ? safeJson(text) : {};
164
+ let text;
165
+ try {
166
+ text = res.status === 204 ? '' : await res.text();
167
+ }
168
+ catch (err) {
169
+ if (this.signal?.aborted)
170
+ throw new LexAPITransportError('the request was cancelled by the client', false, true);
171
+ const timedOut = err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError');
172
+ throw new LexAPITransportError(timedOut ? `no response within ${Math.round(this.timeoutMs / 1000)} s` : networkReason(err), timedOut);
173
+ }
174
+ finally {
175
+ attemptSignal.dispose();
176
+ }
177
+ const kept = {};
178
+ for (const h of KEPT_HEADERS) {
179
+ const v = res.headers.get(h);
180
+ if (v !== null)
181
+ kept[h] = v;
182
+ }
59
183
  if (!res.ok) {
60
- const { slug, message } = extractError(json, text, res.status);
61
- throw new LexAPIError(res.status, slug, message);
184
+ const parsed = parseErrorBody(safeJson(text), text, res.status);
185
+ const quota = parsed.code === 'QUOTA_EXHAUSTED';
186
+ throw new LexAPIError(res.status, parsed.code, parsed.message, parsed.details,
187
+ // A quota 429 has no meaningful retry-after (SDK contract §1.2).
188
+ quota ? undefined : (retryAfterSeconds(res) ?? parsed.retryAfter), parsed.resetsAt);
189
+ }
190
+ let body;
191
+ if (opts.ndjson && !(res.headers.get('content-type') ?? '').includes('application/json')) {
192
+ body = {
193
+ lines: text
194
+ .split('\n')
195
+ .filter((l) => l.trim())
196
+ .map((l) => safeJson(l) ?? { _unparsed: l.slice(0, 200) }),
197
+ };
62
198
  }
63
- return json;
199
+ else {
200
+ body = text ? (safeJson(text) ?? { _unparsed: text.slice(0, 500) }) : {};
201
+ }
202
+ return { status: res.status, body: body, headers: kept };
64
203
  }
65
204
  }
66
- // ── Endpoints ─────────────────────────────────────────────────────
67
- search(body) {
68
- return this.request('POST', '/search', body);
205
+ // ── Meta ─────────────────────────────────────────────────────────
206
+ info() { return this.request('GET', '/info'); }
207
+ // ── Search & documents ───────────────────────────────────────────
208
+ search(body) { return this.request('POST', '/search', { body }); }
209
+ getDocument(body) { return this.request('POST', '/documentContent', { body }); }
210
+ getDocumentsBatch(body) { return this.request('POST', '/documentContent/batch', { body }); }
211
+ getMetadata(body) { return this.request('POST', '/documents/metadata', { body }); }
212
+ getDocumentByUrl(body) { return this.request('POST', '/documents/url', { body }); }
213
+ recentDocuments(query) { return this.request('GET', '/documents/recent', { query }); }
214
+ resolve(body) { return this.request('POST', '/resolve', { body }); }
215
+ // ── Version history (observation snapshots) ──────────────────────
216
+ listVersions(celex, query) {
217
+ return this.request('GET', `/documents/${enc(celex)}/versions`, { query });
69
218
  }
70
- getDocument(body) {
71
- return this.request('POST', '/documentContent', body);
219
+ getVersion(celex, version, query) {
220
+ return this.request('GET', `/documents/${enc(celex)}/versions/${version}`, { query });
72
221
  }
73
- getMetadata(body) {
74
- return this.request('POST', '/documents/metadata', body);
222
+ getAtDate(celex, date, query) {
223
+ return this.request('GET', `/documents/${enc(celex)}/at/${enc(date)}`, { query });
75
224
  }
76
- getDocumentByUrl(body) {
77
- return this.request('POST', '/documents/url', body);
225
+ // ── Export (NDJSON) ──────────────────────────────────────────────
226
+ exportCorpus(query) {
227
+ return this.request('GET', '/export', { query, ndjson: true });
78
228
  }
79
- recentDocuments(query) {
80
- return this.request('GET', '/documents/recent', undefined, query);
229
+ // ── Semantic ─────────────────────────────────────────────────────
230
+ semanticCaseLaw(body) { return this.request('POST', '/search/semantic', { body }); }
231
+ semanticLegislation(body) { return this.request('POST', '/legislation/semantic', { body }); }
232
+ // ── Citations ────────────────────────────────────────────────────
233
+ extractCitations(body) { return this.request('POST', '/citations/extract', { body }); }
234
+ citedBy(celex, query) { return this.request('GET', `/citations/cited-by/${enc(celex)}`, { query }); }
235
+ cites(celex, query) { return this.request('GET', `/citations/cites/${enc(celex)}`, { query }); }
236
+ citationNetwork(celex, query) {
237
+ return this.request('GET', `/citations/network/${enc(celex)}`, { query });
81
238
  }
82
- citedBy(celex, query = {}) {
83
- return this.request('GET', `/citations/cited-by/${encodeURIComponent(celex)}`, undefined, query);
239
+ citationPath(from, to, query) {
240
+ return this.request('GET', `/citations/path/${enc(from)}/${enc(to)}`, { query });
84
241
  }
85
- cites(celex, query = {}) {
86
- return this.request('GET', `/citations/cites/${encodeURIComponent(celex)}`, undefined, query);
242
+ related(celex, query) { return this.request('GET', `/citations/related/${enc(celex)}`, { query }); }
243
+ citationStats() { return this.request('GET', '/citations/stats'); }
244
+ // ── Webhooks ─────────────────────────────────────────────────────
245
+ listWebhooks() { return this.request('GET', '/webhooks'); }
246
+ getWebhook(id) { return this.request('GET', `/webhooks/${enc(id)}`); }
247
+ webhookDeliveries(id, query) {
248
+ return this.request('GET', `/webhooks/${enc(id)}/deliveries`, { query });
87
249
  }
88
- citationNetwork(celex) {
89
- return this.request('GET', `/citations/network/${encodeURIComponent(celex)}`);
250
+ // A retried create would make a second webhook — never auto-retried.
251
+ createWebhook(body) { return this.request('POST', '/webhooks', { body, retry: false }); }
252
+ updateWebhook(id, body) { return this.request('PUT', `/webhooks/${enc(id)}`, { body }); }
253
+ // A lost response + retry would turn a successful delete into a confusing 404.
254
+ deleteWebhook(id) { return this.request('DELETE', `/webhooks/${enc(id)}`, { retry: false }); }
255
+ // A retried test would POST to the user's endpoint twice.
256
+ testWebhook(id) { return this.request('POST', `/webhooks/${enc(id)}/test`, { retry: false }); }
257
+ }
258
+ /**
259
+ * The call's cancellation signal combined with this attempt's timeout.
260
+ * `dispose()` detaches the listeners of the pre-20.3 fallback (no
261
+ * AbortSignal.any), so long-lived call signals don't accumulate them.
262
+ */
263
+ export function combineSignals(a, b) {
264
+ if (!a)
265
+ return { signal: b, dispose: () => { } };
266
+ if (typeof AbortSignal.any === 'function')
267
+ return { signal: AbortSignal.any([a, b]), dispose: () => { } };
268
+ const c = new AbortController();
269
+ const dispose = () => {
270
+ a.removeEventListener('abort', abort);
271
+ b.removeEventListener('abort', abort);
272
+ };
273
+ function abort() {
274
+ dispose();
275
+ c.abort();
90
276
  }
91
- semanticCaseLaw(body) {
92
- return this.request('POST', '/search/semantic', body);
277
+ if (a.aborted || b.aborted) {
278
+ c.abort();
279
+ return { signal: c.signal, dispose: () => { } };
93
280
  }
94
- semanticLegislation(body) {
95
- return this.request('POST', '/legislation/semantic', body);
281
+ a.addEventListener('abort', abort, { once: true });
282
+ b.addEventListener('abort', abort, { once: true });
283
+ return { signal: c.signal, dispose };
284
+ }
285
+ /** A key-free description of a network failure: errno code if there is one, else the error class. */
286
+ function networkReason(err) {
287
+ const cause = err instanceof Error ? err.cause : undefined;
288
+ const code = cause && typeof cause === 'object' && typeof cause.code === 'string'
289
+ ? cause.code
290
+ : undefined;
291
+ if (code && /^[A-Z_]+$/.test(code))
292
+ return `network error ${code}`;
293
+ if (err instanceof TypeError && /invalid header/i.test(err.message))
294
+ return 'invalid request header (check the API key)';
295
+ return `network error (${err instanceof Error ? err.name : 'unknown'})`;
296
+ }
297
+ function enc(s) {
298
+ return encodeURIComponent(s);
299
+ }
300
+ async function discard(res) {
301
+ try {
302
+ await res.body?.cancel();
303
+ }
304
+ catch {
305
+ /* already consumed */
306
+ }
307
+ }
308
+ /** Peeks a 429 body (on a clone) for `code: "QUOTA_EXHAUSTED"`. */
309
+ async function isQuotaExhausted(res) {
310
+ try {
311
+ const j = safeJson(await res.clone().text());
312
+ return !!j && typeof j === 'object' && j.code === 'QUOTA_EXHAUSTED';
313
+ }
314
+ catch {
315
+ return false;
96
316
  }
97
317
  }
98
- function sleep(ms) {
99
- return new Promise((resolve) => setTimeout(resolve, ms));
318
+ function retryAfterSeconds(res) {
319
+ const raw = res.headers.get('retry-after');
320
+ if (!raw)
321
+ return undefined;
322
+ const n = Number(raw);
323
+ if (Number.isFinite(n) && n >= 0)
324
+ return Math.ceil(n);
325
+ const date = Date.parse(raw);
326
+ if (!Number.isNaN(date))
327
+ return Math.max(0, Math.ceil((date - Date.now()) / 1000));
328
+ return undefined;
100
329
  }
101
330
  function safeJson(text) {
331
+ if (!text)
332
+ return undefined;
102
333
  try {
103
334
  return JSON.parse(text);
104
335
  }
105
336
  catch {
106
- return { error: 'invalid_json', message: text.slice(0, 500) };
337
+ return undefined;
107
338
  }
108
339
  }
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,35 @@
1
+ export declare class LexAPIError extends Error {
2
+ readonly status: number;
3
+ /** Typed `error.code` (e.g. CREDITS_EXHAUSTED) or the legacy slug. */
4
+ readonly code: string;
5
+ readonly details?: unknown | undefined;
6
+ /** Seconds from the `Retry-After` header / `retryAfter` body (429); never set for QUOTA_EXHAUSTED. */
7
+ readonly retryAfterSeconds?: number | undefined;
8
+ /** When an exhausted legacy quota refills (`resetsAt`, else `usage.resetsAt`). */
9
+ readonly resetsAt?: string | undefined;
10
+ constructor(status: number,
11
+ /** Typed `error.code` (e.g. CREDITS_EXHAUSTED) or the legacy slug. */
12
+ code: string, message: string, details?: unknown | undefined,
13
+ /** Seconds from the `Retry-After` header / `retryAfter` body (429); never set for QUOTA_EXHAUSTED. */
14
+ retryAfterSeconds?: number | undefined,
15
+ /** When an exhausted legacy quota refills (`resetsAt`, else `usage.resetsAt`). */
16
+ resetsAt?: string | undefined);
17
+ }
18
+ /** Raised for network failures / timeouts before any HTTP status arrived. */
19
+ export declare class LexAPITransportError extends Error {
20
+ readonly timedOut: boolean;
21
+ readonly cancelled: boolean;
22
+ constructor(message: string, timedOut: boolean, cancelled?: boolean);
23
+ }
24
+ export declare function parseErrorBody(json: unknown, rawText: string, status: number): {
25
+ code: string;
26
+ message: string;
27
+ details?: unknown;
28
+ retryAfter?: number;
29
+ resetsAt?: string;
30
+ };
31
+ /**
32
+ * The tool-result text for a failed call. Never includes the API key: the
33
+ * key only travels in a request header and is never part of any message.
34
+ */
35
+ export declare function describeError(err: unknown): string;
package/dist/errors.js ADDED
@@ -0,0 +1,164 @@
1
+ // Error type + the text a model sees when a call fails.
2
+ //
3
+ // LexAPI answers errors in two shapes (docs.md "Errors & retries"):
4
+ // typed: { success: false, error: { code, message, details? } }
5
+ // legacy: { error: "slug or sentence", message?, details?, retryAfter?, upgradeUrl?, usage? }
6
+ // — from lex-api #304 on also a top-level `code` (e.g. RATE_LIMITED,
7
+ // QUOTA_EXHAUSTED) and, on quota 429s, a top-level `resetsAt`.
8
+ // We normalise both, then turn the status into a message that says what
9
+ // happened AND what to do next — the model relays it to the user, so it has
10
+ // to be actionable without the model knowing LexAPI's billing rules.
11
+ const DASHBOARD_URL = 'https://lex-api.com/dashboard?ref=mcp';
12
+ const PRICING_URL = 'https://lex-api.com/pricing?ref=mcp';
13
+ export class LexAPIError extends Error {
14
+ status;
15
+ code;
16
+ details;
17
+ retryAfterSeconds;
18
+ resetsAt;
19
+ constructor(status,
20
+ /** Typed `error.code` (e.g. CREDITS_EXHAUSTED) or the legacy slug. */
21
+ code, message, details,
22
+ /** Seconds from the `Retry-After` header / `retryAfter` body (429); never set for QUOTA_EXHAUSTED. */
23
+ retryAfterSeconds,
24
+ /** When an exhausted legacy quota refills (`resetsAt`, else `usage.resetsAt`). */
25
+ resetsAt) {
26
+ super(message);
27
+ this.status = status;
28
+ this.code = code;
29
+ this.details = details;
30
+ this.retryAfterSeconds = retryAfterSeconds;
31
+ this.resetsAt = resetsAt;
32
+ this.name = 'LexAPIError';
33
+ }
34
+ }
35
+ /** Raised for network failures / timeouts before any HTTP status arrived. */
36
+ export class LexAPITransportError extends Error {
37
+ timedOut;
38
+ cancelled;
39
+ constructor(message, timedOut, cancelled = false) {
40
+ super(message);
41
+ this.timedOut = timedOut;
42
+ this.cancelled = cancelled;
43
+ this.name = 'LexAPITransportError';
44
+ }
45
+ }
46
+ export function parseErrorBody(json, rawText, status) {
47
+ const fallback = { code: `HTTP_${status}`, message: rawText.trim().slice(0, 300) || `HTTP ${status}` };
48
+ if (!json || typeof json !== 'object' || Array.isArray(json))
49
+ return fallback;
50
+ const j = json;
51
+ const retryAfter = typeof j.retryAfter === 'number' ? j.retryAfter : undefined;
52
+ // A top-level string `code` (lex-api #304) beats the legacy `error` text.
53
+ const topCode = typeof j.code === 'string' && j.code ? j.code : undefined;
54
+ const usage = j.usage && typeof j.usage === 'object' ? j.usage : undefined;
55
+ const resetsAt = typeof j.resetsAt === 'string' ? j.resetsAt
56
+ : usage && typeof usage.resetsAt === 'string' ? usage.resetsAt
57
+ : undefined;
58
+ const e = j.error;
59
+ if (e && typeof e === 'object' && !Array.isArray(e)) {
60
+ const eo = e;
61
+ return {
62
+ code: typeof eo.code === 'string' ? eo.code : (topCode ?? fallback.code),
63
+ message: typeof eo.message === 'string' ? eo.message
64
+ : typeof j.message === 'string' ? j.message
65
+ : fallback.message,
66
+ details: eo.details ?? j.details,
67
+ retryAfter,
68
+ resetsAt,
69
+ };
70
+ }
71
+ // Legacy: `error` is a short sentence ("Invalid API key"), `message` the detail.
72
+ const errStr = typeof e === 'string' ? e : undefined;
73
+ const msg = typeof j.message === 'string' ? j.message : undefined;
74
+ return {
75
+ code: topCode ?? errStr ?? fallback.code,
76
+ message: errStr && msg ? `${errStr}: ${msg}` : (msg ?? errStr ?? fallback.message),
77
+ details: j.details ?? j.usage,
78
+ retryAfter,
79
+ resetsAt,
80
+ };
81
+ }
82
+ function detailsLine(details) {
83
+ if (details === undefined || details === null)
84
+ return '';
85
+ if (Array.isArray(details)) {
86
+ const items = details.map((d) => (typeof d === 'string' ? d : JSON.stringify(d))).slice(0, 10);
87
+ return items.length ? ` Details: ${items.join('; ')}.` : '';
88
+ }
89
+ if (typeof details === 'object')
90
+ return ` Details: ${JSON.stringify(details)}.`;
91
+ return ` Details: ${String(details)}.`;
92
+ }
93
+ /**
94
+ * The tool-result text for a failed call. Never includes the API key: the
95
+ * key only travels in a request header and is never part of any message.
96
+ */
97
+ export function describeError(err) {
98
+ if (err instanceof LexAPITransportError) {
99
+ if (err.cancelled)
100
+ return 'Cancelled: the client cancelled this request before LexAPI answered.';
101
+ return err.timedOut
102
+ ? `LexAPI did not answer in time (${err.message}). Live EUR-Lex fetches can take longer than an MCP client waits; the call is safe to retry once, and a repeat may be served from the LexAPI corpus. If it keeps timing out, narrow the request (fewer pages, a smaller limit) or raise the client's tool timeout (Claude Code: MCP_TOOL_TIMEOUT) and LEXAPI_TIMEOUT_MS.`
103
+ : `Could not reach LexAPI (${err.message}). Check network access to lex-api.com (or LEXAPI_BASE_URL) and retry.`;
104
+ }
105
+ if (!(err instanceof LexAPIError)) {
106
+ const message = err instanceof Error ? err.message : String(err);
107
+ return `Tool execution failed: ${message}`;
108
+ }
109
+ const head = `LexAPI error ${err.status} (${err.code}): ${err.message.trim().replace(/[.\s]+$/, '')}.`;
110
+ const d = (err.details && typeof err.details === 'object' && !Array.isArray(err.details))
111
+ ? err.details
112
+ : undefined;
113
+ switch (err.status) {
114
+ case 400:
115
+ return `${head}${detailsLine(err.details)} The request was rejected before any work was done and its credits were refunded. Fix the arguments and call again.`;
116
+ case 401:
117
+ return `${head} The LexAPI API key is missing, wrong, or revoked. Ask the user to check the key configured for this MCP server (LEXAPI_API_KEY, or the Authorization header for the hosted server) or create a new one at ${DASHBOARD_URL}.`;
118
+ case 402: {
119
+ const parts = [];
120
+ if (d) {
121
+ if (typeof d.weight === 'number')
122
+ parts.push(`this call needs ${d.weight} credits`);
123
+ if (typeof d.available === 'number')
124
+ parts.push(`${d.available} are available`);
125
+ if (typeof d.resetsAt === 'string')
126
+ parts.push(`the monthly pool resets at ${d.resetsAt}`);
127
+ }
128
+ return `${head}${parts.length ? ` (${parts.join(', ')}).` : ''} The account's monthly LexAPI credit pool is exhausted. Tell the user: they can wait for the reset, buy a top-up pack or upgrade at ${DASHBOARD_URL} (plans: ${PRICING_URL}). Cheaper calls may still succeed (e.g. lex_resolve or lex_cites cost 1 credit); do not retry this call unchanged.`;
129
+ }
130
+ case 403:
131
+ return `${head} The account's plan or subscription does not allow this call (not a temporary error — do not retry). Tell the user which feature was refused; plans are compared at ${PRICING_URL}.`;
132
+ case 404:
133
+ return `${head} Not retryable as-is. Check the identifier (lex_resolve turns URLs, ELIs and ECLIs into CELEX numbers; lex_search finds documents by title).`;
134
+ case 409:
135
+ return `${head} The account's current state does not allow this action; tell the user (it is not fixed by retrying).`;
136
+ case 429: {
137
+ const wait = err.retryAfterSeconds;
138
+ const resetsAt = err.resetsAt ?? (d && typeof d.resetsAt === 'string' ? d.resetsAt : undefined);
139
+ // QUOTA_EXHAUSTED (lex-api #304) is a used-up legacy quota, whatever
140
+ // else the response carries. Fallback for older servers: the per-minute
141
+ // limiter sends Retry-After / retryAfter, the legacy quotas (daily
142
+ // calls, monthly semantic searches) send neither — only usage.resetsAt.
143
+ // Retrying a quota before it refills is pointless.
144
+ if (err.code === 'QUOTA_EXHAUSTED' || (wait === undefined && (resetsAt || /quota/i.test(`${err.code} ${err.message}`)))) {
145
+ const which = /semantic/i.test(err.message)
146
+ ? 'the monthly semantic-search quota of this (legacy) plan'
147
+ : /daily/i.test(err.message)
148
+ ? 'the daily call quota of this (legacy) plan'
149
+ : 'a usage quota of this plan';
150
+ return `${head} This is ${which}, not a per-minute limit: it is exhausted${resetsAt ? ` until ${resetsAt}` : ''} — do not retry, tell the user. Moving to a credit plan (${PRICING_URL}) removes the quota.`;
151
+ }
152
+ return `${head} Per-minute rate limit of the API key reached.${wait !== undefined ? ` Wait ${wait} s before calling again.` : ' Wait about a minute before calling again.'} Avoid parallel calls; a higher plan raises the per-minute limit (${PRICING_URL}).`;
153
+ }
154
+ case 502:
155
+ return `${head} An upstream service (EUR-Lex or the semantic index) returned an error. Retry later; failed calls are refunded.`;
156
+ case 504:
157
+ return `${head} The upstream fetch timed out. Retry-safe — retry once, or narrow the request (fewer pages, a smaller limit). Failed searches are refunded.`;
158
+ default:
159
+ if (err.status >= 500) {
160
+ return `${head} LexAPI had a server error; server failures are refunded. Retry once; if it persists, status is at https://lex-api.com/status.`;
161
+ }
162
+ return `${head}${detailsLine(err.details)}`;
163
+ }
164
+ }
@@ -1,2 +1,16 @@
1
- import { type Server as HttpServer } from 'node:http';
1
+ import { type IncomingMessage, type Server as HttpServer } from 'node:http';
2
+ /**
3
+ * The caller's LexAPI key: `Authorization: Bearer <key>` (what server.json
4
+ * advertises), or `x-api-key: <key>` (the REST API's own header).
5
+ */
6
+ export declare function extractApiKey(req: IncomingMessage): string | null;
7
+ /**
8
+ * Origin validation (MCP Streamable HTTP: servers MUST validate Origin, a
9
+ * DNS-rebinding defence). Requests without an Origin header — every
10
+ * non-browser MCP client — are allowed. A browser request is allowed only
11
+ * when its Origin is listed in LEXAPI_MCP_ALLOWED_ORIGINS (comma-separated;
12
+ * "*" allows any). Auth is a bearer key with no ambient credentials, so this
13
+ * is defence in depth, not the access control.
14
+ */
15
+ export declare function originAllowed(origin: string | undefined, env?: NodeJS.ProcessEnv): boolean;
2
16
  export declare function createHttpServer(): HttpServer;