@lexapi/mcp 0.2.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tools.js CHANGED
@@ -1,263 +1,1118 @@
1
- const READ_ONLY = {
2
- readOnlyHint: true,
3
- openWorldHint: true,
4
- idempotentHint: true,
5
- };
6
- const LANGUAGES = [
7
- 'en', 'fr', 'de', 'es', 'it', 'pl', 'nl', 'pt', 'ro', 'bg',
8
- 'cs', 'da', 'el', 'et', 'fi', 'ga', 'hr', 'hu', 'lt', 'lv',
9
- 'mt', 'sk', 'sl', 'sv',
1
+ import { z } from 'zod';
2
+ import { webhookUrlProblem } from './webhookUrl.js';
3
+ import { compact, creditNotice, isObj, nationalAllowanceOf, shapeCaseLaw, shapeCitedBy, shapeCites, shapeContent, shapeCounterparts, shapeDocument, shapeLegislation, shapeMetadata, shapeNationalCaseLaw, shapeNationalDocument, shapeNationalLegislation, shapeNationalSearchResult, shapeNetwork, shapeRecent, shapeSearch, shapeTransposition, nodeFields, stripEnvelope, } from './shape.js';
4
+ // ── Shared vocabularies (mirroring openapi.yaml / GET /info) ─────────
5
+ export const LANGUAGES = [
6
+ 'en', 'fr', 'de', 'es', 'it', 'pl', 'nl', 'pt', 'ro', 'bg', 'cs', 'da',
7
+ 'el', 'et', 'fi', 'ga', 'hr', 'hu', 'lt', 'lv', 'mt', 'sk', 'sl', 'sv',
8
+ ];
9
+ /** Languages the semantic index holds (server/controllers/semanticController.js). */
10
+ export const SEMANTIC_LANGUAGES = ['en', 'fr', 'de', 'es', 'it', 'sl', 'el', 'nl', 'pt', 'pl'];
11
+ export const DOCUMENT_TYPES = [
12
+ 'judgment', 'opinion', 'order', 'regulation', 'directive', 'decision',
13
+ 'recommendation', 'communication', 'proposal', 'report', 'resolution',
14
+ 'declaration', 'treaty', 'protocol', 'agreement', 'written-question',
15
+ 'oral-question', 'consolidated-text', 'guideline', 'implementing',
16
+ 'staff-working-document',
17
+ ];
18
+ export const AUTHORS = [
19
+ 'commission', 'council', 'parliament', 'court-of-justice', 'general-court',
20
+ 'civil-service-tribunal', 'ecb', 'eca', 'eesc', 'cor', 'ema', 'efsa',
10
21
  ];
11
- const DOCUMENT_TYPES = [
12
- 'judgment', 'opinion', 'order', 'regulation', 'directive',
13
- 'decision', 'recommendation', 'opinion-act', 'communication',
14
- 'proposal', 'report', 'resolution', 'declaration', 'treaty',
15
- 'protocol', 'agreement', 'written-question', 'oral-question',
16
- 'consolidated-text', 'guideline', 'implementing',
22
+ export const PROCEDURES = [
23
+ 'ordinary', 'codecision', 'consent', 'consultation', 'budget',
24
+ 'implementing', 'delegated', 'comitology', 'appointment', 'non-legislative',
17
25
  ];
18
- const AUTHORS = [
19
- 'commission', 'council', 'parliament', 'court-of-justice',
20
- 'general-court', 'ecb', 'eca', 'eesc', 'cor', 'ema', 'efsa',
26
+ /** EUR-Lex subdomain codes plus the friendly aliases the API maps to them. */
27
+ export const SUBDOMAINS = [
28
+ 'LEGISLATION', 'CONSLEG', 'TREATIES', 'EU_CASE_LAW', 'LEGAL_PROCEDURE',
29
+ 'INTER_AGREE', 'PRE_ACTS', 'PAR_QUESTION', 'NAT_CASE_LAW',
30
+ 'legislation', 'consolidated', 'treaties', 'case-law', 'legal-procedure',
31
+ 'international', 'preparatory', 'questions', 'national-case-law',
21
32
  ];
22
- const CITATION_TYPES = [
23
- 'reference', 'amendment', 'repeal',
24
- 'implementation', 'legal-basis', 'proposal',
33
+ export const CITATION_TYPES = [
34
+ 'reference', 'amendment', 'repeal', 'corrigendum', 'implementation', 'legal-basis', 'proposal', 'transposition',
25
35
  ];
26
- const CELEX_PATTERN = '^[0-9A-Z]{2,20}$';
36
+ /** Where an edge comes from (API 2.11.0 CitationProvenance). */
37
+ export const CITATION_PROVENANCES = ['notice', 'cellar', 'notice+cellar', 'cellar-nim', 'source', 'resolver'];
38
+ /** How a national edge's target was identified (API 2.11.0 CitationResolution). */
39
+ export const CITATION_RESOLUTIONS = ['id', 'key', 'abbreviation', 'text-pattern'];
40
+ const CONTENT_PARTS = ['metadata', 'fullText', 'articles', 'recitals', 'paragraphs', 'sections', 'tables', 'annexes'];
41
+ // Mirrors the API's isValidCelexToken (corrigenda `32013R0952R(04)` and
42
+ // consolidated `02016R0679-20180524` included), case-insensitive; an
43
+ // optional `CELEX:` prefix is stripped before sending.
44
+ const CELEX_RE = /^(?:CELEX:)?[0-9A-Za-z][0-9A-Za-z()._-]{4,}$/i;
45
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
46
+ const celex = (what = 'CELEX number') => z.string().trim().regex(CELEX_RE, `${what} must look like 32016R0679, 62018CJ0311, 02016R0679-20180524 or 32013R0952R(04)`)
47
+ .describe(`${what}, e.g. 32016R0679.`);
48
+ // National-corpus ids (e.g. `AT-NOR-10001597`, `SI-JUD-UPRS-2025-I.U.727.2022.`):
49
+ // a two-letter jurisdiction prefix, same as middleware/jurisdiction.js's
50
+ // nationalIdParamGuard (`/^([A-Z]{2})-/`) uses to recognise them on the
51
+ // citation graph. `includeNational`-aware citation tools accept either
52
+ // shape; document reads stay celex()-only (lex_get_national_document /
53
+ // lex_list_national_documents cover national documents directly).
54
+ const NATIONAL_ID_RE = /^[A-Za-z]{2}-[0-9A-Za-z()./_-]+$/;
55
+ const celexOrNationalId = (what = 'identifier') => z.string().trim()
56
+ .refine((v) => CELEX_RE.test(v) || NATIONAL_ID_RE.test(v), `${what} must be a CELEX number (e.g. 32016R0679) or a national document id (e.g. AT-NOR-12345)`)
57
+ .describe(`${what}: a CELEX number, or (with includeNational) a national document id, e.g. "AT-NOR-12345".`);
58
+ // National law: jurisdiction codes
59
+ // are not enumerated here — the server is the single source of truth for
60
+ // which are registered and which are LIVE (lex_national_coverage), and the
61
+ // set grows over time. A two-letter code that isn't live 404s like any
62
+ // unmatched path, same as EU_LAW.
63
+ const jurisdiction = () => z.string().trim().regex(/^[A-Za-z]{2}$/, 'a two-letter country code, e.g. "at"')
64
+ .transform((v) => v.toLowerCase())
65
+ .describe('Two-letter country code, e.g. "at".');
66
+ // The 24-code enum used to be repeated in ~10 tools (~3k tokens of tools/list).
67
+ // A pattern + refine keeps the validation and lists the codes nowhere.
68
+ const LANG_SET = new Set(LANGUAGES);
69
+ const lang = (d = 'Language: ISO 639-1 code of an official EU language (en, fr, de, …; default en).') => z.string().regex(/^[a-z]{2}$/).refine((v) => LANG_SET.has(v), 'not an official EU language code').describe(d);
70
+ // Webhook targets: https, public host — mirrors the DNS-free part of the API's
71
+ // egress guard (defence in depth; the API is authoritative).
72
+ const webhookUrl = (d) => z.string().trim().superRefine((v, ctx) => {
73
+ const problem = webhookUrlProblem(v);
74
+ if (problem)
75
+ ctx.addIssue({ code: 'custom', message: problem });
76
+ }).describe(d);
77
+ // The export API's own checks (lex-api exportController parseIsoDate /
78
+ // parseIsoTimestamp), mirrored exactly so the schema accepts what the server
79
+ // accepts and nothing else: a calendar-valid YYYY-MM-DD; a date-time needs a
80
+ // zone (Z, ±HH:MM or ±HHMM), seconds are optional, a fraction has 1–9 digits.
81
+ const ISO_TS_RE = /^(\d{4}-\d{2}-\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,9})?)?(Z|[+-]\d{2}:?\d{2}))?$/;
82
+ export function isApiDate(value) {
83
+ if (!DATE_RE.test(value))
84
+ return false;
85
+ const d = new Date(`${value}T00:00:00Z`);
86
+ return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === value;
87
+ }
88
+ export function isApiTimestamp(value) {
89
+ const m = ISO_TS_RE.exec(value);
90
+ if (!m || !isApiDate(m[1]))
91
+ return false;
92
+ if (m[2] !== undefined && (Number(m[2]) > 23 || Number(m[3]) > 59 || Number(m[4] ?? 0) > 59))
93
+ return false;
94
+ return !Number.isNaN(new Date(m[2] === undefined ? `${m[1]}T00:00:00Z` : value).getTime());
95
+ }
96
+ const isoDate = (d) => z.string().regex(DATE_RE, 'use YYYY-MM-DD').refine(isApiDate, 'not a calendar date').describe(d);
97
+ /** An ISO 8601 date, or a date-time WITH a timezone (the API rejects one without). */
98
+ const since = (d) => z.string().regex(ISO_TS_RE, 'use YYYY-MM-DD or an ISO 8601 date-time with a timezone (Z or ±HH:MM)')
99
+ .refine(isApiTimestamp, 'not a valid date/time')
100
+ .describe(`${d} ISO 8601: a date (YYYY-MM-DD, midnight UTC) or a date-time with a timezone.`);
101
+ // One value or a list; the allowed values are listed once, in the description
102
+ // (an enum inside a string|array union would print them twice).
103
+ const oneOrMany = (values, d) => {
104
+ const set = new Set(values);
105
+ return z.union([z.string(), z.array(z.string()).min(1)])
106
+ .refine((v) => (Array.isArray(v) ? v : [v]).every((x) => set.has(x)), `allowed: ${values.join(', ')}`)
107
+ .describe(`${d} One or a list of: ${values.join(', ')}.`);
108
+ };
109
+ // A list filter sent comma-separated: an array, one value, or "a,b".
110
+ const splitList = (v) => (Array.isArray(v) ? v : v.split(',')).map((x) => x.trim()).filter(Boolean);
111
+ // The values are listed once, in the array's enum; a plain string ("a,b")
112
+ // is accepted too and checked against the same set.
113
+ const csvOf = (values, d) => {
114
+ const set = new Set(values);
115
+ return z.union([z.string(), z.array(z.enum(values)).min(1)])
116
+ .transform(splitList)
117
+ .refine((v) => v.length > 0 && v.every((x) => set.has(x)), `allowed: ${values.join(', ')}`)
118
+ .describe(d);
119
+ };
120
+ // Two-letter codes (lower-cased), e.g. ["eu","at"]. Which national codes
121
+ // are live is the server's call (lex_national_coverage), not listed here.
122
+ const codeList = (d) => z.union([z.string(), z.array(z.string()).min(1).max(30)])
123
+ .transform((v) => splitList(v).map((x) => x.toLowerCase()))
124
+ .refine((v) => v.length > 0 && v.length <= 30 && v.every((x) => /^[a-z]{2}$/.test(x)), 'two-letter codes, e.g. ["eu","at"]')
125
+ .describe(d);
126
+ /** The edge filters shared by the graph tools (API 2.11.0). */
127
+ const graphFilters = {
128
+ citationType: csvOf(CITATION_TYPES, 'Only these edge types.').optional(),
129
+ provenance: csvOf(CITATION_PROVENANCES, 'Edge origins (cellar-nim: a notified measure, not a finding of transposition). The last three: 400 while no country is live.').optional(),
130
+ jurisdictions: codeList('Neighbours in: "eu" and/or live national codes (national: BUSINESS+).').optional(),
131
+ resolution: csvOf(CITATION_RESOLUTIONS, 'National edges: match method.').optional(),
132
+ };
133
+ const titleLanguage = lang('Title language (default en).').optional();
134
+ const unresolved = z.boolean().optional()
135
+ .describe('National id: add references that got no edge (100 shown).');
136
+ const view = z.enum(['auto', 'outline', 'full']).default('auto').describe('auto: the body if it fits maxChars, else an outline. full: body up to maxChars, then offset to continue.');
137
+ const maxChars = (def) => z.number().int().min(2000).max(200_000).default(def)
138
+ .describe(`Text budget in characters (default ${def}).`);
139
+ const offset = z.number().int().min(0).optional()
140
+ .describe('Continue after a truncated response (value given in its note).');
141
+ const include = z.array(z.enum(CONTENT_PARTS)).min(1).optional().describe('Only these parts. "paragraphs" = judgment grounds / text of documents without articles.');
142
+ export function normCelex(v) {
143
+ return v.trim().replace(/^CELEX:/i, '').toUpperCase();
144
+ }
145
+ const READ = { readOnlyHint: true, idempotentHint: true, openWorldHint: true };
146
+ /** Attach the low-credit notice (if any) to a shaped result. */
147
+ function withNotice(res, shaped) {
148
+ const notice = creditNotice(res.body);
149
+ return notice ? { ...shaped, notice } : shaped;
150
+ }
151
+ /** Attach the national-law allowance (FREE/STARTER/PROFESSIONAL only), when the response carried it. */
152
+ function withAllowance(res, shaped) {
153
+ const allowance = nationalAllowanceOf(res.headers);
154
+ return allowance ? { ...shaped, allowance } : shaped;
155
+ }
156
+ /** API `include` for a document request — articleId alone means "metadata + that article". */
157
+ function apiInclude(a) {
158
+ if (a.include?.length)
159
+ return a.include;
160
+ if (a.articleId)
161
+ return ['metadata', 'articles'];
162
+ return undefined;
163
+ }
164
+ /** The API answers an unmatched articleId with `articles: []`, not an error — say so. */
165
+ function noteArticleMiss(a, shaped) {
166
+ if (!a.articleId || shaped.content === null)
167
+ return shaped;
168
+ const c = isObj(shaped.content) ? shaped.content : {};
169
+ if (Array.isArray(c.articles) && c.articles.length)
170
+ return shaped;
171
+ return {
172
+ ...shaped,
173
+ note: `No article matched articleId "${a.articleId}". Call again without articleId to see the outline (article ids, or paragraphs for documents without articles).`,
174
+ };
175
+ }
176
+ /**
177
+ * Shaping options. An articleId (or include) means "read these parts": the
178
+ * selected parts are returned (paged by maxChars/offset), never re-outlined —
179
+ * otherwise a large article would bounce the model back to the outline it
180
+ * just used.
181
+ */
182
+ function contentOpts(a, budget) {
183
+ const include = a.include?.length ? a.include : a.articleId ? ['articles'] : undefined;
184
+ return {
185
+ view: a.view,
186
+ maxChars: budget ?? a.maxChars ?? 40_000,
187
+ include,
188
+ offset: a.offset,
189
+ };
190
+ }
191
+ // ── Tools ─────────────────────────────────────────────────────────────
27
192
  export const tools = [
28
- // ── Search ────────────────────────────────────────────────────────
193
+ // ── Account ─────────────────────────────────────────────────────────
194
+ {
195
+ name: 'lex_info',
196
+ title: 'LexAPI account & capabilities',
197
+ description: "The caller's LexAPI plan, credit balance (remaining, reset date) and limits, plus the accepted values for search filters. Free (0 credits). Use it when the user asks about their plan or credits, or to check the connection.",
198
+ inputSchema: {},
199
+ annotations: READ,
200
+ handler: async (_a, client) => {
201
+ const res = await client.info();
202
+ const b = res.body;
203
+ return compact({
204
+ service: b.service,
205
+ apiVersion: b.version,
206
+ subscription: b.subscription,
207
+ credits: isObj(b.credits) ? compact({ ...b.credits, operation_weight: undefined }) : undefined,
208
+ usage: b.credits ? undefined : b.usage,
209
+ searchFilters: b.searchFilters,
210
+ supportedLanguages: Array.isArray(b.supportedLanguages) ? b.supportedLanguages.join(',') : undefined,
211
+ });
212
+ },
213
+ },
214
+ // ── Search ──────────────────────────────────────────────────────────
29
215
  {
30
216
  name: 'lex_search',
31
- description: 'Search EUR-Lex with structured filters (free text, date range, document type, author, language). Returns a paginated list of matching documents with CELEX numbers, titles, and dates. Use this when the user wants to find documents matching a topic or filter; use lex_get_document afterwards to fetch full content of a specific result.',
217
+ title: 'Search EUR-Lex',
218
+ description: 'Structured EUR-Lex search: keywords plus filters (dates, type, author, procedure, collection) → CELEX numbers, titles, dates; read a hit with lex_get_document. Matching is literal: use 1–3 distinctive terms; for concept questions use lex_semantic_legislation / lex_semantic_case_law. Cost: 3 credits per result page (~10 results; unfetched pages refunded).',
32
219
  inputSchema: {
33
- type: 'object',
34
- properties: {
35
- query: { type: 'string', description: 'Free-text search.' },
36
- textScope: {
37
- type: 'string',
38
- enum: ['title', 'text', 'title-text', 'any'],
39
- description: 'Where to apply the query string.',
40
- },
41
- dateFrom: { type: 'string', format: 'date' },
42
- dateTo: { type: 'string', format: 'date' },
43
- year: {
44
- oneOf: [
45
- { type: 'integer' },
46
- { type: 'array', items: { type: 'integer' } },
47
- ],
48
- },
49
- documentType: {
50
- oneOf: [
51
- { type: 'string', enum: DOCUMENT_TYPES },
52
- { type: 'array', items: { type: 'string', enum: DOCUMENT_TYPES } },
53
- ],
54
- },
55
- author: {
56
- oneOf: [
57
- { type: 'string', enum: AUTHORS },
58
- { type: 'array', items: { type: 'string', enum: AUTHORS } },
59
- ],
60
- },
61
- language: { type: 'string', enum: LANGUAGES, default: 'en' },
62
- maxPages: {
63
- type: 'integer',
64
- minimum: 1,
65
- default: 1,
66
- description: 'Result pages to fetch (clamped by subscription tier).',
67
- },
68
- },
69
- additionalProperties: false,
70
- },
71
- annotations: { title: 'Search EUR-Lex', ...READ_ONLY },
72
- handler: (args, client) => client.search(args),
73
- },
74
- // ── Document fetch ────────────────────────────────────────────────
220
+ query: z.string().max(1000).optional().describe('Search text. Quotes force an exact phrase. "*" = no text constraint (filter-only search).'),
221
+ textScope: z.enum(['title', 'text', 'title-text', 'any']).optional().describe('Where the text must match (API default title-text).'),
222
+ dateFrom: isoDate('Document date from (inclusive).').optional(),
223
+ dateTo: isoDate('Document date to (inclusive).').optional(),
224
+ year: z.union([z.number().int().min(1950).max(2100), z.array(z.number().int().min(1950).max(2100)).min(1)]).optional().describe('Document year(s).'),
225
+ month: z.union([z.number().int().min(1).max(12), z.array(z.number().int().min(1).max(12)).min(1)]).optional().describe('Month(s) 1–12, combined with year.'),
226
+ documentType: oneOrMany(DOCUMENT_TYPES, 'Document type(s). Several types fan out into one EUR-Lex query each.').optional(),
227
+ author: oneOrMany(AUTHORS, 'Issuing institution(s).').optional(),
228
+ procedure: oneOrMany(PROCEDURES, 'Legislative procedure(s).').optional(),
229
+ domain: z.enum(['EU_LAW', 'NATIONAL_LAW', 'ALL']).optional().describe('EUR-Lex collection.'),
230
+ subdomain: oneOrMany(SUBDOMAINS, 'Sub-collection(s), e.g. "case-law", "legislation", "consolidated".').optional(),
231
+ language: lang('Result language (default en).').optional(),
232
+ maxPages: z.number().int().min(1).max(100).default(1).describe('Result pages to fetch (3 credits each; clamped to the plan: FREE 1, STARTER 5, PROFESSIONAL 20, higher 100). Raise it when a tight date filter reports postFilteredBy "date".'),
233
+ fresh: z.boolean().optional().describe('Bypass the 60-minute result cache.'),
234
+ },
235
+ annotations: READ,
236
+ handler: async (a, client) => {
237
+ const res = await client.search(compact(a));
238
+ return withNotice(res, shapeSearch(res));
239
+ },
240
+ },
241
+ {
242
+ name: 'lex_recent_documents',
243
+ title: 'Recently published EU documents',
244
+ description: 'Documents published on EUR-Lex in the last N days (default 7), newest first, optionally filtered. Use for "what was published this week". Cost: 3 credits per 10 results of limit (clamped to the plan); an unfiltered request is answered from the Publications Office in one query for 3 credits.',
245
+ inputSchema: {
246
+ days: z.number().int().min(1).max(366).default(7).describe('Look-back window in days.'),
247
+ documentType: z.enum(DOCUMENT_TYPES).optional(),
248
+ author: z.enum(AUTHORS).optional(),
249
+ domain: z.enum(['EU_LAW', 'NATIONAL_LAW', 'ALL']).optional(),
250
+ subdomain: z.enum(SUBDOMAINS).optional(),
251
+ language: lang('Keep documents available in this language (default en).').optional(),
252
+ limit: z.number().int().min(1).max(500).default(20).describe('Max results (each 10 cost 3 credits when filtered).'),
253
+ },
254
+ annotations: { ...READ, idempotentHint: false },
255
+ handler: async (a, client) => {
256
+ const res = await client.recentDocuments(a);
257
+ return withNotice(res, shapeRecent(res));
258
+ },
259
+ },
260
+ {
261
+ name: 'lex_resolve',
262
+ title: 'Resolve a legal identifier to CELEX',
263
+ description: 'Turn a pasted EUR-Lex URL, an ELI URI, an ECLI (e.g. ECLI:EU:C:2020:559) or a bare CELEX into the canonical CELEX number plus EUR-Lex links. Cost: 1 credit. ECLIs resolve only for case law already in the LexAPI corpus (404 otherwise). resolvedVia says how: celex / url (read off the identifier), ecli-corpus / eli-corpus (corpus lookup), eli-cellar (Publications Office register), eli (derived from the ELI pattern only). verified: false is normal for CELEX and URL inputs (they are not looked up, so a mistyped CELEX also comes back); with resolvedVia "eli" the mapping itself is a guess — check it with lex_get_document before relying on it.',
264
+ inputSchema: {
265
+ identifier: z.string().trim().min(3).max(2000).describe('CELEX, EUR-Lex URL, ELI URI or ECLI.'),
266
+ },
267
+ annotations: READ,
268
+ handler: async (a, client) => {
269
+ const res = await client.resolve({ identifier: a.identifier });
270
+ return withNotice(res, stripEnvelope(res.body));
271
+ },
272
+ },
273
+ // ── Documents ───────────────────────────────────────────────────────
75
274
  {
76
275
  name: 'lex_get_document',
77
- description: 'Fetch the full parsed content of a single EU document by CELEX number. Returns metadata (title, type, dates, author, ECLI/ELI, keywords) plus structured body (articles, sections, tables, annexes). Articles are individually addressable with id, number, title, and content. Use this when the user has a specific CELEX or wants the body of a known document.',
276
+ title: 'Fetch an EU document by CELEX',
277
+ description: 'A parsed EU document by CELEX: metadata plus body (articles, recitals, judgment paragraphs, annexes). Large documents return an outline first; then read an article with articleId or parts with include. content: null means no published text — textAvailability says why and may point to the latest consolidated version. Consolidated CELEXes (0…-YYYYMMDD) are labelled: not the authentic text, cite the base act. Cost: 1 credit from the corpus, 4 via the Publications Office, 5 live (every call is charged).',
278
+ inputSchema: {
279
+ celexNumber: celex(),
280
+ language: lang('Language of the whole document (default en). Falls back to English, labelled languageFallback, when EUR-Lex lacks it.').optional(),
281
+ acceptLanguages: z.union([z.array(lang()).min(1), z.literal('any')]).optional().describe('Fallback languages to serve when the requested one has no text (e.g. ["fr"] for General Court decisions), or "any".'),
282
+ articleId: z.string().trim().min(1).max(40).optional().describe('Return only this article: "17", "art_17", "Article 17", "6a".'),
283
+ include,
284
+ view,
285
+ maxChars: maxChars(40_000),
286
+ offset,
287
+ bypassCorpus: z.boolean().optional().describe('Force a fresh upstream read (charged at the live rate). Only when the stored copy is suspected stale.'),
288
+ },
289
+ annotations: READ,
290
+ handler: async (a, client) => {
291
+ const body = compact({
292
+ celexNumber: normCelex(a.celexNumber),
293
+ language: a.language,
294
+ acceptLanguages: a.acceptLanguages,
295
+ articleId: a.articleId,
296
+ include: apiInclude(a),
297
+ bypassCorpus: a.bypassCorpus,
298
+ });
299
+ const res = await client.getDocument(body);
300
+ return withNotice(res, noteArticleMiss(a, shapeDocument(res.body.document, res.headers, contentOpts(a))));
301
+ },
302
+ },
303
+ {
304
+ name: 'lex_get_documents_batch',
305
+ title: 'Fetch several EU documents',
306
+ description: 'Fetch up to 50 documents by CELEX in one call (batch size is clamped to the plan: FREE 1, STARTER 5, PROFESSIONAL 20, higher 50). Per-document failures are listed in errors; documents without published text stay in documents with textAvailability. Same per-document cost as lex_get_document (1 / 4 / 5 credits); trimmed items are not charged.',
78
307
  inputSchema: {
79
- type: 'object',
80
- required: ['celexNumber'],
81
- properties: {
82
- celexNumber: {
83
- type: 'string',
84
- pattern: CELEX_PATTERN,
85
- description: 'CELEX identifier, e.g. 32016R0679 for the GDPR.',
86
- },
87
- bypassCorpus: {
88
- type: 'boolean',
89
- description: 'Force a fresh live fetch instead of the cached copy.',
90
- },
91
- },
92
- additionalProperties: false,
93
- },
94
- annotations: { title: 'Fetch EU document by CELEX', ...READ_ONLY },
95
- handler: (args, client) => client.getDocument(args),
308
+ celexNumbers: z.array(celex()).min(1).max(50).describe('CELEX numbers.'),
309
+ language: lang().optional(),
310
+ acceptLanguages: z.union([z.array(lang()).min(1), z.literal('any')]).optional(),
311
+ articleId: z.string().trim().min(1).max(40).optional().describe('Return only this article of each document.'),
312
+ include,
313
+ view: z.enum(['auto', 'outline', 'full']).optional().describe('Per document. Default: outline, except when articleId or include is given (then those parts are returned).'),
314
+ maxChars: maxChars(60_000).describe('Character budget shared by all documents.'),
315
+ },
316
+ annotations: READ,
317
+ handler: async (a, client) => {
318
+ const res = await client.getDocumentsBatch(compact({
319
+ celexNumbers: a.celexNumbers.map(normCelex),
320
+ language: a.language,
321
+ acceptLanguages: a.acceptLanguages,
322
+ articleId: a.articleId,
323
+ include: apiInclude(a),
324
+ }));
325
+ const b = res.body;
326
+ const docs = Array.isArray(b.documents) ? b.documents : [];
327
+ // The budget is shared: per-document shares never add up past maxChars.
328
+ const per = Math.max(500, Math.floor((a.maxChars ?? 60_000) / Math.max(1, docs.length)));
329
+ const batchView = a.view ?? (a.articleId || a.include?.length ? 'auto' : 'outline');
330
+ return withNotice(res, compact({
331
+ requested: b.requested,
332
+ processed: b.processed,
333
+ successful: b.successful,
334
+ failed: b.failed,
335
+ textUnavailable: b.textUnavailable,
336
+ trimmedReason: b.trimmed ? b.trimmedReason : undefined,
337
+ documents: docs.map((d) => shapeDocument(d, {}, contentOpts({ ...a, view: batchView, offset: undefined }, per))),
338
+ errors: b.errors,
339
+ }));
340
+ },
96
341
  },
