@topline-build/harness-mcp 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -7,23 +7,37 @@ import os from "node:os";
7
7
  import path from "node:path";
8
8
  import { gzipSync } from "node:zlib";
9
9
  import { externalBuildHelperTools, EXTERNAL_BUILD_FORWARD_TOOLS } from "./build-session-tools.js";
10
+ import { domainHelperTools, DOMAIN_FORWARD_TOOLS, DOMAIN_ERROR_CODES } from "./domain-tools.js";
10
11
  import { boundedTransfer, extractArtifactSourceArchive, MAX_SOURCE_ARCHIVE_BYTES, safeSourcePath } from "./source-checkout.js";
11
12
  import { Server as McpServer } from "@modelcontextprotocol/sdk/server/index.js";
12
13
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
14
  import { AjvJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/ajv";
14
15
  import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError } from "@modelcontextprotocol/sdk/types.js";
16
+ const MCP_SURFACES = ["build", "topline", "harness"];
15
17
  export const DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
16
18
  const DEFAULT_TIMEOUT_MS = 120_000;
17
19
  export const BUILD_MCP_SERVER_NAME = "topline-build-stdio";
18
- export const HARNESS_MCP_VERSION = "0.6.0";
20
+ export const HARNESS_MCP_VERSION = "0.8.0";
19
21
  export const DEFAULT_OAUTH_SCOPES = Object.freeze(["harness:artifact:read", "harness:artifact:write", "harness:artifact:deploy", "harness:artifact:delete"]);
