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.

chore: MCP catalogs, forge, chat, avatar SDK and docs updates

nirholas850903a522a4
diff --git a/.githooks/pre-push b/.githooks/pre-push
new file mode 100755
index 000000000..1981f9f37
--- /dev/null
+++ b/.githooks/pre-push
@@ -0,0 +1,21 @@
+#!/bin/sh
+# Pre-push safety net. GitHub Actions are unavailable on this account, so no
+# CI runs tests or typecheck — the Vercel build is the only automated gate,
+# and it fires after the push. This hook runs the same typecheck that gates
+# deploys (npm run typecheck) before anything leaves the machine.
+#
+# Bypass (emergencies only): git push --no-verify or SKIP_HOOKS=1 git push
+#
+# Wired via `git config core.hooksPath .githooks` (npm run setup does this).
+
+if [ "$SKIP_HOOKS" = "1" ]; then
+ exit 0
+fi
+
+echo "[pre-push] npm run typecheck"
+if ! npm run typecheck; then
+ echo "" >&2
+ echo "[pre-push] typecheck failed — push blocked." >&2
+ echo "[pre-push] Fix the errors above, or bypass with: git push --no-verify" >&2
+ exit 1
+fi
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 79ba8d3d4..1a298ef9f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,7 +8,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Describe it to 3D joins the rest of the site — and the two generators now point at each other** — The avatar generator at /create/prompt was a cul-de-sac: no site navigation, no footer, no way onward except a back button. It now carries the full three.ws header and footer like every other page, and finishing an avatar pops the same 'what now?' card the Forge shows — open it in Studio, make it an agent, walk it, or embed it, with your new avatar carried along. The two text-to-3D tools also cross-link: Forge points character-makers to Describe it to 3D (rigged avatars), and Describe it to 3D points prop-makers to Forge (textured objects), so you always land in the right tool. (`/create/prompt`) `[improvement]`
- **Embed any Forge model on your own site with one line** — Every model you forge now has an Embed button next to Download. It hands you a ready-to-paste snippet — an iframe by default, or a <model-viewer> web component for builders — that drops a live, orbitable, AR-ready 3D model onto any website, with a live preview and size presets (16:9, square, 4:5) right in the panel. The iframe points at a new lightweight three.ws viewer (/forge/embed) that needs no scripts on the host page, and clicking its corner badge brings visitors back to Forge with your prompt pre-loaded to remix. Same idea as the <agent-3d> embed, now for any generated object. (`/forge`) `[feature]`
+- **Refine any Forge model to higher quality in one click — plus sharper multi-view guidance** — Three upgrades to the Forge (/forge). After a model generates, a new Refine button re-runs that exact prompt or photos one quality tier higher — Draft to Standard to High — so you can preview cheaply, then commit to the best version without retyping anything. When building from photos, a live counter now shows how many of the four reference views you've added and reminds you that more angles make a sharper mesh. And the action bar under each finished model now reflows cleanly on phones, with Refine and Make-another leading at full width. Sketch mode also makes its required description unmistakable. (`/forge`) `[improvement]`
+- **See any Forge model in AR — scan from your desktop, place it in your room** — Every finished model now has a View in AR button. On a phone it drops the model into your space through the camera; on a desktop it shows a QR code you scan with your phone to open the same model, one tap from AR — so you can walk around what you just made at real-world scale. The embed viewer gained a big one-tap AR launcher on phones too, so models embedded on other sites are placeable in AR as well. No app, no download — it runs in the browser. (`/forge`) `[feature]`
- **The full page directory is now one click away — and instantly filterable** — three.ws has grown past 200 pages, so the sitemap directory got a real upgrade. A new "All pages" link in the Discover menu takes you straight to it, and the page itself now has an instant filter — press / and type to narrow every page by name, path, or description, with live per-section counts. Filtered views are shareable links, so you can send someone exactly the slice of the platform you mean. The directory now finds you when you're lost, too: it's a quick action in the ⌘K search palette, a no-results search hands you off to it with your query carried over, the 404 page offers it pre-filtered to the closest matches for the address you tried, and /pages, /directory, /everything, and /all-pages all take you there. Eighteen pages that had never been registered in the index — What is three.ws?, the 3D Scanner, the Glossary, Support, the agent-economy demos, and all six IBM watsonx showcases under a new Integrations section — are now in the directory, the search palette, and the crawler sitemap. (`/sitemap`) `[improvement]`
+- **Tutorials read better: one-tap copy on every code block, live progress, and a jump-to-the-tool button** — The tutorial reader (/tutorials) got a polish pass that applies to every guide. Code blocks now have a one-click Copy button, so you can lift a snippet without selecting it by hand. A slim progress rail across the top tracks how far you've read, and a back-to-top button appears once you scroll in. Each section heading has a hover link for sharing a deep link to that exact spot, and every tutorial now opens with a clear call-to-action button — the new text-to-3D guides drop you straight into the Forge. New this release: four beginner guides for turning a text prompt or photos into a downloadable 3D model, a copy-paste prompt cookbook, and an API walkthrough. (`/tutorials`) `[docs, improvement]`
## 2026-06-12
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 39be43485..aba75f94d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -10,11 +10,19 @@ Thanks for your interest in contributing! This guide covers everything you need
git clone https://github.com/nirholas/three.ws.git
cd three.ws
npm install
+npm run setup
npm run dev
```
Open [http://localhost:3000](http://localhost:3000) and verify the default model loads.
+`npm run setup` finishes what `npm install` can't: it builds the local
+`solana-agent-sdk` (linked as a `file:` dependency, ships no prebuilt `dist/`)
+and generates the gitignored `data/_generated/*` artifacts that the app,
+sitemap, and test suite read. It also activates the repo's pre-push hook
+(`.githooks/pre-push`), which runs `npm run typecheck` before every push.
+It is idempotent — re-running it skips anything already up to date.
+
---
## How to Contribute
@@ -102,6 +110,17 @@ See [docs/architecture.md](docs/architecture.md) for a deep dive.
## Testing Your Changes
+### Automated tests
+
+```bash
+npm run typecheck # tsc over the @ts-check'd files — also gates every deploy
+npm run test:core # vitest unit suite
+npm test # vitest + playwright e2e
+```
+
+If unit tests fail on a fresh clone with module-resolution or missing-file
+errors, run `npm run setup` first.
+
### Manual Testing Checklist
Before submitting a PR, verify:
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index f5c444c57..633f3f524 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -49,16 +49,27 @@ function failClosedLimiter({ limit, window }) {
/**
* @param {string} name
- * @param {{ limit: number, window: string, critical?: boolean }} opts
+ * @param {{ limit: number, window: string, critical?: boolean, local?: boolean }} opts
* `critical: true` marks a cost/money-moving bucket. When Redis is absent in
* production these fail closed (deny) instead of using the unbounded in-memory
* fallback. Non-critical buckets keep the permissive in-memory fallback so a
* missing-Redis misconfig degrades read endpoints gracefully rather than
* taking the whole site down.
+ * `local: true` deliberately enforces per-instance, in-memory only — never a
+ * Redis command. For high-frequency, cheap-read buckets (status polling) whose
+ * only job is to bound poll floods, per-instance caps bound throughput just as
+ * well (limit × warm instances, and Vercel bounds instances), and the saved
+ * commands are what keep the Upstash quota alive (June 2026 outage). Never
+ * combine with `critical`.
*/
function getLimiter(name, opts) {
const key = `${name}:${opts.limit}:${opts.window}`;
if (limiters.has(key)) return limiters.get(key);
+ if (opts.local) {
+ const lim = memoryLimiter(opts);
+ limiters.set(key, lim);
+ return lim;
+ }
if (!redis) {
const lim = opts.critical && IS_PRODUCTION ? failClosedLimiter(opts) : memoryLimiter(opts);
limiters.set(key, lim);
@@ -247,7 +258,13 @@ export const limits = {
// human iterating on a prompt routinely exceeds 12/h; this lane lets them.
mcp3dGenerateFree: (key) =>
getLimiter('mcp3d:generate:free', { limit: 60, window: '1 h' }).limit(key),
- mcp3dStatus: (key) => getLimiter('mcp3d:status', { limit: 240, window: '1 m' }).limit(key),
+ // Status polling is the highest-frequency call in the generation flow (every
+ // active job polls every few seconds, plus the /forge health pill). It only
+ // guards against pathological poll floods, so it is enforced per instance
+ // (`local`) — spending a distributed Redis command per poll is what drained
+ // the Upstash quota without buying any real protection here.
+ mcp3dStatus: (key) =>
+ getLimiter('mcp3d:status', { limit: 240, window: '1 m', local: true }).limit(key),
// Forge prompt enhancer — one free-tier LLM rewrite per call. Cheap text
// completion, but each one hits an upstream provider, so cap per principal to
// keep that egress bounded. Non-critical: a Redis outage must never block a
diff --git a/api/_mcp/catalog.js b/api/_mcp/catalog.js
index 37039e9d0..d619b480a 100644
--- a/api/_mcp/catalog.js
+++ b/api/_mcp/catalog.js
@@ -25,18 +25,29 @@ const baseDefs = [
// Free, public entry point — listed first so discovery clients see it up top.
// priceFor annotates the per-call price of the paid tools in the overview.
-const gettingStarted = buildGettingStartedTool({
- server: 'three.ws',
- tagline:
- 'The main three.ws MCP server: render and manage 3D avatars and models, animations, an agent registry, agent memory, and live pump.fun market data.',
- tools: baseDefs,
- priceFor,
- access: [
- 'Connect with a three.ws account (OAuth) for your account-scoped avatars, agents, and memory.',
- 'Or pay per call via x402 (USDC) for the public tools — each priced tool shows its price in tools/list.',
- ],
- links: { homepage: 'https://three.ws', source: 'https://github.com/nirholas/three.ws' },
-});
+// Annotations: a static, local overview built at module load — read-only,
+// deterministic, closed-world (destructiveHint is explicit because the MCP
+// spec defaults it to true when omitted).
+const gettingStarted = {
+ ...buildGettingStartedTool({
+ server: 'three.ws',
+ tagline:
+ 'The main three.ws MCP server: render and manage 3D avatars and models, animations, an agent registry, agent memory, and live pump.fun market data.',
+ tools: baseDefs,
+ priceFor,
+ access: [
+ 'Connect with a three.ws account (OAuth) for your account-scoped avatars, agents, and memory.',
+ 'Or pay per call via x402 (USDC) for the public tools — each priced tool shows its price in tools/list.',
+ ],
+ links: { homepage: 'https://three.ws', source: 'https://github.com/nirholas/three.ws' },
+ }),
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false,
+ },
+};
const allDefs = [gettingStarted, ...baseDefs];
diff --git a/api/_mcp/tools/agents.js b/api/_mcp/tools/agents.js
index 7e3d5c976..64be9e548 100644
--- a/api/_mcp/tools/agents.js
+++ b/api/_mcp/tools/agents.js
@@ -185,6 +185,13 @@ export const toolDefs = [
{
name: 'call_agent',
title: 'Call agent',
+ // Invokes another agent's LLM turn — not a pure read, never destructive.
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description:
'Send a message to another three.ws agent and get its response. Use this to delegate specialized tasks.',
inputSchema: {
@@ -223,6 +230,15 @@ export const toolDefs = [
{
name: 'register_agent',
title: 'Register an agent on-chain',
+ // Creates on-chain state (mint + registry enrolment). The handler
+ // short-circuits an already-registered agent, but force:true re-runs,
+ // so the conservative hint is non-idempotent.
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description:
"Mint one of your agents' on-chain digital identity. On Solana (chain:solana) " +
'this enrols the agent in the Metaplex Agent Registry server-custodially — ' +
@@ -309,6 +325,13 @@ export const toolDefs = [
{
name: 'identity_check',
title: 'Screen an agent identity for impersonation',
+ // Pure screening read; verdicts come from live models, so not idempotent.
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description:
'Screen an agent identity (an existing agent_id, or a proposed name + description) ' +
'for impersonation and policy violations before it goes public. Uses IBM Granite ' +
diff --git a/api/_mcp/tools/animations.js b/api/_mcp/tools/animations.js
index 36128da73..b5df03be7 100644
--- a/api/_mcp/tools/animations.js
+++ b/api/_mcp/tools/animations.js
@@ -159,6 +159,14 @@ export const toolDefs = [
{
name: 'list_animations',
title: 'List animation presets',
+ // Reads the platform's own static, curated manifest — deterministic
+ // and closed-world.
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false,
+ },
description:
'List the curated, retargetable animation presets in the three.ws library — name, label, category, and whether the clip loops. Use this to discover valid `animation` values for apply_animation.',
inputSchema: {
@@ -200,6 +208,12 @@ export const toolDefs = [
{
name: 'apply_animation',
title: 'Apply an animation preset to a rigged model',
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description:
'Retarget a curated animation preset onto a caller-supplied rigged humanoid GLB. Returns the retargeted three.js AnimationClip JSON (keyed to the rig\'s actual bone names, hip translation rescaled to its proportions) plus a retarget report — load it alongside the model and play. Set format="glb" to also bake an animated GLB server-side (best-effort: textured rigs may exceed the headless bake budget and fall back to clip JSON — the /pose gallery is the guaranteed GLB export). SSRF-hardened: only public https model URLs are fetched.',
inputSchema: {
@@ -357,6 +371,12 @@ export const toolDefs = [
{
name: 'text_to_animation',
title: 'Generate an animation from a text prompt and retarget it onto a model',
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description:
'Generate a brand-new motion from a natural-language prompt (e.g. "waving confidently", "a slow tai-chi sweep") with a motion-diffusion model, then retarget it onto a caller-supplied rigged humanoid GLB — the same retarget engine apply_animation uses. Returns the retargeted three.js AnimationClip JSON (or a baked animated GLB) plus a report. Unlike preset libraries, the motion does not pre-exist: it is synthesized for the prompt. Requires the text2motion worker configured on the deployment.',
inputSchema: {
diff --git a/api/_mcp/tools/avatars.js b/api/_mcp/tools/avatars.js
index be3d57631..97198a3c9 100644
--- a/api/_mcp/tools/avatars.js
+++ b/api/_mcp/tools/avatars.js
@@ -24,10 +24,22 @@ function rpcError(code, message, data) {
return e;
}
+// MCP tool annotations (2025-06-18 spec). destructiveHint defaults to TRUE when
+// omitted, so every tool sets all four hints explicitly. Reads of account/gallery
+// state are not idempotent (the underlying data and signed URLs change between
+// calls) but never write anything.
+const READ_ANNOTATIONS = {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+};
+
export const toolDefs = [
{
name: 'list_my_avatars',
title: 'List my avatars',
+ annotations: READ_ANNOTATIONS,
description:
"List the authenticated user's avatars. Returns id, name, slug, size, visibility, and direct model_url (when visibility permits).",
inputSchema: {
@@ -59,6 +71,7 @@ export const toolDefs = [
{
name: 'get_avatar',
title: 'Get avatar',
+ annotations: READ_ANNOTATIONS,
description:
'Fetch a single avatar by id or by owner+slug. Returns metadata and a model_url (public/unlisted) or short-lived signed URL (private).',
inputSchema: {
@@ -92,6 +105,7 @@ export const toolDefs = [
{
name: 'search_public_avatars',
title: 'Search public avatars',
+ annotations: READ_ANNOTATIONS,
description:
'Search the public avatar gallery. Useful for finding characters to render without prior knowledge of an id.',
inputSchema: {
@@ -122,6 +136,8 @@ export const toolDefs = [
{
name: 'render_avatar',
title: 'Render avatar',
+ // Builds viewer HTML in-memory; persists nothing — a read, not a write.
+ annotations: READ_ANNOTATIONS,
description:
'Produce an HTML <model-viewer> snippet that renders the given avatar. ' +
'Return this text as an inline HTML artifact to display an interactive 3D avatar.',
@@ -210,6 +226,15 @@ export const toolDefs = [
{
name: 'render_avatar_image',
title: 'Render an avatar to an image',
+ // Persists the render to storage, but the cache keys on the exact
+ // parameters: repeating a call returns the cached image with no
+ // additional effect — idempotent, non-destructive write.
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: true,
+ },
description:
'Render a stored avatar to a real PNG/JPEG/WebP image (headless three.js) and ' +
'return its URL — ready for an <img> tag, social card, or game loader. Choose a ' +
@@ -326,6 +351,13 @@ export const toolDefs = [
{
name: 'delete_avatar',
title: 'Delete avatar',
+ // Deletes a user's avatar — the destructive hint is real here.
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: true,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description: 'Soft-delete an avatar you own. Requires avatars:delete scope.',
inputSchema: {
type: 'object',
diff --git a/api/_mcp/tools/embed.js b/api/_mcp/tools/embed.js
index de93e9261..bbf440677 100644
--- a/api/_mcp/tools/embed.js
+++ b/api/_mcp/tools/embed.js
@@ -124,6 +124,14 @@ export const toolDefs = [
{
name: 'get_embed_code',
title: 'Get embed code',
+ // Pure read: builds the iframe snippet from existing records, mutates
+ // nothing, and the same target yields the same snippet.
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: true,
+ },
description:
'Return a ready-to-paste <iframe> embed snippet (plus shareable URL, oEmbed URL, and OG thumbnail) for a three.ws avatar, on-chain agent, or Forge creation. Embed a persistent 3D avatar into Notion, Webflow, Framer, a blog, or any site as easily as a YouTube video. Provide exactly one target: agent_id, OR chain_id + onchain_agent_id, OR creation_id.',
inputSchema: {
diff --git a/api/_mcp/tools/memory.js b/api/_mcp/tools/memory.js
index eb83a83d6..2384053dd 100644
--- a/api/_mcp/tools/memory.js
+++ b/api/_mcp/tools/memory.js
@@ -86,6 +86,13 @@ export const toolDefs = [
{
name: 'remember',
title: 'Remember',
+ // Inserts a new row every call — additive write, never destructive.
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description:
'Store a long-term memory for one of your agents. Use for durable facts: who the user is (type=user), guidance/corrections (feedback), ongoing work (project), or external pointers (reference). Returns the stored memory.',
inputSchema: {
@@ -150,6 +157,12 @@ export const toolDefs = [
{
name: 'recall',
title: 'Recall',
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description:
'Retrieve the most relevant memories for a query from one of your agents. Ranks by relevance to the query blended with salience and recency, excluding expired memories. Returns an ordered list.',
inputSchema: {
@@ -228,6 +241,13 @@ export const toolDefs = [
{
name: 'forget',
title: 'Forget',
+ // Permanently deletes a stored memory — destructive.
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: true,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description: 'Delete a memory you own by its id.',
inputSchema: {
type: 'object',
diff --git a/api/_mcp/tools/models.js b/api/_mcp/tools/models.js
index cfe84c173..e55138451 100644
--- a/api/_mcp/tools/models.js
+++ b/api/_mcp/tools/models.js
@@ -19,6 +19,16 @@ async function safeFetchModel(url) {
}
}
+// MCP tool annotations (2025-06-18 spec): all three tools are deterministic,
+// pure inspections of a caller-supplied URL — same file, same report.
+// destructiveHint defaults to TRUE when omitted, so it is set explicitly.
+const INSPECTION_ANNOTATIONS = {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: true,
+};
+
function formatValidationSummary(s, messages) {
const head =
`glTF-Validator report for ${s.filename} (${(s.fileSize / 1024).toFixed(1)} KB)\n` +
@@ -73,6 +83,7 @@ export const toolDefs = [
{
name: 'validate_model',
title: 'Validate glTF/GLB model',
+ annotations: INSPECTION_ANNOTATIONS,
description:
'Run the Khronos glTF-Validator against a remote GLB or glTF URL. Returns a structured report of errors, warnings, infos, and hints — the authoritative answer to "is this file spec-compliant?". SSRF-hardened: only public https URLs are fetched.',
inputSchema: {
@@ -125,6 +136,7 @@ export const toolDefs = [
{
name: 'inspect_model',
title: 'Inspect glTF/GLB model',
+ annotations: INSPECTION_ANNOTATIONS,
description:
'Parse a remote GLB or glTF and return structural stats: scene/node/mesh counts, vertex and triangle totals, material and texture summaries, extensions used. Pure inspection — no optimization advice.',
inputSchema: {
@@ -156,6 +168,7 @@ export const toolDefs = [
{
name: 'optimize_model',
title: 'Suggest optimizations for a glTF/GLB model',
+ annotations: INSPECTION_ANNOTATIONS,
description:
'Inspect the model and return actionable suggestions for reducing size and draw-call overhead: triangle budget, Draco/Meshopt compression, oversized textures, KTX2 transcoding, non-indexed primitives, redundant materials, and more.',
inputSchema: {
diff --git a/api/_mcp/tools/pumpfun.js b/api/_mcp/tools/pumpfun.js
index 12817008f..04cea1106 100644
--- a/api/_mcp/tools/pumpfun.js
+++ b/api/_mcp/tools/pumpfun.js
@@ -6,6 +6,17 @@ function clamp(n, lo, hi, fallback) {
return Math.max(lo, Math.min(hi, x));
}
+// MCP tool annotations (2025-06-18 spec): every pump.fun intel tool is a
+// read-only view of a live upstream feed — never idempotent (the market moves),
+// never destructive. destructiveHint defaults to TRUE when omitted, so it is
+// set explicitly.
+const LIVE_FEED_ANNOTATIONS = {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+};
+
function pumpfunToolResult(r) {
if (!pumpfunBotEnabled()) {
return {
@@ -30,6 +41,7 @@ export const toolDefs = [
{
name: 'pumpfun_recent_claims',
title: 'Recent pump.fun claims',
+ annotations: LIVE_FEED_ANNOTATIONS,
description:
"Fetch the most recent pump.fun GitHub social-fee claim events with full enrichment: GitHub profile, X/Twitter follower data, influencer tier, first-time-claim flag, fake-claim detection, and AI summary. Use to answer 'what's happening on pump.fun right now?'.",
inputSchema: {
@@ -48,6 +60,7 @@ export const toolDefs = [
{
name: 'pumpfun_token_intel',
title: 'Pump.fun token intel',
+ annotations: LIVE_FEED_ANNOTATIONS,
description:
'Full intel on a pump.fun token: graduation status, bonding-curve progress, creator profile, top holders, volume, bundle detection, and trust signals.',
inputSchema: {
@@ -66,6 +79,7 @@ export const toolDefs = [
{
name: 'pumpfun_creator_intel',
title: 'Pump.fun creator intel',
+ annotations: LIVE_FEED_ANNOTATIONS,
description:
'Reputation profile for a pump.fun creator wallet: prior launches, graduation rate, claim activity, and behavioural trust signals.',
inputSchema: {
@@ -84,6 +98,7 @@ export const toolDefs = [
{
name: 'pumpfun_recent_graduations',
title: 'Recent pump.fun graduations',
+ annotations: LIVE_FEED_ANNOTATIONS,
description:
'Tokens that recently graduated from the bonding curve to PumpAMM, with creator + holder analysis.',
inputSchema: {
diff --git a/api/_mcp/tools/solana.js b/api/_mcp/tools/solana.js
index e43e6da55..65a3b2d35 100644
--- a/api/_mcp/tools/solana.js
+++ b/api/_mcp/tools/solana.js
@@ -93,10 +93,22 @@ async function solanaPassport(asset, network) {
};
}
+// MCP tool annotations (2025-06-18 spec): public, read-only views over the
+// live on-chain attestation index — new attestations land between calls, so
+// not idempotent. destructiveHint defaults to TRUE when omitted, so it is set
+// explicitly.
+const ATTESTATION_READ_ANNOTATIONS = {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+};
+
export const toolDefs = [
{
name: 'solana_agent_reputation',
title: 'Get Solana agent reputation',
+ annotations: ATTESTATION_READ_ANNOTATIONS,
description:
'Computed reputation summary for a Solana-registered three.ws agent. Returns total/verified feedback counts, score averages (raw + verified-only), validation pass/fail, task acceptance, and dispute counts. Verified score only includes feedback whose task was acknowledged on-chain by the agent owner. Public; no auth required.',
inputSchema: {
@@ -119,6 +131,7 @@ export const toolDefs = [
{
name: 'solana_agent_attestations',
title: 'List Solana agent attestations',
+ annotations: ATTESTATION_READ_ANNOTATIONS,
description:
'List recent on-chain attestations about a Solana-registered agent (feedback, validation, task offers, acceptances, disputes). Backed by the three.ws indexer for sub-100ms reads. Each row includes verified/disputed/revoked flags. Public; no auth required.',
inputSchema: {
@@ -152,6 +165,7 @@ export const toolDefs = [
{
name: 'solana_agent_passport',
title: 'Get Solana agent passport',
+ annotations: ATTESTATION_READ_ANNOTATIONS,
description:
'Full discovery card for a Solana agent: identity (Metaplex Core asset), owner wallet, reputation summary, latest validation result, and attestation schema endpoint. Equivalent to an ERC-8004 passport — use this when one tool call should answer "who is this agent and can I trust them?".',
inputSchema: {
diff --git a/api/_mcp3d/catalog.js b/api/_mcp3d/catalog.js
index 3b50b7df7..665b57fc1 100644
--- a/api/_mcp3d/catalog.js
+++ b/api/_mcp3d/catalog.js
@@ -2,6 +2,7 @@ import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import { buildGettingStartedTool } from '../_lib/mcp-getting-started.js';
+import { priceUsdcForTier } from '../_lib/forge-tiers.js';
import { toolDefs as studioDefs } from './tools/studio.js';
import { toolDefs as modelDefs } from '../_mcp/tools/models.js';
import { toolDefs as animationDefs } from '../_mcp/tools/animations.js';
@@ -20,16 +21,28 @@ const reusedModelDefs = modelDefs.filter(
const baseDefs = [...studioDefs, ...reusedModelDefs, ...animationDefs];
// Free, public entry point — listed first so discovery clients see it up top.
-const gettingStarted = buildGettingStartedTool({
- server: 'three.ws 3D Studio',
- tagline: 'Turn text or images into interactive, animation-ready 3D models.',
- tools: baseDefs,
- access: [
- 'Connect with a three.ws account (OAuth) or an x402 wallet — most studio tools just need a connected client.',
- 'Generation tools (text_to_3d, image_to_3d) run async jobs; poll generation_status for the GLB and an inline <model-viewer> artifact.',
- ],
- links: { homepage: 'https://three.ws', source: 'https://github.com/nirholas/three.ws' },
-});
+// Annotations: a static, local overview built at module load — read-only,
+// deterministic, closed-world (destructiveHint is explicit because the MCP
+// spec defaults it to true when omitted).
+const gettingStarted = {
+ ...buildGettingStartedTool({
+ server: 'three.ws 3D Studio',
+ tagline: 'Turn text or images into interactive, animation-ready 3D models.',
+ tools: baseDefs,
+ access: [
+ 'Discovery is free: initialize, tools/list, ping, and this tool need no credentials.',
+ `Connect with a three.ws account (OAuth) to run every tool operator-funded, or pay per call with an x402 wallet (USDC on Base or Solana) — generation is priced by tier ($${priceUsdcForTier('draft')} draft / $${priceUsdcForTier('standard')} standard / $${priceUsdcForTier('high')} high), mesh edits $0.01–0.05, and status/preview/inspection tools are free.`,
+ 'Generation tools (text_to_3d, image_to_3d) run async jobs; poll generation_status for the GLB and an inline <model-viewer> artifact.',
+ ],
+ links: { homepage: 'https://three.ws', source: 'https://github.com/nirholas/three.ws' },
+ }),
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false,
+ },
+};
const allDefs = [gettingStarted, ...baseDefs];
diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.js
index ad226db7c..cbf30966e 100644
--- a/api/_mcp3d/tools/studio.js
+++ b/api/_mcp3d/tools/studio.js
@@ -60,6 +60,17 @@ function rateKey(auth) {
return auth.userId || auth.rateKey || 'anon';
}
+// MCP tool annotations (2025-06-18 spec). destructiveHint defaults to TRUE
+// when omitted, so every tool sets all four hints explicitly. The generation
+// and mesh-op tools create new assets/jobs (never overwrite the source), so
+// they are non-read-only, non-destructive, and non-idempotent.
+const GENERATIVE_ANNOTATIONS = {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+};
+
async function enforce(limiter, auth) {
const rl = await limiter(rateKey(auth));
if (!rl.success) {
@@ -395,6 +406,7 @@ export const toolDefs = [
{
name: 'text_to_3d',
title: 'Generate a 3D model from a text prompt',
+ annotations: GENERATIVE_ANNOTATIONS,
description:
'Turn a text description into a textured 3D model (GLB). Runs a fast text-to-image pass, then reconstructs a mesh from that image with Microsoft TRELLIS. Returns a job_id (poll with generation_status) plus the intermediate preview image. Best results: a single, clearly described object — "a worn leather armchair", "a low-poly red fox", "a sci-fi helmet".',
inputSchema: {
@@ -480,6 +492,7 @@ export const toolDefs = [
{
name: 'image_to_3d',
title: 'Reconstruct a 3D model from one or more images',
+ annotations: GENERATIVE_ANNOTATIONS,
description:
'Reconstruct a textured 3D model (GLB) from a reference image using Microsoft TRELLIS. Pass a single image_url, or image_urls (2–4 views of the SAME object from different angles — front/back/left/right) for multi-view reconstruction, which removes the back-of-object hallucination of single-image reconstruction. Returns a job_id to poll with generation_status, plus how many views were fused and which backend handled it. The cleaner the inputs — one subject, plain background, even lighting — the better the mesh.',
inputSchema: {
@@ -619,6 +632,13 @@ export const toolDefs = [
{
name: 'generation_status',
title: 'Check a 3D generation job',
+ // Status poll — pure read; the job state changes between calls.
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description:
'Poll a text_to_3d or image_to_3d job by its job_id. While running it reports the status; when finished it returns the GLB download URL and an inline <model-viewer> artifact — display that text/html resource as an interactive 3D artifact.',
inputSchema: {
@@ -718,6 +738,13 @@ export const toolDefs = [
{
name: 'preview_3d',
title: 'Preview any GLB as an interactive 3D artifact',
+ // Builds viewer HTML in-memory — deterministic for the same arguments.
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: true,
+ },
description:
'Render any public GLB URL as an inline <model-viewer> HTML artifact — orbit controls, AR on mobile, auto-rotate. Display the returned text/html resource as an inline 3D artifact. Use it to view a generated model, or any GLB on the web.',
inputSchema: {
@@ -767,6 +794,7 @@ export const toolDefs = [
{
name: 'remove_background',
title: 'Remove the background from an image',
+ annotations: GENERATIVE_ANNOTATIONS,
description:
'Strip the background from a photo or illustration using BRIA RMBG-2.0 (Apache-2.0). Returns a PNG with a transparent background — useful for preparing clean inputs before image_to_3d reconstruction.',
inputSchema: {
@@ -825,6 +853,7 @@ export const toolDefs = [
{
name: 'remesh_model',
title: 'Remesh, simplify, repair, or convert a 3D model',
+ annotations: GENERATIVE_ANNOTATIONS,
description:
'Process an existing GLB/OBJ/STL/PLY mesh: fix holes and degenerate geometry, reduce face count via quadric decimation, or convert to a different format (including FBX with skeleton for Unity/Unreal — a convert of a rigged GLB keeps its bones, skin weights, and blendshapes). Returns a clean GLB (or the requested format) job_id to poll with generation_status.',
inputSchema: {
@@ -902,6 +931,7 @@ export const toolDefs = [
{
name: 'stylize_model',
title: 'Apply a one-click geometric stylization filter to a 3D model',
+ annotations: GENERATIVE_ANNOTATIONS,
description:
'Transform any GLB/OBJ/STL/PLY mesh into a stylized variant with a single geometry pass — ' +
'no model inference, fast and cheap. Styles: "voxel" (blocky cubes on a grid), "brick" ' +
@@ -982,6 +1012,7 @@ export const toolDefs = [
{
name: 'segment_model',
title: 'Split a 3D model into named, separable parts',
+ annotations: GENERATIVE_ANNOTATIONS,
description:
'Segment a GLB/OBJ/STL/PLY mesh into meaningful parts with clean boundaries — head/torso/limbs on a character, body/wheels on a vehicle. Splits at physically disconnected shells and at concave creases (the minima rule), then names each part by region and tints it a distinct colour. Returns a GLB whose nodes ARE the parts (so each can be hidden, recoloured, replaced, or exported on its own) plus a parts manifest. Poll with generation_status; the result lists every part with its id, name, face count, and colour. Pass only_part to export a single part on its own.',
inputSchema: {
@@ -1077,6 +1108,7 @@ export const toolDefs = [
{
name: 'retexture_model',
title: 'Paint a new texture onto a 3D model from a text prompt',
+ annotations: GENERATIVE_ANNOTATIONS,
description:
'Generate a fresh texture for an untextured or poorly-textured GLB using SDXL + ControlNet depth. Renders the mesh from 8 viewpoints, generates coherent texture views guided by your prompt, and back-projects them onto the UV atlas. Returns a job_id to poll with generation_status.',
inputSchema: {
@@ -1157,6 +1189,7 @@ export const toolDefs = [
{
name: 'retexture_region',
title: "Repaint one masked region of a model's texture (magic brush)",
+ annotations: GENERATIVE_ANNOTATIONS,
description:
'Surgically repaint ONLY a region of an existing texture from a prompt and/or colour, ' +
'leaving the rest of the surface untouched and feathering the seam so the edit is invisible. ' +
@@ -1288,6 +1321,7 @@ export const toolDefs = [
{
name: 'auto_rig_model',
title: 'Auto-rig a static 3D model (skeleton + skin weights)',
+ annotations: GENERATIVE_ANNOTATIONS,
description:
'Turn a static GLB mesh into an animation-ready character: adds a humanoid skeleton and per-vertex skin weights via the three.ws rig pipeline (VAST-AI UniRig). Pairs with text_to_3d / image_to_3d — generate a mesh, then rig it, then drive it with apply_animation or pose_model. Returns a job_id; poll generation_status for the rigged GLB.',
inputSchema: {
@@ -1348,6 +1382,15 @@ export const toolDefs = [
{
name: 'pose_model',
title: 'Resolve a text prompt to a pose-studio seed + joint rotations',
+ // Pure local computation over the in-repo preset library — deterministic
+ // ("the same prompt always yields the same pose"), no external calls,
+ // nothing persisted.
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false,
+ },
description:
'Map a natural-language pose description to a deterministic pose-studio seed and the full Euler joint-rotation map for the three.ws humanoid mannequin, picked from the in-repo preset library. Returns the preset id, the complete pose (radians per joint), a stable seed, and a previewUrl on three.ws/pose. Deterministic and free — the same prompt always yields the same pose. Pair with auto_rig_model to pose a rigged character.',
inputSchema: {
@@ -1395,6 +1438,7 @@ export const toolDefs = [
{
name: 'direct_prompt',
title: 'Optimize a rough idea into a 3D-generation prompt (IBM Granite)',
+ annotations: GENERATIVE_ANNOTATIONS,
description:
'Rewrite a rough idea into an optimized text_to_3d prompt using IBM Granite. Returns one clean single-subject description plus structured directives (subject, style, materials, colors, detail) that produce cleaner meshes. Run before text_to_3d when a prompt is vague, conflicting, or multi-subject. Requires IBM watsonx.ai credentials on the server.',
inputSchema: {
@@ -1463,6 +1507,7 @@ export const toolDefs = [
{
name: 'generate_material',
title: 'Generate a glTF PBR material from a description (IBM Granite)',
+ annotations: GENERATIVE_ANNOTATIONS,
description:
'Generate a physically-based (PBR) glTF 2.0 material from a text description using IBM Granite — base color, metallic, roughness, and emissive factors. Returns a pbrMetallicRoughness material object you can attach to a generated mesh. Requires IBM watsonx.ai credentials on the server.',
inputSchema: {
@@ -1532,6 +1577,9 @@ export const toolDefs = [
{
name: 'save_avatar',
title: 'Save a generated GLB as a durable, named avatar',
+ // Each call mints a fresh slug + storage object — additive, never
+ // overwrites, so non-idempotent and non-destructive.
+ annotations: GENERATIVE_ANNOTATIONS,
description:
'Persist a generated GLB (e.g. the glb_url returned by generation_status) as a durable avatar in your three.ws library. The mesh is copied into our own storage so it survives the provider URL expiring, then registered as a named avatar you own. Returns avatar_id, slug, model_url, and a view_url. This is the bridge from the studio to the avatar system: after saving, get_avatar, render_avatar_image, embeds, and on-chain identity all work on the result. Requires you to be signed in.',
inputSchema: {
diff --git a/api/_mcpagent/catalog.js b/api/_mcpagent/catalog.js
index 23baa09a1..bac695ba5 100644
--- a/api/_mcpagent/catalog.js
+++ b/api/_mcpagent/catalog.js
@@ -5,16 +5,27 @@ import { buildGettingStartedTool } from '../_lib/mcp-getting-started.js';
import { toolDefs } from './tools.js';
// Free, public entry point — listed first so discovery clients see it up top.
-const gettingStarted = buildGettingStartedTool({
- server: 'three.ws Agent',
- tagline: 'Give your assistant a real on-chain wallet to discover, pay for, and call x402 services in USDC.',
- tools: toolDefs,
- access: [
- 'Sign in with your three.ws account (OAuth) to use your agent wallet.',
- 'pay_and_call spends USDC from your own three.ws agent wallet within your spend caps — check wallet_status first.',
- ],
- links: { homepage: 'https://three.ws', source: 'https://github.com/nirholas/three.ws' },
-});
+// Annotations: a static, local overview built at module load — read-only,
+// deterministic, closed-world (destructiveHint is explicit because the MCP
+// spec defaults it to true when omitted).
+const gettingStarted = {
+ ...buildGettingStartedTool({
+ server: 'three.ws Agent',
+ tagline: 'Give your assistant a real on-chain wallet to discover, pay for, and call x402 services in USDC.',
+ tools: toolDefs,
+ access: [
+ 'Sign in with your three.ws account (OAuth) to use your agent wallet.',
+ 'pay_and_call spends USDC from your own three.ws agent wallet within your spend caps — check wallet_status first.',
+ ],
+ links: { homepage: 'https://three.ws', source: 'https://github.com/nirholas/three.ws' },
+ }),
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false,
+ },
+};
const allDefs = [gettingStarted, ...toolDefs];
diff --git a/api/_mcpagent/tools.js b/api/_mcpagent/tools.js
index d5319012a..4ee8c703b 100644
--- a/api/_mcpagent/tools.js
+++ b/api/_mcpagent/tools.js
@@ -136,6 +136,13 @@ export const toolDefs = [
{
name: 'wallet_status',
title: "Check the agent's wallet",
+ // Read-only; balances move between calls, so not idempotent.
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description:
"Show the signed-in user's three.ws agent wallet: address, SOL and USDC balance, the per-call/hour/day spending caps, and whether autonomous spending is enabled. Read-only — never moves funds. Call this before pay_and_call to confirm there's balance and headroom.",
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
@@ -171,6 +178,13 @@ export const toolDefs = [
{
name: 'find_services',
title: 'Find paid services the agent can call',
+ // Read-only search over the live facilitator network.
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description:
'Search the live x402 facilitator network for paid services (HTTP APIs and MCP tools). Returns each match with its price and resource URL — feed a resource into pay_and_call to actually use it.',
inputSchema: {
@@ -224,6 +238,13 @@ export const toolDefs = [
{
name: 'pay_and_call',
title: 'Pay an x402 service and return its result',
+ // Spends the user's USDC — an irreversible transfer, so destructive.
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: true,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description:
"Call a paid x402 endpoint and settle the USDC payment automatically from the signed-in user's three.ws agent wallet, bounded by spending caps. Returns the service's response. Requires sign-in. If the per-call price exceeds max_usd (or the caps), the call is refused before any money moves.",
inputSchema: {
@@ -322,6 +343,14 @@ export const toolDefs = [
{
name: 'provision_wallet',
title: "Create the agent's wallet",
+ // Creates a wallet (idempotent for an existing one, but airdrop:true
+ // re-requests the faucet each call — conservative hint is false).
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description:
'Create (or return) the custodial Solana wallet for one of your agents so it can hold and earn USDC. Idempotent — if the agent already has a wallet, its address and live SOL/USDC balances are returned unchanged. On devnet you can request a 1 SOL airdrop for testing; mainnet wallets are never airdropped. Requires sign-in; you can only provision wallets for agents on your own account.',
inputSchema: {
@@ -396,6 +425,13 @@ export const toolDefs = [
{
name: 'monetize_endpoint',
title: 'Publish a paid endpoint to earn USDC',
+ // Publishes a new listing each call — additive write, never destructive.
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
description:
"Put a price on an upstream API your agent already serves and publish it as an x402 endpoint other agents can pay to call. three.ws hosts the paywall, settles each buyer's USDC to your agent's own wallet, and proxies the call to your target_url. The listing becomes discoverable via find_services / the bazaar and callable by pay_and_call. Requires a provisioned wallet for the chosen network — run provision_wallet first if you haven't. Requires sign-in; you can only monetize agents on your own account.",
inputSchema: {
diff --git a/api/_mcpbazaar/catalog.js b/api/_mcpbazaar/catalog.js
index a95f155ba..80f927169 100644
--- a/api/_mcpbazaar/catalog.js
+++ b/api/_mcpbazaar/catalog.js
@@ -5,16 +5,27 @@ import { buildGettingStartedTool } from '../_lib/mcp-getting-started.js';
import { toolDefs } from './tools.js';
// Free, public entry point — listed first so discovery clients see it up top.
-const gettingStarted = buildGettingStartedTool({
- server: 'three.ws x402 Bazaar',
- tagline: 'Discover, price, and locate paid agent services across the live x402 facilitator network.',
- tools: toolDefs,
- access: [
- 'Connect with a three.ws account (OAuth) or an x402 wallet — discovery tools query the live x402 facilitator network.',
- 'Use get_service(resource_url) to see a service’s exact price, payment networks, and a ready pay link before calling it.',
- ],
- links: { homepage: 'https://three.ws', source: 'https://github.com/nirholas/three.ws' },
-});
+// Annotations: a static, local overview built at module load — read-only,
+// deterministic, closed-world (destructiveHint is explicit because the MCP
+// spec defaults it to true when omitted).
+const gettingStarted = {
+ ...buildGettingStartedTool({
+ server: 'three.ws x402 Bazaar',
+ tagline: 'Discover, price, and locate paid agent services across the live x402 facilitator network.',
+ tools: toolDefs,
+ access: [
+ 'Connect with a three.ws account (OAuth) or an x402 wallet — discovery tools query the live x402 facilitator network.',
+ 'Use get_service(resource_url) to see a service’s exact price, payment networks, and a ready pay link before calling it.',
+ ],
+ links: { homepage: 'https://three.ws', source: 'https://github.com/nirholas/three.ws' },
+ }),
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false,
+ },
+};
const allDefs = [gettingStarted, ...toolDefs];
diff --git a/api/_mcpbazaar/tools.js b/api/_mcpbazaar/tools.js
index bcba3afe0..220bb6497 100644
--- a/api/_mcpbazaar/tools.js
+++ b/api/_mcpbazaar/tools.js
@@ -83,10 +83,22 @@ function formatList(items, { query } = {}) {
.join('\n');
}
+// MCP tool annotations (2025-06-18 spec): every discovery tool is a read-only
+// query of the live facilitator network — listings and prices change between
+// calls, so not idempotent. destructiveHint defaults to TRUE when omitted, so
+// it is set explicitly.
+const DISCOVERY_ANNOTATIONS = {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+};
+
export const toolDefs = [
{
name: 'search_services',
title: 'Search the x402 bazaar',
+ annotations: DISCOVERY_ANNOTATIONS,
description:
'Ranked search across the live x402 facilitator network for paid agent services (APIs and MCP tools you can pay for in stablecoin). Returns matching services with price, networks, and resource URL. Use get_service for full payment + input details.',
inputSchema: {
@@ -123,6 +135,7 @@ export const toolDefs = [
{
name: 'browse_services',
title: 'Browse the x402 bazaar',
+ annotations: DISCOVERY_ANNOTATIONS,
description:
'List paid agent services from the live x402 facilitator network without a search query — useful for "what can I pay for?". Returns services with price, networks, and resource URL, cheapest filters applied.',
inputSchema: {
@@ -150,6 +163,7 @@ export const toolDefs = [
{
name: 'get_service',
title: 'Get full details for one x402 service',
+ annotations: DISCOVERY_ANNOTATIONS,
description:
'Resolve a single x402 service by its resource URL (and tool_name for MCP services). Returns the exact payment requirements (price, asset, network, recipient), the input/output schema, and a ready-to-use pay link on three.ws. This is what you read before paying.',
inputSchema: {
diff --git a/api/_mcpibm/catalog.js b/api/_mcpibm/catalog.js
index 775809949..a5363f499 100644
--- a/api/_mcpibm/catalog.js
+++ b/api/_mcpibm/catalog.js
@@ -21,13 +21,15 @@ addFormats(ajv);
// Public tools/list entries — strip the server-side `handler` and the spec-only
// `example`/`output` (carried into the bazaar extension instead), and attach
-// pricing + discovery.
+// pricing + discovery. `annotations` (read-only/destructive/idempotent/
+// open-world hints) ride through to the wire verbatim.
export const TOOL_CATALOG = toolDefs.map((def) => {
const price = priceFor(def.name);
const entry = {
name: def.name,
title: def.title,
description: def.description,
+ annotations: def.annotations,
inputSchema: def.inputSchema,
};
if (price) {
diff --git a/api/_mcpibm/tools.js b/api/_mcpibm/tools.js
index 7e1bda92b..f390cc99b 100644
--- a/api/_mcpibm/tools.js
+++ b/api/_mcpibm/tools.js
@@ -34,6 +34,27 @@ function graniteConfig() {
return cfg;
}
+// MCP tool annotations (2025-06-18 spec) — mirrors the constants shipped in
+// packages/ibm-x402-mcp/src/tools/_shared.js so the hosted and stdio transports
+// advertise identical semantics. Granite inference reads the operator's models
+// without touching caller state (readOnlyHint true); generative tools can
+// return different output for identical input, embeddings are deterministic
+// for a given model. destructiveHint defaults to TRUE when omitted, so the
+// hosted catalog sets it explicitly.
+const generativeAnnotations = Object.freeze({
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+});
+
+const deterministicAnnotations = Object.freeze({
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: true,
+});
+
// MCP tool result helper. structuredContent carries the full machine-readable
// object (the same shape the npm package returns); content[0].text is a concise
// human-readable view for clients that render text.
@@ -129,6 +150,13 @@ const gettingStartedTool = {
name: 'ibm_granite_getting_started',
title: 'Getting Started (free)',
description: GETTING_STARTED_DESCRIPTION,
+ // Static, local overview — same annotations the npm package ships.
+ annotations: Object.freeze({
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false,
+ }),
inputSchema: {
type: 'object',
additionalProperties: false,
@@ -160,6 +188,7 @@ const chatTool = {
name: 'ibm_granite_chat',
title: 'IBM Granite Chat ($0.02)',
description: CHAT_DESCRIPTION,
+ annotations: generativeAnnotations,
inputSchema: {
type: 'object',
properties: {
@@ -264,6 +293,7 @@ const codeTool = {
name: 'ibm_granite_code',
title: 'IBM Granite Code ($0.025)',
description: CODE_DESCRIPTION,
+ annotations: generativeAnnotations,
inputSchema: {
type: 'object',
properties: {
@@ -336,6 +366,7 @@ const embedTool = {
name: 'ibm_granite_embed',
title: 'IBM Granite Embed ($0.005)',
description: EMBED_DESCRIPTION,
+ annotations: deterministicAnnotations,
inputSchema: {
type: 'object',
properties: {
@@ -432,6 +463,7 @@ const analyzeTool = {
name: 'ibm_granite_analyze',
title: 'IBM Granite Analyze ($0.04)',
description: ANALYZE_DESCRIPTION,
+ annotations: generativeAnnotations,
inputSchema: {
type: 'object',
properties: {
@@ -536,6 +568,7 @@ const forecastTool = {
name: 'ibm_granite_forecast',
title: 'IBM Granite Forecast ($0.05)',
description: FORECAST_DESCRIPTION,
+ annotations: generativeAnnotations,
inputSchema: {
type: 'object',
properties: {
diff --git a/api/cron/forge-smoke.js b/api/cron/forge-smoke.js
index bf716eebe..9f78c5e5a 100644
--- a/api/cron/forge-smoke.js
+++ b/api/cron/forge-smoke.js
@@ -12,6 +12,13 @@
// the resulting GLB's first bytes — only the 'glTF' magic counts as up.
// 3. GET /api/forge?health — surfaces paid-lane breakage (provider auth,
// quota, the rate-limiter store failing closed) that the free lane masks.
+// 4. Agent surfaces — the June 2026 MCP audit found the 3D Studio answering
+// with the wrong server's 402 and missing from the discovery catalog for
+// months; nothing generation-shaped could catch that. This leg asserts
+// what a paying agent sees: free tools/list reaches the studio toolset,
+// the unpaid 402 names /api/mcp-3d and quotes the standard tier price,
+// /.well-known/x402.json lists every generation surface, and the paid
+// REST endpoint still challenges with usable accepts.
//
// Failures page the ops Telegram channel; recovery is announced once. Like
// uptime-check, a concrete file keeps the import graph tiny.
@@ -127,13 +134,81 @@ async function runHealthCheck(origin) {
return { ok: false, reason: broken.join('\n') || `health status: ${health.body?.status}` };
}
+// What a wallet-holding agent actually experiences, end to end minus the
+// payment broadcast. Each probe asserts the exact contract the agent tooling
+// keys on; any drift (wrong resource URL, missing catalog entry, vanished
+// accepts) pages ops the same day instead of rotting for months.
+async function runAgentSurfaceCheck(origin) {
+ const failures = [];
+ const postJsonRpc = (path, payload) =>
+ fetchJson(`${origin}${path}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+
+ // Free discovery: a plain (non-MCP-protocol) client lists tools with no
+ // credentials and must see the generation tools.
+ const list = await postJsonRpc('/api/mcp-3d', { jsonrpc: '2.0', id: 1, method: 'tools/list' });
+ const toolNames = (list.body?.result?.tools || []).map((t) => t.name);
+ if (list.status !== 200 || !toolNames.includes('text_to_3d')) {
+ failures.push(
+ `mcp-3d free tools/list: HTTP ${list.status}, ` +
+ `${toolNames.length} tools, text_to_3d ${toolNames.includes('text_to_3d') ? 'present' : 'MISSING'}`,
+ );
+ }
+
+ // 402 identity: an unpaid text_to_3d call must be challenged by the 3D
+ // Studio itself — its own resource URL and the standard-tier price.
+ const challenge = await postJsonRpc('/api/mcp-3d', {
+ jsonrpc: '2.0',
+ id: 2,
+ method: 'tools/call',
+ params: { name: 'text_to_3d', arguments: { prompt: 'smoke probe — a small clay fox' } },
+ });
+ const resourceUrl = challenge.body?.resource?.url;
+ const amounts = (challenge.body?.accepts || []).map((a) => a.amount);
+ if (challenge.status !== 402 || resourceUrl !== `${origin}/api/mcp-3d`) {
+ failures.push(
+ `mcp-3d 402 identity: HTTP ${challenge.status}, resource ${resourceUrl || 'none'}`,
+ );
+ } else if (!amounts.includes('150000')) {
+ failures.push(`mcp-3d 402 price: expected standard-tier 150000, got [${amounts.join(', ')}]`);
+ }
+
+ // Discovery catalog: every generation surface stays indexed for crawlers.
+ const wk = await fetchJson(`${origin}/.well-known/x402.json`);
+ const cataloged = new Set((wk.body?.resources || []).map((r) => r.path));
+ for (const path of ['/api/x402/forge', '/api/mcp-3d', '/api/mcp']) {
+ if (!cataloged.has(path)) failures.push(`${path} missing from /.well-known/x402.json`);
+ }
+
+ // Paid REST: the bare endpoint must still challenge with usable accepts.
+ const forge = await fetchJson(`${origin}/api/x402/forge`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ prompt: 'smoke probe — a small clay fox', tier: 'draft' }),
+ });
+ if (forge.status !== 402 || !(forge.body?.accepts || []).length) {
+ failures.push(
+ `x402/forge challenge: HTTP ${forge.status}, ${(forge.body?.accepts || []).length} accepts`,
+ );
+ }
+
+ return failures.length ? { ok: false, reason: failures.join('\n') } : { ok: true };
+}
+
export default wrap(async (req, res) => {
if (!method(req, res, ['GET'])) return;
if (!requireCron(req, res)) return;
const origin = env.APP_ORIGIN || 'https://three.ws';
- const [generation, health] = await Promise.all([runGeneration(origin), runHealthCheck(origin)]);
- const ok = generation.ok && health.ok;
+ const [generation, health, agentSurfaces] = await Promise.all([
+ runGeneration(origin),
+ runHealthCheck(origin),
+ runAgentSurfaceCheck(origin),
+ ]);
+ const ok = generation.ok && health.ok && agentSurfaces.ok;
const previous = await cacheGet(LAST_STATUS_KEY);
await cacheSet(LAST_STATUS_KEY, { ok, at: Date.now() }, LAST_STATUS_TTL_S);
@@ -150,11 +225,16 @@ export default wrap(async (req, res) => {
signature: 'forge-smoke:health',
});
}
+ if (!agentSurfaces.ok) {
+ sendOpsAlert('FORGE SMOKE: agent surface contract broken', agentSurfaces.reason, {
+ signature: 'forge-smoke:agent-surfaces',
+ });
+ }
if (ok && previous && previous.ok === false) {
sendOpsAlert('RECOVERED: forge generation smoke test', `${origin}/forge — prompt→GLB verified`, {
signature: `forge-smoke:recovered:${Date.now()}`,
});
}
- return json(res, 200, { ok, generation, health });
+ return json(res, 200, { ok, generation, health, agent_surfaces: agentSurfaces });
});
diff --git a/api/forge-poster.js b/api/forge-poster.js
new file mode 100644
index 000000000..80bd66f70
--- /dev/null
+++ b/api/forge-poster.js
@@ -0,0 +1,83 @@
+/**
+ * Forge poster — attach a client-rendered thumbnail to a creation.
+ *
+ * POST /api/forge-poster { creation_id, image } (image: data URL)
+ *
+ * Image-intermediate engines store their flux reference image as the
+ * creation's preview, but the geometry-first and sketch lanes paint no image
+ * at all — their gallery and showcase cards rendered as glyph placeholders.
+ * After the finished GLB loads, the browser renders the actual mesh to a
+ * small webp and posts it here; the store uploads it to object storage and
+ * fills the row's empty preview slot.
+ *
+ * Fill-only and owner-scoped: a row that already has a preview keeps it (the
+ * reference image is half of the training pair), and writes only match rows
+ * created by the same anonymous client key (x-forge-client header). When the
+ * store is unconfigured this returns a clean { ok: false } — same contract as
+ * /api/forge-feedback.
+ */
+
+import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { hashClient, attachPoster, forgeStoreEnabled } from './_lib/forge-store.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+// Posters are 640px webp/png/jpeg renders — ~30-80 KB typical. The caps leave
+// generous headroom without letting the endpoint ingest arbitrary blobs.
+const MAX_POSTER_BYTES = 1_500_000;
+const MAX_BODY_BYTES = 2_500_000; // base64 inflation + JSON envelope
+
+const DATA_URL_RE = /^data:image\/(webp|png|jpeg);base64,([A-Za-z0-9+/=]+)$/;
+const EXT_BY_TYPE = { webp: 'webp', png: 'png', jpeg: 'jpg' };
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.mcp3dStatus(clientIp(req));
+ if (!rl.success) {
+ return rateLimited(res, rl);
+ }
+
+ if (!forgeStoreEnabled()) {
+ return json(res, 200, { ok: false, stored: false, reason: 'persistence_unconfigured' });
+ }
+
+ const body = await readJson(req, MAX_BODY_BYTES).catch(() => null);
+ const creationId = typeof body?.creation_id === 'string' ? body.creation_id.trim() : '';
+ if (!UUID_RE.test(creationId)) {
+ return json(res, 400, { error: 'invalid_creation', message: 'creation_id must be a uuid.' });
+ }
+
+ const match = DATA_URL_RE.exec(typeof body?.image === 'string' ? body.image : '');
+ if (!match) {
+ return json(res, 400, {
+ error: 'invalid_image',
+ message: 'image must be a base64 data URL (webp, png, or jpeg).',
+ });
+ }
+ const [, subtype, base64] = match;
+ const buf = Buffer.from(base64, 'base64');
+ if (buf.length === 0 || buf.length > MAX_POSTER_BYTES) {
+ return json(res, 400, {
+ error: 'invalid_image',
+ message: `Poster must be 1 byte – ${MAX_POSTER_BYTES} bytes.`,
+ });
+ }
+
+ const rawClient = req.headers['x-forge-client'];
+ const clientKey = hashClient(Array.isArray(rawClient) ? rawClient[0] : rawClient);
+
+ const url = await attachPoster({
+ id: creationId,
+ clientKey,
+ body: buf,
+ contentType: `image/${subtype}`,
+ ext: EXT_BY_TYPE[subtype],
+ });
+
+ // `stored: false` covers all benign no-ops — row not found for this client,
+ // or the creation already has a preview. Not an error worth a 4xx.
+ return json(res, 200, { ok: true, stored: Boolean(url), preview_image_url: url });
+});
diff --git a/api/ibm-mcp.js b/api/ibm-mcp.js
index 42bbc8326..90a5492fa 100644
--- a/api/ibm-mcp.js
+++ b/api/ibm-mcp.js
@@ -14,7 +14,7 @@
import { cors, readJson, wrap } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { settlePayment, encodePaymentResponseHeader } from './_lib/x402-spec.js';
-import { priceBatch } from './_lib/mcp-batch-price.js';
+import { priceBatch, isDiscoveryOnlyBatch } from './_lib/mcp-batch-price.js';
import { PROTOCOL_VERSION, dispatch } from './_mcpibm/dispatch.js';
import { graniteX402Amount } from './_mcpibm/pricing.js';
import { isFreeTool } from './_mcpibm/catalog.js';
@@ -25,6 +25,7 @@ import {
authenticateRequest,
handleSse,
handleTerminate,
+ isMcpProtocolClient,
} from './_mcp/auth.js';
import { sendX402Error } from './_mcp/payments.js';
@@ -54,11 +55,14 @@ export default wrap(async (req, res) => {
// A batch composed solely of the free public ibm_granite_getting_started tool
// is served without an x402 payment or OAuth token so any client — including
// non-x402 hosts like watsonx Orchestrate — can discover the server first.
+ // Discovery-only batches (initialize / tools/list / ping) from plain x402
+ // agents and crawlers are also free; MCP protocol clients still get the
+ // 401 that starts their OAuth flow.
const result = await authenticateRequest(req, res, {
x402Amount,
resourcePath: RESOURCE_PATH,
challenge: GRANITE_CHALLENGE,
- allowFree: allFree,
+ allowFree: allFree || (isDiscoveryOnlyBatch(body) && !isMcpProtocolClient(req)),
});
if (!result) return;
const { auth, x402Ctx } = result;
diff --git a/api/mcp.js b/api/mcp.js
index 1895605f2..70c2e521c 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -4,7 +4,7 @@ import { cors, readJson, wrap } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { settlePayment, encodePaymentResponseHeader } from './_lib/x402-spec.js';
import { x402AmountForTool } from './_lib/pump-pricing.js';
-import { priceBatch } from './_lib/mcp-batch-price.js';
+import { priceBatch, isDiscoveryOnlyBatch } from './_lib/mcp-batch-price.js';
import { PROTOCOL_VERSION, dispatch, isPublicTool } from './_mcp/dispatch.js';
import {
send401,
@@ -12,6 +12,7 @@ import {
authenticateRequest,
handleSse,
handleTerminate,
+ isMcpProtocolClient,
} from './_mcp/auth.js';
import { sendX402Error } from './_mcp/payments.js';
@@ -39,10 +40,12 @@ export default wrap(async (req, res) => {
// A batch composed solely of free public tools (e.g. getting_started) is
// served without an OAuth token or x402 payment so any client can discover
- // the server first.
+ // the server first. Likewise discovery-only batches (initialize /
+ // tools/list / ping) from plain x402 agents and crawlers — but NOT from
+ // MCP protocol clients, which need the 401 to start their OAuth flow.
const result = await authenticateRequest(req, res, {
x402Amount,
- allowFree: allFree,
+ allowFree: allFree || (isDiscoveryOnlyBatch(body) && !isMcpProtocolClient(req)),
});
if (!result) return;
const { auth, x402Ctx } = result;
diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.js
index e90748bd9..9e6f52b5c 100644
--- a/api/pump-fun-mcp.js
+++ b/api/pump-fun-mcp.js
@@ -1,20 +1,29 @@
-// POST /api/pump-fun-mcp
+// /api/pump-fun-mcp — pump.fun MCP server (Streamable HTTP transport, MCP 2025-06-18).
+// POST — JSON-RPC (single + batch) GET/HEAD — SSE handshake DELETE — terminate.
//
-// Real, in-house JSON-RPC 2.0 MCP server exposing read-only pump.fun tools to
-// the in-page <agent-3d> skill bundle (public/skills/pump-fun/).
+// Real, in-house MCP server exposing read-only pump.fun tools to remote MCP
+// connectors, the npm bridge (@three-ws/pumpfun-mcp), and the in-page
+// <agent-3d> skill bundle (public/skills/pump-fun/). Registered with the MCP
+// Registry as io.github.nirholas/pumpfun-solana-remote (see server-pumpfun.json).
+//
+// Back-compat: raw JSON-RPC consumers that POST plain application/json with no
+// MCP headers (the npm bridge, the skill bundle) keep working unchanged —
+// single requests return the same envelopes, statuses, and bodies as before.
+//
+// Tool names: canonical names are snake_case; the legacy camelCase names
+// remain accepted forever via TOOL_NAME_ALIASES (src/pump/mcp-tools.js).
//
// Tools backed by on-chain reads (no external indexer required):
-// - getBondingCurve → @pump-fun/pump-sdk fetchBondingCurve
-// - getTokenDetails → @solana/web3.js getAccountInfo + Metaplex metadata
-// - getTokenHolders → connection.getTokenLargestAccounts + concentration
+// - get_bonding_curve → @pump-fun/pump-sdk fetchBondingCurve
+// - get_token_details → @solana/web3.js getAccountInfo + Metaplex metadata
+// - get_token_holders → connection.getTokenLargestAccounts + concentration
//
// Tools that require indexed/aggregate data are routed through the existing
// pumpfunMcp client (api/_lib/pumpfun-mcp.js → upstream pumpfun-claims-bot).
// When PUMPFUN_BOT_URL is unset they return JSON-RPC error -32004 ("indexer
// not configured") — never a fabricated payload.
//
-// Methods: initialize, tools/list, tools/call. CORS open (read-only data).
-// Rate-limited by IP via limits.mcpIp.
+// CORS open (read-only data). Rate-limited by IP via limits.mcpIp.
import { cors, json, method, wrap, readJson, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
@@ -30,7 +39,7 @@ import {
import { getPumpSdk, getConnection, solanaPubkey, getAmmPoolState } from './_lib/pump.js';
import { pumpfunMcp, pumpfunBotEnabled } from './_lib/pumpfun-mcp.js';
import { getRadarSignals } from '../src/kol/radar.js';
-import { TOOLS, rpcError, rpcEnvelope } from '../src/pump/mcp-tools.js';
+import { TOOLS, resolveToolName, rpcError, rpcEnvelope } from '../src/pump/mcp-tools.js';
import { generateVanityKey } from '../src/pump/vanity-keygen.js';
import bs58 from 'bs58';
import { resolveSnsName, reverseLookupAddress } from '../src/solana/sns.js';
@@ -206,18 +215,18 @@ function indexerOrUnavailable(name) {
`tool "${name}" requires the pump.fun indexer (PUMPFUN_BOT_URL) to be configured`,
);
}
- // Map our tool names to the upstream bot's tool surface.
+ // Map our canonical tool names to the upstream bot's (camelCase) surface.
const upstreamMap = {
- searchTokens: { tool: 'searchTokens', args: { query: args.query, limit: args.limit } },
- getTokenTrades: {
+ search_tokens: { tool: 'searchTokens', args: { query: args.query, limit: args.limit } },
+ get_token_trades: {
tool: 'getTokenTrades',
args: { mint: args.mint, limit: args.limit },
},
- getTrendingTokens: { tool: 'getTrendingTokens', args: { limit: args.limit } },
- getNewTokens: { tool: 'getNewTokens', args: { limit: args.limit } },
- getGraduatedTokens: { tool: 'getGraduatedTokens', args: { limit: args.limit } },
- getKingOfTheHill: { tool: 'getKingOfTheHill', args: {} },
- getCreatorProfile: { tool: 'getCreatorIntel', args: { wallet: args.creator } },
+ get_trending_tokens: { tool: 'getTrendingTokens', args: { limit: args.limit } },
+ get_new_tokens: { tool: 'getNewTokens', args: { limit: args.limit } },
+ get_graduated_tokens: { tool: 'getGraduatedTokens', args: { limit: args.limit } },
+ get_king_of_the_hill: { tool: 'getKingOfTheHill', args: {} },
+ get_creator_profile: { tool: 'getCreatorIntel', args: { wallet: args.creator } },
};
const upstream = upstreamMap[name];
if (!upstream) throw rpcError(-32601, `tool "${name}" not implemented`);
@@ -728,21 +737,23 @@ async function handleGetTokenTrades({ mint, limit = 20, network = 'mainnet' }) {
// ── Dispatch ───────────────────────────────────────────────────────────────
+// Keyed by CANONICAL (snake_case) names. tools/call resolves legacy camelCase
+// aliases through resolveToolName before this lookup.
const HANDLERS = {
- getBondingCurve: handleGetBondingCurve,
- getTokenDetails: handleGetTokenDetails,
- getTokenHolders: handleGetTokenHolders,
+ get_bonding_curve: handleGetBondingCurve,
+ get_token_details: handleGetTokenDetails,
+ get_token_holders: handleGetTokenHolders,
kol_radar: handleKolRadar,
kol_leaderboard: handleKolLeaderboard,
- searchTokens: indexerOrUnavailable('searchTokens'),
- getTokenTrades: handleGetTokenTrades,
- getTrendingTokens: indexerOrUnavailable('getTrendingTokens'),
- getNewTokens: indexerOrUnavailable('getNewTokens'),
- getGraduatedTokens: indexerOrUnavailable('getGraduatedTokens'),
- getKingOfTheHill: indexerOrUnavailable('getKingOfTheHill'),
+ search_tokens: indexerOrUnavailable('search_tokens'),
+ get_token_trades: handleGetTokenTrades,
+ get_trending_tokens: indexerOrUnavailable('get_trending_tokens'),
+ get_new_tokens: indexerOrUnavailable('get_new_tokens'),
+ get_graduated_tokens: indexerOrUnavailable('get_graduated_tokens'),
+ get_king_of_the_hill: indexerOrUnavailable('get_king_of_the_hill'),
social_cashtag_sentiment: handleSocialCashtagSentiment,
social_x_post_impact: handleSocialXPostImpact,
- getCreatorProfile: indexerOrUnavailable('getCreatorProfile'),
+ get_creator_profile: indexerOrUnavailable('get_creator_profile'),
pumpfun_list_claims: handleListClaims,
pumpfun_watch_claims: handleWatchClaims,
pumpfun_first_claims: handleGetFirstClaims,
@@ -755,6 +766,24 @@ const HANDLERS = {
// ── HTTP entrypoint ────────────────────────────────────────────────────────
+// Keep in sync with api/_lib/mcp-dispatch.js PROTOCOL_VERSION. Declared locally
+// (not imported) so this read-only lambda — and the Worker mirror — don't pull
+// the usage/db graph that mcp-dispatch carries.
+const PROTOCOL_VERSION = '2025-06-18';
+const RESOURCE_PATH = '/api/pump-fun-mcp';
+const SERVER_INFO = { name: 'three.ws-pumpfun-mcp', version: '1.0.0' };
+const INSTRUCTIONS =
+ 'Free, read-only pump.fun + Solana tools from three.ws. Token discovery ' +
+ '(search_tokens, get_trending_tokens, get_new_tokens, get_graduated_tokens, ' +
+ 'get_king_of_the_hill), on-chain analysis (get_bonding_curve, get_token_holders, ' +
+ 'get_token_details, get_token_trades), creator intelligence (get_creator_profile, ' +
+ 'pumpfun_list_claims, pumpfun_watch_claims, pumpfun_first_claims), Solana Name ' +
+ 'Service (sns_resolve, sns_reverseLookup), market signals (kol_radar, ' +
+ 'kol_leaderboard, pumpfun_quote_swap, pumpfun_watch_whales), and social ' +
+ 'sentiment (social_cashtag_sentiment, social_x_post_impact). All data is live ' +
+ 'and on-chain; no API keys required for the free tools.';
+const MAX_BATCH = 16;
+
// Tools that are expensive (CPU grind or long-lived RPC subscriptions) or that
// return sensitive material (a secret key). These require authentication — a
// valid bearer (OAuth access token or sk_live_/sk_test_ API key) OR a verified
@@ -765,75 +794,215 @@ const AUTH_REQUIRED_TOOLS = new Set([
'pumpfun_watch_claims',
]);
-// Verify the request is authenticated for a gated tool. Returns
-// `{ x402Ctx }` on success — x402Ctx is null for bearer auth, and carries the
-// verified payment envelope for x402 callers so the dispatcher can settle it
-// AFTER the tool succeeds (verify → work → settle, same sequence as /api/mcp).
-// On failure it writes the JSON-RPC error envelope and returns null.
-async function authorizeGatedTool(req, res, id) {
+// Resolve the caller's credentials for a gated tool, once per request. Returns
+// { ok: true, x402Ctx } x402Ctx null for bearer auth, or the
+// verified payment envelope to settle later
+// { ok: false, failure } failure.kind ∈ bad_bearer | bad_payment |
+// no_credentials (+ message, envelope)
+// The result is memoized so a batch carrying several gated calls verifies the
+// bearer / X-PAYMENT exactly once and one payment covers the whole request.
+async function resolveGatedAuth(req) {
const bearer = extractBearer(req);
if (bearer) {
const auth = await authenticateBearer(bearer).catch(() => null);
- if (auth) return { x402Ctx: null };
- json(
- res,
- 401,
- rpcEnvelope(id, null, {
+ if (auth) return { ok: true, x402Ctx: null };
+ return {
+ ok: false,
+ failure: {
+ kind: 'bad_bearer',
code: -32001,
message: 'authentication required: invalid or expired bearer token',
- }),
- );
- return null;
+ },
+ };
}
const paymentHeader = req.headers['x-payment'];
if (paymentHeader) {
- const resourceUrl = resolveResourceUrl(req, '/api/pump-fun-mcp');
+ const resourceUrl = resolveResourceUrl(req, RESOURCE_PATH);
const requirements = paymentRequirements(resourceUrl);
try {
const verified = await verifyPayment({ paymentHeader, requirements });
- return { x402Ctx: { resourceUrl, requirements, verified } };
+ return { ok: true, x402Ctx: { resourceUrl, requirements, verified } };
} catch (err) {
- json(
- res,
- 402,
- rpcEnvelope(id, null, {
+ return {
+ ok: false,
+ failure: {
+ kind: 'bad_payment',
code: -32402,
message: `payment verification failed: ${err?.message || 'invalid payment'}`,
- }),
- );
- return null;
+ },
+ };
}
}
- // No bearer, no payment: answer 402 Payment Required with the full x402
- // envelope so paying agents (and registry crawlers like zauth) can discover
- // price/accepts. The body keeps the JSON-RPC error shape MCP clients
- // expect, with the envelope mirrored in error.data and the
- // PAYMENT-REQUIRED header (same dual-protocol pattern as _mcp/auth.js).
- const resourceUrl = resolveResourceUrl(req, '/api/pump-fun-mcp');
+ // No bearer, no payment: surface the full x402 envelope so paying agents
+ // (and registry crawlers like zauth) can discover price/accepts. The body
+ // keeps the JSON-RPC error shape MCP clients expect, with the envelope
+ // mirrored in error.data and the PAYMENT-REQUIRED header (same
+ // dual-protocol pattern as _mcp/auth.js).
+ const resourceUrl = resolveResourceUrl(req, RESOURCE_PATH);
const envelope = build402Body({
resourceUrl,
accepts: paymentRequirements(resourceUrl),
error: 'X-PAYMENT header is required',
});
- res.setHeader(
- 'PAYMENT-REQUIRED',
- Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64'),
- );
- json(
- res,
- 402,
- rpcEnvelope(id, null, {
+ return {
+ ok: false,
+ failure: {
+ kind: 'no_credentials',
code: -32402,
message:
'payment or authentication required for this tool (provide a Bearer token or X-PAYMENT)',
- data: envelope,
+ envelope,
+ },
+ };
+}
+
+// Single-request gate denial: same statuses, bodies, and headers raw JSON-RPC
+// consumers have always received (401 bad bearer / 402 otherwise).
+function writeGatedAuthFailure(res, id, failure) {
+ if (failure.kind === 'no_credentials') {
+ res.setHeader(
+ 'PAYMENT-REQUIRED',
+ Buffer.from(JSON.stringify(failure.envelope), 'utf8').toString('base64'),
+ );
+ }
+ const status = failure.kind === 'bad_bearer' ? 401 : 402;
+ return json(
+ res,
+ status,
+ rpcEnvelope(id, null, {
+ code: failure.code,
+ message: failure.message,
+ ...(failure.envelope ? { data: failure.envelope } : {}),
}),
+ { 'mcp-protocol-version': PROTOCOL_VERSION },
);
- return null;
+}
+
+// Batch-mode gate denial: HTTP stays 200, the denial becomes a per-message
+// JSON-RPC error (the PAYMENT-REQUIRED header is still set for discovery).
+function gatedAuthFailureEnvelope(res, id, failure) {
+ if (failure.kind === 'no_credentials' && !res.headersSent) {
+ res.setHeader(
+ 'PAYMENT-REQUIRED',
+ Buffer.from(JSON.stringify(failure.envelope), 'utf8').toString('base64'),
+ );
+ }
+ return rpcEnvelope(id, null, {
+ code: failure.code,
+ message: failure.message,
+ ...(failure.envelope ? { data: failure.envelope } : {}),
+ });
+}
+
+// GET/HEAD — the Streamable HTTP SSE handshake. This server never initiates
+// server→client messages (stateless, request-scoped lambda), so the stream
+// opens with the correct content-type and closes immediately; the spec allows
+// the server to close the SSE stream at any time. All tools that don't carry
+// an auth gate are free, so unlike /api/mcp-3d the handshake itself requires
+// no credentials.
+function handleSseHandshake(req, res) {
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/event-stream');
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);
+ if (req.method === 'HEAD') return res.end();
+ res.write(`: ${SERVER_INFO.name} streamable-http — POST JSON-RPC 2.0 to this URL\n\n`);
+ return res.end();
+}
+
+// Dispatch ONE JSON-RPC message. Returns null for notifications (no response
+// is owed) or the response envelope. `ctx` carries per-request state:
+// ensureGateAuth() memoized resolveGatedAuth for this request
+// batch true → gate denials become per-message error envelopes
+// (single requests keep their legacy HTTP 401/402 — the
+// caller handles the `gateDenied` flag)
+async function dispatchRpc(msg, ctx) {
+ const { id = null, method: rpcMethod, params } = msg || {};
+ const isNotification = msg?.id === undefined && typeof rpcMethod === 'string';
+
+ if (rpcMethod === 'initialize') {
+ return rpcEnvelope(id, {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: { tools: { listChanged: false } },
+ serverInfo: SERVER_INFO,
+ instructions: INSTRUCTIONS,
+ });
+ }
+ if (rpcMethod === 'ping') return rpcEnvelope(id, {});
+ if (rpcMethod === 'notifications/initialized') return null;
+ if (rpcMethod === 'tools/list') return rpcEnvelope(id, { tools: TOOLS });
+ if (rpcMethod === 'resources/list') return rpcEnvelope(id, { resources: [] });
+ if (rpcMethod === 'resources/templates/list') return rpcEnvelope(id, { resourceTemplates: [] });
+ if (rpcMethod === 'prompts/list') return rpcEnvelope(id, { prompts: [] });
+
+ if (rpcMethod === 'tools/call') {
+ const requestedName = params?.name;
+ // Legacy camelCase aliases resolve to the canonical snake_case names —
+ // both forms are accepted forever (TOOL_NAME_ALIASES is the contract).
+ const name = resolveToolName(requestedName);
+ // Own-property lookup only so "__proto__"/"constructor" can't resolve an
+ // inherited member and pass the !handler guard.
+ const handler =
+ typeof name === 'string' && Object.hasOwn(HANDLERS, name) ? HANDLERS[name] : null;
+ if (!handler) {
+ return rpcEnvelope(id, null, { code: -32601, message: `unknown tool: ${requestedName}` });
+ }
+ // Auth gate: expensive (vanity grind, long-lived RPC watch) and sensitive
+ // (returns a secret key) tools require a bearer or verified x402 payment.
+ if (AUTH_REQUIRED_TOOLS.has(name)) {
+ const authz = await ctx.ensureGateAuth();
+ if (!authz.ok) {
+ if (!ctx.batch) {
+ ctx.gateDenied = { id, failure: authz.failure };
+ return null;
+ }
+ return gatedAuthFailureEnvelope(ctx.res, id, authz.failure);
+ }
+ ctx.x402Ctx = authz.x402Ctx;
+ try {
+ const data = await handler(params?.arguments || {});
+ ctx.gatedSuccess = true;
+ ctx.gatedId = id;
+ return rpcEnvelope(id, {
+ content: [{ type: 'text', text: JSON.stringify(data) }],
+ structuredContent: data,
+ });
+ } catch (err) {
+ return rpcEnvelope(id, null, {
+ code: err.rpcCode || -32603,
+ message: err.message || 'tool error',
+ });
+ }
+ }
+ try {
+ const data = await handler(params?.arguments || {});
+ // Mirror MCP content shape so existing skill clients can unwrap text.
+ return rpcEnvelope(id, {
+ content: [{ type: 'text', text: JSON.stringify(data) }],
+ structuredContent: data,
+ });
+ } catch (err) {
+ return rpcEnvelope(id, null, {
+ code: err.rpcCode || -32603,
+ message: err.message || 'tool error',
+ });
+ }
+ }
+
+ if (isNotification) return null;
+ return rpcEnvelope(id, null, { code: -32601, message: `unknown method: ${rpcMethod}` });
}
export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
+ if (cors(req, res, { methods: 'GET,HEAD,POST,DELETE,OPTIONS', origins: '*' })) return;
+
+ if (req.method === 'GET' || req.method === 'HEAD') return handleSseHandshake(req, res);
+ if (req.method === 'DELETE') {
+ // Stateless per-request server — nothing to tear down (same contract as
+ // api/_mcp/auth.js handleTerminate).
+ res.statusCode = 204;
+ return res.end();
+ }
if (!method(req, res, ['POST'])) return;
const rl = await limits.mcpIp(clientIp(req));
@@ -842,100 +1011,84 @@ export default wrap(async (req, res) => {
let body;
try {
body = await readJson(req);
- } catch (e) {
+ } catch {
return json(res, 400, rpcEnvelope(null, null, { code: -32700, message: 'parse error' }));
}
- const { id = null, method: rpcMethod, params } = body || {};
-
- if (rpcMethod === 'initialize') {
+ const isBatch = Array.isArray(body);
+ const messages = isBatch ? body : [body];
+ if (isBatch && messages.length === 0) {
+ return json(res, 200, rpcEnvelope(null, null, { code: -32600, message: 'empty batch' }), {
+ 'mcp-protocol-version': PROTOCOL_VERSION,
+ });
+ }
+ if (messages.length > MAX_BATCH) {
return json(
res,
200,
- rpcEnvelope(id, {
- protocolVersion: '2025-06-18',
- capabilities: { tools: {} },
- serverInfo: { name: 'three.ws-pumpfun-mcp', version: '0.1.0' },
- }),
+ rpcEnvelope(null, null, { code: -32600, message: `batch too large (max ${MAX_BATCH})` }),
+ { 'mcp-protocol-version': PROTOCOL_VERSION },
);
}
- if (rpcMethod === 'tools/list') {
- return json(res, 200, rpcEnvelope(id, { tools: TOOLS }));
+ // Per-request dispatch context. Gate credentials resolve at most once.
+ let gateAuthPromise = null;
+ const ctx = {
+ res,
+ batch: isBatch,
+ x402Ctx: null,
+ gatedSuccess: false,
+ gatedId: null,
+ gateDenied: null,
+ ensureGateAuth() {
+ if (!gateAuthPromise) gateAuthPromise = resolveGatedAuth(req);
+ return gateAuthPromise;
+ },
+ };
+
+ const responses = [];
+ for (const msg of messages) {
+ const envelope = await dispatchRpc(msg, ctx);
+ // Single-request gate denial keeps the legacy 401/402 HTTP semantics.
+ if (ctx.gateDenied) return writeGatedAuthFailure(res, ctx.gateDenied.id, ctx.gateDenied.failure);
+ if (envelope !== null) responses.push(envelope);
}
- if (rpcMethod === 'tools/call') {
- const name = params?.name;
- const args = params?.arguments || {};
- // Own-property lookup only so "__proto__"/"constructor" can't resolve an
- // inherited member and pass the !handler guard.
- const handler =
- typeof name === 'string' && Object.hasOwn(HANDLERS, name) ? HANDLERS[name] : null;
- if (!handler) {
- return json(
- res,
- 200,
- rpcEnvelope(id, null, { code: -32601, message: `unknown tool: ${name}` }),
- );
- }
- // Auth gate: expensive (vanity grind, long-lived RPC watch) and sensitive
- // (returns a secret key) tools require a bearer or verified x402 payment.
- // authorizeGatedTool writes the 401/402 envelope and returns null on deny.
- let x402Ctx = null;
- if (AUTH_REQUIRED_TOOLS.has(name)) {
- const authz = await authorizeGatedTool(req, res, id);
- if (!authz) return;
- x402Ctx = authz.x402Ctx;
- }
+ // Settle the verified x402 payment AFTER gated work succeeded — atomic from
+ // the payer's perspective (verify → work → settle, mirroring /api/mcp): a
+ // failed tool never broadcasts the payment, and a successful one is always
+ // captured so the gated work can't be delivered free or the same signed
+ // payload replayed. One settlement covers the whole request.
+ if (ctx.x402Ctx && ctx.gatedSuccess) {
try {
- const data = await handler(args);
- // Settle the verified x402 payment AFTER the tool succeeded — atomic
- // from the payer's perspective (verify → work → settle, mirroring
- // /api/mcp): a failed tool never broadcasts the payment, and a
- // successful one is always captured so the gated work can't be
- // delivered free or the same signed payload replayed.
- if (x402Ctx) {
- try {
- const settled = await settlePayment({ verified: x402Ctx.verified });
- res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));
- } catch (settleErr) {
- return json(
- res,
- 402,
- rpcEnvelope(id, null, {
- code: -32402,
- message: `payment settlement failed: ${settleErr?.message || 'settle error'}`,
- data: build402Body({
- resourceUrl: x402Ctx.resourceUrl,
- accepts: x402Ctx.requirements,
- error: settleErr?.message || 'settle error',
- }),
- }),
- );
- }
- }
- // Mirror MCP content shape so existing skill clients can unwrap text.
+ const settled = await settlePayment({ verified: ctx.x402Ctx.verified });
+ res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));
+ } catch (settleErr) {
return json(
res,
- 200,
- rpcEnvelope(id, {
- content: [{ type: 'text', text: JSON.stringify(data) }],
- structuredContent: data,
+ 402,
+ rpcEnvelope(ctx.gatedId, null, {
+ code: -32402,
+ message: `payment settlement failed: ${settleErr?.message || 'settle error'}`,
+ data: build402Body({
+ resourceUrl: ctx.x402Ctx.resourceUrl,
+ accepts: ctx.x402Ctx.requirements,
+ error: settleErr?.message || 'settle error',
+ }),
}),
- );
- } catch (err) {
- const code = err.rpcCode || -32603;
- return json(
- res,
- 200,
- rpcEnvelope(id, null, { code, message: err.message || 'tool error' }),
+ { 'mcp-protocol-version': PROTOCOL_VERSION },
);
}
}
- return json(
- res,
- 200,
- rpcEnvelope(id, null, { code: -32601, message: `unknown method: ${rpcMethod}` }),
- );
+ // All-notification requests owe no body — 202 Accepted per Streamable HTTP.
+ if (responses.length === 0) {
+ res.statusCode = 202;
+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);
+ return res.end();
+ }
+
+ return json(res, 200, isBatch ? responses : responses[0], {
+ 'mcp-protocol-version': PROTOCOL_VERSION,
+ });
});
diff --git a/api/wk.js b/api/wk.js
index 98a23d73f..c324605d1 100644
--- a/api/wk.js
+++ b/api/wk.js
@@ -15,9 +15,15 @@ import {
NETWORK_BASE_MAINNET,
NETWORK_SOLANA_MAINNET,
} from './_lib/x402-spec.js';
-import { declareMcpDiscovery, withService } from './_lib/x402/bazaar-helpers.js';
+import {
+ declareHttpDiscovery,
+ declareMcpDiscovery,
+ withService,
+} from './_lib/x402/bazaar-helpers.js';
import { TOOL_CATALOG } from './_mcp/catalog.js';
import { STUDIO_CHALLENGE } from './_mcp3d/discovery.js';
+import { TOOL_CATALOG as STUDIO_TOOL_CATALOG } from './_mcp3d/catalog.js';
+import { priceFor as studioPriceFor } from './_mcp3d/pricing.js';
import { priceFor } from './_lib/pump-pricing.js';
import { priceAtomicsForTier } from './_lib/forge-tiers.js';
import { listBazaarServices, serviceResourceUrl } from './_lib/agent-paid-services.js';
@@ -244,8 +250,23 @@ function pushAcceptWithPermit2Sibling(out, accept) {
// EIP-2612 covers tokens that implement `permit()` (USDC, DAI, ...); the
// ERC-20 approval variant covers tokens that don't. Both let the facilitator
// sponsor the approve() so the payer never broadcasts the approval tx.
+// Normalize the second arg into a spec-shaped v2 bazaar extension
+// ({discoverable, info, schema}). Catalog entries historically passed a raw
+// {method, discoverable, input, inputSchema} descriptor straight through,
+// which facilitator validators reject as a malformed discovery extension —
+// every REST row was silently uncatalogable while the MCP rows (already
+// spec-shaped) validated fine. Already-proper extensions (bazaarExtension(),
+// declareMcpDiscovery(), STUDIO_CHALLENGE.bazaar) pass through untouched.
function extensionsForAccepts(accepts, bazaar) {
- const exts = { bazaar };
+ const normalized =
+ bazaar && bazaar.info && bazaar.schema
+ ? bazaar
+ : declareHttpDiscovery({
+ method: bazaar?.method || 'GET',
+ input: bazaar?.input,
+ inputSchema: bazaar?.inputSchema,
+ });
+ const exts = { bazaar: normalized };
if (accepts.some((a) => a?.extra?.assetTransferMethod === 'permit2')) {
Object.assign(
exts,
@@ -303,25 +324,28 @@ function acceptsForPrice(amountAtomics, resourceUrl) {
// catalog entry for a free tool and confuse buyers about what's actually
// gated). Falls back to the canonical `mcp://tool/<name>` identifier when
// the spec wants a logical resource that distinguishes tools at the URL
-// level, while the actual call still goes to `/api/mcp`.
-function buildMcpToolItems({ mcpUrl, mcpAccepts, mcpService }) {
+// level, while the actual call still goes to the server's own path.
+// Generic over the server: pass the endpoint path/url, its accepts, its
+// service metadata, its tool catalog, and its per-tool pricing lookup —
+// /api/mcp and /api/mcp-3d both feed through here.
+function buildMcpToolItems({ path, mcpUrl, mcpAccepts, mcpService, catalog, priceForTool }) {
const items = [];
- for (const tool of TOOL_CATALOG) {
- const pricing = priceFor(tool.name);
+ for (const tool of catalog) {
+ const pricing = priceForTool(tool.name);
if (!pricing) continue;
const exampleArgs = exampleArgsForTool(tool);
const discovery = declareMcpDiscovery({
toolName: tool.name,
description: tool.description,
// MCP 2025-06-18 transport: Streamable HTTP is the default for
- // /api/mcp; SSE clients still work through the same path.
+ // these servers; SSE clients still work through the same path.
transport: 'streamable-http',
inputSchema: tool.inputSchema,
example: exampleArgs,
});
items.push({
type: 'mcp',
- path: '/api/mcp',
+ path,
url: mcpUrl,
toolName: tool.name,
method: 'POST',
@@ -651,7 +675,31 @@ async function handleX402Discovery(req, res) {
// individually instead of all hiding behind the parent /api/mcp resource.
// Built from the live TOOL_CATALOG so adding a new priced tool only
// requires a pricing entry; the discovery shape follows automatically.
- const mcpToolItems = buildMcpToolItems({ mcpUrl, mcpAccepts, mcpService: routeMeta.mcp });
+ const mcpToolItems = buildMcpToolItems({
+ path: '/api/mcp',
+ mcpUrl,
+ mcpAccepts,
+ mcpService: routeMeta.mcp,
+ catalog: TOOL_CATALOG,
+ priceForTool: priceFor,
+ });
+
+ // 3D Studio paid tools — one row per priced tool so "text to 3d" searches
+ // on facilitators land on the tool, not just the transport. Service
+ // identity comes from STUDIO_CHALLENGE (same source as the live 402).
+ const studioService = {
+ serviceName: STUDIO_CHALLENGE.serviceName,
+ tags: STUDIO_CHALLENGE.tags,
+ iconUrl: STUDIO_CHALLENGE.iconUrl,
+ };
+ const studioToolItems = buildMcpToolItems({
+ path: '/api/mcp-3d',
+ mcpUrl: mcp3dUrl,
+ mcpAccepts: mcp3dAccepts,
+ mcpService: studioService,
+ catalog: STUDIO_TOOL_CATALOG,
+ priceForTool: studioPriceFor,
+ });
// Agent-published paid services — dynamic, one entry per active listing.
const agentServiceItems = await buildAgentServiceItems(origin);
@@ -1502,9 +1550,11 @@ async function handleX402Discovery(req, res) {
};
})(),
// USE-13: one Bazaar catalog row per priced MCP tool. The shared
- // `/api/mcp` resource above is the transport entry; these are
- // the individual paid tools facilitators index by toolName.
+ // `/api/mcp` and `/api/mcp-3d` resources above are the transport
+ // entries; these are the individual paid tools facilitators
+ // index by toolName.
...mcpToolItems,
+ ...studioToolItems,
// Agent-published paid endpoints (monetize_endpoint). Dynamic —
// one entry per active agent_paid_services listing.
...agentServiceItems,
diff --git a/chat/src/App.svelte b/chat/src/App.svelte
index 0999cb796..c1c4103b5 100644
--- a/chat/src/App.svelte
+++ b/chat/src/App.svelte
@@ -1603,6 +1603,26 @@
console.warn('[x402-pay] bootstrap failed:', err);
}
+ // Same one-time bootstrap for the Text → 3D Forge pack, so "make me a
+ // 3D model of…" works on a fresh chat without a trip through Tool Packs.
+ // Honors removal via the bootstrap flag, exactly like the x402 pack.
+ try {
+ if (!localStorage.getItem('forgePackBootstrapped')) {
+ const forgePack = curatedToolPacks.find((p) => p.id === 'forge-text-to-3d');
+ if (forgePack && !$toolSchema.some((g) => g.name === forgePack.name)) {
+ $toolSchema = [...$toolSchema, { name: forgePack.name, schema: forgePack.schema }];
+ }
+ if (forgePack && convo && (convo.messages?.length ?? 0) === 0) {
+ const names = forgePack.schema.map((t) => t.function?.name).filter(Boolean);
+ convo.tools = Array.from(new Set([...(convo.tools || []), ...names]));
+ saveConversation(convo);
+ }
+ localStorage.setItem('forgePackBootstrapped', '1');
+ }
+ } catch (err) {
+ console.warn('[forge-text-to-3d] bootstrap failed:', err);
+ }
+
// When the user installs a Local skill from the Skills modal, auto-enable
// the new tools in the current conversation so the LLM can call them on
// the next turn — same UX as the x402-pay bootstrap above, but
diff --git a/chat/src/convo.js b/chat/src/convo.js
index de4e35105..cbc0ac691 100644
--- a/chat/src/convo.js
+++ b/chat/src/convo.js
@@ -70,8 +70,8 @@ export async function complete(convo, onupdate, onabort) {
messages = limitMessagesContext(messages, param.messagesContextLimit);
}
- // TODO: Actually it works with Anthropic also. How to show it as disabled for unsupported?
- // Filter out unclosed messages from being submitted if using external models
+ // Drop a trailing unclosed, empty assistant message so we never submit a
+ // dangling turn — applies across every provider, Anthropic included.
if (
convo.messages[convo.messages.length - 1].unclosed &&
convo.messages[convo.messages.length - 1].content === ''
diff --git a/chat/src/three-ui/SuggestionChips.svelte b/chat/src/three-ui/SuggestionChips.svelte
index a5020821e..9b0b96b26 100644
--- a/chat/src/three-ui/SuggestionChips.svelte
+++ b/chat/src/three-ui/SuggestionChips.svelte
@@ -1,12 +1,13 @@
<script>
import { mode } from '../stores.js';
import Icon from '../Icon.svelte';
- import { feTrendingUp, feBarChart2, feActivity, feAlertCircle, feMoreHorizontal, feBox, feLayers } from '../feather.js';
+ import { feTrendingUp, feBarChart2, feActivity, feAlertCircle, feMoreHorizontal, feBox, feLayers, feZap } from '../feather.js';
import MoreDropdown from './MoreDropdown.svelte';
let moreOpen = false;
const chips = [
+ { id: 'text3d', label: 'Text → 3D', icon: feZap },
{ id: 'gems', label: 'Find new gems', icon: feTrendingUp },
{ id: 'track', label: 'Track a token', icon: feActivity },
{ id: 'portfolio', label: 'Check my portfolio', icon: feBarChart2 },
diff --git a/chat/src/three-ui/flows/UtilityFlows.svelte b/chat/src/three-ui/flows/UtilityFlows.svelte
index 458e11361..633c88c68 100644
--- a/chat/src/three-ui/flows/UtilityFlows.svelte
+++ b/chat/src/three-ui/flows/UtilityFlows.svelte
@@ -20,6 +20,7 @@
walletviewPrompts,
txexplainPrompts,
mintnftPrompts,
+ text3dPrompts,
} from './utilityFlowData.js';
</script>
@@ -49,6 +50,8 @@
<SamplePromptGrid title="Portfolio examples" prompts={portfolioPrompts} />
{:else if $mode === 'rugcheck'}
<SamplePromptGrid title="Rug check examples" prompts={rugcheckPrompts} />
+{:else if $mode === 'text3d'}
+ <SamplePromptGrid title="Generate a 3D model from text" prompts={text3dPrompts} />
{:else if $mode === 'chart3d'}
<SamplePromptGrid title="3D chart examples" prompts={chart3dPrompts} />
{:else if $mode === 'scene3d'}
diff --git a/chat/src/three-ui/flows/utilityFlowData.js b/chat/src/three-ui/flows/utilityFlowData.js
index 2614d24d1..a61255621 100644
--- a/chat/src/three-ui/flows/utilityFlowData.js
+++ b/chat/src/three-ui/flows/utilityFlowData.js
@@ -171,6 +171,15 @@ export const scene3dPrompts = [
'Mint the current 3D scene as a Solana NFT',
];
+export const text3dPrompts = [
+ 'Generate a 3D model of a brass steampunk owl, full body',
+ 'Make me a 3D model of a low-poly fox with orange and white fur',
+ 'Forge a weathered bronze dragon statue I can spin around',
+ 'Create a 3D ceramic coffee mug with a glossy teal glaze',
+ 'Generate a sci-fi helmet with matte black finish and gold visor',
+ 'Make a 3D treasure chest with iron bands and carved oak wood',
+];
+
export const ticker3dPrompts = [
'Show a live 3D rotating coin ticker for SOL',
'Display a 3D ticker for Bitcoin with current price',
diff --git a/chat/src/tools.js b/chat/src/tools.js
index 718c47c3c..d05522805 100644
--- a/chat/src/tools.js
+++ b/chat/src/tools.js
@@ -1122,6 +1122,92 @@ return { mint, signature, metadataUri, explorer: 'https://solscan.io/tx/' + sign
},
],
},
+ {
+ id: 'forge-text-to-3d',
+ name: 'Text → 3D Forge',
+ description:
+ 'Generate a real, textured 3D model from a text prompt with the three.ws Forge and render it in an orbit viewer — same engine as three.ws/forge, free, no key required.',
+ schema: [
+ {
+ clientDefinition: {
+ id: 'pack-forge-text-to-3d-001',
+ name: 'ForgeTextTo3D',
+ description: 'Generate a 3D model (GLB) from a text prompt and render it in an orbit viewer.',
+ arguments: [
+ { name: 'prompt', type: 'string', description: 'Single-subject object description, e.g. "a brass steampunk owl, full body". 3–1000 chars.' },
+ ],
+ body: `const prompt = String(args.prompt || '').trim();
+ if (prompt.length < 3) throw new Error('prompt required (3–1000 chars)');
+ const submit = await fetch('/api/forge', { method: 'POST', headers: {'content-type':'application/json'}, credentials: 'include', body: JSON.stringify({ prompt }) });
+ if (!submit.ok) throw new Error('Forge submit failed: ' + submit.status + ' ' + await submit.text());
+ const job = await submit.json();
+ if (!job.job_id) throw new Error('Forge returned no job id');
+ let state = null;
+ for (let i = 0; i < 75; i++) {
+ await new Promise((r) => setTimeout(r, 2500));
+ const poll = await fetch('/api/forge?job=' + encodeURIComponent(job.job_id), { credentials: 'include' });
+ if (!poll.ok) throw new Error('Forge poll failed: ' + poll.status);
+ state = await poll.json();
+ if (state.status === 'done' || state.status === 'failed') break;
+ }
+ if (!state || state.status === 'failed') throw new Error('Generation failed: ' + ((state && state.error) || 'unknown error'));
+ if (state.status !== 'done') throw new Error('Generation timed out after ~3 minutes — try again or open three.ws/forge');
+ const glb = state.glb_url;
+ if (!glb) throw new Error('Job finished without a model URL');
+ const html = \`<!DOCTYPE html><html><head><meta charset="utf-8"><style>
+ html,body{margin:0;height:100%;background:#0b0d10;color:#e5e7eb;font-family:ui-sans-serif,system-ui,sans-serif;overflow:hidden}
+ #hud{position:absolute;left:12px;top:10px;font-size:13px;background:rgba(0,0,0,.4);padding:6px 10px;border-radius:8px;max-width:70%}
+ #bar{position:absolute;left:12px;bottom:10px;display:flex;gap:8px;font-size:12px}
+ #bar a{color:#e5e7eb;background:rgba(0,0,0,.4);padding:6px 10px;border-radius:8px;text-decoration:none;border:1px solid rgba(255,255,255,.15)}
+ #bar a:hover{background:rgba(255,255,255,.12)}
+ </style></head><body>
+ <div id="hud">\${prompt.replace(/</g,'&lt;')}</div>
+ <div id="bar">
+ <a href="\${glb}" download="forge-model.glb">Download GLB</a>
+ <a href="https://three.ws/forge?prompt=\${encodeURIComponent(prompt)}" target="_blank" rel="noopener">Open in Forge ↗</a>
+ </div>
+ <script type="module">
+ import * as THREE from 'https://esm.sh/[email protected]';
+ import { OrbitControls } from 'https://esm.sh/[email protected]/examples/jsm/controls/OrbitControls.js';
+ import { GLTFLoader } from 'https://esm.sh/[email protected]/examples/jsm/loaders/GLTFLoader.js';
+ const renderer = new THREE.WebGLRenderer({ antialias: true });
+ renderer.setPixelRatio(devicePixelRatio); renderer.setSize(innerWidth, innerHeight); renderer.setClearColor(0x0b0d10);
+ document.body.appendChild(renderer.domElement);
+ const scene = new THREE.Scene();
+ const cam = new THREE.PerspectiveCamera(45, innerWidth/innerHeight, 0.01, 1000); cam.position.set(0, 1.2, 3);
+ const ctl = new OrbitControls(cam, renderer.domElement); ctl.enableDamping = true; ctl.autoRotate = true; ctl.autoRotateSpeed = 1.6;
+ addEventListener('resize', () => { renderer.setSize(innerWidth, innerHeight); cam.aspect = innerWidth/innerHeight; cam.updateProjectionMatrix(); });
+ addEventListener('pointerdown', () => { ctl.autoRotate = false; }, { once: true });
+ scene.add(new THREE.AmbientLight(0xffffff, 0.7));
+ const k = new THREE.DirectionalLight(0xffffff, 1.1); k.position.set(3, 4, 5); scene.add(k);
+ const gltf = await new GLTFLoader().loadAsync(\${JSON.stringify(glb)});
+ const m = gltf.scene;
+ const box = new THREE.Box3().setFromObject(m);
+ const size = box.getSize(new THREE.Vector3()).length();
+ const center = box.getCenter(new THREE.Vector3());
+ m.position.sub(center); cam.position.set(0, size * 0.25, size * 1.4); ctl.target.set(0,0,0);
+ scene.add(m);
+ function tick(){ ctl.update(); renderer.render(scene, cam); requestAnimationFrame(tick); }
+ tick();
+ </script></body></html>\`;
+ return { contentType: 'text/html', content: html };`,
+ },
+ type: 'function',
+ function: {
+ name: 'ForgeTextTo3D',
+ description:
+ 'Generate a real 3D model (textured GLB) from a text prompt using the three.ws Forge, then render it in an interactive orbit viewer. Use whenever the user asks to make, create, generate, or forge a 3D model/object/mesh from a description. Takes ~30–90 s. The prompt should describe ONE subject with material and style details.',
+ parameters: {
+ type: 'object',
+ properties: {
+ prompt: { type: 'string', description: 'Single-subject object description, e.g. "a brass steampunk owl, full body". 3–1000 characters.' },
+ },
+ required: ['prompt'],
+ },
+ },
+ },
+ ],
+ },
{
id: 'wallet-balances',
name: 'Wallet Balances',
diff --git a/data/changelog.json b/data/changelog.json
index c26e9e52d..0e1b46901 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,34 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-13",
+ "title": "Tutorials read better: one-tap copy on every code block, live progress, and a jump-to-the-tool button",
+ "summary": "The tutorial reader (/tutorials) got a polish pass that applies to every guide. Code blocks now have a one-click Copy button, so you can lift a snippet without selecting it by hand. A slim progress rail across the top tracks how far you've read, and a back-to-top button appears once you scroll in. Each section heading has a hover link for sharing a deep link to that exact spot, and every tutorial now opens with a clear call-to-action button — the new text-to-3D guides drop you straight into the Forge. New this release: four beginner guides for turning a text prompt or photos into a downloadable 3D model, a copy-paste prompt cookbook, and an API walkthrough.",
+ "tags": [
+ "docs",
+ "improvement"
+ ],
+ "link": "/tutorials"
+ },
+ {
+ "date": "2026-06-13",
+ "title": "Refine any Forge model to higher quality in one click — plus sharper multi-view guidance",
+ "summary": "Three upgrades to the Forge (/forge). After a model generates, a new Refine button re-runs that exact prompt or photos one quality tier higher — Draft to Standard to High — so you can preview cheaply, then commit to the best version without retyping anything. When building from photos, a live counter now shows how many of the four reference views you've added and reminds you that more angles make a sharper mesh. And the action bar under each finished model now reflows cleanly on phones, with Refine and Make-another leading at full width. Sketch mode also makes its required description unmistakable.",
+ "tags": [
+ "improvement"
+ ],
+ "link": "/forge"
+ },
+ {
+ "date": "2026-06-13",
+ "title": "See any Forge model in AR — scan from your desktop, place it in your room",
+ "summary": "Every finished model now has a View in AR button. On a phone it drops the model into your space through the camera; on a desktop it shows a QR code you scan with your phone to open the same model, one tap from AR — so you can walk around what you just made at real-world scale. The embed viewer gained a big one-tap AR launcher on phones too, so models embedded on other sites are placeable in AR as well. No app, no download — it runs in the browser.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/forge"
+ },
{
"date": "2026-06-13",
"title": "Describe it to 3D joins the rest of the site — and the two generators now point at each other",
diff --git a/data/pages.json b/data/pages.json
index 88dc47795..6f8c2af07 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -960,14 +960,6 @@
"changefreq": "weekly",
"lastmod": "2026-05-17"
},
- {
- "path": "/blog/text-to-3d-forge-launch",
- "title": "Text to 3D Is Live: Forge Turns a Prompt Into a Textured 3D Model",
- "description": "Forge is live on three.ws. Type a description — or upload a photo or sketch — and get a textured, downloadable GLB in 30–90 seconds. Free draft lane, AR inspection, shareable links, and one-click attach to your AI agent.",
- "priority": 0.6,
- "changefreq": "monthly",
- "lastmod": "2026-06-12"
- },
{
"path": "/blog/text-to-3d-is-live",
"title": "Text to 3D Is Live — Type a Prompt, Download a 3D Model",
diff --git a/docs/internal/VALIDATION_DEPLOY.md b/docs/internal/VALIDATION_DEPLOY.md
index da6917ce5..08ffd40ff 100644
--- a/docs/internal/VALIDATION_DEPLOY.md
+++ b/docs/internal/VALIDATION_DEPLOY.md
@@ -467,6 +467,6 @@ Update `REGISTRY_DEPLOYMENTS` object—it should already have entries for all 15
- [contracts/CLAUDE.md](../contracts/CLAUDE.md) — Foundry setup & conventions
- [contracts/src/ValidationRegistry.sol](../contracts/src/ValidationRegistry.sol) — Contract source
- [src/erc8004/abi.js](../src/erc8004/abi.js) — Frontend registry deployments
-- [docs/ARCHITECTURE.md](./ARCHITECTURE.md) — System overview
+- [docs/architecture.md](../architecture.md) — System overview
- [Foundry Book](https://book.getfoundry.sh/) — Forge docs
- [CREATE2 deep dive](https://ethereum.org/en/developers/docs/accounts/#contract-accounts) — How deterministic addresses work
diff --git a/docs/mcp-3d-studio.md b/docs/mcp-3d-studio.md
index 40defa997..2e79e4411 100644
--- a/docs/mcp-3d-studio.md
+++ b/docs/mcp-3d-studio.md
@@ -98,6 +98,32 @@ result and the **image path still works keyless**. The job handle for a geometry
job is an opaque forge token; `generation_status` decodes it and re-resolves the
key per poll.
+## Access & pricing
+
+Discovery is free for everyone: `initialize`, `tools/list`, `ping`, and the
+`getting_started` tool answer with no credentials, so any agent or crawler can
+read the catalog before deciding to pay.
+
+For tool calls there are two lanes:
+
+- **OAuth (three.ws account)** — operator-funded. Sign in once and every studio
+ tool runs at no per-call charge, bounded by rate limits.
+- **x402 (pay per call, no account)** — send a USDC payment (Base or Solana
+ mainnet) with the request. The 402 challenge quotes the exact price of the
+ tools you're calling; batches are priced as the sum of their calls. Same
+ numbers as `POST /api/x402/forge`, single source: `api/_mcp3d/pricing.js`.
+
+| Tool | Price (USDC) |
+| ------------------------------------------ | ----------------------------------------- |
+| `text_to_3d` / `image_to_3d` | by tier — $0.05 draft / $0.15 standard / $0.50 high |
+| `auto_rig_model`, `retexture_model`, `retexture_region` | $0.05 |
+| `stylize_model`, `remesh_model`, `segment_model` | $0.02 |
+| `remove_background`, `pose_model`, `apply_animation`, `direct_prompt`, `generate_material` | $0.01 |
+| `generation_status`, `preview_3d`, `list_animations`, `inspect_model`, `optimize_model`, `getting_started` | free |
+
+Payment settles only after the work succeeds — a wholesale failure costs
+nothing, and the same signed payment cannot be replayed.
+
## IBM Granite tools
`direct_prompt` and `generate_material` call IBM Granite foundation models via
diff --git a/docs/pay-skills-listing.md b/docs/pay-skills-listing.md
index 678871f38..f122160bb 100644
--- a/docs/pay-skills-listing.md
+++ b/docs/pay-skills-listing.md
@@ -54,7 +54,7 @@ const { model, suggestions } = await res.json();
// Get a token's 3D representation
const res2 = await fetchWithPayment(
- "https://three.ws/api/x402/mint-to-mesh?mint=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"
+ "https://three.ws/api/x402/mint-to-mesh?mint=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"
);
const { glb } = await res2.json(); // base64 GLB bytes
```
diff --git a/docs/roadmap/creation-consolidation.md b/docs/roadmap/creation-consolidation.md
index a3ea4cb30..6b24180cb 100644
--- a/docs/roadmap/creation-consolidation.md
+++ b/docs/roadmap/creation-consolidation.md
@@ -25,7 +25,7 @@ Every user-facing surface where something gets created. "Nav" reflects `public/n
| Surface | Path | File | What it does | Backend | Nav |
|---|---|---|---|---|---|
| Create avatar | `/create` | `pages/create.html` | Pick template avatar or upload GLB; feeds agent workflow | `/api/avatars/*` | Build ▸ |
-| Avatar Studio | `/avatar-studio` | `pages/avatar-studio.html` | Full character creator (M3-org CharacterStudio fork): sculpt, outfits, export GLB | internal Three.js | Build ▸ |
+| Avatar Studio | `/avatar-studio` | `pages/avatar-studio.html` | Full character creator (M3-org/CharacterStudio fork): sculpt, outfits, export GLB | internal Three.js | Build ▸ |
| Customize avatar | `/avatar-edit` | `pages/avatar-edit.html` | Edit existing avatar attributes/accessories | `/api/avatars/{id}` | — (orphaned) |
| Import avatar | `/import/rpm` | — | Import GLB/glTF from URL or file upload | `/api/avatars` | Build ▸ |
| Avatar Studio demo | `/avatar-studio-demo` | `pages/avatar-studio-demo.html` | Demo variant of Avatar Studio | internal | — (orphaned) |
diff --git a/docs/sdk.md b/docs/sdk.md
index 084d1044e..fe28daf76 100644
--- a/docs/sdk.md
+++ b/docs/sdk.md
@@ -385,7 +385,7 @@ Requires `npm run build:lib` to have completed first. Runs automatically as part
### Versioning
-The platform follows semantic versioning. The web component version tracks `package.json` (currently `1.5.1`). The AgentKit SDK is independently versioned in `sdk/package.json` (currently `0.1.0`). Breaking changes only ship in major releases. See `sdk/CHANGELOG.md` for the AgentKit release history.
+The platform follows semantic versioning. The web component version tracks `package.json` (currently `1.5.1`). The AgentKit SDK is independently versioned in `sdk/package.json` (currently `0.2.0`). Breaking changes only ship in major releases. See `sdk/CHANGELOG.md` for the AgentKit release history.
---
diff --git a/mcp-bridge/LICENSE b/mcp-bridge/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/mcp-bridge/LICENSE
@@ -0,0 +1,180 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship made available under
+ the License, as indicated by a copyright notice that is included in
+ or attached to the work (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other transformations
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
+ in the Work by the copyright owner or by an individual or Legal Entity
+ authorized to submit on behalf of the copyright owner. For the purposes
+ of this definition, "submitted" means any form of electronic, verbal,
+ or written communication sent to the Licensor or its representatives,
+ including but not limited to communication on electronic mailing lists,
+ source code control systems, and issue tracking systems that are managed
+ by, or on behalf of, the Licensor for the purpose of discussing and
+ improving the Work, but excluding communication that is conspicuously
+ marked or designated in writing by the copyright owner as "Not a
+ Contribution."
+
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
+ whom a Contribution has been received by the Licensor and included
+ within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by the combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a cross-claim
+ or counterclaim in a lawsuit) alleging that the Work or any
+ Contribution embodied within the Work constitutes direct or contributory
+ patent infringement, then any patent licenses granted to You under
+ this License for that Work shall terminate as of the date such
+ litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or Derivative
+ Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, You must include a readable copy of the
+ attribution notices contained within such NOTICE file, in
+ at least one of the following places: within a NOTICE text
+ file distributed as part of the Derivative Works; within
+ the Source form or documentation, if provided along with the
+ Derivative Works; or, within a display generated by the
+ Derivative Works, if and wherever such third-party notices
+ normally appear. The contents of the NOTICE file are for
+ informational purposes only and do not modify the License.
+ You may add Your own attribution notices within Derivative
+ Works that You distribute, alongside or in addition to the
+ NOTICE text from the Work, provided that such additional
+ attribution notices cannot be construed as modifying the License.
+
+ You may add Your own license statement for Your modifications and
+ may provide additional grant of rights to use, copy, modify, merge,
+ publish, distribute, sublicense, and/or sell copies of the
+ Derivative Works, and to permit persons to whom the Derivative Works
+ are furnished to do so.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or reproducing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or exemplary damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or all other
+ commercial damages or losses), even if such Contributor has been
+ advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may offer only
+ conditions consistent with this License.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/mcp-bridge/package.json b/mcp-bridge/package.json
index 093fdb8fc..797e21fbd 100644
--- a/mcp-bridge/package.json
+++ b/mcp-bridge/package.json
@@ -1,15 +1,51 @@
{
"name": "@3d-agent/mcp-bridge",
"version": "1.0.0",
- "private": true,
+ "mcpName": "io.github.nirholas/x402-bridge",
"description": "MCP stdio bridge that turns any x402-paid HTTP endpoint into a Claude-callable tool. Auto-pays via the @x402 client (EVM exact, SVM exact, EVM batch-settlement) and pre-loads tools from the Coinbase x402 Bazaar.",
"type": "module",
+ "author": "nirholas <[email protected]>",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/nirholas/three.ws.git",
+ "directory": "mcp-bridge"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "keywords": [
+ "mcp",
+ "model-context-protocol",
+ "x402",
+ "payments",
+ "usdc",
+ "solana",
+ "evm",
+ "base",
+ "bazaar",
+ "micropayments",
+ "ai-agent"
+ ],
+ "publishConfig": {
+ "access": "public"
+ },
+ "files": [
+ "src",
+ "server.json",
+ "README.md",
+ "LICENSE"
+ ],
"bin": {
"x402-mcp-bridge": "./src/index.js"
},
"main": "./src/index.js",
"scripts": {
- "start": "node src/index.js"
+ "start": "node src/index.js",
+ "test": "node --test tests/",
+ "test:smoke": "node tests/smoke.mjs",
+ "inspect": "npx -y @modelcontextprotocol/inspector node src/index.js"
},
"engines": {
"node": ">=20"
diff --git a/mcp-bridge/server.json b/mcp-bridge/server.json
new file mode 100644
index 000000000..a6aadc277
--- /dev/null
+++ b/mcp-bridge/server.json
@@ -0,0 +1,120 @@
+{
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
+ "name": "io.github.nirholas/x402-bridge",
+ "title": "x402 Universal Payer",
+ "description": "Pay any x402 endpoint on the open web: auto-paying bridge with Bazaar discovery and spend caps.",
+ "websiteUrl": "https://three.ws",
+ "icons": [
+ {
+ "src": "https://three.ws/three-ws-mcp-icon.svg",
+ "mimeType": "image/svg+xml",
+ "sizes": ["any"]
+ }
+ ],
+ "repository": {
+ "url": "https://github.com/nirholas/three.ws",
+ "source": "github",
+ "subfolder": "mcp-bridge"
+ },
+ "version": "1.0.0",
+ "packages": [
+ {
+ "registryType": "npm",
+ "identifier": "@3d-agent/mcp-bridge",
+ "version": "1.0.0",
+ "transport": {
+ "type": "stdio"
+ },
+ "environmentVariables": [
+ {
+ "name": "MCP_BRIDGE_EVM_PRIVATE_KEY",
+ "description": "0x-prefixed 32-byte hex private key that funds USDC payments on EVM chains (Base, Arbitrum, …). At least one of the EVM/SVM keys is required. Treat like cash — use a dedicated low-balance wallet.",
+ "format": "string",
+ "isRequired": false,
+ "isSecret": true
+ },
+ {
+ "name": "MCP_BRIDGE_SVM_PRIVATE_KEY",
+ "description": "Solana secret key that funds USDC payments: base58 64-byte secret key (Phantom / solana-keygen format) or a JSON array of 64 integers. At least one of the EVM/SVM keys is required. Treat like cash.",
+ "format": "string",
+ "isRequired": false,
+ "isSecret": true
+ },
+ {
+ "name": "MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC",
+ "description": "Per-call spending cap in atomic units (USDC has 6 decimals). Payments above this abort with a clear reason.",
+ "format": "number",
+ "isRequired": false,
+ "default": "100000"
+ },
+ {
+ "name": "MCP_BRIDGE_MAX_TOTAL_ATOMIC",
+ "description": "Cumulative session spending ceiling in atomic units. Once total spend would exceed it, further payments abort until restart.",
+ "format": "number",
+ "isRequired": false,
+ "default": "1000000"
+ },
+ {
+ "name": "MCP_BRIDGE_ALLOWED_PAYTO",
+ "description": "Comma-separated payee allowlist. When set, any payment whose payTo address is not listed is refused.",
+ "format": "string",
+ "isRequired": false
+ },
+ {
+ "name": "MCP_BRIDGE_ALLOWED_HOSTS",
+ "description": "Comma-separated hostname allowlist for outbound paid requests. When set, any other host is refused before a request is signed.",
+ "format": "string",
+ "isRequired": false
+ },
+ {
+ "name": "MCP_BRIDGE_ALLOW_HTTP",
+ "description": "Set to 1 to allow http:// targets (local development only). https is enforced otherwise.",
+ "format": "boolean",
+ "isRequired": false,
+ "default": "0"
+ },
+ {
+ "name": "MCP_BRIDGE_DISCOVER_LIMIT",
+ "description": "Max number of x402 Bazaar resources to register as dynamic tools at startup. Set 0 to disable discovery.",
+ "format": "number",
+ "isRequired": false,
+ "default": "20"
+ },
+ {
+ "name": "MCP_BRIDGE_BAZAAR_URL",
+ "description": "x402 Bazaar discovery endpoint. Override to point at a self-hosted or alternative bazaar.",
+ "format": "string",
+ "isRequired": false,
+ "default": "https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources"
+ },
+ {
+ "name": "MCP_BRIDGE_BATCH_DEPOSIT_MULTIPLIER",
+ "description": "How many request-amounts to deposit at once when opening an EVM batch-settlement channel.",
+ "format": "number",
+ "isRequired": false,
+ "default": "5"
+ },
+ {
+ "name": "MCP_BRIDGE_MAX_DEPOSIT_ATOMIC",
+ "description": "Hard cap in atomic units on a single batch-settlement channel deposit or top-up.",
+ "format": "number",
+ "isRequired": false,
+ "default": "5000000"
+ },
+ {
+ "name": "X402_MCP_BRIDGE_CHANNELS_DIR",
+ "description": "Directory for persisted batch-settlement channel state (survives client restarts).",
+ "format": "string",
+ "isRequired": false,
+ "default": "~/.x402-mcp-bridge/channels"
+ },
+ {
+ "name": "RPC_URL_8453",
+ "description": "Per-chain RPC override, one variable per chain id (RPC_URL_<chainId>, e.g. RPC_URL_8453 for Base). Defaults to viem's public RPC for that chain.",
+ "format": "string",
+ "isRequired": false
+ }
+ ]
+ }
+ ]
+}
diff --git a/package.json b/package.json
index 43af603b5..1d0bde0a8 100644
--- a/package.json
+++ b/package.json
@@ -64,6 +64,7 @@
"build:pages": "node scripts/build-page-index.mjs",
"changelog:push": "node scripts/changelog-telegram.mjs",
"audit:deploy": "node scripts/audit-deploy-artifacts.mjs",
+ "audit:mcp": "node scripts/audit-mcp-manifests.mjs",
"audit:pages": "node scripts/audit-page-index.mjs",
"audit:handlers": "node scripts/audit-empty-handlers.mjs",
"audit:web": "node scripts/page-audit.mjs",
diff --git a/packages/avatar-agent-mcp/src/lib/output-shapes.js b/packages/avatar-agent-mcp/src/lib/output-shapes.js
new file mode 100644
index 000000000..9bfbdd93d
--- /dev/null
+++ b/packages/avatar-agent-mcp/src/lib/output-shapes.js
@@ -0,0 +1,117 @@
+// Shared Zod fragments for tool OUTPUT schemas.
+//
+// Conventions (mirrors how each tool's inputSchema is a raw Zod shape):
+// • Every tool's `outputSchema` is a raw shape — the SDK wraps it in an
+// object schema and VALIDATES structuredContent against it on every
+// non-error result (isError:true responses skip validation).
+// • Schemas are HONEST: required only for fields every code path sets;
+// soft-fail paths (`{ ok:false, error, ... }` returned without isError)
+// must parse too, so most success fields are optional.
+// • Upstream-shaped subobjects (pump.fun metadata, Khronos validator info,
+// Dexscreener pairs, Replicate output) use `.passthrough()` so new
+// upstream fields never break validation.
+
+import { z } from 'zod';
+
+/** `error` + `message` — present on soft-fail returns, absent on success. */
+export const softFailFields = {
+ error: z.string().optional().describe('Machine-readable error code when ok is false.'),
+ message: z.string().optional().describe('Human-readable explanation when ok is false.'),
+};
+
+/**
+ * Standard result shape: `ok` is the only field EVERY path sets; soft-fail
+ * fields and the given success fields are optional by construction.
+ * @param {import('zod').ZodRawShape} successShape — success fields (already optional unless truly always present)
+ * @returns {import('zod').ZodRawShape}
+ */
+export function resultShape(successShape = {}) {
+ return {
+ ok: z.boolean().describe('True when the operation succeeded (or, for on-chain bundles, confirmed).'),
+ ...softFailFields,
+ ...successShape,
+ };
+}
+
+/**
+ * An upstream-shaped subobject: known fields typed, unknown fields allowed.
+ * @param {import('zod').ZodRawShape} shape
+ */
+export function upstreamObject(shape = {}) {
+ return z.object(shape).passthrough();
+}
+
+/**
+ * A per-source aggregation slot (pump_snapshot pattern): the source either
+ * returned data, soft-failed with `{ error }`, or was skipped (`null`).
+ * @param {import('zod').ZodRawShape} shape — the source's success fields (mark optional)
+ */
+export function softSource(shape = {}) {
+ return upstreamObject({
+ ...shape,
+ error: z.string().optional().describe('Set when this source was unreachable; other sources may still have data.'),
+ }).nullable();
+}
+
+/** Solscan / Jito explorer URL. */
+export const explorerUrl = z.string().describe('Block-explorer URL (Solscan account/tx or Jito bundle).');
+
+/** Base58 transaction signature. */
+export const txSignature = z.string().describe('Base58 Solana transaction signature.');
+
+/** Avatar reference stored on a session ({ glb, source }). */
+export const avatarRef = upstreamObject({
+ glb: z.string().describe('GLB URL of the avatar.'),
+ source: z.string().describe('"three.ws" for CDN-hosted defaults, "external" otherwise.'),
+});
+
+/** Catalog accessory entry ({ id, slot, glb, name }). */
+export const accessoryEntry = upstreamObject({
+ id: z.string(),
+ slot: z.string(),
+ glb: z.string(),
+ name: z.string(),
+});
+
+/** Session id echo — null when the call ran without a session. */
+export const sessionEcho = z.string().nullable().describe('Avatar session id, or null when no session was involved.');
+
+/**
+ * Jito-bundle / signature-wait outcome fields shared by wallet_send,
+ * pump_buy, pump_launch, and pump_collect_fees results.
+ */
+export const bundleOutcomeFields = {
+ status: z
+ .union([z.string(), z.number()])
+ .optional()
+ .describe('"confirmed" | "pending" | "failed" on success paths; an upstream HTTP status on some soft fails.'),
+ note: z.string().optional().describe('Set when status is "pending" — the tx MAY still land; check the explorer before retrying.'),
+ statuses: z.array(z.string().nullable()).nullable().optional().describe('Per-signature confirmation statuses, null on timeout.'),
+ err: z.unknown().describe('On-chain error object, "timeout", or null.'),
+};
+
+/**
+ * Hosted PNG render outcome (three.ws /api/render/*) shared by
+ * thumbnail_glb and render_avatar. Both success and upstream-error
+ * envelopes set status/endpoint/durationMs; local invalid_input does not.
+ */
+export const pngRenderFields = {
+ status: z.number().optional().describe('Upstream HTTP status.'),
+ endpoint: z.string().optional().describe('three.ws render endpoint that produced the image.'),
+ durationMs: z.number().optional(),
+ sizeBytes: z.number().optional(),
+ mime: z.literal('image/png').optional(),
+ dataUrl: z
+ .string()
+ .nullable()
+ .optional()
+ .describe('base64 PNG data URL, or null when the image exceeded the inline cap.'),
+ omittedInline: z.boolean().optional(),
+ meta: upstreamObject({
+ width: z.number().nullable(),
+ height: z.number().nullable(),
+ background: z.string().nullable(),
+ pose: z.string().nullable(),
+ poseLabel: z.string().nullable(),
+ }).optional(),
+};
diff --git a/packages/avatar-agent-mcp/src/tools/inspect-glb.js b/packages/avatar-agent-mcp/src/tools/inspect-glb.js
index 7c920025d..ca8075244 100644
--- a/packages/avatar-agent-mcp/src/tools/inspect-glb.js
+++ b/packages/avatar-agent-mcp/src/tools/inspect-glb.js
@@ -8,6 +8,101 @@
import { z } from 'zod';
import { fetchGlbBytes, getIo } from '../lib/glb-io.js';
+import { resultShape, upstreamObject } from '../lib/output-shapes.js';
+
+const vec3 = z.array(z.number()).length(3);
+
+const outputSchema = resultShape({
+ url: z.string().optional().describe('The inspected GLB URL (echoed).'),
+ sizeBytes: z.number().optional(),
+ generator: z.string().nullable().optional(),
+ version: z.string().nullable().optional(),
+ counts: z
+ .object({
+ meshes: z.number(),
+ materials: z.number(),
+ textures: z.number(),
+ animations: z.number(),
+ skins: z.number(),
+ scenes: z.number(),
+ totalVertices: z.number(),
+ totalTriangles: z.number(),
+ })
+ .optional(),
+ boundingBox: z
+ .object({ min: vec3, max: vec3, center: vec3, size: vec3 })
+ .nullable()
+ .optional()
+ .describe('World-space bbox of the default scene; null when no positioned geometry exists.'),
+ meshes: z
+ .array(
+ upstreamObject({
+ name: z.string().nullable(),
+ primitiveCount: z.number(),
+ primitives: z.array(
+ upstreamObject({
+ mode: z.number(),
+ vertices: z.number(),
+ triangles: z.number(),
+ indexed: z.boolean(),
+ attributes: z.array(z.string()),
+ material: z.string().nullable(),
+ morphTargets: z.number(),
+ }),
+ ),
+ }),
+ )
+ .optional(),
+ materials: z
+ .array(
+ upstreamObject({
+ name: z.string().nullable(),
+ alphaMode: z.string(),
+ doubleSided: z.boolean(),
+ baseColorFactor: z.array(z.number()),
+ metallicFactor: z.number(),
+ roughnessFactor: z.number(),
+ hasBaseColorTexture: z.boolean(),
+ hasMetallicRoughnessTexture: z.boolean(),
+ hasNormalTexture: z.boolean(),
+ hasOcclusionTexture: z.boolean(),
+ hasEmissiveTexture: z.boolean(),
+ }),
+ )
+ .optional(),
+ textures: z
+ .array(
+ upstreamObject({
+ name: z.string().nullable(),
+ mimeType: z.string(),
+ sizeBytes: z.number().nullable(),
+ uri: z.string().nullable(),
+ }),
+ )
+ .optional(),
+ animations: z
+ .array(
+ upstreamObject({
+ name: z.string().nullable(),
+ channelCount: z.number(),
+ samplerCount: z.number(),
+ durationSeconds: z.number(),
+ }),
+ )
+ .optional(),
+ skins: z
+ .array(
+ upstreamObject({
+ name: z.string().nullable(),
+ jointCount: z.number(),
+ hasInverseBindMatrices: z.boolean(),
+ }),
+ )
+ .optional(),
+ scenes: z
+ .array(upstreamObject({ name: z.string().nullable(), rootNodeCount: z.number() }))
+ .optional(),
+});
function arrayLen(prim, semantic) {
const acc = prim.getAttribute(semantic);
@@ -99,6 +194,7 @@ export const def = {
inputSchema: {
url: z.string().describe('Public URL or data: URL of a .glb file.'),
},
+ outputSchema,
async handler(args) {
const { url } = args || {};
if (!url) return { ok: false, error: 'invalid_input', message: 'url is required' };
diff --git a/packages/avatar-agent-mcp/src/tools/validate-glb.js b/packages/avatar-agent-mcp/src/tools/validate-glb.js
index bd7852f07..9f2abd652 100644
--- a/packages/avatar-agent-mcp/src/tools/validate-glb.js
+++ b/packages/avatar-agent-mcp/src/tools/validate-glb.js
@@ -10,9 +10,43 @@ import { z } from 'zod';
import validator from 'gltf-validator';
import { fetchGlbBytes } from '../lib/glb-io.js';
+import { resultShape, upstreamObject } from '../lib/output-shapes.js';
const SEVERITIES = ['error', 'warning', 'info', 'hint'];
+const issueBucket = z.array(
+ upstreamObject({
+ code: z.string(),
+ message: z.string(),
+ pointer: z.string().nullable(),
+ offset: z.number().nullable(),
+ }),
+);
+
+const outputSchema = resultShape({
+ url: z.string().optional().describe('The validated GLB URL (echoed).'),
+ sizeBytes: z.number().optional(),
+ validatorVersion: z.string().nullable().optional(),
+ mimeType: z.string().nullable().optional(),
+ validated: z.string().optional().describe('ISO timestamp of the validation run.'),
+ summary: z
+ .object({
+ numErrors: z.number(),
+ numWarnings: z.number(),
+ numInfos: z.number(),
+ numHints: z.number(),
+ truncated: z.boolean(),
+ })
+ .optional(),
+ info: upstreamObject({})
+ .nullable()
+ .optional()
+ .describe("The Khronos validator's structural info report, passed through verbatim."),
+ issues: z
+ .object({ error: issueBucket, warning: issueBucket, info: issueBucket, hint: issueBucket })
+ .optional(),
+});
+
function classify(messages = []) {
const buckets = { error: [], warning: [], info: [], hint: [] };
for (const m of messages) {
diff --git a/packages/threews-avatar-mcp/README.md b/packages/threews-avatar-mcp/README.md
index 3f1656c3d..ad981ccbe 100644
--- a/packages/threews-avatar-mcp/README.md
+++ b/packages/threews-avatar-mcp/README.md
@@ -107,6 +107,14 @@ All three tools are free, read-only, and annotated (`readOnlyHint`, `idempotentH
{ "handle": "@nirholas" }
```
+Every tool also advertises an `outputSchema` describing its `structuredContent`, so typed clients can consume results without re-parsing the text blocks.
+
+## Prompts
+
+| Prompt | Arguments | What it does |
+| ----------------- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `showcase-avatar` | `avatar` — id (UUID) or @handle | One-step showcase: renders the live, rotatable avatar inline **and** produces the embed iframe, ending with a copy-paste summary (name, viewer URL, embed URL, `<iframe>` snippet). |
+
## How it works
Each selector maps to a real three.ws endpoint. Raw `model` URLs must be `https://` (or `http://localhost` for dev); other schemes are rejected.
diff --git a/packages/threews-avatar-mcp/src/index.js b/packages/threews-avatar-mcp/src/index.js
index 6156522a7..6195c45ae 100755
--- a/packages/threews-avatar-mcp/src/index.js
+++ b/packages/threews-avatar-mcp/src/index.js
@@ -22,9 +22,12 @@ import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ReadResourceRequestSchema,
+ ListPromptsRequestSchema,
+ GetPromptRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { buildTools } from './tools.js';
+import { buildPrompts } from './prompts.js';
import { baseUrl, ThreewsError } from './threews.js';
import { UI_RESOURCE_URI, UI_MIME_TYPE, UI_RESOURCE_META, loadAppHtml } from './ui.js';
@@ -36,16 +39,24 @@ const SERVER_NAME = 'three.ws-avatar-mcp';
async function main() {
const tools = buildTools();
const byName = new Map(tools.map((t) => [t.definition.name, t]));
+ const prompts = buildPrompts();
+ const promptsByName = new Map(prompts.map((p) => [p.definition.name, p]));
const server = new Server(
{ name: SERVER_NAME, version: SERVER_VERSION },
{
- capabilities: { tools: { listChanged: false }, resources: { listChanged: false } },
+ capabilities: {
+ tools: { listChanged: false },
+ resources: { listChanged: false },
+ prompts: { listChanged: false },
+ },
instructions:
'three.ws 3D avatar tools. render_avatar shows a live, rotatable avatar inline ' +
'(preview image + interactive model + embed URL); avatar_embed_code returns a ' +
'paste-anywhere iframe; get_avatar returns metadata. Identify avatars by id, ' +
- '@handle, or a raw GLB url. Free and read-only — no API key for public avatars.',
+ '@handle, or a raw GLB url. The showcase-avatar prompt does the full flow in one ' +
+ 'step: live inline render plus embed iframe with a copy-paste summary. ' +
+ 'Free and read-only — no API key for public avatars.',
},
);
@@ -84,6 +95,16 @@ async function main() {
};
});
+ server.setRequestHandler(ListPromptsRequestSchema, async () => ({
+ prompts: prompts.map((p) => p.definition),
+ }));
+
+ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
+ const prompt = promptsByName.get(request.params.name);
+ if (!prompt) throw new Error(`Unknown prompt: ${request.params.name}`);
+ return prompt.resolve(request.params.arguments || {});
+ });
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
const tool = byName.get(name);
@@ -104,7 +125,7 @@ async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
process.stderr.write(
- `[avatar-mcp] ${SERVER_NAME} v${SERVER_VERSION} ready — ${tools.length} tools via ${baseUrl()}\n`,
+ `[avatar-mcp] ${SERVER_NAME} v${SERVER_VERSION} ready — ${tools.length} tools, ${prompts.length} prompt via ${baseUrl()}\n`,
);
}
diff --git a/packages/threews-avatar-mcp/src/prompts.js b/packages/threews-avatar-mcp/src/prompts.js
new file mode 100644
index 000000000..a4bb26adf
--- /dev/null
+++ b/packages/threews-avatar-mcp/src/prompts.js
@@ -0,0 +1,67 @@
+// Prompt surface for the three.ws avatar MCP server.
+//
+// One prompt: showcase-avatar. Given an avatar id or @handle it drives the
+// full showcase flow — render the live, rotatable avatar inline (render_avatar
+// is an MCP App, so capable hosts show the interactive viewer) AND produce the
+// paste-anywhere embed iframe, finishing with a short copy-paste summary.
+//
+// The argument is resolved here (UUID → id selector, anything else → handle)
+// so the generated message hands the model unambiguous tool arguments.
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+// Map the raw prompt argument to the selector the tools expect.
+export function avatarSelector(raw) {
+ const value = String(raw ?? '').trim();
+ if (!value) {
+ throw new Error('showcase-avatar requires an "avatar" argument: an avatar id (UUID) or @handle.');
+ }
+ if (UUID_RE.test(value)) return { kind: 'id', value };
+ return { kind: 'handle', value: value.replace(/^@/, '') };
+}
+
+export function buildPrompts() {
+ return [
+ {
+ definition: {
+ name: 'showcase-avatar',
+ title: 'Showcase a three.ws avatar',
+ description:
+ 'Render a three.ws 3D avatar live and inline (interactive, rotatable) and produce its ' +
+ 'paste-anywhere embed iframe, with a short copy-paste summary. Takes an avatar id or @handle.',
+ arguments: [
+ {
+ name: 'avatar',
+ description: 'Avatar id (UUID) or three.ws @handle, e.g. "@nirholas".',
+ required: true,
+ },
+ ],
+ },
+ resolve(args = {}) {
+ const selector = avatarSelector(args.avatar);
+ const ref = selector.kind === 'id' ? `avatar ${selector.value}` : `@${selector.value}`;
+ const toolArg = `"${selector.kind === 'id' ? 'id' : 'handle'}": "${selector.value}"`;
+ return {
+ description: `Showcase ${ref}: live inline 3D render plus ready-to-paste embed code.`,
+ messages: [
+ {
+ role: 'user',
+ content: {
+ type: 'text',
+ text:
+ `Showcase the three.ws avatar ${ref}.\n\n` +
+ `1. Call the render_avatar tool with { ${toolArg} } so the live, rotatable 3D ` +
+ `avatar renders inline in this conversation.\n` +
+ `2. Call the avatar_embed_code tool with { ${toolArg} } to get the embed iframe.\n` +
+ `3. Finish with a short copy-paste summary containing exactly: the avatar name, ` +
+ `the interactive viewer URL, the embed URL, and the <iframe> snippet in a code ` +
+ `block — so I can paste the embed into any site without editing.\n\n` +
+ `If the avatar cannot be found, say so plainly and suggest checking the id or handle.`,
+ },
+ },
+ ],
+ };
+ },
+ },
+ ];
+}
diff --git a/packages/threews-avatar-mcp/src/tools.js b/packages/threews-avatar-mcp/src/tools.js
index ac7a759d9..6f316ae8f 100644
--- a/packages/threews-avatar-mcp/src/tools.js
+++ b/packages/threews-avatar-mcp/src/tools.js
@@ -34,6 +34,22 @@ const selectorProps = {
model: { type: 'string', description: 'Direct GLB/GLTF model URL (skips lookup; used as-is).' },
};
+// Shared output fields. The low-level Server only ADVERTISES outputSchema (it
+// never validates structuredContent), so these mirror the exact shapes the
+// handlers below build — every property listed is really emitted, nullables
+// are fields the code can set to null, and additionalProperties stays open so
+// future additive fields never break strict clients.
+const outputProps = {
+ id: {
+ type: ['string', 'null'],
+ description: 'Avatar UUID, or null when the avatar came from a raw model URL.',
+ },
+ name: { type: 'string', description: 'Avatar display name.' },
+ model_url: { type: 'string', description: 'Direct GLB/GLTF model URL.' },
+ embed_url: { type: 'string', description: 'Live avatar-embed page URL (iframe src).' },
+ iframe: { type: 'string', description: 'Ready-to-paste <iframe> embed snippet.' },
+};
+
function textBlock(text) {
return { type: 'text', text };
}
@@ -74,6 +90,19 @@ export function buildTools() {
},
anyOf: [{ required: ['id'] }, { required: ['handle'] }, { required: ['model'] }],
},
+ outputSchema: {
+ type: 'object',
+ properties: {
+ ...outputProps,
+ background: { type: 'string', description: 'Backdrop applied to the preview/embed.' },
+ viewer_url: {
+ type: 'string',
+ description: 'Standalone full-page interactive viewer URL.',
+ },
+ },
+ required: ['id', 'name', 'model_url', 'background', 'embed_url', 'viewer_url', 'iframe'],
+ additionalProperties: true,
+ },
},
handler: async (args) => {
const avatar = await resolveAvatar(args);
@@ -162,6 +191,17 @@ export function buildTools() {
},
anyOf: [{ required: ['id'] }, { required: ['handle'] }, { required: ['model'] }],
},
+ outputSchema: {
+ type: 'object',
+ properties: {
+ embed_url: outputProps.embed_url,
+ iframe: outputProps.iframe,
+ name: outputProps.name,
+ id: outputProps.id,
+ },
+ required: ['embed_url', 'iframe', 'name', 'id'],
+ additionalProperties: true,
+ },
},
handler: async (args) => {
// Validate the avatar exists (and surface a clear error if not) before
@@ -195,6 +235,37 @@ export function buildTools() {
properties: { id: selectorProps.id, handle: selectorProps.handle },
anyOf: [{ required: ['id'] }, { required: ['handle'] }],
},
+ // Mirrors the normalized avatar record from resolveAvatar: nullable
+ // fields are always present (as null when unknown); `owner` is omitted
+ // entirely when the API response carries no user.
+ outputSchema: {
+ type: 'object',
+ properties: {
+ id: outputProps.id,
+ name: outputProps.name,
+ slug: { type: ['string', 'null'], description: 'URL slug, or null if the avatar has none.' },
+ model_url: outputProps.model_url,
+ thumbnail: {
+ type: ['string', 'null'],
+ description: 'Preview/poster image URL, or null if none is published.',
+ },
+ visibility: {
+ type: ['string', 'null'],
+ description: 'Avatar visibility (e.g. "public", "unlisted"), or null if unreported.',
+ },
+ owner: {
+ type: 'object',
+ description: 'Owning user; omitted when the API response has no user record.',
+ properties: {
+ username: { type: 'string' },
+ display_name: { type: 'string' },
+ },
+ additionalProperties: true,
+ },
+ },
+ required: ['id', 'name', 'slug', 'model_url', 'thumbnail', 'visibility'],
+ additionalProperties: true,
+ },
},
handler: async (args) => {
const avatar = await resolveAvatar(args);
diff --git a/packages/threews-avatar-mcp/test/tools.test.mjs b/packages/threews-avatar-mcp/test/tools.test.mjs
index e90dd929a..efc06b2e5 100644
--- a/packages/threews-avatar-mcp/test/tools.test.mjs
+++ b/packages/threews-avatar-mcp/test/tools.test.mjs
@@ -8,6 +8,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { buildTools } from '../src/tools.js';
+import { buildPrompts, avatarSelector } from '../src/prompts.js';
import { UI_RESOURCE_URI, UI_MIME_TYPE, UI_RESOURCE_META } from '../src/ui.js';
const EXPECTED_TOOLS = ['render_avatar', 'avatar_embed_code', 'get_avatar'];
@@ -53,3 +54,85 @@ test('render_avatar declares the MCP Apps ui:// resource', () => {
'UI resource must carry a CSP grant',
);
});
+
+test('every tool advertises an honest object outputSchema', () => {
+ for (const tool of buildTools()) {
+ const { name, outputSchema } = tool.definition;
+ assert.ok(outputSchema, `${name} missing outputSchema`);
+ assert.equal(outputSchema.type, 'object', `${name} outputSchema must be an object schema`);
+ assert.equal(
+ outputSchema.additionalProperties,
+ true,
+ `${name} outputSchema must stay open to additive fields`,
+ );
+ const props = Object.keys(outputSchema.properties || {});
+ assert.ok(props.length > 0, `${name} outputSchema has no properties`);
+ assert.ok(Array.isArray(outputSchema.required), `${name} outputSchema missing required[]`);
+ for (const field of outputSchema.required) {
+ assert.ok(props.includes(field), `${name} requires undeclared field "${field}"`);
+ }
+ }
+});
+
+test('outputSchemas mirror the structuredContent each handler builds', () => {
+ const byName = new Map(buildTools().map((t) => [t.definition.name, t.definition]));
+ const fields = (name) => Object.keys(byName.get(name).outputSchema.properties);
+
+ assert.deepEqual(
+ fields('render_avatar').sort(),
+ ['background', 'embed_url', 'id', 'iframe', 'model_url', 'name', 'viewer_url'],
+ );
+ assert.deepEqual(fields('avatar_embed_code').sort(), ['embed_url', 'id', 'iframe', 'name']);
+ assert.deepEqual(
+ fields('get_avatar').sort(),
+ ['id', 'model_url', 'name', 'owner', 'slug', 'thumbnail', 'visibility'],
+ );
+ // owner is only present when the API response carries a user record, so it
+ // must NOT be advertised as required.
+ const getAvatar = byName.get('get_avatar').outputSchema;
+ assert.ok(!getAvatar.required.includes('owner'), 'owner must stay optional');
+ // id is null for raw-model renders — advertised as nullable, never omitted.
+ assert.deepEqual(byName.get('render_avatar').outputSchema.properties.id.type, ['string', 'null']);
+});
+
+test('showcase-avatar prompt enumerates with its required argument', () => {
+ const prompts = buildPrompts();
+ assert.equal(prompts.length, 1);
+ const def = prompts[0].definition;
+ assert.equal(def.name, 'showcase-avatar');
+ assert.equal(typeof def.title, 'string');
+ assert.ok(def.description.length >= 20, 'prompt description too short');
+ assert.equal(def.arguments.length, 1);
+ assert.deepEqual(
+ { name: def.arguments[0].name, required: def.arguments[0].required },
+ { name: 'avatar', required: true },
+ );
+ assert.equal(typeof prompts[0].resolve, 'function');
+});
+
+test('showcase-avatar resolves a handle into a render + embed instruction', () => {
+ const prompt = buildPrompts()[0];
+ const result = prompt.resolve({ avatar: '@nirholas' });
+ assert.equal(typeof result.description, 'string');
+ assert.equal(result.messages.length, 1);
+ assert.equal(result.messages[0].role, 'user');
+ assert.equal(result.messages[0].content.type, 'text');
+ const text = result.messages[0].content.text;
+ assert.match(text, /render_avatar/, 'must drive the inline render');
+ assert.match(text, /avatar_embed_code/, 'must drive the embed iframe');
+ assert.match(text, /"handle": "nirholas"/, 'handle arg must be normalized (no @)');
+ assert.match(text, /copy-paste summary/i, 'must ask for the copy-paste summary');
+});
+
+test('showcase-avatar resolves a UUID as an id selector and rejects empty input', () => {
+ const uuid = '01234567-89ab-cdef-0123-456789abcdef';
+ const prompt = buildPrompts()[0];
+ const result = prompt.resolve({ avatar: uuid });
+ assert.match(result.messages[0].content.text, new RegExp(`"id": "${uuid}"`));
+
+ assert.deepEqual(avatarSelector(uuid), { kind: 'id', value: uuid });
+ assert.deepEqual(avatarSelector('@nirholas'), { kind: 'handle', value: 'nirholas' });
+ assert.deepEqual(avatarSelector('nirholas'), { kind: 'handle', value: 'nirholas' });
+ assert.throws(() => avatarSelector(''), /avatar/i);
+ assert.throws(() => prompt.resolve({}), /avatar/i);
+});
diff --git a/pages/forge.html b/pages/forge.html
index 55ea2a993..ea7031469 100644
--- a/pages/forge.html
+++ b/pages/forge.html
@@ -44,10 +44,40 @@
crossorigin="anonymous"
></script>
<style>
+ /* ── Forge brand layer ─────────────────────────────────────────────
+ A documented per-surface accent ON TOP of the canonical tokens
+ (same pattern as the IBM Carbon blue at /ibm/*): Forge gets heat.
+ Everything else still consumes the canonical tokens by name. */
+ body.forge-page {
+ --accent: #ff9d57;
+ --accent-soft: rgba(255, 157, 87, 0.14);
+ }
+ html[data-theme='light'] body.forge-page {
+ --accent: #c2530f;
+ --accent-soft: rgba(194, 83, 15, 0.12);
+ }
+ /* Ambient ember glow — gives the page a focal point without panels
+ having to shout. Fixed so it doesn't repaint on scroll. */
+ body.forge-page::before {
+ content: '';
+ position: fixed;
+ inset: 0;
+ z-index: -1;
+ pointer-events: none;
+ background:
+ radial-gradient(900px 480px at 50% -140px, rgba(255, 140, 60, 0.13), transparent 65%),
+ radial-gradient(720px 460px at 88% 108%, rgba(255, 140, 60, 0.05), transparent 60%);
+ }
+ html[data-theme='light'] body.forge-page::before {
+ background:
+ radial-gradient(900px 480px at 50% -140px, rgba(214, 110, 40, 0.10), transparent 65%),
+ radial-gradient(720px 460px at 88% 108%, rgba(214, 110, 40, 0.04), transparent 60%);
+ }
+
.forge-main {
- max-width: 1180px;
+ max-width: 1320px;
margin: 0 auto;
- padding: var(--space-xl) var(--space-md) var(--space-2xl);
+ padding: var(--space-lg) var(--space-md) var(--space-2xl);
}
.forge-head {
/* Reset the global site-nav `header` rule from style.css —
@@ -65,7 +95,23 @@
z-index: auto;
-webkit-app-region: no-drag;
text-align: center;
- margin-bottom: var(--space-xl);
+ margin-bottom: var(--space-lg);
+ }
+
+ /* ── Workspace: composer rail + stage side by side on desktop ────── */
+ .forge-workspace {
+ display: grid;
+ gap: var(--space-lg);
+ align-items: start;
+ }
+ @media (min-width: 1080px) {
+ .forge-workspace {
+ grid-template-columns: minmax(370px, 430px) minmax(0, 1fr);
+ }
+ .forge-rail {
+ position: sticky;
+ top: 84px;
+ }
}
.forge-eyebrow {
display: inline-flex;
@@ -90,15 +136,19 @@
}
.forge-head h1 {
display: block;
- color: var(--ink);
font-family: var(--font-display);
- font-size: clamp(2rem, 5vw, var(--text-2xl));
+ font-size: clamp(2rem, 4.6vw, var(--text-2xl));
line-height: var(--leading-tight);
- margin: var(--space-md) 0 var(--space-xs);
+ margin: var(--space-md) auto var(--space-xs);
+ max-width: 24ch;
+ background: linear-gradient(115deg, var(--ink) 55%, var(--accent) 125%);
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
}
.forge-head p {
color: var(--ink-dim);
- max-width: 46ch;
+ max-width: 52ch;
margin: 0 auto;
line-height: var(--leading-normal);
}
@@ -238,6 +288,25 @@
background: var(--surface-2);
box-shadow: none;
}
+ /* The one unmistakable action on the page — full-width ember CTA. */
+ #generate {
+ width: 100%;
+ justify-content: center;
+ font-size: var(--text-lg);
+ padding: 0.75rem 1.2rem;
+ background: linear-gradient(135deg, #ffb877, #ff7a2f);
+ border-color: transparent;
+ color: #1a0d04;
+ }
+ #generate:hover {
+ box-shadow:
+ 0 0 0 4px var(--accent-soft),
+ 0 8px 28px -8px rgba(255, 130, 50, 0.55);
+ }
+ html[data-theme='light'] body.forge-page #generate {
+ background: linear-gradient(135deg, #d96a1e, #b34a08);
+ color: #fff;
+ }
.gen-kbd {
font-family: var(--font-mono);
font-size: 0.72em;
@@ -417,6 +486,11 @@
color: var(--ink-dim);
min-width: 4.2rem;
}
+ /* forge.js hides the #aspect control itself when the mode makes it
+ irrelevant — collapse the labeled row with it, no orphan label. */
+ .fq-row:has(> .aspect.is-hidden) {
+ display: none;
+ }
.byok-row {
display: flex;
align-items: center;
@@ -472,11 +546,11 @@
/* Mode switch -------------------------------------------------- */
.mode-switch-wrap {
display: flex;
- justify-content: center;
- margin-bottom: var(--space-md);
+ margin-bottom: var(--space-sm);
}
.mode-switch {
- display: inline-flex;
+ display: flex;
+ width: 100%;
gap: 2px;
background: var(--surface-1);
border: 1px solid var(--stroke);
@@ -484,13 +558,14 @@
padding: 3px;
}
.mode-switch button {
+ flex: 1;
background: transparent;
border: none;
color: var(--ink-dim);
font-family: var(--font-display);
font-size: var(--text-sm);
font-weight: 600;
- padding: 0.5rem 1.05rem;
+ padding: 0.5rem 0.6rem;
border-radius: var(--radius-sm);
cursor: pointer;
transition:
@@ -802,8 +877,7 @@
display: flex;
flex-wrap: wrap;
gap: var(--space-xs);
- justify-content: center;
- margin-top: var(--space-md);
+ margin-top: var(--space-sm);
}
.chip {
background: var(--surface-1);
@@ -821,14 +895,82 @@
}
.chip:hover {
color: var(--ink);
- border-color: var(--stroke-strong);
- background: var(--surface-2);
+ border-color: var(--accent);
+ background: var(--accent-soft);
}
/* Workspace / states ------------------------------------------ */
.stage {
- margin-top: var(--space-xl);
- min-height: 320px;
+ min-height: 480px;
+ }
+
+ /* Idle — a live model, not a void. The newest community forge (or a
+ labeled first-party sample) stands here so the first thing a visitor
+ sees is the product's output. Markup in #state-empty; data wiring in
+ the inline idle-teaser module at the end of the page. */
+ .idle-viewer-wrap {
+ position: relative;
+ }
+ .idle-viewer-wrap model-viewer {
+ width: 100%;
+ height: min(52vh, 480px);
+ background: radial-gradient(120% 120% at 50% 0%, #1a1612 0%, #0b0a09 70%);
+ --poster-color: transparent;
+ }
+ html[data-theme='light'] .idle-viewer-wrap model-viewer {
+ background: radial-gradient(120% 120% at 50% 0%, #f3eee9 0%, #e7e2dc 70%);
+ }
+ .idle-tag {
+ position: absolute;
+ top: 10px;
+ left: 12px;
+ font-family: var(--font-mono);
+ font-size: 0.65rem;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--ink-dim);
+ background: rgba(0, 0, 0, 0.45);
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ padding: 2px 9px;
+ backdrop-filter: blur(4px);
+ }
+ .idle-bar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ padding: var(--space-sm) var(--space-md);
+ border-top: 1px solid var(--stroke);
+ flex-wrap: wrap;
+ }
+ .idle-caption {
+ display: flex;
+ flex-direction: column;
+ gap: 0.15rem;
+ min-width: 0;
+ flex: 1 1 16rem;
+ }
+ .idle-kicker {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--accent);
+ }
+ .idle-prompt {
+ color: var(--ink);
+ font-size: var(--text-sm);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .idle-hint {
+ flex-basis: 100%;
+ margin: 0;
+ color: var(--ink-dim);
+ font-size: var(--text-xs);
+ line-height: var(--leading-normal);
}
.panel {
background: var(--surface-glass);
@@ -2411,6 +2553,7 @@
<script type="module" src="/src/forge-enhance.js"></script>
<script type="module" src="/src/forge-stylize.js"></script>
<script type="module" src="/src/forge-optimize.js"></script>
+ <script type="module" src="/src/forge-export.js"></script>
<script type="module" src="/src/forge-embed-panel.js"></script>
<script type="module" src="/src/forge-ar.js"></script>
<script type="module" src="/src/forge-showcase.js"></script>
diff --git a/pages/home.html b/pages/home.html
index b7e296c57..0896ae0cc 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -3233,6 +3233,73 @@
#home-forge .hf-toast[hidden] { display: none; }
#home-forge .hf-toast.is-on { opacity: 1; transform: translateX(-50%) translateY(0); }
+ /* Embed sheet — an in-chamber glass dialog in the chamber's own language. */
+ #home-forge .hf-embed {
+ position: absolute; inset: 0; z-index: 9; display: flex; align-items: center; justify-content: center;
+ padding: 22px;
+ }
+ #home-forge .hf-embed[hidden] { display: none; }
+ #home-forge .hf-embed-scrim {
+ position: absolute; inset: 0; background: rgba(6, 6, 8, 0.62);
+ -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px);
+ animation: hf-embed-fade 0.22s ease both;
+ }
+ @keyframes hf-embed-fade { from { opacity: 0; } }
+ #home-forge .hf-embed-card {
+ position: relative; z-index: 1; width: min(440px, 100%); max-height: 100%; overflow-y: auto;
+ display: flex; flex-direction: column; gap: 12px; padding: 18px;
+ border-radius: 18px; scrollbar-width: none;
+ background: linear-gradient(rgba(13, 13, 17, 0.92), rgba(13, 13, 17, 0.92)) padding-box,
+ linear-gradient(120deg, rgba(255, 180, 84, 0.4), rgba(255, 106, 213, 0.4) 38%, rgba(139, 92, 246, 0.4) 64%, rgba(79, 195, 255, 0.4)) border-box;
+ border: 1px solid transparent;
+ -webkit-backdrop-filter: blur(18px); backdrop-filter: blur(18px);
+ box-shadow: 0 30px 80px -28px rgba(0, 0, 0, 0.92);
+ animation: hf-embed-rise 0.3s cubic-bezier(0.22, 1, 0.36, 1) both;
+ }
+ #home-forge .hf-embed-card::-webkit-scrollbar { display: none; }
+ @keyframes hf-embed-rise { from { opacity: 0; transform: translateY(14px) scale(0.97); } }
+ #home-forge .hf-embed-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
+ #home-forge .hf-embed-kicker {
+ margin: 0 0 2px; font-family: var(--font-mono); font-size: 10.5px; letter-spacing: 0.14em;
+ text-transform: uppercase; color: #ffb454;
+ }
+ #home-forge .hf-embed-title { margin: 0; font-family: var(--font-display); font-size: 17px; font-weight: 600; letter-spacing: -0.01em; color: var(--text); }
+ #home-forge .hf-embed-preview {
+ width: 100%; border-radius: 12px; overflow: hidden; border: 1px solid var(--hairline);
+ background: #0b0b0d; aspect-ratio: 16 / 9; transition: aspect-ratio 0.32s cubic-bezier(0.22, 1, 0.36, 1);
+ }
+ #home-forge .hf-embed-frame { display: block; width: 100%; height: 100%; border: 0; }
+ #home-forge .hf-embed-controls { display: flex; flex-wrap: wrap; gap: 8px; justify-content: space-between; }
+ #home-forge .hf-seg {
+ display: inline-flex; gap: 2px; padding: 2px; border-radius: 10px;
+ background: rgba(255, 255, 255, 0.035); border: 1px solid var(--hairline);
+ }
+ #home-forge .hf-seg-btn {
+ background: transparent; border: 0; cursor: pointer; color: var(--text-3);
+ font-family: var(--font-mono); font-size: 11.5px; font-weight: 600; letter-spacing: 0.02em;
+ padding: 7px 11px; border-radius: 8px; transition: background 0.14s, color 0.14s;
+ }
+ #home-forge .hf-seg-btn:hover { color: var(--text); }
+ #home-forge .hf-seg-btn[aria-pressed='true'] { background: rgba(255, 255, 255, 0.1); color: var(--text); }
+ #home-forge .hf-seg-btn:focus-visible { outline: 2px solid #8b5cf6; outline-offset: 2px; }
+ #home-forge .hf-embed-codelabel {
+ font-family: var(--font-mono); font-size: 10.5px; letter-spacing: 0.06em; text-transform: uppercase;
+ color: var(--text-3); margin-top: 2px;
+ }
+ #home-forge .hf-embed-code {
+ width: 100%; box-sizing: border-box; resize: vertical; min-height: 96px;
+ background: rgba(0, 0, 0, 0.42); border: 1px solid var(--hairline); border-radius: 10px;
+ padding: 11px 12px; color: var(--text); white-space: pre; overflow-x: auto;
+ font-family: var(--font-mono); font-size: 12px; line-height: 1.55; scrollbar-width: thin;
+ }
+ #home-forge .hf-embed-code:focus-visible { outline: 2px solid #8b5cf6; outline-offset: 1px; }
+ #home-forge .hf-embed-copy { width: 100%; justify-content: center; padding: 12px 16px; }
+ #home-forge .hf-embed-copy.is-copied { background: #58d68d; border-color: #58d68d; box-shadow: 0 0 24px -6px rgba(88, 214, 141, 0.6); }
+ #home-forge .hf-embed-foot { margin: 0; font-size: 12px; line-height: 1.5; color: var(--text-3); text-align: center; }
+ #home-forge .hf-embed-foot a { color: var(--text-2); text-decoration: none; border-bottom: 1px solid var(--hairline-strong); }
+ #home-forge .hf-embed-foot a:hover { color: var(--text); }
+ #home-forge .hf-embed-foot a:focus-visible { outline: 2px solid #8b5cf6; outline-offset: 2px; }
+
@media (max-width: 720px) {
#home-forge .hf-chamber { min-height: 600px; border-radius: 16px; }
#home-forge .hf-state { padding: 24px 18px 190px; }
@@ -3256,6 +3323,8 @@
#home-forge .hf-hud .dot { animation: none; }
#home-forge .hf-thumb { animation: none; }
#home-forge .hf-toast { transition: opacity 0.2s ease; }
+ #home-forge .hf-embed-scrim, #home-forge .hf-embed-card { animation: none; }
+ #home-forge .hf-embed-preview { transition: none; }
}
</style>
<section class="block" id="home-forge">
@@ -3320,6 +3389,9 @@
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2 3 7v10l9 5 9-5V7z"/><path d="M3 7l9 5 9-5"/><path d="M12 12v10"/></svg>
Scene Studio
</a>
+ <button type="button" class="hf-btn hf-icon-btn" data-hf-embed-open title="Embed on any website" aria-label="Embed on any website" aria-haspopup="dialog">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
+ </button>
<button type="button" class="hf-btn hf-icon-btn" data-hf-share title="Copy share link" aria-label="Copy share link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1.5 1.5"/><path d="M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1.5-1.5"/></svg>
</button>
@@ -3340,6 +3412,49 @@
<button type="button" class="hf-btn hf-btn--bright" data-hf-retry>Try again</button>
</div>
+ <!-- Embed sheet — drop the forged model on any site. Snippet shapes are
+ shared with the full Forge via src/forge-embed-snippets.js. -->
+ <div class="hf-embed" data-hf-embed hidden role="dialog" aria-modal="true" aria-label="Embed this model">
+ <div class="hf-embed-scrim" data-hf-embed-close aria-hidden="true"></div>
+ <div class="hf-embed-card" role="document">
+ <div class="hf-embed-head">
+ <div>
+ <p class="hf-embed-kicker">Embed</p>
+ <h3 class="hf-embed-title">Put this model on any site</h3>
+ </div>
+ <button type="button" class="hf-btn hf-icon-btn" data-hf-embed-close title="Close" aria-label="Close embed panel">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
+ </button>
+ </div>
+
+ <div class="hf-embed-preview" data-hf-embed-preview>
+ <iframe class="hf-embed-frame" data-hf-embed-frame title="Embed preview" allow="xr-spatial-tracking; fullscreen" loading="lazy"></iframe>
+ </div>
+
+ <div class="hf-embed-controls">
+ <div class="hf-seg" data-hf-embed-tabs role="group" aria-label="Embed type">
+ <button type="button" class="hf-seg-btn" data-hf-embed-tab="iframe" aria-pressed="true">iframe</button>
+ <button type="button" class="hf-seg-btn" data-hf-embed-tab="component" aria-pressed="false">Web component</button>
+ </div>
+ <div class="hf-seg" data-hf-embed-sizes role="group" aria-label="Size">
+ <button type="button" class="hf-seg-btn" data-hf-embed-size="wide" aria-pressed="true">16 : 9</button>
+ <button type="button" class="hf-seg-btn" data-hf-embed-size="square" aria-pressed="false">Square</button>
+ <button type="button" class="hf-seg-btn" data-hf-embed-size="portrait" aria-pressed="false">4 : 5</button>
+ </div>
+ </div>
+
+ <label class="hf-embed-codelabel" for="hf-embed-code">Paste this where you want the model</label>
+ <textarea id="hf-embed-code" class="hf-embed-code" data-hf-embed-code readonly spellcheck="false" rows="5"></textarea>
+
+ <button type="button" class="hf-forge-btn hf-embed-copy" data-hf-embed-copy>
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
+ <span data-hf-embed-copy-label>Copy embed code</span>
+ </button>
+
+ <p class="hf-embed-foot">Live, orbitable, AR-ready on phones &middot; <a data-hf-embed-standalone target="_blank" rel="noopener">open the standalone viewer &#8599;</a></p>
+ </div>
+ </div>
+
<form class="hf-dock" data-hf-form autocomplete="off">
<div class="hf-chips" data-hf-chips role="group" aria-label="Example prompts">
<button type="button" class="hf-chip" data-prompt="a low-poly red fox, sitting">low-poly fox</button>
diff --git a/pages/tutorial.html b/pages/tutorial.html
index 0feeeeb8a..b52a78ee3 100644
--- a/pages/tutorial.html
+++ b/pages/tutorial.html
@@ -1237,6 +1237,13 @@
seen.set(id, 1);
}
h.id = id;
+ // Hover-revealed deep-link anchor in the heading's left margin.
+ const anchor = document.createElement('a');
+ anchor.className = 'tdoc-anchor';
+ anchor.href = `#${id}`;
+ anchor.setAttribute('aria-label', `Link to “${h.textContent}”`);
+ anchor.innerHTML = ICON_LINK;
+ h.insertBefore(anchor, h.firstChild);
const li = document.createElement('li');
const a = document.createElement('a');
a.href = `#${id}`;
@@ -1342,6 +1349,7 @@
}
});
+ addCopyButtons(article);
buildToc(article);
appendPager(article, slug);
} catch (e) {
@@ -1354,6 +1362,66 @@
}
}
+ // One-click copy on every code block. Copies the raw code text (not the
+ // highlight markup) and confirms inline before reverting.
+ function addCopyButtons(article) {
+ article.querySelectorAll('pre').forEach((pre) => {
+ const code = pre.querySelector('code');
+ if (!code) return;
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'tdoc-copy-btn';
+ btn.setAttribute('aria-label', 'Copy code to clipboard');
+ btn.innerHTML = `${ICON_COPY}<span>Copy</span>`;
+ let resetTimer = null;
+ btn.addEventListener('click', async () => {
+ try {
+ await navigator.clipboard.writeText(code.innerText);
+ btn.classList.add('is-copied');
+ btn.innerHTML = `${ICON_CHECK}<span>Copied</span>`;
+ } catch {
+ btn.innerHTML = `${ICON_COPY}<span>Press ⌘C</span>`;
+ }
+ clearTimeout(resetTimer);
+ resetTimer = setTimeout(() => {
+ btn.classList.remove('is-copied');
+ btn.innerHTML = `${ICON_COPY}<span>Copy</span>`;
+ }, 1700);
+ });
+ pre.appendChild(btn);
+ });
+ }
+
+ // Reading-progress rail + back-to-top, driven by real scroll position.
+ (function readingChrome() {
+ const fill = document.getElementById('tdoc-progress-fill');
+ const topBtn = document.getElementById('tdoc-top');
+ const root = document.documentElement;
+ let ticking = false;
+ function update() {
+ ticking = false;
+ const max = root.scrollHeight - root.clientHeight;
+ const pct = max > 0 ? Math.min(100, (root.scrollTop / max) * 100) : 0;
+ if (fill) fill.style.width = `${pct}%`;
+ if (topBtn) topBtn.classList.toggle('is-visible', root.scrollTop > 600);
+ }
+ window.addEventListener(
+ 'scroll',
+ () => {
+ if (!ticking) {
+ ticking = true;
+ requestAnimationFrame(update);
+ }
+ },
+ { passive: true },
+ );
+ topBtn?.addEventListener('click', () => {
+ const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ window.scrollTo({ top: 0, behavior: reduce ? 'auto' : 'smooth' });
+ });
+ update();
+ })();
+
// Wait for the manifest script (deferred) to expose TUTORIALS, then render.
if (window.TUTORIALS) {
loadTutorial();
diff --git a/public/agents/index.html b/public/agents/index.html
index 0f4a06dd3..bab7a1a2e 100644
--- a/public/agents/index.html
+++ b/public/agents/index.html
@@ -297,6 +297,17 @@
box-shadow: 0 8px 24px rgba(0, 217, 255, 0.3);
}
+ .cta-button--ghost {
+ background: transparent;
+ border: 1px solid rgba(255, 255, 255, 0.25);
+ margin-left: 0.75rem;
+ }
+
+ .cta-button--ghost:hover {
+ box-shadow: 0 8px 24px rgba(255, 255, 255, 0.12);
+ border-color: rgba(255, 255, 255, 0.45);
+ }
+
.pagination {
display: flex;
justify-content: center;
@@ -444,8 +455,9 @@
<div id="empty-state" class="empty-state" style="display: none">
<h2>No agents found</h2>
- <p>Be the first to register your agent on-chain.</p>
+ <p>Be the first to register your agent on-chain — generate its 3D body from a text prompt, then give it a brain.</p>
<a href="/create" class="cta-button">Create Agent</a>
+ <a href="/create/prompt" class="cta-button cta-button--ghost">Generate a body from text</a>
</div>
<div id="pagination" class="pagination" style="display: none">
diff --git a/public/changelog.json b/public/changelog.json
index 7e771e504..351c84fca 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-13T01:04:38.535Z",
+ "generated_at": "2026-06-13T01:16:42.831Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -26,6 +26,26 @@
"feature"
]
},
+ {
+ "date": "2026-06-13",
+ "type": "update",
+ "title": "Refine any Forge model to higher quality in one click — plus sharper multi-view guidance",
+ "summary": "Three upgrades to the Forge (/forge). After a model generates, a new Refine button re-runs that exact prompt or photos one quality tier higher — Draft to Standard to High — so you can preview cheaply, then commit to the best version without retyping anything. When building from photos, a live counter now shows how many of the four reference views you've added and reminds you that more angles make a sharper mesh. And the action bar under each finished model now reflows cleanly on phones, with Refine and Make-another leading at full width. Sketch mode also makes its required description unmistakable.",
+ "link": "/forge",
+ "tags": [
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-13",
+ "type": "update",
+ "title": "See any Forge model in AR — scan from your desktop, place it in your room",
+ "summary": "Every finished model now has a View in AR button. On a phone it drops the model into your space through the camera; on a desktop it shows a QR code you scan with your phone to open the same model, one tap from AR — so you can walk around what you just made at real-world scale. The embed viewer gained a big one-tap AR launcher on phones too, so models embedded on other sites are placeable in AR as well. No app, no download — it runs in the browser.",
+ "link": "/forge",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-13",
"type": "update",
@@ -36,6 +56,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-13",
+ "type": "update",
+ "title": "Tutorials read better: one-tap copy on every code block, live progress, and a jump-to-the-tool button",
+ "summary": "The tutorial reader (/tutorials) got a polish pass that applies to every guide. Code blocks now have a one-click Copy button, so you can lift a snippet without selecting it by hand. A slim progress rail across the top tracks how far you've read, and a back-to-top button appears once you scroll in. Each section heading has a hover link for sharing a deep link to that exact spot, and every tutorial now opens with a clear call-to-action button — the new text-to-3D guides drop you straight into the Forge. New this release: four beginner guides for turning a text prompt or photos into a downloadable 3D model, a copy-paste prompt cookbook, and an API walkthrough.",
+ "link": "/tutorials",
+ "tags": [
+ "docs",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-12",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index 5068090b7..27d17e0ab 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -22,6 +22,22 @@
<category>feature</category>
<description>Every model you forge now has an Embed button next to Download. It hands you a ready-to-paste snippet — an iframe by default, or a &lt;model-viewer&gt; web component for builders — that drops a live, orbitable, AR-ready 3D model onto any website, with a live preview and size presets (16:9, square, 4:5) right in the panel. The iframe points at a new lightweight three.ws viewer (/forge/embed) that needs no scripts on the host page, and clicking its corner badge brings visitors back to Forge with your prompt pre-loaded to remix. Same idea as the &lt;agent-3d&gt; embed, now for any generated object.</description>
</item>
+ <item>
+ <title>Refine any Forge model to higher quality in one click — plus sharper multi-view guidance</title>
+ <link>https://three.ws/forge</link>
+ <guid isPermaLink="false">2026-06-13:Refine any Forge model to higher quality in one click — plus sharper multi-view guidance</guid>
+ <pubDate>Sat, 13 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Three upgrades to the Forge (/forge). After a model generates, a new Refine button re-runs that exact prompt or photos one quality tier higher — Draft to Standard to High — so you can preview cheaply, then commit to the best version without retyping anything. When building from photos, a live counter now shows how many of the four reference views you've added and reminds you that more angles make a sharper mesh. And the action bar under each finished model now reflows cleanly on phones, with Refine and Make-another leading at full width. Sketch mode also makes its required description unmistakable.</description>
+ </item>
+ <item>
+ <title>See any Forge model in AR — scan from your desktop, place it in your room</title>
+ <link>https://three.ws/forge</link>
+ <guid isPermaLink="false">2026-06-13:See any Forge model in AR — scan from your desktop, place it in your room</guid>
+ <pubDate>Sat, 13 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Every finished model now has a View in AR button. On a phone it drops the model into your space through the camera; on a desktop it shows a QR code you scan with your phone to open the same model, one tap from AR — so you can walk around what you just made at real-world scale. The embed viewer gained a big one-tap AR launcher on phones too, so models embedded on other sites are placeable in AR as well. No app, no download — it runs in the browser.</description>
+ </item>
<item>
<title>The full page directory is now one click away — and instantly filterable</title>
<link>https://three.ws/sitemap</link>
@@ -30,6 +46,14 @@
<category>improvement</category>
<description>three.ws has grown past 200 pages, so the sitemap directory got a real upgrade. A new &quot;All pages&quot; link in the Discover menu takes you straight to it, and the page itself now has an instant filter — press / and type to narrow every page by name, path, or description, with live per-section counts. Filtered views are shareable links, so you can send someone exactly the slice of the platform you mean. The directory now finds you when you're lost, too: it's a quick action in the ⌘K search palette, a no-results search hands you off to it with your query carried over, the 404 page offers it pre-filtered to the closest matches for the address you tried, and /pages, /directory, /everything, and /all-pages all take you there. Eighteen pages that had never been registered in the index — What is three.ws?, the 3D Scanner, the Glossary, Support, the agent-economy demos, and all six IBM watsonx showcases under a new Integrations section — are now in the directory, the search palette, and the crawler sitemap.</description>
</item>
+ <item>
+ <title>Tutorials read better: one-tap copy on every code block, live progress, and a jump-to-the-tool button</title>
+ <link>https://three.ws/tutorials</link>
+ <guid isPermaLink="false">2026-06-13:Tutorials read better: one-tap copy on every code block, live progress, and a jump-to-the-tool button</guid>
+ <pubDate>Sat, 13 Jun 2026 12:00:00 GMT</pubDate>
+ <category>docs</category>
+ <description>The tutorial reader (/tutorials) got a polish pass that applies to every guide. Code blocks now have a one-click Copy button, so you can lift a snippet without selecting it by hand. A slim progress rail across the top tracks how far you've read, and a back-to-top button appears once you scroll in. Each section heading has a hover link for sharing a deep link to that exact spot, and every tutorial now opens with a clear call-to-action button — the new text-to-3D guides drop you straight into the Forge. New this release: four beginner guides for turning a text prompt or photos into a downloadable 3D model, a copy-paste prompt cookbook, and an API walkthrough.</description>
+ </item>
<item>
<title>Agent Launches</title>
<link>https://three.ws/launches</link>
diff --git a/public/features.json b/public/features.json
index df276fb9c..9a27fe163 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-13T01:04:38.520Z",
+ "generated_at": "2026-06-13T01:16:42.773Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/gmgn.html b/public/gmgn.html
index c3d89495e..b0e79ba2f 100644
--- a/public/gmgn.html
+++ b/public/gmgn.html
@@ -770,7 +770,7 @@
const filtered = pickerQuery ? items.filter((a) => (a.name || a.url || '').toLowerCase().includes(pickerQuery)) : items;
if (!filtered.length) {
- body.innerHTML = `<div class="empty">${pickerLoading[pickerTab] ? 'Loading…' : pickerTab === 'mine' && pickerAuthed === false ? '<a href="/auth">Sign in</a> to see your agents' : 'No avatars found'}</div>`;
+ body.innerHTML = `<div class="empty">${pickerLoading[pickerTab] ? 'Loading…' : pickerTab === 'mine' && pickerAuthed === false ? '<a href="/login">Sign in</a> to see your agents' : 'No avatars found'}</div>`;
return;
}
const grid = document.createElement('div');
diff --git a/public/tutorials-manifest.js b/public/tutorials-manifest.js
index 871c5beaf..3c72d7daa 100644
--- a/public/tutorials-manifest.js
+++ b/public/tutorials-manifest.js
@@ -170,7 +170,7 @@
builds: 'A script that turns a prompt list into a folder of GLB files',
time: '25 min',
previewModel: '/animations/soldier.glb',
- ctaPrimary: { label: 'Read the API tutorial', href: '/tutorials/generate-3d-api' },
+ ctaPrimary: { label: 'Open the Forge', href: '/forge' },
},
{
slug: 'upload-custom-glb',
diff --git a/scripts/audit-mcp-manifests.mjs b/scripts/audit-mcp-manifests.mjs
new file mode 100644
index 000000000..5a03ec26c
--- /dev/null
+++ b/scripts/audit-mcp-manifests.mjs
@@ -0,0 +1,123 @@
+#!/usr/bin/env node
+// Build gate: validate every MCP registry manifest in this repo, offline.
+//
+// The official registry (registry.modelcontextprotocol.io) enforces these
+// rules at publish time; a manifest that drifts past them blocks the next
+// release without anyone noticing until publish day. This audit fails the
+// build instead. Checks, per manifest:
+// - JSON parses, name/description/version present
+// - description ≤ 100 chars (registry schema maxLength)
+// - name is io.github.<owner>/<server> form
+// - icons use https URLs; websiteUrl is https
+// - stdio packages: server.json version matches package.json version,
+// packages[0].identifier/version match, mcpName matches server.json name
+// - remote manifests: every remotes[].url is https
+//
+// Run: node scripts/audit-mcp-manifests.mjs (exit 1 on any violation)
+
+import { readFileSync, existsSync, readdirSync } from 'node:fs';
+import { resolve, dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+// stdio package manifests live next to their package.json.
+const PACKAGE_MANIFESTS = [
+ 'mcp-server/server.json',
+ 'mcp-bridge/server.json',
+ 'packages/pumpfun-mcp/server.json',
+ 'packages/ibm-watsonx-mcp/server.json',
+ 'packages/ibm-x402-mcp/server.json',
+ 'packages/avatar-agent-mcp/server.json',
+ 'packages/threews-avatar-mcp/server.json',
+ 'packages/three-token-mcp/server.json',
+];
+
+// Remote manifests are every server*.json at the repo root.
+const remoteManifests = readdirSync(root).filter((f) => /^server(-[\w-]+)?\.json$/.test(f));
+
+let violations = 0;
+const fail = (file, msg) => {
+ violations += 1;
+ console.error(`[audit:mcp] ${file}: ${msg}`);
+};
+
+function load(path) {
+ try {
+ return JSON.parse(readFileSync(resolve(root, path), 'utf8'));
+ } catch (err) {
+ fail(path, `unreadable or invalid JSON (${err.message})`);
+ return null;
+ }
+}
+
+function checkCommon(path, m) {
+ if (!m.name) fail(path, 'missing name');
+ else if (!/^io\.github\.[\w-]+\/[\w.-]+$/.test(m.name)) {
+ fail(path, `name "${m.name}" is not io.github.<owner>/<server>`);
+ }
+ if (!m.version) fail(path, 'missing version');
+ if (!m.description) fail(path, 'missing description');
+ else if (m.description.length > 100) {
+ fail(path, `description is ${m.description.length} chars (registry max is 100)`);
+ }
+ if (m.websiteUrl && !m.websiteUrl.startsWith('https://')) {
+ fail(path, `websiteUrl must be https (${m.websiteUrl})`);
+ }
+ for (const icon of m.icons ?? []) {
+ if (!icon.src?.startsWith('https://')) fail(path, `icon src must be https (${icon.src})`);
+ }
+}
+
+for (const path of PACKAGE_MANIFESTS) {
+ if (!existsSync(resolve(root, path))) {
+ // mcp-bridge gains its manifest when it goes public; absence is only an
+ // error once the package itself is publishable.
+ const pkgPath = join(dirname(path), 'package.json');
+ const pkg = existsSync(resolve(root, pkgPath)) ? load(pkgPath) : null;
+ if (pkg && !pkg.private) fail(path, 'missing server.json for a publishable MCP package');
+ continue;
+ }
+ const m = load(path);
+ if (!m) continue;
+ checkCommon(path, m);
+
+ const pkg = load(join(dirname(path), 'package.json'));
+ if (!pkg) continue;
+ if (pkg.version !== m.version) {
+ fail(path, `version ${m.version} ≠ package.json ${pkg.version}`);
+ }
+ if (pkg.mcpName !== m.name) {
+ fail(path, `package.json mcpName "${pkg.mcpName}" ≠ name "${m.name}"`);
+ }
+ const entry = m.packages?.[0];
+ if (!entry) fail(path, 'missing packages[0]');
+ else {
+ if (entry.identifier !== pkg.name) {
+ fail(path, `packages[0].identifier "${entry.identifier}" ≠ npm name "${pkg.name}"`);
+ }
+ if (entry.version !== m.version) {
+ fail(path, `packages[0].version ${entry.version} ≠ manifest version ${m.version}`);
+ }
+ }
+}
+
+for (const path of remoteManifests) {
+ const m = load(path);
+ if (!m) continue;
+ checkCommon(path, m);
+ const remotes = m.remotes ?? [];
+ if (remotes.length === 0 && !m.packages?.length) {
+ fail(path, 'declares neither remotes nor packages');
+ }
+ for (const r of remotes) {
+ if (!r.url?.startsWith('https://')) fail(path, `remote url must be https (${r.url})`);
+ }
+}
+
+const total = PACKAGE_MANIFESTS.length + remoteManifests.length;
+if (violations) {
+ console.error(`[audit:mcp] ${violations} violation(s) across ${total} manifests`);
+ process.exit(1);
+}
+console.log(`[audit:mcp] ${total} MCP manifests consistent`);
diff --git a/scripts/backfill-added-dates.mjs b/scripts/backfill-added-dates.mjs
index 2caa5641d..116098a21 100644
--- a/scripts/backfill-added-dates.mjs
+++ b/scripts/backfill-added-dates.mjs
@@ -24,7 +24,31 @@ for (const m of viteSrc.matchAll(/'(\/[^']*)':\s*resolve\(root,\s*'([^']+)'\)/g)
viteMap.set(m[1].replace(/\/$/, '') || '/', m[2]);
}
+// Routes whose serving file can't be derived by convention: SPA sub-routes,
+// markdown-backed docs views, and dynamic API-served documents.
+const MANUAL_SOURCES = {
+ '/dashboard/account': 'pages/dashboard-next/account.html',
+ '/dashboard/analytics': 'pages/dashboard-next/analytics.html',
+ '/dashboard/settings': 'pages/dashboard-next/settings.html',
+ '/docs/quick-start': 'docs/quick-start.md',
+ '/docs/agent-system': 'docs/agent-system.md',
+ '/docs/erc8004': 'docs/erc8004.md',
+ '/docs/embedding': 'docs/embedding.md',
+ '/docs/web-component': 'docs/web-component.md',
+ '/docs/mcp': 'docs/mcp.md',
+ '/docs/skills': 'docs/skills.md',
+ '/docs/api-reference': 'docs/api-reference.md',
+ '/docs/sdk': 'docs/sdk.md',
+ '/docs/listings': 'docs/listings.md',
+ '/sitemap.xml': 'api/sitemap.js',
+ '/openapi.json': 'api/openapi-json.js',
+ '/.well-known/x402': 'api/wk.js',
+ '/.well-known/agent-attestation-schemas': 'api/wk.js',
+ '/.well-known/oauth-authorization-server': 'api/wk.js',
+};
+
function candidatesFor(path) {
+ if (MANUAL_SOURCES[path]) return [MANUAL_SOURCES[path]];
const p = path.replace(/^\//, '');
const list = [];
const mapped = viteMap.get(path) || viteMap.get(path.replace(/\/$/, ''));
diff --git a/scripts/build-vercel.mjs b/scripts/build-vercel.mjs
index 0670c6413..bf36589c3 100644
--- a/scripts/build-vercel.mjs
+++ b/scripts/build-vercel.mjs
@@ -209,6 +209,9 @@ try {
// undeclared api/ imports — the classes behind the 2026-06-11 outage —
// instead of 18 minutes into NFT tracing or, worse, at runtime.
run('audit:deploy', 'node scripts/audit-deploy-artifacts.mjs'),
+ // MCP registry manifests: catches version drift, >100-char descriptions,
+ // and mcpName mismatches at build time instead of on publish day.
+ run('audit:mcp', 'node scripts/audit-mcp-manifests.mjs'),
prebuild(),
ensureSDKDist().then(bundleApi),
]);
diff --git a/scripts/publish-mcp-servers.mjs b/scripts/publish-mcp-servers.mjs
index 3a4dd3aa6..bbb856199 100644
--- a/scripts/publish-mcp-servers.mjs
+++ b/scripts/publish-mcp-servers.mjs
@@ -61,7 +61,9 @@ const SERVERS = [
dir: 'packages/three-token-mcp',
manifest: 'packages/three-token-mcp/server.json',
},
+ { key: 'mcp-bridge', dir: 'mcp-bridge', manifest: 'mcp-bridge/server.json' },
{ key: 'remote-main', manifest: 'server.json' },
+ { key: 'remote-pumpfun', manifest: 'server-pumpfun.json' },
{ key: 'remote-3d', manifest: 'server-3d.json' },
{ key: 'remote-agent', manifest: 'server-agent.json' },
{ key: 'remote-ibm', manifest: 'server-ibm.json' },
diff --git a/scripts/setup-dev.mjs b/scripts/setup-dev.mjs
index 952eedfa1..aa7d5df1a 100644
--- a/scripts/setup-dev.mjs
+++ b/scripts/setup-dev.mjs
@@ -54,7 +54,11 @@ if (!existsSync(resolve(ROOT, 'agent-payments-sdk/dist/index.js'))) {
buildSdk('setup-agent-payments-sdk', 'agent-payments-sdk', 'agent-payments-sdk/dist/index.js');
}
-// 2. Generated data consumed by the app, sitemap, and tests.
+// 2. Git hooks: no CI runs on this repo, so the pre-push typecheck in
+// .githooks/ is the only automated gate before the Vercel build.
+run('git config core.hooksPath .githooks');
+
+// 3. Generated data consumed by the app, sitemap, and tests.
run('node scripts/build-news.mjs');
run('node scripts/build-skill-metadata.mjs');
run('node scripts/build-local-skill-packs.mjs');
diff --git a/scripts/verify-forge-export.mjs b/scripts/verify-forge-export.mjs
new file mode 100644
index 000000000..ab65c262f
--- /dev/null
+++ b/scripts/verify-forge-export.mjs
@@ -0,0 +1,72 @@
+// Browser verification for src/forge-export.js — exercises the real /forge
+// page in Chromium: opens the format menu, converts the live GLB to OBJ, STL,
+// PLY and USDZ client-side, and asserts a real download lands for each.
+// Usage: BASE_URL=http://localhost:3013 node scripts/verify-forge-export.mjs
+
+import { chromium } from '@playwright/test';
+
+const BASE_URL = process.env.BASE_URL || 'http://localhost:3013';
+const GLB_PATH = '/accessories/hat-baseball.glb';
+
+const browser = await chromium.launch();
+const page = await browser.newPage();
+const consoleErrors = [];
+page.on('console', (msg) => {
+ if (msg.type() === 'error') consoleErrors.push(msg.text());
+});
+
+await page.goto(`${BASE_URL}/forge`, { waitUntil: 'domcontentloaded' });
+await page.waitForSelector('.export-split .export-caret', { state: 'attached', timeout: 15_000 });
+
+// Stage a finished generation: point the download anchor at a real local GLB
+// and reveal the result panel, exactly the state showResult() leaves behind.
+await page.evaluate((glbPath) => {
+ const download = document.getElementById('download');
+ download.setAttribute('href', glbPath);
+ download.setAttribute('download', 'verify-export.glb');
+ for (const panel of document.querySelectorAll('.panel')) panel.classList.add('is-hidden');
+ document.getElementById('state-result')?.classList.remove('is-hidden');
+}, GLB_PATH);
+await page.waitForSelector('.export-split .export-caret', { timeout: 5_000 });
+
+const results = {};
+for (const format of ['obj', 'stl', 'ply', 'usdz']) {
+ await page.click('.export-caret');
+ await page.waitForSelector('.export-menu.is-open', { timeout: 5_000 });
+ const downloadPromise = page.waitForEvent('download', { timeout: 60_000 });
+ await page.click(`.export-item[data-format="${format}"]`);
+ const dl = await downloadPromise;
+ const filename = dl.suggestedFilename();
+ const stream = await dl.createReadStream();
+ let bytes = 0;
+ for await (const chunk of stream) bytes += chunk.length;
+ results[format] = { filename, bytes };
+ if (!filename.endsWith(`.${format}`) || bytes === 0) {
+ console.error(`FAIL ${format}: filename=${filename} bytes=${bytes}`);
+ process.exit(1);
+ }
+ console.log(`ok ${format}: ${filename} (${bytes} bytes)`);
+ await page.keyboard.press('Escape');
+}
+
+// Keyboard accessibility: caret opens the menu and Escape closes it.
+await page.focus('.export-caret');
+await page.keyboard.press('Enter');
+const opened = await page.$eval('.export-menu', (el) => el.classList.contains('is-open'));
+await page.keyboard.press('Escape');
+const closed = await page.$eval('.export-menu', (el) => !el.classList.contains('is-open'));
+console.log(`keyboard: open=${opened} close=${closed}`);
+
+await page.screenshot({ path: 'reports/forge-export-menu.png' });
+
+const ownErrors = consoleErrors.filter((e) => e.includes('forge-export'));
+if (ownErrors.length) {
+ console.error('console errors from forge-export:', ownErrors);
+ process.exit(1);
+}
+if (!opened || !closed) {
+ console.error('FAIL keyboard interaction');
+ process.exit(1);
+}
+console.log('forge-export verification passed');
+await browser.close();
diff --git a/sdk/CHANGELOG.md b/sdk/CHANGELOG.md
index f6edd792b..8b4e8bf82 100644
--- a/sdk/CHANGELOG.md
+++ b/sdk/CHANGELOG.md
@@ -4,6 +4,15 @@ All notable changes to `@three-ws/sdk` are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.2.0] — 2026-06-12
+
+Packaging metadata release — no API or behavior changes. Public surface is identical to `0.1.0`.
+
+### Changed
+
+- Added `author`, `homepage`, and `repository` fields so the npm listing links back to three.ws and the canonical GitHub repo.
+- Normalized `package.json` formatting (one keyword/optional-dependency per line) to match the repo's Prettier config.
+
## [0.1.0] — 2026-04-14
Initial public release.
diff --git a/src/forge-embed-panel.js b/src/forge-embed-panel.js
index a1666ec97..a546a2cf4 100644
--- a/src/forge-embed-panel.js
+++ b/src/forge-embed-panel.js
@@ -12,90 +12,45 @@
// inline in their own DOM with their own controls.
import { Modal } from './shared/modal.js';
+import {
+ EMBED_SIZES,
+ embedSize,
+ escEmbed as esc,
+ absoluteGlb,
+ embedPageUrl as embedPageUrlFor,
+ embedPreviewUrl,
+ buildIframeSnippet,
+ buildWebComponentSnippet,
+} from './forge-embed-snippets.js';
-const ORIGIN = 'https://three.ws';
const STYLE_ID = 'tws-forge-embed-styles';
-const SIZES = [
- { id: 'wide', label: '16 : 9', w: 640, h: 360, ratio: '16 / 9' },
- { id: 'square', label: 'Square', w: 480, h: 480, ratio: '1 / 1' },
- { id: 'portrait', label: '4 : 5', w: 432, h: 540, ratio: '4 / 5' },
-];
+// Snippet shapes, size presets, and /forge/embed URLs all live in
+// ./forge-embed-snippets.js so the homepage mini Forge embed sheet stays
+// byte-identical. These thin wrappers just bind the module's pure builders to
+// this panel's `state`, keeping every call site below unchanged.
+const SIZES = EMBED_SIZES;
let state = { sizeId: 'wide', tab: 'iframe', glbUrl: '', title: '' };
-function esc(s) {
- return String(s ?? '').replace(
- /[&<>"']/g,
- (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
- );
-}
-
-// Absolute, embeddable URL for the model. Forge's download href is already a
-// public hosted URL; resolve relatives against the prod origin so a copied
-// snippet works off-site.
-function absoluteGlb(url) {
- if (!url) return '';
- try {
- return new URL(url, ORIGIN).href;
- } catch {
- return url;
- }
-}
-
function size() {
- return SIZES.find((s) => s.id === state.sizeId) || SIZES[0];
-}
-
-function embedQuery() {
- const q = new URLSearchParams({ src: state.glbUrl });
- if (state.title) q.set('title', state.title.slice(0, 120));
- return q.toString();
+ return embedSize(state.sizeId);
}
-// Pretty, absolute URL for the copyable snippet + "open standalone" link —
-// resolves via the /forge/embed rewrite in production.
function embedPageUrl() {
- return `${ORIGIN}/forge/embed?${embedQuery()}`;
+ return embedPageUrlFor(state.glbUrl, state.title);
}
-// Same viewer, but at the built file path on the *current* origin, so the
-// in-panel live preview renders in local dev and previews too (the clean
-// /forge/embed route is a production rewrite).
function previewSrc() {
- const origin = typeof location !== 'undefined' ? location.origin : ORIGIN;
- return `${origin}/forge-embed.html?${embedQuery()}`;
+ return embedPreviewUrl(state.glbUrl, state.title);
}
function iframeSnippet() {
- const s = size();
- const src = embedPageUrl();
- return (
- `<iframe src="${esc(src)}"\n` +
- ` width="${s.w}" height="${s.h}"\n` +
- ` style="border:0;border-radius:14px;max-width:100%"\n` +
- ` allow="xr-spatial-tracking; fullscreen"\n` +
- ` loading="lazy" title="${esc(state.title || '3D model forged on three.ws')}">` +
- `</iframe>`
- );
+ return buildIframeSnippet(state.glbUrl, state.title, state.sizeId);
}
function webComponentSnippet() {
- const s = size();
- const alt = esc(state.title || '3D model forged on three.ws');
- return (
- `<!-- once per page -->\n` +
- `<script type="module"\n` +
- ` src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></scr` +
- `ipt>\n\n` +
- `<model-viewer\n` +
- ` src="${esc(state.glbUrl)}"\n` +
- ` alt="${alt}"\n` +
- ` camera-controls auto-rotate ar\n` +
- ` shadow-intensity="1"\n` +
- ` style="width:${s.w}px;height:${s.h}px;max-width:100%;background:#0b0b0b;border-radius:14px">` +
- `\n</model-viewer>`
- );
+ return buildWebComponentSnippet(state.glbUrl, state.title, state.sizeId);
}
function currentSnippet() {
diff --git a/src/forge-embed-snippets.js b/src/forge-embed-snippets.js
new file mode 100644
index 000000000..30f1c215a
--- /dev/null
+++ b/src/forge-embed-snippets.js
@@ -0,0 +1,95 @@
+// Forge embed snippets — the single source of truth for the "embed this model"
+// code the platform hands out. Pure, framework-free builders shared by the full
+// Forge embed modal (src/forge-embed-panel.js) and the homepage mini Forge embed
+// sheet (src/home-forge.js), so the two surfaces never drift on snippet shape,
+// size presets, or the /forge/embed URLs.
+//
+// Two flavours, both real:
+// • iframe — points at /forge/embed?src=<glb>, the zero-dependency
+// three.ws viewer page (orbit + AR + branding). Drops onto
+// any site with no scripts on the host page.
+// • web component — a <model-viewer> snippet for builders who want the model
+// inline in their own DOM with their own controls.
+
+const ORIGIN = 'https://three.ws';
+const MODEL_VIEWER_CDN =
+ 'https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js';
+
+export const EMBED_SIZES = [
+ { id: 'wide', label: '16 : 9', w: 640, h: 360, ratio: '16 / 9' },
+ { id: 'square', label: 'Square', w: 480, h: 480, ratio: '1 / 1' },
+ { id: 'portrait', label: '4 : 5', w: 432, h: 540, ratio: '4 / 5' },
+];
+
+export function embedSize(sizeId) {
+ return EMBED_SIZES.find((s) => s.id === sizeId) || EMBED_SIZES[0];
+}
+
+export function escEmbed(s) {
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+// Forge's download href is already a public hosted URL; resolve relatives
+// against the prod origin so a copied snippet works off-site.
+export function absoluteGlb(url) {
+ if (!url) return '';
+ try {
+ return new URL(url, ORIGIN).href;
+ } catch {
+ return url;
+ }
+}
+
+function embedQuery(glbUrl, title) {
+ const q = new URLSearchParams({ src: glbUrl });
+ if (title) q.set('title', String(title).slice(0, 120));
+ return q.toString();
+}
+
+// Pretty, absolute URL for the copyable snippet + "open standalone" link —
+// resolves via the /forge/embed rewrite in production.
+export function embedPageUrl(glbUrl, title) {
+ return `${ORIGIN}/forge/embed?${embedQuery(glbUrl, title)}`;
+}
+
+// Same viewer at the built file path on the *current* origin, so an in-panel
+// live preview renders in local dev and previews too (the clean /forge/embed
+// route is a production rewrite).
+export function embedPreviewUrl(glbUrl, title, origin) {
+ const o = origin || (typeof location !== 'undefined' ? location.origin : ORIGIN);
+ return `${o}/forge-embed.html?${embedQuery(glbUrl, title)}`;
+}
+
+export function buildIframeSnippet(glbUrl, title, sizeId) {
+ const s = embedSize(sizeId);
+ const src = embedPageUrl(glbUrl, title);
+ return (
+ `<iframe src="${escEmbed(src)}"\n` +
+ ` width="${s.w}" height="${s.h}"\n` +
+ ` style="border:0;border-radius:14px;max-width:100%"\n` +
+ ` allow="xr-spatial-tracking; fullscreen"\n` +
+ ` loading="lazy" title="${escEmbed(title || '3D model forged on three.ws')}">` +
+ `</iframe>`
+ );
+}
+
+export function buildWebComponentSnippet(glbUrl, title, sizeId) {
+ const s = embedSize(sizeId);
+ const alt = escEmbed(title || '3D model forged on three.ws');
+ return (
+ `<!-- once per page -->\n` +
+ `<script type="module"\n` +
+ ` src="${MODEL_VIEWER_CDN}"></scr` +
+ `ipt>\n\n` +
+ `<model-viewer\n` +
+ ` src="${escEmbed(glbUrl)}"\n` +
+ ` alt="${alt}"\n` +
+ ` camera-controls auto-rotate ar\n` +
+ ` shadow-intensity="1"\n` +
+ ` style="width:${s.w}px;height:${s.h}px;max-width:100%;background:#0b0b0b;border-radius:14px">` +
+ `\n</model-viewer>`
+ );
+}
diff --git a/src/forge-export.js b/src/forge-export.js
new file mode 100644
index 000000000..d1dbafd76
--- /dev/null
+++ b/src/forge-export.js
@@ -0,0 +1,303 @@
+// Multi-format export layered onto the forge result viewer.
+//
+// The download button always offers the source GLB instantly. This module adds
+// a format menu beside it that converts the live model in the browser with
+// three.js exporters — no worker, no queue, no upload:
+// • OBJ — universal geometry for DCC tools (geometry + UVs, no materials)
+// • STL — solid geometry for 3D printing (binary)
+// • PLY — vertex data for scanning/point-cloud tools (binary)
+// • USDZ — textured AR asset for iPhone / Vision Pro
+//
+// three.js and the exporters load lazily on first use; the parsed scene is
+// cached per model URL so switching formats doesn't re-download the GLB.
+// Like the stylize/optimize panels, this module injects its own markup and
+// styles and only needs the result panel's download anchor to exist.
+
+const download = document.getElementById('download');
+const resultPanel = document.getElementById('state-result');
+
+if (download && resultPanel) {
+ const FORMATS = [
+ {
+ id: 'glb',
+ label: 'GLB',
+ blurb: 'Source format — textures embedded. Works everywhere glTF does.',
+ ext: 'glb',
+ },
+ {
+ id: 'obj',
+ label: 'OBJ',
+ blurb: 'Universal geometry + UVs for Blender, Maya, C4D. Materials not included.',
+ ext: 'obj',
+ mime: 'text/plain',
+ },
+ {
+ id: 'stl',
+ label: 'STL',
+ blurb: 'Solid geometry for 3D printing and CAD. Binary, compact.',
+ ext: 'stl',
+ mime: 'model/stl',
+ },
+ {
+ id: 'ply',
+ label: 'PLY',
+ blurb: 'Vertex-level data for scanning and point-cloud tools. Binary.',
+ ext: 'ply',
+ mime: 'application/octet-stream',
+ },
+ {
+ id: 'usdz',
+ label: 'USDZ',
+ blurb: 'Textured AR asset — opens directly on iPhone and Vision Pro.',
+ ext: 'usdz',
+ mime: 'model/vnd.usdz+zip',
+ },
+ ];
+
+ // ---- markup ------------------------------------------------------------
+
+ const style = document.createElement('style');
+ style.textContent = `
+ .export-split { position: relative; display: inline-flex; align-items: stretch; }
+ .export-caret {
+ display: inline-flex; align-items: center; justify-content: center;
+ margin-left: 1px; padding: 0 0.55rem;
+ border: 1px solid var(--border, rgba(255,255,255,0.14));
+ border-radius: 0 8px 8px 0; background: var(--surface-2, rgba(255,255,255,0.05));
+ color: inherit; cursor: pointer;
+ transition: background 0.15s ease, border-color 0.15s ease;
+ }
+ .export-caret:hover, .export-caret:focus-visible { background: var(--surface-3, rgba(255,255,255,0.1)); }
+ .export-caret:focus-visible { outline: 2px solid var(--accent, #7c6cff); outline-offset: 2px; }
+ .export-caret svg { width: 12px; height: 12px; transition: transform 0.18s ease; }
+ .export-caret[aria-expanded="true"] svg { transform: rotate(180deg); }
+ .export-split > a { border-top-right-radius: 0 !important; border-bottom-right-radius: 0 !important; }
+ .export-menu {
+ position: absolute; right: 0; bottom: calc(100% + 8px); z-index: 40;
+ min-width: 290px; padding: 0.35rem;
+ border: 1px solid var(--border, rgba(255,255,255,0.14));
+ border-radius: 12px;
+ background: var(--surface-1, #16161d);
+ box-shadow: 0 16px 40px rgba(0,0,0,0.45);
+ opacity: 0; transform: translateY(6px); pointer-events: none;
+ transition: opacity 0.16s ease, transform 0.16s ease;
+ }
+ .export-menu.is-open { opacity: 1; transform: translateY(0); pointer-events: auto; }
+ .export-item {
+ display: flex; align-items: baseline; gap: 0.65rem; width: 100%;
+ padding: 0.55rem 0.7rem; border: 0; border-radius: 8px;
+ background: transparent; color: inherit; text-align: left; cursor: pointer;
+ transition: background 0.12s ease;
+ }
+ .export-item:hover, .export-item:focus-visible { background: var(--surface-3, rgba(255,255,255,0.08)); }
+ .export-item:focus-visible { outline: 2px solid var(--accent, #7c6cff); outline-offset: -2px; }
+ .export-item[aria-disabled="true"] { opacity: 0.55; cursor: progress; }
+ .export-item .fmt { font-weight: 600; font-size: 0.86rem; min-width: 3.2em; letter-spacing: 0.02em; }
+ .export-item .blurb { flex: 1; font-size: 0.78rem; opacity: 0.72; line-height: 1.35; }
+ .export-item .status { font-size: 0.74rem; min-width: 5.5em; text-align: right; opacity: 0.85; }
+ .export-item .status.is-error { color: var(--danger, #ff6b6b); }
+ .export-spinner {
+ display: inline-block; width: 0.85em; height: 0.85em; vertical-align: -0.1em;
+ border: 2px solid currentColor; border-right-color: transparent;
+ border-radius: 50%; animation: export-spin 0.7s linear infinite;
+ }
+ @keyframes export-spin { to { transform: rotate(360deg); } }
+ @media (prefers-reduced-motion: reduce) {
+ .export-menu { transition: none; }
+ .export-caret svg { transition: none; }
+ .export-spinner { animation-duration: 1.5s; }
+ }
+ `;
+ document.head.appendChild(style);
+
+ const split = document.createElement('div');
+ split.className = 'export-split';
+ download.parentNode.insertBefore(split, download);
+ split.appendChild(download);
+
+ const caret = document.createElement('button');
+ caret.type = 'button';
+ caret.className = 'export-caret';
+ caret.setAttribute('aria-haspopup', 'menu');
+ caret.setAttribute('aria-expanded', 'false');
+ caret.setAttribute('aria-label', 'More download formats');
+ caret.title = 'More formats: OBJ, STL, PLY, USDZ';
+ caret.innerHTML =
+ '<svg viewBox="0 0 12 12" fill="none" aria-hidden="true"><path d="M2 4.5 6 8.5 10 4.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';
+ split.appendChild(caret);
+
+ const menu = document.createElement('div');
+ menu.className = 'export-menu';
+ menu.setAttribute('role', 'menu');
+ menu.setAttribute('aria-label', 'Download format');
+ split.appendChild(menu);
+
+ const itemStatus = new Map();
+ for (const f of FORMATS) {
+ const item = document.createElement('button');
+ item.type = 'button';
+ item.className = 'export-item';
+ item.setAttribute('role', 'menuitem');
+ item.dataset.format = f.id;
+ item.innerHTML = `
+ <span class="fmt">.${f.ext}</span>
+ <span class="blurb">${f.blurb}</span>
+ <span class="status" aria-live="polite"></span>
+ `;
+ item.addEventListener('click', () => onPick(f, item));
+ menu.appendChild(item);
+ itemStatus.set(f.id, item.querySelector('.status'));
+ }
+
+ // ---- menu behavior -------------------------------------------------------
+
+ function setOpen(open) {
+ menu.classList.toggle('is-open', open);
+ caret.setAttribute('aria-expanded', String(open));
+ if (open) menu.querySelector('.export-item')?.focus();
+ }
+ const isOpen = () => menu.classList.contains('is-open');
+
+ caret.addEventListener('click', () => setOpen(!isOpen()));
+ document.addEventListener('click', (e) => {
+ if (isOpen() && !split.contains(e.target)) setOpen(false);
+ });
+ split.addEventListener('keydown', (e) => {
+ if (!isOpen()) return;
+ const items = [...menu.querySelectorAll('.export-item')];
+ const idx = items.indexOf(document.activeElement);
+ if (e.key === 'Escape') {
+ setOpen(false);
+ caret.focus();
+ } else if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ items[(idx + 1) % items.length]?.focus();
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ items[(idx - 1 + items.length) % items.length]?.focus();
+ }
+ });
+
+ // ---- conversion ----------------------------------------------------------
+
+ let three = null; // { THREE, GLTFLoader, exporters... } cached after first load
+ async function loadThree() {
+ if (three) return three;
+ const [THREE, gltf, draco, obj, stl, ply, usdz] = await Promise.all([
+ import('three'),
+ import('three/addons/loaders/GLTFLoader.js'),
+ import('three/addons/loaders/DRACOLoader.js'),
+ import('three/addons/exporters/OBJExporter.js'),
+ import('three/addons/exporters/STLExporter.js'),
+ import('three/addons/exporters/PLYExporter.js'),
+ import('three/addons/exporters/USDZExporter.js'),
+ ]);
+ three = {
+ THREE,
+ GLTFLoader: gltf.GLTFLoader,
+ DRACOLoader: draco.DRACOLoader,
+ OBJExporter: obj.OBJExporter,
+ STLExporter: stl.STLExporter,
+ PLYExporter: ply.PLYExporter,
+ USDZExporter: usdz.USDZExporter,
+ };
+ return three;
+ }
+
+ // Parsed-scene cache: one fetch+parse per model URL no matter how many
+ // formats the user exports.
+ let sceneCache = { url: null, scene: null };
+ async function loadScene(url) {
+ if (sceneCache.url === url && sceneCache.scene) return sceneCache.scene;
+ const t = await loadThree();
+ const loader = new t.GLTFLoader();
+ const dracoLoader = new t.DRACOLoader();
+ dracoLoader.setDecoderPath('/three/draco/gltf/');
+ loader.setDRACOLoader(dracoLoader);
+ const gltf = await loader.loadAsync(url);
+ sceneCache = { url, scene: gltf.scene };
+ return gltf.scene;
+ }
+
+ function baseName() {
+ const attr = download.getAttribute('download') || 'forge.glb';
+ return attr.replace(/\.glb$/i, '') || 'forge';
+ }
+
+ function saveBlob(data, mime, filename) {
+ const blob = data instanceof Blob ? data : new Blob([data], { type: mime });
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(blob);
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(a.href), 30_000);
+ }
+
+ async function convert(format, scene) {
+ const t = await loadThree();
+ switch (format.id) {
+ case 'obj':
+ return new t.OBJExporter().parse(scene);
+ case 'stl':
+ return new t.STLExporter().parse(scene, { binary: true });
+ case 'ply':
+ return await new Promise((resolve, reject) => {
+ try {
+ new t.PLYExporter().parse(scene, resolve, { binary: true });
+ } catch (err) {
+ reject(err);
+ }
+ });
+ case 'usdz':
+ return await new t.USDZExporter().parseAsync(scene);
+ default:
+ throw new Error(`unknown export format: ${format.id}`);
+ }
+ }
+
+ const busy = new Set();
+ async function onPick(format, item) {
+ if (format.id === 'glb') {
+ // The source GLB needs no conversion — hand off to the primary anchor.
+ setOpen(false);
+ download.click();
+ return;
+ }
+ if (busy.has(format.id)) return;
+ const url = download.getAttribute('href');
+ if (!url) return;
+ const status = itemStatus.get(format.id);
+ busy.add(format.id);
+ item.setAttribute('aria-disabled', 'true');
+ status.classList.remove('is-error');
+ status.innerHTML = '<span class="export-spinner" aria-hidden="true"></span> converting';
+ try {
+ const scene = await loadScene(url);
+ const data = await convert(format, scene);
+ saveBlob(data, format.mime, `${baseName()}.${format.ext}`);
+ status.textContent = 'saved ✓';
+ setTimeout(() => {
+ if (status.textContent === 'saved ✓') status.textContent = '';
+ }, 4000);
+ } catch (err) {
+ console.error('[forge-export]', format.id, err);
+ status.textContent = 'failed — retry';
+ status.classList.add('is-error');
+ } finally {
+ busy.delete(format.id);
+ item.removeAttribute('aria-disabled');
+ }
+ }
+
+ // A new generation invalidates the parsed-scene cache (the href changes, but
+ // clearing eagerly also frees the old scene graph for GC).
+ document.addEventListener('forge:model-ready', () => {
+ sceneCache = { url: null, scene: null };
+ for (const status of itemStatus.values()) {
+ status.textContent = '';
+ status.classList.remove('is-error');
+ }
+ });
+}
diff --git a/src/forge.js b/src/forge.js
index fddd25848..a97567636 100644
--- a/src/forge.js
+++ b/src/forge.js
@@ -1,6 +1,7 @@
// Forge — text / image / multi-view → 3D generator (browser client).
import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';
import { showSharePanel } from './shared/share.js';
+import { stampGlbAttribution } from './shared/glb-attribution.js';
ensureStateKitStyles();
//
// Drives /api/forge. Three paths share one polling loop:
@@ -509,18 +510,16 @@ function updateEstimate() {
return;
}
const est = (backend.estimates?.[selectedEngine.path] || []).find((e) => e.tier === selectedTier);
+ // Holder-readable, not pipeline-internal: say how long it usually takes and
+ // what the engine does, in plain words. The mechanism ("builds from a
+ // reference image") replaces jargon like "image-intermediate · fast path".
const parts = [`<strong>${tierMeta.label}</strong>`];
- if (est?.eta_seconds) parts.push(`~${est.eta_seconds}s`);
+ if (est?.eta_seconds) parts.push(`usually ~${est.eta_seconds}s`);
if (est && est.credits != null) parts.push(`~${est.credits} credits`);
- if (backend.poly_control) parts.push(`up to ${tierMeta.polycount.toLocaleString()} polys`);
- else parts.push('image-intermediate · no poly target');
- const pathLabel =
- selectedEngine.path === 'geometry'
- ? 'geometry-first'
- : selectedEngine.path === 'sketch'
- ? 'sketch→3D · untextured'
- : 'fast path';
- parts.push(pathLabel);
+ if (backend.poly_control) parts.push(`up to ${tierMeta.polycount.toLocaleString()} polygons`);
+ if (selectedEngine.path === 'geometry') parts.push('shapes geometry straight from the prompt');
+ else if (selectedEngine.path === 'sketch') parts.push('untextured geometry from your sketch');
+ else parts.push('builds from a reference image');
els.estimate.innerHTML = parts.join(' · ');
}
@@ -615,6 +614,30 @@ function slotEl(i) {
return els.viewsGrid.querySelector(`.view-slot[data-index="${i}"]`);
}
+// One pip per possible reference view — filled as photos upload.
+function buildViewsPips() {
+ if (!els.viewsPips || els.viewsPips.childElementCount) return;
+ for (let i = 0; i < MAX_VIEWS; i++) {
+ const pip = document.createElement('i');
+ pip.dataset.filled = 'false';
+ els.viewsPips.appendChild(pip);
+ }
+}
+
+// Live "N of 4 views" readout + pips. Teaches that more views sharpen the mesh,
+// so users don't stop at a single photo thinking it's enough.
+function updateViewsCounter() {
+ if (!els.viewsCounter || !els.viewsCounterText) return;
+ const n = slots.filter((s) => s.state === 'uploaded').length;
+ const pips = els.viewsPips ? els.viewsPips.children : [];
+ for (let i = 0; i < pips.length; i++) pips[i].dataset.filled = String(i < n);
+ let tail;
+ if (n === 0) tail = ' — add a photo to begin';
+ else if (n < MAX_VIEWS) tail = ' · <span class="vc-quality">more views = sharper</span>';
+ else tail = ' · <span class="vc-quality">full coverage</span>';
+ els.viewsCounterText.innerHTML = `<strong>${n}</strong> of ${MAX_VIEWS} views${tail}`;
+}
+
function renderSlot(i) {
const el = slotEl(i);
if (!el) return;
@@ -624,6 +647,7 @@ function renderSlot(i) {
// Slot changes flip the input mode (prompt-only ↔ photo), which changes
// which engines may serve — keep the selector honest in the same frame.
updateEngineAvailability();
+ updateViewsCounter();
const img = el.querySelector('.vs-thumb');
if (s.objectUrl) {
@@ -1004,6 +1028,74 @@ function resetVerdict() {
}
}
+// Poster capture — the visual half of every creation card. Image-intermediate
+// engines store their flux reference image as the preview, but geometry-first
+// and sketch lanes paint no image at all, so their gallery/showcase cards used
+// to render as glyph placeholders. Once the finished mesh is standing in the
+// viewer, render it onto a small studio-backdrop canvas and attach it to the
+// creation row (POST /api/forge-poster — fill-only, owner-scoped, best-effort).
+const POSTER_MAX_DIM = 640;
+const postedPosters = new Set();
+
+function renderPosterFrame(sourceDataUrl) {
+ return new Promise((resolve) => {
+ const img = new Image();
+ img.onload = () => {
+ const scale = Math.min(1, POSTER_MAX_DIM / Math.max(img.width, img.height, 1));
+ const w = Math.max(1, Math.round(img.width * scale));
+ const h = Math.max(1, Math.round(img.height * scale));
+ const canvas = document.createElement('canvas');
+ canvas.width = w;
+ canvas.height = h;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return resolve(null);
+ // Same studio backdrop as the live viewer, so mesh posters read as a
+ // consistent set next to flux reference images in the galleries.
+ const backdrop = ctx.createRadialGradient(w / 2, 0, 0, w / 2, 0, Math.max(w, h) * 1.2);
+ backdrop.addColorStop(0, '#1a1612');
+ backdrop.addColorStop(0.7, '#0b0a09');
+ backdrop.addColorStop(1, '#0b0a09');
+ ctx.fillStyle = backdrop;
+ ctx.fillRect(0, 0, w, h);
+ ctx.drawImage(img, 0, 0, w, h);
+ const webp = canvas.toDataURL('image/webp', 0.85);
+ // Browsers without webp encoding silently hand back PNG — send what we got.
+ resolve(webp.startsWith('data:image/webp') ? webp : canvas.toDataURL('image/png'));
+ };
+ img.onerror = () => resolve(null);
+ img.src = sourceDataUrl;
+ });
+}
+
+async function capturePoster(creationId) {
+ if (!creationId || postedPosters.has(creationId) || !els.viewer?.toDataURL) return;
+ postedPosters.add(creationId);
+ try {
+ if (!els.viewer.loaded) {
+ await new Promise((resolve) =>
+ els.viewer.addEventListener('load', resolve, { once: true }),
+ );
+ }
+ // Let the materialize entrance settle so the capture is a steady frame.
+ await sleep(REDUCED_MOTION ? 300 : 1500);
+ // A newer generation or an opened creation replaced the model — skip.
+ if (currentCreationId !== creationId) return;
+ const frame = await renderPosterFrame(els.viewer.toDataURL('image/png'));
+ if (!frame) return;
+ const res = await fetch('/api/forge-poster', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
+ body: JSON.stringify({ creation_id: creationId, image: frame }),
+ });
+ const data = await res.json().catch(() => ({}));
+ // The card for this creation is already on screen with a placeholder —
+ // refresh the strip so the new poster shows without a reload.
+ if (data?.stored) loadGallery();
+ } catch {
+ // Best-effort: a missed poster never disturbs the result flow.
+ }
+}
+
// Render the provenance badge from job metadata: how the mesh was produced
// (engine + tier + path) plus any multi-view conditioning. Shows whatever is
// known — the geometry-first path has no reference views, the image path does.
@@ -1367,6 +1459,11 @@ async function run(cfg) {
path: done.path ?? job.path,
});
loadGallery();
+ // Geometry-first and sketch lanes have no reference image — render the
+ // finished mesh itself as the creation's card visual.
+ if (!(done.preview_image_url ?? job.preview_image_url)) {
+ capturePoster(currentCreationId);
+ }
} catch (err) {
if (pollAbort) return;
if (err.kind === 'unconfigured') {
@@ -1435,6 +1532,10 @@ function submit() {
}
const prompt = els.sketchPrompt.value.trim();
if (prompt.length < 3) {
+ // Make the required-input contract unmissable: flag the field and tint
+ // the "Required" tag until the user types a description.
+ els.sketchPrompt.setAttribute('aria-invalid', 'true');
+ if (els.sketchReqTag) els.sketchReqTag.dataset.missing = 'true';
els.sketchPrompt.focus();
return;
}
@@ -1464,6 +1565,8 @@ function submit() {
// Wiring ----------------------------------------------------------------------
buildSlots();
+buildViewsPips();
+updateViewsCounter();
els.modeSwitch.addEventListener('click', (e) => {
const btn = e.target.closest('button[data-mode]');
@@ -1492,6 +1595,12 @@ els.prompt.addEventListener('keydown', submitOnModifierEnter);
els.imagePrompt.addEventListener('keydown', submitOnModifierEnter);
els.sketchPrompt?.addEventListener('keydown', submitOnModifierEnter);
+// Typing into the sketch prompt clears the "required" warning state.
+els.sketchPrompt?.addEventListener('input', () => {
+ els.sketchPrompt.removeAttribute('aria-invalid');
+ if (els.sketchReqTag) els.sketchReqTag.dataset.missing = 'false';
+});
+
els.sketchFileInput?.addEventListener('change', () => {
const file = els.sketchFileInput.files?.[0];
if (file) uploadSketch(file);
@@ -1589,8 +1698,37 @@ if (els.verdict) {
});
}
-els.download.addEventListener('click', () => {
+// Downloads route through a provenance pass: fetch the GLB, stamp
+// asset.generator + asset.extras (source, prompt) into the JSON chunk, and
+// hand the user the stamped file. Any failure falls back to the raw provider
+// file — stamping must never block a download.
+els.download.addEventListener('click', async (e) => {
sendFeedback({ downloaded: true });
+ const glbUrl = els.download.href;
+ if (!glbUrl || glbUrl.startsWith('blob:') || els.download.dataset.stamping) return;
+ e.preventDefault();
+ els.download.dataset.stamping = '1';
+ const filename = els.download.getAttribute('download') || 'forge.glb';
+ try {
+ const res = await fetch(glbUrl);
+ if (!res.ok) throw new Error(`fetch ${res.status}`);
+ const stamped = stampGlbAttribution(await res.arrayBuffer(), {
+ prompt: els.resultLabel?.textContent || '',
+ });
+ const blobUrl = URL.createObjectURL(new Blob([stamped], { type: 'model/gltf-binary' }));
+ const a = document.createElement('a');
+ a.href = blobUrl;
+ a.download = filename;
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(blobUrl), 30_000);
+ } catch {
+ const a = document.createElement('a');
+ a.href = glbUrl;
+ a.download = filename;
+ a.click();
+ } finally {
+ delete els.download.dataset.stamping;
+ }
});
els.cinema?.addEventListener('click', () => setCinema(!cinemaOn));
@@ -1600,11 +1738,18 @@ document.addEventListener('keydown', (e) => {
setCinema(false);
return;
}
- if (e.key !== 'f' && e.key !== 'F') return;
if (e.metaKey || e.ctrlKey || e.altKey) return;
const active = document.activeElement;
if (active?.tagName === 'INPUT' || active?.tagName === 'TEXTAREA' || active?.isContentEditable)
return;
+ // "/" jumps to the prompt for the current mode — the standard quick-focus.
+ if (e.key === '/') {
+ e.preventDefault();
+ const box = mode === 'sketch' ? els.sketchPrompt : mode === 'image' ? els.imagePrompt : els.prompt;
+ box?.focus();
+ return;
+ }
+ if (e.key !== 'f' && e.key !== 'F') return;
if (els.states.result.classList.contains('is-hidden')) return;
e.preventDefault();
setCinema(!cinemaOn);
diff --git a/src/home-forge.js b/src/home-forge.js
index 97adcabcb..390ac21ca 100644
--- a/src/home-forge.js
+++ b/src/home-forge.js
@@ -18,6 +18,15 @@
// into Scene Studio, a shareable link, a same-prompt variation, or download.
// All motion respects prefers-reduced-motion.
+import {
+ absoluteGlb,
+ buildIframeSnippet,
+ buildWebComponentSnippet,
+ embedPageUrl,
+ embedPreviewUrl,
+ embedSize,
+} from './forge-embed-snippets.js';
+
const POLL_INTERVAL_MS = 2500;
const MAX_POLL_MS = 5 * 60 * 1000;
const MODEL_VIEWER_SRC =
@@ -64,6 +73,17 @@ const els = root && {
history: root.querySelector('[data-hf-history]'),
historyTrack: root.querySelector('[data-hf-history-track]'),
toast: root.querySelector('[data-hf-toast]'),
+ embedOpen: root.querySelector('[data-hf-embed-open]'),
+ embed: root.querySelector('[data-hf-embed]'),
+ embedFrame: root.querySelector('[data-hf-embed-frame]'),
+ embedPreview: root.querySelector('[data-hf-embed-preview]'),
+ embedTabs: root.querySelector('[data-hf-embed-tabs]'),
+ embedSizes: root.querySelector('[data-hf-embed-sizes]'),
+ embedCode: root.querySelector('[data-hf-embed-code]'),
+ embedCopy: root.querySelector('[data-hf-embed-copy]'),
+ embedCopyLabel: root.querySelector('[data-hf-embed-copy-label]'),
+ embedStandalone: root.querySelector('[data-hf-embed-standalone]'),
+ embedCloseEls: root ? Array.from(root.querySelectorAll('[data-hf-embed-close]')) : [],
};
// Same anonymous handle as src/forge.js — keep the storage key in sync so the
@@ -97,6 +117,9 @@ let modelViewerReady = null;
let currentViewer = null; // the live <model-viewer> on stage
let currentGlbUrl = ''; // what the toolbar acts on
let toastTimer = null;
+let embedCopyTimer = null;
+let embedTrigger = null; // element to restore focus to when the embed sheet closes
+const embedState = { tab: 'iframe', sizeId: 'wide' };
// Monotonic run token: cancel-then-regenerate must not let the first run's
// poll loop wake up and fight the new one over the shared stage.
let runSeq = 0;
@@ -426,6 +449,7 @@ function showResult(glbUrl, prompt, { fromHistory = false } = {}) {
async function run(prompt) {
if (busy) return;
+ closeEmbed();
lastPrompt = prompt;
pollAbort = false;
const seq = ++runSeq;
@@ -480,6 +504,7 @@ function reset() {
pollAbort = true;
stopElapsed();
setBusy(false);
+ closeEmbed();
currentGlbUrl = '';
currentViewer = null;
markActiveThumb();
@@ -598,6 +623,107 @@ function toggleAutoRotate() {
els.spin.title = on ? 'Resume auto-rotate' : 'Pause auto-rotate';
}
+// ── Embed sheet ────────────────────────────────────────────────────
+// Drop the forged model on any site. Snippet shapes, size presets, and the
+// /forge/embed URLs are shared with the full Forge embed modal via
+// ./forge-embed-snippets.js, so the two surfaces never drift.
+
+function currentEmbedSnippet(glb) {
+ return embedState.tab === 'iframe'
+ ? buildIframeSnippet(glb, lastPrompt, embedState.sizeId)
+ : buildWebComponentSnippet(glb, lastPrompt, embedState.sizeId);
+}
+
+function renderEmbed() {
+ if (!els.embed) return;
+ const glb = absoluteGlb(currentGlbUrl);
+ if (!glb) return;
+ els.embedCode.value = currentEmbedSnippet(glb);
+ if (els.embedPreview) els.embedPreview.style.aspectRatio = embedSize(embedState.sizeId).ratio;
+ if (els.embedStandalone) els.embedStandalone.href = embedPageUrl(glb, lastPrompt);
+ for (const b of els.embedTabs.querySelectorAll('[data-hf-embed-tab]')) {
+ b.setAttribute('aria-pressed', String(b.dataset.hfEmbedTab === embedState.tab));
+ }
+ for (const b of els.embedSizes.querySelectorAll('[data-hf-embed-size]')) {
+ b.setAttribute('aria-pressed', String(b.dataset.hfEmbedSize === embedState.sizeId));
+ }
+}
+
+function openEmbed() {
+ if (!els.embed || !currentGlbUrl) return;
+ const glb = absoluteGlb(currentGlbUrl);
+ embedTrigger = document.activeElement;
+ // Point the live preview at the real embed viewer so what you see is what
+ // ships. Set once on open; size changes only restyle the frame's aspect box.
+ els.embedFrame.src = embedPreviewUrl(glb, lastPrompt);
+ renderEmbed();
+ els.embed.hidden = false;
+ document.addEventListener('keydown', onEmbedKeydown, true);
+ // Focus the first control so the sheet is operable from the keyboard.
+ const first = els.embed.querySelector('[data-hf-embed-close], button, [href], textarea');
+ if (first) first.focus();
+}
+
+function closeEmbed() {
+ if (!els.embed || els.embed.hidden) return;
+ els.embed.hidden = true;
+ els.embedFrame.removeAttribute('src'); // release the preview's WebGL context
+ document.removeEventListener('keydown', onEmbedKeydown, true);
+ if (embedTrigger && typeof embedTrigger.focus === 'function') embedTrigger.focus();
+ embedTrigger = null;
+}
+
+function onEmbedKeydown(e) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ closeEmbed();
+ }
+}
+
+async function copyEmbedCode() {
+ const text = els.embedCode.value;
+ if (!text) return;
+ const label = els.embedCopyLabel;
+ const original = label ? label.textContent : '';
+ let ok = true;
+ try {
+ if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(text);
+ else {
+ els.embedCode.focus();
+ els.embedCode.select();
+ ok = document.execCommand('copy');
+ }
+ } catch {
+ ok = false;
+ }
+ els.embedCopy.classList.toggle('is-copied', ok);
+ if (label) label.textContent = ok ? 'Copied ✓' : 'Press ⌘/Ctrl-C to copy';
+ clearTimeout(embedCopyTimer);
+ embedCopyTimer = setTimeout(() => {
+ els.embedCopy.classList.remove('is-copied');
+ if (label) label.textContent = original;
+ }, 2200);
+}
+
+function wireEmbed() {
+ if (!els.embed || !els.embedOpen) return;
+ els.embedOpen.addEventListener('click', openEmbed);
+ for (const el of els.embedCloseEls) el.addEventListener('click', closeEmbed);
+ els.embedTabs.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-hf-embed-tab]');
+ if (!btn) return;
+ embedState.tab = btn.dataset.hfEmbedTab;
+ renderEmbed();
+ });
+ els.embedSizes.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-hf-embed-size]');
+ if (!btn) return;
+ embedState.sizeId = btn.dataset.hfEmbedSize;
+ renderEmbed();
+ });
+ els.embedCopy.addEventListener('click', copyEmbedCode);
+}
+
function boot() {
els.form.addEventListener('submit', (e) => {
e.preventDefault();
@@ -651,6 +777,7 @@ function boot() {
if (lastPrompt && !busy) run(lastPrompt);
});
+ wireEmbed();
renderHistory();
startTypewriter();
startParallax();
diff --git a/src/pump/mcp-tools.js b/src/pump/mcp-tools.js
index 988709121..46626ce76 100644
--- a/src/pump/mcp-tools.js
+++ b/src/pump/mcp-tools.js
@@ -41,20 +41,50 @@ const LOCAL_GENERATIVE = Object.freeze({
openWorldHint: false,
});
+// Canonical (snake_case) tool name ← legacy (camelCase) alias. tools/list only
+// ever advertises the canonical names; tools/call accepts BOTH forever. This
+// map is the single source of truth for that aliasing — the Vercel handler,
+// the Cloudflare Worker, and the npm bridge all resolve through it (the bridge
+// ships a vendored copy in packages/pumpfun-mcp/src/tools.js).
+export const TOOL_NAME_ALIASES = Object.freeze({
+ searchTokens: 'search_tokens',
+ getTokenDetails: 'get_token_details',
+ getBondingCurve: 'get_bonding_curve',
+ getTokenTrades: 'get_token_trades',
+ getTrendingTokens: 'get_trending_tokens',
+ getNewTokens: 'get_new_tokens',
+ getGraduatedTokens: 'get_graduated_tokens',
+ getKingOfTheHill: 'get_king_of_the_hill',
+ getCreatorProfile: 'get_creator_profile',
+ getTokenHolders: 'get_token_holders',
+});
+
+// Resolve a tools/call name to its canonical form. Unknown names pass through
+// unchanged so the dispatcher's own unknown-tool error still fires. hasOwn
+// guard: "__proto__"/"constructor" must not resolve an inherited member.
+export function resolveToolName(name) {
+ if (typeof name === 'string' && Object.hasOwn(TOOL_NAME_ALIASES, name)) {
+ return TOOL_NAME_ALIASES[name];
+ }
+ return name;
+}
+
// name → { title, ...ToolAnnotations }. Applied onto TOOLS below; exported so
// runtimes (and the npm bridge) can overlay the same map on older tool lists.
+// Keys are the canonical snake_case names — overlay callers resolve legacy
+// names through TOOL_NAME_ALIASES first.
export const TOOL_ANNOTATIONS = Object.freeze({
- searchTokens: { title: 'Search Tokens', ...LIVE_READ },
- getTokenDetails: { title: 'Token Details', ...LIVE_READ },
- getBondingCurve: { title: 'Bonding Curve', ...LIVE_READ },
- getTokenTrades: { title: 'Token Trades', ...LIVE_READ },
- getTrendingTokens: { title: 'Trending Tokens', ...LIVE_READ },
- getNewTokens: { title: 'New Tokens', ...LIVE_READ },
- getGraduatedTokens: { title: 'Graduated Tokens', ...LIVE_READ },
- getKingOfTheHill: { title: 'King of the Hill', ...LIVE_READ },
+ search_tokens: { title: 'Search Tokens', ...LIVE_READ },
+ get_token_details: { title: 'Token Details', ...LIVE_READ },
+ get_bonding_curve: { title: 'Bonding Curve', ...LIVE_READ },
+ get_token_trades: { title: 'Token Trades', ...LIVE_READ },
+ get_trending_tokens: { title: 'Trending Tokens', ...LIVE_READ },
+ get_new_tokens: { title: 'New Tokens', ...LIVE_READ },
+ get_graduated_tokens: { title: 'Graduated Tokens', ...LIVE_READ },
+ get_king_of_the_hill: { title: 'King of the Hill', ...LIVE_READ },
kol_radar: { title: 'KOL Radar', ...LIVE_READ },
- getCreatorProfile: { title: 'Creator Profile', ...LIVE_READ },
- getTokenHolders: { title: 'Token Holders', ...LIVE_READ },
+ get_creator_profile: { title: 'Creator Profile', ...LIVE_READ },
+ get_token_holders: { title: 'Token Holders', ...LIVE_READ },
pumpfun_vanity_mint: { title: 'Vanity Mint Keypair', ...LOCAL_GENERATIVE },
pumpfun_watch_whales: { title: 'Watch Whale Trades', ...LIVE_READ },
pumpfun_list_claims: { title: 'List Creator Fee Claims', ...LIVE_READ },
@@ -68,9 +98,19 @@ export const TOOL_ANNOTATIONS = Object.freeze({
social_x_post_impact: { title: 'X Post Price Impact', ...LIVE_READ },
});
+// outputSchema policy: only tools whose response shape is code-controlled and
+// genuinely stable advertise one (sns_resolve, sns_reverseLookup,
+// social_cashtag_sentiment, pumpfun_vanity_mint, pumpfun_quote_swap,
+// get_bonding_curve). Indexer/upstream-shaped passthroughs (search_tokens,
+// get_token_details, get_token_trades, get_trending_tokens, get_new_tokens,
+// get_graduated_tokens, get_king_of_the_hill, get_creator_profile,
+// get_token_holders, kol_*, pumpfun_*_claims, pumpfun_watch_whales,
+// social_x_post_impact) deliberately ship NO outputSchema — their payloads
+// mirror upstream feeds / multi-source on-chain decoders that can evolve, and
+// a wrong schema is worse than none.
export const TOOLS = [
{
- name: 'searchTokens',
+ name: 'search_tokens',
description: 'Search pump.fun tokens by name, symbol, or mint address.',
inputSchema: {
type: 'object',
@@ -82,7 +122,7 @@ export const TOOLS = [
},
},
{
- name: 'getTokenDetails',
+ name: 'get_token_details',
description: 'Full details for a specific pump.fun token by mint address.',
inputSchema: {
type: 'object',
@@ -91,7 +131,7 @@ export const TOOLS = [
},
},
{
- name: 'getBondingCurve',
+ name: 'get_bonding_curve',
description:
'Bonding curve analysis: real reserves, virtual reserves, and graduation progress (on-chain).',
inputSchema: {
@@ -102,9 +142,33 @@ export const TOOLS = [
},
required: ['mint'],
},
+ outputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ network: { type: 'string' },
+ complete: { type: 'boolean', description: 'true once the curve has graduated' },
+ graduationPercent: { type: 'number', description: '0–100 graduation progress' },
+ solReserves: { type: 'string', description: 'Real SOL reserves in SOL (4-decimal string)' },
+ tokenReserves: { type: 'string', description: 'Real token reserves (raw base units)' },
+ virtualSolReserves: { type: 'string', description: 'Virtual SOL reserves (lamports)' },
+ virtualTokenReserves: { type: 'string', description: 'Virtual token reserves (raw base units)' },
+ },
+ required: [
+ 'mint',
+ 'network',
+ 'complete',
+ 'graduationPercent',
+ 'solReserves',
+ 'tokenReserves',
+ 'virtualSolReserves',
+ 'virtualTokenReserves',
+ ],
+ additionalProperties: true,
+ },
},
{
- name: 'getTokenTrades',
+ name: 'get_token_trades',
description: 'Recent buy/sell history for a token.',
inputSchema: {
type: 'object',
@@ -116,7 +180,7 @@ export const TOOLS = [
},
},
{
- name: 'getTrendingTokens',
+ name: 'get_trending_tokens',
description: 'Top pump.fun tokens by market cap.',
inputSchema: {
type: 'object',
@@ -124,7 +188,7 @@ export const TOOLS = [
},
},
{
- name: 'getNewTokens',
+ name: 'get_new_tokens',
description: 'Most recently launched pump.fun tokens.',
inputSchema: {
type: 'object',
@@ -132,7 +196,7 @@ export const TOOLS = [
},
},
{
- name: 'getGraduatedTokens',
+ name: 'get_graduated_tokens',
description: 'Tokens that graduated from the bonding curve to Raydium AMM.',
inputSchema: {
type: 'object',
@@ -140,7 +204,7 @@ export const TOOLS = [
},
},
{
- name: 'getKingOfTheHill',
+ name: 'get_king_of_the_hill',
description: 'Highest-market-cap token still on the bonding curve.',
inputSchema: { type: 'object', properties: {} },
},
@@ -161,7 +225,7 @@ export const TOOLS = [
},
},
{
- name: 'getCreatorProfile',
+ name: 'get_creator_profile',
description: 'All tokens by a creator wallet, with rug-pull risk flags.',
inputSchema: {
type: 'object',
@@ -170,7 +234,7 @@ export const TOOLS = [
},
},
{
- name: 'getTokenHolders',
+ name: 'get_token_holders',
description: 'Top holders of a token with concentration analysis (on-chain).',
inputSchema: {
type: 'object',
@@ -195,6 +259,17 @@ export const TOOLS = [
maxAttempts: { type: 'integer', default: 5000000 },
},
},
+ outputSchema: {
+ type: 'object',
+ properties: {
+ publicKey: { type: 'string', description: 'Matched Solana address (base58)' },
+ secretKey: { type: 'string', description: 'Secret key (base58) — caller is sole custodian' },
+ attempts: { type: 'integer', description: 'Keypairs ground before the match' },
+ ms: { type: 'number', description: 'Wall-clock grind time in milliseconds' },
+ },
+ required: ['publicKey', 'secretKey', 'attempts', 'ms'],
+ additionalProperties: true,
+ },
},
{
name: 'pumpfun_watch_whales',
@@ -272,6 +347,15 @@ export const TOOLS = [
},
required: ['name'],
},
+ outputSchema: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'The .sol domain that was resolved' },
+ address: { type: 'string', description: 'Owner wallet address (base58)' },
+ },
+ required: ['name', 'address'],
+ additionalProperties: true,
+ },
},
{
name: 'sns_reverseLookup',
@@ -283,6 +367,15 @@ export const TOOLS = [
},
required: ['address'],
},
+ outputSchema: {
+ type: 'object',
+ properties: {
+ address: { type: 'string', description: 'The wallet address that was looked up' },
+ name: { type: 'string', description: 'Primary .sol domain for the address' },
+ },
+ required: ['address', 'name'],
+ additionalProperties: true,
+ },
},
{
name: 'social_cashtag_sentiment',
@@ -308,6 +401,27 @@ export const TOOLS = [
},
required: ['posts'],
},
+ outputSchema: {
+ type: 'object',
+ properties: {
+ score: { type: 'number', description: 'Net sentiment, -1 (bearish) to 1 (bullish)' },
+ posPct: { type: 'number', description: 'Percentage of positive posts (0–100)' },
+ negPct: { type: 'number', description: 'Percentage of negative posts (0–100)' },
+ neuPct: { type: 'number', description: 'Percentage of neutral posts (0–100)' },
+ count: { type: 'integer', description: 'Number of posts scored' },
+ examples: {
+ type: 'object',
+ properties: {
+ pos: { type: 'array', items: { type: 'string' } },
+ neg: { type: 'array', items: { type: 'string' } },
+ },
+ required: ['pos', 'neg'],
+ additionalProperties: true,
+ },
+ },
+ required: ['score', 'posPct', 'negPct', 'neuPct', 'count', 'examples'],
+ additionalProperties: true,
+ },
},
{
name: 'kol_leaderboard',
@@ -336,6 +450,17 @@ export const TOOLS = [
},
required: ['inputMint', 'outputMint', 'amountIn'],
},
+ outputSchema: {
+ type: 'object',
+ properties: {
+ amountOut: { type: 'string', description: 'Expected output amount in raw base units' },
+ priceImpactBps: { type: 'number', description: 'Price impact in basis points' },
+ route: { type: 'string', description: 'AMM pool address the quote routes through (base58)' },
+ expiresAtMs: { type: 'number', description: 'Epoch ms after which the quote is stale' },
+ },
+ required: ['amountOut', 'priceImpactBps', 'route', 'expiresAtMs'],
+ additionalProperties: true,
+ },
},
{
name: 'social_x_post_impact',
diff --git a/src/shared/glb-attribution.js b/src/shared/glb-attribution.js
new file mode 100644
index 000000000..b9efd07a3
--- /dev/null
+++ b/src/shared/glb-attribution.js
@@ -0,0 +1,68 @@
+/**
+ * Stamp provenance into a binary glTF (.glb) container without touching
+ * geometry: rewrites the JSON chunk's `asset.generator` and `asset.extras`,
+ * then repacks the container with correct chunk padding and total length.
+ *
+ * The glTF 2.0 spec reserves `asset.generator` for "the tool that generated
+ * this asset" and `asset.extras` for application-specific metadata — so a
+ * Forge model keeps saying where it came from (and what prompt made it) in
+ * any DCC tool, engine, or validator that opens it.
+ */
+
+const GLB_MAGIC = 0x46546c67; // 'glTF'
+const CHUNK_JSON = 0x4e4f534a; // 'JSON'
+
+export const FORGE_GENERATOR = 'three.ws Forge — text/image → 3D (https://three.ws/forge)';
+
+/**
+ * @param {ArrayBuffer} buffer A complete .glb file.
+ * @param {{ prompt?: string, source?: string }} [meta]
+ * @returns {ArrayBuffer} A new .glb with attribution stamped into asset.*.
+ * @throws {Error} If the buffer is not a well-formed glTF 2.0 binary.
+ */
+export function stampGlbAttribution(buffer, { prompt, source = 'https://three.ws/forge' } = {}) {
+ const dv = new DataView(buffer);
+ if (buffer.byteLength < 20 || dv.getUint32(0, true) !== GLB_MAGIC) {
+ throw new Error('not a GLB container');
+ }
+ const version = dv.getUint32(4, true);
+ if (version !== 2) throw new Error(`unsupported glTF container version ${version}`);
+ const jsonLen = dv.getUint32(12, true);
+ if (20 + jsonLen > buffer.byteLength || dv.getUint32(16, true) !== CHUNK_JSON) {
+ throw new Error('first GLB chunk is not a valid JSON chunk');
+ }
+
+ const json = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 20, jsonLen)));
+ json.asset = json.asset || { version: '2.0' };
+ const extras = { ...(json.asset.extras || {}) };
+ // Keep the upstream reconstruction engine visible instead of erasing it.
+ if (json.asset.generator && !String(json.asset.generator).includes('three.ws')) {
+ extras.pipeline = json.asset.generator;
+ }
+ json.asset.generator = FORGE_GENERATOR;
+ extras.source = source;
+ if (prompt) extras.prompt = String(prompt).slice(0, 500);
+ json.asset.extras = extras;
+
+ // Re-encode and pad to the 4-byte boundary the spec requires (0x20 for JSON).
+ const encoded = new TextEncoder().encode(JSON.stringify(json));
+ const pad = (4 - (encoded.byteLength % 4)) % 4;
+ const outJson = new Uint8Array(encoded.byteLength + pad);
+ outJson.set(encoded);
+ outJson.fill(0x20, encoded.byteLength);
+
+ // Everything after the original JSON chunk (the BIN chunk, if any) is
+ // byte-for-byte untouched.
+ const rest = new Uint8Array(buffer, 20 + jsonLen);
+ const total = 12 + 8 + outJson.byteLength + rest.byteLength;
+ const out = new Uint8Array(total);
+ const outDv = new DataView(out.buffer);
+ outDv.setUint32(0, GLB_MAGIC, true);
+ outDv.setUint32(4, 2, true);
+ outDv.setUint32(8, total, true);
+ outDv.setUint32(12, outJson.byteLength, true);
+ outDv.setUint32(16, CHUNK_JSON, true);
+ out.set(outJson, 20);
+ out.set(rest, 20 + outJson.byteLength);
+ return out.buffer;
+}
diff --git a/tests/api/mcp-3d-challenge.test.js b/tests/api/mcp-3d-challenge.test.js
index b98717962..9488362c6 100644
--- a/tests/api/mcp-3d-challenge.test.js
+++ b/tests/api/mcp-3d-challenge.test.js
@@ -49,6 +49,8 @@ vi.mock('../../api/_mcp3d/text-to-image.js', () => ({
}));
const { default: handler } = await import('../../api/mcp-3d.js');
+const { studioX402Amount } = await import('../../api/_mcp3d/pricing.js');
+const { isDiscoveryOnlyBatch } = await import('../../api/_lib/mcp-batch-price.js');
function makeRes() {
return {
@@ -78,11 +80,17 @@ function makeReq({ method = 'POST', headers = {}, body = null } = {}) {
}
const TOOLS_LIST = { jsonrpc: '2.0', id: 1, method: 'tools/list' };
+const textTo3dCall = (args = { prompt: 'a small clay fox sitting upright' }) => ({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'text_to_3d', arguments: args },
+});
describe('POST /api/mcp-3d — unauthenticated challenge identity', () => {
it('plain x402 clients get a 402 naming the 3D Studio resource', async () => {
const res = makeRes();
- await handler(makeReq({ body: TOOLS_LIST }), res);
+ await handler(makeReq({ body: textTo3dCall() }), res);
expect(res.statusCode).toBe(402);
const challenge = JSON.parse(res.body);
expect(challenge.resource.url).toBe('https://three.ws/api/mcp-3d');
@@ -96,7 +104,7 @@ describe('POST /api/mcp-3d — unauthenticated challenge identity', () => {
it('bazaar discovery example calls text_to_3d, not a main-server tool', async () => {
const res = makeRes();
- await handler(makeReq({ body: TOOLS_LIST }), res);
+ await handler(makeReq({ body: textTo3dCall() }), res);
const { extensions } = JSON.parse(res.body);
expect(extensions.bazaar.discoverable).toBe(true);
expect(extensions.bazaar.info.input.body.params.name).toBe('text_to_3d');
@@ -106,7 +114,10 @@ describe('POST /api/mcp-3d — unauthenticated challenge identity', () => {
it('MCP protocol clients get a 401 with the same studio envelope', async () => {
const res = makeRes();
await handler(
- makeReq({ body: TOOLS_LIST, headers: { accept: 'application/json, text/event-stream' } }),
+ makeReq({
+ body: textTo3dCall(),
+ headers: { accept: 'application/json, text/event-stream' },
+ }),
res,
);
expect(res.statusCode).toBe(401);
diff --git a/tests/glb-attribution.test.js b/tests/glb-attribution.test.js
new file mode 100644
index 000000000..77bec68d0
--- /dev/null
+++ b/tests/glb-attribution.test.js
@@ -0,0 +1,93 @@
+import { describe, it, expect } from 'vitest';
+import { stampGlbAttribution, FORGE_GENERATOR } from '../src/shared/glb-attribution.js';
+
+const GLB_MAGIC = 0x46546c67;
+const CHUNK_JSON = 0x4e4f534a;
+const CHUNK_BIN = 0x004e4942;
+
+/** Build a minimal valid GLB from a gltf JSON object and optional BIN bytes. */
+function buildGlb(gltf, bin = null) {
+ const encoded = new TextEncoder().encode(JSON.stringify(gltf));
+ const jsonPad = (4 - (encoded.byteLength % 4)) % 4;
+ const jsonChunk = new Uint8Array(encoded.byteLength + jsonPad);
+ jsonChunk.set(encoded);
+ jsonChunk.fill(0x20, encoded.byteLength);
+
+ let binChunk = null;
+ if (bin) {
+ const binPad = (4 - (bin.byteLength % 4)) % 4;
+ binChunk = new Uint8Array(bin.byteLength + binPad);
+ binChunk.set(bin);
+ }
+
+ const total = 12 + 8 + jsonChunk.byteLength + (binChunk ? 8 + binChunk.byteLength : 0);
+ const out = new Uint8Array(total);
+ const dv = new DataView(out.buffer);
+ dv.setUint32(0, GLB_MAGIC, true);
+ dv.setUint32(4, 2, true);
+ dv.setUint32(8, total, true);
+ dv.setUint32(12, jsonChunk.byteLength, true);
+ dv.setUint32(16, CHUNK_JSON, true);
+ out.set(jsonChunk, 20);
+ if (binChunk) {
+ const off = 20 + jsonChunk.byteLength;
+ dv.setUint32(off, binChunk.byteLength, true);
+ dv.setUint32(off + 4, CHUNK_BIN, true);
+ out.set(binChunk, off + 8);
+ }
+ return out.buffer;
+}
+
+function parseGlb(buffer) {
+ const dv = new DataView(buffer);
+ const jsonLen = dv.getUint32(12, true);
+ const json = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 20, jsonLen)));
+ let bin = null;
+ const off = 20 + jsonLen;
+ if (off < buffer.byteLength) {
+ const binLen = dv.getUint32(off, true);
+ expect(dv.getUint32(off + 4, true)).toBe(CHUNK_BIN);
+ bin = new Uint8Array(buffer, off + 8, binLen);
+ }
+ return { totalLen: dv.getUint32(8, true), jsonLen, json, bin };
+}
+
+describe('stampGlbAttribution', () => {
+ it('stamps generator, source, and prompt into asset.*', () => {
+ const glb = buildGlb({ asset: { version: '2.0' }, scenes: [] });
+ const out = parseGlb(stampGlbAttribution(glb, { prompt: 'a brass steampunk owl' }));
+ expect(out.json.asset.generator).toBe(FORGE_GENERATOR);
+ expect(out.json.asset.extras.source).toBe('https://three.ws/forge');
+ expect(out.json.asset.extras.prompt).toBe('a brass steampunk owl');
+ expect(out.json.scenes).toEqual([]);
+ });
+
+ it('preserves the upstream engine generator in extras.pipeline', () => {
+ const glb = buildGlb({ asset: { version: '2.0', generator: 'TRELLIS reconstructor' } });
+ const out = parseGlb(stampGlbAttribution(glb));
+ expect(out.json.asset.generator).toBe(FORGE_GENERATOR);
+ expect(out.json.asset.extras.pipeline).toBe('TRELLIS reconstructor');
+ });
+
+ it('keeps the BIN chunk byte-for-byte and updates lengths/alignment', () => {
+ const bin = new Uint8Array([1, 2, 3, 4, 5, 6, 7]); // 7 bytes → padded chunk
+ const glb = buildGlb({ asset: { version: '2.0' } }, bin);
+ const stamped = stampGlbAttribution(glb, { prompt: 'x'.repeat(37) });
+ const out = parseGlb(stamped);
+ expect(out.totalLen).toBe(stamped.byteLength);
+ expect(out.jsonLen % 4).toBe(0);
+ expect(Array.from(out.bin.subarray(0, 7))).toEqual([1, 2, 3, 4, 5, 6, 7]);
+ });
+
+ it('truncates very long prompts to 500 chars', () => {
+ const glb = buildGlb({ asset: { version: '2.0' } });
+ const out = parseGlb(stampGlbAttribution(glb, { prompt: 'y'.repeat(2000) }));
+ expect(out.json.asset.extras.prompt).toHaveLength(500);
+ });
+
+ it('rejects non-GLB input', () => {
+ expect(() => stampGlbAttribution(new TextEncoder().encode('not a glb').buffer)).toThrow(
+ /not a GLB/,
+ );
+ });
+});
diff --git a/workers/pump-fun-mcp/worker.js b/workers/pump-fun-mcp/worker.js
index 56d80f3cd..899f7ed2d 100644
--- a/workers/pump-fun-mcp/worker.js
+++ b/workers/pump-fun-mcp/worker.js
@@ -1,11 +1,11 @@
// Cloudflare Workers mirror of /api/pump-fun-mcp (Vercel).
//
-// Implements the MCP Streamable HTTP transport (JSON-RPC 2.0 over POST).
-// Tool definitions are shared with the Vercel handler via src/pump/mcp-tools.js.
-// Handler logic is adapted from api/pump-fun-mcp.js — the only differences are:
-// • CF Workers fetch handler (Request/Response) instead of Node req/res.
-// • Env vars come from the `env` binding parameter, not process.env.
-// • No rate limiting (handled at the Cloudflare edge layer).
+// Implements the MCP Streamable HTTP transport: POST — JSON-RPC 2.0 (single +
+// batch), GET/HEAD — SSE handshake, DELETE — session terminate. Tool
+// definitions (and the snake_case ↔ camelCase alias map) are shared with the
+// Vercel handler via src/pump/mcp-tools.js. Handler logic is adapted from
+// api/pump-fun-mcp.js — see README.md for the documented divergences (no
+// auth/x402-gated tools, on-chain + indexer subset only).
//
// Secrets (wrangler secret put <NAME>):
// SOLANA_RPC_URL mainnet RPC endpoint (default: public)
@@ -15,16 +15,31 @@
//
// Deploy: wrangler deploy
-import { TOOLS, rpcError, rpcEnvelope } from '../../src/pump/mcp-tools.js';
+import { TOOLS, resolveToolName, rpcError, rpcEnvelope } from '../../src/pump/mcp-tools.js';
// ── Constants ────────────────────────────────────────────────────────────────
const GRADUATION_REAL_SOL_LAMPORTS = 85_000_000_000n;
+// Keep in sync with api/pump-fun-mcp.js (which mirrors api/_lib/mcp-dispatch.js).
+const PROTOCOL_VERSION = '2025-06-18';
+const SERVER_INFO = { name: 'pump-fun-mcp-worker', version: '1.0.0' };
+const INSTRUCTIONS =
+ 'Free, read-only pump.fun + Solana data tools (Cloudflare Workers mirror of ' +
+ 'https://three.ws/api/pump-fun-mcp). Token discovery (search_tokens, ' +
+ 'get_trending_tokens, get_new_tokens, get_graduated_tokens, get_king_of_the_hill), ' +
+ 'on-chain analysis (get_bonding_curve, get_token_holders, get_token_details, ' +
+ 'get_token_trades), and creator intelligence (get_creator_profile). All data is ' +
+ 'live and on-chain; no API keys required.';
+const MAX_BATCH = 16;
+
const CORS_HEADERS = {
'access-control-allow-origin': '*',
- 'access-control-allow-methods': 'POST,OPTIONS',
- 'access-control-allow-headers': 'content-type',
+ 'access-control-allow-methods': 'GET,HEAD,POST,DELETE,OPTIONS',
+ 'access-control-allow-headers':
+ 'authorization, content-type, mcp-session-id, mcp-protocol-version, x-payment',
+ 'access-control-expose-headers': 'mcp-protocol-version',
+ 'access-control-max-age': '86400',
};
// ── Solana helpers (adapted for CF Workers env bindings) ─────────────────────
@@ -235,14 +250,15 @@ function indexerHandler(name, env) {
`tool "${name}" requires the pump.fun indexer (PUMPFUN_BOT_URL) to be configured`,
);
}
+ // Canonical tool name → the upstream bot's (camelCase) surface.
const upstreamMap = {
- searchTokens: { tool: 'searchTokens', args: { query: args.query, limit: args.limit } },
- getTokenTrades: { tool: 'getTokenTrades', args: { mint: args.mint, limit: args.limit } },
- getTrendingTokens: { tool: 'getTrendingTokens', args: { limit: args.limit } },
- getNewTokens: { tool: 'getNewTokens', args: { limit: args.limit } },
- getGraduatedTokens: { tool: 'getGraduatedTokens', args: { limit: args.limit } },
- getKingOfTheHill: { tool: 'getKingOfTheHill', args: {} },
- getCreatorProfile: { tool: 'getCreatorIntel', args: { wallet: args.creator } },
+ search_tokens: { tool: 'searchTokens', args: { query: args.query, limit: args.limit } },
+ get_token_trades: { tool: 'getTokenTrades', args: { mint: args.mint, limit: args.limit } },
+ get_trending_tokens: { tool: 'getTrendingTokens', args: { limit: args.limit } },
+ get_new_tokens: { tool: 'getNewTokens', args: { limit: args.limit } },
+ get_graduated_tokens: { tool: 'getGraduatedTokens', args: { limit: args.limit } },
+ get_king_of_the_hill: { tool: 'getKingOfTheHill', args: {} },
+ get_creator_profile: { tool: 'getCreatorIntel', args: { wallet: args.creator } },
};
const upstream = upstreamMap[name];
if (!upstream) throw rpcError(-32601, `tool "${name}" not implemented`);
@@ -254,18 +270,20 @@ function indexerHandler(name, env) {
// ── Dispatch ─────────────────────────────────────────────────────────────────
+// Keyed by CANONICAL (snake_case) names. tools/call resolves legacy camelCase
+// aliases through resolveToolName before this lookup.
function buildHandlers(env) {
return {
- getBondingCurve: (a) => handleGetBondingCurve(a, env),
- getTokenDetails: (a) => handleGetTokenDetails(a, env),
- getTokenHolders: (a) => handleGetTokenHolders(a, env),
- searchTokens: indexerHandler('searchTokens', env),
- getTokenTrades: indexerHandler('getTokenTrades', env),
- getTrendingTokens: indexerHandler('getTrendingTokens', env),
- getNewTokens: indexerHandler('getNewTokens', env),
- getGraduatedTokens: indexerHandler('getGraduatedTokens', env),
- getKingOfTheHill: indexerHandler('getKingOfTheHill', env),
- getCreatorProfile: indexerHandler('getCreatorProfile', env),
+ get_bonding_curve: (a) => handleGetBondingCurve(a, env),
+ get_token_details: (a) => handleGetTokenDetails(a, env),
+ get_token_holders: (a) => handleGetTokenHolders(a, env),
+ search_tokens: indexerHandler('search_tokens', env),
+ get_token_trades: indexerHandler('get_token_trades', env),
+ get_trending_tokens: indexerHandler('get_trending_tokens', env),
+ get_new_tokens: indexerHandler('get_new_tokens', env),
+ get_graduated_tokens: indexerHandler('get_graduated_tokens', env),
+ get_king_of_the_hill: indexerHandler('get_king_of_the_hill', env),
+ get_creator_profile: indexerHandler('get_creator_profile', env),
};
}