@topline-build/harness-mcp 0.9.0 → 0.9.2

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,11 +2,26 @@
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.0 - source candidate
5
+ ## 0.9.2 - source candidate
6
+
7
+ - The Topline server (`--surface topline`) opens the browser sign-in as soon as it starts signed out, then asks the assistant to list tools again after you choose Allow, so a first chat no longer needs `login` beforehand. A tool call that needs a token while that browser approval is open waits for it instead of opening a second one. `login` still works for signing in ahead of time.
8
+ - Tool errors from Topline now carry Topline's own code (for example `artifact_external_session_active`, `external_private_tables_disabled` or `scope_required`) instead of the generic `platform_mcp_tool_error`, with recovery steps for that code. The full message is unchanged. `platform_mcp_tool_error` remains only when Topline gives no code, and its recovery text no longer suggests changing scopes.
9
+ - `build_session_id_required` names the session-only fields a session-less deploy passed (for example `build_session_id_required:idempotencyKey`), and says to remove them or start a session.
10
+ - `platform_run_artifact_smoke` takes an optional `sessionId`, so the holder of an open build session can rerun smoke without closing it (needs a Topline release with the matching change).
11
+
12
+ ## 0.9.1 - 2026-10-23
13
+
14
+ - `--surface topline` no longer asks for `workspace:todo:write`. Topline retired that scope and leaves it out of every grant, so the package treated each fresh sign-in as incomplete and opened the browser again on the next launch (and twice during `topline-mcp login`). A retired scope named in `TOPLINE_MCP_SCOPES` or `--scopes` is dropped too. Existing sign-ins are reused without another approval.
15
+ - The default `build` surface lists and forwards hosted Build tools the way `--surface topline` does, so new hosted Build tools reach Codex, Claude Code and Cursor without a package release. Local tools (init, inspect, deploy, checkout, materialize and the rest of the package's own list) stay local and win over a hosted tool of the same name. Hosted `platform_create_artifact_app` and `platform_bedrock_local_token_command` stay off. A manual token on `build` keeps the package's own list.
16
+ - Build session tools (start, read and close a session, workspace SQL, checkout, materialize, assets, secrets, acceptance and validation) follow the hosted list, on `build` and on `--surface topline`: they are listed only while the connection's hosted tool list offers them. Today that list follows the granted scopes and the `harness.workforce` capability. OAuth users without the asset, secret, workspace SQL or validation scopes therefore no longer see those tools listed; Topline refused them anyway, and they come back after reconnecting with those scopes. Signed out, or before the first good listing, every session tool stays listed. A call to a hidden one returns `build_session_tool_unavailable` without reaching Topline and asks the host to list tools again; after a reconnect with a changed grant the call goes through to Topline. `platform_capability_status` is always listed.
17
+ - A failed hosted tool listing (network, 5xx, timeout or any error other than a rejected sign-in) keeps the last good list for the life of the process while the same sign-in holds, and lists the package's own tools before any good listing. The next tool call asks the host to list again, so one error never hides tools for the rest of the chat. A rejected sign-in (revoked or invalid refresh token, or a 401 from the hosted list) counts as signed out and clears the last good list, as does signing out. This applies to `--surface topline` too.
18
+ - Session tools that only forward to Topline take the hosted input schema when the hosted list provides one.
19
+
20
+ ## 0.9.0 - 2026-10-14
6
21
 
7
22
  - `platform_init_artifact_app` takes `shape: "web-and-api"` to scaffold one artifact with a static website part and an API part under one address, instead of two artifacts. `platform_inspect_artifact_app` lists an app's parts.
8
23
 
9
- ## 0.8.0 - source candidate
24
+ ## 0.8.0 - 2026-10-13
10
25
 
11
26
  - Add `--surface topline`: one Topline server per account. It runs the local Build tools and lists and forwards every hosted tool the person's grant allows (Workspace tools included), so assistants see one Topline entry.
12
27
  - Add `topline-mcp login --url <account>`: opens the browser once during setup, saves the refresh token to the auth file the server reads, then records a code-free connection check so Topline Developer Access shows the computer as connected.
@@ -17,20 +32,20 @@ All notable customer-visible Build MCP changes are recorded here. A source chang
17
32
  - Every request to the Topline account carries `x-topline-mcp-version`. Topline uses it to show "Update available" in Developer Access and, when this package is older than the account needs, to answer tool calls with `topline_mcp_update_required` and how to update (copy setup again).
18
33
  - The combined server does not list or forward hosted `platform_create_artifact_app` or `platform_bedrock_local_token_command`; the local package, upload and deploy flow stays the only Build write path.
19
34
 
20
- ## 0.7.0 - source candidate
35
+ ## 0.7.0 - 2026-10-12
21
36
 
22
37
  - Add exactly six gated company-domain tools: connected-domain/status/recovery reads, owned-app address reads, single-use plan/apply, manager registration and ownership verification.
23
38
  - Require explicit new scopes and account-bound Build OAuth; preserve manual-token behavior for legacy tools.
24
39
  - Retain original keys and typed recovery context after a lost response. Domain reads never retry setup, apply an address, publish an app or write provider DNS.
25
40
  - Discover enabled server capabilities and current hosted scoped contracts without initiating OAuth during discovery.
26
41
 
27
- ## 0.6.0 - pending publication
42
+ ## 0.6.0 - 2026-10-12
28
43
 
29
44
  - Add server-owned external build sessions, guarded artifact-private SQL, and full acceptance/reviewer forwarding.
30
45
  - Check out exact artifact source and materialize selected assets through authenticated same-account transfers with hash, revision, archive and local-path checks.
31
46
  - Bind local draft create/deploy to the existing session identity, checked-out version, inspected source hash and stable operation keys. Additional asset, secret-metadata and data-verification scopes require explicit consent.
32
47
 
33
- ## 0.5.3 - pending publication
48
+ ## 0.5.3 - 2026-09-28
34
49
 
35
50
  - Add tenant-scoped Storyboard state, guarded edit, and exact-draft publication tools to Build MCP.
36
51
  - Check out the published Storyboard source for local Storybook iteration and submit source-only edits as a private, server-validated draft.
package/README.md CHANGED
@@ -14,13 +14,13 @@ The first authenticated tool call normally opens Topline in a browser for OAuth
14
14
 
15
15
  ### One Topline server (0.8.0)
16
16
 
17
- Topline Developer Access now sets up one Topline connection per account. Its plugin runs this package with `--surface topline`: the local Build tools plus every hosted tool your seat and grant allow, including Workspace tools, under one server entry. Sign in once during setup:
17
+ Topline Developer Access now sets up one Topline connection per account. Its plugin runs this package with `--surface topline`: the local Build tools plus every hosted tool your seat and grant allow, including Workspace tools, under one server entry. The default `build` surface does the same for hosted Build tools (0.9.1); local tools stay local. A manual `--token` on `build` keeps the package's own list. On both surfaces, build session tools follow the hosted list: they are listed only while the connection's hosted tool list offers them, and stay listed while signed out. If listing hosted tools fails temporarily, the server keeps the last good list for the same sign-in, or the package's own tools before the first one. Sign in once during setup:
18
18
 
19
19
  ```bash
20
20
  npx -y @topline-build/harness-mcp login --url https://YOUR-TOPLINE-HOST
21
21
  ```
22
22
 
23
- Run it on the computer where your browser opens. `login` opens the browser, waits up to 5 minutes for you to choose Allow, saves the refresh token where the server reads it, and records a connection check so Developer Access shows the computer as connected without a verification code. Start a new assistant chat afterwards so it loads the tools; the server refreshes the sign-in on its own after that. The plugin runs one exact package version. To update, copy the setup from Developer Access again (it shows "Update available" when a newer version is ready) and paste it into your assistant.
23
+ Run it on the computer where your browser opens. `login` opens the browser, waits up to 5 minutes for you to choose Allow, saves the refresh token where the server reads it, and records a connection check so Developer Access shows the computer as connected without a verification code. Start a new assistant chat afterwards so it loads the tools; the server refreshes the sign-in on its own after that. `login` is optional: when the Topline server starts signed out it opens the same browser sign-in itself and reloads its tools after you choose Allow. The plugin runs one exact package version. To update, copy the setup from Developer Access again (it shows "Update available" when a newer version is ready) and paste it into your assistant.
24
24
 
25
25
  Set `TOPLINE_WORKSPACE_ROOT` when the MCP host starts outside the repository containing the artifact app:
26
26
 
@@ -36,13 +36,13 @@ If a tool returns `authorization_required`, clear only that connection's OAuth c
36
36
 
37
37
  Storyboard authoring uses separate `storyboard:read` and `storyboard:write` OAuth scopes. Request them explicitly with `--scopes` (or `TOPLINE_MCP_SCOPES`) and reconnect so Topline can approve the expanded grant; they are not part of the default artifact scopes. `platform_get_design_system_state` shows the published commit and current draft. `platform_checkout_design_system` creates a local checkout of that published source; run `npm ci` and `npm run storybook` there to iterate, then call `platform_submit_design_system_draft` with the exact published commit and draft ID from the state read. Wait for a successful server build, inspect the private preview, and call `platform_publish_design_system` with the reviewed run and commit values. Alternatively, `platform_edit_design_system` asks Topline's guarded coding agent to edit a draft in an existing writable Storyboard conversation. A timed-out write should be recovered by reading state before another submission. The separate Storybook reference MCP endpoint does not accept source writes.
38
38
 
39
- The 0.7.0 source candidate adds six company-domain tools for a compatible, explicitly enabled server. Request `harness:domains:read` and `harness:artifact:read` for discovery and owned-app address reads; add `harness:artifact:addresses:write` for plan/apply. Setup and full DNS/TLS details also require `harness:domains:manage` and the existing organization-manager capability. These scopes are never implicit defaults. All six require account-bound Build OAuth; unbound manual tokens cannot use them. Runtime discovery follows server gates and, once signed in, current hosted scopes and roles. The helper sends a tool-list change notification after first sign-in so clients can discover authorized setup and recovery selectors.
39
+ Since 0.7.0 the package includes six company-domain tools for a compatible, explicitly enabled server. Request `harness:domains:read` and `harness:artifact:read` for discovery and owned-app address reads; add `harness:artifact:addresses:write` for plan/apply. Setup and full DNS/TLS details also require `harness:domains:manage` and the existing organization-manager capability. These scopes are never implicit defaults. All six require account-bound Build OAuth; unbound manual tokens cannot use them. Runtime discovery follows server gates and, once signed in, current hosted scopes and roles. The helper sends a tool-list change notification after first sign-in so clients can discover authorized setup and recovery selectors.
40
40
 
41
41
  Read connected domains and the current address, show the exact `platform_plan_artifact_address` preview, then apply that single-use plan. Save every mutation key before calling. Recover a lost apply response through `platform_get_artifact_address` with the saved artifact ID and key. Recover a lost registration/verification response through `platform_read_artifact_domains` with its kind and key, even if the response containing the new domain ID was lost. Reads never replay writes. Pending, absent or expired receipts do not authorize a new key. A definite terminal DNS no-admission result permits a fresh verification key only within covered setup/retry intent, after a fresh generation read and the ten-second interval. Read-only polling stops after five minutes and reports the saved recovery context; it never verifies automatically. Saving an address does not publish the app, change access, or write DNS. Exact DNS records must be saved by the customer or a separately authorized DNS connection.
42
42
 
43
43
  ## Typical workflow
44
44
 
45
- The 0.6.0 source adds session authoring; npm publication and a compatible customer API rollout are separate prerequisites. Start `platform_start_build_session` with an existing artifact's exact version or a new app manifest, a stable idempotency key and a Topline operation budget. External client model charges stay separate. For existing apps, `platform_checkout_artifact_app` writes exact saved source into a new local directory and returns its version, commit and source hash. Never reconstruct missing source from its manifest.
45
+ Session authoring (published in 0.6.0) needs a compatible customer API. Start `platform_start_build_session` with an existing artifact's exact version or a new app manifest, a stable idempotency key and a Topline operation budget. External client model charges stay separate. For existing apps, `platform_checkout_artifact_app` writes exact saved source into a new local directory and returns its version, commit and source hash. Never reconstruct missing source from its manifest.
46
46
 
47
47
  Keep Build and Workspace as separate same-account connections. Workspace supplies catalog, SQL and trusted calculations through `data:read`. Reusable assets, approved secret metadata, private table writes, validation and finite artifact data verification each require their separately consented Build scopes: `harness:assets:read`, `harness:secrets:metadata:read`, `harness:artifact:tables:write`, `harness:artifact:validate`, and `harness:artifact:data:verify`. The defaults remain the existing artifact scopes; request an expanded set explicitly and reconnect. Secret discovery returns approved references only, never values.
48
48
 
@@ -6,4 +6,12 @@ type Annotate = (name: string, policy: {
6
6
  }) => ToolAnnotations;
7
7
  export declare function externalBuildHelperTools(annotate: Annotate): ListToolsResult["tools"];
8
8
  export declare const EXTERNAL_BUILD_FORWARD_TOOLS: Set<string>;
9
+ /**
10
+ * Session tools listed only while the hosted Build list offers them. Each
11
+ * calls the hosted tool of the same name; checkout and materialize then do
12
+ * their local transfer. Capability status stays listed so it can say why.
13
+ */
14
+ export declare const EXTERNAL_BUILD_SESSION_TOOLS: ReadonlySet<string>;
15
+ /** Session tools that only call the hosted tool of the same name, so they can take its input schema. */
16
+ export declare const EXTERNAL_BUILD_SESSION_FORWARD_TOOLS: ReadonlySet<string>;
9
17
  export {};
@@ -61,3 +61,14 @@ export const EXTERNAL_BUILD_FORWARD_TOOLS = new Set([
61
61
  "platform_list_asset_folders", "platform_list_assets", "platform_list_build_secrets", "platform_add_acceptance_check", "platform_run_acceptance_checks",
62
62
  "platform_record_acceptance_review", "platform_prepare_artifact_validation", "platform_request_artifact_validation", "platform_artifact_validation_status", "platform_answer_operator_prompt"
63
63
  ]);
64
+ /**
65
+ * Session tools listed only while the hosted Build list offers them. Each
66
+ * calls the hosted tool of the same name; checkout and materialize then do
67
+ * their local transfer. Capability status stays listed so it can say why.
68
+ */
69
+ export const EXTERNAL_BUILD_SESSION_TOOLS = new Set([
70
+ ...[...EXTERNAL_BUILD_FORWARD_TOOLS].filter((name) => name !== "platform_capability_status"),
71
+ "platform_checkout_artifact_app", "platform_materialize_assets"
72
+ ]);
73
+ /** Session tools that only call the hosted tool of the same name, so they can take its input schema. */
74
+ 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
@@ -3,9 +3,10 @@ import { type CallToolResult, type ListToolsResult } from "@modelcontextprotocol
3
3
  export interface HarnessMcpStdioOptions {
4
4
  apiUrl: string;
5
5
  /**
6
- * Defaults to the Build MCP. `topline` is the one server per account: local
7
- * Build tools plus every hosted tool the person's grant allows. Use harness
8
- * only for legacy deployments.
6
+ * Defaults to the Build MCP: local Build tools plus the hosted Build tools
7
+ * the person's OAuth grant allows. `topline` is the one server per account:
8
+ * local Build tools plus every hosted tool the person's grant allows. Use
9
+ * harness only for legacy deployments.
9
10
  */
10
11
  surface?: McpSurface;
11
12
  token?: string;
@@ -39,7 +40,7 @@ type ToolProgressReporter = (progress: number, message: string) => void | Promis
39
40
  export type McpSurface = "build" | "topline" | "harness";
40
41
  export declare const DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
41
42
  export declare const BUILD_MCP_SERVER_NAME = "topline-build-stdio";
42
- export declare const HARNESS_MCP_VERSION = "0.9.0";
43
+ export declare const HARNESS_MCP_VERSION = "0.9.2";
43
44
  export declare const DEFAULT_OAUTH_SCOPES: readonly string[];
44
45
  /** The Topline server's scopes: Build and Workspace. Consent shows what the seat allows. */
45
46
  export declare const TOPLINE_OAUTH_SCOPES: readonly string[];
@@ -57,6 +58,14 @@ export declare function parseHarnessOptions(argv: string[], env?: Record<string,
57
58
  surface?: McpSurface;
58
59
  }): HarnessMcpStdioOptions;
59
60
  export declare function runHarnessMcpStdioCli(): Promise<void>;
61
+ /**
62
+ * The one Topline server lists most of its tools only once signed in, so a
63
+ * first chat that starts signed out would see almost nothing. Start the browser
64
+ * sign-in as soon as the server is up instead, and tell the host to list tools
65
+ * again after Allow. Returns whether it signed in. Never throws: a sign-in that
66
+ * is ignored or refused leaves the on-demand sign-in of the first tool call.
67
+ */
68
+ export declare function signInAtStartup(opts: HarnessMcpStdioOptions, onSignedIn: () => Promise<void>, log?: (message: string) => void): Promise<boolean>;
60
69
  /**
61
70
  * `topline-mcp login`: sign in once during setup so the assistant's next chat
62
71
  * starts already connected. Opens the browser, saves the refresh token to the
@@ -72,6 +81,7 @@ export declare function cliInfo(argv: string[]): string | null;
72
81
  export declare function createHarnessMcpStdioServer(opts: HarnessMcpStdioOptions, toolAllowlist?: readonly string[]): McpServer;
73
82
  export declare function callHarnessTool(opts: HarnessMcpStdioOptions, name: string, args: unknown, hooks?: {
74
83
  onProgress?: ToolProgressReporter;
84
+ inputSchema?: ListToolsResult["tools"][number]["inputSchema"];
75
85
  }): Promise<CallToolResult>;
76
86
  export declare function deployArtifactApp(opts: HarnessMcpStdioOptions, input: Record<string, unknown>, onProgress?: ToolProgressReporter): Promise<{
77
87
  operationId: string | null;
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import { createServer } from "node:http";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
8
  import { gzipSync } from "node:zlib";
9
- import { externalBuildHelperTools, EXTERNAL_BUILD_FORWARD_TOOLS } from "./build-session-tools.js";
9
+ import { externalBuildHelperTools, EXTERNAL_BUILD_FORWARD_TOOLS, EXTERNAL_BUILD_SESSION_FORWARD_TOOLS, EXTERNAL_BUILD_SESSION_TOOLS } from "./build-session-tools.js";
10
10
  import { domainHelperTools, DOMAIN_FORWARD_TOOLS, DOMAIN_ERROR_CODES } from "./domain-tools.js";
11
11
  import { boundedTransfer, extractArtifactSourceArchive, MAX_SOURCE_ARCHIVE_BYTES, safeSourcePath } from "./source-checkout.js";
12
12
  import { Server as McpServer } from "@modelcontextprotocol/sdk/server/index.js";
@@ -17,7 +17,7 @@ const MCP_SURFACES = ["build", "topline", "harness"];
17
17
  export const DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
18
18
  const DEFAULT_TIMEOUT_MS = 120_000;
19
19
  export const BUILD_MCP_SERVER_NAME = "topline-build-stdio";
20
- export const HARNESS_MCP_VERSION = "0.9.0";
20
+ export const HARNESS_MCP_VERSION = "0.9.2";
21
21
  export const DEFAULT_OAUTH_SCOPES = Object.freeze(["harness:artifact:read", "harness:artifact:write", "harness:artifact:deploy", "harness:artifact:delete"]);
22
22
  /** The Topline server's scopes: Build and Workspace. Consent shows what the seat allows. */
23
23
  export const TOPLINE_OAUTH_SCOPES = Object.freeze([
@@ -26,11 +26,16 @@ export const TOPLINE_OAUTH_SCOPES = Object.freeze([
26
26
  "harness:secrets:metadata:read", "harness:domains:read", "harness:domains:manage", "harness:artifact:addresses:write",
27
27
  "storyboard:read", "storyboard:write",
28
28
  "docs:read", "chat:read", "chat:write", "workspace:write", "workspace:delete", "workspace:content:read",
29
- "workspace:content:write", "workspace:content:delete", "workspace:todo:write", "workspace:skills:read",
29
+ "workspace:content:write", "workspace:content:delete", "workspace:skills:read",
30
30
  "workspace:skills:write", "workspace:access:manage", "schedules:read", "schedules:write", "schedules:delete",
31
31
  "workforce:read", "workforce:write", "memory:read", "preferences:write", "glossary:read", "glossary:write",
32
32
  "company_knowledge:propose", "company_knowledge:write", "customer_profiles:read", "data:read"
33
33
  ]);
34
+ /**
35
+ * Scopes Topline no longer grants. It drops them from every grant, so asking for one
36
+ * makes a fresh grant look incomplete and reopens the browser on every launch.
37
+ */
38
+ const RETIRED_OAUTH_SCOPES = new Set(["workspace:todo:write"]);
34
39
  export const BUILD_MCP_SETUP_OPTIONS = Object.freeze([
35
40
  { flag: "--url", env: "TOPLINE_API_URL", aliases: ["PLATFORM_API_URL", "OVERSITE_API_URL"], required: true, description: "Topline tenant base URL. HTTPS is required except for loopback development." },
36
41
  { flag: "--workspace-root", env: "TOPLINE_WORKSPACE_ROOT", aliases: ["PLATFORM_WORKSPACE_ROOT"], default: "current working directory", description: "Local root that contains artifact app directories." },
@@ -81,7 +86,7 @@ export function parseHarnessOptions(argv, env = process.env, defaults = {}) {
81
86
  const scopes = (getArg("--scopes") || firstEnv(env, "TOPLINE_MCP_SCOPES", "PLATFORM_MCP_SCOPES") || defaultScopes.join(" "))
82
87
  .split(/[\s,]+/)
83
88
  .map((scope) => scope.trim())
84
- .filter(Boolean);
89
+ .filter((scope) => scope && !RETIRED_OAUTH_SCOPES.has(scope));
85
90
  return {
86
91
  apiUrl: normalizedApiUrl,
87
92
  surface: surfaceRaw,
@@ -111,7 +116,94 @@ export async function runHarnessMcpStdioCli() {
111
116
  }
112
117
  const opts = parseHarnessOptions(argv);
113
118
  const mcp = createHarnessMcpStdioServer(opts);
119
+ // A browser sign-in holds a callback server and a 5-minute timer; once the
120
+ // host closes the connection nothing will use it, so do not linger.
121
+ mcp.onclose = () => { if (inFlightSignIns.size > 0)
122
+ process.exit(0); };
114
123
  await mcp.connect(new StdioServerTransport());
124
+ void signInAtStartup(opts, () => mcp.sendToolListChanged());
125
+ }
126
+ /**
127
+ * The one Topline server lists most of its tools only once signed in, so a
128
+ * first chat that starts signed out would see almost nothing. Start the browser
129
+ * sign-in as soon as the server is up instead, and tell the host to list tools
130
+ * again after Allow. Returns whether it signed in. Never throws: a sign-in that
131
+ * is ignored or refused leaves the on-demand sign-in of the first tool call.
132
+ */
133
+ export async function signInAtStartup(opts, onSignedIn, log = (message) => process.stderr.write(`${message}\n`)) {
134
+ if (opts.token || mcpSurface(opts) !== "topline")
135
+ return false;
136
+ try {
137
+ const stored = await readStoredOAuthCredentials(opts);
138
+ if (stored?.refreshToken || (stored?.accessToken && Date.parse(stored.accessTokenExpiresAt ?? "") > Date.now()))
139
+ return false;
140
+ // Hosts often start one server per window or session; only one of them opens the browser.
141
+ if (!(await takeStartupSignInLock(opts.authFile)))
142
+ return false;
143
+ try {
144
+ log(`Opening your browser to sign in to Topline at ${platformBaseUrl(opts)}. Choose Allow to load the Topline tools.`);
145
+ await interactiveSignIn({
146
+ ...opts,
147
+ quietOpenFailure: true,
148
+ openUrl: async (url) => {
149
+ // Printed every time: with no browser (SSH, a container) this is the only way to finish.
150
+ log(`If it does not open, visit this address:\n${url}`);
151
+ await (opts.openUrl ? opts.openUrl(url) : openBrowser({ ...opts, openUrl: undefined, quietOpenFailure: true }, url));
152
+ }
153
+ });
154
+ }
155
+ finally {
156
+ await rm(startupSignInLockFile(opts.authFile), { force: true }).catch(() => undefined);
157
+ }
158
+ await onSignedIn().catch(() => undefined);
159
+ return true;
160
+ }
161
+ catch (err) {
162
+ log(`Topline sign-in did not finish (${err instanceof Error ? err.message : "unknown error"}). The first Topline tool will ask again.`);
163
+ return false;
164
+ }
165
+ }
166
+ function startupSignInLockFile(authFile) {
167
+ return `${path.resolve(authFile)}.signin-lock`;
168
+ }
169
+ /** True when this process may run the startup sign-in; a lock younger than the 5-minute sign-in window means another one is. */
170
+ async function takeStartupSignInLock(authFile) {
171
+ const lock = startupSignInLockFile(authFile);
172
+ await mkdir(path.dirname(lock), { recursive: true });
173
+ for (let attempt = 0; attempt < 2; attempt += 1) {
174
+ try {
175
+ await writeFile(lock, `${process.pid}\n`, { flag: "wx", mode: 0o600 });
176
+ return true;
177
+ }
178
+ catch {
179
+ const age = Date.now() - ((await lstat(lock).catch(() => null))?.mtimeMs ?? 0);
180
+ if (age < 6 * 60 * 1000)
181
+ return false;
182
+ await rm(lock, { force: true }).catch(() => undefined);
183
+ }
184
+ }
185
+ return false;
186
+ }
187
+ // One browser sign-in per auth file at a time: the startup sign-in and a tool
188
+ // call that needs a token share it instead of opening two approvals.
189
+ const inFlightSignIns = new Map();
190
+ async function interactiveSignIn(opts) {
191
+ const key = path.resolve(opts.authFile);
192
+ const pending = inFlightSignIns.get(key);
193
+ if (pending)
194
+ return pending;
195
+ const started = (async () => {
196
+ const credentials = await runOAuthLogin(opts);
197
+ await writeStoredOAuthCredentials(opts, credentials);
198
+ return credentials;
199
+ })();
200
+ inFlightSignIns.set(key, started);
201
+ try {
202
+ return await started;
203
+ }
204
+ finally {
205
+ inFlightSignIns.delete(key);
206
+ }
115
207
  }
116
208
  /**
117
209
  * `topline-mcp login`: sign in once during setup so the assistant's next chat
@@ -179,8 +271,27 @@ export function cliInfo(argv) {
179
271
  }
180
272
  export function createHarnessMcpStdioServer(opts, toolAllowlist) {
181
273
  let discoveredGrant = null;
274
+ // The last tools/list built from a successful hosted listing, bound to the
275
+ // sign-in it was made with. A temporary listing failure reuses it for the
276
+ // life of the process instead of hiding tools; signing out clears it.
277
+ let lastHostedListing = null;
278
+ let hostedListingFailed = false;
279
+ // Session tools the most recent listing left out; calls to them are refused.
280
+ let hiddenSessionTools = new Set();
281
+ // Hosted input schemas for session tools that only forward, from the last good listing.
282
+ let hostedSessionSchemas = new Map();
283
+ // Only the newest listing writes shared state, so a slow older one cannot overwrite it.
284
+ let listingGeneration = 0;
182
285
  const grantTag = (stored) => stored?.accessToken && Date.parse(stored.accessTokenExpiresAt ?? "") > Date.now()
183
286
  ? JSON.stringify([stored.clientId, stored.resource, [...stored.scopes].sort()]) : null;
287
+ // Identifies one sign-in regardless of access-token expiry: each browser
288
+ // sign-in registers a new client.
289
+ const signInTag = async () => {
290
+ if (opts.token)
291
+ return "manual-token";
292
+ const stored = await readStoredOAuthCredentials(opts).catch(() => null);
293
+ return stored ? JSON.stringify([stored.issuer, stored.clientId, stored.resource, [...stored.scopes].sort()]) : null;
294
+ };
184
295
  const allowedTools = toolAllowlist ? new Set(toolAllowlist) : null;
185
296
  const listedTools = () => {
186
297
  const listed = listTools();
@@ -191,35 +302,91 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
191
302
  const listed = listedTools();
192
303
  if (!servesBuild(opts) || (opts.token && mcpSurface(opts) !== "topline"))
193
304
  return { tools: listed.tools.filter(tool => !DOMAIN_FORWARD_TOOLS.has(tool.name)) };
305
+ const generation = ++listingGeneration;
306
+ const newest = () => generation === listingGeneration;
307
+ let names = new Set();
308
+ // Signed out (or the sign-in was rejected): the package's own list, with
309
+ // session tools listed so first-run users see them.
310
+ const signedOut = () => {
311
+ if (newest()) {
312
+ lastHostedListing = null;
313
+ hiddenSessionTools = new Set();
314
+ hostedSessionSchemas = new Map();
315
+ }
316
+ return { tools: listed.tools.filter(tool => !DOMAIN_FORWARD_TOOLS.has(tool.name) || names.has(tool.name)).map(tool => tool.name === "platform_read_artifact_domains"
317
+ ? { ...tool, inputSchema: { type: "object", additionalProperties: false, properties: { limit: { type: "integer", minimum: 1, maximum: 100 }, cursor: { type: "integer", minimum: 0, maximum: 10000 } } } }
318
+ : tool) };
319
+ };
194
320
  // Public deployment metadata never initiates OAuth or changes consent.
195
321
  // Unknown/old servers fail closed for this default-off family.
196
322
  try {
197
323
  const metadata = asRecord(await fetchJson({ ...opts, timeoutMs: Math.min(opts.timeoutMs, 5000) }, hostedMcpUrl(opts), { method: "GET" }));
198
- const names = new Set(Array.isArray(metadata.tools) ? metadata.tools.map(item => typeof item === "string" ? item : asRecord(item).name) : []);
324
+ names = new Set(Array.isArray(metadata.tools) ? metadata.tools.map(item => typeof item === "string" ? item : asRecord(item).name) : []);
199
325
  // Listing never opens the browser, but it does refresh an expired access
200
- // token so hosted tools still appear in a chat started hours later.
201
- const bearer = await getBearerTokenWithoutSignIn(opts).catch(() => null);
202
- if (bearer) {
203
- const payload = asRecord(await fetchJson({ ...opts, timeoutMs: Math.min(opts.timeoutMs, 5000) }, hostedMcpUrl(opts), {
326
+ // token so hosted tools still appear in a chat started hours later. A
327
+ // rejected sign-in counts as signed out; a temporary refresh failure
328
+ // after a good listing keeps that listing.
329
+ let bearer = null;
330
+ try {
331
+ bearer = await getBearerTokenWithoutSignIn(opts);
332
+ }
333
+ catch (error) {
334
+ if (lastHostedListing && !isSignInRejected(error))
335
+ throw error;
336
+ }
337
+ if (!bearer)
338
+ return signedOut();
339
+ let payload;
340
+ try {
341
+ payload = asRecord(await fetchJson({ ...opts, timeoutMs: Math.min(opts.timeoutMs, 5000) }, hostedMcpUrl(opts), {
204
342
  method: "POST", headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
205
343
  body: JSON.stringify({ jsonrpc: "2.0", id: "domain-discovery", method: "tools/list", params: {} }),
206
344
  }));
207
- const remote = asRecord(payload.result).tools;
208
- if (!Array.isArray(remote))
209
- throw new Error("domain_discovery_unavailable");
210
- const contracts = new Map(remote.filter(isRecord).map(tool => [tool.name, tool]));
345
+ }
346
+ catch (error) {
347
+ if (isSignInRejected(error))
348
+ return signedOut();
349
+ throw error;
350
+ }
351
+ const remote = asRecord(payload.result).tools;
352
+ if (!Array.isArray(remote))
353
+ throw new Error("domain_discovery_unavailable");
354
+ const contracts = new Map(remote.filter(isRecord).map(tool => [tool.name, tool]));
355
+ const hostedSchema = (name) => isRecord(contracts.get(name)?.inputSchema)
356
+ ? contracts.get(name).inputSchema : undefined;
357
+ // Session tools follow the hosted list: listed only while it offers them.
358
+ const hidden = new Set(listed.tools.map(tool => tool.name).filter(name => EXTERNAL_BUILD_SESSION_TOOLS.has(name) && !contracts.has(name)));
359
+ const schemas = new Map(listed.tools.map(tool => tool.name)
360
+ .filter(name => EXTERNAL_BUILD_SESSION_FORWARD_TOOLS.has(name) && !hidden.has(name) && hostedSchema(name))
361
+ .map(name => [name, hostedSchema(name)]));
362
+ const local = listed.tools.filter(tool => !DOMAIN_FORWARD_TOOLS.has(tool.name) || (names.has(tool.name) && contracts.has(tool.name)))
363
+ .filter(tool => !hidden.has(tool.name))
364
+ .map(tool => DOMAIN_FORWARD_TOOLS.has(tool.name) ? { ...tool, inputSchema: contracts.get(tool.name).inputSchema }
365
+ : schemas.has(tool.name) ? { ...tool, inputSchema: schemas.get(tool.name) } : tool);
366
+ const tools = [...local, ...hostedOnlyTools(opts, remote, allowedTools)];
367
+ const signIn = await signInTag();
368
+ if (newest()) {
211
369
  if (!opts.token)
212
370
  discoveredGrant = grantTag(await readStoredOAuthCredentials(opts));
213
- const local = listed.tools.filter(tool => !DOMAIN_FORWARD_TOOLS.has(tool.name) || (names.has(tool.name) && contracts.has(tool.name)))
214
- .map(tool => DOMAIN_FORWARD_TOOLS.has(tool.name) ? { ...tool, inputSchema: contracts.get(tool.name).inputSchema } : tool);
215
- return { tools: [...local, ...hostedOnlyTools(opts, remote, allowedTools)] };
371
+ lastHostedListing = { tools, hiddenSessionTools: hidden, signIn };
372
+ hiddenSessionTools = hidden;
373
+ hostedSessionSchemas = schemas;
216
374
  }
217
- return { tools: listed.tools.filter(tool => !DOMAIN_FORWARD_TOOLS.has(tool.name) || names.has(tool.name)).map(tool => tool.name === "platform_read_artifact_domains"
218
- ? { ...tool, inputSchema: { type: "object", additionalProperties: false, properties: { limit: { type: "integer", minimum: 1, maximum: 100 }, cursor: { type: "integer", minimum: 0, maximum: 10000 } } } }
219
- : tool) };
375
+ return { tools: structuredClone(tools) };
220
376
  }
221
377
  catch {
222
- return { tools: listed.tools.filter(tool => !DOMAIN_FORWARD_TOOLS.has(tool.name)) };
378
+ // Network, 5xx or timeout: keep the last good listing while the same
379
+ // sign-in holds; before one exists, list the package's own tools. The
380
+ // next tool call asks the host to list again.
381
+ hostedListingFailed = true;
382
+ const last = lastHostedListing && lastHostedListing.signIn === await signInTag() ? lastHostedListing : null;
383
+ if (newest()) {
384
+ lastHostedListing = last;
385
+ hiddenSessionTools = last?.hiddenSessionTools ?? new Set();
386
+ if (!last)
387
+ hostedSessionSchemas = new Map();
388
+ }
389
+ return { tools: last ? structuredClone(last.tools) : listed.tools.filter(tool => !DOMAIN_FORWARD_TOOLS.has(tool.name)) };
223
390
  }
224
391
  });
225
392
  mcp.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
@@ -227,16 +394,24 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
227
394
  throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${req.params.name}`);
228
395
  }
229
396
  const reportsProgress = req.params.name === "platform_deploy_artifact_app" || req.params.name === "platform_wait_artifact_deploy";
397
+ let refusedHidden = false;
230
398
  try {
231
- if (mcpSurface(opts) === "topline" && !LOCAL_TOOL_NAMES.has(req.params.name)) {
399
+ // A changed sign-in (for example a reconnect with new scopes) may offer
400
+ // the tool again; Topline still checks, so the call goes through.
401
+ if (hiddenSessionTools.has(req.params.name) && (opts.token || grantTag(await readStoredOAuthCredentials(opts)) === discoveredGrant)) {
402
+ refusedHidden = true;
403
+ return structuredToolError("build_session_tool_unavailable");
404
+ }
405
+ if (forwardsHostedSurface(opts) && !LOCAL_TOOL_NAMES.has(req.params.name)) {
232
406
  if (!forwardsHostedTool(req.params.name))
233
407
  throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${req.params.name}`);
234
408
  // Workspace and other hosted tools: Topline checks scopes and seat.
235
409
  return await forwardHostedTool(opts, req.params.name, req.params.arguments ?? {});
236
410
  }
237
- const result = await callHarnessTool(opts, req.params.name, req.params.arguments ?? {}, reportsProgress
238
- ? { onProgress: (progress, message) => sendProgress(extra, progress, 1, message) }
239
- : undefined);
411
+ const result = await callHarnessTool(opts, req.params.name, req.params.arguments ?? {}, {
412
+ ...(reportsProgress ? { onProgress: (progress, message) => sendProgress(extra, progress, 1, message) } : {}),
413
+ inputSchema: hostedSessionSchemas.get(req.params.name)
414
+ });
240
415
  return result;
241
416
  }
242
417
  catch (err) {
@@ -247,15 +422,24 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
247
422
  return structuredToolError(redactSecrets(err instanceof Error ? err.message : String(err), opts));
248
423
  }
249
424
  finally {
425
+ let listChanged = false;
250
426
  if (servesBuild(opts) && !opts.token) {
251
427
  const currentGrant = grantTag(await readStoredOAuthCredentials(opts));
252
428
  if (currentGrant !== discoveredGrant) {
253
429
  discoveredGrant = currentGrant;
254
430
  // First browser sign-in changes manager-only selector availability.
255
431
  // Tell MCP hosts to rediscover before setup status/recovery calls.
256
- await mcp.sendToolListChanged().catch(() => undefined);
432
+ listChanged = true;
257
433
  }
258
434
  }
435
+ if (hostedListingFailed || refusedHidden) {
436
+ // One failed listing, or a refused hidden tool, must not hide tools
437
+ // for the whole chat: the host lists again and sees current access.
438
+ hostedListingFailed = false;
439
+ listChanged = true;
440
+ }
441
+ if (listChanged)
442
+ await mcp.sendToolListChanged().catch(() => undefined);
259
443
  }
260
444
  });
261
445
  return mcp;
@@ -265,7 +449,8 @@ export async function callHarnessTool(opts, name, args, hooks) {
265
449
  const tool = listTools().tools.find((candidate) => candidate.name === name);
266
450
  if (!tool)
267
451
  throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${name}`);
268
- const inputError = validateJsonSchema(tool.inputSchema, input);
452
+ // A forwarding session tool may be checked against the hosted schema it was listed with.
453
+ const inputError = validateJsonSchema(hooks?.inputSchema && EXTERNAL_BUILD_SESSION_FORWARD_TOOLS.has(name) ? hooks.inputSchema : tool.inputSchema, input);
269
454
  if (inputError)
270
455
  return toolError(`Invalid arguments for ${name}: ${inputError}`);
271
456
  let result;
@@ -393,8 +578,13 @@ export async function deployArtifactApp(opts, input, onProgress) {
393
578
  if (input.artifactId !== undefined && input.artifactId !== sessionArtifactId)
394
579
  throw new Error("build_session_artifact_mismatch");
395
580
  }
396
- else if (sessionVersion || idempotencyKey || inspectedSourceHash || suppliedPlatformAppDir)
397
- throw new Error("build_session_id_required");
581
+ else {
582
+ const sessionOnly = Object.entries({ artifactVersionId: sessionVersion, idempotencyKey, inspectedSourceHash, platformAppDir: suppliedPlatformAppDir })
583
+ .filter(([, value]) => value).map(([field]) => field);
584
+ // Name the fields so the caller can drop them for a plain deploy or start a session.
585
+ if (sessionOnly.length)
586
+ throw new Error(`build_session_id_required:${sessionOnly.join(",")}`);
587
+ }
398
588
  await onProgress?.(0.4, "Creating private artifact draft");
399
589
  const created = await fetchJson(opts, artifactAppsPath(opts), {
400
590
  method: "POST",
@@ -1574,9 +1764,9 @@ const BUILD_MCP_TOOLS = [
1574
1764
  },
1575
1765
  {
1576
1766
  name: "platform_run_artifact_smoke",
1577
- description: "Rerun the trusted draft smoke check and return fresh rendered-page evidence.",
1767
+ description: "Rerun the trusted draft smoke check and return fresh rendered-page evidence. While you hold an open build session on the app, pass its sessionId.",
1578
1768
  annotations: mcpToolAnnotations("platform_run_artifact_smoke", { readOnly: false, openWorld: true }),
1579
- inputSchema: { type: "object", properties: { artifactId: { type: "string", format: "uuid" }, deploymentRecordId: { type: "string", format: "uuid" } }, required: ["artifactId"], additionalProperties: false },
1769
+ inputSchema: { type: "object", properties: { artifactId: { type: "string", format: "uuid" }, deploymentRecordId: { type: "string", format: "uuid" }, sessionId: { type: "string", format: "uuid" } }, required: ["artifactId"], additionalProperties: false },
1580
1770
  outputSchema: { type: "object", properties: { ok: { type: "boolean" }, phase: { type: "string" }, artifactId: { type: "string" }, deploymentRecordId: { type: "string" }, smoke: { type: "object" }, validation: { type: "object" } }, required: ["ok", "phase", "artifactId", "deploymentRecordId", "smoke", "validation"] }
1581
1771
  },
1582
1772
  {
@@ -1613,16 +1803,22 @@ const LOCAL_TOOL_NAMES = new Set(BUILD_MCP_TOOLS.map((tool) => tool.name));
1613
1803
  /**
1614
1804
  * Hosted Build tools this package deliberately replaces with its own local
1615
1805
  * flow (package, upload, deploy) or keeps off entirely. They are neither
1616
- * listed nor forwarded on the combined server.
1806
+ * listed nor forwarded on the Build or combined server.
1617
1807
  */
1618
1808
  const HOSTED_TOOLS_NOT_FORWARDED = new Set(["platform_create_artifact_app", "platform_bedrock_local_token_command"]);
1619
1809
  const forwardsHostedTool = (name) => !LOCAL_TOOL_NAMES.has(name) && !HOSTED_TOOLS_NOT_FORWARDED.has(name);
1620
1810
  /**
1621
- * On the combined Topline server, hosted tools this package does not run
1622
- * locally (Workspace tools, for example) are listed from Topline as-is.
1811
+ * The combined Topline server, and the Build server signed in through OAuth,
1812
+ * list and forward hosted tools this package does not run locally. A local
1813
+ * tool always wins over a hosted tool of the same name.
1814
+ */
1815
+ const forwardsHostedSurface = (opts) => mcpSurface(opts) === "topline" || (mcpSurface(opts) === "build" && !opts.token);
1816
+ /**
1817
+ * Hosted tools this package does not run locally (new hosted Build tools, or
1818
+ * Workspace tools on the combined server) are listed from Topline as-is.
1623
1819
  */
1624
1820
  function hostedOnlyTools(opts, remote, allowedTools) {
1625
- if (mcpSurface(opts) !== "topline")
1821
+ if (!forwardsHostedSurface(opts))
1626
1822
  return [];
1627
1823
  return remote.filter(isRecord)
1628
1824
  .filter((tool) => typeof tool.name === "string" && forwardsHostedTool(tool.name) && (!allowedTools || allowedTools.has(tool.name)) && isRecord(tool.inputSchema))
@@ -1725,9 +1921,12 @@ const BUILD_MCP_RECOVERY_ERROR_VALUES = {
1725
1921
  ...Object.fromEntries([...DOMAIN_ERROR_CODES].map(code => [code, { retryable: false,
1726
1922
  recoveryAction: "Read current domain/address state and the original receipt with the saved pre-call key. Retain the exact original input. Review changed state, scopes or configuration before any new plan/key; never assume a rejected delivery means no effect." }])),
1727
1923
  domain_result_unknown: { retryable: false, recoveryAction: "The response did not establish an outcome. Recover the original receipt through platform_get_artifact_address (saved artifactId and apply key) or platform_read_artifact_domains (request/verify kind and key). Preserve the original plan/domain/input/key; an absent, pending or expired receipt does not authorize a fresh key. No mutation is replayed automatically." },
1924
+ build_session_tool_unavailable: { retryable: false, recoveryAction: "The connection's hosted Build tool list does not offer this build session tool, so the package does not list or run it. Call platform_capability_status to see what is missing, such as a scope or capability, and reconnect through browser sign-in with any missing scope. The package asks the host to list tools again, so the tool comes back once Topline offers it." },
1728
1925
  authorization_required: { retryable: false, recoveryAction: "Clear only this connection's cached OAuth credentials, then reconnect the Build MCP through browser sign-in. If using a manual bearer token, replace the expired or revoked token. Recover existing artifact/deployment progress before retrying a write." },
1729
1926
  platform_harness_timeout: { retryable: true, recoveryAction: "Retry the call. For a deployment, use platform_list_artifact_drafts to recover the artifact and platform_wait_artifact_deploy to resume progress." },
1730
- platform_mcp_tool_error: { retryable: false, recoveryAction: "Read the returned error code, correct the request or OAuth scopes, then retry." },
1927
+ platform_mcp_tool_error: { retryable: false, recoveryAction: "Topline refused the call without a code. Read the message, correct the request, then retry. Reconnect only when the message names a missing scope." },
1928
+ build_session_id_required: { retryable: false, recoveryAction: "The fields named after the code only work inside a build session. Remove them for a plain deploy of an app you created over MCP, or start a session and pass its sessionId." },
1929
+ artifact_external_session_active: { retryable: false, recoveryAction: "An open build session holds this app. If it is yours, pass its sessionId; otherwise close it with platform_close_build_session or wait for it to end." },
1731
1930
  artifact_deploy_wait_timeout: { retryable: true, recoveryAction: "Call platform_wait_artifact_deploy again with the same artifactId and operationId." },
1732
1931
  artifact_delete_plan_stale: { retryable: true, recoveryAction: "Call platform_plan_artifact_draft_delete again, review the new effects, and use its planToken." },
1733
1932
  artifact_app_bundle_changed_after_inspection: { retryable: true, recoveryAction: "Call platform_inspect_artifact_app again, review the new bundle hash, then retry deployment with that hash." },
@@ -1750,9 +1949,32 @@ function structuredToolError(message) {
1750
1949
  isError: true
1751
1950
  };
1752
1951
  }
1952
+ /** The code Topline put inside a wrapped tool error: JSON `{ error: { code } }`, `{ error: "code" }`, or a leading code token. */
1953
+ function hostedToolErrorCode(inner) {
1954
+ try {
1955
+ const parsed = JSON.parse(inner);
1956
+ if (isRecord(parsed)) {
1957
+ const error = parsed.error;
1958
+ const code = isRecord(error) ? error.code : typeof error === "string" ? error : parsed.code;
1959
+ if (typeof code === "string" && /^[a-z][a-z0-9_]{2,}$/.test(code))
1960
+ return code;
1961
+ }
1962
+ }
1963
+ catch {
1964
+ // Not JSON; fall back to a leading code token.
1965
+ }
1966
+ // Only a code-shaped token (it has an underscore): plain English such as
1967
+ // "missing scope ..." or "not found" is a message, not a code.
1968
+ return inner.match(/^([a-z][a-z0-9]*_[a-z0-9_]+)(?::|$|\s)/)?.[1] ?? null;
1969
+ }
1753
1970
  function recoveryErrorCode(message) {
1754
1971
  if (/^platform_harness_http_error:401(?::|$)/.test(message))
1755
1972
  return "authorization_required";
1973
+ if (message.startsWith("platform_mcp_tool_error:")) {
1974
+ const inner = hostedToolErrorCode(message.slice("platform_mcp_tool_error:".length).trim());
1975
+ if (inner && !["unknown_error", "tool_failed", "empty_response"].includes(inner))
1976
+ return inner === "mcp_tool_failed" ? "platform_mcp_tool_error" : inner;
1977
+ }
1756
1978
  if (DOMAIN_ERROR_CODES.has(message) || message === "domain_result_unknown")
1757
1979
  return message;
1758
1980
  const known = [
@@ -1761,8 +1983,9 @@ function recoveryErrorCode(message) {
1761
1983
  "artifact_app_scaffold_target_not_empty",
1762
1984
  "artifact_app_scaffold_shape_invalid",
1763
1985
  "platform_harness_timeout",
1764
- "platform_mcp_tool_error",
1765
- "scope_required"
1986
+ // Before the generic wrapper, which every hosted error message starts with.
1987
+ "scope_required",
1988
+ "platform_mcp_tool_error"
1766
1989
  ].find((candidate) => message.includes(candidate));
1767
1990
  if (known)
1768
1991
  return known;
@@ -1868,8 +2091,7 @@ async function getOAuthBearerToken(opts) {
1868
2091
  // Fall through to an interactive login; the stored refresh token may have been revoked.
1869
2092
  }
1870
2093
  }
1871
- const loggedIn = await runOAuthLogin(opts);
1872
- await writeStoredOAuthCredentials(opts, loggedIn);
2094
+ const loggedIn = await interactiveSignIn(opts);
1873
2095
  return loggedIn.accessToken;
1874
2096
  }
1875
2097
  async function refreshOAuthToken(opts, stored) {
@@ -1889,6 +2111,11 @@ async function refreshOAuthToken(opts, stored) {
1889
2111
  });
1890
2112
  return credentialsFromTokenResponse(stored.issuer, stored.resource, stored.clientId, stored.scopes, token);
1891
2113
  }
2114
+ /** The sign-in itself was refused (revoked, expired or invalid), as opposed to a temporary failure. */
2115
+ function isSignInRejected(err) {
2116
+ const message = err instanceof Error ? err.message : String(err);
2117
+ return isRefreshTokenRejected(err) || /^(?:platform_harness|topline_oauth)_http_error:401(?::|$)/.test(message) || message === "missing_topline_refresh_token";
2118
+ }
1892
2119
  function isRefreshTokenRejected(err) {
1893
2120
  const message = err instanceof Error ? err.message : String(err);
1894
2121
  return /^topline_oauth_http_error:(400|401):/.test(message) && /invalid_(grant|token)/i.test(message);
@@ -2,7 +2,7 @@
2
2
  "schemaVersion": 1,
3
3
  "package": {
4
4
  "name": "@topline-build/harness-mcp",
5
- "version": "0.9.0",
5
+ "version": "0.9.2",
6
6
  "bin": {
7
7
  "topline-mcp": "dist/cli.js"
8
8
  }
@@ -12,7 +12,7 @@
12
12
  "defaultVersion": "2025-11-25",
13
13
  "server": {
14
14
  "name": "topline-build-stdio",
15
- "version": "0.9.0"
15
+ "version": "0.9.2"
16
16
  }
17
17
  },
18
18
  "generatedFrom": {
@@ -337,6 +337,11 @@
337
337
  "retryable": false,
338
338
  "recoveryAction": "The response did not establish an outcome. Recover the original receipt through platform_get_artifact_address (saved artifactId and apply key) or platform_read_artifact_domains (request/verify kind and key). Preserve the original plan/domain/input/key; an absent, pending or expired receipt does not authorize a fresh key. No mutation is replayed automatically."
339
339
  },
340
+ {
341
+ "code": "build_session_tool_unavailable",
342
+ "retryable": false,
343
+ "recoveryAction": "The connection's hosted Build tool list does not offer this build session tool, so the package does not list or run it. Call platform_capability_status to see what is missing, such as a scope or capability, and reconnect through browser sign-in with any missing scope. The package asks the host to list tools again, so the tool comes back once Topline offers it."
344
+ },
340
345
  {
341
346
  "code": "platform_harness_timeout",
342
347
  "retryable": true,
@@ -345,7 +350,17 @@
345
350
  {
346
351
  "code": "platform_mcp_tool_error",
347
352
  "retryable": false,
348
- "recoveryAction": "Read the returned error code, correct the request or OAuth scopes, then retry."
353
+ "recoveryAction": "Topline refused the call without a code. Read the message, correct the request, then retry. Reconnect only when the message names a missing scope."
354
+ },
355
+ {
356
+ "code": "build_session_id_required",
357
+ "retryable": false,
358
+ "recoveryAction": "The fields named after the code only work inside a build session. Remove them for a plain deploy of an app you created over MCP, or start a session and pass its sessionId."
359
+ },
360
+ {
361
+ "code": "artifact_external_session_active",
362
+ "retryable": false,
363
+ "recoveryAction": "An open build session holds this app. If it is yours, pass its sessionId; otherwise close it with platform_close_build_session or wait for it to end."
349
364
  },
350
365
  {
351
366
  "code": "artifact_deploy_wait_timeout",
@@ -2509,7 +2524,7 @@
2509
2524
  },
2510
2525
  {
2511
2526
  "name": "platform_run_artifact_smoke",
2512
- "description": "Rerun the trusted draft smoke check and return fresh rendered-page evidence.",
2527
+ "description": "Rerun the trusted draft smoke check and return fresh rendered-page evidence. While you hold an open build session on the app, pass its sessionId.",
2513
2528
  "annotations": {
2514
2529
  "title": "Platform Run Artifact Smoke",
2515
2530
  "readOnlyHint": false,
@@ -2526,6 +2541,10 @@
2526
2541
  "deploymentRecordId": {
2527
2542
  "type": "string",
2528
2543
  "format": "uuid"
2544
+ },
2545
+ "sessionId": {
2546
+ "type": "string",
2547
+ "format": "uuid"
2529
2548
  }
2530
2549
  },
2531
2550
  "required": [
@@ -2,7 +2,7 @@
2
2
 
3
3
  > Generated from `src/index.ts#BUILD_MCP_TOOLS`. Do not edit this file by hand.
4
4
 
5
- Package: `@topline-build/harness-mcp@0.9.0`
5
+ Package: `@topline-build/harness-mcp@0.9.2`
6
6
  Transport: `stdio`
7
7
  Default protocol: `2025-11-25`
8
8
  Canonical guide: https://topline.build/docs/build-mcp-guide
@@ -65,8 +65,11 @@ Tool failures set `isError: true` and return `structuredContent.error` with `cod
65
65
  - `scope_required` (not automatically retryable): Reconnect the Build MCP and approve the requested scope.
66
66
  - `domain_tools_require_build_oauth` (not automatically retryable): Read current domain/address state and the original receipt with the saved pre-call key. Retain the exact original input. Review changed state, scopes or configuration before any new plan/key; never assume a rejected delivery means no effect.
67
67
  - `domain_result_unknown` (not automatically retryable): The response did not establish an outcome. Recover the original receipt through platform_get_artifact_address (saved artifactId and apply key) or platform_read_artifact_domains (request/verify kind and key). Preserve the original plan/domain/input/key; an absent, pending or expired receipt does not authorize a fresh key. No mutation is replayed automatically.
68
+ - `build_session_tool_unavailable` (not automatically retryable): The connection's hosted Build tool list does not offer this build session tool, so the package does not list or run it. Call platform_capability_status to see what is missing, such as a scope or capability, and reconnect through browser sign-in with any missing scope. The package asks the host to list tools again, so the tool comes back once Topline offers it.
68
69
  - `platform_harness_timeout` (retryable): Retry the call. For a deployment, use platform_list_artifact_drafts to recover the artifact and platform_wait_artifact_deploy to resume progress.
69
- - `platform_mcp_tool_error` (not automatically retryable): Read the returned error code, correct the request or OAuth scopes, then retry.
70
+ - `platform_mcp_tool_error` (not automatically retryable): Topline refused the call without a code. Read the message, correct the request, then retry. Reconnect only when the message names a missing scope.
71
+ - `build_session_id_required` (not automatically retryable): The fields named after the code only work inside a build session. Remove them for a plain deploy of an app you created over MCP, or start a session and pass its sessionId.
72
+ - `artifact_external_session_active` (not automatically retryable): An open build session holds this app. If it is yours, pass its sessionId; otherwise close it with platform_close_build_session or wait for it to end.
70
73
  - `artifact_deploy_wait_timeout` (retryable): Call platform_wait_artifact_deploy again with the same artifactId and operationId.
71
74
  - `artifact_delete_plan_stale` (retryable): Call platform_plan_artifact_draft_delete again, review the new effects, and use its planToken.
72
75
  - `artifact_app_bundle_changed_after_inspection` (retryable): Call platform_inspect_artifact_app again, review the new bundle hash, then retry deployment with that hash.
@@ -2409,7 +2412,7 @@ Output schema:
2409
2412
 
2410
2413
  ### `platform_run_artifact_smoke`
2411
2414
 
2412
- Rerun the trusted draft smoke check and return fresh rendered-page evidence.
2415
+ Rerun the trusted draft smoke check and return fresh rendered-page evidence. While you hold an open build session on the app, pass its sessionId.
2413
2416
 
2414
2417
  Safety: read-only=false, destructive=false, idempotent=false, open-world=true.
2415
2418
 
@@ -2447,6 +2450,10 @@ Input schema:
2447
2450
  "deploymentRecordId": {
2448
2451
  "type": "string",
2449
2452
  "format": "uuid"
2453
+ },
2454
+ "sessionId": {
2455
+ "type": "string",
2456
+ "format": "uuid"
2450
2457
  }
2451
2458
  },
2452
2459
  "required": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@topline-build/harness-mcp",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
4
4
  "description": "Topline Build MCP for creating and deploying artifact app drafts.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",