Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(mcp-studio): get_job, idempotency_key and progress notifications so agent retries never generate twice

nirholas1396f114692c
diff --git a/api/_mcp-studio/dispatch.js b/api/_mcp-studio/dispatch.js
index cefeb09bc..92ef83261 100644
--- a/api/_mcp-studio/dispatch.js
+++ b/api/_mcp-studio/dispatch.js
@@ -12,6 +12,7 @@ import { sanitizeToolError } from '../_lib/mcp-error-sanitize.js';
import { TOOL_CATALOG, TOOLS } from './tools.js';
import { PERSONA_TOOL_CATALOG, PERSONA_TOOLS } from './persona-tools.js';
import { CATALOG_TOOL_CATALOG, CATALOG_TOOLS } from './catalog-tools.js';
+import { JOB_TOOL_CATALOG, JOB_TOOLS } from './job-tools.js';
import { finishCall, gateCall, listForRequest } from '../_mcp/policy.js';
// The @three-ws/mcp-policy server id for the free studio.
@@ -64,8 +65,9 @@ const GROK_INSTRUCTIONS = [
'Nothing renders inline in Grok, so always give the user the viewerUrl (an interactive 3D viewer that opens in any',
'browser) and the glbUrl (the downloadable model); poster_png_url is a picture of it to attach or show, and',
'embed_html puts it on a web page. A pending result is normal: wait the suggested seconds, then call',
- 'check_job(job_id) again until it is done, and keep going without asking the user; a Grok Bot task should finish',
- 'with the finished model, not the pending handle. To give yourself a body, forge_avatar a character, then',
+ 'get_job(job_id) again until it is done, and keep going without asking the user; a Grok Bot task should finish',
+ 'with the finished model, not the pending handle. On a scheduled or retried task, pass the same idempotency_key',
+ '(the task id works) so a retry picks up the model the first run started. To give yourself a body, forge_avatar a character, then',
'create_agent_persona(glb_url, name) and share its embed_url; persona_say makes that body speak your reply and',
'returns an embed_url that plays it.',
];
@@ -80,6 +82,14 @@ const CATALOG_INSTRUCTIONS = [
'match. Say whether you used an existing asset or generated a new one.',
];
+// The full and Grok surfaces list get_job (./job-tools.js); the ChatGPT one
+// collects jobs through its inline viewer instead.
+const JOB_INSTRUCTIONS = [
+ 'Every generation tool takes an optional idempotency_key: calling again with the same key within 24 hours returns',
+ 'the first call\'s job instead of generating twice, so set one whenever a call might be retried. get_job(job_id)',
+ 'reports status, progress and eta_seconds for a pending job, and the model links once it is done.',
+];
+
const PERSONA_INSTRUCTIONS = [
'To give the assistant a LIVING body: create_agent_persona(glb_url, name) saves a rigged model as a named,',
'persistent persona and returns a persona_id; persona_say(persona_id, text) makes that body lip-sync the reply and',
@@ -106,16 +116,17 @@ const PERSONA_INSTRUCTIONS = [
// hand out links in place of the widgets Grok does not render.
// ./handler.js keys its generation caps on the MCP session, because
// every Grok user reaches us from xAI's shared egress.
-// check_job and the persona tools stay out of the generation quota on both; see
+// check_job, get_job and the persona tools stay out of the generation quota; see
// ./handler.js callsGenerationTool. look_at_model renders frames server-side, so
// it rides that quota.
const SURFACES = {
full: {
server: 'mcp-studio',
- catalog: [...TOOL_CATALOG, ...CATALOG_TOOL_CATALOG, ...PERSONA_TOOL_CATALOG],
- tools: { ...TOOLS, ...CATALOG_TOOLS, ...PERSONA_TOOLS },
+ catalog: [...TOOL_CATALOG, ...JOB_TOOL_CATALOG, ...CATALOG_TOOL_CATALOG, ...PERSONA_TOOL_CATALOG],
+ tools: { ...TOOLS, ...JOB_TOOLS, ...CATALOG_TOOLS, ...PERSONA_TOOLS },
personas: true,
- instructions: [...BASE_INSTRUCTIONS, ...CATALOG_INSTRUCTIONS, ...PERSONA_INSTRUCTIONS].join(' '),
+ jobTool: 'get_job',
+ instructions: [...BASE_INSTRUCTIONS, ...JOB_INSTRUCTIONS, ...CATALOG_INSTRUCTIONS, ...PERSONA_INSTRUCTIONS].join(' '),
},
chatgpt: {
server: 'mcp-chatgpt',
@@ -127,10 +138,17 @@ const SURFACES = {
},
grok: {
server: 'mcp-grok',
- catalog: [...TOOL_CATALOG, ...CATALOG_TOOL_CATALOG, ...PERSONA_TOOL_CATALOG],
- tools: { ...TOOLS, ...CATALOG_TOOLS, ...PERSONA_TOOLS },
+ catalog: [...TOOL_CATALOG, ...JOB_TOOL_CATALOG, ...CATALOG_TOOL_CATALOG, ...PERSONA_TOOL_CATALOG],
+ tools: { ...TOOLS, ...JOB_TOOLS, ...CATALOG_TOOLS, ...PERSONA_TOOLS },
personas: true,
- instructions: [...BASE_INSTRUCTIONS, ...CATALOG_INSTRUCTIONS, ...PERSONA_INSTRUCTIONS, ...GROK_INSTRUCTIONS].join(' '),
+ jobTool: 'get_job',
+ instructions: [
+ ...BASE_INSTRUCTIONS,
+ ...JOB_INSTRUCTIONS,
+ ...CATALOG_INSTRUCTIONS,
+ ...PERSONA_INSTRUCTIONS,
+ ...GROK_INSTRUCTIONS,
+ ].join(' '),
callBudgetMs: GROK_CALL_BUDGET_MS,
},
};
@@ -207,7 +225,10 @@ function summarize(args) {
return o;
}
-async function onToolCall(params, auth, started, req, surface) {
+// `opts.caller` is who the studio's limits charge on this request (./handler.js
+// studioCaller), and an idempotency_key belongs to it; `opts.onProgress`
+// receives status frames when the client asked for progress notifications.
+async function onToolCall(params, auth, started, req, surface, opts = {}) {
const { name, arguments: args = {} } = params || {};
const tool = typeof name === 'string' && Object.hasOwn(surface.tools, name) ? surface.tools[name] : null;
if (!tool) throw rpcError(-32602, `unknown tool: ${name}`);
@@ -220,7 +241,12 @@ async function onToolCall(params, auth, started, req, surface) {
throw rpcError(-32602, `invalid params for ${name}: ${detail}`);
}
try {
- const ctx = surface.callBudgetMs ? { deadline: started + surface.callBudgetMs } : {};
+ const ctx = {
+ ...(surface.callBudgetMs ? { deadline: started + surface.callBudgetMs } : {}),
+ jobTool: surface.jobTool || 'check_job',
+ ...(opts.caller ? { caller: opts.caller } : {}),
+ ...(opts.onProgress ? { onProgress: opts.onProgress } : {}),
+ };
const result = await tool.handler(args, auth, req, ctx);
recordEvent({ kind: 'tool_call', tool: name, latencyMs: Date.now() - started, meta: { args_summary: summarize(args), server: surface.server } });
return await finishCall(POLICY_SERVER, name, sentArgs, auth, result, gate.preview);
@@ -232,7 +258,7 @@ async function onToolCall(params, auth, started, req, surface) {
}
}
-export async function dispatch(msg, auth, req, { surface: surfaceName = 'full' } = {}) {
+export async function dispatch(msg, auth, req, { surface: surfaceName = 'full', caller = null, onProgress = null } = {}) {
const surface = surfaceOf(surfaceName);
const started = Date.now();
const id = msg.id;
@@ -252,7 +278,7 @@ export async function dispatch(msg, auth, req, { surface: surfaceName = 'full' }
if (method === 'ping') return ok(id, {});
if (method === 'notifications/initialized') return null;
if (method === 'tools/list') return ok(id, { tools: await listForRequest(POLICY_SERVER, surface.catalog, auth, req) });
- if (method === 'tools/call') return ok(id, await onToolCall(msg.params, auth, started, req, surface));
+ if (method === 'tools/call') return ok(id, await onToolCall(msg.params, auth, started, req, surface, { caller, onProgress }));
if (method === 'resources/list') {
return ok(id, { resources: widgetResources(surface.personas).map(({ text: _t, ...r }) => r) });
}
diff --git a/api/_mcp-studio/gpt-forge-client.js b/api/_mcp-studio/gpt-forge-client.js
index e77cc2ca0..8326da519 100644
--- a/api/_mcp-studio/gpt-forge-client.js
+++ b/api/_mcp-studio/gpt-forge-client.js
@@ -124,9 +124,11 @@ function internalHeaders() {
// ../_lib/forge-submit-ticket.js). If the submit is still running at the
// deadline, it resolves to the ticket's handle, `{ status: 'submitting',
// job_id: 't1.…' }`, instead of a timeout: the server records the job under the
-// ticket when it lands, and polling that handle collects it.
-export async function startForge(base, { prompt, imageUrls, aspect, backend, path, tier, internal, director, strictTier = false }, { deadline } = {}) {
- const ticket = deadline ? newTicket() : null;
+// ticket when it lands, and polling that handle collects it. A caller that
+// needs the handle before the submit leaves (an idempotent call records it
+// first) passes its own `ticket`; a ticketed submit is never sent twice.
+export async function startForge(base, { prompt, imageUrls, aspect, backend, path, tier, internal, director, strictTier = false }, { deadline, ticket: givenTicket } = {}) {
+ const ticket = givenTicket || (deadline ? newTicket() : null);
const attempt = async (tierId, withInternal) => {
const payload = {
...(prompt ? { prompt } : {}),
@@ -190,16 +192,19 @@ export async function startForge(base, { prompt, imageUrls, aspect, backend, pat
return data;
}
-export async function startRig(base, glbUrl, { deadline } = {}) {
+// `ticket` works as it does for startForge: a rig submit that outlives its
+// window resolves to the ticket's handle instead of a timeout.
+export async function startRig(base, glbUrl, { deadline, ticket } = {}) {
let res;
try {
res = await fetch(`${base}/api/gpt-forge?action=rig`, {
method: 'POST',
- headers: { 'content-type': 'application/json' },
+ headers: { 'content-type': 'application/json', ...(ticket ? { [TICKET_HEADER]: ticket } : {}) },
body: JSON.stringify({ glb_url: glbUrl }),
- signal: AbortSignal.timeout(submitWindow(deadline, RIG_SUBMIT_TIMEOUT_MS)),
+ signal: AbortSignal.timeout(submitWindow(deadline, RIG_SUBMIT_TIMEOUT_MS, ticket ? TICKET_SUBMIT_FLOOR_MS : SUBMIT_FLOOR_MS)),
});
} catch (err) {
+ if (ticket && (err?.name === 'TimeoutError' || err?.name === 'AbortError')) return { status: 'submitting', job_id: ticketHandle(ticket) };
if (err?.name === 'TimeoutError' || err?.name === 'AbortError')
throw failure('timeout', 'the rigger took too long to accept the job; try again');
throw failure('provider_error', `the rigger is unreachable: ${err?.message || err}`);
@@ -214,8 +219,9 @@ export async function startRig(base, glbUrl, { deadline } = {}) {
// Poll a /api/gpt-forge job to a terminal state. Returns the done payload, throws a
// coded failure on a failed job, or returns { _timedOut: true } at the deadline.
// `deadline` (epoch ms) caps the wait below timeoutMs when the caller's own call
-// budget ends sooner; no probe or sleep is allowed to run past it.
-export async function pollJob(base, jobId, { timeoutMs, intervalMs, deadline: callDeadline } = {}) {
+// budget ends sooner; no probe or sleep is allowed to run past it. `onFrame`
+// sees every status frame the server answers (progress notifications ride it).
+export async function pollJob(base, jobId, { timeoutMs, intervalMs, deadline: callDeadline, onFrame } = {}) {
const tMs = timeoutMs || DEFAULT_TIMEOUT_MS;
const deadline = Math.min(Date.now() + tMs, callDeadline || Infinity);
const left = () => deadline - Date.now();
@@ -255,6 +261,7 @@ export async function pollJob(base, jobId, { timeoutMs, intervalMs, deadline: ca
if (!res.ok) throw failure('provider_error', data?.message || `generation poll returned ${res.status}`);
softFails = 0;
last = data;
+ onFrame?.(data);
if (data.status === 'done' && data.glb_url) return data;
if (data.status === 'failed') {
throw failure('generation_failed', data.error || 'generation failed', {
@@ -302,25 +309,35 @@ export async function pollOnce(base, jobId) {
// Run a submit→poll cycle end to end, returning the terminal job payload.
// A timed-out payload keeps `job_id` so the caller can hand the (still
// running) job back to the client as a pollable handle instead of an error.
-export async function generate(base, submitArgs, { timeoutEnv, deadline } = {}) {
- const job = await startForge(base, submitArgs, { deadline });
+// `onSubmitted(jobId)` fires once the submit has a handle (an idempotent call
+// records it), and `onFrame` sees every status frame along the way.
+export async function generate(base, submitArgs, { timeoutEnv, deadline, ticket, onSubmitted, onFrame } = {}) {
+ const job = await startForge(base, submitArgs, { deadline, ticket });
+ if (job.job_id) await onSubmitted?.(job.job_id);
if (job.status === 'done' && job.glb_url) return job;
- // The submit outlived the call budget: its ticket handle is the job id.
- if (job.status === 'submitting') return { _timedOut: true, job_id: job.job_id };
+ // The submit outlived the call budget: its ticket handle is the job id, and
+ // the frame says the request is still being accepted.
+ if (job.status === 'submitting') return { _timedOut: true, job_id: job.job_id, status: 'queued', stage: 'submit' };
+ onFrame?.(job);
const out = await pollJob(base, job.job_id, {
timeoutMs: timeoutEnv ? envNum(timeoutEnv, DEFAULT_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS,
intervalMs: envNum('STUDIO_POLL_MS', DEFAULT_POLL_MS),
deadline,
+ onFrame,
});
return out._timedOut ? { ...out, job_id: job.job_id } : out;
}
-export async function rig(base, glbUrl, { timeoutEnv, deadline } = {}) {
- const job = await startRig(base, glbUrl, { deadline });
+export async function rig(base, glbUrl, { timeoutEnv, deadline, ticket, onSubmitted, onFrame } = {}) {
+ const job = await startRig(base, glbUrl, { deadline, ticket });
+ await onSubmitted?.(job.job_id);
+ if (job.status === 'submitting') return { _timedOut: true, job_id: job.job_id, status: 'queued', stage: 'submit' };
+ onFrame?.(job);
const out = await pollJob(base, job.job_id, {
timeoutMs: timeoutEnv ? envNum(timeoutEnv, DEFAULT_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS,
intervalMs: envNum('STUDIO_POLL_MS', DEFAULT_POLL_MS),
deadline,
+ onFrame,
});
return out._timedOut ? { ...out, job_id: job.job_id } : out;
}
diff --git a/api/_mcp-studio/handler.js b/api/_mcp-studio/handler.js
index 9e1bec162..ca193d982 100644
--- a/api/_mcp-studio/handler.js
+++ b/api/_mcp-studio/handler.js
@@ -1,6 +1,9 @@
// Shared HTTP handler for the free three.ws 3D Studio MCP surfaces.
//
-// POST JSON-RPC (initialize, tools/list, tools/call, resources/*)
+// POST JSON-RPC (initialize, tools/list, tools/call, resources/*). A single
+// tools/call that carries `_meta.progressToken`, from a client that
+// accepts text/event-stream, is answered as an SSE stream: progress
+// notifications while the job runs, then the result.
// GET not offered (no server-initiated stream), answers 405
// OPTIONS CORS preflight
//
@@ -29,6 +32,7 @@ import { cors, wrap, readJson, rateLimited, setRateLimitHeaders } from '../_lib/
import { limits, clientIp, STUDIO_LIMITS } from '../_lib/rate-limit.js';
import { dispatch, PROTOCOL_VERSION } from './dispatch.js';
import { TOOL_NAMES } from './tools.js';
+import { isIdempotentRepeat, progressReporter } from './jobs.js';
import { installTokenFrom, studioOrigin, INSTALL_PARAM } from './install-token.js';
// check_job collects a job that is already running rather than starting one: it
@@ -48,6 +52,50 @@ function rpcError(res, status, code, message, extra = {}) {
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code, message, ...(Object.keys(extra).length ? { data: extra } : {}) } }));
}
+// The progress token a single tools/call asked to be updated on, or null. A
+// batch is answered as one JSON array, so it never streams.
+export function progressTokenOf(body) {
+ if (!body || Array.isArray(body) || body.method !== 'tools/call') return null;
+ const token = body.params?._meta?.progressToken;
+ return (typeof token === 'string' && token.length > 0 && token.length <= 256) || Number.isInteger(token) ? token : null;
+}
+
+function acceptsEventStream(req) {
+ return /\btext\/event-stream\b/i.test(String(req?.headers?.accept || ''));
+}
+
+// An idle proxy can close a quiet stream between status frames (a submit can run
+// 40 s before the first one), so a comment line goes out this often.
+const SSE_KEEPALIVE_MS = 15_000;
+
+// Answer one tools/call as a Streamable HTTP SSE response: each status frame of
+// the job becomes a notifications/progress message (./jobs.js
+// progressReporter), and the JSON-RPC result is the last event.
+async function streamToolCall(res, msg, auth, req, { surface, caller, token }) {
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/event-stream; charset=utf-8');
+ res.setHeader('cache-control', 'no-cache, no-transform');
+ res.setHeader('x-accel-buffering', 'no');
+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);
+ res.flushHeaders?.();
+ const send = (message) => {
+ if (!res.writableEnded) res.write(`event: message\ndata: ${JSON.stringify(message)}\n\n`);
+ };
+ const keepAlive = setInterval(() => {
+ if (!res.writableEnded) res.write(': keep-alive\n\n');
+ }, SSE_KEEPALIVE_MS);
+ keepAlive.unref?.();
+ try {
+ const report = progressReporter(token, send);
+ report({ status: 'queued', stage: 'submit' }, 'request');
+ const response = await dispatch(msg, auth, req, { surface, caller, onProgress: report });
+ if (response !== null) send(response);
+ } finally {
+ clearInterval(keepAlive);
+ res.end();
+ }
+}
+
// Does the (possibly batched) body invoke any generation tool? Used to apply the
// cost-bearing generation quota only to calls that actually generate.
function callsGenerationTool(body) {
@@ -55,6 +103,16 @@ function callsGenerationTool(body) {
return batch.some((m) => m && m.method === 'tools/call' && isGenerationTool(m?.params?.name));
}
+// Is every generation call in the body a repeat of an idempotency_key its
+// caller already used? Those return the first call's job and start nothing, so
+// a scheduled agent's retry never spends its generation quota.
+async function onlyRepeats(body, caller) {
+ const batch = Array.isArray(body) ? body : [body];
+ const calls = batch.filter((m) => m && m.method === 'tools/call' && isGenerationTool(m?.params?.name));
+ const repeats = await Promise.all(calls.map((m) => isIdempotentRepeat(m, caller)));
+ return repeats.every(Boolean);
+}
+
// ChatGPT sends an anonymized, per-user `openai/subject` on every tool call and
// documents it for rate limiting. All ChatGPT traffic shares OpenAI's egress
// IPs, so on that surface the per-caller caps key on it. Bounded to a sane
@@ -258,12 +316,15 @@ export function studioHandler({ surface = 'full' } = {}) {
const batch = Array.isArray(body) ? body : [body];
if (batch.length > 16) return rpcError(res, 400, -32600, 'batch too large (max 16)');
+ // Who this request is: the key the per-caller caps charge, and the owner of
+ // any idempotency_key it sends (./jobs.js).
+ const caller = studioCaller(surface, body, req, ip, install);
+
// Generation quota, burst then hourly, per caller. Applied only when the
// request actually calls a generation tool, so discovery is never throttled
// by it. A denial is a JSON-RPC error on HTTP 200: an MCP client hands that
// message to the model, where a 429 body is often dropped by the transport.
- if (callsGenerationTool(body)) {
- const caller = studioCaller(surface, body, req, ip, install);
+ if (callsGenerationTool(body) && !(await onlyRepeats(body, caller.key))) {
const deny = (bucket, result) =>
rpcDenial(res, body, studioDenial({ bucket, kind: caller.kind, result, surfacePath }), result);
// Any caller key other than the IP is one the client chose, so one source
@@ -286,9 +347,14 @@ export function studioHandler({ surface = 'full' } = {}) {
// Anonymous principal, no auth, no scope. rateKey carries the IP for usage logs.
const auth = { userId: null, rateKey: ip, scope: '' };
+ const token = progressTokenOf(body);
+ if (token !== null && acceptsEventStream(req)) {
+ return streamToolCall(res, body, auth, req, { surface, caller: caller.key, token });
+ }
+
const responses = [];
for (const msg of batch) {
- const r = await dispatch(msg, auth, req, { surface });
+ const r = await dispatch(msg, auth, req, { surface, caller: caller.key });
if (r !== null) responses.push(r);
}
diff --git a/api/_mcp-studio/job-tools.js b/api/_mcp-studio/job-tools.js
new file mode 100644
index 000000000..3b5a02a0e
--- /dev/null
+++ b/api/_mcp-studio/job-tools.js
@@ -0,0 +1,73 @@
+// three.ws 3D Studio (free): get_job, the job status tool for agents.
+//
+// A generation that outlives its tool call comes back as a job_id. get_job
+// reads that job any time, as often as needed: status (pending, done, failed),
+// phase, progress (0 to 1), eta_seconds and elapsed_seconds while it runs; the
+// four asset links (viewer_url, glb_url, poster_png_url, embed_html) once it is
+// done; and a plain reason plus a remedy if it failed. It answers from the same
+// core as check_job (./tools.js collectJob), so the two always agree.
+//
+// It is listed on the full and Grok surfaces, beside the catalog tools, and
+// not on the ChatGPT listing, whose inline viewer collects jobs through
+// check_job by itself. Never counted against the generation quota
+// (./handler.js isGenerationTool).
+
+import Ajv from 'ajv';
+import addFormats from 'ajv-formats';
+import { collectJob, toolError } from './tools.js';
+import { originFromReq } from './gpt-forge-client.js';
+
+async function handleGetJob(args, _auth, req, ctx = {}) {
+ const jobId = String(args.job_id || '').trim();
+ if (!jobId) return toolError('Provide the job_id a generation returned.');
+ return collectJob(originFromReq(req), jobId, args.refine ? { refine: args.refine } : {}, { jobTool: ctx.jobTool || 'get_job' });
+}
+
+const DEFS = [
+ {
+ name: 'get_job',
+ title: 'Get a 3D generation job',
+ description:
+ 'Status of a 3D generation job. Pass the job_id any generation tool returned with status "pending". ' +
+ 'Returns status (pending, done or failed), phase, progress from 0 to 1, eta_seconds and elapsed_seconds ' +
+ 'while it runs; when done, the model with its viewer_url, glb_url, poster_png_url and embed_html; when ' +
+ 'failed, the reason and what to do next. Call it as often as you like: it never starts or repeats a ' +
+ 'generation. Between calls, wait about the eta_seconds it reports, or 15 seconds when it reports none.',
+ inputSchema: {
+ type: 'object',
+ additionalProperties: false,
+ required: ['job_id'],
+ properties: {
+ job_id: {
+ type: 'string',
+ minLength: 8,
+ maxLength: 4096,
+ description: 'The job_id (or jobId) a generation tool returned.',
+ },
+ refine: {
+ type: 'object',
+ additionalProperties: true,
+ description:
+ 'Optional: the refine object a pending refine_model result carried, passed back unchanged so the ' +
+ 'finished model joins that version history.',
+ },
+ },
+ },
+ annotations: {
+ readOnlyHint: false, // the first check of a finished job saves the model
+ destructiveHint: false,
+ idempotentHint: true, // it never starts a generation
+ openWorldHint: true,
+ },
+ handler: handleGetJob,
+ },
+];
+
+export const JOB_TOOL_CATALOG = DEFS.map(({ handler: _h, ...schema }) => schema);
+
+const ajv = new Ajv({ allErrors: true, useDefaults: true, coerceTypes: true, strict: false });
+addFormats(ajv);
+
+export const JOB_TOOLS = Object.fromEntries(
+ DEFS.map(({ name, handler, inputSchema }) => [name, { handler, validate: ajv.compile(inputSchema) }]),
+);
diff --git a/api/_mcp-studio/jobs.js b/api/_mcp-studio/jobs.js
new file mode 100644
index 000000000..8f7a73186
--- /dev/null
+++ b/api/_mcp-studio/jobs.js
@@ -0,0 +1,280 @@
+// three.ws 3D Studio (free): jobs an agent can trust across retries.
+//
+// A text-to-3D job can outlast one tool call, and a scheduled agent (Grok Bot,
+// a cron, a CI step) retries a call that timed out. Three pieces make that safe:
+//
+// jobFields one status vocabulary for every job result: status,
+// progress, eta_seconds, elapsed_seconds. get_job and
+// check_job return it, and so does every pending result.
+// withIdempotency a generation tool called with `idempotency_key` runs once
+// per caller and key for 24 hours. A repeat gets the first
+// call's job (its current state, or the finished model)
+// instead of starting a second generation. The record lives
+// in the shared store the HTTP `Idempotency-Key` uses
+// (../_lib/idempotency.js).
+// progressReporter turns status frames into MCP `notifications/progress` for
+// a client that sent a progressToken (./handler.js streams
+// them).
+//
+// The caller is who the studio's rate limits charge (./handler.js
+// studioCaller): an install token, a ChatGPT user, a Grok MCP session, else the
+// IP. A different caller with the same key gets its own job.
+
+import {
+ claimIdempotent,
+ fingerprint,
+ IDEMPOTENCY_KEY_MAX,
+ idempotencyStoreKey,
+ normalizeIdempotencyKey,
+ readIdempotent,
+ releaseIdempotent,
+ sha256Hex,
+ writeIdempotent,
+} from '../_lib/idempotency.js';
+import { newTicket, ticketHandle } from '../_lib/forge-submit-ticket.js';
+import { clientIp } from '../_lib/rate-limit.js';
+
+/** The optional argument every generation tool accepts. */
+export const IDEMPOTENCY_KEY_PROP = {
+ type: 'string',
+ minLength: 1,
+ maxLength: IDEMPOTENCY_KEY_MAX,
+ description:
+ 'Optional: any string you choose (up to 200 characters) that names this one generation, such as a task id. ' +
+ 'Calling again with the same key within 24 hours returns the original job instead of starting a new one, ' +
+ 'so a retry after a timeout never generates twice. Use a new key for a new model.',
+};
+
+// Past the lane's typical duration a job is late, not finished; progress holds
+// here until the frame says done rather than claiming a completion it lacks.
+const PROGRESS_CEILING = 0.95;
+
+function seconds(v) {
+ const n = Number(v);
+ return Number.isFinite(n) && n >= 0 ? Math.round(n) : null;
+}
+
+/**
+ * The status fields every job result carries, read off a /api/gpt-forge status
+ * frame. `progress` is 0 to 1, estimated from the job's elapsed time over its
+ * lane's typical duration (null when the server reports neither); `eta_seconds`
+ * is the time the server expects is left, absent once a job runs past its
+ * estimate.
+ * @param {object} frame
+ */
+export function jobFields(frame = {}) {
+ const raw = String(frame?.status || '');
+ const status = raw === 'done' ? 'done' : raw === 'failed' ? 'failed' : 'pending';
+ // queued (waiting for a worker or a container boot), submitting (the request
+ // is still being accepted), running (rendering), or the terminal status.
+ const phase = status !== 'pending' ? status : frame?.stage === 'submit' ? 'submitting' : raw === 'queued' ? 'queued' : 'running';
+ const elapsed = seconds(frame?.elapsed_seconds);
+ const typical = seconds(frame?.eta_seconds);
+ const remaining = seconds(frame?.eta_remaining_seconds);
+ let progress = null;
+ if (status === 'done') progress = 1;
+ else if (status === 'pending' && elapsed != null && typical) progress = Math.min(PROGRESS_CEILING, Math.round((elapsed / typical) * 100) / 100);
+ return {
+ status,
+ phase,
+ progress,
+ eta_seconds: status === 'pending' ? remaining : status === 'done' ? 0 : null,
+ elapsed_seconds: elapsed,
+ };
+}
+
+/**
+ * A function that turns status frames into `notifications/progress` messages
+ * and hands each to `send`. `progress` is the seconds this call has run, so it
+ * always increases across stages (a rig job's clock restarts; this one does
+ * not); `total` is that plus the server's remaining estimate when it has one.
+ * @param {string|number} progressToken
+ * @param {(notification: object) => void} send
+ */
+export function progressReporter(progressToken, send, now = () => Date.now()) {
+ const started = now();
+ let last = -1;
+ return function report(frame = {}, label = '') {
+ const progress = Math.round((now() - started) / 100) / 10;
+ if (!(progress > last)) return;
+ last = progress;
+ const f = jobFields(frame);
+ const total = f.eta_seconds ? Math.round((progress + f.eta_seconds) * 10) / 10 : null;
+ send({
+ jsonrpc: '2.0',
+ method: 'notifications/progress',
+ params: { progressToken, progress, ...(total ? { total } : {}), message: progressMessage(f, label) },
+ });
+ };
+}
+
+function progressMessage(f, label) {
+ const what = label || 'job';
+ if (f.phase === 'submitting') return `Submitting the ${what}.`;
+ if (f.phase === 'queued') return `The ${what} is queued; the GPU worker is picking it up.`;
+ if (f.phase === 'done') return `The ${what} is done.`;
+ const eta = f.eta_seconds ? `, about ${f.eta_seconds}s left` : '';
+ const pct = f.progress != null ? ` (${Math.round(f.progress * 100)}%)` : '';
+ return `Rendering the ${what}${pct}${eta}.`;
+}
+
+/** Who an idempotency key belongs to on this call. */
+export function idempotencyCaller(auth, req, ctx = {}) {
+ if (ctx.caller) return ctx.caller;
+ if (auth?.userId) return `user:${auth.userId}`;
+ return `ip:${clientIp(req)}`;
+}
+
+// The caller is hashed too: it can be an IP or an install token id, and
+// neither belongs in a key listing.
+function studioStoreKey(caller, key) {
+ return idempotencyStoreKey('mcp-studio', sha256Hex(caller).slice(0, 32), key);
+}
+
+/**
+ * Is this tools/call a repeat of a key its caller already used? A repeat never
+ * starts a generation, so ./handler.js does not charge it to the generation
+ * quota.
+ * @param {object} msg a JSON-RPC message
+ * @param {string} caller
+ */
+export async function isIdempotentRepeat(msg, caller) {
+ let key;
+ try {
+ key = normalizeIdempotencyKey(msg?.params?.arguments?.idempotency_key);
+ } catch {
+ return false;
+ }
+ if (!key || !caller) return false;
+ return Boolean(await readIdempotent(studioStoreKey(caller, key)));
+}
+
+function reusedKey(tool) {
+ const message =
+ `This idempotency_key was already used with different arguments (by ${tool}). ` +
+ 'Keys name one generation: use a new key for a new request.';
+ return {
+ content: [{ type: 'text', text: message }],
+ structuredContent: { error: true, message, reason: 'idempotency_key_reused', status: 'failed' },
+ isError: true,
+ };
+}
+
+function withKeyFields(result, key, replayed) {
+ if (!result || typeof result !== 'object') return result;
+ const sc = result.structuredContent && typeof result.structuredContent === 'object' ? result.structuredContent : {};
+ const out = { ...result, structuredContent: { ...sc, idempotency_key: key, idempotent_replay: replayed } };
+ if (replayed && Array.isArray(result.content) && result.content[0]?.type === 'text') {
+ out.content = [
+ {
+ ...result.content[0],
+ text:
+ 'Same idempotency_key as an earlier call: this is that call\'s job, and nothing new was started.\n' +
+ result.content[0].text,
+ },
+ ...result.content.slice(1),
+ ];
+ }
+ return out;
+}
+
+/**
+ * Make a generation handler idempotent on `args.idempotency_key`.
+ *
+ * The first call claims the key together with a submit ticket's handle in one
+ * atomic write, before anything is submitted, so a repeat that arrives a
+ * millisecond later already has a job id to follow. The handler reports each
+ * job it submits through `ctx.onJob(jobId, shape)`; `shape` says how to render
+ * that job when it finishes (kind, prompt, rigged, refine lineage). When the
+ * call ends the record keeps its outcome: the finished result, the pending
+ * job, or the failure. A call that never got a job accepted (a refused prompt,
+ * a busy generator) gives the key back, so retrying it can still run.
+ *
+ * `replay(record, { save, release, req, ctx })` renders a repeat from the record.
+ *
+ * @param {string} tool
+ * @param {(args: object, auth: object, req: object, ctx: object) => Promise<object>} handler
+ * @param {{ replay: (record: object, opts: object) => Promise<object> }} opts
+ */
+export function withIdempotency(tool, handler, { replay }) {
+ return async function idempotent(args = {}, auth, req, ctx = {}) {
+ const { idempotency_key: rawKey, ...rest } = args || {};
+ let key;
+ try {
+ key = normalizeIdempotencyKey(rawKey);
+ } catch (err) {
+ return invalidKey(err.message);
+ }
+ if (!key) return handler(rest, auth, req, ctx);
+
+ const storeKey = studioStoreKey(idempotencyCaller(auth, req, ctx), key);
+ const print = fingerprint({ tool, args: rest });
+ const ticket = newTicket();
+ const first = {
+ v: 1,
+ tool,
+ fingerprint: print,
+ state: 'running',
+ job_id: ticketHandle(ticket),
+ accepted: false,
+ shape: {},
+ created_at: new Date().toISOString(),
+ };
+ // Two tries: a record can expire between a lost claim and the read.
+ for (let attempt = 0; attempt < 2; attempt++) {
+ if (await claimIdempotent(storeKey, first)) return runClaimed();
+ const prior = await readIdempotent(storeKey);
+ if (!prior) continue;
+ if (prior.fingerprint !== print) return reusedKey(prior.tool || tool);
+ const save = (patch) => writeIdempotent(storeKey, { ...prior, ...patch }).catch(() => {});
+ const release = () => releaseIdempotent(storeKey).catch(() => {});
+ return withKeyFields(await replay(prior, { save, release, req, ctx }), key, true);
+ }
+ // The store refused both ways: run the call rather than refuse it.
+ return withKeyFields(await handler(rest, auth, req, ctx), key, false);
+
+ async function runClaimed() {
+ let record = first;
+ const save = (patch) => {
+ record = { ...record, ...patch };
+ return writeIdempotent(storeKey, record).catch(() => {});
+ };
+ const onJob = (jobId, shape = {}) => save({ job_id: jobId, accepted: true, shape: { ...record.shape, ...shape } });
+ let result;
+ try {
+ result = await handler(rest, auth, req, { ...ctx, ticket, onJob });
+ } catch (err) {
+ if (!record.accepted) await releaseIdempotent(storeKey).catch(() => {});
+ throw err;
+ }
+ const sc = result?.structuredContent || {};
+ if (sc.status === 'pending' && sc.jobId) {
+ await save({ state: 'pending', job_id: sc.jobId, accepted: true });
+ } else if (result?.isError) {
+ if (record.accepted) await save({ state: 'failed', message: result.content?.[0]?.text || 'Generation failed.' });
+ else await releaseIdempotent(storeKey).catch(() => {});
+ } else {
+ result = stampDone(result, record.job_id);
+ await save({ state: 'done', result });
+ }
+ return withKeyFields(result, key, false);
+ }
+ };
+}
+
+// A finished keyed result names its job, so a repeat and the first call carry
+// the same job_id whichever state each of them saw.
+function stampDone(result, jobId) {
+ const sc = result?.structuredContent;
+ if (!sc || typeof sc !== 'object') return result;
+ return { ...result, structuredContent: { ...sc, status: sc.status || 'done', job_id: sc.job_id || jobId } };
+}
+
+function invalidKey(message) {
+ const text = `${message}. Shorten the idempotency_key.`;
+ return {
+ content: [{ type: 'text', text }],
+ structuredContent: { error: true, message: text, reason: 'invalid_idempotency_key' },
+ isError: true,
+ };
+}
diff --git a/api/_mcp-studio/tools.js b/api/_mcp-studio/tools.js
index 9b5ff5f6a..20dd82d7f 100644
--- a/api/_mcp-studio/tools.js
+++ b/api/_mcp-studio/tools.js
@@ -22,6 +22,9 @@
// Every model-bearing result also carries the four agent-first links from
// ./asset-links.js (viewer_url, glb_url, poster_png_url, embed_html), stated in
// the first lines of its text too, for clients that render no widget.
+// Every generation tool also takes an optional idempotency_key, and every job
+// result carries the shared status fields (status, progress, eta_seconds); see
+// ./jobs.js. collectJob below is the status core check_job and get_job share.
// Each tool links the Apps SDK widget via _meta["openai/outputTemplate"] and returns structuredContent
// the widget renders. No coin, token, wallet, or payment surface anywhere.
@@ -49,6 +52,8 @@ import {
} from './gpt-forge-client.js';
import { COMPONENT_URI } from './component.js';
import { assetLinks, assetLinksText } from './asset-links.js';
+import { IDEMPOTENCY_KEY_PROP, jobFields, withIdempotency } from './jobs.js';
+import { newTicket } from '../_lib/forge-submit-ticket.js';
import { renderTurntable, describeGeometry, fetchGeometryStats } from '../_lib/3d-vision.js';
import { buildSpatialArtifact } from '../_lib/spatial-mcp.js';
// The same pure cold-start core the browser surfaces render from
@@ -149,7 +154,7 @@ function ok({ glbUrl, base, kind, prompt, rigged, referenceImageUrl }) {
// `extra` carries machine-readable facts about the failure, such as
// `retryable: true` when the job is fine and only the check itself failed.
-function toolError(message, extra = {}) {
+export function toolError(message, extra = {}) {
return {
content: [{ type: 'text', text: message }],
structuredContent: { error: true, message, ...extra },
@@ -167,6 +172,7 @@ function pendingTiming(job) {
etaRemainingSeconds: job?.eta_remaining_seconds,
// null when the API is not reporting a boot on this frame.
cold: coldStartState(job || {}),
+ frame: job || {},
};
}
@@ -187,7 +193,11 @@ function pendingTiming(job) {
// model joins. A client hands it back to check_job, which appends the finished
// version the same way refine_model would have, so the version strip survives
// the wait.
-function pendingResult({ base, jobId, what, prompt, etaRemainingSeconds, stage = 'mesh', cold = null, next = null, refine = null }) {
+//
+// `frame` is the last status frame the job answered; it fills the shared job
+// fields (status, progress, eta_seconds) that get_job returns too. `jobTool`
+// names the status tool this surface lists.
+function pendingResult({ base, jobId, what, prompt, etaRemainingSeconds, stage = 'mesh', cold = null, next = null, refine = null, frame = {}, jobTool = 'check_job' }) {
// The ChatGPT pipeline's own endpoint, not /api/forge: the whole point of
// the clone is that this surface can evolve independently.
const pollUrl = `${base}/api/gpt-forge?job=${encodeURIComponent(jobId)}`;
@@ -226,15 +236,21 @@ function pendingResult({ base, jobId, what, prompt, etaRemainingSeconds, stage =
const retryIn = cold?.remainingSeconds ?? eta;
const message =
`${head}. ` +
- `It keeps running: call the check_job tool with this job_id${retryIn ? ` in ~${retryIn}s` : ' shortly'} to collect it, ` +
+ `It keeps running: call the ${jobTool} tool with this job_id${retryIn ? ` in ~${retryIn}s` : ' shortly'} to collect it, ` +
`or poll ${pollUrl} until status is "done", then use its glb_url ` +
`(view at ${base}/viewer?src=<glb_url>).\n` +
`Viewer (opens the model by itself the moment it is ready): ${watchUrl}`;
+ const fields = jobFields({ ...frame, status: frame?.status === 'queued' ? 'queued' : 'running' });
return {
content: [{ type: 'text', text: message }],
structuredContent: {
status: 'pending',
jobId,
+ job_id: jobId,
+ phase: fields.phase,
+ progress: fields.progress,
+ eta_seconds: eta,
+ elapsed_seconds: elapsed ?? fields.elapsed_seconds,
pollUrl,
viewer_url: watchUrl,
// Which half of the pipeline is still running. A client that collects
@@ -397,6 +413,18 @@ export function avatarFallbackBrief(prompt, subject) {
// over the already-directed brief. refine_model is the exception; it composes
// rather than directs, and keeps the server's pass.
+// What every submit passes besides its own arguments: an idempotent call's
+// submit ticket (first submit only; ./jobs.js holds its handle already) and job
+// tracking, and the progress stream when the client asked for one. `shape`
+// tells a later get_job how to render the finished job.
+function jobOpts(ctx, shape, { ticket = ctx.ticket } = {}) {
+ return {
+ ...(ticket ? { ticket } : {}),
+ ...(ctx.onJob ? { onSubmitted: (jobId) => ctx.onJob(jobId, shape) } : {}),
+ ...(ctx.onProgress ? { onFrame: (frame) => ctx.onProgress(frame, shape.what) } : {}),
+ };
+}
+
async function handleForgeFree(args, _auth, req, ctx = {}) {
const base = originFromReq(req);
const prompt = String(args.prompt || '').trim();
@@ -437,12 +465,12 @@ async function handleForgeFree(args, _auth, req, ctx = {}) {
markImageUrls
? { prompt: effective, imageUrls: markImageUrls, tier, internal: true, director: false }
: { prompt: effective, path: 'image', tier, internal: true, director: false },
- { timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS', deadline: ctx.deadline },
+ { timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS', deadline: ctx.deadline, ...jobOpts(ctx, { kind: 'model', what: 'model', prompt }) },
);
} catch (err) {
return toolError(failureMessage(err));
}
- if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'model', prompt, ...pendingTiming(job) });
+ if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'model', prompt, ...pendingTiming(job), jobTool: ctx.jobTool });
if (job._timedOut || !job.glb_url) return toolError('Generation is taking longer than expected. Please try again.');
return ok({ glbUrl: job.glb_url, base, kind: 'model', prompt, referenceImageUrl: job.preview_image_url });
}
@@ -475,12 +503,12 @@ async function handleTextToAvatar(args, _auth, req, ctx = {}) {
job = await generate(
base,
{ prompt: effective || undefined, imageUrls: imageUrl ? [imageUrl] : undefined, aspect: '1:1', tier: AVATAR_TIER, internal: true, director: false },
- { timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS', deadline: ctx.deadline },
+ { timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS', deadline: ctx.deadline, ...jobOpts(ctx, { kind: 'avatar', what: 'avatar', prompt: prompt || undefined }) },
);
} catch (err) {
return toolError(failureMessage(err));
}
- if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'avatar', prompt: prompt || undefined, ...pendingTiming(job) });
+ if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'avatar', prompt: prompt || undefined, ...pendingTiming(job), jobTool: ctx.jobTool });
if (job._timedOut || !job.glb_url) return toolError('Generation is taking longer than expected. Please try again.');
return ok({ glbUrl: job.glb_url, base, kind: 'avatar', prompt: prompt || undefined, referenceImageUrl: job.preview_image_url });
}
@@ -528,12 +556,12 @@ async function handleMeshForge(args, _auth, req, ctx = {}) {
internal: true,
director: false,
},
- { timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS', deadline: ctx.deadline },
+ { timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS', deadline: ctx.deadline, ...jobOpts(ctx, { kind: 'mesh', what: 'mesh', prompt: prompt || undefined }) },
);
} catch (err) {
return toolError(failureMessage(err));
}
- if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'mesh', prompt: prompt || undefined, ...pendingTiming(job) });
+ if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'mesh', prompt: prompt || undefined, ...pendingTiming(job), jobTool: ctx.jobTool });
if (job._timedOut || !job.glb_url) return toolError('Generation is taking longer than expected. Please try again.');
return ok({ glbUrl: job.glb_url, base, kind: 'mesh', prompt: prompt || undefined, referenceImageUrl: job.preview_image_url });
}
@@ -549,11 +577,15 @@ async function handleRigMesh(args, _auth, req, ctx = {}) {
}
let job;
try {
- job = await rig(base, glbUrl, { timeoutEnv: 'STUDIO_RIG_TIMEOUT_MS', deadline: ctx.deadline });
+ job = await rig(base, glbUrl, {
+ timeoutEnv: 'STUDIO_RIG_TIMEOUT_MS',
+ deadline: ctx.deadline,
+ ...jobOpts(ctx, { kind: 'rigged model', what: 'rigged model', rigged: true, stage: 'rig' }),
+ });
} catch (err) {
return toolError(failureMessage(err));
}
- if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'rigged model', ...pendingTiming(job), stage: 'rig' });
+ if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'rigged model', ...pendingTiming(job), stage: 'rig', jobTool: ctx.jobTool });
if (job._timedOut || !job.glb_url) return toolError('Rigging is taking longer than expected. Please try again.');
return ok({ glbUrl: job.glb_url, base, kind: 'rigged model', rigged: true });
}
@@ -589,18 +621,32 @@ async function handleForgeAvatar(args, _auth, req, ctx = {}) {
gen = await generate(
base,
{ prompt: effective || undefined, imageUrls: imageUrl ? [imageUrl] : undefined, aspect: '1:1', tier: AVATAR_TIER, internal: true, director: false },
- { timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS', deadline: ctx.deadline },
+ {
+ timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS',
+ deadline: ctx.deadline,
+ ...jobOpts(ctx, { kind: 'mesh', what: 'avatar mesh (rig it with rig_mesh once done)', prompt: prompt || undefined, stage: 'mesh', next: 'rig' }),
+ },
);
} catch (err) {
return toolError(failureMessage(err));
}
- if (gen._timedOut && gen.job_id) return pendingResult({ base, jobId: gen.job_id, what: 'avatar mesh (rig it with rig_mesh once done)', prompt: prompt || undefined, ...pendingTiming(gen), stage: 'mesh', next: 'rig' });
+ if (gen._timedOut && gen.job_id) return pendingResult({ base, jobId: gen.job_id, what: 'avatar mesh (rig it with rig_mesh once done)', prompt: prompt || undefined, ...pendingTiming(gen), stage: 'mesh', next: 'rig', jobTool: ctx.jobTool });
if (gen._timedOut || !gen.glb_url) return toolError('Generation is taking longer than expected. Please try again.');
// Stage 2 — auto-rig the generated mesh.
let rigged;
try {
- rigged = await rig(base, gen.glb_url, { timeoutEnv: 'STUDIO_RIG_TIMEOUT_MS', deadline: ctx.deadline });
+ // The rig is a second job, so an idempotent call gives it a ticket of its
+ // own and moves the key's record onto it.
+ rigged = await rig(base, gen.glb_url, {
+ timeoutEnv: 'STUDIO_RIG_TIMEOUT_MS',
+ deadline: ctx.deadline,
+ ...jobOpts(
+ ctx,
+ { kind: 'avatar', what: 'avatar rig', prompt: prompt || undefined, rigged: true, stage: 'rig', next: null },
+ { ticket: ctx.onJob ? newTicket() : undefined },
+ ),
+ });
} catch (err) {
// Generation succeeded but rigging failed: hand back the (unrigged) mesh so
// the work isn't lost, and say so plainly.
@@ -623,7 +669,7 @@ async function handleForgeAvatar(args, _auth, req, ctx = {}) {
],
};
}
- if (rigged._timedOut && rigged.job_id) return pendingResult({ base, jobId: rigged.job_id, what: 'avatar rig', prompt: prompt || undefined, ...pendingTiming(rigged), stage: 'rig' });
+ if (rigged._timedOut && rigged.job_id) return pendingResult({ base, jobId: rigged.job_id, what: 'avatar rig', prompt: prompt || undefined, ...pendingTiming(rigged), stage: 'rig', jobTool: ctx.jobTool });
if (rigged._timedOut || !rigged.glb_url) return toolError('Rigging is taking longer than expected. Please try again.');
return ok({ glbUrl: rigged.glb_url, base, kind: 'avatar', prompt: prompt || undefined, rigged: true, referenceImageUrl: gen.preview_image_url });
}
@@ -700,6 +746,12 @@ async function handleRefineModel(args, _auth, req, ctx = {}) {
}
}
+ const refine = {
+ lineage: baseLineage,
+ instruction,
+ refKind: refImageUrl ? 'image' : 'text',
+ ...(parentIndex !== undefined ? { parentIndex } : {}),
+ };
let job;
try {
job = await generate(
@@ -707,7 +759,11 @@ async function handleRefineModel(args, _auth, req, ctx = {}) {
refImageUrl
? { prompt: composed, imageUrls: [refImageUrl], aspect: '1:1', tier: 'standard', internal: true }
: { prompt: composed, tier: 'standard', internal: true },
- { timeoutEnv: 'STUDIO_REFINE_TIMEOUT_MS', deadline: ctx.deadline },
+ {
+ timeoutEnv: 'STUDIO_REFINE_TIMEOUT_MS',
+ deadline: ctx.deadline,
+ ...jobOpts(ctx, { kind: 'refined model', what: 'refined model', prompt: composed || undefined, refine }),
+ },
);
} catch (err) {
return toolError(failureMessage(err));
@@ -719,12 +775,8 @@ async function handleRefineModel(args, _auth, req, ctx = {}) {
what: 'refined model',
prompt: composed || undefined,
...pendingTiming(job),
- refine: {
- lineage: baseLineage,
- instruction,
- refKind: refImageUrl ? 'image' : 'text',
- ...(parentIndex !== undefined ? { parentIndex } : {}),
- },
+ refine,
+ jobTool: ctx.jobTool,
});
if (job._timedOut || !job.glb_url) return toolError('Refinement is taking longer than expected. Please try again.');
@@ -766,15 +818,41 @@ function finishRefinement(base, data, refine) {
return refineOk({ glbUrl: data.glb_url, base, prompt: prompt || undefined, instruction, lineage: next, activeIndex: next.length - 1 });
}
-// Collect a generation that outlived a tool call's inline wait. One status
-// probe, no loop: done renders the full result envelope in the widget, still
-// running returns a fresh pending envelope with updated timing, failed returns
-// the same clean failure copy the generating tools use. Without this tool the
-// only way back to a pending job was browsing the raw poll URL.
-async function handleCheckJob(args, _auth, req) {
- const base = originFromReq(req);
- const jobId = String(args.job_id || '').trim();
- if (!jobId) return toolError('Provide the job_id a pending generation returned.');
+// The failure envelope for a job: what went wrong in plain words, and the one
+// action that fixes it. `retryable` keeps its meaning across the studio: the
+// job is fine and only this check failed, so checking again works (the viewer
+// widget retries on it). A failed job is never `retryable`; its remedy says to
+// start a new generation.
+function jobFailure({ jobId, message, remedy, reason, status = 'failed', retryable = false, retryAfter = null }) {
+ return toolError(`${message} ${remedy}`, {
+ status,
+ job_id: jobId,
+ reason,
+ remedy,
+ ...(retryable ? { retryable: true } : {}),
+ ...(retryAfter ? { retry_after: retryAfter } : {}),
+ });
+}
+
+// A finished envelope stamped with the shared job fields.
+function doneJob(envelope, jobId, frame) {
+ const fields = jobFields({ ...frame, status: 'done' });
+ return {
+ ...envelope,
+ structuredContent: { ...envelope.structuredContent, ...fields, job_id: jobId },
+ };
+}
+
+const START_AGAIN = 'Start a new generation (with a new idempotency_key if you used one); a retry is routed to a healthy engine.';
+
+/**
+ * One status probe of a job, rendered for an agent: done gives the full model
+ * result with its links, still running gives a fresh pending result with live
+ * timing, failed gives the reason and the remedy. No loop. `shape` is how the
+ * call that started the job described it (kind, prompt, rigged, the refine
+ * lineage it joins), so a finished job renders as that call would have.
+ */
+export async function collectJob(base, jobId, shape = {}, { jobTool = 'check_job' } = {}) {
let data;
try {
data = await pollOnce(base, jobId);
@@ -783,32 +861,98 @@ async function handleCheckJob(args, _auth, req) {
// an upstream blip leaves the job running, and the first check of a
// finished job does the slow save-and-score work, so checking again
// usually returns the model at once.
- return toolError(failureMessage(err), err?.code === 'unknown_job' ? {} : { retryable: true });
+ if (err?.code === 'unknown_job') {
+ return jobFailure({
+ jobId,
+ message: 'That job id is not recognized (it may be mistyped or expired).',
+ remedy: 'Start a new generation to get a fresh one.',
+ reason: 'unknown_job',
+ });
+ }
+ const wait = Number(err?.retryAfter) > 0 ? Math.ceil(Number(err.retryAfter)) : 10;
+ return jobFailure({
+ jobId,
+ status: 'unknown',
+ message: `${failureMessage(err)}`,
+ remedy: `The job itself keeps running: call ${jobTool} again in about ${wait}s.`,
+ reason: 'check_failed',
+ retryable: true,
+ retryAfter: wait,
+ });
}
if (data.status === 'done' && data.glb_url) {
- const refined = finishRefinement(base, data, args.refine);
- if (refined) return refined;
- return ok({
- glbUrl: data.glb_url,
- base,
- kind: 'model',
- prompt: typeof data.prompt === 'string' && data.prompt ? data.prompt : undefined,
- referenceImageUrl: data.preview_image_url,
- });
+ const refined = shape.refine ? finishRefinement(base, data, shape.refine) : null;
+ const prompt = shape.prompt || (typeof data.prompt === 'string' && data.prompt ? data.prompt : undefined);
+ const envelope =
+ refined ||
+ ok({
+ glbUrl: data.glb_url,
+ base,
+ kind: shape.kind && shape.kind !== 'refined model' ? shape.kind : 'model',
+ prompt,
+ rigged: Boolean(shape.rigged),
+ referenceImageUrl: data.preview_image_url,
+ });
+ return doneJob(envelope, jobId, data);
}
if (data.status === 'failed') {
// data.error is already sanitized server-side (sanitizeJobError): safe copy.
- return toolError(data.error ? `Generation failed: ${data.error}` : failureMessage({ code: 'generation_failed' }));
+ return jobFailure({
+ jobId,
+ message: data.error ? `Generation failed: ${data.error}` : 'Generation failed for this prompt.',
+ remedy: START_AGAIN,
+ reason: 'generation_failed',
+ });
}
return pendingResult({
base,
jobId,
- what: 'model',
- prompt: typeof data.prompt === 'string' && data.prompt ? data.prompt : undefined,
+ what: shape.what || 'model',
+ prompt: shape.prompt || (typeof data.prompt === 'string' && data.prompt ? data.prompt : undefined),
...pendingTiming(data),
+ ...(shape.stage ? { stage: shape.stage } : {}),
+ ...(shape.next ? { next: shape.next } : {}),
+ ...(shape.refine ? { refine: shape.refine } : {}),
+ jobTool,
});
}
+// check_job: collect a generation that outlived a tool call's inline wait.
+// Without it the only way back to a pending job was browsing the raw poll URL.
+async function handleCheckJob(args, _auth, req, ctx = {}) {
+ const jobId = String(args.job_id || '').trim();
+ if (!jobId) return toolError('Provide the job_id a pending generation returned.');
+ return collectJob(originFromReq(req), jobId, args.refine ? { refine: args.refine } : {}, { jobTool: ctx.jobTool });
+}
+
+// A repeat of an idempotent generation (./jobs.js): render the first call's job
+// from its record instead of starting another. A finished or failed job answers
+// from the record; a running one gets one status probe, and a pending record
+// whose job has since finished keeps that result for the next repeat.
+async function replayJob(record, { save, release, req, ctx = {} }) {
+ if (record.state === 'done' && record.result) return record.result;
+ if (record.state === 'failed') {
+ return jobFailure({
+ jobId: record.job_id,
+ message: String(record.message || 'Generation failed.').replace(/\s*Start a new generation.*$/s, ''),
+ remedy: START_AGAIN,
+ reason: 'generation_failed',
+ });
+ }
+ const out = await collectJob(originFromReq(req), record.job_id, record.shape || {}, { jobTool: ctx.jobTool });
+ const sc = out.structuredContent || {};
+ // Only a call that already returned hands its key over to a repeat. While the
+ // first call is still running it writes its own outcome (forge_avatar goes on
+ // to rig a mesh that just finished).
+ if (record.state === 'pending') {
+ if (sc.status === 'done') await save({ state: 'done', result: out });
+ else if (sc.reason === 'generation_failed') await save({ state: 'failed', message: sc.message });
+ }
+ // A job too old to look up frees its key, so calling again starts fresh.
+ if (sc.reason === 'unknown_job') await release();
+ return out;
+}
+
// ── definitions ─────────────────────────────────────────────────────────────
const GEN_ANNOTATIONS = {
@@ -895,7 +1039,7 @@ async function handleLookAtModel(args, _auth, req) {
};
}
-const DEFS = [
+const BASE_DEFS = [
{
name: 'forge_free',
title: 'Generate a 3D model from text',
@@ -1139,6 +1283,23 @@ const DEFS = [
},
];
+// Every tool that starts a job takes an optional idempotency_key, and a repeat
+// with the same key returns that job instead of starting another (./jobs.js).
+export const JOB_STARTERS = ['forge_free', 'text_to_avatar', 'mesh_forge', 'rig_mesh', 'forge_avatar', 'refine_model'];
+
+const DEFS = BASE_DEFS.map((def) =>
+ JOB_STARTERS.includes(def.name)
+ ? {
+ ...def,
+ inputSchema: {
+ ...def.inputSchema,
+ properties: { ...def.inputSchema.properties, idempotency_key: IDEMPOTENCY_KEY_PROP },
+ },
+ handler: withIdempotency(def.name, def.handler, { replay: replayJob }),
+ }
+ : def,
+);
+
// Schemas for tools/list — strip the handler (and any server-only field).
export const TOOL_CATALOG = DEFS.map(({ handler: _h, ...schema }) => schema);
diff --git a/api/gpt-forge.js b/api/gpt-forge.js
index 912a58e1f..fb4b3061c 100644
--- a/api/gpt-forge.js
+++ b/api/gpt-forge.js
@@ -3191,17 +3191,19 @@ export default wrap(async (req, res) => {
if (req.method === 'POST') {
// ?action=rig auto-rigs an existing GLB; the default POST reconstructs a
// mesh from a prompt (text→3D) or a reference image (image→3D).
- if ((url.searchParams.get('action') || '').trim() === 'rig') {
- return startRigJob(req, res);
- }
- // A bounded caller (the ChatGPT surface) sends a ticket so a submit that
- // outlives its call budget still yields a job it can collect. See
- // _lib/forge-submit-ticket.js.
+ // A bounded caller (the ChatGPT surface) or one retrying under an
+ // idempotency key sends a ticket, so a submit that outlives its call
+ // budget still yields a job it can collect. Rig submits take one too: an
+ // idempotent rig_mesh holds the ticket's handle before the rig job
+ // exists. See _lib/forge-submit-ticket.js.
const ticket = ticketFromRequest(req);
if (ticket) {
await markTicketSubmitting(ticket).catch((err) => console.warn(`[forge] submit ticket mark failed: ${err?.message || err}`));
captureTicketOutcome(res, ticket);
}
+ if ((url.searchParams.get('action') || '').trim() === 'rig') {
+ return startRigJob(req, res);
+ }
return startJob(req, res);
}
diff --git a/data/changelog.json b/data/changelog.json
index 24328296f..025814728 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-10-08",
+ "title": "Long 3D jobs and safe retries for AI agents",
+ "summary": "Agents that run on schedules can now generate 3D models without ever making the same model twice. Every generation tool on the free 3D Studio MCP server accepts an optional idempotency_key: retry a call that timed out with the same key and you get the first call's job back instead of a second generation, and the retry costs none of your quota. A new get_job tool reports any job's status, progress and time left, hands back the viewer, download, picture and embed links when it is done, and says what went wrong and what to do next when it fails. MCP clients that ask for progress updates now receive them live while the model renders.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/docs/mcp-studio"
+ },
{
"date": "2026-10-08",
"title": "API keys for AI agents that can never spend",
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 2a30048c9..94c7964b2 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -70,7 +70,7 @@ If the body also has `"reason": "rate_limiter_unavailable"`, you did not hit a q
### Idempotency
-Writes on the versioned agents API accept an `Idempotency-Key` header (up to 200 characters). The first request with a key runs; a retry with the same key and the same body within 24 hours gets the stored response back with `Idempotent-Replayed: true`, and nothing runs twice. Reusing a key with a different body is rejected with `422 idempotency_key_reused`, and a retry that arrives while the first is still running gets `409 idempotency_in_progress`. Other write endpoints are not idempotent unless their section says so, so guard retries on your side. Paid x402 endpoints are idempotent per payment: see [x402](/docs/x402).
+Writes on the versioned agents API accept an `Idempotency-Key` header (up to 200 characters). The first request with a key runs; a retry with the same key and the same body within 24 hours gets the stored response back with `Idempotent-Replayed: true`, and nothing runs twice. Reusing a key with a different body is rejected with `422 idempotency_key_reused`, and a retry that arrives while the first is still running gets `409 idempotency_in_progress`. Other write endpoints are not idempotent unless their section says so, so guard retries on your side. Paid x402 endpoints are idempotent per payment: see [x402](/docs/x402). The free 3D Studio MCP server keeps its `idempotency_key` argument in the same 24-hour store ([MCP studio](./mcp-studio.md#retries-and-idempotency_key)).
### Paid (x402) errors
diff --git a/docs/grok.md b/docs/grok.md
index 33e6ec4fb..da46b0c11 100644
--- a/docs/grok.md
+++ b/docs/grok.md
@@ -13,7 +13,7 @@ It is free: no account, no payment, no API key.
| **Transport** | Streamable HTTP (JSON-RPC over `POST`) |
| **Auth** | None |
| **Protocol** | MCP `2025-06-18` |
-| **Tools** | The full free studio: the same fourteen tools as [`/api/mcp-studio`](./mcp-studio.md) |
+| **Tools** | The full free studio: the same fifteen tools as [`/api/mcp-studio`](./mcp-studio.md) |
## Grok Bot
@@ -96,7 +96,7 @@ print(chat.sample().content)
```
Add `allowed_tools` (`allowed_tool_names` in the Python SDK) to expose only the
-tools a task needs, for example `["search_catalog", "forge_free", "check_job"]`.
+tools a task needs, for example `["search_catalog", "forge_free", "get_job"]`.
A complete, zero-dependency Node script that also collects slow renders lives in
[examples/grok-remote-mcp](../examples/grok-remote-mcp/README.md).
@@ -109,7 +109,7 @@ A complete, zero-dependency Node script that also collects slow renders lives in
| `forge_avatar` | Generate and rig a character in one step. |
| `rig_mesh` | Add a humanoid skeleton to any static GLB. |
| `refine_model` | Change a model in words ("make it metallic") with a version history. |
-| `check_job` | Collect a render that outlived one call. |
+| `get_job` | Status of a render that outlived one call: `status`, `progress`, `eta_seconds`, then the model and its links. `check_job` does the same and stays for older clients. |
| `look_at_model` | Render a GLB from several angles so Grok can see what it made. |
| `search_catalog`, `get_catalog_item`, `get_item_source` | Thousands of ready-made CC0 props, rigged characters and motion clips, plus paste-ready embed code. |
| `create_agent_persona`, `get_agent_persona`, `persona_say` | Save a rigged model as a named body, bring it back later, and make it speak a reply with lip-sync and emotion. |
@@ -125,8 +125,16 @@ links to the user.
scaled to zero boots first, and a render can take a few minutes. Grok calls MCP
from xAI's cloud with no published timeout, so this surface answers every call
within 40 seconds: with the model, or with a pending job and the seconds to
-wait. The server's instructions tell Grok to call `check_job(job_id)` until the
-model is done and keep going without asking the user. In the Responses API,
+wait. The server's instructions tell Grok to call `get_job(job_id)` until the
+model is done and keep going without asking the user.
+
+**Retries never generate twice.** Every generation tool takes an optional
+`idempotency_key`. A scheduled task that passes its task id as the key and
+retries after a timeout gets the first run's job back (`idempotent_replay:
+true`), not a second model, and the retry costs none of its quota. Keys belong to
+the caller, so a task that reconnects keeps them only on a connector URL with an
+install token (below). Details:
+[Retries and `idempotency_key`](./mcp-studio.md#retries-and-idempotency_key). In the Responses API,
where Grok cannot wait between calls in one response, continue the conversation
with `previous_response_id`, as the example does.
diff --git a/docs/mcp-studio.md b/docs/mcp-studio.md
index 90ee7e5b8..80e8dcf05 100644
--- a/docs/mcp-studio.md
+++ b/docs/mcp-studio.md
@@ -127,10 +127,12 @@ launcher, living avatars, link unfurls) is documented end to end in
## Tools
-`tools/list` returns exactly **fourteen** tools, and they split five ways:
+`tools/list` returns exactly **fifteen** tools, and they split six ways:
- **Six generation tools** (`forge_free`, `text_to_avatar`, `mesh_forge`,
- `rig_mesh`, `forge_avatar`, `refine_model`), in the table below.
+ `rig_mesh`, `forge_avatar`, `refine_model`), in the table below. Each takes an
+ optional [`idempotency_key`](#retries-and-idempotency_key).
+- **One job status tool**, [`get_job`](#job-status-get_job), for agents.
- **One collector**, `check_job`, also in the table below.
- **One inspector**, `look_at_model`, also in the table below.
- **Three asset catalog reads** (`search_catalog`, `get_catalog_item`,
@@ -138,7 +140,9 @@ launcher, living avatars, link unfurls) is documented end to end in
- **Three persona/embodiment tools** (`create_agent_persona`,
`get_agent_persona`, `persona_say`), in the **Embodiment** section further down.
-All fourteen are free and keyless.
+All fifteen are free and keyless. `/api/mcp-chatgpt` lists eleven of them: the
+eight in the table below and the three persona tools, without `get_job` or the
+catalog reads.
The six generation tools run operator-funded on the platform's own generation
pipeline. Annotations: `readOnlyHint:false`, `destructiveHint:false`,
@@ -156,13 +160,14 @@ quota as the six generators.
| Tool | Title | Input | Returns |
|---|---|---|---|
-| `forge_free` | Generate a 3D model from text | `prompt`, `tier?` | GLB model |
-| `text_to_avatar` | Generate a 3D avatar | `prompt?` / `image_url?` | GLB avatar |
-| `mesh_forge` | Generate a 3D mesh (art-directed) | `prompt?` / `image_url?` | GLB mesh |
-| `rig_mesh` | Rig a 3D model for animation | `glb_url` | rigged GLB |
-| `forge_avatar` | Generate a rigged, animation-ready avatar | `prompt?` / `image_url?`, `allow_non_humanoid?` | rigged GLB avatar |
-| `refine_model` | Refine a 3D model by describing a change | `glb_url`, `instruction`, `parent_prompt?`, `parent_lineage?`, `parent_index?` | refined GLB + version lineage |
-| `check_job` | Check a pending 3D generation and collect it | `job_id` | GLB model, or an updated pending state |
+| `forge_free` | Generate a 3D model from text | `prompt`, `tier?`, `idempotency_key?` | GLB model |
+| `text_to_avatar` | Generate a 3D avatar | `prompt?` / `image_url?`, `idempotency_key?` | GLB avatar |
+| `mesh_forge` | Generate a 3D mesh (art-directed) | `prompt?` / `image_url?`, `idempotency_key?` | GLB mesh |
+| `rig_mesh` | Rig a 3D model for animation | `glb_url`, `idempotency_key?` | rigged GLB |
+| `forge_avatar` | Generate a rigged, animation-ready avatar | `prompt?` / `image_url?`, `allow_non_humanoid?`, `idempotency_key?` | rigged GLB avatar |
+| `refine_model` | Refine a 3D model by describing a change | `glb_url`, `instruction`, `parent_prompt?`, `parent_lineage?`, `parent_index?`, `idempotency_key?` | refined GLB + version lineage |
+| `get_job` | Get a 3D generation job | `job_id`, `refine?` | `status`, `progress`, `eta_seconds`; the model and its links when done; reason and remedy when failed |
+| `check_job` | Check a pending 3D generation and collect it | `job_id`, `refine?` | GLB model, or an updated pending state |
| `look_at_model` | Look at a 3D model | `glb_url`, `views?` (up to 6 of `front`, `three-quarter`, `side`, `back`, `top`, `bottom`; default three-quarter, front, side, back), `size?` (128 to 1024 px, default 512) | rendered frames as images, plus geometry stats (triangles, materials, textures) and a plain reading of them |
### Ready-made assets (`search_catalog`, `get_catalog_item`, `get_item_source`)
@@ -369,6 +374,132 @@ three minutes), because other MCP hosts wait for it.
Any HTTP client can poll `pollUrl` directly instead; it is the same public,
auth-free job handle the [3D API](/docs/3d-api) hands anonymous callers.
+### Job status (`get_job`)
+
+`get_job(job_id)` is the job status tool for agents that run unattended: Grok
+Bot, a scheduled task, a CI step. It answers from the same code as `check_job`,
+so the two always agree; `check_job` stays for the ChatGPT inline viewer, which
+calls it by name. Call `get_job` as often as you like. It never starts or
+repeats a generation, and it never counts against the generation quota.
+
+Every job result, from `get_job`, `check_job` or a generating tool that returned
+a pending job, carries the same fields:
+
+| Field | Meaning |
+|---|---|
+| `job_id` | The handle to pass back (`jobId` is the same value, kept for older clients). |
+| `status` | `pending`, `done` or `failed`. `unknown` means only the check failed (see below). |
+| `phase` | Finer detail: `submitting` (the request is still being accepted), `queued` (waiting for a GPU worker, often a container boot), `running`, `done` or `failed`. |
+| `progress` | 0 to 1. While a job runs it is an estimate, its elapsed time over its lane's typical duration, held at 0.95 until the job is actually done; `null` when the server reports neither number. `1` when done. |
+| `eta_seconds` | Seconds the server expects are left. Absent once a job runs past its estimate, rather than a countdown stuck at a few seconds. `0` when done. |
+| `elapsed_seconds` | Seconds since the job was submitted. |
+
+What each status adds:
+
+- **`pending`**: a `viewer_url` that opens the model by itself the moment it is
+ ready, and the sentence telling the agent when to call again.
+- **`done`**: the whole model result, including the four
+ [agent links](#links-for-agents-that-render-no-widget) (`viewer_url`,
+ `glb_url`, `poster_png_url`, `embed_html`), `progress: 1` and `eta_seconds: 0`.
+- **`failed`**: `isError: true` with `reason`, a plain `message` and a `remedy`
+ naming the one action that fixes it:
+
+```json
+{
+ "status": "failed",
+ "job_id": "f1.eyJwIjoiZ2NwIiw…",
+ "reason": "generation_failed",
+ "message": "Generation failed: The mesh came back empty for this prompt.",
+ "remedy": "Start a new generation (with a new idempotency_key if you used one); a retry is routed to a healthy engine."
+}
+```
+
+`reason` is `generation_failed` (the job failed; start a new one),
+`unknown_job` (the id is mistyped or expired; start a new one) or
+`check_failed` with `status: "unknown"`, `retryable: true` and `retry_after`
+(the status check itself timed out or was rate-limited; the job keeps running,
+so call again after `retry_after` seconds). A failed job is never marked
+`retryable`, so a client that loops on `retryable` never polls a dead job.
+
+### Retries and `idempotency_key`
+
+An agent that retries a timed-out call would otherwise start a second
+generation, spend a second slot of the shared free quota, and end up with two
+models and no way to tell which one was meant. Every generation tool takes an
+optional `idempotency_key`: any string up to 200 characters that names one
+generation (a task id, a schedule run id). The first call with a key runs; any
+later call **from the same caller with the same key within 24 hours** gets that
+first call's job back instead of starting another:
+
+- while the job is still running, its current state (one status probe, the
+ pending fields above),
+- once it is done, the finished result, served from the record without asking
+ the pipeline again,
+- if it failed, the same failure, so the agent knows to start over with a new key.
+
+A repeat carries `idempotent_replay: true` and opens its text with "this is that
+call's job, and nothing new was started"; the first call carries
+`idempotent_replay: false`. Both carry the `idempotency_key` they were sent and
+the same `job_id`. A repeat is not charged to the generation quota, so retrying
+cannot rate-limit a task.
+
+```json
+{
+ "jsonrpc": "2.0", "id": 7, "method": "tools/call",
+ "params": {
+ "name": "forge_free",
+ "arguments": { "prompt": "a brass desk lamp", "idempotency_key": "grok-task-2026-10-08-lamp" }
+ }
+}
+```
+
+The rules:
+
+- **The caller owns the key.** It is the identity the
+ [rate limits](#funding--limits) charge: an install token from the connector
+ URL, the ChatGPT user, the Grok MCP session, else the IP address. A different
+ caller using the same key gets its own job. An agent that reconnects (and so
+ gets a new Grok session) keeps its keys only on a
+ [connector URL with an install token](#connector-url-for-cloud-agents-install-tokens).
+- **A key names one request.** The same key with different arguments, or on a
+ different tool, is refused with `reason: "idempotency_key_reused"` and starts
+ nothing.
+- **A call that never got a job gives its key back.** A refused prompt or a busy
+ generator leaves no job behind, so retrying with the same key runs normally.
+ An expired job frees its key the same way.
+- **The handle exists before the job does.** The first call records a submit
+ ticket's handle before it submits, so a repeat that lands while the first
+ submit is still in flight follows that handle (`phase: "submitting"`) rather
+ than racing it.
+
+The record lives in the same store as the HTTP `Idempotency-Key` header on the
+[agents API](./api-reference.md#idempotency):
+[`api/_lib/idempotency.js`](../api/_lib/idempotency.js), with the MCP side in
+[`api/_mcp-studio/jobs.js`](../api/_mcp-studio/jobs.js).
+
+### Progress notifications
+
+A client that sends `_meta.progressToken` on a `tools/call`, and accepts
+`text/event-stream` (the Streamable HTTP transport requires clients to accept
+it), gets the call answered as a server-sent event stream: one
+`notifications/progress` message when the call starts, one for each status the
+job reports while the tool waits, then the JSON-RPC result as the last event.
+
+```
+event: message
+data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"p1","progress":42.3,"total":132.3,"message":"Rendering the model (25%), about 90s left."}}
+
+event: message
+data: {"jsonrpc":"2.0","id":7,"result":{…}}
+```
+
+`progress` is the seconds the call has been running, so it only ever increases,
+even when a rigged avatar moves from its mesh job to its rig job. `total` is
+that plus the server's remaining estimate, present only while there is one.
+Without a `progressToken`, or from a client that does not accept an event
+stream, the call answers plain JSON exactly as before. A batch is always
+answered as one JSON array.
+
### Conversational refinement (`refine_model`)
Iterate on a model by describing the change in words — *"make it metallic"*,
@@ -508,8 +639,9 @@ connector URL carries one, else the door's own per-user identity, else the IP:
under the hourly cap, would collectively drain it
The generation quota is charged only when a request actually calls a generation
-tool, so `initialize`, `tools/list`, `resources/list`, and `check_job` are never
-throttled by it.
+tool, so `initialize`, `tools/list`, `resources/list`, `get_job` and `check_job`
+are never throttled by it, and neither is a repeat of an `idempotency_key` the
+caller already used.
A capped generation answers HTTP 200 with a JSON-RPC error, because MCP clients
pass that message to the model while many drop a 429 body. `Retry-After` and the
diff --git a/docs/mcp.md b/docs/mcp.md
index 2e12e3868..c4bd3a140 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -346,6 +346,23 @@ What every hosted server does on the wire, so a connector never fails silently:
- A `GET` with `accept: text/event-stream` answers a `405` with an `Allow` header where there is no server-to-client stream, a `401` with the OAuth challenge when the caller is unauthenticated, or the event stream itself (resource subscriptions on an authenticated core, 3D Studio, wallet or Bazaar connection, and the pump.fun feed).
- These servers are stateless and issue no `Mcp-Session-Id`, so a connector has no session to echo, resume or tear down; every request stands alone.
- An unauthenticated or expired-token request on a protected server gets `401` with `WWW-Authenticate: Bearer resource_metadata="…", resource="…"` naming that server, so the connector can sign in again on its own.
+- On the free 3D Studio (`/api/mcp-studio` and `/api/mcp-grok`), a `tools/call` that carries `_meta.progressToken` from a client that accepts `text/event-stream` is answered as an event stream: `notifications/progress` while the job runs, then the result. Without a token it answers plain JSON.
+
+### Long jobs and safe retries
+
+A text-to-3D job can outlast one tool call, and an unattended agent retries a call that timed out. The free 3D Studio gives such an agent two tools for that ([full reference](./mcp-studio.md#job-status-get_job)):
+
+- **`get_job(job_id)`** reports any generation job in one shape: `status` (`pending`, `done` or `failed`), `phase`, `progress` (0 to 1), `eta_seconds` and `elapsed_seconds` while it runs; the model and its four links (`viewer_url`, `glb_url`, `poster_png_url`, `embed_html`) when it is done; and a `reason` with a plain `remedy` when it failed. It never starts a generation and never counts against the generation quota, so call it as often as needed.
+- **`idempotency_key`** is an optional argument on every generation tool (`forge_free`, `text_to_avatar`, `mesh_forge`, `rig_mesh`, `forge_avatar`, `refine_model`). Calling again with the same key from the same caller within 24 hours returns the first call's job (`idempotent_replay: true`) instead of starting a second generation, and the repeat is not charged to the quota. A different caller with the same key gets its own job, and the same key with different arguments is refused with `idempotency_key_reused`.
+
+A scheduled Grok Bot task that generates a model:
+
+```json
+{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"forge_free","arguments":{"prompt":"a brass desk lamp","idempotency_key":"nightly-lamp-2026-10-08"}}}
+{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_job","arguments":{"job_id":"<job_id from the first result>"}}}
+```
+
+If the first call times out and the task retries it, the retry answers with the same `job_id`. Keys belong to the caller the studio's limits charge, so a cloud agent that reconnects keeps them only on a [connector URL with an install token](./mcp-studio.md#connector-url-for-cloud-agents-install-tokens). The store behind the key is the same one the agents API uses for its [`Idempotency-Key` header](./api-reference.md#idempotency).
---
diff --git a/packages/mcp-policy/src/table.js b/packages/mcp-policy/src/table.js
index d1577eebc..683261cf0 100644
--- a/packages/mcp-policy/src/table.js
+++ b/packages/mcp-policy/src/table.js
@@ -235,6 +235,7 @@ export const POLICY = {
forge_avatar: w('assets'),
refine_model: w('assets'),
check_job: w('assets'),
+ get_job: w('assets'),
look_at_model: r('assets'),
search_catalog: r('assets'),
get_catalog_item: r('assets'),
diff --git a/tests/mcp-grok.test.js b/tests/mcp-grok.test.js
index 075e15f9a..8ec0646e0 100644
--- a/tests/mcp-grok.test.js
+++ b/tests/mcp-grok.test.js
@@ -97,13 +97,15 @@ describe('grok surface catalog', () => {
expect(names('grok')).toEqual(names('full'));
expect(names('grok')).toContain('create_agent_persona');
expect(names('grok')).toContain('check_job');
+ expect(names('grok')).toContain('get_job');
});
it('tells Grok to share links and collect pending jobs on initialize', async () => {
const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }, auth, req, { surface: 'grok' });
const text = r.result.instructions;
expect(text).toContain('viewerUrl');
- expect(text).toContain('check_job(job_id)');
+ expect(text).toContain('get_job(job_id)');
+ expect(text).toContain('idempotency_key');
expect(text).toContain('embed_url');
});
});
@@ -118,12 +120,13 @@ describe('grok call budget', () => {
expect(opts.deadline).toBeLessThanOrEqual(Date.now() + GROK_CALL_BUDGET_MS);
});
- it('returns a pending job with a check_job hint when the render outlives the budget', async () => {
+ it('returns a pending job with a get_job hint when the render outlives the budget', async () => {
vi.mocked(generate).mockResolvedValue({ _timedOut: true, job_id: 'job-abc123', status: 'running' });
const r = await dispatch(callMsg('forge_free', { prompt: 'a reusable rocket booster' }), auth, req, { surface: 'grok' });
expect(r.result.structuredContent.status).toBe('pending');
expect(r.result.structuredContent.jobId).toBe('job-abc123');
- expect(r.result.content[0].text).toContain('check_job');
+ expect(r.result.content[0].text).toContain('call the get_job tool');
+ expect(r.result.structuredContent).toMatchObject({ job_id: 'job-abc123', phase: 'running' });
});
});
diff --git a/tests/mcp-studio-jobs.test.js b/tests/mcp-studio-jobs.test.js
new file mode 100644
index 000000000..220820db6
--- /dev/null
+++ b/tests/mcp-studio-jobs.test.js
@@ -0,0 +1,389 @@
+// Jobs an agent can trust across retries (api/_mcp-studio/jobs.js, get_job in
+// api/_mcp-studio/job-tools.js).
+//
+// A scheduled agent retries a generation that timed out. With an
+// idempotency_key the retry must get the first call's job, never a second
+// generation, and a different caller using the same key must get its own job.
+// get_job must report each job state in one vocabulary (status, progress,
+// eta_seconds, links when done, reason and remedy when failed), and a client
+// that sent a progressToken must get notifications/progress over SSE.
+//
+// The real studio client, ticket and idempotency code run here over the real
+// in-memory cache (no Redis in the test env). Only the HTTP boundary to
+// /api/gpt-forge is replaced, answering with the frame fixtures below, which
+// are captured from that endpoint's own response shapes.
+
+import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest';
+
+vi.mock('../api/_mcp-studio/gpt-forge-client.js', async (importOriginal) => {
+ const real = await importOriginal();
+ return { ...real, directPrompt: vi.fn(async () => null) };
+});
+
+const FIXTURE_GLB = 'https://three.ws/cdn/forge/fixture-teapot.glb';
+const FIXTURE_FRAMES = {
+ running: { status: 'running', backend: 'trellis', tier: 'standard', elapsed_seconds: 30, eta_seconds: 120, eta_remaining_seconds: 90 },
+ queued: { status: 'queued', backend: 'hunyuan3d', tier: 'high', elapsed_seconds: 12, eta_seconds: 240, eta_remaining_seconds: 228, cold_start: true, cold_start_seconds: 90 },
+ done: { status: 'done', glb_url: FIXTURE_GLB, prompt: 'a red ceramic teapot', backend: 'trellis' },
+ failed: { status: 'failed', error: 'The mesh came back empty for this prompt.', retryable: true, retry_backends: ['hunyuan3d'] },
+};
+
+let dispatch, studioHandler, forge;
+
+// The /api/gpt-forge double: every submit gets a fresh job token, and a poll
+// answers whatever frame the test set for that job.
+function installForge() {
+ const state = { submits: [], polls: [], frames: new Map(), next: 0, submitStatus: 200, submitGate: null };
+ const fetchStub = vi.fn(async (url, init = {}) => {
+ const u = new URL(String(url));
+ if (!u.pathname.endsWith('/api/gpt-forge')) throw new Error(`unexpected fetch ${url}`);
+ if ((init.method || 'GET') === 'POST') {
+ const ticket = init.headers?.['x-forge-ticket'] || null;
+ state.submits.push({ body: JSON.parse(init.body), ticket, rig: u.searchParams.get('action') === 'rig' });
+ // Honor the abort signal as real fetch does, so a submit window can close.
+ if (state.submitGate) {
+ await Promise.race([
+ state.submitGate,
+ new Promise((_, reject) => init.signal?.addEventListener('abort', () => reject(init.signal.reason))),
+ ]);
+ }
+ if (state.submitStatus !== 200) {
+ return new Response(JSON.stringify({ error: 'rate_limited', message: 'The 3D generator is busy right now.', retry_after: 20 }), {
+ status: state.submitStatus,
+ });
+ }
+ const jobId = `jobtok-${++state.next}`;
+ state.frames.set(jobId, state.frames.get('*') || FIXTURE_FRAMES.running);
+ return Response.json({ job_id: jobId, status: 'queued', eta_seconds: 120 });
+ }
+ const job = u.searchParams.get('job');
+ state.polls.push(job);
+ if (job.startsWith('t1.')) return Response.json({ job_id: job, status: 'queued', stage: 'submit', elapsed_seconds: 1 });
+ const frame = state.frames.get(job);
+ if (frame === 404) return new Response(JSON.stringify({ error: 'unknown_job' }), { status: 404 });
+ if (frame === 429) return new Response(JSON.stringify({ error: 'rate_limited', retry_after: 7 }), { status: 429 });
+ if (!frame) return new Response(JSON.stringify({ error: 'invalid_job' }), { status: 400 });
+ return Response.json({ job_id: job, ...frame });
+ });
+ vi.stubGlobal('fetch', fetchStub);
+ return state;
+}
+
+const req = { headers: { host: 'three.ws', 'x-forwarded-proto': 'https' } };
+let rpcId = 0;
+
+async function call(name, args, { caller = 'inst:caller-a', surface = 'grok' } = {}) {
+ const r = await dispatch(
+ { jsonrpc: '2.0', id: ++rpcId, method: 'tools/call', params: { name, arguments: args } },
+ { userId: null, rateKey: '203.0.113.9', scope: '' },
+ req,
+ { surface, caller },
+ );
+ return r.result;
+}
+
+beforeAll(async () => {
+ process.env.STUDIO_API_BASE = 'https://three.ws';
+ ({ dispatch } = await import('../api/_mcp-studio/dispatch.js'));
+ ({ studioHandler } = await import('../api/_mcp-studio/handler.js'));
+});
+
+beforeEach(() => {
+ // Return a pending job at once instead of waiting out a real render.
+ process.env.STUDIO_FORGE_TIMEOUT_MS = '1';
+ process.env.STUDIO_RIG_TIMEOUT_MS = '1';
+ forge = installForge();
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('idempotency_key on generation tools', () => {
+ it('every generation tool accepts it, and only those', async () => {
+ const { toolCatalogFor } = await import('../api/_mcp-studio/dispatch.js');
+ const keyed = toolCatalogFor('full')
+ .filter((t) => t.inputSchema?.properties?.idempotency_key)
+ .map((t) => t.name)
+ .sort();
+ expect(keyed).toEqual(['forge_avatar', 'forge_free', 'mesh_forge', 'refine_model', 'rig_mesh', 'text_to_avatar']);
+ });
+
+ it('a duplicate call from the same caller returns the same job and submits once', async () => {
+ const args = { prompt: 'a red ceramic teapot', idempotency_key: 'grok-task-42' };
+ const first = await call('forge_free', args);
+ const second = await call('forge_free', args);
+
+ expect(forge.submits).toHaveLength(1);
+ expect(first.structuredContent.status).toBe('pending');
+ expect(first.structuredContent.job_id).toBe('jobtok-1');
+ expect(first.structuredContent.idempotent_replay).toBe(false);
+ expect(second.structuredContent.job_id).toBe('jobtok-1');
+ expect(second.structuredContent.idempotent_replay).toBe(true);
+ expect(second.content[0].text).toMatch(/nothing new was started/);
+ });
+
+ it('a different caller with the same key gets its own job', async () => {
+ const args = { prompt: 'a red ceramic teapot', idempotency_key: 'grok-task-43' };
+ const a = await call('forge_free', args, { caller: 'inst:caller-a' });
+ const b = await call('forge_free', args, { caller: 'inst:caller-b' });
+
+ expect(forge.submits).toHaveLength(2);
+ expect(a.structuredContent.job_id).toBe('jobtok-1');
+ expect(b.structuredContent.job_id).toBe('jobtok-2');
+ expect(b.structuredContent.idempotent_replay).toBe(false);
+ });
+
+ it('without a key every call is a new generation', async () => {
+ await call('forge_free', { prompt: 'a red ceramic teapot' });
+ await call('forge_free', { prompt: 'a red ceramic teapot' });
+ expect(forge.submits).toHaveLength(2);
+ });
+
+ it('refuses a key reused for different arguments, and submits nothing', async () => {
+ await call('forge_free', { prompt: 'a red ceramic teapot', idempotency_key: 'k-reuse' });
+ const other = await call('forge_free', { prompt: 'a blue glass vase', idempotency_key: 'k-reuse' });
+ expect(forge.submits).toHaveLength(1);
+ expect(other.isError).toBe(true);
+ expect(other.structuredContent.reason).toBe('idempotency_key_reused');
+ });
+
+ it('gives the key back when no job was accepted, so the retry runs', async () => {
+ forge.submitStatus = 429;
+ const busy = await call('forge_free', { prompt: 'a red ceramic teapot', idempotency_key: 'k-busy' });
+ expect(busy.isError).toBe(true);
+ forge.submitStatus = 200;
+ const retry = await call('forge_free', { prompt: 'a red ceramic teapot', idempotency_key: 'k-busy' });
+ expect(retry.structuredContent.job_id).toBe('jobtok-1');
+ expect(retry.structuredContent.idempotent_replay).toBe(false);
+ expect(forge.submits).toHaveLength(2);
+ });
+
+ it('a finished job replays from the record with no further calls upstream', async () => {
+ process.env.STUDIO_FORGE_TIMEOUT_MS = '60000';
+ process.env.STUDIO_POLL_MS = '1';
+ forge.frames.set('*', FIXTURE_FRAMES.done);
+ const first = await call('forge_free', { prompt: 'a red ceramic teapot', idempotency_key: 'k-done' });
+ const callsAfterFirst = forge.submits.length + forge.polls.length;
+ const second = await call('forge_free', { prompt: 'a red ceramic teapot', idempotency_key: 'k-done' });
+
+ expect(first.structuredContent).toMatchObject({ status: 'done', job_id: 'jobtok-1', glbUrl: FIXTURE_GLB });
+ expect(second.structuredContent).toMatchObject({ status: 'done', job_id: 'jobtok-1', glbUrl: FIXTURE_GLB, idempotent_replay: true });
+ expect(forge.submits.length + forge.polls.length).toBe(callsAfterFirst);
+ delete process.env.STUDIO_POLL_MS;
+ });
+
+ it('a repeat that arrives while the first submit is in flight follows its ticket', async () => {
+ let open;
+ forge.submitGate = new Promise((r) => (open = r));
+ const args = { prompt: 'a red ceramic teapot', idempotency_key: 'k-race' };
+ const firstCall = call('forge_free', args);
+ await vi.waitFor(() => expect(forge.submits).toHaveLength(1));
+
+ const repeat = await call('forge_free', args);
+ const handle = `t1.${forge.submits[0].ticket}`;
+ expect(repeat.structuredContent.job_id).toBe(handle);
+ expect(repeat.structuredContent.phase).toBe('submitting');
+
+ open();
+ const first = await firstCall;
+ expect(first.structuredContent.job_id).toBe('jobtok-1');
+ expect(forge.submits).toHaveLength(1);
+ });
+
+ it('a submit still in flight at the call budget returns its ticket as a submitting job', async () => {
+ const { generate } = await import('../api/_mcp-studio/gpt-forge-client.js');
+ const { jobFields } = await import('../api/_mcp-studio/jobs.js');
+ let open;
+ forge.submitGate = new Promise((r) => (open = r));
+ // A deadline already spent: the ticketed submit gets only its short floor.
+ const ticket = 'lzk3m0aa-11111111-2222-4333-8444-555555555555';
+ const job = await generate('https://three.ws', { prompt: 'a red ceramic teapot' }, { deadline: Date.now() - 1, ticket });
+ open();
+ expect(job).toMatchObject({ _timedOut: true, job_id: `t1.${ticket}`, stage: 'submit' });
+ expect(jobFields(job).phase).toBe('submitting');
+ });
+
+ it('rig_mesh sends a ticket so its job has a handle before the rig exists', async () => {
+ await call('rig_mesh', { glb_url: FIXTURE_GLB, idempotency_key: 'k-rig' });
+ expect(forge.submits[0].rig).toBe(true);
+ expect(forge.submits[0].ticket).toMatch(/^[0-9a-z]+-[0-9a-f-]{36}$/);
+ });
+});
+
+describe('get_job', () => {
+ it('reports a running job with progress and eta_seconds', async () => {
+ forge.frames.set('jobtok-77', FIXTURE_FRAMES.running);
+ const r = await call('get_job', { job_id: 'jobtok-77' });
+ expect(r.isError).toBeFalsy();
+ expect(r.structuredContent).toMatchObject({
+ status: 'pending',
+ phase: 'running',
+ job_id: 'jobtok-77',
+ progress: 0.25,
+ eta_seconds: 90,
+ elapsed_seconds: 30,
+ });
+ expect(r.content[0].text).toContain('call the get_job tool');
+ });
+
+ it('reports a queued job on a waking worker as queued', async () => {
+ forge.frames.set('jobtok-78', FIXTURE_FRAMES.queued);
+ const r = await call('get_job', { job_id: 'jobtok-78' });
+ expect(r.structuredContent).toMatchObject({ status: 'pending', phase: 'queued', coldStart: true });
+ });
+
+ it('returns the model and its four links when done', async () => {
+ forge.frames.set('jobtok-79', FIXTURE_FRAMES.done);
+ const r = await call('get_job', { job_id: 'jobtok-79' });
+ expect(r.isError).toBeFalsy();
+ const sc = r.structuredContent;
+ expect(sc).toMatchObject({ status: 'done', phase: 'done', progress: 1, eta_seconds: 0, job_id: 'jobtok-79' });
+ expect(sc.glb_url).toBe(FIXTURE_GLB);
+ expect(sc.viewer_url).toContain('/viewer?src=');
+ expect(sc.poster_png_url).toContain('/api/render/glb');
+ expect(sc.embed_html).toContain('<');
+ });
+
+ it('explains a failed job and how to recover, without marking it retryable', async () => {
+ forge.frames.set('jobtok-80', FIXTURE_FRAMES.failed);
+ const r = await call('get_job', { job_id: 'jobtok-80' });
+ expect(r.isError).toBe(true);
+ expect(r.structuredContent).toMatchObject({ status: 'failed', reason: 'generation_failed', job_id: 'jobtok-80' });
+ expect(r.structuredContent.retryable).toBeUndefined();
+ expect(r.structuredContent.remedy).toMatch(/Start a new generation/);
+ expect(r.content[0].text).toContain('The mesh came back empty');
+ });
+
+ it('names an unknown job as final', async () => {
+ forge.frames.set('jobtok-81', 404);
+ const r = await call('get_job', { job_id: 'jobtok-81' });
+ expect(r.structuredContent).toMatchObject({ status: 'failed', reason: 'unknown_job' });
+ });
+
+ it('marks a failed check as retryable with a wait, since the job keeps running', async () => {
+ forge.frames.set('jobtok-82', 429);
+ const r = await call('get_job', { job_id: 'jobtok-82' });
+ expect(r.structuredContent).toMatchObject({ status: 'unknown', reason: 'check_failed', retryable: true, retry_after: 7 });
+ });
+
+ it('is listed on the full and Grok surfaces but not the ChatGPT listing', async () => {
+ const { toolCatalogFor } = await import('../api/_mcp-studio/dispatch.js');
+ expect(toolCatalogFor('full').map((t) => t.name)).toContain('get_job');
+ expect(toolCatalogFor('grok').map((t) => t.name)).toContain('get_job');
+ expect(toolCatalogFor('chatgpt').map((t) => t.name)).not.toContain('get_job');
+ });
+});
+
+// A minimal node-style req/res pair for driving the real HTTP handler.
+function httpPair(body, headers = {}) {
+ const payload = Buffer.from(JSON.stringify(body));
+ const ip = '198.51.100.23';
+ const req = {
+ method: 'POST',
+ url: '/api/mcp-studio',
+ headers: { host: 'three.ws', 'content-type': 'application/json', 'x-forwarded-for': ip, ...headers },
+ socket: { remoteAddress: ip },
+ async *[Symbol.asyncIterator]() {
+ yield payload;
+ },
+ on(event, cb) {
+ if (event === 'data') cb(payload);
+ if (event === 'end') cb();
+ return this;
+ },
+ };
+ const out = { headers: {}, body: '', ended: false };
+ const res = {
+ statusCode: 200,
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) {
+ out.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return out.headers[k.toLowerCase()];
+ },
+ removeHeader(k) {
+ delete out.headers[k.toLowerCase()];
+ },
+ flushHeaders() {
+ this.headersSent = true;
+ },
+ write(chunk) {
+ out.body += chunk;
+ return true;
+ },
+ end(chunk) {
+ if (chunk) out.body += chunk;
+ out.status = this.statusCode;
+ this.headersSent = true;
+ this.writableEnded = true;
+ out.ended = true;
+ },
+ };
+ return { req, res, out };
+}
+
+function sseMessages(body) {
+ return body
+ .split('\n\n')
+ .filter((block) => block.startsWith('event: message'))
+ .map((block) => JSON.parse(block.split('\n').find((l) => l.startsWith('data: ')).slice(6)));
+}
+
+describe('progress notifications', () => {
+ const toolCall = (meta) => ({
+ jsonrpc: '2.0',
+ id: 9,
+ method: 'tools/call',
+ params: { name: 'forge_free', arguments: { prompt: 'a red ceramic teapot' }, ...(meta ? { _meta: meta } : {}) },
+ });
+
+ it('streams notifications/progress then the result when the client sent a progressToken', async () => {
+ process.env.STUDIO_FORGE_TIMEOUT_MS = '60000';
+ process.env.STUDIO_POLL_MS = '1';
+ let polls = 0;
+ forge.frames.set('*', FIXTURE_FRAMES.running);
+ const realFetch = globalThis.fetch;
+ vi.stubGlobal('fetch', async (url, init) => {
+ if (String(url).includes('job=')) {
+ // Status frames arrive seconds apart in production; progress is
+ // reported in tenths of a second, so space these past that.
+ await new Promise((r) => setTimeout(r, 120));
+ polls++;
+ if (polls >= 3) forge.frames.set('jobtok-1', FIXTURE_FRAMES.done);
+ }
+ return realFetch(url, init);
+ });
+ const { req: rq, res, out } = httpPair(toolCall({ progressToken: 'tok-1' }), { accept: 'application/json, text/event-stream' });
+ await studioHandler({ surface: 'full' })(rq, res);
+ delete process.env.STUDIO_POLL_MS;
+
+ expect(out.headers['content-type']).toMatch(/^text\/event-stream/);
+ const msgs = sseMessages(out.body);
+ const progress = msgs.filter((m) => m.method === 'notifications/progress');
+ expect(progress.length).toBeGreaterThanOrEqual(2);
+ for (const p of progress) expect(p.params.progressToken).toBe('tok-1');
+ const values = progress.map((p) => p.params.progress);
+ for (let i = 1; i < values.length; i++) expect(values[i]).toBeGreaterThan(values[i - 1]);
+ expect(progress.some((p) => /Rendering the model/.test(p.params.message))).toBe(true);
+ const final = msgs.at(-1);
+ expect(final.id).toBe(9);
+ expect(final.result.structuredContent.glbUrl).toBe(FIXTURE_GLB);
+ expect(out.ended).toBe(true);
+ });
+
+ it('answers plain JSON when no progressToken was sent', async () => {
+ const { req: rq, res, out } = httpPair(toolCall(null), { accept: 'application/json, text/event-stream' });
+ await studioHandler({ surface: 'full' })(rq, res);
+ expect(out.headers['content-type']).toMatch(/^application\/json/);
+ expect(JSON.parse(out.body).result.structuredContent.status).toBe('pending');
+ });
+
+ it('answers plain JSON when the client does not accept an event stream', async () => {
+ const { req: rq, res, out } = httpPair(toolCall({ progressToken: 3 }), { accept: 'application/json' });
+ await studioHandler({ surface: 'full' })(rq, res);
+ expect(out.headers['content-type']).toMatch(/^application\/json/);
+ });
+});
diff --git a/tests/mcp-studio.test.js b/tests/mcp-studio.test.js
index 2e0c6769a..25ccd9421 100644
--- a/tests/mcp-studio.test.js
+++ b/tests/mcp-studio.test.js
@@ -18,7 +18,10 @@ import { MODEL_VIEWER_CDN_ORIGIN } from '../api/_lib/model-viewer-cdn.js';
const ALLOWED = ['forge_free', 'text_to_avatar', 'mesh_forge', 'rig_mesh', 'forge_avatar', 'refine_model', 'check_job', 'look_at_model'];
const PERSONA = ['create_agent_persona', 'get_agent_persona', 'persona_say'];
const CATALOG = ['search_catalog', 'get_catalog_item', 'get_item_source'];
-const ALL = [...ALLOWED, ...CATALOG, ...PERSONA];
+// 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];
// 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