sceneview-mcp 4.1.2 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,221 @@
1
+ /**
2
+ * TRELLIS.2 on Runware — the low-cost provider behind `generate_3d_model`.
3
+ *
4
+ * TRELLIS.2 (Microsoft, MIT-licensed weights) is image→3D only, so text→3D
5
+ * runs in two Runware tasks:
6
+ * 1. `imageInference` with FLUX.1 [schnell] (`runware:100@1`) renders a
7
+ * single, centred object on a plain background from the prompt;
8
+ * 2. `3dInference` with `microsoft:trellis-2@4b` turns that image (or the
9
+ * caller's own image) into a textured GLB.
10
+ * Runware bills by compute time — a TRELLIS.2 run costs from ~$0.008 (512³)
11
+ * to a few US cents (Runware model page, November 2026). The reported `cost`
12
+ * is surfaced to the user.
13
+ *
14
+ * API contract (runware.ai/docs/models-api, November 2026):
15
+ * POST https://api.runware.ai/v1, `Authorization: Bearer <key>`, body = an
16
+ * array of task objects. Responses are `{ data: [...] }` or
17
+ * `{ errors: [...] }`. An async task is polled with
18
+ * `{ taskType: "getResponse", taskUUID }`, whose rows carry
19
+ * `status: processing | success | error`.
20
+ *
21
+ * BYOK like the Tripo path: users bring their own `RUNWARE_API_KEY`
22
+ * (my.runware.ai/keys). SceneView never ships, proxies or pays for a key.
23
+ */
24
+ import { randomUUID } from "node:crypto";
25
+ export const RUNWARE_ENDPOINT = "https://api.runware.ai/v1";
26
+ export const RUNWARE_KEYS_URL = "https://my.runware.ai/keys";
27
+ export const TRELLIS_MODEL = "microsoft:trellis-2@4b";
28
+ export const CONCEPT_IMAGE_MODEL = "runware:100@1"; // FLUX.1 [schnell]
29
+ /** Prompt suffix that gives TRELLIS.2 a clean, single-object input image. */
30
+ const CONCEPT_SUFFIX = "single object, centered, full view, plain white background, soft studio lighting, no text";
31
+ export const TRELLIS_TIERS = {
32
+ fast: { resolution: 1024, label: "fast (TRELLIS.2 1024³ on Runware)", timeoutMs: 180_000 },
33
+ hd: { resolution: 1536, label: "hd (TRELLIS.2 1536³ on Runware)", timeoutMs: 300_000 },
34
+ };
35
+ export const TRELLIS_LICENSE = "Generated with your own Runware API key — TRELLIS.2 weights are MIT-licensed (Microsoft) and usage follows Runware's terms (https://runware.ai/terms). No author attribution is required.";
36
+ export const TRELLIS_ATTRIBUTION = "TRELLIS.2 (Microsoft) via Runware (https://runware.ai)";
37
+ const DEFAULT_POLL_INTERVAL_MS = 2_000;
38
+ function sleep(ms) {
39
+ return new Promise((resolve) => setTimeout(resolve, ms));
40
+ }
41
+ function fail(code, message) {
42
+ return { ok: false, code, message };
43
+ }
44
+ /** Build the TRELLIS.2 `3dInference` task. Exported for tests. */
45
+ export function buildTrellisTask(taskUUID, imageUrl, quality) {
46
+ return {
47
+ taskType: "3dInference",
48
+ taskUUID,
49
+ model: TRELLIS_MODEL,
50
+ deliveryMethod: "async",
51
+ includeCost: true,
52
+ outputFormat: "GLB",
53
+ settings: { resolution: TRELLIS_TIERS[quality].resolution, textureSize: 2048, remesh: true },
54
+ inputs: { image: imageUrl },
55
+ };
56
+ }
57
+ /** Build the FLUX.1 [schnell] concept-image task for text→3D. Exported for tests. */
58
+ export function buildConceptTask(taskUUID, prompt) {
59
+ return {
60
+ taskType: "imageInference",
61
+ taskUUID,
62
+ model: CONCEPT_IMAGE_MODEL,
63
+ positivePrompt: `${prompt}, ${CONCEPT_SUFFIX}`,
64
+ width: 1024,
65
+ height: 1024,
66
+ numberResults: 1,
67
+ includeCost: true,
68
+ };
69
+ }
70
+ function errorText(envelope) {
71
+ const first = envelope.errors?.[0];
72
+ if (first)
73
+ return [first.code, first.message].filter(Boolean).join(": ") || "unknown error";
74
+ if (typeof envelope.error === "string")
75
+ return envelope.error;
76
+ if (envelope.error) {
77
+ return ([envelope.error.code, envelope.error.message].filter(Boolean).join(": ") || "unknown error");
78
+ }
79
+ return null;
80
+ }
81
+ async function post(apiKey, tasks) {
82
+ let response;
83
+ try {
84
+ response = await fetch(RUNWARE_ENDPOINT, {
85
+ method: "POST",
86
+ headers: {
87
+ Authorization: `Bearer ${apiKey}`,
88
+ "Content-Type": "application/json",
89
+ Accept: "application/json",
90
+ },
91
+ body: JSON.stringify(tasks),
92
+ });
93
+ }
94
+ catch (err) {
95
+ const cause = err instanceof Error ? err.message : String(err);
96
+ return {
97
+ ok: false,
98
+ error: fail("network", `Could not reach Runware (${cause}). Check your internet connection and try again.`),
99
+ };
100
+ }
101
+ if (response.status === 401 || response.status === 403) {
102
+ return {
103
+ ok: false,
104
+ error: fail("unauthorized", `Runware rejected the API key (HTTP ${response.status}). Double-check it at ${RUNWARE_KEYS_URL}, or create a new one.`),
105
+ };
106
+ }
107
+ if (response.status === 429) {
108
+ return {
109
+ ok: false,
110
+ error: fail("rate_limited", "Runware rate limit reached (HTTP 429). Wait a minute and retry."),
111
+ };
112
+ }
113
+ let body;
114
+ try {
115
+ body = (await response.json());
116
+ }
117
+ catch (err) {
118
+ const cause = err instanceof Error ? err.message : String(err);
119
+ return { ok: false, error: fail("bad_response", `Runware returned invalid JSON: ${cause}`) };
120
+ }
121
+ if (!response.ok && !body.data) {
122
+ const detail = errorText(body);
123
+ return {
124
+ ok: false,
125
+ error: fail("bad_response", `Runware returned HTTP ${response.status}${detail ? `: ${detail}` : ""}`),
126
+ };
127
+ }
128
+ return { ok: true, body };
129
+ }
130
+ /**
131
+ * Generate a GLB with TRELLIS.2 on Runware. Inputs are already validated by
132
+ * `generateModel`; exactly one of `prompt` / `imageUrl` is set.
133
+ */
134
+ export async function generateWithTrellis(options) {
135
+ const newUuid = options.newUuid ?? randomUUID;
136
+ const tier = TRELLIS_TIERS[options.quality];
137
+ let costUsd = 0;
138
+ let sawCost = false;
139
+ // ── 1. Text→3D: render a concept image first ──────────────────────────────
140
+ let sourceImage = options.imageUrl ?? "";
141
+ if (options.prompt !== undefined) {
142
+ const imageTask = buildConceptTask(newUuid(), options.prompt);
143
+ const imageCall = await post(options.apiKey, [imageTask]);
144
+ if (!imageCall.ok)
145
+ return imageCall.error;
146
+ const detail = errorText(imageCall.body);
147
+ const row = imageCall.body.data?.find((r) => typeof r.imageURL === "string");
148
+ if (!row?.imageURL) {
149
+ return fail("task_failed", `Runware could not render the concept image${detail ? ` (${detail})` : ""}. Try rephrasing the prompt.`);
150
+ }
151
+ sourceImage = row.imageURL;
152
+ if (typeof row.cost === "number") {
153
+ costUsd += row.cost;
154
+ sawCost = true;
155
+ }
156
+ }
157
+ // ── 2. Submit the TRELLIS.2 task (async) ──────────────────────────────────
158
+ const taskUUID = newUuid();
159
+ const submit = await post(options.apiKey, [
160
+ buildTrellisTask(taskUUID, sourceImage, options.quality),
161
+ ]);
162
+ if (!submit.ok)
163
+ return submit.error;
164
+ const submitError = errorText(submit.body);
165
+ if (submitError && !submit.body.data?.length) {
166
+ return fail("bad_response", `Runware rejected the 3D task: ${submitError}`);
167
+ }
168
+ // ── 3. Poll getResponse until success / error / deadline ──────────────────
169
+ const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
170
+ const timeoutMs = options.timeoutMs ?? tier.timeoutMs;
171
+ const deadline = Date.now() + timeoutMs;
172
+ let lastProgress = 0;
173
+ for (;;) {
174
+ const poll = await post(options.apiKey, [{ taskType: "getResponse", taskUUID }]);
175
+ if (!poll.ok) {
176
+ // A key that stops working is final; other hiccups are retried until the deadline.
177
+ if (poll.error.code === "unauthorized")
178
+ return poll.error;
179
+ }
180
+ else {
181
+ const failed = poll.body.errors?.find((e) => !e.taskUUID || e.taskUUID === taskUUID);
182
+ if (failed) {
183
+ return fail("task_failed", `Runware task ${taskUUID} failed${failed.message ? `: ${failed.message}` : ""}. Try a clearer prompt or source image and generate again.`);
184
+ }
185
+ const row = poll.body.data?.find((r) => r.taskUUID === taskUUID) ?? poll.body.data?.[0];
186
+ if (typeof row?.progress === "number")
187
+ lastProgress = row.progress;
188
+ const modelUrl = row?.outputs?.files?.find((f) => typeof f.url === "string")?.url;
189
+ if (row && (row.status === "success" || modelUrl)) {
190
+ if (!modelUrl) {
191
+ return fail("bad_response", `Runware task ${taskUUID} succeeded but returned no GLB URL.`);
192
+ }
193
+ if (typeof row.cost === "number") {
194
+ costUsd += row.cost;
195
+ sawCost = true;
196
+ }
197
+ return {
198
+ ok: true,
199
+ model: {
200
+ taskId: taskUUID,
201
+ modelUrl,
202
+ previewImageUrl: options.prompt !== undefined ? sourceImage : "",
203
+ quality: options.quality,
204
+ modelVersion: TRELLIS_MODEL,
205
+ mode: options.prompt !== undefined ? "text" : "image",
206
+ input: options.prompt ?? sourceImage,
207
+ creditsConsumed: null,
208
+ costUsd: sawCost ? Math.round(costUsd * 10_000) / 10_000 : null,
209
+ provider: "trellis",
210
+ license: TRELLIS_LICENSE,
211
+ attribution: TRELLIS_ATTRIBUTION,
212
+ },
213
+ };
214
+ }
215
+ }
216
+ if (Date.now() >= deadline) {
217
+ return fail("timeout", `Runware task ${taskUUID} did not finish within ${Math.round(timeoutMs / 1000)}s (progress ${lastProgress}%). The generation may still complete and be billed — retry later.`);
218
+ }
219
+ await sleep(pollIntervalMs);
220
+ }
221
+ }
@@ -1,5 +1,12 @@
1
1
  /**
2
- * generate_3d_model — Tripo BYOK text/image→GLB generation tool.
2
+ * generate_3d_model — BYOK text/image→GLB generation tool (Tripo or TRELLIS.2).
3
+ *
4
+ * Two providers, both bring-your-own-key:
5
+ * - Tripo (`TRIPO_API_KEY`) — documented below.
6
+ * - TRELLIS.2 on Runware (`RUNWARE_API_KEY`) — roughly 10× cheaper per
7
+ * model; see `generate-model-runware.ts`.
8
+ * `provider` picks one explicitly; otherwise Tripo is used when its key is
9
+ * set (unchanged behaviour), then TRELLIS.2 when only the Runware key is.
3
10
  *
4
11
  * `search_models` finds assets that already exist; this tool closes the other
5
12
  * half of the agentic asset loop: when no existing model fits, the assistant
@@ -36,6 +43,7 @@
36
43
  * translated to a structured `GenerateModelError` so the MCP handler can
37
44
  * render a clear message without crashing the server.
38
45
  */