97
342
  {
98
343
  name: 'lex_get_metadata',
99
- description: 'Fetch metadata only for a CELEX (title, dates, type, author, ECLI/ELI, keywords, subjects) — significantly faster than lex_get_document because it skips body parsing. Use this for quick "what is this document" lookups or before deciding whether to fetch the body.',
344
+ title: 'EU document metadata',
345
+ description: 'Metadata only for a CELEX — title, type, author, dates, ECLI/ELI, EuroVoc keywords, EUR-Lex link — without the body. Use to identify a document cheaply before deciding to read it. Cost: 1 credit from the corpus, 4 via the Publications Office, 5 live.',
100
346
  inputSchema: {
101
- type: 'object',
102
- required: ['celexNumber'],
103
- properties: {
104
- celexNumber: {
105
- type: 'string',
106
- pattern: CELEX_PATTERN,
107
- description: 'CELEX identifier.',
108
- },
109
- },
110
- additionalProperties: false,
347
+ celexNumber: celex(),
348
+ bypassCorpus: z.boolean().optional().describe('Force a fresh upstream read (live rate).'),
349
+ },
350
+ annotations: READ,
351
+ handler: async (a, client) => {
352
+ const res = await client.getMetadata(compact({ celexNumber: normCelex(a.celexNumber), bypassCorpus: a.bypassCorpus }));
353
+ const md = isObj(res.body.metadata) ? res.body.metadata : {};
354
+ return withNotice(res, shapeMetadata(md, res.headers));
111
355
  },
112
- annotations: { title: 'Fetch EU document metadata', ...READ_ONLY },
113
- handler: (args, client) => client.getMetadata(args),
114
356
  },
