util-beauty-mcp 1.0.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +37 -0
  3. package/package.json +33 -0
  4. package/src/index.mjs +289 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Undercurrent Labs LLC
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,37 @@
1
+ # util-beauty-mcp
2
+
3
+ Thin [MCP](https://modelcontextprotocol.io) stdio server for [util.beauty](https://util.beauty).
4
+
5
+ **Three tools only** (low context cost):
6
+
7
+ | Tool | Purpose |
8
+ |---|---|
9
+ | `list_utilities` | Live catalog from `GET /v1/meta` |
10
+ | `describe_utility` | OpenAPI request schema for one utility |
11
+ | `call_utility` | Paid POST (x402 or API key) |
12
+
13
+ ## Run
14
+
15
+ ```bash
16
+ cd mcp && npm install
17
+ export X402_PRIVATE_KEY=0x... # USDC on Base
18
+ # optional: export UB_API_KEY=ub_...
19
+ # optional: export UTIL_BEAUTY_BASE_URL=https://util.beauty
20
+ npx util-beauty-mcp
21
+ ```
22
+
23
+ ## Claude Code
24
+
25
+ ```bash
26
+ claude mcp add util-beauty \
27
+ -e X402_PRIVATE_KEY=0x... \
28
+ -- npx -y util-beauty-mcp
29
+ ```
30
+
31
+ ## Design
32
+
33
+ Schemas are **not** embedded in tool definitions. Agents must list → describe → call, which matches util.beauty’s `/v1/meta` + OpenAPI discovery model and keeps `tools/list` small.
34
+
35
+ Payment for `call_utility` reuses the same EIP-3009 flow as production x402 (viem), without requiring `@x402/fetch` to understand util.beauty’s 402 envelope.
36
+
37
+ See https://util.beauty/mcp and https://util.beauty/skill.md.
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "util-beauty-mcp",
3
+ "version": "1.0.0",
4
+ "description": "Thin MCP server for util.beauty — list_utilities, describe_utility, call_utility (discover-then-call, low context).",
5
+ "type": "module",
6
+ "bin": {
7
+ "util-beauty-mcp": "./src/index.mjs"
8
+ },
9
+ "files": [
10
+ "src"
11
+ ],
12
+ "scripts": {
13
+ "start": "node src/index.mjs"
14
+ },
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "dependencies": {
19
+ "@modelcontextprotocol/sdk": "^1.12.1",
20
+ "viem": "^2.55.0",
21
+ "zod": "^3.25.0"
22
+ },
23
+ "keywords": [
24
+ "mcp",
25
+ "x402",
26
+ "util.beauty",
27
+ "agents"
28
+ ],
29
+ "license": "MIT",
30
+ "author": "Undercurrent Labs LLC",
31
+ "homepage": "https://util.beauty/mcp",
32
+ "bugs": "https://util.beauty/contact"
33
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,289 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * util-beauty-mcp — discover-then-call MCP server.
4
+ *
5
+ * Tools (intentionally tiny schemas):
6
+ * list_utilities → GET /v1/meta
7
+ * describe_utility → OpenAPI request body for one utility
8
+ * call_utility → POST paid endpoint (x402 or API key)
9
+ *
10
+ * Env:
11
+ * UTIL_BEAUTY_BASE_URL default https://util.beauty
12
+ * X402_PRIVATE_KEY hex EVM key with USDC on Base
13
+ * UB_API_KEY optional prepaid key
14
+ */
15
+ import { randomBytes, randomUUID } from "node:crypto";
16
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
17
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
18
+ import { z } from "zod";
19
+ import { privateKeyToAccount } from "viem/accounts";
20
+
21
+ const BASE = (process.env.UTIL_BEAUTY_BASE_URL ?? "https://util.beauty").replace(/\/$/, "");
22
+ const CHAIN_IDS = { base: 8453, "base-sepolia": 84532 };
23
+
24
+ /** @type {{ doc: object, fetchedAt: number } | null} */
25
+ let openapiCache = null;
26
+ const OPENAPI_TTL_MS = 10 * 60 * 1000;
27
+
28
+ function textResult(data, isError = false) {
29
+ const text = typeof data === "string" ? data : JSON.stringify(data, null, 2);
30
+ return { content: [{ type: "text", text }], isError };
31
+ }
32
+
33
+ async function fetchJson(url, init) {
34
+ const res = await fetch(url, init);
35
+ const text = await res.text();
36
+ let body;
37
+ try {
38
+ body = text ? JSON.parse(text) : null;
39
+ } catch {
40
+ body = { raw: text.slice(0, 2000) };
41
+ }
42
+ return { res, body };
43
+ }
44
+
45
+ async function getOpenApi() {
46
+ const now = Date.now();
47
+ if (openapiCache && now - openapiCache.fetchedAt < OPENAPI_TTL_MS) {
48
+ return openapiCache.doc;
49
+ }
50
+ const { res, body } = await fetchJson(`${BASE}/openapi.json`);
51
+ if (!res.ok) throw new Error(`openapi.json HTTP ${res.status}`);
52
+ openapiCache = { doc: body, fetchedAt: now };
53
+ return body;
54
+ }
55
+
56
+ function pathForUtility(utility) {
57
+ return `/v1/${utility.replace(".", "/")}`;
58
+ }
59
+
60
+ function schemaForUtility(openapi, utility) {
61
+ const path = pathForUtility(utility);
62
+ const op = openapi.paths?.[path]?.post;
63
+ if (!op) {
64
+ return {
65
+ utility,
66
+ path,
67
+ note: "No POST operation in OpenAPI for this utility. Check /v1/meta.",
68
+ };
69
+ }
70
+ const ref = op.requestBody?.content?.["application/json"]?.schema;
71
+ let schema = ref;
72
+ if (ref?.$ref) {
73
+ const name = ref.$ref.split("/").pop();
74
+ schema = openapi.components?.schemas?.[name] ?? ref;
75
+ }
76
+ return {
77
+ utility,
78
+ path: `${BASE}${path}`,
79
+ method: "POST",
80
+ summary: op.summary ?? op.description ?? null,
81
+ requestBodySchema: schema ?? null,
82
+ notes: [
83
+ "Browser utilities: provide exactly one of url or html.",
84
+ "Crypto utilities: binary fields are base64-encoded.",
85
+ "Always send Idempotency-Key on paid calls.",
86
+ "Billing is per-attempt after validation (VALIDATION_ERROR is free).",
87
+ ],
88
+ };
89
+ }
90
+
91
+ async function signX402Payment(accepts0) {
92
+ const key = process.env.X402_PRIVATE_KEY;
93
+ if (!key) throw new Error("X402_PRIVATE_KEY is not set");
94
+ const raw = key.startsWith("0x") ? key : `0x${key}`;
95
+ const account = privateKeyToAccount(/** @type {`0x${string}`} */ (raw));
96
+ const chainId = CHAIN_IDS[accepts0.network];
97
+ if (!chainId) throw new Error(`Unsupported x402 network: ${accepts0.network}`);
98
+
99
+ const now = Math.floor(Date.now() / 1000);
100
+ const authorization = {
101
+ from: account.address,
102
+ to: accepts0.payTo,
103
+ value: BigInt(accepts0.maxAmountRequired),
104
+ validAfter: BigInt(now - 60),
105
+ validBefore: BigInt(now + (accepts0.maxTimeoutSeconds ?? 300)),
106
+ nonce: `0x${randomBytes(32).toString("hex")}`,
107
+ };
108
+ const signature = await account.signTypedData({
109
+ domain: {
110
+ name: accepts0.extra?.name ?? "USD Coin",
111
+ version: accepts0.extra?.version ?? "2",
112
+ chainId,
113
+ verifyingContract: accepts0.asset,
114
+ },
115
+ types: {
116
+ TransferWithAuthorization: [
117
+ { name: "from", type: "address" },
118
+ { name: "to", type: "address" },
119
+ { name: "value", type: "uint256" },
120
+ { name: "validAfter", type: "uint256" },
121
+ { name: "validBefore", type: "uint256" },
122
+ { name: "nonce", type: "bytes32" },
123
+ ],
124
+ },
125
+ primaryType: "TransferWithAuthorization",
126
+ message: authorization,
127
+ });
128
+
129
+ const payload = {
130
+ x402Version: 1,
131
+ scheme: accepts0.scheme,
132
+ network: accepts0.network,
133
+ payload: {
134
+ signature,
135
+ authorization: {
136
+ from: authorization.from,
137
+ to: authorization.to,
138
+ value: authorization.value.toString(),
139
+ validAfter: authorization.validAfter.toString(),
140
+ validBefore: authorization.validBefore.toString(),
141
+ nonce: authorization.nonce,
142
+ },
143
+ },
144
+ };
145
+ return Buffer.from(JSON.stringify(payload)).toString("base64");
146
+ }
147
+
148
+ async function callUtility(utility, body, idempotencyKey) {
149
+ const url = `${BASE}${pathForUtility(utility)}`;
150
+ const headers = {
151
+ "Content-Type": "application/json",
152
+ "Idempotency-Key": idempotencyKey || randomUUID(),
153
+ };
154
+ const jsonBody = JSON.stringify(body ?? {});
155
+
156
+ if (process.env.UB_API_KEY) {
157
+ headers.Authorization = `Bearer ${process.env.UB_API_KEY}`;
158
+ const { res, body: resp } = await fetchJson(url, {
159
+ method: "POST",
160
+ headers,
161
+ body: jsonBody,
162
+ });
163
+ return {
164
+ status: res.status,
165
+ paymentMode: "api_key",
166
+ paymentResponse: res.headers.get("x-payment-response"),
167
+ body: resp,
168
+ };
169
+ }
170
+
171
+ if (!process.env.X402_PRIVATE_KEY) {
172
+ throw new Error(
173
+ "Set X402_PRIVATE_KEY (USDC on Base) or UB_API_KEY before call_utility.",
174
+ );
175
+ }
176
+
177
+ // Unpaid probe → 402 with accepts
178
+ const unpaid = await fetchJson(url, { method: "POST", headers, body: jsonBody });
179
+ if (unpaid.res.status !== 402) {
180
+ // Already succeeded (unlikely) or validation error free
181
+ return {
182
+ status: unpaid.res.status,
183
+ paymentMode: "none",
184
+ body: unpaid.body,
185
+ };
186
+ }
187
+
188
+ const accepts0 = unpaid.body?.error?.details?.accepts?.[0];
189
+ if (!accepts0) {
190
+ return {
191
+ status: 402,
192
+ paymentMode: "x402",
193
+ error: "PAYMENT_REQUIRED without accepts[0]",
194
+ body: unpaid.body,
195
+ };
196
+ }
197
+
198
+ const xPayment = await signX402Payment(accepts0);
199
+ const paid = await fetchJson(url, {
200
+ method: "POST",
201
+ headers: { ...headers, "X-PAYMENT": xPayment },
202
+ body: jsonBody,
203
+ });
204
+ return {
205
+ status: paid.res.status,
206
+ paymentMode: "x402",
207
+ paymentResponse: paid.res.headers.get("x-payment-response"),
208
+ quote: unpaid.body?.error?.details?.quote,
209
+ body: paid.body,
210
+ };
211
+ }
212
+
213
+ const server = new McpServer({
214
+ name: "util-beauty",
215
+ version: "1.0.0",
216
+ });
217
+
218
+ server.tool(
219
+ "list_utilities",
220
+ "List util.beauty utilities, prices, payment modes, and limits from live GET /v1/meta. Call this before inventing names or prices.",
221
+ {},
222
+ async () => {
223
+ try {
224
+ const { res, body } = await fetchJson(`${BASE}/v1/meta`);
225
+ if (!res.ok) return textResult({ status: res.status, body }, true);
226
+ // Compact payload for agents
227
+ const compact = {
228
+ service: body.service,
229
+ version: body.version,
230
+ base: BASE,
231
+ payment: body.payment,
232
+ utilities: (body.utilities ?? []).map((u) => ({
233
+ name: u.name,
234
+ endpoint: u.endpoint,
235
+ credits: u.credits,
236
+ usdMicros: u.usdMicros,
237
+ description: u.description,
238
+ })),
239
+ limits: body.limits,
240
+ openapiUrl: body.openapiUrl,
241
+ };
242
+ return textResult(compact);
243
+ } catch (err) {
244
+ return textResult({ error: String(err?.message ?? err) }, true);
245
+ }
246
+ },
247
+ );
248
+
249
+ server.tool(
250
+ "describe_utility",
251
+ "Return the OpenAPI request body schema and notes for one util.beauty utility (e.g. browser.screenshot, crypto.hash). Use after list_utilities.",
252
+ { utility: z.string().describe("Utility name from list_utilities, e.g. crypto.hash") },
253
+ async ({ utility }) => {
254
+ try {
255
+ const openapi = await getOpenApi();
256
+ return textResult(schemaForUtility(openapi, utility));
257
+ } catch (err) {
258
+ return textResult({ error: String(err?.message ?? err) }, true);
259
+ }
260
+ },
261
+ );
262
+
263
+ server.tool(
264
+ "call_utility",
265
+ "Call a util.beauty utility (POST). Pays with X402_PRIVATE_KEY (x402) or UB_API_KEY. Prefer describe_utility first for body shape. Billing is per-attempt after validation.",
266
+ {
267
+ utility: z.string().describe("e.g. browser.extract or crypto.hash"),
268
+ body: z
269
+ .record(z.unknown())
270
+ .describe("JSON request body for the utility")
271
+ .optional(),
272
+ idempotencyKey: z
273
+ .string()
274
+ .describe("Optional Idempotency-Key; generated if omitted")
275
+ .optional(),
276
+ },
277
+ async ({ utility, body, idempotencyKey }) => {
278
+ try {
279
+ const result = await callUtility(utility, body ?? {}, idempotencyKey);
280
+ const isError = result.status >= 400;
281
+ return textResult(result, isError);
282
+ } catch (err) {
283
+ return textResult({ error: String(err?.message ?? err) }, true);
284
+ }
285
+ },
286
+ );
287
+
288
+ const transport = new StdioServerTransport();
289
+ await server.connect(transport);