Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
Fix cross-client MCP delivery and dogfood portability (#113)
Matthew Kissinger026f95b17510
diff --git a/README.md b/README.mdindex f7376a5d..a9698b69 100644--- a/README.md+++ b/README.md@@ -168,9 +168,10 @@ the same viewer. See [saved assets and the viewer](docs/collections.md).Create and refine assets in ChatGPT through a private MCP connection, then ask tosee a saved revision. `kiln_present` opens that exact revision in an interactive 3D card in-supporting MCP App clients. Coding harnesses normally receive exact resource links instead; their-agent can launch the local viewer on the saved revision and provide its loopback URL. Orbit the-model and inspect its animation without leaving chat.+supporting MCP App clients. Every coding harness receives exact artifact descriptors and readable+resource URIs in the JSON result; a verified host can opt into core MCP `resource_link` blocks.+An agent can also launch the local viewer on the saved revision and provide its loopback URL.+Orbit the model and inspect its animation without leaving chat.ChatGPT viewing was verified with real saved assets.1. Build the runtime and connect its stdio MCP server through an OpenAI Securediff --git a/bun.lock b/bun.lockindex e2b3751c..b9da708c 100644--- a/bun.lock+++ b/bun.lock@@ -9,6 +9,7 @@"@gltf-transform/extensions": "4.5.0","@gltf-transform/functions": "4.5.0","@modelcontextprotocol/client": "^2.0.0",+ "@modelcontextprotocol/ext-apps": "2.0.0","@modelcontextprotocol/server": "^2.0.0","@openrouter/ai-sdk-provider": "^2.10.0","@types/three": "^0.186.0",@@ -194,6 +195,8 @@"@modelcontextprotocol/core": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA=="],+ "@modelcontextprotocol/ext-apps": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0" }, "peerDependencies": { "@modelcontextprotocol/client": "^2.0.0", "@modelcontextprotocol/core": "^2.0.0", "@modelcontextprotocol/server": "^2.0.0", "react": "^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0", "zod": "^4.2.0" }, "optionalPeers": ["@modelcontextprotocol/server", "react", "react-dom"] }, "sha512-a6tXzFcIbIIdnqumQ7W8Oxd8W/KAPkAKYpoxpD9nDgxZ24ywgxG5pK/8G9W5pOFUygS7gWHQhPv8cwRB44/8yg=="],+"@modelcontextprotocol/sdk": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA=="],"@modelcontextprotocol/server": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "zod": "^4.2.0" } }, "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw=="],diff --git a/dist/build.json b/dist/build.jsonindex d05ffb9f..4307e14d 100644--- a/dist/build.json+++ b/dist/build.json@@ -2,16 +2,17 @@"schemaVersion": 1,"entries": {"mcp": {- "identity": "sha256:d9b848e40e1d4fc932ec6b08d10291fb5dede9f2155be7a80d1c867ae282577c",+ "identity": "sha256:9c784960b8c9d45c9a179f12e60e2e61b7cff83d5c67695b672eebf04ca086c0","engineVersion": "0.7.0","toolchain": "[email protected]",- "sourceHash": "7efbefcd064790488996dc67ba13a6a4e68b960c47fdfebdcd91ac180e0335b2",- "dependencyHash": "82c9bae4be67acfa200409a71834d66220481bd9f0c6e5840667579292f0c718",+ "sourceHash": "65f9f084243609fc0616f98c5f21532c8d4f6c8ba6a13db4822993a5939002a5",+ "dependencyHash": "ec89db810fc1196f4058317df0fd1b59ac0fd3ffea2ac52def221406488c6541","dependencies": {"@gltf-transform/core": "4.5.0","@gltf-transform/extensions": "4.5.0","@gltf-transform/functions": "4.5.0","@modelcontextprotocol/client": "^2.0.0",+ "@modelcontextprotocol/ext-apps": "2.0.0","@modelcontextprotocol/server": "^2.0.0","@openrouter/ai-sdk-provider": "^2.10.0","@types/three": "^0.186.0",@@ -27,19 +28,20 @@},"target": "node","file": "mcp-server.mjs",- "bundleHash": "sha256:5ca87421a8f574be854be3aebc2371e89c6d56fa7842de2de7bfc5a9124f1df1"+ "bundleHash": "sha256:2ddb5b1621dc8b4728371fc81d3c1529b6c0f6e336e6788a8f65c6da345645b1"},"cli": {- "identity": "sha256:d9b848e40e1d4fc932ec6b08d10291fb5dede9f2155be7a80d1c867ae282577c",+ "identity": "sha256:9c784960b8c9d45c9a179f12e60e2e61b7cff83d5c67695b672eebf04ca086c0","engineVersion": "0.7.0","toolchain": "[email protected]",- "sourceHash": "7efbefcd064790488996dc67ba13a6a4e68b960c47fdfebdcd91ac180e0335b2",- "dependencyHash": "82c9bae4be67acfa200409a71834d66220481bd9f0c6e5840667579292f0c718",+ "sourceHash": "65f9f084243609fc0616f98c5f21532c8d4f6c8ba6a13db4822993a5939002a5",+ "dependencyHash": "ec89db810fc1196f4058317df0fd1b59ac0fd3ffea2ac52def221406488c6541","dependencies": {"@gltf-transform/core": "4.5.0","@gltf-transform/extensions": "4.5.0","@gltf-transform/functions": "4.5.0","@modelcontextprotocol/client": "^2.0.0",+ "@modelcontextprotocol/ext-apps": "2.0.0","@modelcontextprotocol/server": "^2.0.0","@openrouter/ai-sdk-provider": "^2.10.0","@types/three": "^0.186.0",@@ -55,19 +57,20 @@},"target": "node","file": "cli.mjs",- "bundleHash": "sha256:38230fb911cec65e873edeca0f835fe45669301399f2a5e72015cb7e3f534efd"+ "bundleHash": "sha256:1dfe4d601166294d3394d15769e58e1607e2b8678c42d3b81d1a6aa4896db51b"},"worker": {- "identity": "sha256:d9b848e40e1d4fc932ec6b08d10291fb5dede9f2155be7a80d1c867ae282577c",+ "identity": "sha256:9c784960b8c9d45c9a179f12e60e2e61b7cff83d5c67695b672eebf04ca086c0","engineVersion": "0.7.0","toolchain": "[email protected]",- "sourceHash": "7efbefcd064790488996dc67ba13a6a4e68b960c47fdfebdcd91ac180e0335b2",- "dependencyHash": "82c9bae4be67acfa200409a71834d66220481bd9f0c6e5840667579292f0c718",+ "sourceHash": "65f9f084243609fc0616f98c5f21532c8d4f6c8ba6a13db4822993a5939002a5",+ "dependencyHash": "ec89db810fc1196f4058317df0fd1b59ac0fd3ffea2ac52def221406488c6541","dependencies": {"@gltf-transform/core": "4.5.0","@gltf-transform/extensions": "4.5.0","@gltf-transform/functions": "4.5.0","@modelcontextprotocol/client": "^2.0.0",+ "@modelcontextprotocol/ext-apps": "2.0.0","@modelcontextprotocol/server": "^2.0.0","@openrouter/ai-sdk-provider": "^2.10.0","@types/three": "^0.186.0",@@ -86,16 +89,17 @@"bundleHash": "sha256:03c4ce7c118e4bca76c8feb1f70dff31533dacb1a77541af3f474697df59bdc5"},"agent-run": {- "identity": "sha256:d9b848e40e1d4fc932ec6b08d10291fb5dede9f2155be7a80d1c867ae282577c",+ "identity": "sha256:9c784960b8c9d45c9a179f12e60e2e61b7cff83d5c67695b672eebf04ca086c0","engineVersion": "0.7.0","toolchain": "[email protected]",- "sourceHash": "7efbefcd064790488996dc67ba13a6a4e68b960c47fdfebdcd91ac180e0335b2",- "dependencyHash": "82c9bae4be67acfa200409a71834d66220481bd9f0c6e5840667579292f0c718",+ "sourceHash": "65f9f084243609fc0616f98c5f21532c8d4f6c8ba6a13db4822993a5939002a5",+ "dependencyHash": "ec89db810fc1196f4058317df0fd1b59ac0fd3ffea2ac52def221406488c6541","dependencies": {"@gltf-transform/core": "4.5.0","@gltf-transform/extensions": "4.5.0","@gltf-transform/functions": "4.5.0","@modelcontextprotocol/client": "^2.0.0",+ "@modelcontextprotocol/ext-apps": "2.0.0","@modelcontextprotocol/server": "^2.0.0","@openrouter/ai-sdk-provider": "^2.10.0","@types/three": "^0.186.0",@@ -114,16 +118,17 @@"bundleHash": "sha256:c90f03948131e6396530d8abaa3e569574c71dfbfba368b1ff3453cae7534b88"},"agent-providers": {- "identity": "sha256:d9b848e40e1d4fc932ec6b08d10291fb5dede9f2155be7a80d1c867ae282577c",+ "identity": "sha256:9c784960b8c9d45c9a179f12e60e2e61b7cff83d5c67695b672eebf04ca086c0","engineVersion": "0.7.0","toolchain": "[email protected]",- "sourceHash": "7efbefcd064790488996dc67ba13a6a4e68b960c47fdfebdcd91ac180e0335b2",- "dependencyHash": "82c9bae4be67acfa200409a71834d66220481bd9f0c6e5840667579292f0c718",+ "sourceHash": "65f9f084243609fc0616f98c5f21532c8d4f6c8ba6a13db4822993a5939002a5",+ "dependencyHash": "ec89db810fc1196f4058317df0fd1b59ac0fd3ffea2ac52def221406488c6541","dependencies": {"@gltf-transform/core": "4.5.0","@gltf-transform/extensions": "4.5.0","@gltf-transform/functions": "4.5.0","@modelcontextprotocol/client": "^2.0.0",+ "@modelcontextprotocol/ext-apps": "2.0.0","@modelcontextprotocol/server": "^2.0.0","@openrouter/ai-sdk-provider": "^2.10.0","@types/three": "^0.186.0",diff --git a/dist/cli.mjs b/dist/cli.mjsindex 5c4507a2..1eb72bf0 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -28368,7 +28368,7 @@ function createKilnAssetDefs(context) {},{name: "kiln_present",- description: "Present one exact saved revision. Supporting MCP App clients show an interactive 3D card with GLB, editable ZIP, and source downloads. Other hosts receive portable resource links; this tool does not launch a local browser in coding harnesses. Call after saving or when the user wants to see or download an asset.",+ description: "Present one exact saved revision. Supporting MCP App clients show an interactive 3D card with GLB, editable ZIP, and source downloads. Every host receives exact artifact descriptors with resource URIs in the JSON result; verified hosts may also receive core MCP resource-link blocks. This tool does not launch a local browser in coding harnesses. Call after saving or when the user wants to see or download an asset.",inputSchema: exportInput,outputSchema: z4.object({ok: z4.literal(true),@@ -28414,7 +28414,7 @@ function createKilnAssetDefs(context) {},{name: "kiln_export",- description: "Get downloadable GLB, source, manifest, and portable ZIP resource links for one exact saved revision. The ZIP contains source when available and does not require the original program store. Use the host resource reader/download UI; no binary bytes are placed in tool text.",+ description: "Get exact GLB, source, preview, and manifest descriptors for one saved revision. Their resource URIs remain readable through resources/read, and configured hosts may also return download URLs including a portable editable ZIP. No binary bytes are placed in tool text.",inputSchema: exportInput,run: async (raw) => {const input = exportInput.parse(raw);@@ -28597,7 +28597,7 @@ var init_registry2 = __esm(() => {// src/render-service-host.tsimport { spawn as spawn2 } from "node:child_process";import { existsSync as existsSync2 } from "node:fs";-import { fileURLToPath as fileURLToPath5 } from "node:url";+import { fileURLToPath as fileURLToPath5, pathToFileURL } from "node:url";import { join as join6 } from "node:path";function localRenderServicePort() {const raw = Number(process.env["KILN_RENDER_SERVICE_PORT"]);@@ -28606,6 +28606,13 @@ function localRenderServicePort() {function localRenderServiceUrl() {return `http://127.0.0.1:${localRenderServicePort()}`;}+function renderServiceNodeArguments(dir) {+ return [+ "--import",+ pathToFileURL(join6(dir, "src/register-hooks.mjs")).href,+ join6(dir, "src/server.mjs")+ ];+}function renderServiceDir() {const override = process.env["KILN_RENDER_SERVICE_DIR"];if (override)@@ -28664,7 +28671,7 @@ async function startLocalRenderService(dir = renderServiceDir()) {throw new Error(explainRenderServiceState(state, dir));registerTeardown();let stderr = "";- child = spawn2(nodeBinary(), ["--import", join6(dir, "src/register-hooks.mjs"), join6(dir, "src/server.mjs")], {+ child = spawn2(nodeBinary(), renderServiceNodeArguments(dir), {cwd: dir,env: {...process.env,@@ -28837,7 +28844,7 @@ async function buildRenderPort(mode, portUrl, options) {context.viewRenderPort = makeLazyRenderPort(async () => {url = await start();return url;- }, process.env["KILN_RENDER_TOKEN"]);+ }, process.env["KILN_RENDER_TOKEN"] ?? process.env["RENDER_SERVICE_TOKEN"]);context.viewRenderTimeoutMs = CLI_VIEW_RENDER_TIMEOUT_MS;context.captureCacheIdentity = () => url ? probeCaptureIdentity(url) : undefined;selected.set(context, label);diff --git a/dist/mcp-server.mjs b/dist/mcp-server.mjsindex ceb45498..78556a77 100644--- a/dist/mcp-server.mjs+++ b/dist/mcp-server.mjs@@ -25953,6 +25953,12 @@ var init_asset_widget2 = __esm(() => {// src/mcp-server.tsimport { McpServer, ResourceTemplate } from "@modelcontextprotocol/server";+import {+ EXTENSION_ID as MCP_APPS_EXTENSION_ID,+ RESOURCE_MIME_TYPE as MCP_APPS_MIME_TYPE,+ registerAppResource,+ registerAppTool+} from "@modelcontextprotocol/ext-apps/server";// src/assets-node.tsinit_assets();@@ -28185,7 +28191,7 @@ function createKilnAssetDefs(context) {},{name: "kiln_present",- description: "Present one exact saved revision. Supporting MCP App clients show an interactive 3D card with GLB, editable ZIP, and source downloads. Other hosts receive portable resource links; this tool does not launch a local browser in coding harnesses. Call after saving or when the user wants to see or download an asset.",+ description: "Present one exact saved revision. Supporting MCP App clients show an interactive 3D card with GLB, editable ZIP, and source downloads. Every host receives exact artifact descriptors with resource URIs in the JSON result; verified hosts may also receive core MCP resource-link blocks. This tool does not launch a local browser in coding harnesses. Call after saving or when the user wants to see or download an asset.",inputSchema: exportInput,outputSchema: z4.object({ok: z4.literal(true),@@ -28231,7 +28237,7 @@ function createKilnAssetDefs(context) {},{name: "kiln_export",- description: "Get downloadable GLB, source, manifest, and portable ZIP resource links for one exact saved revision. The ZIP contains source when available and does not require the original program store. Use the host resource reader/download UI; no binary bytes are placed in tool text.",+ description: "Get exact GLB, source, preview, and manifest descriptors for one saved revision. Their resource URIs remain readable through resources/read, and configured hosts may also return download URLs including a portable editable ZIP. No binary bytes are placed in tool text.",inputSchema: exportInput,run: async (raw) => {const input = exportInput.parse(raw);@@ -28259,7 +28265,7 @@ import { createHash as createHash8 } from "node:crypto";// src/render-service-host.tsimport { spawn as spawn2 } from "node:child_process";import { existsSync as existsSync2 } from "node:fs";-import { fileURLToPath as fileURLToPath3 } from "node:url";+import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";import { join as join3 } from "node:path";var DEFAULT_LOCAL_RENDER_SERVICE_PORT = 8000;function localRenderServicePort() {@@ -28269,6 +28275,13 @@ function localRenderServicePort() {function localRenderServiceUrl() {return `http://127.0.0.1:${localRenderServicePort()}`;}+function renderServiceNodeArguments(dir) {+ return [+ "--import",+ pathToFileURL(join3(dir, "src/register-hooks.mjs")).href,+ join3(dir, "src/server.mjs")+ ];+}var STARTUP_BUDGET_MS = Number(process.env["KILN_RENDER_SERVICE_STARTUP_MS"] ?? 60000);var STARTUP_POLL_MS = 250;function renderServiceDir() {@@ -28331,7 +28344,7 @@ async function startLocalRenderService(dir = renderServiceDir()) {throw new Error(explainRenderServiceState(state, dir));registerTeardown();let stderr = "";- child = spawn2(nodeBinary(), ["--import", join3(dir, "src/register-hooks.mjs"), join3(dir, "src/server.mjs")], {+ child = spawn2(nodeBinary(), renderServiceNodeArguments(dir), {cwd: dir,env: {...process.env,@@ -28487,7 +28500,7 @@ async function buildRenderPort(mode, portUrl, options) {context.viewRenderPort = makeLazyRenderPort(async () => {url = await start();return url;- }, process.env["KILN_RENDER_TOKEN"]);+ }, process.env["KILN_RENDER_TOKEN"] ?? process.env["RENDER_SERVICE_TOKEN"]);context.viewRenderTimeoutMs = CLI_VIEW_RENDER_TIMEOUT_MS;context.captureCacheIdentity = () => url ? probeCaptureIdentity(url) : undefined;selected.set(context, label);@@ -29191,7 +29204,7 @@ Most harnesses register skills only from their own directories, so these may notfunction kilnMcpToolDefs(context = {}) {return createKilnProgramToolRegistry(context);}-async function runTool(def, args) {+async function runTool(def, args, options = {}) {const output = await def.run(args);const multi = def.mediaMulti?.(output);if (multi) {@@ -29223,28 +29236,46 @@ async function runTool(def, args) {if (asText !== undefined)return { content: [{ type: "text", text: asText }] };const resources = output?.resources ?? [];- const payload = resources.length ? { ...output, resources: undefined } : output;+ const includeResourceLinks = options.artifactResourceLinks === true;+ const payload = resources.length && includeResourceLinks ? { ...output, resources: undefined } : output;return {- content: [{ type: "text", text: JSON.stringify(payload, null, 2) }, ...resources],+ content: [+ { type: "text", text: JSON.stringify(payload, null, 2) },+ ...includeResourceLinks ? resources : []+ ],...def.ui ? {structuredContent: output,_meta: await def.ui.data(output)} : {}};}-function createKilnMcpServer(context = {}) {+function createKilnMcpServer(context = {}, options = {}) {const server = new McpServer({name: MCP_SERVER_NAME,version: MCP_SERVER_VERSION- }, { instructions: MCP_SERVER_INSTRUCTIONS });- server.registerResource("kiln-asset-viewer", KILN_ASSET_WIDGET_URI, {+ }, {+ instructions: MCP_SERVER_INSTRUCTIONS,+ capabilities: {+ extensions: {+ [MCP_APPS_EXTENSION_ID]: { mimeTypes: [MCP_APPS_MIME_TYPE] }+ }+ }+ });+ registerAppResource(server, "kiln-asset-viewer", KILN_ASSET_WIDGET_URI, {description: "Interactive Kiln asset viewer and downloads",- mimeType: "text/html;profile=mcp-app"+ _meta: {+ ui: {+ prefersBorder: true,+ csp: { connectDomains: [], resourceDomains: [] }+ },+ "openai/widgetDescription": "Inspect the saved 3D asset and download its GLB or editable bundle.",+ "openai/widgetPrefersBorder": true+ }}, async (uri) => ({contents: [{uri: uri.href,- mimeType: "text/html;profile=mcp-app",+ mimeType: MCP_APPS_MIME_TYPE,text: await (await Promise.resolve().then(() => (init_asset_widget2(), exports_asset_widget2))).readAssetWidgetHtml(),_meta: {ui: {@@ -29290,21 +29321,15 @@ function createKilnMcpServer(context = {}) {}};for (const def of kilnMcpToolDefs(requestContext)) {- server.registerTool(def.name, {+ const config = {description: def.description,annotations: def.annotations,- ...def.ui ? {- _meta: {- ui: { resourceUri: def.ui.resourceUri },- "openai/outputTemplate": def.ui.resourceUri,- "openai/widgetAccessible": true- }- } : {},inputSchema: def.inputSchema,...def.outputSchema ? { outputSchema: def.outputSchema } : {}- }, async (args, request) => {+ };+ const handler = async (args, request) => {try {- return await requests.run(request.mcpReq.signal, () => runTool(def, args));+ return await requests.run(request.mcpReq.signal, () => runTool(def, args, options));} catch (err) {return {isError: true,@@ -29316,7 +29341,18 @@ function createKilnMcpServer(context = {}) {]};}- });+ };+ if (def.ui) {+ registerAppTool(server, def.name, {+ ...config,+ _meta: {+ ui: { resourceUri: def.ui.resourceUri, visibility: ["model"] },+ "openai/outputTemplate": def.ui.resourceUri+ }+ }, handler);+ } else {+ server.registerTool(def.name, config, handler);+ }}return server;}@@ -29336,7 +29372,9 @@ if (isDirectEntry(import.meta.url)) {]));}console.error(`kiln MCP server on stdio (${mode})`);- serveStdio(() => createKilnMcpServer(context));+ serveStdio(() => createKilnMcpServer(context, {+ artifactResourceLinks: process.env["KILN_MCP_RESOURCE_LINKS"] === "1"+ }));}export {MCP_SERVER_INSTRUCTIONS,diff --git a/docs/chatgpt.md b/docs/chatgpt.mdindex 0bf4f709..0a2dd290 100644--- a/docs/chatgpt.md+++ b/docs/chatgpt.md@@ -33,7 +33,7 @@ A local desktop marketplace is not automatically a web installation. Attaching s## Downloads and viewing-MCP save/export replies contain `resource_link` entries for exact GLB, source, preview, manifest, and editable ZIP bytes. The full provenance lives in the manifest resource; chat replies carry compact revision summaries. Whether a host renders those links as download buttons is host-dependent and must be tested. A `kiln://` resource URI is not an HTTPS link and should not be presented as one.+MCP save/export replies keep descriptors for the exact GLB, source, preview, and manifest bytes in their JSON results. Every `kiln://` URI remains readable through `resources/read`; configured download URLs may additionally expose the editable ZIP. Set `KILN_MCP_RESOURCE_LINKS=1` only for a host verified to accept core MCP `resource_link` content blocks; core MCP does not expose a capability flag for that content type, and some otherwise compatible hosts reject the whole tool result. The full provenance lives in the manifest resource, while chat replies carry compact revision summaries. A `kiln://` resource URI is not an HTTPS link and should not be presented as one.`kiln_present` adds an MCP App card for a pinned saved revision. It reuses the local Three.js stage for orbit/zoom, studio lighting, and animation, and offers GLB, editable ZIP, and source downloads through the host's `ui/download-file` bridge. Binary data travels in tool-result `_meta`, separate from model-visible text. The self-contained HTML resource needs no CDN or public asset URL. Chat presentation is bounded to 16 MiB of asset files; larger assets remain available through the local viewer. Host support must be verified: MCP resource links alone do not prove a chat-native download works.diff --git a/docs/collections.md b/docs/collections.mdindex b246d4e1..c006ee2a 100644--- a/docs/collections.md+++ b/docs/collections.md@@ -67,8 +67,9 @@ by default. There is no automatic deletion or disk quota for saved collections.`programRef`, `name`, and that collection. The authoring skill records the known model andharness. Optional fields include tags, brief, description and author attribution; unknownattribution is omitted.-3. Save the returned asset/revision IDs. `kiln_export` returns resource links for the- GLB, source, preview, manifest and ZIP. MCP clients choose how to show downloads.+3. Save the returned asset/revision IDs. `kiln_export` returns exact artifact descriptors+ and readable resource URIs for the GLB, source, preview, and manifest. Configured hosts+ may also provide direct download URLs, including the editable ZIP.4. In a later session, use `kiln_assets` with `action: "restore"`, collection,assetId and revisionId. Use the returned programRef with `kiln_source`/`kiln_edit`.5. Save a child with the same assetId and `parentRevision` equal to the base revision.diff --git a/docs/tools.md b/docs/tools.mdindex 44ff8f32..9a5a0f4e 100644--- a/docs/tools.md+++ b/docs/tools.md@@ -1728,7 +1728,7 @@ Discover collections; list/search saved asset revisions; get a build record and## kiln_present-Present one exact saved revision. Supporting MCP App clients show an interactive 3D card with GLB, editable ZIP, and source downloads. Other hosts receive portable resource links; this tool does not launch a local browser in coding harnesses. Call after saving or when the user wants to see or download an asset.+Present one exact saved revision. Supporting MCP App clients show an interactive 3D card with GLB, editable ZIP, and source downloads. Every host receives exact artifact descriptors with resource URIs in the JSON result; verified hosts may also receive core MCP resource-link blocks. This tool does not launch a local browser in coding harnesses. Call after saving or when the user wants to see or download an asset.<details><summary>Input JSON Schema</summary>@@ -1767,7 +1767,7 @@ Present one exact saved revision. Supporting MCP App clients show an interactive## kiln_export-Get downloadable GLB, source, manifest, and portable ZIP resource links for one exact saved revision. The ZIP contains source when available and does not require the original program store. Use the host resource reader/download UI; no binary bytes are placed in tool text.+Get exact GLB, source, preview, and manifest descriptors for one saved revision. Their resource URIs remain readable through resources/read, and configured hosts may also return download URLs including a portable editable ZIP. No binary bytes are placed in tool text.<details><summary>Input JSON Schema</summary>diff --git a/package.json b/package.jsonindex 69b125cc..1704dfc0 100644--- a/package.json+++ b/package.json@@ -116,6 +116,7 @@"@gltf-transform/extensions": "4.5.0","@gltf-transform/functions": "4.5.0","@modelcontextprotocol/client": "^2.0.0",+ "@modelcontextprotocol/ext-apps": "2.0.0","@modelcontextprotocol/server": "^2.0.0","@openrouter/ai-sdk-provider": "^2.10.0","@types/three": "^0.186.0",diff --git a/render-service/test/smoke.mjs b/render-service/test/smoke.mjsindex eeb315e8..be02134d 100644--- a/render-service/test/smoke.mjs+++ b/render-service/test/smoke.mjs@@ -11,7 +11,7 @@ const PORT = process.env.PORT;const TOKEN = process.env.RENDER_SERVICE_TOKEN;const here = dirname(fileURLToPath(import.meta.url));-const glbPath = process.env.SMOKE_GLB ?? join(here, 'fixtures', 'model.glb');+const glbPath = process.env.SMOKE_GLB ?? join(here, 'fixtures', 'material-channels-v1.glb');await import('../src/server.mjs');await new Promise((r) => setTimeout(r, 300));diff --git a/scripts/build-runtime.mjs b/scripts/build-runtime.mjsindex 47f207d4..4b876787 100644--- a/scripts/build-runtime.mjs+++ b/scripts/build-runtime.mjs@@ -8,6 +8,28 @@ import { fileURLToPath } from 'node:url';const sha = (value) => createHash('sha256').update(value).digest('hex');const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');+async function pinnedBun(root) {+ const pkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));+ const match = /^bun@(.+)$/.exec(pkg.packageManager ?? '');+ if (!match) throw new Error('packageManager must pin the Bun build toolchain.');+ const expected = match[1];+ const installed = spawnSync('bun', ['--version'], {+ cwd: root,+ encoding: 'utf8',+ windowsHide: true,+ });+ if (installed.status === 0 && installed.stdout.trim() === expected)+ return { command: 'bun', prefix: [] };++ // A stale Bun elsewhere on PATH must not silently change committed Node bundles.+ // npm ships with Node on every supported platform and resolves the exact package+ // version without requiring Bun itself to already be current.+ return {+ command: process.platform === 'win32' ? 'npx.cmd' : 'npx',+ prefix: ['--yes', '--package', `bun@${expected}`, 'bun'],+ };+}+async function sources(directory, prefix = '') {const entries = [];for (const item of (await readdir(directory, { withFileTypes: true })).sort((a, b) =>@@ -52,9 +74,11 @@ export async function buildRuntime(target, root = repo) {};if (!entries[target]) throw new Error('Choose cli, mcp, or worker.');const before = await runtimeBuildIdentity(root);+ const compiler = await pinnedBun(root);const built = spawnSync(- 'bun',+ compiler.command,[+ ...compiler.prefix,'build',entries[target],'--target=node',diff --git a/scripts/create-workspace.mjs b/scripts/create-workspace.mjsindex e7ce277c..3b4e6bcc 100644--- a/scripts/create-workspace.mjs+++ b/scripts/create-workspace.mjs@@ -115,7 +115,7 @@ function managedFiles(root, runtime, harness, nodeExecutable) {// `--cd` sets the project directory; a workspace is deliberately not a git// checkout, so `--skip-git-repo-check` is required rather than optional.files['codex.mjs'] =- `import { spawn } from 'node:child_process';\nimport { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst root = dirname(fileURLToPath(import.meta.url));\nconst overrides = [\n ['mcp_servers.kiln_workspace.command', ${quote(mcp.command)}],\n ['mcp_servers.kiln_workspace.args', [${quote(server)}]],\n ['mcp_servers.kiln_workspace.env.KILN_PROGRAM_STORE', ${quote(store)}],\n ['mcp_servers.kiln_workspace.env.KILN_RENDER', 'auto'],\n].flatMap(([key, value]) => ['-c', key + '=' + JSON.stringify(value)]);\nconst args = process.argv.slice(2);\nconst sub = args.find(arg => !arg.startsWith('-'));\nconst rest = sub === 'exec' ? args : ['exec', ...args];\nconst child = spawn('codex', [...rest.slice(0, 1), ...overrides, '--cd', root, '--skip-git-repo-check', ...rest.slice(1)], { cwd: root, stdio: 'inherit', windowsHide: true });\nchild.on('error', error => { console.error(error.message); process.exitCode = 1; });\nchild.on('exit', code => { process.exitCode = code ?? 1; });\n`;+ `import { spawn } from 'node:child_process';\nimport { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst root = dirname(fileURLToPath(import.meta.url));\nconst overrides = [\n ['mcp_servers.kiln_workspace.command', ${quote(mcp.command)}],\n ['mcp_servers.kiln_workspace.args', [${quote(server)}]],\n ['mcp_servers.kiln_workspace.env.KILN_PROGRAM_STORE', ${quote(store)}],\n ['mcp_servers.kiln_workspace.env.KILN_RENDER', 'auto'],\n].flatMap(([key, value]) => ['-c', key + '=' + JSON.stringify(value)]);\nconst args = process.argv.slice(2);\nconst sub = args.find(arg => !arg.startsWith('-'));\nconst rest = sub === 'exec' ? args : ['exec', ...args];\nconst executable = process.platform === 'win32' ? 'codex.cmd' : 'codex';\nconst child = spawn(executable, [...rest.slice(0, 1), ...overrides, '--cd', root, '--skip-git-repo-check', ...rest.slice(1)], { cwd: root, stdio: 'inherit', windowsHide: true });\nchild.on('error', error => { console.error(error.message); process.exitCode = 1; });\nchild.on('exit', code => { process.exitCode = code ?? 1; });\n`;}if (harness === 'agy') {files['.agents/mcp_config.json'] = quote({ mcpServers: { kiln_workspace: mcp } });diff --git a/scripts/tier2-dogfood.mjs b/scripts/tier2-dogfood.mjsindex 50c697fd..87dae129 100644--- a/scripts/tier2-dogfood.mjs+++ b/scripts/tier2-dogfood.mjs@@ -53,6 +53,7 @@ Options:Acknowledge a contributor model in an isolated Hermes home--hermes-home PATH Operator-prepared isolated Hermes home for an authenticated route--agy-home PATH Operator-prepared clean Agy home retaining only required auth+ --allow-env NAME Explicitly pass one environment variable (repeatable; secrets may reach the provider)--timeout 45m Per-run wall deadline--compact-tokens N Supported per-run compaction threshold (for example 333000)--out PATH Raw evidence directory (default: ignored .dogfood/tier2/...)@@ -74,6 +75,7 @@ export function parseArgs(argv) {allowDataTrainingTier: false,hermesHome: null,agyHome: null,+ allowedEnvironmentNames: [],timeoutMs: parseDuration('45m'),compactTokens: null,outDir: null,@@ -102,6 +104,7 @@ export function parseArgs(argv) {else if (arg === '--allow-data-training-tier') opts.allowDataTrainingTier = true;else if (arg === '--hermes-home') opts.hermesHome = resolve(value());else if (arg === '--agy-home') opts.agyHome = resolve(value());+ else if (arg === '--allow-env') opts.allowedEnvironmentNames.push(value());else if (arg === '--timeout') {const duration = parseDuration(value());if (!duration) throw new Error('--timeout must be a positive duration such as 45m.');@@ -160,6 +163,8 @@ export function parseArgs(argv) {throw new Error('--agy-home is supported only for Agy.');if (opts.harness === 'agy' && !opts.agyHome)throw new Error('Agy blind runs require an operator-prepared --agy-home.');+ if (opts.allowedEnvironmentNames.some((name) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name)))+ throw new Error('--allow-env requires an environment variable name.');if (opts.live && !opts.authorization)throw new Error('--run-live requires --authorization pointing to the recorded approval.');return opts;@@ -230,7 +235,7 @@ export function buildInvocation({return {bin: 'agy',args,- env: { HOME: agyHome },+ env: agyIsolationEnv(agyHome),isolation: ['operator-prepared clean Agy home suppresses user MCP servers and plugins','only authentication/runtime links explicitly placed in that home are inherited',@@ -261,10 +266,10 @@ export function buildInvocation({'-c','model_auto_compact_token_limit_scope="total"',);- args.push(prompt);return {bin: 'codex',args,+ stdin: prompt,isolation: ['user config ignored; CODEX_HOME retained for authentication','user/project execution rules ignored',@@ -347,6 +352,19 @@ export function buildInvocation({throw new Error(`Unsupported harness: ${harness}`);}+export function agyIsolationEnv(agyHome, platform = process.platform) {+ const env = { HOME: agyHome };+ if (platform !== 'win32') return env;++ env.USERPROFILE = agyHome;+ const windowsHome = /^([A-Za-z]:)([\\/].*)$/u.exec(agyHome);+ if (windowsHome) {+ env.HOMEDRIVE = windowsHome[1];+ env.HOMEPATH = windowsHome[2].replaceAll('/', '\\');+ }+ return env;+}+function appendErrorText(value, found) {if (typeof value === 'string') found.push(value);else if (value && typeof value === 'object') {@@ -377,7 +395,7 @@ const AUTH_FAILURE =/\b401\b|authentication (?:failed|required)|unauthorized|invalid (?:api[ _-]?key|oauth token|access token)|(?:oauth|access) token (?:has )?expired|(?:not logged in|login required|sign[ -]?in required)|missing (?:api[ _-]?key|credentials)/iu;const HARNESS_STDOUT_FAILURE = /^API call failed after \d+ retries?:/iu;const BENIGN_STDERR_NOTICE =- /^root agent idle; waiting for \d+ background task\(s\)(?: \(bounded by --print-timeout\))?$/iu;+ /^(?:root agent idle; waiting for \d+ background task\(s\)(?: \(bounded by --print-timeout\))?|Reading (?:additional input|prompt) from stdin\.\.\.)$/iu;function classifyMessage(message) {if (QUOTA_FAILURE.test(message)) return 'provider-quota';@@ -442,7 +460,7 @@ function killProcessTree(child, signal = 'SIGTERM') {export function runProcess(bin,args,- { cwd, env, stdoutPath, stderrPath, timeoutMs, killGraceMs = 5_000, signal = null },+ { cwd, env, stdin = null, stdoutPath, stderrPath, timeoutMs, killGraceMs = 5_000, signal = null },) {return new Promise((resolveRun) => {const stdout = createWriteStream(stdoutPath, { flags: 'wx', mode: 0o600 });@@ -458,12 +476,13 @@ export function runProcess(env,detached: process.platform !== 'win32',shell: resolved.shell,- stdio: ['ignore', 'pipe', 'pipe'],+ stdio: [stdin === null ? 'ignore' : 'pipe', 'pipe', 'pipe'],windowsHide: true,};const child = resolved.shell? spawn(quoteArg(resolved.cmd), args.map(quoteArg), spawnOptions): spawn(resolved.cmd, args, spawnOptions);+ if (stdin !== null) child.stdin.end(stdin);child.stdout.pipe(stdout);child.stderr.pipe(stderr);const started = Date.now();@@ -647,6 +666,56 @@ function sensitiveEnvironmentNames(env) {.sort();}+const CHILD_ENVIRONMENT_NAMES = new Set([+ 'ALLUSERSPROFILE',+ 'APPDATA',+ 'CODEX_HOME',+ 'CommonProgramFiles',+ 'CommonProgramFiles(x86)',+ 'CommonProgramW6432',+ 'ComSpec',+ 'HOME',+ 'HOMEDRIVE',+ 'HOMEPATH',+ 'LANG',+ 'LOCALAPPDATA',+ 'NODE_EXTRA_CA_CERTS',+ 'PATH',+ 'PATHEXT',+ 'PROGRAMDATA',+ 'ProgramFiles',+ 'ProgramFiles(x86)',+ 'ProgramW6432',+ 'PSModulePath',+ 'SSL_CERT_DIR',+ 'SSL_CERT_FILE',+ 'SystemDrive',+ 'SystemRoot',+ 'TEMP',+ 'TMP',+ 'TMPDIR',+ 'USERDOMAIN',+ 'USERNAME',+ 'USERPROFILE',+ 'WINDIR',+ 'XDG_CACHE_HOME',+ 'XDG_DATA_HOME',+ 'XDG_STATE_HOME',+]);++export function childEnvironment(base, overrides = {}, allowedNames = []) {+ const allowed = new Set(allowedNames);+ const env = {};+ for (const [name, value] of Object.entries(base)) {+ if (+ value !== undefined &&+ (CHILD_ENVIRONMENT_NAMES.has(name) || name.startsWith('LC_') || allowed.has(name))+ )+ env[name] = value;+ }+ return { ...env, ...overrides };+}+const savedAssetKey = (asset) => asset.manifestPath ?? `${asset.sourcePath}\0${asset.glbPath}`;async function main(argv) {@@ -747,7 +816,8 @@ async function main(argv) {workspaceRoot,localGallery: opts.localGallery,localGalleryRoot: opts.localGallery ? galleryRoot : null,- inheritedSensitiveEnvironmentNames: sensitiveEnvironmentNames(process.env),+ ambientSensitiveEnvironmentNames: sensitiveEnvironmentNames(process.env),+ explicitlyAllowedEnvironmentNames: opts.allowedEnvironmentNames,requestedRunCount: planned.length,plannedRuns: planned.map(({ runId, goal }) => ({ runId, goal })),runs: [],@@ -779,17 +849,23 @@ async function main(argv) {),);const savedBefore = new Set(discoverSavedAssets([workspaceRoot]).map(savedAssetKey));+ const runEnvironment = childEnvironment(+ process.env,+ plan.invocation.env,+ opts.allowedEnvironmentNames,+ );writeJsonAtomic(invocationPath, {command: plan.invocation.bin,args: plan.invocation.args,cwd: plan.workspace,isolation: plan.invocation.isolation,- inheritedEnvironmentNames: Object.keys(process.env).sort(),+ inheritedEnvironmentNames: Object.keys(runEnvironment).sort(),});process.stdout.write(`[${plan.runId}] starting ${opts.harness} in ${plan.workspace}\n`);const processResult = await runProcess(plan.invocation.bin, plan.invocation.args, {cwd: plan.workspace,- env: { ...process.env, ...plan.invocation.env },+ env: runEnvironment,+ stdin: plan.invocation.stdin ?? null,stdoutPath,stderrPath,timeoutMs: opts.timeoutMs,diff --git a/scripts/tier2-dogfood.test.mjs b/scripts/tier2-dogfood.test.mjsindex cdfbf312..71f2e9fb 100644--- a/scripts/tier2-dogfood.test.mjs+++ b/scripts/tier2-dogfood.test.mjs@@ -3,7 +3,9 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSyncimport { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import {+ agyIsolationEnv,buildInvocation,+ childEnvironment,classifyOutcome,composeBlindPrompt,discoverArtifacts,@@ -46,6 +48,31 @@ describe('Tier 2 blind dogfood driver', () => {).toThrow(/authorization/i);});+ test('live child environments exclude ambient secrets unless explicitly allowed', () => {+ const base = {+ PATH: '/bin',+ HOME: '/home/tester',+ CLOUDFLARE_TOKEN: 'must-not-pass',+ OPENAI_API_KEY: 'explicit-provider-key',+ LC_ALL: 'C',+ };+ expect(childEnvironment(base, { HOME: '/isolated' })).toEqual({+ PATH: '/bin',+ HOME: '/isolated',+ LC_ALL: 'C',+ });+ expect(childEnvironment(base, {}, ['OPENAI_API_KEY'])).toEqual({+ PATH: '/bin',+ HOME: '/home/tester',+ OPENAI_API_KEY: 'explicit-provider-key',+ LC_ALL: 'C',+ });+ expect(+ parseArgs(['--harness', 'codex', '--goal', 'a crane', '--allow-env', 'OPENAI_API_KEY'])+ .allowedEnvironmentNames,+ ).toEqual(['OPENAI_API_KEY']);+ });+test('user-library capture is default-on and can be explicitly redirected or disabled', () => {expect(parseArgs(['--harness', 'codex', '--goal', 'an intricate walking crane'])).toMatchObject({ localGallery: true, galleryRoot: null },@@ -85,6 +112,8 @@ describe('Tier 2 blind dogfood driver', () => {expect(codex.args).toContain('--ephemeral');expect(codex.args).toContain('--dangerously-bypass-approvals-and-sandbox');expect(codex.args).toContain('model_auto_compact_token_limit=333000');+ expect(codex.args).not.toContain('brief');+ expect(codex.stdin).toBe('brief');const claude = buildInvocation({harness: 'claude',@@ -234,7 +263,24 @@ describe('Tier 2 blind dogfood driver', () => {expect(invocation.args).toContain('--print=brief');expect(invocation.args).toContain('--new-project');- expect(invocation.env).toEqual({ HOME: resolve('/tmp/agy-home') });+ expect(invocation.env).toEqual(agyIsolationEnv(resolve('/tmp/agy-home')));+ });++ test('Agy isolates the Windows profile variables used by its config resolver', () => {+ expect(agyIsolationEnv('C:\\isolated\\agy-home', 'win32')).toEqual({+ HOME: 'C:\\isolated\\agy-home',+ USERPROFILE: 'C:\\isolated\\agy-home',+ HOMEDRIVE: 'C:',+ HOMEPATH: '\\isolated\\agy-home',+ });+ });++ test('Agy keeps the conventional isolated HOME on Linux and macOS', () => {+ for (const platform of ['linux', 'darwin']) {+ expect(agyIsolationEnv('/tmp/isolated-agy-home', platform)).toEqual({+ HOME: '/tmp/isolated-agy-home',+ });+ }});test('telemetry field names do not masquerade as a quota failure', () => {@@ -286,6 +332,11 @@ describe('Tier 2 blind dogfood driver', () => {expect(evidence).toEqual([{ class: 'harness-error', message: 'Error: child process failed' }]);});+ test('Codex stdin progress notices are not failure evidence', () => {+ expect(evidenceFromTrace('', 'Reading prompt from stdin...\n')).toEqual([]);+ expect(evidenceFromTrace('', 'Reading additional input from stdin...\n')).toEqual([]);+ });+test('a source and GLB are necessary but remain pending human quality review', () => {expect(classifyOutcome({@@ -353,6 +404,31 @@ describe('Tier 2 blind dogfood driver', () => {expect(readFileSync(stderrPath, 'utf8')).toContain('deadline exceeded');});+ test('a harness prompt can be delivered through stdin without becoming a shell argument', async () => {+ const root = mkdtempSync(join(tmpdir(), 'kiln-tier2-stdin-test-'));+ roots.push(root);+ const stdoutPath = join(root, 'stdout.jsonl');+ const stderrPath = join(root, 'stderr.log');+ const result = await runProcess(+ 'node',+ [+ '-e',+ "process.stdin.setEncoding('utf8');let s='';process.stdin.on('data',d=>s+=d);process.stdin.on('end',()=>process.stdout.write(s))",+ ],+ {+ cwd: root,+ env: process.env,+ stdin: 'line one\nline two',+ stdoutPath,+ stderrPath,+ timeoutMs: 1_000,+ },+ );++ expect(result.exitCode).toBe(0);+ expect(readFileSync(stdoutPath, 'utf8')).toBe('line one\nline two');+ });+test('sanitized receipts redact credentials and machine paths', () => {const sanitized = sanitizeReceipt({diff --git a/src/__tests__/cli-render-mode.test.ts b/src/__tests__/cli-render-mode.test.tsindex c2101e42..2ca731e5 100644--- a/src/__tests__/cli-render-mode.test.ts+++ b/src/__tests__/cli-render-mode.test.ts@@ -17,7 +17,7 @@ import type { AddressInfo } from 'node:net';import { afterEach, describe, expect, it } from 'bun:test';-import { makeRemoteRenderPort, probeRenderService } from '../cli-render-mode';+import { buildRenderPort, makeRemoteRenderPort, probeRenderService } from '../cli-render-mode';const servers: Server[] = [];@@ -102,3 +102,50 @@ it('sends the shared grid background to the GPU service for ordinary asset sheetexpect(body?.background).toBe('#1a1a1a');});++it('authenticates an auto-started local renderer with its inherited service token', async () => {+ const previousClientToken = process.env.KILN_RENDER_TOKEN;+ const previousServiceToken = process.env.RENDER_SERVICE_TOKEN;+ const token = 'local-renderer-test-token';+ let receivedToken: string | undefined;+ const server = createServer(async (req, res) => {+ receivedToken = req.headers['x-render-token'] as string | undefined;+ for await (const _chunk of req) {+ // Drain the request before answering, like the real render service.+ }+ res.setHeader('content-type', 'application/json');+ res.end(+ JSON.stringify({+ ok: true,+ rendererId: 'test-renderer',+ views: [Buffer.from('png').toString('base64')],+ }),+ );+ });+ servers.push(server);+ const url = await new Promise<string>((resolve) => {+ server.listen(0, '127.0.0.1', () => {+ resolve(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);+ });+ });++ try {+ delete process.env.KILN_RENDER_TOKEN;+ process.env.RENDER_SERVICE_TOKEN = token;+ const context = await buildRenderPort('auto', undefined, {+ autoSpawn: true,+ start: async () => url,+ });+ await context.viewRenderPort!({+ glb: new Uint8Array([1]),+ viewDirs: [[1, 0, 0]],+ size: 384,+ });+ expect(receivedToken).toBe(token);+ } finally {+ if (previousClientToken === undefined) delete process.env.KILN_RENDER_TOKEN;+ else process.env.KILN_RENDER_TOKEN = previousClientToken;+ if (previousServiceToken === undefined) delete process.env.RENDER_SERVICE_TOKEN;+ else process.env.RENDER_SERVICE_TOKEN = previousServiceToken;+ }+});diff --git a/src/__tests__/mcp-instructions.test.ts b/src/__tests__/mcp-instructions.test.tsindex efc30afd..f101ba28 100644--- a/src/__tests__/mcp-instructions.test.ts+++ b/src/__tests__/mcp-instructions.test.ts@@ -18,7 +18,13 @@ const repo = fileURLToPath(new URL('../..', import.meta.url));describe('MCP server instructions', () => {it('names only skills that exist on disk', async () => {- const named = [...new Set(MCP_SERVER_INSTRUCTIONS.match(/kiln-[a-z-]+/g) ?? [])];+ const named = [+ ...new Set(+ [...MCP_SERVER_INSTRUCTIONS.matchAll(/^\s*-\s+(kiln-[a-z-]+):/gm)].map(+ (match) => match[1]!,+ ),+ ),+ ];expect(named.length).toBeGreaterThan(0);for (const name of named) {const skill = join(repo, 'skills', name, 'SKILL.md');diff --git a/src/__tests__/render-service-host.test.ts b/src/__tests__/render-service-host.test.tsindex fb5364d0..00b0f941 100644--- a/src/__tests__/render-service-host.test.ts+++ b/src/__tests__/render-service-host.test.ts@@ -28,6 +28,7 @@ import { afterEach, describe, expect, it } from 'bun:test';import {localRenderServiceState,+ renderServiceNodeArguments,startLocalRenderService,stopLocalRenderService,} from '../render-service-host';@@ -88,6 +89,14 @@ describe('localRenderServiceState', () => {});});+it('passes the Node import hook as a file URL on every platform', () => {+ const [flag, hook, server] = renderServiceNodeArguments(resolve('render-service'));+ expect(flag).toBe('--import');+ expect(hook).toStartWith('file:');+ expect(hook).toEndWith('/src/register-hooks.mjs');+ expect(server).toEndWith(join('render-service', 'src', 'server.mjs'));+});+describe('buildRenderPort with autoSpawn', () => {it('attaches nothing when the renderer is not installed, so a CPU-only machine reads as ordinary', async () => {const context = await buildRenderPort('auto', undefined, {diff --git a/src/__tests__/workspace-bootstrap.test.ts b/src/__tests__/workspace-bootstrap.test.tsindex 86cccf19..dc1ba8da 100644--- a/src/__tests__/workspace-bootstrap.test.ts+++ b/src/__tests__/workspace-bootstrap.test.ts@@ -292,6 +292,7 @@ it('gives every user-global harness a launcher that configures without relocatin// A workspace is deliberately not a git checkout.expect(codex).toContain('--skip-git-repo-check');expect(codex).toContain("'--cd'");+ expect(codex).toContain("process.platform === 'win32' ? 'codex.cmd' : 'codex'");// The launcher must never move the home that holds credentials.expect(codex).not.toContain('CODEX_HOME');diff --git a/src/__tests__/workspace-node-path.test.ts b/src/__tests__/workspace-node-path.test.tsindex e18ed11d..6692f0b8 100644--- a/src/__tests__/workspace-node-path.test.ts+++ b/src/__tests__/workspace-node-path.test.ts@@ -9,6 +9,8 @@ it('generated MCP command survives removal of a transient Node directory link',const root = await mkdtemp(join(tmpdir(), 'kiln-node-link-'));const probe = spawnSync('node', ['-p', 'process.execPath'], { encoding: 'utf8' });expect(probe.status).toBe(0);+ const versionProbe = spawnSync('node', ['--version'], { encoding: 'utf8' });+ expect(versionProbe.status).toBe(0);const canonical = realpathSync(probe.stdout.trim()),link = join(root, 'ephemeral-shell'),alias = join(link, basename(canonical)),@@ -30,7 +32,7 @@ it('generated MCP command survives removal of a transient Node directory link',encoding: 'utf8',});expect(started.status).toBe(0);- expect(started.stdout).toMatch(/^v22\./);+ expect(started.stdout).toBe(versionProbe.stdout);} finally {await rm(root, { recursive: true, force: true });}diff --git a/src/assets-tools.test.ts b/src/assets-tools.test.tsindex 5d8a8041..c31d71a1 100644--- a/src/assets-tools.test.ts+++ b/src/assets-tools.test.ts@@ -3,6 +3,7 @@ import { mkdtemp, rm } from 'node:fs/promises';import { join } from 'node:path';import { tmpdir } from 'node:os';import { Client, InMemoryTransport } from '@modelcontextprotocol/client';+import { EXTENSION_ID as MCP_APPS_EXTENSION_ID } from '@modelcontextprotocol/ext-apps/server';import { createKilnMcpServer } from './mcp-server';import { FileAssetLibrary } from './assets-node';import { MemoryProgramStore, retainProgram } from './program-store';@@ -20,11 +21,14 @@ test('MCP saves an editable revision, exposes exact downloadable bytes, and restconst code ="const meta = { name: 'Box', category: 'prop' }; function build() { const root = createRoot('Box'); createPart('Body', boxGeo(1,1,1), gameMaterial(0x88aa66), {parent: root, position: [0,0.5,0]}); return root; }";const programRef = await retainProgram(programStore, code);- const server = createKilnMcpServer({- programStore,- assetLibrary,- assetDownloadUrls: async () => ({ 'asset.glb': 'https://example.com/asset.glb' }),- });+ const server = createKilnMcpServer(+ {+ programStore,+ assetLibrary,+ assetDownloadUrls: async () => ({ 'asset.glb': 'https://example.com/asset.glb' }),+ },+ { artifactResourceLinks: true },+ );const client = new Client({ name: 'asset-test', version: '1' });const [ct, st] = InMemoryTransport.createLinkedPair();await Promise.all([client.connect(ct), server.connect(st)]);@@ -40,6 +44,11 @@ test('MCP saves an editable revision, exposes exact downloadable bytes, and restexpect(presentation.description).toContain('does not launch a local browser');expect(presentation.outputSchema).toBeDefined();expect(presentation._meta?.ui).toBeDefined();+ const uiMeta = presentation._meta?.ui as { resourceUri?: string } | undefined;+ expect(presentation._meta?.['ui/resourceUri']).toBe(uiMeta?.resourceUri);+ expect(client.getServerCapabilities()?.extensions?.[MCP_APPS_EXTENSION_ID]).toEqual({+ mimeTypes: ['text/html;profile=mcp-app'],+ });const result = await client.callTool({name: 'kiln_save',arguments: { programRef, name: 'Box' },@@ -148,7 +157,10 @@ test('every advertised asset link says how big it is and who it is for', async (programStore,"const meta = { name: 'Box', category: 'prop' }; function build() { const root = createRoot('Box'); createPart('Body', boxGeo(1,1,1), gameMaterial(0x88aa66), {parent: root, position: [0,0.5,0]}); return root; }",);- const server = createKilnMcpServer({ programStore, assetLibrary });+ const server = createKilnMcpServer(+ { programStore, assetLibrary },+ { artifactResourceLinks: true },+ );const client = new Client({ name: 'asset-link-test', version: '1' });const [ct, st] = InMemoryTransport.createLinkedPair();await Promise.all([client.connect(ct), server.connect(st)]);@@ -195,3 +207,37 @@ test('every advertised asset link says how big it is and who it is for', async (await rm(root, { recursive: true, force: true });}});++test('the default MCP transport keeps artifact URIs readable without resource-link blocks', async () => {+ const root = await mkdtemp(join(tmpdir(), 'kiln-resource-link-compat-'));+ const programStore = new MemoryProgramStore();+ const assetLibrary = new FileAssetLibrary({ project: root });+ const server = createKilnMcpServer({ programStore, assetLibrary });+ const client = new Client({ name: 'portable-result-test', version: '1' });+ const [ct, st] = InMemoryTransport.createLinkedPair();+ await Promise.all([client.connect(ct), server.connect(st)]);+ try {+ const code =+ "const meta = { name: 'Box', category: 'prop' }; function build() { const root = createRoot('Box'); createPart('Body', boxGeo(1,1,1), gameMaterial(0x88aa66), {parent: root, position: [0,0.5,0]}); return root; }";+ const programRef = await retainProgram(programStore, code);+ const result = await client.callTool({+ name: 'kiln_save',+ arguments: { programRef, name: 'Compatibility Box' },+ });+ expect(result.content.map((block) => block.type)).toEqual(['text']);+ const payload = JSON.parse((result.content[0] as { type: 'text'; text: string }).text);+ expect(payload.resources.length).toBeGreaterThan(0);+ expect(+ payload.resources.every((link: { uri?: string }) => link.uri?.startsWith('kiln://assets/')),+ ).toBe(true);+ const source = payload.resources.find(+ (link: { name?: string }) => link.name === 'source.kiln.js',+ );+ const read = await client.readResource({ uri: source.uri });+ expect('text' in read.contents[0]! ? read.contents[0].text : undefined).toBe(code);+ } finally {+ await client.close();+ await server.close();+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/src/cli-render-mode.ts b/src/cli-render-mode.tsindex 8e09aad2..f04c19bc 100644--- a/src/cli-render-mode.ts+++ b/src/cli-render-mode.ts@@ -337,7 +337,7 @@ export async function buildRenderPort(context.viewRenderPort = makeLazyRenderPort(async () => {url = await start();return url;- }, process.env['KILN_RENDER_TOKEN']);+ }, process.env['KILN_RENDER_TOKEN'] ?? process.env['RENDER_SERVICE_TOKEN']);context.viewRenderTimeoutMs = CLI_VIEW_RENDER_TIMEOUT_MS;// Nothing to attest until a producer exists. `undefined` bypasses cell reuse,// which is the correct reading of "no renderer has drawn anything yet".diff --git a/src/mcp-server.ts b/src/mcp-server.tsindex d79cde65..ad6fc729 100644--- a/src/mcp-server.ts+++ b/src/mcp-server.ts@@ -5,6 +5,12 @@* their own store and renderer; schemas and image extraction stay in the registry.*/import { McpServer, ResourceTemplate } from '@modelcontextprotocol/server';+import {+ EXTENSION_ID as MCP_APPS_EXTENSION_ID,+ RESOURCE_MIME_TYPE as MCP_APPS_MIME_TYPE,+ registerAppResource,+ registerAppTool,+} from '@modelcontextprotocol/ext-apps/server';import { localAssetLibrary } from './assets-node';import { readAssetResource, type AssetLink } from './assets-resources';import { serveStdio } from '@modelcontextprotocol/server/stdio';@@ -27,6 +33,19 @@ import { createPackagedLocalToolContext } from './local-runtime';export const MCP_SERVER_NAME = 'kiln';export const MCP_SERVER_VERSION = ENGINE_VERSION;+/** Optional wire features whose support is not negotiated by core MCP. */+export type KilnMcpCompatibilityOptions = {+ /**+ * Add core `resource_link` blocks for saved artifact files.+ *+ * Core MCP 2026-07-28 permits these blocks but exposes no client capability+ * for them. They therefore remain opt-in while clients differ in how they+ * consume them. The same resource descriptors always remain in JSON text and+ * structured content, and every URI remains readable through resources/read.+ */+ artifactResourceLinks?: boolean;+};+/*** Absolute path to the skills that ship beside this server. Both entry shapes* resolve correctly: `dist/mcp-server.mjs` and `src/mcp-server.ts` each sit one@@ -105,7 +124,11 @@ export function kilnMcpToolDefs(context: KilnToolContext = {}): KilnToolDef[] {* description of it. The JSON that accompanies an image has its embedded base64* stripped by the extractor, so pixels are never double-encoded onto the wire.*/-export async function runTool(def: KilnToolDef, args: unknown): Promise<KilnToolResult> {+export async function runTool(+ def: KilnToolDef,+ args: unknown,+ options: KilnMcpCompatibilityOptions = {},+): Promise<KilnToolResult> {const output = await def.run(args);const multi = def.mediaMulti?.(output);@@ -143,9 +166,16 @@ export async function runTool(def: KilnToolDef, args: unknown): Promise<KilnToolif (asText !== undefined) return { content: [{ type: 'text', text: asText }] };const resources = (output as { resources?: AssetLink[] } | null)?.resources ?? [];- const payload = resources.length ? { ...(output as object), resources: undefined } : output;+ const includeResourceLinks = options.artifactResourceLinks === true;+ const payload =+ resources.length && includeResourceLinks+ ? { ...(output as object), resources: undefined }+ : output;return {- content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }, ...resources],+ content: [+ { type: 'text', text: JSON.stringify(payload, null, 2) },+ ...(includeResourceLinks ? resources : []),+ ],...(def.ui? {structuredContent: output as Record<string, unknown>,@@ -156,26 +186,45 @@ export async function runTool(def: KilnToolDef, args: unknown): Promise<KilnTool}/** Build the server, registering every def from the registry. */-export function createKilnMcpServer(context: KilnToolContext = {}): McpServer {+export function createKilnMcpServer(+ context: KilnToolContext = {},+ options: KilnMcpCompatibilityOptions = {},+): McpServer {const server = new McpServer({name: MCP_SERVER_NAME,version: MCP_SERVER_VERSION,},- { instructions: MCP_SERVER_INSTRUCTIONS },+ {+ instructions: MCP_SERVER_INSTRUCTIONS,+ capabilities: {+ extensions: {+ [MCP_APPS_EXTENSION_ID]: { mimeTypes: [MCP_APPS_MIME_TYPE] },+ },+ },+ },);- server.registerResource(+ registerAppResource(+ server,'kiln-asset-viewer',KILN_ASSET_WIDGET_URI,{description: 'Interactive Kiln asset viewer and downloads',- mimeType: 'text/html;profile=mcp-app',+ _meta: {+ ui: {+ prefersBorder: true,+ csp: { connectDomains: [], resourceDomains: [] },+ },+ 'openai/widgetDescription':+ 'Inspect the saved 3D asset and download its GLB or editable bundle.',+ 'openai/widgetPrefersBorder': true,+ },},async (uri) => ({contents: [{uri: uri.href,- mimeType: 'text/html;profile=mcp-app',+ mimeType: MCP_APPS_MIME_TYPE,text: await (await import('./asset-widget')).readAssetWidgetHtml(),_meta: {ui: {@@ -233,47 +282,54 @@ export function createKilnMcpServer(context: KilnToolContext = {}): McpServer {};for (const def of kilnMcpToolDefs(requestContext)) {- server.registerTool(- def.name,- {- description: def.description,- annotations: def.annotations,- ...(def.ui- ? {- _meta: {- ui: { resourceUri: def.ui.resourceUri },- 'openai/outputTemplate': def.ui.resourceUri,- 'openai/widgetAccessible': true,- },- }- : {}),- // The registry's zod schema, passed straight through as Standard Schema.- // The SDK advertises the derived JSON Schema and validates arguments, so- // there is no second copy of the schema anywhere in this file. No cast:- // a cast here would silently decouple the advertised schema from the- // registry's, which is the one thing this file exists not to do.- inputSchema: def.inputSchema,- ...(def.outputSchema ? { outputSchema: def.outputSchema } : {}),- },- async (args: unknown, request): Promise<KilnToolResult> => {- try {- return await requests.run(request.mcpReq.signal, () => runTool(def, args));- } catch (err) {- // A tool error is a result, not a transport failure: the calling agent- // should see the message and correct its program rather than lose the- // session.- return {- isError: true,- content: [- {- type: 'text' as const,- text: err instanceof Error ? err.message : String(err),- },- ],- };- }- },- );+ const config = {+ description: def.description,+ annotations: def.annotations,+ // The registry's zod schema, passed straight through as Standard Schema.+ // The SDK advertises the derived JSON Schema and validates arguments, so+ // there is no second copy of the schema anywhere in this file. No cast:+ // a cast here would silently decouple the advertised schema from the+ // registry's, which is the one thing this file exists not to do.+ inputSchema: def.inputSchema,+ ...(def.outputSchema ? { outputSchema: def.outputSchema } : {}),+ };+ const handler = async (+ args: unknown,+ request: Parameters<Parameters<typeof server.registerTool>[2]>[1],+ ): Promise<KilnToolResult> => {+ try {+ return await requests.run(request.mcpReq.signal, () => runTool(def, args, options));+ } catch (err) {+ // A tool error is a result, not a transport failure: the calling agent+ // should see the message and correct its program rather than lose the+ // session.+ return {+ isError: true,+ content: [+ {+ type: 'text' as const,+ text: err instanceof Error ? err.message : String(err),+ },+ ],+ };+ }+ };+ if (def.ui) {+ registerAppTool(+ server,+ def.name,+ {+ ...config,+ _meta: {+ ui: { resourceUri: def.ui.resourceUri, visibility: ['model'] },+ 'openai/outputTemplate': def.ui.resourceUri,+ },+ },+ handler,+ );+ } else {+ server.registerTool(def.name, config, handler);+ }}return server;@@ -314,5 +370,9 @@ if (isDirectEntry(import.meta.url)) {}// stdout is the MCP transport; diagnostics must never touch it.console.error(`kiln MCP server on stdio (${mode})`);- void serveStdio(() => createKilnMcpServer(context));+ void serveStdio(() =>+ createKilnMcpServer(context, {+ artifactResourceLinks: process.env['KILN_MCP_RESOURCE_LINKS'] === '1',+ }),+ );}diff --git a/src/render-service-host.ts b/src/render-service-host.tsindex 8ed2f0b4..09e6bd6d 100644--- a/src/render-service-host.ts+++ b/src/render-service-host.ts@@ -22,7 +22,7 @@*/import { spawn, type ChildProcess } from 'node:child_process';import { existsSync } from 'node:fs';-import { fileURLToPath } from 'node:url';+import { fileURLToPath, pathToFileURL } from 'node:url';import { join } from 'node:path';/**@@ -51,6 +51,14 @@ export function localRenderServiceUrl(): string {return `http://127.0.0.1:${localRenderServicePort()}`;}+export function renderServiceNodeArguments(dir: string): string[] {+ return [+ '--import',+ pathToFileURL(join(dir, 'src/register-hooks.mjs')).href,+ join(dir, 'src/server.mjs'),+ ];+}+/** How long a starting service has to answer `/health` before it is called failed. */const STARTUP_BUDGET_MS = Number(process.env['KILN_RENDER_SERVICE_STARTUP_MS'] ?? 60_000);const STARTUP_POLL_MS = 250;@@ -173,25 +181,21 @@ export async function startLocalRenderService(dir = renderServiceDir()): PromiseregisterTeardown();let stderr = '';- child = spawn(- nodeBinary(),- ['--import', join(dir, 'src/register-hooks.mjs'), join(dir, 'src/server.mjs')],- {- cwd: dir,- env: {- ...process.env,- PORT: String(localRenderServicePort()),- // Loopback, where the documented manual start binds every interface. We- // are choosing on the user's behalf here, so the narrow choice is the- // right one; the Docker deployment sets its own HOST and is unaffected.- HOST: '127.0.0.1',- },- // NEVER `inherit`: stdout is the MCP transport, and the service greets its- // own boot on stdout. One `listening on :8000` line in that stream is a- // protocol error for every tool call after it.- stdio: ['ignore', 'ignore', 'pipe'],+ child = spawn(nodeBinary(), renderServiceNodeArguments(dir), {+ cwd: dir,+ env: {+ ...process.env,+ PORT: String(localRenderServicePort()),+ // Loopback, where the documented manual start binds every interface. We+ // are choosing on the user's behalf here, so the narrow choice is the+ // right one; the Docker deployment sets its own HOST and is unaffected.+ HOST: '127.0.0.1',},- );+ // NEVER `inherit`: stdout is the MCP transport, and the service greets its+ // own boot on stdout. One `listening on :8000` line in that stream is a+ // protocol error for every tool call after it.+ stdio: ['ignore', 'ignore', 'pipe'],+ });child.stderr?.on('data', (chunk: Buffer) => {stderr = `${stderr}${chunk.toString()}`.slice(-2_000);});diff --git a/src/tools/registry.ts b/src/tools/registry.tsindex 1e17622c..9903a020 100644--- a/src/tools/registry.ts+++ b/src/tools/registry.ts@@ -2572,7 +2572,7 @@ export function createKilnAssetDefs(context: KilnToolContext): KilnToolDef[] {{name: 'kiln_present',description:- 'Present one exact saved revision. Supporting MCP App clients show an interactive 3D card with GLB, editable ZIP, and source downloads. Other hosts receive portable resource links; this tool does not launch a local browser in coding harnesses. Call after saving or when the user wants to see or download an asset.',+ 'Present one exact saved revision. Supporting MCP App clients show an interactive 3D card with GLB, editable ZIP, and source downloads. Every host receives exact artifact descriptors with resource URIs in the JSON result; verified hosts may also receive core MCP resource-link blocks. This tool does not launch a local browser in coding harnesses. Call after saving or when the user wants to see or download an asset.',inputSchema: exportInput,outputSchema: z.object({ok: z.literal(true),@@ -2635,7 +2635,7 @@ export function createKilnAssetDefs(context: KilnToolContext): KilnToolDef[] {{name: 'kiln_export',description:- 'Get downloadable GLB, source, manifest, and portable ZIP resource links for one exact saved revision. The ZIP contains source when available and does not require the original program store. Use the host resource reader/download UI; no binary bytes are placed in tool text.',+ 'Get exact GLB, source, preview, and manifest descriptors for one saved revision. Their resource URIs remain readable through resources/read, and configured hosts may also return download URLs including a portable editable ZIP. No binary bytes are placed in tool text.',inputSchema: exportInput,run: async (raw) => {const input = exportInput.parse(raw);