115
357
  {
116
358
  name: 'lex_get_document_by_url',
117
- description: 'Fetch a parsed document from any EUR-Lex URL — useful when the user pastes a link from their browser. Extracts the CELEX from the URL and returns the same shape as lex_get_document plus sourceUrl and extractedCelex echoes.',
359
+ title: 'Fetch an EU document by EUR-Lex URL',
360
+ description: 'Same as lex_get_document, for a eur-lex.europa.eu URL the user pasted (the CELEX is extracted from CELEX:… or uri=…). Always English. For ELI/ECLI links use lex_resolve first. Cost: 1 / 4 / 5 credits by source.',
118
361
  inputSchema: {
119
- type: 'object',
120
- required: ['url'],
121
- properties: {
122
- url: {
123
- type: 'string',
124
- format: 'uri',
125
- description: 'Any eur-lex.europa.eu URL containing a CELEX: identifier or uri= parameter.',
126
- },
127
- },
128
- additionalProperties: false,
362
+ url: z.string().trim().url().describe('A eur-lex.europa.eu URL containing CELEX:<id> or uri=CELEX:<id>.'),
363
+ articleId: z.string().trim().min(1).max(40).optional(),
364
+ include,
365
+ view,
366
+ maxChars: maxChars(40_000),
367
+ offset,
368
+ bypassCorpus: z.boolean().optional().describe('Force a fresh upstream read (live rate).'),
369
+ },
370
+ annotations: READ,
371
+ handler: async (a, client) => {
372
+ const res = await client.getDocumentByUrl(compact({
373
+ url: a.url,
374
+ articleId: a.articleId,
375
+ include: apiInclude(a),
376
+ bypassCorpus: a.bypassCorpus,
377
+ }));
378
+ return withNotice(res, noteArticleMiss(a, {
379
+ extractedCelex: res.body.extractedCelex,
380
+ ...shapeDocument(res.body.document, res.headers, contentOpts(a)),
381
+ }));
129
382
  },
130
- annotations: { title: 'Fetch EU document by EUR-Lex URL', ...READ_ONLY },
131
- handler: (args, client) => client.getDocumentByUrl(args),
132
383
  },
