@lexapi/mcp 0.2.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +110 -0
- package/LICENSE +1 -1
- package/README.md +128 -35
- package/dist/client.d.ts +125 -21
- package/dist/client.js +442 -97
- package/dist/credentials.d.ts +67 -0
- package/dist/credentials.js +118 -0
- package/dist/errors.d.ts +53 -0
- package/dist/errors.js +313 -0
- package/dist/http-entry.js +19 -2
- package/dist/http-server.d.ts +48 -2
- package/dist/http-server.js +544 -111
- package/dist/index.js +18 -60
- package/dist/oauth/body.d.ts +5 -0
- package/dist/oauth/body.js +35 -0
- package/dist/oauth/config.d.ts +59 -0
- package/dist/oauth/config.js +149 -0
- package/dist/oauth/exchange.d.ts +196 -0
- package/dist/oauth/exchange.js +573 -0
- package/dist/oauth/jwt.d.ts +124 -0
- package/dist/oauth/jwt.js +352 -0
- package/dist/oauth/redact.d.ts +1 -0
- package/dist/oauth/redact.js +23 -0
- package/dist/oauth/upstream.d.ts +41 -0
- package/dist/oauth/upstream.js +95 -0
- package/dist/server.d.ts +62 -0
- package/dist/server.js +100 -0
- package/dist/shape.d.ts +115 -0
- package/dist/shape.js +1043 -0
- package/dist/tools.d.ts +29 -8
- package/dist/tools.js +1071 -216
- package/dist/webhookUrl.d.ts +4 -0
- package/dist/webhookUrl.js +114 -0
- package/package.json +23 -15
- package/dist/types.d.ts +0 -43
- package/dist/types.js +0 -7
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import { LexAPIClient } from './client.js';
|
|
3
|
+
import { type ToolDef } from './tools.js';
|
|
4
|
+
export declare const PACKAGE_NAME = "lexapi-mcp";
|
|
5
|
+
/**
|
|
6
|
+
* Sent to the client at initialize (MCP `instructions`): how to use these
|
|
7
|
+
* tools well. Kept short — clients put it in the model's context.
|
|
8
|
+
*/
|
|
9
|
+
export declare const SERVER_INSTRUCTIONS = "LexAPI: EU law from EUR-Lex, the CJEU and the Official Journal \u2014 legislation parsed to article level, case law, a typed citation graph and semantic search.\n\nWorkflow: identify the act (lex_semantic_legislation / lex_semantic_case_law for concepts, lex_search for titles and filters, lex_resolve for URLs/ELI/ECLI), then read it with lex_get_document \u2014 large documents return an outline first; fetch the article you need with articleId. Amendments: lex_cited_by with citationType \"amendment\". Member-state measures for an EU act: lex_transposition \u2014 these are notifications to the Commission, not findings that a measure transposes the act (or does so completely); never present them as such.\n\nCiting: always give the CELEX number (and the EUR-Lex link). Consolidated texts (CELEX 0\u2026-YYYYMMDD, or hits labelled consolidated: true) are documentation tools without legal force \u2014 quote them, but cite the authentic act as published in the Official Journal (baseCelex). For the law on a past date use lex_semantic_legislation with asOf; trust a hit as the text in force on that date only when asOfResolved is true. For a known article on a past date when you already know the consolidated version for that date (CELEX 0\u2026-YYYYMMDD; lex_get_metadata and textAvailability show latestConsolidated), read it directly with lex_get_document; otherwise asOf is the route that resolves the version in force. lex_document_versions / lex_get_document_version are LexAPI's fetch snapshots, not in-force law.\n\nLexAPI provides source texts; it does not decide whether anyone is compliant \u2014 leave legal conclusions to the user and their advisers.\n\nNational law (member-state legislation and case law): call lex_national_coverage before any other national tool \u2014 a country can be registered but not yet launched, and availability, courts and source licensing differ by country. Always carry the sources/attribution it and the national tools return through to the user; national-law calls also draw from a separate monthly allowance on some plans, reported in each tool's response. Consolidated national texts are not authentic \u2014 only the official gazette is; never try to re-identify parties a court anonymised or pseudonymised; for French decisions, never evaluate, compare or predict individual judges (art. 33, loi n\u00B0 2019-222).\n\nCosts come from the user's monthly credit pool and are stated in each tool description; avoid repeated or speculative calls. On a 402 (credits exhausted) or 429 (rate limit), stop and tell the user what the error says.";
|
|
10
|
+
export interface CreateServerOptions {
|
|
11
|
+
readOnly?: boolean;
|
|
12
|
+
}
|
|
13
|
+
export declare function createLexServer(client: LexAPIClient, opts?: CreateServerOptions): McpServer;
|
|
14
|
+
/** The parts of the SDK's RequestHandlerExtra a tool call uses. */
|
|
15
|
+
export interface CallExtra {
|
|
16
|
+
signal?: AbortSignal;
|
|
17
|
+
_meta?: {
|
|
18
|
+
progressToken?: string | number;
|
|
19
|
+
};
|
|
20
|
+
sendNotification?: (n: {
|
|
21
|
+
method: 'notifications/progress';
|
|
22
|
+
params: {
|
|
23
|
+
progressToken: string | number;
|
|
24
|
+
progress: number;
|
|
25
|
+
message?: string;
|
|
26
|
+
};
|
|
27
|
+
}) => Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
export declare const PROGRESS_INTERVAL_MS = 10000;
|
|
30
|
+
/**
|
|
31
|
+
* Execute a tool and render its result (or error) as MCP tool content.
|
|
32
|
+
*
|
|
33
|
+
* - The MCP request's abort signal (client cancellation, closed HTTP
|
|
34
|
+
* connection) aborts the upstream LexAPI request.
|
|
35
|
+
* - Timeout: 55 s by default, under the 60 s default request timeout of MCP
|
|
36
|
+
* clients, so the model gets our actionable message rather than the
|
|
37
|
+
* client's generic -32001. A progress token does NOT tell us the client
|
|
38
|
+
* will extend its timeout on progress (TS SDK `resetTimeoutOnProgress`
|
|
39
|
+
* defaults to false), so it does not raise the timeout; LEXAPI_TIMEOUT_MS
|
|
40
|
+
* does, for users who also raised their client's timeout.
|
|
41
|
+
* - With a progress token we still send a heartbeat every 10 s, so clients
|
|
42
|
+
* that DO reset on progress — and UIs showing progress — see the call alive.
|
|
43
|
+
*/
|
|
44
|
+
export declare function runTool(tool: ToolDef, args: Record<string, unknown>, client: LexAPIClient, extra?: CallExtra, opts?: {
|
|
45
|
+
timeoutMs?: number;
|
|
46
|
+
progressIntervalMs?: number;
|
|
47
|
+
}): Promise<{
|
|
48
|
+
content: {
|
|
49
|
+
type: "text";
|
|
50
|
+
text: string;
|
|
51
|
+
}[];
|
|
52
|
+
isError?: undefined;
|
|
53
|
+
} | {
|
|
54
|
+
isError: boolean;
|
|
55
|
+
content: {
|
|
56
|
+
type: "text";
|
|
57
|
+
text: string;
|
|
58
|
+
}[];
|
|
59
|
+
}>;
|
|
60
|
+
export declare function readOnlyFromEnv(env?: NodeJS.ProcessEnv): boolean;
|
|
61
|
+
/** API-key requests (stdio and hosted): LEXAPI_BASE_URL exactly as 0.3.0 read it. */
|
|
62
|
+
export declare function clientFromEnv(apiKey: string, env?: NodeJS.ProcessEnv): LexAPIClient;
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import { DEFAULT_TIMEOUT_MS, LexAPIClient } from './client.js';
|
|
3
|
+
import { describeError } from './errors.js';
|
|
4
|
+
import { selectTools } from './tools.js';
|
|
5
|
+
import { PACKAGE_VERSION } from './version.js';
|
|
6
|
+
export const PACKAGE_NAME = 'lexapi-mcp';
|
|
7
|
+
/**
|
|
8
|
+
* Sent to the client at initialize (MCP `instructions`): how to use these
|
|
9
|
+
* tools well. Kept short — clients put it in the model's context.
|
|
10
|
+
*/
|
|
11
|
+
export const SERVER_INSTRUCTIONS = `LexAPI: EU law from EUR-Lex, the CJEU and the Official Journal — legislation parsed to article level, case law, a typed citation graph and semantic search.
|
|
12
|
+
|
|
13
|
+
Workflow: identify the act (lex_semantic_legislation / lex_semantic_case_law for concepts, lex_search for titles and filters, lex_resolve for URLs/ELI/ECLI), then read it with lex_get_document — large documents return an outline first; fetch the article you need with articleId. Amendments: lex_cited_by with citationType "amendment". Member-state measures for an EU act: lex_transposition — these are notifications to the Commission, not findings that a measure transposes the act (or does so completely); never present them as such.
|
|
14
|
+
|
|
15
|
+
Citing: always give the CELEX number (and the EUR-Lex link). Consolidated texts (CELEX 0…-YYYYMMDD, or hits labelled consolidated: true) are documentation tools without legal force — quote them, but cite the authentic act as published in the Official Journal (baseCelex). For the law on a past date use lex_semantic_legislation with asOf; trust a hit as the text in force on that date only when asOfResolved is true. For a known article on a past date when you already know the consolidated version for that date (CELEX 0…-YYYYMMDD; lex_get_metadata and textAvailability show latestConsolidated), read it directly with lex_get_document; otherwise asOf is the route that resolves the version in force. lex_document_versions / lex_get_document_version are LexAPI's fetch snapshots, not in-force law.
|
|
16
|
+
|
|
17
|
+
LexAPI provides source texts; it does not decide whether anyone is compliant — leave legal conclusions to the user and their advisers.
|
|
18
|
+
|
|
19
|
+
National law (member-state legislation and case law): call lex_national_coverage before any other national tool — a country can be registered but not yet launched, and availability, courts and source licensing differ by country. Always carry the sources/attribution it and the national tools return through to the user; national-law calls also draw from a separate monthly allowance on some plans, reported in each tool's response. Consolidated national texts are not authentic — only the official gazette is; never try to re-identify parties a court anonymised or pseudonymised; for French decisions, never evaluate, compare or predict individual judges (art. 33, loi n° 2019-222).
|
|
20
|
+
|
|
21
|
+
Costs come from the user's monthly credit pool and are stated in each tool description; avoid repeated or speculative calls. On a 402 (credits exhausted) or 429 (rate limit), stop and tell the user what the error says.`;
|
|
22
|
+
export function createLexServer(client, opts = {}) {
|
|
23
|
+
const server = new McpServer({
|
|
24
|
+
name: PACKAGE_NAME,
|
|
25
|
+
title: 'LexAPI',
|
|
26
|
+
version: PACKAGE_VERSION,
|
|
27
|
+
websiteUrl: 'https://lex-api.com',
|
|
28
|
+
}, {
|
|
29
|
+
capabilities: { tools: {} },
|
|
30
|
+
instructions: SERVER_INSTRUCTIONS,
|
|
31
|
+
});
|
|
32
|
+
for (const tool of selectTools(opts))
|
|
33
|
+
registerTool(server, tool, client);
|
|
34
|
+
return server;
|
|
35
|
+
}
|
|
36
|
+
function registerTool(server, tool, client) {
|
|
37
|
+
server.registerTool(tool.name, {
|
|
38
|
+
title: tool.title,
|
|
39
|
+
description: tool.description,
|
|
40
|
+
inputSchema: tool.inputSchema,
|
|
41
|
+
// The tool-level `title` already names it; annotations.title would repeat it.
|
|
42
|
+
annotations: tool.annotations,
|
|
43
|
+
}, async (args, extra) => runTool(tool, args, client, extra));
|
|
44
|
+
}
|
|
45
|
+
export const PROGRESS_INTERVAL_MS = 10_000;
|
|
46
|
+
/**
|
|
47
|
+
* Execute a tool and render its result (or error) as MCP tool content.
|
|
48
|
+
*
|
|
49
|
+
* - The MCP request's abort signal (client cancellation, closed HTTP
|
|
50
|
+
* connection) aborts the upstream LexAPI request.
|
|
51
|
+
* - Timeout: 55 s by default, under the 60 s default request timeout of MCP
|
|
52
|
+
* clients, so the model gets our actionable message rather than the
|
|
53
|
+
* client's generic -32001. A progress token does NOT tell us the client
|
|
54
|
+
* will extend its timeout on progress (TS SDK `resetTimeoutOnProgress`
|
|
55
|
+
* defaults to false), so it does not raise the timeout; LEXAPI_TIMEOUT_MS
|
|
56
|
+
* does, for users who also raised their client's timeout.
|
|
57
|
+
* - With a progress token we still send a heartbeat every 10 s, so clients
|
|
58
|
+
* that DO reset on progress — and UIs showing progress — see the call alive.
|
|
59
|
+
*/
|
|
60
|
+
export async function runTool(tool, args, client, extra = {}, opts = {}) {
|
|
61
|
+
const token = extra._meta?.progressToken;
|
|
62
|
+
const timeoutMs = opts.timeoutMs ?? configuredTimeout() ?? DEFAULT_TIMEOUT_MS;
|
|
63
|
+
const callClient = client.forCall({ signal: extra.signal, timeoutMs });
|
|
64
|
+
let heartbeat;
|
|
65
|
+
if (token !== undefined && extra.sendNotification) {
|
|
66
|
+
let n = 0;
|
|
67
|
+
const send = extra.sendNotification;
|
|
68
|
+
heartbeat = setInterval(() => {
|
|
69
|
+
n += 1;
|
|
70
|
+
send({ method: 'notifications/progress', params: { progressToken: token, progress: n, message: 'Waiting for LexAPI…' } }).catch(() => { });
|
|
71
|
+
}, opts.progressIntervalMs ?? PROGRESS_INTERVAL_MS);
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
const result = await tool.handler(args ?? {}, callClient);
|
|
75
|
+
// Compact JSON: indentation costs ~25% more tokens and models read it fine.
|
|
76
|
+
return { content: [{ type: 'text', text: JSON.stringify(result) }] };
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
return { isError: true, content: [{ type: 'text', text: describeError(err) }] };
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
if (heartbeat)
|
|
83
|
+
clearInterval(heartbeat);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function configuredTimeout(env = process.env) {
|
|
87
|
+
const t = Number.parseInt(env.LEXAPI_TIMEOUT_MS ?? '', 10);
|
|
88
|
+
return Number.isFinite(t) && t >= 5000 ? t : undefined;
|
|
89
|
+
}
|
|
90
|
+
export function readOnlyFromEnv(env = process.env) {
|
|
91
|
+
const v = (env.LEXAPI_MCP_READ_ONLY ?? '').trim().toLowerCase();
|
|
92
|
+
return v === '1' || v === 'true' || v === 'yes';
|
|
93
|
+
}
|
|
94
|
+
/** API-key requests (stdio and hosted): LEXAPI_BASE_URL exactly as 0.3.0 read it. */
|
|
95
|
+
export function clientFromEnv(apiKey, env = process.env) {
|
|
96
|
+
return new LexAPIClient({
|
|
97
|
+
apiKey,
|
|
98
|
+
...(env.LEXAPI_BASE_URL ? { baseUrl: env.LEXAPI_BASE_URL } : {}),
|
|
99
|
+
});
|
|
100
|
+
}
|
package/dist/shape.d.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { Json, LexResponse } from './client.js';
|
|
2
|
+
type Obj = Record<string, unknown>;
|
|
3
|
+
export declare function isObj(v: unknown): v is Obj;
|
|
4
|
+
/** Remove undefined / null / '' / empty-array / empty-object values (one level deep per call site). */
|
|
5
|
+
export declare function compact<T extends Obj>(o: T): Partial<T>;
|
|
6
|
+
/**
|
|
7
|
+
* The core API router attaches `credits` to v2 responses. Surfacing it on
|
|
8
|
+
* every call would cost tokens for nothing; a notice only when the pool is
|
|
9
|
+
* nearly empty lets the model warn the user before calls start to 402.
|
|
10
|
+
*/
|
|
11
|
+
export declare function creditNotice(body: unknown): string | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* FREE/STARTER/PROFESSIONAL accounts get a monthly allowance of national
|
|
14
|
+
* calls, separate from the credit pool; BUSINESS and higher have no
|
|
15
|
+
* separate limit, so the `X-National-*` headers are simply absent for them.
|
|
16
|
+
* Surfaced on every national tool response (except lex_national_coverage,
|
|
17
|
+
* which does not count against it) so the model can warn the user before
|
|
18
|
+
* calls start to 402 `NATIONAL_ALLOWANCE_EXHAUSTED`.
|
|
19
|
+
*/
|
|
20
|
+
export declare function nationalAllowanceOf(headers: LexResponse['headers']): Obj | undefined;
|
|
21
|
+
/** `02016R0679-20160504` → { base: '32016R0679', date: '2016-05-04' }; null otherwise. */
|
|
22
|
+
export declare function consolidatedBaseOf(celex: unknown): {
|
|
23
|
+
base: string;
|
|
24
|
+
date: string;
|
|
25
|
+
} | null;
|
|
26
|
+
export declare function consolidatedLabel(celex: unknown): Obj | undefined;
|
|
27
|
+
export declare function shapeMetadata(doc: Obj, headers?: LexResponse['headers']): Obj;
|
|
28
|
+
export type View = 'auto' | 'outline' | 'full';
|
|
29
|
+
export interface ContentOptions {
|
|
30
|
+
/** Default 'auto'. 'outline' only when the caller asked for it explicitly. */
|
|
31
|
+
view?: View;
|
|
32
|
+
maxChars: number;
|
|
33
|
+
/** Parts the caller asked for explicitly (API `include`); undefined = all. */
|
|
34
|
+
include?: string[];
|
|
35
|
+
/** Skip this many items (across parts, in order) — paging after truncation. In outline view: articles. */
|
|
36
|
+
offset?: number;
|
|
37
|
+
/**
|
|
38
|
+
* The calling tool has no `articleId` / `include` parameters (the national
|
|
39
|
+
* document tool): the outline's reading hint then points at view "full" +
|
|
40
|
+
* offset, the only way that tool reads on.
|
|
41
|
+
*/
|
|
42
|
+
noPartSelection?: boolean;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Shape `content` (a document's parsed body) under a character budget.
|
|
46
|
+
* Returns the shaped content plus a note when anything was outlined, split,
|
|
47
|
+
* truncated or omitted.
|
|
48
|
+
*/
|
|
49
|
+
export declare function shapeContent(content: unknown, opts: ContentOptions): {
|
|
50
|
+
content?: Obj;
|
|
51
|
+
note?: string;
|
|
52
|
+
};
|
|
53
|
+
/** A full document object (from /documentContent, batch, by-URL) → compact form. */
|
|
54
|
+
export declare function shapeDocument(doc: unknown, headers: LexResponse['headers'], opts: ContentOptions): Obj;
|
|
55
|
+
export declare function shapeSearchResult(r: unknown): Obj;
|
|
56
|
+
export declare function shapeSearch(res: LexResponse<Json>): Obj;
|
|
57
|
+
export declare function shapeRecent(res: LexResponse<Json>): Obj;
|
|
58
|
+
export declare function shapeCaseLawHit(r: unknown): Obj;
|
|
59
|
+
export declare function shapeCaseLaw(res: LexResponse<Json>): Obj;
|
|
60
|
+
export declare function shapeLegislationHit(r: unknown): Obj;
|
|
61
|
+
export declare function shapeLegislation(res: LexResponse<Json>): Obj;
|
|
62
|
+
/**
|
|
63
|
+
* One instruction per class of unresolved hit present. Every unresolved
|
|
64
|
+
* hit carries the LATEST text; what the model should do differs:
|
|
65
|
+
* - not in force on the date → that IS the answer (say so);
|
|
66
|
+
* - transient → retry shortly, or with a smaller limit;
|
|
67
|
+
* - credits → tell the user;
|
|
68
|
+
* - anything else (no text in that version, language, article missing…) →
|
|
69
|
+
* the version in force could not be read; don't quote it as of that date.
|
|
70
|
+
*/
|
|
71
|
+
export declare function asOfCaveat(results: Obj[], asOf: string): Obj | undefined;
|
|
72
|
+
export declare function nodeFields(n: Obj): Obj;
|
|
73
|
+
/** `unresolved=true` on a national id: at most this many references are shown. */
|
|
74
|
+
export declare const UNRESOLVED_SHOWN = 100;
|
|
75
|
+
export declare function shapeCitedBy(res: LexResponse<Json>): Obj;
|
|
76
|
+
export declare function shapeCites(res: LexResponse<Json>): Obj;
|
|
77
|
+
export declare function shapeNetwork(res: LexResponse<Json>): Obj;
|
|
78
|
+
/** Character budget of one transposition / counterparts result. */
|
|
79
|
+
export declare const GRAPH_RESULT_BUDGET = 40000;
|
|
80
|
+
/**
|
|
81
|
+
* The measures are bounded here (`limit` / `offset`, counted across
|
|
82
|
+
* countries in the API's order, and a character budget: measures stop once
|
|
83
|
+
* it is spent, so the next offset is exact); every country's `counts` is
|
|
84
|
+
* always kept.
|
|
85
|
+
*/
|
|
86
|
+
export declare function shapeTransposition(res: LexResponse<Json>, limit: number, offset: number, budget?: number): Obj;
|
|
87
|
+
/**
|
|
88
|
+
* Counterparts: at most `acts` EU acts per call (from `offset`), at most
|
|
89
|
+
* `limit` counterparts per act, and acts stop once the character budget is
|
|
90
|
+
* spent (the first one is always shown).
|
|
91
|
+
*/
|
|
92
|
+
export declare function shapeCounterparts(res: LexResponse<Json>, limit: number, offset: number, acts: number, budget?: number): Obj;
|
|
93
|
+
export declare function shapeNationalSearchResult(r: unknown): Obj;
|
|
94
|
+
/** A full national document (from GET /{jur}/documents/{id}). */
|
|
95
|
+
export declare function shapeNationalDocument(doc: unknown, opts: ContentOptions): Obj;
|
|
96
|
+
/**
|
|
97
|
+
* A national case-law hit. `documentKind`, `title`, `ecli` and
|
|
98
|
+
* `dateOfDocument` come from the hit's `document` (LexAPI's own record, the
|
|
99
|
+
* same fields in every country — API 2.8.0), falling back to the index's
|
|
100
|
+
* own metadata; `court` / `caseNumbers` come from the index (a summary
|
|
101
|
+
* carries no decision block — lex_get_national_document has the normalized
|
|
102
|
+
* court, chamber, caseNumbers and citedNorms).
|
|
103
|
+
*/
|
|
104
|
+
export declare function shapeNationalCaseLawHit(r: unknown): Obj;
|
|
105
|
+
export declare function shapeNationalCaseLaw(res: LexResponse<Json>): Obj;
|
|
106
|
+
/**
|
|
107
|
+
* A national legislation hit. The index fields (snake_case — the server's
|
|
108
|
+
* own names on this endpoint) are always sent since API 2.8.0, null when
|
|
109
|
+
* the index has nothing (compacted away here); `documentKind`, `title` and
|
|
110
|
+
* the act's validity come from the hit's `document` summary.
|
|
111
|
+
*/
|
|
112
|
+
export declare function shapeNationalLegislationHit(r: unknown): Obj;
|
|
113
|
+
export declare function shapeNationalLegislation(res: LexResponse<Json>): Obj;
|
|
114
|
+
export declare function stripEnvelope(body: unknown, drop?: string[]): Obj;
|
|
115
|
+
export {};
|