@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/CHANGELOG.md ADDED
@@ -0,0 +1,61 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@lexapi/mcp`. Versions follow [semver](https://semver.org); while the package is 0.x, a minor bump can change behaviour.
4
+
5
+ ## 0.3.0 — 2026-10-26
6
+
7
+ Brings the server in line with the current LexAPI API (API changelog up to the consolidated-text / `asOf` release, LexAPI PR #298).
8
+
9
+ ### Added
10
+ - **`asOf` on `lex_semantic_legislation`** — the law as in force on a date. Hits carry `asOf`, `asOfResolved`, `asOfReason`, `asOfVersion`, `matchedVersion`; the response carries `asOf` / `asOfSummary`, plus an `asOfCaveat` when some hits could not be resolved to that date.
11
+ - **Consolidated-text labels** surfaced on legislation hits (`consolidated`, `consolidatedAsOf`, `baseCelex`, `consolidatedNote`, `baseAct`) and derived on documents fetched by a consolidated CELEX, with a `citing` note telling the model to cite the authentic act.
12
+ - 16 tools for endpoints the server did not cover: `lex_info`, `lex_resolve`, `lex_get_documents_batch`, `lex_document_versions`, `lex_get_document_version`, `lex_citation_path`, `lex_related`, `lex_citation_stats`, `lex_extract_citations`, `lex_export`, `lex_list_webhooks`, `lex_get_webhook`, `lex_create_webhook`, `lex_update_webhook`, `lex_delete_webhook`, `lex_test_webhook`.
13
+ - `lex_export` (API 2.3.0, LexAPI #303): `dateFrom` / `dateTo` (the API's document-date filter now works), `changedSince` (rows whose text changed) and `documentTypeCode` (type families); `documentType` is described as an exact, case-insensitive label match; `fetchedSince` / `changedSince` take a date or a date-time with a timezone, validated exactly as the API does (zone `Z`, `±HH:MM` or `±HHMM`; optional seconds; a 1–9 digit fraction; calendar-valid dates, also for `dateFrom` / `dateTo`). The result carries `truncatedBy` (`limit`, `max_rows` or `credits`) next to `truncated`. The cost is stated exactly: 1 credit per row returned, at least 1 per call — a 1-credit admission, a reservation up to `limit`, a refund of unreturned rows, and a 402 before anything is returned when the pool cannot cover the reservation. **Publish only after LexAPI #303 is deployed.**
14
+ - Webhook URLs are checked before the call: https, port 443/8443, no credentials, no single-label / internal / reserved hostnames, no private, loopback, link-local or other special-purpose IP literals (IPv4-mapped and NAT64 included) — the DNS-free half of the API's egress guard (eurlex-parser #302); the API remains authoritative.
15
+ - Missing parameters: `lex_get_document` `language`, `acceptLanguages`, `articleId`, `include`; `lex_get_document_by_url` `articleId`, `include`, `bypassCorpus`; `lex_get_metadata` `bypassCorpus`; `lex_search` `month`, `procedure`, `domain`, `subdomain`, `fresh`; `lex_recent_documents` `domain`, `subdomain`; `lex_citation_network` `citationType`, `limit`, `offset`; semantic tools `language`, `include`; `lex_semantic_case_law` `hyde` and typed `filters` (`court`, `date_from`, `date_to`, `case_number`, `ecli`).
16
+ - Server `instructions` (workflow, citing consolidated texts, `asOf` vs. version snapshots, credit awareness), tool `title`s, server `title` / `websiteUrl`.
17
+ - `LEXAPI_MCP_READ_ONLY` hides the webhook-changing tools; `LEXAPI_TIMEOUT_MS`.
18
+ - Hosted HTTP server also accepts `x-api-key`; answers `405` to GET/DELETE (stateless), `413` to oversized bodies (and closes the connection), `WWW-Authenticate` on `401`; validates `Origin` (MCP spec, DNS-rebinding defence): browser origins must be listed in `LEXAPI_MCP_ALLOWED_ORIGINS`, requests without `Origin` are allowed.
19
+ - Cancellation: an MCP `notifications/cancelled` (or a closed HTTP connection) aborts the upstream LexAPI request. Progress notifications every 10 s when the request carries a progress token (they do not raise the timeout: a server cannot tell whether the client resets its timeout on progress).
20
+ - `asOfCaveat` groups unresolved hits by reason: `notInForce` (that is the answer), `retryable`, `needsCredits`, `unavailable`, each with guidance.
21
+ - Long items (a giant annex, a `fullText` without blank lines) are split into parts that `offset` pages through; the outline's article list is bounded by `maxChars` and paged with `offset`; the outline hint only suggests parts the document has.
22
+ - Tests (vitest: unit, in-memory MCP, Streamable HTTP and stdio end-to-end against a mock API), ESLint, CI, `scripts/smoke-stdio.mjs`.
23
+
24
+ ### Changed
25
+ - **Responses are compact and bounded.** Tool output is unindented JSON without the `subscription` / `usage` envelopes, legacy duplicate fields, opaque upstream metadata or snapshot-scoped ids. `lex_get_document` (and by-URL / batch / version snapshots) return the full body only when it fits `maxChars` (default 40,000 characters) — otherwise an outline with article ids, and `articleId` / `include` / `offset` to read on. v0.2 returned the whole document (hundreds of KB for large acts), which most clients truncate.
26
+ - `textAvailability` is passed through verbatim whenever text is missing (reason, languages, consolidated pointers); language fallback (`languageRequested`, `languageFallback`) and `titleLanguage` are kept.
27
+ - **Errors are actionable**: 402 states the credits needed, available and the reset date; 429 the wait; 401/403/404/5xx what to do. Both the typed and the legacy error envelopes are parsed.
28
+ - 429s from the legacy daily quota and monthly semantic quota (no `Retry-After`) say "exhausted until `usage.resetsAt` — do not retry", instead of "wait a minute".
29
+ - A top-level string `code` on a legacy-shape error body (LexAPI #304) is now the error code, ahead of the legacy `error` text. A 429 with `code: "QUOTA_EXHAUSTED"` is never retried (even with a short `Retry-After`), carries no retry-after, exposes `resetsAt` (the body's `resetsAt`, else `usage.resetsAt`) and says "exhausted until <resetsAt> — do not retry, tell the user". Servers without the `code` are still recognised by the old shape check.
30
+ - `lex_export` no longer presents a partial export as the result: a stream without its `_done` trailer, a `_done` with `complete: false`, or a line whose only key is `_error` returns an error naming the rows received; an `_error` line is never returned as a row (SDK contract §1.8; LexAPI #303).
31
+ - One 55 s deadline per tool call (under the 60 s default of MCP clients), shared by all attempts, backoff and 429 waits; `LEXAPI_TIMEOUT_MS` raises it.
32
+ - The API key is validated at startup (no whitespace / control characters); network errors never echo runtime text (undici can quote header values).
33
+ - Retries: a 429 is retried once only when `Retry-After` ≤ 10 s (v0.2 slept on any Retry-After, twice); 500/502/503 and network errors once; 504 never (it already spent a 90 s upstream budget); webhook create/test/delete never. Every call has one deadline (55 s default; v0.2 had no timeout).
34
+ - Inputs are validated by the MCP SDK (zod) before any API call.
35
+ - CELEX inputs accept consolidated (`02016R0679-20180524`) and corrigendum (`32013R0952R(04)`) forms, lower case and a `CELEX:` prefix — v0.2's pattern rejected the first two.
36
+ - Enums synced with the API: document type `staff-working-document` added and `opinion-act` removed (the API ignores it); citation type `corrigendum`; author `civil-service-tribunal`; semantic `language` limited to the indexed languages.
37
+ - Defaults lowered to cut credit and token use: `lex_recent_documents` `limit` 20 (was 50, i.e. 15 credits when filtered), citation `limit` 50 (was 100).
38
+ - Tool descriptions rewritten: costs per call, when to use which tool, FREE plans can use semantic search (credit plans), legislation `filters` honour only `language`.
39
+ - `@modelcontextprotocol/sdk` ^1.0.0 → ^1.32.2 (protocol 2025-11-25), high-level `McpServer` API; `zod` added; dependency overrides removed (`npm audit`: 0 vulnerabilities).
40
+ - `User-Agent: lexapi-mcp/<version>` on every request.
41
+
42
+ ### Breaking
43
+ - Tool output shape changed (compact; large documents outlined). Prompts that relied on v0.2's raw API JSON (e.g. `document.content.fullText` always present) need `include: ["fullText"]`.
44
+ - Inputs are validated before any call; v0.2 forwarded anything. Newly rejected:
45
+ - `documentType: "opinion-act"` (it never filtered anything);
46
+ - `lex_semantic_case_law.query` shorter than 3 characters (the semantic index rejects it; the API answered 502);
47
+ - semantic `language` outside the 10 indexed languages (`en, fr, de, es, it, sl, el, nl, pt, pl`); document/search `language` outside the 24 EU codes;
48
+ - `lex_search.maxPages` above 100 (the highest plan cap); `year` outside 1950–2100; `month` outside 1–12;
49
+ - malformed CELEX numbers, dates not in `YYYY-MM-DD`, unknown webhook `searchCriteria` keys.
50
+ - Smaller defaults: `lex_recent_documents` `limit` 20 (was 50), citation `limit` 50 (was 100).
51
+ - `LEXAPI_MCP_READ_ONLY` also hides `lex_extract_citations`.
52
+ - One 55 s deadline per tool call (v0.2: no timeout at all) unless `LEXAPI_TIMEOUT_MS` is set.
53
+ - Hosted HTTP: browser requests with an `Origin` not listed in `LEXAPI_MCP_ALLOWED_ORIGINS` get 403; a malformed key (whitespace inside the value) gets 401 `malformed_api_key`; an oversized body is drained (up to 16 MB / 5 s) and answered 413, then the connection closes.
54
+ - Webhook `url` values that are not public https URLs are rejected at validation.
55
+ - Tool names are unchanged.
56
+
57
+ ## 0.2.0
58
+ - Hosted Streamable HTTP transport (`/v1`, Bearer auth) for mcp.lex-api.com; `server.json` advertises it.
59
+
60
+ ## 0.1.x
61
+ - Initial ten tools over stdio; registry metadata; README fixes.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 LexAPI
3
+ Copyright (c) 2026 Arieta Labs Ltd
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,16 +1,16 @@
1
1
  # LexAPI MCP
2
2
 
3
- [Model Context Protocol](https://modelcontextprotocol.io) server for [LexAPI](https://lex-api.com/?ref=npm-mcp) — query EUR-Lex, EU case law, and the citation graph from Claude, Cursor, and other MCP-enabled clients.
3
+ [Model Context Protocol](https://modelcontextprotocol.io) server for [LexAPI](https://lex-api.com/?ref=npm-mcp) — EU law for AI assistants: EUR-Lex legislation parsed to article level, CJEU case law, the typed citation graph, and semantic search (including **the law as in force on a past date**). Works with Claude, Cursor, VS Code and any other MCP client.
4
4
 
5
- Install once, get an API key, and ask your AI assistant: *"summarize Article 17 of the GDPR"* or *"which regulations amend Directive 95/46/EC?"* — the model calls LexAPI directly.
5
+ Ask your assistant *"what does Article 17 GDPR require?"*, *"which acts amended REACH?"* or *"what were the own-funds requirements for banks in June 2019?"* — the model calls LexAPI and answers from the source text, with CELEX citations.
6
6
 
7
- ## Install
7
+ You need a LexAPI API key. Create one for free at [lex-api.com/dashboard](https://lex-api.com/dashboard?ref=npm-mcp) — the FREE plan includes 500 credits a month, no card required, enough to try the read tools.
8
8
 
9
- You'll need a LexAPI API key. Create one for free at [lex-api.com/dashboard](https://lex-api.com/dashboard?ref=npm-mcp) (500 credits/month on the FREE tier, no card required).
9
+ ## Install
10
10
 
11
11
  ### Claude Desktop
12
12
 
13
- Add to `claude_desktop_config.json` (location: `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):
13
+ Add to `claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`):
14
14
 