384
+ // ── Version history (observation snapshots) ─────────────────────────
133
385
  {
134
- name: 'lex_recent_documents',
135
- description: 'List documents published to the Official Journal recently. Default window is 7 days. Filterable by document type, author, and language. Use this when the user asks "what was published this week" or wants a delta over a date window.',
386
+ name: 'lex_document_versions',
387
+ title: 'Version history of a document',
388
+ description: "Every text change LexAPI observed on a document, newest first. These are snapshots of the document as LexAPI fetched it — NOT the law in force on a date (for that use lex_semantic_legislation with asOf, or a consolidated CELEX). History starts when the document entered the corpus. Cost: 1 credit.",
136
389
  inputSchema: {
137
- type: 'object',
138
- properties: {
139
- days: {
140
- type: 'integer',
141
- minimum: 1,
142
- default: 7,
143
- description: 'Look-back window in days.',
144
- },
145
- documentType: { type: 'string', enum: DOCUMENT_TYPES },
146
- author: { type: 'string', enum: AUTHORS },
147
- language: { type: 'string', enum: LANGUAGES, default: 'en' },
148
- limit: { type: 'integer', minimum: 1, maximum: 500, default: 50 },
149
- },
150
- additionalProperties: false,
151
- },
152
- annotations: { title: 'List recent Official Journal documents', ...READ_ONLY, idempotentHint: false },
153
- handler: (args, client) => client.recentDocuments(args),
154
- },
155
- // ── Citation graph ────────────────────────────────────────────────
390
+ celexNumber: celex(),
391
+ language: lang().optional(),
392
+ },
393
+ annotations: READ,
394
+ handler: async (a, client) => {
395
+ const res = await client.listVersions(normCelex(a.celexNumber), { language: a.language });
396
+ const b = res.body;
397
+ return withNotice(res, compact({
398
+ celex: b.celex,
399
+ language: b.language,
400
+ currentVersion: b.currentVersion,
401
+ trackedSince: b.trackedSince,
402
+ versions: Array.isArray(b.versions)
403
+ ? b.versions.map((v) => (isObj(v) ? compact({
404
+ version: v.version,
405
+ isCurrent: v.isCurrent || undefined,
406
+ fetchedAt: v.fetchedAt,
407
+ contentHash: typeof v.contentHash === 'string' ? v.contentHash.slice(0, 12) : undefined,
408
+ title: v.title,
409
+ }) : v))
410
+ : [],
411
+ semantics: 'Observation snapshots (as fetched by LexAPI), not legal in-force reconstructions.',
412
+ }));
413
+ },
414
+ },
415
+ {
416
+ name: 'lex_get_document_version',
417
+ title: 'A document snapshot by version or date',
418
+ description: 'The text of one observed snapshot — by version number, or the snapshot LexAPI held on a date (YYYY-MM-DD). This is what LexAPI had fetched then, NOT the law in force on that date; dates before the document entered the corpus return 404. Cost: 1 credit.',
419
+ inputSchema: {
420
+ celexNumber: celex(),
421
+ version: z.number().int().min(1).optional().describe('Snapshot number (from lex_document_versions).'),
422
+ date: isoDate('Return the snapshot current on this date (end of day UTC).').optional(),
423
+ language: lang().optional(),
424
+ include: z.array(z.enum(CONTENT_PARTS)).min(1).optional(),
425
+ view,
426
+ maxChars: maxChars(40_000),
427
+ offset,
428
+ },
429
+ annotations: READ,
430
+ handler: async (a, client) => {
431
+ if ((a.version === undefined) === (a.date === undefined)) {
432
+ throw new Error('Pass exactly one of version or date.');
433
+ }
434
+ const c = normCelex(a.celexNumber);
435
+ const res = a.version !== undefined
436
+ ? await client.getVersion(c, a.version, { language: a.language })
437
+ : await client.getAtDate(c, a.date, { language: a.language });
438
+ const b = res.body;
439
+ const d = isObj(b.document) ? b.document : {};
440
+ const { content, note } = shapeContent(d.parsedContent, contentOpts(a));
441
+ return withNotice(res, compact({
442
+ celex: b.celex,
443
+ language: b.language,
444
+ asOf: b.asOf,
445
+ version: d.version,
446
+ isCurrent: d.isCurrent,
447
+ fetchedAt: d.fetchedAt,
448
+ title: d.title,
449
+ documentType: d.documentType,
450
+ content,
451
+ note,
452
+ semantics: 'Observation snapshot (as fetched by LexAPI), not a legal in-force reconstruction.',
453
+ }));
454
+ },
455
+ },
456
+ // ── Semantic search ─────────────────────────────────────────────────
457
+ {
458
+ name: 'lex_semantic_legislation',
459
+ title: 'Semantic search over EU legislation',
460
+ description: 'Find EU legislation articles by meaning. Hits: law_id (CELEX), article_ref (use as articleId in lex_get_document), law_title, score, snippet. Consolidated hits (consolidated: true) are not authentic: quote them, cite baseCelex. asOf gives the text in force on a past date. Cost: 5 credits; with asOf, plus up to 5 per in-force version fetched live (default max 3 per call; failed fetches free).',
461
+ inputSchema: {
462
+ query: z.string().trim().min(1).max(1000).describe('Natural-language description of the provision you are looking for.'),
463
+ asOf: isoDate('The law as in force on this date (YYYY-MM-DD, 1952-01-01 to today) — use for questions about a past date. Hits then carry the version in force (asOfResolved: true, asOfVersion). Unresolved hits keep the CURRENT text with an asOfReason; follow asOfCaveat. Omit for current law.').optional(),
464
+ limit: z.number().int().min(1).max(50).default(10).describe('Max hits (plan cap: FREE 10, STARTER 20, higher 50). Merged consolidated/base duplicates can make a page shorter.'),
465
+ min_score: z.number().min(0).max(1).optional().describe('Similarity floor. Default ≈0.7 server-side; lower (0.5) when you got fewer hits than limit, 0 disables it.'),
466
+ language: z.enum(SEMANTIC_LANGUAGES).optional().describe('Preferred language of the text (default en); acts without it come back in another language, labelled.'),
467
+ include: z.array(z.literal('text')).optional().describe('["text"] returns the full matched article text instead of a ~600-character snippet.'),
468
+ filters: z.record(z.string(), z.unknown()).optional().describe('Pass-through to the semantic index. Today only "language" is honoured for legislation; other keys are ignored.'),
469
+ maxChars: maxChars(40_000).describe('Character budget for hit texts when include is ["text"].'),
470
+ },
471
+ annotations: { ...READ, idempotentHint: false },
472
+ handler: async (a, client) => {
473
+ const res = await client.semanticLegislation(compact({
474
+ query: a.query,
475
+ asOf: a.asOf,
476
+ limit: a.limit,
477
+ min_score: a.min_score,
478
+ language: a.language,
479
+ include: a.include,
480
+ filters: a.filters,
481
+ }));
482
+ return withNotice(res, budgetHitTexts(shapeLegislation(res), a.maxChars ?? 40_000));
483
+ },
484
+ },
485
+ {
486
+ name: 'lex_semantic_case_law',
487
+ title: 'Semantic search over EU case law',
488
+ description: 'Find CJEU / General Court judgments, orders and AG opinions by meaning. Returns cases with celex (feed to lex_get_document), case number, ECLI, court, date, score and a summary. For short keyword-style queries set hyde: true (better recall, 15 credits instead of 5, +1–3 s; refunded to 5 if it falls back). Cost: 5 credits.',
489
+ inputSchema: {
490
+ query: z.string().trim().min(3).max(1000).describe('Natural-language question or description of the legal issue.'),
491
+ limit: z.number().int().min(1).max(100).default(10).describe('Max cases (plan cap: FREE 10, STARTER 20, PROFESSIONAL 50, higher 100). One result per case.'),
492
+ min_score: z.number().min(0).max(1).optional().describe('Similarity floor. Default ≈0.7 server-side; lower (0.5) when you got fewer hits than limit, 0 disables it.'),
493
+ language: z.enum(SEMANTIC_LANGUAGES).optional().describe('Preferred language (default en).'),
494
+ hyde: z.boolean().optional().describe('LLM query rewriting for terse queries (15 credits).'),
495
+ include: z.array(z.literal('text')).optional().describe('["text"] returns each judgment\'s full text (large; bounded by maxChars).'),
496
+ filters: z.object({
497
+ court: z.string().optional().describe('Court name as indexed, e.g. "Court of Justice", "General Court".'),
498
+ date_from: isoDate('Decided on or after (YYYY-MM-DD).').optional(),
499
+ date_to: isoDate('Decided on or before (YYYY-MM-DD).').optional(),
500
+ case_number: z.string().optional().describe('Exact case number, e.g. "C-311/18" (direct lookup).'),
501
+ ecli: z.string().optional().describe('Exact ECLI (direct lookup).'),
502
+ }).catchall(z.unknown()).optional().describe('Optional filters passed to the semantic index.'),
503
+ maxChars: maxChars(40_000).describe('Character budget for hit texts when include is ["text"].'),
504
+ },
505
+ annotations: { ...READ, idempotentHint: false },
506
+ handler: async (a, client) => {
507
+ const res = await client.semanticCaseLaw(compact({
508
+ query: a.query,
509
+ limit: a.limit,
510
+ min_score: a.min_score,
511
+ language: a.language,
512
+ hyde: a.hyde,
513
+ include: a.include,
514
+ filters: a.filters,
515
+ }));
516
+ return withNotice(res, budgetHitTexts(shapeCaseLaw(res), a.maxChars ?? 40_000));
517
+ },
518
+ },
519
+ // ── National law ─────────────────────────────────────────────────
520
+ // Member-state legislation and case law, alongside the EU_LAW corpus
521
+ // above. A country can be registered on LexAPI before it is available to
522
+ // customers, so every tool below except lex_national_coverage says to
523
+ // call it first; an unavailable country answers like an unmatched path
524
+ // (404), never a silent empty result. Attribution (source, licence) is
525
+ // kept on every result — it is required, not optional, context.
526
+ {
527
+ name: 'lex_national_coverage',
528
+ title: 'National-law coverage',
529
+ description: "Countries with national-law coverage: live status, legislation/case-law coverage (counts, dates, courts), semantic-search availability, citation-graph measurements (citationGraph: methods, rates, floors; null = not measured), and sources with licence/attribution. Call this before any other national tool. Free.",
530
+ inputSchema: {},
531
+ annotations: READ,
532
+ handler: async (_a, client) => {
533
+ const res = await client.nationalCoverage();
534
+ return compact(res.body);
535
+ },
536
+ },
537
+ {
538
+ name: 'lex_list_national_documents',
539
+ title: 'Browse national documents',
540
+ description: 'Browse a country\'s national documents by title/type, newest-first by document date. documentKind ("act" | "decision") tells legislation from case law. Not yet live 404s — check lex_national_coverage first. Cost: 3 credits flat, not per page; counts against the national-law allowance on lower plans (see allowance). Paging: page reaches only the first 1,000 rows; beyond, pass the previous nextCursor as cursor (any depth), without page.',
541
+ inputSchema: {
542
+ jurisdiction: jurisdiction(),
543
+ q: z.string().trim().min(3).max(200).optional().describe('Title search, 3–200 characters.'),
544
+ documentType: z.string().trim().min(1).max(200).optional().describe('Document type as stored for this country.'),
545
+ page: z.number().int().min(1).optional().describe('1-based page, first 1,000 rows only. Omit when paging with cursor.'),
546
+ cursor: z.string().trim().min(1).optional().describe('Opaque cursor from a previous call\'s nextCursor — pages past the first 1,000 rows. Do not combine with page.'),
547
+ limit: z.number().int().min(1).max(100).default(20),
548
+ includeRepealed: z.boolean().optional().describe('Also list repealed/superseded acts.'),
549
+ },
550
+ annotations: { ...READ, idempotentHint: false },
551
+ handler: async (a, client) => {
552
+ const res = await client.listNationalDocuments(a.jurisdiction, compact({
553
+ q: a.q,
554
+ type: a.documentType,
555
+ page: a.cursor ? undefined : a.page,
556
+ cursor: a.cursor,
557
+ limit: a.limit,
558
+ includeRepealed: a.includeRepealed,
559
+ }));
560
+ const b = res.body;
561
+ const results = Array.isArray(b.results) ? b.results.map(shapeNationalSearchResult) : [];
562
+ // nextCursor is meaningfully `null` ("no more pages") — compact()
563
+ // would otherwise drop it indistinguishably from "absent", the same
564
+ // pitfall `content: null` has elsewhere.
565
+ const shaped = compact({
566
+ jurisdiction: b.jurisdiction,
567
+ total: b.total,
568
+ totalExact: b.totalExact,
569
+ page: b.page,
570
+ limit: b.limit,
571
+ includeRepealed: b.includeRepealed,
572
+ hasMore: b.hasMore,
573
+ results,
574
+ });
575
+ if (b.hasMore !== undefined)
576
+ shaped.nextCursor = b.nextCursor ?? null;
577
+ return withAllowance(res, withNotice(res, shaped));
578
+ },
579
+ },
580
+ {
581
+ name: 'lex_get_national_document',
582
+ title: 'Fetch a national document',
583
+ description: 'A national document by id, e.g. "AT-NOR-12345". Same fields in every country: documentKind ("act" | "decision"); decisions add court, chamber, caseNumbers, citedNorms; articles {number, title, section, text, inForceFrom, inForceTo} (text: null = no text for that unit). Large documents return an outline first; read on with view "full" and offset. content: null = the source publishes no machine-readable text (textAvailability says why). A document its source withdrew is a distinct error: nothing of it is served; do not retry, drop any copy held. Not yet live 404s — check lex_national_coverage first. Cost: 5 reserved, settles at 1 (an unknown id too), so a pool under 5 402s. Counts against the national-law allowance on lower plans (see allowance). Show attribution (source/licence) to the user.',
584
+ inputSchema: {
585
+ jurisdiction: jurisdiction(),
586
+ id: z.string().trim().min(1).max(200).describe('National document id, e.g. "AT-NOR-12345".'),
587
+ language: lang().optional(),
588
+ view,
589
+ maxChars: maxChars(40_000),
590
+ offset,
591
+ },
592
+ annotations: READ,
593
+ handler: async (a, client) => {
594
+ const res = await client.getNationalDocument(a.jurisdiction, a.id, compact({ language: a.language }));
595
+ const shaped = shapeNationalDocument(res.body.document, contentOpts(a));
596
+ return withAllowance(res, withNotice(res, shaped));
597
+ },
598
+ },
599
+ {
600
+ name: 'lex_national_semantic_case_law',
601
+ title: 'Semantic search over national case law',
602
+ description: 'Find one country\'s case law by meaning. Hits carry documentKind, ecli, dateOfDocument, and court/caseNumbers where indexed. hyde is a no-op here (no rewrite, no extra cost). Not yet live errors — check lex_national_coverage first. partial: true (partialReason SEARCH_INCOMPLETE) means the index could not complete the search: results may be incomplete — say so, and follow the hint. Cost: flat 5 credits, never 15; counts against the national-law allowance on lower plans (see allowance). Each hit\'s attribution names the source/licence — show it to the user.',
603
+ inputSchema: {
604
+ jurisdiction: jurisdiction(),
605
+ query: z.string().trim().min(3).max(1000).describe('Natural-language question or description of the legal issue.'),
606
+ limit: z.number().int().min(1).max(100).default(10).describe('Max cases (plan cap, same as lex_semantic_case_law).'),
607
+ min_score: z.number().min(0).max(1).optional().describe('Similarity floor (default ≈0.7).'),
608
+ language: lang('Optional — omit, or the country\'s own language (e.g. "de" for AT, from lex_national_coverage); any other value is a 400.').optional(),
609
+ hyde: z.boolean().optional().describe('No-op here; never adds cost or latency.'),
610
+ include: z.array(z.literal('text')).optional().describe('["text"] returns full judgment text, bounded by maxChars.'),
611
+ filters: z.object({
612
+ court: z.string().optional(),
613
+ date_from: isoDate('From.').optional(),
614
+ date_to: isoDate('To.').optional(),
615
+ ecli: z.string().optional(),
616
+ }).strict().optional().describe('No case_number nationally.'),
617
+ maxChars: maxChars(40_000),
618
+ },
619
+ annotations: { ...READ, idempotentHint: false },
620
+ handler: async (a, client) => {
621
+ const res = await client.nationalSemanticCaseLaw(a.jurisdiction, compact({
622
+ query: a.query,
623
+ limit: a.limit,
624
+ min_score: a.min_score,
625
+ language: a.language,
626
+ hyde: a.hyde,
627
+ include: a.include,
628
+ filters: a.filters,
629
+ }));
630
+ return withAllowance(res, withNotice(res, budgetHitTexts(shapeNationalCaseLaw(res), a.maxChars ?? 40_000)));
631
+ },
632
+ },
633
+ {
634
+ name: 'lex_national_semantic_legislation',
635
+ title: 'Semantic search over national legislation',
636
+ description: 'Find one country\'s legislation articles by meaning. No asOf — current text only. Not yet live errors — check lex_national_coverage first. partial: true (partialReason SEARCH_INCOMPLETE) means the index could not complete the search: results may be incomplete — say so, and follow the hint. Cost: flat 5 credits; counts against the national-law allowance on lower plans (see allowance). Each hit\'s attribution names the source/licence — show it to the user.',
637
+ inputSchema: {
638
+ jurisdiction: jurisdiction(),
639
+ query: z.string().trim().min(3).max(1000).describe('Natural-language description of the provision you are looking for.'),
640
+ limit: z.number().int().min(1).max(50).default(10).describe('Max hits (plan cap, same as lex_semantic_legislation).'),
641
+ min_score: z.number().min(0).max(1).optional().describe('Similarity floor (default ≈0.7).'),
642
+ language: lang('Optional — omit, or the country\'s own language (e.g. "de" for AT, from lex_national_coverage); any other value is a 400.').optional(),
643
+ include: z.array(z.literal('text')).optional().describe('["text"] returns full article text instead of a snippet.'),
644
+ filters: z.object({
645
+ id: z.string().trim().min(1).optional().describe('A specific national document id.'),
646
+ inForce: z.boolean().optional().describe('As of today.'),
647
+ documentType: z.string().trim().min(1).optional(),
648
+ }).strict().optional(),
649
+ maxChars: maxChars(40_000),
650
+ },
651
+ annotations: { ...READ, idempotentHint: false },
652
+ handler: async (a, client) => {
653
+ const res = await client.nationalSemanticLegislation(a.jurisdiction, compact({
654
+ query: a.query,
655
+ limit: a.limit,
656
+ min_score: a.min_score,
657
+ language: a.language,
658
+ include: a.include,
659
+ filters: a.filters,
660
+ }));
661
+ return withAllowance(res, withNotice(res, budgetHitTexts(shapeNationalLegislation(res), a.maxChars ?? 40_000)));
662
+ },
663
+ },
664
+ // ── Citation graph ──────────────────────────────────────────────────
156
665
  {
157
666
  name: 'lex_cited_by',
158
- description: 'Find documents that cite this CELEX (inbound edges). Returns source documents grouped with their edge type (reference, amendment, repeal, implementation, legal-basis, proposal). Use to see who depends on or modifies a given act.',
667
+ title: 'Documents citing a CELEX',
668
+ description: 'Inbound citations: documents that cite, amend, correct, repeal, implement, transpose or are based on this act, with the edge type and its provenance. For legislation, amendment / corrigendum / repeal edges are read from the Publications Office (Cellar) and refreshed on read when older than 7 days; if that refresh does not finish in ~2.5 s, relationSync.status is "pending" (or "skipped") and the stored edges are served — check relationSync before calling the list complete. Other edge types cover only documents LexAPI has extracted. Page until offset + limit >= totalEdges. includeNational adds national neighbours of live countries (BUSINESS+ only; also accepts a national id, e.g. "AT-NOR-12345"). Cost: 1 credit.',
159
669
  inputSchema: {
160
- type: 'object',
161
- required: ['celexNumber'],
162
- properties: {
163
- celexNumber: { type: 'string', pattern: CELEX_PATTERN },
164
- citationType: {
165
- type: 'string',
166
- enum: CITATION_TYPES,
167
- description: 'Optionally filter to one edge type.',
168
- },
169
- limit: { type: 'integer', minimum: 1, maximum: 500, default: 100 },
170
- offset: { type: 'integer', minimum: 0, default: 0 },
171
- },
172
- additionalProperties: false,
173
- },
174
- annotations: { title: 'Find documents citing a CELEX', ...READ_ONLY },
175
- handler: (args, client) => {
176
- const { celexNumber, ...query } = args;
177
- return client.citedBy(celexNumber, query);
670
+ celexNumber: celexOrNationalId(),
671
+ ...graphFilters,
672
+ limit: z.number().int().min(1).max(500).default(50).describe('Edges per page.'),
673
+ offset: z.number().int().min(0).default(0).describe('Paging offset, in edges.'),
674
+ includeNational: z.boolean().optional().describe('Add national documents (BUSINESS+ only).'),
675
+ language: titleLanguage,
676
+ },
677
+ annotations: READ,
678
+ handler: async (a, client) => {
679
+ const { celexNumber, ...q } = a;
680
+ const res = await client.citedBy(normCelex(celexNumber), q);
681
+ return withNotice(res, shapeCitedBy(res));
178
682
  },
179
683
  },
