@topline-build/harness-mcp 0.9.16 → 0.9.18

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/CHANGELOG.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  All notable customer-visible Build MCP changes are recorded here. A source change is not a published package or customer release.
4
4
 
5
+ ## 0.9.18 - 2026-11-18
6
+
7
+ - `platform_request_build_secret` asks a person for a key the app needs. Without `source`, Topline posts a request card in the session's build thread and the tool returns the thread link and what to tell the person. With `source` (`{fromEnv: "VAR"}` or `{fromFile: ".env", key: "VAR"}`, a dotenv file inside the workspace), this helper reads the value on this computer and uploads it to `PUT /api/v1/secrets/{name}` with the build session's own sign-in; the tool returns only `provided`. The value never appears in the result, progress or errors, and a missing variable returns `source_not_found:<VAR>` before Topline is called. Needs a Topline server that offers the tool.
8
+
9
+ ## 0.9.17 - 2026-11-16
10
+
11
+ - `platform_inspect_artifact_app`, when this computer is signed in, sends the bundle to Topline's preflight (`POST /api/harness/artifact-apps/preflight-bundle`). It runs the build's own local validation, such as `undeclared_package_import` for `react`, `esbuild` or `@aws-sdk/*`, and the manifest rules Topline applies on save, such as `tables[].operations` needing at least one operation. Each problem is listed under `problems`. `serverChecks` says whether the preflight ran (`passed`, `failed`, or `skipped:<reason>`), and `serverManifestValidationRequired` is false once it has. It never opens a browser sign-in.
12
+ - `platform_deploy_artifact_app` returns one `operationId`, the id `platform_wait_artifact_deploy` and `platform_deploy_operation` take: the build session's operation, or the task for a deploy outside a session. The worker task is `deployTaskId`, and the nested `deploy` record no longer repeats either id.
13
+ - `platform_init_artifact_app` has a `table-approvals-app` starter: a request form, "My requests" and an approver queue over company tables, written through server table SQL (`serverTables: true`) with a copyable `tablesSql()` helper and an app-owned approvers table. It declares no `tables[]`, so viewers can't list rows through a browser table route. Before its tables exist the page shows a setup state instead of failing smoke.
14
+ - The `cache-warmed-multi-source-dashboard` starter now says it needs the Redis live cache, and its first step is to check `platform_capability_status` and use `precomputed-s3-report` where `families.redis` is `not_supported`.
15
+
5
16
  ## 0.9.16 - 2026-11-11
6
17
 
7
18
  - `platform_deploy_artifact_app` runs inspect's manifest and `node --check` checks and refuses with `artifact_package_not_ready`, naming each problem's code and file, before it uploads anything or spends build budget. (Data-binding findings stay inspect-only, since a leftover build file can trip them.)
@@ -26,6 +26,13 @@ export type ArtifactStarter = {
26
26
  routes: ArtifactStarterRoute[];
27
27
  /** What the recipe adds on top of the scaffold, in the order to do it. */
28
28
  nextSteps: string[];
29
+ /**
30
+ * A complete app source shipped in templates/<id>/src/index.js instead of the
31
+ * generated placeholder handler; "__ARTIFACT_TITLE__" is replaced with the title.
32
+ */
33
+ template?: boolean;
34
+ /** Extra top-level manifest fields the starter needs (for example serverTables). */
35
+ manifest?: Record<string, unknown>;
29
36
  };
30
37
  export declare const ARTIFACT_STARTERS: ArtifactStarter[];
31
38
  export declare const ARTIFACT_STARTER_IDS: string[];
@@ -42,5 +49,7 @@ export declare function artifactStarterRecipe(starter: ArtifactStarter): {
42
49
  pluginPath: string;
43
50
  nextSteps: string[];
44
51
  };
52
+ /** The shipped source of a template starter, with its title filled in. */
53
+ export declare function artifactStarterTemplateSource(starter: ArtifactStarter, title: string): Promise<string>;
45
54
  /** Source for src/index.js: one handler serving the page and a placeholder per declared route. */
46
55
  export declare function artifactStarterSource(starter: ArtifactStarter, title: string): string;