15
15
  ```json
16
16
  {
@@ -18,9 +18,7 @@ Add to `claude_desktop_config.json` (location: `~/Library/Application Support/Cl
18
18
  "lexapi": {
19
19
  "command": "npx",
20
20
  "args": ["-y", "@lexapi/mcp"],
21
- "env": {
22
- "LEXAPI_API_KEY": "lex_..."
23
- }
21
+ "env": { "LEXAPI_API_KEY": "lex_..." }
24
22
  }
25
23
  }
26
24
  }
@@ -34,53 +32,94 @@ Restart Claude Desktop.
34
32
  claude mcp add lexapi --env LEXAPI_API_KEY=lex_... -- npx -y @lexapi/mcp
35
33
  ```
36
34
 
37
- ### Cursor / other MCP clients
35
+ ### Cursor, VS Code and other stdio clients
36
+
37
+ Run `npx -y @lexapi/mcp` with `LEXAPI_API_KEY` in the environment (Cursor: `~/.cursor/mcp.json`; VS Code: `.vscode/mcp.json`; same `command` / `args` / `env` shape as above).
38
+
39
+ ### Hosted server (no local install)
40
+
41
+ The same tools are served over Streamable HTTP at `https://mcp.lex-api.com/v1`, authenticated with your key as `Authorization: Bearer lex_...` (or `x-api-key: lex_...`):
42
+
43
+ ```bash
44
+ claude mcp add --transport http lexapi https://mcp.lex-api.com/v1 --header "Authorization: Bearer lex_..."
45
+ ```
38
46
 
