@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/shape.js
ADDED
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
// Response shaping: turn LexAPI responses into compact, model-friendly
|
|
2
|
+
// objects. Principles:
|
|
3
|
+
// - drop what a model can't use (subscription/usage envelopes, legacy
|
|
4
|
+
// duplicate fields, opaque upstream metadata, snapshot-scoped ids);
|
|
5
|
+
// - keep every field that changes how an answer must be read or cited
|
|
6
|
+
// (textAvailability, language fallback, consolidated labels, asOf
|
|
7
|
+
// resolution, partial/truncated flags, hints);
|
|
8
|
+
// - bound document bodies by a character budget, with an explicit note
|
|
9
|
+
// saying what was left out and how to get it.
|
|
10
|
+
export function isObj(v) {
|
|
11
|
+
return !!v && typeof v === 'object' && !Array.isArray(v);
|
|
12
|
+
}
|
|
13
|
+
/** Remove undefined / null / '' / empty-array / empty-object values (one level deep per call site). */
|
|
14
|
+
export function compact(o) {
|
|
15
|
+
const out = {};
|
|
16
|
+
for (const [k, v] of Object.entries(o)) {
|
|
17
|
+
if (v === undefined || v === null || v === '')
|
|
18
|
+
continue;
|
|
19
|
+
if (Array.isArray(v) && v.length === 0)
|
|
20
|
+
continue;
|
|
21
|
+
if (isObj(v) && Object.keys(v).length === 0)
|
|
22
|
+
continue;
|
|
23
|
+
out[k] = v;
|
|
24
|
+
}
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
function str(v) {
|
|
28
|
+
return typeof v === 'string' && v.trim() ? v : undefined;
|
|
29
|
+
}
|
|
30
|
+
function num(v) {
|
|
31
|
+
return typeof v === 'number' && Number.isFinite(v) ? v : undefined;
|
|
32
|
+
}
|
|
33
|
+
function round3(v) {
|
|
34
|
+
const n = num(v);
|
|
35
|
+
return n === undefined ? undefined : Math.round(n * 1000) / 1000;
|
|
36
|
+
}
|
|
37
|
+
function truncate(s, max) {
|
|
38
|
+
if (!s)
|
|
39
|
+
return s;
|
|
40
|
+
return s.length > max ? `${s.slice(0, max - 1)}…` : s;
|
|
41
|
+
}
|
|
42
|
+
// ── Low-credit notice ──────────────────────────────────────────────
|
|
43
|
+
/**
|
|
44
|
+
* The core API router attaches `credits` to v2 responses. Surfacing it on
|
|
45
|
+
* every call would cost tokens for nothing; a notice only when the pool is
|
|
46
|
+
* nearly empty lets the model warn the user before calls start to 402.
|
|
47
|
+
*/
|
|
48
|
+
export function creditNotice(body) {
|
|
49
|
+
if (!isObj(body) || !isObj(body.credits))
|
|
50
|
+
return undefined;
|
|
51
|
+
const c = body.credits;
|
|
52
|
+
const remaining = num(c.remaining);
|
|
53
|
+
const limit = num(c.limit);
|
|
54
|
+
if (remaining === undefined || limit === undefined || limit <= 0)
|
|
55
|
+
return undefined;
|
|
56
|
+
if (remaining > 100 && remaining / limit > 0.1)
|
|
57
|
+
return undefined;
|
|
58
|
+
const reset = str(c.resetsAt);
|
|
59
|
+
return `LexAPI credit pool is low: ${remaining} of ${limit} credits left${reset ? ` (resets ${reset})` : ''}.`;
|
|
60
|
+
}
|
|
61
|
+
// ── Consolidated texts ─────────────────────────────────────────────
|
|
62
|
+
const CONSOLIDATED_RE = /^0([0-9]{4}[A-Z]{1,2}[0-9]{4}(?:\([0-9]{2}\))?)-([0-9]{4})([0-9]{2})([0-9]{2})$/;
|
|
63
|
+
/** `02016R0679-20160504` → { base: '32016R0679', date: '2016-05-04' }; null otherwise. */
|
|
64
|
+
export function consolidatedBaseOf(celex) {
|
|
65
|
+
if (typeof celex !== 'string')
|
|
66
|
+
return null;
|
|
67
|
+
const m = CONSOLIDATED_RE.exec(celex.toUpperCase().trim());
|
|
68
|
+
return m ? { base: `3${m[1]}`, date: `${m[2]}-${m[3]}-${m[4]}` } : null;
|
|
69
|
+
}
|
|
70
|
+
export function consolidatedLabel(celex) {
|
|
71
|
+
const c = consolidatedBaseOf(celex);
|
|
72
|
+
if (!c)
|
|
73
|
+
return undefined;
|
|
74
|
+
return {
|
|
75
|
+
consolidated: true,
|
|
76
|
+
consolidatedAsOf: c.date,
|
|
77
|
+
baseCelex: c.base,
|
|
78
|
+
consolidatedNote: `Consolidated text (the act with its amendments integrated, as of ${c.date}) — a documentation tool, not the authentic text. Cite the act as published in the Official Journal (${c.base}) and its amending acts.`,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
// ── Document metadata ──────────────────────────────────────────────
|
|
82
|
+
const META_KEYS = [
|
|
83
|
+
'title', 'titleLanguage', 'documentType', 'documentTypeCode', 'author',
|
|
84
|
+
'dateOfDocumentISO', 'dateOfEffectISO', 'dateOfPublicationISO', 'dateType',
|
|
85
|
+
'ecli', 'eli', 'caseNumber', 'parties', 'subject',
|
|
86
|
+
'language', 'languageRequested', 'languageFallback', 'version', 'fetchedAt',
|
|
87
|
+
'latestConsolidated', 'upcomingConsolidated', 'newestConsolidated',
|
|
88
|
+
];
|
|
89
|
+
export function shapeMetadata(doc, headers = {}) {
|
|
90
|
+
const out = { celex: str(doc.celex) ?? str(doc.celexNumber) };
|
|
91
|
+
for (const k of META_KEYS)
|
|
92
|
+
out[k] = doc[k];
|
|
93
|
+
// Legacy DD/MM/YYYY strings only when no ISO twin exists.
|
|
94
|
+
if (!doc.dateOfDocumentISO && doc.dateOfDocument)
|
|
95
|
+
out.dateOfDocument = doc.dateOfDocument;
|
|
96
|
+
if (Array.isArray(doc.keywords))
|
|
97
|
+
out.keywords = doc.keywords.slice(0, 20);
|
|
98
|
+
const urls = isObj(doc.urls) ? doc.urls : undefined;
|
|
99
|
+
if (urls)
|
|
100
|
+
out.url = urls.html ?? urls.metadata;
|
|
101
|
+
if (headers['x-source'])
|
|
102
|
+
out.source = headers['x-source'];
|
|
103
|
+
// A text-availability block that just says "available" is noise; any
|
|
104
|
+
// other state (no text, why, which languages, consolidated pointers) is
|
|
105
|
+
// essential and passed through verbatim — null vs [] languages differ.
|
|
106
|
+
const ta = doc.textAvailability;
|
|
107
|
+
if (isObj(ta) && !(ta.available === true && Object.keys(ta).length === 1))
|
|
108
|
+
out.textAvailability = ta;
|
|
109
|
+
Object.assign(out, consolidatedLabel(out.celex) ?? {});
|
|
110
|
+
return compact(out);
|
|
111
|
+
}
|
|
112
|
+
const PART_ORDER = ['articles', 'recitals', 'paragraphs', 'annexes', 'tables', 'sections', 'fullText'];
|
|
113
|
+
/** Split a long string into pieces of at most `max` chars, preferring line / word boundaries. */
|
|
114
|
+
function splitText(t, max) {
|
|
115
|
+
if (t.length <= max)
|
|
116
|
+
return [t];
|
|
117
|
+
const out = [];
|
|
118
|
+
let rest = t;
|
|
119
|
+
while (rest.length > max) {
|
|
120
|
+
let cut = rest.lastIndexOf('\n', max);
|
|
121
|
+
if (cut < max * 0.5)
|
|
122
|
+
cut = rest.lastIndexOf(' ', max);
|
|
123
|
+
if (cut < max * 0.5)
|
|
124
|
+
cut = max;
|
|
125
|
+
out.push(rest.slice(0, cut));
|
|
126
|
+
rest = rest.slice(cut).replace(/^\s+/, '');
|
|
127
|
+
}
|
|
128
|
+
if (rest)
|
|
129
|
+
out.push(rest);
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Body items in reading order. Any item whose text is longer than `chunk`
|
|
134
|
+
* is split into consecutive pieces (labelled "part j/k"), so `offset` can
|
|
135
|
+
* page through a giant annex or a fullText without blank lines.
|
|
136
|
+
*/
|
|
137
|
+
function itemsOf(content, parts, chunk) {
|
|
138
|
+
const items = [];
|
|
139
|
+
for (const part of parts) {
|
|
140
|
+
const v = content[part];
|
|
141
|
+
if (part === 'fullText') {
|
|
142
|
+
if (typeof v === 'string' && v.trim()) {
|
|
143
|
+
v.split(/\n{2,}/).map((b) => b.trim()).filter(Boolean).forEach((block, i) => {
|
|
144
|
+
const pieces = splitText(block, chunk);
|
|
145
|
+
pieces.forEach((piece, j) => items.push({
|
|
146
|
+
part,
|
|
147
|
+
value: piece,
|
|
148
|
+
label: `fullText block ${i + 1}${pieces.length > 1 ? ` part ${j + 1}/${pieces.length}` : ''}`,
|
|
149
|
+
}));
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (!Array.isArray(v))
|
|
155
|
+
continue;
|
|
156
|
+
v.forEach((entry, i) => {
|
|
157
|
+
const e = isObj(entry) ? entry : {};
|
|
158
|
+
const label = part === 'articles' ? String(e.id ?? e.number ?? `article #${i + 1}`)
|
|
159
|
+
: part === 'recitals' || part === 'paragraphs' ? `${part.slice(0, -1)} ${e.number ?? i + 1}`
|
|
160
|
+
: part === 'annexes' ? `annex: ${truncate(str(e.title), 60) ?? `#${i + 1}`}`
|
|
161
|
+
: `${part.slice(0, -1)} #${i + 1}`;
|
|
162
|
+
const key = typeof e.content === 'string' ? 'content' : typeof e.text === 'string' ? 'text' : undefined;
|
|
163
|
+
const text = key ? e[key] : undefined;
|
|
164
|
+
if (key && text && text.length > chunk) {
|
|
165
|
+
const pieces = splitText(text, chunk);
|
|
166
|
+
pieces.forEach((piece, j) => items.push({
|
|
167
|
+
part,
|
|
168
|
+
value: { ...e, [key]: piece, part: `${j + 1}/${pieces.length}` },
|
|
169
|
+
label: `${label} part ${j + 1}/${pieces.length}`,
|
|
170
|
+
}));
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
items.push({ part, value: entry, label });
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
return items;
|
|
178
|
+
}
|
|
179
|
+
function size(v) {
|
|
180
|
+
return typeof v === 'string' ? v.length : JSON.stringify(v).length;
|
|
181
|
+
}
|
|
182
|
+
/** Last resort: cut the text of one item that still exceeds the budget. */
|
|
183
|
+
function clipItem(item, budget) {
|
|
184
|
+
const marker = (n) => ` …[truncated: ${n} more characters]`;
|
|
185
|
+
if (typeof item.value === 'string') {
|
|
186
|
+
return item.value.slice(0, budget) + marker(item.value.length - budget);
|
|
187
|
+
}
|
|
188
|
+
if (isObj(item.value)) {
|
|
189
|
+
const v = { ...item.value };
|
|
190
|
+
for (const k of ['content', 'text']) {
|
|
191
|
+
if (typeof v[k] === 'string') {
|
|
192
|
+
const t = v[k];
|
|
193
|
+
const keep = Math.max(200, budget - (size(v) - t.length));
|
|
194
|
+
if (t.length > keep)
|
|
195
|
+
v[k] = t.slice(0, keep) + marker(t.length - keep);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return v;
|
|
199
|
+
}
|
|
200
|
+
return item.value;
|
|
201
|
+
}
|
|
202
|
+
/** How to read on from an outline — only suggesting parts this document has. */
|
|
203
|
+
function readingHint(content) {
|
|
204
|
+
const has = (k) => Array.isArray(content[k]) && content[k].length > 0;
|
|
205
|
+
const ways = [];
|
|
206
|
+
if (has('articles'))
|
|
207
|
+
ways.push(`one article with articleId (e.g. "${firstArticleId(content)}")`);
|
|
208
|
+
if (has('paragraphs'))
|
|
209
|
+
ways.push('the paragraphs (judgment grounds / body text) with include ["paragraphs"]');
|
|
210
|
+
if (has('recitals'))
|
|
211
|
+
ways.push('the recitals with include ["recitals"]');
|
|
212
|
+
if (has('annexes'))
|
|
213
|
+
ways.push('the annexes with include ["annexes"]');
|
|
214
|
+
if (has('tables'))
|
|
215
|
+
ways.push('the tables with include ["tables"]');
|
|
216
|
+
if (!ways.length && typeof content.fullText === 'string' && content.fullText)
|
|
217
|
+
ways.push('the text with include ["fullText"] (or view "full")');
|
|
218
|
+
return ways.length ? `Read on: ${ways.join('; ')}. Long parts continue with offset.` : 'The document has no body text.';
|
|
219
|
+
}
|
|
220
|
+
function outlineOf(content, maxChars, offset) {
|
|
221
|
+
const articles = Array.isArray(content.articles) ? content.articles : [];
|
|
222
|
+
const annexes = Array.isArray(content.annexes) ? content.annexes : [];
|
|
223
|
+
const sections = Array.isArray(content.sections) ? content.sections : [];
|
|
224
|
+
const count = (k) => (Array.isArray(content[k]) ? content[k].length : 0);
|
|
225
|
+
const base = compact({
|
|
226
|
+
sections: sections.map((sec) => (isObj(sec)
|
|
227
|
+
? compact({ type: sec.type, number: sec.number, title: sec.title, articles: Array.isArray(sec.articleRange) ? sec.articleRange.join('–') : undefined })
|
|
228
|
+
: sec)),
|
|
229
|
+
recitalCount: count('recitals') || undefined,
|
|
230
|
+
paragraphCount: count('paragraphs') || undefined,
|
|
231
|
+
annexes: annexes.map((a, i) => (isObj(a) ? truncate(str(a.title), 120) ?? `Annex #${i + 1}` : a)),
|
|
232
|
+
tableCount: count('tables') || undefined,
|
|
233
|
+
fullTextChars: typeof content.fullText === 'string' ? content.fullText.length : undefined,
|
|
234
|
+
});
|
|
235
|
+
// The article list is the part that grows (CRR-size acts: ~500 entries) —
|
|
236
|
+
// bound it by maxChars and page it with offset.
|
|
237
|
+
let budget = maxChars - size(base);
|
|
238
|
+
const listed = [];
|
|
239
|
+
const from = Math.min(offset, articles.length);
|
|
240
|
+
let i = from;
|
|
241
|
+
for (; i < articles.length; i++) {
|
|
242
|
+
const a = articles[i];
|
|
243
|
+
const entry = isObj(a) ? compact({ id: a.id, number: a.number, title: truncate(str(a.title), 160) }) : a;
|
|
244
|
+
const s = size(entry) + 1;
|
|
245
|
+
if (s > budget && listed.length)
|
|
246
|
+
break;
|
|
247
|
+
budget -= s;
|
|
248
|
+
listed.push(entry);
|
|
249
|
+
}
|
|
250
|
+
const outline = compact({ ...base, articles: listed, articleCount: articles.length > listed.length ? articles.length : undefined });
|
|
251
|
+
const note = articles.length && (from > 0 || i < articles.length)
|
|
252
|
+
? `Article list ${from + 1}–${i} of ${articles.length}${i < articles.length ? `; call again with view "outline" and offset=${i} for the rest` : ''}.`
|
|
253
|
+
: undefined;
|
|
254
|
+
return { outline, note };
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Shape `content` (a document's parsed body) under a character budget.
|
|
258
|
+
* Returns the shaped content plus a note when anything was outlined, split,
|
|
259
|
+
* truncated or omitted.
|
|
260
|
+
*/
|
|
261
|
+
export function shapeContent(content, opts) {
|
|
262
|
+
if (!isObj(content))
|
|
263
|
+
return {};
|
|
264
|
+
if (opts.include && !opts.include.some((p) => PART_ORDER.includes(p)))
|
|
265
|
+
return {};
|
|
266
|
+
const explicit = opts.include?.filter((p) => PART_ORDER.includes(p));
|
|
267
|
+
// Without an explicit include, fullText duplicates the structured parts —
|
|
268
|
+
// use it only when the document has no structured body at all.
|
|
269
|
+
const structured = PART_ORDER.filter((p) => p !== 'fullText' && Array.isArray(content[p]) && content[p].length);
|
|
270
|
+
const parts = explicit && explicit.length
|
|
271
|
+
? PART_ORDER.filter((p) => explicit.includes(p))
|
|
272
|
+
: structured.length ? structured.filter((p) => p !== 'sections') : ['fullText'];
|
|
273
|
+
const chunk = Math.max(1000, Math.floor(opts.maxChars * 0.9));
|
|
274
|
+
const all = itemsOf(content, parts, chunk);
|
|
275
|
+
const totalSize = all.reduce((n, i) => n + size(i.value), 0);
|
|
276
|
+
const offset = Math.max(0, opts.offset ?? 0);
|
|
277
|
+
// Explicitly selected parts are read, never outlined — unless the caller
|
|
278
|
+
// asked for the outline itself.
|
|
279
|
+
let view = opts.view ?? 'auto';
|
|
280
|
+
if (view === 'auto')
|
|
281
|
+
view = explicit?.length || offset || totalSize <= opts.maxChars ? 'full' : 'outline';
|
|
282
|
+
if (view === 'outline') {
|
|
283
|
+
const { outline, note } = outlineOf(content, opts.maxChars, offset);
|
|
284
|
+
return {
|
|
285
|
+
content: outline,
|
|
286
|
+
note: [`Outline only: the body is ${totalSize} characters (budget maxChars=${opts.maxChars}).`, note, readingHint(content)].filter(Boolean).join(' '),
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
const out = {};
|
|
290
|
+
let used = 0;
|
|
291
|
+
let emitted = 0;
|
|
292
|
+
let clipped = false;
|
|
293
|
+
const rest = all.slice(offset);
|
|
294
|
+
let stoppedAt;
|
|
295
|
+
for (let i = 0; i < rest.length; i++) {
|
|
296
|
+
const item = rest[i];
|
|
297
|
+
const s = size(item.value);
|
|
298
|
+
let value = item.value;
|
|
299
|
+
if (used + s > opts.maxChars) {
|
|
300
|
+
if (emitted > 0) {
|
|
301
|
+
stoppedAt = i;
|
|
302
|
+
break;
|
|
303
|
+
}
|
|
304
|
+
value = clipItem(item, opts.maxChars);
|
|
305
|
+
clipped = true;
|
|
306
|
+
}
|
|
307
|
+
if (item.part === 'fullText') {
|
|
308
|
+
out.fullText = out.fullText ? `${out.fullText}\n\n${value}` : value;
|
|
309
|
+
}
|
|
310
|
+
else {
|
|
311
|
+
const list = out[item.part] ?? [];
|
|
312
|
+
list.push(value);
|
|
313
|
+
out[item.part] = list;
|
|
314
|
+
}
|
|
315
|
+
used += Math.min(s, opts.maxChars);
|
|
316
|
+
emitted++;
|
|
317
|
+
}
|
|
318
|
+
const notes = [];
|
|
319
|
+
if (offset)
|
|
320
|
+
notes.push(`Skipped the first ${offset} items (offset).`);
|
|
321
|
+
if (offset >= all.length && all.length)
|
|
322
|
+
notes.push(`offset ${offset} is past the end (${all.length} items).`);
|
|
323
|
+
if (all.some((i) => / part \d+\/\d+$/.test(i.label)))
|
|
324
|
+
notes.push('Long items are split into consecutive parts ("part j/k").');
|
|
325
|
+
if (stoppedAt !== undefined) {
|
|
326
|
+
const omitted = rest.slice(stoppedAt);
|
|
327
|
+
notes.push(`Truncated at maxChars=${opts.maxChars}: ${omitted.length} more items omitted (${omitted[0].label} … ${omitted[omitted.length - 1].label}). Call again with the same arguments and offset=${offset + stoppedAt}.`);
|
|
328
|
+
}
|
|
329
|
+
if (clipped)
|
|
330
|
+
notes.push('One item was longer than maxChars and was cut; raise maxChars (max 200000) to read it whole.');
|
|
331
|
+
return { content: out, note: notes.length ? notes.join(' ') : undefined };
|
|
332
|
+
}
|
|
333
|
+
function firstArticleId(content) {
|
|
334
|
+
const a = Array.isArray(content.articles) ? content.articles[0] : undefined;
|
|
335
|
+
return isObj(a) ? (str(a.id) ?? str(a.number)) : undefined;
|
|
336
|
+
}
|
|
337
|
+
/** A full document object (from /documentContent, batch, by-URL) → compact form. */
|
|
338
|
+
export function shapeDocument(doc, headers, opts) {
|
|
339
|
+
if (!isObj(doc))
|
|
340
|
+
return {};
|
|
341
|
+
const out = shapeMetadata(doc, headers);
|
|
342
|
+
if (doc.content === null) {
|
|
343
|
+
out.content = null; // no text published — textAvailability says why
|
|
344
|
+
return out;
|
|
345
|
+
}
|
|
346
|
+
const { content, note } = shapeContent(doc.content, opts);
|
|
347
|
+
if (content)
|
|
348
|
+
out.content = content;
|
|
349
|
+
if (note)
|
|
350
|
+
out.note = note;
|
|
351
|
+
return out;
|
|
352
|
+
}
|
|
353
|
+
// ── Search results ─────────────────────────────────────────────────
|
|
354
|
+
const ALL_LANGS = 24;
|
|
355
|
+
export function shapeSearchResult(r) {
|
|
356
|
+
if (!isObj(r))
|
|
357
|
+
return {};
|
|
358
|
+
const langs = Array.isArray(r.availableLanguages) ? r.availableLanguages : [];
|
|
359
|
+
return compact({
|
|
360
|
+
celex: str(r.celex) ?? str(r.celexNumber),
|
|
361
|
+
title: r.title,
|
|
362
|
+
type: r.documentTypeCode ?? r.documentType ?? r.form,
|
|
363
|
+
date: r.dateOfDocumentISO ?? r.date,
|
|
364
|
+
author: r.author,
|
|
365
|
+
// 24 codes per hit is a lot of tokens for "all of them".
|
|
366
|
+
languages: langs.length && langs.length < ALL_LANGS ? langs.join(',') : undefined,
|
|
367
|
+
url: r.url,
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
export function shapeSearch(res) {
|
|
371
|
+
const b = res.body;
|
|
372
|
+
const results = Array.isArray(b.results) ? b.results.map(shapeSearchResult) : [];
|
|
373
|
+
return compact({
|
|
374
|
+
totalResults: b.totalResults,
|
|
375
|
+
totalPages: b.totalPages,
|
|
376
|
+
pagesFetched: b.pagesFetched,
|
|
377
|
+
resultCount: results.length,
|
|
378
|
+
results,
|
|
379
|
+
hint: b.hint,
|
|
380
|
+
truncated: b.truncated,
|
|
381
|
+
truncatedReason: b.truncatedReason,
|
|
382
|
+
partial: b.partial,
|
|
383
|
+
partialReason: b.partialReason,
|
|
384
|
+
postFilteredBy: b.postFilteredBy,
|
|
385
|
+
ignoredDocumentTypes: b.ignoredDocumentTypes,
|
|
386
|
+
source: b.source ?? res.headers['x-search-source'],
|
|
387
|
+
cache: res.headers['x-search-cache'] === 'hit' ? 'hit' : undefined,
|
|
388
|
+
warning: res.headers['x-warning'],
|
|
389
|
+
fetchedAt: b.fetchedAt,
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
export function shapeRecent(res) {
|
|
393
|
+
const b = res.body;
|
|
394
|
+
const results = Array.isArray(b.results) ? b.results.map(shapeSearchResult) : [];
|
|
395
|
+
const p = isObj(b.parameters) ? b.parameters : {};
|
|
396
|
+
return compact({
|
|
397
|
+
window: p.dateFrom && p.dateTo ? `${p.dateFrom}..${p.dateTo}` : undefined,
|
|
398
|
+
totalResults: b.totalResults,
|
|
399
|
+
resultCount: results.length,
|
|
400
|
+
results,
|
|
401
|
+
languageFilter: b.languageFilter,
|
|
402
|
+
hint: b.hint,
|
|
403
|
+
partial: b.partial,
|
|
404
|
+
partialReason: b.partialReason,
|
|
405
|
+
source: res.headers['x-source'],
|
|
406
|
+
warning: res.headers['x-warning'],
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
// ── Semantic search ────────────────────────────────────────────────
|
|
410
|
+
const CASE_ANALYTICS = [
|
|
411
|
+
'outcome', 'outcome_detail', 'party_role', 'claimed_amount', 'awarded_amount', 'currency',
|
|
412
|
+
'award_percentage', 'legal_area', 'legislation_cited', 'duration_days', 'was_appealed', 'appeal_outcome',
|
|
413
|
+
];
|
|
414
|
+
export function shapeCaseLawHit(r) {
|
|
415
|
+
if (!isObj(r))
|
|
416
|
+
return {};
|
|
417
|
+
const md = isObj(r.metadata) ? r.metadata : {};
|
|
418
|
+
const out = {
|
|
419
|
+
celex: md.celex_id,
|
|
420
|
+
documentType: md.document_type,
|
|
421
|
+
score: round3(r.score),
|
|
422
|
+
case_name: r.case_name,
|
|
423
|
+
case_number: r.case_number,
|
|
424
|
+
ecli: r.ecli,
|
|
425
|
+
court: r.court,
|
|
426
|
+
decision_date: r.decision_date,
|
|
427
|
+
parties: r.parties,
|
|
428
|
+
language: r.language && r.language !== 'en' ? r.language : undefined,
|
|
429
|
+
paragraph: md.paragraph_number,
|
|
430
|
+
// `snippet` is the head of `summary` when one exists — send one, not both.
|
|
431
|
+
summary: r.summary,
|
|
432
|
+
snippet: r.summary ? undefined : r.snippet,
|
|
433
|
+
text: r.text,
|
|
434
|
+
};
|
|
435
|
+
for (const k of CASE_ANALYTICS)
|
|
436
|
+
out[k] = r[k];
|
|
437
|
+
return compact(out);
|
|
438
|
+
}
|
|
439
|
+
export function shapeCaseLaw(res) {
|
|
440
|
+
const b = res.body;
|
|
441
|
+
const results = Array.isArray(b.results) ? b.results.map(shapeCaseLawHit) : [];
|
|
442
|
+
return compact({
|
|
443
|
+
resultCount: results.length,
|
|
444
|
+
results,
|
|
445
|
+
hint: b.hint,
|
|
446
|
+
hyde: b.hyde,
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
export function shapeLegislationHit(r) {
|
|
450
|
+
if (!isObj(r))
|
|
451
|
+
return {};
|
|
452
|
+
return compact({
|
|
453
|
+
law_id: r.law_id,
|
|
454
|
+
law_title: r.law_title,
|
|
455
|
+
article_ref: r.article_ref,
|
|
456
|
+
section: r.section,
|
|
457
|
+
chapter: r.chapter,
|
|
458
|
+
score: round3(r.score),
|
|
459
|
+
language: r.language,
|
|
460
|
+
snippet: r.snippet,
|
|
461
|
+
text: r.text,
|
|
462
|
+
// Consolidated-text labelling (#284 §6) — kept verbatim.
|
|
463
|
+
consolidated: r.consolidated,
|
|
464
|
+
consolidatedAsOf: r.consolidatedAsOf,
|
|
465
|
+
baseCelex: r.baseCelex,
|
|
466
|
+
consolidatedNote: r.consolidatedNote,
|
|
467
|
+
baseAct: isObj(r.baseAct) ? compact({ ...r.baseAct, score: round3(r.baseAct.score) }) : undefined,
|
|
468
|
+
// asOf resolution (#284 §7).
|
|
469
|
+
asOf: r.asOf,
|
|
470
|
+
asOfResolved: r.asOfResolved,
|
|
471
|
+
asOfReason: r.asOfReason,
|
|
472
|
+
asOfVersion: r.asOfVersion,
|
|
473
|
+
matchedVersion: r.matchedVersion,
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
export function shapeLegislation(res) {
|
|
477
|
+
const b = res.body;
|
|
478
|
+
const results = Array.isArray(b.results) ? b.results.map(shapeLegislationHit) : [];
|
|
479
|
+
const anyConsolidated = results.some((r) => r.consolidated === true
|
|
480
|
+
|| (isObj(r.asOfVersion) && r.asOfVersion.kind === 'consolidated'));
|
|
481
|
+
return compact({
|
|
482
|
+
asOf: b.asOf,
|
|
483
|
+
asOfSummary: b.asOfSummary,
|
|
484
|
+
resultCount: results.length,
|
|
485
|
+
results,
|
|
486
|
+
hint: b.hint,
|
|
487
|
+
citing: anyConsolidated
|
|
488
|
+
? 'Some hits are consolidated texts (consolidated: true, or asOfVersion.kind "consolidated"): they are documentation tools without legal force. Quote them for reading, but cite the authentic act (baseCelex / baseAct.law_id) as published in the Official Journal, plus the amending acts where relevant.'
|
|
489
|
+
: undefined,
|
|
490
|
+
asOfCaveat: b.asOf ? asOfCaveat(results, String(b.asOf)) : undefined,
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
// asOfReason classes (docs.md "asOf — the text in force on a date").
|
|
494
|
+
const AS_OF_NOT_IN_FORCE = new Set(['not_yet_adopted', 'not_yet_in_force', 'no_longer_in_force']);
|
|
495
|
+
const AS_OF_RETRYABLE = new Set([
|
|
496
|
+
'fetch_pending', 'fetch_capacity', 'fetch_budget_exhausted', 'request_deadline', 'fetch_timeout',
|
|
497
|
+
'fetch_failed', 'version_lookup_cap', 'version_list_unavailable', 'credit_check_failed',
|
|
498
|
+
]);
|
|
499
|
+
const AS_OF_USER_ACTION = new Set(['insufficient_credits']);
|
|
500
|
+
/**
|
|
501
|
+
* One instruction per class of unresolved hit present. Every unresolved
|
|
502
|
+
* hit carries the LATEST text; what the model should do differs:
|
|
503
|
+
* - not in force on the date → that IS the answer (say so);
|
|
504
|
+
* - transient → retry shortly, or with a smaller limit;
|
|
505
|
+
* - credits → tell the user;
|
|
506
|
+
* - anything else (no text in that version, language, article missing…) →
|
|
507
|
+
* the version in force could not be read; don't quote it as of that date.
|
|
508
|
+
*/
|
|
509
|
+
export function asOfCaveat(results, asOf) {
|
|
510
|
+
const groups = { notInForce: [], retryable: [], needsCredits: [], unavailable: [] };
|
|
511
|
+
for (const r of results) {
|
|
512
|
+
if (r.asOfResolved !== false)
|
|
513
|
+
continue;
|
|
514
|
+
const reason = String(r.asOfReason ?? 'unknown');
|
|
515
|
+
const id = `${String(r.law_id ?? '?')}${r.article_ref ? ` ${String(r.article_ref)}` : ''} (${reason})`;
|
|
516
|
+
if (AS_OF_NOT_IN_FORCE.has(reason))
|
|
517
|
+
groups.notInForce.push(id);
|
|
518
|
+
else if (AS_OF_RETRYABLE.has(reason))
|
|
519
|
+
groups.retryable.push(id);
|
|
520
|
+
else if (AS_OF_USER_ACTION.has(reason))
|
|
521
|
+
groups.needsCredits.push(id);
|
|
522
|
+
else
|
|
523
|
+
groups.unavailable.push(id);
|
|
524
|
+
}
|
|
525
|
+
const guidance = [];
|
|
526
|
+
if (groups.notInForce.length)
|
|
527
|
+
guidance.push(`notInForce: these acts were not in force on ${asOf} (not yet adopted / not yet in force / no longer in force) — that is the answer for them; say so, and do not quote their text as the law on that date.`);
|
|
528
|
+
if (groups.retryable.length)
|
|
529
|
+
guidance.push('retryable: the version in force could not be fetched in this call (busy, time or fetch limits) — call again shortly, or with a smaller limit.');
|
|
530
|
+
if (groups.needsCredits.length)
|
|
531
|
+
guidance.push('needsCredits: the credit pool could not cover fetching the version in force — tell the user.');
|
|
532
|
+
if (groups.unavailable.length)
|
|
533
|
+
guidance.push(`unavailable: the version in force on ${asOf} could not be read (see asOfReason) — do not present the returned text as the law on that date.`);
|
|
534
|
+
if (!guidance.length)
|
|
535
|
+
return undefined;
|
|
536
|
+
return compact({
|
|
537
|
+
note: `Unresolved hits carry the LATEST text, not the text in force on ${asOf}.`,
|
|
538
|
+
...Object.fromEntries(Object.entries(groups).filter(([, v]) => v.length)),
|
|
539
|
+
guidance,
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
// ── Citations ──────────────────────────────────────────────────────
|
|
543
|
+
function shapeEdgeGroup(g) {
|
|
544
|
+
if (!isObj(g))
|
|
545
|
+
return {};
|
|
546
|
+
const edges = Array.isArray(g.citations) ? g.citations : [];
|
|
547
|
+
const types = [...new Set(edges.map((e) => (isObj(e) ? e.citationType : undefined)).filter(Boolean))];
|
|
548
|
+
const snippet = edges.map((e) => (isObj(e) ? str(e.contextSnippet) : undefined)).find(Boolean);
|
|
549
|
+
return compact({
|
|
550
|
+
celex: g.celexNumber,
|
|
551
|
+
title: g.title,
|
|
552
|
+
types,
|
|
553
|
+
count: g.citationCount,
|
|
554
|
+
context: truncate(snippet, 240),
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
export function shapeCitedBy(res) {
|
|
558
|
+
const b = res.body;
|
|
559
|
+
return compact({
|
|
560
|
+
target: b.targetDocument,
|
|
561
|
+
totalCitations: b.totalCitations,
|
|
562
|
+
limit: b.limit,
|
|
563
|
+
offset: b.offset,
|
|
564
|
+
citedBy: Array.isArray(b.citedBy) ? b.citedBy.map(shapeEdgeGroup) : [],
|
|
565
|
+
relationSync: b.relationSync,
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
export function shapeCites(res) {
|
|
569
|
+
const b = res.body;
|
|
570
|
+
return compact({
|
|
571
|
+
source: b.sourceDocument,
|
|
572
|
+
totalCitations: b.totalCitations,
|
|
573
|
+
limit: b.limit,
|
|
574
|
+
offset: b.offset,
|
|
575
|
+
cites: Array.isArray(b.cites) ? b.cites.map(shapeEdgeGroup) : [],
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
function shapeNeighbour(n) {
|
|
579
|
+
if (!isObj(n))
|
|
580
|
+
return {};
|
|
581
|
+
return compact({ celex: n.celexNumber, title: n.title, types: n.types, count: n.count });
|
|
582
|
+
}
|
|
583
|
+
export function shapeNetwork(res) {
|
|
584
|
+
const b = res.body;
|
|
585
|
+
const net = isObj(b.network) ? b.network : {};
|
|
586
|
+
return compact({
|
|
587
|
+
celex: b.document,
|
|
588
|
+
cites: Array.isArray(net.cites) ? net.cites.map(shapeNeighbour) : [],
|
|
589
|
+
citedBy: Array.isArray(net.citedBy) ? net.citedBy.map(shapeNeighbour) : [],
|
|
590
|
+
paging: b.paging,
|
|
591
|
+
partial: b.partial,
|
|
592
|
+
partialReason: b.partialReason,
|
|
593
|
+
message: b.message,
|
|
594
|
+
relationSync: b.relationSync,
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
export function stripEnvelope(body, drop = []) {
|
|
598
|
+
if (!isObj(body))
|
|
599
|
+
return {};
|
|
600
|
+
const out = {};
|
|
601
|
+
for (const [k, v] of Object.entries(body)) {
|
|
602
|
+
if (k === 'success' || k === 'subscription' || k === 'usage' || k === 'credits' || drop.includes(k))
|
|
603
|
+
continue;
|
|
604
|
+
out[k] = v;
|
|
605
|
+
}
|
|
606
|
+
return out;
|
|
607
|
+
}
|
package/dist/tools.d.ts
CHANGED
|
@@ -1,17 +1,34 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
1
2
|
import type { LexAPIClient } from './client.js';
|
|
2
|
-
|
|
3
|
-
|
|
3
|
+
export declare const LANGUAGES: readonly ["en", "fr", "de", "es", "it", "pl", "nl", "pt", "ro", "bg", "cs", "da", "el", "et", "fi", "ga", "hr", "hu", "lt", "lv", "mt", "sk", "sl", "sv"];
|
|
4
|
+
/** Languages the semantic index holds (server/controllers/semanticController.js). */
|
|
5
|
+
export declare const SEMANTIC_LANGUAGES: readonly ["en", "fr", "de", "es", "it", "sl", "el", "nl", "pt", "pl"];
|
|
6
|
+
export declare const DOCUMENT_TYPES: readonly ["judgment", "opinion", "order", "regulation", "directive", "decision", "recommendation", "communication", "proposal", "report", "resolution", "declaration", "treaty", "protocol", "agreement", "written-question", "oral-question", "consolidated-text", "guideline", "implementing", "staff-working-document"];
|
|
7
|
+
export declare const AUTHORS: readonly ["commission", "council", "parliament", "court-of-justice", "general-court", "civil-service-tribunal", "ecb", "eca", "eesc", "cor", "ema", "efsa"];
|
|
8
|
+
export declare const PROCEDURES: readonly ["ordinary", "codecision", "consent", "consultation", "budget", "implementing", "delegated", "comitology", "appointment", "non-legislative"];
|
|
9
|
+
/** EUR-Lex subdomain codes plus the friendly aliases the API maps to them. */
|
|
10
|
+
export declare const SUBDOMAINS: readonly ["LEGISLATION", "CONSLEG", "TREATIES", "EU_CASE_LAW", "LEGAL_PROCEDURE", "INTER_AGREE", "PRE_ACTS", "PAR_QUESTION", "NAT_CASE_LAW", "legislation", "consolidated", "treaties", "case-law", "legal-procedure", "international", "preparatory", "questions", "national-case-law"];
|
|
11
|
+
export declare const CITATION_TYPES: readonly ["reference", "amendment", "repeal", "corrigendum", "implementation", "legal-basis", "proposal"];
|
|
12
|
+
export declare function isApiDate(value: string): boolean;
|
|
13
|
+
export declare function isApiTimestamp(value: string): boolean;
|
|
14
|
+
export declare function normCelex(v: string): string;
|
|
15
|
+
export interface ToolAnnotations {
|
|
4
16
|
readOnlyHint: boolean;
|
|
5
|
-
|
|
17
|
+
destructiveHint?: boolean;
|
|
6
18
|
idempotentHint?: boolean;
|
|
19
|
+
openWorldHint: boolean;
|
|
7
20
|
}
|
|
8
|
-
interface ToolDef {
|
|
21
|
+
export interface ToolDef {
|
|
9
22
|
name: string;
|
|
23
|
+
title: string;
|
|
10
24
|
description: string;
|
|
11
|
-
inputSchema:
|
|
25
|
+
inputSchema: z.ZodRawShape;
|
|
12
26
|
annotations: ToolAnnotations;
|
|
13
|
-
|
|
27
|
+
/** Not read-only (webhooks, citation extraction). Hidden when LEXAPI_MCP_READ_ONLY is set. */
|
|
28
|
+
write?: boolean;
|
|
29
|
+
handler: (args: any, client: LexAPIClient) => Promise<unknown>;
|
|
14
30
|
}
|
|
15
31
|
export declare const tools: ToolDef[];
|
|
16
|
-
export declare
|
|
17
|
-
|
|
32
|
+
export declare function selectTools(opts?: {
|
|
33
|
+
readOnly?: boolean;
|
|
34
|
+
}): ToolDef[];
|