@pipeworx/mcp-tw-law 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mojibake Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,176 @@
1
- # Temporary Holding Version
1
+ # @pipeworx/tw-law
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Taiwan's national statutes and the Constitution — full text in Chinese, plus
4
+ the Ministry of Justice's own official English translation where one exists
5
+ — searchable by title, resolvable by exact citation, and readable one
6
+ provision at a time.
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.
9
+
10
+ ## Tools
11
+
12
+ - `tw_law_search(query, limit?)` — find a law by title keyword, Chinese or
13
+ English ("個人資料保護法", "Personal Data Protection", "民法").
14
+ - `tw_law_info(pcode?, name?)` — a law's full metadata: level, category,
15
+ official English title if any, repeal status, the last amendment date and
16
+ the date that amendment takes/took legal effect as SEPARATE fields, and
17
+ the promulgation history (Chinese, and English when translated).
18
+ - `tw_law_toc(pcode?, name?, offset?, limit?)` — a law's chapter/section
19
+ structure and article numbers, paged.
20
+ - `tw_law_article(pcode?, name?, article)` — one article's full text,
21
+ Chinese plus the official English translation when the Ministry has
22
+ published one, labelled `official`.
23
+
24
+ ## Auth
25
+
26
+ Keyless.
27
+
28
+ ## Data sources
29
+
30
+ - Taiwan Ministry of Justice, Laws & Regulations Database (全國法規資料庫) —
31
+ the Chinese text of every national statute and the Constitution, plus the
32
+ Ministry's own official English translations for the subset it has
33
+ translated (973 of 1,351 laws as of the 2026-10-15 load).
34
+
35
+ The source publishes its whole catalog only as two bulk exports (Chinese,
36
+ English), never a per-law or per-article live route — confirmed 2026-10-15.
37
+ Per Bruce's 2026-09-23 local-copy ruling, this pack reads from a D1 copy
38
+ loaded by `scripts/tw-law/load-data.mjs`, refreshed by re-running that
39
+ script. `data_as_of` on every response is when that load last ran.
40
+
41
+ **Licence:** 政府資料開放授權條款-第1版 (Government Open Data Licence v1), the
42
+ licence the source's own data-reuse declaration
43
+ (law.moj.gov.tw/Service/Copyright.aspx) names — free, non-exclusive,
44
+ re-licensable, and explicitly permits reproduction, adaptation and public
45
+ transmission (a mirror, not only a live proxy), conditioned on citing the
46
+ source. Every response carries `source`.
47
+
48
+ ## English translations are tied to the exact Chinese version
49
+
50
+ Chinese and English are two separate bulk exports from the same publisher,
51
+ joined by this pack's loader at load time, by law title and then by article
52
+ number (normalizing "第 6-1 條" / "Article 6-1" / "6-1" to the same key) —
53
+ never machine-translated, never guessed. An article with no official
54
+ translation returns `eng_content: null` and
55
+ `has_official_english_translation: false` rather than a translation that
56
+ doesn't exist. A law can gain or lose an official translation between loads;
57
+ `tw_law_info`/`tw_law_search` report `has_official_english_translation` as of
58
+ the current `data_as_of`.
59
+
60
+ ## Notes
61
+
62
+ - `tw_law_search` is a TITLE search — it will not find a law by a phrase that
63
+ appears only inside an article's text.
64
+ - Article numbering is not always contiguous: amendments can delete an
65
+ article or insert a sub-article ("第 1-1 條" after "第 1 條"). Use
66
+ `tw_law_toc` to see a law's real article numbers rather than assuming
67
+ 1..N.
68
+ - `effective_date` and `last_amended_date` are tracked separately because
69
+ Taiwanese statutes are routinely amended on one date and brought into
70
+ force on another (sometimes "date to be set later by the Executive Yuan"
71
+ — surfaced as `effective_date_pending: true`, with the full
72
+ `effective_note` explaining which provisions are affected).
73
+
74
+ ## Quick Start
75
+
76
+ Add to your MCP client (Claude Desktop, Cursor, Windsurf, etc.):
77
+
78
+ ```json
79
+ {
80
+ "mcpServers": {
81
+ "tw-law": {
82
+ "url": "https://gateway.pipeworx.io/tw-law/mcp"
83
+ }
84
+ }
85
+ }
86
+ ```
87
+
88
+ ### What this endpoint actually serves
89
+
90
+ `tools/list` at `https://gateway.pipeworx.io/tw-law/mcp` returns the tools in the table
91
+ above **plus the shared Pipeworx meta-tools** — `ask_pipeworx`,
92
+ `discover_tools`, `search_within`, `remember`/`recall` and the rest of the
93
+ gateway-wide set. So the tool count you see is larger than this table: a
94
+ single-pack endpoint currently lists roughly 30 shared tools alongside the
95
+ pack's own. The connection's `initialize` response states its exact scope, and
96
+ is the authoritative answer for a given day.
97
+
98
+ This is deliberate, not multiplexing by accident. The meta-tools are what let a
99
+ scoped connection answer a question this pack does not cover — via
100
+ `ask_pipeworx`, which routes across the whole catalog — without you adding a
101
+ second MCP server. There is currently no way to mount a pack endpoint without
102
+ them; if the extra schemas cost you more context than the routing is worth,
103
+ connect to the full gateway once rather than to several pack endpoints.
104
+
105
+ Or connect to the full Pipeworx gateway to get every pack's tools listed
106
+ directly, instead of just this one's:
107
+
108
+ ```json
109
+ {
110
+ "mcpServers": {
111
+ "pipeworx": {
112
+ "url": "https://gateway.pipeworx.io/mcp"
113
+ }
114
+ }
115
+ }
116
+ ```
117
+
118
+ Both URLs reach the same gateway and the same 1815+ data sources. The
119
+ only difference is which pack's tools are listed **directly**; `ask_pipeworx`
120
+ reaches all of them from either one.
121
+
122
+ ## No MCP client? Call it over HTTP
123
+
124
+ ```bash
125
+ curl -X POST https://gateway.pipeworx.io/v1/tools/tw_law_search \
126
+ -H 'Content-Type: application/json' \
127
+ -d '{"query":"個人資料保護法"}'
128
+ ```
129
+
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
+
132
+ ## Standalone (no gateway account)
133
+
134
+ This package also runs as a local stdio MCP server — no Pipeworx account, no
135
+ gateway round-trip:
136
+
137
+ ```json
138
+ {
139
+ "mcpServers": {
140
+ "tw-law": {
141
+ "command": "npx",
142
+ "args": ["-y", "@pipeworx/mcp-tw-law"]
143
+ }
144
+ }
145
+ }
146
+ ```
147
+
148
+ Or run it directly to confirm it starts:
149
+
150
+ ```bash
151
+ npx -y @pipeworx/mcp-tw-law
152
+ ```
153
+
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.
157
+
158
+ ## Using with ask_pipeworx
159
+
160
+ Instead of calling tools directly, you can ask questions in plain English —
161
+ this works on the pack endpoint above as well as on the full gateway:
162
+
163
+ ```
164
+ ask_pipeworx({ question: "your question about Tw Law data" })
165
+ ```
166
+
167
+ The gateway picks the right tool and fills the arguments automatically.
168
+
169
+ ## More
170
+
171
+ - [Docs and guides](https://pipeworx.io/docs)
172
+ - [pipeworx.io](https://pipeworx.io)
173
+
174
+ ## License
175
+
176
+ MIT
package/bin/cli.js ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ //
3
+ // Entry point for `npx @pipeworx/mcp-<slug>`.
4
+ //
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
+ //
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
+
15
+ register();
16
+
17
+ await import('../src/server.ts');
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@pipeworx/mcp-tw-law",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
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
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "bin": {
9
+ "mcp-tw-law": "bin/cli.js"
10
+ },
11
+ "keywords": ["mcp", "mcp-server", "model-context-protocol", "pipeworx", "tw-law"],
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/pipeworx-io/mcp-tw-law.git"
16
+ },
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
+ },
28
+ "pipeworx": {
29
+ "sourceHash": "v1-93f7e951839b7103df727620fff2c2dd9349d7ec823117325ece1c28e2bfcafd",
30
+ "sourceCommit": "fe38188882d0fe91e5a45d82b7b989b4aae1e8b6"
31
+ }
32
+ }
package/server.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
+ "name": "io.github.pipeworx-io/tw-law",
4
+ "title": "Tw Law",
5
+ "description": "tw-law — Taiwan national statutes and the Constitution, in Chinese plus the Ministry of Justice's…",
6
+ "version": "0.1.0",
7
+ "websiteUrl": "https://pipeworx.io/packs/tw-law",
8
+ "repository": {
9
+ "url": "https://github.com/pipeworx-io/mcp-tw-law",
10
+ "source": "github"
11
+ },
12
+ "remotes": [
13
+ {
14
+ "type": "streamable-http",
15
+ "url": "https://gateway.pipeworx.io/tw-law/mcp"
16
+ }
17
+ ]
18
+ }
package/src/index.ts ADDED
@@ -0,0 +1,223 @@
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 ADDED
@@ -0,0 +1,48 @@
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 ADDED
@@ -0,0 +1,214 @@
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 ADDED
@@ -0,0 +1,18 @@
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
+ }