180
684
  {
181
685
  name: 'lex_cites',
182
- description: 'Find documents this CELEX cites (outbound edges). Returns target documents grouped with their edge type. Use to see what an act relies on, amends, or implements.',
686
+ title: 'Documents a CELEX cites',
687
+ description: 'Outbound citations: what this document references, amends, repeals, implements, transposes or is based on, with the edge type and its provenance. Only populated for documents whose citations were extracted (lex_extract_citations). includeNational adds national neighbours of live countries (BUSINESS+ only; also accepts a national id, e.g. "AT-NOR-12345"). Cost: 1 credit.',
183
688
  inputSchema: {
184
- type: 'object',
185
- required: ['celexNumber'],
186
- properties: {
187
- celexNumber: { type: 'string', pattern: CELEX_PATTERN },
188
- citationType: { type: 'string', enum: CITATION_TYPES },
189
- limit: { type: 'integer', minimum: 1, maximum: 500, default: 100 },
190
- offset: { type: 'integer', minimum: 0, default: 0 },
191
- },
192
- additionalProperties: false,
689
+ celexNumber: celexOrNationalId(),
690
+ ...graphFilters,
691
+ unresolved,
692
+ limit: z.number().int().min(1).max(500).default(50),
693
+ offset: z.number().int().min(0).default(0),
694
+ includeNational: z.boolean().optional().describe('Add national documents (BUSINESS+ only).'),
695
+ language: titleLanguage,
193
696
  },
194
- annotations: { title: 'Find documents a CELEX cites', ...READ_ONLY },
195
- handler: (args, client) => {
196
- const { celexNumber, ...query } = args;
197
- return client.cites(celexNumber, query);
697
+ annotations: READ,
698
+ handler: async (a, client) => {
699
+ const { celexNumber, ...q } = a;
700
+ const res = await client.cites(normCelex(celexNumber), q);
701
+ return withNotice(res, shapeCites(res));
198
702
  },
199
703
  },
200
704
  {
201
705
  name: 'lex_citation_network',
202
- description: 'Fetch both inbound and outbound citations for a CELEX in one call, with per-edge-type counts. Use when the user wants a holistic view of how a document sits in the citation graph.',
706
+ title: 'Citation neighbourhood of a CELEX',
707
+ description: 'Both directions at once — documents this one cites and documents citing it — deduplicated, with edge types and provenance per neighbour; paging.citesTotal / citedByTotal give the full counts. includeNational adds national neighbours of live countries (BUSINESS+ only; also accepts a national id). Cost: 20 credits, refunded on a partial (timeout) answer (prefer lex_cited_by / lex_cites at 1 credit when one direction is enough).',
203
708
  inputSchema: {
204
- type: 'object',
205
- required: ['celexNumber'],
206
- properties: {
207
- celexNumber: { type: 'string', pattern: CELEX_PATTERN },
208
- },
209
- additionalProperties: false,
709
+ celexNumber: celexOrNationalId(),
710
+ ...graphFilters,
711
+ unresolved,
712
+ limit: z.number().int().min(1).max(500).default(50).describe('Edges per direction.'),
713
+ offset: z.number().int().min(0).default(0),
714
+ includeNational: z.boolean().optional().describe('Add national documents (BUSINESS+ only).'),
715
+ language: titleLanguage,
716
+ },
717
+ annotations: READ,
718
+ handler: async (a, client) => {
719
+ const { celexNumber, ...q } = a;
720
+ const res = await client.citationNetwork(normCelex(celexNumber), q);
721
+ return withNotice(res, shapeNetwork(res));
210
722
  },
211
- annotations: { title: 'Fetch full citation network for a CELEX', ...READ_ONLY },
212
- handler: (args, client) => client.citationNetwork(args.celexNumber),
213
723
  },
214
- // ── Semantic ──────────────────────────────────────────────────────
215
724
  {
216
- name: 'lex_semantic_case_law',
217
- description: 'Embedding-based search over EU case law — finds cases by meaning, not exact keywords. Returns relevance-scored matches with ECLI, court, case name/number, and (where available) full text. Requires a paid LexAPI plan; returns 403 on FREE tier.',
725
+ name: 'lex_citation_path',
726
+ title: 'Citation path between two documents',
727
+ description: 'Shortest chain of outbound citations from one document to another (e.g. how a judgment reaches a directive), optionally over filtered edges only. found: false is a normal answer, not an error. includeNational follows national documents of live countries too (BUSINESS+ only; from/to also accept a national id). Cost: 20 credits.',
218
728
  inputSchema: {
219
- type: 'object',
220
- required: ['query'],
221
- properties: {
222
- query: { type: 'string', minLength: 1 },
223
- limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 },
224
- min_score: {
225
- type: 'number',
226
- minimum: 0,
227
- maximum: 1,
228
- description: 'Drop results below this cosine similarity (0–1).',
229
- },
230
- filters: {
231
- type: 'object',
232
- additionalProperties: true,
233
- description: 'Optional filters passed through to the LexAPI semantic backend. See the LexAPI docs at https://lex-api.com/docs for accepted filter keys (e.g. court, dateFrom, dateTo, ecli).',
234
- },
235
- },
236
- additionalProperties: false,
237
- },
238
- annotations: { title: 'Semantic search over EU case law', ...READ_ONLY },
239
- handler: (args, client) => client.semanticCaseLaw(args),
729
+ from: celexOrNationalId('Start identifier'),
730
+ to: celexOrNationalId('Target identifier'),
731
+ maxDepth: z.number().int().min(1).max(8).default(3).describe('Max hops.'),
732
+ ...graphFilters,
733
+ includeNational: z.boolean().optional().describe('Add national documents (BUSINESS+ only).'),
734
+ language: titleLanguage,
735
+ },
736
+ annotations: READ,
737
+ handler: async (a, client) => {
738
+ const res = await client.citationPath(normCelex(a.from), normCelex(a.to), {
739
+ maxDepth: a.maxDepth,
740
+ includeNational: a.includeNational,
741
+ citationType: a.citationType,
742
+ provenance: a.provenance,
743
+ jurisdictions: a.jurisdictions,
744
+ resolution: a.resolution,
745
+ language: a.language,
746
+ });
747
+ const b = stripEnvelope(res.body);
748
+ if (Array.isArray(b.path)) {
749
+ b.path = b.path.map((n) => (isObj(n) ? compact({ ...nodeFields(n), title: n.title }) : n));
750
+ }
751
+ return withNotice(res, compact(b));
752
+ },
240
753
  },
