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(cli): npx three-ws setup --client grok-bot prints the connector fields, copies the URL and verifies it live
nirholascd9b7f5be1da
diff --git a/data/changelog.json b/data/changelog.jsonindex 3962feac3..6ec95ba3d 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,13 @@{"$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-09",+ "title": "Set up Grok Bot from the terminal with npx three-ws setup",+ "summary": "Grok Bot keeps its connectors in xAI's cloud, so there is no config file to write, but the three-ws CLI now does every other step. Run npx three-ws setup --client grok-bot, or tick Grok Bot in the setup picker, and it prints the exact fields Grok Bot's custom MCP form asks for, copies the server URL to your clipboard, and checks the public URL live the way Grok Bot will call it. Pick how Grok Bot signs in: free with no account, free with an install token that keeps one quota across scheduled runs, a connector key it mints for you that can read and generate but never spend, or OAuth so Grok Bot signs in itself.",+ "tags": ["feature", "sdk"],+ "link": "/docs/cli"+ },{"date": "2026-10-09","title": "AI agents can now read how to connect three.ws to their client",diff --git a/docs/cli.md b/docs/cli.mdindex 41b9b4068..c5a9a2864 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -46,7 +46,7 @@ npx three-ws setup --clients print| Flag | Values ||---|---|-| `--clients` | `claude-code`, `claude-desktop`, `cursor`, `windsurf`, `vscode`, `codex`, `gemini`, `hermes`, `print` |+| `--clients` | `claude-code`, `claude-desktop`, `cursor`, `windsurf`, `vscode`, `codex`, `gemini`, `hermes`, `grok-bot`, `print` (`--client` works too) || `--servers` | Server names from `npx three-ws mcp list --available` || `--packages` | Also add stdio `@three-ws/*-mcp` packages || `--project` | Write project-scoped config in the current directory |@@ -75,6 +75,7 @@ Every client stores a server under the same name, which is also what `--servers`| `three-ws-main` | `https://three.ws/api/mcp` | Sign-in || `three-ws-3d` | `https://three.ws/api/mcp-3d` | Sign-in or x402 || `three-ws-studio` | `https://three.ws/api/mcp-studio` | None |+| `three-ws-grok` | `https://three.ws/api/mcp-grok` | None for the free 3D tools; a connector key or OAuth adds your agents || `three-ws-agent` | `https://three.ws/api/mcp-agent` | Sign-in || `three-ws-bazaar` | `https://three.ws/api/mcp-bazaar` | Sign-in or x402 || `three-ws-pump-fun` | `https://three.ws/api/pump-fun-mcp` | None for reads |@@ -82,6 +83,49 @@ Every client stores a server under the same name, which is also what `--servers``npx three-ws mcp list --available` prints the live list, which is the source of truth if this table and the directory ever disagree.+## Grok Bot++Grok Bot, xAI's computer-use agent, runs on xAI's machines and keeps its connectors there, so there is no file on your computer to write. `setup --client grok-bot` does everything else: it picks the server, gets the credential the auth mode needs, prints the exact fields Grok Bot's custom MCP connector form asks for, copies the server URL to your clipboard, and runs a live check against the public URL the way Grok Bot will call it.++```bash+# Free, no account: the 3D studio for Grok+npx three-ws setup --client grok-bot++# Free, with a quota of its own that survives reconnects (for scheduled tasks)+npx three-ws setup --client grok-bot --auth install++# Your agents, memory and skills too: mints a connector key that can never spend+npx three-ws setup --client grok-bot --auth key++# Sign in from Grok Bot instead of holding a key+npx three-ws setup --client grok-bot --auth oauth+```++What it prints, for the free connector:++```text+Grok Bot three-ws-grok · add it in Grok Bot's Connectors (custom MCP server); nothing is written on this machine+ Name three-ws-grok+ Transport Streamable HTTP+ Server URL https://three.ws/api/mcp-grok+ Authentication None+ Or tell it: "Add a custom MCP server called three-ws-grok at https://three.ws/api/mcp-grok"+ ✔ Server URL copied to the clipboard++ Live check https://three.ws/api/mcp-grok+ ✔ public https URL a cloud agent can reach three.ws+ ✔ initialize + tools/list 15 tools from three-ws-3d-studio-free 1.0.0+```++| `--auth` | What Grok Bot gets | What setup does |+|---|---|---|+| `none` (default) | The free studio: text to 3D, image to 3D, rigging, the asset catalog, personas | Prints the URL and runs `initialize` + `tools/list` against it |+| `install` | The same tools, with a generation budget that lasts across every scheduled run | Mints a free [install token](/docs/mcp-studio#connector-url-for-cloud-agents-install-tokens) (no account), puts it in the URL, and reuses it on later runs so the URL stays the same |+| `key` | Also your agents, memory and skills; a connector key reads, generates and edits but can never spend | Mints a connector key for the signed-in account (signing you in first when needed), or checks the one you pass with `--connector-key`, refuses a key that carries a spend scope, then runs `tools/list` with it |+| `oauth` | The same as `key`, signed in once from Grok Bot and revocable any time | Prints the `?auth=oauth` URL and checks that an anonymous call is answered `401` with a protected-resource document that names the authorization server |++Pass `--servers <name>` to connect a server other than `three-ws-grok`, for example `--servers three-ws-main --auth key` for the full core server. A server that needs an account only takes `key` or `oauth`, and setup says so instead of printing fields that would fail. The live check fails on any URL Grok Bot cannot reach from the internet, such as `--origin http://localhost:3000`, because Grok Bot connects from xAI's cloud. The clipboard step is best-effort (`pbcopy`, `clip`, `wl-copy`, `xclip`, `xsel`, or `clip.exe` under WSL); with none available the URL is printed as usual, and `THREE_WS_NO_CLIPBOARD=1` turns it off. `--json` prints the fields, the key's scope and every check as one document. Connector settings, the tool contract and the fix for every probe failure are in the [Grok Bot connector reference](/docs/grok-bot).+## Create an agent and launch its coin```bashdiff --git a/docs/grok-bot.md b/docs/grok-bot.mdindex ba6f87b63..6fea970e1 100644--- a/docs/grok-bot.md+++ b/docs/grok-bot.md@@ -29,7 +29,9 @@ server never works. Add the server either by telling Grok Bot in chat("Add a custom MCP server called three-ws-grok at https://three.ws/api/mcp-grok")or through its connector form. The form takes four fields, and[three.ws/connect?client=grok](/connect?client=grok) shows them with a copy-button for every hosted server. Use the name `three-ws-grok` so the guided+button for every hosted server. From a terminal, `npx three-ws setup --client grok-bot`+prints the same fields, mints the install token or connector key the mode needs,+copies the URL and checks it live ([CLI docs](./cli.md#grok-bot)). Use the name `three-ws-grok` so the guidedprompts, the [skill file](https://three.ws/grok-skill.md) and the `/grok` pageall refer to the connector by the same name.diff --git a/packages/three-ws-cli/README.md b/packages/three-ws-cli/README.mdindex 8d83e8423..6d766c632 100644--- a/packages/three-ws-cli/README.md+++ b/packages/three-ws-cli/README.md@@ -1,6 +1,6 @@# three-ws-Connect any MCP client to [three.ws](https://three.ws) in one command. `three-ws` signs you in, writes the hosted three.ws MCP servers into every client it finds (Claude Code, Claude Desktop, Cursor, Windsurf, VS Code, Codex, Gemini CLI, Hermes), and verifies each one with a live `tools/list`.+Connect any MCP client to [three.ws](https://three.ws) in one command. `three-ws` signs you in, writes the hosted three.ws MCP servers into every client it finds (Claude Code, Claude Desktop, Cursor, Windsurf, VS Code, Codex, Gemini CLI, Hermes), and verifies each one with a live `tools/list`. For Grok Bot, whose connectors live in xAI's cloud, it prints the connector fields and checks them live instead.```bashnpx three-ws setup@@ -29,6 +29,32 @@ npx three-ws launch --agent <id> --name Nova --symbol NOVA # prefilled, youSign-in is a browser OAuth flow by default. `--device` approves a code from any browser, and `--key sk_live_...` (or `THREE_WS_API_KEY`) uses an API key from [Dashboard → API](https://three.ws/dashboard/api). Tools that move funds are off unless you sign in with `--financial` and enable them.+## Grok Bot++Grok Bot keeps its connectors in xAI's cloud, so `setup` has no file to write for it. It picks the server, gets the credential, prints the fields Grok Bot's custom MCP connector form asks for, copies the server URL to the clipboard, and runs `initialize` + `tools/list` against the public URL the way Grok Bot will.++```bash+npx three-ws setup --client grok-bot # free 3D studio, no account+npx three-ws setup --client grok-bot --auth install # free, a quota that survives reconnects+npx three-ws setup --client grok-bot --auth key # mints a connector key that can never spend+npx three-ws setup --client grok-bot --auth oauth # Grok Bot signs in itself+```++```text+Grok Bot three-ws-grok · add it in Grok Bot's Connectors (custom MCP server); nothing is written on this machine+ Name three-ws-grok+ Transport Streamable HTTP+ Server URL https://three.ws/api/mcp-grok+ Authentication None+ ✔ Server URL copied to the clipboard++ Live check https://three.ws/api/mcp-grok+ ✔ public https URL a cloud agent can reach three.ws+ ✔ initialize + tools/list 15 tools from three-ws-3d-studio-free 1.0.0+```++`--connector-key sk_live_...` uses a key you made at [Dashboard → API](https://three.ws/dashboard/api) ("For an AI agent") instead of minting one; a key that can spend is refused. `--servers <name>` connects another server. `mcp add` and `mcp remove` do not apply to Grok Bot, since there is no local file. Details: [three.ws/docs/cli#grok-bot](https://three.ws/docs/cli#grok-bot) and the [Grok Bot connector reference](https://three.ws/docs/grok-bot).+## Programmatic useThe package exports its building blocks (server directory, client detection, config writers, OAuth helpers) for tools that want to reuse them. List every hosted server and the name clients store it under:diff --git a/packages/three-ws-cli/package.json b/packages/three-ws-cli/package.jsonindex 7a0d6bc8f..10ae7cc38 100644--- a/packages/three-ws-cli/package.json+++ b/packages/three-ws-cli/package.json@@ -1,7 +1,7 @@{"name": "three-ws","version": "0.1.0",- "description": "One command to connect any MCP client to three.ws: sign in with OAuth or an API key, write the three.ws MCP servers into Claude Code, Claude Desktop, Cursor, Windsurf, VS Code, Codex, Gemini CLI or Hermes, and verify each with a live tools/list.",+ "description": "One command to connect any MCP client to three.ws: sign in with OAuth or an API key, write the three.ws MCP servers into Claude Code, Claude Desktop, Cursor, Windsurf, VS Code, Codex, Gemini CLI or Hermes, print a ready Grok Bot connector, and verify each with a live tools/list.","keywords": ["three.ws","mcp",@@ -13,6 +13,7 @@"vscode","codex","gemini",+ "grok","solana","agents"],diff --git a/packages/three-ws-cli/src/cli.js b/packages/three-ws-cli/src/cli.jsindex 5cff69e0d..afa53ba5d 100755--- a/packages/three-ws-cli/src/cli.js+++ b/packages/three-ws-cli/src/cli.js@@ -44,13 +44,19 @@ ${c.bold('Sign-in options')} (setup, login)--financial Also request the scopes that let tools spend from your agent wallet${c.bold('Setup options')}- --clients a,b claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, hermes, print+ --clients a,b claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, hermes, grok-bot, print--servers a,b Server slugs or paths (default: /mcp, the unified server with every tool)--packages a,b Also add stdio @three-ws/*-mcp packages--project Write project-scoped config (.mcp.json, .cursor/, .vscode/, .gemini/) in this directory--proxy Route every server through the local proxy (enforces tool choices in every client)--yes Never prompt; use defaults+${c.bold('Grok Bot options')} (setup --client grok-bot; Grok Bot keeps connectors in xAI's cloud)+ --auth <mode> none (free), install (free, a quota that survives reconnects),+ key (a connector key that can never spend) or oauth+ --connector-key <key> Use this key for --auth key instead of minting one+ --servers <slug> Connect another server than the recommended three-ws-grok+${c.bold('Tools options')}--server <slug> Server to change--enable a,b Tiers (read, write, financial) or tool names to turn on@@ -110,6 +116,8 @@ const OPTIONS = {symbol: { type: 'string' },image: { type: 'string' },'initial-buy': { type: 'string' },+ auth: { type: 'string' },+ 'connector-key': { type: 'string' },};// `--key` alone (no value) means "prompt for it"; parseArgs needs a value for adiff --git a/packages/three-ws-cli/src/clients/index.js b/packages/three-ws-cli/src/clients/index.jsindex 2e45de57b..00029502d 100644--- a/packages/three-ws-cli/src/clients/index.js+++ b/packages/three-ws-cli/src/clients/index.js@@ -114,6 +114,25 @@ export const CLIENTS = [},];+// Clients of the "remote" kind keep their configuration in their own cloud, so+// there is no file to write: `setup` prints the connector form's fields, copies+// the URL and verifies it live instead (../remote.js). Never detected locally.+export const REMOTE_CLIENTS = [+ {+ id: 'grok-bot',+ label: 'Grok Bot',+ kind: 'remote',+ // Its key in the directory's `clients` block (/.well-known/mcp.json).+ directoryKey: 'grok-bot',+ // Used when the directory predates that block: the Grok surface of the+ // free studio, then the studio itself.+ preferredPaths: ['/api/mcp-grok', '/api/mcp-studio'],+ transport: 'Streamable HTTP',+ where: "Grok Bot's Connectors (custom MCP server)",+ docs: '/docs/grok-bot',+ },+];+// Not a real client: the shape `setup` prints for any client it does not know.export const PRINT_CLIENT = {id: 'print',@@ -123,11 +142,13 @@ export const PRINT_CLIENT = {};export function getClient(id) {- const c = CLIENTS.find((x) => x.id === id);- if (!c) throw new Error(`unknown client "${id}". Known: ${CLIENTS.map((x) => x.id).join(', ')}`);+ const c = CLIENTS.find((x) => x.id === id) || REMOTE_CLIENTS.find((x) => x.id === id);+ if (!c) throw new Error(`unknown client "${id}". Known: ${[...CLIENTS, ...REMOTE_CLIENTS].map((x) => x.id).join(', ')}`);return c;}+export const isRemote = (client) => client?.kind === 'remote';+export function detectClients(env = systemEnv()) {return CLIENTS.filter((c) => c.detect(env));}diff --git a/packages/three-ws-cli/src/clipboard.js b/packages/three-ws-cli/src/clipboard.jsnew file mode 100644index 000000000..aa9003f13--- /dev/null+++ b/packages/three-ws-cli/src/clipboard.js@@ -0,0 +1,31 @@+// Copy text to the system clipboard with the OS's own tool. No dependency:+// `pbcopy` on macOS, `clip` on Windows, then wl-copy, xclip, xsel and WSL's+// clip.exe on Linux. Best-effort by design: returns the tool that took the+// text, or null (never throws) when none exists, e.g. over SSH or in CI, and+// the caller has already printed the text anyway.++import { spawnSync } from 'node:child_process';++export function clipboardCommands({ platform = process.platform, env = process.env } = {}) {+ if (platform === 'darwin') return [['pbcopy', []]];+ if (platform === 'win32') return [['clip', []]];+ const cmds = [];+ if (env.WAYLAND_DISPLAY) cmds.push(['wl-copy', []]);+ if (env.DISPLAY) cmds.push(['xclip', ['-selection', 'clipboard']], ['xsel', ['--clipboard', '--input']]);+ // WSL: the Windows clipboard is reachable with no display at all.+ if (env.WSL_DISTRO_NAME) cmds.push(['clip.exe', []]);+ return cmds;+}++export function copyToClipboard(text, { platform = process.platform, env = process.env, run = spawnSync } = {}) {+ if (env.THREE_WS_NO_CLIPBOARD === '1') return null;+ for (const [cmd, args] of clipboardCommands({ platform, env })) {+ try {+ const res = run(cmd, args, { input: String(text), stdio: ['pipe', 'ignore', 'ignore'], timeout: 3000 });+ if (!res.error && res.status === 0) return cmd;+ } catch {+ // A missing tool is the normal case on most machines; try the next one.+ }+ }+ return null;+}diff --git a/packages/three-ws-cli/src/commands/mcp.js b/packages/three-ws-cli/src/commands/mcp.jsindex 95752b5af..7c22c1ae9 100644--- a/packages/three-ws-cli/src/commands/mcp.js+++ b/packages/three-ws-cli/src/commands/mcp.js@@ -4,12 +4,17 @@import { c, line, sym, printJson, tildify } from '../ui.js';import { readStore } from '../store.js';import { loadDirectory, hostedServers } from '../servers.js';-import { detectClients, getClient, removeServer } from '../clients/index.js';+import { detectClients, getClient, removeServer, isRemote } from '../clients/index.js';import { verifyServers, ensureSelections, applyToClients } from '../configure.js';import { scanClients } from './account.js';function clientsFrom(flags, env) {- if (flags.clients) return String(flags.clients).split(',').map((s) => getClient(s.trim()));+ if (flags.clients) {+ const clients = String(flags.clients).split(',').map((s) => getClient(s.trim()));+ const remote = clients.find(isRemote);+ if (remote) throw new Error(`${remote.label} keeps its connectors in its own cloud, so there is no file to edit. Run \`three-ws setup --client ${remote.id}\` to print its fields and verify them.`);+ return clients;+ }const detected = detectClients(env);if (!detected.length) throw new Error('no MCP clients detected; name one with --clients (e.g. --clients cursor)');return detected;@@ -50,9 +55,9 @@ async function addCmd(ctx, name) {const { flags, env, origin } = ctx;if (!name) throw new Error('usage: three-ws mcp add <server> [--clients a,b] [--project] [--proxy]');const store = readStore(env);+ const clients = clientsFrom(flags, env);const server = findServer(hostedServers(await loadDirectory(origin), origin), name);if (server.auth === 'required' && !store.auth) throw new Error('sign in first: `three-ws login` (or `three-ws login --key sk_live_...` in CI)');- const clients = clientsFrom(flags, env);const mode = store.auth?.type === 'apikey' ? 'apikey' : 'oauth';ensureSelections([server], { financial: /\bwallet:write\b/.test(store.auth?.scope || ''), env });const [result] = await verifyServers({ servers: [server], env, origin });diff --git a/packages/three-ws-cli/src/commands/setup-remote.js b/packages/three-ws-cli/src/commands/setup-remote.jsnew file mode 100644index 000000000..6d871cde9--- /dev/null+++ b/packages/three-ws-cli/src/commands/setup-remote.js@@ -0,0 +1,173 @@+// The remote half of `three-ws setup`: clients such as Grok Bot whose+// connectors live in their own cloud. Nothing is written on this machine.+// For each one: pick the server and auth mode, get the credential that mode+// needs, print the connector form's exact fields, copy the URL, and run the+// live check against the public URL (../remote.js).++import * as p from '@clack/prompts';+import { answer, canPrompt, signIn } from './common.js';+import { c, line, sym, rows } from '../ui.js';+import { currentIdentity } from '../auth.js';+import { copyToClipboard } from '../clipboard.js';+import {+ directoryEntry,+ recommendedServer,+ modesFor,+ defaultMode,+ parseMode,+ installUrl,+ connectorKey,+ checkConnectorKey,+ connectorUrl,+ connectorFields,+ sayLine,+ verifyConnector,+} from '../remote.js';++const MODE_OPTIONS = {+ none: { label: 'None, free', hint: 'the free 3D tools; the quota lasts one connection' },+ install: { label: 'None, with a free install token', hint: 'its own quota that survives reconnects, for scheduled tasks' },+ key: { label: 'Connector API key', hint: 'adds your agents, memory and skills; can never spend' },+ oauth: { label: 'OAuth 2.1', hint: 'sign in from the client once; revoke any time' },+};++const STEPS = (client, { say }) => [+ `In ${client.label}, open Connectors and add a custom MCP server with the fields above${say ? ', or send it the sentence above and confirm what it shows' : ''}.`,+ 'Check the name and URL it shows, then confirm.',+ 'Ask for 3D in any task, or attach the server with @ and its name.',+];++async function chooseServer(ctx, client, { directory, servers, picked }) {+ if (picked?.length) return picked;+ const recommended = recommendedServer(client, directory, servers);+ if (!canPrompt(ctx) || !recommended) return recommended ? [recommended] : [];+ const slug = answer(await p.select({+ message: `Which server should ${client.label} connect to?`,+ options: servers.map((s) => ({ value: s.slug, label: `${s.name} ${c.dim(s.path)}`, hint: s === recommended ? 'recommended' : s.keyless ? 'free tools need no account' : 'needs a key or sign-in' })),+ initialValue: recommended.slug,+ }));+ return servers.filter((s) => s.slug === slug);+}++async function chooseMode(ctx, client, { directory, server }) {+ if (ctx.flags.auth) return parseMode(ctx.flags.auth);+ if (ctx.flags['connector-key']) return 'key';+ const supported = modesFor(server);+ const initial = defaultMode(client, directory, server);+ if (!canPrompt(ctx)) return initial;+ return answer(await p.select({+ message: `How should ${client.label} authenticate to ${server.slug}?`,+ options: supported.map((m) => ({ value: m, ...MODE_OPTIONS[m] })),+ initialValue: initial,+ }));+}++/** The connector key for key mode: the one passed in, else a minted (or reused) connector-preset key. */+async function keyFor(ctx, client) {+ const { origin, env } = ctx;+ const passed = ctx.flags['connector-key'];+ if (passed) return checkConnectorKey({ origin, key: String(passed).trim() });+ let me = null;+ try { me = await currentIdentity({ origin, env }); } catch { me = null; }+ if (!me && canPrompt(ctx)) {+ p.log.info('A connector key belongs to your account, so sign in once to mint it.');+ await signIn(ctx, {});+ }+ return connectorKey({ origin, label: client.label, env });+}++/** One connector: credential, fields, live check. Never throws; failures land in `error` and `checks`. */+async function connectOne(ctx, client, { directory, server, mode }) {+ const base = { client, server, mode, url: null, fields: [], say: null, key: null, checks: [], error: null };+ try {+ if (!modesFor(server).includes(mode)) {+ throw new Error(`${server.slug} does not take --auth ${mode}; it supports ${modesFor(server).join(', ')}`);+ }+ let install = null;+ let key = null;+ if (mode === 'install') install = (await installUrl({ client, directory, server, origin: ctx.origin, env: ctx.env })).url;+ if (mode === 'key') key = await keyFor(ctx, client);+ const url = connectorUrl(server, mode, { install });+ const checks = await verifyConnector({ url, mode, key: key?.key });+ return {+ ...base,+ url,+ key: key ? { value: key.key, scope: key.scope, connector: key.connector, reused: key.reused } : null,+ fields: connectorFields({ client, server, mode, url, key: key?.key }),+ say: sayLine({ server, mode, url }),+ checks,+ };+ } catch (err) {+ return { ...base, error: err.message };+ }+}++export const remoteOk = (r) => !r.error && r.checks.length > 0 && r.checks.every((x) => x.ok);++/**+ * Connect every remote client. `picked` is the server list `--servers` chose,+ * or null for the client's recommendation.+ */+export async function connectRemote(ctx, { clients, directory, servers, picked = null }) {+ const results = [];+ for (const client of clients) {+ const chosen = await chooseServer(ctx, client, { directory, servers, picked });+ if (!chosen.length) {+ results.push({ client, server: null, mode: null, url: null, fields: [], say: null, key: null, checks: [], error: `${ctx.origin} lists no MCP server ${client.label} can connect to` });+ continue;+ }+ for (const server of chosen) {+ const mode = await chooseMode(ctx, client, { directory, server });+ const spin = canPrompt(ctx) ? p.spinner() : null;+ spin?.start(`Checking ${server.slug} from outside, the way ${client.label} will call it`);+ const result = await connectOne(ctx, client, { directory, server, mode });+ spin?.stop(remoteOk(result) ? 'Live check passed' : 'Live check finished with problems');+ const entry = directoryEntry(client, directory);+ result.steps = STEPS(client, result);+ result.note = entry?.notes || null;+ results.push(result);+ }+ }+ // One clipboard: copy the URL when there is exactly one to paste.+ const pasteable = results.filter((r) => r.url && !r.error);+ if (!ctx.flags.json && pasteable.length === 1) pasteable[0].copied = copyToClipboard(pasteable[0].url, { env: ctx.env.vars });+ return results;+}++export function remoteJson(results) {+ return results.map((r) => ({+ id: r.client.id,+ server: r.server?.slug || null,+ auth: r.mode,+ url: r.url,+ fields: Object.fromEntries(r.fields),+ say: r.say,+ key: r.key ? { scope: r.key.scope, connector: r.key.connector, reused: r.key.reused } : null,+ checks: r.checks.map(({ id, label, ok, detail }) => ({ id, label, ok, detail })),+ ok: remoteOk(r),+ error: r.error,+ }));+}++export function printRemote(results, { origin }) {+ for (const r of results) {+ line('');+ line(`${c.bold(r.client.label)} ${c.dim(`${r.server ? r.server.slug : ''} · add it in ${r.client.where}; nothing is written on this machine`)}`);+ if (r.error) {+ line(` ${c.red(sym.fail)} ${r.error}`);+ continue;+ }+ rows(r.fields.map(([k, v]) => [k, k === 'Value' ? `${c.bold(v)} ${c.dim('(store it as a Bot secret)')}` : c.bold(v)]), ' ');+ if (r.say) line(` ${c.dim('Or tell it:')} "${r.say}"`);+ if (r.copied) line(` ${c.green(sym.ok)} Server URL copied to the clipboard`);+ if (r.note) line(` ${c.dim(r.note)}`);+ line('');+ line(` ${c.bold('Live check')} ${c.dim(r.url.split('?')[0])}`);+ const width = Math.max(...r.checks.map((x) => x.label.length));+ for (const x of r.checks) line(` ${x.ok ? c.green(sym.ok) : c.red(sym.fail)} ${x.label.padEnd(width)} ${c.dim(x.detail)}`);+ line('');+ line(` ${c.bold('Next')}`);+ r.steps.forEach((s, i) => line(` ${i + 1}. ${s}`));+ line(` ${c.dim(`Docs: ${origin}${r.client.docs}`)}`);+ }+}diff --git a/packages/three-ws-cli/src/commands/setup.js b/packages/three-ws-cli/src/commands/setup.jsindex d88087263..aa4b5712f 100644--- a/packages/three-ws-cli/src/commands/setup.js+++ b/packages/three-ws-cli/src/commands/setup.js@@ -1,5 +1,6 @@// `three-ws setup`: sign in, pick servers and clients, write every config,-// then prove it with a real tools/list per server.+// then prove it with a real tools/list per server. Remote clients (Grok Bot)+// get their connector fields printed and checked live instead (setup-remote.js).import * as p from '@clack/prompts';import { answer, canPrompt, signIn, authModeFromFlags } from './common.js';@@ -7,10 +8,11 @@ import { c, line, sym, printJson, tildify } from '../ui.js';import { readStore } from '../store.js';import { currentIdentity, ensureStdioKey } from '../auth.js';import { loadDirectory, loadCatalog, hostedServers, stdioPackages } from '../servers.js';-import { CLIENTS, PRINT_CLIENT, detectClients, getClient } from '../clients/index.js';+import { CLIENTS, REMOTE_CLIENTS, PRINT_CLIENT, detectClients, getClient, isRemote } from '../clients/index.js';import { verifyServers, ensureSelections, applyToClients } from '../configure.js';import { usesProxy, buildEntry } from '../entries.js';import { VERSION } from '../http.js';+import { connectRemote, printRemote, remoteJson, remoteOk } from './setup-remote.js';function list(value) {if (!value) return null;@@ -31,6 +33,14 @@ export async function setup(ctx) {const interactive = canPrompt(ctx);if (interactive) p.intro(`${c.bold('three.ws')} setup ${c.dim(`v${VERSION} · ${origin}`)}`);+ // Only remote clients asked for: nothing to write here, and no account+ // needed unless the chosen auth mode mints a key.+ const requestedClients = list(flags.clients);+ const requested = requestedClients ? requestedClients.filter((id) => id !== 'print').map(getClient) : [];+ if (requested.length && requested.every(isRemote) && !requestedClients.includes('print')) {+ return setupRemoteOnly(ctx, requested, interactive);+ }+// 1. Account. Reuse a working credential unless a mode was asked for.const requestedMode = authModeFromFlags(flags);let me = null;@@ -77,15 +87,15 @@ export async function setup(ctx) {const detected = detectClients(env);let clients;let printOnly = false;- const requestedClients = list(flags.clients);if (requestedClients) {printOnly = requestedClients.includes('print');- clients = requestedClients.filter((id) => id !== 'print').map(getClient);+ clients = requested;} else if (interactive) {const chosen = answer(await p.multiselect({message: detected.length ? 'Write the config into which clients?' : 'No MCP clients found on this machine. Write a config for which ones anyway?',options: [...CLIENTS.map((cl) => ({ value: cl.id, label: cl.label, hint: detected.includes(cl) ? tildify(cl.configPath(env, { project: flags.project })) : 'not detected' })),+ ...REMOTE_CLIENTS.map((cl) => ({ value: cl.id, label: cl.label, hint: 'runs in its own cloud: prints the connector fields and checks them live' })),{ value: 'print', label: 'Print the JSON instead', hint: 'for any other MCP client' },],initialValues: detected.length ? detected.map((cl) => cl.id) : ['print'],@@ -97,6 +107,8 @@ export async function setup(ctx) {clients = detected;printOnly = !detected.length;}+ const remoteClients = clients.filter(isRemote);+ clients = clients.filter((cl) => !isRemote(cl));// 4. Optional stdio packages.let packages = [];@@ -132,6 +144,7 @@ export async function setup(ctx) {const apiKey = mode === 'apikey' ? readStore(env).auth.key : null;const writes = applyToClients({ clients, servers, packages, mode, apiKey, stdioKey, liveTools, forceProxy: Boolean(flags.proxy), project: Boolean(flags.project), origin, env });const selections = readStore(env).tools || {};+ const remote = remoteClients.length ? await connectRemote(ctx, { clients: remoteClients, directory, servers: allServers }) : [];const printed = printOnly? Object.fromEntries(servers.map((s) => [s.slug, buildEntry({ client: PRINT_CLIENT, server: s, mode, apiKey, selection: selections[s.slug], liveTools: liveTools[s.slug], forceProxy: Boolean(flags.proxy) })])): null;@@ -143,8 +156,9 @@ export async function setup(ctx) {servers: results.map((r) => ({ slug: r.server.slug, url: r.server.url, ok: r.ok, tools: r.ok ? r.total : null, enabled: r.ok ? r.enabled : null, error: r.error || null })),clients: writes.map((w) => ({ id: w.client.id, file: w.file, servers: w.servers, error: w.error })),...(printed ? { print: { mcpServers: printed } } : {}),+ ...(remote.length ? { remote: remoteJson(remote) } : {}),});- return results.every((r) => r.ok) && writes.every((w) => !w.error) ? 0 : 1;+ return results.every((r) => r.ok) && writes.every((w) => !w.error) && remote.every(remoteOk) ? 0 : 1;}line('');@@ -173,8 +187,9 @@ export async function setup(ctx) {line(c.bold('Add this to any MCP client:'));printJson({ mcpServers: printed });}+ if (remote.length) printRemote(remote, { origin });line('');- const failed = results.filter((r) => !r.ok).length + writes.filter((w) => w.error).length;+ const failed = results.filter((r) => !r.ok).length + writes.filter((w) => w.error).length + remote.filter((r) => !remoteOk(r)).length;if (interactive) {if (failed) p.outro(c.yellow(`${failed} step${failed === 1 ? '' : 's'} failed above. Fix it and run \`three-ws setup\` again; finished steps are kept.`));else p.outro(`Done. Restart your client${writes.length === 1 ? '' : 's'} to load the tools. ${c.dim('Check anytime: three-ws status')}`);@@ -183,3 +198,25 @@ export async function setup(ctx) {}return failed ? 1 : 0;}++async function setupRemoteOnly(ctx, clients, interactive) {+ const { flags, origin } = ctx;+ const directory = await loadDirectory(origin);+ const servers = hostedServers(directory, origin);+ const results = await connectRemote(ctx, { clients, directory, servers, picked: pickServers(servers, list(flags.servers)) });+ const ok = results.every(remoteOk);+ if (flags.json) {+ printJson({ remote: remoteJson(results) });+ return ok ? 0 : 1;+ }+ printRemote(results, { origin });+ line('');+ const names = clients.map((cl) => cl.label).join(' and ');+ if (interactive) {+ if (ok) p.outro(`Ready. Add the connector in ${names} with the fields above.`);+ else p.outro(c.yellow('A step failed above. Fix it and run setup again.'));+ } else {+ line(ok ? `Ready. Add the connector in ${names} with the fields above.` : c.yellow('A step failed above.'));+ }+ return ok ? 0 : 1;+}diff --git a/packages/three-ws-cli/src/index.js b/packages/three-ws-cli/src/index.jsindex ef0420f1a..68a3e672c 100644--- a/packages/three-ws-cli/src/index.js+++ b/packages/three-ws-cli/src/index.js@@ -7,8 +7,10 @@ export { credentialsPath, configDir, systemEnv } from './paths.js';export { bearerFor, authorizeInBrowser, discover, pkcePair } from './oauth.js';export { deviceLogin, startLink, pollLink } from './device.js';export { loginKey, loginOAuth, loginDevice, logout, whoami, currentIdentity, ensureStdioKey, scopesFor } from './auth.js';-export { CLIENTS, PRINT_CLIENT, getClient, detectClients, readServers, writeServer, removeServer } from './clients/index.js';+export { CLIENTS, REMOTE_CLIENTS, PRINT_CLIENT, getClient, isRemote, detectClients, readServers, writeServer, removeServer } from './clients/index.js';export { hostedServers, stdioPackages, slugForPath, loadDirectory, loadCatalog } from './servers.js';+export { recommendedServer, modesFor, defaultMode, installUrl, connectorKey, checkConnectorKey, connectorUrl, connectorFields, verifyConnector, isPublicUrl } from './remote.js';+export { copyToClipboard } from './clipboard.js';export { buildEntry, buildPackageEntry, proxyInvocation, usesProxy } from './entries.js';export { listTools, post as mcpPost, parseSse } from './mcp-http.js';export { runProxy } from './proxy.js';diff --git a/packages/three-ws-cli/src/remote.js b/packages/three-ws-cli/src/remote.jsnew file mode 100644index 000000000..a4d13e482--- /dev/null+++ b/packages/three-ws-cli/src/remote.js@@ -0,0 +1,273 @@+// Remote clients: MCP clients whose configuration lives in someone else's+// cloud. Grok Bot runs on xAI's machines and keeps its connectors there, so+// there is no file on this machine to write. `setup` does everything else:+// picks the server, gets the credential the auth mode needs (a free install+// token, or a connector key that can never spend), prints the connector form's+// exact fields, copies the URL, and proves the public URL answers from outside.+//+// What to connect comes from the live directory (/.well-known/mcp.json): its+// `clients` block names each client's recommended server and install endpoint,+// and a deployment that predates the block falls back to the client's+// preferred paths among the servers the directory lists.++import os from 'node:os';+import { requestJson, request, ApiError, VERSION } from './http.js';+import { listTools, PROTOCOL_VERSION } from './mcp-http.js';+import { readStore, updateStore } from './store.js';+import { bearerFor } from './oauth.js';+import { whoami } from './auth.js';+import { systemEnv } from './paths.js';++/** none: anonymous. install: anonymous with a free install token. key: a connector API key. oauth: sign in from the client. */+export const AUTH_MODES = ['none', 'install', 'key', 'oauth'];++export const AUTH_LABELS = {+ none: 'None',+ install: 'None',+ key: 'API key',+ oauth: 'OAuth 2.1',+};++// A connector key is held unattended by a cloud agent, so it must never carry+// a scope that moves funds (api/_lib/spend-scope.js).+const SPEND_SCOPES = ['wallet:write', 'services:write'];+const CONNECTOR_MARKER = 'connector';++// The query parameter that makes a studio surface answer anonymous callers 401+// so a connector set to OAuth 2.1 starts sign-in (api/_mcp-studio/handler.js).+const SIGN_IN_PARAM = 'auth';++/** The directory's `clients` entry for a remote client, or null. */+export function directoryEntry(client, directory) {+ const entry = directory?.clients?.[client.directoryKey];+ return entry && typeof entry === 'object' ? entry : null;+}++function pathOf(url) {+ try {+ return new URL(url).pathname;+ } catch {+ return null;+ }+}++/**+ * The server a remote client is pointed at when the person names none: the+ * directory's recommendation, else the first of the client's preferred paths+ * the directory lists, else the first server that needs no account.+ */+export function recommendedServer(client, directory, servers) {+ const entry = directoryEntry(client, directory);+ const byPath = (p) => servers.find((s) => s.path === p);+ return (entry?.server && byPath(pathOf(entry.server))) || client.preferredPaths.map(byPath).find(Boolean) || servers.find((s) => s.keyless) || servers[0] || null;+}++/** The auth modes a server supports as a connector. */+export function modesFor(server) {+ if (server.auth === 'none') return ['none', 'install'];+ if (server.keyless) return ['none', 'install', 'key', 'oauth'];+ return ['key', 'oauth'];+}++/** The default mode for a server: the directory's, when it applies, else the first supported one. */+export function defaultMode(client, directory, server) {+ const entry = directoryEntry(client, directory);+ const fromDirectory = { none: 'none', 'api-key': 'key', oauth: 'oauth' }[entry?.auth];+ const supported = modesFor(server);+ if (fromDirectory && pathOf(entry.server) === server.path && supported.includes(fromDirectory)) return fromDirectory;+ return supported[0];+}++export function parseMode(value) {+ const v = String(value || '').trim().toLowerCase();+ const alias = { 'api-key': 'key', apikey: 'key', token: 'install', anonymous: 'none' }[v] || v;+ if (!AUTH_MODES.includes(alias)) throw new ApiError(`unknown --auth "${value}". Use one of: ${AUTH_MODES.join(', ')}`);+ return alias;+}++/** The install endpoint: the directory's, rebased onto this origin, else the platform default. */+export function installEndpoint(client, directory, origin) {+ const alt = directoryEntry(client, directory)?.alternatives?.find?.((a) => a?.install);+ const p = alt ? pathOf(alt.install) : null;+ return `${origin}${p || '/api/mcp-studio/install'}`;+}++/**+ * The connector URL carrying a free install token for `server`. A token this+ * machine already minted for the origin is reused, so running setup again+ * prints the same URL and the connector keeps its budget.+ */+export async function installUrl({ client, directory, server, origin, env = systemEnv() }) {+ const pick = (urls) => Object.values(urls || {}).find((u) => pathOf(u) === server.path) || null;+ const saved = readStore(env).install_tokens?.[origin];+ if (saved && pick(saved.connector_urls)) return { url: pick(saved.connector_urls), reused: true };+ let minted;+ try {+ minted = await requestJson(installEndpoint(client, directory, origin), { method: 'POST' });+ } catch (err) {+ if (err.status === 404) throw new ApiError(`${origin} cannot mint install tokens yet; connect with --auth none, or try again after it updates`, { status: 404 });+ throw err;+ }+ const url = pick(minted?.connector_urls) || (pathOf(minted?.connector_url) === server.path ? minted.connector_url : null);+ if (!url) throw new ApiError(`${server.path} does not take install tokens; use --auth none, key or oauth`);+ updateStore((s) => {+ s.install_tokens = { ...(s.install_tokens || {}), [origin]: { token: minted.token, connector_urls: minted.connector_urls || { [server.path]: url }, created_at: minted.created_at || null } };+ return s;+ }, env);+ return { url, reused: false, limits: minted.limits || null };+}++function scopeList(scope) {+ return String(scope || '').split(/\s+/).filter(Boolean);+}++/** Why a key must not be handed to an unattended connector, or null when it may. */+export function connectorKeyProblem(scope) {+ const spend = scopeList(scope).filter((s) => SPEND_SCOPES.includes(s));+ if (spend.length) return `this key carries ${spend.join(' and ')}, which moves funds; a cloud agent holds a connector key unattended. Make one with "For an AI agent" at /dashboard/api, or let setup mint one`;+ return null;+}++/** Check a key someone brought: it must verify and must not be able to spend. */+export async function checkConnectorKey({ origin, key }) {+ let me;+ try {+ me = await whoami(origin, key);+ } catch (err) {+ if (err.status === 401) throw new ApiError('three.ws does not recognize that key; it may be revoked or expired', { status: 401 });+ throw err;+ }+ const scope = me.credential?.scope || '';+ const problem = connectorKeyProblem(scope);+ if (problem) throw new ApiError(problem);+ return { key, scope, connector: scopeList(scope).includes(CONNECTOR_MARKER), reused: true };+}++/**+ * A connector key for the signed-in account: the one this machine minted+ * before when it still verifies, else a new one from the `connector` preset,+ * which reads, generates and edits agent data and never spends.+ */+export async function connectorKey({ origin, label, env = systemEnv() }) {+ const saved = readStore(env).connector_keys?.[origin];+ if (saved?.key) {+ try {+ return await checkConnectorKey({ origin, key: saved.key });+ } catch (err) {+ if (err.status !== 401) throw err;+ }+ }+ const bearer = await bearerFor(env, { origin });+ if (!bearer) throw new ApiError('sign in first so setup can mint a connector key: `npx three-ws login`, or pass --connector-key sk_live_...');+ const res = await requestJson(`${origin}/api/api-keys`, {+ method: 'POST',+ headers: { authorization: `Bearer ${bearer}` },+ // The preset fixes the scopes server side. `scope` names the marker too,+ // so a deployment that predates the preset refuses the request with 400+ // instead of minting a standard key in its place.+ json: { name: `${label} (three-ws CLI on ${os.hostname()})`.slice(0, 80), preset: CONNECTOR_MARKER, scope: `avatars:read ${CONNECTOR_MARKER}` },+ }).catch((err) => {+ if (err.status === 400) throw new ApiError(`${origin} cannot mint connector keys from the CLI yet. Make one at ${origin}/dashboard/api ("For an AI agent") and pass it with --connector-key`, { status: 400 });+ throw err;+ });+ const minted = res.data;+ if (!scopeList(minted.scope).includes(CONNECTOR_MARKER) || connectorKeyProblem(minted.scope)) {+ throw new ApiError(`the key ${origin} minted is not a connector key (scope: ${minted.scope}); revoke ${minted.prefix} at ${origin}/dashboard/api`);+ }+ updateStore((s) => {+ s.connector_keys = { ...(s.connector_keys || {}), [origin]: { key: minted.token, prefix: minted.prefix, key_id: minted.id, scope: minted.scope } };+ return s;+ }, env);+ return { key: minted.token, scope: minted.scope, connector: true, reused: false };+}++/** The URL the connector form takes for this server and mode. */+export function connectorUrl(server, mode, { install = null } = {}) {+ if (mode === 'install') return install;+ if (mode === 'oauth' && server.keyless) {+ const u = new URL(server.url);+ u.searchParams.set(SIGN_IN_PARAM, 'oauth');+ return u.toString();+ }+ return server.url;+}++/** The fields the client's connector form asks for, in its order. */+export function connectorFields({ client, server, mode, url, key = null }) {+ const fields = [+ ['Name', server.slug],+ ['Transport', client.transport],+ ['Server URL', url],+ ['Authentication', AUTH_LABELS[mode]],+ ];+ if (mode === 'key') fields.push(['Header', 'Authorization'], ['Value', `Bearer ${key}`]);+ if (mode === 'oauth') fields.push(['Client ID', 'leave empty: the connector registers itself']);+ return fields;+}++/** The sentence to paste into the client's chat instead of filling the form. A key never goes in chat. */+export function sayLine({ server, mode, url }) {+ if (mode === 'key') return null;+ return `Add a custom MCP server called ${server.slug} at ${url}${mode === 'oauth' ? ' with OAuth authentication' : ''}`;+}++const PRIVATE_HOST = /^(localhost|.*\.localhost|.*\.local|.*\.internal|127\.\d+\.\d+\.\d+|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|169\.254\.\d+\.\d+|0\.0\.0\.0|\[?::1\]?|\[?f[cd][0-9a-f]{2}:.*)$/i;++/** True when a cloud client can reach the URL: https on a public host name. */+export function isPublicUrl(url) {+ try {+ const u = new URL(url);+ return u.protocol === 'https:' && !PRIVATE_HOST.test(u.hostname);+ } catch {+ return false;+ }+}++async function oauthChecks(url) {+ const checks = [];+ const res = await request(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'mcp-protocol-version': PROTOCOL_VERSION },+ json: { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: 'three-ws-cli', version: VERSION } } },+ });+ await res.text();+ const challenge = res.headers.get('www-authenticate') || '';+ const metadata = /resource_metadata="([^"]+)"/.exec(challenge)?.[1] || null;+ const asks = res.status === 401 && Boolean(metadata);+ checks.push({ id: 'oauth-challenge', label: 'asks an anonymous client to sign in', ok: asks, detail: asks ? `401, ${new URL(metadata).pathname}` : `answered ${res.status}${challenge ? '' : ' with no www-authenticate'}` });+ if (!asks) return checks;+ try {+ const doc = await requestJson(metadata);+ const servers = Array.isArray(doc?.authorization_servers) ? doc.authorization_servers : [];+ checks.push({ id: 'oauth-metadata', label: 'publishes its authorization server', ok: servers.length > 0, detail: servers[0] || 'no authorization_servers' });+ } catch (err) {+ checks.push({ id: 'oauth-metadata', label: 'publishes its authorization server', ok: false, detail: err.message });+ }+ return checks;+}++/**+ * The live check, made from this machine exactly as the cloud client will+ * call: the public URL, the connector's own credential, a real initialize and+ * tools/list. Never throws; each check carries its own result.+ */+export async function verifyConnector({ url, mode, key = null }) {+ const checks = [];+ const reachable = isPublicUrl(url);+ checks.push({ id: 'public', label: 'public https URL a cloud agent can reach', ok: reachable, detail: reachable ? new URL(url).host : `${new URL(url).host} is not reachable from the internet; use the public deployment` });+ try {+ const { tools, serverInfo } = await listTools(url, { bearer: mode === 'key' ? key : null });+ const name = serverInfo?.name ? ` from ${serverInfo.name}${serverInfo.version ? ` ${serverInfo.version}` : ''}` : '';+ if (mode === 'oauth') {+ // A client only starts OAuth on a 401, so a URL that serves anonymous+ // callers would leave the connector signed out forever.+ checks.push({ id: 'oauth-challenge', label: 'asks an anonymous client to sign in', ok: false, detail: `answered anonymously with ${tools.length} tools, so sign-in never starts` });+ } else {+ checks.push({ id: 'tools', label: 'initialize + tools/list', ok: tools.length > 0, detail: `${tools.length} tools${name}`, tools: tools.length });+ }+ } catch (err) {+ if (mode === 'oauth' && err.status === 401) checks.push(...(await oauthChecks(url).catch((e) => [{ id: 'oauth-challenge', label: 'asks an anonymous client to sign in', ok: false, detail: e.message }])));+ else checks.push({ id: 'tools', label: 'initialize + tools/list', ok: false, detail: err.message });+ }+ return checks;+}diff --git a/packages/three-ws-cli/src/servers.js b/packages/three-ws-cli/src/servers.jsindex a1d434371..5342d297f 100644--- a/packages/three-ws-cli/src/servers.js+++ b/packages/three-ws-cli/src/servers.js@@ -36,6 +36,11 @@ export function authRequired(authText) {return !/^none\b/i.test(String(authText || '').trim());}+/** True when anonymous callers are served, even if an account unlocks more ("none needed for the free 3D tools"). */+export function servesAnonymous(authText) {+ return !authRequired(authText) || /\bnone needed\b/i.test(String(authText || ''));+}+/** Normalize the live directory into the CLI's server records, rebased onto `origin`. */export function hostedServers(directory, origin) {const list = Array.isArray(directory?.servers) ? directory.servers : [];@@ -53,6 +58,7 @@ export function hostedServers(directory, origin) {url: `${origin}${pathname}`,description: s.description || '',auth: needsAuth ? 'required' : 'none',+ keyless: servesAnonymous(s.auth),unified: pathname === UNIFIED_PATH,defaultSelected,};diff --git a/packages/three-ws-cli/tests/grok-bot.test.js b/packages/three-ws-cli/tests/grok-bot.test.jsnew file mode 100644index 000000000..623d9413b--- /dev/null+++ b/packages/three-ws-cli/tests/grok-bot.test.js@@ -0,0 +1,307 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { writeStore, readStore } from '../src/store.js';+import { main } from '../src/cli.js';+import { hostedServers } from '../src/servers.js';+import { getClient, REMOTE_CLIENTS, isRemote } from '../src/clients/index.js';+import { recommendedServer, modesFor, defaultMode, parseMode, connectorUrl, connectorFields, isPublicUrl, connectorKeyProblem } from '../src/remote.js';+import { copyToClipboard, clipboardCommands } from '../src/clipboard.js';++const ORIGIN = 'https://three.ws';+const KEY = 'sk_live_cli_grok_test_signin_key_000000';+const CONNECTOR = 'sk_live_cli_grok_test_connector_key_00';++// Fixture: the directory this repo publishes at /.well-known/mcp.json, and the+// same document as a deployment that predates its `clients` block and the Grok+// surface (production on 2026-10-09).+const DIRECTORY = JSON.parse(fs.readFileSync(new URL('../../../public/.well-known/mcp.json', import.meta.url), 'utf8'));+const OLD_DIRECTORY = (() => {+ const { clients: _clients, ...rest } = DIRECTORY;+ return { ...rest, servers: rest.servers.filter((s) => !s.endpoint.endsWith('/api/mcp-grok')) };+})();++function tempEnv() {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'three-ws-grok-'));+ return { home, platform: process.platform, cwd: home, vars: { THREE_WS_NO_BROWSER: '1', THREE_WS_NO_CLIPBOARD: '1', XDG_CONFIG_HOME: path.join(home, '.config') } };+}++function reply(status, body, headers = {}) {+ return new Response(body == null ? null : JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...headers } });+}++const toolList = (n) => Array.from({ length: n }, (_, i) => ({ name: `tool_${i}`, description: 'fixture tool', inputSchema: { type: 'object' } }));++/**+ * A fetch that answers like the platform: the directory, the install mint, the+ * key routes, and Streamable HTTP MCP servers. `anonTools` and `keyTools` are+ * how many tools tools/list returns without and with a bearer.+ */+function platformFetch({ directory = DIRECTORY, anonTools = 15, keyTools = 26, install = 'ok', keyMint = 'ok', whoamiScope = 'avatars:read agents:read memory:read connector' } = {}) {+ return vi.fn(async (url, init = {}) => {+ const u = new URL(url);+ const auth = init.headers?.authorization || null;+ if (u.pathname === '/.well-known/mcp.json') return reply(200, directory);+ if (u.pathname === '/api/mcp-studio/install') {+ if (install === 'missing') return reply(404, { error: 'not_found', message: 'No API route matches /api/mcp-studio/install.' });+ const token = 'tws_tmm834_3cd31c19c4ac43d0e72e539055edb441f0b7a6eb10676d4479c2314dd207f2fe';+ return reply(201, {+ token,+ created_at: '2026-10-09T00:59:19.000Z',+ connector_url: `${u.origin}/api/mcp-studio?install=${token}`,+ connector_urls: { studio: `${u.origin}/api/mcp-studio?install=${token}`, grok: `${u.origin}/api/mcp-grok?install=${token}`, chatgpt: `${u.origin}/api/mcp-chatgpt?install=${token}` },+ limits: { generations_per_minute: 3, generations_per_hour: 20, requests_per_minute: 120 },+ });+ }+ if (u.pathname === '/api/cli/whoami') {+ if (auth === `Bearer ${KEY}`) return reply(200, { user: { id: 'u1', email: '[email protected]' }, credential: { source: 'apikey', scope: 'profile avatars:read avatars:write agents:read memory:read memory:write wallet:read' } });+ if (auth === `Bearer ${CONNECTOR}`) return reply(200, { user: { id: 'u1' }, credential: { source: 'apikey', scope: whoamiScope } });+ return reply(401, { error: 'invalid_token' });+ }+ if (u.pathname === '/api/api-keys' && init.method === 'POST') {+ if (keyMint === 'old') return reply(400, { error: 'validation_error', error_description: 'unknown scopes: connector' });+ return reply(201, { data: { id: 'k-conn', name: 'Grok Bot', prefix: CONNECTOR.slice(0, 12), scope: 'avatars:read avatars:write agents:read memory:read memory:write connector', token: CONNECTOR } });+ }+ if (/^\/api\/mcp/.test(u.pathname)) {+ const body = JSON.parse(init.body);+ if (u.searchParams.get('auth') === 'oauth' && !auth) {+ return reply(401, { error: 'unauthorized' }, { 'www-authenticate': `Bearer resource_metadata="${u.origin}/.well-known/oauth-protected-resource${u.pathname}", resource="${u.origin}${u.pathname}"` });+ }+ if (body.method === 'initialize') return reply(200, { jsonrpc: '2.0', id: body.id, result: { protocolVersion: '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'three-ws-3d-studio-free', version: '1.0.0' } } }, { 'mcp-session-id': 'grk_fixture' });+ if (body.method === 'notifications/initialized') return new Response(null, { status: 202 });+ if (body.method === 'tools/list') return reply(200, { jsonrpc: '2.0', id: body.id, result: { tools: toolList(auth ? keyTools : anonTools) } });+ }+ if (u.pathname.startsWith('/.well-known/oauth-protected-resource')) return reply(200, { resource: `${u.origin}/api/mcp-grok`, authorization_servers: [u.origin] });+ return reply(404, { error: 'not_found' });+ });+}++async function run(argv, env) {+ let out = '';+ const write = vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {+ out += String(chunk);+ return true;+ });+ const err = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);+ try {+ const code = await main(argv, env);+ return { code, out, json: argv.includes('--json') && out ? JSON.parse(out) : null };+ } finally {+ write.mockRestore();+ err.mockRestore();+ }+}++const grok = getClient('grok-bot');+const servers = (directory) => hostedServers(directory, ORIGIN);++describe('the grok-bot client', () => {+ it('is a remote client: never detected, nothing to write', () => {+ expect(isRemote(grok)).toBe(true);+ expect(REMOTE_CLIENTS.map((c) => c.id)).toContain('grok-bot');+ expect(grok.configPath).toBeUndefined();+ });++ it('recommends the server the directory names for it', () => {+ expect(recommendedServer(grok, DIRECTORY, servers(DIRECTORY)).path).toBe('/api/mcp-grok');+ });++ it('falls back to the free studio on a deployment with no Grok surface', () => {+ expect(recommendedServer(grok, OLD_DIRECTORY, servers(OLD_DIRECTORY)).path).toBe('/api/mcp-studio');+ });++ it('offers every mode on the Grok surface and only keyed modes on an account server', () => {+ const all = servers(DIRECTORY);+ const grokServer = all.find((s) => s.path === '/api/mcp-grok');+ expect(grokServer.keyless).toBe(true);+ expect(modesFor(grokServer)).toEqual(['none', 'install', 'key', 'oauth']);+ expect(modesFor(all.find((s) => s.path === '/api/mcp-studio'))).toEqual(['none', 'install']);+ expect(modesFor(all.find((s) => s.path === '/api/mcp'))).toEqual(['key', 'oauth']);+ expect(defaultMode(grok, DIRECTORY, grokServer)).toBe('none');+ expect(defaultMode(grok, DIRECTORY, all.find((s) => s.path === '/api/mcp'))).toBe('key');+ });++ it('parses --auth with the directory spelling too', () => {+ expect(parseMode('api-key')).toBe('key');+ expect(parseMode('OAuth')).toBe('oauth');+ expect(() => parseMode('x402')).toThrow(/none, install, key, oauth/);+ });++ it('asks for sign-in with ?auth=oauth only where anonymous callers are otherwise served', () => {+ const all = servers(DIRECTORY);+ expect(connectorUrl(all.find((s) => s.path === '/api/mcp-grok'), 'oauth')).toBe(`${ORIGIN}/api/mcp-grok?auth=oauth`);+ expect(connectorUrl(all.find((s) => s.path === '/api/mcp'), 'oauth')).toBe(`${ORIGIN}/api/mcp`);+ });++ it('prints the key fields Grok Bot asks for', () => {+ const server = servers(DIRECTORY).find((s) => s.path === '/api/mcp-grok');+ expect(connectorFields({ client: grok, server, mode: 'key', url: server.url, key: CONNECTOR })).toEqual([+ ['Name', 'three-ws-grok'],+ ['Transport', 'Streamable HTTP'],+ ['Server URL', `${ORIGIN}/api/mcp-grok`],+ ['Authentication', 'API key'],+ ['Header', 'Authorization'],+ ['Value', `Bearer ${CONNECTOR}`],+ ]);+ });++ it('treats only a public https host as reachable from a cloud agent', () => {+ expect(isPublicUrl('https://three.ws/api/mcp-grok')).toBe(true);+ for (const u of ['http://three.ws/api/mcp', 'https://localhost:3000/api/mcp', 'https://127.0.0.1/api/mcp', 'https://192.168.1.4/api/mcp', 'https://box.local/api/mcp', 'https://[::1]/api/mcp']) {+ expect(isPublicUrl(u), u).toBe(false);+ }+ });++ it('refuses to hand a key that can spend to an unattended connector', () => {+ expect(connectorKeyProblem('avatars:read wallet:write')).toMatch(/wallet:write/);+ expect(connectorKeyProblem('avatars:read agents:read connector')).toBeNull();+ });+});++describe('clipboard', () => {+ it('uses the OS tool and reports which one took the text', () => {+ const run = vi.fn(() => ({ status: 0 }));+ expect(copyToClipboard('https://three.ws/api/mcp-grok', { platform: 'darwin', env: {}, run })).toBe('pbcopy');+ expect(run.mock.calls[0][2].input).toBe('https://three.ws/api/mcp-grok');+ });++ it('tries the next Linux tool when one is missing, and gives up quietly with no display', () => {+ const run = vi.fn((cmd) => (cmd === 'xclip' ? { error: new Error('ENOENT') } : { status: 0 }));+ expect(copyToClipboard('x', { platform: 'linux', env: { DISPLAY: ':0' }, run })).toBe('xsel');+ expect(clipboardCommands({ platform: 'linux', env: {} })).toEqual([]);+ expect(copyToClipboard('x', { platform: 'linux', env: {}, run })).toBeNull();+ });+});++describe('three-ws setup --client grok-bot', () => {+ let env;+ afterEach(() => vi.unstubAllGlobals());+ beforeEach(() => {+ env = tempEnv();+ });++ it('prints the free connector and passes the live check without signing in', async () => {+ const fetchMock = platformFetch();+ vi.stubGlobal('fetch', fetchMock);+ const { code, json } = await run(['setup', '--client', 'grok-bot', '--json', '--origin', ORIGIN], env);+ expect(code).toBe(0);+ const [r] = json.remote;+ expect(r).toMatchObject({ id: 'grok-bot', server: 'three-ws-grok', auth: 'none', url: `${ORIGIN}/api/mcp-grok`, ok: true, error: null });+ expect(r.fields).toEqual({ Name: 'three-ws-grok', Transport: 'Streamable HTTP', 'Server URL': `${ORIGIN}/api/mcp-grok`, Authentication: 'None' });+ expect(r.say).toBe(`Add a custom MCP server called three-ws-grok at ${ORIGIN}/api/mcp-grok`);+ expect(r.checks.map((c) => [c.id, c.ok])).toEqual([['public', true], ['tools', true]]);+ expect(r.checks[1].detail).toBe('15 tools from three-ws-3d-studio-free 1.0.0');+ expect(fetchMock.mock.calls.some(([u]) => String(u).includes('/api/cli/whoami'))).toBe(false);+ });++ it('connects the free studio on a deployment that predates the Grok surface', async () => {+ vi.stubGlobal('fetch', platformFetch({ directory: OLD_DIRECTORY, anonTools: 14 }));+ const { code, json } = await run(['setup', '--client', 'grok-bot', '--json', '--origin', ORIGIN], env);+ expect(code).toBe(0);+ expect(json.remote[0]).toMatchObject({ server: 'three-ws-studio', url: `${ORIGIN}/api/mcp-studio`, ok: true });+ });++ it('mints an install token once and reuses it on the next run', async () => {+ const fetchMock = platformFetch();+ vi.stubGlobal('fetch', fetchMock);+ const first = await run(['setup', '--client', 'grok-bot', '--auth', 'install', '--json', '--origin', ORIGIN], env);+ expect(first.code).toBe(0);+ expect(first.json.remote[0].url).toMatch(/^https:\/\/three\.ws\/api\/mcp-grok\?install=tws_/);+ expect(first.json.remote[0].fields.Authentication).toBe('None');+ const second = await run(['setup', '--client', 'grok-bot', '--auth', 'install', '--json', '--origin', ORIGIN], env);+ expect(second.json.remote[0].url).toBe(first.json.remote[0].url);+ expect(fetchMock.mock.calls.filter(([u]) => String(u).endsWith('/api/mcp-studio/install'))).toHaveLength(1);+ });++ it('says plainly when the deployment cannot mint install tokens', async () => {+ vi.stubGlobal('fetch', platformFetch({ install: 'missing' }));+ const { code, json } = await run(['setup', '--client', 'grok-bot', '--auth', 'install', '--json', '--origin', ORIGIN], env);+ expect(code).toBe(1);+ expect(json.remote[0].error).toMatch(/cannot mint install tokens yet/);+ });++ it('mints a connector key for the signed-in account and checks it signed in', async () => {+ writeStore({ origin: ORIGIN, auth: { type: 'apikey', key: KEY, prefix: KEY.slice(0, 12) } }, env);+ const fetchMock = platformFetch();+ vi.stubGlobal('fetch', fetchMock);+ const { code, json } = await run(['setup', '--client', 'grok-bot', '--auth', 'key', '--json', '--origin', ORIGIN], env);+ expect(code).toBe(0);+ const [r] = json.remote;+ expect(r.fields).toMatchObject({ Authentication: 'API key', Header: 'Authorization', Value: `Bearer ${CONNECTOR}` });+ expect(r.say).toBeNull();+ expect(r.key).toMatchObject({ connector: true, reused: false });+ expect(r.checks[1].detail).toMatch(/^26 tools/);+ const mint = fetchMock.mock.calls.find(([u, i]) => String(u).endsWith('/api/api-keys') && i.method === 'POST');+ expect(mint[1].headers.authorization).toBe(`Bearer ${KEY}`);+ expect(JSON.parse(mint[1].body)).toMatchObject({ preset: 'connector' });+ expect(readStore(env).connector_keys[ORIGIN]).toMatchObject({ key: CONNECTOR, key_id: 'k-conn' });+ });++ it('never mints a wider key on a deployment without the connector preset', async () => {+ writeStore({ origin: ORIGIN, auth: { type: 'apikey', key: KEY, prefix: KEY.slice(0, 12) } }, env);+ vi.stubGlobal('fetch', platformFetch({ keyMint: 'old' }));+ const { code, json } = await run(['setup', '--client', 'grok-bot', '--auth', 'key', '--json', '--origin', ORIGIN], env);+ expect(code).toBe(1);+ expect(json.remote[0].error).toMatch(/cannot mint connector keys from the CLI yet.*--connector-key/);+ expect(readStore(env).connector_keys).toBeUndefined();+ });++ it('takes a key passed with --connector-key and refuses one that can spend', async () => {+ vi.stubGlobal('fetch', platformFetch());+ const ok = await run(['setup', '--client', 'grok-bot', '--connector-key', CONNECTOR, '--json', '--origin', ORIGIN], env);+ expect(ok.code).toBe(0);+ expect(ok.json.remote[0]).toMatchObject({ auth: 'key', key: { connector: true, reused: true } });++ vi.stubGlobal('fetch', platformFetch({ whoamiScope: 'avatars:read wallet:write' }));+ const refused = await run(['setup', '--client', 'grok-bot', '--connector-key', CONNECTOR, '--json', '--origin', ORIGIN], env);+ expect(refused.code).toBe(1);+ expect(refused.json.remote[0].error).toMatch(/wallet:write, which moves funds/);+ });++ it('checks OAuth from outside: a 401 challenge and a published authorization server', async () => {+ vi.stubGlobal('fetch', platformFetch());+ const { code, json } = await run(['setup', '--client', 'grok-bot', '--auth', 'oauth', '--json', '--origin', ORIGIN], env);+ expect(code).toBe(0);+ const [r] = json.remote;+ expect(r.url).toBe(`${ORIGIN}/api/mcp-grok?auth=oauth`);+ expect(r.fields).toMatchObject({ Authentication: 'OAuth 2.1', 'Client ID': 'leave empty: the connector registers itself' });+ expect(r.checks.map((c) => [c.id, c.ok])).toEqual([['public', true], ['oauth-challenge', true], ['oauth-metadata', true]]);+ });++ it('fails the live check for a URL a cloud agent cannot reach', async () => {+ vi.stubGlobal('fetch', platformFetch());+ const { code, json } = await run(['setup', '--client', 'grok-bot', '--json', '--origin', 'http://localhost:3107'], env);+ expect(code).toBe(1);+ expect(json.remote[0].checks[0]).toMatchObject({ id: 'public', ok: false });+ expect(json.remote[0].checks[1]).toMatchObject({ id: 'tools', ok: true });+ });++ it('refuses a mode the server does not take', async () => {+ vi.stubGlobal('fetch', platformFetch());+ const { code, json } = await run(['setup', '--client', 'grok-bot', '--servers', 'three-ws-studio', '--auth', 'oauth', '--json', '--origin', ORIGIN], env);+ expect(code).toBe(1);+ expect(json.remote[0].error).toBe('three-ws-studio does not take --auth oauth; it supports none, install');+ });++ it('prints the fields and the live check for a person', async () => {+ vi.stubGlobal('fetch', platformFetch());+ const { code, out } = await run(['setup', '--client', 'grok-bot', '--yes', '--origin', ORIGIN], env);+ expect(code).toBe(0);+ expect(out).toContain('three-ws-grok');+ expect(out).toContain(`${ORIGIN}/api/mcp-grok`);+ expect(out).toContain('Streamable HTTP');+ expect(out).toContain('15 tools');+ expect(out).toContain(`${ORIGIN}/docs/grok-bot`);+ });+});++describe('three-ws mcp add --clients grok-bot', () => {+ it('points at setup, since there is no file to edit', async () => {+ vi.stubGlobal('fetch', platformFetch());+ const { code, json } = await run(['mcp', 'add', 'three-ws-grok', '--clients', 'grok-bot', '--json', '--origin', ORIGIN], tempEnv());+ vi.unstubAllGlobals();+ expect(code).toBe(1);+ expect(json.message).toMatch(/setup --client grok-bot/);+ });+});diff --git a/public/.well-known/mcp.json b/public/.well-known/mcp.jsonindex ca3729c97..2e8c9d973 100644--- a/public/.well-known/mcp.json+++ b/public/.well-known/mcp.json@@ -6,7 +6,7 @@"documentation": "https://three.ws/docs/mcp","setup": {"command": "npx three-ws setup",- "description": "One command signs you in (OAuth or API key), writes these servers into Claude Code, Claude Desktop, Cursor, Windsurf, VS Code, Codex, Gemini CLI or Hermes, and verifies each with a live tools/list.",+ "description": "One command signs you in (OAuth or API key), writes these servers into Claude Code, Claude Desktop, Cursor, Windsurf, VS Code, Codex, Gemini CLI or Hermes, prints a ready Grok Bot connector (npx three-ws setup --client grok-bot), and verifies each with a live tools/list.","documentation": "https://three.ws/docs/cli"},"registry": "https://registry.modelcontextprotocol.io/?q=io.github.nirholas",