@@ -1,19 +1,4 @@
1
- /**
2
- * Catalog-backed starters for platform_init_artifact_app.
3
- *
4
- * Each starter mirrors the route shape of one golden example in the Build
5
- * cookbook (skills/build-topline-artifact-apps/examples/<id>/), so a new app
6
- * starts with the recipe's page and private routes instead of a blank page.
7
- * The scaffold is dependency-free Node and serves placeholder answers only:
8
- * it never declares datasets, source bindings, secret bindings or Bedrock env,
9
- * because those need the customer's own tables, sources and approved secrets.
10
- * The platform itself serves /_artifact/data/* and /_artifact/knowledge/*, and
11
- * only for a declared dataset, binding or grant, so app code never sees those
12
- * requests. A starter's data route is therefore not a manifest route or a
13
- * handler: the page shows it as not connected and never fetches it, so a
14
- * fresh deploy's smoke check stays healthy instead of failing on a 404.
15
- * Its structured tests are labelled scaffold checks, not proof of behavior.
16
- */
1
+ import { readFile } from "node:fs/promises";
17
2
  export const ARTIFACT_STARTERS = [
18
3
  {
19
4
  id: "bounded-bedrock-assistant",
@@ -32,9 +17,10 @@ export const ARTIFACT_STARTERS = [
32
17
  {
33
18
  id: "cache-warmed-multi-source-dashboard",
34
19
  kind: "dashboard",
35
- summary: "Dashboard over a live dataset whose cache a schedule keeps warm.",
20
+ summary: "Dashboard over a live dataset whose cache a schedule keeps warm. Needs the Redis live cache: check platform_capability_status first, and where families.redis is not_supported use precomputed-s3-report instead.",
36
21
  routes: [{ path: "/_artifact/data/branch-service-summary", note: "Placeholder for the recipe's live dataset." }],
37
22
  nextSteps: [
23
+ "Call platform_capability_status: if families.redis is not_supported, this recipe's cache warming can't run on this account; start again from precomputed-s3-report.",
38
24
  "Find your own tables with the Workspace data catalog, then add the recipe's datasets[] and refreshSchedules[] with your SQL.",
39
25
  "Once the dataset serves the route, fetch it from the page in place of the not-connected notice and replace its scaffold check."
40
26
  ]
@@ -93,6 +79,24 @@ export const ARTIFACT_STARTERS = [
93
79
  ],
94
80
  nextSteps: ["The recipe uses the python-api template; keep this Node scaffold or port it, but keep every route under /_artifact/api/."]
95
81
  },
82
+ {
83
+ id: "table-approvals-app",
84
+ kind: "tool",
85
+ summary: "Requests and approvals over company tables: a request form, \"My requests\", and an approver queue, all through server table SQL with no tables[] browser route.",
86
+ routes: [
87
+ { path: "/_artifact/api/requests", note: "GET the viewer's requests (and the approver queue); POST a new request." },
88
+ { path: "/_artifact/api/decisions", method: "POST", note: "An approver approves or rejects the version they saw." }
89
+ ],
90
+ nextSteps: [
91
+ "Create the two tables with platform_run_artifact_workspace_sql (scope company), using the CREATE TABLE statements in the recipe; rename them to fit (for example company_data.time_off_requests) and update REQUESTS and APPROVERS in src/index.js.",
92
+ "Insert the approvers' emails into the approvers table (active true). There are no platform roles; this table is the app's role list.",
93
+ "Add your request fields (dates, amounts) as columns, in the form, and in the insert; every value comes back from server SQL as a string.",
94
+ "Drafts can only read through server SQL. To try submit and decide on a draft, set previewWrites: true, knowing it changes real rows; otherwise check writes on the live app after a person publishes it.",
95
+ "Keep tables[] out of the manifest: a tables[] binding would let every viewer list the rows directly."
96
+ ],
97
+ template: true,
98
+ manifest: { serverTables: true }
99
+ },
96
100
  {
97
101
  id: "viewer-scoped-customer-portal",
98
102
  kind: "dashboard",
@@ -129,6 +133,12 @@ export function artifactStarterRecipe(starter) {
129
133
  };
130
134
  }
131
135
  const escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[char]));
136
+ /** The shipped source of a template starter, with its title filled in. */
137
+ export async function artifactStarterTemplateSource(starter, title) {
138
+ const source = await readFile(new URL(`../templates/${starter.id}/src/index.js`, import.meta.url), "utf8");
139
+ // JSON.stringify yields a valid JS string literal; slice off its quotes to sit inside the existing ones.
140
+ return source.replace("__ARTIFACT_TITLE__", () => JSON.stringify(title).slice(1, -1));
141
+ }
132
142
  /** Source for src/index.js: one handler serving the page and a placeholder per declared route. */
133
143
  export function artifactStarterSource(starter, title) {
134
144
  const safeTitle = escapeHtml(title);
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Build secret requests, local source (Topline design 2026-11-18 §2b): when the person says a key
3
+ * is already on their machine, this helper reads it here and uploads it straight to Topline. The
4
+ * value never appears in a tool result, progress message, log line or error. Only the variable
5
+ * name is ever reported back.
6
+ */
7
+ export declare const MAX_LOCAL_SECRET_BYTES = 65536;
8
+ export type LocalSecretSource = {
9
+ fromEnv: string;
10
+ } | {
11
+ fromFile: string;
12
+ key: string;
13
+ };
14
+ export declare class LocalSecretSourceError extends Error {
15
+ readonly code: string;
16
+ readonly variable?: string | undefined;
17
+ constructor(code: string, variable?: string | undefined);
18
+ }
19
+ export declare function parseLocalSecretSource(value: unknown): LocalSecretSource;
20
+ /** Parses dotenv text: KEY=value, optional `export`, quotes, `#` comments; a double-quoted value may span lines. */
21
+ export declare function parseDotenv(text: string): Map<string, string>;
22
+ /** Reads the value on this machine. Throws source_not_found naming the variable, never a value. */
23
+ export declare function readLocalSecretValue(workspaceRoot: string, source: LocalSecretSource, env?: NodeJS.ProcessEnv): Promise<string>;
@@ -0,0 +1,119 @@
1
+ import { lstat, readFile, realpath } from "node:fs/promises";
2
+ import path from "node:path";
3
+ /**
4
+ * Build secret requests, local source (Topline design 2026-11-18 §2b): when the person says a key
5
+ * is already on their machine, this helper reads it here and uploads it straight to Topline. The
6
+ * value never appears in a tool result, progress message, log line or error. Only the variable
7
+ * name is ever reported back.
8
+ */
9
+ export const MAX_LOCAL_SECRET_BYTES = 65_536;
10
+ const MAX_DOTENV_FILE_BYTES = 1024 * 1024;
11
+ const VARIABLE = /^[A-Za-z_][A-Za-z0-9_.-]{0,127}$/;
12
+ export class LocalSecretSourceError extends Error {
13
+ code;
14
+ variable;
15
+ constructor(code, variable) {
16
+ // The variable name only, never a value.
17
+ super(variable ? `${code}:${variable}` : code);
18
+ this.code = code;
19
+ this.variable = variable;
20
+ }
21
+ }
22
+ export function parseLocalSecretSource(value) {
23
+ if (!value || typeof value !== "object" || Array.isArray(value))
24
+ throw new LocalSecretSourceError("source_invalid");
25
+ const record = value;
26
+ const keys = Object.keys(record).sort().join(",");
27
+ if (keys === "fromEnv" && typeof record.fromEnv === "string" && VARIABLE.test(record.fromEnv))
28
+ return { fromEnv: record.fromEnv };
29
+ if (keys === "fromFile,key" && typeof record.fromFile === "string" && record.fromFile.trim() && typeof record.key === "string" && VARIABLE.test(record.key)) {
30
+ return { fromFile: record.fromFile, key: record.key };
31
+ }
32
+ throw new LocalSecretSourceError("source_invalid");
33
+ }
34
+ /** Parses dotenv text: KEY=value, optional `export`, quotes, `#` comments; a double-quoted value may span lines. */
35
+ export function parseDotenv(text) {
36
+ const values = new Map();
37
+ const source = text.replace(/^/, "").replace(/\r\n?/g, "\n");
38
+ const line = /^[ \t]*(?:export[ \t]+)?([A-Za-z_][A-Za-z0-9_.-]*)[ \t]*=[ \t]*/gm;
39
+ let match;
40
+ while ((match = line.exec(source))) {
41
+ const name = match[1];
42
+ let at = line.lastIndex;
43
+ let value;
44
+ const quote = source[at];
45
+ if (quote === "\"" || quote === "'" || quote === "`") {
46
+ let end = at + 1;
47
+ while (end < source.length && (source[end] !== quote || (quote === "\"" && source[end - 1] === "\\" && source[end - 2] !== "\\")))
48
+ end++;
49
+ // An unterminated quote is not a value: the key reads as missing (source_not_found), never as the rest of the file.
50
+ if (end >= source.length)
51
+ break;
52
+ value = source.slice(at + 1, end);
53
+ if (quote === "\"")
54
+ value = value.replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, "\t").replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
55
+ at = end + 1;
56
+ }
57
+ else {
58
+ const newline = source.indexOf("\n", at);
59
+ const raw = source.slice(at, newline === -1 ? source.length : newline);
60
+ value = raw.replace(/[ \t]+#.*$/, "").trim();
61
+ at = newline === -1 ? source.length : newline;
62
+ }
63
+ values.set(name, value);
64
+ const rest = source.indexOf("\n", at);
65
+ line.lastIndex = rest === -1 ? source.length : rest + 1;
66
+ }
67
+ return values;
68
+ }
69
+ async function insideWorkspace(workspaceRoot, file) {
70
+ const root = await realpath(path.resolve(workspaceRoot));
71
+ const resolved = path.resolve(root, file);
72
+ const relative = path.relative(root, resolved);
73
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative))
74
+ throw new LocalSecretSourceError("source_file_outside_workspace");
75
+ let stat;
76
+ try {
77
+ stat = await lstat(resolved);
78
+ }
79
+ catch {
80
+ throw new LocalSecretSourceError("source_file_not_found");
81
+ }
82
+ if (stat.isSymbolicLink() || !stat.isFile())
83
+ throw new LocalSecretSourceError("source_file_not_found");
84
+ const real = await realpath(resolved);
85
+ const realRelative = path.relative(root, real);
86
+ if (!realRelative || realRelative.startsWith("..") || path.isAbsolute(realRelative))
87
+ throw new LocalSecretSourceError("source_file_outside_workspace");
88
+ if (stat.size > MAX_DOTENV_FILE_BYTES)
89
+ throw new LocalSecretSourceError("source_file_too_large");
90
+ // Read the file that was checked, not a path a rename could repoint afterwards.
91
+ return real;
92
+ }
93
+ /** Reads the value on this machine. Throws source_not_found naming the variable, never a value. */
94
+ export async function readLocalSecretValue(workspaceRoot, source, env = process.env) {
95
+ let value;
96
+ let variable;
97
+ if ("fromEnv" in source) {
98
+ variable = source.fromEnv;
99
+ value = env[source.fromEnv];
100
+ }
101
+ else {
102
+ variable = source.key;
103
+ const file = await insideWorkspace(workspaceRoot, source.fromFile);
104
+ const bytes = await readFile(file);
105
+ let text;
106
+ try {
107
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
108
+ }
109
+ catch {
110
+ throw new LocalSecretSourceError("source_not_utf8", variable);
111
+ }
112
+ value = parseDotenv(text).get(source.key);
113
+ }
114
+ if (value === undefined || value.trim() === "")
115
+ throw new LocalSecretSourceError("source_not_found", variable);
116
+ if (Buffer.byteLength(value, "utf8") > MAX_LOCAL_SECRET_BYTES)
117
+ throw new LocalSecretSourceError("source_value_too_large", variable);
118
+ return value;
119
+ }
@@ -34,7 +34,16 @@ export function externalBuildHelperTools(annotate) {
34
34
  tool("platform_materialize_assets", "Download exactly selected approved files into a new local directory. Verify each authenticated transfer's hash and size; source and attachment budgets remain separate.", {
35
35
  ...session, assetIds: { type: "array", minItems: 1, maxItems: 50, uniqueItems: true, items: id }, targetDir: { type: "string", minLength: 1 }
36
36
  }, ["sessionId", "assetIds", "targetDir"]),
37
- tool("platform_list_build_secrets", "Read only exact operator-approved binding references for this session. Values are never retrieved. Authoring detach does not prove deployed runtime revocation.", session, ["sessionId"], true),
37
+ tool("platform_request_build_secret", "Ask a person for a named key this app needs (an API key, webhook URL or token) without ever seeing it. Check platform_list_build_secrets first and never ask twice. Without source, Topline posts a request card in the session's build thread and returns pending with threadUrl and instructions: tell the person to open threadUrl, find the card titled with your label, and paste the value there or pick a saved key. Never ask them to paste it into your chat. Pass source only when the person says the key is already on this machine: {fromEnv: \"VAR\"} reads an environment variable, {fromFile: \".env\", key: \"VAR\"} reads a dotenv file inside the workspace. This helper reads the value here and uploads it to Topline itself; you get back only provided. Never search files for keys on your own.", {
38
+ ...session, idempotencyKey: requestKey,
39
+ name: { type: "string", pattern: "^[a-z][a-z0-9_]{0,30}$" }, label: { type: "string", minLength: 1, maxLength: 200 },
40
+ reason: { type: "string", minLength: 3, maxLength: 300 }, hint: { type: "string", maxLength: 300 },
41
+ source: { oneOf: [
42
+ { type: "object", additionalProperties: false, properties: { fromEnv: { type: "string", minLength: 1, maxLength: 128 } }, required: ["fromEnv"] },
43
+ { type: "object", additionalProperties: false, properties: { fromFile: { type: "string", minLength: 1 }, key: { type: "string", minLength: 1, maxLength: 128 } }, required: ["fromFile", "key"] }
44
+ ] }
45
+ }, ["sessionId", "idempotencyKey", "name", "label", "reason"]),
46
+ tool("platform_list_build_secrets", "Read this session's keys: approved references to bind exactly by name, secretArn and suggestedEnv, the build thread's requests (pending, provided, declined or expired) and a plain nextStep. Read live, so a key provided after the session started counts. Values are never retrieved. Removing a key does not prove deployed runtime revocation.", session, ["sessionId"], true),
38
47
  tool("platform_add_acceptance_check", "Add a required acceptance check bound to this build session and deployed revision. A semantic control query requires separate Build data-verification consent.", {
39
48
  ...mutation, description: { type: "string", minLength: 3, maxLength: 1000 }
40
49
  }, [...Object.keys(mutation), "description"]),
@@ -69,7 +78,7 @@ export const EXTERNAL_BUILD_FORWARD_TOOLS = new Set([
69
78
  */
70
79
  export const EXTERNAL_BUILD_SESSION_TOOLS = new Set([
71
80
  ...[...EXTERNAL_BUILD_FORWARD_TOOLS].filter((name) => name !== "platform_capability_status"),
72
- "platform_checkout_artifact_app", "platform_materialize_assets"
81
+ "platform_checkout_artifact_app", "platform_materialize_assets", "platform_request_build_secret"
73
82
  ]);
74
83
  /** Session tools that only call the hosted tool of the same name, so they can take its input schema. */
75
84
  export const EXTERNAL_BUILD_SESSION_FORWARD_TOOLS = new Set([...EXTERNAL_BUILD_SESSION_TOOLS].filter((name) => EXTERNAL_BUILD_FORWARD_TOOLS.has(name)));
package/dist/index.d.ts CHANGED
@@ -42,7 +42,7 @@ type ToolProgressReporter = (progress: number, message: string) => void | Promis
42
42
  export type McpSurface = "build" | "topline" | "harness";
43
43
  export declare const DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
44
44
  export declare const BUILD_MCP_SERVER_NAME = "topline-build-stdio";
45
- export declare const HARNESS_MCP_VERSION = "0.9.16";
45
+ export declare const HARNESS_MCP_VERSION = "0.9.18";
46
46
  export declare const DEFAULT_OAUTH_SCOPES: readonly string[];
47
47
  /** The Topline server's scopes: Build and Workspace. Consent shows what the seat allows. */
48
48
  export declare const TOPLINE_OAUTH_SCOPES: readonly string[];
@@ -88,6 +88,7 @@ export declare function callHarnessTool(opts: HarnessMcpStdioOptions, name: stri
88
88
  }): Promise<CallToolResult>;
89
89
  export declare function deployArtifactApp(opts: HarnessMcpStdioOptions, input: Record<string, unknown>, onProgress?: ToolProgressReporter): Promise<{
90
90
  operationId: string | null;
91
+ deployTaskId: string | null;
91
92
  bundle: {
92
93
  fileCount: number;
93
94
  byteCount: number;
@@ -95,7 +96,9 @@ export declare function deployArtifactApp(opts: HarnessMcpStdioOptions, input: R
95
96
  excluded: string[];
96
97
  };
97
98
  create: unknown;
98
- deploy: unknown;
99
+ deploy: {
100
+ [x: string]: unknown;
101
+ };
99
102
  sessionId?: string | undefined;
100
103
  ok: boolean;
101
104
  artifactId: string;
@@ -115,6 +118,33 @@ export declare function checkoutArtifactApp(opts: HarnessMcpStdioOptions, input:
115
118
  fileCount: number;
116
119
  byteCount: number;
117
120
  }>;
121
+ /**
122
+ * platform_request_build_secret with `source` (Topline design 2026-11-18 §2b). Reads the value on
123
+ * this machine first (a missing variable fails before Topline is called), asks Topline for the
124
+ * request and its upload path, then PUTs the value to /api/v1/secrets with this session's own
125
+ * token. The result, progress and errors carry names only.
126
+ */
127
+ export declare function requestBuildSecretFromSource(opts: HarnessMcpStdioOptions, input: Record<string, unknown>, env?: NodeJS.ProcessEnv): Promise<{
128
+ ok: boolean;
129
+ requestId: string | null;
130
+ status: string;
131
+ name: string;
132
+ alreadyProvided: boolean;
133
+ } | {
134
+ declineNote?: string | undefined;
135
+ ok: boolean;
136
+ requestId: string | null;
137
+ status: string;
138
+ name: string;
139
+ alreadyProvided?: undefined;
140
+ } | {
141
+ threadUrl?: string | undefined;
142
+ ok: boolean;
143
+ requestId: string;
144
+ status: string;
145
+ name: string;
146
+ alreadyProvided?: undefined;
147
+ }>;
118
148
  export declare function materializeBuildAssets(opts: HarnessMcpStdioOptions, input: Record<string, unknown>): Promise<{
119
149
  ok: boolean;
120
150
  sessionId: string;
@@ -143,6 +173,7 @@ export declare function inspectArtifactApp(opts: HarnessMcpStdioOptions, input:
143
173
  detail: string;
144
174
  }[];
145
175
  serverManifestValidationRequired: boolean;
176
+ serverChecks: string;
146
177
  appDir: string;
147
178
  platformAppDir: string;
148
179
  manifest: {
package/dist/index.js CHANGED
@@ -7,9 +7,10 @@ import { AsyncLocalStorage } from "node:async_hooks";
7
7
  import os from "node:os";
8
8
  import path from "node:path";
9
9
  import { gzipSync } from "node:zlib";
10
+ import { parseLocalSecretSource, readLocalSecretValue } from "./build-secret-source.js";
10
11
  import { externalBuildHelperTools, EXTERNAL_BUILD_FORWARD_TOOLS, EXTERNAL_BUILD_SESSION_FORWARD_TOOLS, EXTERNAL_BUILD_SESSION_TOOLS } from "./build-session-tools.js";
11
12
  import { domainHelperTools, DOMAIN_FORWARD_TOOLS, DOMAIN_ERROR_CODES } from "./domain-tools.js";
12
- import { ARTIFACT_STARTER_IDS, artifactStarterAppRoutes, artifactStarterRecipe, artifactStarterSource, findArtifactStarter } from "./artifact-starters.js";
13
+ import { ARTIFACT_STARTER_IDS, artifactStarterAppRoutes, artifactStarterRecipe, artifactStarterSource, artifactStarterTemplateSource, findArtifactStarter } from "./artifact-starters.js";
13
14
  import { boundedTransfer, extractArtifactSourceArchive, MAX_SOURCE_ARCHIVE_BYTES, safeSourcePath } from "./source-checkout.js";
14
15
  import { Server as McpServer } from "@modelcontextprotocol/sdk/server/index.js";
15
16
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -19,7 +20,7 @@ const MCP_SURFACES = ["build", "topline", "harness"];
19
20
  export const DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
20
21
  const DEFAULT_TIMEOUT_MS = 120_000;
21
22
  export const BUILD_MCP_SERVER_NAME = "topline-build-stdio";
22
- export const HARNESS_MCP_VERSION = "0.9.16";
23
+ export const HARNESS_MCP_VERSION = "0.9.18";
23
24
  export const DEFAULT_OAUTH_SCOPES = Object.freeze(["harness:artifact:read", "harness:artifact:write", "harness:artifact:deploy", "harness:artifact:delete"]);
24
25
  /** The Topline server's scopes: Build and Workspace. Consent shows what the seat allows. */
25
26
  export const TOPLINE_OAUTH_SCOPES = Object.freeze([
@@ -856,6 +857,11 @@ export async function callHarnessTool(opts, name, args, hooks) {
856
857
  case "platform_materialize_assets":
857
858
  result = toolResult(await materializeBuildAssets(opts, input));
858
859
  break;
860
+ case "platform_request_build_secret":
861
+ if (!servesBuild(opts))
862
+ throw new Error("external_session_requires_build_surface");
863
+ result = toolResult(input.source === undefined ? await callHostedBuildTool(opts, name, input) : await requestBuildSecretFromSource(opts, input));
864
+ break;
859
865
  case "platform_submit_design_system_draft":
860
866
  result = toolResult(await submitDesignSystemDraft(opts, input));
861
867
  break;
@@ -1014,8 +1020,13 @@ export async function deployArtifactApp(opts, input, onProgress) {
1014
1020
  });
1015
1021
  await onProgress?.(1, "Completed trusted draft deployment");
1016
1022
  const deployedRecord = asRecord(deployed);
1017
- const operationId = typeof deployedRecord.taskId === "string" ? deployedRecord.taskId
1018
- : typeof deployedRecord.operationId === "string" ? deployedRecord.operationId : null;
1023
+ // W3 (2026-11-16): one id. operationId is the deploy operation platform_wait_artifact_deploy and
1024
+ // platform_deploy_operation take (a session's operation, or the task for a sessionless deploy);
1025
+ // the worker task is only deployTaskId, and the nested deploy record no longer repeats either.
1026
+ const operationId = typeof deployedRecord.operationId === "string" ? deployedRecord.operationId
1027
+ : typeof deployedRecord.taskId === "string" ? deployedRecord.taskId : null;
1028
+ const deployTaskId = typeof deployedRecord.taskId === "string" ? deployedRecord.taskId : null;
1029
+ const { operationId: _operationId, taskId: _taskId, ...deployRecord } = deployedRecord;
1019
1030
  return {
1020
1031
  ok: true,
1021
1032
  artifactId,
@@ -1024,6 +1035,7 @@ export async function deployArtifactApp(opts, input, onProgress) {
1024
1035
  clientRequestId,
1025
1036
  ...(sessionId ? { sessionId } : {}),
1026
1037
  operationId,
1038
+ deployTaskId,
1027
1039
  bundle: {
1028
1040
  fileCount: bundle.fileCount,
1029
1041
  byteCount: bundle.byteCount,
@@ -1031,7 +1043,7 @@ export async function deployArtifactApp(opts, input, onProgress) {
1031
1043
  excluded: bundle.excluded
1032
1044
  },
1033
1045
  create: created,
1034
- deploy: deployed
1046
+ deploy: deployRecord
1035
1047
  };
1036
1048
  }
1037
1049
  async function fetchBuildTransfer(opts, advertisedPath, expectedPath, sha256, maxBytes, expectedSize, revision) {
@@ -1118,6 +1130,44 @@ export async function checkoutArtifactApp(opts, input) {
1118
1130
  await rm(staging, { recursive: true, force: true });
1119
1131
  }
1120
1132
  }
1133
+ /**
1134
+ * platform_request_build_secret with `source` (Topline design 2026-11-18 §2b). Reads the value on
1135
+ * this machine first (a missing variable fails before Topline is called), asks Topline for the
1136
+ * request and its upload path, then PUTs the value to /api/v1/secrets with this session's own
1137
+ * token. The result, progress and errors carry names only.
1138
+ */
1139
+ export async function requestBuildSecretFromSource(opts, input, env = process.env) {
1140
+ const { source: rawSource, ...hostedInput } = input;
1141
+ const source = parseLocalSecretSource(rawSource);
1142
+ const sessionId = stringArg(input, "sessionId");
1143
+ let value = await readLocalSecretValue(opts.workspaceRoot, source, env);
1144
+ try {
1145
+ const hosted = asRecord(await callHostedBuildTool(opts, "platform_request_build_secret", { ...hostedInput, localUpload: true }));
1146
+ const name = stringValue(hosted.name, "name");
1147
+ if (hosted.status === "provided")
1148
+ return { ok: true, requestId: typeof hosted.requestId === "string" ? hosted.requestId : null, status: "provided", name, alreadyProvided: true };
1149
+ // A retried key that was declined or expired: report it, upload nothing.
1150
+ if (hosted.status === "declined" || hosted.status === "expired") {
1151
+ return { ok: true, requestId: typeof hosted.requestId === "string" ? hosted.requestId : null, status: hosted.status, name,
1152
+ ...(typeof hosted.declineNote === "string" ? { declineNote: hosted.declineNote } : {}) };
1153
+ }
1154
+ const requestId = stringValue(hosted.requestId, "requestId");
1155
+ const upload = asRecord(hosted.upload);
1156
+ const uploadPath = stringValue(upload.path, "upload.path");
1157
+ if (!/^\/api\/v1\/secrets\/[a-z][a-z0-9_]{0,62}$/.test(uploadPath) || !/^[0-9a-f-]{36}$/i.test(requestId))
1158
+ throw new Error("build_secret_upload_invalid");
1159
+ const headers = await jsonHeaders(opts);
1160
+ await fetchJson(opts, `${platformBaseUrl(opts)}${uploadPath}`, {
1161
+ method: "PUT",
1162
+ headers: { ...headers, "x-topline-build-session": sessionId, "x-topline-build-secret-request": requestId },
1163
+ body: JSON.stringify({ value })
1164
+ });
1165
+ return { ok: true, requestId, status: "provided", name, ...(typeof hosted.threadUrl === "string" ? { threadUrl: hosted.threadUrl } : {}) };
1166
+ }
1167
+ finally {
1168
+ value = null;
1169
+ }
1170
+ }
1121
1171
  export async function materializeBuildAssets(opts, input) {
1122
1172
  const target = await newBuildInputTarget(opts, input);
1123
1173
  const sessionId = stringArg(input, "sessionId");
@@ -1166,13 +1216,20 @@ export async function inspectArtifactApp(opts, input) {
1166
1216
  const bundle = await packArtifactAppDirectory(absoluteAppDir, platformAppDir === "." ? "" : platformAppDir);
1167
1217
  const problems = await localPreflightProblems(absoluteAppDir, manifest);
1168
1218
  problems.push(...await javascriptSyntaxProblems(absoluteAppDir));
1219
+ const server = await serverPreflightProblems(opts, bundle.body, platformAppDir);
1220
+ // A rule both sides check (a data binding with no dataset) is listed once, in inspect's words.
1221
+ const reported = new Set(problems.map((problem) => `${problem.code}\0${problem.path}`));
1222
+ for (const problem of server.problems)
1223
+ if (!reported.has(`${problem.code}\0${problem.path}`))
1224
+ problems.push(problem);
1169
1225
  const warnings = await renderedTextRuleWarnings(absoluteAppDir);
1170
1226
  return {
1171
1227
  ok: true,
1172
1228
  packageReady: problems.length === 0,
1173
1229
  problems,
1174
1230
  warnings,
1175
- serverManifestValidationRequired: true,
1231
+ serverManifestValidationRequired: !server.checks.startsWith("passed") && !server.checks.startsWith("failed"),
1232
+ serverChecks: server.checks,
1176
1233
  appDir: workspaceAppDir,
1177
1234
  platformAppDir,
1178
1235
  manifest: {
@@ -1199,6 +1256,43 @@ export async function inspectArtifactApp(opts, input) {
1199
1256
  : "Call platform_deploy_artifact_app with the same appDir and expectedBundleSha256 set to bundle.sha256 when this local package is ready to deploy."
1200
1257
  };
1201
1258
  }
1259
+ /**
1260
+ * W3 (MCP friction 2026-11-16): inspect said packageReady, then the build failed LOCAL_VALIDATION
1261
+ * (undeclared_package_import for react, esbuild, @aws-sdk/*) or the server refused the manifest
1262
+ * (tables[].operations: []). Rather than copy those rules here, send the same bundle to Topline's
1263
+ * preflight, which runs the build's own validation function and the server's manifest validator.
1264
+ * Never opens a browser sign-in: without a saved sign-in this is skipped and says so.
1265
+ */
1266
+ async function serverPreflightProblems(opts, body, platformAppDir) {
1267
+ if (!servesBuild(opts))
1268
+ return { checks: "skipped:no_build_surface", problems: [] };
1269
+ const bearer = await getBearerTokenWithoutSignIn(opts).catch(() => null);
1270
+ if (!bearer)
1271
+ return { checks: "skipped:not_signed_in", problems: [] };
1272
+ try {
1273
+ const payload = asRecord(await fetchJson(opts, `${artifactAppsPath(opts)}/preflight-bundle`, {
1274
+ method: "POST",
1275
+ headers: {
1276
+ authorization: `Bearer ${bearer}`,
1277
+ "content-type": "application/gzip",
1278
+ "MCP-Protocol-Version": opts.protocolVersion,
1279
+ "x-platform-app-dir": platformAppDir
1280
+ },
1281
+ body: body
1282
+ }));
1283
+ const problems = (Array.isArray(payload.problems) ? payload.problems : []).filter(isRecord).map((problem) => ({
1284
+ code: typeof problem.code === "string" ? problem.code : "server_preflight_problem",
1285
+ path: typeof problem.path === "string" ? problem.path : "",
1286
+ detail: typeof problem.detail === "string" ? problem.detail : String(problem.code ?? "")
1287
+ }));
1288
+ return { checks: problems.length ? "failed" : "passed", problems };
1289
+ }
1290
+ catch (error) {
1291
+ const message = error instanceof Error ? error.message : String(error);
1292
+ // An older Topline has no preflight route (404); anything else is reported, not fatal.
1293
+ return { checks: /^platform_harness_http_error:404:/.test(message) ? "skipped:server_without_preflight" : "skipped:request_failed", problems: [] };
1294
+ }
1295
+ }
1202
1296
  const PREFLIGHT_SCAN_EXTENSIONS = new Set([".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".html", ".json", ".py", ".txt"]);
1203
1297
  const PREFLIGHT_SKIP_DIRS = new Set(["node_modules", ".git", ".next", ".vite", ".turbo", ".cache"]);
1204
1298
  /**
@@ -1563,11 +1657,12 @@ export async function initArtifactApp(opts, input) {
1563
1657
  ],
1564
1658
  sourceBindings: [],
1565
1659
  env: ["ARTIFACT_ID", "ARTIFACT_VERSION_ID", "ARTIFACT_MANIFEST_URI", "PLATFORM_ARTIFACT_ID", "PLATFORM_ARTIFACT_VERSION_ID", "PLATFORM_ARTIFACT_MANIFEST_URI"],
1566
- viewerPolicy: "private"
1660
+ viewerPolicy: "private",
1661
+ ...(starter?.manifest ?? {})
1567
1662
  };
1568
1663
  const packageJson = { name: manifestId, private: true, type: "module", main: "src/index.js", scripts: { build: "node src/index.js --build", test: "node src/index.js --test" } };
1569
1664
  const safeTitle = title.replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[char]));
1570
- const source = starter ? artifactStarterSource(starter, title) : `import { mkdirSync, writeFileSync } from "node:fs";\nimport path from "node:path";\n\nconst page = ${JSON.stringify(`<!doctype html><html><body><main data-platform-artifact-root><h1>${safeTitle}</h1><p>Ready.</p></main></body></html>`)};\n\nexport function artifactApp(_req, res) {\n res.setHeader("content-type", "text/html; charset=utf-8");\n res.end(page);\n}\n\nif (process.argv.includes("--build")) {\n mkdirSync("dist", { recursive: true });\n writeFileSync(path.join("dist", "index.html"), page, "utf8");\n}\n\nif (process.argv.includes("--test") && process.argv.includes("--artifact-tests-json")) {\n console.log(JSON.stringify({ tests: [{ description: "Scaffold check: the artifact renders a visible app root.", required: true, status: "passed", summary: "Generated starter check; not proof of implemented behavior.", evidence: { selector: "data-platform-artifact-root", scaffold: true } }] }));\n} else if (process.argv.includes("--build") || process.argv.includes("--test")) {\n console.log("artifact app template ok");\n}\n`;
1665
+ const source = starter?.template ? await artifactStarterTemplateSource(starter, title) : starter ? artifactStarterSource(starter, title) : `import { mkdirSync, writeFileSync } from "node:fs";\nimport path from "node:path";\n\nconst page = ${JSON.stringify(`<!doctype html><html><body><main data-platform-artifact-root><h1>${safeTitle}</h1><p>Ready.</p></main></body></html>`)};\n\nexport function artifactApp(_req, res) {\n res.setHeader("content-type", "text/html; charset=utf-8");\n res.end(page);\n}\n\nif (process.argv.includes("--build")) {\n mkdirSync("dist", { recursive: true });\n writeFileSync(path.join("dist", "index.html"), page, "utf8");\n}\n\nif (process.argv.includes("--test") && process.argv.includes("--artifact-tests-json")) {\n console.log(JSON.stringify({ tests: [{ description: "Scaffold check: the artifact renders a visible app root.", required: true, status: "passed", summary: "Generated starter check; not proof of implemented behavior.", evidence: { selector: "data-platform-artifact-root", scaffold: true } }] }));\n} else if (process.argv.includes("--build") || process.argv.includes("--test")) {\n console.log("artifact app template ok");\n}\n`;
1571
1666
  await Promise.all([
1572
1667
  writeFile(path.join(absoluteAppDir, "artifact-app.json"), `${JSON.stringify(manifest, null, 2)}\n`, { flag: "wx" }),
1573
1668
  writeFile(path.join(absoluteAppDir, "package.json"), `${JSON.stringify(packageJson, null, 2)}\n`, { flag: "wx" }),
@@ -2114,7 +2209,8 @@ const BUILD_MCP_TOOLS = [
2114
2209
  artifactId: { type: "string" },
2115
2210
  artifactVersionId: { type: "string" },
2116
2211
  clientRequestId: { type: "string" },
2117
- operationId: { type: ["string", "null"] },
2212
+ operationId: { type: ["string", "null"], description: "The one deploy id: pass it to platform_wait_artifact_deploy and platform_deploy_operation." },
2213
+ deployTaskId: { type: ["string", "null"], description: "The worker task that ran the deploy, for logs only. Not an operation id." },
2118
2214
  bundle: { type: "object" },
2119
2215
  create: { type: "object" },
2120
2216
  deploy: { type: "object" }
@@ -2124,7 +2220,7 @@ const BUILD_MCP_TOOLS = [
2124
2220
  },
2125
2221
  {
2126
2222
  name: "platform_inspect_artifact_app",
2127
- description: "Inspect local artifact paths and package boundaries without authenticating, uploading, or creating a remote draft. Also runs the manifest and data-binding checks Topline's build would fail (datasets[].name and route, routes[].path, ./_artifact/data/<name> references with no matching dataset) and a node --check of each .js/.mjs/.cjs file (javascript_syntax_error with file and line); packageReady is false and problems lists each one until they are fixed. warnings lists static text the build's page-text rules would refuse if the page shows it.",
2223
+ description: "Inspect local artifact paths and package boundaries without creating a remote draft, building or spending anything. Runs the manifest and data-binding checks Topline's build would fail (datasets[].name and route, routes[].path, ./_artifact/data/<name> references with no matching dataset) and a node --check of each .js/.mjs/.cjs file (javascript_syntax_error with file and line). When this computer is signed in to Topline, it also sends the bundle to Topline's preflight, which runs the build's own local validation (undeclared_package_import and the rest) and the manifest rules the server applies on save; serverChecks says whether that ran. packageReady is false and problems lists each one until they are fixed. warnings lists static text the build's page-text rules would refuse if the page shows it.",
2128
2224
  annotations: mcpToolAnnotations("platform_inspect_artifact_app", { readOnly: true }),
2129
2225
  inputSchema: {
2130
2226
  type: "object",
@@ -2139,7 +2235,8 @@ const BUILD_MCP_TOOLS = [
2139
2235
  packageReady: { type: "boolean" },
2140
2236
  problems: { type: "array", items: { type: "object" }, description: "Checks Topline's build would fail: each has code, path (manifest field or file, with :line for javascript_syntax_error) and detail. packageReady is false while any remain." },
2141
2237
  warnings: { type: "array", items: { type: "object" }, description: "Static text that matches a rule Topline's render smoke applies to the page (rendered_text_rule:sample_or_mock_data_text), with the file and phrase. The build fails only if the rendered page shows it." },
2142
- serverManifestValidationRequired: { type: "boolean" },
2238
+ serverManifestValidationRequired: { type: "boolean", description: "True when Topline's preflight did not run (see serverChecks), so the server's manifest rules and the build's local validation are still unchecked." },
2239
+ serverChecks: { type: "string", description: "passed, failed (its problems are in problems), or skipped:<reason> (not signed in, an older Topline without the preflight, or the request failed)." },
2143
2240
  appDir: { type: "string" },
2144
2241
  platformAppDir: { type: "string" },
2145
2242
  manifest: { type: "object" },