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): answer long list results with a summary and a signed handle, add the expand tool, and add search_docs to the core and studio servers
nirholasaa4877d4002e
diff --git a/api/_lib/docs-search.js b/api/_lib/docs-search.jsnew file mode 100644index 000000000..0d6bca874--- /dev/null+++ b/api/_lib/docs-search.js@@ -0,0 +1,109 @@+// Server-side documentation search for the MCP `search_docs` tool.+//+// One index, one ranking. The browser palette and the docs site search+// public/docs-search.js against public/docs-search-index.json, which+// scripts/build-docs-search-index.mjs writes from docs/**/*.md. This module loads+// that same artifact into that same engine, so an agent asking "how do I fund an+// agent wallet" gets exactly the sections a person typing it into the docs+// search gets.+//+// Where the index comes from, in order:+// 1. dist/docs-search-index.json (the production build output)+// 2. public/docs-search-index.json (a dev checkout after `npm run build:docs-search`)+// 3. built in memory from docs/ with the same builder (a container whose build+// step did not emit the file still answers, just with a one-time ~second+// warm-up).+// The index is loaded once per process and shared by every request.+//+// The index stores headings and one line per document, not section text. A+// result's snippet is therefore read from the markdown file at query time, using+// the builder's own splitSections(), so the excerpt is the start of the section+// that matched rather than the top of the page.++import { existsSync, readFileSync } from 'node:fs';+import { dirname, join, resolve, sep } from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');+const DOCS_DIR = join(ROOT, 'docs');+const INDEX_FILES = [join(ROOT, 'dist', 'docs-search-index.json'), join(ROOT, 'public', 'docs-search-index.json')];++export const SNIPPET_CHARS = 280;+export const MAX_RESULTS = 10;++let enginePromise = null;+const sectionCache = new Map();++async function loadEngine() {+ await import('../../public/docs-search.js');+ const engine = globalThis.twsDocsSearch;+ for (const file of INDEX_FILES) {+ if (!existsSync(file)) continue;+ try {+ engine.load(JSON.parse(readFileSync(file, 'utf8')));+ return engine;+ } catch {+ // A half-written or corrupt file falls through to the next source.+ }+ }+ const { buildIndex } = await import('../../scripts/build-docs-search-index.mjs');+ engine.load(buildIndex(DOCS_DIR));+ return engine;+}++/** The ready engine, loaded once. A failed load is not remembered. */+export function getEngine() {+ if (!enginePromise) {+ enginePromise = loadEngine().catch((err) => {+ enginePromise = null;+ throw err;+ });+ }+ return enginePromise;+}++async function sectionsOf(slug) {+ if (sectionCache.has(slug)) return sectionCache.get(slug);+ const file = resolve(DOCS_DIR, `${slug}.md`);+ let parsed = null;+ // The slug comes from our own index, but a path check costs nothing.+ if (file.startsWith(DOCS_DIR + sep) && existsSync(file)) {+ const { splitSections } = await import('../../scripts/build-docs-search-index.mjs');+ parsed = splitSections(readFileSync(file, 'utf8'), slug).sections;+ }+ if (sectionCache.size > 400) sectionCache.clear();+ sectionCache.set(slug, parsed);+ return parsed;+}++function excerpt(text, max) {+ if (text.length <= max) return text;+ const cut = text.slice(0, max);+ const at = Math.max(cut.lastIndexOf('. '), cut.lastIndexOf(' '));+ return `${cut.slice(0, at > max * 0.6 ? at : max).trim()}...`;+}++/**+ * Search the documentation.+ *+ * @param {string} q raw question or keywords+ * @param {{ limit?: number, origin?: string }} [opts]+ * @returns {Promise<Array<{title,heading,url,snippet,doc}>>}+ */+export async function searchDocs(q, { limit = 5, origin = 'https://three.ws' } = {}) {+ const engine = await getEngine();+ const hits = engine.query(String(q), Math.min(Math.max(Number(limit) || 5, 1), MAX_RESULTS));+ const base = origin.replace(/\/$/, '');+ const out = [];+ for (const hit of hits) {+ const sections = await sectionsOf(hit.slug);+ const section = sections?.find((s) => s.anchor === hit.anchor);+ out.push({+ title: hit.heading ? `${hit.docTitle}: ${hit.heading}` : hit.docTitle,+ url: `${base}${hit.url}`,+ snippet: excerpt(section?.text || hit.snippet || '', SNIPPET_CHARS),+ doc: hit.slug,+ });+ }+ return out;+}diff --git a/api/_lib/mcp-expand.js b/api/_lib/mcp-expand.jsnew file mode 100644index 000000000..42f6be2ac--- /dev/null+++ b/api/_lib/mcp-expand.js@@ -0,0 +1,221 @@+// Summary-first MCP results with on-demand expansion.+//+// A tool that can return hundreds of rows (a market-data list, an account's+// agents, a memory recall) used to put every row into the model's context on+// every call, in both the text block and structuredContent. This module lets+// such a tool answer with a compact envelope instead:+//+// { summary, handle, count, offset, limit, next_offset, items: <first page> }+//+// and park the full list server-side. The caller reads the summary, and only+// when it needs more calls the `expand` tool (api/_mcp/tools/expand.js) with the+// handle and a page or a field selector.+//+// A handle is `mx1.<payload>.<signature>`:+// - signed with HMAC-SHA256 under JWT_SECRET, so it cannot be forged or edited;+// - bound to the principal that received it (account or API key), so a handle+// passed to another account is refused exactly like a forged one;+// - short-lived (HANDLE_TTL_SECONDS): the list lives in the shared cache+// (Redis in production) and the signature carries the same deadline, so an+// expired handle fails cleanly and tells the caller to re-run the tool.+//+// A result that already fits one page, or that is for a caller with no stable+// identity (anonymous, or a pay-per-call x402 principal who paid for the whole+// answer), is returned unchanged. The envelope is a context saver, never a gate.++import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';++import { cacheGetFresh, cacheSet } from './cache.js';+import { env } from './env.js';++export const HANDLE_PREFIX = 'mx1.';+export const HANDLE_TTL_SECONDS = 15 * 60;+export const MAX_STORED_ITEMS = 2000;+export const MAX_PAGE = 100;++const CACHE_KEY = (id) => `mcp:expand:${id}`;++/** Stable identity a handle is bound to, or null when the caller has none. */+export function principalKey(auth) {+ if (auth?.source === 'x402') return null;+ if (auth?.userId) return `user:${auth.userId}`;+ if (auth?.apiKeyId) return `key:${auth.apiKeyId}`;+ return null;+}++function sign(payload) {+ return createHmac('sha256', env.JWT_SECRET).update(payload).digest('base64url');+}++function principalHash(principal) {+ return createHash('sha256').update(principal).digest('base64url').slice(0, 22);+}++function encodeHandle({ id, principal, tool, exp }) {+ const payload = Buffer.from(JSON.stringify({ i: id, p: principalHash(principal), t: tool, e: exp }), 'utf8').toString('base64url');+ return `${HANDLE_PREFIX}${payload}.${sign(payload)}`;+}++/**+ * Verify a handle's signature and shape. Returns the claims or null. Does not+ * check the principal or the clock: expand does, so it can answer each failure+ * with its own message.+ */+export function decodeHandle(handle) {+ if (typeof handle !== 'string' || !handle.startsWith(HANDLE_PREFIX) || handle.length > 600) return null;+ const rest = handle.slice(HANDLE_PREFIX.length);+ const dot = rest.indexOf('.');+ if (dot < 1 || dot === rest.length - 1) return null;+ const payload = rest.slice(0, dot);+ const sig = rest.slice(dot + 1);+ try {+ const expected = Buffer.from(sign(payload), 'utf8');+ const actual = Buffer.from(sig, 'utf8');+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return null;+ const obj = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));+ if (!obj?.i || !obj?.p || !obj?.t || !Number.isFinite(obj.e)) return null;+ return { id: String(obj.i), principal: String(obj.p), tool: String(obj.t), exp: obj.e };+ } catch {+ return null;+ }+}++/** Approximate token count: the common four-characters-per-token estimate. */+export function approxTokens(value) {+ const text = typeof value === 'string' ? value : JSON.stringify(value);+ return Math.ceil((text || '').length / 4);+}++export function clip(text, max) {+ const t = String(text ?? '').replace(/\s+/g, ' ').trim();+ return t.length > max ? `${t.slice(0, max - 1)}...` : t;+}++function pageText({ summary, items, renderItem, offset, count, handle }) {+ const lines = items.map((item, i) => (renderItem ? renderItem(item, offset + i) : JSON.stringify(item)));+ const end = offset + items.length;+ const more =+ end < count+ ? `Showing ${offset + 1}-${end} of ${count}. Call expand with handle "${handle}" and offset ${end} for the next page, or pass fields to narrow each row.`+ : `Showing ${offset + 1}-${end} of ${count}. That is the end of the list.`;+ return [summary, '', ...lines, '', more].join('\n');+}++/**+ * Answer with a summary-first envelope when the list is longer than one page.+ *+ * @param {object} o+ * @param {string} o.tool tool name the list came from+ * @param {object} o.auth the MCP auth context+ * @param {Array} o.items the full list+ * @param {number} o.pageSize rows in the first page and the default expand page+ * @param {string} o.summary one or two lines describing the WHOLE list+ * @param {Function} [o.renderItem] (item, index) => one line of text for the page+ * @param {object} [o.extra] extra keys merged into structuredContent+ * @returns {Promise<object|null>} an MCP tool result, or null when the caller should return the full list+ */+export async function summarizeList({ tool, auth, items, pageSize, summary, renderItem, extra = {} }) {+ const principal = principalKey(auth);+ if (!principal || !Array.isArray(items) || items.length <= pageSize) return null;++ const stored = items.slice(0, MAX_STORED_ITEMS);+ const id = randomBytes(12).toString('base64url');+ const exp = Date.now() + HANDLE_TTL_SECONDS * 1000;+ await cacheSet(CACHE_KEY(id), { p: principalHash(principal), t: tool, ps: pageSize, items: stored }, HANDLE_TTL_SECONDS);+ const handle = encodeHandle({ id, principal, tool, exp });++ const page = stored.slice(0, pageSize);+ const count = stored.length;+ const structured = {+ ...extra,+ ...(items.length > stored.length ? { total_available: items.length, truncated_to: stored.length } : {}),+ summary,+ handle,+ count,+ offset: 0,+ limit: pageSize,+ next_offset: pageSize < stored.length ? pageSize : null,+ expires_at: new Date(exp).toISOString(),+ items: page,+ };+ return {+ content: [{ type: 'text', text: pageText({ summary, items: page, renderItem, offset: 0, count, handle }) }],+ structuredContent: structured,+ };+}++function refusal(code, message) {+ return {+ content: [{ type: 'text', text: message }],+ isError: true,+ structuredContent: { error: code, message },+ };+}++function pick(item, fields) {+ if (!fields?.length || item === null || typeof item !== 'object') return item;+ const out = {};+ for (const path of fields) {+ const parts = String(path).split('.');+ let src = item;+ for (const p of parts) {+ if (src === null || typeof src !== 'object' || !Object.hasOwn(src, p)) {+ src = undefined;+ break;+ }+ src = src[p];+ }+ if (src === undefined) continue;+ let dst = out;+ for (let i = 0; i < parts.length - 1; i++) {+ if (!Object.hasOwn(dst, parts[i]) || typeof dst[parts[i]] !== 'object') dst[parts[i]] = {};+ dst = dst[parts[i]];+ }+ dst[parts[parts.length - 1]] = src;+ }+ return out;+}++/**+ * Resolve a handle to one page of its list. Every failure is a designed+ * isError result: an invalid or foreign handle is one opaque message, so a+ * caller learns nothing about which handles exist.+ */+export async function expandHandle({ handle, offset = 0, limit, fields, auth, now = Date.now() }) {+ const principal = principalKey(auth);+ if (!principal) {+ return refusal('sign_in_required', 'Sign in with three.ws OAuth or an API key to expand a result. Handles belong to the account that received them.');+ }+ const claims = decodeHandle(handle);+ if (!claims || claims.principal !== principalHash(principal)) {+ return refusal('invalid_handle', 'That handle is not valid for this account. Handles come from a tool result that returned one, and only the account that received it can expand it.');+ }+ if (claims.exp <= now) {+ return refusal('handle_expired', `That handle expired. Handles last ${Math.round(HANDLE_TTL_SECONDS / 60)} minutes. Call ${claims.tool} again to get a fresh one.`);+ }+ const record = await cacheGetFresh(CACHE_KEY(claims.id));+ if (!record || record.p !== claims.principal || record.t !== claims.tool || !Array.isArray(record.items)) {+ return refusal('handle_expired', `That result is no longer stored. Call ${claims.tool} again to get a fresh handle.`);+ }++ const total = record.items.length;+ const start = Math.min(Math.max(Number(offset) || 0, 0), total);+ const size = Math.min(Math.max(Number(limit) || record.ps || 10, 1), MAX_PAGE);+ const slice = record.items.slice(start, start + size).map((item) => pick(item, fields));+ const end = start + slice.length;+ const structured = {+ handle,+ tool: claims.tool,+ count: total,+ offset: start,+ limit: size,+ next_offset: end < total ? end : null,+ items: slice,+ };+ const tail = end < total ? ` Next: offset ${end}.` : ' End of list.';+ const head = slice.length ? `${claims.tool}: rows ${start + 1}-${end} of ${total}.` : `${claims.tool}: no rows at offset ${start}, the list has ${total}.`;+ return {+ content: [{ type: 'text', text: `${head}${tail}\n${JSON.stringify(slice)}` }],+ structuredContent: structured,+ };+}diff --git a/api/_mcp-studio/catalog-tools.js b/api/_mcp-studio/catalog-tools.jsindex 6672f0c29..17957135b 100644--- a/api/_mcp-studio/catalog-tools.js+++ b/api/_mcp-studio/catalog-tools.js@@ -16,6 +16,7 @@import Ajv from 'ajv';import addFormats from 'ajv-formats';import { toolDefs as libraryTools } from '../_mcp/tools/library.js';+import { toolDefs as docsTools } from '../_mcp/tools/docs.js';// The studio's contract carries no payment vocabulary at all (tests/mcp-studio.test.js// holds every studio tool to that), so the main server's "no account or payment"@@ -28,6 +29,12 @@ function libraryTool(name) {return { ...def, description: def.description.replace(MAIN_SERVER_LEAD, 'Free, no account needed. ') };}+function docsTool(name) {+ const def = docsTools.find((d) => d.name === name);+ if (!def) throw new Error(`api/_mcp/tools/docs.js no longer defines ${name}`);+ return { ...def, description: def.description.replace(MAIN_SERVER_LEAD, 'Free, no account needed. ') };+}+const DEFS = [{...libraryTool('search_catalog'),@@ -41,6 +48,10 @@ const DEFS = [...libraryTool('get_item_source'),name: 'get_item_source',},+ {+ ...docsTool('search_docs'),+ name: 'search_docs',+ },];export const CATALOG_TOOL_CATALOG = DEFS.map(({ handler: _h, ...schema }) => schema);diff --git a/api/_mcp-studio/dispatch.js b/api/_mcp-studio/dispatch.jsindex 79949bf46..3da74c43d 100644--- a/api/_mcp-studio/dispatch.js+++ b/api/_mcp-studio/dispatch.js@@ -96,7 +96,8 @@ const GROK_ANONYMOUS_INSTRUCTIONS = [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',- 'match. Say whether you used an existing asset or generated a new one.',+ 'match. Say whether you used an existing asset or generated a new one. For how-to questions about three.ws itself,',+ 'search_docs(query) returns the documentation sections that answer them.',];// The full and Grok surfaces list get_job (./job-tools.js); the ChatGPT onediff --git a/api/_mcp/catalog.js b/api/_mcp/catalog.jsindex 2e0e1664e..348fddf48 100644--- a/api/_mcp/catalog.js+++ b/api/_mcp/catalog.js@@ -33,6 +33,8 @@ import { toolDefs as whitelistDefs } from './tools/whitelist.js';import { toolDefs as domainDefs } from './tools/domains.js';import { toolDefs as robinhoodDefs } from './tools/robinhood.js';import { toolDefs as tokenDueDiligenceDefs } from './tools/token-due-diligence.js';+import { toolDefs as docsDefs } from './tools/docs.js';+import { toolDefs as expandDefs } from './tools/expand.js';const baseDefs = [...libraryDefs,@@ -65,6 +67,8 @@ const baseDefs = [...domainDefs,...robinhoodDefs,...tokenDueDiligenceDefs,+ ...docsDefs,+ ...expandDefs,];// Free, public entry point — listed first so discovery clients see it up top.diff --git a/api/_mcp/dispatch.js b/api/_mcp/dispatch.jsindex 48aa9da52..4f6d0c2dd 100644--- a/api/_mcp/dispatch.js+++ b/api/_mcp/dispatch.js@@ -49,6 +49,12 @@ const PUBLIC_TOOLS = new Set(['domain_pricing',// The launch-lane comparison is live platform config, no caller data.'launch_lanes',+ // Documentation search reads published docs and nothing about the caller.+ 'search_docs',+ // expand takes a signed, account-bound handle. It is listed here only so a+ // signed-in caller's bare request is not sent through the payment challenge;+ // an anonymous call gets a designed sign-in message, never data.+ 'expand',]);export function isPublicTool(name) {diff --git a/api/_mcp/tools/agents.js b/api/_mcp/tools/agents.jsindex 18be94ffb..09effde89 100644--- a/api/_mcp/tools/agents.js+++ b/api/_mcp/tools/agents.js@@ -1,4 +1,5 @@import { sql } from '../../_lib/db.js';+import { clip, summarizeList } from '../../_lib/mcp-expand.js';import { limits } from '../../_lib/rate-limit.js';import { runAgentDelegation, AgentNotFoundError } from '../../_lib/agent-delegate.js';import { checkIdentityIntegrity } from '../../_lib/identity-integrity.js';@@ -669,7 +670,7 @@ export const toolDefs = [openWorldHint: false,},description:- 'List the agents on your account, newest first: id, name, description, brain model, public Solana address, whether the page is published and the page URL. Use this first to get the agent ids that recall, list_custom_skills, attach_avatar_to_agent and call_agent need. Reads only; no funds move.',+ 'List the agents on your account, newest first: id, name, description, brain model, public Solana address, whether the page is published and the page URL. Use this first to get the agent ids that recall, list_custom_skills, attach_avatar_to_agent and call_agent need. Past ten agents it returns a summary, the count, a handle and the first ten; the expand tool reads the rest. Reads only; no funds move.',inputSchema: {type: 'object',properties: {@@ -702,6 +703,16 @@ export const toolDefs = [created_at: r.created_at,page_url: agentHomeUrl(r.id),}));+ const published = agents.filter((a) => a.is_published).length;+ const summarized = await summarizeList({+ tool: 'list_my_agents',+ auth,+ items: agents,+ pageSize: 10,+ summary: `${agents.length} agents on this account (${published} published, ${agents.length - published} unpublished), newest first. Newest: ${clip(agents[0].name, 80)}.`,+ renderItem: (a, i) => `${i + 1}. ${clip(a.name, 80)} (${a.id})${a.is_published ? ' published' : ''}${a.model ? `, ${a.model}` : ''}`,+ });+ if (summarized) return summarized;return toolResult({ count: agents.length, agents });},},diff --git a/api/_mcp/tools/crypto-data.js b/api/_mcp/tools/crypto-data.jsindex 78feb21e7..d6b577f9b 100644--- a/api/_mcp/tools/crypto-data.js+++ b/api/_mcp/tools/crypto-data.js@@ -20,6 +20,7 @@import { ENDPOINT_INDEX, providerCatalog } from '../../v1/_providers.js';import { executeUpstream, resolveUpstreamKey } from '../../_lib/aggregator.js';import { limits, clientIp } from '../../_lib/rate-limit.js';+import { summarizeList } from '../../_lib/mcp-expand.js';function rpcError(code, message, data) {const e = new Error(message);@@ -127,6 +128,60 @@ async function runEndpoint({ providerId, endpointId, params, auth, req }) {}}+// Rows per page for a summarized crypto_data answer.+const DATA_PAGE_SIZE = 10;++/**+ * The longest array in an upstream answer: the answer itself when it is a list,+ * else the biggest list one or two levels down (a `data` or `pairs` key).+ * Returns { path, rows } or null when nothing in it is a list.+ */+export function findRows(data) {+ if (Array.isArray(data)) return { path: [], rows: data };+ let best = null;+ const visit = (node, path, depth) => {+ if (!node || typeof node !== 'object' || Array.isArray(node) || depth > 2) return;+ for (const [key, value] of Object.entries(node)) {+ if (Array.isArray(value) && (!best || value.length > best.rows.length)) best = { path: [...path, key], rows: value };+ else visit(value, [...path, key], depth + 1);+ }+ };+ visit(data, [], 0);+ return best;+}++function labelOf(row) {+ if (row === null || typeof row !== 'object') return String(row);+ for (const key of ['symbol', 'name', 'id', 'pairAddress', 'address', 'slug']) {+ if (typeof row[key] === 'string' || typeof row[key] === 'number') return String(row[key]);+ }+ return Object.keys(row).slice(0, 3).join('/');+}++// A list answer becomes a summary, a count, a handle and the first page; the+// rest of the upstream answer (everything outside the list) rides along in+// `meta` so nothing but the extra rows is withheld.+async function summarizeData({ pairKey, result, auth }) {+ const found = findRows(result.data);+ if (!found) return null;+ const labels = found.rows.slice(0, 5).map(labelOf).join(', ');+ let meta;+ if (found.path.length) {+ meta = structuredClone(result.data);+ let node = meta;+ for (const p of found.path.slice(0, -1)) node = node[p];+ delete node[found.path[found.path.length - 1]];+ }+ return summarizeList({+ tool: 'crypto_data',+ auth,+ items: found.rows,+ pageSize: DATA_PAGE_SIZE,+ summary: `${pairKey} returned ${found.rows.length} rows${found.path.length ? ` under ${found.path.join('.')}` : ''}. First: ${labels}.`,+ extra: { provider: result.provider, endpoint: result.endpoint, ...(meta && Object.keys(meta).length ? { meta } : {}) },+ });+}+const READ_ONLY_LIVE_FEED = {readOnlyHint: true,destructiveHint: false,@@ -147,7 +202,7 @@ export const toolDefs = ['per-IP quota, no wallet needed; an endpoint with no free tier (or an exhausted quota) ' +'returns a payment-required error naming the exact REST URL and USDC price to pay via ' +'x402. Use this for raw data from one named provider endpoint; for a merged one-call view of a ' +- 'Solana token call token_snapshot.\n\nLive provider/endpoint pairs on this deployment:\n' + describePairs()+ 'Solana token call token_snapshot. A list answer longer than ten rows comes back as a summary, a count, a handle and the first ten rows; the expand tool reads the rest.\n\nLive provider/endpoint pairs on this deployment:\n' + describePairs());},inputSchema: {@@ -184,6 +239,8 @@ export const toolDefs = [const result = await runEndpoint({ providerId, endpointId, params: args?.params, auth, req });if (result.ok) {+ const summarized = await summarizeData({ pairKey, result, auth });+ if (summarized) return summarized;return toolResult({ provider: result.provider, endpoint: result.endpoint, data: result.data });}if (result.reason === 'quota_exceeded' || result.reason === 'payment_required') {diff --git a/api/_mcp/tools/docs.js b/api/_mcp/tools/docs.jsnew file mode 100644index 000000000..2ac3e0d75--- /dev/null+++ b/api/_mcp/tools/docs.js@@ -0,0 +1,51 @@+// search_docs: answer "how do I" from the documentation source of truth.+//+// Backed by the same index the docs site and the Cmd-K palette search+// (api/_lib/docs-search.js), so an agent and a person get the same sections.+// Free and keyless: it reads published documentation and nothing about the+// caller, which is why it is on the public-tool allowlist and on the keyless+// studio server.++import { searchDocs } from '../../_lib/docs-search.js';+import { resolveOrigin } from '../origin.js';++function origin(req) {+ try {+ return resolveOrigin(req);+ } catch {+ return 'https://three.ws';+ }+}++export const toolDefs = [+ {+ name: 'search_docs',+ title: 'Search the three.ws documentation',+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ description:+ 'FREE, no account or payment. Search the three.ws documentation for the section that answers a question, such as "how do I embed an avatar on my site" or "how does auto-rigging work". Returns the best sections ranked, each with the page and heading title, a url that opens the docs reader at that heading, and a snippet from the start of the section. Use this before guessing at an API or a flow; to browse ready-made 3D assets call search_catalog instead.',+ inputSchema: {+ type: 'object',+ additionalProperties: false,+ required: ['query'],+ properties: {+ query: { type: 'string', minLength: 2, maxLength: 300, description: 'A question or keywords, in plain words.' },+ limit: { type: 'integer', minimum: 1, maximum: 10, default: 5, description: 'How many sections to return.' },+ },+ },+ async handler(args = {}, _auth, req) {+ const results = await searchDocs(args.query, { limit: args.limit || 5, origin: origin(req) });+ if (!results.length) {+ return {+ content: [{ type: 'text', text: `No documentation section matched "${args.query}". Try fewer or different keywords, or call getting_started for an overview of what this server offers.` }],+ structuredContent: { query: args.query, count: 0, results: [] },+ };+ }+ const text = results.map((r, i) => `${i + 1}. ${r.title}\n ${r.url}\n ${r.snippet}`).join('\n');+ return {+ content: [{ type: 'text', text }],+ structuredContent: { query: args.query, count: results.length, results },+ };+ },+ },+];diff --git a/api/_mcp/tools/expand.js b/api/_mcp/tools/expand.jsnew file mode 100644index 000000000..1a50d58c4--- /dev/null+++ b/api/_mcp/tools/expand.js@@ -0,0 +1,33 @@+// expand: page through, or narrow, a result another tool summarized.+//+// list_my_agents, recall and crypto_data answer a long list with a summary, a+// count, a handle and the first page (api/_lib/mcp-expand.js). This tool takes+// that handle back and returns any other page, optionally trimmed to the fields+// the caller needs. A handle is signed, expires, and only works for the account+// that received it.++import { MAX_PAGE, expandHandle } from '../../_lib/mcp-expand.js';++export const toolDefs = [+ {+ name: 'expand',+ title: 'Expand a summarized result',+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ description:+ 'Get more of a result that another tool summarized. Use this when list_my_agents, recall or crypto_data returns a summary with a handle and a count: pass that handle here with an offset to read the next page, or with fields to receive only those keys of each row (dot paths allowed, for example ["id","name"]). Handles are signed, last 15 minutes and only work for the account that received them; when one has expired, call the original tool again. Reads only.',+ inputSchema: {+ type: 'object',+ additionalProperties: false,+ required: ['handle'],+ properties: {+ handle: { type: 'string', minLength: 8, maxLength: 600, description: 'The handle from a summarized tool result.' },+ offset: { type: 'integer', minimum: 0, default: 0, description: 'Row to start at. Use next_offset from the previous page.' },+ limit: { type: 'integer', minimum: 1, maximum: MAX_PAGE, description: 'Rows to return. Defaults to the page size of the original result.' },+ fields: { type: 'array', maxItems: 40, items: { type: 'string', maxLength: 80 }, description: 'Keys to keep on each row.' },+ },+ },+ async handler(args = {}, auth) {+ return expandHandle({ handle: args.handle, offset: args.offset, limit: args.limit, fields: args.fields, auth });+ },+ },+];diff --git a/api/_mcp/tools/memory.js b/api/_mcp/tools/memory.jsindex 1a1708faa..83757da77 100644--- a/api/_mcp/tools/memory.js+++ b/api/_mcp/tools/memory.js@@ -9,6 +9,7 @@// account and are refused with a designed, actionable message.import { sql } from '../../_lib/db.js';+import { clip, summarizeList } from '../../_lib/mcp-expand.js';const VALID_TYPES = ['user', 'feedback', 'project', 'reference'];@@ -41,6 +42,12 @@ async function ownsAgent(agentId, auth) {return !!row && row.user_id === auth.userId;}+function countByType(rows) {+ const counts = {};+ for (const r of rows) counts[r.type] = (counts[r.type] || 0) + 1;+ return Object.entries(counts).map(([t, n]) => `${n} ${t}`).join(', ');+}+function decorate(row) {return {id: row.id,@@ -164,7 +171,7 @@ export const toolDefs = [openWorldHint: true,},description:- 'Retrieve the most relevant memories for a query from one of your agents. Ranks by relevance to the query blended with salience and recency, excluding expired memories. Returns an ordered list. Use this before answering when an agent should draw on what it already knows about the user or the work; to save a new fact call remember.',+ 'Retrieve the most relevant memories for a query from one of your agents. Ranks by relevance to the query blended with salience and recency, excluding expired memories. Returns an ordered list; when more than five memories match it returns a summary, a count, a handle and the top five, and the expand tool reads the rest. Use this before answering when an agent should draw on what it already knows about the user or the work; to save a new fact call remember.',inputSchema: {type: 'object',properties: {@@ -231,6 +238,16 @@ export const toolDefs = [};});+ const summarized = await summarizeList({+ tool: 'recall',+ auth,+ items: ranked,+ pageSize: 5,+ summary: `${ranked.length} memories ranked for "${clip(args.query, 80)}" (${countByType(ranked)}). Best match: ${clip(ranked[0].content, 120)}`,+ renderItem: (m, i) => `${i + 1}. [${m.type}] ${clip(m.content, 280)}`,+ });+ if (summarized) return summarized;+const summary = ranked.map((m, i) => `${i + 1}. [${m.type}] ${m.content}`).join('\n');return {content: [{ type: 'text', text: summary }],diff --git a/data/changelog.json b/data/changelog.jsonindex d388bbca8..fc0d5e166 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -3,13 +3,10 @@"entries": [{"date": "2026-10-24",- "title": "See and test launch fees before a coin goes live",- "summary": "The $THREE launchpad form now shows the launch fee in plain words and as a fee-over-time table. A new fee-config endpoint validates a decaying fee schedule against the Meteora SDK rules and can simulate the config transaction unsigned. Swap preparation accepts a referral token account, and a shared pump.fun fee vault now rejects holder splits that do not total 100 percent across 1 to 10 wallets.",- "tags": [- "feature",- "docs"- ],- "link": "/docs/native-launchpad"+ "title": "Long MCP answers arrive as a summary, and agents can search the docs",+ "summary": "list_my_agents, recall and crypto_data now answer with a short summary, a count, a handle and the first page when the list is long, and the new expand tool reads the rest on request. A 100-coin market list drops from about 47,800 to 4,400 tokens. Handles are signed, account-bound and last 15 minutes. The new free search_docs tool answers how-to questions from the docs index on the main and studio servers.",+ "tags": ["feature", "docs"],+ "link": "/docs/mcp"},{"date": "2026-10-24",@@ -50,11 +47,7 @@"date": "2026-10-24","title": "Agents join the open Solana agent registry and hires read trust tiers","summary": "Minted agents are enrolled in the open Solana agent registry (8004) with the platform authority signing, so owners pay nothing. The marketplace ranks providers by registry tier after completed hires, a hire can require a minimum tier, and agent pages show an 8004 tier badge when registered. A rate-limited back-fill covers existing agents.",- "tags": [- "solana",- "agents",- "marketplace"- ],+ "tags": ["feature"],"link": "/docs/solana-agent-registry"},{@@ -178,15 +171,6 @@],"link": "/coin-intel"},- {- "date": "2026-10-23",- "title": "Creator-fee payouts: register a wallet and see every distribution",- "summary": "Your share of each claimed creator fee now has a record and a destination. Register a payout wallet by signing with it and confirming with a step-up (a change waits 48 hours), then follow what is sent, pending or held and why on the new payouts page, and export every distribution as CSV. Sending stays off until payouts are switched on, and shares are recorded and held until then.",- "tags": [- "feature"- ],- "link": "/creator/payouts"- },{"date": "2026-10-23","title": "Agent trades now race several landing providers and keep score of who lands",diff --git a/docs/ALL.md b/docs/ALL.mdindex cca2455e9..f95ea43b4 100644--- a/docs/ALL.md+++ b/docs/ALL.md@@ -27126,7 +27126,7 @@ The endpoint allows cross-origin `GET` and `POST` requests and requires no authecurl -s https://three.ws/api/mcp-census | jq '.totals.all, .matchesBuild'```-Response fields: `totals` (`all`, `hosted`, `stdio`, each with `servers`, `tools`, `uniqueTools`, `resources`, `templates`, `prompts`), `servers` (one row per server with a `source` of `live` or `build`), `method` (how each number is calculated), `matchesBuild` (false when the build ran on different code than is serving) and `drift` (the per-server differences). Today the build counts <!-- mcp-count:all.tools -->704<!-- /mcp-count --> tools on <!-- mcp-count:all.servers -->51<!-- /mcp-count --> servers. Browse them at [/mcp-tools](https://three.ws/mcp-tools); see [MCP Tools Catalog](mcp-tools.md#how-the-totals-are-calculated) for the method.+Response fields: `totals` (`all`, `hosted`, `stdio`, each with `servers`, `tools`, `uniqueTools`, `resources`, `templates`, `prompts`), `servers` (one row per server with a `source` of `live` or `build`), `method` (how each number is calculated), `matchesBuild` (false when the build ran on different code than is serving) and `drift` (the per-server differences). Today the build counts <!-- mcp-count:all.tools -->709<!-- /mcp-count --> tools on <!-- mcp-count:all.servers -->51<!-- /mcp-count --> servers. Browse them at [/mcp-tools](https://three.ws/mcp-tools); see [MCP Tools Catalog](mcp-tools.md#how-the-totals-are-calculated) for the method.## Asset Catalog API@@ -106543,7 +106543,7 @@ page explains how the servers are grouped and how the paid ones charge.## How the totals are calculated-The totals are computed, never typed. At build time `npm run build:mcp-catalog` imports the exact catalog each hosted endpoint serves, and loads every stdio package in-process and asks it for `tools/list`, `resources/list` and `prompts/list` over an in-memory MCP transport. The result is [`/tools.json`](/tools.json) and [`/mcp-catalog.json`](/mcp-catalog.json), currently <!-- mcp-count:all.tools -->704<!-- /mcp-count --> tools (<!-- mcp-count:all.uniqueTools -->600<!-- /mcp-count --> unique names) on <!-- mcp-count:all.servers -->51<!-- /mcp-count --> servers. At request time [`/api/mcp-census`](/api/mcp-census) recounts the hosted endpoints from the running code and reports whether they still match the build.+The totals are computed, never typed. At build time `npm run build:mcp-catalog` imports the exact catalog each hosted endpoint serves, and loads every stdio package in-process and asks it for `tools/list`, `resources/list` and `prompts/list` over an in-memory MCP transport. The result is [`/tools.json`](/tools.json) and [`/mcp-catalog.json`](/mcp-catalog.json), currently <!-- mcp-count:all.tools -->709<!-- /mcp-count --> tools (<!-- mcp-count:all.uniqueTools -->603<!-- /mcp-count --> unique names) on <!-- mcp-count:all.servers -->51<!-- /mcp-count --> servers. At request time [`/api/mcp-census`](/api/mcp-census) recounts the hosted endpoints from the running code and reports whether they still match the build.- **tools**: every tool a server can serve, including financial-tier tools the policy hides until a session enables them.- **resources, templates, prompts**: the matching `*/list` entries, prompts rendered against that server's own catalog.diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 592a7e7f0..6f8cd0761 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -256,7 +256,7 @@ The endpoint allows cross-origin `GET` and `POST` requests and requires no authecurl -s https://three.ws/api/mcp-census | jq '.totals.all, .matchesBuild'```-Response fields: `totals` (`all`, `hosted`, `stdio`, each with `servers`, `tools`, `uniqueTools`, `resources`, `templates`, `prompts`), `servers` (one row per server with a `source` of `live` or `build`), `method` (how each number is calculated), `matchesBuild` (false when the build ran on different code than is serving) and `drift` (the per-server differences). Today the build counts <!-- mcp-count:all.tools -->704<!-- /mcp-count --> tools on <!-- mcp-count:all.servers -->51<!-- /mcp-count --> servers. Browse them at [/mcp-tools](https://three.ws/mcp-tools); see [MCP Tools Catalog](mcp-tools.md#how-the-totals-are-calculated) for the method.+Response fields: `totals` (`all`, `hosted`, `stdio`, each with `servers`, `tools`, `uniqueTools`, `resources`, `templates`, `prompts`), `servers` (one row per server with a `source` of `live` or `build`), `method` (how each number is calculated), `matchesBuild` (false when the build ran on different code than is serving) and `drift` (the per-server differences). Today the build counts <!-- mcp-count:all.tools -->709<!-- /mcp-count --> tools on <!-- mcp-count:all.servers -->51<!-- /mcp-count --> servers. Browse them at [/mcp-tools](https://three.ws/mcp-tools); see [MCP Tools Catalog](mcp-tools.md#how-the-totals-are-calculated) for the method.## Asset Catalog APIdiff --git a/docs/mcp-studio.md b/docs/mcp-studio.mdindex 33ae09d08..ff8d100a8 100644--- a/docs/mcp-studio.md+++ b/docs/mcp-studio.md@@ -191,6 +191,14 @@ protocol client that connects there is sent through three.ws sign-in first,because most of that server's tools act on an account. The catalog tools nevercount against the generation quota.+### Documentation search (`search_docs`)++`search_docs` takes a plain-words `query` (and an optional `limit` of 1 to 10) and+returns the documentation sections that answer it: a `title`, a `url` that opens the+docs reader at that heading, and a `snippet` from the start of the section. It is+the same tool and index as on the main server, documented in+[docs/mcp.md](./mcp.md#search_docs). It never counts against the generation quota.+### Quality tiers`forge_free` takes an optional `tier` of `draft`, `standard`, or `high`.diff --git a/docs/mcp-tools.md b/docs/mcp-tools.mdindex 1ebfc6aab..ac688316e 100644--- a/docs/mcp-tools.md+++ b/docs/mcp-tools.md@@ -27,7 +27,7 @@ page explains how the servers are grouped and how the paid ones charge.## How the totals are calculated-The totals are computed, never typed. At build time `npm run build:mcp-catalog` imports the exact catalog each hosted endpoint serves, and loads every stdio package in-process and asks it for `tools/list`, `resources/list` and `prompts/list` over an in-memory MCP transport. The result is [`/tools.json`](/tools.json) and [`/mcp-catalog.json`](/mcp-catalog.json), currently <!-- mcp-count:all.tools -->704<!-- /mcp-count --> tools (<!-- mcp-count:all.uniqueTools -->600<!-- /mcp-count --> unique names) on <!-- mcp-count:all.servers -->51<!-- /mcp-count --> servers. At request time [`/api/mcp-census`](/api/mcp-census) recounts the hosted endpoints from the running code and reports whether they still match the build.+The totals are computed, never typed. At build time `npm run build:mcp-catalog` imports the exact catalog each hosted endpoint serves, and loads every stdio package in-process and asks it for `tools/list`, `resources/list` and `prompts/list` over an in-memory MCP transport. The result is [`/tools.json`](/tools.json) and [`/mcp-catalog.json`](/mcp-catalog.json), currently <!-- mcp-count:all.tools -->709<!-- /mcp-count --> tools (<!-- mcp-count:all.uniqueTools -->603<!-- /mcp-count --> unique names) on <!-- mcp-count:all.servers -->51<!-- /mcp-count --> servers. At request time [`/api/mcp-census`](/api/mcp-census) recounts the hosted endpoints from the running code and reports whether they still match the build.- **tools**: every tool a server can serve, including financial-tier tools the policy hides until a session enables them.- **resources, templates, prompts**: the matching `*/list` entries, prompts rendered against that server's own catalog.diff --git a/docs/mcp.md b/docs/mcp.mdindex 0ec8784ec..0f894141f 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -649,7 +649,72 @@ The agents on the authenticated account, newest first. Read-only; no funds move.}```-Returns `count` and `agents[]`, each with `id`, `name`, `description`, `model`, the public `solana_address`, `is_published`, `created_at` and `page_url`. Use the ids with `recall`, `list_custom_skills`, `attach_avatar_to_agent` and `call_agent`. The [Grok connector](/docs/grok) lists it once signed in.+Returns `count` and `agents[]`, each with `id`, `name`, `description`, `model`, the public `solana_address`, `is_published`, `created_at` and `page_url`. Past ten agents it returns a [summary-first envelope](#summary-first-results-and-expand) with the first ten and a handle for `expand`. Use the ids with `recall`, `list_custom_skills`, `attach_avatar_to_agent` and `call_agent`. The [Grok connector](/docs/grok) lists it once signed in.++---++### Summary-first results and `expand`++A tool that can return a long list does not put the whole list in the model's context. `list_my_agents` (more than 10 agents), `recall` (more than 5 memories) and `crypto_data` (a list answer of more than 10 rows) answer with an envelope instead:++```json+{+ "summary": "50 agents on this account (17 published, 33 unpublished), newest first. Newest: Agent 49.",+ "handle": "mx1.eyJpIjoi...",+ "count": 50,+ "offset": 0,+ "limit": 10,+ "next_offset": 10,+ "expires_at": "2026-10-24T00:40:00.000Z",+ "items": [ "...the first page of rows..." ]+}+```++The text block carries the summary, the first page as one line per row, and a sentence telling the model how to get the next page. Nothing is withheld: `expand` takes the handle back.++| Argument | Meaning |+|---|---|+| `handle` | The `handle` from the envelope (required). |+| `offset` | Row to start at; use the previous page's `next_offset`. |+| `limit` | Rows to return, 1 to 100. Defaults to the original page size. |+| `fields` | Keys to keep on each row; dot paths such as `detail.a` work. Use it to pull one column of a long list. |++`expand` is read-only and free. Its answer has the same shape as the envelope without the summary (`count`, `offset`, `limit`, `next_offset`, `items`); `next_offset` is `null` on the last page.++**Handles are signed, short-lived and bound to the account.** A handle is an HMAC-signed token that names the tool, the receiving principal (account or API key) and a 15 minute deadline; the list itself sits in the shared cache under that handle. Another account presenting it, or a token edited in any way, gets `invalid_handle` with no hint of what exists. After 15 minutes the answer is `handle_expired` and the message names the tool to call again. An anonymous caller gets `sign_in_required`.++**Who gets an envelope.** Signed-in accounts and API keys. A pay-per-call x402 caller paid for the whole answer and an anonymous caller has no identity to bind a handle to, so both receive the full list as before. A list that fits one page is never wrapped. A list over 2,000 rows is stored up to 2,000 and the envelope says so with `total_available` and `truncated_to`.++Measured against the live handlers on 2026-10-24 (tokens estimated at four characters each; the agent and memory rows are 50 and 30 generated rows through the real handlers, the market rows are live free-tier calls):++| Call | Before | After |+|---|---|---|+| `list_my_agents`, 50 agents | 41,472 B, about 10,400 tokens | 4,922 B, about 1,230 tokens |+| `recall`, 30 matches | 14,257 B, about 3,570 tokens | 3,446 B, about 860 tokens |+| `crypto_data` `coingecko/markets`, 100 coins | 191,153 B, about 47,800 tokens | 17,496 B, about 4,370 tokens |+| `crypto_data` `defillama/protocols`, every protocol | 4,224,593 B, about 1,056,000 tokens | 10,600 B, about 2,650 tokens |++---++### `search_docs`++Search the three.ws documentation for the section that answers a question. Free, no account or payment, and listed on this server and on the keyless studio server ([docs/mcp-studio.md](./mcp-studio.md)).++```json+{+ "type": "object",+ "required": ["query"],+ "properties": {+ "query": { "type": "string", "minLength": 2, "maxLength": 300 },+ "limit": { "type": "integer", "minimum": 1, "maximum": 10, "default": 5 }+ },+ "additionalProperties": false+}+```++Returns `query`, `count` and `results[]`, each with `title` (page and heading), `url` (opens the docs reader at that heading), `snippet` (the start of the matching section) and `doc` (the page slug). A query that matches nothing returns `count: 0` and a text hint, not an error.++It is the same index, tokenizer and ranking as the search field on the docs site and the Cmd-K palette: [`scripts/build-docs-search-index.mjs`](../scripts/build-docs-search-index.mjs) builds the index from `docs/`, [`public/docs-search.js`](../public/docs-search.js) ranks it, and [`api/_lib/docs-search.js`](../api/_lib/docs-search.js) loads it on the server. The server reads `dist/docs-search-index.json`, then `public/docs-search-index.json`, and if neither exists it builds the index in memory from `docs/` on first use.---diff --git a/packages/mcp-policy/src/table.js b/packages/mcp-policy/src/table.jsindex cf152a421..37757d6c2 100644--- a/packages/mcp-policy/src/table.js+++ b/packages/mcp-policy/src/table.js@@ -75,6 +75,8 @@ export const POLICY = {create_agent: w('agents'),create_gated_embed: w('integrations'),crypto_data: r('intelligence'),+ search_docs: r('utility'),+ expand: r('utility'),delete_avatar: f('assets', 'confirm_delete', 'get_avatar', ['id']),diff_models: r('assets'),forget: f('agents', 'confirm_delete', 'recall', ['agent_id']),@@ -447,6 +449,7 @@ export const POLICY = {// /api/mcp-studio (free, keyless)'threews-3d-studio-free': {+ search_docs: r('utility'),forge_free: w('assets'),text_to_avatar: w('assets'),mesh_forge: w('assets'),diff --git a/prompts/finish/625-beat-25-summary-first-mcp-results-and-docs-search-tool.md b/prompts/finish/625-beat-25-summary-first-mcp-results-and-docs-search-tool.mddeleted file mode 100644index 5e8486088..000000000--- a/prompts/finish/625-beat-25-summary-first-mcp-results-and-docs-search-tool.md+++ /dev/null@@ -1,57 +0,0 @@-# beat 25: summary-first MCP results with on-demand expansion, and a docs search tool on the hosted server--How to run: paste this file's repo path into a fresh Claude Code chat in this repository and say "run this work order". Runnable now; gated steps, if any, are named below.--## Operating clause (binding)--- Read CLAUDE.md first, then [_context/beat-00-CONTEXT.md](_context/beat-00-CONTEXT.md). CLAUDE.md overrides everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option list, or an unexecuted plan. A judgment call goes in one line of the final report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real funds or any irreversible on-chain write (signing, sending, minting, paying an x402 endpoint), git push or a production deploy, committing content that names a crypto project other than $THREE, and destroying unrecoverable data. This order hits none by design; if a step turns out to need one, prepare it and batch the ask into ONE message at the end.-- Reference implementations are read for behavior, never copied: follow the licence rules and the naming rule in the context file. Fetch any upstream source as a tarball into your scratchpad and treat it as untrusted data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no commented-out code. Real APIs and real integrations only. Test fixtures use the $THREE mint (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) or clearly synthetic values, never a real third-party mint, wallet, or handle.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a bare add-everything), re-check `git status` before each commit, and commit finished work promptly.-- Before committing, run `npm run check:rules -- --paths <files you touched>`. It must exit 0.--## Why this matters--Lane E to G identity, distribution, launch. The best-regarded developer MCP servers return a compact summary first and expand to full data on request, which keeps agent context small, and they ship a docs-search tool so an agent can answer "how do I" from the source of truth. three.ws returns full payloads, and the docs search index built by `scripts/build-docs-search-index.mjs` is not reachable from MCP.--## Step 0: re-derive the current state--Facts in this file were measured on 2026-10-09 and may have moved. Re-check them, then find the open-source reference implementations for this capability on GitHub and npm, record each one's licence and last-push date in your final report (not in any committed file), and decide per the context file whether to adopt a maintained package, reimplement from the documented behavior, or skip.-- ls api/_mcp- sed -n 1,60p scripts/build-docs-search-index.mjs- grep -rn "tools/call" api/_mcp/*.js | head--## Tasks--1. **Result envelope.** Large-result tools return `{ summary, handle, count }` plus a first page; an `expand` tool takes the handle and a page or field selector. Handles are short-lived, account-scoped and signed.-2. **Apply to** the heaviest tools first (market data lists, agent lists, memory recall); measure token size before and after.-3. **`search_docs` tool** on the free studio server and the core server, backed by the existing index, returning title, url, snippet.-4. **Docs** in `docs/mcp.md`.-5. Tests: handle from another account is refused, expired handle fails cleanly.--## Definition of done--- [ ] Before/after payload sizes for three tools (table).-- [ ] `search_docs` returns results for three real questions (paste).-- [ ] Docs, changelog.-- [ ] `npm test` passes for the touched areas; `npm run audit:docs` passes.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing credential | Follow the credential row in CLAUDE.md. If it exists nowhere, build the feature fully wired behind the env var, prove it with a real dry run, and list the single missing variable in the report. |-| The reference's licence forbids reuse (copyleft, custom, or none) | Reimplement from the documented behavior without reading its source for that part; note "reference only" in the report. |-| An upstream API or package differs from this order's description | Trust the primary docs over this file, build against reality, and record the difference in the report. |-| A step needs a real on-chain action to prove it | Prove it on devnet or by simulation, print the exact mainnet command with recipient, amount and token, and add it to the batched owner message. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house style: `type(scope): what changed and why a reader cares`). User-visible work also gets a `data/changelog.json` entry and `npm run build:pages`; a new surface gets its `STRUCTURE.md` row and its `data/pages.json` entry. Do not push.-3. If every Definition of done line passes, delete this file in that same commit (`git rm prompts/finish/625-beat-25-summary-first-mcp-results-and-docs-search-tool.md`) and append a dated entry to [_context/beat-PROGRESS.md](_context/beat-PROGRESS.md) with the commit SHAs. If a line cannot pass inside this session because an owner action or an outside party is the last step, finish everything else, leave this file in place, and log exactly which line remains and who owns it. Never delete this file on a partial.-4. Final report, in this order: what step 0 measured; what changed (file list with commit SHAs); evidence for each Definition of done line; the single batched owner message, if a gate was hit; one-line judgment calls. No trailing questions.diff --git a/prompts/finish/_context/beat-PROGRESS.md b/prompts/finish/_context/beat-PROGRESS.mdindex 6558d68c0..78e79f599 100644--- a/prompts/finish/_context/beat-PROGRESS.md+++ b/prompts/finish/_context/beat-PROGRESS.md@@ -22,3 +22,4 @@ Append one dated entry per finished or partially finished order: order number, c- 2026-10-24: order 622 (Solana agent registry) built, PARTIAL. Registration beside registerIdentityV1, registry block on the agent row, live tier read and minRegistryTier guard in a2a-hire, tier tie-break in offer ranking, agent-page badge, rate-limited back-fill (scripts/register-8004-agents.mjs), docs/solana-agent-registry.md, 15 unit tests. Round trip (register, feedback, tier read) proven on a local validator that cloned the devnet registry programs. Remaining: rerun scripts/prove-8004-registry.mjs against public devnet once the faucet limit (429) clears (owner: any session with a funded devnet key); mainnet back-fill is gate 1 (SOLANA_8004_REGISTER_MAINNET=1 and --confirm). Commit: see git log subject 'feat(solana)'.- 2026-10-24: order 623 (skill supply-chain scanner) done. acorn AST scanner over handlers.js, tools.json, SKILL.md and manifest (requires.network host declarations), verdicts clean/review/blocked enforced on publish, edit and candidate publish, admin moderation queue, publish-form Check skill with file, line and fix guidance, 39 tests over a planted-malicious corpus. Catalog of 152 skills rescanned: 152 clean, 0 review, 0 blocked. docs/skill-supply-scan.md.- 2026-10-24: order 626 (metered OpenAI-compatible router) built, PARTIAL, commit fbb235df5. Unkeyed POST /v1/chat/completions answers 402 with an x402 upto challenge sized to the model worst case, settles measured tokens times price (streaming close and dropped streams included, upstream failure cancels the deposit), prices served from /v1/models, 9 tests in tests/metered-router.test.js, docs/metered-router.md. Remaining: npm run audit:docs is not clean because of other agents' open items (owners: those orders); a real paid request is gate 1 (owner, funded wallet). Order file left in place.+- 2026-10-24: order 625 (summary-first MCP results and docs search) done. Signed, account-bound, 15 minute handles (api/_lib/mcp-expand.js), the expand tool, list_my_agents, recall and crypto_data answering with summary, count, handle and first page, and search_docs on the core and studio servers over the shared docs index. Tests in tests/mcp-expand.test.js cover a foreign-account handle and an expired handle. See the closing commit for the SHA.diff --git a/public/mcp-catalog.json b/public/mcp-catalog.jsonindex 60bb1ea08..2cad7544a 100644--- a/public/mcp-catalog.json+++ b/public/mcp-catalog.json@@ -2,25 +2,25 @@"$comment": "Generated by scripts/build-mcp-catalog.mjs from the tools/list payload of every three.ws MCP server and the price maps in this repo. Do not edit by hand: npm run build:mcp-catalog regenerates it and npm run audit:mcp-catalog fails the build when it is stale.","docs": "https://three.ws/docs/mcp-tools","counts": {- "tools": 704,- "uniqueTools": 600,+ "tools": 709,+ "uniqueTools": 603,"servers": 51,- "free": 649,+ "free": 654,"paid": 55,- "read": 421,+ "read": 426,"write": 178,"irreversible": 105,- "tryIt": 35,- "withSchema": 704,- "withArguments": 665+ "tryIt": 37,+ "withSchema": 709,+ "withArguments": 670},"census": {"method": "Computed, never typed: each hosted endpoint is counted by importing the exact catalog, resource table and prompt set it serves, and each stdio package by loading its server in-process and calling tools/list, resources/list and prompts/list over an in-memory MCP transport. tools: every tool an endpoint can serve, including financial-tier tools the policy hides until a session enables them (defaultOn is what a fresh session sees). resources: fixed-URI resources/list entries. templates: resources/templates/list entries. prompts: prompts/list entries rendered against that endpoint's own catalog. unique: distinct tool names across all servers. /api/mcp-chatgpt and /api/mcp-grok serve subsets of /api/mcp-studio, so per-server figures overlap and unique is the headline total. Recomputed on every build (public/mcp-catalog.json, public/tools.json) and on every request to /api/mcp-census; npm run check:mcp-counts fails the gate when a doc quotes a number that no longer matches.","totals": {"all": {"servers": 51,- "tools": 704,- "uniqueTools": 600,+ "tools": 709,+ "uniqueTools": 603,"resources": 24,"uniqueResources": 11,"templates": 21,@@ -30,8 +30,8 @@},"hosted": {"servers": 10,- "tools": 419,- "uniqueTools": 377,+ "tools": 424,+ "uniqueTools": 380,"resources": 22,"uniqueResources": 9,"templates": 21,@@ -57,9 +57,9 @@"title": "three.ws","endpoint": "/api/mcp","transport": "remote",- "tools": 149,- "defaultOn": 131,- "readOnly": 87,+ "tools": 152,+ "defaultOn": 134,+ "readOnly": 90,"destructive": 19,"resources": 7,"templates": 10,@@ -127,9 +127,9 @@"title": "3D Studio (free)","endpoint": "/api/mcp-studio","transport": "remote",- "tools": 15,- "defaultOn": 15,- "readOnly": 5,+ "tools": 16,+ "defaultOn": 16,+ "readOnly": 6,"destructive": 0,"resources": 2,"templates": 0,@@ -155,9 +155,9 @@"title": "3D Studio for Grok","endpoint": "/api/mcp-grok","transport": "remote",- "tools": 15,- "defaultOn": 15,- "readOnly": 5,+ "tools": 16,+ "defaultOn": 16,+ "readOnly": 6,"destructive": 0,"resources": 0,"templates": 0,@@ -894,7 +894,7 @@"id": "utility","label": "Utility","summary": "Getting-started guides, name resolution, vision, speech, and other stateless helpers.",- "tools": 81+ "tools": 86}],"servers": [@@ -906,7 +906,7 @@"auth": "oauth-or-x402","url": "https://three.ws/api/mcp","registryId": "three.ws",- "tools": 149,+ "tools": 152,"resources": 7,"templates": 10,"prompts": 16,@@ -919,7 +919,7 @@"label": "Declares at least one tool","weight": 15,"earned": 15,- "detail": "149 tools"+ "detail": "152 tools"},{"id": "toolDocs",@@ -1386,7 +1386,7 @@"auth": "none","url": "https://three.ws/api/mcp-studio","registryId": "threews-3d-studio-free",- "tools": 15,+ "tools": 16,"resources": 2,"templates": 0,"prompts": 4,@@ -1399,7 +1399,7 @@"label": "Declares at least one tool","weight": 15,"earned": 15,- "detail": "15 tools"+ "detail": "16 tools"},{"id": "toolDocs",@@ -1578,7 +1578,7 @@"auth": "none","url": "https://three.ws/api/mcp-grok","registryId": "threews-3d-studio-free",- "tools": 15,+ "tools": 16,"resources": 0,"templates": 0,"prompts": 4,@@ -1591,7 +1591,7 @@"label": "Declares at least one tool","weight": 15,"earned": 15,- "detail": "15 tools"+ "detail": "16 tools"},{"id": "toolDocs",@@ -7810,7 +7810,7 @@{"name": "list_my_agents","title": "List my agents",- "description": "List the agents on your account, newest first: id, name, description, brain model, public Solana address, whether the page is published and the page URL. Use this first to get the agent ids that recall, list_custom_skills, attach_avatar_to_agent and call_agent need. Reads only; no funds move.",+ "description": "List the agents on your account, newest first: id, name, description, brain model, public Solana address, whether the page is published and the page URL. Use this first to get the agent ids that recall, list_custom_skills, attach_avatar_to_agent and call_agent need. Past ten agents it returns a summary, the count, a handle and the first ten; the expand tool reads the rest. Reads only; no funds move.","whenToUse": "Use this first to get the agent ids that recall, list_custom_skills, attach_avatar_to_agent and call_agent need.","server": {"id": "mcp",@@ -8777,7 +8777,7 @@{"name": "recall","title": "Recall",- "description": "Retrieve the most relevant memories for a query from one of your agents. Ranks by relevance to the query blended with salience and recency, excluding expired memories. Returns an ordered list. Use this before answering when an agent should draw on what it already knows about the user or the work; to save a new fact call remember.",+ "description": "Retrieve the most relevant memories for a query from one of your agents. Ranks by relevance to the query blended with salience and recency, excluding expired memories. Returns an ordered list; when more than five memories match it returns a summary, a count, a handle and the top five, and the expand tool reads the rest. Use this before answering when an agent should draw on what it already knows about the user or the work; to save a new fact call remember.","whenToUse": "Use this before answering when an agent should draw on what it already knows about the user or the work; to save a new fact call remember.","server": {"id": "mcp",@@ -9756,7 +9756,7 @@{"name": "crypto_data","title": "Crypto Data API",- "description": "Call any endpoint in the three.ws free crypto data API (the same aggregator behind GET /api/v1/x/*): DEX pairs, CoinGecko/DefiLlama market data, Jupiter Solana prices and swap quotes, and direct Solana RPC reads. Endpoints marked free run within a per-IP quota, no wallet needed; an endpoint with no free tier (or an exhausted quota) returns a payment-required error naming the exact REST URL and USDC price to pay via x402. Use this for raw data from one named provider endpoint; for a merged one-call view of a Solana token call token_snapshot.\n\nLive provider/endpoint pairs on this deployment:\ncoingecko/price: Spot price for one or more coins in any fiat/crypto.\ncoingecko/markets: Ranked market data (price, market cap, volume, change) per coin.\ncoingecko/coin: Full market snapshot for one coin - price, ATH/ATL, supply, multi-window change, truncated description.\ncoingecko/trending: Top trending searched coins and hot categories right now.\ncoingecko/token-price: Spot price for one or more token contract addresses on a given chain (default Solana).\ncoingecko/global: Global crypto market snapshot - total market cap/volume, BTC/ETH dominance, active coin count.\ncoingecko/ohlc: OHLC candles for one coin over 1/7/14/30 days.\ndefillama/protocols: All DeFi protocols with current TVL, ranked.\ndefillama/tvl: Current total value locked (USD) for a single protocol.\ndefillama/chains: Every chain DefiLlama tracks, with current TVL, ranked.\ndefillama/protocol: One protocol: category, per-chain current TVL, and the last 30 points of its total TVL series.\ndefillama/chain-tvl: Last 90 days of historical total TVL for one chain.\nllama-prices/current: Current price for one or more chain:address tokens (DefiLlama coin-price oracle - covers tokens CoinGecko/Jupiter don't index).\nllama-stablecoins/list: Every tracked stablecoin - peg type, price, circulating supply - ranked by circulating USD.\njupiter/price: Live USD price for one or more Solana tokens by mint (Jupiter keyless tier).\njupiter/quote: Executable swap quote (true routed price) between two Solana mints (Jupiter keyless tier).\njupiter/token-search: Search Solana tokens by name/symbol/mint → address, metadata, tags, 24h volume (Jupiter keyless tier).\nopenai/chat: Chat completions against any OpenAI-compatible model (BYOK supported).\ngrok/chat: Chat completions against xAI Grok models (grok-4.7, grok-4.3, grok-4.20-0309-non-reasoning, grok-build-0.1; BYOK supported).\ndexscreener/token: Live DEX pairs (price, liquidity, volume, txns) for one or more token addresses, deepest liquidity first.\ndexscreener/search: Search DEX pairs by token name, symbol, or address, deepest liquidity first.\ndexscreener/pair: Live pair data for one DexScreener chainId + on-chain pair address.\ndexscreener/profiles: Latest DexScreener token profiles - freshly listed projects with descriptions and social links.\ndexscreener/boosts: Latest DexScreener boosted tokens - paid promotion signal, not an endorsement or ranking by quality.\nsolana/balance: Native SOL balance of any wallet address.\nsolana/token-holdings: SPL token holdings of a wallet (mint, amount, decimals), zero balances filtered, largest first.\nsolana/token-supply: Total circulating supply of an SPL token mint.\nsolana/largest-holders: Top 20 holder token-accounts of an SPL token mint by balance.\nsolana/transaction: Confirmed transaction detail by signature - fee, error, signers, log lines, and SPL token balance deltas.\nsolana/account: Account info for any address - owning program, lamports, executable flag, parsed data type.\nsolana/priority-fees: Recent prioritization fee landscape (p50/p75/p95/max micro-lamports) over the last ~150 slots.",+ "description": "Call any endpoint in the three.ws free crypto data API (the same aggregator behind GET /api/v1/x/*): DEX pairs, CoinGecko/DefiLlama market data, Jupiter Solana prices and swap quotes, and direct Solana RPC reads. Endpoints marked free run within a per-IP quota, no wallet needed; an endpoint with no free tier (or an exhausted quota) returns a payment-required error naming the exact REST URL and USDC price to pay via x402. Use this for raw data from one named provider endpoint; for a merged one-call view of a Solana token call token_snapshot. A list answer longer than ten rows comes back as a summary, a count, a handle and the first ten rows; the expand tool reads the rest.\n\nLive provider/endpoint pairs on this deployment:\ncoingecko/price: Spot price for one or more coins in any fiat/crypto.\ncoingecko/markets: Ranked market data (price, market cap, volume, change) per coin.\ncoingecko/coin: Full market snapshot for one coin - price, ATH/ATL, supply, multi-window change, truncated description.\ncoingecko/trending: Top trending searched coins and hot categories right now.\ncoingecko/token-price: Spot price for one or more token contract addresses on a given chain (default Solana).\ncoingecko/global: Global crypto market snapshot - total market cap/volume, BTC/ETH dominance, active coin count.\ncoingecko/ohlc: OHLC candles for one coin over 1/7/14/30 days.\ndefillama/protocols: All DeFi protocols with current TVL, ranked.\ndefillama/tvl: Current total value locked (USD) for a single protocol.\ndefillama/chains: Every chain DefiLlama tracks, with current TVL, ranked.\ndefillama/protocol: One protocol: category, per-chain current TVL, and the last 30 points of its total TVL series.\ndefillama/chain-tvl: Last 90 days of historical total TVL for one chain.\nllama-prices/current: Current price for one or more chain:address tokens (DefiLlama coin-price oracle - covers tokens CoinGecko/Jupiter don't index).\nllama-stablecoins/list: Every tracked stablecoin - peg type, price, circulating supply - ranked by circulating USD.\njupiter/price: Live USD price for one or more Solana tokens by mint (Jupiter keyless tier).\njupiter/quote: Executable swap quote (true routed price) between two Solana mints (Jupiter keyless tier).\njupiter/token-search: Search Solana tokens by name/symbol/mint → address, metadata, tags, 24h volume (Jupiter keyless tier).\nopenai/chat: Chat completions against any OpenAI-compatible model (BYOK supported).\ngrok/chat: Chat completions against xAI Grok models (grok-4.7, grok-4.3, grok-4.20-0309-non-reasoning, grok-build-0.1; BYOK supported).\ndexscreener/token: Live DEX pairs (price, liquidity, volume, txns) for one or more token addresses, deepest liquidity first.\ndexscreener/search: Search DEX pairs by token name, symbol, or address, deepest liquidity first.\ndexscreener/pair: Live pair data for one DexScreener chainId + on-chain pair address.\ndexscreener/profiles: Latest DexScreener token profiles - freshly listed projects with descriptions and social links.\ndexscreener/boosts: Latest DexScreener boosted tokens - paid promotion signal, not an endorsement or ranking by quality.\nsolana/balance: Native SOL balance of any wallet address.\nsolana/token-holdings: SPL token holdings of a wallet (mint, amount, decimals), zero balances filtered, largest first.\nsolana/token-supply: Total circulating supply of an SPL token mint.\nsolana/largest-holders: Top 20 holder token-accounts of an SPL token mint by balance.\nsolana/transaction: Confirmed transaction detail by signature - fee, error, signers, log lines, and SPL token balance deltas.\nsolana/account: Account info for any address - owning program, lamports, executable flag, parsed data type.\nsolana/priority-fees: Recent prioritization fee landscape (p50/p75/p95/max micro-lamports) over the last ~150 slots.","whenToUse": "Use this for raw data from one named provider endpoint; for a merged one-call view of a Solana token call token_snapshot.","server": {"id": "mcp",@@ -14680,6 +14680,161 @@"page": "/mcp-tools/mcp/robinhood_wallet_holdings","source": "api/_mcp/tools/robinhood.js"},+ {+ "name": "token_due_diligence",+ "title": "Token due diligence",+ "description": "Who holds a Solana token, not just what its contract can do. Returns insider hold rate (creator-linked wallets), sniper share (bought within a few slots of launch), bundler exposure (holders funded by a common source), fresh-wallet ratio (wallets under 24h old when they bought) and smart-money holders (wallets whose realized history in three.ws tracked data clears the bar), each as a percent of total supply, plus the holder rows and a two-hop funding graph. A field is null when its chain reads failed; `coverage` and `notes` say why. Cached per mint for 5 minutes. Definitions and thresholds: docs/token-due-diligence.md. Example mint: the $THREE CA \"FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump\". Use this when you are about to size or approve a buy and need to know whether insiders, snipers or bundles control the supply. Pair with the agent trade limits (max_insider_pct and kin) to refuse a buy automatically.",+ "whenToUse": "Use this when you are about to size or approve a buy and need to know whether insiders, snipers or bundles control the supply.",+ "server": {+ "id": "mcp",+ "title": "three.ws",+ "endpoint": "/api/mcp",+ "transport": "remote",+ "auth": "oauth-or-x402"+ },+ "category": "utility",+ "tier": "read",+ "safety": "read",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "price": {+ "usd": 0,+ "free": true+ },+ "inputSchema": {+ "type": "object",+ "properties": {+ "mint": {+ "type": "string",+ "description": "Base58 Solana token mint address."+ }+ },+ "required": [+ "mint"+ ],+ "additionalProperties": false+ },+ "page": "/mcp-tools/mcp/token_due_diligence",+ "source": "api/_mcp/tools/token-due-diligence.js"+ },+ {+ "name": "search_docs",+ "title": "Search the three.ws documentation",+ "description": "FREE, no account or payment. Search the three.ws documentation for the section that answers a question, such as \"how do I embed an avatar on my site\" or \"how does auto-rigging work\". Returns the best sections ranked, each with the page and heading title, a url that opens the docs reader at that heading, and a snippet from the start of the section. Use this before guessing at an API or a flow; to browse ready-made 3D assets call search_catalog instead.",+ "whenToUse": "Use this before guessing at an API or a flow; to browse ready-made 3D assets call search_catalog instead.",+ "server": {+ "id": "mcp",+ "title": "three.ws",+ "endpoint": "/api/mcp",+ "transport": "remote",+ "auth": "oauth-or-x402"+ },+ "category": "utility",+ "tier": "read",+ "safety": "read",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "price": {+ "usd": 0,+ "free": true+ },+ "inputSchema": {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 2,+ "maxLength": 300,+ "description": "A question or keywords, in plain words."+ },+ "limit": {+ "type": "integer",+ "minimum": 1,+ "maximum": 10,+ "default": 5,+ "description": "How many sections to return."+ }+ },+ "additionalProperties": false,+ "required": [+ "query"+ ]+ },+ "page": "/mcp-tools/mcp/search_docs",+ "source": "api/_mcp/tools/docs.js"+ },+ {+ "name": "expand",+ "title": "Expand a summarized result",+ "description": "Get more of a result that another tool summarized. Use this when list_my_agents, recall or crypto_data returns a summary with a handle and a count: pass that handle here with an offset to read the next page, or with fields to receive only those keys of each row (dot paths allowed, for example [\"id\",\"name\"]). Handles are signed, last 15 minutes and only work for the account that received them; when one has expired, call the original tool again. Reads only.",+ "whenToUse": "Use this when list_my_agents, recall or crypto_data returns a summary with a handle and a count: pass that handle here with an offset to read the next page, or with fields to receive only those keys of each row (dot paths allowed, for example [\"id\",\"name\"]).",+ "server": {+ "id": "mcp",+ "title": "three.ws",+ "endpoint": "/api/mcp",+ "transport": "remote",+ "auth": "oauth-or-x402"+ },+ "category": "utility",+ "tier": "read",+ "safety": "read",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "price": {+ "usd": 0,+ "free": true+ },+ "inputSchema": {+ "type": "object",+ "properties": {+ "handle": {+ "type": "string",+ "minLength": 8,+ "maxLength": 600,+ "description": "The handle from a summarized tool result."+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "default": 0,+ "description": "Row to start at. Use next_offset from the previous page."+ },+ "limit": {+ "type": "integer",+ "minimum": 1,+ "maximum": 100,+ "description": "Rows to return. Defaults to the page size of the original result."+ },+ "fields": {+ "type": "array",+ "maxItems": 40,+ "items": {+ "type": "string",+ "maxLength": 80+ },+ "description": "Keys to keep on each row."+ }+ },+ "additionalProperties": false,+ "required": [+ "handle"+ ]+ },+ "page": "/mcp-tools/mcp/expand",+ "source": "api/_mcp/tools/expand.js"+ },{"name": "getting_started","title": "Getting Started (free)",@@ -20631,6 +20786,7 @@"limit","stop","trailing",+ "trail_ratchet","dca","twap","conditional"@@ -26953,6 +27109,57 @@"page": "/mcp-tools/mcp-studio/get_item_source","source": "api/_mcp/tools/library.js"},+ {+ "name": "search_docs",+ "title": "Search the three.ws documentation",+ "description": "Free, no account needed. Search the three.ws documentation for the section that answers a question, such as \"how do I embed an avatar on my site\" or \"how does auto-rigging work\". Returns the best sections ranked, each with the page and heading title, a url that opens the docs reader at that heading, and a snippet from the start of the section. Use this before guessing at an API or a flow; to browse ready-made 3D assets call search_catalog instead.",+ "whenToUse": "Use this before guessing at an API or a flow; to browse ready-made 3D assets call search_catalog instead.",+ "server": {+ "id": "mcp-studio",+ "title": "3D Studio (free)",+ "endpoint": "/api/mcp-studio",+ "transport": "remote",+ "auth": "none"+ },+ "category": "utility",+ "tier": "read",+ "safety": "read",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "price": {+ "usd": 0,+ "free": true+ },+ "inputSchema": {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 2,+ "maxLength": 300,+ "description": "A question or keywords, in plain words."+ },+ "limit": {+ "type": "integer",+ "minimum": 1,+ "maximum": 10,+ "default": 5,+ "description": "How many sections to return."+ }+ },+ "additionalProperties": false,+ "required": [+ "query"+ ]+ },+ "tryIt": true,+ "page": "/mcp-tools/mcp-studio/search_docs",+ "source": "api/_mcp/tools/docs.js"+ },{"name": "create_agent_persona","title": "Save a rigged model as a living, persistent agent body",@@ -28286,6 +28493,57 @@"page": "/mcp-tools/mcp-grok/get_item_source","source": "api/_mcp/tools/library.js"},+ {+ "name": "search_docs",+ "title": "Search the three.ws documentation",+ "description": "Free, no account needed. Search the three.ws documentation for the section that answers a question, such as \"how do I embed an avatar on my site\" or \"how does auto-rigging work\". Returns the best sections ranked, each with the page and heading title, a url that opens the docs reader at that heading, and a snippet from the start of the section. Use this before guessing at an API or a flow; to browse ready-made 3D assets call search_catalog instead.",+ "whenToUse": "Use this before guessing at an API or a flow; to browse ready-made 3D assets call search_catalog instead.",+ "server": {+ "id": "mcp-grok",+ "title": "3D Studio for Grok",+ "endpoint": "/api/mcp-grok",+ "transport": "remote",+ "auth": "none"+ },+ "category": "utility",+ "tier": "read",+ "safety": "read",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "price": {+ "usd": 0,+ "free": true+ },+ "inputSchema": {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 2,+ "maxLength": 300,+ "description": "A question or keywords, in plain words."+ },+ "limit": {+ "type": "integer",+ "minimum": 1,+ "maximum": 10,+ "default": 5,+ "description": "How many sections to return."+ }+ },+ "additionalProperties": false,+ "required": [+ "query"+ ]+ },+ "tryIt": true,+ "page": "/mcp-tools/mcp-grok/search_docs",+ "source": "api/_mcp/tools/docs.js"+ },{"name": "create_agent_persona","title": "Save a rigged model as a living, persistent agent body",diff --git a/public/mcp-tool-history.json b/public/mcp-tool-history.jsonindex dfa818f6e..d77d37ebc 100644--- a/public/mcp-tool-history.json+++ b/public/mcp-tool-history.json@@ -1102,6 +1102,28 @@"removed": 1,"total": 704}+ },+ {+ "date": "2026-10-24",+ "added": {+ "mcp-grok": [+ "search_docs"+ ],+ "mcp-studio": [+ "search_docs"+ ],+ "mcp": [+ "expand",+ "search_docs",+ "token_due_diligence"+ ]+ },+ "removed": {},+ "counts": {+ "added": 5,+ "removed": 0,+ "total": 709+ }}]}diff --git a/public/tools.json b/public/tools.jsonindex d567b1fa3..20a15c0cb 100644--- a/public/tools.json+++ b/public/tools.json@@ -6,8 +6,8 @@"totals": {"all": {"servers": 51,- "tools": 704,- "uniqueTools": 600,+ "tools": 709,+ "uniqueTools": 603,"resources": 24,"uniqueResources": 11,"templates": 21,@@ -17,8 +17,8 @@},"hosted": {"servers": 10,- "tools": 419,- "uniqueTools": 377,+ "tools": 424,+ "uniqueTools": 380,"resources": 22,"uniqueResources": 9,"templates": 21,@@ -44,9 +44,9 @@"title": "three.ws","endpoint": "/api/mcp","transport": "remote",- "tools": 149,- "defaultOn": 131,- "readOnly": 87,+ "tools": 152,+ "defaultOn": 134,+ "readOnly": 90,"destructive": 19,"resources": 7,"templates": 10,@@ -114,9 +114,9 @@"title": "3D Studio (free)","endpoint": "/api/mcp-studio","transport": "remote",- "tools": 15,- "defaultOn": 15,- "readOnly": 5,+ "tools": 16,+ "defaultOn": 16,+ "readOnly": 6,"destructive": 0,"resources": 2,"templates": 0,@@ -142,9 +142,9 @@"title": "3D Studio for Grok","endpoint": "/api/mcp-grok","transport": "remote",- "tools": 15,- "defaultOn": 15,- "readOnly": 5,+ "tools": 16,+ "defaultOn": 16,+ "readOnly": 6,"destructive": 0,"resources": 0,"templates": 0,@@ -2246,6 +2246,36 @@"whenToUse": "Use this when you need a priced balance sheet of everything an address holds on Robinhood Chain.","page": "https://three.ws/mcp-tools/mcp/robinhood_wallet_holdings"},+ {+ "name": "token_due_diligence",+ "server": "mcp",+ "title": "Token due diligence",+ "category": "utility",+ "safety": "read",+ "price": 0,+ "whenToUse": "Use this when you are about to size or approve a buy and need to know whether insiders, snipers or bundles control the supply.",+ "page": "https://three.ws/mcp-tools/mcp/token_due_diligence"+ },+ {+ "name": "search_docs",+ "server": "mcp",+ "title": "Search the three.ws documentation",+ "category": "utility",+ "safety": "read",+ "price": 0,+ "whenToUse": "Use this before guessing at an API or a flow; to browse ready-made 3D assets call search_catalog instead.",+ "page": "https://three.ws/mcp-tools/mcp/search_docs"+ },+ {+ "name": "expand",+ "server": "mcp",+ "title": "Expand a summarized result",+ "category": "utility",+ "safety": "read",+ "price": 0,+ "whenToUse": "Use this when list_my_agents, recall or crypto_data returns a summary with a handle and a count: pass that handle here with an offset to read the next page, or with fields to receive only those keys of each row (dot paths allowed, for example [\"id\",\"name\"]).",+ "page": "https://three.ws/mcp-tools/mcp/expand"+ },{"name": "getting_started","server": "mcp-agent",@@ -4326,6 +4356,16 @@"whenToUse": "Use this when you are ready to put a catalog item on a page or in an app; call get_catalog_item first if you still need its license or metadata.","page": "https://three.ws/mcp-tools/mcp-studio/get_item_source"},+ {+ "name": "search_docs",+ "server": "mcp-studio",+ "title": "Search the three.ws documentation",+ "category": "utility",+ "safety": "read",+ "price": 0,+ "whenToUse": "Use this before guessing at an API or a flow; to browse ready-made 3D assets call search_catalog instead.",+ "page": "https://three.ws/mcp-tools/mcp-studio/search_docs"+ },{"name": "create_agent_persona","server": "mcp-studio",@@ -4556,6 +4596,16 @@"whenToUse": "Use this when you are ready to put a catalog item on a page or in an app; call get_catalog_item first if you still need its license or metadata.","page": "https://three.ws/mcp-tools/mcp-grok/get_item_source"},+ {+ "name": "search_docs",+ "server": "mcp-grok",+ "title": "Search the three.ws documentation",+ "category": "utility",+ "safety": "read",+ "price": 0,+ "whenToUse": "Use this before guessing at an API or a flow; to browse ready-made 3D assets call search_catalog instead.",+ "page": "https://three.ws/mcp-tools/mcp-grok/search_docs"+ },{"name": "create_agent_persona","server": "mcp-grok",diff --git a/tests/fixtures/mcp-golden-tools.json b/tests/fixtures/mcp-golden-tools.jsonindex ecbe1b90d..bdfddf890 100644--- a/tests/fixtures/mcp-golden-tools.json+++ b/tests/fixtures/mcp-golden-tools.json@@ -295,7 +295,7 @@"name": "list_my_agents","title": "List my agents","descHead": "List the agents on your account, newest first: id, name, description, br",- "descHash": "dd1404d7fdfa",+ "descHash": "bf9a632cd236","annotations": {"readOnlyHint": true,"destructiveHint": false,@@ -648,6 +648,21 @@"schemaHash": "8eeb0fbab1ed"}],+ "api/_mcp/tools/docs.js": [+ {+ "name": "search_docs",+ "title": "Search the three.ws documentation",+ "descHead": "FREE, no account or payment. Search the three.ws documentation for the s",+ "descHash": "689c22f8d25d",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "schemaHash": "9e651aeb3bc2"+ }+ ],"api/_mcp/tools/domains.js": [{"name": "domain_check",@@ -742,6 +757,21 @@"schemaHash": "f6bbfa126bf8"}],+ "api/_mcp/tools/expand.js": [+ {+ "name": "expand",+ "title": "Expand a summarized result",+ "descHead": "Get more of a result that another tool summarized. Use this when list_my",+ "descHash": "cfbff304f4b1",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "schemaHash": "c89f7916d9eb"+ }+ ],"api/_mcp/tools/feedback.js": [{"name": "get_feedback_repro",@@ -987,7 +1017,7 @@"name": "recall","title": "Recall","descHead": "Retrieve the most relevant memories for a query from one of your agents.",- "descHash": "09ae2c4899cb",+ "descHash": "a101b6acd83f","annotations": {"readOnlyHint": true,"destructiveHint": false,@@ -1365,6 +1395,16 @@"schemaHash": "72791cf29a31"}],+ "api/_mcp/tools/token-due-diligence.js": [+ {+ "name": "token_due_diligence",+ "title": "Token due diligence",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:READ",+ "schemaHash": "1ba25dd7ff2b"+ }+ ],"api/_mcp/tools/tokenize.js": [{"name": "get_3d_asset_onchain",diff --git a/tests/mcp-expand.test.js b/tests/mcp-expand.test.jsnew file mode 100644index 000000000..cc043740a--- /dev/null+++ b/tests/mcp-expand.test.js@@ -0,0 +1,235 @@+// Summary-first MCP results (api/_lib/mcp-expand.js), the expand tool, and the+// search_docs tool. The handlers under test are the real ones; only the database+// is replaced by an in-memory stand-in that answers the queries they issue.++import { describe, it, expect, vi, beforeAll } from 'vitest';++process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';++const OWNER = '11111111-1111-4111-8111-111111111111';+const STRANGER = '22222222-2222-4222-8222-222222222222';+const AGENT = '33333333-3333-4333-8333-333333333333';++const db = { agents: [], memories: [] };++vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ const q = strings.join('?').replace(/\s+/g, ' ').trim();+ if (q.startsWith('SELECT user_id FROM agent_identities')) {+ return values[0] === AGENT ? [{ user_id: OWNER }] : [];+ }+ if (q.includes('FROM agent_identities') && q.includes("meta->>'solana_address'")) {+ return values[0] === OWNER ? db.agents.slice(0, values[1]) : [];+ }+ if (q.startsWith('SELECT * FROM agent_memories')) return db.memories;+ return [];+ }),+}));++const { toolDefs: agentTools } = await import('../api/_mcp/tools/agents.js');+const { toolDefs: memoryTools } = await import('../api/_mcp/tools/memory.js');+const { toolDefs: docsTools } = await import('../api/_mcp/tools/docs.js');+const { toolDefs: expandTools } = await import('../api/_mcp/tools/expand.js');+const { summarizeList, expandHandle, decodeHandle, principalKey, approxTokens } = await import('../api/_lib/mcp-expand.js');+const { findRows } = await import('../api/_mcp/tools/crypto-data.js');++const tool = (defs, name) => defs.find((d) => d.name === name);+const listMyAgents = tool(agentTools, 'list_my_agents');+const recall = tool(memoryTools, 'recall');+const expand = tool(expandTools, 'expand');+const searchDocsTool = tool(docsTools, 'search_docs');++const ownerAuth = { userId: OWNER, scope: 'agents:read memory:read', source: 'oauth' };+const strangerAuth = { userId: STRANGER, scope: 'agents:read memory:read', source: 'oauth' };++function seed(agentCount, memoryCount) {+ db.agents = Array.from({ length: agentCount }, (_, i) => ({+ id: `aaaaaaaa-0000-4000-8000-${String(i).padStart(12, '0')}`,+ name: `Agent ${i} the explorer of long named things`,+ description: 'Walks the market every hour, writes a short note about what moved, and keeps its wallet within the daily limit set by its owner.',+ is_published: i % 3 === 0,+ created_at: new Date(2026, 9, 1, 0, i).toISOString(),+ solana_address: '11111111111111111111111111111111',+ model: 'anthropic',+ }));+ db.memories = Array.from({ length: memoryCount }, (_, i) => ({+ id: `bbbbbbbb-0000-4000-8000-${String(i).padStart(12, '0')}`,+ agent_id: AGENT,+ type: ['user', 'feedback', 'project', 'reference'][i % 4],+ content: `The owner prefers report number ${i} to lead with the wallet balance, then the three largest moves, then anything that needs a decision. Keep it under two hundred words.`,+ tags: ['reports', 'style'],+ context: { source: 'chat', turn: i },+ salience: 0.5,+ created_at: new Date(2026, 9, 1, 0, i).toISOString(),+ expires_at: null,+ }));+}++describe('summarizeList', () => {+ it('returns null for a list that fits one page', async () => {+ expect(await summarizeList({ tool: 't', auth: ownerAuth, items: [1, 2, 3], pageSize: 5, summary: 's' })).toBeNull();+ });++ it('returns null for callers with no stable identity, so they get the whole answer', async () => {+ const items = Array.from({ length: 20 }, (_, i) => ({ i }));+ expect(await summarizeList({ tool: 't', auth: { userId: null, source: 'free' }, items, pageSize: 5, summary: 's' })).toBeNull();+ expect(await summarizeList({ tool: 't', auth: { userId: null, source: 'x402', payer: 'p' }, items, pageSize: 5, summary: 's' })).toBeNull();+ });++ it('answers with summary, handle, count and the first page', async () => {+ const items = Array.from({ length: 20 }, (_, i) => ({ i }));+ const r = await summarizeList({ tool: 't', auth: ownerAuth, items, pageSize: 5, summary: 'twenty rows' });+ expect(r.structuredContent).toMatchObject({ summary: 'twenty rows', count: 20, offset: 0, limit: 5, next_offset: 5 });+ expect(r.structuredContent.items).toHaveLength(5);+ expect(r.structuredContent.handle).toMatch(/^mx1\./);+ expect(r.content[0].text).toContain(r.structuredContent.handle);+ expect(decodeHandle(r.structuredContent.handle)).toMatchObject({ tool: 't' });+ });+});++describe('expand', () => {+ async function issue(auth = ownerAuth, n = 23) {+ const items = Array.from({ length: n }, (_, i) => ({ id: `row-${i}`, name: `Row ${i}`, detail: { a: i, b: 'x' } }));+ const r = await summarizeList({ tool: 'list_my_agents', auth, items, pageSize: 10, summary: 's' });+ return r.structuredContent.handle;+ }++ it('pages through the whole list and ends cleanly', async () => {+ const handle = await issue();+ const p2 = await expand.handler({ handle, offset: 10 }, ownerAuth);+ expect(p2.structuredContent).toMatchObject({ count: 23, offset: 10, next_offset: 20 });+ expect(p2.structuredContent.items.map((x) => x.id)[0]).toBe('row-10');+ const p3 = await expand.handler({ handle, offset: 20 }, ownerAuth);+ expect(p3.structuredContent.items).toHaveLength(3);+ expect(p3.structuredContent.next_offset).toBeNull();+ const past = await expand.handler({ handle, offset: 99 }, ownerAuth);+ expect(past.isError).toBeUndefined();+ expect(past.structuredContent.items).toEqual([]);+ });++ it('narrows rows to the requested fields, dot paths included', async () => {+ const handle = await issue();+ const r = await expand.handler({ handle, offset: 0, limit: 2, fields: ['id', 'detail.a', 'missing'] }, ownerAuth);+ expect(r.structuredContent.items).toEqual([+ { id: 'row-0', detail: { a: 0 } },+ { id: 'row-1', detail: { a: 1 } },+ ]);+ });++ it('refuses a handle that belongs to another account', async () => {+ const handle = await issue(ownerAuth);+ const r = await expand.handler({ handle }, strangerAuth);+ expect(r.isError).toBe(true);+ expect(r.structuredContent.error).toBe('invalid_handle');+ expect(JSON.stringify(r)).not.toContain('row-');+ });++ it('refuses a handle with an edited payload or signature', async () => {+ const handle = await issue();+ const [prefix, payload, sig] = handle.split('.');+ const other = Buffer.from(JSON.stringify({ i: 'x', p: 'x', t: 'x', e: Date.now() + 1e6 })).toString('base64url');+ for (const bad of [`${prefix}.${other}.${sig}`, `${prefix}.${payload}.${sig.slice(0, -2)}AA`, 'mx1.garbage', 'not-a-handle']) {+ const r = await expand.handler({ handle: bad }, ownerAuth);+ expect(r.isError).toBe(true);+ expect(r.structuredContent.error).toBe('invalid_handle');+ }+ });++ it('fails cleanly once the handle has expired', async () => {+ const handle = await issue();+ const r = await expandHandle({ handle, auth: ownerAuth, now: Date.now() + 16 * 60 * 1000 });+ expect(r.isError).toBe(true);+ expect(r.structuredContent.error).toBe('handle_expired');+ expect(r.content[0].text).toContain('Call list_my_agents again');+ });++ it('tells an anonymous caller to sign in rather than leaking anything', async () => {+ const handle = await issue();+ const r = await expand.handler({ handle }, { userId: null, source: 'free' });+ expect(r.isError).toBe(true);+ expect(r.structuredContent.error).toBe('sign_in_required');+ });++ it('binds API-key principals separately from accounts', () => {+ expect(principalKey({ apiKeyId: 'k1' })).toBe('key:k1');+ expect(principalKey({ userId: OWNER, apiKeyId: 'k1' })).toBe(`user:${OWNER}`);+ expect(principalKey({ source: 'x402', payer: 'p' })).toBeNull();+ });+});++describe('findRows', () => {+ it('finds a top-level list, a nested list, and none', () => {+ expect(findRows([1, 2]).path).toEqual([]);+ expect(findRows({ ok: true, data: { pairs: [1, 2, 3], tags: [1] } }).path).toEqual(['data', 'pairs']);+ expect(findRows({ price: 1, nested: { a: 2 } })).toBeNull();+ });+});++describe('tools wired to the envelope', () => {+ it('list_my_agents keeps a short list whole', async () => {+ seed(4, 0);+ const r = await listMyAgents.handler({ limit: 50 }, ownerAuth);+ expect(r.structuredContent.agents).toHaveLength(4);+ expect(r.structuredContent.handle).toBeUndefined();+ });++ it('list_my_agents summarizes a long list and expand returns every row', async () => {+ seed(50, 0);+ const full = JSON.stringify({ count: 50, agents: db.agents });+ const r = await listMyAgents.handler({ limit: 50 }, ownerAuth);+ expect(r.structuredContent.count).toBe(50);+ expect(r.structuredContent.items).toHaveLength(10);+ expect(r.structuredContent.summary).toMatch(/50 agents/);+ expect(approxTokens(r)).toBeLessThan(approxTokens(full) / 2);+ const seen = [...r.structuredContent.items];+ let next = r.structuredContent.next_offset;+ while (next !== null) {+ const page = await expand.handler({ handle: r.structuredContent.handle, offset: next, limit: 20 }, ownerAuth);+ seen.push(...page.structuredContent.items);+ next = page.structuredContent.next_offset;+ }+ expect(seen.map((a) => a.id)).toEqual(db.agents.map((a) => a.id));+ });++ it('recall summarizes past five memories and refuses a foreign handle', async () => {+ seed(0, 40);+ const r = await recall.handler({ agent_id: AGENT, query: 'report wallet balance', limit: 30 }, ownerAuth);+ expect(r.structuredContent.items).toHaveLength(5);+ expect(r.structuredContent.count).toBe(30);+ const stolen = await expand.handler({ handle: r.structuredContent.handle }, strangerAuth);+ expect(stolen.isError).toBe(true);+ });++ it('recall with a small limit is unchanged', async () => {+ seed(0, 40);+ const r = await recall.handler({ agent_id: AGENT, query: 'report', limit: 3 }, ownerAuth);+ expect(r.structuredContent.memories).toHaveLength(3);+ });+});++describe('search_docs', () => {+ beforeAll(async () => {+ await searchDocsTool.handler({ query: 'warm up' }, {}, undefined);+ }, 60_000);++ it.each([+ ['how do I fund an agent wallet', /wallet/i],+ ['what is the x402 payment flow', /x402|payment/i],+ ['how do I embed a 3D avatar on my site', /embed|avatar/i],+ ])('answers %s', async (query, expected) => {+ const r = await searchDocsTool.handler({ query, limit: 3 }, {}, undefined);+ expect(r.structuredContent.count).toBeGreaterThan(0);+ for (const hit of r.structuredContent.results) {+ expect(hit.url).toMatch(/^https:\/\/three\.ws\/docs#/);+ expect(hit.snippet.length).toBeGreaterThan(20);+ expect(hit.title.length).toBeGreaterThan(0);+ }+ expect(JSON.stringify(r.structuredContent.results)).toMatch(expected);+ });++ it('says so when nothing matches', async () => {+ const r = await searchDocsTool.handler({ query: 'zzqxv qqwwzz' }, {}, undefined);+ expect(r.structuredContent.count).toBe(0);+ expect(r.isError).toBeUndefined();+ });+});diff --git a/tests/mcp-studio.test.js b/tests/mcp-studio.test.jsindex 25ccd9421..8bc2ce922 100644--- a/tests/mcp-studio.test.js+++ b/tests/mcp-studio.test.js@@ -21,7 +21,9 @@ const CATALOG = ['search_catalog', 'get_catalog_item', 'get_item_source'];// get_job, the agent-facing job status tool, rides beside the catalog tools on// the full surface and is not one of the eleven the ChatGPT listing carries.const JOB = ['get_job'];-const ALL = [...ALLOWED, ...JOB, ...CATALOG, ...PERSONA];+// search_docs answers how-to questions from the documentation index, free.+const DOCS = ['search_docs'];+const ALL = [...ALLOWED, ...JOB, ...CATALOG, ...DOCS, ...PERSONA];// Anything that would signal a crypto / payment surface. The whole point of the// free studio app is that NONE of this appears anywhere in its contract — the@@ -604,7 +606,7 @@ describe('mcp-studio dispatch', () => {// handler, same schema) and hold the studio's no-payment-vocabulary bar.describe('mcp-studio asset catalog tools', () => {it('serves the main server catalog tools with their own handlers and schemas', () => {- expect(CATALOG_TOOL_CATALOG.map((t) => t.name)).toEqual(CATALOG);+ expect(CATALOG_TOOL_CATALOG.map((t) => t.name)).toEqual([...CATALOG, ...DOCS]);for (const name of CATALOG) {const lib = LIBRARY_TOOLS.find((d) => d.name === name);const studio = CATALOG_TOOL_CATALOG.find((t) => t.name === name);