@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
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// Strict classification of the credential an MCP HTTP request carries.
|
|
2
|
+
//
|
|
3
|
+
// The invariant: a value that could be an inbound OAuth access token is
|
|
4
|
+
// NEVER forwarded to LexAPI's REST API, whatever header it arrives in and
|
|
5
|
+
// however it is padded. LexAPI API keys start with `lex_` and never contain
|
|
6
|
+
// a '.', while every JWT does — so a value containing a '.' is never an API
|
|
7
|
+
// key, in either mode.
|
|
8
|
+
/**
|
|
9
|
+
* Longest credential value considered at all. Checked on the value as soon
|
|
10
|
+
* as it is read from its header, BEFORE any routing, so an oversized token can
|
|
11
|
+
* never fall through to the API-key path (both API keys and access tokens
|
|
12
|
+
* are far shorter).
|
|
13
|
+
*/
|
|
14
|
+
export const MAX_CREDENTIAL_LENGTH = 8192;
|
|
15
|
+
/**
|
|
16
|
+
* What counts as an API key when OAuth is on: any `lex_` value made of word characters is accepted as a key (so a
|
|
17
|
+
* mistyped or older key still gets the API's own 401 as before). It can
|
|
18
|
+
* never match a JWT: no '.', no '-', and a JWT starts with `eyJ`.
|
|
19
|
+
*/
|
|
20
|
+
const API_KEY_SHAPE = /^lex_[A-Za-z0-9_]{1,256}$/;
|
|
21
|
+
export function isApiKeyShaped(value) {
|
|
22
|
+
return API_KEY_SHAPE.test(value);
|
|
23
|
+
}
|
|
24
|
+
/** Could be a JWT / JWS (or a fragment of one): API keys never contain a '.'. */
|
|
25
|
+
export function isTokenShaped(value) {
|
|
26
|
+
return value.includes('.');
|
|
27
|
+
}
|
|
28
|
+
const BEARER = /^Bearer\s+(.+?)\s*$/i;
|
|
29
|
+
function header(req, name) {
|
|
30
|
+
const v = req.headers[name];
|
|
31
|
+
return typeof v === 'string' ? v : undefined;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The caller's LexAPI key as 0.3.0 read it: `Authorization: Bearer <key>`,
|
|
35
|
+
* else `x-api-key: <key>`. A value with inner whitespace is returned as-is
|
|
36
|
+
* so it is reported as malformed, not as missing.
|
|
37
|
+
*/
|
|
38
|
+
export function extractApiKey(req) {
|
|
39
|
+
const auth = header(req, 'authorization');
|
|
40
|
+
if (auth !== undefined) {
|
|
41
|
+
const m = auth.match(BEARER);
|
|
42
|
+
if (m)
|
|
43
|
+
return m[1];
|
|
44
|
+
}
|
|
45
|
+
const x = header(req, 'x-api-key');
|
|
46
|
+
if (x !== undefined && x.trim())
|
|
47
|
+
return x.trim();
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* OAuth off: 0.3.0's precedence and key handling, except that a value which
|
|
52
|
+
* is too long or token-shaped is refused instead of being forwarded.
|
|
53
|
+
*
|
|
54
|
+
* OAuth on:
|
|
55
|
+
* - `x-api-key` wins when present; it must be API-key shaped — a JWT (or
|
|
56
|
+
* anything else) there is refused, never forwarded and never exchanged;
|
|
57
|
+
* - `Authorization: Bearer <lex_…>` is an API key;
|
|
58
|
+
* - any other Bearer value is an OAuth access token (garbage is then
|
|
59
|
+
* refused by validation with 401 invalid_token);
|
|
60
|
+
* - the length cap applies before any of this.
|
|
61
|
+
*/
|
|
62
|
+
export function classifyCredential(req, oauthEnabled) {
|
|
63
|
+
const auth = header(req, 'authorization');
|
|
64
|
+
const x = header(req, 'x-api-key');
|
|
65
|
+
if (!oauthEnabled) {
|
|
66
|
+
const bearer = auth === undefined ? null : auth.match(BEARER);
|
|
67
|
+
if (bearer) {
|
|
68
|
+
const key = bearer[1];
|
|
69
|
+
if (key.length > MAX_CREDENTIAL_LENGTH)
|
|
70
|
+
return { kind: 'rejected', header: 'authorization', reason: 'too_long' };
|
|
71
|
+
return isTokenShaped(key) ? { kind: 'rejected', header: 'authorization', reason: 'token_as_api_key' } : { kind: 'apiKey', key };
|
|
72
|
+
}
|
|
73
|
+
if (x !== undefined && x.trim()) {
|
|
74
|
+
const key = x.trim();
|
|
75
|
+
if (key.length > MAX_CREDENTIAL_LENGTH)
|
|
76
|
+
return { kind: 'rejected', header: 'x-api-key', reason: 'too_long' };
|
|
77
|
+
return isTokenShaped(key) ? { kind: 'rejected', header: 'x-api-key', reason: 'token_as_api_key' } : { kind: 'apiKey', key };
|
|
78
|
+
}
|
|
79
|
+
return { kind: 'none' };
|
|
80
|
+
}
|
|
81
|
+
if (x !== undefined && x.trim()) {
|
|
82
|
+
const key = x.trim();
|
|
83
|
+
if (key.length > MAX_CREDENTIAL_LENGTH)
|
|
84
|
+
return { kind: 'rejected', header: 'x-api-key', reason: 'too_long' };
|
|
85
|
+
if (isTokenShaped(key))
|
|
86
|
+
return { kind: 'rejected', header: 'x-api-key', reason: 'token_as_api_key' };
|
|
87
|
+
return isApiKeyShaped(key) ? { kind: 'apiKey', key } : { kind: 'rejected', header: 'x-api-key', reason: 'not_an_api_key' };
|
|
88
|
+
}
|
|
89
|
+
const bearer = auth === undefined ? null : auth.match(BEARER);
|
|
90
|
+
if (bearer) {
|
|
91
|
+
const value = bearer[1];
|
|
92
|
+
if (value.length > MAX_CREDENTIAL_LENGTH)
|
|
93
|
+
return { kind: 'rejected', header: 'authorization', reason: 'too_long' };
|
|
94
|
+
return isApiKeyShaped(value) ? { kind: 'apiKey', key: value } : { kind: 'oauth', token: value };
|
|
95
|
+
}
|
|
96
|
+
return { kind: 'none' };
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* The client address used for per-IP limits. With LEXAPI_MCP_TRUST_PROXY_HOPS
|
|
100
|
+
* = N > 0 the server sits behind N reverse proxies that each append to
|
|
101
|
+
* X-Forwarded-For, so the client is the N-th entry from the right (entries
|
|
102
|
+
* further left are client-controlled and ignored). N = 0: the socket peer.
|
|
103
|
+
*/
|
|
104
|
+
export function deriveClientAddress(req, trustProxyHops) {
|
|
105
|
+
const socketIp = req.socket?.remoteAddress ?? 'unknown';
|
|
106
|
+
const xff = req.headers['x-forwarded-for'];
|
|
107
|
+
const raw = Array.isArray(xff) ? xff.join(',') : xff;
|
|
108
|
+
const hops = raw ? raw.split(',').map((s) => s.trim()).filter(Boolean) : [];
|
|
109
|
+
if (trustProxyHops <= 0)
|
|
110
|
+
return { ip: socketIp, xffEntries: hops.length, short: false };
|
|
111
|
+
if (hops.length < trustProxyHops)
|
|
112
|
+
return { ip: socketIp, xffEntries: hops.length, short: true };
|
|
113
|
+
const ip = hops[hops.length - trustProxyHops];
|
|
114
|
+
return { ip: ip.length <= 64 ? ip : socketIp, xffEntries: hops.length, short: false };
|
|
115
|
+
}
|
|
116
|
+
export function clientIp(req, trustProxyHops) {
|
|
117
|
+
return deriveClientAddress(req, trustProxyHops).ip;
|
|
118
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export declare class LexAPIError extends Error {
|
|
2
|
+
readonly status: number;
|
|
3
|
+
/** Typed `error.code` (e.g. CREDITS_EXHAUSTED) or the legacy slug. */
|
|
4
|
+
readonly code: string;
|
|
5
|
+
readonly details?: unknown | undefined;
|
|
6
|
+
/** Seconds from the `Retry-After` header / `retryAfter` body (429); never set for QUOTA_EXHAUSTED. */
|
|
7
|
+
readonly retryAfterSeconds?: number | undefined;
|
|
8
|
+
/** When an exhausted legacy quota refills (`resetsAt`, else `usage.resetsAt`). */
|
|
9
|
+
readonly resetsAt?: string | undefined;
|
|
10
|
+
constructor(status: number,
|
|
11
|
+
/** Typed `error.code` (e.g. CREDITS_EXHAUSTED) or the legacy slug. */
|
|
12
|
+
code: string, message: string, details?: unknown | undefined,
|
|
13
|
+
/** Seconds from the `Retry-After` header / `retryAfter` body (429); never set for QUOTA_EXHAUSTED. */
|
|
14
|
+
retryAfterSeconds?: number | undefined,
|
|
15
|
+
/** When an exhausted legacy quota refills (`resetsAt`, else `usage.resetsAt`). */
|
|
16
|
+
resetsAt?: string | undefined);
|
|
17
|
+
}
|
|
18
|
+
/** Raised for network failures / timeouts before any HTTP status arrived. */
|
|
19
|
+
export declare class LexAPITransportError extends Error {
|
|
20
|
+
readonly timedOut: boolean;
|
|
21
|
+
readonly cancelled: boolean;
|
|
22
|
+
constructor(message: string, timedOut: boolean, cancelled?: boolean);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The hosted server's OAuth credential could not authenticate a call
|
|
26
|
+
* (token exchange refused / failed, or the API refused the exchanged
|
|
27
|
+
* token). `httpStatus` is what the MCP client is answered when the HTTP
|
|
28
|
+
* response is still uncommitted (src/oauth/upstream.ts); otherwise the
|
|
29
|
+
* model sees describeError's text as a tool error.
|
|
30
|
+
*/
|
|
31
|
+
export type UpstreamAuthKind = 'invalid_token' | 'config' | 'client_auth' | 'unavailable' | 'rate_limited' | 'upstream' | 'api_rejected';
|
|
32
|
+
export declare class UpstreamAuthError extends Error {
|
|
33
|
+
readonly kind: UpstreamAuthKind;
|
|
34
|
+
readonly httpStatus: number;
|
|
35
|
+
/** Token-free reason. */
|
|
36
|
+
readonly description: string;
|
|
37
|
+
readonly retryAfterSeconds?: number | undefined;
|
|
38
|
+
constructor(kind: UpstreamAuthKind, httpStatus: number,
|
|
39
|
+
/** Token-free reason. */
|
|
40
|
+
description: string, retryAfterSeconds?: number | undefined);
|
|
41
|
+
}
|
|
42
|
+
export declare function parseErrorBody(json: unknown, rawText: string, status: number): {
|
|
43
|
+
code: string;
|
|
44
|
+
message: string;
|
|
45
|
+
details?: unknown;
|
|
46
|
+
retryAfter?: number;
|
|
47
|
+
resetsAt?: string;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* The tool-result text for a failed call. Never includes the API key: the
|
|
51
|
+
* key only travels in a request header and is never part of any message.
|
|
52
|
+
*/
|
|
53
|
+
export declare function describeError(err: unknown): string;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
// Error type + the text a model sees when a call fails.
|
|
2
|
+
//
|
|
3
|
+
// LexAPI answers errors in two shapes (docs.md "Errors & retries"):
|
|
4
|
+
// typed: { success: false, error: { code, message, details? } }
|
|
5
|
+
// legacy: { error: "slug or sentence", message?, details?, retryAfter?, upgradeUrl?, usage? }
|
|
6
|
+
// — newer servers also send a top-level `code` (e.g. RATE_LIMITED,
|
|
7
|
+
// QUOTA_EXHAUSTED) and, on quota 429s, a top-level `resetsAt`.
|
|
8
|
+
// We normalise both, then turn the status into a message that says what
|
|
9
|
+
// happened AND what to do next — the model relays it to the user, so it has
|
|
10
|
+
// to be actionable without the model knowing LexAPI's billing rules.
|
|
11
|
+
const DASHBOARD_URL = 'https://lex-api.com/dashboard?ref=mcp';
|
|
12
|
+
const PRICING_URL = 'https://lex-api.com/pricing?ref=mcp';
|
|
13
|
+
export class LexAPIError extends Error {
|
|
14
|
+
status;
|
|
15
|
+
code;
|
|
16
|
+
details;
|
|
17
|
+
retryAfterSeconds;
|
|
18
|
+
resetsAt;
|
|
19
|
+
constructor(status,
|
|
20
|
+
/** Typed `error.code` (e.g. CREDITS_EXHAUSTED) or the legacy slug. */
|
|
21
|
+
code, message, details,
|
|
22
|
+
/** Seconds from the `Retry-After` header / `retryAfter` body (429); never set for QUOTA_EXHAUSTED. */
|
|
23
|
+
retryAfterSeconds,
|
|
24
|
+
/** When an exhausted legacy quota refills (`resetsAt`, else `usage.resetsAt`). */
|
|
25
|
+
resetsAt) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.status = status;
|
|
28
|
+
this.code = code;
|
|
29
|
+
this.details = details;
|
|
30
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
31
|
+
this.resetsAt = resetsAt;
|
|
32
|
+
this.name = 'LexAPIError';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** Raised for network failures / timeouts before any HTTP status arrived. */
|
|
36
|
+
export class LexAPITransportError extends Error {
|
|
37
|
+
timedOut;
|
|
38
|
+
cancelled;
|
|
39
|
+
constructor(message, timedOut, cancelled = false) {
|
|
40
|
+
super(message);
|
|
41
|
+
this.timedOut = timedOut;
|
|
42
|
+
this.cancelled = cancelled;
|
|
43
|
+
this.name = 'LexAPITransportError';
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export class UpstreamAuthError extends Error {
|
|
47
|
+
kind;
|
|
48
|
+
httpStatus;
|
|
49
|
+
description;
|
|
50
|
+
retryAfterSeconds;
|
|
51
|
+
constructor(kind, httpStatus,
|
|
52
|
+
/** Token-free reason. */
|
|
53
|
+
description, retryAfterSeconds) {
|
|
54
|
+
super(description);
|
|
55
|
+
this.kind = kind;
|
|
56
|
+
this.httpStatus = httpStatus;
|
|
57
|
+
this.description = description;
|
|
58
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
59
|
+
this.name = 'UpstreamAuthError';
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export function parseErrorBody(json, rawText, status) {
|
|
63
|
+
const fallback = { code: `HTTP_${status}`, message: rawText.trim().slice(0, 300) || `HTTP ${status}` };
|
|
64
|
+
if (!json || typeof json !== 'object' || Array.isArray(json))
|
|
65
|
+
return fallback;
|
|
66
|
+
const j = json;
|
|
67
|
+
const retryAfter = typeof j.retryAfter === 'number' ? j.retryAfter : undefined;
|
|
68
|
+
// A top-level string `code` beats the legacy `error` text.
|
|
69
|
+
const topCode = typeof j.code === 'string' && j.code ? j.code : undefined;
|
|
70
|
+
const usage = j.usage && typeof j.usage === 'object' ? j.usage : undefined;
|
|
71
|
+
const resetsAt = typeof j.resetsAt === 'string' ? j.resetsAt
|
|
72
|
+
: usage && typeof usage.resetsAt === 'string' ? usage.resetsAt
|
|
73
|
+
: undefined;
|
|
74
|
+
// National error bodies carry `jurisdiction` (and, for a withdrawn
|
|
75
|
+
// document, also `id` and `withdrawnAt`) as plain top-level siblings of
|
|
76
|
+
// `error`/`code`/`message`,
|
|
77
|
+
// never nested in `details` — the document-id 404, the 409
|
|
78
|
+
// NATIONAL_SEMANTIC_NOT_ENABLED and 503 NATIONAL_SEMANTIC_UNAVAILABLE
|
|
79
|
+
// bodies, the per-jurisdiction 403 tier gate, and the citation routes' 410
|
|
80
|
+
// DOCUMENT_WITHDRAWN all do this. Fall back to it only when nothing else
|
|
81
|
+
// supplied a details object, so it never shadows a real one.
|
|
82
|
+
const strayFields = {};
|
|
83
|
+
if (typeof j.jurisdiction === 'string')
|
|
84
|
+
strayFields.jurisdiction = j.jurisdiction;
|
|
85
|
+
if (typeof j.id === 'string')
|
|
86
|
+
strayFields.id = j.id;
|
|
87
|
+
if (typeof j.withdrawnAt === 'string')
|
|
88
|
+
strayFields.withdrawnAt = j.withdrawnAt;
|
|
89
|
+
// The citation routes' legacy 400 INVALID_PARAMS names the parameter and
|
|
90
|
+
// its allowed values at the top level; the national-terms 403 its acceptUrl.
|
|
91
|
+
if (typeof j.param === 'string')
|
|
92
|
+
strayFields.param = j.param;
|
|
93
|
+
if (Array.isArray(j.allowed))
|
|
94
|
+
strayFields.allowed = j.allowed;
|
|
95
|
+
if (typeof j.acceptUrl === 'string')
|
|
96
|
+
strayFields.acceptUrl = j.acceptUrl;
|
|
97
|
+
// National semantic 503/422: why the search could not be completed.
|
|
98
|
+
if (typeof j.partialReason === 'string')
|
|
99
|
+
strayFields.partialReason = j.partialReason;
|
|
100
|
+
const jurisdictionFallback = Object.keys(strayFields).length ? strayFields : undefined;
|
|
101
|
+
const e = j.error;
|
|
102
|
+
if (e && typeof e === 'object' && !Array.isArray(e)) {
|
|
103
|
+
const eo = e;
|
|
104
|
+
return {
|
|
105
|
+
code: typeof eo.code === 'string' ? eo.code : (topCode ?? fallback.code),
|
|
106
|
+
message: typeof eo.message === 'string' ? eo.message
|
|
107
|
+
: typeof j.message === 'string' ? j.message
|
|
108
|
+
: fallback.message,
|
|
109
|
+
details: eo.details ?? j.details ?? jurisdictionFallback,
|
|
110
|
+
retryAfter,
|
|
111
|
+
resetsAt,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
// Legacy: `error` is a short sentence ("Invalid API key"), `message` the detail.
|
|
115
|
+
const errStr = typeof e === 'string' ? e : undefined;
|
|
116
|
+
const msg = typeof j.message === 'string' ? j.message : undefined;
|
|
117
|
+
return {
|
|
118
|
+
code: topCode ?? errStr ?? fallback.code,
|
|
119
|
+
message: errStr && msg ? `${errStr}: ${msg}` : (msg ?? errStr ?? fallback.message),
|
|
120
|
+
details: j.details ?? j.usage ?? jurisdictionFallback,
|
|
121
|
+
retryAfter,
|
|
122
|
+
resetsAt,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
function detailsLine(details) {
|
|
126
|
+
if (details === undefined || details === null)
|
|
127
|
+
return '';
|
|
128
|
+
if (Array.isArray(details)) {
|
|
129
|
+
const items = details.map((d) => (typeof d === 'string' ? d : JSON.stringify(d))).slice(0, 10);
|
|
130
|
+
return items.length ? ` Details: ${items.join('; ')}.` : '';
|
|
131
|
+
}
|
|
132
|
+
if (typeof details === 'object')
|
|
133
|
+
return ` Details: ${JSON.stringify(details)}.`;
|
|
134
|
+
return ` Details: ${String(details)}.`;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* The tool-result text for a failed call. Never includes the API key: the
|
|
138
|
+
* key only travels in a request header and is never part of any message.
|
|
139
|
+
*/
|
|
140
|
+
export function describeError(err) {
|
|
141
|
+
if (err instanceof LexAPITransportError) {
|
|
142
|
+
if (err.cancelled)
|
|
143
|
+
return 'Cancelled: the client cancelled this request before LexAPI answered.';
|
|
144
|
+
return err.timedOut
|
|
145
|
+
? `LexAPI did not answer in time (${err.message}). Live EUR-Lex fetches can take longer than an MCP client waits; the call is safe to retry once, and a repeat may be served from the LexAPI corpus. If it keeps timing out, narrow the request (fewer pages, a smaller limit) or raise the client's tool timeout (Claude Code: MCP_TOOL_TIMEOUT) and LEXAPI_TIMEOUT_MS.`
|
|
146
|
+
: `Could not reach LexAPI (${err.message}). Check network access to lex-api.com (or LEXAPI_BASE_URL) and retry.`;
|
|
147
|
+
}
|
|
148
|
+
if (err instanceof UpstreamAuthError) {
|
|
149
|
+
switch (err.kind) {
|
|
150
|
+
case 'invalid_token':
|
|
151
|
+
return `LexAPI sign-in expired or was revoked (${err.description}). The user must reconnect LexAPI in their MCP client (sign in again); retrying with the same sign-in will not help.`;
|
|
152
|
+
case 'rate_limited':
|
|
153
|
+
return `LexAPI sign-in is rate limited right now.${err.retryAfterSeconds !== undefined ? ` Wait ${err.retryAfterSeconds} s before calling again.` : ' Wait a little before calling again.'}`;
|
|
154
|
+
case 'upstream':
|
|
155
|
+
return `LexAPI sign-in could not be checked right now (${err.description}). Retry in a minute; if it persists, status is at https://lex-api.com/status.`;
|
|
156
|
+
case 'api_rejected':
|
|
157
|
+
return `LexAPI refused this connection's access (${err.description}). Ask the user to disconnect and reconnect LexAPI in their MCP client; if that does not help, contact support@lex-api.com.`;
|
|
158
|
+
default:
|
|
159
|
+
return `LexAPI sign-in is temporarily unavailable on this server (${err.kind}). This is not the user's fault and signing in again will not help; retry later or use an API key (https://lex-api.com/dashboard?ref=mcp).`;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (!(err instanceof LexAPIError)) {
|
|
163
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
164
|
+
return `Tool execution failed: ${message}`;
|
|
165
|
+
}
|
|
166
|
+
const head = `LexAPI error ${err.status} (${err.code}): ${err.message.trim().replace(/[.\s]+$/, '')}.`;
|
|
167
|
+
const d = (err.details && typeof err.details === 'object' && !Array.isArray(err.details))
|
|
168
|
+
? err.details
|
|
169
|
+
: undefined;
|
|
170
|
+
switch (err.status) {
|
|
171
|
+
case 400:
|
|
172
|
+
return `${head}${detailsLine(err.details)} The request was rejected before any work was done and its credits were refunded. Fix the arguments and call again.`;
|
|
173
|
+
case 401:
|
|
174
|
+
return `${head} The LexAPI API key is missing, wrong, or revoked. Ask the user to check the key configured for this MCP server (LEXAPI_API_KEY, or the Authorization header for the hosted server) or create a new one at ${DASHBOARD_URL}.`;
|
|
175
|
+
case 402: {
|
|
176
|
+
// The monthly allowance of national-law calls for FREE/STARTER/
|
|
177
|
+
// PROFESSIONAL plans — a separate counter from the
|
|
178
|
+
// credit pool, so the usual "buy a top-up" advice does not apply.
|
|
179
|
+
if (err.code === 'NATIONAL_ALLOWANCE_EXHAUSTED') {
|
|
180
|
+
const parts = [];
|
|
181
|
+
if (d) {
|
|
182
|
+
if (typeof d.limit === 'number')
|
|
183
|
+
parts.push(`the monthly allowance is ${d.limit} national-law calls`);
|
|
184
|
+
if (typeof d.resetsAt === 'string')
|
|
185
|
+
parts.push(`it resets at ${d.resetsAt} (start of next UTC month)`);
|
|
186
|
+
}
|
|
187
|
+
return `${head}${parts.length ? ` (${parts.join(', ')}).` : ''} This is the account's monthly allowance of national-law calls on its plan, not the LexAPI credit pool — a top-up does not help. Tell the user: wait for the reset, or upgrade to BUSINESS or higher, which has no separate national-law limit (${DASHBOARD_URL}, plans: ${PRICING_URL}). Do not retry this call unchanged.`;
|
|
188
|
+
}
|
|
189
|
+
const parts = [];
|
|
190
|
+
if (d) {
|
|
191
|
+
if (typeof d.weight === 'number')
|
|
192
|
+
parts.push(`this call needs ${d.weight} credits`);
|
|
193
|
+
if (typeof d.available === 'number')
|
|
194
|
+
parts.push(`${d.available} are available`);
|
|
195
|
+
if (typeof d.resetsAt === 'string')
|
|
196
|
+
parts.push(`the monthly pool resets at ${d.resetsAt}`);
|
|
197
|
+
}
|
|
198
|
+
return `${head}${parts.length ? ` (${parts.join(', ')}).` : ''} The account's monthly LexAPI credit pool is exhausted. Tell the user: they can wait for the reset, buy a top-up pack or upgrade at ${DASHBOARD_URL} (plans: ${PRICING_URL}). Cheaper calls may still succeed (e.g. lex_resolve or lex_cites cost 1 credit); do not retry this call unchanged.`;
|
|
199
|
+
}
|
|
200
|
+
case 403:
|
|
201
|
+
if (err.code === 'NATIONAL_TERMS_NOT_ACCEPTED') {
|
|
202
|
+
const url = d && typeof d.acceptUrl === 'string' ? ` (${d.acceptUrl})` : '';
|
|
203
|
+
return `${head} The account must accept the national-source terms once in the LexAPI dashboard${url} before national documents are served. Tell the user; retrying before that will not help. Nothing was charged.`;
|
|
204
|
+
}
|
|
205
|
+
return `${head} The account's plan or subscription does not allow this call (not a temporary error — do not retry). Tell the user which feature was refused; plans are compared at ${PRICING_URL}.`;
|
|
206
|
+
case 404: {
|
|
207
|
+
// National 404s take three shapes, none of which point at lex_resolve
|
|
208
|
+
// or lex_search (both EU-only): the typed document-id miss (`details:
|
|
209
|
+
// {id, jurisdiction}`, via the jurisdiction fallback above), the
|
|
210
|
+
// citation-graph id guard (`{"error": "Document not found: <ID>"}`,
|
|
211
|
+
// no code/jurisdiction at all), and a country that is not live yet
|
|
212
|
+
// (falls through every route to the generic `apiNotFound` handler's
|
|
213
|
+
// "Unknown API endpoint" 404 — the jurisdiction path segment never
|
|
214
|
+
// matched, which for a country code can only mean it is unlaunched).
|
|
215
|
+
const isNational = (d && typeof d.jurisdiction === 'string')
|
|
216
|
+
|| /^Document not found:/i.test(err.message)
|
|
217
|
+
|| /Unknown API endpoint/i.test(err.message);
|
|
218
|
+
if (isNational) {
|
|
219
|
+
// "Unknown API endpoint" is the generic 404 for ANY unmatched route,
|
|
220
|
+
// not only an unlaunched country — these tools only ever build
|
|
221
|
+
// known routes, so that's the near-certain cause here, but the
|
|
222
|
+
// hedge keeps the message honest if that ever changes.
|
|
223
|
+
return `${head} Not retryable as-is. Likely either the country is not live yet (call lex_national_coverage to check) or the id is wrong (call lex_list_national_documents) — or the route itself is wrong.`;
|
|
224
|
+
}
|
|
225
|
+
return `${head} Not retryable as-is. Check the identifier (lex_resolve turns URLs, ELIs and ECLIs into CELEX numbers; lex_search finds documents by title).`;
|
|
226
|
+
}
|
|
227
|
+
case 409:
|
|
228
|
+
// National semantic search not yet enabled for a live country
|
|
229
|
+
// (nationalSemanticController.js unavailableError): a different
|
|
230
|
+
// country, not account state — do not say "tell the user to retry
|
|
231
|
+
// their account", point at the right tools instead.
|
|
232
|
+
if (err.code === 'NATIONAL_SEMANTIC_NOT_ENABLED') {
|
|
233
|
+
const jur = d && typeof d.jurisdiction === 'string' ? d.jurisdiction : 'this country';
|
|
234
|
+
return `${head} Semantic search is not available for ${jur} yet — check semanticSearch in lex_national_coverage's output before retrying. lex_list_national_documents and lex_get_national_document still work there. Not retryable; nothing was charged.`;
|
|
235
|
+
}
|
|
236
|
+
return `${head} The account's current state does not allow this action; tell the user (it is not fixed by retrying).`;
|
|
237
|
+
case 503:
|
|
238
|
+
// National semantic index temporarily down (same source as 409 above).
|
|
239
|
+
if (err.code === 'NATIONAL_SEMANTIC_UNAVAILABLE') {
|
|
240
|
+
const jur = d && typeof d.jurisdiction === 'string' ? d.jurisdiction : 'This country';
|
|
241
|
+
// The index could not complete this search and had nothing left to
|
|
242
|
+
// return: an empty answer would not have meant "no matches".
|
|
243
|
+
if (d && d.partialReason === 'SEARCH_INCOMPLETE') {
|
|
244
|
+
const wait = err.retryAfterSeconds;
|
|
245
|
+
return wait !== undefined
|
|
246
|
+
? `${head} ${jur}'s national semantic index could not complete this search and had nothing to return — this is NOT a "no matches" answer; nothing was charged. Retry in ${wait} s.`
|
|
247
|
+
: `${head} ${jur}'s national semantic index has repeatedly been unable to complete this search — this is NOT a "no matches" answer; nothing was charged. Do not retry right away: try again later, or rephrase or narrow the query.`;
|
|
248
|
+
}
|
|
249
|
+
return `${head} ${jur}'s national semantic index is temporarily unavailable; nothing was charged. Retry later, with backoff.`;
|
|
250
|
+
}
|
|
251
|
+
// lex_counterparts past its server-side budget (legacy shape, refunded).
|
|
252
|
+
if (err.code === 'TIMEOUT') {
|
|
253
|
+
return `${head} The lookup ran out of its server-side time budget; nothing was charged. Narrow it with jurisdictions, or retry later.`;
|
|
254
|
+
}
|
|
255
|
+
return `${head} LexAPI had a server error; server failures are refunded. Retry once; if it persists, status is at https://lex-api.com/status.`;
|
|
256
|
+
case 422:
|
|
257
|
+
// The national index cannot search this slice completely and had
|
|
258
|
+
// nothing left to return; the same request gets the same answer.
|
|
259
|
+
if (err.code === 'NATIONAL_SEMANTIC_FILTER_UNREACHABLE') {
|
|
260
|
+
const jur = d && typeof d.jurisdiction === 'string' ? d.jurisdiction : 'this country';
|
|
261
|
+
return `${head} The national semantic index for ${jur} cannot search this slice (country, document kind, filters) completely and had nothing to return — this is NOT a "no matches" answer; nothing was charged. Retrying the same call will not help: rephrase the query, or change or drop the filters.`;
|
|
262
|
+
}
|
|
263
|
+
return `${head}${detailsLine(err.details)}`;
|
|
264
|
+
case 429: {
|
|
265
|
+
const wait = err.retryAfterSeconds;
|
|
266
|
+
const resetsAt = err.resetsAt ?? (d && typeof d.resetsAt === 'string' ? d.resetsAt : undefined);
|
|
267
|
+
// QUOTA_EXHAUSTED is a used-up legacy quota, whatever
|
|
268
|
+
// else the response carries. Fallback for older servers: the per-minute
|
|
269
|
+
// limiter sends Retry-After / retryAfter, the legacy quotas (daily
|
|
270
|
+
// calls, monthly semantic searches) send neither — only usage.resetsAt.
|
|
271
|
+
// Retrying a quota before it refills is pointless.
|
|
272
|
+
if (err.code === 'QUOTA_EXHAUSTED' || (wait === undefined && (resetsAt || /quota/i.test(`${err.code} ${err.message}`)))) {
|
|
273
|
+
const which = /semantic/i.test(err.message)
|
|
274
|
+
? 'the monthly semantic-search quota of this (legacy) plan'
|
|
275
|
+
: /daily/i.test(err.message)
|
|
276
|
+
? 'the daily call quota of this (legacy) plan'
|
|
277
|
+
: 'a usage quota of this plan';
|
|
278
|
+
return `${head} This is ${which}, not a per-minute limit: it is exhausted${resetsAt ? ` until ${resetsAt}` : ''} — do not retry, tell the user. Moving to a credit plan (${PRICING_URL}) removes the quota.`;
|
|
279
|
+
}
|
|
280
|
+
return `${head} Per-minute rate limit of the API key reached.${wait !== undefined ? ` Wait ${wait} s before calling again.` : ' Wait about a minute before calling again.'} Avoid parallel calls; a higher plan raises the per-minute limit (${PRICING_URL}).`;
|
|
281
|
+
}
|
|
282
|
+
case 410: {
|
|
283
|
+
// A national document its source withdrew — a
|
|
284
|
+
// takedown, a pseudonymisation fix, a robots.txt listing. Served
|
|
285
|
+
// nowhere: no title, no metadata, no text. Two shapes carry it: the
|
|
286
|
+
// typed envelope (lex_get_national_document, details nested) and the
|
|
287
|
+
// legacy shape (citation tools, id/jurisdiction/withdrawnAt as
|
|
288
|
+
// top-level siblings via the fallback above) — `d` covers either.
|
|
289
|
+
if (err.code === 'DOCUMENT_WITHDRAWN') {
|
|
290
|
+
const parts = [];
|
|
291
|
+
if (d) {
|
|
292
|
+
if (typeof d.id === 'string')
|
|
293
|
+
parts.push(`id ${d.id}`);
|
|
294
|
+
if (typeof d.jurisdiction === 'string')
|
|
295
|
+
parts.push(`jurisdiction ${d.jurisdiction}`);
|
|
296
|
+
if (typeof d.withdrawnAt === 'string')
|
|
297
|
+
parts.push(`withdrawn ${d.withdrawnAt}`);
|
|
298
|
+
}
|
|
299
|
+
return `${head}${parts.length ? ` (${parts.join(', ')}).` : ''} This document was withdrawn by its source and LexAPI serves nothing of it — not even the title. Gone for good, not a temporary failure: do not retry. If you or the user were holding a cached copy, drop it — a withdrawal can be a legal takedown or a pseudonymisation fix, and keeping or re-deriving the content (including trying to identify who it was about) would defeat that. Nothing was charged.`;
|
|
300
|
+
}
|
|
301
|
+
return `${head} Gone. Not retryable; nothing was charged.`;
|
|
302
|
+
}
|
|
303
|
+
case 502:
|
|
304
|
+
return `${head} An upstream service (EUR-Lex or the semantic index) returned an error. Retry later; failed calls are refunded.`;
|
|
305
|
+
case 504:
|
|
306
|
+
return `${head} The upstream fetch timed out. Retry-safe — retry once, or narrow the request (fewer pages, a smaller limit). Failed searches are refunded.`;
|
|
307
|
+
default:
|
|
308
|
+
if (err.status >= 500) {
|
|
309
|
+
return `${head} LexAPI had a server error; server failures are refunded. Retry once; if it persists, status is at https://lex-api.com/status.`;
|
|
310
|
+
}
|
|
311
|
+
return `${head}${detailsLine(err.details)}`;
|
|
312
|
+
}
|
|
313
|
+
}
|
package/dist/http-entry.js
CHANGED
|
@@ -6,9 +6,26 @@ if (!Number.isFinite(port) || port < 1 || port > 65535) {
|
|
|
6
6
|
console.error(`[lexapi-mcp] invalid PORT: ${portEnv}`);
|
|
7
7
|
process.exit(1);
|
|
8
8
|
}
|
|
9
|
-
|
|
9
|
+
let server;
|
|
10
|
+
try {
|
|
11
|
+
server = createHttpServer();
|
|
12
|
+
}
|
|
13
|
+
catch (err) {
|
|
14
|
+
// A half-configured OAuth env (a short secret, OAuth variables without the
|
|
15
|
+
// secret, an API base off the issuer's origin …) must fail the deploy, not
|
|
16
|
+
// silently run without sign-in. The message never contains the secret.
|
|
17
|
+
console.error(`[lexapi-mcp] invalid configuration: ${err instanceof Error ? err.message : 'error'}`);
|
|
18
|
+
process.exit(1);
|
|
19
|
+
}
|
|
10
20
|
server.listen(port, () => {
|
|
11
|
-
|
|
21
|
+
const o = server.oauth?.cfg;
|
|
22
|
+
console.error(`[lexapi-mcp] HTTP transport listening on :${port} (POST ${o?.resourcePath ?? '/v1'}, GET /health) · auth: API keys${o ? ` + OAuth (issuer ${o.issuer}, resource ${o.resource}, client ${o.clientId}, API ${o.apiBase})` : ' only (OAuth off: LEXAPI_OAUTH_CLIENT_SECRET not set)'}`);
|
|
23
|
+
if (o) {
|
|
24
|
+
console.error(`[lexapi-mcp] OAuth: client address for per-IP limits = ${server.clientAddressMode}${o.trustProxyHops ? '' : ' — behind a reverse proxy that is the proxy for everyone; set LEXAPI_MCP_TRUST_PROXY_HOPS (verify with the /health operator view)'}`);
|
|
25
|
+
console.error(`[lexapi-mcp] OAuth: at most ${o.exchangesPerUserPerMin} new token exchanges per user a minute (LEXAPI_MCP_EXCHANGES_PER_USER_PER_MIN)`);
|
|
26
|
+
}
|
|
27
|
+
const healthToken = Boolean(process.env.LEXAPI_MCP_HEALTH_TOKEN?.trim());
|
|
28
|
+
console.error(`[lexapi-mcp] /health operator view: ${!healthToken ? 'off (set LEXAPI_MCP_HEALTH_TOKEN to enable)' : o ? 'on (LEXAPI_MCP_HEALTH_TOKEN)' : 'nothing to show (LEXAPI_MCP_HEALTH_TOKEN set, OAuth off)'}`);
|
|
12
29
|
});
|
|
13
30
|
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
14
31
|
process.on(signal, () => {
|
package/dist/http-server.d.ts
CHANGED
|
@@ -1,2 +1,48 @@
|
|
|
1
|
-
import { type Server as HttpServer } from 'node:http';
|
|
2
|
-
|
|
1
|
+
import { type IncomingMessage, type Server as HttpServer } from 'node:http';
|
|
2
|
+
import { type OAuthConfig } from './oauth/config.js';
|
|
3
|
+
import { TokenExchanger } from './oauth/exchange.js';
|
|
4
|
+
import { JwksCache } from './oauth/jwt.js';
|
|
5
|
+
/**
|
|
6
|
+
* SSE keep-alive of the OAuth transport, pinned (the SDK default could
|
|
7
|
+
* change). Together with the first progress frame (PROGRESS_INTERVAL_MS) it
|
|
8
|
+
* commits the 200; a token exchange is bounded below both
|
|
9
|
+
* (EXCHANGE_DEADLINE_MS), so its refusal is still answered as an HTTP status.
|
|
10
|
+
*/
|
|
11
|
+
export declare const SSE_KEEP_ALIVE_MS = 15000;
|
|
12
|
+
export { classifyCredential, extractApiKey, type Credential } from './credentials.js';
|
|
13
|
+
/**
|
|
14
|
+
* Origin validation (MCP Streamable HTTP: servers MUST validate Origin, a
|
|
15
|
+
* DNS-rebinding defence). Requests without an Origin header — every
|
|
16
|
+
* non-browser MCP client — are allowed. A browser request is allowed only
|
|
17
|
+
* when its Origin is listed in LEXAPI_MCP_ALLOWED_ORIGINS (comma-separated;
|
|
18
|
+
* "*" allows any). Auth is a bearer key with no ambient credentials, so this
|
|
19
|
+
* is defence in depth, not the access control.
|
|
20
|
+
*/
|
|
21
|
+
export declare function originAllowed(origin: string | undefined, env?: NodeJS.ProcessEnv): boolean;
|
|
22
|
+
/** The OAuth half of the hosted server: config + JWKS cache + token exchanger (shared by all requests). */
|
|
23
|
+
export interface OAuthRuntime {
|
|
24
|
+
cfg: OAuthConfig;
|
|
25
|
+
jwks: JwksCache;
|
|
26
|
+
exchanger: TokenExchanger;
|
|
27
|
+
}
|
|
28
|
+
export declare function createOAuthRuntime(cfg: OAuthConfig, fetchImpl?: typeof fetch): OAuthRuntime;
|
|
29
|
+
/** `oauthAlerts.proxyHopsMismatch` stays set this long after the last mismatched request, then clears by itself. */
|
|
30
|
+
export declare const PROXY_MISMATCH_ALERT_MS: number;
|
|
31
|
+
export declare const MIN_HEALTH_TOKEN_LENGTH = 32;
|
|
32
|
+
/** The request the MCP layer sees: no credential headers (exported for tests). */
|
|
33
|
+
export declare function toWebRequest(req: IncomingMessage): Request;
|
|
34
|
+
export interface HttpServerOptions {
|
|
35
|
+
/** Defaults to process.env. */
|
|
36
|
+
env?: NodeJS.ProcessEnv;
|
|
37
|
+
/**
|
|
38
|
+
* OAuth configuration: undefined → from env (oauthConfigFromEnv, throws
|
|
39
|
+
* OAuthConfigError on a half-configured env), null → OAuth off.
|
|
40
|
+
*/
|
|
41
|
+
oauth?: OAuthConfig | null;
|
|
42
|
+
/** Injected for tests: every outbound request (JWKS, token exchange, LexAPI on OAuth requests). */
|
|
43
|
+
fetch?: typeof fetch;
|
|
44
|
+
}
|
|
45
|
+
export declare function createHttpServer(opts?: HttpServerOptions): HttpServer & {
|
|
46
|
+
oauth: OAuthRuntime | null;
|
|
47
|
+
clientAddressMode: string;
|
|
48
|
+
};
|