depthview-mcp 0.0.0-stage → 0.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.
package/dist/cli.js ADDED
@@ -0,0 +1,1373 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
6
+ import { dirname as dirname2, join, resolve as resolve2, sep as sep2 } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ // src/mcp.ts
10
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
11
+ import { z } from "zod";
12
+
13
+ // src/guide.ts
14
+ var INSTRUCTIONS = `Depthview connects you to a three.js / React Three Fiber scene running in the developer's Chrome. You can read the live scene, change values on the page at once (undoable), look at the result, and write the final values into the source.
15
+
16
+ 1. Call get_status first. paired:false: give the developer the pairingCode to type into the Depthview side panel, then wait. inspectorOpen:false: ask them to click the Depthview icon on their page.
17
+ 2. Call describe_scene once to learn the scene's scale, camera and lights before you move or size anything.
18
+ 3. Find objects with find_objects, then get_object. Only paths listed in "editable" can be set. Use uuids; they change after a page reload.
19
+ 4. Change values with set_value, or set_values for several at once (one undo step). Start from the current value and work in small steps. Rotations and angles are radians unless you pass degrees:true.
20
+ 5. Check every visible change with take_screenshot view:"site" (compare:true shows before and after). If a result says overwritten:true, the site's code animates that value: tell the developer instead of retrying.
21
+ 6. When it looks right: get_changes, then apply_changes_to_code, then finish every "queued" edit (get_edit_context, then apply_edit or mark_edit_done). Report file, prop and old to new value.
22
+
23
+ Scroll camera path: get_camera_path shows it; edit_camera_path edits it (the developer can also drag its handles); get_camera_path_edit returns the edited keys; save_camera_path writes camera-path.json, or rewrite the developer's own camera code with the keys.
24
+
25
+ Never change unrelated code. Never write a value into the source that is not in get_changes or given by the developer. Tool results often end with "next": follow it.`;
26
+ var PROMPTS = [
27
+ {
28
+ name: "pair",
29
+ title: "Pair with Depthview",
30
+ description: "Connect this agent to the Depthview inspector open in Chrome.",
31
+ text: () => "Pair with Depthview: call get_status. If it is not paired, give me the pairing code and tell me where to type it, then wait for me. Once paired, call describe_scene and tell me in two lines what the scene contains."
32
+ },
33
+ {
34
+ name: "tune",
35
+ title: "Tune the 3D scene",
36
+ description: "Change the live scene towards a goal, checking each step with a screenshot.",
37
+ argument: {
38
+ name: "goal",
39
+ description: 'What should change, e.g. "warmer, moodier lighting" or "camera closer".'
40
+ },
41
+ text: (goal) => `Tune my live three.js scene with the Depthview tools. Goal: ${goal?.trim() || "ask me what I want changed"}.
42
+
43
+ Steps: get_status, describe_scene, then find the objects that matter (find_objects, get_object). Take a take_screenshot view:"site" first. Make the change in small steps with set_values, starting from the current values, and check each step with take_screenshot view:"site" compare:true. At most three rounds. Do not write anything into the source yet: tell me what you changed (object, path, old to new) and ask whether to keep it.`
44
+ },
45
+ {
46
+ name: "apply",
47
+ title: "Write Depthview changes into the code",
48
+ description: "Write every change made in the inspector (by you or by hand) into the source.",
49
+ text: () => 'Write my Depthview changes into the code: get_changes, then apply_changes_to_code. For every edit that comes back "queued", call get_edit_context and finish it with apply_edit or your own edit plus mark_edit_done. Write changes without a source location yourself from get_changes. Then list_pending_edits to confirm nothing is left, and list per change: file, prop, old value to new value. Change nothing else.'
50
+ },
51
+ {
52
+ name: "camera-path",
53
+ title: "Write the edited camera path into the code",
54
+ description: "Put the scroll camera path edited in Depthview into the project: as camera-path.json, or in your own camera code.",
55
+ text: () => `Write my edited Depthview camera path into the code.
56
+
57
+ 1. get_camera_path_edit. If it is not editing, tell me to edit the path first (Camera path > Edit camera path in the inspector) and stop.
58
+ 2. Find how my project moves the camera on scroll: search for useScroll / ScrollControls, ScrollTrigger or gsap timelines on camera.position, CatmullRomCurve3 or other curves, and useFrame code that sets camera.position or calls camera.lookAt. Also check for useCameraPath and camera-path.json.
59
+ 3. If the project already uses useCameraPath with a JSON file, call save_camera_path with that file and stop.
60
+ 4. Otherwise, change my camera code so it follows the keys: each key is a scroll percent with a camera position, a look-at target and a fov. Keep my code's structure (same library, same scroll source, same easing where possible): replace keyframe values, curve points or look-at targets with the new ones, adding or removing keyframes to match. If my code cannot express the path well, ask me whether to switch to useCameraPath(path) from depthview-r3f-bridge/camera-path with save_camera_path.
61
+ 5. Tell me per key what changed in which file, and ask me to check it by scrolling the site.`
62
+ },
63
+ {
64
+ name: "performance",
65
+ title: "Check scene performance",
66
+ description: "Measure the scene and find what costs the most.",
67
+ text: () => "Check the performance of my live three.js scene: get_performance, get_resources and get_lighting. Name the three biggest costs with numbers, and for each one the change you would make. Try a fix live only if it is a value change, measure again with get_performance, and put it back with undo_change unless I say keep it."
68
+ }
69
+ ];
70
+
71
+ // src/mcp.ts
72
+ var text = (value2) => ({
73
+ content: [
74
+ {
75
+ type: "text",
76
+ text: typeof value2 === "string" ? value2 : JSON.stringify(value2, null, 2)
77
+ }
78
+ ]
79
+ });
80
+ var withNext = (data, next) => next && data && typeof data === "object" && !Array.isArray(data) ? { ...data, next } : data;
81
+ var asRec = (v) => v && typeof v === "object" ? v : {};
82
+ var CHECK_NEXT = 'Check it: take_screenshot view:"site" compare:true. Adjust, or when it is right: get_changes, then apply_changes_to_code.';
83
+ var animatedNext = (paths) => `The site's own code moved ${paths.join(", ")} back right after the change: it is animated, scrolled or driven by state. Call get_animated_values. Do not write a constant for it into the source without asking the developer.`;
84
+ var ANGLE_PATHS = /* @__PURE__ */ new Set(["rotation", "angle"]);
85
+ function toRadians(path, value2) {
86
+ if (!ANGLE_PATHS.has(path))
87
+ throw new Error(
88
+ `degrees:true only applies to rotation and angle, not "${path}" (fov is in degrees already).`
89
+ );
90
+ const rad = (n) => Math.round(n * Math.PI / 180 * 1e6) / 1e6;
91
+ if (typeof value2 === "number") return rad(value2);
92
+ if (Array.isArray(value2) && value2.every((n) => typeof n === "number"))
93
+ return value2.map((n) => rad(n));
94
+ throw new Error(`"${path}" with degrees:true needs a number or [x, y, z].`);
95
+ }
96
+ var failure = (err) => ({
97
+ ...text(err instanceof Error ? err.message : String(err)),
98
+ isError: true
99
+ });
100
+ var promptMessage = (body) => ({
101
+ messages: [{ role: "user", content: { type: "text", text: body } }]
102
+ });
103
+ function buildMcpServer(server, options) {
104
+ const { core } = server;
105
+ const mcp = new McpServer(
106
+ { name: "depthview", version: "0.2.0" },
107
+ { instructions: INSTRUCTIONS }
108
+ );
109
+ mcp.registerTool(
110
+ "list_pending_edits",
111
+ {
112
+ description: 'List edits sent from the Depthview browser inspector. Status "queued" means the edit could not be applied automatically and needs you; "applied" was written to source already.',
113
+ inputSchema: {
114
+ status: z.enum(["queued", "applied", "failed", "done"]).optional().describe("Only edits with this status. Default: queued.")
115
+ }
116
+ },
117
+ async ({ status }) => text(core.list(status ?? "queued"))
118
+ );
119
+ mcp.registerTool(
120
+ "get_edit_context",
121
+ {
122
+ description: "Source code around the JSX element an edit targets, with line numbers, plus why it was queued. Always call this before editing.",
123
+ inputSchema: {
124
+ id: z.string(),
125
+ radius: z.number().int().min(1).max(80).optional().describe("Lines before and after. Default 12.")
126
+ }
127
+ },
128
+ async ({ id, radius }) => {
129
+ try {
130
+ return text(core.context(id, radius));
131
+ } catch (err) {
132
+ return failure(err);
133
+ }
134
+ }
135
+ );
136
+ mcp.registerTool(
137
+ "apply_edit",
138
+ {
139
+ description: 'Apply one edit with exact AST replacement of the JSX prop (formatting and comments are kept). Pass `expression` to write a specific expression instead of the literal value, e.g. "[x, 2.5, 0]".',
140
+ inputSchema: { id: z.string(), expression: z.string().max(500).optional() }
141
+ },
142
+ async ({ id, expression }) => {
143
+ try {
144
+ return text(core.apply(id, expression));
145
+ } catch (err) {
146
+ return failure(err);
147
+ }
148
+ }
149
+ );
150
+ mcp.registerTool(
151
+ "mark_edit_done",
152
+ {
153
+ description: "Report the outcome of an edit you made yourself with your own file tools. The browser inspector shows it.",
154
+ inputSchema: {
155
+ id: z.string(),
156
+ status: z.enum(["done", "failed"]).optional(),
157
+ note: z.string().max(300).optional()
158
+ }
159
+ },
160
+ async ({ id, status, note }) => {
161
+ try {
162
+ return text(core.markDone(id, status ?? "done", note));
163
+ } catch (err) {
164
+ return failure(err);
165
+ }
166
+ }
167
+ );
168
+ mcp.registerTool(
169
+ "get_scene_snapshot",
170
+ {
171
+ description: "The live three.js scene from the inspected page as JSON: scene tree, site camera, renderer info and the values the developer changed.",
172
+ inputSchema: {}
173
+ },
174
+ async () => {
175
+ const snapshot = await server.requestSnapshot();
176
+ return snapshot ? text(snapshot) : failure(
177
+ "No scene snapshot yet. Open the Depthview inspector on the page and pair it with this server."
178
+ );
179
+ }
180
+ );
181
+ const live = async (method, params = {}, timeoutMs, next) => {
182
+ try {
183
+ const data = await server.rpc(method, params, timeoutMs);
184
+ return text(next ? withNext(data, next(asRec(data))) : data);
185
+ } catch (err) {
186
+ return failure(err);
187
+ }
188
+ };
189
+ const target = {
190
+ uuid: z.string().max(64).optional().describe("Object id from find_objects."),
191
+ name: z.string().max(128).optional().describe("Object name, when it is unique in the scene. Use uuid otherwise.")
192
+ };
193
+ const editValue = z.union([
194
+ z.number().finite(),
195
+ z.boolean(),
196
+ z.string().max(128),
197
+ z.array(z.number().finite()).length(3)
198
+ ]);
199
+ mcp.registerTool(
200
+ "get_status",
201
+ {
202
+ description: "Whether the browser inspector is connected, which page it is on, the three.js version, the object the developer has selected and how many values are changed. Call this first.",
203
+ inputSchema: {}
204
+ },
205
+ async () => {
206
+ if (!server.extensionConnected)
207
+ return text({
208
+ paired: false,
209
+ pairingCode: server.code,
210
+ next: `Tell the developer: open your site in Chrome, click the Depthview icon, and type ${server.code} under "AI agent & code sync" in the side panel. Then wait for them and call get_status again.`
211
+ });
212
+ try {
213
+ const status = asRec(await server.rpc("status"));
214
+ const next = status.sceneAvailable === false ? "This page has no readable three.js scene (not loaded yet, or the WebGPU renderer). Say so; do not guess values." : status.sourceLocations === false ? "Live tuning works, but objects have no source locations: you will find the code yourself when writing changes. Call describe_scene next." : "Call describe_scene to learn the scale, camera and lights, then find_objects.";
215
+ return text({ paired: true, ...status, next });
216
+ } catch (err) {
217
+ return text({
218
+ paired: true,
219
+ inspectorOpen: false,
220
+ error: err.message,
221
+ next: "Ask the developer to click the Depthview icon on their page and keep that tab in front, then call get_status again."
222
+ });
223
+ }
224
+ }
225
+ );
226
+ mcp.registerTool(
227
+ "describe_scene",
228
+ {
229
+ description: "A short summary of the live scene: how big it is in scene units (center and radius), what the site camera looks at, the camera (position, fov, distance to the scene), every light (type, colour, intensity, position), object counts by kind and renderer numbers. Call it once before moving, sizing or adding anything, so values fit the scene's scale.",
230
+ inputSchema: {}
231
+ },
232
+ async () => live(
233
+ "describe",
234
+ {},
235
+ void 0,
236
+ () => "find_objects to locate what you want to change, then get_object for its editable paths."
237
+ )
238
+ );
239
+ mcp.registerTool(
240
+ "find_objects",
241
+ {
242
+ description: "Search the live scene. Returns id, name, type, kind and the path from the scene root for each match. Use it instead of get_scene_snapshot when the scene is large.",
243
+ inputSchema: {
244
+ query: z.string().max(128).optional().describe("Part of a name or a three.js type, case ignored. Empty: everything."),
245
+ kind: z.enum(["mesh", "points", "light", "camera", "object"]).optional(),
246
+ limit: z.number().int().min(1).max(500).optional().describe("Default 50.")
247
+ }
248
+ },
249
+ async (params) => live(
250
+ "find",
251
+ params,
252
+ void 0,
253
+ (d) => d.total === 0 ? 'Nothing matched. Try a three.js type ("light", "Mesh", "PerspectiveCamera"), a kind filter, or an empty query.' : "get_object with a uuid to read its values and editable paths."
254
+ )
255
+ );
256
+ mcp.registerTool(
257
+ "get_object",
258
+ {
259
+ description: "Everything the inspector knows about one object: transform, light / camera / material values, shader uniforms, textures, its world-space bounding box in scene units (`worldBounds`: min, max, size, center; null for lights and cameras), and where its JSX element is in the source (`source`, `materialSource`) when the project uses depthview-r3f-bridge. `editable` lists every path set_value accepts for it, with the current value. With no uuid or name: the object the developer has selected.",
260
+ inputSchema: target
261
+ },
262
+ async (params) => live(
263
+ "object",
264
+ params,
265
+ void 0,
266
+ () => "Change it with set_value (one value) or set_values (several, one undo step), using a path from editable. select_object shows the developer which object you mean."
267
+ )
268
+ );
269
+ mcp.registerTool(
270
+ "set_value",
271
+ {
272
+ description: 'Change one value on the live page, at once, without touching source code. The developer sees it happen, it appears under Changes in the inspector and can be undone. Paths: position, rotation (radians), scale, visible, castShadow, receiveShadow; lights: color, intensity, distance, decay, angle, penumbra; cameras: fov, near, far, zoom; materials: material.color, material.roughness, material.metalness, material.opacity, material.transparent, material.emissive, material.emissiveIntensity, material.side, material.wireframe, material.flatShading, material.depthTest, material.depthWrite, material.size; shaders: uniform.<name>. Vectors are [x, y, z], colours are "#rrggbb". The result has `before`, the new `value`, and `overwritten: true` when the site\'s own code moved the value back straight away (it is animated).',
273
+ inputSchema: {
274
+ ...target,
275
+ path: z.string().regex(/^[A-Za-z_$][\w$.]{0,80}$/),
276
+ value: editValue,
277
+ degrees: z.boolean().optional().describe("The value of rotation or angle is in degrees; it is converted to radians.")
278
+ }
279
+ },
280
+ async ({ degrees, ...params }) => {
281
+ try {
282
+ if (degrees) params.value = toRadians(params.path, params.value);
283
+ } catch (err) {
284
+ return failure(err);
285
+ }
286
+ return live(
287
+ "set",
288
+ params,
289
+ void 0,
290
+ (d) => d.overwritten ? animatedNext([String(d.path)]) : CHECK_NEXT
291
+ );
292
+ }
293
+ );
294
+ mcp.registerTool(
295
+ "set_values",
296
+ {
297
+ description: "Change several values on the live page in one go, on one or more objects: a lighting set-up, a camera move, a material look. Every change is checked first and nothing is changed if one is wrong. They appear under Changes and one undo_change takes all of them back. Same paths and values as set_value.",
298
+ inputSchema: {
299
+ changes: z.array(
300
+ z.object({
301
+ ...target,
302
+ path: z.string().regex(/^[A-Za-z_$][\w$.]{0,80}$/),
303
+ value: editValue,
304
+ degrees: z.boolean().optional()
305
+ })
306
+ ).min(1).max(40)
307
+ }
308
+ },
309
+ async ({ changes }) => {
310
+ let converted;
311
+ try {
312
+ converted = changes.map(
313
+ ({ degrees, ...c }) => degrees ? { ...c, value: toRadians(c.path, c.value) } : c
314
+ );
315
+ } catch (err) {
316
+ return failure(err);
317
+ }
318
+ return live("setMany", { changes: converted }, 15e3, (d) => {
319
+ const moved = (Array.isArray(d.results) ? d.results : []).filter((r) => r.overwritten).map((r) => `${String(r.object || r.uuid)}.${String(r.path)}`);
320
+ return moved.length ? animatedNext(moved) : CHECK_NEXT;
321
+ });
322
+ }
323
+ );
324
+ mcp.registerTool(
325
+ "get_changes",
326
+ {
327
+ description: "Everything that differs from what the page loaded with, whether the developer changed it in the inspector or you did: changed values (object, path, original and current value, source location when known, and the same as React Three Fiber JSX), objects added (with their JSX), objects removed, and shaders replaced.",
328
+ inputSchema: {}
329
+ },
330
+ async () => live("changes", {}, void 0, (d) => {
331
+ const n = (Array.isArray(d.changes) ? d.changes.length : 0) + (Array.isArray(d.added) ? d.added.length : 0) + (Array.isArray(d.removed) ? d.removed.length : 0) + (Array.isArray(d.shaders) ? d.shaders.length : 0);
332
+ return n === 0 ? "Nothing is changed. Say so and stop." : "apply_changes_to_code writes the value changes. Added objects, removed objects and shaders are written by you with your own file tools.";
333
+ })
334
+ );
335
+ mcp.registerTool(
336
+ "apply_changes_to_code",
337
+ {
338
+ description: 'Write all current changes into the source files (same as the "Apply to code" button). Literal props are rewritten directly; the rest come back with status "queued" for you to finish with get_edit_context and apply_edit. Changes on objects without a source location are counted in `unmapped`: write those yourself from get_changes.',
339
+ inputSchema: {}
340
+ },
341
+ async () => live("apply", {}, void 0, (d) => {
342
+ const edits = Array.isArray(d.edits) ? d.edits : [];
343
+ const queued = edits.filter((e) => e.status === "queued").length;
344
+ const failed = edits.filter((e) => e.status === "failed").length;
345
+ const unmapped = typeof d.unmapped === "number" ? d.unmapped : 0;
346
+ const todo = [
347
+ queued && `${queued} queued: get_edit_context, then apply_edit or mark_edit_done for each`,
348
+ failed && `${failed} failed: report their message`,
349
+ unmapped && `${unmapped} without a source location: write them yourself from get_changes`
350
+ ].filter(Boolean);
351
+ if (todo.length)
352
+ return `${todo.join("; ")}. Then list_pending_edits to confirm nothing is left.`;
353
+ return edits.length ? "All written. Tell the developer per change: file, prop, old value to new value." : void 0;
354
+ })
355
+ );
356
+ mcp.registerTool(
357
+ "select_object",
358
+ {
359
+ description: "Select an object in the inspector so the developer sees which one you mean (it is outlined and its values are shown).",
360
+ inputSchema: target
361
+ },
362
+ async (params) => live("select", params)
363
+ );
364
+ mcp.registerTool(
365
+ "undo_change",
366
+ { description: "Undo the latest live change (one step).", inputSchema: {} },
367
+ async () => live(
368
+ "undo",
369
+ {},
370
+ void 0,
371
+ () => "One undo step taken (a whole set_values call is one step)."
372
+ )
373
+ );
374
+ mcp.registerTool(
375
+ "reset_changes",
376
+ {
377
+ description: "Put everything back to what the page loaded with: changed values, added and removed objects, replaced shaders. Ask the developer first if they made changes themselves.",
378
+ inputSchema: {}
379
+ },
380
+ async () => live("reset")
381
+ );
382
+ mcp.registerTool(
383
+ "take_screenshot",
384
+ {
385
+ description: 'A picture of what is on screen now. view "inspector" (default): the whole tab with the inspector\'s panels. "scene": only the inspector\'s 3D view, from its free camera, with helpers. "site": the real page exactly as a visitor sees it, HTML included, with the inspector out of the way: use this to judge the result. `angle` turns the inspector camera first (not for "site"). `compare: true` also returns the previous picture of the same view, labelled before and after, to judge a change. The tab must be in front.',
386
+ inputSchema: {
387
+ view: z.enum(["inspector", "scene", "site"]).optional(),
388
+ angle: z.enum(["front", "side", "back", "reset"]).optional(),
389
+ compare: z.boolean().optional().describe('Also return the previous picture of this view, as "before".')
390
+ }
391
+ },
392
+ async ({ compare, ...params }) => {
393
+ try {
394
+ const view = params.view ?? "inspector";
395
+ const shot = await server.rpc("screenshot", params, 2e4);
396
+ const image = { type: "image", data: shot.data, mimeType: shot.mimeType };
397
+ const previous = server.lastShots.get(view);
398
+ server.lastShots.set(view, { data: shot.data, mimeType: shot.mimeType });
399
+ if (!compare) return { content: [image] };
400
+ if (!previous)
401
+ return {
402
+ content: [
403
+ {
404
+ type: "text",
405
+ text: `No earlier "${view}" picture to compare with: this one is the baseline. Take another after the change.`
406
+ },
407
+ image
408
+ ]
409
+ };
410
+ return {
411
+ content: [
412
+ { type: "text", text: `Before (previous "${view}" picture):` },
413
+ { type: "image", data: previous.data, mimeType: previous.mimeType },
414
+ { type: "text", text: "After (now):" },
415
+ image
416
+ ]
417
+ };
418
+ } catch (err) {
419
+ return failure(err);
420
+ }
421
+ }
422
+ );
423
+ mcp.registerTool(
424
+ "get_performance",
425
+ {
426
+ description: "Measures the running scene for a moment: frames per second, frame time (average, 95th percentile, worst), draw calls, triangles and render passes per frame, canvas size and pixel ratio, JS heap, and every renderer.render() call of one frame (scene, shadow and post-processing passes with their cost). Use it before and after a change to prove the change helped.",
427
+ inputSchema: {
428
+ seconds: z.number().min(0.5).max(5).optional().describe("How long to measure. Default 1.5.")
429
+ }
430
+ },
431
+ async (params) => live("performance", params, 15e3)
432
+ );
433
+ mcp.registerTool(
434
+ "get_resources",
435
+ {
436
+ description: "What the scene holds in GPU memory: textures, geometries and materials, biggest first, with size, memory and how many objects use each. Finds the oversized texture, the duplicated material and the heavy geometry.",
437
+ inputSchema: {
438
+ limit: z.number().int().min(1).max(100).optional().describe("Rows per list. Default 15.")
439
+ }
440
+ },
441
+ async (params) => live("resources", params)
442
+ );
443
+ mcp.registerTool(
444
+ "get_errors",
445
+ {
446
+ description: "What the page logged: uncaught errors and rejected promises since it loaded, console.error and console.warn since the inspector was opened, and shader programs that failed to compile. Call it when something does not show or after a source edit.",
447
+ inputSchema: {
448
+ clear: z.boolean().optional().describe("Empty the list after reading it.")
449
+ }
450
+ },
451
+ async (params) => live("errors", params)
452
+ );
453
+ mcp.registerTool(
454
+ "get_lighting",
455
+ {
456
+ description: "Every light with its cost and shadow set-up, and a list of problems found: castShadow with shadows switched off on the renderer, nothing casting or receiving, oversized shadow maps, point-light shadows (6 passes), a directional shadow camera that is far larger than the casters (blurry shadows) or too small (cut-off shadows), too many lights.",
457
+ inputSchema: {}
458
+ },
459
+ async () => live("lighting")
460
+ );
461
+ mcp.registerTool(
462
+ "get_shader",
463
+ {
464
+ description: "The GLSL of an object's material as it runs on the page, with line numbers, plus its uniforms. `kind` says whether this is the full program three.js compiled or the source as written. Long shaders: read them in parts with fromLine and lines.",
465
+ inputSchema: {
466
+ ...target,
467
+ stage: z.enum(["vertex", "fragment"]).optional().describe("Default: both."),
468
+ fromLine: z.number().int().min(1).optional(),
469
+ lines: z.number().int().min(1).max(2e3).optional().describe("Default 400.")
470
+ }
471
+ },
472
+ async (params) => live("shader", params)
473
+ );
474
+ mcp.registerTool(
475
+ "set_shader",
476
+ {
477
+ description: "Replace the vertex and/or fragment shader of a ShaderMaterial or RawShaderMaterial on the live page and compile it. Returns the compiler's errors with line numbers; a shader that does not compile is put back at once. Send the material's own source (as in the project file), complete, not the expanded program from get_shader. Live only: write the same source into the file when it is right.",
478
+ inputSchema: {
479
+ ...target,
480
+ vertex: z.string().max(2e5).optional(),
481
+ fragment: z.string().max(2e5).optional()
482
+ }
483
+ },
484
+ async (params) => live("setShader", params, 12e3)
485
+ );
486
+ mcp.registerTool(
487
+ "set_scroll",
488
+ {
489
+ description: "Scroll the site to a position, 0 (top) to 100 (bottom), and return where the site camera is there. Use it to check a scroll-driven scene at several points.",
490
+ inputSchema: { percent: z.number().min(0).max(100) }
491
+ },
492
+ async (params) => live("scroll", params, 12e3)
493
+ );
494
+ mcp.registerTool(
495
+ "set_time",
496
+ {
497
+ description: 'Hold, step or release the site\'s animation. "pause" freezes the page\'s clock and its animation frames; "step" moves it on by `frames` frames of `stepMs` each (default 1 frame of 16.67 ms) so you can look at one exact moment; "resume" lets it run again without a jump. Always resume when done.',
498
+ inputSchema: {
499
+ action: z.enum(["pause", "step", "resume"]),
500
+ frames: z.number().int().min(1).max(600).optional(),
501
+ stepMs: z.number().min(0.1).max(1e3).optional()
502
+ }
503
+ },
504
+ async (params) => live("time", params)
505
+ );
506
+ mcp.registerTool(
507
+ "get_animated_values",
508
+ {
509
+ description: "Which values the site's own code is moving: `overTime` lists what changes by itself while you watch, `onScroll` what changes when the page scrolls. Also reports animation clips on objects, React Three Fiber useFrame callbacks and GSAP tweens. Call it before writing any position, rotation, scale, opacity or uniform into the source: a value listed here is driven by code, and a constant in JSX would be overwritten.",
510
+ inputSchema: {
511
+ seconds: z.number().min(0.3).max(4).optional().describe("How long to watch. Default 1."),
512
+ checkScroll: z.boolean().optional().describe("Also scroll the page to see what follows it, then scroll back. Default true.")
513
+ }
514
+ },
515
+ async (params) => live("animated", params, 2e4)
516
+ );
517
+ mcp.registerTool(
518
+ "get_camera_path",
519
+ {
520
+ description: "How the site camera moves as the page scrolls: position, rotation (quaternion) and field of view at up to 40 scroll positions. Records the path by scrolling the page if it has not been recorded yet.",
521
+ inputSchema: {
522
+ record: z.boolean().optional().describe("Record again even if a path exists.")
523
+ }
524
+ },
525
+ async (params) => live(
526
+ "cameraPath",
527
+ params,
528
+ 6e4,
529
+ () => 'To change this path: edit_camera_path with action "start" turns it into a few keys you (or the developer, by dragging in the view) can move.'
530
+ )
531
+ );
532
+ const vec32 = z.array(z.number().finite()).length(3);
533
+ mcp.registerTool(
534
+ "get_camera_path_edit",
535
+ {
536
+ description: "The scroll camera path as it is being edited in the inspector (by the developer dragging handles, or by you): `keys` (each: scroll `percent` 0-100, camera `position`, look-at `target`, `fov`, world space), the `original` keys from the recording, `changes` as readable lines, where it was saved (`savedTo`), the camera-path.json contents (`json`) and a TypeScript snippet (`code`). Between keys the camera follows a Catmull-Rom curve through the positions and through the targets.",
537
+ inputSchema: {}
538
+ },
539
+ async () => live(
540
+ "pathEdit",
541
+ {},
542
+ void 0,
543
+ (d) => d.editing ? `To put it into the project: save_camera_path (a JSON file for useCameraPath), or rewrite the developer's own scroll camera code with these keys (read it first; see the "camera-path" prompt).` : void 0
544
+ )
545
+ );
546
+ mcp.registerTool(
547
+ "edit_camera_path",
548
+ {
549
+ description: 'Edit the scroll camera path live, the same as dragging its handles in the inspector. action "start": turn the recorded path into editable keys (or pass `keys`). "set_key": move key `index` (`position`, `target`, `fov`, `percent`). "add_key": a new key at `percent` on the current curve (optionally with `position`/`target`). "remove_key": key `index`. "preview": the site camera follows the edited path (`on`, default true). "reset": back to the recording. "stop": end editing. `scroll` moves the page to a percent afterwards, to look at the result with take_screenshot view:"site". Returns the edit as get_camera_path_edit does.',
550
+ inputSchema: {
551
+ action: z.enum(["start", "set_key", "add_key", "remove_key", "preview", "reset", "stop"]),
552
+ index: z.number().int().min(0).optional(),
553
+ position: vec32.optional(),
554
+ target: vec32.optional(),
555
+ fov: z.number().min(1).max(179).optional(),
556
+ percent: z.number().min(0).max(100).optional(),
557
+ on: z.boolean().optional(),
558
+ scroll: z.number().min(0).max(100).optional(),
559
+ keys: z.array(
560
+ z.object({
561
+ percent: z.number().min(0).max(100),
562
+ position: vec32,
563
+ target: vec32,
564
+ fov: z.number().min(1).max(179)
565
+ })
566
+ ).max(200).optional()
567
+ }
568
+ },
569
+ async (params) => live(
570
+ "pathAction",
571
+ params,
572
+ 15e3,
573
+ (d) => d.editing === false ? void 0 : d.preview ? 'Look at it: set_scroll or scroll, then take_screenshot view:"site" compare:true.' : 'edit_camera_path action "preview" shows the edited path on the live site.'
574
+ )
575
+ );
576
+ mcp.registerTool(
577
+ "save_camera_path",
578
+ {
579
+ description: "Write the edited camera path into the project as JSON (default src/camera-path.json, or `file`, a .json path inside the project). The site then drives its camera with `useCameraPath(path)` from depthview-r3f-bridge/camera-path. Use this when the developer wants the file; to keep their own camera code, rewrite that code instead.",
580
+ inputSchema: { file: z.string().max(512).optional() }
581
+ },
582
+ async (params) => live("pathSave", params, 15e3, (d) => {
583
+ const file = String(d.file ?? "the file");
584
+ return `Saved ${file}. If the project does not use it yet: import path from './${file.split("/").pop()}' and call useCameraPath(path) inside <Canvas> in place of the old scroll camera code (ask the developer before removing their code).`;
585
+ })
586
+ );
587
+ mcp.registerTool(
588
+ "add_object",
589
+ {
590
+ description: 'Add an object to the live scene and get its React Three Fiber JSX back. `copyOf` duplicates an existing object (always works). `kind` makes a new one: "box", "sphere", "plane" (unit-sized meshes), "Group", or a light type the page already uses, such as "PointLight" (the classes are taken from the site\'s own three.js, so a light type the site never created cannot be made: the error lists what can). Live only: it is gone after a reload until the JSX is in the source.',
591
+ inputSchema: {
592
+ kind: z.string().max(40).optional(),
593
+ copyOf: z.string().max(64).optional().describe("uuid of the object to duplicate."),
594
+ parent: z.string().max(64).optional().describe("uuid of the parent. Default: the scene."),
595
+ objectName: z.string().max(80).optional().describe("Name for the new object."),
596
+ position: z.array(z.number().finite()).length(3).optional(),
597
+ color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),
598
+ intensity: z.number().finite().optional()
599
+ }
600
+ },
601
+ async (params) => live("add", params)
602
+ );
603
+ mcp.registerTool(
604
+ "remove_object",
605
+ {
606
+ description: "Take an object (and its children) out of the live scene, to see the scene without it or measure what it costs. Returns its source location when known. Live only: reset_changes puts it back.",
607
+ inputSchema: target
608
+ },
609
+ async (params) => live("remove", params)
610
+ );
611
+ mcp.registerTool(
612
+ "set_viewport",
613
+ {
614
+ description: "Responsive check. `width` and `height` resize the browser window so the page gets that size, and the site's own resize code runs; the result says the size really reached (a window cannot go below about 500 px wide). `pixelRatio` sets the renderer's pixel ratio live, to measure what a 2x or 3x phone screen costs with get_performance. `reset: true` puts the window and the pixel ratio back: always do that when done.",
615
+ inputSchema: {
616
+ width: z.number().int().min(200).max(7680).optional(),
617
+ height: z.number().int().min(200).max(4320).optional(),
618
+ pixelRatio: z.number().min(0.25).max(4).optional(),
619
+ reset: z.boolean().optional()
620
+ }
621
+ },
622
+ async (params) => live("viewport", params, 12e3)
623
+ );
624
+ for (const prompt of PROMPTS) {
625
+ const arg = prompt.argument;
626
+ if (arg)
627
+ mcp.registerPrompt(
628
+ prompt.name,
629
+ {
630
+ title: prompt.title,
631
+ description: prompt.description,
632
+ argsSchema: { [arg.name]: z.string().optional().describe(arg.description) }
633
+ },
634
+ (args) => promptMessage(prompt.text(args[arg.name]))
635
+ );
636
+ else
637
+ mcp.registerPrompt(
638
+ prompt.name,
639
+ { title: prompt.title, description: prompt.description },
640
+ () => promptMessage(prompt.text(void 0))
641
+ );
642
+ }
643
+ const resource = (name, uri, description, read) => {
644
+ mcp.registerResource(
645
+ name,
646
+ uri,
647
+ { title: name, description, mimeType: "application/json" },
648
+ async () => {
649
+ let value2;
650
+ try {
651
+ value2 = await read();
652
+ } catch (err) {
653
+ value2 = { error: err instanceof Error ? err.message : String(err) };
654
+ }
655
+ return {
656
+ contents: [{ uri, mimeType: "application/json", text: JSON.stringify(value2, null, 2) }]
657
+ };
658
+ }
659
+ );
660
+ };
661
+ resource(
662
+ "status",
663
+ "depthview://status",
664
+ "Paired? Which page, what is selected, how many values are changed.",
665
+ async () => server.extensionConnected ? { paired: true, ...asRec(await server.rpc("status")) } : { paired: false, pairingCode: server.code }
666
+ );
667
+ resource(
668
+ "scene",
669
+ "depthview://scene",
670
+ "Summary of the live scene: scale, camera, lights, object counts.",
671
+ () => server.rpc("describe")
672
+ );
673
+ resource(
674
+ "selection",
675
+ "depthview://selection",
676
+ "The object selected in the inspector, with its editable values and bounds.",
677
+ () => server.rpc("object")
678
+ );
679
+ resource(
680
+ "changes",
681
+ "depthview://changes",
682
+ "Everything changed on the live page, with source locations.",
683
+ () => server.rpc("changes")
684
+ );
685
+ if (options.includePairingCode) {
686
+ mcp.registerTool(
687
+ "get_pairing_code",
688
+ {
689
+ description: "One-time code the developer types into the Depthview extension to pair it with this server.",
690
+ inputSchema: {}
691
+ },
692
+ async () => text({ code: server.code, paired: server.extensionConnected })
693
+ );
694
+ }
695
+ return mcp;
696
+ }
697
+
698
+ // src/server.ts
699
+ import { randomInt, timingSafeEqual } from "node:crypto";
700
+ import { createServer } from "node:http";
701
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
702
+ import { WebSocketServer } from "ws";
703
+ import { z as z3 } from "zod";
704
+
705
+ // src/core.ts
706
+ import { randomUUID } from "node:crypto";
707
+ import { EventEmitter } from "node:events";
708
+ import { existsSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
709
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
710
+ import { z as z2 } from "zod";
711
+
712
+ // src/edits.ts
713
+ import { parse as babelParse, parseExpression } from "@babel/parser";
714
+ import recast from "recast";
715
+ var b = recast.types.builders;
716
+ var parser = {
717
+ parse: (source) => babelParse(source, {
718
+ sourceType: "module",
719
+ tokens: true,
720
+ allowReturnOutsideFunction: true,
721
+ plugins: ["jsx", "typescript"]
722
+ })
723
+ };
724
+ var round = (n) => {
725
+ const r = Math.round(n * 1e3) / 1e3;
726
+ return Object.is(r, -0) ? 0 : r;
727
+ };
728
+ var numberNode = (n) => {
729
+ const v = round(n);
730
+ return v < 0 ? b.unaryExpression("-", b.numericLiteral(-v)) : b.numericLiteral(v);
731
+ };
732
+ function evalConstant(node) {
733
+ if (!node) return void 0;
734
+ switch (node.type) {
735
+ case "NumericLiteral":
736
+ return node.value;
737
+ case "Literal":
738
+ return typeof node.value === "number" ? node.value : void 0;
739
+ case "UnaryExpression": {
740
+ const v = evalConstant(node.argument);
741
+ if (v === void 0) return void 0;
742
+ return node.operator === "-" ? -v : node.operator === "+" ? v : void 0;
743
+ }
744
+ case "BinaryExpression": {
745
+ const l = evalConstant(node.left);
746
+ const r = evalConstant(node.right);
747
+ if (l === void 0 || r === void 0) return void 0;
748
+ if (node.operator === "+") return l + r;
749
+ if (node.operator === "-") return l - r;
750
+ if (node.operator === "*") return l * r;
751
+ if (node.operator === "/") return l / r;
752
+ return void 0;
753
+ }
754
+ case "MemberExpression":
755
+ return !node.computed && node.object?.type === "Identifier" && node.object.name === "Math" && node.property?.name === "PI" ? Math.PI : void 0;
756
+ case "ParenthesizedExpression":
757
+ case "TSAsExpression":
758
+ case "TSNonNullExpression":
759
+ return evalConstant(node.expression);
760
+ default:
761
+ return void 0;
762
+ }
763
+ }
764
+ var isSimpleLiteral = (node) => ["StringLiteral", "BooleanLiteral", "NullLiteral", "Literal"].includes(node?.type) || evalConstant(node) !== void 0;
765
+ function literalNode(value2) {
766
+ if (typeof value2 === "number") return numberNode(value2);
767
+ if (typeof value2 === "boolean") return b.booleanLiteral(value2);
768
+ if (typeof value2 === "string") return b.stringLiteral(value2);
769
+ return b.arrayExpression(value2.map(numberNode));
770
+ }
771
+ function attributeValue(value2) {
772
+ if (value2 === true) return null;
773
+ if (typeof value2 === "string") return b.stringLiteral(value2);
774
+ return b.jsxExpressionContainer(literalNode(value2));
775
+ }
776
+ var needsAgent = (reason) => ({ ok: false, needsAgent: true, reason });
777
+ function applyJsxPropEdit(source, edit) {
778
+ let ast;
779
+ try {
780
+ ast = recast.parse(source, { parser });
781
+ } catch (err) {
782
+ return needsAgent(
783
+ `Could not parse the file: ${err instanceof Error ? err.message : String(err)}`
784
+ );
785
+ }
786
+ const onLine = [];
787
+ recast.types.visit(ast, {
788
+ visitJSXOpeningElement(path) {
789
+ const loc = path.node.loc;
790
+ if (loc && loc.start.line === edit.line) onLine.push(path.node);
791
+ this.traverse(path);
792
+ }
793
+ });
794
+ const element = onLine.find((n) => n.loc.start.column === edit.column) ?? (onLine.length === 1 ? onLine[0] : void 0);
795
+ if (!element) {
796
+ return needsAgent(
797
+ `No JSX element starts at line ${edit.line}, column ${edit.column}. The file may have changed since the page loaded.`
798
+ );
799
+ }
800
+ const attributes = element.attributes;
801
+ const attr = attributes.find(
802
+ (a) => a.type === "JSXAttribute" && a.name?.type === "JSXIdentifier" && a.name.name === edit.prop
803
+ );
804
+ const hasSpread = attributes.some((a) => a.type === "JSXSpreadAttribute");
805
+ const firstChar = attr?.value?.type === "StringLiteral" && typeof attr.value.start === "number" ? source[attr.value.start] : void 0;
806
+ const print = (note) => {
807
+ const code = recast.print(ast, { quote: firstChar === "'" ? "single" : "double" }).code;
808
+ return { ok: true, code, changed: code !== source, note };
809
+ };
810
+ if (edit.expression !== void 0) {
811
+ let expression;
812
+ try {
813
+ expression = parseExpression(edit.expression, { plugins: ["jsx", "typescript"] });
814
+ } catch (err) {
815
+ return {
816
+ ok: false,
817
+ needsAgent: false,
818
+ reason: `Invalid expression: ${err instanceof Error ? err.message : String(err)}`
819
+ };
820
+ }
821
+ const container = b.jsxExpressionContainer(expression);
822
+ if (attr) attr.value = container;
823
+ else attributes.push(b.jsxAttribute(b.jsxIdentifier(edit.prop), container));
824
+ return print();
825
+ }
826
+ const value2 = edit.newValue;
827
+ if (!attr) {
828
+ if (hasSpread)
829
+ return needsAgent(
830
+ `\`${edit.prop}\` is not written on this element and the element spreads props from a variable.`
831
+ );
832
+ attributes.push(b.jsxAttribute(b.jsxIdentifier(edit.prop), attributeValue(value2)));
833
+ return print(`Added the \`${edit.prop}\` prop (it was not set in source).`);
834
+ }
835
+ if (attr.value === null || attr.value === void 0) {
836
+ if (value2 === true) return print();
837
+ attr.value = attributeValue(value2);
838
+ return print();
839
+ }
840
+ if (attr.value.type === "StringLiteral" || attr.value.type === "Literal") {
841
+ attr.value = attributeValue(value2);
842
+ return print();
843
+ }
844
+ if (attr.value.type !== "JSXExpressionContainer")
845
+ return needsAgent(`Unsupported value for \`${edit.prop}\`.`);
846
+ const expr = attr.value.expression;
847
+ const text2 = typeof expr.start === "number" ? source.slice(expr.start, expr.end) : expr.type;
848
+ const computed = () => needsAgent(`\`${edit.prop}\` is computed in code (\`${text2}\`), not a literal.`);
849
+ if (Array.isArray(value2)) {
850
+ if (expr.type === "ArrayExpression") {
851
+ const current = expr.elements.map(evalConstant);
852
+ if (current.some((v) => v === void 0)) return computed();
853
+ if (current.length !== value2.length) attr.value.expression = literalNode(value2);
854
+ else {
855
+ value2.forEach((v, i) => {
856
+ if (Math.abs(current[i] - v) > 5e-4) expr.elements[i] = numberNode(v);
857
+ });
858
+ }
859
+ return print();
860
+ }
861
+ if (evalConstant(expr) === void 0) return computed();
862
+ const uniform = value2.every((v) => round(v) === round(value2[0]));
863
+ attr.value.expression = uniform && edit.prop === "scale" ? numberNode(value2[0]) : literalNode(value2);
864
+ return print();
865
+ }
866
+ if (!isSimpleLiteral(expr)) return computed();
867
+ if (typeof value2 === "number") {
868
+ const current = evalConstant(expr);
869
+ if (current !== void 0 && Math.abs(current - value2) <= 5e-4) return print();
870
+ }
871
+ attr.value.expression = literalNode(value2);
872
+ return print();
873
+ }
874
+ function sourceContext(source, line, radius = 12) {
875
+ const lines = source.split("\n");
876
+ const from = Math.max(1, line - radius);
877
+ const to = Math.min(lines.length, line + radius);
878
+ const width = String(to).length;
879
+ return lines.slice(from - 1, to).map(
880
+ (text2, i) => `${from + i === line ? ">" : " "} ${String(from + i).padStart(width)} | ${text2}`
881
+ ).join("\n");
882
+ }
883
+
884
+ // src/core.ts
885
+ var value = z2.union([
886
+ z2.number().finite(),
887
+ z2.boolean(),
888
+ z2.string().max(128),
889
+ z2.array(z2.number().finite()).min(2).max(4)
890
+ ]);
891
+ var editIntentSchema = z2.object({
892
+ file: z2.string().min(1).max(1024),
893
+ line: z2.number().int().min(1),
894
+ column: z2.number().int().min(0),
895
+ component: z2.string().max(128).default(""),
896
+ prop: z2.string().regex(/^[A-Za-z_$][\w$-]{0,63}$/),
897
+ oldValue: value,
898
+ newValue: value
899
+ });
900
+ var SOURCE_FILE = /\.(jsx|tsx|js|ts|mjs)$/;
901
+ var vec3 = z2.tuple([z2.number().finite(), z2.number().finite(), z2.number().finite()]);
902
+ var cameraPathSchema = z2.object({
903
+ version: z2.literal(1),
904
+ keys: z2.array(
905
+ z2.object({
906
+ percent: z2.number().min(0).max(100),
907
+ position: vec3,
908
+ target: vec3,
909
+ fov: z2.number().min(1).max(179)
910
+ })
911
+ ).min(1).max(200)
912
+ });
913
+ var DepthviewCore = class extends EventEmitter {
914
+ root;
915
+ edits = /* @__PURE__ */ new Map();
916
+ snapshot = null;
917
+ constructor(root) {
918
+ super();
919
+ this.root = realpathSync(resolve(root));
920
+ }
921
+ /** Resolves a path from the browser and refuses anything outside the project. */
922
+ resolveFile(file) {
923
+ const real = realpathSync(isAbsolute(file) ? file : resolve(this.root, file));
924
+ if (!real.startsWith(this.root + sep)) throw new Error("File is outside the project root");
925
+ if (real.split(sep).includes("node_modules"))
926
+ throw new Error("Files in node_modules are not edited");
927
+ if (!SOURCE_FILE.test(real)) throw new Error("Not a JavaScript/TypeScript source file");
928
+ return real;
929
+ }
930
+ /**
931
+ * Writes the edited camera path as JSON into the project. Default: src/camera-path.json when
932
+ * the project has a src folder, else camera-path.json. Only .json files, inside the root, in a
933
+ * folder that exists, never in node_modules.
934
+ */
935
+ writeCameraPath(path, file) {
936
+ const wanted = file && file.trim() ? file.trim() : existsSync(resolve(this.root, "src")) ? "src/camera-path.json" : "camera-path.json";
937
+ if (!/^[\w.-]+\.json$/.test(basename(wanted)))
938
+ throw new Error("The camera path file must be a .json file name (letters, digits, - _ .).");
939
+ const target = isAbsolute(wanted) ? wanted : resolve(this.root, wanted);
940
+ let folder;
941
+ try {
942
+ folder = realpathSync(dirname(target));
943
+ } catch {
944
+ throw new Error(`The folder ${relative(this.root, dirname(target)) || "."} does not exist.`);
945
+ }
946
+ if (folder !== this.root && !folder.startsWith(this.root + sep))
947
+ throw new Error("File is outside the project root");
948
+ if (folder.split(sep).includes("node_modules"))
949
+ throw new Error("Files in node_modules are not edited");
950
+ const out = resolve(folder, basename(target));
951
+ if (existsSync(out) && !statSync(out).isFile()) throw new Error("Not a file");
952
+ writeFileSync(out, `${JSON.stringify(cameraPathSchema.parse(path), null, 2)}
953
+ `);
954
+ this.cameraPath = { file: relative(this.root, out), savedAt: Date.now() };
955
+ return this.cameraPath.file;
956
+ }
957
+ /** Where the camera path was last saved. */
958
+ cameraPath = null;
959
+ tryApply(edit, expression) {
960
+ let path;
961
+ try {
962
+ path = this.resolveFile(edit.file);
963
+ } catch (err) {
964
+ edit.status = "failed";
965
+ edit.message = err instanceof Error ? err.message : String(err);
966
+ return;
967
+ }
968
+ const source = readFileSync(path, "utf8");
969
+ const result = applyJsxPropEdit(source, {
970
+ line: edit.line,
971
+ column: edit.column,
972
+ prop: edit.prop,
973
+ newValue: edit.newValue,
974
+ expression
975
+ });
976
+ if (result.ok) {
977
+ if (result.changed) writeFileSync(path, result.code);
978
+ edit.status = "applied";
979
+ edit.message = result.note;
980
+ } else {
981
+ edit.status = result.needsAgent ? "queued" : "failed";
982
+ edit.message = result.reason;
983
+ }
984
+ }
985
+ /** Takes a batch from the extension. Returns one result per intent, in the same order. */
986
+ submit(intents) {
987
+ const edits = intents.map((intent) => ({
988
+ ...intent,
989
+ id: randomUUID().slice(0, 8),
990
+ status: "queued"
991
+ }));
992
+ for (const edit of [...edits].sort(
993
+ (a, b2) => a.file === b2.file ? b2.line - a.line || b2.column - a.column : 0
994
+ )) {
995
+ this.tryApply(edit);
996
+ this.edits.set(edit.id, edit);
997
+ }
998
+ return edits;
999
+ }
1000
+ list(status) {
1001
+ const all = [...this.edits.values()];
1002
+ return status ? all.filter((e) => e.status === status) : all;
1003
+ }
1004
+ get(id) {
1005
+ const edit = this.edits.get(id);
1006
+ if (!edit) throw new Error(`Unknown edit id: ${id}`);
1007
+ return edit;
1008
+ }
1009
+ context(id, radius = 12) {
1010
+ const edit = this.get(id);
1011
+ const file = this.resolveFile(edit.file);
1012
+ return { edit, file, source: sourceContext(readFileSync(file, "utf8"), edit.line, radius) };
1013
+ }
1014
+ /** Applies a queued edit, optionally with an expression chosen by the agent. */
1015
+ apply(id, expression) {
1016
+ const edit = this.get(id);
1017
+ this.tryApply(edit, expression);
1018
+ this.emit("change", edit);
1019
+ return edit;
1020
+ }
1021
+ markDone(id, status, note) {
1022
+ const edit = this.get(id);
1023
+ edit.status = status;
1024
+ if (note) edit.message = note;
1025
+ this.emit("change", edit);
1026
+ return edit;
1027
+ }
1028
+ };
1029
+
1030
+ // src/server.ts
1031
+ var LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
1032
+ var MAX_ATTEMPTS = 5;
1033
+ var editsMessage = z3.object({
1034
+ type: z3.literal("edits"),
1035
+ requestId: z3.string().max(64),
1036
+ edits: z3.array(editIntentSchema).max(200)
1037
+ });
1038
+ var pathFileMessage = z3.object({
1039
+ type: z3.literal("path_file"),
1040
+ requestId: z3.string().max(64),
1041
+ file: z3.string().max(512).optional(),
1042
+ path: cameraPathSchema
1043
+ });
1044
+ var newCode = () => String(randomInt(0, 1e6)).padStart(6, "0");
1045
+ var DepthviewServer = class {
1046
+ constructor(options) {
1047
+ this.options = options;
1048
+ this.core = new DepthviewCore(options.root);
1049
+ this.core.on(
1050
+ "change",
1051
+ (edit) => this.broadcast({ type: "edit_status", edits: [edit] })
1052
+ );
1053
+ this.http = createServer((req, res) => void this.onRequest(req, res));
1054
+ this.http.on("upgrade", (req, socket, head) => {
1055
+ const origin = req.headers.origin;
1056
+ const allowed = LOOPBACK.has(req.socket.remoteAddress ?? "") && (req.url ?? "").split("?")[0] === "/ws" && // Web pages may not connect: only the extension (or a non-browser client with no Origin).
1057
+ (origin === void 0 || /^(chrome|moz)-extension:\/\//.test(origin));
1058
+ if (!allowed) {
1059
+ socket.destroy();
1060
+ return;
1061
+ }
1062
+ this.wss.handleUpgrade(req, socket, head, (ws) => this.onSocket(ws));
1063
+ });
1064
+ }
1065
+ core;
1066
+ code = newCode();
1067
+ http;
1068
+ wss = new WebSocketServer({ noServer: true, maxPayload: 4 * 1024 * 1024 });
1069
+ paired = /* @__PURE__ */ new Set();
1070
+ failures = 0;
1071
+ snapshotWaiters = /* @__PURE__ */ new Map();
1072
+ rpcWaiters = /* @__PURE__ */ new Map();
1073
+ counter = 0;
1074
+ /** Last screenshot per view, so take_screenshot can show before and after. */
1075
+ lastShots = /* @__PURE__ */ new Map();
1076
+ listen() {
1077
+ return new Promise((resolve3, reject) => {
1078
+ this.http.once("error", reject);
1079
+ this.http.listen(
1080
+ this.options.port,
1081
+ "127.0.0.1",
1082
+ () => resolve3(this.http.address().port)
1083
+ );
1084
+ });
1085
+ }
1086
+ close() {
1087
+ for (const ws of this.wss.clients) ws.terminate();
1088
+ this.wss.close();
1089
+ return new Promise((resolve3) => this.http.close(() => resolve3()));
1090
+ }
1091
+ get extensionConnected() {
1092
+ return this.paired.size > 0;
1093
+ }
1094
+ rotateCode(reason) {
1095
+ this.code = newCode();
1096
+ this.failures = 0;
1097
+ this.options.log(`${reason} New pairing code: ${this.code}`);
1098
+ }
1099
+ broadcast(message) {
1100
+ const text2 = JSON.stringify(message);
1101
+ for (const ws of this.paired) if (ws.readyState === ws.OPEN) ws.send(text2);
1102
+ }
1103
+ onSocket(ws) {
1104
+ const send = (message) => ws.send(JSON.stringify(message));
1105
+ ws.on("close", () => this.paired.delete(ws));
1106
+ ws.on("error", () => this.paired.delete(ws));
1107
+ ws.on("message", (raw) => {
1108
+ let msg;
1109
+ try {
1110
+ msg = JSON.parse(String(raw));
1111
+ } catch {
1112
+ return;
1113
+ }
1114
+ if (!this.paired.has(ws)) {
1115
+ if (msg.type !== "pair" || typeof msg.code !== "string") {
1116
+ ws.close(1008, "pair first");
1117
+ return;
1118
+ }
1119
+ const given = Buffer.from(msg.code.padEnd(6).slice(0, 6));
1120
+ if (msg.code.length === 6 && timingSafeEqual(given, Buffer.from(this.code))) {
1121
+ this.paired.add(ws);
1122
+ send({ type: "paired" });
1123
+ this.rotateCode("Extension paired.");
1124
+ } else {
1125
+ send({ type: "error", message: "Wrong pairing code" });
1126
+ ws.close(1008, "wrong code");
1127
+ if (++this.failures >= MAX_ATTEMPTS) this.rotateCode("Too many wrong codes.");
1128
+ }
1129
+ return;
1130
+ }
1131
+ if (msg.type === "ping") send({ type: "pong" });
1132
+ else if (msg.type === "edits") {
1133
+ const parsed = editsMessage.safeParse(msg);
1134
+ if (!parsed.success) {
1135
+ send({
1136
+ type: "edits_result",
1137
+ requestId: String(msg.requestId ?? ""),
1138
+ edits: [],
1139
+ error: "Malformed edit request"
1140
+ });
1141
+ return;
1142
+ }
1143
+ const edits = this.core.submit(parsed.data.edits);
1144
+ for (const edit of edits)
1145
+ this.options.log(
1146
+ `${edit.status.padEnd(7)} ${edit.file.replace(this.core.root, ".")}:${edit.line} ${edit.prop}${edit.message ? ` (${edit.message})` : ""}`
1147
+ );
1148
+ send({ type: "edits_result", requestId: parsed.data.requestId, edits });
1149
+ } else if (msg.type === "path_file") {
1150
+ const parsed = pathFileMessage.safeParse(msg);
1151
+ const requestId = String(msg.requestId ?? "");
1152
+ if (!parsed.success) {
1153
+ send({ type: "path_file_result", requestId, ok: false, error: "Malformed camera path" });
1154
+ return;
1155
+ }
1156
+ try {
1157
+ const file = this.core.writeCameraPath(parsed.data.path, parsed.data.file);
1158
+ this.options.log(`camera path ${file} (${parsed.data.path.keys.length} keys)`);
1159
+ send({ type: "path_file_result", requestId, ok: true, file });
1160
+ } catch (err) {
1161
+ send({
1162
+ type: "path_file_result",
1163
+ requestId,
1164
+ ok: false,
1165
+ error: err instanceof Error ? err.message : String(err)
1166
+ });
1167
+ }
1168
+ } else if (msg.type === "snapshot") {
1169
+ if (msg.snapshot) this.core.snapshot = msg.snapshot;
1170
+ const waiter = this.snapshotWaiters.get(String(msg.requestId ?? ""));
1171
+ if (waiter) waiter(this.core.snapshot);
1172
+ } else if (msg.type === "rpc_result") {
1173
+ const waiter = this.rpcWaiters.get(String(msg.requestId ?? ""));
1174
+ if (!waiter) return;
1175
+ if (msg.ok === true) waiter.resolve(msg.data);
1176
+ else waiter.reject(new Error(typeof msg.error === "string" ? msg.error : "Failed"));
1177
+ }
1178
+ });
1179
+ }
1180
+ /** Asks the extension for a fresh scene snapshot; falls back to the last one received. */
1181
+ requestSnapshot(timeoutMs = 3e3) {
1182
+ if (!this.extensionConnected) return Promise.resolve(this.core.snapshot);
1183
+ const requestId = `s${++this.counter}`;
1184
+ return new Promise((resolve3) => {
1185
+ const timer = setTimeout(() => {
1186
+ this.snapshotWaiters.delete(requestId);
1187
+ resolve3(this.core.snapshot);
1188
+ }, timeoutMs);
1189
+ this.snapshotWaiters.set(requestId, (snapshot) => {
1190
+ clearTimeout(timer);
1191
+ this.snapshotWaiters.delete(requestId);
1192
+ resolve3(snapshot);
1193
+ });
1194
+ this.broadcast({ type: "request_snapshot", requestId });
1195
+ });
1196
+ }
1197
+ /**
1198
+ * Asks the inspector in the browser to do something with the live scene (read an object,
1199
+ * change a value, take a picture) and waits for its answer.
1200
+ */
1201
+ rpc(method, params = {}, timeoutMs = 8e3) {
1202
+ if (!this.extensionConnected)
1203
+ return Promise.reject(
1204
+ new Error(
1205
+ 'The Depthview extension is not paired with this server. Ask the developer to open Depthview on their page and enter the pairing code under "Code sync".'
1206
+ )
1207
+ );
1208
+ const requestId = `c${++this.counter}`;
1209
+ return new Promise((resolve3, reject) => {
1210
+ const done = () => {
1211
+ clearTimeout(timer);
1212
+ this.rpcWaiters.delete(requestId);
1213
+ };
1214
+ const timer = setTimeout(() => {
1215
+ done();
1216
+ reject(
1217
+ new Error(
1218
+ "The Depthview inspector did not answer. It must be open on the page (click the extension icon) and the tab must be in front."
1219
+ )
1220
+ );
1221
+ }, timeoutMs);
1222
+ this.rpcWaiters.set(requestId, {
1223
+ resolve: (data) => {
1224
+ done();
1225
+ resolve3(data);
1226
+ },
1227
+ reject: (err) => {
1228
+ done();
1229
+ reject(err);
1230
+ }
1231
+ });
1232
+ this.broadcast({ type: "rpc", requestId, method, params });
1233
+ });
1234
+ }
1235
+ async onRequest(req, res) {
1236
+ const json = (status, body) => {
1237
+ res.writeHead(status, { "content-type": "application/json" });
1238
+ res.end(JSON.stringify(body));
1239
+ };
1240
+ try {
1241
+ const host = (req.headers.host ?? "").replace(/:\d+$/, "");
1242
+ const origin = req.headers.origin;
1243
+ if (!LOOPBACK.has(req.socket.remoteAddress ?? "") || !["127.0.0.1", "localhost", "[::1]"].includes(host))
1244
+ return json(403, { error: "Local connections only" });
1245
+ if (origin !== void 0 && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin))
1246
+ return json(403, { error: "Origin not allowed" });
1247
+ const path = (req.url ?? "/").split("?")[0];
1248
+ if (path === "/health")
1249
+ return json(200, { name: "depthview-mcp", extensionConnected: this.extensionConnected });
1250
+ if (path !== "/mcp" || !this.options.mcpHttp) return json(404, { error: "Not found" });
1251
+ if (req.method !== "POST")
1252
+ return json(405, {
1253
+ jsonrpc: "2.0",
1254
+ error: { code: -32e3, message: "Method not allowed" },
1255
+ id: null
1256
+ });
1257
+ const chunks = [];
1258
+ let size = 0;
1259
+ for await (const chunk of req) {
1260
+ size += chunk.length;
1261
+ if (size > 4 * 1024 * 1024) return json(413, { error: "Request too large" });
1262
+ chunks.push(chunk);
1263
+ }
1264
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
1265
+ const mcp = buildMcpServer(this, { includePairingCode: false });
1266
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: void 0 });
1267
+ res.on("close", () => {
1268
+ void transport.close();
1269
+ void mcp.close();
1270
+ });
1271
+ await mcp.connect(transport);
1272
+ await transport.handleRequest(req, res, body);
1273
+ } catch (err) {
1274
+ if (!res.headersSent)
1275
+ json(400, {
1276
+ jsonrpc: "2.0",
1277
+ error: { code: -32700, message: err instanceof Error ? err.message : "Bad request" },
1278
+ id: null
1279
+ });
1280
+ }
1281
+ }
1282
+ };
1283
+
1284
+ // src/cli.ts
1285
+ var HELP = `Depthview MCP server
1286
+
1287
+ npx depthview-mcp [--root <dir>] [--port <n>] [--stdio]
1288
+ npx depthview-mcp init [--root <dir>]
1289
+
1290
+ init Set a project up for Claude Code: adds the server to .mcp.json and copies the
1291
+ Depthview skill to .claude/skills/depthview/. Run it once per project.
1292
+
1293
+ --root Project root. Only files inside it are edited. Default: current directory.
1294
+ --port Port on 127.0.0.1. Default: 7411.
1295
+ --stdio Speak MCP on stdin/stdout (for clients that start the server themselves).
1296
+ Without it, MCP is served at http://127.0.0.1:<port>/mcp.
1297
+ `;
1298
+ function option(name) {
1299
+ const i = process.argv.indexOf(`--${name}`);
1300
+ return i >= 0 ? process.argv[i + 1] : void 0;
1301
+ }
1302
+ function init(root) {
1303
+ const out = (line) => void process.stdout.write(`${line}
1304
+ `);
1305
+ const cli = fileURLToPath(import.meta.url);
1306
+ const installed = cli.split(sep2).includes("node_modules");
1307
+ const entry = installed ? { command: "npx", args: ["-y", "depthview-mcp", "--stdio"] } : { command: "node", args: [cli, "--stdio"] };
1308
+ const configPath = join(root, ".mcp.json");
1309
+ let config = {};
1310
+ if (existsSync2(configPath)) {
1311
+ try {
1312
+ config = JSON.parse(readFileSync2(configPath, "utf8"));
1313
+ } catch {
1314
+ throw new Error(`${configPath} is not valid JSON. Fix it, then run init again.`);
1315
+ }
1316
+ if (typeof config !== "object" || config === null || Array.isArray(config))
1317
+ throw new Error(`${configPath} is not a JSON object. Fix it, then run init again.`);
1318
+ }
1319
+ config.mcpServers = { ...config.mcpServers, depthview: entry };
1320
+ writeFileSync2(configPath, `${JSON.stringify(config, null, 2)}
1321
+ `);
1322
+ out(`wrote ${configPath}`);
1323
+ const skill = join(dirname2(cli), "..", "skill", "SKILL.md");
1324
+ const skillPath = join(root, ".claude", "skills", "depthview", "SKILL.md");
1325
+ mkdirSync(dirname2(skillPath), { recursive: true });
1326
+ writeFileSync2(skillPath, readFileSync2(skill));
1327
+ out(`wrote ${skillPath}`);
1328
+ out("");
1329
+ out("Next:");
1330
+ out(' 1. Start (or restart) Claude Code in this project and allow the "depthview" server.');
1331
+ out(" 2. Open your dev site in Chrome and click the Depthview icon.");
1332
+ out(' 3. Ask Claude: "pair with Depthview". Type the code it gives into the side panel,');
1333
+ out(' under "AI agent & code sync".');
1334
+ out(" For exact source edits, add depthview-r3f-bridge to the project.");
1335
+ }
1336
+ async function main() {
1337
+ if (process.argv.includes("--help") || process.argv.includes("-h")) {
1338
+ process.stdout.write(HELP);
1339
+ return;
1340
+ }
1341
+ const stdio = process.argv.includes("--stdio");
1342
+ const root = resolve2(option("root") ?? process.cwd());
1343
+ if (process.argv[2] === "init") {
1344
+ init(root);
1345
+ return;
1346
+ }
1347
+ const port = Number(option("port") ?? process.env.DEPTHVIEW_PORT ?? 7411);
1348
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
1349
+ throw new Error(`Invalid port: ${option("port")}`);
1350
+ const log = (line) => void process.stderr.write(`[depthview] ${line}
1351
+ `);
1352
+ const server = new DepthviewServer({ root, port, mcpHttp: !stdio, log });
1353
+ const actualPort = await server.listen();
1354
+ log(`project root ${root}`);
1355
+ log(`extension ws://127.0.0.1:${actualPort}/ws`);
1356
+ if (!stdio) {
1357
+ log(`MCP (http) http://127.0.0.1:${actualPort}/mcp`);
1358
+ log(
1359
+ ` claude mcp add --transport http depthview http://127.0.0.1:${actualPort}/mcp`
1360
+ );
1361
+ }
1362
+ log(`pairing code ${server.code} (type it into the Depthview side panel)`);
1363
+ if (stdio)
1364
+ await buildMcpServer(server, { includePairingCode: true }).connect(new StdioServerTransport());
1365
+ const stop = () => void server.close().then(() => process.exit(0));
1366
+ process.on("SIGINT", stop);
1367
+ process.on("SIGTERM", stop);
1368
+ }
1369
+ main().catch((err) => {
1370
+ process.stderr.write(`[depthview] ${err instanceof Error ? err.message : String(err)}
1371
+ `);
1372
+ process.exit(1);
1373
+ });