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(mcp-grok): one Grok Bot connector URL that adds the account's agent tools on sign-in and never lists a wallet tool
nirholas80e7892545ef
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 0b9daf325..b5e74d7c7 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -229,7 +229,7 @@ bottom.| On-chain agent invocation | [contracts/agent-invocation/](contracts/agent-invocation) | In-repo | Anchor program: verifiable agent-to-agent skill invocation events. SDK: [agent-protocol-sdk/](agent-protocol-sdk) || Escrowed knocks (pay-per-reply) | [contracts/knock-escrow/](contracts/knock-escrow) | In-repo | Anchor program making a knock's payment conditional instead of final: `knock` parks the price in a vault owned by the knock's own PDA, and only three things can happen to it. `answer` pays the owner minus a fee capped at 10% in the program itself, `refuse` refunds the sender in full and takes no fee, and `reclaim` refunds the sender once the reply window closes and can be called by anyone. Each `KnockRecord` snapshots the fee that was in force when it was made, so an authority cannot reprice money already in escrow, and it stores only the SHA-256 of the message and the reply, never their text. The trust-me version of this settles straight to the owner at [api/knock/](api/knock) (row above); this is the version that works between strangers. Both sides are reachable from a browser: senders escrow and crank their own refund from the door page, owners open their on-chain door, answer for payment or refuse for a refund from [/knock](pages/knock.html), all signed by their own wallet ([src/knock/escrow-checkout.js](src/knock/escrow-checkout.js)). Docs: [contracts/knock-escrow/README.md](contracts/knock-escrow/README.md), [docs/knock.md](docs/knock.md). Tests: [tests/knock-escrow-program.test.js](tests/knock-escrow-program.test.js), [tests/knock-escrow-pda.test.js](tests/knock-escrow-pda.test.js), [tests/api-knock-escrowed.test.js](tests/api-knock-escrowed.test.js), [tests/api-knock-escrow-sync.test.js](tests/api-knock-escrow-sync.test.js) || Cross-chain SDKs | [sdk/](sdk), [solana-agent-sdk/](solana-agent-sdk), [agent-payments-sdk/](agent-payments-sdk), [agent-protocol-sdk/](agent-protocol-sdk) | Published | Cross-chain agent SDKs |-| MCP integration | [mcp-server/](mcp-server), [mcp-bridge/](mcp-bridge), [packages/*-mcp/](packages) | 43 npm servers + 7 hosted remote (50 total, incl. the free `/api/mcp-studio` 3D Studio, whose ChatGPT plugin surface [api/mcp-chatgpt.js](api/mcp-chatgpt.js) `→ /api/mcp-chatgpt` serves the eight 3D tools and the model viewer without the persona tools or any `frameDomains`; both doors share [api/_mcp-studio/handler.js](api/_mcp-studio/handler.js), and `SURFACES` in [api/_mcp-studio/dispatch.js](api/_mcp-studio/dispatch.js) defines what each advertises), all in the [MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas). Canonical metadata: [prompts/store-submissions/_generated/mcp-listing-source.json](prompts/store-submissions/_generated/mcp-listing-source.json), generated from the manifests by [scripts/build-mcp-listing-source.mjs](scripts/build-mcp-listing-source.mjs) (`npm run audit:mcp-listing` fails when it drifts) | Model Context Protocol surface, full server list in [docs/mcp.md](docs/mcp.md). One-click client setup: [pages/connect.html](pages/connect.html) `→ /connect` (Claude, Cursor and VS Code install links plus ChatGPT, Claude Code and generic steps, built live from [public/.well-known/mcp.json](public/.well-known/mcp.json) with tool counts from the catalog; config names match the CLI's `slugForPath`). CLI: [packages/three-ws-cli/](packages/three-ws-cli) (`npx three-ws setup`), docs [docs/cli.md](docs/cli.md) `→ /docs/cli`. Searchable index of every tool: [pages/mcp-tools.html](pages/mcp-tools.html) `→ /mcp-tools`, rendered from the generated [public/mcp-catalog.json](public/mcp-catalog.json) ([scripts/build-mcp-catalog.mjs](scripts/build-mcp-catalog.mjs), `npm run build:mcp-catalog`, staleness gated by `npm run audit:mcp-catalog`). Tool safety annotations are verified against each handler by [scripts/audit-mcp-safety.mjs](scripts/audit-mcp-safety.mjs) (`npm run audit:mcp-safety`, rules in [scripts/lib/mcp-safety-check.mjs](scripts/lib/mcp-safety-check.mjs), guarded-file list shared with the golden snapshot via [scripts/lib/mcp-tool-sources.mjs](scripts/lib/mcp-tool-sources.mjs)); docs [docs/mcp-safety.md](docs/mcp-safety.md) `→ /docs/mcp-safety`. Trust policy: [api/mcp-policy.js](api/mcp-policy.js) `-> GET /api/mcp-policy` turns those verified labels into a ready-to-paste client allowlist (profiles strict/balanced/open x formats claude/vscode/json), surfaced by the builder panel on `/mcp-tools`. Connector-review readiness (every paid stdio tool answers a clean x402 challenge, and the reviewer entitlement lifts it): [scripts/audit-mcp-reviewer-path.mjs](scripts/audit-mcp-reviewer-path.mjs), `npm run audit:mcp-reviewer`. Tests: [tests/mcp-safety-audit.test.js](tests/mcp-safety-audit.test.js), [tests/mcp-catalog.test.js](tests/mcp-catalog.test.js), [tests/api/mcp-policy.test.js](tests/api/mcp-policy.test.js) |+| MCP integration | [mcp-server/](mcp-server), [mcp-bridge/](mcp-bridge), [packages/*-mcp/](packages) | 43 npm servers + 8 hosted remote (51 total, incl. the free `/api/mcp-studio` 3D Studio, whose ChatGPT plugin surface [api/mcp-chatgpt.js](api/mcp-chatgpt.js) `→ /api/mcp-chatgpt` serves the eight 3D tools and the model viewer without the persona tools or any `frameDomains`, and whose Grok surface [api/mcp-grok.js](api/mcp-grok.js) `→ /api/mcp-grok` serves every studio tool with no widget templates plus, for a caller signed in with OAuth 2.1 or a connector key, the account's agent tools from the core server ([api/_mcp-studio/account-tools.js](api/_mcp-studio/account-tools.js), never a value-moving tool; docs [docs/grok.md](docs/grok.md), test [tests/mcp-grok-accounts.test.js](tests/mcp-grok-accounts.test.js)); all three doors share [api/_mcp-studio/handler.js](api/_mcp-studio/handler.js), and `SURFACES` in [api/_mcp-studio/dispatch.js](api/_mcp-studio/dispatch.js) defines what each advertises), all in the [MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas). Canonical metadata: [prompts/store-submissions/_generated/mcp-listing-source.json](prompts/store-submissions/_generated/mcp-listing-source.json), generated from the manifests by [scripts/build-mcp-listing-source.mjs](scripts/build-mcp-listing-source.mjs) (`npm run audit:mcp-listing` fails when it drifts) | Model Context Protocol surface, full server list in [docs/mcp.md](docs/mcp.md). One-click client setup: [pages/connect.html](pages/connect.html) `→ /connect` (Claude, Cursor and VS Code install links plus ChatGPT, Claude Code and generic steps, built live from [public/.well-known/mcp.json](public/.well-known/mcp.json) with tool counts from the catalog; config names match the CLI's `slugForPath`). CLI: [packages/three-ws-cli/](packages/three-ws-cli) (`npx three-ws setup`), docs [docs/cli.md](docs/cli.md) `→ /docs/cli`. Searchable index of every tool: [pages/mcp-tools.html](pages/mcp-tools.html) `→ /mcp-tools`, rendered from the generated [public/mcp-catalog.json](public/mcp-catalog.json) ([scripts/build-mcp-catalog.mjs](scripts/build-mcp-catalog.mjs), `npm run build:mcp-catalog`, staleness gated by `npm run audit:mcp-catalog`). Tool safety annotations are verified against each handler by [scripts/audit-mcp-safety.mjs](scripts/audit-mcp-safety.mjs) (`npm run audit:mcp-safety`, rules in [scripts/lib/mcp-safety-check.mjs](scripts/lib/mcp-safety-check.mjs), guarded-file list shared with the golden snapshot via [scripts/lib/mcp-tool-sources.mjs](scripts/lib/mcp-tool-sources.mjs)); docs [docs/mcp-safety.md](docs/mcp-safety.md) `→ /docs/mcp-safety`. Trust policy: [api/mcp-policy.js](api/mcp-policy.js) `-> GET /api/mcp-policy` turns those verified labels into a ready-to-paste client allowlist (profiles strict/balanced/open x formats claude/vscode/json), surfaced by the builder panel on `/mcp-tools`. Connector-review readiness (every paid stdio tool answers a clean x402 challenge, and the reviewer entitlement lifts it): [scripts/audit-mcp-reviewer-path.mjs](scripts/audit-mcp-reviewer-path.mjs), `npm run audit:mcp-reviewer`. Tests: [tests/mcp-safety-audit.test.js](tests/mcp-safety-audit.test.js), [tests/mcp-catalog.test.js](tests/mcp-catalog.test.js), [tests/api/mcp-policy.test.js](tests/api/mcp-policy.test.js) || Awesome 3D Agents (curated list) | Source [data/awesome.json](data/awesome.json), generator [scripts/build-awesome.mjs](scripts/build-awesome.mjs) (`npm run build:awesome`, drift-gated by `npm run check:awesome`, publishable mirror via `npm run awesome:standalone`), outputs [awesome/README.md](awesome/README.md) + [public/awesome.json](public/awesome.json), page [pages/awesome.html](pages/awesome.html) `-> /awesome`, link checker [scripts/check-awesome-links.mjs](scripts/check-awesome-links.mjs) (`npm run awesome:links`) | Live | An awesome-list of everything needed to give an AI agent a body: text-to-3D, capture and splatting, avatars, rigging, motion, lipsync and voice, web renderers, asset pipelines, physics and networking, agent frameworks, datasets, free assets, learning. One JSON source produces both the GitHub-facing list and the searchable page, so they cannot disagree. Every url is fetched and classified (ok / moved / bot-filtered / broken) before it ships; the checker stays out of the deploy path so a third-party outage cannot redden someone else's build. The README is written to pass `npx awesome-lint`: badge on the heading line, no License section, no Contributing entry in the contents, and every description capitalised and ended with a period, all enforced by the generator and by [tests/awesome-list.test.js](tests/awesome-list.test.js). Its last two lint rules read GitHub repository topics, which a list inside a product repo cannot satisfy, so `--standalone` emits a ready-to-publish mirror repo (readme, contributing, code of conduct, license) outside this checkout. Contributing: [awesome/CONTRIBUTING.md](awesome/CONTRIBUTING.md) || Agent Skills pack | [.agents/skills/](.agents/skills) (canonical) → manifest [.agents/skills/SKILLS.md](.agents/skills/SKILLS.md), [.agents/skills/skills-pack.json](.agents/skills/skills-pack.json); published 3D subset [public/skills/3d-studio/](public/skills/3d-studio) `→ /skills/3d-studio/` | In-repo; bundled in the `three-ws-core` [plugin](.claude-plugin/marketplace.json); 3D subset live on the site | Portable `SKILL.md` folders (Agent Skills open standard) for any Claude surface, in five categories: 3d/creative (cross-platform-safe), platform/agents (create an agent, author and sell its skills, hire other agents, connect a client to the MCP servers), wallet/payments, intel/trading, ops/production. Counts live in the generated manifest, never here. The 3d/creative ones are also published as a public, downloadable bundle at `/skills/3d-studio/` (`three-ws-3d-skills.zip`), which is what an OpenAI Plugin Directory submission uploads on its Skills tab; a skill referencing a tool [api/_mcp-studio/](api/_mcp-studio) does not declare is dropped rather than shipped as a dead path. Regenerate manifest: `npm run build:skills-pack` (drift gate `npm run check:skills-pack`); regenerate the published bundle: `npm run build:openai-skills` (drift gate `npm run check:openai-skills`, wired into `npm run gate`). Docs: [docs/agent-skills.md](docs/agent-skills.md) || Standalone skill repos | [scripts/build-standalone-skill-repos.mjs](scripts/build-standalone-skill-repos.mjs) → `.data/standalone-repos/<repo>/` (gitignored) | Generated on demand; publishing is owner-gated | Assembles the three.ws-origin skills into small, publishable repos so an external user installs with one `/plugin marketplace add nirholas/<repo>` instead of cloning this monorepo: `three-ws-skills` (everything), `three-ws-3d-skills` (the crypto-free 3d/creative subset), `three-ws-agent-economy-skills` (wallet/payments + platform/agents). Each output is a complete one-plugin marketplace (`.claude-plugin/{marketplace,plugin}.json`, `skills/`, generated `README.md` with every trigger, `LICENSE`). Built from the same `collectSkills()` the manifest uses, so a copy cannot drift; nothing is committed here. `npm run build:skill-repos`, validate with `npm run check:skill-repos` (wired into `npm run gate`). Docs: [docs/agent-skills.md](docs/agent-skills.md) |diff --git a/api/_lib/mcp-resources.js b/api/_lib/mcp-resources.jsindex b0d0e8b8d..1f8375fe0 100644--- a/api/_lib/mcp-resources.js+++ b/api/_lib/mcp-resources.js@@ -21,7 +21,14 @@ import { env } from './env.js';// Paths, not URLs: the origin is env.APP_ORIGIN at call time. Keep in step// with the servers in public/.well-known/mcp.json whose auth names OAuth or a// bearer (tests/mcp-resources.test.js fails when they drift).-export const OAUTH_MCP_PATHS = Object.freeze(['/api/mcp', '/api/mcp-3d', '/api/mcp-agent', '/api/mcp-bazaar', '/api/ibm-mcp']);+export const OAUTH_MCP_PATHS = Object.freeze([+ '/api/mcp',+ '/api/mcp-3d',+ '/api/mcp-agent',+ '/api/mcp-bazaar',+ '/api/ibm-mcp',+ '/api/mcp-grok',+]);const PLATFORM_PATH = '/api/mcp';const PRM_ROOT = '/.well-known/oauth-protected-resource';diff --git a/api/_mcp-studio/account-tools.js b/api/_mcp-studio/account-tools.jsnew file mode 100644index 000000000..577b9ba8c--- /dev/null+++ b/api/_mcp-studio/account-tools.js@@ -0,0 +1,103 @@+// The signed-in half of /api/mcp-grok: the account's agent tools, composed+// from the core server (/api/mcp) at the dispatch layer.+//+// Grok Bot holds its credential unattended (an OAuth 2.1 grant or a connector+// API key stored as a Bot secret), so this surface lists only tools that read+// or edit agent data: agents, their memory, their custom skills, and the+// account's avatars. Nothing here moves value. A tool is admitted only when it+// is on GROK_ACCOUNT_TOOLS AND the shared policy says it moves no funds and is+// not in the financial tier AND the core server's own tools/list advertises no+// price for it, so a later change to the policy or the prices can only shrink+// this list, never widen it.+//+// tools/call runs only a tool this caller's tools/list would show, through the+// core dispatcher unchanged: the same tool policy (enablement, the spend gate),+// scope check, usage accounting and error sanitizing as /api/mcp. Any other+// core tool name is unknown here, whatever scopes the credential holds, so an+// OAuth grant that includes `wallet:write` still cannot reach a wallet tool+// through this URL.+//+// The core catalog is imported lazily: an anonymous studio request never pays+// for loading every core tool module.++import { POLICY } from '@three-ws/mcp-policy';+import { hasScope } from '../_lib/auth.js';+import { spendScopeFor } from '../_mcp/policy.js';++// The core server's @three-ws/mcp-policy id.+const CORE_SERVER = 'three.ws';++export const GROK_ACCOUNT_TOOLS = Object.freeze([+ // Agents+ 'create_agent',+ 'attach_avatar_to_agent',+ 'identity_check',+ 'call_agent',+ // Agent memory+ 'remember',+ 'recall',+ // Agent skills (prompt-only instruction files)+ 'list_available_skills',+ 'list_custom_skills',+ 'get_custom_skill',+ 'create_custom_skill',+ 'update_custom_skill',+ 'import_community_skill',+ // The account's avatars+ 'list_my_avatars',+ 'get_avatar',+ 'get_embed_code',+ 'render_avatar_image',+]);++/** Does the shared policy put this core tool among the value-moving ones? */+export function movesValue(name) {+ if (spendScopeFor(CORE_SERVER, name)) return true;+ return POLICY[CORE_SERVER]?.[name]?.tier === 'financial';+}++const ADMITTED = new Set(GROK_ACCOUNT_TOOLS.filter((name) => !movesValue(name)));++/** Is `name` an account tool this surface serves? */+export function isAccountTool(name) {+ return typeof name === 'string' && ADMITTED.has(name);+}++let corePromise = null;+function loadCore() {+ corePromise ??= Promise.all([import('../_mcp/catalog.js'), import('../_mcp/dispatch.js')]).then(([catalog, dispatch]) => ({+ tools: catalog.TOOLS,+ dispatch: dispatch.dispatch,+ }));+ return corePromise;+}++/**+ * The account tools a signed-in caller sees on tools/list: admitted, granted by+ * the credential's scope (a tool it could only be refused is left out), enabled+ * by the account's MCP tool settings, and unpriced. The last two come from the+ * core server's own tools/list for this caller, so this surface can never show+ * a tool /api/mcp would hide from the same credential.+ */+export async function accountToolCatalog(auth, req) {+ if (!auth?.userId) return [];+ const { tools, dispatch } = await loadCore();+ const listed = await dispatch({ jsonrpc: '2.0', id: 'grok-account-tools', method: 'tools/list' }, auth, req);+ return (listed?.result?.tools || []).filter((t) => {+ if (!ADMITTED.has(t.name) || t.pricing) return false;+ const scope = tools[t.name]?.scope;+ return !scope || hasScope(auth.scope, scope);+ });+}++/**+ * Run one tools/call for an account tool through the core dispatcher, but only+ * when this caller's tools/list shows it. Returns the JSON-RPC response exactly+ * as /api/mcp would, or null when the tool is not listed for this caller.+ */+export async function callAccountTool(msg, auth, req) {+ const listed = await accountToolCatalog(auth, req);+ if (!listed.some((t) => t.name === msg.params?.name)) return null;+ const { dispatch } = await loadCore();+ return dispatch(msg, auth, req);+}diff --git a/api/_mcp-studio/dispatch.js b/api/_mcp-studio/dispatch.jsindex 92ef83261..29fa8d069 100644--- a/api/_mcp-studio/dispatch.js+++ b/api/_mcp-studio/dispatch.js@@ -14,6 +14,8 @@ import { PERSONA_TOOL_CATALOG, PERSONA_TOOLS } from './persona-tools.js';import { CATALOG_TOOL_CATALOG, CATALOG_TOOLS } from './catalog-tools.js';import { JOB_TOOL_CATALOG, JOB_TOOLS } from './job-tools.js';import { finishCall, gateCall, listForRequest } from '../_mcp/policy.js';+import { accountToolCatalog, callAccountTool, isAccountTool } from './account-tools.js';+import { studioOrigin } from './install-token.js';// The @three-ws/mcp-policy server id for the free studio.const POLICY_SERVER = 'threews-3d-studio-free';@@ -76,6 +78,20 @@ const GROK_INSTRUCTIONS = [// timeout is lost work, while a pending handle costs one check_job round trip.export const GROK_CALL_BUDGET_MS = 40_000;+// /api/mcp-grok also serves the account's agent tools (./account-tools.js) to a+// caller that signs in. Which half of the sentence the model reads depends on+// whether this request carried a valid credential.+const GROK_SIGNED_IN_INSTRUCTIONS = [+ 'This connector is signed in to a three.ws account, so it can also manage the account\'s agents:',+ 'create_agent, attach_avatar_to_agent (give an agent a generated body), remember and recall (agent memory), the',+ 'custom skill tools, list_my_avatars and get_embed_code. It can never move funds: wallet, payment and launch',+ 'actions happen only in a browser at https://three.ws/dashboard, so tell the user that when they ask for one.',+];+const GROK_ANONYMOUS_INSTRUCTIONS = [+ 'To also manage a three.ws account\'s agents, reconnect with a three.ws connector API key as the bearer token, or',+ 'sign in with OAuth 2.1 at https://three.ws/api/mcp-grok?auth=oauth.',+];+const CATALOG_INSTRUCTIONS = ['Before generating a prop, character or animation, search_catalog(q) checks the thousands of ready-made CC0 props,','rigged characters and motion clips three.ws already publishes; get_item_source(id) returns paste-ready code for a',@@ -97,7 +113,7 @@ const PERSONA_INSTRUCTIONS = ['idles between turns.',];-// Two surfaces share this dispatcher, each advertising a consistent set of+// Three surfaces share this dispatcher, each advertising a consistent set of// tools, widgets and model instructions.// full /api/mcp-studio: every tool and both widgets, for Claude, the// examples, and any MCP host that renders the inline living body,@@ -113,17 +129,33 @@ const PERSONA_INSTRUCTIONS = [// review for an exception.// grok /api/mcp-grok: every tool of the full surface for Grok Bot and the// xAI Responses API, with a per-call budget and instructions that-// hand out links in place of the widgets Grok does not render.-// ./handler.js keys its generation caps on the MCP session, because-// every Grok user reaches us from xAI's shared egress.+// hand out links in place of the widgets Grok does not render, so+// it lists no widget templates and no ui:// resources. A caller+// that signs in (OAuth 2.1 or a connector key, ./handler.js) also+// gets the account's agent tools (./account-tools.js), never a+// value-moving one. ./handler.js keys its generation caps on the MCP+// session, because every Grok user reaches us from xAI's shared+// egress.// check_job, get_job and the persona tools stay out of the generation quota; see// ./handler.js callsGenerationTool. look_at_model renders frames server-side, so// it rides that quota.+// A tool descriptor without the Apps SDK keys that bind it to a widget+// template, for a surface whose host renders none.+function withoutWidgetMeta(catalog) {+ return catalog.map((tool) => {+ if (!tool._meta) return tool;+ const meta = Object.fromEntries(Object.entries(tool._meta).filter(([key]) => !key.startsWith('openai/')));+ const { _meta: _dropped, ...rest } = tool;+ return Object.keys(meta).length ? { ...rest, _meta: meta } : rest;+ });+}+const SURFACES = {full: {server: 'mcp-studio',catalog: [...TOOL_CATALOG, ...JOB_TOOL_CATALOG, ...CATALOG_TOOL_CATALOG, ...PERSONA_TOOL_CATALOG],tools: { ...TOOLS, ...JOB_TOOLS, ...CATALOG_TOOLS, ...PERSONA_TOOLS },+ widgets: true,personas: true,jobTool: 'get_job',instructions: [...BASE_INSTRUCTIONS, ...JOB_INSTRUCTIONS, ...CATALOG_INSTRUCTIONS, ...PERSONA_INSTRUCTIONS].join(' '),@@ -132,15 +164,18 @@ const SURFACES = {server: 'mcp-chatgpt',catalog: [...TOOL_CATALOG],tools: { ...TOOLS },+ widgets: true,personas: false,instructions: [...BASE_INSTRUCTIONS, ...CHATGPT_INSTRUCTIONS].join(' '),callBudgetMs: CHATGPT_CALL_BUDGET_MS,},grok: {server: 'mcp-grok',- catalog: [...TOOL_CATALOG, ...JOB_TOOL_CATALOG, ...CATALOG_TOOL_CATALOG, ...PERSONA_TOOL_CATALOG],+ catalog: withoutWidgetMeta([...TOOL_CATALOG, ...JOB_TOOL_CATALOG, ...CATALOG_TOOL_CATALOG, ...PERSONA_TOOL_CATALOG]),tools: { ...TOOLS, ...JOB_TOOLS, ...CATALOG_TOOLS, ...PERSONA_TOOLS },+ widgets: false,personas: true,+ accounts: true,jobTool: 'get_job',instructions: [...BASE_INSTRUCTIONS,@@ -149,12 +184,19 @@ const SURFACES = {...PERSONA_INSTRUCTIONS,...GROK_INSTRUCTIONS,].join(' '),+ signedInInstructions: GROK_SIGNED_IN_INSTRUCTIONS.join(' '),+ anonymousInstructions: GROK_ANONYMOUS_INSTRUCTIONS.join(' '),callBudgetMs: GROK_CALL_BUDGET_MS,},};export const SURFACE_NAMES = Object.keys(SURFACES);+/** Does this surface serve the account's agent tools to a signed-in caller? */+export function surfaceServesAccounts(name) {+ return Boolean(Object.hasOwn(SURFACES, name) && SURFACES[name].accounts);+}+function surfaceOf(name) {return Object.hasOwn(SURFACES, name) ? SURFACES[name] : SURFACES.full;}@@ -172,7 +214,8 @@ export function toolsFor(name = 'full') {// The Apps SDK widget resources: the model viewer every generation tool renders,// and the living-body persona widget the embodiment tools render. _meta (incl.// the CSP) is built per call so the storage origin always tracks env.-function widgetResources(personas = true) {+function widgetResources({ widgets = true, personas = true } = {}) {+ if (!widgets) return [];const all = [{uri: COMPONENT_URI,@@ -258,8 +301,18 @@ async function onToolCall(params, auth, started, req, surface, opts = {}) {}}-export async function dispatch(msg, auth, req, { surface: surfaceName = 'full', caller = null, onProgress = null } = {}) {+// `opts.account` is the signed-in principal on a surface that serves accounts+// (./handler.js), or null. Studio tools always run as the anonymous `auth`, so+// signing in never changes what a free tool does; only the account tools see+// the account.+export async function dispatch(+ msg,+ auth,+ req,+ { surface: surfaceName = 'full', caller = null, onProgress = null, account = null } = {},+) {const surface = surfaceOf(surfaceName);+ const signedIn = Boolean(surface.accounts && account?.userId);const started = Date.now();const id = msg.id;const isNotification = id === undefined;@@ -268,23 +321,53 @@ export async function dispatch(msg, auth, req, { surface: surfaceName = 'full',const method = msg.method;if (method === 'initialize') {+ const accountNote = surface.accounts ? [signedIn ? surface.signedInInstructions : surface.anonymousInstructions] : [];return ok(id, {protocolVersion: PROTOCOL_VERSION,serverInfo: SERVER_INFO,- capabilities: { tools: { listChanged: false }, resources: { listChanged: false, subscribe: false }, logging: {} },- instructions: surface.instructions,+ capabilities: {+ tools: { listChanged: false },+ ...(surface.widgets ? { resources: { listChanged: false, subscribe: false } } : {}),+ logging: {},+ },+ instructions: [surface.instructions, ...accountNote].join(' '),});}if (method === 'ping') return ok(id, {});if (method === 'notifications/initialized') return null;- if (method === 'tools/list') return ok(id, { tools: await listForRequest(POLICY_SERVER, surface.catalog, auth, req) });- if (method === 'tools/call') return ok(id, await onToolCall(msg.params, auth, started, req, surface, { caller, onProgress }));+ if (method === 'tools/list') {+ const studio = await listForRequest(POLICY_SERVER, surface.catalog, auth, req);+ if (!signedIn) return ok(id, { tools: studio });+ return ok(id, { tools: [...studio, ...(await accountToolCatalog(account, req))] });+ }+ if (method === 'tools/call') {+ const name = msg.params?.name;+ if (surface.accounts && !Object.hasOwn(surface.tools, name) && isAccountTool(name)) {+ if (!signedIn) {+ throw rpcError(-32002, `${name} manages a three.ws account and needs a signed-in connector`, {+ reason: 'sign_in_required',+ tool: name,+ oauth_url: `${studioOrigin()}/api/mcp-grok?auth=oauth`,+ docs: `${studioOrigin()}/docs/grok`,+ });+ }+ const response = await callAccountTool(msg, account, req);+ if (response) return response;+ throw rpcError(-32002, `${name} is not available to this connector: its scopes or your MCP tool settings leave it off`, {+ reason: 'tool_not_granted',+ tool: name,+ settings: `${studioOrigin()}/settings/mcp-tools`,+ docs: `${studioOrigin()}/docs/mcp#api-key-scopes`,+ });+ }+ return ok(id, await onToolCall(msg.params, auth, started, req, surface, { caller, onProgress }));+ }if (method === 'resources/list') {- return ok(id, { resources: widgetResources(surface.personas).map(({ text: _t, ...r }) => r) });+ return ok(id, { resources: widgetResources(surface).map(({ text: _t, ...r }) => r) });}if (method === 'resources/read') {const uri = msg.params?.uri;- const res = widgetResources(surface.personas).find((r) => r.uri === uri);+ const res = widgetResources(surface).find((r) => r.uri === uri);if (!res) throw rpcError(-32602, `unknown resource: ${uri}`);return ok(id, { contents: [{ uri: res.uri, mimeType: res.mimeType, text: res.text, _meta: res._meta }] });}diff --git a/api/_mcp-studio/handler.js b/api/_mcp-studio/handler.jsindex ca193d982..a750f2589 100644--- a/api/_mcp-studio/handler.js+++ b/api/_mcp-studio/handler.js@@ -10,13 +10,17 @@// Parameterized by the tool surface it serves (SURFACES in ./dispatch.js):// api/mcp-studio.js surface 'full' every tool, both widgets// api/mcp-chatgpt.js surface 'chatgpt' generation tools, model viewer only-// api/mcp-grok.js surface 'grok' every tool, for Grok Bot and the xAI API+// api/mcp-grok.js surface 'grok' every tool, for Grok Bot and the xAI API,+// plus the account's agent tools once+// the caller signs in// Every front door shares one transport cap, one per-IP generation quota and one// platform-wide circuit breaker, so a second door never doubles the free GPU// budget.//-// There is no OAuth and no payment path anywhere in this server: generation runs+// There is no payment path anywhere in this server: generation runs// operator-funded over /api/forge, whose server-side keys cover provider cost.+// Only the grok surface reads a credential (signedInAccount below), and only to+// add the account's agent tools; the free tools never need one.// Abuse protection is real: a per-caller transport cap plus a per-caller// generation burst and hourly quota (../_lib/rate-limit.js), enforced whenever// Redis is healthy. The caller is, in order: a verified install token on the@@ -30,7 +34,10 @@import { randomUUID } from 'node:crypto';import { cors, wrap, readJson, rateLimited, setRateLimitHeaders } from '../_lib/http.js';import { limits, clientIp, STUDIO_LIMITS } from '../_lib/rate-limit.js';-import { dispatch, PROTOCOL_VERSION } from './dispatch.js';+import { dispatch, PROTOCOL_VERSION, surfaceServesAccounts } from './dispatch.js';+import { authenticateBearer, extractBearer } from '../_lib/auth.js';+import { acceptedAudiences, mcpResourceFor } from '../_lib/mcp-resources.js';+import { send401 } from '../_mcp/auth.js';import { TOOL_NAMES } from './tools.js';import { isIdempotentRepeat, progressReporter } from './jobs.js';import { installTokenFrom, studioOrigin, INSTALL_PARAM } from './install-token.js';@@ -71,7 +78,7 @@ const SSE_KEEPALIVE_MS = 15_000;// Answer one tools/call as a Streamable HTTP SSE response: each status frame of// the job becomes a notifications/progress message (./jobs.js// progressReporter), and the JSON-RPC result is the last event.-async function streamToolCall(res, msg, auth, req, { surface, caller, token }) {+async function streamToolCall(res, msg, auth, req, { surface, caller, token, account = null }) {res.statusCode = 200;res.setHeader('content-type', 'text/event-stream; charset=utf-8');res.setHeader('cache-control', 'no-cache, no-transform');@@ -88,7 +95,7 @@ async function streamToolCall(res, msg, auth, req, { surface, caller, token }) {try {const report = progressReporter(token, send);report({ status: 'queued', stage: 'submit' }, 'request');- const response = await dispatch(msg, auth, req, { surface, caller, onProgress: report });+ const response = await dispatch(msg, auth, req, { surface, caller, onProgress: report, account });if (response !== null) send(response);} finally {clearInterval(keepAlive);@@ -156,12 +163,14 @@ export function callerSubject(surface, body, req) {/*** Who the per-caller caps charge, on every surface: a verified install token- * first, then the surface's own subject, then the IP. An unknown or forged token- * is ignored, so the request keys exactly as it would with no token at all.- * @returns {{ key: string, kind: 'install'|'session'|'chatgpt_user'|'ip' }}+ * first, then a signed-in account, then the surface's own subject, then the IP.+ * An unknown or forged token is ignored, so the request keys exactly as it+ * would with no token at all.+ * @returns {{ key: string, kind: 'install'|'account'|'session'|'chatgpt_user'|'ip' }}*/-export function studioCaller(surface, body, req, ip, install = installTokenFrom(req)) {+export function studioCaller(surface, body, req, ip, install = installTokenFrom(req), account = null) {if (install) return { key: `inst:${install.id}`, kind: 'install' };+ if (account?.userId) return { key: `acct:${account.userId}`, kind: 'account' };const subject = callerSubject(surface, body, req);if (subject) return { key: subject, kind: surface === 'chatgpt' ? 'chatgpt_user' : 'session' };return { key: ip, kind: 'ip' };@@ -173,6 +182,7 @@ export const STUDIO_RATE_LIMITED = -32000;const CALLER_SCOPE = {install: 'this install token',+ account: 'this three.ws account',session: 'this MCP session',chatgpt_user: 'this ChatGPT user',ip: 'your IP address',@@ -196,15 +206,15 @@ function resetAt(result) {/*** The remedy for a capped caller. A per-IP caller is told to get an install- * token (one URL of its own); a caller that already has its own budget, or hit a- * cap no token lifts, is pointed at the signed-in server, whose free lane is- * metered per account.+ * token (one URL of its own); a caller that already has its own budget (a token+ * or an account), or hit a cap no token lifts, is pointed at the signed-in+ * server, whose free lane is metered per account.*/export function studioRemedy(kind, bucket, surfacePath) {const origin = studioOrigin();const installEndpoint = `${origin}/api/mcp-studio/install`;const accountServer = `${origin}/api/mcp-3d`;- if (bucket !== 'global' && bucket !== 'pool' && kind !== 'install') {+ if (bucket !== 'global' && bucket !== 'pool' && kind !== 'install' && kind !== 'account') {return {kind: 'install_token',install_endpoint: installEndpoint,@@ -273,7 +283,48 @@ function rpcDenial(res, body, denial, result) {res.end(JSON.stringify(one(body)));}+// `?auth=oauth` on the connector URL asks for sign-in: an MCP client only+// starts OAuth when a server answers 401, and an anonymous request here is+// otherwise served, so a connector set to OAuth 2.1 needs a URL that refuses it.+export const SIGN_IN_PARAM = 'auth';++function wantsSignIn(req) {+ try {+ return new URL(req.url || '/', 'http://localhost').searchParams.get(SIGN_IN_PARAM) === 'oauth';+ } catch {+ return false;+ }+}++/**+ * The account a request on an account-serving surface signed in as. Returns+ * { account } (null when anonymous) or { refused: true } after answering 401:+ * a bearer that does not verify (expired, revoked, wrong audience) is refused+ * rather than quietly served anonymously, so the client re-authenticates+ * instead of losing its account tools without a word.+ */+export async function signedInAccount(req, res, surfacePath) {+ const bearer = extractBearer(req);+ const refuse = (message) => {+ // A browser MCP client cannot start OAuth off a header it may not read.+ const exposed = res.getHeader('access-control-expose-headers');+ res.setHeader('access-control-expose-headers', exposed ? `${exposed}, www-authenticate` : 'www-authenticate');+ send401(res, message, { req, resourcePath: surfacePath });+ return { refused: true };+ };+ if (!bearer) {+ if (wantsSignIn(req)) {+ return refuse('sign in to add your three.ws agent tools to this connector');+ }+ return { account: null };+ }+ const account = await authenticateBearer(bearer, { audience: acceptedAudiences(mcpResourceFor(surfacePath)) });+ if (!account) return refuse('missing or invalid access token');+ return { account };+}+export function studioHandler({ surface = 'full' } = {}) {+ const servesAccounts = surfaceServesAccounts(surface);return wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,HEAD,POST,OPTIONS', origins: '*', payments: false })) return;@@ -316,9 +367,26 @@ export function studioHandler({ surface = 'full' } = {}) {const batch = Array.isArray(body) ? body : [body];if (batch.length > 16) return rpcError(res, 400, -32600, 'batch too large (max 16)');+ let account = null;+ if (servesAccounts) {+ const signIn = await signedInAccount(req, res, surfacePath);+ if (signIn.refused) return;+ account = signIn.account;+ // The same per-account flood guard /api/mcp applies to these tools.+ if (account) {+ const userRl = await limits.mcpUser(account.userId);+ if (!userRl.success) {+ const at = resetAt(userRl);+ return rateLimited(res, userRl, `too many requests for this three.ws account, resets at ${at.toISOString()}`, {+ reset_at: at.toISOString(),+ });+ }+ }+ }+// Who this request is: the key the per-caller caps charge, and the owner of// any idempotency_key it sends (./jobs.js).- const caller = studioCaller(surface, body, req, ip, install);+ const caller = studioCaller(surface, body, req, ip, install, account);// Generation quota, burst then hourly, per caller. Applied only when the// request actually calls a generation tool, so discovery is never throttled@@ -349,12 +417,12 @@ export function studioHandler({ surface = 'full' } = {}) {const token = progressTokenOf(body);if (token !== null && acceptsEventStream(req)) {- return streamToolCall(res, body, auth, req, { surface, caller: caller.key, token });+ return streamToolCall(res, body, auth, req, { surface, caller: caller.key, token, account });}const responses = [];for (const msg of batch) {- const r = await dispatch(msg, auth, req, { surface, caller: caller.key });+ const r = await dispatch(msg, auth, req, { surface, caller: caller.key, account });if (r !== null) responses.push(r);}diff --git a/data/changelog.json b/data/changelog.jsonindex 025814728..92671473f 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-08",+ "title": "One Grok Bot connector for 3D and your agents",+ "summary": "https://three.ws/api/mcp-grok is now the one URL to paste into Grok Bot. With no sign-in it is the free 3D studio: text or an image to a 3D model, a rigged avatar, or a talking persona, with links Grok can share. Give the same URL a connector API key, or sign it in with OAuth at https://three.ws/api/mcp-grok?auth=oauth, and Grok also manages your agents, their memory and skills, and your avatars. It never lists a wallet, payment, card, trading, launch or delete tool, whatever the sign-in allows, so a Grok Bot task can build with your agents but can never spend.",+ "tags": [+ "feature"+ ],+ "link": "/docs/grok"+ },{"date": "2026-10-08","title": "Long 3D jobs and safe retries for AI agents",diff --git a/docs/grok.md b/docs/grok.mdindex da46b0c11..192024811 100644--- a/docs/grok.md+++ b/docs/grok.md@@ -3,7 +3,9 @@Give Grok a 3D studio and a body. One remote MCP server lets Grok Bot, Grokconnectors and the xAI API turn text or an image into a textured 3D model, arigged animation-ready avatar, or a named 3D persona that lip-syncs its replies.-It is free: no account, no payment, no API key.+It is free: no account, no payment, no API key. Sign the same URL in to your+three.ws account and it also manages your agents, their memory and skills,+without ever being able to spend.**Live page and demo:** [three.ws/grok](/grok)@@ -11,9 +13,9 @@ It is free: no account, no payment, no API key.|---|---|| **URL** | `https://three.ws/api/mcp-grok` || **Transport** | Streamable HTTP (JSON-RPC over `POST`) |-| **Auth** | None |+| **Auth** | None. Optional: a connector API key, or OAuth 2.1 at `https://three.ws/api/mcp-grok?auth=oauth` || **Protocol** | MCP `2025-06-18` |-| **Tools** | The full free studio: the same fifteen tools as [`/api/mcp-studio`](./mcp-studio.md) |+| **Tools** | The full free studio: the same fifteen tools as [`/api/mcp-studio`](./mcp-studio.md). Signed in, also your [account's agent tools](#your-account-on-the-same-url) |## Grok Bot@@ -35,21 +37,41 @@ in any task, or attach the server with `@three-ws`:Grok Bot works on its own cloud computer, so it can save the GLB to its files,hand it to another tool in the same task, or run the request on a schedule.-## Your account with a connector key+## Your account on the same URL-The free server above needs no account. To let Grok Bot work with **your**-avatars, agents and their memory (on a schedule, say), connect it to the core-server with a connector key:+The free studio needs no account. To let Grok Bot also work with **your**+agents, their memory and skills, and your avatars (on a schedule, say), keep the+same URL and give it a credential. Two ways:-1. At [three.ws/dashboard/api](/dashboard/api) choose **New key**, then **For an AI agent (Grok Bot, schedules, CI)**, name it, and copy the key it shows once.-2. Ask Grok Bot to add a custom MCP server at `https://three.ws/api/mcp` with API key authentication, and store the key as a Bot secret.+- **Connector key (recommended for Grok Bot).** At [three.ws/dashboard/api](/dashboard/api) choose **New key**, then **For an AI agent (Grok Bot, schedules, CI)**, name it, and copy the key it shows once. Ask Grok Bot to add a custom MCP server at `https://three.ws/api/mcp-grok` with API key authentication, and store the key as a Bot secret. It is sent as `Authorization: Bearer sk_live_…`.+- **OAuth 2.1.** Use `https://three.ws/api/mcp-grok?auth=oauth` as the server URL with OAuth authentication. The `?auth=oauth` form answers an anonymous client with `401` and a `WWW-Authenticate` challenge, which is what makes an MCP client start sign-in; the plain URL serves anonymous clients and so never would. The connector registers itself, you approve the consent screen once, and every token it holds is refused the moment you revoke the app in [Connected apps](/dashboard/settings#connected-apps).-A connector key reads, generates and edits agent data and can never spend.-If a task reaches anything that pays, sends, trades or launches, the server-answers with a JSON-RPC error that says the action needs a browser session on-three.ws and links there, so Grok Bot can tell you instead of retrying. Revoke-the key from the same page at any time; it stops on its next request. Scopes-and the exact error: [API key scopes](./mcp.md#api-key-scopes).+Signed in, `tools/list` adds these to the fifteen studio tools, each only when+the credential's scopes allow it and your [MCP tool settings](/settings/mcp-tools)+leave it on:++| Tool | What it does |+|---|---|+| `create_agent`, `attach_avatar_to_agent` | Create an agent on your account and give it a body you generated with `forge_avatar`. |+| `identity_check`, `call_agent` | Screen an agent identity, or send another three.ws agent a message and get its reply. |+| `remember`, `recall` | Your agents' long-term memory. |+| `list_available_skills`, `import_community_skill`, `list_custom_skills`, `get_custom_skill`, `create_custom_skill`, `update_custom_skill` | Your agents' prompt-only skills. |+| `list_my_avatars`, `get_avatar`, `get_embed_code`, `render_avatar_image` | Your avatars, their embed snippets and rendered images. |++**It never spends.** No wallet, payment, card, trading, launch or delete tool is+ever listed on this URL, whatever scopes the credential holds, and calling one by+name answers `unknown tool`. Those actions happen in a browser at+[three.ws/dashboard](/dashboard). The same tools run through the core server's+policy, scope checks and spend gate exactly as on `/api/mcp`, and the free tools+stay anonymous: signing in changes nothing about what they do, except that your+generation caps key on your account instead of the MCP session.++A credential that no longer verifies (expired, revoked, or minted for another+server) is answered with `401` and the challenge rather than served anonymously,+so a connector re-authenticates instead of quietly losing your tools. An account+tool called without signing in answers JSON-RPC `-32002` with+`data.reason: "sign_in_required"` and the OAuth URL. Scopes and the exact spend+refusal: [API key scopes](./mcp.md#api-key-scopes).## Grok connectors@@ -116,8 +138,9 @@ A complete, zero-dependency Node script that also collects slow renders lives inEvery finished model comes back with a `viewer_url` (an interactive viewer thatopens in any browser), a `glb_url`, a `poster_png_url` and `embed_html`. Nothing-renders inline in Grok, and the server's instructions tell Grok to hand those-links to the user.+renders inline in Grok, so this URL lists no widget templates and no `ui://`+resources, and the server's instructions tell Grok to hand those links to the+user. Signed in, Grok also gets the [account tools](#your-account-on-the-same-url).## How it behaves under Grok@@ -166,6 +189,8 @@ caller that already has one).`/api/mcp-grok` is one of three front doors on the same handler([`api/_mcp-studio/handler.js`](../api/_mcp-studio/handler.js)); `SURFACES` in[`api/_mcp-studio/dispatch.js`](../api/_mcp-studio/dispatch.js) defines what each-advertises. They share one generation quota and one breaker, so the Grok door+advertises. The account tools come from the core server through+[`api/_mcp-studio/account-tools.js`](../api/_mcp-studio/account-tools.js), whose+allowlist only admits a tool the shared policy says moves no value. They share one generation quota and one breaker, so the Grok doornever adds GPU spend of its own. See [the free 3D Studio MCP](./mcp-studio.md)for the tools in depth and [MCP integration](./mcp.md) for every hosted server.diff --git a/docs/mcp.md b/docs/mcp.mdindex c4bd3a140..903821ea1 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -51,19 +51,20 @@ The hosted servers are also self-describing: [`https://three.ws/.well-known/mcp.There are two kinds. **Hosted remote servers** run over Streamable HTTP with nothing to install — add them by URL. **Install-and-run servers** are published on npm under the `@three-ws` scope and run locally over stdio — add them in one line with `npx`.-**Seven hosted remote servers** (Streamable HTTP, no install):+**Eight hosted remote servers** (Streamable HTTP, no install):| Server | Endpoint | What it does ||--------|----------|--------------|| three.ws | `/api/mcp` | Avatars, glTF/GLB validation, agent data, memory, copy-trading, a connected home (this page) || 3D Studio | `/api/mcp-3d` | Paid text/image→3D, rigging, retexture, optimization || 3D Studio (free) | `/api/mcp-studio` | Free text/image→3D and rigged avatars — no auth, no payment |+| Grok | `/api/mcp-grok` | One connector URL for Grok Bot and the xAI API: the free studio with no widgets, plus your agents, memory and skills once signed in (OAuth 2.1 or a connector key). Never lists a value-moving tool. See [three.ws for Grok](./grok.md) || Agent wallet | `/api/mcp-agent` | The agent's custodial wallet: balance, find + pay services, and `monetize_endpoint` || x402 Bazaar | `/api/mcp-bazaar` | Discover and price paid agent services across the facilitator network || pump.fun | `/api/pump-fun-mcp` | Free pump.fun + Solana token tools; `get_new_tokens` and `get_trending_tokens` read the live pump.fun feed with no indexer needed; `pumpfun_upload_metadata` needs a key || IBM x402 | `/api/ibm-mcp` | Pay-per-use IBM Granite AI |-The free studio also has two client-tuned doors on the same tools and quota: `/api/mcp-chatgpt` for the ChatGPT plugin directory, and `/api/mcp-grok` for Grok Bot, Grok connectors and the xAI API, where no call hangs and the quota follows your MCP session. See [three.ws for Grok](./grok.md).+The free studio also has two client-tuned doors on the same tools and quota: `/api/mcp-chatgpt` for the ChatGPT plugin directory, and `/api/mcp-grok` for Grok Bot, Grok connectors and the xAI API, where no call hangs, the quota follows your MCP session, and a signed-in connector also gets the account's agent tools (never a wallet tool). See [three.ws for Grok](./grok.md).**Forty-two install-and-run servers** on npm under the `@three-ws` scope, each running over stdio with one command:@@ -328,6 +329,7 @@ The probe reads its server list from [`/.well-known/mcp.json`](../public/.well-k| Core | `https://three.ws/api/mcp` | Streamable HTTP | API key, OAuth 2.1 | Transport: Streamable HTTP. URL: `https://three.ws/api/mcp`. Authentication: API key or OAuth 2.1 || 3D Studio | `https://three.ws/api/mcp-3d` | Streamable HTTP | API key, OAuth 2.1 | Transport: Streamable HTTP. URL: `https://three.ws/api/mcp-3d`. Authentication: API key or OAuth 2.1 || 3D Studio (free) | `https://three.ws/api/mcp-studio` | Streamable HTTP | None | Transport: Streamable HTTP. URL: `https://three.ws/api/mcp-studio`. Authentication: None |+| Grok | `https://three.ws/api/mcp-grok` | Streamable HTTP | None, API key, OAuth 2.1 | Transport: Streamable HTTP. URL: `https://three.ws/api/mcp-grok`. Authentication: None for the free studio; API key (connector key) adds your agent tools; for OAuth 2.1 use `https://three.ws/api/mcp-grok?auth=oauth` || Agent wallet | `https://three.ws/api/mcp-agent` | Streamable HTTP | API key (read-only scopes), OAuth 2.1 | Transport: Streamable HTTP. URL: `https://three.ws/api/mcp-agent`. Authentication: connector key (browses and quotes; spending answers with a link to three.ws) || x402 Bazaar | `https://three.ws/api/mcp-bazaar` | Streamable HTTP | API key, OAuth 2.1 | Transport: Streamable HTTP. URL: `https://three.ws/api/mcp-bazaar`. Authentication: API key or OAuth 2.1 || pump.fun | `https://three.ws/api/pump-fun-mcp` | Streamable HTTP | None (read-only tools), API key | Transport: Streamable HTTP. URL: `https://three.ws/api/pump-fun-mcp`. Authentication: None |diff --git a/prompts/x-grok/_generated/connector-probe-dev.json b/prompts/x-grok/_generated/connector-probe-dev.jsonindex 34d8259dd..60b39ebc6 100644--- a/prompts/x-grok/_generated/connector-probe-dev.json+++ b/prompts/x-grok/_generated/connector-probe-dev.json@@ -1,8 +1,8 @@{"probe": "scripts/mcp-client-probe.mjs","base": "http://localhost:3107",- "startedAt": "2026-10-08T19:03:41.146Z",- "finishedAt": "2026-10-08T19:03:45.282Z",+ "startedAt": "2026-10-08T22:14:49.103Z",+ "finishedAt": "2026-10-08T22:14:53.655Z","sdkVersion": "1.32.1","clientProtocolVersion": "2025-11-25","apiKeyMode": "ran",@@ -126,7 +126,7 @@"call": {"name": "search_catalog","ok": true,- "ms": 82,+ "ms": 303,"contentItems": 1,"structured": true}@@ -253,7 +253,7 @@"call": {"name": "getting_started","ok": true,- "ms": 77,+ "ms": 76,"contentItems": 1,"structured": true}@@ -339,12 +339,12 @@"resources","tools"],- "tools": 14,+ "tools": 15,"prompts": null,"call": {"name": "search_catalog","ok": true,- "ms": 5,+ "ms": 11,"contentItems": 1,"structured": true}@@ -363,12 +363,12 @@"resources","tools"],- "tools": 14,+ "tools": 15,"prompts": null,"call": {"name": "search_catalog","ok": true,- "ms": 4,+ "ms": 9,"contentItems": 1,"structured": true}@@ -377,6 +377,149 @@"failures": [],"pass": true},+ {+ "name": "Grok",+ "endpoint": "https://three.ws/api/mcp-grok",+ "url": "http://localhost:3107/api/mcp-grok",+ "auth": "none for the free 3D tools; OAuth 2.1 or a connector API key adds the account's agent tools",+ "expects": {+ "anonymous": true,+ "oauth": true,+ "apiKey": true+ },+ "http": {+ "initialize": {+ "status": 200,+ "contentType": "application/json; charset=utf-8",+ "sessionId": "grk_0fef4b53-53f1-4d93-b44e-3728bd24107c",+ "wwwAuthenticate": null,+ "protocolVersion": "2025-06-18",+ "rpcError": null+ },+ "getStream": {+ "status": 405,+ "contentType": "application/json; charset=utf-8",+ "allow": "POST, OPTIONS",+ "wwwAuthenticate": null+ },+ "getStreamProblem": null,+ "negotiation": [+ {+ "requested": "2025-11-25",+ "status": 200,+ "negotiated": "2025-06-18",+ "echoed": false,+ "clientSupportsAnswer": true,+ "error": null+ },+ {+ "requested": "2025-06-18",+ "status": 200,+ "negotiated": "2025-06-18",+ "echoed": true,+ "clientSupportsAnswer": true,+ "error": null+ },+ {+ "requested": "2025-03-26",+ "status": 200,+ "negotiated": "2025-06-18",+ "echoed": false,+ "clientSupportsAnswer": true,+ "error": null+ },+ {+ "requested": "2024-11-05",+ "status": 200,+ "negotiated": "2025-06-18",+ "echoed": false,+ "clientSupportsAnswer": true,+ "error": null+ }+ ],+ "session": {+ "echoed": 200,+ "unknown": 200+ },+ "sessionIssued": true+ },+ "modes": {+ "anonymous": {+ "transport": "streamable-http",+ "ok": true,+ "serverInfo": {+ "name": "three-ws-3d-studio-free",+ "version": "1.0.0"+ },+ "protocolVersion": "2025-06-18",+ "sessionId": "grk_f75adff3-09b4-4f35-91d7-191f1ef9229f",+ "capabilities": [+ "logging",+ "tools"+ ],+ "tools": 15,+ "prompts": null,+ "call": {+ "name": "search_catalog",+ "ok": true,+ "ms": 10,+ "contentItems": 1,+ "structured": true+ }+ },+ "oauth": {+ "failures": [],+ "status": 401,+ "wwwAuthenticate": "Bearer resource_metadata=\"http://localhost:3107/.well-known/oauth-protected-resource/api/mcp-grok\", resource=\"http://localhost:3107/api/mcp-grok\"",+ "resourceMetadataUrl": "http://localhost:3107/.well-known/oauth-protected-resource/api/mcp-grok",+ "metadata": {+ "status": 200,+ "resource": "http://localhost:3107/api/mcp-grok",+ "authorizationServers": [+ "http://localhost:3107"+ ]+ },+ "resourceAllowed": true,+ "authorizationServer": {+ "url": "http://localhost:3107/.well-known/oauth-authorization-server",+ "status": 200,+ "issuer": "http://localhost:3107",+ "pkceS256": true,+ "dynamicRegistration": true+ },+ "invalidBearer": {+ "status": 401,+ "wwwAuthenticate": "Bearer resource_metadata=\"http://localhost:3107/.well-known/oauth-protected-resource/api/mcp-grok\", resource=\"http://localhost:3107/api/mcp-grok\""+ }+ },+ "apiKey": {+ "transport": "streamable-http",+ "ok": true,+ "serverInfo": {+ "name": "three-ws-3d-studio-free",+ "version": "1.0.0"+ },+ "protocolVersion": "2025-06-18",+ "sessionId": "grk_080d238d-4e40-4fd7-905a-4e95f1db5292",+ "capabilities": [+ "logging",+ "tools"+ ],+ "tools": 25,+ "prompts": null,+ "call": {+ "name": "search_catalog",+ "ok": true,+ "ms": 85,+ "contentItems": 1,+ "structured": true+ }+ }+ },+ "signIn": "http://localhost:3107/api/mcp-grok?auth=oauth",+ "failures": [],+ "pass": true+ },{"name": "Agent wallet","endpoint": "https://three.ws/api/mcp-agent",@@ -490,12 +633,12 @@"resources","tools"],- "tools": 23,+ "tools": 24,"prompts": 7,"call": {"name": "getting_started","ok": true,- "ms": 78,+ "ms": 77,"contentItems": 1,"structured": true}@@ -622,7 +765,7 @@"call": {"name": "getting_started","ok": true,- "ms": 76,+ "ms": 75,"contentItems": 1,"structured": true}diff --git a/public/.well-known/mcp.json b/public/.well-known/mcp.jsonindex 7fb6195ab..65f33b020 100644--- a/public/.well-known/mcp.json+++ b/public/.well-known/mcp.json@@ -78,6 +78,15 @@"description": "Free text-to-3D, image-to-3D, rigged avatars, persistent talking personas, and a search of the ready-made asset catalog. No account, no payment.","documentation": "https://three.ws/docs/mcp-studio"},+ {+ "name": "Grok",+ "endpoint": "https://three.ws/api/mcp-grok",+ "transport": "streamable-http",+ "auth": "none for the free 3D tools; OAuth 2.1 or a connector API key adds the account's agent tools",+ "signIn": "https://three.ws/api/mcp-grok?auth=oauth",+ "description": "One connector URL for Grok Bot and the xAI API: the free 3D studio with agent-ready links and no widgets, plus your agents, their memory and skills once signed in. Never lists a wallet or payment tool.",+ "documentation": "https://three.ws/docs/grok"+ },{"name": "Agent wallet","endpoint": "https://three.ws/api/mcp-agent",diff --git a/scripts/build-mcp-listing-source.mjs b/scripts/build-mcp-listing-source.mjsindex 048bd20d3..d2547e736 100644--- a/scripts/build-mcp-listing-source.mjs+++ b/scripts/build-mcp-listing-source.mjs@@ -164,6 +164,16 @@ const OVERLAY = {"Free: auto-rig this GLB for animation.",],},+ "io.github.nirholas/threews-grok": {+ tagline: "One connector URL for Grok Bot: free text/image to 3D with shareable links, plus your agents once signed in. Never spends.",+ category: "3d",+ tags: ["grok","text-to-3d","free","avatars","agents"],+ examplePrompts: [+ "Make a 3D model of a reusable rocket booster and send me the viewer link and the GLB.",+ "Forge a friendly robot avatar and attach it to my agent as its body.",+ "Remember for my support agent that our office hours are 9 to 5 UTC.",+ ],+ },"io.github.nirholas/threews-agent": {tagline: "Give your agent an x402 wallet: discover, pay for, and earn from services in USDC, bounded by spend caps.",category: "payments",diff --git a/scripts/mcp-client-probe.mjs b/scripts/mcp-client-probe.mjsindex 76f0db05d..f23392b7f 100644--- a/scripts/mcp-client-probe.mjs+++ b/scripts/mcp-client-probe.mjs@@ -21,6 +21,11 @@// authorization server metadata supports PKCE S256. An// invalid bearer must earn the same challenge (re-auth path).//+// A server that works anonymously AND upgrades on sign-in (/api/mcp-grok)+// names its sign-in URL in the manifest's `signIn` field. The oauth checks run+// against that URL, and an API key must list more tools than an anonymous+// client sees, since the account's tools are what signing in is for.+//// Records initialize, tools/list count, prompts/list count, and one free// tools/call where a free tool exists (search_catalog, getting_started).// No paid tool is ever called and no payment header is ever sent.@@ -418,6 +423,14 @@ export function judgeServer(r) {if (http.initialize && !/application\/json|text\/event-stream/.test(http.initialize.contentType)) {failures.push(`initialize answered content-type ${http.initialize.contentType}`);}+ if (r.signIn) {+ if (modes.oauth?.error) failures.push(modes.oauth.error);+ for (const f of modes.oauth?.failures || []) failures.push(`sign-in URL: ${f}`);+ const k = modes.apiKey;+ if (k?.ok && a.ok && !(k.tools > a.tools)) {+ failures.push(`signing in with an API key listed ${k.tools} tools, no more than the ${a.tools} an anonymous client sees`);+ }+ }} else {if (modes.anonymous.ok) failures.push('anonymous MCP client was served on a server that requires auth');for (const f of modes.oauth?.failures || []) failures.push(f);@@ -437,6 +450,7 @@ async function probeServer(server, { base, timeout, apiKey }) {const url = serverUrlFor(server.endpoint, base);const expects = authExpectations(server.auth);const r = { name: server.name, endpoint: server.endpoint, url, auth: server.auth, expects, http: {}, modes: {} };+ if (expects.anonymous && expects.oauth && server.signIn) r.signIn = serverUrlFor(server.signIn, base);const guard = async (label, fn) => {try {return await fn();@@ -457,6 +471,7 @@ async function probeServer(server, { base, timeout, apiKey }) {r.modes.anonymous = await runMode(url, { headers: {}, timeout });if (!expects.anonymous) r.modes.oauth = await guard('oauth', () => probeChallenge(url, { timeout }));+ else if (r.signIn) r.modes.oauth = await guard('oauth', () => probeChallenge(r.signIn, { timeout }));if (!apiKey) r.modes.apiKey = { skipped: 'THREE_WS_API_KEY is not set' };else r.modes.apiKey = await runMode(url, { headers: { authorization: `Bearer ${apiKey}` }, timeout });diff --git a/scripts/publish-mcp-servers.mjs b/scripts/publish-mcp-servers.mjsindex 812c8c7df..85c16dac1 100644--- a/scripts/publish-mcp-servers.mjs+++ b/scripts/publish-mcp-servers.mjs@@ -136,6 +136,8 @@ const SERVERS = [{ key: 'remote-bazaar', manifest: 'server-bazaar.json' },// Free, non-crypto 3D Studio (api/mcp-studio.js) for the OpenAI Apps SDK.{ key: 'remote-studio', manifest: 'server-studio.json' },+ // The free studio plus signed-in agent tools for Grok Bot (api/mcp-grok.js).+ { key: 'remote-grok', manifest: 'server-grok.json' },];const args = process.argv.slice(2);diff --git a/server-grok.json b/server-grok.jsonnew file mode 100644index 000000000..6a24d2cdd--- /dev/null+++ b/server-grok.json@@ -0,0 +1,25 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/threews-grok",+ "title": "three.ws for Grok",+ "websiteUrl": "https://three.ws/docs/grok",+ "icons": [+ {+ "src": "https://three.ws/three-ws-mcp-icon.svg",+ "mimeType": "image/svg+xml",+ "sizes": ["any"]+ }+ ],+ "description": "Free text/image to 3D for Grok Bot, plus your three.ws agents once signed in. Never spends.",+ "repository": {+ "url": "https://github.com/nirholas/three.ws",+ "source": "github"+ },+ "version": "1.0.0",+ "remotes": [+ {+ "type": "streamable-http",+ "url": "https://three.ws/api/mcp-grok"+ }+ ]+}diff --git a/tests/mcp-client-probe.test.js b/tests/mcp-client-probe.test.jsindex 108c93bf7..c356bc44c 100644--- a/tests/mcp-client-probe.test.js+++ b/tests/mcp-client-probe.test.js@@ -86,6 +86,34 @@ describe('judgeServer', () => {expect(judgeServer(r)).toHaveLength(1);});+ describe('a server that is open and upgrades on sign-in', () => {+ const upgradeable = (modes) => ({+ ...base,+ expects: { anonymous: true, oauth: true, apiKey: true },+ signIn: 'http://localhost:3000/api/mcp-grok?auth=oauth',+ modes,+ });++ it('passes when the sign-in URL challenges correctly and a key adds tools', () => {+ const r = upgradeable({ anonymous: { ok: true, tools: 18 }, oauth: { failures: [] }, apiKey: { ok: true, tools: 34 } });+ expect(judgeServer(r)).toEqual([]);+ });++ it('fails when signing in adds no tools', () => {+ const r = upgradeable({ anonymous: { ok: true, tools: 18 }, oauth: { failures: [] }, apiKey: { ok: true, tools: 18 } });+ expect(judgeServer(r)[0]).toMatch(/no more than the 18/);+ });++ it('fails when the sign-in URL does not start OAuth', () => {+ const r = upgradeable({+ anonymous: { ok: true, tools: 18 },+ oauth: { failures: ['unauthenticated initialize answered 200, an OAuth client needs 401 to start sign-in'] },+ apiKey: { skipped: 'x' },+ });+ expect(judgeServer(r)[0]).toMatch(/^sign-in URL: unauthenticated initialize answered 200/);+ });+ });+it('fails a protected server that serves an anonymous MCP client', () => {const r = { ...base, expects: { anonymous: false, oauth: true }, modes: { anonymous: { ok: true, tools: 3 }, oauth: { failures: [] }, apiKey: { skipped: 'x' } } };expect(judgeServer(r)[0]).toMatch(/requires auth/);diff --git a/tests/mcp-grok-accounts.test.js b/tests/mcp-grok-accounts.test.jsnew file mode 100644index 000000000..f3d15aced--- /dev/null+++ b/tests/mcp-grok-accounts.test.js@@ -0,0 +1,330 @@+// /api/mcp-grok with and without a credential (x-grok order 029).+//+// One URL a person pastes into Grok Bot once: anonymously it serves the free+// 3D studio, and once the connector holds an OAuth 2.1 token or a connector API+// key it also lists the account's agent tools from the core server. It never+// lists a value-moving tool, whatever the credential's scopes, and it never+// lists a widget template, since Grok renders none. These tests drive the real+// HTTP handler with real minted tokens and a real-shaped api_keys row; only the+// database and the rate limiter are replaced.++import { createHash } from 'node:crypto';+import { describe, it, expect, vi } from 'vitest';+import { checkResourceAllowed } from '@modelcontextprotocol/sdk/shared/auth-utils.js';++process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';+process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';++// A connector key as POST /api/keys {preset:"connector"} stores it.+const CONNECTOR_KEY = 'sk_live_fixture_grok_connector_0123456789abcdef';+const CONNECTOR_KEY_HASH = createHash('sha256').update(CONNECTOR_KEY).digest('hex');+const CONNECTOR_ROW = {+ id: '6f1d2c3b-0000-4000-8000-00000000c0de',+ user_id: '9a8b7c6d-0000-4000-8000-0000000000aa',+ scope: 'avatars:read avatars:write agents:read agents:write memory:read memory:write connector',+ expires_at: null,+ revoked_at: null,+};++const queries = [];+vi.mock('../api/_lib/db.js', () => {+ // Tagged-template queries, plus the plain sql(text, params) form the avatar+ // listing uses.+ const sql = (strings, ...values) => {+ if (!Array.isArray(strings)) {+ queries.push(String(strings));+ return Promise.resolve([]);+ }+ const text = strings.join('?');+ queries.push(text);+ if (/from api_keys where token_hash/.test(text)) return Promise.resolve(values.includes(CONNECTOR_KEY_HASH) ? [CONNECTOR_ROW] : []);+ return Promise.resolve([]);+ };+ return {+ sql,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: () => false,+ };+});++vi.mock('../api/_lib/usage.js', () => ({+ recordEvent: vi.fn(),+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),+}));++vi.mock('../api/_lib/rate-limit.js', async (importOriginal) => {+ const real = await importOriginal();+ const pass = async () => ({ success: true, limit: 1, remaining: 1, reset: Date.now() + 1000 });+ return {+ ...real,+ limits: {+ ...real.limits,+ studioIp: pass,+ studioGenBurst: pass,+ studioGenHourly: pass,+ studioGenPoolHourly: pass,+ studioGenerateGlobal: pass,+ mcpUser: pass,+ agentDelegate: pass,+ },+ };+});++const { default: grokHandler } = await import('../api/mcp-grok.js');+const { default: studioHandler } = await import('../api/mcp-studio.js');+const { default: wkHandler } = await import('../api/wk.js');+const { mintAccessToken } = await import('../api/_lib/auth.js');+const { POLICY } = await import('@three-ws/mcp-policy');+const { spendScopeFor } = await import('../api/_mcp/policy.js');+const { dispatch: coreDispatch } = await import('../api/_mcp/dispatch.js');+const { toolCatalogFor } = await import('../api/_mcp-studio/dispatch.js');+const { GROK_ACCOUNT_TOOLS } = await import('../api/_mcp-studio/account-tools.js');+const { parseWwwAuthenticate } = await import('../scripts/mcp-client-probe.mjs');++const ORIGIN = 'https://three.ws';+const USER = '9a8b7c6d-0000-4000-8000-0000000000bb';+// Every scope an OAuth client can be granted, spend included: the surface must+// still refuse to list or run a value-moving tool.+const EVERY_SCOPE = 'avatars:read avatars:write avatars:delete agents:read agents:write memory:read memory:write wallet:read wallet:write services:write profile';+const CONNECTOR_SCOPE = 'avatars:read avatars:write agents:read agents:write memory:read memory:write';+// Every hosted server id the policy table knows, so "value-moving" means+// value-moving anywhere, not only on the core server.+const SERVER_IDS = Object.keys(POLICY);++function rpc(method, params = {}, id = 1) {+ return { jsonrpc: '2.0', id, method, params };+}++// A minimal node-style req/res pair for driving the real HTTP handler.+function httpPair(body, { headers = {}, url = '/api/mcp-grok' } = {}) {+ const payload = Buffer.from(JSON.stringify(body));+ const req = {+ method: 'POST',+ url,+ headers: {+ host: 'three.ws',+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ 'x-forwarded-for': '203.0.113.29',+ ...headers,+ },+ socket: { remoteAddress: '203.0.113.29' },+ async *[Symbol.asyncIterator]() {+ yield payload;+ },+ on(event, cb) {+ if (event === 'data') cb(payload);+ if (event === 'end') cb();+ return this;+ },+ };+ const out = { headers: {}, body: '', status: 200 };+ const res = {+ statusCode: 200,+ headersSent: false,+ setHeader(k, v) {+ out.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return out.headers[k.toLowerCase()];+ },+ removeHeader(k) {+ delete out.headers[k.toLowerCase()];+ },+ end(chunk) {+ if (chunk) out.body += chunk;+ out.status = this.statusCode;+ this.headersSent = true;+ },+ write(chunk) {+ out.body += chunk;+ },+ };+ return { req, res, out };+}++async function post(handler, body, opts) {+ const { req, res, out } = httpPair(body, opts);+ await handler(req, res);+ return { status: out.status, headers: out.headers, json: out.body ? JSON.parse(out.body) : null };+}++const bearer = (token) => ({ authorization: `Bearer ${token}` });++async function oauthToken(scope, resource = `${ORIGIN}/api/mcp-grok`) {+ return mintAccessToken({ userId: USER, clientId: 'grok-bot-client', scope, resource });+}++async function listNames(headers = {}, opts = {}) {+ const r = await post(grokHandler, rpc('tools/list'), { headers, ...opts });+ expect(r.status).toBe(200);+ return r.json.result.tools;+}++function expectNoValueMoving(tools) {+ for (const t of tools) {+ for (const server of SERVER_IDS) expect(spendScopeFor(server, t.name), `${t.name} on ${server}`).toBeNull();+ for (const server of SERVER_IDS) expect(POLICY[server]?.[t.name]?.tier, `${t.name} tier on ${server}`).not.toBe('financial');+ expect(t.pricing, `${t.name} price`).toBeUndefined();+ expect(PRICED_ON_CORE.has(t.name), `${t.name} is priced on /api/mcp`).toBe(false);+ }+}++const STUDIO_NAMES = toolCatalogFor('grok').map((t) => t.name).sort();++// Every tool the core server advertises a price for, read from its own+// tools/list with everything switched on.+const PRICED_ON_CORE = new Set(+ (+ await coreDispatch(+ rpc('tools/list'),+ { userId: null, rateKey: 'test', scope: EVERY_SCOPE },+ { headers: { 'x-three-tools': 'default,financial' } },+ )+ ).result.tools+ .filter((t) => t.pricing)+ .map((t) => t.name),+);++describe('anonymous /api/mcp-grok', () => {+ it('lists the free studio and no account tool', async () => {+ const tools = await listNames();+ const names = tools.map((t) => t.name).sort();+ expect(names).toEqual(STUDIO_NAMES);+ for (const name of GROK_ACCOUNT_TOOLS) expect(names).not.toContain(name);+ expectNoValueMoving(tools);+ });++ it('lists no widget template and no ui:// resource, unlike /api/mcp-studio', async () => {+ const tools = await listNames();+ for (const t of tools) expect(Object.keys(t._meta || {}).filter((k) => k.startsWith('openai/')), t.name).toEqual([]);+ const resources = await post(grokHandler, rpc('resources/list'));+ expect(resources.json.result.resources).toEqual([]);+ const init = await post(grokHandler, rpc('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 't', version: '1' } }));+ expect(init.json.result.capabilities.resources).toBeUndefined();++ const studio = await post(studioHandler, rpc('tools/list'), { url: '/api/mcp-studio' });+ expect(studio.json.result.tools.some((t) => t._meta?.['openai/outputTemplate'])).toBe(true);+ });++ it('tells the model how to sign in, and answers an account tool with the sign-in route', async () => {+ const init = await post(grokHandler, rpc('initialize', {}));+ expect(init.json.result.instructions).toContain('?auth=oauth');+ const r = await post(grokHandler, rpc('tools/call', { name: 'list_my_avatars', arguments: {} }));+ expect(r.json.error.code).toBe(-32002);+ expect(r.json.error.data).toMatchObject({ reason: 'sign_in_required', oauth_url: `${ORIGIN}/api/mcp-grok?auth=oauth` });+ });+});++describe('signed-in /api/mcp-grok', () => {+ it('an OAuth token adds the account agent tools to the studio', async () => {+ const tools = await listNames(bearer(await oauthToken(CONNECTOR_SCOPE)));+ const names = tools.map((t) => t.name);+ for (const name of STUDIO_NAMES) expect(names).toContain(name);+ for (const name of ['create_agent', 'attach_avatar_to_agent', 'remember', 'recall', 'list_my_avatars', 'create_custom_skill']) {+ expect(names).toContain(name);+ }+ expect(new Set(names).size).toBe(names.length);+ expectNoValueMoving(tools);+ });++ it('a connector API key adds them too, capped to what the key may do', async () => {+ const tools = await listNames(bearer(CONNECTOR_KEY));+ const names = tools.map((t) => t.name);+ expect(names).toEqual(expect.arrayContaining(['create_agent', 'remember', 'recall', 'list_my_avatars']));+ expect(queries.some((q) => /from api_keys where token_hash/.test(q))).toBe(true);+ expectNoValueMoving(tools);+ });++ it('lists no value-moving tool even for a grant holding every scope with the financial tier switched on', async () => {+ const tools = await listNames({ ...bearer(await oauthToken(EVERY_SCOPE)), 'x-three-tools': 'default,financial' });+ expect(PRICED_ON_CORE.size).toBeGreaterThan(0);+ expectNoValueMoving(tools);+ const names = tools.map((t) => t.name);+ for (const name of ['agent_card_create', 'agent_card_quote', 'oracle_arm_watch', 'delete_avatar', 'forget', 'register_agent', 'home_call']) {+ expect(names).not.toContain(name);+ }+ });++ it('refuses to run a core wallet tool by name, whatever the grant', async () => {+ const r = await post(grokHandler, rpc('tools/call', { name: 'agent_card_create', arguments: { quote_id: 'q', confirm_spend: true } }), {+ headers: bearer(await oauthToken(EVERY_SCOPE)),+ });+ expect(r.json.error.code).toBe(-32602);+ expect(r.json.error.message).toContain('unknown tool');+ });++ it('lists only the account tools the grant can use', async () => {+ const names = (await listNames(bearer(await oauthToken('avatars:read')))).map((t) => t.name);+ expect(names).toContain('list_my_avatars');+ expect(names).not.toContain('create_agent');+ expect(names).not.toContain('remember');+ });++ it('refuses an account tool the grant cannot use, naming why', async () => {+ const r = await post(grokHandler, rpc('tools/call', { name: 'create_agent', arguments: { name: 'Scout' } }), {+ headers: bearer(await oauthToken('avatars:read')),+ });+ expect(r.json.error.code).toBe(-32002);+ expect(r.json.error.data.reason).toBe('tool_not_granted');+ });++ it('runs an account tool through the core dispatcher as the signed-in account', async () => {+ const r = await post(grokHandler, rpc('tools/call', { name: 'list_my_avatars', arguments: {} }), {+ headers: bearer(await oauthToken(CONNECTOR_SCOPE)),+ });+ expect(r.status).toBe(200);+ expect(r.json.error).toBeUndefined();+ expect(r.json.result.isError).toBeFalsy();+ expect(queries.some((q) => /avatars/i.test(q) && /owner_id/i.test(q))).toBe(true);+ });++ it('names the account in the instructions and keeps studio tools anonymous', async () => {+ const init = await post(grokHandler, rpc('initialize', {}), { headers: bearer(CONNECTOR_KEY) });+ expect(init.json.result.instructions).toContain('signed in to a three.ws account');+ expect(init.json.result.instructions).toContain('never move funds');+ });+});++describe('the OAuth door', () => {+ async function expectGrokChallenge(r) {+ expect(r.status).toBe(401);+ const parsed = parseWwwAuthenticate(r.headers['www-authenticate']);+ expect(parsed.params.resource).toBe(`${ORIGIN}/api/mcp-grok`);+ expect(parsed.params.resource_metadata).toBe(`${ORIGIN}/.well-known/oauth-protected-resource/api/mcp-grok`);+ // The document the challenge points at must pass the MCP SDK's own check.+ const md = httpPair(null, { url: '/api/wk?name=oauth-protected-resource&path=/api/mcp-grok' });+ md.req.method = 'GET';+ await wkHandler(md.req, md.res);+ const doc = JSON.parse(md.out.body);+ expect(doc.resource).toBe(`${ORIGIN}/api/mcp-grok`);+ expect(checkResourceAllowed({ requestedResource: `${ORIGIN}/api/mcp-grok?auth=oauth`, configuredResource: doc.resource })).toBe(true);+ }++ it('an invalid bearer is told to re-authenticate, never served anonymously', async () => {+ const r = await post(grokHandler, rpc('tools/list'), { headers: bearer('expired.or.forged') });+ await expectGrokChallenge(r);+ });++ it('?auth=oauth refuses an anonymous client so a connector set to OAuth 2.1 starts sign-in', async () => {+ const r = await post(grokHandler, rpc('initialize', {}), { url: '/api/mcp-grok?auth=oauth' });+ await expectGrokChallenge(r);+ const signedIn = await post(grokHandler, rpc('tools/list'), {+ url: '/api/mcp-grok?auth=oauth',+ headers: bearer(await oauthToken(CONNECTOR_SCOPE)),+ });+ expect(signedIn.status).toBe(200);+ expect(signedIn.json.result.tools.map((t) => t.name)).toContain('create_agent');+ });++ it('a token minted for another hosted server is refused here', async () => {+ const r = await post(grokHandler, rpc('tools/list'), { headers: bearer(await oauthToken(CONNECTOR_SCOPE, `${ORIGIN}/api/mcp-3d`)) });+ expect(r.status).toBe(401);+ });++ it('a platform token (what npx three-ws setup holds) works here', async () => {+ const names = (await listNames(bearer(await oauthToken(CONNECTOR_SCOPE, `${ORIGIN}/api/mcp`)))).map((t) => t.name);+ expect(names).toContain('create_agent');+ });+});