@lexapi/mcp 0.3.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 CHANGED
@@ -2,16 +2,65 @@
2
2
 
3
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
4
 
5
+ ## 0.5.0 — unreleased
6
+
7
+ Brings the citation-graph tools in line with LexAPI API 2.11.0 (transposition, counterparts, edge provenance and filters); **requires LexAPI API 2.11.0**. The coverage fields of API 2.12.0 / 2.13.0 are passed through unchanged.
8
+
9
+ ### Added
10
+ - **`lex_transposition`** (5 credits, every plan): the measures the member states (and the United Kingdom) notified to the Commission for an EU act, grouped by country, from the Publications Office's Cellar records. The API's `note` — a notification is not a finding that the measure transposes the act, or transposes it completely — is always kept, and the tool description tells the model to say so. On BUSINESS, SCALE and ENTERPRISE, for live countries, the measures LexAPI holds carry `id` / `resolved` / `resolution` / `resolutionBasis`, and measures recorded by the national source itself are added (`provenance: "source"`); `termsRequired` is surfaced. `jurisdictions` and `resolvedOnly` are forwarded; the measures are bounded by `limit` (default 50, at most 200) / `offset` across countries and about 40,000 characters per result, with every country's `counts` and `source.cellar.attribution` kept; when the API truncated its answer, the result says so and where the full numbers are.
11
+ - **`lex_counterparts`** (20 credits, BUSINESS, SCALE and ENTERPRISE only): a national document's counterparts in the other live countries, through the EU acts it transposes or implements, ranked 1–3; an EU act as `id` lists its measures the same way. `jurisdictions` is forwarded; output is bounded to 25 EU acts and about 40,000 characters per call (`offset`) and `limit` counterparts per act (default 10, at most 50).
12
+ - **Edge filters** on `lex_cited_by`, `lex_cites`, `lex_citation_network`, `lex_citation_path` and `lex_related`: `citationType` now takes a list (and the new type `transposition`), plus `provenance`, `resolution` and `jurisdictions`. Lists are sent comma-separated; values are validated before the call.
13
+ - `language` (the language of the titles shown) on `lex_cited_by`, `lex_cites`, `lex_citation_network`, `lex_citation_path`, `lex_related`, `lex_transposition` and `lex_counterparts`.
14
+ - **`unresolved`** on `lex_cites` and `lex_citation_network` (national document ids): the references that could not be turned into an edge, the first 100 shown, with `unresolvedTruncated`.
15
+ - Citation results show each edge group's `provenance` and `resolution`, and a node's `jurisdiction` (national documents only) and `documentKind`; `lex_cited_by` / `lex_cites` keep `totalEdges` and `countsSource` (API 2.10.0), `lex_citation_network` keeps `paging.countsSource`. `lex_citation_stats` passes `byJurisdiction`, `byProvenance` and `transposition` through.
16
+ - `describeError`: a legacy-shape `400 INVALID_PARAMS` now shows `param` and `allowed`; `403 NATIONAL_TERMS_NOT_ACCEPTED` points at the one-time acceptance in the dashboard (`acceptUrl`); a `503 TIMEOUT` (counterparts) says it was refunded and to narrow with `jurisdictions`.
17
+ - `lex_national_semantic_case_law` / `lex_national_semantic_legislation` keep `partial` / `partialReason` (`SEARCH_INCOMPLETE`): the national index could not complete the search, so results may be incomplete; both descriptions say so.
18
+ - `describeError`: `422 NATIONAL_SEMANTIC_FILTER_UNREACHABLE` says the index cannot search that slice completely, that it is not a "no matches" answer, and to rephrase the query or change the filters (not retryable as is); a `503 NATIONAL_SEMANTIC_UNAVAILABLE` with `partialReason: "SEARCH_INCOMPLETE"` says it is not a "no matches" answer and gives the wait, or — without one — to try later or rephrase.
19
+ - `lex_resolve`'s description explains `resolvedVia` (incl. `eli-cellar`) and `verified` (passed through when the API sends them); it suggests checking the CELEX only for an unverified `eli` answer.
20
+
21
+ ### Changed
22
+ - A `503` whose body says `TIMEOUT` (a server-side time budget ran out) is no longer retried automatically; other 503s are retried as before.
23
+ - A `503` with `partialReason: "SEARCH_INCOMPLETE"` is retried at most once, only after its wait (`Retry-After`, else the body's `retryAfter`; at most 10 s) and only when at least 15 s of the call's deadline is left after it; without a wait it is not retried. Other 503s are retried as before, and a 503 is never described as a rate limit.
24
+ - `lex_national_coverage`'s description mentions the `citationGraph` measurements it returns.
25
+
26
+ ## 0.4.0 — unreleased
27
+
28
+ Adds national-law support (member-state legislation and case law alongside EUR-Lex; **requires LexAPI API 2.8.0**) and **Sign in with LexAPI** on the hosted server.
29
+
30
+ ### National document shape (API 2.8.0)
31
+ - The national tools present the same fields for every country, read from the normalized contract and never from a source's raw keys (Austria's `gericht`, Germany's `aktenzeichen`, the Netherlands' `zaaknummer`, …): `documentKind` (`act` | `decision`) on listing rows, documents and semantic hits; on a decision, `lex_get_national_document` flattens `decision` into `court`, `chamber`, `caseNumbers` and `citedNorms` (`{ text, documentId }`) — also when the decision has no text; articles are `{ number, title, section, text, inForceFrom, inForceTo }` (a unit without text keeps `text: null`). The text's language facts (`textLanguages` when it differs from the document's language, `textLanguage`, `embeddedForeignText`) and a confirmed `repeal` are surfaced at the top level. Null-filled summary fields are compacted away, as before.
32
+ - `lex_national_semantic_case_law` hits take `documentKind`, `title`, `ecli` and `dateOfDocument` from each hit's `document` (LexAPI's own record), falling back to the index's metadata; `court` and `caseNumbers` come from the index. `lex_national_semantic_legislation` hits add `documentKind`, `documentType`, `valid_from` and `law_type`.
33
+
34
+ ### Added
35
+ - **5 tools**: `lex_national_coverage` (which countries are live, and their legislation/case-law/semantic coverage, sources, licences and attribution — call this first), `lex_list_national_documents` (browse by title/type), `lex_get_national_document` (fetch one by id), `lex_national_semantic_case_law` and `lex_national_semantic_legislation` (separate tools, mirroring the `lex_semantic_case_law` / `lex_semantic_legislation` split — different filters and billing notes). Every tool but the coverage one states in its description that a country may be registered but not yet available to customers, and to call `lex_national_coverage` first.
36
+ - **National-law allowance**: `X-National-Limit` / `X-National-Remaining` / `X-National-Reset` response headers are surfaced as `allowance: { limit, remaining, resetsAt }` on every national tool's result (omitted for BUSINESS and higher, which have no separate limit). A `402 NATIONAL_ALLOWANCE_EXHAUSTED` gets its own actionable message in `describeError`, distinct from the credit-pool `CREDITS_EXHAUSTED` message: it's a separate monthly counter, a credit top-up does not help, and it resets at the start of next UTC month.
37
+ - `attribution` (the official source and its licence, e.g. RIS, gesetze-im-internet.de, Normattiva, Légifrance/Judilibre, the Rechtspraak open data) is kept on every national document and every semantic hit — never dropped by response shaping, since it's required legal attribution, not optional context.
38
+ - National legislation search has no `asOf` parameter (not supported for national law); national case-law search accepts `hyde` for schema compatibility with `lex_semantic_case_law` but it is always a no-op (the national index never rewrites, so it never costs the 15-credit premium).
39
+ - **`includeNational` on the citation-graph tools** (`lex_cited_by`, `lex_cites`, `lex_citation_network`, `lex_citation_path`, `lex_related`, `lex_citation_stats`): also returns/follows national neighbours of live countries (BUSINESS, SCALE and ENTERPRISE only — 403 below that). `celexNumber` and `lex_citation_path`'s `from`/`to` now also accept a national document id directly (e.g. `"AT-NOR-12345"`); `includeNational` is carried through response shaping. `lex_extract_citations` is unchanged (CELEX/EU-only).
40
+ - A national document its source withdrew (a takedown, a pseudonymisation fix) now answers `410 DOCUMENT_WITHDRAWN` — a dedicated `describeError` branch says it's gone for good (not retryable), to drop any cached copy, and not to try to identify who it was about. Covers both envelope shapes: the typed one (`lex_get_national_document`) and the legacy one (citation tools for a withdrawn national id). `lex_list_national_documents` gained `cursor` (pages past the first 1,000 rows that `page` reaches) and the response fields `totalExact`/`hasMore`/`nextCursor`; `q`'s minimum length is 3; its cost stays 3 credits flat.
41
+ - A licensing/permitted-use guardrail in `SERVER_INSTRUCTIONS`: consolidated national texts are not authentic; never re-identify anonymised/pseudonymised parties; never evaluate/compare/predict individual French judges (art. 33 loi n° 2019-222).
42
+ - **Sign in with LexAPI** on the hosted server (`https://mcp.lex-api.com/v1`). MCP clients that support MCP authorization (OAuth 2.1) can connect with your LexAPI account instead of a pasted API key: add the URL, sign in, approve the consent page. Calls are billed to your plan exactly as with an API key, and you can disconnect the app at any time from the LexAPI dashboard.
43
+ - OAuth Protected Resource Metadata (RFC 9728) at `https://mcp.lex-api.com/.well-known/oauth-protected-resource/v1`. An unauthenticated request gets `401` with `WWW-Authenticate: Bearer realm="lexapi", resource_metadata="…", scope="lex"`; a rejected or expired token gets `error="invalid_token"`, so clients refresh or re-authorize.
44
+ - A connection that is revoked while in use is answered with `401 invalid_token` where possible, or with a tool error asking to reconnect.
45
+ - `/health` reports whether sign-in is enabled.
46
+ ### Changed
47
+ - `409 NATIONAL_SEMANTIC_NOT_ENABLED` and `503 NATIONAL_SEMANTIC_UNAVAILABLE` get their own `describeError` messages (point at the right country/tools, not the account); the 404 branch detects a national miss and stops pointing at `lex_resolve`/`lex_search`. `lex_national_semantic_legislation`'s `query` has a minimum length of 3 characters, matching case law. Both national semantic tools' `language` accepts the full ISO 639-1 range rather than the 10-language EU enum (national lanes are single-language and not all are in that list). `lex_get_national_document`'s cost note is "5 reserved, settles at 1" (a pool under 5 credits still 402s). `lex_list_national_documents`' `documentType` accepts up to 200 characters.
48
+ - `lex_get_national_document`'s outline reading hint points at `view "full"` + `offset` (that tool has no `articleId`/`include` parameter).
49
+ - README: how to connect from claude.ai / Claude Desktop (custom connector), Claude Code (`claude mcp add --transport http lexapi https://mcp.lex-api.com/v1`, then `/mcp` → *Authenticate*) and other MCP clients; the API-key option remains documented. The FREE-plan note now points to the pricing page instead of quoting an allowance.
50
+ - `server.json`: the remote's `Authorization` header is now optional (sign-in is discovered from the server's 401); version 0.4.0.
51
+ - Hosted server: a credential that cannot be a LexAPI API key (contains a `.` or is over 8192 characters) is answered `401` by the MCP server instead of being forwarded. No valid API key is affected.
52
+ - API keys (`Authorization: Bearer lex_…` or `x-api-key`) keep working on the hosted server exactly as before; when both headers are sent with sign-in enabled, `x-api-key` takes precedence.
53
+
5
54
  ## 0.3.0 — 2026-10-26