22
+ /** The Topline server's scopes: Build and Workspace. Consent shows what the seat allows. */
23
+ export const TOPLINE_OAUTH_SCOPES = Object.freeze([
24
+ "harness:artifact:read", "harness:artifact:write", "harness:artifact:deploy", "harness:artifact:delete",
25
+ "harness:artifact:tables:write", "harness:artifact:validate", "harness:artifact:data:verify", "harness:assets:read",
26
+ "harness:secrets:metadata:read", "harness:domains:read", "harness:domains:manage", "harness:artifact:addresses:write",
27
+ "storyboard:read", "storyboard:write",
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",
30
+ "workspace:skills:write", "workspace:access:manage", "schedules:read", "schedules:write", "schedules:delete",
31
+ "workforce:read", "workforce:write", "memory:read", "preferences:write", "glossary:read", "glossary:write",
32
+ "company_knowledge:propose", "company_knowledge:write", "customer_profiles:read", "data:read"
33
+ ]);
20
34
  export const BUILD_MCP_SETUP_OPTIONS = Object.freeze([
21
35
  { 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." },
22
36
  { flag: "--workspace-root", env: "TOPLINE_WORKSPACE_ROOT", aliases: ["PLATFORM_WORKSPACE_ROOT"], default: "current working directory", description: "Local root that contains artifact app directories." },
23
- { flag: "--surface", env: "TOPLINE_MCP_SURFACE", default: "build", allowed: ["build", "harness"], description: "Build is the current surface; harness preserves legacy OAuth compatibility." },
37
+ { flag: "--surface", env: "TOPLINE_MCP_SURFACE", default: "build", allowed: ["build", "topline", "harness"], description: "topline is one server for Build and Workspace tools; build serves Build tools only; harness preserves legacy OAuth compatibility." },
24
38
  { flag: "--protocol-version", env: "TOPLINE_MCP_PROTOCOL_VERSION", aliases: ["PLATFORM_MCP_PROTOCOL_VERSION"], default: DEFAULT_MCP_PROTOCOL_VERSION, description: "MCP protocol version sent to Topline HTTP endpoints." },
25
39
  { flag: "--auth-file", env: "TOPLINE_MCP_AUTH_FILE", aliases: ["PLATFORM_MCP_AUTH_FILE"], default: "per-tenant file in the local Topline config directory", description: "OAuth credential cache. Keep it outside artifact app directories." },
26
- { flag: "--scopes", env: "TOPLINE_MCP_SCOPES", aliases: ["PLATFORM_MCP_SCOPES"], default: DEFAULT_OAUTH_SCOPES.join(" "), description: "Space- or comma-separated OAuth scopes." },
40
+ { flag: "--scopes", env: "TOPLINE_MCP_SCOPES", aliases: ["PLATFORM_MCP_SCOPES"], default: "Build scopes; every Topline scope with --surface topline", description: "Space- or comma-separated OAuth scopes." },
27
41
  { flag: "--timeout-ms", env: "TOPLINE_MCP_TIMEOUT_MS", aliases: ["PLATFORM_MCP_TIMEOUT_MS", "OVERSITE_MCP_TIMEOUT_MS"], default: DEFAULT_TIMEOUT_MS, description: "Positive request timeout in milliseconds." },
28
42
  { flag: "--token", env: "TOPLINE_MCP_TOKEN", aliases: ["PLATFORM_MCP_TOKEN", "OVERSITE_MCP_TOKEN"], description: "Advanced manual bearer-token fallback. Prefer browser-approved OAuth." }
29
43
  ].map((option) => Object.freeze({
@@ -38,7 +52,7 @@ const MAX_MANIFEST_BYTES = 512 * 1024;
38
52
  const MAX_FILES = 25_000;
39
53
  const MAX_DEPTH = 64;
40
54
  const FORBIDDEN_DIRS = new Set([".git", "node_modules", ".next", ".vite", ".turbo", ".cache", "dist", "build", "coverage"]);
41
- export function parseHarnessOptions(argv, env = process.env) {
55
+ export function parseHarnessOptions(argv, env = process.env, defaults = {}) {
42
56
  const getArg = (name) => {
43
57
  const index = argv.indexOf(name);
44
58
  if (index < 0)
@@ -52,9 +66,9 @@ export function parseHarnessOptions(argv, env = process.env) {
52
66
  const token = getArg("--token") || firstEnv(env, "TOPLINE_MCP_TOKEN", "PLATFORM_MCP_TOKEN", "OVERSITE_MCP_TOKEN") || undefined;
53
67
  const timeoutRaw = getArg("--timeout-ms") || firstEnv(env, "TOPLINE_MCP_TIMEOUT_MS", "PLATFORM_MCP_TIMEOUT_MS", "OVERSITE_MCP_TIMEOUT_MS");
54
68
  const protocolVersion = getArg("--protocol-version") || firstEnv(env, "TOPLINE_MCP_PROTOCOL_VERSION", "PLATFORM_MCP_PROTOCOL_VERSION") || DEFAULT_MCP_PROTOCOL_VERSION;
55
- const surfaceRaw = getArg("--surface") || firstEnv(env, "TOPLINE_MCP_SURFACE") || "build";
56
- if (surfaceRaw !== "build" && surfaceRaw !== "harness")
57
- throw new Error("TOPLINE_MCP_SURFACE must be build or harness");
69
+ const surfaceRaw = (getArg("--surface") || firstEnv(env, "TOPLINE_MCP_SURFACE") || defaults.surface || "build");
70
+ if (!MCP_SURFACES.includes(surfaceRaw))
71
+ throw new Error("TOPLINE_MCP_SURFACE must be build, topline or harness");
58
72
  const workspaceRoot = path.resolve(getArg("--workspace-root") || firstEnv(env, "TOPLINE_WORKSPACE_ROOT", "PLATFORM_WORKSPACE_ROOT") || process.cwd());
59
73
  const timeoutMs = timeoutRaw ? Number(timeoutRaw) : DEFAULT_TIMEOUT_MS;
60
74
  if (!apiUrl)
@@ -63,7 +77,8 @@ export function parseHarnessOptions(argv, env = process.env) {
63
77
  throw new Error("TOPLINE_MCP_TIMEOUT_MS must be a positive number");
64
78
  const normalizedApiUrl = normalizeApiUrl(apiUrl);
65
79
  const authFile = path.resolve(getArg("--auth-file") || firstEnv(env, "TOPLINE_MCP_AUTH_FILE", "PLATFORM_MCP_AUTH_FILE") || defaultAuthFile(normalizedApiUrl, surfaceRaw));
66
- const scopes = (getArg("--scopes") || firstEnv(env, "TOPLINE_MCP_SCOPES", "PLATFORM_MCP_SCOPES") || DEFAULT_OAUTH_SCOPES.join(" "))
80
+ const defaultScopes = surfaceRaw === "topline" ? TOPLINE_OAUTH_SCOPES : DEFAULT_OAUTH_SCOPES;
81
+ const scopes = (getArg("--scopes") || firstEnv(env, "TOPLINE_MCP_SCOPES", "PLATFORM_MCP_SCOPES") || defaultScopes.join(" "))
67
82
  .split(/[\s,]+/)
68
83
  .map((scope) => scope.trim())
69
84
  .filter(Boolean);
@@ -72,7 +87,7 @@ export function parseHarnessOptions(argv, env = process.env) {
72
87
  surface: surfaceRaw,
73
88
  token,
74
89
  authFile,
75
- oauthScopes: scopes.length > 0 ? [...new Set(scopes)] : [...DEFAULT_OAUTH_SCOPES],
90
+ oauthScopes: scopes.length > 0 ? [...new Set(scopes)] : [...defaultScopes],
76
91
  timeoutMs: Math.floor(timeoutMs),
77
92
  protocolVersion,
78
93
  workspaceRoot
@@ -80,6 +95,15 @@ export function parseHarnessOptions(argv, env = process.env) {
80
95
  }
81
96
  export async function runHarnessMcpStdioCli() {
82
97
  const argv = process.argv.slice(2);
98
+ if (argv[0] === "login") {
99
+ const info = cliInfo(argv.slice(1));
100
+ if (info) {
101
+ console.log(info);
102
+ return;
103
+ }
104
+ await runLoginCommand(argv.slice(1));
105
+ return;
106
+ }
83
107
  const info = cliInfo(argv);
84
108
  if (info) {
85
109
  console.log(info);
@@ -89,6 +113,49 @@ export async function runHarnessMcpStdioCli() {
89
113
  const mcp = createHarnessMcpStdioServer(opts);
90
114
  await mcp.connect(new StdioServerTransport());
91
115
  }
116
+ /**
117
+ * `topline-mcp login`: sign in once during setup so the assistant's next chat
118
+ * starts already connected. Opens the browser, saves the refresh token to the
119
+ * same auth file the MCP server reads, then tells Topline this computer works.
120
+ */
121
+ export async function runLoginCommand(argv, env = process.env, io = { log: (message) => console.log(message) }, overrides = {}) {
122
+ const parsed = { ...parseHarnessOptions(argv, env, { surface: "topline" }), ...overrides };
123
+ if (parsed.token)
124
+ throw new Error("topline-mcp login uses browser sign-in. Remove TOPLINE_MCP_TOKEN and try again.");
125
+ if (!servesBuild(parsed))
126
+ throw new Error("topline-mcp login supports --surface topline or build.");
127
+ const base = platformBaseUrl(parsed);
128
+ const opts = {
129
+ ...parsed,
130
+ openUrl: async (url) => {
131
+ io.log(`Opening your browser to sign in to Topline at ${base}.`);
132
+ io.log(`If it does not open, visit this address:\n${url}`);
133
+ await openBrowser({ ...parsed, quietOpenFailure: true }, url);
134
+ io.log("Waiting for you to choose Allow in the browser (up to 5 minutes).");
135
+ }
136
+ };
137
+ let credentials;
138
+ try {
139
+ credentials = await runOAuthLogin(opts);
140
+ }
141
+ catch (err) {
142
+ if (err instanceof Error && err.message === "topline_oauth_login_timeout") {
143
+ throw new Error("Sign-in did not finish within 5 minutes. Run this command on the computer where your browser opens, sign in to Topline, choose Allow, and try again. If Topline said you need access, ask an admin for Build access.");
144
+ }
145
+ if (err instanceof Error && err.message === "topline_oauth_callback_invalid") {
146
+ throw new Error("Sign-in was not approved in the browser. Run the command again and choose Allow.");
147
+ }
148
+ throw err;
149
+ }
150
+ await writeStoredOAuthCredentials(opts, credentials);
151
+ const check = asRecord(await callHostedBuildTool(opts, "platform_connection_check", {}));
152
+ if (check.verified !== true) {
153
+ throw new Error("Signed in, but Topline could not confirm this computer. Run the command again; if it keeps failing, check Developer Access in Topline.");
154
+ }
155
+ io.log(`Connected to Topline at ${base}. Developer Access now shows this computer as connected.`);
156
+ io.log("Start a new chat in your assistant to use the Topline tools.");
157
+ return { apiUrl: base, verifiedAt: typeof check.verifiedAt === "string" ? check.verifiedAt : null };
158
+ }
92
159
  export function cliInfo(argv) {
93
160
  if (argv.includes("--version") || argv.includes("-v"))
94
161
  return HARNESS_MCP_VERSION;
@@ -96,6 +163,7 @@ export function cliInfo(argv) {
96
163
  return null;
97
164
  return [
98
165
  "Usage: topline-mcp --url https://your-topline-host [--workspace-root <path>]",
166
+ " topline-mcp login --url https://your-topline-host Sign in once in the browser (one Topline server)",
99
167
  "",
100
168
  "Options and environment:",
101
169
  ...BUILD_MCP_SETUP_OPTIONS.map((option) => {
@@ -105,23 +173,67 @@ export function cliInfo(argv) {
105
173
  "",
106
174
  "Examples:",
107
175
  " npx -y @topline-build/harness-mcp --url https://hawx.topline.build",
176
+ " npx -y @topline-build/harness-mcp login --url https://hawx.topline.build",
108
177
  " TOPLINE_API_URL=https://hawx.topline.build npx -y @topline-build/harness-mcp"
109
178
  ].join("\n");
110
179
  }
111
180
  export function createHarnessMcpStdioServer(opts, toolAllowlist) {
181
+ let discoveredGrant = null;
182
+ const grantTag = (stored) => stored?.accessToken && Date.parse(stored.accessTokenExpiresAt ?? "") > Date.now()
183
+ ? JSON.stringify([stored.clientId, stored.resource, [...stored.scopes].sort()]) : null;
112
184
  const allowedTools = toolAllowlist ? new Set(toolAllowlist) : null;
113
185
  const listedTools = () => {
114
186
  const listed = listTools();
115
187
  return allowedTools ? { ...listed, tools: listed.tools.filter((tool) => allowedTools.has(tool.name)) } : listed;
116
188
  };
117
- const mcp = new McpServer({ name: BUILD_MCP_SERVER_NAME, version: HARNESS_MCP_VERSION }, { capabilities: { tools: {} } });
118
- mcp.setRequestHandler(ListToolsRequestSchema, async () => listedTools());
189
+ const mcp = new McpServer({ name: BUILD_MCP_SERVER_NAME, version: HARNESS_MCP_VERSION }, { capabilities: { tools: { listChanged: true } } });
190
+ mcp.setRequestHandler(ListToolsRequestSchema, async () => {
191
+ const listed = listedTools();
192
+ if (!servesBuild(opts) || (opts.token && mcpSurface(opts) !== "topline"))
193
+ return { tools: listed.tools.filter(tool => !DOMAIN_FORWARD_TOOLS.has(tool.name)) };
194
+ // Public deployment metadata never initiates OAuth or changes consent.
195
+ // Unknown/old servers fail closed for this default-off family.
196
+ try {
197
+ 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) : []);
199
+ // 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), {
204
+ method: "POST", headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
205
+ body: JSON.stringify({ jsonrpc: "2.0", id: "domain-discovery", method: "tools/list", params: {} }),
206
+ }));
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]));
211
+ if (!opts.token)
212
+ 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)] };
216
+ }
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) };
220
+ }
221
+ catch {
222
+ return { tools: listed.tools.filter(tool => !DOMAIN_FORWARD_TOOLS.has(tool.name)) };
223
+ }
224
+ });
119
225
  mcp.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
120
226
  if (allowedTools && !allowedTools.has(req.params.name)) {
121
227
  throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${req.params.name}`);
122
228
  }
123
229
  const reportsProgress = req.params.name === "platform_deploy_artifact_app" || req.params.name === "platform_wait_artifact_deploy";
124
230
  try {
231
+ if (mcpSurface(opts) === "topline" && !LOCAL_TOOL_NAMES.has(req.params.name)) {
232
+ if (!forwardsHostedTool(req.params.name))
233
+ throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${req.params.name}`);
234
+ // Workspace and other hosted tools: Topline checks scopes and seat.
235
+ return await forwardHostedTool(opts, req.params.name, req.params.arguments ?? {});
236
+ }
125
237
  const result = await callHarnessTool(opts, req.params.name, req.params.arguments ?? {}, reportsProgress
126
238
  ? { onProgress: (progress, message) => sendProgress(extra, progress, 1, message) }
127
239
  : undefined);
@@ -134,6 +246,17 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
134
246
  await sendProgress(extra, 1, 1, "Failed artifact deployment");
135
247
  return structuredToolError(redactSecrets(err instanceof Error ? err.message : String(err), opts));
136
248
  }
249
+ finally {
250
+ if (servesBuild(opts) && !opts.token) {
251
+ const currentGrant = grantTag(await readStoredOAuthCredentials(opts));
252
+ if (currentGrant !== discoveredGrant) {
253
+ discoveredGrant = currentGrant;
254
+ // First browser sign-in changes manager-only selector availability.
255
+ // Tell MCP hosts to rediscover before setup status/recovery calls.
256
+ await mcp.sendToolListChanged().catch(() => undefined);
257
+ }
258
+ }
259
+ }
137
260
  });
