@lexapi/mcp 0.2.0 → 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.
@@ -1,100 +1,153 @@
1
1
  import { createServer } from 'node:http';
2
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
2
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
4
- import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
5
- import { LexAPIClient, LexAPIError } from './client.js';
6
- import { tools, toolsByName } from './tools.js';
3
+ import { isWellFormedKey } from './client.js';
4
+ import { clientFromEnv, createLexServer, PACKAGE_NAME, readOnlyFromEnv } from './server.js';
5
+ import { selectTools } from './tools.js';
7
6
  import { PACKAGE_VERSION } from './version.js';
8
- const PACKAGE_NAME = 'lexapi-mcp';
9
7
  const MCP_PATH = '/v1';
10
- function extractBearer(req) {
11
- const header = req.headers['authorization'];
12
- if (!header || typeof header !== 'string')
13
- return null;
14
- const match = header.match(/^Bearer\s+(.+)$/i);
15
- return match ? match[1].trim() : null;
8
+ const MAX_BODY_BYTES = 1_000_000;
9
+ /**
10
+ * An oversized body is still read (and discarded) up to this much / this
11
+ * long, so the client finishes uploading and actually receives the 413 —
12
+ * closing the socket mid-upload makes clients report EPIPE / ECONNRESET.
13
+ */
14
+ const DRAIN_MAX_BYTES = 16_000_000;
15
+ const DRAIN_MAX_MS = 5000;
16
+ /**
17
+ * The caller's LexAPI key: `Authorization: Bearer <key>` (what server.json
18
+ * advertises), or `x-api-key: <key>` (the REST API's own header).
19
+ */
20
+ export function extractApiKey(req) {
21
+ const auth = req.headers['authorization'];
22
+ if (typeof auth === 'string') {
23
+ // Everything after "Bearer " is the key; a value with inner whitespace
24
+ // is returned as-is so it is reported as malformed, not as missing.
25
+ const m = auth.match(/^Bearer\s+(.+?)\s*$/i);
26
+ if (m)
27
+ return m[1];
28
+ }
29
+ const x = req.headers['x-api-key'];
30
+ if (typeof x === 'string' && x.trim())
31
+ return x.trim();
32
+ return null;
16
33
  }
17
- async function readJsonBody(req) {
18
- const chunks = [];
19
- for await (const chunk of req) {
20
- chunks.push(chunk);
21
- // 1 MB request-body cap — MCP JSON-RPC messages are tiny; anything larger is abuse.
22
- if (chunks.reduce((n, c) => n + c.length, 0) > 1_000_000) {
23
- throw new Error('request body too large');
24
- }
34
+ /**
35
+ * Origin validation (MCP Streamable HTTP: servers MUST validate Origin, a
36
+ * DNS-rebinding defence). Requests without an Origin header — every
37
+ * non-browser MCP client — are allowed. A browser request is allowed only
38
+ * when its Origin is listed in LEXAPI_MCP_ALLOWED_ORIGINS (comma-separated;
39
+ * "*" allows any). Auth is a bearer key with no ambient credentials, so this
40
+ * is defence in depth, not the access control.
41
+ */
42
+ export function originAllowed(origin, env = process.env) {
43
+ if (!origin)
44
+ return true;
45
+ const list = (env.LEXAPI_MCP_ALLOWED_ORIGINS ?? '').split(',').map((s) => s.trim()).filter(Boolean);
46
+ return list.includes('*') || list.includes(origin);
47
+ }
48
+ class BodyTooLargeError extends Error {
49
+ drained;
50
+ constructor(drained) {
51
+ super('request body too large');
52
+ this.drained = drained;
25
53
  }
26
- const text = Buffer.concat(chunks).toString('utf8');
27
- if (!text)
28
- return undefined;
29
- return JSON.parse(text);
30
54
  }
31
- function buildMcpServer(apiKey) {
32
- const baseUrl = process.env.LEXAPI_BASE_URL;
33
- const client = new LexAPIClient({
34
- apiKey,
35
- ...(baseUrl ? { baseUrl } : {}),
55
+ /** Discard the rest of an oversized body; resolves true if it ended within the caps. */
56
+ function drain(req, alreadyRead) {
57
+ return new Promise((resolve) => {
58
+ if (req.readableEnded)
59
+ return resolve(true);
60
+ let seen = alreadyRead;
61
+ const done = (ok) => {
62
+ clearTimeout(timer);
63
+ req.removeListener('data', onData);
64
+ req.removeListener('end', onEnd);
65
+ req.removeListener('error', onEnd);
66
+ resolve(ok);
67
+ };
68
+ const onData = (chunk) => {
69
+ seen += chunk.length;
70
+ if (seen > DRAIN_MAX_BYTES)
71
+ done(false);
72
+ };
73
+ const onEnd = () => done(true);
74
+ const timer = setTimeout(() => done(false), DRAIN_MAX_MS);
75
+ req.on('data', onData);
76
+ req.once('end', onEnd);
77
+ req.once('error', onEnd);
78
+ req.resume();
36
79
  });
37
- const server = new Server({ name: PACKAGE_NAME, version: PACKAGE_VERSION }, { capabilities: { tools: {} } });
38
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
39
- tools: tools.map(({ name, description, inputSchema, annotations }) => ({
40
- name,
41
- description,
42
- inputSchema,
43
- annotations,
44
- })),
45
- }));
46
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
47
- const { name, arguments: args = {} } = request.params;
48
- const tool = toolsByName[name];
49
- if (!tool) {
50
- return {
51
- isError: true,
52
- content: [{ type: 'text', text: `Unknown tool: ${name}` }],
53
- };
54
- }
55
- try {
56
- const result = await tool.handler(args, client);
57
- return {
58
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
59
- };
60
- }
61
- catch (err) {
62
- if (err instanceof LexAPIError) {
63
- return {
64
- isError: true,
65
- content: [
66
- {
67
- type: 'text',
68
- text: `LexAPI error (${err.status} ${err.slug}): ${err.message}`,
69
- },
70
- ],
71
- };
80
+ }
81
+ async function readJsonBody(req) {
82
+ const declared = Number(req.headers['content-length']);
83
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
84
+ throw new BodyTooLargeError(await drain(req, 0));
85
+ }
86
+ // Event listeners, not `for await`: leaving a for-await loop early destroys
87
+ // the stream, and the remaining body must stay readable for drain().
88
+ const text = await new Promise((resolve, reject) => {
89
+ const chunks = [];
90
+ let size = 0;
91
+ const cleanup = () => {
92
+ req.removeListener('data', onData);
93
+ req.removeListener('end', onEnd);
94
+ req.removeListener('error', onError);
95
+ };
96
+ const onData = (chunk) => {
97
+ size += chunk.length;
98
+ if (size > MAX_BODY_BYTES) {
99
+ cleanup();
100
+ req.pause();
101
+ drain(req, size).then((ok) => resolve(new BodyTooLargeError(ok)));
102
+ return;
72
103
  }
73
- const message = err instanceof Error ? err.message : String(err);
74
- return {
75
- isError: true,
76
- content: [{ type: 'text', text: `Tool execution failed: ${message}` }],
77
- };
78
- }
104
+ chunks.push(chunk);
105
+ };
106
+ const onEnd = () => { cleanup(); resolve(Buffer.concat(chunks).toString('utf8')); };
107
+ const onError = (e) => { cleanup(); reject(e); };
108
+ req.on('data', onData);
109
+ req.on('end', onEnd);
110
+ req.on('error', onError);
79
111
  });
80
- return server;
112
+ if (text instanceof BodyTooLargeError)
113
+ throw text;
114
+ if (!text)
115
+ return undefined;
116
+ return JSON.parse(text);
81
117
  }
82
- function writeJson(res, status, body) {
118
+ function writeJson(res, status, body, extra = {}) {
83
119
  res.writeHead(status, {
84
120
  'Content-Type': 'application/json',
85
121
  'Cache-Control': 'no-store, private',
122
+ ...extra,
86
123
  });
87
124
  res.end(JSON.stringify(body));
88
125
  }
126
+ function jsonRpcError(res, status, code, message, extra = {}) {
127
+ writeJson(res, status, { jsonrpc: '2.0', error: { code, message }, id: null }, extra);
128
+ }
89
129
  async function handleMcp(req, res) {
90
- const apiKey = extractBearer(req);
130
+ // Stateless server: there is no session to open a GET event stream on or to
131
+ // DELETE, so only POST is meaningful (MCP Streamable HTTP, stateless mode).
132
+ if (req.method !== 'POST') {
133
+ jsonRpcError(res, 405, -32000, 'Method not allowed: this server is stateless; send JSON-RPC requests with POST.', { Allow: 'POST, OPTIONS' });
134
+ return;
135
+ }
136
+ const apiKey = extractApiKey(req);
91
137
  if (!apiKey) {
92
138
  writeJson(res, 401, {
93
139
  error: {
94
140
  code: 'unauthorized',
95
- message: 'Missing or invalid Authorization header. Send: Authorization: Bearer <your LexAPI key>. Get a key at https://lex-api.com/dashboard.',
141
+ message: 'Missing API key. Send "Authorization: Bearer <your LexAPI key>" (or "x-api-key: <key>"). Get a key at https://lex-api.com/dashboard?ref=mcp-hosted.',
96
142
  },
97
- });
143
+ }, { 'WWW-Authenticate': 'Bearer realm="lexapi"' });
144
+ return;
145
+ }
146
+ if (!isWellFormedKey(apiKey)) {
147
+ // Never echo the value.
148
+ writeJson(res, 401, {
149
+ error: { code: 'malformed_api_key', message: 'Malformed API key: it contains whitespace or control characters. Send the key exactly as shown in the dashboard, on one line.' },
150
+ }, { 'WWW-Authenticate': 'Bearer realm="lexapi", error="invalid_token"' });
98
151
  return;
99
152
  }
100
153
  let body;
@@ -102,64 +155,77 @@ async function handleMcp(req, res) {
102
155
  body = await readJsonBody(req);
103
156
  }
104
157
  catch (err) {
105
- const message = err instanceof Error ? err.message : String(err);
106
- writeJson(res, 400, { error: { code: 'bad_request', message } });
158
+ if (err instanceof BodyTooLargeError) {
159
+ // The body was drained (up to the caps), so the client receives this
160
+ // 413. Close the connection anyway: if the drain hit a cap, the rest of
161
+ // the body is still on the socket and must not be read as a request.
162
+ res.on('finish', () => { if (!err.drained)
163
+ req.destroy(); });
164
+ jsonRpcError(res, 413, -32600, `Request body too large (max ${MAX_BODY_BYTES} bytes)`, { Connection: 'close' });
165
+ }
166
+ else
167
+ jsonRpcError(res, 400, -32700, 'Parse error: body is not valid JSON');
107
168
  return;
108
169
  }
109
- // Defense-in-depth headers — Cloudflare + intermediate proxies should not
110
- // buffer streamed responses, and per-user MCP responses must never be cached.
170
+ // Per-user responses must never be cached or buffered by proxies.
111
171
  res.setHeader('X-Accel-Buffering', 'no');
112
172
  res.setHeader('Cache-Control', 'no-store, private');
113
- const mcpServer = buildMcpServer(apiKey);
114
- const transport = new StreamableHTTPServerTransport({
115
- sessionIdGenerator: undefined,
116
- });
173
+ const server = createLexServer(clientFromEnv(apiKey), { readOnly: readOnlyFromEnv() });
174
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
117
175
  res.on('close', () => {
118
176
  transport.close().catch(() => { });
119
- mcpServer.close().catch(() => { });
177
+ server.close().catch(() => { });
120
178
  });
121
- await mcpServer.connect(transport);
179
+ await server.connect(transport);
122
180
  await transport.handleRequest(req, res, body);
123
181
  }
124
182
  export function createHttpServer() {
125
183
  return createServer(async (req, res) => {
126
184
  try {
127
- // CORS preflight — MCP clients called from browsers need this.
185
+ const path = (req.url ?? '/').split('?')[0];
186
+ const origin = typeof req.headers.origin === 'string' ? req.headers.origin : undefined;
187
+ if (!originAllowed(origin)) {
188
+ writeJson(res, 403, { error: { code: 'origin_not_allowed', message: `Origin ${origin} is not allowed. Browser clients must be listed in LEXAPI_MCP_ALLOWED_ORIGINS.` } });
189
+ return;
190
+ }
191
+ // CORS for allowed browser origins (echoed, never a wildcard with a real origin).
128
192
  if (req.method === 'OPTIONS') {
129
193
  res.writeHead(204, {
130
- 'Access-Control-Allow-Origin': '*',
131
- 'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
132
- 'Access-Control-Allow-Headers': 'Authorization, Content-Type, Mcp-Session-Id, Mcp-Protocol-Version',
194
+ ...(origin ? { 'Access-Control-Allow-Origin': origin, Vary: 'Origin' } : {}),
195
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
196
+ 'Access-Control-Allow-Headers': 'Authorization, X-API-Key, Content-Type, Accept, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID',
133
197
  'Access-Control-Max-Age': '86400',
134
198
  });
135
199
  res.end();
136
200
  return;
137
201
  }
138
- res.setHeader('Access-Control-Allow-Origin', '*');
139
- res.setHeader('Access-Control-Expose-Headers', 'Mcp-Session-Id');
140
- if (req.method === 'GET' && req.url === '/health') {
202
+ if (origin) {
203
+ res.setHeader('Access-Control-Allow-Origin', origin);
204
+ res.setHeader('Vary', 'Origin');
205
+ }
206
+ res.setHeader('Access-Control-Expose-Headers', 'Mcp-Session-Id, Mcp-Protocol-Version, WWW-Authenticate');
207
+ if (path === '/health' && (req.method === 'GET' || req.method === 'HEAD')) {
141
208
  writeJson(res, 200, {
142
209
  status: 'ok',
143
210
  name: PACKAGE_NAME,
144
211
  version: PACKAGE_VERSION,
145
- tools: tools.length,
212
+ tools: selectTools({ readOnly: readOnlyFromEnv() }).length,
146
213
  });
147
214
  return;
148
215
  }
149
- if (req.url === MCP_PATH || req.url === MCP_PATH + '/') {
216
+ if (path === MCP_PATH || path === `${MCP_PATH}/`) {
150
217
  await handleMcp(req, res);
151
218
  return;
152
219
  }
153
- writeJson(res, 404, { error: { code: 'not_found', message: `No route for ${req.method} ${req.url}` } });
220
+ writeJson(res, 404, { error: { code: 'not_found', message: `No route for ${req.method} ${path}. The MCP endpoint is POST ${MCP_PATH}.` } });
154
221
  }
155
222
  catch (err) {
156
- const message = err instanceof Error ? err.message : String(err);
157
- if (!res.headersSent) {
158
- writeJson(res, 500, { error: { code: 'internal_error', message } });
159
- }
160
- else {
223
+ // Log server-side only; the client gets a generic message (no internals).
224
+ console.error(`[${PACKAGE_NAME}] request failed:`, err instanceof Error ? err.message : err);
225
+ if (!res.headersSent)
226
+ jsonRpcError(res, 500, -32603, 'Internal server error');
227
+ else
161
228
  res.end();
162
- }
163
229
  }
164
230
  });
165
231
  }
package/dist/index.js CHANGED
@@ -1,66 +1,24 @@
1
1
  #!/usr/bin/env node
2
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
2
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
- import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
5
- import { LexAPIClient, LexAPIError } from './client.js';
6
- import { tools, toolsByName } from './tools.js';
3
+ import { clientFromEnv, createLexServer, PACKAGE_NAME, readOnlyFromEnv } from './server.js';
4
+ import { selectTools } from './tools.js';
7
5
  import { PACKAGE_VERSION } from './version.js';
8
- const PACKAGE_NAME = 'lexapi-mcp';
9
- const apiKey = process.env.LEXAPI_API_KEY;
6
+ // stdout is the MCP channel — every log line goes to stderr.
7
+ const apiKey = process.env.LEXAPI_API_KEY?.trim();
10
8
  if (!apiKey) {
11
- console.error(`[${PACKAGE_NAME}] LEXAPI_API_KEY is not set. Get a key at https://lex-api.com/dashboard and pass it in your MCP client config.`);
9
+ console.error(`[${PACKAGE_NAME}] LEXAPI_API_KEY is not set. Get a key at https://lex-api.com/dashboard?ref=npm-mcp and pass it in your MCP client config.`);
12
10
  process.exit(1);
13
11
  }
14
- const baseUrl = process.env.LEXAPI_BASE_URL;
15
- const client = new LexAPIClient({
16
- apiKey,
17
- ...(baseUrl ? { baseUrl } : {}),
18
- });
19
- const server = new Server({ name: PACKAGE_NAME, version: PACKAGE_VERSION }, { capabilities: { tools: {} } });
20
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
21
- tools: tools.map(({ name, description, inputSchema, annotations }) => ({
22
- name,
23
- description,
24
- inputSchema,
25
- annotations,
26
- })),
27
- }));
28
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
29
- const { name, arguments: args = {} } = request.params;
30
- const tool = toolsByName[name];
31
- if (!tool) {
32
- return {
33
- isError: true,
34
- content: [{ type: 'text', text: `Unknown tool: ${name}` }],
35
- };
36
- }
37
- try {
38
- const result = await tool.handler(args, client);
39
- return {
40
- content: [
41
- { type: 'text', text: JSON.stringify(result, null, 2) },
42
- ],
43
- };
44
- }
45
- catch (err) {
46
- if (err instanceof LexAPIError) {
47
- return {
48
- isError: true,
49
- content: [
50
- {
51
- type: 'text',
52
- text: `LexAPI error (${err.status} ${err.slug}): ${err.message}`,
53
- },
54
- ],
55
- };
56
- }
57
- const message = err instanceof Error ? err.message : String(err);
58
- return {
59
- isError: true,
60
- content: [{ type: 'text', text: `Tool execution failed: ${message}` }],
61
- };
62
- }
63
- });
64
- const transport = new StdioServerTransport();
65
- await server.connect(transport);
66
- console.error(`[${PACKAGE_NAME}] v${PACKAGE_VERSION} ready · ${tools.length} tools registered`);
12
+ const readOnly = readOnlyFromEnv();
13
+ let client;
14
+ try {
15
+ client = clientFromEnv(apiKey);
16
+ }
17
+ catch (err) {
18
+ // The message never contains the key (see LexAPIClient).
19
+ console.error(`[${PACKAGE_NAME}] ${err instanceof Error ? err.message : 'invalid configuration'} (LEXAPI_API_KEY)`);
20
+ process.exit(1);
21
+ }
22
+ const server = createLexServer(client, { readOnly });
23
+ await server.connect(new StdioServerTransport());
24
+ console.error(`[${PACKAGE_NAME}] v${PACKAGE_VERSION} ready · ${selectTools({ readOnly }).length} tools${readOnly ? ' (read-only)' : ''}`);
@@ -0,0 +1,61 @@
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\".\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\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
+ export declare function clientFromEnv(apiKey: string, env?: NodeJS.ProcessEnv): LexAPIClient;
package/dist/server.js ADDED
@@ -0,0 +1,97 @@
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".
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
+ 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.`;
20
+ export function createLexServer(client, opts = {}) {
21
+ const server = new McpServer({
22
+ name: PACKAGE_NAME,
23
+ title: 'LexAPI',
24
+ version: PACKAGE_VERSION,
25
+ websiteUrl: 'https://lex-api.com',
26
+ }, {
27
+ capabilities: { tools: {} },
28
+ instructions: SERVER_INSTRUCTIONS,
29
+ });
30
+ for (const tool of selectTools(opts))
31
+ registerTool(server, tool, client);
32
+ return server;
33
+ }
34
+ function registerTool(server, tool, client) {
35
+ server.registerTool(tool.name, {
36
+ title: tool.title,
37
+ description: tool.description,
38
+ inputSchema: tool.inputSchema,
39
+ // The tool-level `title` already names it; annotations.title would repeat it.
40
+ annotations: tool.annotations,
41
+ }, async (args, extra) => runTool(tool, args, client, extra));
42
+ }
43
+ export const PROGRESS_INTERVAL_MS = 10_000;
44
+ /**
45
+ * Execute a tool and render its result (or error) as MCP tool content.
46
+ *
47
+ * - The MCP request's abort signal (client cancellation, closed HTTP
48
+ * connection) aborts the upstream LexAPI request.
49
+ * - Timeout: 55 s by default, under the 60 s default request timeout of MCP
50
+ * clients, so the model gets our actionable message rather than the
51
+ * client's generic -32001. A progress token does NOT tell us the client
52
+ * will extend its timeout on progress (TS SDK `resetTimeoutOnProgress`
53
+ * defaults to false), so it does not raise the timeout; LEXAPI_TIMEOUT_MS
54
+ * does, for users who also raised their client's timeout.
55
+ * - With a progress token we still send a heartbeat every 10 s, so clients
56
+ * that DO reset on progress — and UIs showing progress — see the call alive.
57
+ */
58
+ export async function runTool(tool, args, client, extra = {}, opts = {}) {
59
+ const token = extra._meta?.progressToken;
60
+ const timeoutMs = opts.timeoutMs ?? configuredTimeout() ?? DEFAULT_TIMEOUT_MS;
61
+ const callClient = client.forCall({ signal: extra.signal, timeoutMs });
62
+ let heartbeat;
63
+ if (token !== undefined && extra.sendNotification) {
64
+ let n = 0;
65
+ const send = extra.sendNotification;
66
+ heartbeat = setInterval(() => {
67
+ n += 1;
68
+ send({ method: 'notifications/progress', params: { progressToken: token, progress: n, message: 'Waiting for LexAPI…' } }).catch(() => { });
69
+ }, opts.progressIntervalMs ?? PROGRESS_INTERVAL_MS);
70
+ }
71
+ try {
72
+ const result = await tool.handler(args ?? {}, callClient);
73
+ // Compact JSON: indentation costs ~25% more tokens and models read it fine.
74
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
75
+ }
76
+ catch (err) {
77
+ return { isError: true, content: [{ type: 'text', text: describeError(err) }] };
78
+ }
79
+ finally {
80
+ if (heartbeat)
81
+ clearInterval(heartbeat);
82
+ }
83
+ }
84
+ function configuredTimeout(env = process.env) {
85
+ const t = Number.parseInt(env.LEXAPI_TIMEOUT_MS ?? '', 10);
86
+ return Number.isFinite(t) && t >= 5000 ? t : undefined;
87
+ }
88
+ export function readOnlyFromEnv(env = process.env) {
89
+ const v = (env.LEXAPI_MCP_READ_ONLY ?? '').trim().toLowerCase();
90
+ return v === '1' || v === 'true' || v === 'yes';
91
+ }
92
+ export function clientFromEnv(apiKey, env = process.env) {
93
+ return new LexAPIClient({
94
+ apiKey,
95
+ ...(env.LEXAPI_BASE_URL ? { baseUrl: env.LEXAPI_BASE_URL } : {}),
96
+ });
97
+ }
@@ -0,0 +1,61 @@
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
+ /** `02016R0679-20160504` → { base: '32016R0679', date: '2016-05-04' }; null otherwise. */
13
+ export declare function consolidatedBaseOf(celex: unknown): {
14
+ base: string;
15
+ date: string;
16
+ } | null;
17
+ export declare function consolidatedLabel(celex: unknown): Obj | undefined;
18
+ export declare function shapeMetadata(doc: Obj, headers?: LexResponse['headers']): Obj;
19
+ export type View = 'auto' | 'outline' | 'full';
20
+ export interface ContentOptions {
21
+ /** Default 'auto'. 'outline' only when the caller asked for it explicitly. */
22
+ view?: View;
23
+ maxChars: number;
24
+ /** Parts the caller asked for explicitly (API `include`); undefined = all. */
25
+ include?: string[];
26
+ /** Skip this many items (across parts, in order) — paging after truncation. In outline view: articles. */
27
+ offset?: number;
28
+ }
29
+ /**
30
+ * Shape `content` (a document's parsed body) under a character budget.
31
+ * Returns the shaped content plus a note when anything was outlined, split,
32
+ * truncated or omitted.
33
+ */
34
+ export declare function shapeContent(content: unknown, opts: ContentOptions): {
35
+ content?: Obj;
36
+ note?: string;
37
+ };
38
+ /** A full document object (from /documentContent, batch, by-URL) → compact form. */
39
+ export declare function shapeDocument(doc: unknown, headers: LexResponse['headers'], opts: ContentOptions): Obj;
40
+ export declare function shapeSearchResult(r: unknown): Obj;
41
+ export declare function shapeSearch(res: LexResponse<Json>): Obj;
42
+ export declare function shapeRecent(res: LexResponse<Json>): Obj;
43
+ export declare function shapeCaseLawHit(r: unknown): Obj;
44
+ export declare function shapeCaseLaw(res: LexResponse<Json>): Obj;
45
+ export declare function shapeLegislationHit(r: unknown): Obj;
46
+ export declare function shapeLegislation(res: LexResponse<Json>): Obj;
47
+ /**
48
+ * One instruction per class of unresolved hit present. Every unresolved
49
+ * hit carries the LATEST text; what the model should do differs:
50
+ * - not in force on the date → that IS the answer (say so);
51
+ * - transient → retry shortly, or with a smaller limit;
52
+ * - credits → tell the user;
53
+ * - anything else (no text in that version, language, article missing…) →
54
+ * the version in force could not be read; don't quote it as of that date.
55
+ */
56
+ export declare function asOfCaveat(results: Obj[], asOf: string): Obj | undefined;
57
+ export declare function shapeCitedBy(res: LexResponse<Json>): Obj;
58
+ export declare function shapeCites(res: LexResponse<Json>): Obj;
59
+ export declare function shapeNetwork(res: LexResponse<Json>): Obj;
60
+ export declare function stripEnvelope(body: unknown, drop?: string[]): Obj;
61
+ export {};