241
754
  {
242
- name: 'lex_semantic_legislation',
243
- description: 'Embedding-based search over EU legislation at article granularity. Returns relevance-scored article hits with parent CELEX, article reference, and law title. Requires a paid LexAPI plan; returns 403 on FREE tier.',
755
+ name: 'lex_related',
756
+ title: 'Documents related by shared citations',
757
+ description: 'Documents that cite the most of the same acts as this one (bibliographic coupling) — "what else deals with this"; the edge filters narrow which shared citations count. Needs the seed\'s outbound citations (lex_extract_citations). includeNational considers national documents of live countries too (BUSINESS+ only; also accepts a national id). Cost: 20 credits.',
244
758
  inputSchema: {
245
- type: 'object',
246
- required: ['query'],
247
- properties: {
248
- query: { type: 'string', minLength: 1 },
249
- limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 },
250
- min_score: { type: 'number', minimum: 0, maximum: 1 },
251
- filters: {
252
- type: 'object',
253
- additionalProperties: true,
254
- description: 'Optional filters passed through to the LexAPI semantic backend. See the LexAPI docs at https://lex-api.com/docs for accepted filter keys (e.g. documentType, author, language, dateFrom, dateTo).',
255
- },
256
- },
257
- additionalProperties: false,
258
- },
259
- annotations: { title: 'Semantic search over EU legislation', ...READ_ONLY },
260
- handler: (args, client) => client.semanticLegislation(args),
759
+ celexNumber: celexOrNationalId(),
760
+ limit: z.number().int().min(1).max(50).default(10),
761
+ ...graphFilters,
762
+ includeNational: z.boolean().optional().describe('Add national documents (BUSINESS+ only).'),
763
+ language: titleLanguage,
764
+ },
765
+ annotations: READ,
766
+ handler: async (a, client) => {
767
+ const res = await client.related(normCelex(a.celexNumber), {
768
+ limit: a.limit,
769
+ includeNational: a.includeNational,
770
+ citationType: a.citationType,
771
+ provenance: a.provenance,
772
+ jurisdictions: a.jurisdictions,
773
+ resolution: a.resolution,
774
+ language: a.language,
775
+ });
776
+ const b = stripEnvelope(res.body, ['method']);
777
+ if (Array.isArray(b.related)) {
778
+ b.related = b.related.map((r) => (isObj(r) ? compact({
779
+ ...nodeFields(r),
780
+ title: r.title,
781
+ sharedCount: r.sharedCount,
782
+ sharedTargets: Array.isArray(r.sharedTargets) ? r.sharedTargets.slice(0, 10) : undefined,
783
+ }) : r));
784
+ }
785
+ return withNotice(res, compact(b));
786
+ },
787
+ },
788
+ {
789
+ name: 'lex_citation_stats',
790
+ title: 'Citation graph statistics',
791
+ description: 'Totals for the whole LexAPI citation graph plus the 10 most-cited and 10 most-citing documents. includeNational counts national documents of live countries too and adds byJurisdiction, byProvenance and transposition (notified measures, and how many LexAPI holds) — BUSINESS+ only. Cost: 20 credits.',
792
+ inputSchema: {
793
+ includeNational: z.boolean().optional().describe('Add national documents (BUSINESS+ only).'),
794
+ },
795
+ annotations: READ,
796
+ handler: async (a, client) => {
797
+ const res = await client.citationStats({ includeNational: a.includeNational });
798
+ return withNotice(res, stripEnvelope(res.body));
799
+ },
800
+ },
801
+ {
802
+ name: 'lex_transposition',
803
+ title: 'Notified national measures for an EU act',
804
+ description: 'The measures member states (and the UK) notified to the Commission for an EU act (CELEX sector 3, e.g. a directive), by country, from the Publications Office\'s Cellar records. A notification is not a finding that the measure transposes the act, or transposes it completely — say so when presenting it (the result\'s note). Every plan. On BUSINESS+ it also says, for live countries only, which measures LexAPI holds (id, resolved) and adds documents whose national source records the relation (provenance "source"); below that those fields are absent. termsRequired: true = the account must accept the national-source terms in the dashboard first. Keep source.cellar.attribution with anything republished. Output is bounded (limit, ~40,000 characters): page with the offset given in more. Cost: 5 credits per call (each offset page too); not an EU act = 404, settles at 1.',
805
+ inputSchema: {
806
+ celexNumber: celex('CELEX number of the EU act'),
807
+ jurisdictions: codeList('Only these countries, e.g. ["es","cz"] (EL = Greece, UK = United Kingdom); default all 28.').optional(),
808
+ resolvedOnly: z.boolean().optional().describe('Only measures resolved to a document LexAPI holds (BUSINESS+, live countries).'),
809
+ limit: z.number().int().min(1).max(200).default(50).describe('Measures shown, across countries.'),
810
+ offset: z.number().int().min(0).default(0).describe('Skip this many measures (value given in the previous result\'s more).'),
811
+ language: titleLanguage,
812
+ },
813
+ annotations: READ,
814
+ handler: async (a, client) => {
815
+ const res = await client.transposition(normCelex(a.celexNumber), {
816
+ jurisdictions: a.jurisdictions,
817
+ resolvedOnly: a.resolvedOnly,
818
+ language: a.language,
819
+ });
820
+ return withNotice(res, shapeTransposition(res, a.limit ?? 50, a.offset ?? 0));
821
+ },
822
+ },
823
+ {
824
+ name: 'lex_counterparts',
825
+ title: 'Counterparts of a national act in other countries',
826
+ description: 'A national document\'s counterparts in the other live countries, through the EU acts it transposes or implements (via), ranked: 1 = the national source records the relation; 2 = a notified measure LexAPI holds; 3 = a notified Cellar record LexAPI does not hold (no id). An EU act (CELEX sector 3) as id groups its measures the same way. Only live countries are returned — check lex_national_coverage; a national id of a country not live 404s (nothing charged); any other 404 settles at 1 credit. A notification is not a finding that the measure transposes the act. BUSINESS, SCALE and ENTERPRISE only (403 below, refunded); the national-law allowance does not apply. Output is bounded (limit per act, up to 25 acts and ~40,000 characters): page with the offset given in more. Cost: 20 credits (each offset page too); a server timeout is refunded — narrow with jurisdictions.',
827
+ inputSchema: {
828
+ id: celexOrNationalId('National document id or EU act CELEX'),
829
+ jurisdictions: codeList('Only these live countries, e.g. ["si","es"]; default every live one.').optional(),
830
+ limit: z.number().int().min(1).max(50).default(10).describe('Counterparts shown per EU act.'),
831
+ offset: z.number().int().min(0).default(0).describe('Skip this many EU acts (value given in more).'),
832
+ language: titleLanguage,
833
+ },
834
+ annotations: READ,
835
+ handler: async (a, client) => {
836
+ const res = await client.counterparts(normCelex(a.id), { jurisdictions: a.jurisdictions, language: a.language });
837
+ return withNotice(res, shapeCounterparts(res, a.limit ?? 10, a.offset ?? 0, 25));
838
+ },
839
+ },
840
+ {
841
+ name: 'lex_extract_citations',
842
+ title: 'Extract a document\'s citations',
843
+ description: 'Read a document\'s EUR-Lex notice and add its outbound citations to the graph, so lex_cites / lex_related work for it. Idempotent: returns alreadyExtracted when done before. Cost: 5 credits (1 when already extracted).',
844
+ inputSchema: { celexNumber: celex() },
845
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
846
+ // Writes to the shared citation graph and spends credits: hidden in read-only mode like the other writes.
847
+ write: true,
848
+ handler: async (a, client) => {
849
+ const res = await client.extractCitations({ celexNumber: normCelex(a.celexNumber) });
850
+ const b = stripEnvelope(res.body);
851
+ if (Array.isArray(b.citations)) {
852
+ const all = b.citations;
853
+ b.citations = all.slice(0, 100).map((c) => (isObj(c) ? compact({ celex: c.targetCelex, type: c.citationType }) : c));
854
+ if (all.length > 100)
855
+ b.note = `${all.length - 100} more citations stored; read them with lex_cites.`;
856
+ }
857
+ return withNotice(res, compact(b));
858
+ },
859
+ },
860
+ // ── Export ──────────────────────────────────────────────────────────
861
+ {
862
+ name: 'lex_export',
863
+ title: 'Export corpus rows',
864
+ description: 'Rows from the LexAPI corpus matching filters — e.g. regulations dated 2024 or documents whose text changed since a date. BUSINESS plans and above (403 otherwise). Cost: 1 credit per row returned, at least 1 per call. The call is admitted for 1 credit, the matching rows are counted, and the rest of 1 credit per row it can return (up to limit) is reserved; if the pool cannot cover that, LexAPI answers 402 before returning anything (retry with a smaller limit). Reserved credits for rows not returned are refunded. Keep limit small. An export that fails part-way is reported as incomplete, never as a result. Bulk export for ML training needs a separate licence (Terms §6).',
865
+ inputSchema: {
866
+ documentType: z.array(z.string().min(1)).min(1).optional().describe('Stored document-type labels, matched exactly but ignoring case, e.g. ["Regulation","Directive"]: "regulation" matches Regulation, not Implementing regulation (use documentTypeCode for the family).'),
867
+ documentTypeCode: z.array(z.string().min(1)).min(1).optional().describe('Type families by documentTypeCode, e.g. ["regulation"] — includes implementing and delegated regulations. Combined with documentType, both must match.'),
868
+ author: z.array(z.string().min(1)).min(1).optional().describe('Stored author values, matched whole and ignoring case (a joint act\'s "European Parliament, Council of the European Union" is one value).'),
869
+ subdomain: z.array(z.enum(['treaties', 'international', 'legislation', 'internal', 'preparatory', 'case-law', 'national-transposition', 'national-case-law', 'questions', 'consolidated'])).min(1).optional(),
870
+ language: lang().optional(),
871
+ dateFrom: isoDate('Document date from (inclusive, YYYY-MM-DD).').optional(),
872
+ dateTo: isoDate('Document date to (inclusive, YYYY-MM-DD).').optional(),
873
+ changedSince: since('Only rows whose text changed at or after this time — the cheapest incremental sync.').optional(),
874
+ fetchedSince: since('Only rows written to at or after this time (any update, including metadata-only). Prefer changedSince for syncing text.').optional(),
875
+ includeContent: z.boolean().default(false).describe('Include each row\'s parsed body (bounded by maxChars).'),
876
+ includeStubs: z.boolean().optional().describe('Also rows whose text EUR-Lex does not publish.'),
877
+ limit: z.number().int().min(1).max(200).default(20).describe('Rows (1 credit each; at least 1 credit per call).'),
878
+ maxChars: maxChars(40_000),
879
+ },
880
+ annotations: READ,
881
+ handler: async (a, client) => {
882
+ const res = await client.exportCorpus({
883
+ documentType: a.documentType,
884
+ documentTypeCode: a.documentTypeCode,
885
+ author: a.author,
886
+ subdomain: a.subdomain,
887
+ language: a.language,
888
+ dateFrom: a.dateFrom,
889
+ dateTo: a.dateTo,
890
+ changedSince: a.changedSince,
891
+ fetchedSince: a.fetchedSince,
892
+ includeContent: a.includeContent ? 'true' : 'false',
893
+ includeStubs: a.includeStubs ? 'true' : undefined,
894
+ limit: a.limit,
895
+ });
896
+ const lines = Array.isArray(res.body.lines) ? res.body.lines : [];
897
+ let meta;
898
+ let done;
899
+ let serverError;
900
+ const rows = [];
901
+ for (const l of lines) {
902
+ if (isObj(l) && '_meta' in l)
903
+ meta = l._meta;
904
+ else if (isObj(l) && '_done' in l)
905
+ done = l._done;
906
+ // A line whose only key is `_error` is a failure signal, never a row.
907
+ else if (isObj(l) && Object.keys(l).length === 1 && '_error' in l)
908
+ serverError = l._error;
909
+ else
910
+ rows.push(l);
911
+ }
912
+ // SDK contract §1.8: complete only with a `_done` trailer that does not
913
+ // say `complete: false`, and no `_error` line. Anything else is a
914
+ // partial export that must not be presented as the result.
915
+ if (done === undefined || (isObj(done) && done.complete === false) || serverError !== undefined) {
916
+ const why = serverError !== undefined
917
+ ? `the server reported an error mid-stream (${isObj(serverError) ? `${String(serverError.code ?? 'UNKNOWN')}: ${String(serverError.message ?? '')}` : String(serverError)})`
918
+ : done === undefined
919
+ ? 'the stream ended without its completion trailer'
920
+ : 'its completion trailer says complete: false';
921
+ throw new Error(`lex_export is incomplete: ${why} after ${rows.length} row(s). The rows received are not the whole result — do not treat them as complete; retry the export (a smaller limit or narrower filters helps).`);
922
+ }
923
+ const per = Math.max(500, Math.floor((a.maxChars ?? 40_000) / Math.max(1, rows.length)));
924
+ return compact({
925
+ totalMatching: isObj(meta) ? meta.totalMatching : res.headers['x-export-total'],
926
+ returned: rows.length,
927
+ truncated: isObj(done) ? done.truncated : undefined,
928
+ // limit | max_rows | credits (the pool could not pay for rows added since the
929
+ // count) | recovered (the server's recovery sweep took the export's billing record mid-stream)
930
+ truncatedBy: isObj(done) ? done.truncatedBy : undefined,
931
+ skippedStubs: isObj(done) ? done.skippedStubs : undefined,
932
+ rows: rows.map((r) => {
933
+ if (!isObj(r))
934
+ return r;
935
+ const shaped = shapeMetadata(r);
936
+ if (a.includeContent && r.parsedContent) {
937
+ const { content, note } = shapeContent(r.parsedContent, { view: 'auto', maxChars: per });
938
+ return compact({ ...shaped, content, note });
939
+ }
940
+ return compact({ ...shaped, contentHash: undefined, lastSeenAt: r.lastSeenAt });
941
+ }),
942
+ });
943
+ },
944
+ },
945
+ // ── Webhooks (account state) ────────────────────────────────────────
946
+ {
947
+ name: 'lex_list_webhooks',
948
+ title: 'List webhooks',
949
+ description: 'The account\'s webhooks with status, criteria, watch list and delivery counters. Free.',
950
+ inputSchema: {},
951
+ annotations: READ,
952
+ handler: async (_a, client) => {
953
+ const res = await client.listWebhooks();
954
+ const list = Array.isArray(res.body.webhooks) ? res.body.webhooks : [];
955
+ return { count: list.length, webhooks: list.map((w) => (isObj(w) ? compact(w) : w)) };
956
+ },
957
+ },
958
+ {
959
+ name: 'lex_get_webhook',
960
+ title: 'Webhook details and deliveries',
961
+ description: 'One webhook with its recent delivery attempts (status, HTTP response, attempts). Pass deliveriesOffset/deliveriesLimit to page through older deliveries. Free.',
962
+ inputSchema: {
963
+ id: z.string().trim().min(1).max(64).describe('Webhook id.'),
964
+ deliveriesLimit: z.number().int().min(1).max(100).optional(),
965
+ deliveriesOffset: z.number().int().min(0).optional(),
966
+ },
967
+ annotations: READ,
968
+ handler: async (a, client) => {
969
+ const res = await client.getWebhook(a.id);
970
+ const w = isObj(res.body.webhook) ? { ...res.body.webhook } : {};
971
+ let deliveries = Array.isArray(w.recentDeliveries) ? w.recentDeliveries : [];
972
+ let total;
973
+ if (a.deliveriesLimit !== undefined || a.deliveriesOffset !== undefined) {
974
+ const d = await client.webhookDeliveries(a.id, { limit: a.deliveriesLimit, offset: a.deliveriesOffset });
975
+ deliveries = Array.isArray(d.body.deliveries) ? d.body.deliveries : [];
976
+ total = d.body.total;
977
+ }
978
+ delete w.recentDeliveries;
979
+ return compact({
980
+ webhook: compact(w),
981
+ deliveriesTotal: total,
982
+ deliveries: deliveries.map(shapeDelivery),
983
+ });
984
+ },
985
+ },
986
+ {
987
+ name: 'lex_create_webhook',
988
+ title: 'Create a webhook',
989
+ description: 'Subscribe a URL (must be a public https URL) to (a) new EUR-Lex documents matching searchCriteria and/or (b) changes to watched acts (watchCelex: amendments, corrigenda, repeals, new consolidated versions). Checked hourly; deliveries are free and HMAC-signed. The signing secret is returned ONLY in this response — tell the user to store it. Plan limits apply (FREE has no webhooks). Confirm the URL and criteria with the user first. Free.',
990
+ inputSchema: {
991
+ name: z.string().trim().min(1).max(200).describe('Label.'),
992
+ url: webhookUrl('Must be a public https URL (port 443 or 8443, a public domain name or address); it receives the POSTs.'),
993
+ searchCriteria: z.object({
994
+ query: z.string().optional().describe('Words that must all appear in the title (whole words; 4+ characters match word starts; trailing * for prefixes).'),
995
+ documentType: z.union([z.string(), z.array(z.string())]).optional(),
996
+ author: z.union([z.string(), z.array(z.string())]).optional(),
997
+ subdomain: z.union([z.string(), z.array(z.string())]).optional().describe('Replaces the default (EU law, no consolidated texts); "consolidated" = consolidated texts only.'),
998
+ dateFrom: isoDate('Lower bound on the document date.').optional(),
999
+ dateTo: isoDate('Upper bound on the document date.').optional(),
1000
+ year: z.union([z.number().int().min(1950).max(2100), z.array(z.number().int().min(1950).max(2100))]).optional(),
1001
+ textScope: z.enum(['title', 'title-text', 'any']).optional(),
1002
+ domain: z.enum(['EU_LAW', 'ALL']).optional(),
1003
+ language: z.string().optional(),
1004
+ }).strict().optional().describe('Filters for documents.new, in the lex_search vocabulary.'),
1005
+ watchCelex: z.array(celex('Base-act CELEX')).max(5000).optional().describe('Base acts to watch (not consolidated versions or corrigenda).'),
1006
+ secret: z.string().min(16).max(256).optional().describe('Own signing secret; generated when omitted.'),
1007
+ },
1008
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
1009
+ write: true,
1010
+ handler: async (a, client) => {
1011
+ if (!a.searchCriteria && !a.watchCelex?.length)
1012
+ throw new Error('Pass searchCriteria, watchCelex, or both.');
1013
+ const res = await client.createWebhook(compact({
1014
+ name: a.name,
1015
+ url: a.url,
1016
+ searchCriteria: a.searchCriteria,
1017
+ watchCelex: a.watchCelex?.map(normCelex),
1018
+ secret: a.secret,
1019
+ }));
1020
+ return {
1021
+ ...stripEnvelope(res.body),
1022
+ important: 'The webhook secret above is shown only once: the user must store it now to verify X-Webhook-Signature.',
1023
+ };
1024
+ },
1025
+ },
1026
+ {
1027
+ name: 'lex_update_webhook',
1028
+ title: 'Update a webhook',
1029
+ description: 'Change a webhook\'s name, URL, searchCriteria (null removes them), watch list (replaces the whole list) or status. status ACTIVE re-enables a PAUSED or FAILED webhook and re-queues its recent failed deliveries; PAUSED stops deliveries. Free.',
1030
+ inputSchema: {
1031
+ id: z.string().trim().min(1).max(64),
1032
+ name: z.string().trim().min(1).max(200).optional(),
1033
+ url: webhookUrl('Must be a public https URL.').optional().describe('Must be a public https URL.'),
1034
+ searchCriteria: z.union([z.record(z.string(), z.unknown()), z.null()]).optional().describe('New criteria (same shape as lex_create_webhook), or null to remove.'),
1035
+ watchCelex: z.array(celex('Base-act CELEX')).max(5000).optional(),
1036
+ status: z.enum(['ACTIVE', 'PAUSED']).optional(),
1037
+ },
1038
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
1039
+ write: true,
1040
+ handler: async (a, client) => {
1041
+ const { id, ...rest } = a;
1042
+ const body = {};
1043
+ for (const [k, v] of Object.entries(rest))
1044
+ if (v !== undefined)
1045
+ body[k] = v;
1046
+ if (Array.isArray(body.watchCelex))
1047
+ body.watchCelex = body.watchCelex.map(normCelex);
1048
+ if (!Object.keys(body).length)
1049
+ throw new Error('Nothing to update: pass at least one field.');
1050
+ const res = await client.updateWebhook(id, body);
1051
+ return stripEnvelope(res.body);
1052
+ },
1053
+ },
1054
+ {
1055
+ name: 'lex_delete_webhook',
1056
+ title: 'Delete a webhook',
1057
+ description: 'Permanently delete a webhook and its delivery history. Cannot be undone — confirm with the user first. Free.',
1058
+ inputSchema: { id: z.string().trim().min(1).max(64) },
1059
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
1060
+ write: true,
1061
+ handler: async (a, client) => {
1062
+ await client.deleteWebhook(a.id);
1063
+ return { deleted: a.id };
1064
+ },
1065
+ },
1066
+ {
1067
+ name: 'lex_test_webhook',
1068
+ title: 'Send a test delivery',
1069
+ description: 'POST a signed webhook.test payload to the webhook URL now and report the endpoint\'s response. Use to check an endpoint is reachable and verifies signatures. Free.',
1070
+ inputSchema: { id: z.string().trim().min(1).max(64) },
1071
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
1072
+ write: true,
1073
+ handler: async (a, client) => {
1074
+ const res = await client.testWebhook(a.id);
1075
+ return stripEnvelope(res.body);
1076
+ },
261
1077
  },
