@lexapi/mcp 0.1.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +61 -0
- package/LICENSE +1 -1
- package/README.md +73 -34
- package/dist/client.d.ts +93 -19
- package/dist/client.js +300 -94
- package/dist/errors.d.ts +35 -0
- package/dist/errors.js +164 -0
- package/dist/http-entry.d.ts +2 -0
- package/dist/http-entry.js +19 -0
- package/dist/http-server.d.ts +16 -0
- package/dist/http-server.js +231 -0
- package/dist/index.js +19 -61
- package/dist/server.d.ts +61 -0
- package/dist/server.js +97 -0
- package/dist/shape.d.ts +61 -0
- package/dist/shape.js +607 -0
- package/dist/tools.d.ts +25 -8
- package/dist/tools.js +803 -218
- package/dist/version.d.ts +1 -0
- package/dist/version.js +9 -0
- package/dist/webhookUrl.d.ts +4 -0
- package/dist/webhookUrl.js +114 -0
- package/package.json +24 -14
- package/dist/types.d.ts +0 -43
- package/dist/types.js +0 -7
package/dist/tools.js
CHANGED
|
@@ -1,263 +1,848 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
'
|
|
8
|
-
|
|
9
|
-
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { webhookUrlProblem } from './webhookUrl.js';
|
|
3
|
+
import { compact, creditNotice, isObj, shapeCaseLaw, shapeCitedBy, shapeCites, shapeContent, shapeDocument, shapeLegislation, shapeMetadata, shapeNetwork, shapeRecent, shapeSearch, 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
|
|
12
|
-
'
|
|
13
|
-
'
|
|
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
|
-
|
|
19
|
-
|
|
20
|
-
'
|
|
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',
|
|
25
35
|
];
|
|
26
|
-
const
|
|
36
|
+
const CONTENT_PARTS = ['metadata', 'fullText', 'articles', 'recitals', 'paragraphs', 'sections', 'tables', 'annexes'];
|
|
37
|
+
// Mirrors the API's isValidCelexToken (corrigenda `32013R0952R(04)` and
|
|
38
|
+
// consolidated `02016R0679-20180524` included), case-insensitive; an
|
|
39
|
+
// optional `CELEX:` prefix is stripped before sending.
|
|
40
|
+
const CELEX_RE = /^(?:CELEX:)?[0-9A-Za-z][0-9A-Za-z()._-]{4,}$/i;
|
|
41
|
+
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
42
|
+
const celex = (what = 'CELEX number') => z.string().trim().regex(CELEX_RE, `${what} must look like 32016R0679, 62018CJ0311, 02016R0679-20180524 or 32013R0952R(04)`)
|
|
43
|
+
.describe(`${what}, e.g. 32016R0679.`);
|
|
44
|
+
// The 24-code enum used to be repeated in ~10 tools (~3k tokens of tools/list).
|
|
45
|
+
// A pattern + refine keeps the validation and lists the codes nowhere.
|
|
46
|
+
const LANG_SET = new Set(LANGUAGES);
|
|
47
|
+
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);
|
|
48
|
+
// Webhook targets: https, public host — mirrors the DNS-free part of the API's
|
|
49
|
+
// egress guard (defence in depth; the API is authoritative).
|
|
50
|
+
const webhookUrl = (d) => z.string().trim().superRefine((v, ctx) => {
|
|
51
|
+
const problem = webhookUrlProblem(v);
|
|
52
|
+
if (problem)
|
|
53
|
+
ctx.addIssue({ code: 'custom', message: problem });
|
|
54
|
+
}).describe(d);
|
|
55
|
+
// The export API's own checks (lex-api exportController parseIsoDate /
|
|
56
|
+
// parseIsoTimestamp), mirrored exactly so the schema accepts what the server
|
|
57
|
+
// accepts and nothing else: a calendar-valid YYYY-MM-DD; a date-time needs a
|
|
58
|
+
// zone (Z, ±HH:MM or ±HHMM), seconds are optional, a fraction has 1–9 digits.
|
|
59
|
+
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}))?$/;
|
|
60
|
+
export function isApiDate(value) {
|
|
61
|
+
if (!DATE_RE.test(value))
|
|
62
|
+
return false;
|
|
63
|
+
const d = new Date(`${value}T00:00:00Z`);
|
|
64
|
+
return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === value;
|
|
65
|
+
}
|
|
66
|
+
export function isApiTimestamp(value) {
|
|
67
|
+
const m = ISO_TS_RE.exec(value);
|
|
68
|
+
if (!m || !isApiDate(m[1]))
|
|
69
|
+
return false;
|
|
70
|
+
if (m[2] !== undefined && (Number(m[2]) > 23 || Number(m[3]) > 59 || Number(m[4] ?? 0) > 59))
|
|
71
|
+
return false;
|
|
72
|
+
return !Number.isNaN(new Date(m[2] === undefined ? `${m[1]}T00:00:00Z` : value).getTime());
|
|
73
|
+
}
|
|
74
|
+
const isoDate = (d) => z.string().regex(DATE_RE, 'use YYYY-MM-DD').refine(isApiDate, 'not a calendar date').describe(d);
|
|
75
|
+
/** An ISO 8601 date, or a date-time WITH a timezone (the API rejects one without). */
|
|
76
|
+
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)')
|
|
77
|
+
.refine(isApiTimestamp, 'not a valid date/time')
|
|
78
|
+
.describe(`${d} ISO 8601: a date (YYYY-MM-DD, midnight UTC) or a date-time with a timezone.`);
|
|
79
|
+
// One value or a list; the allowed values are listed once, in the description
|
|
80
|
+
// (an enum inside a string|array union would print them twice).
|
|
81
|
+
const oneOrMany = (values, d) => {
|
|
82
|
+
const set = new Set(values);
|
|
83
|
+
return z.union([z.string(), z.array(z.string()).min(1)])
|
|
84
|
+
.refine((v) => (Array.isArray(v) ? v : [v]).every((x) => set.has(x)), `allowed: ${values.join(', ')}`)
|
|
85
|
+
.describe(`${d} One or a list of: ${values.join(', ')}.`);
|
|
86
|
+
};
|
|
87
|
+
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.');
|
|
88
|
+
const maxChars = (def) => z.number().int().min(2000).max(200_000).default(def)
|
|
89
|
+
.describe(`Text budget in characters (default ${def}).`);
|
|
90
|
+
const offset = z.number().int().min(0).optional()
|
|
91
|
+
.describe('Continue after a truncated response (value given in its note).');
|
|
92
|
+
const include = z.array(z.enum(CONTENT_PARTS)).min(1).optional().describe('Only these parts. "paragraphs" = judgment grounds / text of documents without articles.');
|
|
93
|
+
export function normCelex(v) {
|
|
94
|
+
return v.trim().replace(/^CELEX:/i, '').toUpperCase();
|
|
95
|
+
}
|
|
96
|
+
const READ = { readOnlyHint: true, idempotentHint: true, openWorldHint: true };
|
|
97
|
+
/** Attach the low-credit notice (if any) to a shaped result. */
|
|
98
|
+
function withNotice(res, shaped) {
|
|
99
|
+
const notice = creditNotice(res.body);
|
|
100
|
+
return notice ? { ...shaped, notice } : shaped;
|
|
101
|
+
}
|
|
102
|
+
/** API `include` for a document request — articleId alone means "metadata + that article". */
|
|
103
|
+
function apiInclude(a) {
|
|
104
|
+
if (a.include?.length)
|
|
105
|
+
return a.include;
|
|
106
|
+
if (a.articleId)
|
|
107
|
+
return ['metadata', 'articles'];
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
/** The API answers an unmatched articleId with `articles: []`, not an error — say so. */
|
|
111
|
+
function noteArticleMiss(a, shaped) {
|
|
112
|
+
if (!a.articleId || shaped.content === null)
|
|
113
|
+
return shaped;
|
|
114
|
+
const c = isObj(shaped.content) ? shaped.content : {};
|
|
115
|
+
if (Array.isArray(c.articles) && c.articles.length)
|
|
116
|
+
return shaped;
|
|
117
|
+
return {
|
|
118
|
+
...shaped,
|
|
119
|
+
note: `No article matched articleId "${a.articleId}". Call again without articleId to see the outline (article ids, or paragraphs for documents without articles).`,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Shaping options. An articleId (or include) means "read these parts": the
|
|
124
|
+
* selected parts are returned (paged by maxChars/offset), never re-outlined —
|
|
125
|
+
* otherwise a large article would bounce the model back to the outline it
|
|
126
|
+
* just used.
|
|
127
|
+
*/
|
|
128
|
+
function contentOpts(a, budget) {
|
|
129
|
+
const include = a.include?.length ? a.include : a.articleId ? ['articles'] : undefined;
|
|
130
|
+
return {
|
|
131
|
+
view: a.view,
|
|
132
|
+
maxChars: budget ?? a.maxChars ?? 40_000,
|
|
133
|
+
include,
|
|
134
|
+
offset: a.offset,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
// ── Tools ─────────────────────────────────────────────────────────────
|
|
27
138
|
export const tools = [
|
|
28
|
-
// ──
|
|
139
|
+
// ── Account ─────────────────────────────────────────────────────────
|
|
140
|
+
{
|
|
141
|
+
name: 'lex_info',
|
|
142
|
+
title: 'LexAPI account & capabilities',
|
|
143
|
+
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.",
|
|
144
|
+
inputSchema: {},
|
|
145
|
+
annotations: READ,
|
|
146
|
+
handler: async (_a, client) => {
|
|
147
|
+
const res = await client.info();
|
|
148
|
+
const b = res.body;
|
|
149
|
+
return compact({
|
|
150
|
+
service: b.service,
|
|
151
|
+
apiVersion: b.version,
|
|
152
|
+
subscription: b.subscription,
|
|
153
|
+
credits: isObj(b.credits) ? compact({ ...b.credits, operation_weight: undefined }) : undefined,
|
|
154
|
+
usage: b.credits ? undefined : b.usage,
|
|
155
|
+
searchFilters: b.searchFilters,
|
|
156
|
+
supportedLanguages: Array.isArray(b.supportedLanguages) ? b.supportedLanguages.join(',') : undefined,
|
|
157
|
+
});
|
|
158
|
+
},
|
|
159
|
+
},
|
|
160
|
+
// ── Search ──────────────────────────────────────────────────────────
|
|
29
161
|
{
|
|
30
162
|
name: 'lex_search',
|
|
31
|
-
|
|
163
|
+
title: 'Search EUR-Lex',
|
|
164
|
+
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).',
|
|
165
|
+
inputSchema: {
|
|
166
|
+
query: z.string().max(1000).optional().describe('Search text. Quotes force an exact phrase. "*" = no text constraint (filter-only search).'),
|
|
167
|
+
textScope: z.enum(['title', 'text', 'title-text', 'any']).optional().describe('Where the text must match (API default title-text).'),
|
|
168
|
+
dateFrom: isoDate('Document date from (inclusive).').optional(),
|
|
169
|
+
dateTo: isoDate('Document date to (inclusive).').optional(),
|
|
170
|
+
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).'),
|
|
171
|
+
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.'),
|
|
172
|
+
documentType: oneOrMany(DOCUMENT_TYPES, 'Document type(s). Several types fan out into one EUR-Lex query each.').optional(),
|
|
173
|
+
author: oneOrMany(AUTHORS, 'Issuing institution(s).').optional(),
|
|
174
|
+
procedure: oneOrMany(PROCEDURES, 'Legislative procedure(s).').optional(),
|
|
175
|
+
domain: z.enum(['EU_LAW', 'NATIONAL_LAW', 'ALL']).optional().describe('EUR-Lex collection.'),
|
|
176
|
+
subdomain: oneOrMany(SUBDOMAINS, 'Sub-collection(s), e.g. "case-law", "legislation", "consolidated".').optional(),
|
|
177
|
+
language: lang('Result language (default en).').optional(),
|
|
178
|
+
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".'),
|
|
179
|
+
fresh: z.boolean().optional().describe('Bypass the 60-minute result cache.'),
|
|
180
|
+
},
|
|
181
|
+
annotations: READ,
|
|
182
|
+
handler: async (a, client) => {
|
|
183
|
+
const res = await client.search(compact(a));
|
|
184
|
+
return withNotice(res, shapeSearch(res));
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
{
|
|
188
|
+
name: 'lex_recent_documents',
|
|
189
|
+
title: 'Recently published EU documents',
|
|
190
|
+
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.',
|
|
191
|
+
inputSchema: {
|
|
192
|
+
days: z.number().int().min(1).max(366).default(7).describe('Look-back window in days.'),
|
|
193
|
+
documentType: z.enum(DOCUMENT_TYPES).optional(),
|
|
194
|
+
author: z.enum(AUTHORS).optional(),
|
|
195
|
+
domain: z.enum(['EU_LAW', 'NATIONAL_LAW', 'ALL']).optional(),
|
|
196
|
+
subdomain: z.enum(SUBDOMAINS).optional(),
|
|
197
|
+
language: lang('Keep documents available in this language (default en).').optional(),
|
|
198
|
+
limit: z.number().int().min(1).max(500).default(20).describe('Max results (each 10 cost 3 credits when filtered).'),
|
|
199
|
+
},
|
|
200
|
+
annotations: { ...READ, idempotentHint: false },
|
|
201
|
+
handler: async (a, client) => {
|
|
202
|
+
const res = await client.recentDocuments(a);
|
|
203
|
+
return withNotice(res, shapeRecent(res));
|
|
204
|
+
},
|
|
205
|
+
},
|
|
206
|
+
{
|
|
207
|
+
name: 'lex_resolve',
|
|
208
|
+
title: 'Resolve a legal identifier to CELEX',
|
|
209
|
+
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).',
|
|
32
210
|
inputSchema: {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
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),
|
|
211
|
+
identifier: z.string().trim().min(3).max(2000).describe('CELEX, EUR-Lex URL, ELI URI or ECLI.'),
|
|
212
|
+
},
|
|
213
|
+
annotations: READ,
|
|
214
|
+
handler: async (a, client) => {
|
|
215
|
+
const res = await client.resolve({ identifier: a.identifier });
|
|
216
|
+
return withNotice(res, stripEnvelope(res.body));
|
|
217
|
+
},
|
|
73
218
|
},
|
|
74
|
-
// ──
|
|
219
|
+
// ── Documents ───────────────────────────────────────────────────────
|
|
75
220
|
{
|
|
76
221
|
name: 'lex_get_document',
|
|
77
|
-
|
|
222
|
+
title: 'Fetch an EU document by CELEX',
|
|
223
|
+
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).',
|
|
224
|
+
inputSchema: {
|
|
225
|
+
celexNumber: celex(),
|
|
226
|
+
language: lang('Language of the whole document (default en). Falls back to English, labelled languageFallback, when EUR-Lex lacks it.').optional(),
|
|
227
|
+
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".'),
|
|
228
|
+
articleId: z.string().trim().min(1).max(40).optional().describe('Return only this article: "17", "art_17", "Article 17", "6a".'),
|
|
229
|
+
include,
|
|
230
|
+
view,
|
|
231
|
+
maxChars: maxChars(40_000),
|
|
232
|
+
offset,
|
|
233
|
+
bypassCorpus: z.boolean().optional().describe('Force a fresh upstream read (charged at the live rate). Only when the stored copy is suspected stale.'),
|
|
234
|
+
},
|
|
235
|
+
annotations: READ,
|
|
236
|
+
handler: async (a, client) => {
|
|
237
|
+
const body = compact({
|
|
238
|
+
celexNumber: normCelex(a.celexNumber),
|
|
239
|
+
language: a.language,
|
|
240
|
+
acceptLanguages: a.acceptLanguages,
|
|
241
|
+
articleId: a.articleId,
|
|
242
|
+
include: apiInclude(a),
|
|
243
|
+
bypassCorpus: a.bypassCorpus,
|
|
244
|
+
});
|
|
245
|
+
const res = await client.getDocument(body);
|
|
246
|
+
return withNotice(res, noteArticleMiss(a, shapeDocument(res.body.document, res.headers, contentOpts(a))));
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
{
|
|
250
|
+
name: 'lex_get_documents_batch',
|
|
251
|
+
title: 'Fetch several EU documents',
|
|
252
|
+
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
253
|
inputSchema: {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
254
|
+
celexNumbers: z.array(celex()).min(1).max(50).describe('CELEX numbers.'),
|
|
255
|
+
language: lang().optional(),
|
|
256
|
+
acceptLanguages: z.union([z.array(lang()).min(1), z.literal('any')]).optional(),
|
|
257
|
+
articleId: z.string().trim().min(1).max(40).optional().describe('Return only this article of each document.'),
|
|
258
|
+
include,
|
|
259
|
+
view: z.enum(['auto', 'outline', 'full']).optional().describe('Per document. Default: outline, except when articleId or include is given (then those parts are returned).'),
|
|
260
|
+
maxChars: maxChars(60_000).describe('Character budget shared by all documents.'),
|
|
261
|
+
},
|
|
262
|
+
annotations: READ,
|
|
263
|
+
handler: async (a, client) => {
|
|
264
|
+
const res = await client.getDocumentsBatch(compact({
|
|
265
|
+
celexNumbers: a.celexNumbers.map(normCelex),
|
|
266
|
+
language: a.language,
|
|
267
|
+
acceptLanguages: a.acceptLanguages,
|
|
268
|
+
articleId: a.articleId,
|
|
269
|
+
include: apiInclude(a),
|
|
270
|
+
}));
|
|
271
|
+
const b = res.body;
|
|
272
|
+
const docs = Array.isArray(b.documents) ? b.documents : [];
|
|
273
|
+
// The budget is shared: per-document shares never add up past maxChars.
|
|
274
|
+
const per = Math.max(500, Math.floor((a.maxChars ?? 60_000) / Math.max(1, docs.length)));
|
|
275
|
+
const batchView = a.view ?? (a.articleId || a.include?.length ? 'auto' : 'outline');
|
|
276
|
+
return withNotice(res, compact({
|
|
277
|
+
requested: b.requested,
|
|
278
|
+
processed: b.processed,
|
|
279
|
+
successful: b.successful,
|
|
280
|
+
failed: b.failed,
|
|
281
|
+
textUnavailable: b.textUnavailable,
|
|
282
|
+
trimmedReason: b.trimmed ? b.trimmedReason : undefined,
|
|
283
|
+
documents: docs.map((d) => shapeDocument(d, {}, contentOpts({ ...a, view: batchView, offset: undefined }, per))),
|
|
284
|
+
errors: b.errors,
|
|
285
|
+
}));
|
|
286
|
+
},
|
|
96
287
|
},
|
|
97
288
|
{
|
|
98
289
|
name: 'lex_get_metadata',
|
|
99
|
-
|
|
290
|
+
title: 'EU document metadata',
|
|
291
|
+
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
292
|
inputSchema: {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
additionalProperties: false,
|
|
111
|
-
},
|
|
112
|
-
annotations: { title: 'Fetch EU document metadata', ...READ_ONLY },
|
|
113
|
-
handler: (args, client) => client.getMetadata(args),
|
|
293
|
+
celexNumber: celex(),
|
|
294
|
+
bypassCorpus: z.boolean().optional().describe('Force a fresh upstream read (live rate).'),
|
|
295
|
+
},
|
|
296
|
+
annotations: READ,
|
|
297
|
+
handler: async (a, client) => {
|
|
298
|
+
const res = await client.getMetadata(compact({ celexNumber: normCelex(a.celexNumber), bypassCorpus: a.bypassCorpus }));
|
|
299
|
+
const md = isObj(res.body.metadata) ? res.body.metadata : {};
|
|
300
|
+
return withNotice(res, shapeMetadata(md, res.headers));
|
|
301
|
+
},
|
|
114
302
|
},
|
|
115
303
|
{
|
|
116
304
|
name: 'lex_get_document_by_url',
|
|
117
|
-
|
|
305
|
+
title: 'Fetch an EU document by EUR-Lex URL',
|
|
306
|
+
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
307
|
inputSchema: {
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
308
|
+
url: z.string().trim().url().describe('A eur-lex.europa.eu URL containing CELEX:<id> or uri=CELEX:<id>.'),
|
|
309
|
+
articleId: z.string().trim().min(1).max(40).optional(),
|
|
310
|
+
include,
|
|
311
|
+
view,
|
|
312
|
+
maxChars: maxChars(40_000),
|
|
313
|
+
offset,
|
|
314
|
+
bypassCorpus: z.boolean().optional().describe('Force a fresh upstream read (live rate).'),
|
|
315
|
+
},
|
|
316
|
+
annotations: READ,
|
|
317
|
+
handler: async (a, client) => {
|
|
318
|
+
const res = await client.getDocumentByUrl(compact({
|
|
319
|
+
url: a.url,
|
|
320
|
+
articleId: a.articleId,
|
|
321
|
+
include: apiInclude(a),
|
|
322
|
+
bypassCorpus: a.bypassCorpus,
|
|
323
|
+
}));
|
|
324
|
+
return withNotice(res, noteArticleMiss(a, {
|
|
325
|
+
extractedCelex: res.body.extractedCelex,
|
|
326
|
+
...shapeDocument(res.body.document, res.headers, contentOpts(a)),
|
|
327
|
+
}));
|
|
328
|
+
},
|
|
132
329
|
},
|
|
330
|
+
// ── Version history (observation snapshots) ─────────────────────────
|
|
133
331
|
{
|
|
134
|
-
name: '
|
|
135
|
-
|
|
332
|
+
name: 'lex_document_versions',
|
|
333
|
+
title: 'Version history of a document',
|
|
334
|
+
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.",
|
|
335
|
+
inputSchema: {
|
|
336
|
+
celexNumber: celex(),
|
|
337
|
+
language: lang().optional(),
|
|
338
|
+
},
|
|
339
|
+
annotations: READ,
|
|
340
|
+
handler: async (a, client) => {
|
|
341
|
+
const res = await client.listVersions(normCelex(a.celexNumber), { language: a.language });
|
|
342
|
+
const b = res.body;
|
|
343
|
+
return withNotice(res, compact({
|
|
344
|
+
celex: b.celex,
|
|
345
|
+
language: b.language,
|
|
346
|
+
currentVersion: b.currentVersion,
|
|
347
|
+
trackedSince: b.trackedSince,
|
|
348
|
+
versions: Array.isArray(b.versions)
|
|
349
|
+
? b.versions.map((v) => (isObj(v) ? compact({
|
|
350
|
+
version: v.version,
|
|
351
|
+
isCurrent: v.isCurrent || undefined,
|
|
352
|
+
fetchedAt: v.fetchedAt,
|
|
353
|
+
contentHash: typeof v.contentHash === 'string' ? v.contentHash.slice(0, 12) : undefined,
|
|
354
|
+
title: v.title,
|
|
355
|
+
}) : v))
|
|
356
|
+
: [],
|
|
357
|
+
semantics: 'Observation snapshots (as fetched by LexAPI), not legal in-force reconstructions.',
|
|
358
|
+
}));
|
|
359
|
+
},
|
|
360
|
+
},
|
|
361
|
+
{
|
|
362
|
+
name: 'lex_get_document_version',
|
|
363
|
+
title: 'A document snapshot by version or date',
|
|
364
|
+
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.',
|
|
365
|
+
inputSchema: {
|
|
366
|
+
celexNumber: celex(),
|
|
367
|
+
version: z.number().int().min(1).optional().describe('Snapshot number (from lex_document_versions).'),
|
|
368
|
+
date: isoDate('Return the snapshot current on this date (end of day UTC).').optional(),
|
|
369
|
+
language: lang().optional(),
|
|
370
|
+
include: z.array(z.enum(CONTENT_PARTS)).min(1).optional(),
|
|
371
|
+
view,
|
|
372
|
+
maxChars: maxChars(40_000),
|
|
373
|
+
offset,
|
|
374
|
+
},
|
|
375
|
+
annotations: READ,
|
|
376
|
+
handler: async (a, client) => {
|
|
377
|
+
if ((a.version === undefined) === (a.date === undefined)) {
|
|
378
|
+
throw new Error('Pass exactly one of version or date.');
|
|
379
|
+
}
|
|
380
|
+
const c = normCelex(a.celexNumber);
|
|
381
|
+
const res = a.version !== undefined
|
|
382
|
+
? await client.getVersion(c, a.version, { language: a.language })
|
|
383
|
+
: await client.getAtDate(c, a.date, { language: a.language });
|
|
384
|
+
const b = res.body;
|
|
385
|
+
const d = isObj(b.document) ? b.document : {};
|
|
386
|
+
const { content, note } = shapeContent(d.parsedContent, contentOpts(a));
|
|
387
|
+
return withNotice(res, compact({
|
|
388
|
+
celex: b.celex,
|
|
389
|
+
language: b.language,
|
|
390
|
+
asOf: b.asOf,
|
|
391
|
+
version: d.version,
|
|
392
|
+
isCurrent: d.isCurrent,
|
|
393
|
+
fetchedAt: d.fetchedAt,
|
|
394
|
+
title: d.title,
|
|
395
|
+
documentType: d.documentType,
|
|
396
|
+
content,
|
|
397
|
+
note,
|
|
398
|
+
semantics: 'Observation snapshot (as fetched by LexAPI), not a legal in-force reconstruction.',
|
|
399
|
+
}));
|
|
400
|
+
},
|
|
401
|
+
},
|
|
402
|
+
// ── Semantic search ─────────────────────────────────────────────────
|
|
403
|
+
{
|
|
404
|
+
name: 'lex_semantic_legislation',
|
|
405
|
+
title: 'Semantic search over EU legislation',
|
|
406
|
+
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).',
|
|
407
|
+
inputSchema: {
|
|
408
|
+
query: z.string().trim().min(1).max(1000).describe('Natural-language description of the provision you are looking for.'),
|
|
409
|
+
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(),
|
|
410
|
+
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.'),
|
|
411
|
+
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.'),
|
|
412
|
+
language: z.enum(SEMANTIC_LANGUAGES).optional().describe('Preferred language of the text (default en); acts without it come back in another language, labelled.'),
|
|
413
|
+
include: z.array(z.literal('text')).optional().describe('["text"] returns the full matched article text instead of a ~600-character snippet.'),
|
|
414
|
+
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.'),
|
|
415
|
+
maxChars: maxChars(40_000).describe('Character budget for hit texts when include is ["text"].'),
|
|
416
|
+
},
|
|
417
|
+
annotations: { ...READ, idempotentHint: false },
|
|
418
|
+
handler: async (a, client) => {
|
|
419
|
+
const res = await client.semanticLegislation(compact({
|
|
420
|
+
query: a.query,
|
|
421
|
+
asOf: a.asOf,
|
|
422
|
+
limit: a.limit,
|
|
423
|
+
min_score: a.min_score,
|
|
424
|
+
language: a.language,
|
|
425
|
+
include: a.include,
|
|
426
|
+
filters: a.filters,
|
|
427
|
+
}));
|
|
428
|
+
return withNotice(res, budgetHitTexts(shapeLegislation(res), a.maxChars ?? 40_000));
|
|
429
|
+
},
|
|
430
|
+
},
|
|
431
|
+
{
|
|
432
|
+
name: 'lex_semantic_case_law',
|
|
433
|
+
title: 'Semantic search over EU case law',
|
|
434
|
+
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.',
|
|
136
435
|
inputSchema: {
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
},
|
|
150
|
-
|
|
151
|
-
},
|
|
152
|
-
annotations: {
|
|
153
|
-
handler: (
|
|
436
|
+
query: z.string().trim().min(3).max(1000).describe('Natural-language question or description of the legal issue.'),
|
|
437
|
+
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.'),
|
|
438
|
+
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.'),
|
|
439
|
+
language: z.enum(SEMANTIC_LANGUAGES).optional().describe('Preferred language (default en).'),
|
|
440
|
+
hyde: z.boolean().optional().describe('LLM query rewriting for terse queries (15 credits).'),
|
|
441
|
+
include: z.array(z.literal('text')).optional().describe('["text"] returns each judgment\'s full text (large; bounded by maxChars).'),
|
|
442
|
+
filters: z.object({
|
|
443
|
+
court: z.string().optional().describe('Court name as indexed, e.g. "Court of Justice", "General Court".'),
|
|
444
|
+
date_from: isoDate('Decided on or after (YYYY-MM-DD).').optional(),
|
|
445
|
+
date_to: isoDate('Decided on or before (YYYY-MM-DD).').optional(),
|
|
446
|
+
case_number: z.string().optional().describe('Exact case number, e.g. "C-311/18" (direct lookup).'),
|
|
447
|
+
ecli: z.string().optional().describe('Exact ECLI (direct lookup).'),
|
|
448
|
+
}).catchall(z.unknown()).optional().describe('Optional filters passed to the semantic index.'),
|
|
449
|
+
maxChars: maxChars(40_000).describe('Character budget for hit texts when include is ["text"].'),
|
|
450
|
+
},
|
|
451
|
+
annotations: { ...READ, idempotentHint: false },
|
|
452
|
+
handler: async (a, client) => {
|
|
453
|
+
const res = await client.semanticCaseLaw(compact({
|
|
454
|
+
query: a.query,
|
|
455
|
+
limit: a.limit,
|
|
456
|
+
min_score: a.min_score,
|
|
457
|
+
language: a.language,
|
|
458
|
+
hyde: a.hyde,
|
|
459
|
+
include: a.include,
|
|
460
|
+
filters: a.filters,
|
|
461
|
+
}));
|
|
462
|
+
return withNotice(res, budgetHitTexts(shapeCaseLaw(res), a.maxChars ?? 40_000));
|
|
463
|
+
},
|
|
154
464
|
},
|
|
155
|
-
// ── Citation graph
|
|
465
|
+
// ── Citation graph ──────────────────────────────────────────────────
|
|
156
466
|
{
|
|
157
467
|
name: 'lex_cited_by',
|
|
158
|
-
|
|
468
|
+
title: 'Documents citing a CELEX',
|
|
469
|
+
description: 'Inbound citations: documents that cite, amend, correct, repeal, implement or are based on this act, with the edge type. 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. Cost: 1 credit.',
|
|
159
470
|
inputSchema: {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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);
|
|
471
|
+
celexNumber: celex(),
|
|
472
|
+
citationType: z.enum(CITATION_TYPES).optional().describe('Only this edge type (e.g. "amendment" for the amending acts).'),
|
|
473
|
+
limit: z.number().int().min(1).max(500).default(50).describe('Edges per page.'),
|
|
474
|
+
offset: z.number().int().min(0).default(0).describe('Paging offset, in edges.'),
|
|
475
|
+
},
|
|
476
|
+
annotations: READ,
|
|
477
|
+
handler: async (a, client) => {
|
|
478
|
+
const { celexNumber, ...q } = a;
|
|
479
|
+
const res = await client.citedBy(normCelex(celexNumber), q);
|
|
480
|
+
return withNotice(res, shapeCitedBy(res));
|
|
178
481
|
},
|
|
179
482
|
},
|
|
180
483
|
{
|
|
181
484
|
name: 'lex_cites',
|
|
182
|
-
|
|
485
|
+
title: 'Documents a CELEX cites',
|
|
486
|
+
description: 'Outbound citations: what this document references, amends, repeals, implements or is based on, with the edge type. Only populated for documents whose citations were extracted (lex_extract_citations). Cost: 1 credit.',
|
|
183
487
|
inputSchema: {
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
|
|
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);
|
|
488
|
+
celexNumber: celex(),
|
|
489
|
+
citationType: z.enum(CITATION_TYPES).optional(),
|
|
490
|
+
limit: z.number().int().min(1).max(500).default(50),
|
|
491
|
+
offset: z.number().int().min(0).default(0),
|
|
492
|
+
},
|
|
493
|
+
annotations: READ,
|
|
494
|
+
handler: async (a, client) => {
|
|
495
|
+
const { celexNumber, ...q } = a;
|
|
496
|
+
const res = await client.cites(normCelex(celexNumber), q);
|
|
497
|
+
return withNotice(res, shapeCites(res));
|
|
198
498
|
},
|
|
199
499
|
},
|
|
200
500
|
{
|
|
201
501
|
name: 'lex_citation_network',
|
|
202
|
-
|
|
502
|
+
title: 'Citation neighbourhood of a CELEX',
|
|
503
|
+
description: 'Both directions at once — documents this one cites and documents citing it — deduplicated, with edge types per neighbour; paging.citesTotal / citedByTotal give the full counts. Cost: 20 credits (prefer lex_cited_by / lex_cites at 1 credit when one direction is enough).',
|
|
203
504
|
inputSchema: {
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
505
|
+
celexNumber: celex(),
|
|
506
|
+
citationType: z.enum(CITATION_TYPES).optional(),
|
|
507
|
+
limit: z.number().int().min(1).max(500).default(50).describe('Edges per direction.'),
|
|
508
|
+
offset: z.number().int().min(0).default(0),
|
|
509
|
+
},
|
|
510
|
+
annotations: READ,
|
|
511
|
+
handler: async (a, client) => {
|
|
512
|
+
const { celexNumber, ...q } = a;
|
|
513
|
+
const res = await client.citationNetwork(normCelex(celexNumber), q);
|
|
514
|
+
return withNotice(res, shapeNetwork(res));
|
|
515
|
+
},
|
|
213
516
|
},
|
|
214
|
-
// ── Semantic ──────────────────────────────────────────────────────
|
|
215
517
|
{
|
|
216
|
-
name: '
|
|
217
|
-
|
|
518
|
+
name: 'lex_citation_path',
|
|
519
|
+
title: 'Citation path between two documents',
|
|
520
|
+
description: 'Shortest chain of outbound citations from one document to another (e.g. how a judgment reaches a directive). found: false is a normal answer, not an error. Cost: 20 credits.',
|
|
218
521
|
inputSchema: {
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
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),
|
|
522
|
+
from: celex('Start CELEX'),
|
|
523
|
+
to: celex('Target CELEX'),
|
|
524
|
+
maxDepth: z.number().int().min(1).max(8).default(3).describe('Max hops.'),
|
|
525
|
+
},
|
|
526
|
+
annotations: READ,
|
|
527
|
+
handler: async (a, client) => {
|
|
528
|
+
const res = await client.citationPath(normCelex(a.from), normCelex(a.to), { maxDepth: a.maxDepth });
|
|
529
|
+
const b = stripEnvelope(res.body);
|
|
530
|
+
if (Array.isArray(b.path)) {
|
|
531
|
+
b.path = b.path.map((n) => (isObj(n) ? compact({ celex: n.celexNumber, title: n.title }) : n));
|
|
532
|
+
}
|
|
533
|
+
return withNotice(res, compact(b));
|
|
534
|
+
},
|
|
240
535
|
},
|
|
241
536
|
{
|
|
242
|
-
name: '
|
|
243
|
-
|
|
537
|
+
name: 'lex_related',
|
|
538
|
+
title: 'Documents related by shared citations',
|
|
539
|
+
description: 'Documents that cite the most of the same acts as this one (bibliographic coupling) — "what else deals with this". Needs the seed\'s outbound citations (lex_extract_citations). Cost: 20 credits.',
|
|
540
|
+
inputSchema: {
|
|
541
|
+
celexNumber: celex(),
|
|
542
|
+
limit: z.number().int().min(1).max(50).default(10),
|
|
543
|
+
},
|
|
544
|
+
annotations: READ,
|
|
545
|
+
handler: async (a, client) => {
|
|
546
|
+
const res = await client.related(normCelex(a.celexNumber), { limit: a.limit });
|
|
547
|
+
const b = stripEnvelope(res.body, ['method']);
|
|
548
|
+
if (Array.isArray(b.related)) {
|
|
549
|
+
b.related = b.related.map((r) => (isObj(r) ? compact({
|
|
550
|
+
celex: r.celexNumber,
|
|
551
|
+
title: r.title,
|
|
552
|
+
sharedCount: r.sharedCount,
|
|
553
|
+
sharedTargets: Array.isArray(r.sharedTargets) ? r.sharedTargets.slice(0, 10) : undefined,
|
|
554
|
+
}) : r));
|
|
555
|
+
}
|
|
556
|
+
return withNotice(res, compact(b));
|
|
557
|
+
},
|
|
558
|
+
},
|
|
559
|
+
{
|
|
560
|
+
name: 'lex_citation_stats',
|
|
561
|
+
title: 'Citation graph statistics',
|
|
562
|
+
description: 'Totals for the whole LexAPI citation graph plus the 10 most-cited and 10 most-citing documents. Cost: 20 credits.',
|
|
563
|
+
inputSchema: {},
|
|
564
|
+
annotations: READ,
|
|
565
|
+
handler: async (_a, client) => {
|
|
566
|
+
const res = await client.citationStats();
|
|
567
|
+
return withNotice(res, stripEnvelope(res.body));
|
|
568
|
+
},
|
|
569
|
+
},
|
|
570
|
+
{
|
|
571
|
+
name: 'lex_extract_citations',
|
|
572
|
+
title: 'Extract a document\'s citations',
|
|
573
|
+
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).',
|
|
574
|
+
inputSchema: { celexNumber: celex() },
|
|
575
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
576
|
+
// Writes to the shared citation graph and spends credits: hidden in read-only mode like the other writes.
|
|
577
|
+
write: true,
|
|
578
|
+
handler: async (a, client) => {
|
|
579
|
+
const res = await client.extractCitations({ celexNumber: normCelex(a.celexNumber) });
|
|
580
|
+
const b = stripEnvelope(res.body);
|
|
581
|
+
if (Array.isArray(b.citations)) {
|
|
582
|
+
const all = b.citations;
|
|
583
|
+
b.citations = all.slice(0, 100).map((c) => (isObj(c) ? compact({ celex: c.targetCelex, type: c.citationType }) : c));
|
|
584
|
+
if (all.length > 100)
|
|
585
|
+
b.note = `${all.length - 100} more citations stored; read them with lex_cites.`;
|
|
586
|
+
}
|
|
587
|
+
return withNotice(res, compact(b));
|
|
588
|
+
},
|
|
589
|
+
},
|
|
590
|
+
// ── Export ──────────────────────────────────────────────────────────
|
|
591
|
+
{
|
|
592
|
+
name: 'lex_export',
|
|
593
|
+
title: 'Export corpus rows',
|
|
594
|
+
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).',
|
|
595
|
+
inputSchema: {
|
|
596
|
+
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).'),
|
|
597
|
+
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.'),
|
|
598
|
+
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).'),
|
|
599
|
+
subdomain: z.array(z.enum(['treaties', 'international', 'legislation', 'internal', 'preparatory', 'case-law', 'national-transposition', 'national-case-law', 'questions', 'consolidated'])).min(1).optional(),
|
|
600
|
+
language: lang().optional(),
|
|
601
|
+
dateFrom: isoDate('Document date from (inclusive, YYYY-MM-DD).').optional(),
|
|
602
|
+
dateTo: isoDate('Document date to (inclusive, YYYY-MM-DD).').optional(),
|
|
603
|
+
changedSince: since('Only rows whose text changed at or after this time — the cheapest incremental sync.').optional(),
|
|
604
|
+
fetchedSince: since('Only rows written to at or after this time (any update, including metadata-only). Prefer changedSince for syncing text.').optional(),
|
|
605
|
+
includeContent: z.boolean().default(false).describe('Include each row\'s parsed body (bounded by maxChars).'),
|
|
606
|
+
includeStubs: z.boolean().optional().describe('Also rows whose text EUR-Lex does not publish.'),
|
|
607
|
+
limit: z.number().int().min(1).max(200).default(20).describe('Rows (1 credit each; at least 1 credit per call).'),
|
|
608
|
+
maxChars: maxChars(40_000),
|
|
609
|
+
},
|
|
610
|
+
annotations: READ,
|
|
611
|
+
handler: async (a, client) => {
|
|
612
|
+
const res = await client.exportCorpus({
|
|
613
|
+
documentType: a.documentType,
|
|
614
|
+
documentTypeCode: a.documentTypeCode,
|
|
615
|
+
author: a.author,
|
|
616
|
+
subdomain: a.subdomain,
|
|
617
|
+
language: a.language,
|
|
618
|
+
dateFrom: a.dateFrom,
|
|
619
|
+
dateTo: a.dateTo,
|
|
620
|
+
changedSince: a.changedSince,
|
|
621
|
+
fetchedSince: a.fetchedSince,
|
|
622
|
+
includeContent: a.includeContent ? 'true' : 'false',
|
|
623
|
+
includeStubs: a.includeStubs ? 'true' : undefined,
|
|
624
|
+
limit: a.limit,
|
|
625
|
+
});
|
|
626
|
+
const lines = Array.isArray(res.body.lines) ? res.body.lines : [];
|
|
627
|
+
let meta;
|
|
628
|
+
let done;
|
|
629
|
+
let serverError;
|
|
630
|
+
const rows = [];
|
|
631
|
+
for (const l of lines) {
|
|
632
|
+
if (isObj(l) && '_meta' in l)
|
|
633
|
+
meta = l._meta;
|
|
634
|
+
else if (isObj(l) && '_done' in l)
|
|
635
|
+
done = l._done;
|
|
636
|
+
// A line whose only key is `_error` is a failure signal, never a row.
|
|
637
|
+
else if (isObj(l) && Object.keys(l).length === 1 && '_error' in l)
|
|
638
|
+
serverError = l._error;
|
|
639
|
+
else
|
|
640
|
+
rows.push(l);
|
|
641
|
+
}
|
|
642
|
+
// SDK contract §1.8: complete only with a `_done` trailer that does not
|
|
643
|
+
// say `complete: false`, and no `_error` line. Anything else is a
|
|
644
|
+
// partial export that must not be presented as the result.
|
|
645
|
+
if (done === undefined || (isObj(done) && done.complete === false) || serverError !== undefined) {
|
|
646
|
+
const why = serverError !== undefined
|
|
647
|
+
? `the server reported an error mid-stream (${isObj(serverError) ? `${String(serverError.code ?? 'UNKNOWN')}: ${String(serverError.message ?? '')}` : String(serverError)})`
|
|
648
|
+
: done === undefined
|
|
649
|
+
? 'the stream ended without its completion trailer'
|
|
650
|
+
: 'its completion trailer says complete: false';
|
|
651
|
+
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).`);
|
|
652
|
+
}
|
|
653
|
+
const per = Math.max(500, Math.floor((a.maxChars ?? 40_000) / Math.max(1, rows.length)));
|
|
654
|
+
return compact({
|
|
655
|
+
totalMatching: isObj(meta) ? meta.totalMatching : res.headers['x-export-total'],
|
|
656
|
+
returned: rows.length,
|
|
657
|
+
truncated: isObj(done) ? done.truncated : undefined,
|
|
658
|
+
// limit | max_rows | credits (the pool could not pay for rows added since the
|
|
659
|
+
// count) | recovered (the server's recovery sweep took the export's billing record mid-stream)
|
|
660
|
+
truncatedBy: isObj(done) ? done.truncatedBy : undefined,
|
|
661
|
+
skippedStubs: isObj(done) ? done.skippedStubs : undefined,
|
|
662
|
+
rows: rows.map((r) => {
|
|
663
|
+
if (!isObj(r))
|
|
664
|
+
return r;
|
|
665
|
+
const shaped = shapeMetadata(r);
|
|
666
|
+
if (a.includeContent && r.parsedContent) {
|
|
667
|
+
const { content, note } = shapeContent(r.parsedContent, { view: 'auto', maxChars: per });
|
|
668
|
+
return compact({ ...shaped, content, note });
|
|
669
|
+
}
|
|
670
|
+
return compact({ ...shaped, contentHash: undefined, lastSeenAt: r.lastSeenAt });
|
|
671
|
+
}),
|
|
672
|
+
});
|
|
673
|
+
},
|
|
674
|
+
},
|
|
675
|
+
// ── Webhooks (account state) ────────────────────────────────────────
|
|
676
|
+
{
|
|
677
|
+
name: 'lex_list_webhooks',
|
|
678
|
+
title: 'List webhooks',
|
|
679
|
+
description: 'The account\'s webhooks with status, criteria, watch list and delivery counters. Free.',
|
|
680
|
+
inputSchema: {},
|
|
681
|
+
annotations: READ,
|
|
682
|
+
handler: async (_a, client) => {
|
|
683
|
+
const res = await client.listWebhooks();
|
|
684
|
+
const list = Array.isArray(res.body.webhooks) ? res.body.webhooks : [];
|
|
685
|
+
return { count: list.length, webhooks: list.map((w) => (isObj(w) ? compact(w) : w)) };
|
|
686
|
+
},
|
|
687
|
+
},
|
|
688
|
+
{
|
|
689
|
+
name: 'lex_get_webhook',
|
|
690
|
+
title: 'Webhook details and deliveries',
|
|
691
|
+
description: 'One webhook with its recent delivery attempts (status, HTTP response, attempts). Pass deliveriesOffset/deliveriesLimit to page through older deliveries. Free.',
|
|
692
|
+
inputSchema: {
|
|
693
|
+
id: z.string().trim().min(1).max(64).describe('Webhook id.'),
|
|
694
|
+
deliveriesLimit: z.number().int().min(1).max(100).optional(),
|
|
695
|
+
deliveriesOffset: z.number().int().min(0).optional(),
|
|
696
|
+
},
|
|
697
|
+
annotations: READ,
|
|
698
|
+
handler: async (a, client) => {
|
|
699
|
+
const res = await client.getWebhook(a.id);
|
|
700
|
+
const w = isObj(res.body.webhook) ? { ...res.body.webhook } : {};
|
|
701
|
+
let deliveries = Array.isArray(w.recentDeliveries) ? w.recentDeliveries : [];
|
|
702
|
+
let total;
|
|
703
|
+
if (a.deliveriesLimit !== undefined || a.deliveriesOffset !== undefined) {
|
|
704
|
+
const d = await client.webhookDeliveries(a.id, { limit: a.deliveriesLimit, offset: a.deliveriesOffset });
|
|
705
|
+
deliveries = Array.isArray(d.body.deliveries) ? d.body.deliveries : [];
|
|
706
|
+
total = d.body.total;
|
|
707
|
+
}
|
|
708
|
+
delete w.recentDeliveries;
|
|
709
|
+
return compact({
|
|
710
|
+
webhook: compact(w),
|
|
711
|
+
deliveriesTotal: total,
|
|
712
|
+
deliveries: deliveries.map(shapeDelivery),
|
|
713
|
+
});
|
|
714
|
+
},
|
|
715
|
+
},
|
|
716
|
+
{
|
|
717
|
+
name: 'lex_create_webhook',
|
|
718
|
+
title: 'Create a webhook',
|
|
719
|
+
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.',
|
|
720
|
+
inputSchema: {
|
|
721
|
+
name: z.string().trim().min(1).max(200).describe('Label.'),
|
|
722
|
+
url: webhookUrl('Must be a public https URL (port 443 or 8443, a public domain name or address); it receives the POSTs.'),
|
|
723
|
+
searchCriteria: z.object({
|
|
724
|
+
query: z.string().optional().describe('Words that must all appear in the title (whole words; 4+ characters match word starts; trailing * for prefixes).'),
|
|
725
|
+
documentType: z.union([z.string(), z.array(z.string())]).optional(),
|
|
726
|
+
author: z.union([z.string(), z.array(z.string())]).optional(),
|
|
727
|
+
subdomain: z.union([z.string(), z.array(z.string())]).optional().describe('Replaces the default (EU law, no consolidated texts); "consolidated" = consolidated texts only.'),
|
|
728
|
+
dateFrom: isoDate('Lower bound on the document date.').optional(),
|
|
729
|
+
dateTo: isoDate('Upper bound on the document date.').optional(),
|
|
730
|
+
year: z.union([z.number().int().min(1950).max(2100), z.array(z.number().int().min(1950).max(2100))]).optional(),
|
|
731
|
+
textScope: z.enum(['title', 'title-text', 'any']).optional(),
|
|
732
|
+
domain: z.enum(['EU_LAW', 'ALL']).optional(),
|
|
733
|
+
language: z.string().optional(),
|
|
734
|
+
}).strict().optional().describe('Filters for documents.new, in the lex_search vocabulary.'),
|
|
735
|
+
watchCelex: z.array(celex('Base-act CELEX')).max(5000).optional().describe('Base acts to watch (not consolidated versions or corrigenda).'),
|
|
736
|
+
secret: z.string().min(16).max(256).optional().describe('Own signing secret; generated when omitted.'),
|
|
737
|
+
},
|
|
738
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
739
|
+
write: true,
|
|
740
|
+
handler: async (a, client) => {
|
|
741
|
+
if (!a.searchCriteria && !a.watchCelex?.length)
|
|
742
|
+
throw new Error('Pass searchCriteria, watchCelex, or both.');
|
|
743
|
+
const res = await client.createWebhook(compact({
|
|
744
|
+
name: a.name,
|
|
745
|
+
url: a.url,
|
|
746
|
+
searchCriteria: a.searchCriteria,
|
|
747
|
+
watchCelex: a.watchCelex?.map(normCelex),
|
|
748
|
+
secret: a.secret,
|
|
749
|
+
}));
|
|
750
|
+
return {
|
|
751
|
+
...stripEnvelope(res.body),
|
|
752
|
+
important: 'The webhook secret above is shown only once: the user must store it now to verify X-Webhook-Signature.',
|
|
753
|
+
};
|
|
754
|
+
},
|
|
755
|
+
},
|
|
756
|
+
{
|
|
757
|
+
name: 'lex_update_webhook',
|
|
758
|
+
title: 'Update a webhook',
|
|
759
|
+
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.',
|
|
244
760
|
inputSchema: {
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
761
|
+
id: z.string().trim().min(1).max(64),
|
|
762
|
+
name: z.string().trim().min(1).max(200).optional(),
|
|
763
|
+
url: webhookUrl('Must be a public https URL.').optional().describe('Must be a public https URL.'),
|
|
764
|
+
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.'),
|
|
765
|
+
watchCelex: z.array(celex('Base-act CELEX')).max(5000).optional(),
|
|
766
|
+
status: z.enum(['ACTIVE', 'PAUSED']).optional(),
|
|
767
|
+
},
|
|
768
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
769
|
+
write: true,
|
|
770
|
+
handler: async (a, client) => {
|
|
771
|
+
const { id, ...rest } = a;
|
|
772
|
+
const body = {};
|
|
773
|
+
for (const [k, v] of Object.entries(rest))
|
|
774
|
+
if (v !== undefined)
|
|
775
|
+
body[k] = v;
|
|
776
|
+
if (Array.isArray(body.watchCelex))
|
|
777
|
+
body.watchCelex = body.watchCelex.map(normCelex);
|
|
778
|
+
if (!Object.keys(body).length)
|
|
779
|
+
throw new Error('Nothing to update: pass at least one field.');
|
|
780
|
+
const res = await client.updateWebhook(id, body);
|
|
781
|
+
return stripEnvelope(res.body);
|
|
782
|
+
},
|
|
783
|
+
},
|
|
784
|
+
{
|
|
785
|
+
name: 'lex_delete_webhook',
|
|
786
|
+
title: 'Delete a webhook',
|
|
787
|
+
description: 'Permanently delete a webhook and its delivery history. Cannot be undone — confirm with the user first. Free.',
|
|
788
|
+
inputSchema: { id: z.string().trim().min(1).max(64) },
|
|
789
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
790
|
+
write: true,
|
|
791
|
+
handler: async (a, client) => {
|
|
792
|
+
await client.deleteWebhook(a.id);
|
|
793
|
+
return { deleted: a.id };
|
|
794
|
+
},
|
|
795
|
+
},
|
|
796
|
+
{
|
|
797
|
+
name: 'lex_test_webhook',
|
|
798
|
+
title: 'Send a test delivery',
|
|
799
|
+
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.',
|
|
800
|
+
inputSchema: { id: z.string().trim().min(1).max(64) },
|
|
801
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
802
|
+
write: true,
|
|
803
|
+
handler: async (a, client) => {
|
|
804
|
+
const res = await client.testWebhook(a.id);
|
|
805
|
+
return stripEnvelope(res.body);
|
|
806
|
+
},
|
|
261
807
|
},
|
|
262
808
|
];
|
|
263
|
-
|
|
809
|
+
function shapeDelivery(d) {
|
|
810
|
+
if (!isObj(d))
|
|
811
|
+
return d;
|
|
812
|
+
const p = isObj(d.payload) ? d.payload : {};
|
|
813
|
+
const data = isObj(p.data) ? p.data : {};
|
|
814
|
+
return compact({
|
|
815
|
+
id: d.id,
|
|
816
|
+
status: d.status,
|
|
817
|
+
event: p.event,
|
|
818
|
+
documents: typeof data.count === 'number' ? data.count : undefined,
|
|
819
|
+
responseStatus: d.responseStatus,
|
|
820
|
+
errorMessage: d.errorMessage,
|
|
821
|
+
attemptCount: d.attemptCount,
|
|
822
|
+
nextRetryAt: d.nextRetryAt,
|
|
823
|
+
deliveredAt: d.deliveredAt,
|
|
824
|
+
createdAt: d.createdAt,
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
/** Bound `text` across semantic hits to a total budget (only present with include: ['text']). */
|
|
828
|
+
function budgetHitTexts(shaped, budget) {
|
|
829
|
+
const results = Array.isArray(shaped.results) ? shaped.results : [];
|
|
830
|
+
const withText = results.filter((r) => typeof r.text === 'string');
|
|
831
|
+
if (!withText.length)
|
|
832
|
+
return shaped;
|
|
833
|
+
const per = Math.max(1000, Math.floor(budget / withText.length));
|
|
834
|
+
let cut = 0;
|
|
835
|
+
for (const r of withText) {
|
|
836
|
+
const t = r.text;
|
|
837
|
+
if (t.length > per) {
|
|
838
|
+
r.text = `${t.slice(0, per)} …[truncated: ${t.length - per} more characters]`;
|
|
839
|
+
cut++;
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
return cut
|
|
843
|
+
? { ...shaped, note: `${cut} hit text(s) truncated to ${per} characters (maxChars=${budget}). Read a full document with lex_get_document.` }
|
|
844
|
+
: shaped;
|
|
845
|
+
}
|
|
846
|
+
export function selectTools(opts = {}) {
|
|
847
|
+
return opts.readOnly ? tools.filter((t) => !t.write) : tools;
|
|
848
|
+
}
|