@pipeworx/mcp-abn-lookup 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 ADDED
@@ -0,0 +1,148 @@
1
+ # @pipeworx/abn-lookup
2
+
3
+ BYOK. Australian Business Register lookup: resolve an ABN or ACN to the registered
4
+ legal entity name, entity type, ABN status, GST registration, address state/postcode,
5
+ and business names, or search the register by entity/business name.
6
+
7
+ Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 1558+ live data sources.
8
+
9
+ ## Tools
10
+
11
+ - `abn_lookup(abn, _apiKey)` — ABN -> legal name, entity type, status, GST, address, business names.
12
+ - `abn_search(name, state?, maxResults?, _apiKey)` — entity/business name -> ranked ABN matches.
13
+ - `acn_lookup(acn, _apiKey)` — ACN (company number) -> the same detail as `abn_lookup`.
14
+
15
+ ## Auth
16
+
17
+ BYO only. There is no platform key. Every call requires the caller's own ABR
18
+ web-services GUID via `_apiKey`. Register free at
19
+ https://abr.business.gov.au/Tools/WebServices — ABR requires accepting its Web
20
+ Services Agreement (terms + a personal-info-sharing acknowledgement) under a
21
+ registered identity before it emails a GUID; that's a human consent step, so
22
+ Pipeworx does not hold or front one.
23
+
24
+ Without `_apiKey`, every tool refuses with "requires an API key" and points to
25
+ the registration URL above.
26
+
27
+ ## Data sources
28
+
29
+ - `https://abr.business.gov.au/json/AbnDetails.aspx` — ABN or ACN detail.
30
+ - `https://abr.business.gov.au/json/AcnDetails.aspx` — ACN detail.
31
+ - `https://abr.business.gov.au/json/MatchingNames.aspx` — name search.
32
+
33
+ ## Gotchas
34
+
35
+ - The JSON endpoints are JSONP: the body is wrapped as `<callback>({...})`,
36
+ where `<callback>` follows whatever `callback=` query param is sent
37
+ (defaults to `callback` if omitted — verified live). This pack strips the
38
+ wrapper generically by function name, not by hardcoding `callback`.
39
+ - An invalid or unrecognised GUID returns **HTTP 200** with every core field
40
+ empty and a `Message` string (e.g. `"The GUID entered is not recognised as a
41
+ Registered Party"`), not an HTTP error. ABR uses the same shape for a
42
+ genuine not-found result, so an empty core field alongside a `Message`
43
+ cannot be told apart from a rejected key by the response alone — this pack
44
+ says so explicitly in the error rather than guessing.
45
+ - Field names in the mapped output (`Abn`, `AbnStatus`, `EntityName`,
46
+ `BusinessName[]`, etc.) come from ABR's published JSON sample URLs; the
47
+ *populated* (successful-lookup) shape is unverified end-to-end because no
48
+ fleet GUID exists (BYOK, ruled 2026-09-03). The raw ABR payload is always
49
+ returned as `raw` so a caller with a real key is never blocked by a stale
50
+ field name here.
51
+ - `state` on `abn_search` is a client-side filter over ABR's returned
52
+ matches (by each match's `State` field), not a documented ABR query
53
+ parameter — ABR's public JSON sample docs don't show a state filter param
54
+ for `MatchingNames.aspx`.
55
+
56
+ ## Quick Start
57
+
58
+ Add to your MCP client (Claude Desktop, Cursor, Windsurf, etc.):
59
+
60
+ ```json
61
+ {
62
+ "mcpServers": {
63
+ "abn-lookup": {
64
+ "url": "https://gateway.pipeworx.io/abn-lookup/mcp"
65
+ }
66
+ }
67
+ }
68
+ ```
69
+
70
+ ### What this endpoint actually serves
71
+
72
+ `tools/list` at `https://gateway.pipeworx.io/abn-lookup/mcp` returns the tools in the table
73
+ above **plus the shared Pipeworx meta-tools** — `ask_pipeworx`,
74
+ `discover_tools`, `search_within`, `remember`/`recall` and the rest of the
75
+ gateway-wide set. So the tool count you see is larger than this table: a
76
+ single-pack endpoint currently lists roughly 30 shared tools alongside the
77
+ pack's own. The connection's `initialize` response states its exact scope, and
78
+ is the authoritative answer for a given day.
79
+
80
+ This is deliberate, not multiplexing by accident. The meta-tools are what let a
81
+ scoped connection answer a question this pack does not cover — via
82
+ `ask_pipeworx`, which routes across the whole catalog — without you adding a
83
+ second MCP server. There is currently no way to mount a pack endpoint without
84
+ them; if the extra schemas cost you more context than the routing is worth,
85
+ connect to the full gateway once rather than to several pack endpoints.
86
+
87
+ Or connect to the full Pipeworx gateway to get every pack's tools listed
88
+ directly, instead of just this one's:
89
+
90
+ ```json
91
+ {
92
+ "mcpServers": {
93
+ "pipeworx": {
94
+ "url": "https://gateway.pipeworx.io/mcp"
95
+ }
96
+ }
97
+ }
98
+ ```
99
+
100
+ Both URLs reach the same gateway and the same 1558+ data sources. The
101
+ only difference is which pack's tools are listed **directly**; `ask_pipeworx`
102
+ reaches all of them from either one.
103
+
104
+ ## Standalone (no gateway account)
105
+
106
+ This package also runs as a local stdio MCP server — no Pipeworx account, no
107
+ gateway round-trip:
108
+
109
+ ```json
110
+ {
111
+ "mcpServers": {
112
+ "abn-lookup": {
113
+ "command": "npx",
114
+ "args": ["-y", "@pipeworx/mcp-abn-lookup"]
115
+ }
116
+ }
117
+ }
118
+ ```
119
+
120
+ Or run it directly to confirm it starts:
121
+
122
+ ```bash
123
+ npx -y @pipeworx/mcp-abn-lookup
124
+ ```
125
+
126
+ It speaks MCP over stdin/stdout and answers `initialize`/`tools/list`/`tools/call`
127
+ for **only** this pack's tools — none of the shared meta-tools the gateway
128
+ connection above adds. Same source, same tools, no ask_pipeworx routing.
129
+
130
+ ## Using with ask_pipeworx
131
+
132
+ Instead of calling tools directly, you can ask questions in plain English —
133
+ this works on the pack endpoint above as well as on the full gateway:
134
+
135
+ ```
136
+ ask_pipeworx({ question: "your question about Abn Lookup data" })
137
+ ```
138
+
139
+ The gateway picks the right tool and fills the arguments automatically.
140
+
141
+ ## More
142
+
143
+ - [Docs and guides](https://pipeworx.io/docs)
144
+ - [pipeworx.io](https://pipeworx.io)
145
+
146
+ ## License
147
+
148
+ 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 ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "@pipeworx/mcp-abn-lookup",
3
+ "version": "0.1.0",
4
+ "description": "ABN Lookup MCP — BYOK wrapper around the Australian Business Register's",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "bin": {
9
+ "mcp-abn-lookup": "bin/cli.js"
10
+ },
11
+ "keywords": ["mcp", "mcp-server", "model-context-protocol", "pipeworx", "abn-lookup"],
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/pipeworx-io/mcp-abn-lookup.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.7.0"
26
+ }
27
+ }
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/abn-lookup",
4
+ "title": "Abn Lookup",
5
+ "description": "ABN Lookup MCP — BYOK wrapper around the Australian Business Register's",
6
+ "version": "0.1.0",
7
+ "websiteUrl": "https://pipeworx.io/packs/abn-lookup",
8
+ "repository": {
9
+ "url": "https://github.com/pipeworx-io/mcp-abn-lookup",
10
+ "source": "github"
11
+ },
12
+ "remotes": [
13
+ {
14
+ "type": "streamable-http",
15
+ "url": "https://gateway.pipeworx.io/abn-lookup/mcp"
16
+ }
17
+ ]
18
+ }
package/src/index.ts ADDED
@@ -0,0 +1,896 @@
1
+ interface McpToolDefinition {
2
+ name: string;
3
+ description: string;
4
+ inputSchema: {
5
+ type: 'object';
6
+ properties: Record<string, unknown>;
7
+ required?: string[];
8
+ anyOf?: Array<{ required: string[] }>;
9
+ oneOf?: Array<{ required: string[] }>;
10
+ allOf?: Array<{ required: string[] }>;
11
+ };
12
+ outputSchema?: Record<string, unknown>;
13
+ }
14
+
15
+ interface McpToolExport {
16
+ tools: McpToolDefinition[];
17
+ callTool: (name: string, args: Record<string, unknown>) => Promise<unknown>;
18
+ meter?: { credits: number };
19
+ cost?: Record<string, unknown>;
20
+ provider?: string;
21
+ }
22
+
23
+ /**
24
+ * One place to turn a failed `fetch` into an error a caller can act on.
25
+ *
26
+ * Nearly every pack was written the same way:
27
+ *
28
+ * if (!res.ok) throw new Error(`Unsplash: ${res.status}`);
29
+ *
30
+ * which discards the response body — and the body is usually where the upstream
31
+ * says what was actually wrong ("**symbol** not found: GBP", "parameter `year`
32
+ * out of range", "unknown taxonomy id"). The caller gets a number, cannot
33
+ * self-correct, and retries the same broken call. A 2026-07-31 sweep found this
34
+ * shape in 481 of 1,400 packs, 47 of them PLATFORM-keyed.
35
+ *
36
+ * It also hides bugs one level down. Two of the first three packs audited had a
37
+ * second defect that only existed because of this line: unsplash's rate-limit
38
+ * branch sat BELOW a catch-all and was unreachable, and bea-gov parsed
39
+ * `BEAAPI.Error.APIErrorDescription` below a `!res.ok` throw that made the
40
+ * parsing dead code for every non-200.
41
+ *
42
+ * DELIBERATELY NOT A CLASSIFIER. It does not add `user_error:` /
43
+ * `upstream_down:` prefixes. Those decide which tier a failure lands in, and the
44
+ * `error` tier is what the daily problem-tools list is built from — it means
45
+ * "Pipeworx has a defect". A 400 is genuinely ambiguous: often a caller's bad
46
+ * argument, but sometimes a query WE built wrong (ted-eu comma-joined its CPV
47
+ * values into something TED rejected, and that bug was found only because it sat
48
+ * in `error`). Blanket-classifying 400s as caller mistakes would have hidden it.
49
+ * A pack that KNOWS which it is should keep saying so explicitly; this helper is
50
+ * for the 481 that say nothing at all.
51
+ */
52
+
53
+ /** Longest upstream explanation we'll pass through. Enough for a real message,
54
+ * short enough that an HTML page or a stack trace can't swamp the error. */
55
+
56
+ const MAX_DETAIL = 300;
57
+
58
+ /**
59
+ * Default bound for `fetchWithTimeout` when a pack doesn't state its own.
60
+ *
61
+ * 25s mirrors the number `epo-ops` landed on after measuring the real failure:
62
+ * a degraded upstream that doesn't error, it just never answers, and a Worker
63
+ * sits in `await fetch()` until ITS OWN execution budget kills the request —
64
+ * which can take minutes, not seconds (epo_ops_search_patents measured 4-8
65
+ * MINUTE hangs before this existed). 25s is short enough that a caller gets a
66
+ * fast, actionable error instead of holding the connection, and long enough
67
+ * that it doesn't false-trip on a merely-slow-but-alive upstream.
68
+ */
69
+ const DEFAULT_FETCH_TIMEOUT_MS = 25_000;
70
+
71
+ /**
72
+ * Read the body of a failed response and fold it into a throwable Error.
73
+ *
74
+ * Usage — note the `await`, which is the one thing that makes this a mechanical
75
+ * change rather than a drop-in:
76
+ *
77
+ * if (!res.ok) throw await httpError(res, 'Unsplash');
78
+ *
79
+ * Safe to call on any non-ok response: a body that is missing, empty, unreadable
80
+ * or HTML degrades to exactly the old `Name: 404` string rather than throwing
81
+ * something new from inside the error path.
82
+ */
83
+ async function httpError(res: Response, name: string): Promise<Error> {
84
+ return new Error(await httpErrorMessage(res, name));
85
+ }
86
+
87
+ /** The message text without constructing an Error — for packs that need to wrap
88
+ * it in their own envelope or add an explicit classification prefix. */
89
+ async function httpErrorMessage(res: Response, name: string): Promise<string> {
90
+ // The one place a 5xx from a host WE run gets stamped as ours. `res.url` is
91
+ // the URL the fetch actually resolved to (after redirects), so this is a fact
92
+ // about the call rather than a guess from the `name` the pack passed in —
93
+ // reword that label freely, the class does not move. See
94
+ // internal-host-class.ts; no-op for every third-party upstream, which is why
95
+ // this touches 481 packs' error text and changes none of it.
96
+ return markInternalOrigin(
97
+ `${name}: ${res.status}${detailSuffix(await readDetail(res))}`,
98
+ res.url,
99
+ res.status,
100
+ );
101
+ }
102
+
103
+ /**
104
+ * Just the upstream's own explanation — no name, no status.
105
+ *
106
+ * For a pack that has already said both in its own sentence. epo-ops reads
107
+ * `EPO rejected this search as too large (HTTP 413) — ${httpErrorMessage(…)}`,
108
+ * which rendered as `… (HTTP 413) — EPO: 413.` once the XML detail was being
109
+ * dropped: the upstream named twice, the status twice, and the one thing EPO
110
+ * actually said ("Not enough characters before truncation character") nowhere
111
+ * (fleet #712). Returns '' when the body carries nothing readable, so a caller
112
+ * can fall back to its own wording.
113
+ */
114
+ async function upstreamDetail(res: Response): Promise<string> {
115
+ return readDetail(res);
116
+ }
117
+
118
+ /**
119
+ * Read a SUCCESSFUL response as JSON, failing loudly when it isn't JSON.
120
+ *
121
+ * `httpError` above only ever runs on `!res.ok`, which leaves the nastier half
122
+ * of the problem unhandled: an upstream that answers **HTTP 200 with an HTML
123
+ * page**. A bot wall, a login redirect, a maintenance interstitial and a CDN
124
+ * error page are all 200s, so `res.ok` is true, and `res.json()` then throws
125
+ * `Unexpected token '<', "<!DOCTYPE "... is not valid JSON`.
126
+ *
127
+ * That string is the problem. It names no upstream, carries no status, and
128
+ * reads like a parser bug in Pipeworx — so it lands in the `error` tier, which
129
+ * means "we have a defect", and the caller is told nothing they can act on.
130
+ * data.govt.nz sat dead behind an Imperva challenge this way and every
131
+ * status-code health check we own reported it green (7889a845). A zero-length
132
+ * body has the same shape: `Unexpected end of JSON input`, seen this week on
133
+ * uk-gazette (83% of external calls) and census.
134
+ *
135
+ * UNLIKE `httpError`, this one DOES classify, and the asymmetry is deliberate.
136
+ * A 400 is genuinely ambiguous — often the caller's bad argument, sometimes a
137
+ * query we built wrong — so blanket-classifying it would hide our own bugs.
138
+ * There is no such ambiguity here: **no argument a caller can pass makes a JSON
139
+ * API return an HTML page.** It is always the upstream, so `upstream_down:` is
140
+ * a statement of fact rather than a guess, and it keeps these out of the
141
+ * problem-tools list where they crowd out real defects.
142
+ *
143
+ * const data = await parseJson<Feed>(res, 'UK Gazette');
144
+ *
145
+ * Call it only after the `!res.ok` check — on a failed response you want
146
+ * `httpError`, which mines the body for the upstream's own explanation.
147
+ */
148
+ async function parseJson<T>(res: Response, name: string): Promise<T> {
149
+ let raw: string;
150
+ try {
151
+ raw = await res.text();
152
+ } catch {
153
+ throw new Error(
154
+ `upstream_down: ${name} returned a body that could not be read (HTTP ${res.status}). ` +
155
+ 'The connection most likely dropped mid-response; retrying is reasonable.',
156
+ );
157
+ }
158
+
159
+ const type = res.headers.get('content-type') ?? 'no content-type';
160
+
161
+ if (!raw.trim()) {
162
+ throw new Error(
163
+ `upstream_down: ${name} answered HTTP ${res.status} with an EMPTY body where JSON was expected (${type}). ` +
164
+ 'Nothing about the request can cause this — it is an upstream fault, and the same call may well work on retry.',
165
+ );
166
+ }
167
+
168
+ // Checked before parsing rather than in the catch, because knowing it is
169
+ // markup is what turns "we failed to parse something" into "they served a
170
+ // web page" — the second is diagnosable, the first is not.
171
+ const head = raw.slice(0, 200).trimStart().toLowerCase();
172
+ if (head.startsWith('<!doctype') || head.startsWith('<html') || head.startsWith('<?xml')) {
173
+ const kind = head.startsWith('<?xml') ? 'an XML document' : 'an HTML page';
174
+ // The summary, not the source. Pasting the first 120 characters of a web
175
+ // page handed the agent `<!DOCTYPE html><html lang="en"…` — the same leak
176
+ // this branch exists to describe (fleet #712).
177
+ throw new Error(
178
+ `upstream_down: ${name} answered HTTP ${res.status} with ${kind} instead of JSON (${type}). ` +
179
+ 'That is typically a bot wall, a login redirect or a maintenance page — it is returned as a SUCCESS, ' +
180
+ `so status-code health checks read it as fine. No argument change will get past it. ` +
181
+ `The page says: ${summarizeErrorBody(raw) || 'nothing readable'}`,
182
+ );
183
+ }
184
+
185
+ try {
186
+ return JSON.parse(raw) as T;
187
+ } catch {
188
+ throw new Error(
189
+ `upstream_down: ${name} answered HTTP ${res.status} with a body that is not valid JSON (${type}). ` +
190
+ `It begins: ${stripMarkup(raw).slice(0, 120) || '(unreadable)'}`,
191
+ );
192
+ }
193
+ }
194
+
195
+ /**
196
+ * `fetch`, but bounded — the fix for a systemic gap found 2026-08-30: a grep
197
+ * audit of every pack's `mcps/*\/src/index.ts` found 1,339 of ~1,500 call
198
+ * `fetch()` with NO timeout guard anywhere in the file. Two of those
199
+ * (epo-ops, statcan) were confirmed live-hanging for 4-8 minutes before this
200
+ * existed — every unguarded call carries the same risk, just unconfirmed.
201
+ *
202
+ * Mirrors the `epoFetch` wrapper `mcps/epo-ops/src/index.ts` shipped first:
203
+ * bound the request with `AbortSignal.timeout`, and on a timeout/abort throw
204
+ * an `upstream_down:` error that names the upstream and the bound rather than
205
+ * letting the raw `TimeoutError`/`AbortError` (which names neither) propagate.
206
+ * `upstream_down:` is deliberate, same reasoning as `parseJson` above — no
207
+ * argument a caller passes can make an upstream hang, so it is always the
208
+ * upstream's fault, and marking it that way keeps a slow API off the
209
+ * problem-tools list where it would crowd out our own defects.
210
+ *
211
+ * Usage — a mechanical swap for a bare `fetch(url, init)`:
212
+ *
213
+ * const res = await fetchWithTimeout(url, init, 'Some API');
214
+ *
215
+ * Pass `timeoutMs` as a fourth argument to override the default for a pack
216
+ * with a known-slower upstream; the label should be the same short name you'd
217
+ * pass to `httpError`/`httpErrorMessage` for that call.
218
+ */
219
+ async function fetchWithTimeout(
220
+ url: string | URL,
221
+ init: RequestInit = {},
222
+ name: string,
223
+ timeoutMs: number = DEFAULT_FETCH_TIMEOUT_MS,
224
+ ): Promise<Response> {
225
+ try {
226
+ return await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
227
+ } catch (err) {
228
+ if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
229
+ // States the OBSERVATION (no response in N seconds), not a diagnosis.
230
+ // "appears to be degraded" is an inference about the vendor that we have
231
+ // not checked, and it is wrong in a way that misdirects whoever reads it:
232
+ // a timeout from a Worker can equally mean OUR egress is blocked.
233
+ //
234
+ // Measured today (2026-09-01, fleet #1047): every call to
235
+ // mainnet.base.org failed from the x402 facilitator while the identical
236
+ // request from a laptop returned 200. Base was entirely healthy; the
237
+ // public RPC refuses Cloudflare Worker egress. Had this message fired
238
+ // there it would have blamed Base by name, and the next person would have
239
+ // waited for a vendor outage to clear that did not exist.
240
+ // A timeout has no status to test — there is no response at all — so
241
+ // `markInternalOrigin` is called without one: an origin we run that never
242
+ // answered is an availability failure by definition. This is the half of
243
+ // fleet #1096 with neither a SQLSTATE nor a status code to key on.
244
+ throw new Error(
245
+ markInternalOrigin(
246
+ `upstream_down: ${name} did not respond within ${timeoutMs / 1000}s. ` +
247
+ `That can be ${name} being slow or down, or this environment being unable to reach it ` +
248
+ `(some hosts refuse datacenter/Worker egress) — retry shortly, and check reachability ` +
249
+ `from elsewhere before concluding ${name} is down.`,
250
+ url,
251
+ ),
252
+ );
253
+ }
254
+ throw err;
255
+ }
256
+ }
257
+
258
+ function detailSuffix(detail: string): string {
259
+ return detail ? ` — ${detail}` : '';
260
+ }
261
+
262
+ async function readDetail(res: Response): Promise<string> {
263
+ let raw: string;
264
+ try {
265
+ raw = await res.text();
266
+ } catch {
267
+ // Body already consumed, or the connection died mid-read. The status alone
268
+ // is still worth throwing — never let the error path throw its own error.
269
+ return '';
270
+ }
271
+ return summarizeErrorBody(raw);
272
+ }
273
+
274
+ /**
275
+ * Turn ANY error body — JSON, HTML, XML or plain text — into one short phrase
276
+ * that never contains markup.
277
+ *
278
+ * This used to just drop an HTML or XML body on the floor, on the reasoning
279
+ * that markup crowds out the status. That was half right. Dropping it loses the
280
+ * one sentence a caller could have acted on: an `Access Denied` title, an SDMX
281
+ * `<message:Error>` text, an OPS fault string. A 2026-08-30 support sweep
282
+ * measured 13 of 291 caller-facing error rows carrying a raw page or document
283
+ * verbatim, across 11 packs, and in every one of them the useful content —
284
+ * "Access Denied", "Invalid country code", "SCRAPE_TIMEOUT" — was in there,
285
+ * buried in markup the agent had to parse out of a string (fleet #712).
286
+ *
287
+ * So: extract the meaning, discard the markup. The output is passed through
288
+ * `stripMarkup` unconditionally, which is what lets `check:error-body-leak`
289
+ * assert mechanically that no caller-facing message can contain `<?xml`,
290
+ * `<!DOCTYPE` or `<html`.
291
+ */
292
+ function summarizeErrorBody(raw: string): string {
293
+ if (!raw || !raw.trim()) return '';
294
+
295
+ const head = raw.slice(0, 400).trimStart().toLowerCase();
296
+
297
+ // An HTML error page (Cloudflare interstitial, nginx default, a login
298
+ // redirect) says what it is in its <title>, and almost nowhere else.
299
+ if (head.startsWith('<!doctype') || head.startsWith('<html')) {
300
+ const title = htmlTitle(raw);
301
+ return title
302
+ ? `${title} (upstream returned an HTML error page, not an API response)`
303
+ : 'upstream returned an HTML error page, not an API response';
304
+ }
305
+
306
+ // XML fault documents — EPO OPS, SDMX (`<message:Error>`), SOAP faults. The
307
+ // human sentence sits in a child element whose tag name says what it is.
308
+ if (head.startsWith('<?xml') || head.startsWith('<')) {
309
+ const fault = xmlFaultText(raw);
310
+ return fault
311
+ ? `${stripMarkup(fault).slice(0, MAX_DETAIL)} (from the upstream's XML error document)`
312
+ : 'upstream returned an XML error document with no readable message';
313
+ }
314
+
315
+ // Most JSON error bodies bury one human sentence among ids and echoed request
316
+ // params. Prefer that sentence; fall back to the whole body when the shape is
317
+ // unfamiliar, since an unfamiliar shape is exactly when we can least afford to
318
+ // guess wrong and show nothing.
319
+ const fromJson = messageFromJson(raw);
320
+ return stripMarkup(fromJson ?? raw).slice(0, MAX_DETAIL);
321
+ }
322
+
323
+ /** The `<title>` of an HTML error page, or its first `<h1>` — the two places a
324
+ * bot wall, a 502 and an "Access Denied" all state what happened. */
325
+ function htmlTitle(raw: string): string | null {
326
+ const head = raw.slice(0, 4000);
327
+ for (const re of [/<title[^>]*>([\s\S]*?)<\/title>/i, /<h1[^>]*>([\s\S]*?)<\/h1>/i]) {
328
+ const m = re.exec(head);
329
+ const text = m ? stripMarkup(m[1]) : '';
330
+ if (text) return text.slice(0, 160);
331
+ }
332
+ return null;
333
+ }
334
+
335
+ /** Tag names that carry the explanation in an XML fault document, namespace
336
+ * prefix optional (`<message:Error>`, `<com:Text>`, `<faultstring>`). */
337
+ const XML_FAULT_TAG_RE =
338
+ /<(?:[A-Za-z0-9_.-]+:)?(?:text|message|description|faultstring|reason|detail|title|errormessage|error)\b[^>]*>([^<]{2,400})</i;
339
+
340
+ function xmlFaultText(raw: string): string | null {
341
+ const head = raw.slice(0, 8000);
342
+ const tagged = XML_FAULT_TAG_RE.exec(head);
343
+ if (tagged && tagged[1].trim()) return tagged[1];
344
+
345
+ // Nothing conventionally named — take the longest text node instead. A fault
346
+ // document with one sentence in an oddly named element is still readable;
347
+ // returning nothing at all is not.
348
+ let best = '';
349
+ for (const m of head.matchAll(/>([^<>]{8,400})</g)) {
350
+ const text = m[1].trim();
351
+ if (text.length > best.length) best = text;
352
+ }
353
+ return best || null;
354
+ }
355
+
356
+ /**
357
+ * Remove every tag and stray angle bracket, then collapse whitespace.
358
+ *
359
+ * Applied to everything on the way out, including the JSON and plain-text
360
+ * paths, because an upstream is free to embed markup in a JSON string field —
361
+ * and a leak is a leak regardless of which branch produced it.
362
+ */
363
+ function stripMarkup(s: string): string {
364
+ return collapse(decodeEntities(s.replace(/<[^>]*>/g, ' ')).replace(/[<>]/g, ' '));
365
+ }
366
+
367
+ /** The handful of entities that show up in error-page titles. Decoded AFTER
368
+ * tags are stripped and BEFORE the angle-bracket sweep, so `&lt;script&gt;`
369
+ * in a title cannot decode into markup that survives — EMBL-EBI's ChEMBL 500
370
+ * page renders as `500 Internal Server Error &lt; EMBL-EBI` otherwise. */
371
+ function decodeEntities(s: string): string {
372
+ return s
373
+ .replace(/&(?:amp|#0*38);/gi, '&')
374
+ .replace(/&(?:lt|#0*60);/gi, '<')
375
+ .replace(/&(?:gt|#0*62);/gi, '>')
376
+ .replace(/&(?:quot|#0*34);/gi, '"')
377
+ .replace(/&(?:#0*39|apos|#x0*27);/gi, "'")
378
+ .replace(/&nbsp;/gi, ' ');
379
+ }
380
+
381
+ /** The conventional "what went wrong" field, under any of the names upstreams
382
+ * actually use. Checked in order; first non-empty string wins. */
383
+ const MESSAGE_KEYS = [
384
+ 'message', 'error_message', 'errorMessage', 'detail', 'details',
385
+ 'description', 'error_description', 'reason', 'title', 'fault',
386
+ ];
387
+
388
+ function messageFromJson(raw: string): string | null {
389
+ let parsed: unknown;
390
+ try {
391
+ parsed = JSON.parse(raw);
392
+ } catch {
393
+ return null;
394
+ }
395
+ return pickMessage(parsed, 0);
396
+ }
397
+
398
+ function pickMessage(node: unknown, depth: number): string | null {
399
+ // Two levels covers `{error: {message}}` and `{errors: [{detail}]}`, the two
400
+ // shapes that account for nearly all of them, without walking a large payload.
401
+ if (depth > 2 || node == null) return null;
402
+
403
+ if (typeof node === 'string') return node.trim() || null;
404
+
405
+ if (Array.isArray(node)) {
406
+ for (const item of node) {
407
+ const found = pickMessage(item, depth + 1);
408
+ if (found) return found;
409
+ }
410
+ return null;
411
+ }
412
+
413
+ if (typeof node !== 'object') return null;
414
+ const obj = node as Record<string, unknown>;
415
+
416
+ for (const key of MESSAGE_KEYS) {
417
+ const v = obj[key];
418
+ if (typeof v === 'string' && v.trim()) return v.trim();
419
+ }
420
+ // `{error: …}` where error is itself an object or a string — the single most
421
+ // common wrapper, so it is worth descending into by name rather than scanning
422
+ // every key and risking picking up an echoed request parameter.
423
+ for (const key of ['error', 'errors', 'fault', 'Error', 'data']) {
424
+ if (key in obj) {
425
+ const found = pickMessage(obj[key], depth + 1);
426
+ if (found) return found;
427
+ }
428
+ }
429
+ return null;
430
+ }
431
+
432
+ /** Errors are read in a single line of log output; newlines and runs of
433
+ * whitespace make a multi-line body unreadable there. */
434
+ function collapse(s: string): string {
435
+ return s.replace(/\s+/g, ' ').trim();
436
+ }
437
+
438
+ /**
439
+ * Was this failure OUR OWN web service? — the other half of `internal-db-class.ts`.
440
+ *
441
+ * fleet #1089 pulled failures from our own Postgres out of `upstream_down` by
442
+ * keying on the SQLSTATE inside PostgREST's four-key error envelope. That
443
+ * covered the majority and structurally could not cover the rest: the rest
444
+ * never reach Postgres, so they carry no SQLSTATE. What was left, measured over
445
+ * the 24h to 2026-09-02T15:00Z (fleet #1096):
446
+ *
447
+ * 5 pipeworx-catalog get_pack_tools Pipeworx catalog error: 522 — error code: 522
448
+ * 3 fleet fleet_list_open … upstream_down: Fleet task queue did not respond within 25s
449
+ *
450
+ * 521/522/523/526 are Cloudflare saying its edge could not reach an ORIGIN, and
451
+ * in both of those rows the origin is ours — `gateway.pipeworx.io` for the
452
+ * catalog pack (it self-fetches when the gateway hasn't injected a manifest),
453
+ * our own Supabase for fleet. There is no third party anywhere in either call.
454
+ * Same defect as #1089: our own outage filed under `upstream_down`, the one
455
+ * class that means "the source is unreachable and there is nothing for us to
456
+ * fix", which is why the problem-tools triage skips it.
457
+ *
458
+ * WHY NOT A WORDING RULE. The obvious fix is to match `fleet db error:` and
459
+ * `Pipeworx catalog error:` in classifyToolError. Each is emitted from exactly
460
+ * one site today, so it would work today. It would also rot the first time
461
+ * somebody rewords a label — silently, and in the direction of hiding our own
462
+ * outage, which is worse than the bug being fixed. Every prose rule in
463
+ * error-class.ts has needed widening as packs invented new wording (#409/#450/
464
+ * #584); that history is most of that file's comment budget.
465
+ *
466
+ * WHAT THIS KEYS ON INSTEAD: **the host the call actually reached.** A URL's
467
+ * hostname is a fact about the call, not a guess about its prose. Two
468
+ * consequences that a pack-level flag could not give us, and the reason the
469
+ * flag was rejected:
470
+ *
471
+ * - It describes the CALL, not the pack. `govcon-intel` fans out to our own
472
+ * Supabase AND to genuine third parties; `court-listener` holds our cache
473
+ * in Supabase and fetches courtlistener.com. An `internallyHosted: true` on
474
+ * either pack would relabel a real third-party outage as ours — inventing
475
+ * work, which is the same class of error in the opposite direction.
476
+ * - It covers every future internal pack for free, instead of one declared
477
+ * slug at a time.
478
+ *
479
+ * WHY IT SURVIVES A REWORD. The marker below is not matched as a literal by two
480
+ * separate files. `markInternalOrigin()` writes it and `internalHostMetricsClass()`
481
+ * reads it, both from the single exported `INTERNAL_ORIGIN_MARKER` constant in
482
+ * this module — so changing the wording changes both sides in the same edit and
483
+ * cannot desynchronise them. The pack's own label (`fleet db error:`,
484
+ * `Pipeworx catalog error:`) is not read at all: reword it freely, the class is
485
+ * unaffected. That is the property `stripClassPrefix` lacked when it drifted
486
+ * from its own classifier three times and needed a CI gate to hold them
487
+ * together.
488
+ *
489
+ * WHERE THE 5xx TEST LIVES. `markInternalOrigin` is called from the places that
490
+ * hold the real `Response` — `httpError`/`httpErrorMessage` and the timeout
491
+ * branch of `fetchWithTimeout` in `shared/src/http.ts` — so "is this an
492
+ * availability failure" is decided from the actual status code, never re-derived
493
+ * by scraping a number out of a sentence. A 404 from our own registry for a slug
494
+ * that does not exist is a caller's bad argument and is deliberately NOT marked.
495
+ */
496
+
497
+ /**
498
+ * OUR OWN web service was unreachable — not an upstream, and never `upstream_down`.
499
+ *
500
+ * ONE value, not three, unlike `internal_db_*`. That split existed because a
501
+ * slow query, an exhausted pool and an unknown SQLSTATE have different owners
502
+ * and different fixes. Here there is only one story to tell — an origin we run
503
+ * did not answer the edge — and one owner. A bucket with no distinct owner per
504
+ * value is decoration; #724 is what happens when a class holds several
505
+ * situations, and inventing sub-values ahead of a reason to act on them
506
+ * differently is the same mistake with the sign flipped.
507
+ *
508
+ * METRICS ONLY, exactly like PLATFORM_KEY_ERROR_CLASS and the internal_db
509
+ * values. `classifyToolError` still answers `upstream_down` for the retry and
510
+ * hint paths, which only care whether retrying or a sibling tool might work —
511
+ * and it might. Nothing a caller sees or is charged changes here.
512
+ *
513
+ * READ SIDE: this value is in BROKEN_TOOL_CLASSES, FAULT_CLASSES and
514
+ * ALL_ERROR_CLASSES in `workers/registry-api/src/index.ts`. All three, or it
515
+ * lands on no dashboard — fleet #721 is the warning, where the #719 split
516
+ * worked on the write side and was invisible for weeks.
517
+ */
518
+ const INTERNAL_SERVICE_UNREACHABLE_CLASS = 'internal_service_unreachable';
519
+
520
+ /**
521
+ * The token that carries "this origin is ours" from the call site to the
522
+ * classifier.
523
+ *
524
+ * Appended to the error message rather than attached to the Error object,
525
+ * because the object does not survive the trip: 275 packs return `{ error:
526
+ * string }` instead of throwing, the gateway reads `observedError` as a string,
527
+ * and the fleet pack rebuilds its error from a captured status + body across a
528
+ * retry loop. A property on an Error would be dropped by every one of those
529
+ * paths and the class would work in tests and vanish in production.
530
+ *
531
+ * Written as a sentence rather than a sigil because it is going to be read by
532
+ * whoever gets the error, and "our own service, not a third party" is the
533
+ * single most useful thing to tell them — fetchWithTimeout's own comment
534
+ * (fleet #1047) is about exactly this ambiguity, where blaming a healthy vendor
535
+ * by name sent the next person waiting for an outage that did not exist.
536
+ */
537
+ const INTERNAL_ORIGIN_MARKER = ' [pipeworx-hosted origin — our own service, not a third party]';
538
+
539
+ /**
540
+ * Supabase's data plane for a project is `<ref>.supabase.co`, where the ref is
541
+ * exactly twenty lowercase letters (ours is `pqauisounztsgdgfkhke`).
542
+ *
543
+ * Matching the shape rather than listing the ref keeps this correct when we add
544
+ * a project — `supabaseEnv` on a pack entry already points some packs at a
545
+ * second one — while still excluding `status.supabase.co`, which is Supabase's
546
+ * own status page and emphatically not our database. Verified 2026-09-02 by
547
+ * `grep -rhoE '[a-z0-9-]+\.supabase\.(co|in)' mcps shared workers scripts`: the
548
+ * only real project ref anywhere in the tree is ours, the rest are doc
549
+ * placeholders (`abc`, `xyz`, `example`) which this pattern also excludes. Same
550
+ * finding internal-db-class.ts relies on for the PostgREST envelope being ours
551
+ * by construction.
552
+ */
553
+ const SUPABASE_PROJECT_HOST = /^[a-z]{20}\.supabase\.(co|in)$/;
554
+
555
+ /**
556
+ * Is this a host WE run?
557
+ *
558
+ * Deliberately NOT including `*.workers.dev`: plenty of third-party APIs are
559
+ * hosted on workers.dev, so the suffix says where something runs and not who
560
+ * owns it. Every internal call we actually make goes to a `pipeworx.io`
561
+ * hostname or to our Supabase project, both of which are ownership facts.
562
+ *
563
+ * Returns false on anything unparseable rather than throwing — this runs inside
564
+ * an error path, and an error path that can itself throw turns a diagnosable
565
+ * failure into a mystery.
566
+ */
567
+ function isPipeworxOrigin(url: string | URL | undefined | null): boolean {
568
+ if (!url) return false;
569
+ let host: string;
570
+ try {
571
+ host = new URL(url instanceof URL ? url.href : url).hostname.toLowerCase();
572
+ } catch {
573
+ return false;
574
+ }
575
+ if (host === 'pipeworx.io' || host.endsWith('.pipeworx.io')) return true;
576
+ return SUPABASE_PROJECT_HOST.test(host);
577
+ }
578
+
579
+ /**
580
+ * Append the marker when this failure was OUR origin failing to answer.
581
+ *
582
+ * `status` is the HTTP status when there is one, and omitted for a timeout —
583
+ * where there is no response at all, and "the origin did not answer" is the
584
+ * whole observation. Statuses below 500 are left alone: a 404 from our own
585
+ * registry for a slug that does not exist is the caller's argument, not our
586
+ * outage, and marking it would put ordinary 404s on the incident dashboard.
587
+ *
588
+ * Idempotent, so a message that is wrapped and re-marked on the way up (the
589
+ * fleet pack's retry loop re-throws through two layers) carries the marker once.
590
+ */
591
+ function markInternalOrigin(
592
+ message: string,
593
+ url: string | URL | undefined | null,
594
+ status?: number,
595
+ ): string {
596
+ if (status !== undefined && status < 500) return message;
597
+ if (!isPipeworxOrigin(url)) return message;
598
+ if (message.includes(INTERNAL_ORIGIN_MARKER)) return message;
599
+ return message + INTERNAL_ORIGIN_MARKER;
600
+ }
601
+
602
+ /**
603
+ * Which blob4 value a failure from our own web services books as, or undefined
604
+ * if this is not one.
605
+ *
606
+ * Ordered AFTER `internalDbMetricsClass` at the call site: a PostgREST envelope
607
+ * from our own Supabase is a strictly more specific statement about the same
608
+ * row (which of our services, and why), and the two cannot disagree about
609
+ * whether the failure is ours.
610
+ */
611
+ function internalHostMetricsClass(error: string): string | undefined {
612
+ return error.includes(INTERNAL_ORIGIN_MARKER) ? INTERNAL_SERVICE_UNREACHABLE_CLASS : undefined;
613
+ }
614
+
615
+
616
+ /**
617
+ * ABN Lookup MCP — BYOK wrapper around the Australian Business Register's
618
+ * ABN Lookup JSON web services (https://abr.business.gov.au/json/).
619
+ *
620
+ * BYOK: every tool requires the caller's own ABR web-services GUID, passed
621
+ * as `_apiKey`. There is no platform key and none will be added — ABR issues
622
+ * a GUID only after a human accepts the Web Services Agreement (two
623
+ * checkboxes: terms + personal-info-sharing) under a registered identity, and
624
+ * that acceptance step cannot be done autonomously (fleet #1207, Bruce ruled
625
+ * BYOK 2026-09-03). Register free at
626
+ * https://abr.business.gov.au/Tools/WebServices.
627
+ *
628
+ * Tools:
629
+ * - abn_lookup: ABN -> legal name, entity type, status, GST registration,
630
+ * address (state/postcode), business names
631
+ * - abn_search: entity/business name -> ranked ABN matches
632
+ * - acn_lookup: ACN (company number) -> the same detail as abn_lookup
633
+ *
634
+ * IMPORTANT — response shape is UNVERIFIED beyond the no-GUID case:
635
+ * ABR's JSON endpoints return a fixed empty-field shell plus a `Message`
636
+ * string when the GUID is not recognised (confirmed live 2026-09-03, no
637
+ * fleet GUID exists to verify the populated/successful shape). The field
638
+ * *names* below (Abn, AbnStatus, EntityName, BusinessName[], etc.) come from
639
+ * ABR's published JSON sample URLs
640
+ * (https://abr.business.gov.au/json/AbnDetails.aspx?abn=...&guid=...).
641
+ * Mapping is defensive and always includes `raw` so a caller with a real key
642
+ * gets the full untouched payload even if a field name here is stale.
643
+ */
644
+
645
+
646
+ async function pwFetch(url: string | URL, init?: RequestInit): Promise<Response> {
647
+ const headers = { 'User-Agent': 'pipeworx-mcp-abn-lookup/1.0 (+https://pipeworx.io)', ...(init?.headers ?? {}) };
648
+ return fetchWithTimeout(url, { ...init, headers }, 'ABR ABN Lookup');
649
+ }
650
+
651
+ const BASE_URL = 'https://abr.business.gov.au/json/';
652
+ const REGISTER_URL = 'https://abr.business.gov.au/Tools/WebServices';
653
+
654
+ const KEY_DESC =
655
+ 'Your ABR web-services GUID. Requires an API key — this pack is BYOK: there is no platform key. Register free at ' +
656
+ REGISTER_URL +
657
+ ' (accept the Web Services Agreement to receive a GUID by email).';
658
+
659
+ const tools: McpToolExport['tools'] = [
660
+ {
661
+ name: 'abn_lookup',
662
+ description:
663
+ 'BYOK. Look up an Australian Business Number (ABN): returns legal entity name, entity type, ABN status (active/cancelled) with effective date, GST registration, address state/postcode, and registered business names. Requires your own ABR web-services GUID via _apiKey (register free at https://abr.business.gov.au/Tools/WebServices). Example: abn_lookup({ abn: "37067751151", _apiKey: "your-guid" })',
664
+ inputSchema: {
665
+ type: 'object',
666
+ properties: {
667
+ abn: {
668
+ type: 'string',
669
+ description: 'Australian Business Number, 11 digits, with or without spaces (e.g. "37 067 751 151" or "37067751151").',
670
+ },
671
+ _apiKey: { type: 'string', description: KEY_DESC },
672
+ },
673
+ required: ['abn', '_apiKey'],
674
+ },
675
+ },
676
+ {
677
+ name: 'abn_search',
678
+ description:
679
+ 'BYOK. Search the Australian Business Register by entity or business name and return ranked ABN matches. Requires your own ABR web-services GUID via _apiKey (register free at https://abr.business.gov.au/Tools/WebServices). Example: abn_search({ name: "Frame Promotional Products", _apiKey: "your-guid" })',
680
+ inputSchema: {
681
+ type: 'object',
682
+ properties: {
683
+ name: { type: 'string', description: 'Entity or business name to search for, e.g. "Frame Promotional Products".' },
684
+ state: {
685
+ type: 'string',
686
+ description:
687
+ 'Optional Australian state/territory abbreviation to filter results client-side (e.g. "NSW", "VIC"). Applied after the ABR search returns, matched against each result\'s state field when present.',
688
+ },
689
+ maxResults: {
690
+ type: 'number',
691
+ description: 'Maximum number of matches to return (ABR default is small; pass a higher number for more). Default 20.',
692
+ },
693
+ _apiKey: { type: 'string', description: KEY_DESC },
694
+ },
695
+ required: ['name', '_apiKey'],
696
+ },
697
+ },
698
+ {
699
+ name: 'acn_lookup',
700
+ description:
701
+ 'BYOK. Look up an Australian Company Number (ACN): returns the same detail as abn_lookup (legal entity name, entity type, ABN status, GST registration, address, business names) for the company\'s associated ABN. Requires your own ABR web-services GUID via _apiKey (register free at https://abr.business.gov.au/Tools/WebServices). Example: acn_lookup({ acn: "004085616", _apiKey: "your-guid" })',
702
+ inputSchema: {
703
+ type: 'object',
704
+ properties: {
705
+ acn: { type: 'string', description: 'Australian Company Number, 9 digits, with or without spaces.' },
706
+ _apiKey: { type: 'string', description: KEY_DESC },
707
+ },
708
+ required: ['acn', '_apiKey'],
709
+ },
710
+ },
711
+ ];
712
+
713
+ async function callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
714
+ const apiKey = args._apiKey as string | undefined;
715
+ delete args._apiKey;
716
+
717
+ if (!apiKey) {
718
+ throw new Error(
719
+ 'ABN Lookup requires an API key — this pack is BYOK, there is no platform key. Pass your own ABR web-services GUID via _apiKey. Register free at ' +
720
+ REGISTER_URL +
721
+ ' (accept the Web Services Agreement and ABR emails you a GUID).',
722
+ );
723
+ }
724
+
725
+ switch (name) {
726
+ case 'abn_lookup':
727
+ return abnLookup(args.abn as string | undefined, apiKey);
728
+ case 'abn_search':
729
+ return abnSearch(
730
+ args.name as string | undefined,
731
+ args.state as string | undefined,
732
+ args.maxResults as number | undefined,
733
+ apiKey,
734
+ );
735
+ case 'acn_lookup':
736
+ return acnLookup(args.acn as string | undefined, apiKey);
737
+ default:
738
+ throw new Error(`Unknown tool: ${name}`);
739
+ }
740
+ }
741
+
742
+ // ABR's JSON endpoints wrap the payload in a JSONP callback whose name
743
+ // follows whatever `callback=` param we send (confirmed live 2026-09-03:
744
+ // callback=myFunc123 -> `myFunc123({...})`; omitted -> defaults to
745
+ // `callback({...})`). Strip generically by function name rather than
746
+ // hardcoding "callback".
747
+ function unwrapJsonp(text: string): unknown {
748
+ const match = text.match(/^\s*[\w$]+\s*\((.*)\)\s*;?\s*$/s);
749
+ const body = match ? match[1] : text;
750
+ return JSON.parse(body);
751
+ }
752
+
753
+ interface AbrDetailResponse {
754
+ Abn?: string;
755
+ AbnStatus?: string;
756
+ AbnStatusEffectiveFrom?: string;
757
+ Acn?: string;
758
+ AddressDate?: string | null;
759
+ AddressPostcode?: string;
760
+ AddressState?: string;
761
+ BusinessName?: string[];
762
+ EntityName?: string;
763
+ EntityTypeCode?: string;
764
+ EntityTypeName?: string;
765
+ Gst?: string | null;
766
+ Message?: string;
767
+ }
768
+
769
+ function normalizeAbn(abn: string): string {
770
+ return abn.replace(/\s+/g, '');
771
+ }
772
+
773
+ async function fetchAbr<T>(path: string, params: Record<string, string>, apiKey: string, tool: string): Promise<T> {
774
+ const qs = new URLSearchParams({ ...params, guid: apiKey, callback: 'callback' });
775
+ let res: Response;
776
+ try {
777
+ res = await pwFetch(`${BASE_URL}${path}?${qs}`);
778
+ } catch (e) {
779
+ throw new Error(`ABN Lookup ${tool}: network error reaching ABR — ${(e as Error).message}`);
780
+ }
781
+ if (!res.ok) {
782
+ throw new Error(`ABN Lookup ${tool}: ABR returned HTTP ${res.status}. Check your ABR _apiKey (GUID) and the input.`);
783
+ }
784
+ const text = await res.text();
785
+ let data: T;
786
+ try {
787
+ data = unwrapJsonp(text) as T;
788
+ } catch {
789
+ // Extract meaning rather than pasting the raw body into a caller-facing
790
+ // error (check:error-body-leak, fleet #712) — ABR's unparseable response
791
+ // is most often an HTML interstitial or an XML fault, and summarizeErrorBody
792
+ // pulls the human sentence out of either without handing the agent markup.
793
+ const summary = summarizeErrorBody(text);
794
+ throw new Error(
795
+ `ABN Lookup ${tool}: ABR returned an unparseable response (unexpected)${summary ? ` — ${summary}` : ''}.`,
796
+ );
797
+ }
798
+ return data;
799
+ }
800
+
801
+ // ABR returns HTTP 200 with an all-empty field shell plus a `Message` string
802
+ // for every rejected-GUID or not-found case (verified live 2026-09-03: "The
803
+ // GUID entered is not recognised as a Registered Party" when the GUID is
804
+ // invalid; ABR also uses Message for "not found" and other soft errors). An
805
+ // empty core field (Abn/Acn/EntityName) alongside a non-empty Message means
806
+ // we cannot distinguish "key rejected" from "record not found" from the
807
+ // response alone — say so explicitly rather than claiming one or the other.
808
+ function detailResult(data: AbrDetailResponse, tool: string, coreField: 'Abn' | 'Acn') {
809
+ const core = data[coreField];
810
+ if (!core && data.Message) {
811
+ throw new Error(
812
+ `ABN Lookup ${tool}: ABR returned no record (Message: "${data.Message}"). This can mean the _apiKey (GUID) was rejected, or the ${coreField} has no matching record — ABR's response does not distinguish the two. Verify your GUID at ${REGISTER_URL}, and double-check the ${coreField}.`,
813
+ );
814
+ }
815
+ return {
816
+ abn: data.Abn || undefined,
817
+ acn: data.Acn || undefined,
818
+ entity_name: data.EntityName || undefined,
819
+ entity_type_code: data.EntityTypeCode || undefined,
820
+ entity_type_name: data.EntityTypeName || undefined,
821
+ abn_status: data.AbnStatus || undefined,
822
+ abn_status_effective_from: data.AbnStatusEffectiveFrom || undefined,
823
+ gst_registered: data.Gst ? true : data.Gst === '' ? undefined : false,
824
+ gst_effective_from: typeof data.Gst === 'string' && data.Gst ? data.Gst : undefined,
825
+ address_state: data.AddressState || undefined,
826
+ address_postcode: data.AddressPostcode || undefined,
827
+ address_date: data.AddressDate || undefined,
828
+ business_names: Array.isArray(data.BusinessName) ? data.BusinessName : [],
829
+ raw: data,
830
+ };
831
+ }
832
+
833
+ async function abnLookup(abn: string | undefined, apiKey: string) {
834
+ if (!abn) throw new Error('ABN Lookup abn_lookup requires an `abn` (11-digit Australian Business Number).');
835
+ const data = await fetchAbr<AbrDetailResponse>('AbnDetails.aspx', { abn: normalizeAbn(abn) }, apiKey, 'abn_lookup');
836
+ return detailResult(data, 'abn_lookup', 'Abn');
837
+ }
838
+
839
+ async function acnLookup(acn: string | undefined, apiKey: string) {
840
+ if (!acn) throw new Error('ABN Lookup acn_lookup requires an `acn` (9-digit Australian Company Number).');
841
+ const data = await fetchAbr<AbrDetailResponse>('AcnDetails.aspx', { acn: normalizeAbn(acn) }, apiKey, 'acn_lookup');
842
+ return detailResult(data, 'acn_lookup', 'Acn');
843
+ }
844
+
845
+ interface AbrNameMatch {
846
+ Name?: string;
847
+ Abn?: string;
848
+ Score?: number;
849
+ State?: string;
850
+ Postcode?: string;
851
+ IsCurrentIndicator?: string;
852
+ [k: string]: unknown;
853
+ }
854
+
855
+ interface AbrSearchResponse {
856
+ Names?: AbrNameMatch[];
857
+ Message?: string;
858
+ }
859
+
860
+ async function abnSearch(name: string | undefined, state: string | undefined, maxResults: number | undefined, apiKey: string) {
861
+ if (!name) throw new Error('ABN Lookup abn_search requires a `name` (entity or business name to search for).');
862
+ const data = await fetchAbr<AbrSearchResponse>(
863
+ 'MatchingNames.aspx',
864
+ { name, maxResults: String(maxResults ?? 20) },
865
+ apiKey,
866
+ 'abn_search',
867
+ );
868
+
869
+ const names = Array.isArray(data.Names) ? data.Names : [];
870
+ if (names.length === 0 && data.Message) {
871
+ throw new Error(
872
+ `ABN Lookup abn_search: ABR returned no matches (Message: "${data.Message}"). This can mean the _apiKey (GUID) was rejected, or there were genuinely no matches for "${name}" — ABR's response does not distinguish the two. Verify your GUID at ${REGISTER_URL}.`,
873
+ );
874
+ }
875
+
876
+ const filtered = state
877
+ ? names.filter((n) => typeof n.State === 'string' && n.State.toUpperCase() === state.toUpperCase())
878
+ : names;
879
+
880
+ return {
881
+ query: name,
882
+ state_filter: state || undefined,
883
+ match_count: filtered.length,
884
+ matches: filtered.map((n) => ({
885
+ name: n.Name,
886
+ abn: n.Abn,
887
+ score: n.Score,
888
+ state: n.State,
889
+ postcode: n.Postcode,
890
+ is_current: n.IsCurrentIndicator,
891
+ })),
892
+ raw: data,
893
+ };
894
+ }
895
+
896
+ export default { tools, callTool, meter: { credits: 1 } } satisfies McpToolExport;
package/src/server.ts ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Stdio MCP server entry point for @pipeworx/mcp-abn-lookup.
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
+ const server = new Server(
12
+ { name: '@pipeworx/mcp-abn-lookup', version: '0.1.0' },
13
+ { capabilities: { tools: {} } },
14
+ );
15
+
16
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
17
+ tools: pack.tools.map((t) => ({
18
+ name: t.name,
19
+ description: t.description,
20
+ inputSchema: t.inputSchema,
21
+ })),
22
+ }));
23
+
24
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
25
+ const { name, arguments: args } = request.params;
26
+ try {
27
+ const result = await pack.callTool(name, (args ?? {}) as Record<string, unknown>);
28
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
29
+ } catch (err) {
30
+ return {
31
+ content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }],
32
+ isError: true,
33
+ };
34
+ }
35
+ });
36
+
37
+ async function main() {
38
+ const transport = new StdioServerTransport();
39
+ await server.connect(transport);
40
+ }
41
+
42
+ main().catch((err) => {
43
+ console.error('Fatal error running server:', err);
44
+ process.exit(1);
45
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "strict": true,
7
+ "esModuleInterop": true,
8
+ "skipLibCheck": true,
9
+ "outDir": "dist",
10
+ "rootDir": "src",
11
+ "declaration": true
12
+ },
13
+ "include": ["src"],
14
+ "exclude": ["src/server.ts"]
15
+ }