39
- Any client that supports stdio MCP servers can run this. The command is `npx -y @lexapi/mcp` with `LEXAPI_API_KEY` in the environment.
47
+ The npm package needs Node.js 20 or newer.
40
48
 
41
49
  ## Tools
42
50
 
43
- | Tool | What it does |
44
- |---|---|
45
- | `lex_search` | Structured EUR-Lex search (text, dates, document type, author, language). |
46
- | `lex_get_document` | Full parsed document by CELEX — metadata + articles, sections, tables, annexes. |
47
- | `lex_get_metadata` | Metadata only (faster than full content). |
48
- | `lex_get_document_by_url` | Fetch by EUR-Lex URL (pasted from a browser). |
49
- | `lex_recent_documents` | Recent Official Journal publications (default 7 days). |
50
- | `lex_cited_by` | Documents citing this CELEX (inbound, typed edges). |
51
- | `lex_cites` | Documents this CELEX cites (outbound, typed edges). |
52
- | `lex_citation_network` | Both directions in one call. |
53
- | `lex_semantic_case_law` | Embedding search over EU case law (paid plans). |
54
- | `lex_semantic_legislation` | Embedding search over EU legislation (paid plans). |
51
+ Every call is billed from your LexAPI credit pool exactly like the REST endpoint it wraps; each tool's description states its cost so the model can see it.
52
+
53
+ | Tool | What it does | Credits |
54
+ |---|---|---|
55
+ | `lex_semantic_legislation` | Find legislation articles by meaning. `asOf` returns the text in force on a date. Consolidated hits are labelled, with the authentic act to cite. | 5 (+ up to 5 per live version fetch with `asOf`) |
56
+ | `lex_semantic_case_law` | Find judgments, orders and AG opinions by meaning; `hyde` for terse queries; court / date / case-number filters. | 5 (15 with `hyde`) |
57
+ | `lex_search` | Structured EUR-Lex search: text, dates, type, author, procedure, collection. | 3 per page |
58
+ | `lex_recent_documents` | What was published in the last N days. | 3 per 10 results |
59
+ | `lex_resolve` | URL / ELI / ECLI → CELEX. | 1 |
60
+ | `lex_get_document` | A document by CELEX — an outline first for large acts, then `articleId` or `include` parts; language and fallback languages. | 1 corpus · 4 Cellar · 5 live |
61
+ | `lex_get_documents_batch` | Up to 50 documents at once (plan-capped). | per document, as above |
62
+ | `lex_get_metadata` | Metadata only. | 1 · 4 · 5 |
63
+ | `lex_get_document_by_url` | A document from a pasted EUR-Lex URL. | 1 · 4 · 5 |
64
+ | `lex_document_versions` | LexAPI's observed version history of a document. | 1 |
65
+ | `lex_get_document_version` | One observed snapshot, by version number or date. | 1 |
66
+ | `lex_cited_by` | Documents citing / amending / correcting / repealing an act. | 1 |
67
+ | `lex_cites` | What a document cites. | 1 |
68
+ | `lex_citation_network` | Both directions in one call. | 20 |
69
+ | `lex_citation_path` | Shortest citation chain between two documents. | 20 |
70
+ | `lex_related` | Documents citing the same acts (bibliographic coupling). | 20 |
71
+ | `lex_citation_stats` | Citation graph totals and most-cited documents. | 20 |
72
+ | `lex_extract_citations` | Add a document's outbound citations to the graph. | 5 (1 if already done) |
73
+ | `lex_export` | Corpus rows by type (exact label, any case) or type family (`documentTypeCode`), author, collection, language, document date (`dateFrom`/`dateTo`), `changedSince` or `fetchedSince` (BUSINESS plans and above). | 1 per row returned, at least 1 per call (1-credit admission, rows reserved up to `limit`, unreturned rows refunded; 402 if the pool cannot cover the reservation) |
74
+ | `lex_info` | Your plan, credit balance and limits. | free |
75
+ | `lex_list_webhooks` · `lex_get_webhook` | Your webhooks and their deliveries. | free |
76
+ | `lex_create_webhook` · `lex_update_webhook` · `lex_delete_webhook` · `lex_test_webhook` | Webhooks for new documents and for changes to watched acts (paid plans). The URL must be a public https URL (port 443/8443, no internal hosts or private addresses) — checked here as well as by the API. | free |
77
+
78
+ ### How results are shaped for models
79
+
80
+ - **Compact output.** Responses drop envelopes and duplicate legacy fields. Documents keep their metadata, `textAvailability` (why text is missing, which languages exist, a pointer to the latest consolidated version) and language-fallback labels.
81
+ - **Large documents.** `lex_get_document` returns the whole body when it fits `maxChars` (default 40,000 characters), otherwise an outline (article ids, section tree, counts). Fetch an article with `articleId` or parts with `include`; long parts continue with `offset`.
82
+ - **Consolidated texts are not authentic.** Consolidated versions carry `consolidated: true`, `consolidatedAsOf`, `baseCelex` and a note: quote them, cite the act as published in the Official Journal.
83
+ - **`asOf`.** Each legislation hit says whether it carries the version in force on that date (`asOfResolved`, `asOfVersion`); unresolved hits keep the current text with an `asOfReason`, and the response warns about them.
84
+ - **Errors say what to do.** A 402 states the credits needed, the credits left and the reset date; a 429 says how long to wait.
55
85
 
