@pipeworx/mcp-alchemy-eth 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,129 @@
1
+ # @pipeworx/alchemy-eth
2
+
3
+ [Alchemy](https://docs.alchemy.com/) MCP — Ethereum + L2 enhanced RPC (NFT, token, txn enrichment endpoints). Free key 300M compute units/mo.
4
+
5
+ Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 1558+ live data sources.
6
+
7
+ ## Auth
8
+
9
+ - Platform: `PLATFORM_ALCHEMY_KEY`. BYO: `?_apiKey=…`.
10
+ - Chain selector: pass `chain` to most tools (`eth-mainnet` (default) | `eth-sepolia` | `polygon-mainnet` | `arb-mainnet` | `opt-mainnet` | `base-mainnet`).
11
+
12
+ ## Tools (Core RPC passthrough)
13
+
14
+ - `eth_call(method, params, chain?)` — generic JSON-RPC call
15
+
16
+ ## Tools (Token API)
17
+
18
+ - `token_balances(address, contracts?, chain?)` — ERC-20 balances
19
+ - `token_metadata(contract, chain?)` — ERC-20 metadata
20
+ - `token_allowance(contract, owner, spender, chain?)` — allowance
21
+
22
+ ## Tools (NFT API)
23
+
24
+ - `nfts_owned(owner, contracts?, page_key?, page_size?, chain?)` — NFTs owned by address
25
+ - `nft_metadata(contract, tokenId, refresh_cache?, chain?)` — single NFT metadata
26
+ - `nfts_for_collection(contract, withMetadata?, startToken?, limit?, chain?)` — NFTs in a collection
27
+ - `nft_owners(contract, tokenId?, chain?)` — owners of a contract / token
28
+
29
+ ## Tools (Transfers + Webhooks)
30
+
31
+ - `asset_transfers(from?, to?, contract_addresses?, category?, fromBlock?, toBlock?, order?, withMetadata?, excludeZeroValue?, maxCount?, pageKey?, chain?)` — enhanced transfer feed
32
+
33
+ ## Data source
34
+
35
+ `https://<chain>.g.alchemy.com/v2/<key>` (RPC), `https://<chain>.g.alchemy.com/nft/v3/<key>` (NFT v3)
36
+
37
+ ## Quick Start
38
+
39
+ Add to your MCP client (Claude Desktop, Cursor, Windsurf, etc.):
40
+
41
+ ```json
42
+ {
43
+ "mcpServers": {
44
+ "alchemy-eth": {
45
+ "url": "https://gateway.pipeworx.io/alchemy-eth/mcp"
46
+ }
47
+ }
48
+ }
49
+ ```
50
+
51
+ ### What this endpoint actually serves
52
+
53
+ `tools/list` at `https://gateway.pipeworx.io/alchemy-eth/mcp` returns the tools in the table
54
+ above **plus the shared Pipeworx meta-tools** — `ask_pipeworx`,
55
+ `discover_tools`, `search_within`, `remember`/`recall` and the rest of the
56
+ gateway-wide set. So the tool count you see is larger than this table: a
57
+ single-pack endpoint currently lists roughly 30 shared tools alongside the
58
+ pack's own. The connection's `initialize` response states its exact scope, and
59
+ is the authoritative answer for a given day.
60
+
61
+ This is deliberate, not multiplexing by accident. The meta-tools are what let a
62
+ scoped connection answer a question this pack does not cover — via
63
+ `ask_pipeworx`, which routes across the whole catalog — without you adding a
64
+ second MCP server. There is currently no way to mount a pack endpoint without
65
+ them; if the extra schemas cost you more context than the routing is worth,
66
+ connect to the full gateway once rather than to several pack endpoints.
67
+
68
+ Or connect to the full Pipeworx gateway to get every pack's tools listed
69
+ directly, instead of just this one's:
70
+
71
+ ```json
72
+ {
73
+ "mcpServers": {
74
+ "pipeworx": {
75
+ "url": "https://gateway.pipeworx.io/mcp"
76
+ }
77
+ }
78
+ }
79
+ ```
80
+
81
+ Both URLs reach the same gateway and the same 1558+ data sources. The
82
+ only difference is which pack's tools are listed **directly**; `ask_pipeworx`
83
+ reaches all of them from either one.
84
+
85
+ ## Standalone (no gateway account)
86
+
87
+ This package also runs as a local stdio MCP server — no Pipeworx account, no
88
+ gateway round-trip:
89
+
90
+ ```json
91
+ {
92
+ "mcpServers": {
93
+ "alchemy-eth": {
94
+ "command": "npx",
95
+ "args": ["-y", "@pipeworx/mcp-alchemy-eth"]
96
+ }
97
+ }
98
+ }
99
+ ```
100
+
101
+ Or run it directly to confirm it starts:
102
+
103
+ ```bash
104
+ npx -y @pipeworx/mcp-alchemy-eth
105
+ ```
106
+
107
+ It speaks MCP over stdin/stdout and answers `initialize`/`tools/list`/`tools/call`
108
+ for **only** this pack's tools — none of the shared meta-tools the gateway
109
+ connection above adds. Same source, same tools, no ask_pipeworx routing.
110
+
111
+ ## Using with ask_pipeworx
112
+
113
+ Instead of calling tools directly, you can ask questions in plain English —
114
+ this works on the pack endpoint above as well as on the full gateway:
115
+
116
+ ```
117
+ ask_pipeworx({ question: "your question about Alchemy Eth data" })
118
+ ```
119
+
120
+ The gateway picks the right tool and fills the arguments automatically.
121
+
122
+ ## More
123
+
124
+ - [Docs and guides](https://pipeworx.io/docs)
125
+ - [pipeworx.io](https://pipeworx.io)
126
+
127
+ ## License
128
+
129
+ 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-alchemy-eth",
3
+ "version": "0.1.0",
4
+ "description": "Alchemy (Ethereum + L2) MCP.",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "bin": {
9
+ "mcp-alchemy-eth": "bin/cli.js"
10
+ },
11
+ "keywords": ["mcp", "mcp-server", "model-context-protocol", "pipeworx", "alchemy-eth"],
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/pipeworx-io/mcp-alchemy-eth.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/alchemy-eth",
4
+ "title": "Alchemy Eth",
5
+ "description": "Alchemy (Ethereum + L2) MCP.",
6
+ "version": "0.1.0",
7
+ "websiteUrl": "https://pipeworx.io/packs/alchemy-eth",
8
+ "repository": {
9
+ "url": "https://github.com/pipeworx-io/mcp-alchemy-eth",
10
+ "source": "github"
11
+ },
12
+ "remotes": [
13
+ {
14
+ "type": "streamable-http",
15
+ "url": "https://gateway.pipeworx.io/alchemy-eth/mcp"
16
+ }
17
+ ]
18
+ }
package/src/index.ts ADDED
@@ -0,0 +1,768 @@
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
+ * Alchemy (Ethereum + L2) MCP.
618
+ */
619
+
620
+
621
+ // Bound every fetch() in this pack to a fixed timeout — an upstream that
622
+ // degrades without erroring would otherwise hold the Worker in `await fetch()`
623
+ // until its own execution budget kills the request (minutes, not seconds).
624
+ // Mirrors the epoFetch / usaspending retryFetch pattern (fleet #685).
625
+ async function pwFetch(url: string | URL, init?: RequestInit): Promise<Response> {
626
+ return fetchWithTimeout(url, init ?? {}, 'Alchemy');
627
+ }
628
+
629
+ const UA = 'pipeworx-mcp-alchemy-eth/1.0 (+https://pipeworx.io)';
630
+
631
+ const tools: McpToolExport['tools'] = [
632
+ {
633
+ name: 'eth_call',
634
+ description: 'Execute any Ethereum JSON-RPC method (e.g. eth_blockNumber, eth_getBalance, eth_getTransactionByHash) on the specified chain (default: eth-mainnet) via Alchemy; pass method name and params array.',
635
+ inputSchema: {
636
+ type: 'object',
637
+ properties: { method: { type: 'string' }, params: {}, chain: { type: 'string' } },
638
+ required: ['method'],
639
+ },
640
+ },
641
+ {
642
+ name: 'token_balances',
643
+ description: 'ERC-20 balances.',
644
+ inputSchema: { type: 'object', properties: { address: { type: 'string' }, contracts: { type: 'array', items: { type: 'string' } }, chain: { type: 'string' } }, required: ['address'] },
645
+ },
646
+ { name: 'token_metadata', description: 'ERC-20 metadata.', inputSchema: { type: 'object', properties: { contract: { type: 'string' }, chain: { type: 'string' } }, required: ['contract'] } },
647
+ {
648
+ name: 'token_allowance',
649
+ description: 'ERC-20 allowance.',
650
+ inputSchema: { type: 'object', properties: { contract: { type: 'string' }, owner: { type: 'string' }, spender: { type: 'string' }, chain: { type: 'string' } }, required: ['contract', 'owner', 'spender'] },
651
+ },
652
+ {
653
+ name: 'nfts_owned',
654
+ description: 'NFTs owned by address.',
655
+ inputSchema: {
656
+ type: 'object',
657
+ properties: { owner: { type: 'string' }, contracts: { type: 'string' }, page_key: { type: 'string' }, page_size: { type: 'number' }, chain: { type: 'string' } },
658
+ required: ['owner'],
659
+ },
660
+ },
661
+ {
662
+ name: 'nft_metadata',
663
+ description: 'Single NFT metadata.',
664
+ inputSchema: {
665
+ type: 'object',
666
+ properties: { contract: { type: 'string' }, tokenId: { type: 'string' }, refresh_cache: { type: 'boolean' }, chain: { type: 'string' } },
667
+ required: ['contract', 'tokenId'],
668
+ },
669
+ },
670
+ {
671
+ name: 'nfts_for_collection',
672
+ description: 'NFTs in a collection.',
673
+ inputSchema: {
674
+ type: 'object',
675
+ properties: { contract: { type: 'string' }, withMetadata: { type: 'boolean' }, startToken: { type: 'string' }, limit: { type: 'number' }, chain: { type: 'string' } },
676
+ required: ['contract'],
677
+ },
678
+ },
679
+ {
680
+ name: 'nft_owners',
681
+ description: 'Owners of a contract/token.',
682
+ inputSchema: { type: 'object', properties: { contract: { type: 'string' }, tokenId: { type: 'string' }, chain: { type: 'string' } }, required: ['contract'] },
683
+ },
684
+ {
685
+ name: 'asset_transfers',
686
+ description: 'Fetch Ethereum asset transfer history via Alchemy\'s alchemy_getAssetTransfers RPC on the specified chain; accepts fromBlock, toBlock, fromAddress, toAddress, contractAddresses, category, and maxCount as passthrough params.',
687
+ inputSchema: { type: 'object', properties: {} },
688
+ },
689
+ ];
690
+
691
+ function chainHost(chain: string | undefined): string {
692
+ const c = chain && chain.length > 0 ? chain : 'eth-mainnet';
693
+ // SSRF / key-exfil guard: `chain` is caller-supplied and the API key is in the
694
+ // URL PATH (https://${chain}.g.alchemy.com/v2/${apiKey}), so a value like
695
+ // "evil.com/" would resolve the host to evil.com and leak the (platform) key.
696
+ // Alchemy network slugs are bare labels (eth-mainnet, base-sepolia, …).
697
+ if (!/^[a-z0-9-]+$/i.test(c)) {
698
+ throw new Error(`Alchemy: invalid chain "${c}" — expected a network slug like "eth-mainnet".`);
699
+ }
700
+ return c;
701
+ }
702
+
703
+ async function callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
704
+ const apiKey = (args._apiKey as string | undefined)?.trim();
705
+ if (!apiKey) throw new Error('Alchemy requires an API key: pass your key as the _apiKey argument (free at https://dashboard.alchemy.com/).');
706
+ const chain = chainHost(args.chain as string | undefined);
707
+ const rpcUrl = `https://${chain}.g.alchemy.com/v2/${apiKey}`;
708
+ const nftBase = `https://${chain}.g.alchemy.com/nft/v3/${apiKey}`;
709
+
710
+ const rpc = async (method: string, params: unknown[]) => {
711
+ const res = await pwFetch(rpcUrl, {
712
+ method: 'POST',
713
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': UA },
714
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
715
+ });
716
+ if (res.status === 401 || res.status === 403) throw new Error('Alchemy: invalid API key.');
717
+ if (!res.ok) throw await httpError(res, 'Alchemy');
718
+ const j = (await res.json()) as { result?: unknown; error?: { message?: string } };
719
+ if (j.error) throw new Error(`Alchemy RPC: ${j.error.message ?? 'error'}`);
720
+ return j.result;
721
+ };
722
+ const nftGet = async (path: string, params?: Record<string, unknown>) => {
723
+ const p = new URLSearchParams();
724
+ if (params) for (const [k, v] of Object.entries(params)) if (k !== '_apiKey' && k !== 'chain' && v != null) p.set(k, String(v));
725
+ const res = await pwFetch(`${nftBase}${path}${[...p].length ? `?${p}` : ''}`, { headers: { Accept: 'application/json', 'User-Agent': UA } });
726
+ if (res.status === 401 || res.status === 403) throw new Error('Alchemy: invalid API key.');
727
+ if (!res.ok) throw await httpError(res, 'Alchemy NFT');
728
+ return res.json();
729
+ };
730
+ const reqStr = (k: string, ex: string) => {
731
+ const v = args[k];
732
+ if (typeof v !== 'string' || !v.trim()) throw new Error(`Required argument "${k}" is missing. Pass a string like ${ex}.`);
733
+ return v;
734
+ };
735
+ switch (name) {
736
+ case 'eth_call': {
737
+ const method = reqStr('method', '"eth_blockNumber"');
738
+ const params = Array.isArray(args.params) ? args.params : [];
739
+ return rpc(method, params);
740
+ }
741
+ case 'token_balances':
742
+ return rpc('alchemy_getTokenBalances', [reqStr('address', '"0x..."'), args.contracts ?? 'DEFAULT_TOKENS']);
743
+ case 'token_metadata':
744
+ return rpc('alchemy_getTokenMetadata', [reqStr('contract', '"0x..."')]);
745
+ case 'token_allowance':
746
+ return rpc('alchemy_getTokenAllowance', [{ contract: reqStr('contract', '"0x..."'), owner: reqStr('owner', '"0x..."'), spender: reqStr('spender', '"0x..."') }]);
747
+ case 'nfts_owned':
748
+ return nftGet('/getNFTsForOwner', { owner: reqStr('owner', '"0x..."'), contractAddresses: args.contracts, pageKey: args.page_key, pageSize: args.page_size });
749
+ case 'nft_metadata':
750
+ return nftGet('/getNFTMetadata', { contractAddress: reqStr('contract', '"0x..."'), tokenId: reqStr('tokenId', '"123"'), refreshCache: args.refresh_cache });
751
+ case 'nfts_for_collection':
752
+ return nftGet('/getNFTsForContract', { contractAddress: reqStr('contract', '"0x..."'), withMetadata: args.withMetadata, startToken: args.startToken, limit: args.limit });
753
+ case 'nft_owners':
754
+ return nftGet('/getOwnersForContract', { contractAddress: reqStr('contract', '"0x..."'), tokenId: args.tokenId });
755
+ case 'asset_transfers': {
756
+ const params: Record<string, unknown> = {};
757
+ for (const [k, v] of Object.entries(args)) {
758
+ if (k === '_apiKey' || k === 'chain') continue;
759
+ if (v != null) params[k] = v;
760
+ }
761
+ return rpc('alchemy_getAssetTransfers', [params]);
762
+ }
763
+ default:
764
+ throw new Error(`Unknown tool: ${name}`);
765
+ }
766
+ }
767
+
768
+ 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-alchemy-eth.
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-alchemy-eth', 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
+ }