46
+ import { generateWithTrellis, RUNWARE_KEYS_URL, TRELLIS_TIERS } from "./generate-model-runware.js";
39
47
  // ─── Configuration ──────────────────────────────────────────────────────────
40
48
  const TRIPO_TASK_ENDPOINT = "https://api.tripo3d.ai/v2/openapi/task";
41
49
  const API_KEYS_URL = "https://platform.tripo3d.ai/api-keys";
@@ -64,15 +72,34 @@ const ATTRIBUTION = "Tripo AI (https://www.tripo3d.ai)";
64
72
  /** Finalized-but-not-successful Tripo task statuses. */
65
73
  const FAILED_STATUSES = new Set(["failed", "banned", "expired", "cancelled", "unknown"]);
66
74
  // ─── Helpers ────────────────────────────────────────────────────────────────
67
- function missingKeyError() {
75
+ function missingKeyError(provider) {
76
+ const envName = provider === "tripo" ? "TRIPO_API_KEY" : "RUNWARE_API_KEY";
77
+ const intro = provider === "tripo"
78
+ ? [
79
+ "generate_3d_model needs a Tripo API key (BYOK — generations are billed to YOUR Tripo account, nothing is charged by SceneView).",
80
+ "",
81
+ `1. Create an API key at ${API_KEYS_URL} (new accounts get free trial credits)`,
82
+ ]
83
+ : provider === "trellis"
84
+ ? [
85
+ 'generate_3d_model with provider "trellis" needs a Runware API key (BYOK — generations are billed to YOUR Runware account, a few US cents per model; nothing is charged by SceneView).',
86
+ "",
87
+ `1. Create an API key at ${RUNWARE_KEYS_URL}`,
88
+ ]
89
+ : [
90
+ "generate_3d_model needs an API key from one of two providers (BYOK — generations are billed to YOUR account, nothing is charged by SceneView):",
91
+ "",
92
+ `- TRELLIS.2 on Runware (RUNWARE_API_KEY, ${RUNWARE_KEYS_URL}) — a few US cents per model, image-faithful.`,
93
+ `- Tripo AI (TRIPO_API_KEY, ${API_KEYS_URL}) — $0.10-0.41 per model, low-poly or quad topology.`,
94
+ "",
95
+ "1. Create a key with either provider",
96
+ ];
68
97
  return {
69
98
  ok: false,
70
99
  code: "missing_key",
71
100
  message: [
72
- "generate_3d_model needs a Tripo API key (BYOK — generations are billed to YOUR Tripo account, nothing is charged by SceneView).",
73
- "",
74
- `1. Create an API key at ${API_KEYS_URL} (new accounts get free trial credits)`,
75
- "2. Set the TRIPO_API_KEY environment variable in your MCP client config:",
101
+ ...intro,
102
+ `2. Set the ${envName} environment variable in your MCP client config:`,
76
103
  "",
77
104
  " Claude Desktop / Cursor / Windsurf:",
78
105
  " {",
@@ -80,7 +107,7 @@ function missingKeyError() {
80
107
  ' "sceneview": {',
81
108
  ' "command": "npx",',
82
109
  ' "args": ["-y", "sceneview-mcp"],',
83
- ' "env": { "TRIPO_API_KEY": "YOUR_KEY_HERE" }',
110
+ ` "env": { "${envName}": "YOUR_KEY_HERE" }`,
84
111
  " }",
85
112
  " }",
86
113
  " }",
@@ -209,9 +236,25 @@ export async function generateModel(options) {
209
236
  }
210
237
  const quality = options.quality === "hd" ? "hd" : "fast"; // default + unknown values → fast
211
238
  const tier = QUALITY_TIERS[quality];
212
- const apiKey = process.env.TRIPO_API_KEY;
213
- if (!apiKey || apiKey.trim().length === 0) {
214
- return missingKeyError();
239
+ const tripoKey = process.env.TRIPO_API_KEY?.trim() ?? "";
240
+ const runwareKey = process.env.RUNWARE_API_KEY?.trim() ?? "";
241
+ const requested = options.provider === "tripo" || options.provider === "trellis" ? options.provider : undefined;
242
+ const provider = requested ?? (tripoKey ? "tripo" : runwareKey ? "trellis" : undefined);
243
+ if (provider === "trellis") {
244
+ if (!runwareKey)
245
+ return missingKeyError("trellis");
246
+ return generateWithTrellis({
247
+ apiKey: runwareKey,
248
+ prompt: hasPrompt ? prompt : undefined,
249
+ imageUrl: hasImage ? imageUrl : undefined,
250
+ quality,
251
+ pollIntervalMs: options.pollIntervalMs,
252
+ timeoutMs: options.timeoutMs,
253
+ });
254
+ }
255
+ const apiKey = tripoKey;
256
+ if (!apiKey) {
257
+ return missingKeyError(requested);
215
258
  }
216
259
  const headers = {
217
260
  Authorization: `Bearer ${apiKey}`,
@@ -330,6 +373,8 @@ export async function generateModel(options) {
330
373
  mode: hasPrompt ? "text" : "image",
331
374
  input: hasPrompt ? prompt : imageUrl,
332
375
  creditsConsumed: typeof task?.consumed_credit === "number" ? task.consumed_credit : null,
376
+ costUsd: null,
377
+ provider: "tripo",
333
378
  license: LICENSE_NOTE,
334
379
  attribution: ATTRIBUTION,
335
380
  },
@@ -375,17 +420,25 @@ export function formatGenerateResult(result) {
375
420
  return result.message;
376
421
  }
377
422
  const m = result.model;
423
+ const trellis = m.provider === "trellis";
378
424
  const sourceLabel = m.mode === "text" ? "Prompt" : "Source image";
425
+ const tierLabel = trellis ? TRELLIS_TIERS[m.quality].label : QUALITY_TIERS[m.quality].label;
426
+ const expiry = trellis
427
+ ? "the download link is temporary — download the file NOW and self-host it"
428
+ : "the download link expires ~5 minutes after generation — download the file NOW and self-host it";
379
429
  const lines = [
380
- `## Generated 3D model (${QUALITY_TIERS[m.quality].label})`,
430
+ `## Generated 3D model (${tierLabel})`,
381
431
  "",
382
432
  `- **GLB download:** ${m.modelUrl}`,
383
- `- **⚠️ URL expiry:** the download link expires ~5 minutes after generation — download the file NOW and self-host it (e.g. copy it into your app's \`assets/models/\`).`,
384
- ...(m.previewImageUrl ? [`- **Preview:** ${m.previewImageUrl}`] : []),
433
+ `- **⚠️ URL expiry:** ${expiry} (e.g. copy it into your app's \`assets/models/\`).`,
434
+ ...(m.previewImageUrl
435
+ ? [`- **${trellis ? "Concept image" : "Preview"}:** ${m.previewImageUrl}`]
436
+ : []),
385
437
  `- **${sourceLabel}:** ${m.input}`,
386
438
  `- **Model version:** ${m.modelVersion}`,
387
439
  `- **Task ID:** \`${m.taskId}\``,
388
440
  ...(m.creditsConsumed !== null ? [`- **Tripo credits consumed:** ${m.creditsConsumed}`] : []),
441
+ ...(m.costUsd !== null ? [`- **Cost:** US$${m.costUsd} (billed to your Runware account)`] : []),
389
442
  `- **License:** ${m.license}`,
390
443
  `- **Generator:** ${m.attribution}`,
391
444
  "",
@@ -574,6 +574,17 @@ export function generateScene(description) {
574
574
  }
575
575
  // Generate Kotlin code
576
576
  const lines = [];
577
+ if (isAR) {
578
+ // The AR-only imports an AI cannot guess: `Plane` exists in three packages and
579
+ // `createAnchorOrNull` is an extension. Compose and SceneView entry points are the usual ones.
580
+ lines.push("import com.google.ar.core.Anchor");
581
+ lines.push("import com.google.ar.core.Config");
582
+ lines.push("import com.google.ar.core.Frame");
583
+ lines.push("import com.google.ar.core.Plane");
584
+ lines.push("import io.github.sceneview.ar.arcore.createAnchorOrNull");
585
+ lines.push("import io.github.sceneview.rememberOnGestureListener");
586
+ lines.push("");
587
+ }
577
588
  lines.push("@Composable");
578
589
  lines.push(`fun GeneratedScene() {`);
579
590
  lines.push(" val engine = rememberEngine()");
@@ -606,6 +617,7 @@ export function generateScene(description) {
606
617
  // SceneView or ARSceneView
607
618
  if (isAR) {
608
619
  lines.push(" var anchor by remember { mutableStateOf<Anchor?>(null) }");
620
+ lines.push(" var latestFrame by remember { mutableStateOf<Frame?>(null) }");
609
621
  lines.push("");
610
622
  lines.push(" ARSceneView(");
611
623
  lines.push(" modifier = Modifier.fillMaxSize(),");
@@ -616,12 +628,21 @@ export function generateScene(description) {
616
628
  lines.push(" sessionConfiguration = { session, config ->");
617
629
  lines.push(" config.lightEstimationMode = Config.LightEstimationMode.ENVIRONMENTAL_HDR");
618
630
  lines.push(" },");
619
- lines.push(" onTouchEvent = { event, hitResult ->");
620
- lines.push(" if (event.action == MotionEvent.ACTION_UP && hitResult != null) {");
621
- lines.push(" anchor = hitResult.createAnchor()");
631
+ lines.push(" onSessionUpdated = { _, frame -> latestFrame = frame },");
632
+ // Place on a confirmed single tap on empty space, never on a raw ACTION_UP: that also
633
+ // fires at the end of every drag or pinch, and returning true from onTouchEvent
634
+ // swallows the model's own gestures. The AnchorNode keyed on `anchor` detaches the
635
+ // previous anchor when it is replaced, so no explicit detach() is needed.
636
+ lines.push(" onGestureListener = rememberOnGestureListener(");
637
+ lines.push(" onSingleTapConfirmed = { event, node ->");
638
+ lines.push(" if (node == null) { // empty space, not a placed model");
639
+ lines.push(" latestFrame?.hitTest(event)");
640
+ lines.push(" ?.firstOrNull { (it.trackable as? Plane)?.isPoseInPolygon(it.hitPose) == true }");
641
+ lines.push(" ?.createAnchorOrNull()");
642
+ lines.push(" ?.let { anchor = it } // the old AnchorNode detaches its anchor");
643
+ lines.push(" }");
622
644
  lines.push(" }");
623
- lines.push(" true");
624
- lines.push(" }");
645
+ lines.push(" )");
625
646
  lines.push(" ) {");
626
647
  lines.push(" anchor?.let { a ->");
627
648
  lines.push(" AnchorNode(anchor = a) {");