56
86
  ## Configuration
57
87
 
58
88
  | Env var | Default | Purpose |
59
89
  |---|---|---|
60
- | `LEXAPI_API_KEY` | *(required)* | Your API key. Get one at [lex-api.com/dashboard](https://lex-api.com/dashboard?ref=npm-mcp). |
61
- | `LEXAPI_BASE_URL` | `https://lex-api.com/api/v1` | Override for self-hosted or staging. |
62
-
63
- ## Troubleshooting
90
+ | `LEXAPI_API_KEY` | *(required)* | Your API key from [lex-api.com/dashboard](https://lex-api.com/dashboard?ref=npm-mcp). |
91
+ | `LEXAPI_BASE_URL` | `https://lex-api.com/api/v1` | Override for staging or self-hosting. |
92
+ | `LEXAPI_MCP_READ_ONLY` | off | `true` hides (and refuses) every tool that is not read-only: webhook create / update / delete / test, and `lex_extract_citations` (it writes to the shared citation graph and costs credits). |
93
+ | `LEXAPI_TIMEOUT_MS` | `55000` | Deadline for one tool call towards LexAPI, retries included. Raise it only together with your MCP client's own tool timeout. |
94
+ | `LEXAPI_MCP_ALLOWED_ORIGINS` | *(none)* | Hosted HTTP server only: browser `Origin`s allowed to call it (comma-separated, `*` for any). Requests without an `Origin` header (all non-browser clients) are always allowed. |
64
95
 
65
- **`LEXAPI_API_KEY is not set`** — the env var isn't reaching the spawned process. Double-check the `env` block in your MCP client config.
96
+ The key is sent only as the `x-api-key` header to LexAPI; it is never logged or included in tool output. A key containing whitespace or control characters (e.g. a multi-line paste) is rejected at startup.
66
97
 
67
- **`LexAPI error (401 invalid_api_key)`** — the key is wrong or revoked. Generate a new one at the dashboard.
98
+ **Timeouts.** MCP clients give up on a tool call after their own timeout (60 s by default in the official SDK; Claude Code: `MCP_TOOL_TIMEOUT`). A first, live EUR-Lex fetch can take longer. The server gives each tool call one 55 s deadline — retries and rate-limit waits included — and then returns a message the model can act on, instead of the client's generic timeout error. When the client sends a progress token, the server also sends a progress notification every 10 s; whether that keeps the call alive is up to the client (the official SDK only extends its timeout on progress when the caller opts into `resetTimeoutOnProgress`, and a server cannot detect that), so the deadline stays 55 s. If you raise your client's timeout, raise `LEXAPI_TIMEOUT_MS` to match. Cancelling a call aborts the request to LexAPI.
68
99
 
69
- **`LexAPI error (429 …)`** — you hit your daily quota or per-minute rate limit. The server retries once automatically; if you see this in tool output, you're over quota. Upgrade your plan or wait for reset.
100
+ ## Troubleshooting
70
101
 
71
- **`LexAPI error (403 …)` on semantic tools** — semantic search requires a paid plan. FREE tier returns 403 for those endpoints.
102
+ - **`LEXAPI_API_KEY is not set`** — the variable isn't reaching the spawned process; check the `env` block of your MCP client config.
103
+ - **`LexAPI error 401`** — the key is wrong or revoked; create a new one at the dashboard.
104
+ - **`LexAPI error 402 (CREDITS_EXHAUSTED)`** — the monthly credit pool is used up. The message gives the reset date; top-ups and upgrades are on the dashboard.
105
+ - **`LexAPI error 429`** — the per-minute rate limit of your key (FREE: 15 per minute). Short waits are retried once automatically; otherwise the message says how long to wait.
106
+ - **`LexAPI error 403`** — the plan doesn't include the feature (e.g. export below BUSINESS, or semantic search on a legacy pre-credits FREE plan).
107
+ - **`LexAPI error 400` creating a webhook** — the details name the problem (unsupported criteria, a watch list over the plan limit, or the plan's webhook limit; FREE has none).
72
108
 
73
- ## Local development
109
+ ## Development
74
110
 
75
111
  ```bash
76
112
  git clone https://github.com/Lex-API/lexapi-mcp.git
77
113
  cd lexapi-mcp
78
114
  npm install
79
- npm run build
80
-
81
- LEXAPI_API_KEY=lex_xxx node dist/index.js
115
+ npm test # build + unit and transport tests (mocked API, no network)
116
+ npm run typecheck && npm run lint
117
+ node scripts/smoke-stdio.mjs # stdio smoke test against a local mock API
118
+ LEXAPI_API_KEY=lex_... node scripts/smoke-stdio.mjs --live # against the real API (spends roughly 6–25 credits)
82
119
  ```
83
120
 
121
+ `npm run start:http` runs the hosted Streamable HTTP transport (`POST /v1`, `GET /health`, port from `PORT`, default 3000); the `Dockerfile` builds it.
122
+
84
123
  ## License
85
124
 
86
125
  MIT
package/dist/client.d.ts CHANGED
@@ -1,31 +1,105 @@
1
- import type { AnyResponse, CitationsQuery, DocumentContentRequest, RecentDocumentsQuery, SearchRequest, SemanticSearchRequest } from './types.js';
2
- export declare class LexAPIError extends Error {
3
- readonly status: number;
4
- readonly slug: string;
5
- constructor(status: number, slug: string, message: string);
1
+ export declare const DEFAULT_BASE_URL = "https://lex-api.com/api/v1";
2
+ /**
3
+ * Deadline for one tool call (all attempts, backoff and 429 sleeps included).
4
+ * MCP clients give up after their own request timeout (the TypeScript SDK
5
+ * default is 60 s; Claude Code: MCP_TOOL_TIMEOUT), so stop a few seconds
6
+ * earlier and return an actionable message instead of the client's generic
7
+ * -32001. LexAPI's own upstream budgets (EUR-Lex fetch 90 s, semantic
8
+ * legislation 45 s, citation network 30 s) can exceed this on a cold live
9
+ * fetch; users who raise their client's timeout raise LEXAPI_TIMEOUT_MS too.
10
+ */
11
+ export declare const DEFAULT_TIMEOUT_MS = 55000;
12
+ export declare function isWellFormedKey(key: string): boolean;
13
+ /** Response headers worth surfacing to a model; everything else is dropped. */
14
+ declare const KEPT_HEADERS: readonly ["x-source", "x-language", "x-language-fallback", "x-text-available", "x-warning", "x-search-source", "x-search-cache", "x-ignored-documenttypes", "x-corpus-version", "x-export-total", "x-export-truncated"];
15
+ export type KeptHeader = (typeof KEPT_HEADERS)[number];
16
+ export type Json = Record<string, unknown>;
17
+ export interface LexResponse<T = Json> {
18
+ status: number;
19
+ body: T;
20
+ headers: Partial<Record<KeptHeader, string>>;
6
21
  }
7
22
  export interface LexAPIClientOptions {
8
23
  apiKey: string;
9
24
  baseUrl?: string;
10
- /** Max retries on transient errors (5xx, network). Default 2. */
25
+ /** Retries on transient failures (500/502/503, network errors, short 429s). Default 1. */
11
26
  maxRetries?: number;
27
+ timeoutMs?: number;
28
+ /** Injected for tests. */
29
+ fetch?: typeof fetch;
30
+ /** Injected for tests. */
31
+ sleep?: (ms: number) => Promise<void>;
32
+ /** Aborts every request of this client (MCP request cancellation). */
33
+ signal?: AbortSignal;
34
+ /** Injected for tests (the per-call deadline clock). */
35
+ now?: () => number;
36
+ }
37
+ export type Query = Record<string, string | number | boolean | string[] | undefined | null>;
38
+ interface RequestOptions {
39
+ body?: unknown;
40
+ query?: Query;
41
+ /** Parse the body as NDJSON (one JSON value per line) instead of JSON. */
42
+ ndjson?: boolean;
43
+ /** Calls whose repetition has a side effect (create, test delivery) opt out. */
44
+ retry?: boolean;
12
45
  }
13
46
  export declare class LexAPIClient {
14
47
  private readonly apiKey;
15
48
  private readonly baseUrl;
16
49
  private readonly maxRetries;
50
+ private readonly timeoutMs;
51
+ private readonly fetchImpl;
52
+ private readonly sleep;
53
+ private readonly signal?;
54
+ private readonly now;
55
+ private readonly opts;
17
56
  constructor(opts: LexAPIClientOptions);
18
- private request;
19
- search(body: SearchRequest): Promise<AnyResponse>;
20
- getDocument(body: DocumentContentRequest): Promise<AnyResponse>;
21
- getMetadata(body: DocumentContentRequest): Promise<AnyResponse>;
22
- getDocumentByUrl(body: {
23
- url: string;
24
- }): Promise<AnyResponse>;
25
- recentDocuments(query: RecentDocumentsQuery): Promise<AnyResponse>;
26
- citedBy(celex: string, query?: CitationsQuery): Promise<AnyResponse>;
27
- cites(celex: string, query?: CitationsQuery): Promise<AnyResponse>;
28
- citationNetwork(celex: string): Promise<AnyResponse>;
29
- semanticCaseLaw(body: SemanticSearchRequest): Promise<AnyResponse>;
30
- semanticLegislation(body: SemanticSearchRequest): Promise<AnyResponse>;
57
+ /** A client for one MCP request: its cancellation signal and timeout. */
58
+ forCall(call: {
59
+ signal?: AbortSignal;
60
+ timeoutMs?: number;
61
+ }): LexAPIClient;
62
+ get timeout(): number;
63
+ /** Low-level request. Throws LexAPIError (HTTP error) or LexAPITransportError. */
64
+ request<T = Json>(method: 'GET' | 'POST' | 'PUT' | 'DELETE', path: string, opts?: RequestOptions): Promise<LexResponse<T>>;
65
+ info(): Promise<LexResponse<Json>>;
66
+ search(body: Json): Promise<LexResponse<Json>>;
67
+ getDocument(body: Json): Promise<LexResponse<Json>>;
68
+ getDocumentsBatch(body: Json): Promise<LexResponse<Json>>;
69
+ getMetadata(body: Json): Promise<LexResponse<Json>>;
70
+ getDocumentByUrl(body: Json): Promise<LexResponse<Json>>;
71
+ recentDocuments(query: Query): Promise<LexResponse<Json>>;
72
+ resolve(body: Json): Promise<LexResponse<Json>>;
73
+ listVersions(celex: string, query: Query): Promise<LexResponse<Json>>;
74
+ getVersion(celex: string, version: number, query: Query): Promise<LexResponse<Json>>;
75
+ getAtDate(celex: string, date: string, query: Query): Promise<LexResponse<Json>>;
76
+ exportCorpus(query: Query): Promise<LexResponse<{
77
+ lines?: unknown[];
78
+ }>>;
79
+ semanticCaseLaw(body: Json): Promise<LexResponse<Json>>;
80
+ semanticLegislation(body: Json): Promise<LexResponse<Json>>;
81
+ extractCitations(body: Json): Promise<LexResponse<Json>>;
82
+ citedBy(celex: string, query: Query): Promise<LexResponse<Json>>;
83
+ cites(celex: string, query: Query): Promise<LexResponse<Json>>;
84
+ citationNetwork(celex: string, query: Query): Promise<LexResponse<Json>>;
85
+ citationPath(from: string, to: string, query: Query): Promise<LexResponse<Json>>;
86
+ related(celex: string, query: Query): Promise<LexResponse<Json>>;
87
+ citationStats(): Promise<LexResponse<Json>>;
88
+ listWebhooks(): Promise<LexResponse<Json>>;
89
+ getWebhook(id: string): Promise<LexResponse<Json>>;
90
+ webhookDeliveries(id: string, query: Query): Promise<LexResponse<Json>>;
91
+ createWebhook(body: Json): Promise<LexResponse<Json>>;
92
+ updateWebhook(id: string, body: Json): Promise<LexResponse<Json>>;
93
+ deleteWebhook(id: string): Promise<LexResponse<Json>>;
94
+ testWebhook(id: string): Promise<LexResponse<Json>>;
31
95
  }
96
+ /**
97
+ * The call's cancellation signal combined with this attempt's timeout.
98
+ * `dispose()` detaches the listeners of the pre-20.3 fallback (no
99
+ * AbortSignal.any), so long-lived call signals don't accumulate them.
100
+ */
101
+ export declare function combineSignals(a: AbortSignal | undefined, b: AbortSignal): {
102
+ signal: AbortSignal;
103
+ dispose: () => void;
104
+ };
105
+ export {};