@lexapi/mcp 0.1.3 → 0.2.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/README.md CHANGED
@@ -1,12 +1,12 @@
1
1
  # LexAPI MCP
2
2
 
3
- [Model Context Protocol](https://modelcontextprotocol.io) server for [LexAPI](https://lex-api.com) — query EUR-Lex, EU case law, and the citation graph from Claude, Cursor, and other MCP-enabled clients.
3
+ [Model Context Protocol](https://modelcontextprotocol.io) server for [LexAPI](https://lex-api.com/?ref=npm-mcp) — query EUR-Lex, EU case law, and the citation graph from Claude, Cursor, and other MCP-enabled clients.
4
4
 
5
5
  Install once, get an API key, and ask your AI assistant: *"summarize Article 17 of the GDPR"* or *"which regulations amend Directive 95/46/EC?"* — the model calls LexAPI directly.
6
6
 
7
7
  ## Install
8
8
 
9
- You'll need a LexAPI API key. Create one for free at [lex-api.com/dashboard](https://lex-api.com/dashboard) (50 calls/day on the FREE tier).
9
+ You'll need a LexAPI API key. Create one for free at [lex-api.com/dashboard](https://lex-api.com/dashboard?ref=npm-mcp) (500 credits/month on the FREE tier, no card required).
10
10
 
11
11
  ### Claude Desktop
12
12
 
@@ -57,7 +57,7 @@ Any client that supports stdio MCP servers can run this. The command is `npx -y
57
57
 
58
58
  | Env var | Default | Purpose |
59
59
  |---|---|---|
60
- | `LEXAPI_API_KEY` | *(required)* | Your API key. Get one at [lex-api.com/dashboard](https://lex-api.com/dashboard). |
60
+ | `LEXAPI_API_KEY` | *(required)* | Your API key. Get one at [lex-api.com/dashboard](https://lex-api.com/dashboard?ref=npm-mcp). |
61
61
  | `LEXAPI_BASE_URL` | `https://lex-api.com/api/v1` | Override for self-hosted or staging. |
62
62
 
63
63
  ## Troubleshooting
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ import { createHttpServer } from './http-server.js';
3
+ const portEnv = process.env.PORT ?? '3000';
4
+ const port = Number.parseInt(portEnv, 10);
5
+ if (!Number.isFinite(port) || port < 1 || port > 65535) {
6
+ console.error(`[lexapi-mcp] invalid PORT: ${portEnv}`);
7
+ process.exit(1);
8
+ }
9
+ const server = createHttpServer();
10
+ server.listen(port, () => {
11
+ console.error(`[lexapi-mcp] HTTP transport listening on :${port} (POST /v1, GET /health)`);
12
+ });
13
+ for (const signal of ['SIGINT', 'SIGTERM']) {
14
+ process.on(signal, () => {
15
+ console.error(`[lexapi-mcp] ${signal} received, shutting down`);
16
+ server.close(() => process.exit(0));
17
+ setTimeout(() => process.exit(1), 10_000).unref();
18
+ });
19
+ }
@@ -0,0 +1,2 @@
1
+ import { type Server as HttpServer } from 'node:http';
2
+ export declare function createHttpServer(): HttpServer;
@@ -0,0 +1,165 @@
1
+ import { createServer } from 'node:http';
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
+ 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';
7
+ import { PACKAGE_VERSION } from './version.js';
8
+ const PACKAGE_NAME = 'lexapi-mcp';
9
+ 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;
16
+ }
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
+ }
25
+ }
26
+ const text = Buffer.concat(chunks).toString('utf8');
27
+ if (!text)
28
+ return undefined;
29
+ return JSON.parse(text);
30
+ }
31
+ function buildMcpServer(apiKey) {
32
+ const baseUrl = process.env.LEXAPI_BASE_URL;
33
+ const client = new LexAPIClient({
34
+ apiKey,
35
+ ...(baseUrl ? { baseUrl } : {}),
36
+ });
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
+ };
72
+ }
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
+ }
79
+ });
80
+ return server;
81
+ }
82
+ function writeJson(res, status, body) {
83
+ res.writeHead(status, {
84
+ 'Content-Type': 'application/json',
85
+ 'Cache-Control': 'no-store, private',
86
+ });
87
+ res.end(JSON.stringify(body));
88
+ }
89
+ async function handleMcp(req, res) {
90
+ const apiKey = extractBearer(req);
91
+ if (!apiKey) {
92
+ writeJson(res, 401, {
93
+ error: {
94
+ code: 'unauthorized',
95
+ message: 'Missing or invalid Authorization header. Send: Authorization: Bearer <your LexAPI key>. Get a key at https://lex-api.com/dashboard.',
96
+ },
97
+ });
98
+ return;
99
+ }
100
+ let body;
101
+ try {
102
+ body = await readJsonBody(req);
103
+ }
104
+ catch (err) {
105
+ const message = err instanceof Error ? err.message : String(err);
106
+ writeJson(res, 400, { error: { code: 'bad_request', message } });
107
+ return;
108
+ }
109
+ // Defense-in-depth headers — Cloudflare + intermediate proxies should not
110
+ // buffer streamed responses, and per-user MCP responses must never be cached.
111
+ res.setHeader('X-Accel-Buffering', 'no');
112
+ res.setHeader('Cache-Control', 'no-store, private');
113
+ const mcpServer = buildMcpServer(apiKey);
114
+ const transport = new StreamableHTTPServerTransport({
115
+ sessionIdGenerator: undefined,
116
+ });
117
+ res.on('close', () => {
118
+ transport.close().catch(() => { });
119
+ mcpServer.close().catch(() => { });
120
+ });
121
+ await mcpServer.connect(transport);
122
+ await transport.handleRequest(req, res, body);
123
+ }
124
+ export function createHttpServer() {
125
+ return createServer(async (req, res) => {
126
+ try {
127
+ // CORS preflight — MCP clients called from browsers need this.
128
+ if (req.method === 'OPTIONS') {
129
+ 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',
133
+ 'Access-Control-Max-Age': '86400',
134
+ });
135
+ res.end();
136
+ return;
137
+ }
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') {
141
+ writeJson(res, 200, {
142
+ status: 'ok',
143
+ name: PACKAGE_NAME,
144
+ version: PACKAGE_VERSION,
145
+ tools: tools.length,
146
+ });
147
+ return;
148
+ }
149
+ if (req.url === MCP_PATH || req.url === MCP_PATH + '/') {
150
+ await handleMcp(req, res);
151
+ return;
152
+ }
153
+ writeJson(res, 404, { error: { code: 'not_found', message: `No route for ${req.method} ${req.url}` } });
154
+ }
155
+ 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 {
161
+ res.end();
162
+ }
163
+ }
164
+ });
165
+ }
package/dist/index.js CHANGED
@@ -4,8 +4,8 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
4
4
  import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
