@pipeworx/mcp-tw-law 0.1.0 → 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
@@ -5,7 +5,7 @@ the Ministry of Justice's own official English translation where one exists
5
5
  — searchable by title, resolvable by exact citation, and readable one
6
6
  provision at a time.
7
7
 
8
- Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 1815+ live data sources. This is an independent, unofficial integration — not affiliated with, endorsed by, or published by the upstream provider.
8
+ Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 1857+ live data sources. This is an independent, unofficial integration — not affiliated with, endorsed by, or published by the upstream provider.
9
9
 
10
10
  ## Tools
11
11
 
@@ -115,7 +115,7 @@ directly, instead of just this one's:
115
115
  }
116
116
  ```
117
117
 
118
- Both URLs reach the same gateway and the same 1815+ data sources. The
118
+ Both URLs reach the same gateway and the same 1857+ data sources. The
119
119
  only difference is which pack's tools are listed **directly**; `ask_pipeworx`
120
120
  reaches all of them from either one.
121
121
 
@@ -129,10 +129,12 @@ curl -X POST https://gateway.pipeworx.io/v1/tools/tw_law_search \
129
129
 
130
130
  No account needed for the first calls. Inspect any tool: `GET https://gateway.pipeworx.io/v1/tools/tw_law_search`. Find one: `POST https://gateway.pipeworx.io/v1/tools/search_packs` with `{"query":"..."}`.
131
131
 
132
- ## Standalone (no gateway account)
132
+ ## Run it from npm
133
133
 
134
- This package also runs as a local stdio MCP server — no Pipeworx account, no
135
- gateway round-trip:
134
+ `@pipeworx/mcp-tw-law` is a local stdio bridge to the Pipeworx gateway: your MCP client
135
+ starts it with `npx`, and it forwards every call to the same
136
+ `https://gateway.pipeworx.io/tw-law/mcp` endpoint shown above. It needs network access;
137
+ there is no offline mode.
136
138
 
137
139
  ```json
138
140
  {
@@ -145,15 +147,18 @@ gateway round-trip:
145
147
  }
146
148
  ```
147
149
 
148
- Or run it directly to confirm it starts:
150
+ Without a key it calls anonymously, capped at 50 calls a day. A free account
151
+ raises that to 200 a day: get a key at https://pipeworx.io/signup and add
152
+ `"env": { "PIPEWORX_API_KEY": "<your key>" }` to the server entry.
153
+ The key is sent as a Bearer token, the same way a hosted connection sends it,
154
+ so calls are metered and billed exactly as they are there.
149
155
 
150
- ```bash
151
- npx -y @pipeworx/mcp-tw-law
152
- ```
156
+ It lists **only** this pack's tools by default. Set `PIPEWORX_META_TOOLS=1` to
157
+ also list `ask_pipeworx` and the other gateway-wide tools.
153
158
 
154
- It speaks MCP over stdin/stdout and answers `initialize`/`tools/list`/`tools/call`
155
- for **only** this pack's tools — none of the shared meta-tools the gateway
156
- connection above adds. Same source, same tools, no ask_pipeworx routing.
159
+ Behind an HTTPS proxy: Node's built-in `fetch` does not read `HTTPS_PROXY` by
160
+ default. Newer Node releases honour it when `NODE_USE_ENV_PROXY=1` is set; check
161
+ your Node version's documentation.
157
162
 
158
163
  ## Using with ask_pipeworx
159
164
 
package/bin/cli.js CHANGED
@@ -1,17 +1,61 @@
1
1
  #!/usr/bin/env node
2
+ // Entry point for `npx @pipeworx/mcp-<slug>` in gateway mode (bin/cli.js).
2
3
  //
3
- // Entry point for `npx @pipeworx/mcp-<slug>`.
4
+ // A stdio MCP server that relays every message to the Pipeworx gateway's
5
+ // /<slug>/mcp endpoint -- fleet #3759, docs/standalone-via-gateway-plan.md.
6
+ // It carries no pack code and has no local mode. The relay itself lives in
7
+ // ../lib/index.js (copied from scripts/templates/standalone-gateway-lib.js);
8
+ // this file only owns stdin/stdout.
4
9
  //
5
- // Packs ship as raw TypeScript (no build step — see publish-pack.sh for why:
6
- // tsx sidesteps every extensionless-import / bare-JSON-import edge case a
7
- // per-pack tsc build would have to solve one pack at a time). This file
8
- // registers tsx's ESM loader programmatically, then hands off to src/server.ts,
9
- // which wraps the pack's {tools, callTool} export in a stdio MCP server.
10
+ // Copied VERBATIM into every gateway-mode package by scripts/publish-pack.sh.
11
+ // Edit scripts/templates/standalone-gateway-cli.js in the monorepo, never a
12
+ // per-pack copy. Zero dependencies, Node 18+.
10
13
  //
11
- // Copied verbatim into every published pack repo by scripts/publish-pack.sh —
12
- // edit this file, not a per-pack copy.
13
- import { register } from 'tsx/esm/api';
14
+ // stdout carries newline-delimited JSON-RPC and nothing else; every diagnostic
15
+ // goes to stderr, because a single stray line on stdout breaks the host's
16
+ // parser.
17
+ import { createInterface } from 'node:readline';
18
+ import { relay, bridgeConfig } from '../lib/index.js';
14
19
 
15
- register();
20
+ const cfg = bridgeConfig();
21
+ const warn = (line) => process.stderr.write(`${line}\n`);
22
+ const write = (msg) => { if (msg) process.stdout.write(`${JSON.stringify(msg)}\n`); };
16
23
 