262
1078
  ];
263
- export const toolsByName = Object.fromEntries(tools.map((t) => [t.name, t]));
1079
+ function shapeDelivery(d) {
1080
+ if (!isObj(d))
1081
+ return d;
1082
+ const p = isObj(d.payload) ? d.payload : {};
1083
+ const data = isObj(p.data) ? p.data : {};
1084
+ return compact({
1085
+ id: d.id,
1086
+ status: d.status,
1087
+ event: p.event,
1088
+ documents: typeof data.count === 'number' ? data.count : undefined,
1089
+ responseStatus: d.responseStatus,
1090
+ errorMessage: d.errorMessage,
1091
+ attemptCount: d.attemptCount,
1092
+ nextRetryAt: d.nextRetryAt,
1093
+ deliveredAt: d.deliveredAt,
1094
+ createdAt: d.createdAt,
1095
+ });
1096
+ }
1097
+ /** Bound `text` across semantic hits to a total budget (only present with include: ['text']). */
1098
+ function budgetHitTexts(shaped, budget) {
1099
+ const results = Array.isArray(shaped.results) ? shaped.results : [];
1100
+ const withText = results.filter((r) => typeof r.text === 'string');
1101
+ if (!withText.length)
1102
+ return shaped;
1103
+ const per = Math.max(1000, Math.floor(budget / withText.length));
1104
+ let cut = 0;
1105
+ for (const r of withText) {
1106
+ const t = r.text;
1107
+ if (t.length > per) {
1108
+ r.text = `${t.slice(0, per)} …[truncated: ${t.length - per} more characters]`;
1109
+ cut++;
1110
+ }
1111
+ }
1112
+ return cut
1113
+ ? { ...shaped, note: `${cut} hit text(s) truncated to ${per} characters (maxChars=${budget}). Read a full document with lex_get_document.` }
1114
+ : shaped;
1115
+ }
1116
+ export function selectTools(opts = {}) {
1117
+ return opts.readOnly ? tools.filter((t) => !t.write) : tools;
1118
+ }