5
5
  import { LexAPIClient, LexAPIError } from './client.js';
6
6
  import { tools, toolsByName } from './tools.js';
7
+ import { PACKAGE_VERSION } from './version.js';
7
8
  const PACKAGE_NAME = 'lexapi-mcp';
8
- const PACKAGE_VERSION = '0.1.3';
9
9
  const apiKey = process.env.LEXAPI_API_KEY;
10
10
  if (!apiKey) {
11
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.`);
@@ -0,0 +1 @@
1
+ export declare const PACKAGE_VERSION: string;
@@ -0,0 +1,9 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ // Read version from package.json at load time so it can't drift from the
5
+ // published version. Works in all deploy shapes: npm tarball, source dev,
6
+ // Docker (dist/ sits next to package.json in every case).
7
+ const pkgPath = join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
8
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
9
+ export const PACKAGE_VERSION = pkg.version;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lexapi/mcp",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "mcpName": "io.github.Lex-API/lexapi-mcp",
5
5
  "description": "Model Context Protocol server for LexAPI — query EUR-Lex and EU case law from Claude, Cursor, and other MCP-enabled clients.",
6
6
  "type": "module",
@@ -17,6 +17,7 @@
17
17
  "build": "tsc",
18
18
  "dev": "tsc --watch",
19
19
  "start": "node dist/index.js",
20
+ "start:http": "node dist/http-entry.js",
20
21
  "clean": "rm -rf dist",
21
22
  "prepublishOnly": "npm run clean && npm run build"
22
23
  },
@@ -51,6 +52,7 @@
51
52
  },
52
53
  "overrides": {
53
54
  "hono": "^4.12.27",
54
- "qs": "^6.15.3"
55
+ "qs": "^6.15.3",
56
+ "body-parser": "^2.3.0"
55
57
  }
56
58
  }