@topline-build/harness-mcp 0.6.0 → 0.7.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/CHANGELOG.md CHANGED
@@ -4,6 +4,13 @@ All notable customer-visible Build MCP changes are recorded here. A source chang
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.7.0 - source candidate
8
+
9
+ - 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.
10
+ - Require explicit new scopes and account-bound Build OAuth; preserve manual-token behavior for legacy tools.
11
+ - 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.
12
+ - Discover enabled server capabilities and current hosted scoped contracts without initiating OAuth during discovery.
13
+
7
14
  ## 0.6.0 - pending publication
8
15
 
9
16
  - Add server-owned external build sessions, guarded artifact-private SQL, and full acceptance/reviewer forwarding.
package/README.md CHANGED
@@ -26,6 +26,10 @@ If a tool returns `authorization_required`, clear only that connection's OAuth c
26
26
 
27
27
  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.
28
28
 
29
+ 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.
30
+
31
+ 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.
32
+
29
33
  ## Typical workflow
30
34
 
31
35
  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.
@@ -0,0 +1,11 @@
1
+ import type { ListToolsResult, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
2
+ type Annotate = (name: string, policy: {
3
+ readOnly: boolean;
4
+ destructive?: boolean;
5
+ idempotent?: boolean;
6
+ openWorld?: boolean;
7
+ }) => ToolAnnotations;
8
+ export declare function domainHelperTools(mcpToolAnnotations: Annotate): ListToolsResult["tools"];
9
+ export declare const DOMAIN_FORWARD_TOOLS: Set<string>;
10
+ export declare const DOMAIN_ERROR_CODES: Set<string>;
11
+ export {};
@@ -0,0 +1,53 @@
1
+ export function domainHelperTools(mcpToolAnnotations) {
2
+ const id = { type: "string", format: "uuid" };
3
+ const key = { type: "string", minLength: 1, maxLength: 128, pattern: "^[\\x21-\\x7E]+$" };
4
+ const recovery = { oneOf: [
5
+ { type: "object", additionalProperties: false, properties: { operationId: id }, required: ["operationId"] },
6
+ { type: "object", additionalProperties: false, properties: { idempotencyKey: key }, required: ["idempotencyKey"] },
7
+ ] };
8
+ const setupRecovery = { oneOf: [recovery.oneOf[0], { type: "object", additionalProperties: false,
9
+ properties: { kind: { enum: ["request", "verify"] }, idempotencyKey: key }, required: ["kind", "idempotencyKey"] }] };
10
+ const tool = (name, description, properties, required, _scopes, readOnly, extra = {}) => ({
11
+ name, description,
12
+ inputSchema: { type: "object", additionalProperties: false, properties, required, ...extra },
13
+ outputSchema: { type: "object", properties: { ok: { const: true } } },
14
+ annotations: mcpToolAnnotations(name, { readOnly, destructive: name === "platform_apply_artifact_address", idempotent: name !== "platform_plan_artifact_address", openWorld: name === "platform_verify_artifact_domain" }),
15
+ });
16
+ return [
17
+ tool("platform_read_artifact_domains", "Read connected company domains. With domainId, an explicitly scoped manager can read DNS/TLS setup state. With recovery, recover an original request/verify receipt by operation ID or its pre-call key; reads never retry setup or write DNS. Manager detail/recovery requires the setup capability.", {
18
+ limit: { type: "integer", minimum: 1, maximum: 100 }, cursor: { type: "integer", minimum: 0, maximum: 10000 }, includePending: { type: "boolean" },
19
+ domainId: id, zoneName: { type: "string", minLength: 1, maxLength: 253 }, recovery: setupRecovery,
20
+ }, [], ["harness:domains:read"], true, { oneOf: [
21
+ { not: { anyOf: [{ required: ["domainId"] }, { required: ["recovery"] }, { required: ["zoneName"] }] } },
22
+ { required: ["domainId"], not: { anyOf: ["limit", "cursor", "includePending", "recovery"].map(name => ({ required: [name] })) } },
23
+ { required: ["recovery"], not: { anyOf: ["domainId", "zoneName", "cursor", "limit", "includePending"].map(name => ({ required: [name] })) } },
24
+ ] }),
25
+ tool("platform_get_artifact_address", "Read an owned hosted app's exact company address, revision, connection and publication state. Optional recovery returns the original address-apply receipt under its current write scopes; it does not reapply. Saving an address never publishes an app or changes audience.", {
26
+ artifactId: id, recovery,
27
+ }, ["artifactId"], ["harness:domains:read", "harness:artifact:read"], true),
28
+ tool("platform_plan_artifact_address", "Store a ten-minute single-use address preview for the owned app. domainId=null explicitly detaches the company route. Show old/new URLs and readiness before applying; this changes no customer address or DNS.", {
29
+ artifactId: id, domainId: { type: ["string", "null"], format: "uuid" }, path: { type: "string", minLength: 1, maxLength: 70 },
30
+ }, ["artifactId", "domainId"], ["harness:domains:read", "harness:artifact:read", "harness:artifact:addresses:write"], false, { oneOf: [
31
+ { properties: { domainId: id }, required: ["path"] },
32
+ { properties: { domainId: { type: "null" } }, not: { required: ["path"] } },
33
+ ] }),
34
+ tool("platform_apply_artifact_address", "Apply the exact owned address plan with a stable pre-call key. Rechecks authority and address/domain revisions; consumes the plan once, including a no-op. Recover a lost response through the address-read tool before a new effect. No promotion, audience or DNS write.", {
35
+ planId: id, idempotencyKey: key,
36
+ }, ["planId", "idempotencyKey"], ["harness:domains:read", "harness:artifact:read", "harness:artifact:addresses:write"], false),
37
+ tool("platform_request_artifact_domain", "Manager-only request for an owned company subdomain. Save the key before calling. Returns exact ownership/routing DNS records; never writes customer DNS. The existing reconciler may make the first connected domain the initial default. No artifact is reassigned.", {
38
+ hostname: { type: "string", minLength: 1, maxLength: 253 }, idempotencyKey: key,
39
+ }, ["hostname", "idempotencyKey"], ["harness:domains:read", "harness:domains:manage"], false),
40
+ tool("platform_verify_artifact_domain", "Manager-only bounded ownership verification for the exact current domain generation and pre-call key. Matching DNS admits the existing TLS reconciler once. Same keys retain outcomes; use a new key only after a definite terminal no-admission outcome and covered retry intent. Read status through domain reads.", {
41
+ domainId: id, expectedConnectionGeneration: { type: "integer", minimum: 0 }, idempotencyKey: key,
42
+ }, ["domainId", "expectedConnectionGeneration", "idempotencyKey"], ["harness:domains:read", "harness:domains:manage"], false),
43
+ ];
44
+ }
45
+ export const DOMAIN_FORWARD_TOOLS = new Set(domainHelperTools(() => ({})).map(tool => tool.name));
46
+ export const DOMAIN_ERROR_CODES = new Set([
47
+ "capability_unavailable", "domain_manage_required", "artifact_not_found", "artifact_app_required", "domain_not_found", "domain_not_connected",
48
+ "operation_not_found", "hostname_required", "hostname_invalid", "subdomain_required", "topline_domain_not_customer_domain", "path_required",
49
+ "path_invalid", "path_reserved", "zone_invalid", "domain_path_in_use", "domain_already_claimed", "address_state_changed", "domain_state_changed",
50
+ "plan_expired", "plan_already_used", "verification_interrupted", "verification_pending", "verification_rate_limited", "waiting_for_dns",
51
+ "idempotency_conflict",
52
+ "domain_setup_limit", "domain_operation_failed", "invalid_arguments", "authorization_required", "scope_required", "domain_tools_require_build_oauth",
53
+ ]);
package/dist/index.d.ts CHANGED
@@ -32,7 +32,7 @@ export interface PackedArtifactAppBundle {
32
32
  type ToolProgressReporter = (progress: number, message: string) => void | Promise<void>;
33
33
  export declare const DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
34
34
  export declare const BUILD_MCP_SERVER_NAME = "topline-build-stdio";
35
- export declare const HARNESS_MCP_VERSION = "0.6.0";
35
+ export declare const HARNESS_MCP_VERSION = "0.7.0";
36
36
  export declare const DEFAULT_OAUTH_SCOPES: readonly string[];
37
37
  export interface BuildMcpSetupOption {
38
38
  readonly flag: string;
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ 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";
@@ -15,7 +16,7 @@ import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError } fr
15
16
  export const DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
16
17
  const DEFAULT_TIMEOUT_MS = 120_000;
17
18
  export const BUILD_MCP_SERVER_NAME = "topline-build-stdio";
18
- export const HARNESS_MCP_VERSION = "0.6.0";
19
+ export const HARNESS_MCP_VERSION = "0.7.0";
19
20
  export const DEFAULT_OAUTH_SCOPES = Object.freeze(["harness:artifact:read", "harness:artifact:write", "harness:artifact:deploy", "harness:artifact:delete"]);
20
21
  export const BUILD_MCP_SETUP_OPTIONS = Object.freeze([
21
22
  { 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." },
@@ -109,13 +110,46 @@ export function cliInfo(argv) {
109
110
  ].join("\n");
110
111
  }
111
112
  export function createHarnessMcpStdioServer(opts, toolAllowlist) {
113
+ let discoveredGrant = null;
114
+ const grantTag = (stored) => stored?.accessToken && Date.parse(stored.accessTokenExpiresAt ?? "") > Date.now()
115
+ ? JSON.stringify([stored.clientId, stored.resource, [...stored.scopes].sort()]) : null;
112
116
  const allowedTools = toolAllowlist ? new Set(toolAllowlist) : null;
113
117
  const listedTools = () => {
114
118
  const listed = listTools();
115
119
  return allowedTools ? { ...listed, tools: listed.tools.filter((tool) => allowedTools.has(tool.name)) } : listed;
116
120
  };
117
- const mcp = new McpServer({ name: BUILD_MCP_SERVER_NAME, version: HARNESS_MCP_VERSION }, { capabilities: { tools: {} } });
118
- mcp.setRequestHandler(ListToolsRequestSchema, async () => listedTools());
121
+ const mcp = new McpServer({ name: BUILD_MCP_SERVER_NAME, version: HARNESS_MCP_VERSION }, { capabilities: { tools: { listChanged: true } } });
122
+ mcp.setRequestHandler(ListToolsRequestSchema, async () => {
123
+ const listed = listedTools();
124
+ if (mcpSurface(opts) !== "build" || opts.token)
125
+ return { tools: listed.tools.filter(tool => !DOMAIN_FORWARD_TOOLS.has(tool.name)) };
126
+ // Public deployment metadata never initiates OAuth or changes consent.
127
+ // Unknown/old servers fail closed for this default-off family.
128
+ try {
129
+ const metadata = asRecord(await fetchJson({ ...opts, timeoutMs: Math.min(opts.timeoutMs, 5000) }, `${platformBaseUrl(opts)}/mcp/build`, { method: "GET" }));
130
+ const names = new Set(Array.isArray(metadata.tools) ? metadata.tools.map(item => typeof item === "string" ? item : asRecord(item).name) : []);
131
+ const stored = await readStoredOAuthCredentials(opts);
132
+ if (stored?.accessToken && Date.parse(stored.accessTokenExpiresAt ?? "") > Date.now()) {
133
+ const payload = asRecord(await fetchJson({ ...opts, timeoutMs: Math.min(opts.timeoutMs, 5000) }, `${platformBaseUrl(opts)}/mcp/build`, {
134
+ method: "POST", headers: { authorization: `Bearer ${stored.accessToken}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
135
+ body: JSON.stringify({ jsonrpc: "2.0", id: "domain-discovery", method: "tools/list", params: {} }),
136
+ }));
137
+ const remote = asRecord(payload.result).tools;
138
+ if (!Array.isArray(remote))
139
+ throw new Error("domain_discovery_unavailable");
140
+ const contracts = new Map(remote.filter(isRecord).map(tool => [tool.name, tool]));
141
+ discoveredGrant = grantTag(stored);
142
+ return { tools: listed.tools.filter(tool => !DOMAIN_FORWARD_TOOLS.has(tool.name) || (names.has(tool.name) && contracts.has(tool.name)))
143
+ .map(tool => DOMAIN_FORWARD_TOOLS.has(tool.name) ? { ...tool, inputSchema: contracts.get(tool.name).inputSchema } : tool) };
144
+ }
145
+ return { tools: listed.tools.filter(tool => !DOMAIN_FORWARD_TOOLS.has(tool.name) || names.has(tool.name)).map(tool => tool.name === "platform_read_artifact_domains"
146
+ ? { ...tool, inputSchema: { type: "object", additionalProperties: false, properties: { limit: { type: "integer", minimum: 1, maximum: 100 }, cursor: { type: "integer", minimum: 0, maximum: 10000 } } } }
147
+ : tool) };
148
+ }
149
+ catch {
150
+ return { tools: listed.tools.filter(tool => !DOMAIN_FORWARD_TOOLS.has(tool.name)) };
151
+ }
152
+ });
119
153
  mcp.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
120
154
  if (allowedTools && !allowedTools.has(req.params.name)) {
121
155
  throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${req.params.name}`);
@@ -134,6 +168,17 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
134
168
  await sendProgress(extra, 1, 1, "Failed artifact deployment");
135
169
  return structuredToolError(redactSecrets(err instanceof Error ? err.message : String(err), opts));
136
170
  }
171
+ finally {
172
+ if (mcpSurface(opts) === "build" && !opts.token) {
173
+ const currentGrant = grantTag(await readStoredOAuthCredentials(opts));
174
+ if (currentGrant !== discoveredGrant) {
175
+ discoveredGrant = currentGrant;
176
+ // First browser sign-in changes manager-only selector availability.
177
+ // Tell MCP hosts to rediscover before setup status/recovery calls.
178
+ await mcp.sendToolListChanged().catch(() => undefined);
179
+ }
180
+ }
181
+ }
137
182
  });
138
183
  return mcp;
139
184
  }
@@ -197,6 +242,30 @@ export async function callHarnessTool(opts, name, args, hooks) {
197
242
  result = toolResult(await initArtifactApp(opts, input));
198
243
  break;
199
244
  default:
245
+ if (DOMAIN_FORWARD_TOOLS.has(name)) {
246
+ try {
247
+ if (mcpSurface(opts) !== "build" || opts.token)
248
+ throw new Error("domain_tools_require_build_oauth");
249
+ result = toolResult(await callHostedBuildTool(opts, name, input));
250
+ }
251
+ catch (error) {
252
+ const message = error instanceof Error ? error.message : "";
253
+ const code = /^platform_harness_http_error:401(?::|$)/.test(message) ? "authorization_required"
254
+ : [...DOMAIN_ERROR_CODES].find(candidate => new RegExp(`(?:^|[^a-z_])${candidate}(?:$|[^a-z_])`).test(message)) ?? "domain_result_unknown";
255
+ result = structuredToolError(code);
256
+ const key = typeof input.idempotencyKey === "string" ? input.idempotencyKey : undefined;
257
+ const recovery = key && name === "platform_apply_artifact_address"
258
+ ? { tool: "platform_get_artifact_address", planId: input.planId, artifactIdRequiredFromSavedPlan: true, selector: { idempotencyKey: key } }
259
+ : key && ["platform_request_artifact_domain", "platform_verify_artifact_domain"].includes(name)
260
+ ? { tool: "platform_read_artifact_domains", arguments: { recovery: { kind: name === "platform_request_artifact_domain" ? "request" : "verify", idempotencyKey: key } }, domainId: input.domainId }
261
+ : undefined;
262
+ if (recovery) {
263
+ result.structuredContent.error.recovery = recovery;
264
+ result.content = [{ type: "text", text: JSON.stringify(result.structuredContent, null, 2) }];
265
+ }
266
+ }
267
+ break;
268
+ }
200
269
  if (EXTERNAL_BUILD_FORWARD_TOOLS.has(name)) {
201
270
  if (mcpSurface(opts) !== "build")
202
271
  throw new Error("external_session_requires_build_surface");
@@ -1376,7 +1445,8 @@ const BUILD_MCP_TOOLS = [
1376
1445
  required: ["ok", "deleted", "artifactId"]
1377
1446
  }
1378
1447
  },
1379
- ...externalBuildHelperTools(mcpToolAnnotations)
1448
+ ...externalBuildHelperTools(mcpToolAnnotations),
1449
+ ...domainHelperTools(mcpToolAnnotations)
1380
1450
  ].map(withRecoveryOutputSchema);
1381
1451
  export function listTools() {
1382
1452
  // Preserve the original tools/list isolation boundary: callers must not be
@@ -1403,7 +1473,8 @@ function withRecoveryOutputSchema(value) {
1403
1473
  code: { type: "string" },
1404
1474
  message: { type: "string" },
1405
1475
  retryable: { type: "boolean" },
1406
- recoveryAction: { type: "string" }
1476
+ recoveryAction: { type: "string" },
1477
+ ...(DOMAIN_FORWARD_TOOLS.has(tool.name) ? { recovery: { type: "object", additionalProperties: true } } : {})
1407
1478
  },
1408
1479
  required: ["code", "message", "retryable", "recoveryAction"],
1409
1480
  additionalProperties: false
@@ -1442,6 +1513,9 @@ function toolError(message) {
1442
1513
  return structuredToolError(message);
1443
1514
  }
1444
1515
  const BUILD_MCP_RECOVERY_ERROR_VALUES = {
1516
+ ...Object.fromEntries([...DOMAIN_ERROR_CODES].map(code => [code, { retryable: false,
1517
+ 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." }])),
1518
+ 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
1519
  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
1520
  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
1521
  platform_mcp_tool_error: { retryable: false, recoveryAction: "Read the returned error code, correct the request or OAuth scopes, then retry." },
@@ -1469,6 +1543,8 @@ function structuredToolError(message) {
1469
1543
  function recoveryErrorCode(message) {
1470
1544
  if (/^platform_harness_http_error:401(?::|$)/.test(message))
1471
1545
  return "authorization_required";
1546
+ if (DOMAIN_ERROR_CODES.has(message) || message === "domain_result_unknown")
1547
+ return message;
1472
1548
  const known = [
1473
1549
  "artifact_delete_plan_stale",
1474
1550
  "artifact_deploy_wait_timeout",