Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(mcp): add the /api/mcp-tools endpoint and settings MCP tools page, tokenize tool updates, AWS Marketplace issue-key fix, with tests

nirholascc2a0b51f1c3
diff --git a/api/_lib/tokenize-3d.js b/api/_lib/tokenize-3d.js
index da21627ef..741b72ffe 100644
--- a/api/_lib/tokenize-3d.js
+++ b/api/_lib/tokenize-3d.js
@@ -564,11 +564,13 @@ export async function mintTokenized3dAsset(input, deps = defaultDeps()) {
// split — honestly reported, never a fabricated payout.
let remixRoyalty = null;
if (provenance.parentMint) {
- remixRoyalty = await settleTokenizeRemixRoyalty({
+ remixRoyalty = await settleOrDeferRemixRoyalty({
sql: deps.sql,
+ rowId,
parentMint: provenance.parentMint,
network,
feeAtomics: input.mintFeeAtomicsCollected ?? 0n,
+ defer: input.deferRoyalty,
});
}
@@ -683,6 +685,26 @@ export async function settleTokenizeRemixRoyalty({ sql: sqlClient, parentMint, n
}
}
+/**
+ * Pay the parent creator's remix royalty, or hold it until the caller's x402
+ * payment has settled. The royalty comes out of the platform treasury, so it must
+ * not leave before the fee it is carved from has actually landed: a payer whose
+ * settlement fails would otherwise cost the platform the royalty.
+ *
+ * @param {object} p
+ * @param {(run: () => Promise<void>) => void} [p.defer] registers work to run
+ * after settlement; omitted means pay now (no per-call fee to wait for).
+ */
+export async function settleOrDeferRemixRoyalty({ sql: sqlClient, rowId, parentMint, network, feeAtomics, defer }) {
+ const settle = () => settleTokenizeRemixRoyalty({ sql: sqlClient, parentMint, network, feeAtomics });
+ if (typeof defer !== 'function') return settle();
+ defer(async () => {
+ const settled = await settle();
+ await sqlClient`update tokenized_3d_assets set remix_royalty = ${JSON.stringify(settled)}::jsonb, updated_at = now() where id = ${rowId}`;
+ });
+ return { paid: false, reason: 'pending_payment_settlement', parent_mint: parentMint };
+}
+
function formatMintResult(
row,
{ idempotent, capped, requestedBps, royaltyBps, metadataIpfs = null, provenanceLedger, remixRoyalty },
diff --git a/api/_mcp/tools/tokenize.js b/api/_mcp/tools/tokenize.js
index 5408841dd..6c1962890 100644
--- a/api/_mcp/tools/tokenize.js
+++ b/api/_mcp/tools/tokenize.js
@@ -140,6 +140,11 @@ export const toolDefs = [
generationProvider: args.generation_provider,
idempotencyKey: args.idempotency_key,
mintFeeAtomicsCollected,
+ // The royalty is paid from the treasury, so it waits for the x402
+ // settlement that api/mcp.js performs after this handler returns.
+ deferRoyalty: paidPerCall
+ ? (run) => { (auth.afterSettle ??= []).push(run); }
+ : undefined,
});
const text =
result.status === 'minted'
@@ -156,7 +161,9 @@ export const toolDefs = [
(result.remix_royalty
? result.remix_royalty.paid
? `\nRemix royalty: ${result.remix_royalty.creator_usd} USDC paid to the source creator (${result.remix_royalty.creator_tx})`
- : `\nRemix royalty: not paid (${result.remix_royalty.reason})`
+ : result.remix_royalty.reason === 'pending_payment_settlement'
+ ? '\nRemix royalty: paid to the source creator once your payment settles'
+ : `\nRemix royalty: not paid (${result.remix_royalty.reason})`
: '')
: `Mint in progress for this asset. Read it back with get_3d_asset_onchain once it confirms.`;
return { content: [{ type: 'text', text }], structuredContent: result };
diff --git a/api/aws-marketplace/issue-key.js b/api/aws-marketplace/issue-key.js
index 640b79432..dd3cb0501 100644
--- a/api/aws-marketplace/issue-key.js
+++ b/api/aws-marketplace/issue-key.js
@@ -14,7 +14,7 @@
import { cors, json, readJson, wrap } from '../_lib/http.js';
import { getSessionUser } from '../_lib/auth.js';
import { issueSubscriptionForCustomer } from '../_lib/aws-marketplace-bridge.js';
-import { findCustomerByHandle } from '../_lib/aws-marketplace-store.js';
+import { findCustomerByHandle, claimCustomerForUser } from '../_lib/aws-marketplace-store.js';
import { customerEntitlement } from '../_lib/aws-marketplace.js';
import { env } from '../_lib/env.js';
@@ -85,9 +85,17 @@ export default wrap(async (req, res) => {
}
}
+ // Bind the row to the caller before minting: an unclaimed row must not hand
+ // a key to whoever presents its id first and then lock the real buyer out.
+ let owned = row;
+ if (!row.user_id) {
+ owned = await claimCustomerForUser(row.id, user.id);
+ if (!owned) return json(res, 403, { error: 'customer_linked_to_other_account' });
+ }
+
let issued;
try {
- issued = await issueSubscriptionForCustomer({ ...row, user_id: row.user_id || user.id });
+ issued = await issueSubscriptionForCustomer({ ...owned, user_id: user.id });
} catch (err) {
console.error('[aws-marketplace/issue-key] failed', {
customerId,
diff --git a/api/mcp-tools.js b/api/mcp-tools.js
new file mode 100644
index 000000000..e89335899
--- /dev/null
+++ b/api/mcp-tools.js
@@ -0,0 +1,80 @@
+// Tool-group settings behind /settings/mcp-tools.
+//
+// GET /api/mcp-tools
+// → { groups: [{ id, label, summary }], account: { <group id>: boolean }, key: null }
+// every group the policy knows, and the account's saved choices. A group
+// absent from `account` follows the tier default (read and write tools
+// on, financial tools off).
+// PUT /api/mcp-tools { groups: { <group id>: boolean | null } }
+// → merge a sparse change onto the account-wide row in mcp_tool_settings.
+// true turns the whole group on (financial tools included), false turns
+// it off, null returns it to the default. Unknown group ids are a 400.
+//
+// api/_mcp/policy.js reads the row on every tools/list and tools/call, so a
+// save drops that module's memo (invalidateToolSettings) to take effect now.
+
+import { z } from 'zod';
+import { GROUPS, GROUP_IDS } from '@three-ws/mcp-policy';
+import { sql } from './_lib/db.js';
+import { getRequestUser } from './_lib/auth.js';
+import { cors, json, method, wrap, error, readJson, rateLimited } from './_lib/http.js';
+import { requireCsrf } from './_lib/csrf.js';
+import { limits } from './_lib/rate-limit.js';
+import { parse } from './_lib/validate.js';
+import { loadToolSettings, invalidateToolSettings } from './_mcp/policy.js';
+
+const putBody = z.object({
+ // A record keyed by an enum demands every key, so check the ids by hand: a
+ // sparse change must be accepted and an unknown id must be refused.
+ groups: z.record(z.string(), z.boolean().nullable()).superRefine((groups, ctx) => {
+ for (const id of Object.keys(groups)) {
+ if (!GROUP_IDS.includes(id)) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: [id], message: `unknown tool group "${id}"` });
+ }
+ }
+ }),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PUT'])) return;
+
+ const user = await getRequestUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in to manage tool settings');
+
+ if (req.method === 'GET') {
+ const { account } = await loadToolSettings(user.id);
+ return json(res, 200, { groups: GROUPS, account: account?.groups ?? {}, key: null }, { 'cache-control': 'no-store' });
+ }
+
+ if (!(await requireCsrf(req, res, user.id))) return;
+ const rl = await limits.notifPrefsWrite(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const { groups } = parse(putBody, await readJson(req));
+
+ // Read the stored row directly: the policy memo can be up to 15 seconds old
+ // and a merge onto a stale copy would drop a change saved moments ago.
+ const [row] = await sql`
+ SELECT settings FROM mcp_tool_settings
+ WHERE user_id = ${user.id} AND api_key_id IS NULL
+ `;
+ const stored = row?.settings && typeof row.settings === 'object' ? row.settings : {};
+ const merged = { ...(stored.groups || {}) };
+ for (const [id, on] of Object.entries(groups)) {
+ if (on === null) delete merged[id];
+ else merged[id] = on;
+ }
+ const next = { ...stored, groups: merged };
+
+ await sql`
+ INSERT INTO mcp_tool_settings (user_id, api_key_id, settings, updated_at)
+ VALUES (${user.id}, NULL, ${JSON.stringify(next)}::jsonb, now())
+ ON CONFLICT (user_id) WHERE api_key_id IS NULL DO UPDATE SET
+ settings = EXCLUDED.settings,
+ updated_at = now()
+ `;
+ invalidateToolSettings(user.id);
+
+ return json(res, 200, { ok: true, account: merged });
+});
diff --git a/api/mcp.js b/api/mcp.js
index c4bb0a23d..9212f5d51 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -112,6 +112,11 @@ export default wrap(async (req, res) => {
try {
const settled = await settlePayment({ verified: x402Ctx.verified });
res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));
+ // Treasury-funded payouts carved from this fee (remix royalties) run
+ // only now that the fee has landed. Best-effort: the call already succeeded.
+ for (const run of auth?.afterSettle ?? []) {
+ await run().catch((e) => console.warn('[mcp] post-settle payout failed:', e?.message));
+ }
} catch (err) {
return sendX402Error(
res,
diff --git a/package.json b/package.json
index eaab47f92..a3c468b2f 100644
--- a/package.json
+++ b/package.json
@@ -56,7 +56,7 @@
"uuid@^8": "^11.1.1",
"yaml@^1": "^1.10.3",
"zod": "^4.6.7",
- "nanoid@^2": "^3.3.20",
+ "@colyseus/core": { "nanoid": "2.1.11" },
"@colyseus/core": { "nanoid": "2.1.11" },
"uuid@^10": "^11.1.1",
"fast-xml-parser": "^5.11.2",
diff --git a/public/settings/index.html b/public/settings/index.html
index f578b92d5..127616e20 100644
--- a/public/settings/index.html
+++ b/public/settings/index.html
@@ -1706,6 +1706,7 @@
}
// ── Connections (paired chats) ────────────────────────────────
+ const JSON_HDR = { 'content-type': 'application/json' };
const CONN_PLATFORM = { telegram: 'Telegram', discord: 'Discord' };
const X_OUTCOMES = {
connected: ['ok', 'X account connected successfully.'],
@@ -1761,7 +1762,7 @@
async function connPatch(id, body, undo) {
try {
- await apiJson('/api/gateway/connections', { method: 'PATCH', body: JSON.stringify({ id, ...body }) });
+ await apiJson('/api/gateway/connections', { method: 'PATCH', headers: JSON_HDR, body: JSON.stringify({ id, ...body }) });
connMsg('ok', 'Saved.');
} catch (e) {
undo();
@@ -1806,7 +1807,7 @@
const out = document.getElementById('conn-issued');
btn.disabled = true;
try {
- const r = await apiJson('/api/gateway/connections', { method: 'POST', body: JSON.stringify({ action: 'issue' }) });
+ const r = await apiJson('/api/gateway/connections', { method: 'POST', headers: JSON_HDR, body: JSON.stringify({ action: 'issue' }) });
const mins = Math.max(1, Math.round((new Date(r.expires_at) - Date.now()) / 60000));
out.style.display = 'block';
out.innerHTML = `<div style="font-size:22px;font-weight:700;letter-spacing:.12em;font-family:monospace;color:#eee">${escHtml(r.code)}</div>
@@ -1825,7 +1826,7 @@
box.style.display = 'block';
box.innerHTML = '<p class="muted">Checking code…</p>';
try {
- const r = await apiJson('/api/gateway/connections', { method: 'POST', body: JSON.stringify({ action: 'preview', code: rawCode }) });
+ const r = await apiJson('/api/gateway/connections', { method: 'POST', headers: JSON_HDR, body: JSON.stringify({ action: 'preview', code: rawCode }) });
const c = r.chat;
const name = c.chat_title || c.platform_username || 'a direct chat';
box.innerHTML = `
@@ -1839,7 +1840,7 @@
document.getElementById('conn-redeem-btn').addEventListener('click', async (ev) => {
ev.target.disabled = true;
try {
- await apiJson('/api/gateway/connections', { method: 'POST', body: JSON.stringify({ action: 'redeem', code: rawCode, confirm: r.confirm }) });
+ await apiJson('/api/gateway/connections', { method: 'POST', headers: JSON_HDR, body: JSON.stringify({ action: 'redeem', code: rawCode, confirm: r.confirm }) });
box.style.display = 'none';
document.getElementById('conn-code-input').value = '';
connMsg('ok', 'Chat paired.');
diff --git a/public/settings/mcp-tools/index.html b/public/settings/mcp-tools/index.html
new file mode 100644
index 000000000..ebcacb812
--- /dev/null
+++ b/public/settings/mcp-tools/index.html
@@ -0,0 +1,275 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Tool Access · three.ws</title>
+ <meta name="description" content="Choose which three.ws MCP tool groups your agents and connectors can use." />
+ <meta name="robots" content="noindex" />
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ :root {
+ color-scheme: dark;
+ --bg: #000;
+ --panel: #141414;
+ --border: #222;
+ --text: #eee;
+ --muted: #888;
+ --accent: #fff;
+ --ok: #6fcf97;
+ --err: #ff7b7b;
+ }
+ * { box-sizing: border-box; }
+ body {
+ font: 15px/1.55 -apple-system, system-ui, Segoe UI, Roboto, sans-serif;
+ color: var(--text);
+ background: var(--bg);
+ margin: 0;
+ min-height: 100vh;
+ }
+ a { color: #ccc; }
+ a:hover { color: #fff; }
+ a:focus-visible, button:focus-visible, select:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+ header {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 0 24px;
+ height: 60px;
+ border-bottom: 1px solid var(--border);
+ }
+ header img { height: 1.55rem; width: auto; display: block; }
+ header .back { margin-left: auto; font-size: 13px; }
+ main { max-width: 760px; margin: 0 auto; padding: 32px 16px 96px; }
+ h1 { font-size: 22px; margin: 0 0 6px; letter-spacing: -0.01em; }
+ .sub { color: var(--muted); margin: 0 0 20px; font-size: 14px; }
+ .tiers {
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ padding: 14px 16px;
+ font-size: 13.5px;
+ color: #ccc;
+ margin-bottom: 20px;
+ }
+ .tiers p { margin: 0 0 8px; }
+ .tiers p:last-child { margin: 0; }
+ .list { display: grid; gap: 8px; }
+ .group {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ padding: 12px 16px;
+ }
+ .group.changed { border-color: #555; }
+ .group .text { flex: 1; min-width: 0; }
+ .group .name { font-weight: 600; font-size: 14px; }
+ .group .summary { color: var(--muted); font-size: 13px; margin-top: 2px; }
+ select {
+ background: #0c0c0c;
+ color: var(--text);
+ border: 1px solid #333;
+ border-radius: 8px;
+ padding: 7px 10px;
+ font: inherit;
+ font-size: 13px;
+ max-width: 190px;
+ cursor: pointer;
+ }
+ select:hover { border-color: #555; }
+ .bar {
+ position: sticky;
+ bottom: 0;
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ padding: 14px 0;
+ margin-top: 20px;
+ background: linear-gradient(to top, var(--bg) 70%, transparent);
+ }
+ .btn {
+ padding: 9px 20px;
+ border-radius: 9px;
+ border: 0;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ background: var(--accent);
+ color: #000;
+ transition: filter 0.12s, transform 0.05s;
+ }
+ .btn:hover { filter: brightness(0.88); }
+ .btn:active { transform: translateY(1px); }
+ .btn:disabled { opacity: 0.45; cursor: not-allowed; filter: none; transform: none; }
+ .btn.sec { background: #222; color: #ddd; }
+ .btn.sec:hover { background: #2a2a2a; filter: none; }
+ #status { font-size: 13px; }
+ #status.ok { color: var(--ok); }
+ #status.err { color: var(--err); }
+ .skeleton {
+ height: 62px;
+ border-radius: 10px;
+ background: linear-gradient(90deg, #111 25%, #1a1a1a 50%, #111 75%);
+ background-size: 200% 100%;
+ animation: shimmer 1.2s infinite linear;
+ }
+ @keyframes shimmer { to { background-position: -200% 0; } }
+ @media (prefers-reduced-motion: reduce) { .skeleton { animation: none; } }
+ .empty { color: var(--muted); padding: 24px 0; }
+ @media (max-width: 560px) {
+ header { padding: 0 16px; }
+ .group { flex-direction: column; align-items: stretch; gap: 10px; }
+ select { max-width: none; width: 100%; }
+ }
+ </style>
+ </head>
+ <body>
+ <header>
+ <a href="/"><img src="/three.svg" alt="three.ws" /></a>
+ <a class="back" href="/settings">Back to settings</a>
+ </header>
+ <main>
+ <h1>Tool access</h1>
+ <p class="sub">Choose which tool groups your agents and MCP connectors can use on this account.</p>
+
+ <div class="tiers">
+ <p><strong>Read and write tools are on by default.</strong> They look things up or change account state that a follow-up call can undo.</p>
+ <p><strong>Financial tools are off by default.</strong> They move funds or cannot be undone. Setting a group to <em>On</em> turns on every tool in it, financial ones included. <em>Off</em> hides the whole group. <em>Default</em> keeps read and write on and financial off.</p>
+ <p>Details: <a href="/docs/mcp-safety">MCP tool safety</a>.</p>
+ </div>
+
+ <div id="list" class="list" aria-live="polite">
+ <div class="skeleton"></div><div class="skeleton"></div><div class="skeleton"></div><div class="skeleton"></div>
+ </div>
+
+ <div class="bar">
+ <button class="btn" id="save" disabled>Save changes</button>
+ <button class="btn sec" id="reset" disabled>Discard</button>
+ <span id="status" role="status"></span>
+ </div>
+ </main>
+
+ <script type="module">
+ import { apiFetch } from '/src/api.js';
+
+ const listEl = document.getElementById('list');
+ const saveBtn = document.getElementById('save');
+ const resetBtn = document.getElementById('reset');
+ const statusEl = document.getElementById('status');
+
+ // Option values are what the server stores: a group absent from the
+ // saved map follows the tier default, true is on, false is off.
+ const VALUE = (v) => (v === true ? 'on' : v === false ? 'off' : 'default');
+ const FROM = { on: true, off: false, default: null };
+
+ let groups = [];
+ let loaded = {};
+
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+
+ function setStatus(type, text) {
+ statusEl.className = type;
+ statusEl.textContent = text;
+ }
+
+ async function errorText(res, fallback) {
+ const data = await res.json().catch(() => null);
+ return data?.error_description || data?.error || fallback;
+ }
+
+ function changes() {
+ const out = {};
+ for (const sel of listEl.querySelectorAll('select[data-id]')) {
+ const id = sel.dataset.id;
+ const next = FROM[sel.value];
+ const prev = Object.hasOwn(loaded, id) ? loaded[id] : null;
+ if (next !== prev) out[id] = next;
+ }
+ return out;
+ }
+
+ function refreshDirty() {
+ const dirty = Object.keys(changes()).length > 0;
+ saveBtn.disabled = !dirty;
+ resetBtn.disabled = !dirty;
+ for (const row of listEl.querySelectorAll('.group')) {
+ const sel = row.querySelector('select');
+ const prev = Object.hasOwn(loaded, sel.dataset.id) ? loaded[sel.dataset.id] : null;
+ row.classList.toggle('changed', FROM[sel.value] !== prev);
+ }
+ }
+
+ function render() {
+ if (!groups.length) {
+ listEl.innerHTML = '<p class="empty">No tool groups were returned. Reload the page, or try again in a minute.</p>';
+ return;
+ }
+ listEl.innerHTML = groups.map((g) => `
+ <div class="group">
+ <div class="text">
+ <div class="name"><label for="g-${esc(g.id)}">${esc(g.label)}</label></div>
+ <div class="summary">${esc(g.summary)}</div>
+ </div>
+ <select id="g-${esc(g.id)}" data-id="${esc(g.id)}">
+ <option value="default">Default</option>
+ <option value="on">On (all tools)</option>
+ <option value="off">Off</option>
+ </select>
+ </div>`).join('');
+ for (const sel of listEl.querySelectorAll('select')) {
+ sel.value = VALUE(Object.hasOwn(loaded, sel.dataset.id) ? loaded[sel.dataset.id] : null);
+ }
+ refreshDirty();
+ }
+
+ async function load() {
+ try {
+ const res = await apiFetch('/api/mcp-tools');
+ if (res.status === 401) {
+ location.href = '/login?next=' + encodeURIComponent(location.pathname);
+ return;
+ }
+ if (!res.ok) throw new Error(await errorText(res, 'Could not load your tool settings.'));
+ const data = await res.json();
+ groups = data.groups || [];
+ loaded = data.account || {};
+ render();
+ } catch (e) {
+ listEl.innerHTML = `<p class="empty">${esc(e.message || 'Could not load your tool settings.')} <button class="btn sec" id="retry">Try again</button></p>`;
+ document.getElementById('retry').addEventListener('click', () => {
+ listEl.innerHTML = '<div class="skeleton"></div><div class="skeleton"></div>';
+ load();
+ });
+ }
+ }
+
+ listEl.addEventListener('change', () => { setStatus('', ''); refreshDirty(); });
+ resetBtn.addEventListener('click', () => { render(); setStatus('', ''); });
+
+ saveBtn.addEventListener('click', async () => {
+ const body = { groups: changes() };
+ saveBtn.disabled = true;
+ resetBtn.disabled = true;
+ setStatus('', 'Saving…');
+ try {
+ const res = await apiFetch('/api/mcp-tools', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+ if (!res.ok) throw new Error(await errorText(res, 'Could not save your changes.'));
+ const data = await res.json();
+ loaded = data.account || {};
+ render();
+ setStatus('ok', 'Saved. New sessions pick this up immediately.');
+ } catch (e) {
+ setStatus('err', e.message || 'Could not save your changes.');
+ refreshDirty();
+ }
+ });
+
+ load();
+ </script>
+ </body>
+</html>
diff --git a/solana-agent-sdk/package-lock.json b/solana-agent-sdk/package-lock.json
index b56cbde39..eea5d3310 100644
--- a/solana-agent-sdk/package-lock.json
+++ b/solana-agent-sdk/package-lock.json
@@ -27,13 +27,13 @@
"ts-jest": "^29.4.9",
"tsup": "^8.3.5",
"typescript": "^5.7.3",
- "zod": "^3.0.0"
+ "zod": "^4.6.7"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
- "zod": "^3.0.0"
+ "zod": "^4.6.7"
},
"peerDependenciesMeta": {
"zod": {
@@ -7815,9 +7815,9 @@
}
},
"node_modules/zod": {
- "version": "3.25.76",
- "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
- "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
+ "version": "4.6.7",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
+ "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
"dev": true,
"license": "MIT",
"funding": {
diff --git a/tests/api/aws-marketplace-issue-key.test.js b/tests/api/aws-marketplace-issue-key.test.js
new file mode 100644
index 000000000..fd9a20106
--- /dev/null
+++ b/tests/api/aws-marketplace-issue-key.test.js
@@ -0,0 +1,82 @@
+// /api/aws-marketplace/issue-key must bind an unclaimed marketplace row to the
+// caller before minting a key. Without the claim, a signed-in user who learned
+// a row id could mint the key and a later buyer link got 403.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: Object.assign((...a) => sqlMock(...a), { transaction: (...a) => sqlMock(...a) }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const getSessionUserMock = vi.fn();
+vi.mock('../../api/_lib/auth.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, getSessionUser: (...a) => getSessionUserMock(...a) };
+});
+
+const findMock = vi.fn();
+const claimMock = vi.fn();
+vi.mock('../../api/_lib/aws-marketplace-store.js', () => ({
+ findCustomerByHandle: (...a) => findMock(...a),
+ claimCustomerForUser: (...a) => claimMock(...a),
+}));
+
+const issueMock = vi.fn();
+vi.mock('../../api/_lib/aws-marketplace-bridge.js', () => ({
+ issueSubscriptionForCustomer: (...a) => issueMock(...a),
+}));
+
+const { default: handler } = await import('../../api/aws-marketplace/issue-key.js');
+
+function makeReq() {
+ return {
+ method: 'POST',
+ url: '/api/aws-marketplace/issue-key',
+ headers: { 'content-type': 'application/json', 'user-agent': 'vitest' },
+ rawBody: Buffer.from(JSON.stringify({ customer: 'row-1' })),
+ query: {},
+ };
+}
+function makeRes() {
+ const headers = {};
+ let body = '';
+ const res = {
+ statusCode: 200, headersSent: false, writableEnded: false,
+ setHeader: (k, v) => { headers[k.toLowerCase()] = v; },
+ getHeader: (k) => headers[k.toLowerCase()],
+ end: (c) => { body = c ?? ''; res.writableEnded = true; },
+ _get: () => ({ status: res.statusCode, body: body ? JSON.parse(body) : null }),
+ };
+ return res;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ issueMock.mockResolvedValue({ subscriptionId: 's', keyPrefix: 'k', token: 't', rateLimitPerMinute: 1, alreadyIssued: false });
+});
+
+describe('issue-key ownership', () => {
+ it('claims an unclaimed row for the caller before issuing', async () => {
+ const row = { id: 'row-1', user_id: null, subscription_status: 'active' };
+ findMock.mockResolvedValue(row);
+ claimMock.mockResolvedValue({ ...row, user_id: 'u1' });
+ const res = makeRes();
+ await handler(makeReq(), res);
+ expect(claimMock).toHaveBeenCalledWith('row-1', 'u1');
+ expect(issueMock).toHaveBeenCalledWith(expect.objectContaining({ user_id: 'u1' }));
+ expect(res._get().status).toBe(200);
+ });
+
+ it('refuses when the claim loses a race', async () => {
+ findMock.mockResolvedValue({ id: 'row-1', user_id: null, subscription_status: 'active' });
+ claimMock.mockResolvedValue(null);
+ const res = makeRes();
+ await handler(makeReq(), res);
+ expect(issueMock).not.toHaveBeenCalled();
+ expect(res._get().status).toBe(403);
+ });
+});
diff --git a/tests/api/mcp-tools.test.js b/tests/api/mcp-tools.test.js
new file mode 100644
index 000000000..76684dc5c
--- /dev/null
+++ b/tests/api/mcp-tools.test.js
@@ -0,0 +1,170 @@
+// GET|PUT /api/mcp-tools -> api/mcp-tools.js
+//
+// The writer behind /settings/mcp-tools. Every hosted MCP server refuses a
+// disabled tool with a link to that page, and api/_mcp/policy.js reads the
+// mcp_tool_settings table this endpoint writes ({ groups: {id: bool}, tools }).
+//
+// Mocks: sql (an in-memory account row so a PUT then GET round-trips), auth,
+// csrf, rate-limit and the policy module's cache (spied so the test can assert
+// a save invalidates it). Offline, no DATABASE_URL or Redis needed.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { readFileSync, existsSync } from 'node:fs';
+import { GROUPS, SETTINGS_URL } from '@three-ws/mcp-policy';
+
+const db = { row: null };
+const sqlCalls = [];
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn((strings, ...values) => {
+ const text = strings.join(' ? ');
+ sqlCalls.push({ text, values });
+ if (/insert into mcp_tool_settings/i.test(text)) {
+ db.row = JSON.parse(values[1]);
+ return Promise.resolve([]);
+ }
+ if (/from mcp_tool_settings/i.test(text)) {
+ return Promise.resolve(db.row ? [{ settings: db.row }] : []);
+ }
+ return Promise.resolve([]);
+ }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const authState = { user: null };
+vi.mock('../../api/_lib/auth.js', () => ({
+ getRequestUser: vi.fn(async () => authState.user),
+}));
+
+vi.mock('../../api/_lib/csrf.js', () => ({
+ requireCsrf: vi.fn(async () => true),
+}));
+
+const rlState = { success: true, limit: 60, remaining: 0, reset: 0 };
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { notifPrefsWrite: vi.fn(async () => rlState) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const invalidate = vi.fn();
+vi.mock('../../api/_mcp/policy.js', () => ({
+ loadToolSettings: vi.fn(async () => ({ account: db.row, key: null })),
+ invalidateToolSettings: (...a) => invalidate(...a),
+}));
+
+const { default: handler } = await import('../../api/mcp-tools.js');
+
+const USER = { id: '00000000-0000-0000-0000-0000000000c1' };
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this._body = body; },
+ };
+}
+async function call({ method = 'GET', body } = {}) {
+ const res = makeRes();
+ const req = {
+ method,
+ query: {},
+ url: '/api/mcp-tools',
+ headers: body === undefined ? {} : { 'content-type': 'application/json' },
+ };
+ if (body !== undefined) req.body = body;
+ await handler(req, res);
+ let parsed = null;
+ try { parsed = JSON.parse(res._body); } catch {}
+ return { res, body: parsed };
+}
+
+beforeEach(() => {
+ sqlCalls.length = 0;
+ db.row = null;
+ authState.user = USER;
+ rlState.success = true;
+ invalidate.mockClear();
+});
+
+describe('GET /api/mcp-tools', () => {
+ it('401s for an anonymous caller', async () => {
+ authState.user = null;
+ const { res } = await call();
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('returns every group and an empty account map when nothing is saved', async () => {
+ const { res, body } = await call();
+ expect(res.statusCode).toBe(200);
+ expect(body.groups).toEqual(JSON.parse(JSON.stringify(GROUPS)));
+ expect(body.account).toEqual({});
+ expect(body.key).toBeNull();
+ });
+});
+
+describe('PUT /api/mcp-tools', () => {
+ it('stores a group choice and reflects it on the next GET, leaving the rest unset', async () => {
+ const put = await call({ method: 'PUT', body: { groups: { trading: false } } });
+ expect(put.res.statusCode).toBe(200);
+ const { body } = await call();
+ expect(body.account).toEqual({ trading: false });
+ });
+
+ it('merges into the saved groups and keeps a saved tools map intact', async () => {
+ db.row = { groups: { wallet: true }, tools: { swap_quote: true } };
+ await call({ method: 'PUT', body: { groups: { trading: true } } });
+ expect(db.row).toEqual({ groups: { wallet: true, trading: true }, tools: { swap_quote: true } });
+ });
+
+ it('returns a group to its default when sent null', async () => {
+ db.row = { groups: { wallet: true, trading: false } };
+ await call({ method: 'PUT', body: { groups: { wallet: null } } });
+ expect(db.row.groups).toEqual({ trading: false });
+ });
+
+ it('rejects an unknown group id instead of storing it', async () => {
+ const { res } = await call({ method: 'PUT', body: { groups: { not_a_group: true } } });
+ expect(res.statusCode).toBeGreaterThanOrEqual(400);
+ expect(res.statusCode).toBeLessThan(500);
+ expect(db.row).toBeNull();
+ expect(invalidate).not.toHaveBeenCalled();
+ });
+
+ it('rejects a non-boolean value', async () => {
+ const { res } = await call({ method: 'PUT', body: { groups: { trading: 'yes' } } });
+ expect(res.statusCode).toBe(400);
+ expect(db.row).toBeNull();
+ });
+
+ it('drops the cached settings exactly once per successful write', async () => {
+ await call({ method: 'PUT', body: { groups: { wallet: true } } });
+ expect(invalidate).toHaveBeenCalledTimes(1);
+ expect(invalidate).toHaveBeenCalledWith(USER.id);
+ });
+
+ it('answers 429 when the write budget is spent, without writing', async () => {
+ rlState.success = false;
+ const { res } = await call({ method: 'PUT', body: { groups: { wallet: true } } });
+ expect(res.statusCode).toBe(429);
+ expect(db.row).toBeNull();
+ });
+});
+
+describe('/settings/mcp-tools page route', () => {
+ const routes = JSON.parse(readFileSync('vercel.json', 'utf8')).routes.filter((r) => r.src && r.dest);
+ const path = new URL(SETTINGS_URL).pathname;
+
+ it('is the path every refusal message quotes', () => {
+ expect(path).toBe('/settings/mcp-tools');
+ });
+
+ it('routes to its own page ahead of the /settings catch-all', () => {
+ const idx = routes.findIndex((r) => new RegExp(`^${r.src}$`).test(path));
+ expect(idx).toBeGreaterThan(-1);
+ expect(routes[idx].dest).toBe('/settings/mcp-tools/index.html');
+ expect(idx).toBeLessThan(routes.findIndex((r) => r.src === '/settings/(.*)'));
+ expect(existsSync('public/settings/mcp-tools/index.html')).toBe(true);
+ });
+});
diff --git a/vercel.json b/vercel.json
index a94496672..2f969abb7 100644
--- a/vercel.json
+++ b/vercel.json
@@ -5735,6 +5735,10 @@
"src": "/settings/",
"dest": "/settings/index.html"
},
+ {
+ "src": "/settings/mcp-tools/?",
+ "dest": "/settings/mcp-tools/index.html"
+ },
{
"src": "/settings/(.*)",
"dest": "/settings/index.html"