17
- await import('../src/server.ts');
24
+ const pending = new Set();
25
+ function track(p) {
26
+ pending.add(p);
27
+ p.finally(() => pending.delete(p));
28
+ }
29
+
30
+ async function handleLine(line) {
31
+ const text = line.trim();
32
+ if (!text) return;
33
+ let message;
34
+ try {
35
+ message = JSON.parse(text);
36
+ } catch {
37
+ write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
38
+ return;
39
+ }
40
+ // A JSON-RPC batch: relay each member, answer with the non-notification replies.
41
+ if (Array.isArray(message)) {
42
+ const replies = (await Promise.all(message.map((m) => relay(m, { cfg, warn })))).filter(Boolean);
43
+ if (replies.length) write(replies);
44
+ return;
45
+ }
46
+ write(await relay(message, { cfg, warn }));
47
+ }
48
+
49
+ // Requests are handled concurrently and answered as they finish: JSON-RPC ids
50
+ // let the host match them, and a slow tool call must not hold up a ping.
51
+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
52
+ rl.on('line', (line) => {
53
+ track(handleLine(line).catch((err) => warn(`pipeworx-standalone: ${err && err.stack ? err.stack : err}`)));
54
+ });
55
+ rl.on('close', async () => {
56
+ // stdin closed: finish what is in flight, then exit.
57
+ while (pending.size) await Promise.allSettled([...pending]);
58
+ // Exit only once stdout has flushed: on a pipe that is not synchronous
59
+ // everywhere, and a bare exit can drop the last reply.
60
+ process.stdout.write('', () => process.exit(0));
61
+ });
package/lib/index.js ADDED
@@ -0,0 +1,333 @@
1
+ // @pipeworx/mcp-<slug> -- library half of the gateway bridge (lib/index.js).
2
+ //
3
+ // Copied VERBATIM into every gateway-mode pack package by scripts/publish-pack.sh
4
+ // (fleet #3759, docs/standalone-via-gateway-plan.md section 1). There is no
5
+ // per-pack templating: the slug and version are read from this package's own
6
+ // package.json (`pipeworx.slug`, `version`) at load time, so the same bytes
7
+ // ship in every package and the source hash can cover them once. Edit this
8
+ // file in the monorepo (scripts/templates/standalone-gateway-lib.js), never a
9
+ // per-pack copy.
10
+ //
11
+ // What it is: a relay. Every JSON-RPC message goes to
12
+ // ${PIPEWORX_GATEWAY_URL:-https://gateway.pipeworx.io}/<slug>/mcp, the same
13
+ // endpoint a hosted MCP client uses, so tiers, rate limits and credits apply
14
+ // exactly as they do there. There is no local mode: the pack's code is not in
15
+ // this package.
16
+ //
17
+ // Zero dependencies, plain ESM, Node 18+ (global fetch). Nothing here writes
18
+ // to stdout -- bin/cli.js owns stdout and it carries JSON-RPC only.
19
+ //
20
+ // Environment:
21
+ // PIPEWORX_API_KEY sent as `Authorization: Bearer <key>`. Never as
22
+ // X-API-Key: the gateway reads a pwx_ key sent that way
23
+ // as an unvalidated BYO string with no account.
24
+ // PIPEWORX_GATEWAY_URL gateway base URL (no path), default the public gateway.
25
+ // PIPEWORX_META_TOOLS=1 list the gateway-wide tools (ask_pipeworx, ...) too.
26
+ // PIPEWORX_TIMEOUT_MS per-request timeout, default 120000.
27
+
28
+ import { readFileSync } from 'node:fs';
29
+
30
+ const readJson = (rel) => JSON.parse(readFileSync(new URL(rel, import.meta.url), 'utf8'));
31
+
32
+ const PKG = readJson('../package.json');
33
+ export const SLUG = PKG.pipeworx && PKG.pipeworx.slug;
34
+ if (typeof SLUG !== 'string' || !/^[a-z0-9][a-z0-9_-]*$/.test(SLUG)) {
35
+ throw new Error(`${PKG.name}: package.json carries no valid pipeworx.slug -- this package was built wrong`);
36
+ }
37
+ /**
38
+ * The pack's slug on the GATEWAY: the /<slug>/mcp route and the `_meta.pack`
39
+ * every listed tool carries. Usually the same as `slug` (the npm/directory
40
+ * name), but 14 packs differ -- `hex-pm` is `hex_pm` on the gateway -- and
41
+ * filtering tools/list on the npm slug would match none of their tools
42
+ * (fleet #3761). publish-pack.sh stamps it from the gateway manifest.
43
+ */
44
+ export const GATEWAY_SLUG = (PKG.pipeworx && PKG.pipeworx.gatewaySlug) || SLUG;
45
+ if (typeof GATEWAY_SLUG !== 'string' || !/^[a-z0-9][a-z0-9_-]*$/.test(GATEWAY_SLUG)) {
46
+ throw new Error(`${PKG.name}: package.json carries an invalid pipeworx.gatewaySlug -- this package was built wrong`);
47
+ }
48
+ export const PACKAGE_NAME = PKG.name;
49
+ export const VERSION = PKG.version;
50
+
51
+ /** The pack's own tool definitions at publish time (the offline tools/list answer). */
52
+ export const tools = readJson('../tools.json');
53
+
54
+ const DEFAULT_GATEWAY = 'https://gateway.pipeworx.io';
55
+ const DEFAULT_TIMEOUT_MS = 120_000;
56
+ const SIGNUP_URL = 'https://pipeworx.io/signup';
57
+ const VIA = '(via pipeworx-standalone)';
58
+
59
+ /** Resolve the bridge's settings. Exported for the tests and for callTool. */
60
+ export function bridgeConfig(env = process.env, overrides = {}) {
61
+ const base = String(overrides.gatewayUrl || env.PIPEWORX_GATEWAY_URL || DEFAULT_GATEWAY).trim().replace(/\/+$/, '');
62
+ const apiKey = String(overrides.apiKey ?? env.PIPEWORX_API_KEY ?? '').trim();
63
+ const t = Number(overrides.timeoutMs ?? env.PIPEWORX_TIMEOUT_MS);
64
+ return {
65
+ endpoint: `${base}/${GATEWAY_SLUG}/mcp`,
66
+ apiKey,
67
+ timeoutMs: Number.isFinite(t) && t > 0 ? t : DEFAULT_TIMEOUT_MS,
68
+ metaTools: (overrides.metaTools ?? env.PIPEWORX_META_TOOLS) === '1' || overrides.metaTools === true,
69
+ };
70
+ }
71
+
72
+ function requestHeaders(cfg) {
73
+ const h = {
74
+ 'Content-Type': 'application/json',
75
+ Accept: 'application/json',
76
+ // Stable per package version: the gateway remembers a client's name by
77
+ // identifier + User-Agent (workers/gateway/src/client-identity.ts).
78
+ 'User-Agent': `pipeworx-standalone/${VERSION} (${PACKAGE_NAME})`,
79
+ // Analytics label only (blob11 = 'standalone'). It never changes tier,
80
+ // limits or price -- anyone can send it.
81
+ 'X-Pipeworx-Surface': 'standalone',
82
+ };
83
+ if (cfg.apiKey) h.Authorization = `Bearer ${cfg.apiKey}`;
84
+ return h;
85
+ }
86
+
87
+ /** Parse a gateway body: JSON, or the last JSON `data:` frame of an SSE stream. */
88
+ function parseBody(text, contentType) {
89
+ if (/text\/event-stream/i.test(contentType || '')) {
90
+ let last = null;
91
+ for (const line of text.split(/\r?\n/)) {
92
+ if (!line.startsWith('data:')) continue;
93
+ try { last = JSON.parse(line.slice(5).trim()); } catch { /* keep-alive or partial frame */ }
94
+ }
95
+ return last;
96
+ }
97
+ try { return JSON.parse(text); } catch { return null; }
98
+ }
99
+
100
+ /**
101
+ * POST one JSON-RPC message. Never throws: the outcome is one of
102
+ * { kind: 'http', status, headers, body, text } the gateway answered
103
+ * { kind: 'network', detail } DNS, TLS, refused, reset
104
+ * { kind: 'timeout' } no answer in cfg.timeoutMs
105
+ */
106
+ export async function postToGateway(message, cfg) {
107
+ const ac = new AbortController();
108
+ const timer = setTimeout(() => ac.abort(), cfg.timeoutMs);
109
+ try {
110
+ const res = await fetch(cfg.endpoint, {
111
+ method: 'POST',
112
+ headers: requestHeaders(cfg),
113
+ body: JSON.stringify(message),
114
+ signal: ac.signal,
115
+ });
116
+ const text = await res.text();
117
+ return { kind: 'http', status: res.status, headers: res.headers, body: parseBody(text, res.headers.get('content-type')), text };
118
+ } catch (err) {
119
+ if (ac.signal.aborted || (err && (err.name === 'AbortError' || err.name === 'TimeoutError'))) return { kind: 'timeout' };
120
+ const cause = err && err.cause;
121
+ const detail = (cause && (cause.code || cause.message)) || (err && err.message) || String(err);
122
+ return { kind: 'network', detail };
123
+ } finally {
124
+ clearTimeout(timer);
125
+ }
126
+ }
127
+
128
+ // ── The key-not-accepted warning (one per process) ──────────────────
129
+
130
+ let warnedKeyIgnored = false;
131
+ const KEY_IGNORED = 'PIPEWORX_API_KEY was not accepted, calling anonymously.';
132
+
133
+ /** True when a key was sent but the gateway still served the call as anonymous. */
134
+ function keyIgnored(out, cfg) {
135
+ return !!cfg.apiKey && out.kind === 'http' && (out.headers.get('x-ratelimit-tier') || '').toLowerCase() === 'anonymous';
136
+ }
137
+
138
+ function noteTier(out, cfg, warn) {
139
+ if (!keyIgnored(out, cfg) || warnedKeyIgnored) return;
140
+ warnedKeyIgnored = true;
141
+ warn(`${PACKAGE_NAME}: ${KEY_IGNORED} Check the key at ${SIGNUP_URL}.`);
142
+ }
143
+
144
+ /** Test hook: forget that the warning was printed. */
145
+ export function _resetWarnings() { warnedKeyIgnored = false; }
146
+
147
+ // ── Results the host shows to the model ─────────────────────────────
148
+
149
+ function errorResult(text, detail) {
150
+ const result = { content: [{ type: 'text', text }], isError: true };
151
+ if (detail) result._meta = { pipeworx_standalone: detail };
152
+ return result;
153
+ }
154
+
155
+ const rpcResult = (id, result) => ({ jsonrpc: '2.0', id, result });
156
+ const rpcError = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
157
+
158
+ function firstLine(text) {
159
+ const line = String(text || '').split(/\r?\n/).map((l) => l.trim()).find(Boolean) || '(empty body)';
160
+ return line.length > 200 ? `${line.slice(0, 200)}...` : line;
161
+ }
162
+
163
+ function unreachableText(cfg, out) {
164
+ if (out.kind === 'timeout') {
165
+ return `The Pipeworx gateway at ${cfg.endpoint} did not answer within ${Math.round(cfg.timeoutMs / 1000)}s, so this call timed out. `
166
+ + `${PACKAGE_NAME} forwards every call to the Pipeworx gateway and has no local mode. Try again; a call that keeps timing out is worth reporting.`;
167
+ }
168
+ return `Could not reach the Pipeworx gateway at ${cfg.endpoint} (${out.detail}). `
169
+ + `${PACKAGE_NAME} forwards every call to the Pipeworx gateway and has no local mode, so it needs network access.`;
170
+ }
171
+
172
+ function isAuthRequired(body) {
173
+ return !!body && (body.error_code === 'authentication_required'
174
+ || (body.error && body.error.data && body.error.data.reason === 'authentication_required'));
175
+ }
176
+
177
+ /** Map a tools/call outcome to the JSON-RPC response the host gets. */
178
+ function toolsCallResponse(id, out, cfg) {
179
+ if (out.kind !== 'http') return rpcResult(id, errorResult(unreachableText(cfg, out), { reason: out.kind }));
180
+ const { status, body } = out;
181
+
182
+ // Anonymous daily cap: the gateway answers 401 with a JSON-RPC error whose
183
+ // message is the offer. Hosts often swallow protocol errors, so hand it over
184
+ // as a tool result the model actually reads.
185
+ if (status === 401 && isAuthRequired(body)) {
186
+ const data = (body.error && body.error.data) || {};
187
+ const parts = [body.error && body.error.message ? body.error.message : 'The anonymous daily allowance is used up.'];
188
+ if (data.resets_at) parts.push(`The anonymous allowance resets at ${data.resets_at}.`);
189
+ parts.push(cfg.apiKey
190
+ ? `${KEY_IGNORED} Check the key, or get a free one at ${SIGNUP_URL}.`
191
+ : `To keep going now, set PIPEWORX_API_KEY in this MCP server's environment; a free key is at ${SIGNUP_URL}.`);
192
+ return rpcResult(id, errorResult(parts.join('\n\n'), { status, reason: 'authentication_required', resets_at: data.resets_at ?? null }));
193
+ }
194
+
195
+ // A keyed tier over its cap: today the gateway answers 429 with a RESULT
196
+ // that has no isError, which reads as a success (fleet #3760). Mark it.
197
+ if (status === 429 && body && body.result && typeof body.result === 'object') {
198
+ const result = { ...body.result, isError: true };
199
+ if (cfg.apiKey && keyIgnored(out, cfg)) {
200
+ result.content = [...(Array.isArray(result.content) ? result.content : []), { type: 'text', text: KEY_IGNORED }];
201
+ }
202
+ return rpcResult(id, result);
203
+ }
204
+ if ((status === 401 || status === 429) && body && body.error) {
205
+ const extra = keyIgnored(out, cfg) ? ` ${KEY_IGNORED}` : '';
206
+ return rpcResult(id, errorResult(`${body.error.message || `HTTP ${status}`}${extra}`, { status }));
207
+ }
208
+
209
+ // A real JSON-RPC answer (result or protocol error): relay it verbatim,
210
+ // structuredContent and _meta (cost, tier, provenance) included.
211
+ if (body && body.jsonrpc === '2.0' && (body.result !== undefined || body.error !== undefined) && status < 500) {
212
+ return { ...body, id };
213
+ }
214
+
215
+ // 5xx, an HTML edge page, or anything else that is not JSON-RPC.
216
+ return rpcResult(id, errorResult(`The Pipeworx gateway returned HTTP ${status}: ${firstLine(out.text)}`, { status }));
217
+ }
218
+
219
+ function localInitialize(params) {
220
+ return {
221
+ protocolVersion: (params && params.protocolVersion) || '2025-06-18',
222
+ capabilities: { tools: {} },
223
+ serverInfo: { name: PACKAGE_NAME, version: VERSION },
224
+ };
225
+ }
226
+
227
+ const scopedInstructions = () =>
228
+ `${PACKAGE_NAME} forwards to the Pipeworx gateway and lists only the ${SLUG} pack's tools. `
229
+ + 'Set PIPEWORX_META_TOOLS=1 to also list ask_pipeworx and the other gateway-wide tools.';
230
+
231
+ /** `<host name> (via pipeworx-standalone)`. The slug stays OUT of the name: the
232
+ * gateway's scanner-name check substring-matches words like poll/watch/index. */
233
+ export function bridgedClientName(name) {
234
+ const n = typeof name === 'string' && name.trim() ? name.trim() : 'unknown';
235
+ return n.includes(VIA) ? n : `${n} ${VIA}`;
236
+ }
237
+
238
+ /**
239
+ * Relay one JSON-RPC message to the gateway and return the response to write
240
+ * back, or null for a notification. Never throws.
241
+ *
242
+ * @param {object} message a parsed JSON-RPC request or notification
243
+ * @param {{cfg?: object, warn?: (line: string) => void}} [opts]
244
+ */
245
+ export async function relay(message, opts = {}) {
246
+ const cfg = opts.cfg || bridgeConfig();
247
+ const warn = opts.warn || ((line) => process.stderr.write(`${line}\n`));
248
+ if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0' || typeof message.method !== 'string') {
249
+ const id = message && typeof message === 'object' && 'id' in message ? message.id : null;
250
+ return rpcError(id ?? null, -32600, 'Invalid Request');
251
+ }
252
+ const isNotification = !('id' in message) || message.id === undefined;
253
+ const id = message.id;
254
+
255
+ if (isNotification) {
256
+ const out = await postToGateway(message, cfg);
257
+ if (out.kind !== 'http') warn(`${PACKAGE_NAME}: notification ${message.method} not delivered: ${unreachableText(cfg, out)}`);
258
+ return null;
259
+ }
260
+
261
+ if (message.method === 'initialize') {
262
+ const params = { ...(message.params || {}) };
263
+ params.clientInfo = { ...(params.clientInfo || {}), name: bridgedClientName(params.clientInfo && params.clientInfo.name) };
264
+ if (!params.clientInfo.version) params.clientInfo.version = '0';
265
+ const out = await postToGateway({ ...message, params }, cfg);
266
+ noteTier(out, cfg, warn);
267
+ if (out.kind === 'http' && out.body && out.body.result && typeof out.body.result === 'object') {
268
+ const result = { ...out.body.result, serverInfo: { name: PACKAGE_NAME, version: VERSION } };
269
+ if (!cfg.metaTools) result.instructions = scopedInstructions();
270
+ return rpcResult(id, result);
271
+ }
272
+ // The host must still start: answer locally and let the calls report the
273
+ // gateway problem when they happen.
274
+ warn(`${PACKAGE_NAME}: initialize answered locally -- ${out.kind === 'http' ? `gateway HTTP ${out.status}` : unreachableText(cfg, out)}`);
275
+ return rpcResult(id, { ...localInitialize(message.params), instructions: scopedInstructions() });
276
+ }
277
+
278
+ if (message.method === 'tools/list') {
279
+ const out = await postToGateway(message, cfg);
280
+ noteTier(out, cfg, warn);
281
+ const listed = out.kind === 'http' && out.body && out.body.result && Array.isArray(out.body.result.tools)
282
+ ? out.body.result : null;
283
+ if (listed) {
284
+ if (cfg.metaTools) return rpcResult(id, listed);
285
+ const own = listed.tools.filter((t) => t && t._meta && (t._meta.pack === GATEWAY_SLUG || t._meta.pack === SLUG));
286
+ if (own.length > 0) return rpcResult(id, { ...listed, tools: own });
287
+ warn(`${PACKAGE_NAME}: the gateway listed no ${SLUG} tools; serving the tool list bundled with this package`);
288
+ } else {
289
+ warn(`${PACKAGE_NAME}: tools/list served from the snapshot bundled with this package -- ${out.kind === 'http' ? `gateway HTTP ${out.status}` : unreachableText(cfg, out)}`);
290
+ }
291
+ return rpcResult(id, { tools });
292
+ }
293
+
294
+ if (message.method === 'tools/call') {
295
+ const out = await postToGateway(message, cfg);
296
+ noteTier(out, cfg, warn);
297
+ return toolsCallResponse(id, out, cfg);
298
+ }
299
+
300
+ // Everything else (ping, resources/*, prompts/*, ...): relay as-is.
301
+ const out = await postToGateway(message, cfg);
302
+ noteTier(out, cfg, warn);
303
+ if (out.kind === 'http' && out.body && out.body.jsonrpc === '2.0') return { ...out.body, id };
304
+ if (message.method === 'ping') return rpcResult(id, {});
305
+ return rpcError(id, -32603, out.kind === 'http'
306
+ ? `The Pipeworx gateway returned HTTP ${out.status}: ${firstLine(out.text)}`
307
+ : unreachableText(cfg, out));
308
+ }
309
+
310
+ /**
311
+ * Call one of this pack's tools through the gateway -- the `{tools, callTool}`
312
+ * shape earlier versions of this package exported. Resolves with the tool's
313
+ * structured result; rejects with the gateway's message on any error.
314
+ *
315
+ * @param {string} name
316
+ * @param {Record<string, unknown>} [args]
317
+ * @param {{apiKey?: string, gatewayUrl?: string, timeoutMs?: number}} [opts]
318
+ * apiKey defaults to process.env.PIPEWORX_API_KEY.
319
+ */
320
+ export async function callTool(name, args = {}, opts = {}) {
321
+ const cfg = bridgeConfig(process.env, opts);
322
+ const res = await relay({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, { cfg });
323
+ if (res.error) throw new Error(res.error.message);
324
+ const result = res.result || {};
325
+ const text = Array.isArray(result.content)
326
+ ? result.content.filter((c) => c && c.type === 'text').map((c) => c.text).join('\n')
327
+ : '';
328
+ if (result.isError) throw new Error(text || `${name} failed`);
329
+ if (result.structuredContent !== undefined) return result.structuredContent;
330
+ try { return JSON.parse(text); } catch { return text; }
331
+ }
332
+
333
+ export default { tools, callTool };
package/package.json CHANGED
@@ -1,32 +1,33 @@
1
1
  {
2
2
  "name": "@pipeworx/mcp-tw-law",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "tw-law — Taiwan national statutes and the Constitution, in Chinese plus the Ministry of Justice's own official English translations where one exists, from the Ministry of Justice Laws & Regulations Database (全國法規資料庫). Fleet #3129.",
5
5
  "type": "module",
6
- "main": "src/index.ts",
7
- "types": "src/index.ts",
6
+ "main": "lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./tools.json": "./tools.json",
10
+ "./package.json": "./package.json"
11
+ },
8
12
  "bin": {
9
13
  "mcp-tw-law": "bin/cli.js"
10
14
  },
15
+ "files": ["bin/", "lib/", "tools.json", "server.json"],
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
11
19
  "keywords": ["mcp", "mcp-server", "model-context-protocol", "pipeworx", "tw-law"],
12
20
  "license": "MIT",
13
21
  "repository": {
14
22
  "type": "git",
15
23
  "url": "git+https://github.com/pipeworx-io/mcp-tw-law.git"
16
24
  },
17
- "scripts": {
18
- "typecheck": "tsc --noEmit"
19
- },
20
- "dependencies": {
21
- "@modelcontextprotocol/sdk": "^1.30.0",
22
- "tsx": "^4.19.0"
23
- },
24
- "devDependencies": {
25
- "typescript": "^5.9.3",
26
- "@cloudflare/workers-types": "^4.20260405.1"
27
- },
25
+ "mcpName": "io.github.pipeworx-io/tw-law",
28
26
  "pipeworx": {
29
- "sourceHash": "v1-93f7e951839b7103df727620fff2c2dd9349d7ec823117325ece1c28e2bfcafd",
30
- "sourceCommit": "fe38188882d0fe91e5a45d82b7b989b4aae1e8b6"
27
+ "mode": "gateway",
28
+ "slug": "tw-law",
29
+ "gatewaySlug": "tw-law",
30
+ "sourceHash": "v1-bb03e0a55c3a85636f48efead2fcf80019e28a76db649bda8c5fcc57d05a486d",
31
+ "sourceCommit": "f47d581679e1e887373df51ba623f891fbe4c464"
31
32
  }
32
33
  }
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "io.github.pipeworx-io/tw-law",
4
4
  "title": "Tw Law",