6
55
 
7
- Brings the server in line with the current LexAPI API (API changelog up to the consolidated-text / `asOf` release, LexAPI PR #298).
56
+ Brings the server in line with the current LexAPI API (API changelog up to the consolidated-text / `asOf` release).
8
57
 
9
58
  ### Added
10
59
  - **`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
60
  - **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
61
  - 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.
62
+ - `lex_export` (API 2.3.0): `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.
63
+ - 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; the API remains authoritative.
15
64
  - 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
65
  - Server `instructions` (workflow, citing consolidated texts, `asOf` vs. version snapshots, credit awareness), tool `title`s, server `title` / `websiteUrl`.
17
66
  - `LEXAPI_MCP_READ_ONLY` hides the webhook-changing tools; `LEXAPI_TIMEOUT_MS`.
@@ -26,8 +75,8 @@ Brings the server in line with the current LexAPI API (API changelog up to the c
26
75
  - `textAvailability` is passed through verbatim whenever text is missing (reason, languages, consolidated pointers); language fallback (`languageRequested`, `languageFallback`) and `titleLanguage` are kept.
27
76
  - **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
77
  - 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).
78
+ - A top-level string `code` on a legacy-shape error body 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.
79
+ - `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.
31
80
  - 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
81
  - The API key is validated at startup (no whitespace / control characters); network errors never echo runtime text (undici can quote header values).
33
82
  - 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).
package/README.md CHANGED
@@ -4,11 +4,39 @@
4
4
 
5
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
- 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.
7
+ You need a LexAPI account. With the hosted server you just **sign in with LexAPI** from your MCP client; with the npm package (or if you prefer), use an API key from [lex-api.com/dashboard](https://lex-api.com/dashboard?ref=npm-mcp). There is a FREE plan, no card required, with enough credits to try the read tools; current allowances are on [lex-api.com/pricing](https://lex-api.com/pricing?ref=npm-mcp).
8
8
 
9
- ## Install
9
+ ## Connect to the hosted server (sign in with LexAPI)
10
10
 
11
- ### Claude Desktop
11
+ The server is hosted at **`https://mcp.lex-api.com/v1`** (Streamable HTTP). Add that URL to your client and sign in with your LexAPI account when it asks — no key to copy. You see a LexAPI consent page listing what the connection can do; calls are billed to your plan exactly like your own API key, and you can disconnect the app at any time under *Dashboard → Connected apps* (that revokes it immediately).
12
+
13
+ ### claude.ai and Claude Desktop
14
+
15
+ *Settings → Connectors → Add custom connector*, name it `LexAPI`, URL `https://mcp.lex-api.com/v1`, then *Connect* and sign in. Connectors added on claude.ai are also available in Claude Desktop (same account).
16
+
17
+ ### Claude Code
18
+
19
+ ```bash
20
+ claude mcp add --transport http lexapi https://mcp.lex-api.com/v1
21
+ ```
22
+
23
+ Then run `/mcp` in Claude Code and choose *Authenticate* for `lexapi`; your browser opens the LexAPI sign-in.
24
+
25
+ ### Other MCP clients
26
+
27
+ Any client that implements MCP authorization (OAuth 2.1 with protected-resource discovery) connects the same way: point it at `https://mcp.lex-api.com/v1`. The server answers an unauthenticated request with `401` and `WWW-Authenticate: Bearer … resource_metadata="https://mcp.lex-api.com/.well-known/oauth-protected-resource/v1"`; the client discovers LexAPI (`https://lex-api.com`) as the authorization server from there.
28
+
29
+ ### With an API key instead
30
+
31
+ Clients without OAuth support — or scripts — send a key from the dashboard as `Authorization: Bearer lex_...` (or `x-api-key: lex_...`):
32
+
33
+ ```bash
34
+ claude mcp add --transport http lexapi https://mcp.lex-api.com/v1 --header "Authorization: Bearer lex_..."
35
+ ```
36
+
37
+ ## Run it locally (npm, API key)
38
+
39
+ ### Claude Desktop (local)
12
40
 
13
41
  Add to `claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`):
