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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add core generation tools for 3D asset creation and annotations tests
udvkb402509c3604
diff --git a/docs/store-submissions/00-README.md b/docs/store-submissions/00-README.mdindex 0fafb43ab..ecb4ea98e 100644--- a/docs/store-submissions/00-README.md+++ b/docs/store-submissions/00-README.md@@ -34,6 +34,16 @@ Authoritative sources (re-fetch at submission time; requirements move):5. `05-openai-apps-sdk-component.md` — the embedded GLB-viewer UI component the Apps SDK expects.6. `06-openai-submission-package.md` — OpenAI directory metadata, policy-compliance audit, screenshots, developer verification.+### Track C — Differentiation layer (the 10x–100x; what makes us NOT just another listing)+Baseline (01–06) gets us *listed*. Track C makes us *un-ignorable*. The thesis: three.ws is the only platform in either store with generation + agent payments + agent coordination in one place — so we ship the new primitive nobody else can: **embodied, economically-autonomous agents, and 3D as a native conversational medium.**+7. `07-embodied-agent-live-avatar.md` — a persistent 3D body that lip-syncs, emotes, and idles inline. The consumer screenshot moment. (Both stores.)+8. `08-live-agent-commerce.md` — autonomous discover→reputation→pay→delegate, made *visible* with provenance receipts. The agent-economy demo. (Claude/paid only.)+9. `09-conversational-remixable-3d.md` — iterate on a model by talking to it ("bigger helmet"), plus remixable assets with provenance + automatic creator royalties. (Iteration: both stores. Royalties: Claude/paid only.)++The 100x meta-move (positioning, not a single prompt): don't just *be in* the stores — **own a category across them.** Publish an open pattern for 3D-native / spatial MCP responses (tool results that return live interactive scenes, not text) and x402 agent-commerce patterns, and be the reference implementation other apps call under the hood. Infrastructure, not an app.++**Sequencing:** ship 01–06 first (real listings beat vision). Then 07 is the highest-leverage single add — it's the headline screenshot for both listings. 08 and 09 deepen the moat.+---## Rules every chat must follow (from CLAUDE.md)diff --git a/docs/store-submissions/08-live-agent-commerce.md b/docs/store-submissions/08-live-agent-commerce.mdnew file mode 100644index 000000000..fa3c2c8b1--- /dev/null+++ b/docs/store-submissions/08-live-agent-commerce.md@@ -0,0 +1,32 @@+# Prompt 08 — Live agent-to-agent commerce as a first-class experience (10x differentiator)++> Paste into a fresh Claude Code chat in the three.ws repo. Follow CLAUDE.md. Use TodoWrite. Builds on existing x402 + `agent_delegate_action` + AgenC tooling. NOTE: this is for the **Claude / paid MCP server** track, NOT the OpenAI free app (OpenAI prohibits crypto/payment surface — keep this out of `/api/mcp-studio`).++## The thesis+The agentic-commerce narrative is the story of 2026: agents that discover, hire, and pay other agents autonomously with real money. three.ws already has the rails — x402 USDC settlement, an agent registry, ERC-8004 reputation, and `agent_delegate_action`. Nobody in the directory has packaged this as a **visible, trustable, screenshot-worthy experience** instead of buried plumbing. Make agents transacting *legible*.++## Objective+A flagship capability where the host model can **autonomously discover a specialized agent, check its reputation, pay it via x402, delegate a task, and return the result — with the full transaction + provenance surfaced** so the user sees exactly what happened and what it cost.++## What to build (all real settlements — no simulated payments)+1. **Discovery + reputation gate.** A tool that, given a task description, finds candidate agents (AgenC registry / three.ws agent registry) ranked by ERC-8004 reputation and capability bitmask. Reuse `agent_reputation`, `agenc_list_tasks`, `agenc_get_agent`. Return a ranked shortlist with reputation evidence.+2. **Delegate-with-payment, transparently.** Extend/wrap `agent_delegate_action` so a delegation: (a) quotes the price up front, (b) settles real USDC via the existing x402 facilitator, (c) runs the remote agent, (d) returns the result **plus a provenance block**: which agent, its reputation, amount paid, settlement reference, latency. No mock settlement — use the live Solana x402 path already in `api/_mcp/`.+3. **Make it legible (the innovation).** Return structured content the component can render as a **transaction receipt / provenance card**: "Hired `agent X` (rep 0.94) · paid $0.15 USDC · settled `<tx>` · 3.2s." Build a small Apps-SDK/MCP-Apps component card for this (reuse patterns from prompt 05). The point is *trust through visibility*.+4. **Guardrails.** Hard spend cap per call + per session, confirmation semantics for anything above a threshold, and a clean `PaymentRequired`/insufficient-funds path. Errors handled at the boundary; never a crash-shaped failure.++## Why only three.ws+The registry + reputation + x402 facilitator + delegation primitives already exist and interoperate. The moat isn't any one piece — it's that you have the **whole loop** wired end to end. This demo *is* the agent economy, running live, with real money.++## Verification (must actually run)+- Drive a real end-to-end delegation: discover → reputation-rank → pay (real USDC on the existing facilitator) → get result → render the provenance card. Capture the transcript + settlement reference to `docs/store-submissions/_generated/commerce/`.+- Spend caps demonstrably block an over-threshold call.+- Insufficient funds / no-payment returns the clean `PaymentRequired`, not an error.+- `$THREE` remains the only coin referenced; USDC is settlement only. No other token anywhere.+- `npm test` green; add tests for the spend-cap and provenance-shape invariants.++## Definition of done+- The host model can autonomously and *visibly* hire + pay + delegate to a reputation-ranked agent, with real settlement and a provenance receipt, plus spend guardrails.+- Evidence (with a real settlement reference) saved. Coin policy clean.++## Hand-off+Report the tool name(s), the provenance-card component, the guardrail config, and the evidence path. This is a flagship use case for the Claude submission (prompt 03) and a category-defining demo. Commit/push only if asked; stage touched paths; both remotes.diff --git a/docs/store-submissions/09-conversational-remixable-3d.md b/docs/store-submissions/09-conversational-remixable-3d.mdnew file mode 100644index 000000000..ed06a2e39--- /dev/null+++ b/docs/store-submissions/09-conversational-remixable-3d.md@@ -0,0 +1,39 @@+# Prompt 09 — Conversational, remixable 3D with provenance + royalties (10x differentiator)++> Paste into a fresh Claude Code chat in the three.ws repo. Follow CLAUDE.md. Use TodoWrite. Prereqs: 04 + 05 (and 07 if personas are in play).++## The thesis+Today's in-chat generators are one-shot: prompt in, asset out, dead end. The frontier nobody has nailed is **conversational, iterative 3D** ("make the helmet bigger" → regenerate the diff, live) plus **composability**: every asset has provenance and a remixable license, and when someone builds on yours, value routes back to you. This turns three.ws from a generator into a *creative economy* — Sketchfab/Figma for the agent era.++## Objective+Two linked capabilities:+- **(A) Conversational iteration** on a generated model within the conversation.+- **(B) Remixable assets** with provenance and automatic creator royalties (Claude/paid track only — keep royalty/payment surface OUT of the OpenAI free app).++## What to build+### A. Conversational iteration (works in BOTH free + paid tracks; no payment surface needed)+1. A tool `refine_model(persona_or_asset_id, instruction)` that takes a prior asset + a natural-language change ("bigger helmet", "make it metallic", "add wings") and produces a new version, **anchored to the previous result** (re-use seed/reference image / mesh where the provider supports it; otherwise a guided re-generation that carries forward the prior prompt + adjustments). Real generation — no faked diffing.+2. **Version lineage:** each refinement records parent → child so the user can branch/revert. Return the lineage so the component can show a version strip.+3. **Live/progressive render** in the component if the provider exposes intermediates (TRELLIS/diffusion staged output); otherwise a designed "regenerating" state that swaps in the new GLB smoothly (cross-fade, not a pop). No fake progress bars — real async only.++### B. Remixable assets + provenance + royalties (PAID/Claude track only)+4. **Provenance record** per asset: creator (account/wallet), parent lineage, prompt, license terms. Store it with the existing asset/launch records — reuse, don't invent a parallel store.+5. **Remix economics:** when an asset is generated *from* another creator's published asset, x402 routes a royalty split to the original creator via the existing facilitator. Real settlement, real split logic, hard caps. Keep $THREE the only coin referenced; USDC for settlement only.+6. **A composable feed/tool:** browse published, remixable assets (reuse the `/launches`-style platform-records pattern) and remix one. Provenance and royalty terms visible before remixing.++## Why only three.ws+Generation + asset storage + Solana x402 rails already coexist here. Conversational iteration leverages the generation pipeline; royalties leverage the payment rails; provenance leverages the existing platform launch-records pattern. The composition is the moat.++## Verification (must actually run)+- Generate a model, issue 2 refinements; each is a real, visibly-different model anchored to the prior; version lineage is correct and revertable. Evidence to `docs/store-submissions/_generated/iteration/`.+- Remix a published asset from a *different* test creator; confirm a real royalty settlement to the original creator (paste the settlement reference) and that the split math + caps are correct.+- The free-app path (`/api/mcp-studio`) exposes refinement but **zero** payment/royalty/token surface — grep to prove it.+- No console errors. `npm test` green; add tests for lineage integrity and royalty-split math.++## Definition of done+- Conversational refinement with correct version lineage and smooth re-render, available in the free app (no payment surface) and the paid server.+- Provenance + automatic creator royalties working with real settlement on the paid track, with caps. Coin policy clean.+- Evidence saved.++## Hand-off+Report the refine tool, lineage model, the royalty-split logic + caps, and evidence paths. Conversational iteration is a strong OpenAI listing differentiator; royalties are a Claude/agent-economy differentiator. Commit/push only if asked; stage touched paths; both remotes.diff --git a/docs/store-submissions/_generated/claude-submission.md b/docs/store-submissions/_generated/claude-submission.mdnew file mode 100644index 000000000..cd74a6a5d--- /dev/null+++ b/docs/store-submissions/_generated/claude-submission.md@@ -0,0 +1,337 @@+# Claude Connectors Directory — Submission Answer Sheet++**Status:** copy-paste-ready. Fields the operator must supply privately are marked `[HUMAN: fill in]`.+**Generated for:** three.ws MCP servers. **Date:** 2026-06-25.+**Sources:** live checklist re-fetched 2026-06-25 from+`claude.com/docs/connectors/building/submission` and `.../review-criteria`;+tool data read directly from `api/_mcp/tools/*.js` and `api/_mcp3d/tools/studio.js`.++---++## 0. Read this first — open items the operator must resolve++These are gating decisions/risks surfaced while assembling the package. None are blank+form fields; they are judgment calls only the operator can make.++1. **Org / role (gating).** The in-app portal requires a **Team or Enterprise** Claude org+ and an **Owner** (or a custom role with *Directory management* / *Libraries* permission).+ - `[HUMAN: confirm]` you have a Team/Enterprise org + Owner role. **If not**, use the+ **public MCP directory submission form** instead of the in-app portal — same field+ content below applies.++2. **Media-generation policy (review risk).** The review criteria list *"AI-generated images,+ video, or audio"* among **rejected** use cases (design tools for diagrams/charts are+ permitted). Our **`/api/mcp-3d` 3D Studio** server is almost entirely generative+ (`text_to_3d`, `image_to_3d`, `retexture_*`, `stylize_model`, `generate_material`), and the+ main server has a few generative tools too (`render_avatar_image`, `text_to_animation`).+ - **Recommendation:** submit **`/api/mcp` (main)** first — it is dominated by read-only data,+ glTF *validation/inspection*, agent identity, and account management. Hold **`/api/mcp-3d`**+ as a separate, later submission and, if needed, ask the directory team whether *3D model+ (GLB) generation* is treated as prohibited media generation. `[HUMAN: decide]`++3. **Transactions / financial use (review risk).** Two things to disclose and watch:+ - The connector **charges USDC via x402** for paid tools (a per-call *service fee* for+ compute — disclose under the Transactions acknowledgment).+ - The review criteria reject *"financial asset transfers."* The main server's+ **trader / copy-trading / Oracle / Solana tools** (`trader_leaderboard`, `trader_profile`,+ `copy_subscribe`, `copy_status`, `oracle_*`, `solana_agent_*`, `pumpfun_*`) are **read-only+ market data and on-chain reputation reads — they do not move funds or execute trades.**+ State that explicitly so they aren't misread as asset transfers. `[HUMAN: confirm copy_subscribe+ never auto-executes a trade on the user's behalf — it records a copy subscription only.]`++4. **Discovery is auth-gated in production (verify with reviewer access).** Against+ production, unauthenticated `initialize` / `tools/list` return an **x402 `PaymentRequired`**+ (the server also issues a proper **OAuth `Bearer` challenge** via+ `WWW-Authenticate` + `/.well-known/oauth-protected-resource`). The directory portal syncs+ tools **after** completing the OAuth connection, so this is expected — but the reviewer/portal+ **must connect via OAuth** to see `tools/list`. Confirm the reviewer OAuth account works+ end-to-end (see §6). `[HUMAN: verify in the portal's Connection step.]`++5. **Prerequisite artifacts.** The `_generated/tool-inventory.md` (prompt 01) and+ `claude-reviewer-guide.md` (prompt 02) were **not present** in the repo when this sheet was+ built; the tool list below was rebuilt directly from source, and §6 is a self-contained+ reviewer guide. If prompt 02's funded/bypass review wallet was never provisioned, do that+ before submitting. `[HUMAN: confirm a working reviewer access path exists.]`++6. **Privacy edits pending deploy.** This sheet adds an MCP/AI/payments section to+ `public/legal/privacy.html`. It must be **deployed** before submitting so the live+ `https://three.ws/legal/privacy` reflects it.++---++## 1. Primary server choice++**Submit `https://three.ws/api/mcp` (the "three.ws Avatars & Agents" server) as the flagship.**++Why:+- Broadest, most directory-friendly surface: account-scoped avatar management, glTF/GLB+ **validation/inspection/optimization** (read-only), agent identity & reputation, agent memory,+ and live market/Oracle/trader **reads** — most tools are read-only or non-generative.+- Lower review risk than the 3D Studio server on the media-generation criterion (see §0.2).+- Production resolves and presents a correct OAuth challenge + x402 fallback (verified below).++Optionally submit **`https://three.ws/api/mcp-3d` (three.ws 3D Studio)** as a **second** listing+once the media-generation question (§0.2) is settled.++**Production verification (run 2026-06-25):**+```+POST https://three.ws/api/mcp (no auth)+→ 402, WWW-Authenticate: Bearer resource_metadata="https://three.ws/.well-known/oauth-protected-resource"+→ x402 PaymentRequired body (USDC on Solana; $THREE accepted; both advertised)+GET https://three.ws/.well-known/oauth-protected-resource+→ 200, scopes: avatars:read/write/delete, profile, memory:read/write, agents:read/write+https://three.ws/legal/privacy → 200 https://three.ws/docs/mcp → 200+```+Discovery/`tools/list` returns results **after OAuth** (anonymous discovery is x402-gated — §0.4).++---++## 2. Listing fields (portal "Listing" + "Connection" + "Company" + "Authentication" steps)++| Field | Value |+|---|---|+| **Server name** (≤100) | three.ws — Avatars & Agents |+| **Server URL** | `https://three.ws/api/mcp` |+| **Transport** | Streamable HTTP (MCP 2025-06-18) |+| **Tagline** (≤55) | `3D avatars, glTF tools & on-chain agent data` (44) |+| **Categories (1–5)** | Developer Tools; Productivity; Data & Analytics |+| **Documentation URL** | `https://three.ws/docs/mcp` |+| **Privacy policy URL** | `https://three.ws/legal/privacy` |+| **Support contact** | `[email protected]` `[HUMAN: confirm this inbox is monitored]` |+| **Icon** | `https://three.ws/three-ws-mcp-icon.svg` |+| **URL slug** | `three-ws` |+| **Company name** | `[HUMAN: fill in legal entity name]` |+| **Company website** | `https://three.ws` |+| **Primary contact** | `[HUMAN: fill in name + email]` |+| **Authentication** | OAuth 2.1 (authorization-code + PKCE); x402 (USDC) as an alternative pay-per-call path for unauthenticated callers |+| **User connection model** | Each user connects their own three.ws account via OAuth |++**Description** (≤2,000 chars):+> three.ws turns Claude into a 3D-content and on-chain-agent workstation. Manage your three.ws+> avatars (list, fetch, search public avatars, render to an interactive viewer or a static image,+> delete); validate, inspect, and get optimization guidance for any glTF/GLB model; list and apply+> animation presets to rigged models; and embed a live 3D viewer anywhere with a generated snippet.+>+> It also reads the on-chain agent economy: ERC-8004 / Solana agent reputation, attestations, and+> identity "passport" checks for impersonation screening; an agent registry you can call and+> register into; and persistent agent memory (remember / recall / forget) scoped to your account.+>+> For market context it surfaces live pump.fun data (recent claims, token and creator intel,+> graduations), Oracle conviction signals, and a pump.fun trader leaderboard with full track records+> and copy-subscription management — all read-only market data.+>+> Connect your three.ws account with OAuth to use your account-scoped tools; public data tools can+> alternatively be paid per call with x402 (USDC). The only token three.ws references is $THREE.++---++## 3. Read / write capabilities summary (portal "Use cases" step)++- **Reads:** avatars (own + public search), glTF/GLB validation & inspection, animation presets,+ agent registry & reputation / attestations / passport, agent memory recall, pump.fun market data,+ Oracle signals, trader leaderboard & profiles, copy-subscription status, embed-code generation.+- **Writes:** save/render avatar assets, **delete avatar** (the one destructive op), register an+ agent on-chain, call another agent, remember/forget memory, arm an Oracle watch, subscribe to+ copy a trader. Writes that touch a chain or external API carry `openWorldHint: true`.+- **Destructive:** only `delete_avatar` (`destructiveHint: true`). All others set+ `destructiveHint: false` explicitly.+- **Payments:** paid tools return a structured x402 `PaymentRequired` (not an error) when+ unauthenticated and unpaid; OAuth-connected account tools are operator-funded for the user.++### Use cases (3–5 concrete)+1. **Avatar ops in chat** — "List my three.ws avatars, render `nova` to an image, and give me an+ embed snippet for my site."+2. **glTF QA** — "Validate this GLB URL, inspect its mesh/material counts, and suggest optimizations+ before I ship it."+3. **Agent due-diligence** — "Check the on-chain reputation and impersonation passport for this+ agent address before I delegate to it."+4. **Agent memory** — "Remember that this user prefers low-poly avatars," recalled in later sessions.+5. **Market read** — "Show the top pump.fun traders this week and the recent graduations" (read-only).++---++## 4. Full tool list (with titles)++> Pulled from source. `free*` = no payment when called with an OAuth account (operator-funded) or+> when the tool is inherently free; `x402` = pay-per-call in USDC for unauthenticated callers.+> Read-only tools carry `readOnlyHint: true`; only `delete_avatar` is `destructiveHint: true`.++### `https://three.ws/api/mcp` — three.ws Avatars & Agents+| Tool name | Title | Kind |+|---|---|---|+| `getting_started` | Getting started with three.ws | free, read-only |+| `list_my_avatars` | List my avatars | OAuth, read |+| `get_avatar` | Get avatar | OAuth, read |+| `search_public_avatars` | Search public avatars | read |+| `render_avatar` | Render avatar | x402 |+| `render_avatar_image` | Render an avatar to an image | x402, generative |+| `delete_avatar` | Delete avatar | OAuth, **destructive** |+| `validate_model` | Validate glTF/GLB model | x402, read |+| `inspect_model` | Inspect glTF/GLB model | x402, read |+| `optimize_model` | Suggest optimizations for a glTF/GLB model | x402, read |+| `list_animations` | List animation presets | free, read |+| `apply_animation` | Apply an animation preset to a rigged model | write |+| `text_to_animation` | Generate an animation from a text prompt and retarget it onto a model | write, generative |+| `get_embed_code` | Get embed code | read |+| `call_agent` | Call agent | write, open-world |+| `register_agent` | Register an agent on-chain | write, open-world |+| `identity_check` | Screen an agent identity for impersonation | read, open-world |+| `remember` | Remember | OAuth, write |+| `recall` | Recall | OAuth, read |+| `forget` | Forget | OAuth, write |+| `solana_agent_reputation` | Get Solana agent reputation | read, open-world |+| `solana_agent_attestations` | List Solana agent attestations | read, open-world |+| `solana_agent_passport` | Get Solana agent passport | read, open-world |+| `pumpfun_recent_claims` | Recent pump.fun claims | read, open-world |+| `pumpfun_token_intel` | Pump.fun token intel | read, open-world |+| `pumpfun_creator_intel` | Pump.fun creator intel | read, open-world |+| `pumpfun_recent_graduations` | Recent pump.fun graduations | read, open-world |+| `oracle_top_plays` | Oracle top conviction plays | read |+| `oracle_coin` | Oracle verdict for one coin | read |+| `oracle_arm_watch` | Arm agent Oracle watch | write |+| `oracle_watch_status` | Oracle watch status + track record | read |+| `trader_leaderboard` | Top pump.fun traders | read |+| `trader_profile` | Full track record for one agent | read |+| `copy_subscribe` | Subscribe to copy a trader | write |+| `copy_status` | My copy subscriptions | read |++### `https://three.ws/api/mcp-3d` — three.ws 3D Studio (optional second listing)+| Tool name | Title | Kind |+|---|---|---|+| `getting_started` | Getting started with three.ws 3D Studio | free, read-only |+| `text_to_3d` | Generate a 3D model from a text prompt | x402, generative |+| `image_to_3d` | Reconstruct a 3D model from one or more images | x402, generative |+| `generation_status` | Check a 3D generation job | free, read |+| `preview_3d` | Preview any GLB as an interactive 3D artifact | free, read |+| `remove_background` | Remove the background from an image | generative |+| `remesh_model` | Remesh, simplify, repair, or convert a 3D model | x402 |+| `stylize_model` | Apply a one-click geometric stylization filter to a 3D model | x402, generative |+| `segment_model` | Split a 3D model into named, separable parts | x402 |+| `retexture_model` | Paint a new texture onto a 3D model from a text prompt | x402, generative |+| `retexture_region` | Repaint one masked region of a model's texture (magic brush) | x402, generative |+| `auto_rig_model` | Auto-rig a static 3D model (skeleton + skin weights) | x402 |+| `pose_model` | Resolve a text prompt to a pose-studio seed + joint rotations | read |+| `direct_prompt` | Optimize a rough idea into a 3D-generation prompt (IBM Granite) | x402 |+| `generate_material` | Generate a glTF PBR material from a description (IBM Granite) | x402, generative |+| `save_avatar` | Save a generated GLB as a durable, named avatar | OAuth, write |++---++## 5. Allowed link URIs (portal "Allowed links" — optional, suppresses confirm prompts)++Declare these HTTPS origins (every external link a tool response can open). We **own/control**+the three.ws origins; the rest are reputable, read-only public asset/explorer hosts that tool+responses may reference.++**Owned (declare):**+- `https://three.ws` — viewer links, embed targets, avatar pages, docs, legal.++**Asset hosts we serve from (declare):**+- `https://three-ws-public.r2.dev` — Cloudflare R2 public CDN for GLB/glTF + thumbnails.++**Third-party hosts referenced in responses (reputable; declare as needed):**+- `https://pump.fun` — token/coin links in market-data tool output.+- `https://explorer.solana.com` — Solana tx/address links.+- `https://basescan.org` — Base tx links (x402 settlement / EVM agent data).+- EVM explorers for ERC-8004 agent data (only when that chain is referenced):+ `https://arbiscan.io`, `https://polygonscan.com`, `https://etherscan.io`,+ `https://optimistic.etherscan.io`, `https://snowtrace.io`, `https://bscscan.com`.+- `https://nvidia-kaolin.s3.us-east-2.amazonaws.com` — NVIDIA-hosted reference assets (3D Studio).++> Custom URI schemes: none — the connector opens only `https://` links.++---++## 6. Reviewer access & test instructions (portal "Test & launch" step)++> Paste this into the reviewer-instructions box. Replace the `[HUMAN: ...]` credentials privately.++**Server:** `https://three.ws/api/mcp` (Streamable HTTP). 3D Studio: `https://three.ws/api/mcp-3d`.++**Connect (OAuth 2.1):**+1. Add the connector by URL; the client discovers+ `https://three.ws/.well-known/oauth-protected-resource` and runs the OAuth flow.+2. Sign in with the reviewer test account: `[HUMAN: fill in test account login / wallet]`.+ The account is **fully populated** (sample avatars + agent memory) so list/get/search/recall+ return real data.+3. After OAuth, `tools/list` returns the full catalog and account-scoped tools run+ **operator-funded (free to the reviewer).**++**Free smoke path (no payment needed):**+- `getting_started` → server overview + per-tool pricing.+- `list_my_avatars` → returns the seeded avatars.+- `get_avatar` (id from the list) → full avatar record + viewer URL on `https://three.ws`.+- `search_public_avatars` (e.g. `"robot"`) → public results.+- `list_animations` → preset list.+- `recall` → seeded memory.+- (3D Studio) `generation_status` / `preview_3d` on a sample GLB URL → free, returns a viewer artifact.++**Funded path — exercising paid (x402) tools for real:**+- Paid tools called **without** payment return a clean `PaymentRequired` (price + asset + how to+ pay), **not** an error — see note below.+- To run them for real, use the prepared reviewer path: `[HUMAN: choose ONE and fill in —+ (a) reviewer OAuth account flagged for operator-funded paid tools, or (b) a small pre-funded+ Solana USDC test wallet: address + funding note.]`+- With that, exercise e.g. `validate_model` (pass any public GLB URL) and `render_avatar` to see+ real paid responses.++**Expected output shapes:**+- Read tools → JSON records (avatars, agents, market data) + `https://three.ws/...` links.+- Render/preview → a viewer artifact / image URL on `three.ws` or `three-ws-public.r2.dev`.+- Paid + unpaid → structured x402 `PaymentRequired` (see below).++**"What `PaymentRequired` means" (not a bug):** three.ws tools are pay-per-call in USDC. An+unauthenticated, unpaid call returns a structured `PaymentRequired` (`x402Version: 2`, the price,+the asset = USDC on Solana/Base, and `payTo`). This is the documented v2 MCP/x402 behavior, **not**+a failure — the tool is working and quoting its price. OAuth-connected account calls skip this.++---++## 7. Compliance acknowledgments (portal "Compliance" step — 7 statements)++Truthful draft answers; `[HUMAN: ...]` marks where operator confirmation is required.++1. **Directory guidelines** — *Acknowledged.* We will follow the Connectors Directory guidelines+ and the (non-waivable, evolving) MCP open-source terms; the server source is public at+ `https://github.com/nirholas/three.ws`.+2. **API usage / ownership** — *Acknowledged.* All tools call **first-party three.ws APIs** under+ `three.ws`, or legitimately proxy upstream services for which three.ws holds accounts (model+ providers, Solana/EVM RPC, pump.fun data). No third-party API is impersonated.+3. **Transactions** — *Disclosed.* Paid tools charge a **per-call service fee in USDC via x402**+ for compute. The market/trader/Oracle/Solana tools are **read-only data — they do not transfer+ user funds or execute trades.** `[HUMAN: confirm legal entity for the Company step and that+ copy_subscribe records a subscription only, with no automated on-chain order execution.]`+4. **Media generation** — *Disclosed.* `render_avatar_image` / `text_to_animation` (main) and the+ 3D Studio generative tools produce **3D models / rendered images**. `[HUMAN: confirm with the+ directory team whether 3D-model generation is acceptable; if media generation is disallowed,+ submit `/api/mcp` only and exclude the two generative main-server tools or scope them out.]`+5. **Prompt injection** — *Acknowledged.* Tool descriptions are function-only: no hidden/encoded+ instructions, no directions for Claude to call other tools or follow external instruction+ sources, no system-prompt overrides.+6. **Data collection** — *Acknowledged.* We collect only the tool inputs needed to fulfill a call+ (prompts, asset URLs, addresses) plus usage metadata for quota/abuse. We **never** query+ Claude's memory, chat history, or user files. Disclosed in the privacy policy (§ MCP Connectors).+7. **Documentation** — *Acknowledged.* Public docs are live at `https://three.ws/docs/mcp`; the+ privacy policy at `https://three.ws/legal/privacy`. Both resolve over HTTPS today.++---++## 8. Manifest sanity (server.json / server-3d.json)++Verified clean:+- Schema: `https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json` (live, 200).+- `server.json` → name `io.github.nirholas/three.ws`, remote `https://three.ws/api/mcp`+ (`streamable-http`), website `https://three.ws`, repo public.+- `server-3d.json` → name `io.github.nirholas/threews-3d-studio`, remote `https://three.ws/api/mcp-3d`.+- **No non-`$THREE` token anywhere** in either manifest (no base58 mint strings present). `$THREE`+ remains the only coin referenced across the package.++---++## 9. Privacy policy — coverage confirmation++`https://three.ws/legal/privacy` covers (✓ after this change set):+data collection ✓ · usage/storage ✓ · third-party sharing ✓ (infra + **AI model providers**:+NVIDIA NIM/TRELLIS, Meshy, Replicate, Stability, Hugging Face, OpenAI, Anthropic, IBM Granite) ✓ ·+retention ✓ · contact (`[email protected]`) ✓ · **MCP tool inputs, x402 payment/wallet data, OAuth+scope limits** ✓ (new "MCP Connectors, AI Processing & Payments" section). **Deploy before submitting.**diff --git a/docs/store-submissions/_generated/remote-tools-list.json b/docs/store-submissions/_generated/remote-tools-list.jsonnew file mode 100644index 000000000..3cf2433c8--- /dev/null+++ b/docs/store-submissions/_generated/remote-tools-list.json@@ -0,0 +1,750 @@+{+ "note": "Each TOOL_CATALOG is returned verbatim as the tools/list result by the shared dispatcher (api/_lib/mcp-dispatch.js); the main /api/mcp dispatcher spreads each entry and adds x402 pricing. Asserting on these equals asserting on the wire response (see tests/mcp-remote-annotations.test.js).",+ "servers": {+ "/api/mcp": {+ "count": 35,+ "tools": [+ {+ "name": "getting_started",+ "title": "Getting Started (free)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "list_my_avatars",+ "title": "List my avatars",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "get_avatar",+ "title": "Get avatar",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "search_public_avatars",+ "title": "Search public avatars",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "render_avatar",+ "title": "Render avatar",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "render_avatar_image",+ "title": "Render an avatar to an image",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ }+ },+ {+ "name": "delete_avatar",+ "title": "Delete avatar",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "get_embed_code",+ "title": "Get embed code",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ }+ },+ {+ "name": "validate_model",+ "title": "Validate glTF/GLB model",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ }+ },+ {+ "name": "inspect_model",+ "title": "Inspect glTF/GLB model",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ }+ },+ {+ "name": "optimize_model",+ "title": "Suggest optimizations for a glTF/GLB model",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ }+ },+ {+ "name": "list_animations",+ "title": "List animation presets",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "apply_animation",+ "title": "Apply an animation preset to a rigged model",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "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+ }+ },+ {+ "name": "solana_agent_reputation",+ "title": "Get Solana agent reputation",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "solana_agent_attestations",+ "title": "List Solana agent attestations",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "solana_agent_passport",+ "title": "Get Solana agent passport",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "pumpfun_recent_claims",+ "title": "Recent pump.fun claims",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "pumpfun_token_intel",+ "title": "Pump.fun token intel",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "pumpfun_creator_intel",+ "title": "Pump.fun creator intel",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "pumpfun_recent_graduations",+ "title": "Recent pump.fun graduations",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "call_agent",+ "title": "Call agent",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "register_agent",+ "title": "Register an agent on-chain",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "identity_check",+ "title": "Screen an agent identity for impersonation",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "remember",+ "title": "Remember",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "recall",+ "title": "Recall",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "forget",+ "title": "Forget",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "oracle_top_plays",+ "title": "Oracle top conviction plays",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "oracle_coin",+ "title": "Oracle verdict for one coin",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "oracle_arm_watch",+ "title": "Arm agent Oracle watch",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "oracle_watch_status",+ "title": "Oracle watch status + track record",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "trader_leaderboard",+ "title": "Top pump.fun traders",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "trader_profile",+ "title": "Full track record for one agent",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "copy_subscribe",+ "title": "Subscribe to copy a trader",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "copy_status",+ "title": "My copy subscriptions",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ }+ ]+ },+ "/api/mcp-3d": {+ "count": 21,+ "tools": [+ {+ "name": "getting_started",+ "title": "Getting Started (free)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "text_to_3d",+ "title": "Generate a 3D model from a text prompt",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "image_to_3d",+ "title": "Reconstruct a 3D model from one or more images",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "generation_status",+ "title": "Check a 3D generation job",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "preview_3d",+ "title": "Preview any GLB as an interactive 3D artifact",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ }+ },+ {+ "name": "remove_background",+ "title": "Remove the background from an image",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "remesh_model",+ "title": "Remesh, simplify, repair, or convert a 3D model",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "stylize_model",+ "title": "Apply a one-click geometric stylization filter to a 3D model",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "segment_model",+ "title": "Split a 3D model into named, separable parts",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "retexture_model",+ "title": "Paint a new texture onto a 3D model from a text prompt",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "retexture_region",+ "title": "Repaint one masked region of a model's texture (magic brush)",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "auto_rig_model",+ "title": "Auto-rig a static 3D model (skeleton + skin weights)",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "pose_model",+ "title": "Resolve a text prompt to a pose-studio seed + joint rotations",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "direct_prompt",+ "title": "Optimize a rough idea into a 3D-generation prompt (IBM Granite)",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "generate_material",+ "title": "Generate a glTF PBR material from a description (IBM Granite)",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "save_avatar",+ "title": "Save a generated GLB as a durable, named avatar",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "inspect_model",+ "title": "Inspect glTF/GLB model",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ }+ },+ {+ "name": "optimize_model",+ "title": "Suggest optimizations for a glTF/GLB model",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ }+ },+ {+ "name": "list_animations",+ "title": "List animation presets",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "apply_animation",+ "title": "Apply an animation preset to a rigged model",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "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+ }+ }+ ]+ },+ "/api/agent-mcp": {+ "count": 6,+ "tools": [+ {+ "name": "getting_started",+ "title": "Getting Started (free)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "wallet_status",+ "title": "Check the agent's wallet",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "find_services",+ "title": "Find paid services the agent can call",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "pay_and_call",+ "title": "Pay an x402 service and return its result",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "provision_wallet",+ "title": "Create the agent's wallet",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "monetize_endpoint",+ "title": "Publish a paid endpoint to earn USDC",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ }+ ]+ },+ "/api/ibm-mcp": {+ "count": 6,+ "tools": [+ {+ "name": "ibm_granite_getting_started",+ "title": "Getting Started (free)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "ibm_granite_chat",+ "title": "IBM Granite Chat ($0.02)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "ibm_granite_code",+ "title": "IBM Granite Code ($0.025)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "ibm_granite_embed",+ "title": "IBM Granite Embed ($0.005)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ }+ },+ {+ "name": "ibm_granite_analyze",+ "title": "IBM Granite Analyze ($0.04)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "ibm_granite_forecast",+ "title": "IBM Granite Forecast ($0.05)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ }+ ]+ },+ "/api/bazaar-mcp": {+ "count": 4,+ "tools": [+ {+ "name": "getting_started",+ "title": "Getting Started (free)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "search_services",+ "title": "Search the x402 bazaar",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "browse_services",+ "title": "Browse the x402 bazaar",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "get_service",+ "title": "Get full details for one x402 service",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ }+ ]+ }+ }+}\ No newline at end of filediff --git a/docs/store-submissions/_generated/stdio-tools-list.json b/docs/store-submissions/_generated/stdio-tools-list.jsonnew file mode 100644index 000000000..aceb59a33--- /dev/null+++ b/docs/store-submissions/_generated/stdio-tools-list.json@@ -0,0 +1,177 @@+{+ "captured_via": "node mcp-server/src/index.js — raw JSON-RPC over stdio",+ "protocolVersion": "2025-06-18",+ "tool_count": 17,+ "tools": [+ {+ "name": "text_to_avatar",+ "title": "Text → 3D avatar ($0.15)",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "mesh_forge",+ "title": "Text → 3D mesh ($0.25)",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "forge_free",+ "title": "Free text → 3D (TRELLIS)",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "rig_mesh",+ "title": "Rig 3D mesh ($0.20)",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "forge_avatar",+ "title": "Text/Image → rigged avatar ($0.45)",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "ens_sns_resolve",+ "title": "ENS + SNS resolve ($0.0005)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "agent_delegate_action",+ "title": "Agent delegate action ($0.01)",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "sentiment_pulse",+ "title": "Sentiment pulse ($0.003)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "get_pose_seed",+ "title": "Pose seed ($0.001)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "pump_snapshot",+ "title": "Pump.fun snapshot ($0.005)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "agent_reputation",+ "title": "Agent reputation ($0.01)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "vanity_grinder",+ "title": "Solana vanity grinder ($0.05)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": false+ }+ },+ {+ "name": "agenc_list_tasks",+ "title": "AgenC list tasks ($0.001)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "agenc_get_task",+ "title": "AgenC get task ($0.001)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "agenc_get_agent",+ "title": "AgenC get agent ($0.001)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "aixbt_intel",+ "title": "aixbt intel ($0.01)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ },+ {+ "name": "aixbt_projects",+ "title": "aixbt projects ($0.01)",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ }+ }+ ]+}\ No newline at end of filediff --git a/docs/store-submissions/_generated/tool-inventory.md b/docs/store-submissions/_generated/tool-inventory.mdnew file mode 100644index 000000000..52e7921d7--- /dev/null+++ b/docs/store-submissions/_generated/tool-inventory.md@@ -0,0 +1,114 @@+# three.ws MCP — Tool Annotation & Title Inventory++Generated from the live tool catalogs (`TOOL_CATALOG` / `buildTools()`) — the exact `tools/list` wire payloads.++✅ = true, — = false. destructive ✅ only on irreversible deletes/spends.++| Server | Tool | Title | readOnly | destructive | idempotent | openWorld | Price (x402) |+|---|---|---|:--:|:--:|:--:|:--:|---|+| /api/mcp (main) | `getting_started` | Getting Started (free) | ✅ | — | ✅ | — | free |+| /api/mcp (main) | `list_my_avatars` | List my avatars | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `get_avatar` | Get avatar | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `search_public_avatars` | Search public avatars | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `render_avatar` | Render avatar | ✅ | — | — | ✅ | $0.005 |+| /api/mcp (main) | `render_avatar_image` | Render an avatar to an image | — | — | ✅ | ✅ | free |+| /api/mcp (main) | `delete_avatar` | Delete avatar | — | ✅ | — | ✅ | free |+| /api/mcp (main) | `get_embed_code` | Get embed code | ✅ | — | ✅ | ✅ | free |+| /api/mcp (main) | `validate_model` | Validate glTF/GLB model | ✅ | — | ✅ | ✅ | $0.01 |+| /api/mcp (main) | `inspect_model` | Inspect glTF/GLB model | ✅ | — | ✅ | ✅ | $0.01 |+| /api/mcp (main) | `optimize_model` | Suggest optimizations for a glTF/GLB model | ✅ | — | ✅ | ✅ | $0.05 |+| /api/mcp (main) | `list_animations` | List animation presets | ✅ | — | ✅ | — | free |+| /api/mcp (main) | `apply_animation` | Apply an animation preset to a rigged model | — | — | — | ✅ | $0.02 |+| /api/mcp (main) | `text_to_animation` | Generate an animation from a text prompt and retarget it onto a model | — | — | — | ✅ | free |+| /api/mcp (main) | `solana_agent_reputation` | Get Solana agent reputation | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `solana_agent_attestations` | List Solana agent attestations | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `solana_agent_passport` | Get Solana agent passport | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `pumpfun_recent_claims` | Recent pump.fun claims | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `pumpfun_token_intel` | Pump.fun token intel | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `pumpfun_creator_intel` | Pump.fun creator intel | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `pumpfun_recent_graduations` | Recent pump.fun graduations | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `call_agent` | Call agent | — | — | — | ✅ | free |+| /api/mcp (main) | `register_agent` | Register an agent on-chain | — | — | — | ✅ | free |+| /api/mcp (main) | `identity_check` | Screen an agent identity for impersonation | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `remember` | Remember | — | — | — | ✅ | free |+| /api/mcp (main) | `recall` | Recall | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `forget` | Forget | — | ✅ | — | ✅ | free |+| /api/mcp (main) | `oracle_top_plays` | Oracle top conviction plays | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `oracle_coin` | Oracle verdict for one coin | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `oracle_arm_watch` | Arm agent Oracle watch | — | — | ✅ | — | free |+| /api/mcp (main) | `oracle_watch_status` | Oracle watch status + track record | ✅ | — | ✅ | — | free |+| /api/mcp (main) | `trader_leaderboard` | Top pump.fun traders | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `trader_profile` | Full track record for one agent | ✅ | — | — | ✅ | free |+| /api/mcp (main) | `copy_subscribe` | Subscribe to copy a trader | — | — | ✅ | — | free |+| /api/mcp (main) | `copy_status` | My copy subscriptions | ✅ | — | ✅ | — | free |+| /api/mcp-3d (Studio) | `getting_started` | Getting Started (free) | ✅ | — | ✅ | — | free |+| /api/mcp-3d (Studio) | `text_to_3d` | Generate a 3D model from a text prompt | — | — | — | ✅ | $0.15 |+| /api/mcp-3d (Studio) | `image_to_3d` | Reconstruct a 3D model from one or more images | — | — | — | ✅ | $0.15 |+| /api/mcp-3d (Studio) | `generation_status` | Check a 3D generation job | ✅ | — | — | ✅ | free |+| /api/mcp-3d (Studio) | `preview_3d` | Preview any GLB as an interactive 3D artifact | ✅ | — | ✅ | ✅ | free |+| /api/mcp-3d (Studio) | `remove_background` | Remove the background from an image | — | — | — | ✅ | $0.01 |+| /api/mcp-3d (Studio) | `remesh_model` | Remesh, simplify, repair, or convert a 3D model | — | — | — | ✅ | $0.02 |+| /api/mcp-3d (Studio) | `stylize_model` | Apply a one-click geometric stylization filter to a 3D model | — | — | — | ✅ | $0.02 |+| /api/mcp-3d (Studio) | `segment_model` | Split a 3D model into named, separable parts | — | — | — | ✅ | $0.02 |+| /api/mcp-3d (Studio) | `retexture_model` | Paint a new texture onto a 3D model from a text prompt | — | — | — | ✅ | $0.05 |+| /api/mcp-3d (Studio) | `retexture_region` | Repaint one masked region of a model's texture (magic brush) | — | — | — | ✅ | $0.05 |+| /api/mcp-3d (Studio) | `auto_rig_model` | Auto-rig a static 3D model (skeleton + skin weights) | — | — | — | ✅ | $0.05 |+| /api/mcp-3d (Studio) | `pose_model` | Resolve a text prompt to a pose-studio seed + joint rotations | ✅ | — | ✅ | — | $0.01 |+| /api/mcp-3d (Studio) | `direct_prompt` | Optimize a rough idea into a 3D-generation prompt (IBM Granite) | — | — | — | ✅ | $0.01 |+| /api/mcp-3d (Studio) | `generate_material` | Generate a glTF PBR material from a description (IBM Granite) | — | — | — | ✅ | $0.01 |+| /api/mcp-3d (Studio) | `save_avatar` | Save a generated GLB as a durable, named avatar | — | — | — | ✅ | free |+| /api/mcp-3d (Studio) | `inspect_model` | Inspect glTF/GLB model | ✅ | — | ✅ | ✅ | free |+| /api/mcp-3d (Studio) | `optimize_model` | Suggest optimizations for a glTF/GLB model | ✅ | — | ✅ | ✅ | free |+| /api/mcp-3d (Studio) | `list_animations` | List animation presets | ✅ | — | ✅ | — | free |+| /api/mcp-3d (Studio) | `apply_animation` | Apply an animation preset to a rigged model | — | — | — | ✅ | $0.01 |+| /api/mcp-3d (Studio) | `text_to_animation` | Generate an animation from a text prompt and retarget it onto a model | — | — | — | ✅ | free |+| /api/agent-mcp (Agent) | `getting_started` | Getting Started (free) | ✅ | — | ✅ | — | free / connection |+| /api/agent-mcp (Agent) | `wallet_status` | Check the agent's wallet | ✅ | — | — | ✅ | free / connection |+| /api/agent-mcp (Agent) | `find_services` | Find paid services the agent can call | ✅ | — | — | ✅ | free / connection |+| /api/agent-mcp (Agent) | `pay_and_call` | Pay an x402 service and return its result | — | ✅ | — | ✅ | free / connection |+| /api/agent-mcp (Agent) | `provision_wallet` | Create the agent's wallet | — | — | — | ✅ | free / connection |+| /api/agent-mcp (Agent) | `monetize_endpoint` | Publish a paid endpoint to earn USDC | — | — | — | ✅ | free / connection |+| /api/ibm-mcp (IBM Granite) | `ibm_granite_getting_started` | Getting Started (free) | ✅ | — | ✅ | — | free |+| /api/ibm-mcp (IBM Granite) | `ibm_granite_chat` | IBM Granite Chat ($0.02) | ✅ | — | — | ✅ | $0.02 |+| /api/ibm-mcp (IBM Granite) | `ibm_granite_code` | IBM Granite Code ($0.025) | ✅ | — | — | ✅ | $0.025 |+| /api/ibm-mcp (IBM Granite) | `ibm_granite_embed` | IBM Granite Embed ($0.005) | ✅ | — | ✅ | ✅ | $0.005 |+| /api/ibm-mcp (IBM Granite) | `ibm_granite_analyze` | IBM Granite Analyze ($0.04) | ✅ | — | — | ✅ | $0.04 |+| /api/ibm-mcp (IBM Granite) | `ibm_granite_forecast` | IBM Granite Forecast ($0.05) | ✅ | — | — | ✅ | $0.05 |+| /api/bazaar-mcp (Bazaar) | `getting_started` | Getting Started (free) | ✅ | — | ✅ | — | free / connection |+| /api/bazaar-mcp (Bazaar) | `search_services` | Search the x402 bazaar | ✅ | — | — | ✅ | free / connection |+| /api/bazaar-mcp (Bazaar) | `browse_services` | Browse the x402 bazaar | ✅ | — | — | ✅ | free / connection |+| /api/bazaar-mcp (Bazaar) | `get_service` | Get full details for one x402 service | ✅ | — | — | ✅ | free / connection |+| @three-ws/mcp-server (stdio) | `text_to_avatar` | Text → 3D avatar ($0.15) | — | — | — | ✅ | $0.15 |+| @three-ws/mcp-server (stdio) | `mesh_forge` | Text → 3D mesh ($0.25) | — | — | — | ✅ | $0.25 |+| @three-ws/mcp-server (stdio) | `forge_free` | Free text → 3D (TRELLIS) | — | — | — | ✅ | free |+| @three-ws/mcp-server (stdio) | `rig_mesh` | Rig 3D mesh ($0.20) | — | — | — | ✅ | $0.20 |+| @three-ws/mcp-server (stdio) | `forge_avatar` | Text/Image → rigged avatar ($0.45) | — | — | — | ✅ | $0.45 |+| @three-ws/mcp-server (stdio) | `ens_sns_resolve` | ENS + SNS resolve ($0.0005) | ✅ | — | — | ✅ | $0.0005 |+| @three-ws/mcp-server (stdio) | `agent_delegate_action` | Agent delegate action ($0.01) | — | — | — | ✅ | $0.01 |+| @three-ws/mcp-server (stdio) | `sentiment_pulse` | Sentiment pulse ($0.003) | ✅ | — | — | ✅ | $0.003 |+| @three-ws/mcp-server (stdio) | `get_pose_seed` | Pose seed ($0.001) | ✅ | — | ✅ | — | $0.001 |+| @three-ws/mcp-server (stdio) | `pump_snapshot` | Pump.fun snapshot ($0.005) | ✅ | — | — | ✅ | $0.005 |+| @three-ws/mcp-server (stdio) | `agent_reputation` | Agent reputation ($0.01) | ✅ | — | — | ✅ | $0.01 |+| @three-ws/mcp-server (stdio) | `vanity_grinder` | Solana vanity grinder ($0.05) | ✅ | — | — | — | $0.05 |+| @three-ws/mcp-server (stdio) | `agenc_list_tasks` | AgenC list tasks ($0.001) | ✅ | — | — | ✅ | $0.001 |+| @three-ws/mcp-server (stdio) | `agenc_get_task` | AgenC get task ($0.001) | ✅ | — | — | ✅ | $0.001 |+| @three-ws/mcp-server (stdio) | `agenc_get_agent` | AgenC get agent ($0.001) | ✅ | — | — | ✅ | $0.001 |+| @three-ws/mcp-server (stdio) | `aixbt_intel` | aixbt intel ($0.01) | ✅ | — | — | ✅ | $0.01 |+| @three-ws/mcp-server (stdio) | `aixbt_projects` | aixbt projects ($0.01) | ✅ | — | — | ✅ | $0.01 |++**Total tools across all servers: 89**++## Per-server counts++- /api/mcp (main): 35+- /api/mcp-3d (Studio): 21+- /api/agent-mcp (Agent): 6+- /api/ibm-mcp (IBM Granite): 6+- /api/bazaar-mcp (Bazaar): 4+- @three-ws/mcp-server (stdio): 17++## Tools flagged destructive (destructiveHint: true)++- `delete_avatar` (/api/mcp (main))+- `forget` (/api/mcp (main))+- `pay_and_call` (/api/agent-mcp (Agent))diff --git a/mcp-server/src/tools/_studio-core.js b/mcp-server/src/tools/_studio-core.jsnew file mode 100644index 000000000..b3f265e2c--- /dev/null+++ b/mcp-server/src/tools/_studio-core.js@@ -0,0 +1,854 @@+// Shared, dependency-free generation cores for the three.ws 3D pipeline.+//+// These are the REAL handlers behind the five generation tools — text→3D, 3D+// avatar, text/image→mesh, auto-rig, and one-call text→rigged-avatar. They are+// thin clients over the three.ws production pipeline (/api/forge) and, for+// text_to_avatar, Replicate: no GPU/LLM work happens here, all of it runs on+// the operator-funded backend that holds the provider keys.+//+// One implementation, two transports:+// • the npx-distributed stdio MCP server wraps each core in `paid()`/`free()`+// (mcp-server/src/tools/*.js) — x402 USDC gates the call.+// • the hosted, FREE 3D Studio endpoint (api/_studio/*, /api/mcp-studio) calls+// the SAME cores directly with no payment surface — abuse is bounded by+// server-side rate limits instead.+//+// Keeping the generation logic here (not forked into each transport) means the+// stdio and the free HTTP lanes can never drift. This module imports nothing+// payment- or schema-related: only the global `fetch` and the dependency-free+// humanoid classifier, so it loads in the Vercel `api/` bundle (which carries+// neither the @x402 stack nor zod-to-json-schema) unchanged.++import { classifyHumanoidPrompt } from './_humanoid.js';++// Standard tool error envelope — identical shape to payments.js `toolError`, so+// a core's error is indistinguishable whether it is surfaced through the paid+// stdio wrapper or the free HTTP endpoint. Duplicated (not imported) because+// payments.js pulls the @x402 stack, which the api/ bundle must not load.+export function coreError(code, message, extra) {+ return { ok: false, error: code, message, ...(extra || {}) };+}++function env(k, def) {+ const v = process.env[k];+ return v && String(v).trim() ? String(v).trim() : def;+}++// Resolve the three.ws origin from the first set of the provided env keys,+// trailing slash stripped. Each tool keeps its historical override key.+function apiBaseFrom(keys, def = 'https://three.ws') {+ for (const k of keys) {+ const v = env(k);+ if (v) return v.replace(/\/$/, '');+ }+ return def.replace(/\/$/, '');+}++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++const VALID_TIER = new Set(['draft', 'standard', 'high']);+const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);++// ---------------------------------------------------------------------------+// /api/forge client — submit + poll, shared by forge_free / mesh_forge /+// forge_avatar. The three callers differ only in: which backend/path they pin,+// whether a synchronous `status:"done"` submit is acceptable, and the submit+// timeout. Everything else is identical, so it lives here once.+// ---------------------------------------------------------------------------++async function submitForge({ base, payload, submitTimeoutMs, allowSyncDone }) {+ let res;+ try {+ res = await fetch(`${base}/api/forge`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(payload),+ signal: AbortSignal.timeout(submitTimeoutMs),+ });+ } catch (err) {+ if (err?.name === 'TimeoutError' || err?.name === 'AbortError') {+ const e = new Error('the 3D lane took too long to accept the job; try again');+ e.code = 'timeout';+ throw e;+ }+ const e = new Error(`forge unreachable: ${err?.message || err}`);+ e.code = 'provider_error';+ throw e;+ }+ const data = await res.json().catch(() => ({}));+ if (res.status === 503) {+ const e = new Error(data?.message || 'text→3D is not configured on the three.ws deployment');+ e.code = 'not_configured';+ throw e;+ }+ if (res.status === 429) {+ const e = new Error(data?.message || 'the 3D generator is busy; try again shortly');+ e.code = 'rate_limited';+ e.retryAfter = data?.retry_after;+ throw e;+ }+ const completedSync = allowSyncDone && data?.status === 'done' && data?.glb_url;+ if (!res.ok || !(data?.job_id || completedSync)) {+ const e = new Error(data?.message || `forge returned ${res.status}`);+ e.code = 'provider_error';+ throw e;+ }+ return data;+}++async function pollForge(jobId, { base, timeoutMs, intervalMs, failCode = 'generation_failed' }) {+ const deadline = Date.now() + timeoutMs;+ let last = null;+ while (Date.now() < deadline) {+ let res;+ try {+ res = await fetch(`${base}/api/forge?job=${encodeURIComponent(jobId)}`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(Math.max(intervalMs * 3, 15_000)),+ });+ } catch (err) {+ if (err?.name === 'AbortError' || err?.name === 'TimeoutError') {+ await sleep(intervalMs);+ continue;+ }+ const e = new Error(`forge poll failed: ${err?.message || err}`);+ e.code = 'provider_error';+ throw e;+ }+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ const e = new Error(data?.message || `forge poll returned ${res.status}`);+ e.code = 'provider_error';+ throw e;+ }+ last = data;+ if (data.status === 'done' && data.glb_url) return data;+ if (data.status === 'failed') {+ const e = new Error(data.error || 'generation failed');+ e.code = failCode;+ throw e;+ }+ await sleep(intervalMs);+ }+ return { ...(last || {}), _timedOut: true };+}++async function startRig({ base, glbUrl }) {+ const res = await fetch(`${base}/api/forge?action=rig`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ glb_url: glbUrl }),+ signal: AbortSignal.timeout(30_000),+ });+ const data = await res.json().catch(() => ({}));+ if (res.status === 503 || res.status === 501) {+ const e = new Error(data?.message || 'auto-rigging is not enabled on the three.ws deployment');+ e.code = 'not_configured';+ throw e;+ }+ if (res.status === 429) {+ const e = new Error(data?.message || 'the rigger is busy; try again shortly');+ e.code = 'rate_limited';+ e.retryAfter = data?.retry_after;+ throw e;+ }+ if (!res.ok || !data?.job_id) {+ const e = new Error(data?.message || `rig start returned ${res.status}`);+ e.code = 'provider_error';+ throw e;+ }+ return data;+}++// IBM Granite prompt director over the deployed /api/chat SSE endpoint. Returns+// the refined prompt string, or null on ANY failure so the caller falls back to+// the original prompt (fail-soft, never fabricated).+async function directPrompt({ base, rawPrompt, instruction, model }) {+ let res;+ try {+ res = await fetch(`${base}/api/chat`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'text/event-stream' },+ body: JSON.stringify({+ provider: 'watsonx',+ ...(model ? { model } : {}),+ message: `${instruction}\n\nIdea: ${rawPrompt}`,+ }),+ signal: AbortSignal.timeout(30_000),+ });+ } catch {+ return null;+ }+ if (!res.ok || !res.body) return null;++ let acc = '';+ try {+ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buf = '';+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += decoder.decode(value, { stream: true });+ const lines = buf.split('\n');+ buf = lines.pop() ?? '';+ for (const line of lines) {+ if (!line.startsWith('data: ')) continue;+ let evt;+ try {+ evt = JSON.parse(line.slice(6));+ } catch {+ continue;+ }+ if (evt.type === 'chunk' && typeof evt.text === 'string') acc += evt.text;+ else if (evt.type === 'error') return null;+ else if (evt.type === 'done' && typeof evt.text === 'string' && !acc) acc = evt.text;+ }+ }+ } catch {+ return null;+ }++ const refined = acc.trim().replace(/^["']|["']$/g, '').split('\n')[0].trim();+ return refined.length >= 3 && refined.length <= 1000 ? refined : null;+}++// Merge a multi-view array with a single image_url, de-duped + order-preserving.+function normalizeViews({ image_url, image_urls }) {+ const raw = Array.isArray(image_urls)+ ? image_urls+ : typeof image_url === 'string'+ ? [image_url]+ : [];+ const seen = new Set();+ const views = [];+ for (const v of raw) {+ if (typeof v !== 'string') continue;+ const t = v.trim();+ if (!t || seen.has(t)) continue;+ seen.add(t);+ views.push(t);+ }+ return views;+}++const MESH_DIRECTOR_INSTRUCTION =+ "You are a 3D asset art director. Rewrite the user's idea into ONE concise prompt for a " ++ 'text-to-3D generator. Describe a SINGLE isolated subject on a plain background, naming form, ' ++ 'materials, color, and surface detail. No scenes, no multiple objects, no text or logos, no ' ++ 'background environment. Output ONLY the rewritten prompt as a single line — no preamble, no quotes.';++const AVATAR_DIRECTOR_INSTRUCTION =+ "You are a 3D character art director. Rewrite the user's idea into ONE concise prompt for a text-to-3D " ++ 'generator that will be auto-rigged. Describe a SINGLE full-body humanoid character standing in a neutral ' ++ 'pose with arms slightly away from the body, on a plain background. Name the body type, outfit, materials, ' ++ 'colors, and key features. No scene, no props held across the body, no multiple characters, no text or logos. ' ++ 'Output ONLY the rewritten prompt as a single line — no preamble, no quotes.';++// ---------------------------------------------------------------------------+// forge_free — text → textured 3D GLB on the FREE NVIDIA NIM (TRELLIS) lane.+// ---------------------------------------------------------------------------+export async function runForgeFree({ prompt, tier }) {+ const trimmed = typeof prompt === 'string' ? prompt.trim() : '';+ if (trimmed.length < 3) {+ return coreError('invalid_input', 'Provide a text prompt of at least 3 characters.');+ }+ const tierId = VALID_TIER.has(tier) ? tier : 'draft';+ const base = apiBaseFrom(['FORGE_FREE_API_BASE']);+ const startedAt = Date.now();++ let job;+ try {+ // Pin the free NVIDIA NIM (TRELLIS) lane so the happy path is always the+ // zero-cost engine; path:"image" is the only path NVIDIA serves. NVCF can+ // finish inside the generous submit window, so accept a synchronous done.+ job = await submitForge({+ base,+ payload: { prompt: trimmed, tier: tierId, backend: 'nvidia', path: 'image' },+ submitTimeoutMs: 90_000,+ allowSyncDone: true,+ });+ } catch (err) {+ return coreError(err.code || 'provider_error', err.message, {+ ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}),+ });+ }++ if (job.status === 'done' && job.glb_url) {+ return shapeForgeFree({ data: job, prompt: trimmed, tierId, jobId: null, base, startedAt });+ }++ const timeoutMs = Number(env('FORGE_FREE_TIMEOUT_MS', '180000'));+ const intervalMs = Number(env('FORGE_FREE_POLL_MS', '3000'));+ let final;+ try {+ final = await pollForge(job.job_id, { base, timeoutMs, intervalMs });+ } catch (err) {+ return coreError(err.code || 'provider_error', err.message, {+ jobId: job.job_id,+ creationId: job.creation_id ?? null,+ durationMs: Date.now() - startedAt,+ });+ }++ if (final._timedOut) {+ return coreError('timeout', `generation did not finish within ${timeoutMs}ms`, {+ jobId: job.job_id,+ creationId: job.creation_id ?? null,+ status: final.status || 'running',+ resumeUrl: `${base}/api/forge?job=${job.job_id}`,+ durationMs: Date.now() - startedAt,+ });+ }++ return shapeForgeFree({ data: final, prompt: trimmed, tierId, jobId: job.job_id, base, startedAt });+}++function shapeForgeFree({ data, prompt, tierId, jobId, base, startedAt }) {+ const glbUrl = data.glb_url;+ return {+ ok: true,+ free: true,+ cost: '$0.00',+ mode: 'text_to_3d',+ glbUrl,+ preview: `${base}/viewer?src=${encodeURIComponent(glbUrl)}`,+ prompt,+ tier: tierId,+ backend: data.backend ?? null,+ jobId,+ creationId: data.creation_id ?? null,+ durable: Boolean(data.durable),+ durationMs: Date.now() - startedAt,+ fetchedAt: new Date().toISOString(),+ };+}++// ---------------------------------------------------------------------------+// mesh_forge — text / image / multi-view → textured 3D GLB (Granite-directed).+// ---------------------------------------------------------------------------+export async function runMeshForge({ prompt, image_url, image_urls, aspect_ratio, direct }) {+ const trimmedPrompt = typeof prompt === 'string' ? prompt.trim() : '';+ const views = normalizeViews({ image_url, image_urls });+ if (views.length > 4) {+ return coreError('invalid_input', 'Provide between 1 and 4 reference images.');+ }+ const imageMode = views.length > 0;+ if (!imageMode && trimmedPrompt.length < 3) {+ return coreError(+ 'invalid_input',+ 'Provide a prompt (3+ chars) for text→3D, or 1–4 image_urls for image/multi-view→3D.',+ );+ }+ const aspect = VALID_ASPECT.has(aspect_ratio) ? aspect_ratio : '1:1';+ const base = apiBaseFrom(['MESH_FORGE_API_BASE']);+ const started = Date.now();++ const runDirector =+ !imageMode && trimmedPrompt && direct !== false && env('MESH_FORGE_DIRECTOR', '1') !== '0';+ let directedPrompt = null;+ if (runDirector) {+ directedPrompt = await directPrompt({+ base,+ rawPrompt: trimmedPrompt,+ instruction: MESH_DIRECTOR_INSTRUCTION,+ model: env('MESH_FORGE_DIRECTOR_MODEL'),+ });+ }+ const effectivePrompt = directedPrompt || trimmedPrompt;++ let job;+ try {+ job = await submitForge({+ base,+ payload: imageMode+ ? { image_urls: views, prompt: effectivePrompt || undefined, aspect_ratio: aspect }+ : { prompt: effectivePrompt, aspect_ratio: aspect },+ submitTimeoutMs: 30_000,+ allowSyncDone: false,+ });+ } catch (err) {+ return coreError(err.code || 'provider_error', err.message, {+ ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}),+ });+ }++ const timeoutMs = Number(env('MESH_FORGE_TIMEOUT_MS', '180000'));+ const intervalMs = Number(env('MESH_FORGE_POLL_MS', '3000'));+ let final;+ try {+ final = await pollForge(job.job_id, { base, timeoutMs, intervalMs });+ } catch (err) {+ return coreError(err.code || 'provider_error', err.message, {+ jobId: job.job_id,+ creationId: job.creation_id ?? null,+ durationMs: Date.now() - started,+ });+ }++ const durationMs = Date.now() - started;+ if (final._timedOut) {+ return coreError('timeout', `reconstruction did not finish within ${timeoutMs}ms`, {+ jobId: job.job_id,+ creationId: job.creation_id ?? null,+ status: final.status || 'running',+ resumeUrl: `${base}/api/forge?job=${job.job_id}`,+ durationMs,+ });+ }++ const glbUrl = final.glb_url;+ return {+ ok: true,+ mode: imageMode ? 'image_to_3d' : 'text_to_3d',+ glbUrl,+ preview: `${base}/viewer?src=${encodeURIComponent(glbUrl)}`,+ prompt: trimmedPrompt || null,+ imageUrl: imageMode ? views[0] : null,+ imageUrls: imageMode ? views : null,+ viewsRequested: imageMode ? views.length : 0,+ viewsUsed: (typeof final.views_used === 'number' ? final.views_used : job.views_used) ?? null,+ multiview: (final.multiview ?? job.multiview) ?? null,+ backend: (final.backend ?? job.backend) ?? null,+ directedPrompt: directedPrompt || null,+ directed: Boolean(directedPrompt),+ jobId: job.job_id,+ creationId: final.creation_id ?? job.creation_id ?? null,+ referenceImageUrl: job.preview_image_url ?? null,+ durable: Boolean(final.durable),+ durationMs,+ fetchedAt: new Date().toISOString(),+ };+}++// ---------------------------------------------------------------------------+// rig_mesh — static GLB → rigged, animation-ready GLB (auto-rig pipeline).+// ---------------------------------------------------------------------------+export async function runRigMesh({ glb_url }) {+ const base = apiBaseFrom(['MESH_FORGE_API_BASE']);+ const started = Date.now();++ let job;+ try {+ job = await startRig({ base, glbUrl: glb_url });+ } catch (err) {+ return coreError(err.code || 'provider_error', err.message, {+ ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}),+ });+ }++ const timeoutMs = Number(env('RIG_MESH_TIMEOUT_MS', '180000'));+ const intervalMs = Number(env('RIG_MESH_POLL_MS', '3000'));+ let final;+ try {+ final = await pollForge(job.job_id, { base, timeoutMs, intervalMs, failCode: 'rig_failed' });+ } catch (err) {+ return coreError(err.code || 'provider_error', err.message, {+ jobId: job.job_id,+ creationId: job.creation_id ?? null,+ durationMs: Date.now() - started,+ });+ }++ const durationMs = Date.now() - started;+ if (final._timedOut) {+ return coreError('timeout', `rigging did not finish within ${timeoutMs}ms`, {+ jobId: job.job_id,+ creationId: job.creation_id ?? null,+ status: final.status || 'running',+ resumeUrl: `${base}/api/forge?job=${job.job_id}`,+ durationMs,+ });+ }++ const riggedGlbUrl = final.glb_url;+ return {+ ok: true,+ riggedGlbUrl,+ sourceGlbUrl: glb_url,+ poseStudioUrl: `${base}/pose?src=${encodeURIComponent(riggedGlbUrl)}`,+ jobId: job.job_id,+ creationId: final.creation_id ?? job.creation_id ?? null,+ durable: Boolean(final.durable),+ durationMs,+ fetchedAt: new Date().toISOString(),+ };+}++// ---------------------------------------------------------------------------+// forge_avatar — one-call text/image → rigged, animation-ready avatar.+// ---------------------------------------------------------------------------+export async function runForgeAvatar({+ prompt,+ image_url,+ image_urls,+ aspect_ratio,+ direct,+ allow_non_humanoid,+}) {+ const trimmedPrompt = typeof prompt === 'string' ? prompt.trim() : '';+ const views = normalizeViews({ image_url, image_urls });+ if (views.length > 4) {+ return coreError('invalid_input', 'Provide between 1 and 4 reference images.');+ }+ const imageMode = views.length > 0;+ if (!imageMode && trimmedPrompt.length < 3) {+ return coreError(+ 'invalid_input',+ 'Provide a prompt (3+ chars) for text→avatar, or 1–4 image_urls for image/multi-view→avatar.',+ );+ }++ // Humanoid gate runs BEFORE any work — rigging assumes a humanoid skeleton.+ let humanoidInfo;+ if (trimmedPrompt.length >= 3) {+ const verdict = classifyHumanoidPrompt(trimmedPrompt);+ humanoidInfo = {+ humanoid: verdict.humanoid,+ confidence: verdict.confidence,+ reason: verdict.reason,+ };+ if (!verdict.humanoid && allow_non_humanoid !== true) {+ return coreError(+ 'not_a_character',+ `"${trimmedPrompt}" does not look like a humanoid character (${verdict.reason}). ` ++ 'Auto-rigging needs a humanoid subject. Use forge_free or mesh_forge to generate a ' ++ 'non-character mesh, or set allow_non_humanoid:true to rig it anyway.',+ { humanoid: humanoidInfo },+ );+ }+ } else {+ humanoidInfo = {+ humanoid: true,+ confidence: 'low',+ reason: 'image-only request; trusting caller intent (no prompt to classify)',+ };+ }++ const aspect = VALID_ASPECT.has(aspect_ratio) ? aspect_ratio : '3:4';+ const base = apiBaseFrom(['MESH_FORGE_API_BASE']);+ const intervalMs = Number(env('FORGE_AVATAR_POLL_MS', '3000'));+ const started = Date.now();++ const runDirector =+ !imageMode && trimmedPrompt && direct !== false && env('FORGE_AVATAR_DIRECTOR', '1') !== '0';+ let directedPrompt = null;+ if (runDirector) {+ directedPrompt = await directPrompt({+ base,+ rawPrompt: trimmedPrompt,+ instruction: AVATAR_DIRECTOR_INSTRUCTION,+ });+ }+ const effectivePrompt = directedPrompt || trimmedPrompt;++ // Stage 1 — generate the textured mesh.+ const genStarted = Date.now();+ let genJob;+ try {+ genJob = await submitForge({+ base,+ payload: imageMode+ ? { image_urls: views, prompt: effectivePrompt || undefined, aspect_ratio: aspect }+ : { prompt: effectivePrompt, aspect_ratio: aspect },+ submitTimeoutMs: 30_000,+ allowSyncDone: true,+ });+ } catch (err) {+ return coreError(err.code || 'provider_error', err.message, {+ ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}),+ });+ }++ const genTimeout = Number(env('FORGE_AVATAR_GEN_TIMEOUT_MS', '180000'));+ let gen;+ if (genJob.status === 'done' && genJob.glb_url) {+ gen = genJob;+ } else {+ try {+ gen = await pollForge(genJob.job_id, {+ base,+ timeoutMs: genTimeout,+ intervalMs,+ failCode: 'generation_failed',+ });+ } catch (err) {+ return coreError(err.code || 'provider_error', err.message, {+ stage: 'generation',+ jobId: genJob.job_id,+ creationId: genJob.creation_id ?? null,+ durationMs: Date.now() - started,+ });+ }+ if (gen._timedOut) {+ return coreError('timeout', `generation did not finish within ${genTimeout}ms`, {+ stage: 'generation',+ jobId: genJob.job_id,+ creationId: genJob.creation_id ?? null,+ resumeUrl: `${base}/api/forge?job=${genJob.job_id}`,+ durationMs: Date.now() - started,+ });+ }+ }+ const meshGlbUrl = gen.glb_url;+ const generationMs = Date.now() - genStarted;++ // Stage 2 — auto-rig. Failures still surface meshGlbUrl so generation is not lost.+ const rigStarted = Date.now();+ let rigJob;+ try {+ rigJob = await startRig({ base, glbUrl: meshGlbUrl });+ } catch (err) {+ return coreError(err.code || 'provider_error', `rigging could not start: ${err.message}`, {+ stage: 'rig',+ meshGlbUrl,+ meshViewerUrl: `${base}/viewer?src=${encodeURIComponent(meshGlbUrl)}`,+ generationMs,+ durationMs: Date.now() - started,+ ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}),+ });+ }++ const rigTimeout = Number(env('FORGE_AVATAR_RIG_TIMEOUT_MS', '180000'));+ let rig;+ try {+ rig = await pollForge(rigJob.job_id, {+ base,+ timeoutMs: rigTimeout,+ intervalMs,+ failCode: 'rig_failed',+ });+ } catch (err) {+ return coreError(err.code || 'provider_error', `rigging failed: ${err.message}`, {+ stage: 'rig',+ meshGlbUrl,+ meshViewerUrl: `${base}/viewer?src=${encodeURIComponent(meshGlbUrl)}`,+ rigJobId: rigJob.job_id,+ generationMs,+ durationMs: Date.now() - started,+ });+ }+ if (rig._timedOut) {+ return coreError('timeout', `rigging did not finish within ${rigTimeout}ms`, {+ stage: 'rig',+ meshGlbUrl,+ meshViewerUrl: `${base}/viewer?src=${encodeURIComponent(meshGlbUrl)}`,+ rigJobId: rigJob.job_id,+ resumeUrl: `${base}/api/forge?job=${rigJob.job_id}`,+ generationMs,+ durationMs: Date.now() - started,+ });+ }++ const riggedGlbUrl = rig.glb_url;+ return {+ ok: true,+ mode: imageMode ? 'image_to_avatar' : 'text_to_avatar',+ riggedGlbUrl,+ meshGlbUrl,+ poseStudioUrl: `${base}/pose?src=${encodeURIComponent(riggedGlbUrl)}`,+ viewerUrl: `${base}/viewer?src=${encodeURIComponent(riggedGlbUrl)}`,+ animationReady: true,+ prompt: trimmedPrompt || null,+ imageUrls: imageMode ? views : null,+ viewsUsed: (gen.views_used ?? genJob.views_used) ?? (imageMode ? views.length : 0),+ backend: (gen.backend ?? genJob.backend) ?? null,+ directedPrompt: directedPrompt || null,+ directed: Boolean(directedPrompt),+ humanoid: humanoidInfo,+ meshCreationId: gen.creation_id ?? genJob.creation_id ?? null,+ riggedCreationId: rig.creation_id ?? rigJob.creation_id ?? null,+ rigJobId: rigJob.job_id,+ durable: Boolean(rig.durable),+ generationMs,+ rigMs: Date.now() - rigStarted,+ durationMs: Date.now() - started,+ fetchedAt: new Date().toISOString(),+ };+}++// ---------------------------------------------------------------------------+// text_to_avatar — text/image → 3D GLB avatar via Replicate (Hunyuan-3D).+// ---------------------------------------------------------------------------+const REPLICATE_BASE = 'https://api.replicate.com/v1';++function replicateAuthHeaders() {+ const token = env('REPLICATE_API_TOKEN');+ if (!token) {+ const err = new Error('REPLICATE_API_TOKEN is not configured on the server');+ err.code = 'not_configured';+ throw err;+ }+ return { authorization: `Bearer ${token}`, 'content-type': 'application/json' };+}++function extractGlbUrl(output) {+ if (!output) return null;+ if (typeof output === 'string') return output;+ if (Array.isArray(output)) {+ for (const v of output) {+ if (typeof v === 'string' && /\.glb(\?|$)/i.test(v)) return v;+ }+ for (const v of output) {+ if (typeof v === 'string' && /^https?:\/\//.test(v)) return v;+ }+ }+ if (typeof output === 'object') {+ for (const key of ['glb', 'mesh', 'mesh_url', 'output_url', 'url', 'model']) {+ if (typeof output[key] === 'string') return output[key];+ }+ }+ return null;+}++async function submitPrediction({ version, input }) {+ const res = await fetch(`${REPLICATE_BASE}/predictions`, {+ method: 'POST',+ headers: replicateAuthHeaders(),+ body: JSON.stringify({ version, input }),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ const err = new Error(data?.detail || data?.title || `replicate returned ${res.status}`);+ err.code = 'provider_error';+ err.providerStatus = res.status;+ throw err;+ }+ return data;+}++async function pollPrediction(predictionId, { timeoutMs, intervalMs }) {+ const deadline = Date.now() + timeoutMs;+ let last = null;+ const perFetchTimeoutMs = Math.max(intervalMs * 3, 10_000);+ while (Date.now() < deadline) {+ let r;+ try {+ r = await fetch(`${REPLICATE_BASE}/predictions/${encodeURIComponent(predictionId)}`, {+ headers: replicateAuthHeaders(),+ signal: AbortSignal.timeout(perFetchTimeoutMs),+ });+ } catch (err) {+ if (err?.name === 'AbortError' || err?.name === 'TimeoutError') {+ await sleep(intervalMs);+ continue;+ }+ const e = new Error(`replicate poll fetch failed: ${err?.message || err}`);+ e.code = 'provider_error';+ throw e;+ }+ const data = await r.json().catch(() => ({}));+ if (!r.ok) {+ const err = new Error(data?.detail || `replicate poll returned ${r.status}`);+ err.code = 'provider_error';+ throw err;+ }+ last = data;+ const s = data.status;+ if (s === 'succeeded' || s === 'failed' || s === 'canceled') return data;+ await sleep(intervalMs);+ }+ return { ...last, _timedOut: true };+}++async function rehostIfRequested(glbUrl, { prompt, images }) {+ if (env('MCP_TEXT_TO_AVATAR_REHOST', '0') !== '1') return null;+ const endpoint = env('MCP_REHOST_ENDPOINT', 'https://three.ws/api/avatars/ingest-url');+ const ingestKey = env('MCP_REHOST_KEY');+ if (!ingestKey) return null;+ try {+ const r = await fetch(endpoint, {+ method: 'POST',+ headers: { 'content-type': 'application/json', authorization: `Bearer ${ingestKey}` },+ body: JSON.stringify({+ source_url: glbUrl,+ name: (prompt || 'text-to-avatar').slice(0, 80),+ source: 'mcp',+ source_meta: { provider: 'replicate', prompt, images },+ }),+ });+ if (!r.ok) return { error: `rehost failed: ${r.status}` };+ return await r.json();+ } catch (err) {+ return { error: err?.message || 'rehost call failed' };+ }+}++export async function runTextToAvatar({ prompt, images, seed, texture }) {+ const version = env('REPLICATE_TEXT_TO_AVATAR_MODEL');+ if (!version) {+ return coreError(+ 'not_configured',+ 'REPLICATE_TEXT_TO_AVATAR_MODEL is not set on the server. Pin a commercial-OK image/text-to-3D version (e.g. tencent/hunyuan-3d-3.1 latest).',+ );+ }+ if (!prompt && (!images || images.length === 0)) {+ return coreError('invalid_input', 'Provide either prompt or images[].');+ }+ const input = {+ prompt: prompt || undefined,+ image: images && images.length ? images[0] : undefined,+ images: images && images.length ? images : undefined,+ seed: typeof seed === 'number' ? seed : undefined,+ texture: typeof texture === 'boolean' ? texture : true,+ };+ Object.keys(input).forEach((k) => input[k] === undefined && delete input[k]);++ const started = Date.now();+ let submitted;+ try {+ submitted = await submitPrediction({ version, input });+ } catch (err) {+ return coreError(err.code || 'provider_error', err.message);+ }++ const timeoutMs = Number(env('MCP_TEXT_TO_AVATAR_TIMEOUT_MS', '110000'));+ const intervalMs = Number(env('MCP_TEXT_TO_AVATAR_POLL_MS', '2000'));+ let finalState;+ try {+ finalState = await pollPrediction(submitted.id, { timeoutMs, intervalMs });+ } catch (err) {+ return coreError(err.code || 'provider_error', err.message, { predictionId: submitted.id });+ }++ const durationMs = Date.now() - started;+ if (finalState._timedOut) {+ return coreError('timeout', `prediction did not finish within ${timeoutMs}ms`, {+ predictionId: submitted.id,+ status: finalState.status,+ resumeUrl: `${REPLICATE_BASE}/predictions/${submitted.id}`,+ durationMs,+ });+ }+ if (finalState.status === 'failed' || finalState.status === 'canceled') {+ return coreError(+ 'prediction_failed',+ finalState.error || `prediction ended with status ${finalState.status}`,+ { predictionId: submitted.id, durationMs },+ );+ }++ const glbUrl = extractGlbUrl(finalState.output);+ if (!glbUrl) {+ return coreError('no_glb_in_output', 'prediction succeeded but no GLB url was found in output', {+ rawOutput: finalState.output,+ predictionId: submitted.id,+ durationMs,+ });+ }++ const rehost = await rehostIfRequested(glbUrl, { prompt, images });+ return {+ ok: true,+ predictionId: submitted.id,+ glbUrl,+ rehosted: rehost,+ prompt: prompt || null,+ images: images || null,+ seed: typeof seed === 'number' ? seed : null,+ model: version,+ durationMs,+ preview: `https://three.ws/viewer?src=${encodeURIComponent(glbUrl)}`,+ fetchedAt: new Date().toISOString(),+ };+}diff --git a/mcp-server/src/tools/forge-free.js b/mcp-server/src/tools/forge-free.jsindex 0e0798e92..52d4f6763 100644--- a/mcp-server/src/tools/forge-free.js+++ b/mcp-server/src/tools/forge-free.js@@ -6,21 +6,9 @@// drafts — so anyone can turn a text prompt into a downloadable, viewable 3D// model with NO x402 payment and NO API key.//-// Pipeline:-// POST /api/forge { prompt, tier, backend:"nvidia" }-// → NVCF generates the mesh natively from the prompt (no FLUX intermediate-// view), persists the GLB to three.ws R2, and returns a durable URL. NVCF-// usually completes synchronously (~12–15s at draft) → status:"done" on-// the submit; when it queues the job we poll GET ?job=<id> to a terminal-// state. Returns the GLB URL plus a three.ws viewer link that renders the-// model in-browser. Feed the GLB to `rig_mesh` to make it animation-ready.-//-// Honesty: the free lane is the platform's "never dead-end" default — if NVCF is-// momentarily unreachable or over-quota, /api/forge degrades the SAME request to-// its standing engine and reports the backend that actually ran. This tool-// surfaces that `backend` verbatim, so a degrade is visible, never silent. The-// CALLER is never charged either way (there is no x402 here); only the-// platform's own infra is involved.+// The generation logic lives in `_studio-core.js` (runForgeFree) so the stdio+// (paid-transport) server and the hosted FREE 3D Studio endpoint+// (api/_studio, /api/mcp-studio) share ONE implementation and never drift.//// Environment (all optional — sensible prod defaults):// FORGE_FREE_API_BASE — three.ws origin. Default https://three.ws@@ -29,8 +17,9 @@import { z } from 'zod';-import { free, toolError } from '../payments.js';+import { free } from '../payments.js';import { jsonSchemaFromZod } from './_shared.js';+import { runForgeFree } from './_studio-core.js';const TOOL_NAME = 'forge_free';const TOOL_DESCRIPTION =@@ -43,135 +32,6 @@ const TOOL_DESCRIPTION ='for image/multi-view → 3D or the Granite-directed paid chain use mesh_forge. Feed the returned glbUrl ' +'to rig_mesh to make it animation-ready. Free — no payment required.';-const VALID_TIER = new Set(['draft', 'standard', 'high']);--function env(k, def) {- const v = process.env[k];- return v && String(v).trim() ? String(v).trim() : def;-}--function apiBase() {- return env('FORGE_FREE_API_BASE', 'https://three.ws').replace(/\/$/, '');-}--// Submit a text→3D job to the free NVIDIA NIM lane. The forge endpoint may-// answer in one of two shapes:-// • synchronous completion — { status:"done", glb_url, ... } (NVCF finished-// inside the submit window; no job to poll), or-// • queued — { job_id, status:"queued", ... } (poll GET ?job=<id>).-// Accept BOTH; mesh_forge's startForge requires a job_id and would wrongly throw-// on the free lane's common synchronous-done response.-async function startForge({ prompt, tier }) {- const base = apiBase();- let res;- try {- res = await fetch(`${base}/api/forge`, {- method: 'POST',- headers: { 'content-type': 'application/json' },- // Pin the free NVIDIA NIM (TRELLIS) lane explicitly so the happy path is- // always the zero-cost engine — never the platform's paid Replicate lane.- // The endpoint still degrades to its standing engine if NVCF is down and- // reports which backend ran (surfaced in the result), so this is honest,- // not a silent paid fallback. path:"image" is the only path NVIDIA serves.- body: JSON.stringify({ prompt, tier, backend: 'nvidia', path: 'image' }),- // NVCF can complete synchronously inside the submit (the endpoint holds the- // connection up to its ~45s provider window before returning done), so give- // the submit a generous ceiling rather than the 30s paid-lane budget.- signal: AbortSignal.timeout(90_000),- });- } catch (err) {- if (err?.name === 'TimeoutError' || err?.name === 'AbortError') {- const e = new Error('the free 3D lane took too long to accept the job; try again');- e.code = 'timeout';- throw e;- }- const e = new Error(`forge unreachable: ${err?.message || err}`);- e.code = 'provider_error';- throw e;- }-- const data = await res.json().catch(() => ({}));- if (res.status === 503) {- const e = new Error(data?.message || 'free text→3D is not configured on the three.ws deployment');- e.code = 'not_configured';- throw e;- }- if (res.status === 429) {- const e = new Error(data?.message || 'the free 3D lane is busy; try again shortly');- e.code = 'rate_limited';- e.retryAfter = data?.retry_after;- throw e;- }- const completedSync = data?.status === 'done' && data?.glb_url;- if (!res.ok || !(data?.job_id || completedSync)) {- const e = new Error(data?.message || `forge returned ${res.status}`);- e.code = 'provider_error';- throw e;- }- return data; // { job_id?, creation_id, status, glb_url?, backend, durable?, ... }-}--async function pollForge(jobId, { timeoutMs, intervalMs }) {- const base = apiBase();- const deadline = Date.now() + timeoutMs;- let last = null;- while (Date.now() < deadline) {- let res;- try {- res = await fetch(`${base}/api/forge?job=${encodeURIComponent(jobId)}`, {- headers: { accept: 'application/json' },- signal: AbortSignal.timeout(Math.max(intervalMs * 3, 15_000)),- });- } catch (err) {- if (err?.name === 'AbortError' || err?.name === 'TimeoutError') {- await new Promise((r) => setTimeout(r, intervalMs));- continue;- }- const e = new Error(`forge poll failed: ${err?.message || err}`);- e.code = 'provider_error';- throw e;- }- const data = await res.json().catch(() => ({}));- if (!res.ok) {- const e = new Error(data?.message || `forge poll returned ${res.status}`);- e.code = 'provider_error';- throw e;- }- last = data;- if (data.status === 'done' && data.glb_url) return data;- if (data.status === 'failed') {- const e = new Error(data.error || 'generation failed');- e.code = 'generation_failed';- throw e;- }- await new Promise((r) => setTimeout(r, intervalMs));- }- return { ...(last || {}), _timedOut: true };-}--// Shape the final success envelope. `backend` is reported verbatim from the-// pipeline so a degrade off the free NVIDIA lane is visible, never silent.-function shapeResult({ data, prompt, tierId, jobId, startedAt }) {- const glbUrl = data.glb_url;- const preview = `${apiBase()}/viewer?src=${encodeURIComponent(glbUrl)}`;- return {- ok: true,- free: true,- cost: '$0.00',- mode: 'text_to_3d',- glbUrl,- preview,- prompt,- tier: tierId,- backend: data.backend ?? null,- jobId,- creationId: data.creation_id ?? null,- durable: Boolean(data.durable),- durationMs: Date.now() - startedAt,- fetchedAt: new Date().toISOString(),- };-}-const inputZodShape = {prompt: z.string()@@ -191,57 +51,8 @@ const inputZodShape = {const inputJsonSchema = jsonSchemaFromZod(inputZodShape);export function buildForgeFreeTool() {- const handler = free(- { toolName: TOOL_NAME, inputSchema: inputJsonSchema },- async ({ prompt, tier }) => {- const trimmed = typeof prompt === 'string' ? prompt.trim() : '';- if (trimmed.length < 3) {- return toolError('invalid_input', 'Provide a text prompt of at least 3 characters.');- }- const tierId = VALID_TIER.has(tier) ? tier : 'draft';- const startedAt = Date.now();-- // Stage 1 — submit to the free NVIDIA NIM text→3D lane.- let job;- try {- job = await startForge({ prompt: trimmed, tier: tierId });- } catch (err) {- return toolError(err.code || 'provider_error', err.message, {- ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}),- });- }-- // Fast path — NVCF completed inside the submit and already persisted the GLB.- if (job.status === 'done' && job.glb_url) {- return shapeResult({ data: job, prompt: trimmed, tierId, jobId: null, startedAt });- }-- // Stage 2 — poll the queued job to a terminal state.- const timeoutMs = Number(env('FORGE_FREE_TIMEOUT_MS', '180000'));- const intervalMs = Number(env('FORGE_FREE_POLL_MS', '3000'));- let final;- try {- final = await pollForge(job.job_id, { timeoutMs, intervalMs });- } catch (err) {- return toolError(err.code || 'provider_error', err.message, {- jobId: job.job_id,- creationId: job.creation_id ?? null,- durationMs: Date.now() - startedAt,- });- }-- if (final._timedOut) {- return toolError('timeout', `generation did not finish within ${timeoutMs}ms`, {- jobId: job.job_id,- creationId: job.creation_id ?? null,- status: final.status || 'running',- resumeUrl: `${apiBase()}/api/forge?job=${job.job_id}`,- durationMs: Date.now() - startedAt,- });- }-- return shapeResult({ data: final, prompt: trimmed, tierId, jobId: job.job_id, startedAt });- },+ const handler = free({ toolName: TOOL_NAME, inputSchema: inputJsonSchema }, (args) =>+ runForgeFree(args),);return {diff --git a/mcp-server/src/tools/mesh-forge.js b/mcp-server/src/tools/mesh-forge.jsindex d788393c7..b9cdfac57 100644--- a/mcp-server/src/tools/mesh-forge.js+++ b/mcp-server/src/tools/mesh-forge.js@@ -8,191 +8,31 @@// holds the Replicate / watsonx keys). The x402 USDC payment is what gates the// call.//-// Two modes:-// • text→3D — a chain of specialist models, each doing one job:-// 1. Prompt director (IBM Granite via /api/chat, provider=watsonx) —-// rewrites the caller's rough idea into an optimized 3D-generation spec-// (subject, style, materials, single-subject framing). Fail-soft: if-// the director is unreachable or disabled, the original prompt is-// forwarded unchanged and `directed:false` is reported — never faked.-// 2. Reference synthesis + reconstruction (/api/forge) — FLUX renders a-// clean reference image, then TRELLIS / Hunyuan3D reconstruct a-// textured GLB.-// • image→3D — a caller-supplied image_url is reconstructed directly-// (/api/forge with image_url); the prompt-director stage is skipped.-//-// Either mode returns a textured GLB URL and a three.ws viewer link. Rigging is-// a separate composable step — feed the returned glbUrl to the `rig_mesh` tool-// for a skeleton + skin weights (animation-ready) GLB.+// The generation logic lives in `_studio-core.js` (runMeshForge) so the paid+// stdio transport and the hosted FREE 3D Studio endpoint (api/_studio,+// /api/mcp-studio) share ONE implementation and never drift. Two modes:+// • text→3D — IBM Granite directs the prompt, FLUX renders a reference image,+// then TRELLIS / Hunyuan3D reconstruct a textured GLB.+// • image→3D — a caller-supplied image_url (or 1–4 multi-view image_urls) is+// reconstructed directly.//// Environment (all optional — sensible prod defaults):-// MESH_FORGE_API_BASE — three.ws origin. Default https://three.ws-// MESH_FORGE_DIRECTOR — "0" to skip the Granite director stage. Default on.+// MESH_FORGE_API_BASE — three.ws origin. Default https://three.ws+// MESH_FORGE_DIRECTOR — "0" to skip the Granite director stage. Default on.// MESH_FORGE_DIRECTOR_MODEL — watsonx model id for direction. Default server default.-// MESH_FORGE_TIMEOUT_MS — overall reconstruct poll budget. Default 180000.-// MESH_FORGE_POLL_MS — poll interval. Default 3000.+// MESH_FORGE_TIMEOUT_MS — overall reconstruct poll budget. Default 180000.+// MESH_FORGE_POLL_MS — poll interval. Default 3000.import { z } from 'zod';-import { paid, toolError } from '../payments.js';+import { paid } from '../payments.js';import { jsonSchemaFromZod } from './_shared.js';+import { runMeshForge } from './_studio-core.js';const TOOL_NAME = 'mesh_forge';const TOOL_DESCRIPTION ='Generate a textured 3D GLB model from a text prompt, a single reference image, OR 2–4 reference views of the same object. In text mode, a chain of specialist models runs: an IBM Granite "prompt director" rewrites the prompt into an optimized 3D spec, FLUX renders a reference image, then Microsoft TRELLIS / Tencent Hunyuan3D reconstruct the mesh. In image mode, a supplied image_url is reconstructed directly. In multi-view mode, pass image_urls (1–4 angles such as front/back/left/right) and the backend fuses them for a higher-fidelity mesh with no hallucinated back. Returns the GLB URL, a three.ws viewer link, how many views were fused, which backend handled it, the directed prompt (text mode), and timing. Feed the GLB to rig_mesh for a rigged, animation-ready model. Paid: $0.25 USDC.';-const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);--function env(k, def) {- const v = process.env[k];- return v && String(v).trim() ? String(v).trim() : def;-}--function apiBase() {- return env('MESH_FORGE_API_BASE', 'https://three.ws').replace(/\/$/, '');-}--// The director system instruction. Granite turns a loose idea into a tight,-// single-subject generation spec — the single biggest lever on mesh quality.-const DIRECTOR_INSTRUCTION =- 'You are a 3D asset art director. Rewrite the user\'s idea into ONE concise prompt for a ' +- 'text-to-3D generator. Describe a SINGLE isolated subject on a plain background, naming form, ' +- 'materials, color, and surface detail. No scenes, no multiple objects, no text or logos, no ' +- 'background environment. Output ONLY the rewritten prompt as a single line — no preamble, no quotes.';--// Drive the deployed /api/chat SSE endpoint with IBM Granite (provider=watsonx)-// to refine the prompt. Returns the refined prompt string, or null on any-// failure so the caller can fall back to the original prompt (fail-soft, never-// fabricated). watsonx is a server-side key on prod; an anonymous caller may-// request provider:"watsonx" explicitly per api/chat.js routing.-async function directPrompt(rawPrompt) {- const base = apiBase();- const model = env('MESH_FORGE_DIRECTOR_MODEL');- let res;- try {- res = await fetch(`${base}/api/chat`, {- method: 'POST',- headers: { 'content-type': 'application/json', accept: 'text/event-stream' },- body: JSON.stringify({- provider: 'watsonx',- ...(model ? { model } : {}),- message: `${DIRECTOR_INSTRUCTION}\n\nIdea: ${rawPrompt}`,- }),- signal: AbortSignal.timeout(30_000),- });- } catch {- return null;- }- if (!res.ok || !res.body) return null;-- // Collect SSE `data: {type:'chunk',text}` events until `done`/stream end.- let acc = '';- try {- const reader = res.body.getReader();- const decoder = new TextDecoder();- let buf = '';- for (;;) {- const { value, done } = await reader.read();- if (done) break;- buf += decoder.decode(value, { stream: true });- const lines = buf.split('\n');- buf = lines.pop() ?? '';- for (const line of lines) {- if (!line.startsWith('data: ')) continue;- let evt;- try {- evt = JSON.parse(line.slice(6));- } catch {- continue;- }- if (evt.type === 'chunk' && typeof evt.text === 'string') acc += evt.text;- else if (evt.type === 'error') return null;- else if (evt.type === 'done') {- if (typeof evt.text === 'string' && !acc) acc = evt.text;- }- }- }- } catch {- return null;- }-- const refined = acc.trim().replace(/^["']|["']$/g, '').split('\n')[0].trim();- return refined.length >= 3 && refined.length <= 1000 ? refined : null;-}--async function startForge({ prompt, aspect, imageUrls }) {- const base = apiBase();- // Multi-view: send all supplied views as image_urls[]; the three.ws pipeline- // routes >1 view to a multi-view-capable backend (and reports a downgrade if- // the configured backend can't fuse them). Text mode sends just the prompt.- const payload =- Array.isArray(imageUrls) && imageUrls.length- ? { image_urls: imageUrls, prompt: prompt || undefined, aspect_ratio: aspect }- : { prompt, aspect_ratio: aspect };- const res = await fetch(`${base}/api/forge`, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify(payload),- signal: AbortSignal.timeout(30_000),- });- const data = await res.json().catch(() => ({}));- if (res.status === 503) {- const e = new Error(data?.message || 'text-to-3D is not configured on the three.ws deployment');- e.code = 'not_configured';- throw e;- }- if (res.status === 429) {- const e = new Error(data?.message || 'the 3D generator is busy; try again shortly');- e.code = 'rate_limited';- e.retryAfter = data?.retry_after;- throw e;- }- if (!res.ok || !data?.job_id) {- const e = new Error(data?.message || `forge returned ${res.status}`);- e.code = 'provider_error';- throw e;- }- return data; // { job_id, creation_id, status, preview_image_url, ... }-}--async function pollForge(jobId, { timeoutMs, intervalMs }) {- const base = apiBase();- const deadline = Date.now() + timeoutMs;- let last = null;- while (Date.now() < deadline) {- let res;- try {- res = await fetch(`${base}/api/forge?job=${encodeURIComponent(jobId)}`, {- headers: { accept: 'application/json' },- signal: AbortSignal.timeout(Math.max(intervalMs * 3, 15_000)),- });- } catch (err) {- if (err?.name === 'AbortError' || err?.name === 'TimeoutError') {- await new Promise((r) => setTimeout(r, intervalMs));- continue;- }- const e = new Error(`forge poll failed: ${err?.message || err}`);- e.code = 'provider_error';- throw e;- }- const data = await res.json().catch(() => ({}));- if (!res.ok) {- const e = new Error(data?.message || `forge poll returned ${res.status}`);- e.code = 'provider_error';- throw e;- }- last = data;- if (data.status === 'done' && data.glb_url) return data;- if (data.status === 'failed') {- const e = new Error(data.error || 'generation failed');- e.code = 'generation_failed';- throw e;- }- await new Promise((r) => setTimeout(r, intervalMs));- }- return { ...(last || {}), _timedOut: true };-}-const inputZodShape = {prompt: z.string()@@ -250,115 +90,7 @@ export async function buildMeshForgeTool() {durationMs: 96000,},},- async ({ prompt, image_url, image_urls, aspect_ratio, direct }) => {- const trimmedPrompt = typeof prompt === 'string' ? prompt.trim() : '';-- // Merge the multi-view array form with the legacy single image_url,- // de-duplicating while preserving order. image_urls wins when present.- const rawViews = Array.isArray(image_urls)- ? image_urls- : typeof image_url === 'string'- ? [image_url]- : [];- const seenViews = new Set();- const views = [];- for (const v of rawViews) {- if (typeof v !== 'string') continue;- const t = v.trim();- if (!t || seenViews.has(t)) continue;- seenViews.add(t);- views.push(t);- }- if (views.length > 4) {- return toolError('invalid_input', 'Provide between 1 and 4 reference images.');- }- const imageMode = views.length > 0;- if (!imageMode && trimmedPrompt.length < 3) {- return toolError(- 'invalid_input',- 'Provide a prompt (3+ chars) for text→3D, or 1–4 image_urls for image/multi-view→3D.',- );- }- const aspect = VALID_ASPECT.has(aspect_ratio) ? aspect_ratio : '1:1';- const started = Date.now();-- // Stage 1 — Granite prompt director (text mode only; fail-soft, opt-out).- const runDirector =- !imageMode && trimmedPrompt && direct !== false && env('MESH_FORGE_DIRECTOR', '1') !== '0';- let directedPrompt = null;- if (runDirector) directedPrompt = await directPrompt(trimmedPrompt);- const effectivePrompt = directedPrompt || trimmedPrompt;-- // Stage 2 — submit reference synthesis + reconstruction (or direct- // image reconstruction when an image_url was supplied).- let job;- try {- job = await startForge({- prompt: effectivePrompt || undefined,- aspect,- imageUrls: imageMode ? views : undefined,- });- } catch (err) {- return toolError(err.code || 'provider_error', err.message, {- ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}),- });- }-- // Stage 3 — poll to a terminal state. 3D reconstruction is slow; budget- // generously but bound it so the caller never hangs forever.- const timeoutMs = Number(env('MESH_FORGE_TIMEOUT_MS', '180000'));- const intervalMs = Number(env('MESH_FORGE_POLL_MS', '3000'));- let final;- try {- final = await pollForge(job.job_id, { timeoutMs, intervalMs });- } catch (err) {- return toolError(err.code || 'provider_error', err.message, {- jobId: job.job_id,- creationId: job.creation_id ?? null,- durationMs: Date.now() - started,- });- }-- const durationMs = Date.now() - started;-- if (final._timedOut) {- return toolError('timeout', `reconstruction did not finish within ${timeoutMs}ms`, {- jobId: job.job_id,- creationId: job.creation_id ?? null,- status: final.status || 'running',- resumeUrl: `${apiBase()}/api/forge?job=${job.job_id}`,- durationMs,- });- }-- const glbUrl = final.glb_url;- const preview = `${apiBase()}/viewer?src=${encodeURIComponent(glbUrl)}`;-- return {- ok: true,- mode: imageMode ? 'image_to_3d' : 'text_to_3d',- glbUrl,- preview,- prompt: trimmedPrompt || null,- imageUrl: imageMode ? views[0] : null,- imageUrls: imageMode ? views : null,- viewsRequested: imageMode ? views.length : 0,- // How the backend actually conditioned the mesh — surfaced from the- // submit + poll responses so a multi-view downgrade is never silent.- viewsUsed:- (typeof final.views_used === 'number' ? final.views_used : job.views_used) ?? null,- multiview: (final.multiview ?? job.multiview) ?? null,- backend: (final.backend ?? job.backend) ?? null,- directedPrompt: directedPrompt || null,- directed: Boolean(directedPrompt),- jobId: job.job_id,- creationId: final.creation_id ?? job.creation_id ?? null,- referenceImageUrl: job.preview_image_url ?? null,- durable: Boolean(final.durable),- durationMs,- fetchedAt: new Date().toISOString(),- };- },+ (args) => runMeshForge(args),);return {diff --git a/mcp-server/src/tools/rig-mesh.js b/mcp-server/src/tools/rig-mesh.jsindex 633db0b6f..97ccabef7 100644--- a/mcp-server/src/tools/rig-mesh.js+++ b/mcp-server/src/tools/rig-mesh.js@@ -9,9 +9,9 @@// credentials; the USDC payment gates the call and all GPU work runs on// three.ws prod.//-// Composes with mesh_forge: forge a mesh (text or image → GLB), then feed the-// returned glbUrl here to get an animation-ready model that loads straight into-// the three.ws pose studio.+// The rig logic lives in `_studio-core.js` (runRigMesh) so the paid stdio+// transport and the hosted FREE 3D Studio endpoint (api/_studio,+// /api/mcp-studio) share ONE implementation and never drift.//// Environment (all optional — sensible prod defaults):// MESH_FORGE_API_BASE — three.ws origin. Default https://three.ws@@ -20,93 +20,14 @@import { z } from 'zod';-import { paid, toolError } from '../payments.js';+import { paid } from '../payments.js';import { jsonSchemaFromZod } from './_shared.js';+import { runRigMesh } from './_studio-core.js';const TOOL_NAME = 'rig_mesh';const TOOL_DESCRIPTION ='Auto-rig a static 3D GLB mesh into an animation-ready model: adds a humanoid skeleton and per-vertex skin weights via the three.ws rig pipeline (VAST-AI UniRig by default). Takes a GLB URL, returns the rigged GLB URL and a three.ws pose-studio link. Pairs with mesh_forge — forge a mesh, then rig it. Paid: $0.20 USDC.';-function env(k, def) {- const v = process.env[k];- return v && String(v).trim() ? String(v).trim() : def;-}--function apiBase() {- return env('MESH_FORGE_API_BASE', 'https://three.ws').replace(/\/$/, '');-}--async function startRig(glbUrl) {- const base = apiBase();- const res = await fetch(`${base}/api/forge?action=rig`, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({ glb_url: glbUrl }),- signal: AbortSignal.timeout(30_000),- });- const data = await res.json().catch(() => ({}));- if (res.status === 503) {- const e = new Error(data?.message || 'rigging is not configured on the three.ws deployment');- e.code = 'not_configured';- throw e;- }- if (res.status === 501) {- const e = new Error(data?.message || 'auto-rigging is not enabled on the three.ws deployment');- e.code = 'not_configured';- throw e;- }- if (res.status === 429) {- const e = new Error(data?.message || 'the rigger is busy; try again shortly');- e.code = 'rate_limited';- e.retryAfter = data?.retry_after;- throw e;- }- if (!res.ok || !data?.job_id) {- const e = new Error(data?.message || `rig start returned ${res.status}`);- e.code = 'provider_error';- throw e;- }- return data; // { job_id, creation_id, status, mode:'rig', source_glb_url }-}--async function pollRig(jobId, { timeoutMs, intervalMs }) {- const base = apiBase();- const deadline = Date.now() + timeoutMs;- let last = null;- while (Date.now() < deadline) {- let res;- try {- res = await fetch(`${base}/api/forge?job=${encodeURIComponent(jobId)}`, {- headers: { accept: 'application/json' },- signal: AbortSignal.timeout(Math.max(intervalMs * 3, 15_000)),- });- } catch (err) {- if (err?.name === 'AbortError' || err?.name === 'TimeoutError') {- await new Promise((r) => setTimeout(r, intervalMs));- continue;- }- const e = new Error(`rig poll failed: ${err?.message || err}`);- e.code = 'provider_error';- throw e;- }- const data = await res.json().catch(() => ({}));- if (!res.ok) {- const e = new Error(data?.message || `rig poll returned ${res.status}`);- e.code = 'provider_error';- throw e;- }- last = data;- if (data.status === 'done' && data.glb_url) return data;- if (data.status === 'failed') {- const e = new Error(data.error || 'rigging failed');- e.code = 'rig_failed';- throw e;- }- await new Promise((r) => setTimeout(r, intervalMs));- }- return { ...(last || {}), _timedOut: true };-}-const inputZodShape = {glb_url: z.string()@@ -135,58 +56,7 @@ export async function buildRigMeshTool() {durationMs: 48000,},},- async ({ glb_url }) => {- const started = Date.now();-- let job;- try {- job = await startRig(glb_url);- } catch (err) {- return toolError(err.code || 'provider_error', err.message, {- ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}),- });- }-- const timeoutMs = Number(env('RIG_MESH_TIMEOUT_MS', '180000'));- const intervalMs = Number(env('RIG_MESH_POLL_MS', '3000'));- let final;- try {- final = await pollRig(job.job_id, { timeoutMs, intervalMs });- } catch (err) {- return toolError(err.code || 'provider_error', err.message, {- jobId: job.job_id,- creationId: job.creation_id ?? null,- durationMs: Date.now() - started,- });- }-- const durationMs = Date.now() - started;-- if (final._timedOut) {- return toolError('timeout', `rigging did not finish within ${timeoutMs}ms`, {- jobId: job.job_id,- creationId: job.creation_id ?? null,- status: final.status || 'running',- resumeUrl: `${apiBase()}/api/forge?job=${job.job_id}`,- durationMs,- });- }-- const riggedGlbUrl = final.glb_url;- const poseStudioUrl = `${apiBase()}/pose?src=${encodeURIComponent(riggedGlbUrl)}`;-- return {- ok: true,- riggedGlbUrl,- sourceGlbUrl: glb_url,- poseStudioUrl,- jobId: job.job_id,- creationId: final.creation_id ?? job.creation_id ?? null,- durable: Boolean(final.durable),- durationMs,- fetchedAt: new Date().toISOString(),- };- },+ (args) => runRigMesh(args),);return {diff --git a/tests/mcp-server-annotations.test.js b/tests/mcp-server-annotations.test.jsnew file mode 100644index 000000000..978a88b9c--- /dev/null+++ b/tests/mcp-server-annotations.test.js@@ -0,0 +1,81 @@+import { describe, it, expect } from 'vitest';++// The stdio @three-ws/mcp-server package. buildTools() returns the exact tool+// surface registerTool() hands the MCP client — name, title, description,+// inputSchema, annotations — so asserting on it asserts on the tools/list wire+// payload. It is side-effect-free w.r.t. payment env, so it is safe to call+// here without secrets.+//+// The hosted HTTP servers are covered by mcp-remote-annotations.test.js; this is+// the matching invariant for the published stdio package, which had no test —+// the gap that let read-only tools ship without an explicit destructiveHint+// (the MCP spec defaults destructiveHint to TRUE when omitted, silently marking+// an annotation-less tool destructive).+import { buildTools } from '../mcp-server/src/index.js';++const tools = await buildTools();++// The stdio package exposes no irreversible delete/spend tools today: every tool+// is a read (lookups/snapshots/resolves) or a non-destructive generation+// (mesh/avatar/rig/delegate). If a genuinely destructive tool is ever added,+// pin it here AND set destructiveHint: true on it.+const DESTRUCTIVE_TOOLS = new Set();++describe('@three-ws/mcp-server stdio tool surface', () => {+ it('exposes a non-empty tool set', () => {+ expect(Array.isArray(tools)).toBe(true);+ expect(tools.length).toBeGreaterThan(0);+ });++ it('tool names are unique', () => {+ const names = tools.map((t) => t.name);+ expect(new Set(names).size).toBe(names.length);+ });++ it('tool titles are unique', () => {+ const titles = tools.map((t) => t.title);+ expect(new Set(titles).size).toBe(titles.length);+ });++ it('every tool has a name, a human title, and a description', () => {+ for (const t of tools) {+ expect(typeof t.name, `${t.name}: name`).toBe('string');+ expect(t.name.length).toBeGreaterThan(0);+ expect(typeof t.title, `${t.name}: title`).toBe('string');+ expect(t.title.length, `${t.name}: title`).toBeGreaterThan(0);+ expect(typeof t.description, `${t.name}: description`).toBe('string');+ expect(t.description.length, `${t.name}: description`).toBeGreaterThan(0);+ }+ });++ it('every tool carries complete, explicit boolean annotations', () => {+ for (const t of tools) {+ const a = t.annotations;+ expect(a, `${t.name}: annotations`).toBeTypeOf('object');+ for (const hint of [+ 'readOnlyHint',+ 'destructiveHint',+ 'idempotentHint',+ 'openWorldHint',+ ]) {+ expect(typeof a[hint], `${t.name}: ${hint}`).toBe('boolean');+ }+ }+ });++ it('only pinned destructive tools advertise destructiveHint: true', () => {+ for (const t of tools) {+ const a = t.annotations;+ if (DESTRUCTIVE_TOOLS.has(t.name)) {+ expect(a.destructiveHint, `${t.name}: destructiveHint`).toBe(true);+ expect(a.readOnlyHint, `${t.name}: readOnlyHint`).toBe(false);+ } else {+ expect(a.destructiveHint, `${t.name}: destructiveHint`).toBe(false);+ }+ // A read-only tool can never be destructive.+ if (a.readOnlyHint) {+ expect(a.destructiveHint, `${t.name}: read-only yet destructive`).toBe(false);+ }+ }+ });+});