5
5
  "description": "tw-law — Taiwan national statutes and the Constitution, in Chinese plus the Ministry of Justice's…",
6
- "version": "0.1.0",
6
+ "version": "0.2.0",
7
7
  "websiteUrl": "https://pipeworx.io/packs/tw-law",
8
8
  "repository": {
9
9
  "url": "https://github.com/pipeworx-io/mcp-tw-law",
package/tools.json ADDED
@@ -0,0 +1,88 @@
1
+ [
2
+ {
3
+ "name": "tw_law_search",
4
+ "description": "Search Taiwan national statutes and the Constitution by TITLE keyword, Chinese or English — \"個人資料保護法\", \"Personal Data Protection\", \"民法\", \"Civil Code\". This is a title search, not full-text; it will not find a law by a phrase appearing only inside an article. Returns each match's pcode (for tw_law_info/tw_law_article), Chinese and English titles, law level, category, whether an official English translation exists, and the last amendment date. Source: Taiwan Ministry of Justice, Laws & Regulations Database.",
5
+ "inputSchema": {
6
+ "type": "object",
7
+ "properties": {
8
+ "query": {
9
+ "type": "string",
10
+ "description": "Title keyword, Chinese or English, e.g. \"個人資料保護法\" or \"Personal Data Protection Act\"."
11
+ },
12
+ "limit": {
13
+ "type": "number",
14
+ "description": "Max laws to return (1-50, default 10)."
15
+ }
16
+ },
17
+ "required": [
18
+ "query"
19
+ ]
20
+ }
21
+ },
22
+ {
23
+ "name": "tw_law_info",
24
+ "description": "Resolve a Taiwan law to its full metadata by pcode (from tw_law_search) or an exact/partial Chinese or English title — the exact-citation step before reading an article. Returns the law's level (法律/憲法), category, official English title if one exists, whether it has been abolished, the LAST AMENDMENT date and the date that amendment TAKES/TOOK LEGAL EFFECT as separate fields (Taiwan statutes can be amended on one date and take effect on another, sometimes \"to be set later by the Executive Yuan\" — flagged as effective_date_pending), the full promulgation history (in Chinese, and in English when the law has an official translation), and the article count. Source: Taiwan Ministry of Justice, Laws & Regulations Database.",
25
+ "inputSchema": {
26
+ "type": "object",
27
+ "properties": {
28
+ "pcode": {
29
+ "type": "string",
30
+ "description": "The law's pcode, e.g. \"I0050021\" (from tw_law_search)."
31
+ },
32
+ "name": {
33
+ "type": "string",
34
+ "description": "Chinese or English law title, exact or partial, used when pcode is not known."
35
+ }
36
+ }
37
+ }
38
+ },
39
+ {
40
+ "name": "tw_law_toc",
41
+ "description": "Table of contents for one Taiwan law: its chapter/section headings and the article number of every provision, in order, paged. Use to browse a law's structure before reading a specific article with tw_law_article, or to enumerate every article number a long law has. Returns has_more and next_offset when the law has more entries than the page size.",
42
+ "inputSchema": {
43
+ "type": "object",
44
+ "properties": {
45
+ "pcode": {
46
+ "type": "string",
47
+ "description": "The law's pcode (from tw_law_search or tw_law_info)."
48
+ },
49
+ "name": {
50
+ "type": "string",
51
+ "description": "Chinese or English law title, used when pcode is not known."
52
+ },
53
+ "offset": {
54
+ "type": "number",
55
+ "description": "Pagination offset (default 0)."
56
+ },
57
+ "limit": {
58
+ "type": "number",
59
+ "description": "Max entries to return (1-500, default 200)."
60
+ }
61
+ }
62
+ }
63
+ },
64
+ {
65
+ "name": "tw_law_article",
66
+ "description": "Full text of ONE article (條) of a Taiwan law, by pcode or title plus article number in any spelling — \"2\", \"第 2 條\", \"Article 2\", \"第 6-1 條\", \"Article 6-1\". Returns the Chinese text and, when the Ministry has published an official English translation of that law, the official English text of the SAME article, labelled official (never a machine translation) — plus the chapter/section heading it falls under. A long law is never returned whole; use tw_law_toc to find article numbers, and call this once per article.",
67
+ "inputSchema": {
68
+ "type": "object",
69
+ "properties": {
70
+ "pcode": {
71
+ "type": "string",
72
+ "description": "The law's pcode (from tw_law_search or tw_law_info)."
73
+ },
74
+ "name": {
75
+ "type": "string",
76
+ "description": "Chinese or English law title, used when pcode is not known."
77
+ },
78
+ "article": {
79
+ "type": "string",
80
+ "description": "Article number, any spelling: \"2\", \"第 2 條\", \"Article 2\", \"6-1\"."
81
+ }
82
+ },
83
+ "required": [
84
+ "article"
85
+ ]
86
+ }
87
+ }
88
+ ]
package/src/index.ts DELETED
@@ -1,223 +0,0 @@
1
- interface McpToolDefinition {
2
- name: string;
3
- description: string;
4
- /** Human-facing one-liner (fleet #1967). Optional; consumers fall back to
5
- * description. Kept in step with shared/src/types.ts — scripts/lib/
6
- * check-inlined-types.mjs reports drift at publish time. */
7
- summary?: string;
8
- inputSchema: {
9
- type: 'object';
10
- properties: Record<string, unknown>;
11
- required?: string[];
12
- anyOf?: Array<{ required: string[] }>;
13
- oneOf?: Array<{ required: string[] }>;
14
- allOf?: Array<{ required: string[] }>;
15
- };
16
- outputSchema?: Record<string, unknown>;
17
- }
18
-
19
- interface McpToolExport {
20
- tools: McpToolDefinition[];
21
- callTool: (name: string, args: Record<string, unknown>) => Promise<unknown>;
22
- meter?: { credits: number };
23
- cost?: Record<string, unknown>;
24
- provider?: string;
25
- }
26
-
27
- /**
28
- * tw-law — Taiwan national statutes and the Constitution, in Chinese plus
29
- * the Ministry of Justice's own official English translations where one
30
- * exists, from the Ministry of Justice Laws & Regulations Database
31
- * (全國法規資料庫). Fleet #3129.
32
- *
33
- * The source publishes its whole catalog only as two bulk JSON exports (no
34
- * per-law or per-article live route — verified 2026-10-15), so this pack
35
- * reads from a D1 copy loaded and refreshed by scripts/tw-law/load-data.mjs,
36
- * per Bruce's 2026-09-23 local-copy ruling. See src/store.ts for the licence
37
- * and the full load path.
38
- *
39
- * Every response carries `source` and `data_as_of` (when the load last ran).
40
- * Every English field is the Ministry's OWN translation, tied to the exact
41
- * Chinese law/article it translates, and labelled official — never a
42
- * machine translation.
43
- */
44
- import {
45
- type D1Like,
46
- dataAsOf,
47
- getArticle,
48
- getHeadingBefore,
49
- getLaw,
50
- getToc,
51
- requireDb,
52
- searchLaws,
53
- shapeLaw,
54
- SOURCE,
55
- } from './store.js';
56
-
57
- const tools: McpToolExport['tools'] = [
58
- {
59
- name: 'tw_law_search',
60
- description:
61
- 'Search Taiwan national statutes and the Constitution by TITLE keyword, Chinese or English — "個人資料保護法", "Personal Data Protection", "民法", "Civil Code". This is a title search, not full-text; it will not find a law by a phrase appearing only inside an article. Returns each match\'s pcode (for tw_law_info/tw_law_article), Chinese and English titles, law level, category, whether an official English translation exists, and the last amendment date. Source: Taiwan Ministry of Justice, Laws & Regulations Database.',
62
- summary: 'Find a Taiwan law by title (Chinese or English).',
63
- inputSchema: {
64
- type: 'object' as const,
65
- properties: {
66
- query: { type: 'string', description: 'Title keyword, Chinese or English, e.g. "個人資料保護法" or "Personal Data Protection Act".' },
67
- limit: { type: 'number', description: 'Max laws to return (1-50, default 10).' },
68
- },
69
- required: ['query'],
70
- },
71
- },
72
- {
73
- name: 'tw_law_info',
74
- description:
75
- 'Resolve a Taiwan law to its full metadata by pcode (from tw_law_search) or an exact/partial Chinese or English title — the exact-citation step before reading an article. Returns the law\'s level (法律/憲法), category, official English title if one exists, whether it has been abolished, the LAST AMENDMENT date and the date that amendment TAKES/TOOK LEGAL EFFECT as separate fields (Taiwan statutes can be amended on one date and take effect on another, sometimes "to be set later by the Executive Yuan" — flagged as effective_date_pending), the full promulgation history (in Chinese, and in English when the law has an official translation), and the article count. Source: Taiwan Ministry of Justice, Laws & Regulations Database.',
76
- summary: "One Taiwan law's metadata: level, category, amendment vs. effective dates, repeal status, promulgation history.",
77
- inputSchema: {
78
- type: 'object' as const,
79
- properties: {
80
- pcode: { type: 'string', description: 'The law\'s pcode, e.g. "I0050021" (from tw_law_search).' },
81
- name: { type: 'string', description: 'Chinese or English law title, exact or partial, used when pcode is not known.' },
82
- },
83
- },
84
- },
85
- {
86
- name: 'tw_law_toc',
87
- description:
88
- 'Table of contents for one Taiwan law: its chapter/section headings and the article number of every provision, in order, paged. Use to browse a law\'s structure before reading a specific article with tw_law_article, or to enumerate every article number a long law has. Returns has_more and next_offset when the law has more entries than the page size.',
89
- summary: "A Taiwan law's chapter structure and article numbers, paged.",
90
- inputSchema: {
91
- type: 'object' as const,
92
- properties: {
93
- pcode: { type: 'string', description: 'The law\'s pcode (from tw_law_search or tw_law_info).' },
94
- name: { type: 'string', description: 'Chinese or English law title, used when pcode is not known.' },
95
- offset: { type: 'number', description: 'Pagination offset (default 0).' },
96
- limit: { type: 'number', description: 'Max entries to return (1-500, default 200).' },
97
- },
98
- },
99
- },
100
- {
101
- name: 'tw_law_article',
102
- description:
103
- 'Full text of ONE article (條) of a Taiwan law, by pcode or title plus article number in any spelling — "2", "第 2 條", "Article 2", "第 6-1 條", "Article 6-1". Returns the Chinese text and, when the Ministry has published an official English translation of that law, the official English text of the SAME article, labelled official (never a machine translation) — plus the chapter/section heading it falls under. A long law is never returned whole; use tw_law_toc to find article numbers, and call this once per article.',
104
- summary: 'One article of a Taiwan law, Chinese plus the official English translation when one exists.',
105
- inputSchema: {
106
- type: 'object' as const,
107
- properties: {
108
- pcode: { type: 'string', description: 'The law\'s pcode (from tw_law_search or tw_law_info).' },
109
- name: { type: 'string', description: 'Chinese or English law title, used when pcode is not known.' },
110
- article: { type: 'string', description: 'Article number, any spelling: "2", "第 2 條", "Article 2", "6-1".' },
111
- },
112
- required: ['article'],
113
- },
114
- },
115
- ];
116
-
117
- function clamp(v: unknown, lo: number, hi: number, d: number): number {
118
- const n = Math.floor(Number(v));
119
- return Number.isFinite(n) && n > 0 ? Math.min(hi, Math.max(lo, n)) : d;
120
- }
121
-
122
- async function resolvePcode(db: D1Like, args: Record<string, unknown>): Promise<string> {
123
- const pcode = args.pcode != null ? String(args.pcode).trim() : '';
124
- const name = args.name != null ? String(args.name).trim() : '';
125
- if (!pcode && !name) throw new Error('Provide either "pcode" (from tw_law_search) or "name" (a Chinese or English law title).');
126
- const law = await getLaw(db, { pcode: pcode || undefined, name: name || undefined });
127
- if (!law) throw new Error(`No Taiwan law found for ${pcode ? `pcode "${pcode}"` : `name "${name}"`}. Try tw_law_search first.`);
128
- return law.pcode;
129
- }
130
-
131
- async function searchTool(db: D1Like, args: Record<string, unknown>) {
132
- const query = String(args.query ?? '').trim();
133
- if (!query) throw new Error('Required argument "query" is missing (a Chinese or English law title keyword).');
134
- const limit = clamp(args.limit, 1, 50, 10);
135
- const rows = await searchLaws(db, { query, limit });
136
- return {
137
- query,
138
- returned: rows.length,
139
- laws: rows.map((r) => ({ ...shapeLaw(r), matched_on: r.matched_on })),
140
- note: rows.length === 0 ? 'No law title matched. This is a title search — try tw_law_search with a different keyword, not an article phrase.' : undefined,
141
- source: SOURCE,
142
- data_as_of: await dataAsOf(db),
143
- };
144
- }
145
-
146
- async function infoTool(db: D1Like, args: Record<string, unknown>) {
147
- const pcode = args.pcode != null ? String(args.pcode).trim() : '';
148
- const name = args.name != null ? String(args.name).trim() : '';
149
- if (!pcode && !name) throw new Error('Provide either "pcode" (from tw_law_search) or "name" (a Chinese or English law title).');
150
- const law = await getLaw(db, { pcode: pcode || undefined, name: name || undefined });
151
- if (!law) throw new Error(`No Taiwan law found for ${pcode ? `pcode "${pcode}"` : `name "${name}"`}. Try tw_law_search first.`);
152
- return { ...shapeLaw(law), data_as_of: await dataAsOf(db) };
153
- }
154
-
155
- async function tocTool(db: D1Like, args: Record<string, unknown>) {
156
- const pcode = await resolvePcode(db, args);
157
- const offset = clamp(args.offset, 0, 1_000_000, 0);
158
- const limit = clamp(args.limit, 1, 500, 200);
159
- const { rows, total } = await getToc(db, { pcode, offset, limit });
160
- return {
161
- pcode,
162
- total_entries: total,
163
- returned: rows.length,
164
- offset,
165
- entries: rows.map((r) => ({
166
- seq: r.seq,
167
- kind: r.article_type === 'C' ? 'heading' : 'article',
168
- article_no: r.article_no || null,
169
- eng_article_no: r.eng_article_no || null,
170
- text: r.article_type === 'C' ? r.content : undefined,
171
- })),
172
- has_more: offset + rows.length < total,
173
- next_offset: offset + rows.length < total ? offset + rows.length : null,
174
- source: SOURCE,
175
- data_as_of: await dataAsOf(db),
176
- };
177
- }
178
-
179
- async function articleTool(db: D1Like, args: Record<string, unknown>) {
180
- const articleArg = args.article != null ? String(args.article).trim() : '';
181
- if (!articleArg) throw new Error('Required argument "article" is missing, e.g. "2" or "Article 2".');
182
- const pcode = await resolvePcode(db, args);
183
- const row = await getArticle(db, { pcode, articleNo: articleArg });
184
- if (!row) {
185
- throw new Error(
186
- `No article "${articleArg}" found for this law. Use tw_law_toc to list its real article numbers — some laws skip numbers or use "-1"/"-2" sub-articles.`,
187
- );
188
- }
189
- const law = await getLaw(db, { pcode });
190
- const heading = await getHeadingBefore(db, { pcode, seq: row.seq });
191
- return {
192
- pcode,
193
- law_name: law?.law_name ?? null,
194
- eng_law_name: law?.eng_law_name ?? null,
195
- heading: heading,
196
- article_no: row.article_no,
197
- content: row.content,
198
- eng_article_no: row.eng_article_no,
199
- eng_content: row.eng_content,
200
- translation_label: row.eng_content ? 'official' : null,
201
- has_official_english_translation: !!row.eng_content,
202
- source: SOURCE,
203
- data_as_of: await dataAsOf(db),
204
- };
205
- }
206
-
207
- async function callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
208
- const db = requireDb(args._d1);
209
- switch (name) {
210
- case 'tw_law_search':
211
- return searchTool(db, args);
212
- case 'tw_law_info':
213
- return infoTool(db, args);
214
- case 'tw_law_toc':
215
- return tocTool(db, args);
216
- case 'tw_law_article':
217
- return articleTool(db, args);
218
- default:
219
- throw new Error(`Unknown tool: ${name}`);
220
- }
221
- }
222
-
223
- export default { tools, callTool, meter: { credits: 1 } } satisfies McpToolExport;
package/src/server.ts DELETED
@@ -1,48 +0,0 @@
1
- /**
2
- * Stdio MCP server entry point for @pipeworx/mcp-tw-law.
3
- * Generated by scripts/publish-pack.sh — do not hand-edit in the pack repo;
4
- * edit scripts/publish-pack.sh (the server.ts heredoc) and republish instead.
5
- */
6
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
7
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
8
- import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
9
- import pack from './index.js';
10
-
11
-
12
- const server = new Server(
13
- { name: '@pipeworx/mcp-tw-law', version: '0.1.0' },
14
- { capabilities: { tools: {} } },
15
- );
16
-
17
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
18
- tools: pack.tools.map((t) => ({
19
- name: t.name,
20
- description: t.description,
21
- inputSchema: t.inputSchema,
22
- })),
23
- }));
24
-
25
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
26
- const { name, arguments: args } = request.params;
27
- try {
28
- const callArgs = { ...((args ?? {}) as Record<string, unknown>) };
29
-
30
- const result = await pack.callTool(name, callArgs);
31
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
32
- } catch (err) {
33
- return {
34
- content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }],
35
- isError: true,
36
- };
37
- }
38
- });
39
-
40
- async function main() {
41
- const transport = new StdioServerTransport();
42
- await server.connect(transport);
43
- }
44
-
45
- main().catch((err) => {
46
- console.error('Fatal error running server:', err);
47
- process.exit(1);
48
- });
package/src/store.ts DELETED
@@ -1,214 +0,0 @@
1
- /**
2
- * Reads for tw-law (fleet #3129).
3
- *
4
- * Taiwan's Ministry of Justice Laws & Regulations Database
5
- * (全國法規資料庫, law.moj.gov.tw) publishes its whole catalog — every national
6
- * statute and the Constitution, in Chinese, plus the Ministry's own official
7
- * English translations where one exists — only as two bulk JSON exports (one
8
- * per language), never a per-law or per-article live route (verified
9
- * 2026-10-15: both `/api/Ch/Law/JSON` and `/api/En/Law/JSON` return a zip of
10
- * the ENTIRE catalog; there is no `LawSearchContent`-style per-item endpoint).
11
- * Per Bruce's 2026-09-23 ruling on bulk-only sources, `scripts/tw-law/load-data.mjs`
12
- * downloads both exports, joins each Chinese law to its official English
13
- * translation by title (the join key the source itself uses — see that
14
- * script's header), and writes the result into a D1 database the gateway
15
- * hands this pack as `_d1`
16
- * (pack-manifest "d1Binding": "TW_LAW_DB"). Table/column names here must
17
- * match that script's buildSchemaSql().
18
- *
19
- * Licence: 政府資料開放授權條款-第1版 (Government Open Data Licence v1), the
20
- * licence law.moj.gov.tw's own data-reuse declaration
21
- * (law.moj.gov.tw/Service/Copyright.aspx) names for this database — free,
22
- * non-exclusive, re-licensable, and explicitly permits reproduction,
23
- * adaptation and public transmission (i.e. a mirror, not just a live proxy),
24
- * conditioned only on citing the source. That is what is cited below.
25
- */
26
-
27
- /** The slice of Cloudflare's D1Database this pack uses, declared here so the
28
- * pack needs no workers-types and a test can pass a node:sqlite stub. */
29
- export interface D1Like {
30
- prepare(sql: string): D1StmtLike;
31
- }
32
- export interface D1StmtLike {
33
- bind(...values: unknown[]): D1StmtLike;
34
- all<T = Record<string, unknown>>(): Promise<{ results: T[] }>;
35
- first<T = Record<string, unknown>>(): Promise<T | null>;
36
- }
37
-
38
- // Provenance is publisher + dataset + data_as_of (CLAUDE.md step 9b) — never
39
- // the download route.
40
- export const SOURCE = 'Taiwan Ministry of Justice, Laws & Regulations Database (全國法規資料庫)';
41
- export const LICENSE =
42
- '政府資料開放授權條款-第1版 (Government Open Data Licence v1) — free, non-exclusive, ' +
43
- 're-licensable reuse including reproduction and public transmission, conditioned on citing the source.';
44
-
45
- export class StoreUnavailableError extends Error {
46
- constructor() {
47
- super(
48
- 'tw-law: the law store is not bound in this runtime (no _d1). These tools only answer through the Pipeworx gateway; a standalone install has no data to read.',
49
- );
50
- this.name = 'StoreUnavailableError';
51
- }
52
- }
53
- export function requireDb(d1: unknown): D1Like {
54
- if (!d1 || typeof (d1 as D1Like).prepare !== 'function') throw new StoreUnavailableError();
55
- return d1 as D1Like;
56
- }
57
-
58
- export interface LawRow {
59
- pcode: string;
60
- law_name: string;
61
- eng_law_name: string | null;
62
- law_level: string;
63
- law_category: string | null;
64
- law_url: string;
65
- eng_law_url: string | null;
66
- has_eng_version: number;
67
- modified_date: string | null;
68
- effective_date: string | null;
69
- effective_note: string | null;
70
- abandon_note: string | null;
71
- foreword: string | null;
72
- histories: string | null;
73
- eng_histories: string | null;
74
- article_count: number;
75
- }
76
-
77
- const LAW_COLS = `pcode, law_name, eng_law_name, law_level, law_category, law_url, eng_law_url, has_eng_version,
78
- modified_date, effective_date, effective_note, abandon_note, foreword, histories, eng_histories, article_count`;
79
-
80
- /** Chinese government dates are plain YYYYMMDD strings; a few historical
81
- * entries are empty (effective on promulgation) or the "99991231" sentinel
82
- * the source itself uses for "date set later by the Executive Yuan" — never
83
- * guess a real date for either, surface them as given. */
84
- function fmtDate(raw: string | null): string | null {
85
- if (!raw) return null;
86
- if (raw === '99991231') return null;
87
- const m = /^(\d{4})(\d{2})(\d{2})$/.exec(raw);
88
- return m ? `${m[1]}-${m[2]}-${m[3]}` : raw;
89
- }
90
-
91
- function isPending(raw: string | null): boolean {
92
- return raw === '99991231';
93
- }
94
-
95
- export function shapeLaw(r: LawRow) {
96
- return {
97
- pcode: r.pcode,
98
- law_name: r.law_name,
99
- eng_law_name: r.eng_law_name,
100
- law_level: r.law_level,
101
- law_category: r.law_category,
102
- law_url: r.law_url,
103
- eng_law_url: r.eng_law_url,
104
- has_official_english_translation: r.has_eng_version === 1,
105
- abolished: !!(r.abandon_note && r.abandon_note.trim()),
106
- abandon_note: r.abandon_note || null,
107
- // Dates kept apart per the legal-pack contract: amendment date (most
108
- // recent change to the text) vs. the date that amendment takes/took
109
- // legal effect — the source tracks these as two separate fields, and so
110
- // does this pack.
111
- last_amended_date: fmtDate(r.modified_date),
112
- effective_date: fmtDate(r.effective_date),
113
- effective_date_pending: isPending(r.effective_date),
114
- effective_note: r.effective_note || null,
115
- foreword: r.foreword || null,
116
- promulgation_history: r.histories || null,
117
- promulgation_history_english: r.eng_histories || null,
118
- article_count: r.article_count,
119
- source: SOURCE,
120
- };
121
- }
122
-
123
- export async function dataAsOf(db: D1Like): Promise<string | null> {
124
- const r = await db.prepare(`SELECT value FROM tw_law_meta WHERE key = 'loaded_at'`).first<{ value: string }>();
125
- return r?.value ?? null;
126
- }
127
-
128
- /** The whole catalog is 1,351 laws — a LIKE scan over that is trivial, so
129
- * title search skips FTS5 entirely (and the chunked-import trap that comes
130
- * with it; see reference_d1_fts5_import_trap) in favor of a plain
131
- * substring match on both the Chinese and English titles. */
132
- export async function searchLaws(
133
- db: D1Like,
134
- opts: { query: string; limit: number },
135
- ): Promise<Array<LawRow & { matched_on: 'chinese_title' | 'english_title' }>> {
136
- const q = opts.query.trim();
137
- if (!q) return [];
138
- const cols = LAW_COLS.split(',').map((c) => `l.${c.trim()}`).join(', ');
139
- const r = await db
140
- .prepare(
141
- `SELECT ${cols},
142
- CASE WHEN l.law_name LIKE ? THEN 'chinese_title' ELSE 'english_title' END AS matched_on
143
- FROM tw_laws l WHERE l.law_name LIKE ? OR l.eng_law_name LIKE ?
144
- ORDER BY length(l.law_name) LIMIT ?`,
145
- )
146
- .bind(`%${q}%`, `%${q}%`, `%${q}%`, opts.limit)
147
- .all<LawRow & { matched_on: 'chinese_title' | 'english_title' }>();
148
- return r.results;
149
- }
150
-
151
- export async function getLaw(db: D1Like, opts: { pcode?: string; name?: string }): Promise<LawRow | null> {
152
- if (opts.pcode) {
153
- return db.prepare(`SELECT ${LAW_COLS} FROM tw_laws WHERE pcode = ?`).bind(opts.pcode).first<LawRow>();
154
- }
155
- if (opts.name) {
156
- const exact = await db.prepare(`SELECT ${LAW_COLS} FROM tw_laws WHERE law_name = ? OR eng_law_name = ?`).bind(opts.name, opts.name).first<LawRow>();
157
- if (exact) return exact;
158
- return db
159
- .prepare(`SELECT ${LAW_COLS} FROM tw_laws WHERE law_name LIKE ? OR eng_law_name LIKE ? ORDER BY length(law_name) LIMIT 1`)
160
- .bind(`%${opts.name}%`, `%${opts.name}%`)
161
- .first<LawRow>();
162
- }
163
- return null;
164
- }
165
-
166
- export interface ArticleRow {
167
- seq: number;
168
- article_type: 'A' | 'C';
169
- article_no: string | null;
170
- article_no_norm: string | null;
171
- content: string;
172
- eng_article_no: string | null;
173
- eng_content: string | null;
174
- }
175
- const ARTICLE_COLS = 'seq, article_type, article_no, article_no_norm, content, eng_article_no, eng_content';
176
-
177
- export async function getToc(
178
- db: D1Like,
179
- opts: { pcode: string; offset: number; limit: number },
180
- ): Promise<{ rows: ArticleRow[]; total: number }> {
181
- const total = await db.prepare(`SELECT count(*) AS n FROM tw_articles WHERE pcode = ?`).bind(opts.pcode).first<{ n: number }>();
182
- const r = await db
183
- .prepare(`SELECT ${ARTICLE_COLS} FROM tw_articles WHERE pcode = ? ORDER BY seq LIMIT ? OFFSET ?`)
184
- .bind(opts.pcode, opts.limit, opts.offset)
185
- .all<ArticleRow>();
186
- return { rows: r.results, total: total?.n ?? 0 };
187
- }
188
-
189
- /** "第 2 條" / "2" / "Article 2" / "第 6-1 條" / "Article 6-1" all normalize
190
- * to the same key the loader stored, so any of the source's own spellings
191
- * (Chinese or English) resolves a provision. */
192
- export function normalizeArticleNo(v: string): string {
193
- const m = /(\d+)(?:[-之](\d+))?/.exec(String(v));
194
- if (!m) return String(v).trim();
195
- return m[2] ? `${m[1]}-${m[2]}` : m[1];
196
- }
197
-
198
- export async function getArticle(db: D1Like, opts: { pcode: string; articleNo: string }): Promise<ArticleRow | null> {
199
- const norm = normalizeArticleNo(opts.articleNo);
200
- return db
201
- .prepare(`SELECT ${ARTICLE_COLS} FROM tw_articles WHERE pcode = ? AND article_type = 'A' AND article_no_norm = ? LIMIT 1`)
202
- .bind(opts.pcode, norm)
203
- .first<ArticleRow>();
204
- }
205
-
206
- /** The chapter/section heading (ArticleType 'C') immediately preceding a
207
- * given seq, for context — "第 一 章 總則" above Article 1, etc. */
208
- export async function getHeadingBefore(db: D1Like, opts: { pcode: string; seq: number }): Promise<string | null> {
209
- const r = await db
210
- .prepare(`SELECT content FROM tw_articles WHERE pcode = ? AND article_type = 'C' AND seq < ? ORDER BY seq DESC LIMIT 1`)
211
- .bind(opts.pcode, opts.seq)
212
- .first<{ content: string }>();
213
- return r?.content ?? null;
214
- }
package/tsconfig.json DELETED
@@ -1,18 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2022",
4
- "module": "ESNext",
5
- "moduleResolution": "bundler",
6
- "lib": ["ES2022"],
7
- "types": ["@cloudflare/workers-types"],
8
- "strict": true,
9
- "esModuleInterop": true,
10
- "skipLibCheck": true,
11
- "resolveJsonModule": true,
12
- "outDir": "dist",
13
- "rootDir": "src",
14
- "declaration": true
15
- },
16
- "include": ["src"],
17
- "exclude": ["src/server.ts"]
18
- }