14
42
 
@@ -26,7 +54,7 @@ Add to `claude_desktop_config.json` (macOS: `~/Library/Application Support/Claud
26
54
 
27
55
  Restart Claude Desktop.
28
56
 
29
- ### Claude Code
57
+ ### Claude Code (local)
30
58
 
31
59
  ```bash
32
60
  claude mcp add lexapi --env LEXAPI_API_KEY=lex_... -- npx -y @lexapi/mcp
@@ -36,15 +64,7 @@ claude mcp add lexapi --env LEXAPI_API_KEY=lex_... -- npx -y @lexapi/mcp
36
64
 
37
65
  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
66
 
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
- ```
46
-
47
- The npm package needs Node.js 20 or newer.
67
+ The npm package needs Node.js 20 or newer. It uses an API key; signing in with LexAPI is a feature of the hosted server.
48
68
 
49
69
  ## Tools
50
70
 
@@ -63,18 +83,33 @@ Every call is billed from your LexAPI credit pool exactly like the REST endpoint
63
83
  | `lex_get_document_by_url` | A document from a pasted EUR-Lex URL. | 1 · 4 · 5 |
64
84
  | `lex_document_versions` | LexAPI's observed version history of a document. | 1 |
65
85
  | `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 |
86
+ | `lex_cited_by` | Documents citing / amending / correcting / repealing / transposing an act, with each edge's provenance. `includeNational` adds national neighbours (BUSINESS+). | 1 |
87
+ | `lex_cites` | What a document cites. `includeNational` adds national neighbours (BUSINESS+). | 1 |
88
+ | `lex_citation_network` | Both directions in one call. `includeNational` adds national neighbours (BUSINESS+). | 20 |
89
+ | `lex_citation_path` | Shortest citation chain between two documents. `includeNational` follows national documents (BUSINESS+). | 20 |
90
+ | `lex_related` | Documents citing the same acts (bibliographic coupling). `includeNational` considers national documents (BUSINESS+). | 20 |
91
+ | `lex_citation_stats` | Citation graph totals and most-cited documents. `includeNational` counts national documents (BUSINESS+). | 20 |
72
92
  | `lex_extract_citations` | Add a document's outbound citations to the graph. | 5 (1 if already done) |
93
+ | `lex_transposition` | The measures member states notified to the Commission for an EU act, by country (Cellar records; every plan). A notification is not a finding that the measure transposes the act. On BUSINESS+ it also says which measures LexAPI holds in live countries. | 5 |
94
+ | `lex_counterparts` | A national act's counterparts in the other live countries, through the EU acts it transposes or implements (BUSINESS+). | 20 |
73
95
  | `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) |
96
+ | `lex_national_coverage` | Which countries' national law LexAPI covers and what's live in each (sources, licences, attribution). Call first. | free |
97
+ | `lex_list_national_documents` | Browse a country's national legislation/case law by title or type; cursor paging past the first 1,000 rows. | 3 per call |
98
+ | `lex_get_national_document` | A national document by id. Always served from the corpus. | 5 → 1 |
99
+ | `lex_national_semantic_case_law` | Semantic search over one country's case law. | 5 |
100
+ | `lex_national_semantic_legislation` | Semantic search over one country's legislation. | 5 |
74
101
  | `lex_info` | Your plan, credit balance and limits. | free |
75
102
  | `lex_list_webhooks` · `lex_get_webhook` | Your webhooks and their deliveries. | free |
76
103
  | `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
104
 
105
+ ### National law
106
+
107
+ `lex_national_coverage`, `lex_list_national_documents`, `lex_get_national_document`, `lex_national_semantic_case_law` and `lex_national_semantic_legislation` cover member-state legislation and case law alongside the EU_LAW tools above. A country can be registered on LexAPI before it is made available to customers — always call `lex_national_coverage` first; the other tools answer an error for a country that isn't live yet. The citation-graph tools (`lex_cited_by`, `lex_cites`, `lex_citation_network`, `lex_citation_path`, `lex_related`, `lex_citation_stats`) accept national document ids directly (e.g. `"AT-NOR-12345"`) and an `includeNational` option to pull in national neighbours — BUSINESS, SCALE and ENTERPRISE only, 403 below that. National results have the same fields in every country (LexAPI API 2.8.0): `documentKind` (`act` | `decision`) everywhere, and on a decision `court`, `chamber`, `caseNumbers` and `citedNorms` — whatever the source calls them. Every national result carries `attribution` (the official source and its licence, e.g. RIS, gesetze-im-internet.de, Normattiva, Légifrance/Judilibre, the Rechtspraak open data) — show it to the user alongside anything quoted. On FREE/STARTER/PROFESSIONAL plans, national-law calls also draw from a separate monthly allowance (reported as `allowance` on each response); BUSINESS and higher have no separate limit. A document its source withdrew (a takedown, a pseudonymisation fix) answers a distinct error — nothing of it is served, not even the title; the model is told not to retry and to drop any cached copy. When the national index could not complete a semantic search, the result carries `partial: true` (`partialReason: "SEARCH_INCOMPLETE"`) and a `hint` — results may be incomplete; with nothing left to return the tool answers an error instead (a `503` retried after its `Retry-After`, or a `422 NATIONAL_SEMANTIC_FILTER_UNREACHABLE`: rephrase or change the filters), never an empty "no matches".
108
+
109
+ ### Citation-graph filters and provenance
110
+
111
+ `lex_cited_by`, `lex_cites`, `lex_citation_network`, `lex_citation_path` and `lex_related` take `citationType` (one type or a list, including `transposition`), `provenance` (`notice`, `cellar`, `notice+cellar`, `cellar-nim`, `source`, `resolver`), `resolution` (`id`, `key`, `abbreviation`, `text-pattern` — national edges only) and `jurisdictions` (`eu` and the codes of live countries; a national code needs BUSINESS+ like `includeNational`). Results show each edge's `provenance` and `resolution`, and a node's `jurisdiction` (national documents only) and `documentKind`. `cellar-nim` edges are measures a member state notified to the Commission — a notification, not a finding that the measure transposes the act, or transposes it completely. With a national document id, `unresolved: true` on `lex_cites` / `lex_citation_network` adds the references that could not be turned into an edge (the first 100 are shown). `lex_national_coverage` reports each country's citation-graph measurements (`citationGraph`). `lex_transposition` and `lex_counterparts` bound their output with `limit` / `offset`, applied by this MCP server to the API's answer; each further page is a new call at the tool's cost.
112
+
78
113
  ### How results are shaped for models
79
114
 
80
115
  - **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.
@@ -93,7 +128,20 @@ Every call is billed from your LexAPI credit pool exactly like the REST endpoint
93
128
  | `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
129
  | `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. |
95
130
 
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.
131
+ The key is sent only as the `x-api-key` header to LexAPI; it is never logged or included in tool output. A `LEXAPI_API_KEY` containing whitespace or control characters (e.g. a multi-line paste) is rejected at startup.
132
+
133
+ ### Hosting the HTTP server
134
+
135
+ `npm run start:http` (or the `Dockerfile`) runs the Streamable HTTP transport (`POST /v1`, `GET /health`). Self-hosted, it accepts LexAPI API keys (`Authorization: Bearer lex_…` or `x-api-key: lex_…`); a request without one gets `401`. A value that cannot be an API key (it contains a `.` or is longer than 8192 characters) is answered `401` and never forwarded.
136
+
137
+ | Env var | Default | Purpose |
138
+ |---|---|---|
139
+ | `PORT` | `3000` | Listen port. |
140
+ | `LEXAPI_BASE_URL` | `https://lex-api.com/api/v1` | LexAPI REST base. |
141
+
142
+ Sign in with LexAPI is a feature of the hosted server at `https://mcp.lex-api.com/v1`: it needs an OAuth client registered with LexAPI, so a self-hosted copy runs with API keys only. The OAuth-related settings in `src/oauth/config.ts` (`LEXAPI_OAUTH_*`, `LEXAPI_MCP_*`) are for that deployment; the server refuses to start if they are set incompletely.
143
+
144
+ **`/health`** returns `status`, `name`, `version`, `tools` and `oauth` (whether sign-in is enabled). It never contains addresses, tokens or configuration values.
97
145
 
98
146
  **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.
99
147
 
@@ -101,11 +149,17 @@ The key is sent only as the `x-api-key` header to LexAPI; it is never logged or
101
149
 
102
150
  - **`LEXAPI_API_KEY is not set`** — the variable isn't reaching the spawned process; check the `env` block of your MCP client config.
103
151
  - **`LexAPI error 401`** — the key is wrong or revoked; create a new one at the dashboard.
152
+ - **Hosted server: "LexAPI sign-in expired or was revoked"** — the connection was disconnected (for example from the dashboard); reconnect LexAPI in your client to sign in again.
153
+ - **Hosted server: `403 Subscription inactive`** — the signed-in account's paid plan is not active; the same as with an API key.
104
154
  - **`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
155
  - **`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
156
  - **`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
157
  - **`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).