138
261
  return mcp;
139
262
  }
@@ -197,8 +320,32 @@ export async function callHarnessTool(opts, name, args, hooks) {
197
320
  result = toolResult(await initArtifactApp(opts, input));
198
321
  break;
199
322
  default:
323
+ if (DOMAIN_FORWARD_TOOLS.has(name)) {
324
+ try {
325
+ if (!servesBuild(opts) || opts.token)
326
+ throw new Error("domain_tools_require_build_oauth");
327
+ result = toolResult(await callHostedBuildTool(opts, name, input));
328
+ }
329
+ catch (error) {
330
+ const message = error instanceof Error ? error.message : "";
331
+ const code = /^platform_harness_http_error:401(?::|$)/.test(message) ? "authorization_required"
332
+ : [...DOMAIN_ERROR_CODES].find(candidate => new RegExp(`(?:^|[^a-z_])${candidate}(?:$|[^a-z_])`).test(message)) ?? "domain_result_unknown";
333
+ result = structuredToolError(code);
334
+ const key = typeof input.idempotencyKey === "string" ? input.idempotencyKey : undefined;
335
+ const recovery = key && name === "platform_apply_artifact_address"
336
+ ? { tool: "platform_get_artifact_address", planId: input.planId, artifactIdRequiredFromSavedPlan: true, selector: { idempotencyKey: key } }
337
+ : key && ["platform_request_artifact_domain", "platform_verify_artifact_domain"].includes(name)
338
+ ? { tool: "platform_read_artifact_domains", arguments: { recovery: { kind: name === "platform_request_artifact_domain" ? "request" : "verify", idempotencyKey: key } }, domainId: input.domainId }
339
+ : undefined;
340
+ if (recovery) {
341
+ result.structuredContent.error.recovery = recovery;
342
+ result.content = [{ type: "text", text: JSON.stringify(result.structuredContent, null, 2) }];
343
+ }
344
+ }
345
+ break;
346
+ }
200
347
  if (EXTERNAL_BUILD_FORWARD_TOOLS.has(name)) {
201
- if (mcpSurface(opts) !== "build")
348
+ if (!servesBuild(opts))
202
349
  throw new Error("external_session_requires_build_surface");
203
350
  result = toolResult(await callHostedBuildTool(opts, name, input));
204
351
  break;
@@ -234,7 +381,7 @@ export async function deployArtifactApp(opts, input, onProgress) {
234
381
  const inspectedSourceHash = optionalString(input, "inspectedSourceHash");
235
382
  let sessionArtifactId;
236
383
  if (sessionId) {
237
- if (mcpSurface(opts) !== "build")
384
+ if (!servesBuild(opts))
238
385
  throw new Error("external_session_requires_build_surface");
239
386
  if (!sessionVersion || !idempotencyKey || !inspectedSourceHash || !expectedBundleSha256)
240
387
  throw new Error("build_session_deployment_arguments_required");
@@ -336,7 +483,7 @@ async function fetchBuildTransfer(opts, advertisedPath, expectedPath, sha256, ma
336
483
  }
337
484
  }
338
485
  async function newBuildInputTarget(opts, input) {
339
- if (mcpSurface(opts) !== "build")
486
+ if (!servesBuild(opts))
340
487
  throw new Error("external_session_requires_build_surface");
341
488
  const target = await resolveWorkspacePathSafely(opts.workspaceRoot, stringArg(input, "targetDir"));
342
489
  if (existsSync(target))
@@ -456,10 +603,10 @@ export async function inspectArtifactApp(opts, input) {
456
603
  };
457
604
  }
458
605
  async function callHostedBuildTool(opts, name, input) {
459
- if (mcpSurface(opts) !== "build")
606
+ if (!servesBuild(opts))
460
607
  throw new Error(`${name}_requires_build_surface`);
461
608
  const headers = await jsonHeaders(opts);
462
- const payload = asRecord(await fetchJson(opts, `${platformBaseUrl(opts)}/mcp/build`, {
609
+ const payload = asRecord(await fetchJson(opts, hostedMcpUrl(opts), {
463
610
  method: "POST",
464
611
  headers: { ...headers, accept: "application/json, text/event-stream" },
465
612
  body: JSON.stringify({
@@ -484,7 +631,7 @@ async function callHostedBuildTool(opts, name, input) {
484
631
  throw new Error(`platform_mcp_tool_output_missing:${name}`);
485
632
  }
486
633
  async function checkoutDesignSystem(opts, input) {
487
- if (mcpSurface(opts) !== "build")
634
+ if (!servesBuild(opts))
488
635
  throw new Error("storyboard_requires_build_surface");
489
636
  const targetDir = stringArg(input, "targetDir");
490
637
  const target = await resolveWorkspacePathSafely(opts.workspaceRoot, targetDir);
@@ -567,7 +714,7 @@ async function readBoundedStoryboardBundle(response) {
567
714
  return Buffer.concat(chunks, bytes);
568
715
  }
569
716
  async function submitDesignSystemDraft(opts, input) {
570
- if (mcpSurface(opts) !== "build")
717
+ if (!servesBuild(opts))
571
718
  throw new Error("storyboard_requires_build_surface");
572
719
  const localDir = await resolveWorkspacePathSafely(opts.workspaceRoot, stringArg(input, "localDir"));
573
720
  await assertAuthFileOutsideAppDir(opts.authFile, localDir);
@@ -1009,11 +1156,25 @@ function padSize(size) {
1009
1156
  const remainder = size % BLOCK_SIZE;
1010
1157
  return remainder === 0 ? 0 : BLOCK_SIZE - remainder;
1011
1158
  }
1159
+ /**
1160
+ * Requests to this Topline account carry the package version, so Topline can
1161
+ * ask an outdated computer to update. Other hosts (upload URLs) never see it.
1162
+ */
1163
+ function withPackageVersionHeader(opts, url, init) {
1164
+ let sameAccount = false;
1165
+ try {
1166
+ sameAccount = new URL(url).origin === new URL(platformBaseUrl(opts)).origin;
1167
+ }
1168
+ catch { /* leave the request as-is */ }
1169
+ if (!sameAccount || (init.headers !== undefined && (init.headers instanceof Headers || Array.isArray(init.headers))))
1170
+ return init;
1171
+ return { ...init, headers: { ...init.headers, "x-topline-mcp-version": HARNESS_MCP_VERSION } };
1172
+ }
1012
1173
  async function fetchJson(opts, url, init, timeoutMs = opts.timeoutMs) {
1013
1174
  const controller = new AbortController();
1014
1175
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
1015
1176
  try {
1016
- const response = await (opts.fetchImpl ?? fetch)(url, { ...init, signal: controller.signal });
1177
+ const response = await (opts.fetchImpl ?? fetch)(url, { ...withPackageVersionHeader(opts, url, init), signal: controller.signal });
1017
1178
  const text = await response.text();
1018
1179
  let payload = {};
1019
1180
  try {
@@ -1043,20 +1204,19 @@ async function fetchJson(opts, url, init, timeoutMs = opts.timeoutMs) {
1043
1204
  const BUILD_MCP_TOOLS = [
1044
1205
  {
1045
1206
  name: "platform_connection_check",
1046
- description: "Complete the one-time Developer Access verification challenge for this Build MCP client.",
1207
+ description: "Tell Topline Developer Access that this signed-in client works. Run it with no arguments right after signing in. Pass verificationCode only when Developer Access shows one for a manual check.",
1047
1208
  annotations: mcpToolAnnotations("platform_connection_check", { readOnly: false, openWorld: true }),
1048
1209
  inputSchema: {
1049
1210
  type: "object",
1050
1211
  properties: {
1051
1212
  verificationCode: { type: "string", minLength: 16, maxLength: 80 }
1052
1213
  },
1053
- required: ["verificationCode"],
1054
1214
  additionalProperties: false
1055
1215
  },
1056
1216
  outputSchema: {
1057
1217
  type: "object",
1058
1218
  properties: {
1059
- ok: { type: "boolean" }, verified: { type: "boolean" }, product: { type: "string", enum: ["build"] }, verifiedAt: { type: "string" }
1219
+ ok: { type: "boolean" }, verified: { type: "boolean" }, product: { type: "string", enum: ["build", "topline"] }, verifiedAt: { type: "string" }
1060
1220
  },
1061
1221
  required: ["ok", "verified", "product", "verifiedAt"]
1062
1222
  }
@@ -1376,8 +1536,57 @@ const BUILD_MCP_TOOLS = [
1376
1536
  required: ["ok", "deleted", "artifactId"]
1377
1537
  }
1378
1538
  },
1379
- ...externalBuildHelperTools(mcpToolAnnotations)
1539
+ ...externalBuildHelperTools(mcpToolAnnotations),
1540
+ ...domainHelperTools(mcpToolAnnotations)
1380
1541
  ].map(withRecoveryOutputSchema);
1542
+ const LOCAL_TOOL_NAMES = new Set(BUILD_MCP_TOOLS.map((tool) => tool.name));
1543
+ /**
1544
+ * Hosted Build tools this package deliberately replaces with its own local
1545
+ * flow (package, upload, deploy) or keeps off entirely. They are neither
1546
+ * listed nor forwarded on the combined server.
1547
+ */
1548
+ const HOSTED_TOOLS_NOT_FORWARDED = new Set(["platform_create_artifact_app", "platform_bedrock_local_token_command"]);
1549
+ const forwardsHostedTool = (name) => !LOCAL_TOOL_NAMES.has(name) && !HOSTED_TOOLS_NOT_FORWARDED.has(name);
1550
+ /**
1551
+ * On the combined Topline server, hosted tools this package does not run
1552
+ * locally (Workspace tools, for example) are listed from Topline as-is.
1553
+ */
1554
+ function hostedOnlyTools(opts, remote, allowedTools) {
1555
+ if (mcpSurface(opts) !== "topline")
1556
+ return [];
1557
+ return remote.filter(isRecord)
1558
+ .filter((tool) => typeof tool.name === "string" && forwardsHostedTool(tool.name) && (!allowedTools || allowedTools.has(tool.name)) && isRecord(tool.inputSchema))
1559
+ .map((tool) => ({
1560
+ name: tool.name,
1561
+ ...(typeof tool.title === "string" ? { title: tool.title } : {}),
1562
+ ...(typeof tool.description === "string" ? { description: tool.description } : {}),
1563
+ inputSchema: tool.inputSchema,
1564
+ ...(isRecord(tool.outputSchema) ? { outputSchema: tool.outputSchema } : {}),
1565
+ ...(isRecord(tool.annotations) ? { annotations: tool.annotations } : {})
1566
+ }));
1567
+ }
1568
+ async function forwardHostedTool(opts, name, input) {
1569
+ const headers = await jsonHeaders(opts);
1570
+ const payload = asRecord(await fetchJson(opts, hostedMcpUrl(opts), {
1571
+ method: "POST",
1572
+ headers: { ...headers, accept: "application/json, text/event-stream" },
1573
+ body: JSON.stringify({ jsonrpc: "2.0", id: `stdio-${Date.now()}`, method: "tools/call", params: { name, arguments: isRecord(input) ? input : {} } })
1574
+ }));
1575
+ if (payload.error) {
1576
+ const message = String(asRecord(payload.error).message ?? "unknown_error");
1577
+ if (/unknown tool/i.test(message))
1578
+ throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${name}`);
1579
+ throw new Error(`platform_mcp_tool_error:${message}`);
1580
+ }
1581
+ if (!isRecord(payload.result))
1582
+ throw new Error("platform_mcp_tool_error:empty_response");
1583
+ const result = payload.result;
1584
+ return {
1585
+ content: Array.isArray(result.content) ? result.content : [],
1586
+ ...(isRecord(result.structuredContent) ? { structuredContent: result.structuredContent } : {}),
1587
+ ...(result.isError === true ? { isError: true } : {})
1588
+ };
1589
+ }
1381
1590
  export function listTools() {
1382
1591
  // Preserve the original tools/list isolation boundary: callers must not be
1383
1592
  // able to mutate the registry used by later requests or input validation.
@@ -1403,7 +1612,8 @@ function withRecoveryOutputSchema(value) {
1403
1612
  code: { type: "string" },
1404
1613
  message: { type: "string" },
1405
1614
  retryable: { type: "boolean" },
1406
- recoveryAction: { type: "string" }
1615
+ recoveryAction: { type: "string" },
1616
+ ...(DOMAIN_FORWARD_TOOLS.has(tool.name) ? { recovery: { type: "object", additionalProperties: true } } : {})
1407
1617
  },
1408
1618
  required: ["code", "message", "retryable", "recoveryAction"],
1409
1619
  additionalProperties: false
@@ -1442,6 +1652,9 @@ function toolError(message) {
1442
1652
  return structuredToolError(message);
1443
1653
  }
1444
1654
  const BUILD_MCP_RECOVERY_ERROR_VALUES = {
1655
+ ...Object.fromEntries([...DOMAIN_ERROR_CODES].map(code => [code, { retryable: false,
1656
+ 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." }])),
1657
+ 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." },
1445
1658
  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." },
1446
1659
  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." },
1447
1660
  platform_mcp_tool_error: { retryable: false, recoveryAction: "Read the returned error code, correct the request or OAuth scopes, then retry." },
@@ -1469,6 +1682,8 @@ function structuredToolError(message) {
1469
1682
  function recoveryErrorCode(message) {
1470
1683
  if (/^platform_harness_http_error:401(?::|$)/.test(message))
1471
1684
  return "authorization_required";
1685
+ if (DOMAIN_ERROR_CODES.has(message) || message === "domain_result_unknown")
1686
+ return message;
1472
1687
  const known = [
1473
1688
  "artifact_delete_plan_stale",
1474
1689
  "artifact_deploy_wait_timeout",
@@ -1530,6 +1745,41 @@ export async function getBearerToken(opts) {
1530
1745
  inFlightBearerTokenRequests.delete(key);
1531
1746
  }
1532
1747
  }
1748
+ /**
1749
+ * The stored or refreshed access token, or null when only a browser sign-in
1750
+ * would help. Never opens the browser. A manual token is returned as-is.
1751
+ */
1752
+ async function getBearerTokenWithoutSignIn(opts) {
1753
+ if (opts.token?.trim())
1754
+ return opts.token.trim();
1755
+ const stored = await readStoredOAuthCredentials(opts);
1756
+ if (stored?.accessToken && stored.accessTokenExpiresAt && new Date(stored.accessTokenExpiresAt).getTime() - Date.now() > 60_000) {
1757
+ return stored.accessToken;
1758
+ }
1759
+ if (!stored?.refreshToken || !stored.clientId)
1760
+ return null;
1761
+ return (await refreshStoredOAuthToken(opts, stored)).accessToken ?? null;
1762
+ }
1763
+ const inFlightRefreshes = new Map();
1764
+ /** Refresh tokens rotate, so concurrent refreshes of one token share a single request. */
1765
+ async function refreshStoredOAuthToken(opts, stored) {
1766
+ const key = `${path.resolve(opts.authFile)}\0${stored.refreshToken}`;
1767
+ const existing = inFlightRefreshes.get(key);
1768
+ if (existing)
1769
+ return existing;
1770
+ const pending = (async () => {
1771
+ const refreshed = await refreshOAuthToken(opts, stored);
1772
+ await writeStoredOAuthCredentials(opts, refreshed);
1773
+ return refreshed;
1774
+ })();
1775
+ inFlightRefreshes.set(key, pending);
1776
+ try {
1777
+ return await pending;
1778
+ }
1779
+ finally {
1780
+ inFlightRefreshes.delete(key);
1781
+ }
1782
+ }
1533
1783
  async function getOAuthBearerToken(opts) {
1534
1784
  const stored = await readStoredOAuthCredentials(opts);
1535
1785
  if (stored?.accessToken && stored.accessTokenExpiresAt && new Date(stored.accessTokenExpiresAt).getTime() - Date.now() > 60_000) {
@@ -1537,8 +1787,7 @@ async function getOAuthBearerToken(opts) {
1537
1787
  }
1538
1788
  if (stored?.refreshToken && stored.clientId) {
1539
1789
  try {
1540
- const refreshed = await refreshOAuthToken(opts, stored);
1541
- await writeStoredOAuthCredentials(opts, refreshed);
1790
+ const refreshed = await refreshStoredOAuthToken(opts, stored);
1542
1791
  return refreshed.accessToken;
1543
1792
  }
1544
1793
  catch (err) {
@@ -1602,6 +1851,8 @@ async function runOAuthLogin(opts) {
1602
1851
  authUrl.searchParams.set("code_challenge_method", "S256");
1603
1852
  authUrl.searchParams.set("state", state);
1604
1853
  const codePromise = callback.waitForCode(state);
1854
+ // A denial can land while the browser is still opening; it is reported below.
1855
+ codePromise.catch(() => undefined);
1605
1856
  await openBrowser(opts, authUrl.toString());
1606
1857
  const code = await codePromise;
1607
1858
  const token = await oauthFetchJson(opts, `${issuer}/oauth/token`, {
@@ -1736,10 +1987,17 @@ async function startOAuthCallbackServer() {
1736
1987
  redirectUri: `http://127.0.0.1:${address.port}/callback`,
1737
1988
  waitForCode: async (state) => {
1738
1989
  expectedState = state;
1739
- return await Promise.race([
1740
- codePromise,
1741
- new Promise((_resolve, reject) => setTimeout(() => reject(new Error("topline_oauth_login_timeout")), 5 * 60 * 1000))
1742
- ]);
1990
+ let timer;
1991
+ try {
1992
+ return await Promise.race([
1993
+ codePromise,
1994
+ new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error("topline_oauth_login_timeout")), 5 * 60 * 1000); })
1995
+ ]);
1996
+ }
1997
+ finally {
1998
+ // A pending timer would keep `topline-mcp login` alive after it succeeds.
1999
+ clearTimeout(timer);
2000
+ }
1743
2001
  },
1744
2002
  close: () => closeServer(server)
1745
2003
  };
@@ -1764,10 +2022,14 @@ async function openBrowser(opts, url) {
1764
2022
  const { command, args } = browserOpenCommand(url);
1765
2023
  try {
1766
2024
  const child = spawn(command, args, { detached: true, stdio: "ignore" });
2025
+ // A missing opener (no xdg-open, for example) reports asynchronously.
2026
+ child.on("error", () => { if (!opts.quietOpenFailure)
2027
+ console.error(`Open this URL to authorize Topline MCP:\n${url}`); });
1767
2028
  child.unref();
1768
2029
  }
1769
2030
  catch {
1770
- console.error(`Open this URL to authorize Topline MCP:\n${url}`);
2031
+ if (!opts.quietOpenFailure)
2032
+ console.error(`Open this URL to authorize Topline MCP:\n${url}`);
1771
2033
  }
1772
2034
  }
1773
2035
  export function browserOpenCommand(url, platform = process.platform) {
@@ -1788,6 +2050,13 @@ function platformBaseUrl(opts) {
1788
2050
  function mcpSurface(opts) {
1789
2051
  return opts.surface ?? "build";
1790
2052
  }
2053
+ /** Build tools run on the Build server and on the combined Topline server. */
2054
+ function servesBuild(opts) {
2055
+ return mcpSurface(opts) !== "harness";
2056
+ }
2057
+ function hostedMcpUrl(opts) {
2058
+ return `${platformBaseUrl(opts)}/mcp/${mcpSurface(opts) === "topline" ? "topline" : "build"}`;
2059
+ }
1791
2060
  function logicalArtifactAppDir(workspaceAppDir, manifest) {
1792
2061
  if (workspaceAppDir === "." || workspaceAppDir.startsWith("artifact-apps/"))
1793
2062
  return workspaceAppDir;