108
158
 
159
+ ## Training data
160
+
161
+ Using LexAPI content to train, fine-tune or evaluate models needs a separate licence ([Terms §6](https://lex-api.com/terms?ref=npm-mcp#acceptable-use)). [Arieta Data](https://data.arietalabs.com/?ref=npm-mcp), a sister product from Arieta Labs, licenses datasets drawn from the same corpus for training, retrieval and evaluation.
162
+
109
163
  ## Development
110
164
 
111
165
  ```bash
@@ -118,7 +172,7 @@ node scripts/smoke-stdio.mjs # stdio smoke test against a local mock API
118
172
  LEXAPI_API_KEY=lex_... node scripts/smoke-stdio.mjs --live # against the real API (spends roughly 6–25 credits)
119
173
  ```
120
174
 
121
- `npm run start:http` runs the hosted Streamable HTTP transport (`POST /v1`, `GET /health`, port from `PORT`, default 3000); the `Dockerfile` builds it.
175
+ `npm run start:http` runs the hosted Streamable HTTP transport (`POST /v1`, `GET /health`, port from `PORT`, default 3000; see *Hosting the HTTP server* above); the `Dockerfile` builds it. The OAuth tests run against a local mock authorization server (`tests/oauth-mock.ts`), no network.
122
176
 
123
177
  ## License
124
178
 
package/dist/client.d.ts CHANGED
@@ -11,7 +11,7 @@ export declare const DEFAULT_BASE_URL = "https://lex-api.com/api/v1";
11
11
  export declare const DEFAULT_TIMEOUT_MS = 55000;
12
12
  export declare function isWellFormedKey(key: string): boolean;
13
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"];
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", "x-national-limit", "x-national-remaining", "x-national-reset"];
15
15
  export type KeptHeader = (typeof KEPT_HEADERS)[number];
16
16
  export type Json = Record<string, unknown>;
17
17
  export interface LexResponse<T = Json> {
@@ -19,8 +19,30 @@ export interface LexResponse<T = Json> {
19
19
  body: T;
20
20
  headers: Partial<Record<KeptHeader, string>>;
21
21
  }
22
+ /**
23
+ * How a request authenticates to LexAPI. The API-key credential sends
24
+ * `x-api-key`; the hosted server's OAuth credential (src/oauth/upstream.ts)
25
+ * sends `Authorization: Bearer <exchanged API token>` and no `x-api-key`.
26
+ */
27
+ export interface UpstreamAuth {
28
+ /** Headers for one attempt (may exchange a token: throws its own typed errors). */
29
+ headers(ctx: {
30
+ signal?: AbortSignal;
31
+ }): Promise<Record<string, string>> | Record<string, string>;
32
+ /**
33
+ * The API answered 401. Return 'retry' to send the request once more with
34
+ * fresh headers, an Error to fail with it, or undefined for the normal 401.
35
+ */
36
+ onUnauthorized?(info: {
37
+ wwwAuthenticate: string | null;
38
+ body: string;
39
+ }): Promise<'retry' | Error | undefined> | 'retry' | Error | undefined;
40
+ }
22
41
  export interface LexAPIClientOptions {
23
- apiKey: string;
42
+ /** API key (stdio, hosted API-key requests). Required unless `auth` is given. */
43
+ apiKey?: string;
44
+ /** Any other credential (hosted OAuth requests). Takes precedence over `apiKey`. */
45
+ auth?: UpstreamAuth;
24
46
  baseUrl?: string;
25
47
  /** Retries on transient failures (500/502/503, network errors, short 429s). Default 1. */
26
48
  maxRetries?: number;
@@ -44,7 +66,7 @@ interface RequestOptions {
44
66
  retry?: boolean;
45
67
  }
46
68
  export declare class LexAPIClient {
47
- private readonly apiKey;
69
+ private readonly auth;
48
70
  private readonly baseUrl;
49
71
  private readonly maxRetries;
50
72
  private readonly timeoutMs;
@@ -60,6 +82,7 @@ export declare class LexAPIClient {
60
82
  timeoutMs?: number;
61
83
  }): LexAPIClient;
62
84
  get timeout(): number;
85
+ private credentialHeaders;
63
86
  /** Low-level request. Throws LexAPIError (HTTP error) or LexAPITransportError. */
64
87
  request<T = Json>(method: 'GET' | 'POST' | 'PUT' | 'DELETE', path: string, opts?: RequestOptions): Promise<LexResponse<T>>;
65
88
  info(): Promise<LexResponse<Json>>;
@@ -84,7 +107,14 @@ export declare class LexAPIClient {
84
107
  citationNetwork(celex: string, query: Query): Promise<LexResponse<Json>>;
85
108
  citationPath(from: string, to: string, query: Query): Promise<LexResponse<Json>>;
86
109
  related(celex: string, query: Query): Promise<LexResponse<Json>>;
87
- citationStats(): Promise<LexResponse<Json>>;
110
+ citationStats(query?: Query): Promise<LexResponse<Json>>;
111
+ transposition(celex: string, query?: Query): Promise<LexResponse<Json>>;
112
+ counterparts(id: string, query?: Query): Promise<LexResponse<Json>>;
113
+ nationalCoverage(): Promise<LexResponse<Json>>;
114
+ getNationalDocument(jurisdiction: string, id: string, query: Query): Promise<LexResponse<Json>>;
115
+ listNationalDocuments(jurisdiction: string, query: Query): Promise<LexResponse<Json>>;
116
+ nationalSemanticCaseLaw(jurisdiction: string, body: Json): Promise<LexResponse<Json>>;
117
+ nationalSemanticLegislation(jurisdiction: string, body: Json): Promise<LexResponse<Json>>;
88
118
  listWebhooks(): Promise<LexResponse<Json>>;
89
119
  getWebhook(id: string): Promise<LexResponse<Json>>;
90
120
  webhookDeliveries(id: string, query: Query): Promise<LexResponse<Json>>;
package/dist/client.js CHANGED
@@ -16,8 +16,18 @@ const KEY_RE = /^[\x21-\x7e]+$/;
16
16
  export function isWellFormedKey(key) {
17
17
  return KEY_RE.test(key);
18
18
  }
19
- /** A 429 whose Retry-After is longer than this is returned to the model instead of slept on. */
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
+ */
20
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;
21
31
  /** Response headers worth surfacing to a model; everything else is dropped. */
22
32
  const KEPT_HEADERS = [
23
33
  'x-source',
@@ -31,11 +41,20 @@ const KEPT_HEADERS = [
31
41
  'x-corpus-version',
32
42
  'x-export-total',
33
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',
34
49
  ];
35
50
  /** No retry or 429 sleep is started unless at least this much of the call's deadline would remain. */
36
51
  const MIN_ATTEMPT_MS = 2000;
52
+ function apiKeyAuth(key) {
53
+ const headers = { 'x-api-key': key };
54
+ return { headers: () => headers };
55
+ }
37
56
  export class LexAPIClient {
38
- apiKey;
57
+ auth;
39
58
  baseUrl;
40
59
  maxRetries;
41
60
  timeoutMs;
@@ -45,14 +64,19 @@ export class LexAPIClient {
45
64
  now;
46
65
  opts;
47
66
  constructor(opts) {
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.');
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
+ }
54
79
  this.opts = opts;
55
- this.apiKey = key;
56
80
  this.signal = opts.signal;
57
81
  this.now = opts.now ?? Date.now;
58
82
  this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
@@ -72,6 +96,18 @@ export class LexAPIClient {
72
96
  get timeout() {
73
97
  return this.timeoutMs;
74
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
+ }
75
111
  /** Low-level request. Throws LexAPIError (HTTP error) or LexAPITransportError. */
76
112
  async request(method, path, opts = {}) {
77
113
  const url = new URL(this.baseUrl + path);
@@ -86,13 +122,12 @@ export class LexAPIClient {
86
122
  url.searchParams.set(k, String(v));
87
123
  }
88
124
  }
89
- const headers = {
90
- 'x-api-key': this.apiKey,
125
+ const baseHeaders = {
91
126
  accept: opts.ndjson ? 'application/x-ndjson, application/json' : 'application/json',
92
127
  'user-agent': `lexapi-mcp/${PACKAGE_VERSION}`,
93
128
  };
94
129
  if (opts.body !== undefined)
95
- headers['content-type'] = 'application/json';
130
+ baseHeaders['content-type'] = 'application/json';
96
131
  const canRetry = opts.retry !== false;
97
132
  // ONE deadline for the whole call — attempts, backoff and 429 sleeps all
98
133
  // come out of it, so retries can never push a call past the timeout the
@@ -101,10 +136,20 @@ export class LexAPIClient {
101
136
  const remaining = () => deadline - this.now();
102
137
  const canWait = (ms) => remaining() - ms >= MIN_ATTEMPT_MS;
103
138
  let attempt = 0;
139
+ let authRetried = false;
140
+ let incompleteRetried = false;
104
141
  for (;;) {
105
142
  if (remaining() <= 0) {
106
143
  throw new LexAPITransportError(`no response within ${Math.round(this.timeoutMs / 1000)} s`, true);
107
144
  }
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 };
108
153
  let res;
109
154
  const attemptSignal = combineSignals(this.signal, AbortSignal.timeout(Math.max(1, remaining())));
110
155
  try {
@@ -138,7 +183,27 @@ export class LexAPIClient {
138
183
  await discard(res);
139
184
  throw new LexAPITransportError('the request was cancelled by the client', false, true);
140
185
  }
141
- // A used-up legacy quota (QUOTA_EXHAUSTED, lex-api #304) cannot succeed
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
142
207
  // before it refills, whatever its Retry-After says: never retried.
143
208
  if (res.status === 429 && canRetry && attempt < this.maxRetries && !(await isQuotaExhausted(res))) {
144
209
  const wait = retryAfterSeconds(res);
@@ -151,15 +216,39 @@ export class LexAPIClient {
151
216
  continue;
152
217
  }
153
218
  }
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);
160
- attempt++;
161
- await this.sleep(backoff);
162
- continue;
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
+ }
163
252
  }
164
253
  let text;
165
254
  try {
@@ -184,7 +273,7 @@ export class LexAPIClient {
184
273
  const parsed = parseErrorBody(safeJson(text), text, res.status);
185
274
  const quota = parsed.code === 'QUOTA_EXHAUSTED';
186
275
  throw new LexAPIError(res.status, parsed.code, parsed.message, parsed.details,
187
- // A quota 429 has no meaningful retry-after (SDK contract §1.2).
276
+ // A quota 429 has no meaningful retry-after.
188
277
  quota ? undefined : (retryAfterSeconds(res) ?? parsed.retryAfter), parsed.resetsAt);
189
278
  }
190
279
  let body;
@@ -240,7 +329,29 @@ export class LexAPIClient {
240
329
  return this.request('GET', `/citations/path/${enc(from)}/${enc(to)}`, { query });
241
330
  }
242
331
  related(celex, query) { return this.request('GET', `/citations/related/${enc(celex)}`, { query }); }
243
- citationStats() { return this.request('GET', '/citations/stats'); }
332
+ citationStats(query = {}) { return this.request('GET', '/citations/stats', { query }); }
333
+ transposition(celex, query = {}) {
334
+ return this.request('GET', `/citations/transposition/${enc(celex)}`, { query });
335
+ }
336
+ counterparts(id, query = {}) {
337
+ return this.request('GET', `/citations/counterparts/${enc(id)}`, { query });
338
+ }
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 });
345
+ }
346
+ listNationalDocuments(jurisdiction, query) {
347
+ return this.request('GET', `/${jurisdiction.toLowerCase()}/documents`, { query });
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
+ }
244
355
  // ── Webhooks ─────────────────────────────────────────────────────
245
356
  listWebhooks() { return this.request('GET', '/webhooks'); }
246
357
  getWebhook(id) { return this.request('GET', `/webhooks/${enc(id)}`); }
@@ -315,6 +426,34 @@ async function isQuotaExhausted(res) {
315
426
  return false;
316
427
  }
317
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
+ }
318
457
  function retryAfterSeconds(res) {
319
458
  const raw = res.headers.get('retry-after');
320
459
  if (!raw)