@duct-sdk/sdk 0.5.13 → 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 +61 -0
- package/README.md +418 -264
- package/TOKEN_SPEC.md +243 -243
- package/dist/cli/action-confusion-format.d.ts +17 -0
- package/dist/cli/action-confusion-format.js +24 -0
- package/dist/cli/add.d.ts +7 -0
- package/dist/cli/add.js +152 -0
- package/dist/cli/agent-prompt.d.ts +3 -0
- package/dist/cli/agent-prompt.js +39 -0
- package/dist/cli/api-sources.d.ts +26 -0
- package/dist/cli/api-sources.js +222 -0
- package/dist/cli/cloud.d.ts +162 -0
- package/dist/cli/cloud.js +306 -0
- package/dist/cli/config-loader.d.ts +14 -0
- package/dist/cli/config-loader.js +56 -7
- package/dist/cli/device-login.d.ts +17 -0
- package/dist/cli/device-login.js +75 -0
- package/dist/cli/drift.js +6 -6
- package/dist/cli/generators/any-stack.d.ts +3 -0
- package/dist/cli/generators/any-stack.js +97 -0
- package/dist/cli/generators/config.js +3 -2
- package/dist/cli/generators/receiver.js +7 -7
- package/dist/cli/generators/shell.js +12 -12
- package/dist/cli/generators/token-route.js +245 -245
- package/dist/cli/generators/wiring-snippets.d.ts +0 -14
- package/dist/cli/generators/wiring-snippets.js +188 -305
- package/dist/cli/index.js +396 -611
- package/dist/cli/mcp-core.d.ts +42 -0
- package/dist/cli/mcp-core.js +161 -0
- package/dist/cli/mcp-setup.d.ts +4 -0
- package/dist/cli/mcp-setup.js +352 -0
- package/dist/cli/mcp.d.ts +2 -0
- package/dist/cli/mcp.js +457 -0
- package/dist/cli/migrate-intershell.js +5 -5
- package/dist/cli/policy-defaults.d.ts +37 -0
- package/dist/cli/policy-defaults.js +127 -0
- package/dist/cli/policy-replay-format.d.ts +9 -0
- package/dist/cli/policy-replay-format.js +46 -0
- package/dist/cli/processors/integration-audit.js +2 -2
- package/dist/cli/processors/openapi-parser.d.ts +5 -0
- package/dist/cli/processors/openapi-parser.js +8 -3
- package/dist/cli/project-loader.d.ts +58 -0
- package/dist/cli/project-loader.js +198 -0
- package/dist/cli/project-writer.d.ts +23 -0
- package/dist/cli/project-writer.js +171 -0
- package/dist/cli/push.d.ts +43 -0
- package/dist/cli/push.js +308 -0
- package/dist/cli/safety-checks.d.ts +9 -0
- package/dist/cli/safety-checks.js +29 -0
- package/dist/cli/setup.d.ts +20 -0
- package/dist/cli/setup.js +349 -0
- package/dist/cli/shell-name.d.ts +8 -0
- package/dist/cli/shell-name.js +29 -0
- package/dist/cli/shells.d.ts +22 -0
- package/dist/cli/shells.js +122 -0
- package/dist/cli/split.d.ts +7 -0
- package/dist/cli/split.js +71 -0
- package/dist/cli/sync.d.ts +25 -0
- package/dist/cli/sync.js +120 -0
- package/dist/cli/test-runner.d.ts +21 -0
- package/dist/cli/test-runner.js +281 -0
- package/dist/core/compile.d.ts +43 -0
- package/dist/core/compile.js +512 -0
- package/dist/core/config.d.ts +538 -19
- package/dist/core/config.js +22 -14
- package/dist/core/login-handoff.d.ts +1 -1
- package/dist/core/login-handoff.js +1 -1
- package/dist/core/project.d.ts +1864 -0
- package/dist/core/project.js +291 -0
- package/dist/core/readiness-checks.js +2 -2
- package/dist/core/types.d.ts +10 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/project.d.ts +4 -0
- package/dist/project.js +8 -0
- package/dist/server.d.ts +2 -0
- package/dist/server.js +1 -0
- package/package.json +94 -95
- package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
- package/dist/adapters/react/page-context-guard.test.js +0 -15
- package/dist/cli/agents/api-agent.d.ts +0 -22
- package/dist/cli/agents/api-agent.js +0 -761
- package/dist/cli/agents/auth-agent.d.ts +0 -7
- package/dist/cli/agents/auth-agent.js +0 -212
- package/dist/cli/agents/deeplink-agent.d.ts +0 -6
- package/dist/cli/agents/deeplink-agent.js +0 -285
- package/dist/cli/agents/llm.d.ts +0 -33
- package/dist/cli/agents/llm.js +0 -309
- package/dist/cli/agents/pipeline.d.ts +0 -72
- package/dist/cli/agents/pipeline.js +0 -421
- package/dist/cli/agents/reviewer-agent.d.ts +0 -13
- package/dist/cli/agents/reviewer-agent.js +0 -450
- package/dist/cli/agents/route-agent.d.ts +0 -17
- package/dist/cli/agents/route-agent.js +0 -383
- package/dist/cli/config-loader.test.d.ts +0 -1
- package/dist/cli/config-loader.test.js +0 -63
- package/dist/cli/detectors/topology.d.ts +0 -46
- package/dist/cli/detectors/topology.js +0 -417
- package/dist/cli/generators/config.test.d.ts +0 -1
- package/dist/cli/generators/config.test.js +0 -222
- package/dist/cli/generators/shell.test.d.ts +0 -1
- package/dist/cli/generators/shell.test.js +0 -73
- package/dist/cli/generators/token-route.test.d.ts +0 -1
- package/dist/cli/generators/token-route.test.js +0 -53
- package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
- package/dist/cli/generators/wiring-snippets.test.js +0 -80
- package/dist/cli/init.d.ts +0 -32
- package/dist/cli/init.js +0 -1336
- package/dist/cli/manifest-diff.test.d.ts +0 -1
- package/dist/cli/manifest-diff.test.js +0 -144
- package/dist/cli/processors/curl-parser.test.d.ts +0 -1
- package/dist/cli/processors/curl-parser.test.js +0 -24
- package/dist/cli/processors/integration-audit.test.d.ts +0 -1
- package/dist/cli/processors/integration-audit.test.js +0 -154
- package/dist/cli/processors/postprocess.d.ts +0 -22
- package/dist/cli/processors/postprocess.js +0 -107
- package/dist/cli/processors/prisma-parser.d.ts +0 -35
- package/dist/cli/processors/prisma-parser.js +0 -117
- package/dist/cli/processors/verify-discovery.d.ts +0 -33
- package/dist/cli/processors/verify-discovery.js +0 -193
- package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
- package/dist/cli/processors/verify-discovery.test.js +0 -153
- package/dist/cli/processors/zod-extractor.d.ts +0 -27
- package/dist/cli/processors/zod-extractor.js +0 -153
- package/dist/cli/prompts/review.d.ts +0 -61
- package/dist/cli/prompts/review.js +0 -410
- package/dist/cli/selectors/express.d.ts +0 -12
- package/dist/cli/selectors/express.js +0 -117
- package/dist/cli/selectors/fastapi.d.ts +0 -12
- package/dist/cli/selectors/fastapi.js +0 -122
- package/dist/cli/selectors/generic.d.ts +0 -10
- package/dist/cli/selectors/generic.js +0 -74
- package/dist/cli/selectors/index.d.ts +0 -37
- package/dist/cli/selectors/index.js +0 -315
- package/dist/cli/selectors/next.d.ts +0 -12
- package/dist/cli/selectors/next.js +0 -130
- package/dist/core/config-policy.test.d.ts +0 -1
- package/dist/core/config-policy.test.js +0 -101
- package/dist/core/config-roundtrip.test.d.ts +0 -1
- package/dist/core/config-roundtrip.test.js +0 -180
- package/dist/core/endpoint-guard.test.d.ts +0 -1
- package/dist/core/endpoint-guard.test.js +0 -57
- package/dist/core/env-diagnostics.test.d.ts +0 -1
- package/dist/core/env-diagnostics.test.js +0 -31
- package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
- package/dist/core/evidence-bundle.conformance.test.js +0 -110
- package/dist/core/evidence-bundle.test.d.ts +0 -1
- package/dist/core/evidence-bundle.test.js +0 -58
- package/dist/core/invariants.test.d.ts +0 -1
- package/dist/core/invariants.test.js +0 -217
- package/dist/core/login-handoff.test.d.ts +0 -1
- package/dist/core/login-handoff.test.js +0 -31
- package/dist/core/profile.test.d.ts +0 -1
- package/dist/core/profile.test.js +0 -95
- package/dist/core/readiness-checks.test.d.ts +0 -1
- package/dist/core/readiness-checks.test.js +0 -106
- package/dist/core/receipt.test.d.ts +0 -1
- package/dist/core/receipt.test.js +0 -75
- package/dist/core/sdk-entrypoint.test.d.ts +0 -1
- package/dist/core/sdk-entrypoint.test.js +0 -8
- package/dist/core/side-effects-review.test.d.ts +0 -1
- package/dist/core/side-effects-review.test.js +0 -28
- package/dist/core/token.conformance.test.d.ts +0 -1
- package/dist/core/token.conformance.test.js +0 -43
- package/dist/core/token.test.d.ts +0 -1
- package/dist/core/token.test.js +0 -66
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export type JsonRpcId = string | number | null;
|
|
2
|
+
export interface ToolResult {
|
|
3
|
+
content: Array<{
|
|
4
|
+
type: "text";
|
|
5
|
+
text: string;
|
|
6
|
+
}>;
|
|
7
|
+
structuredContent?: Record<string, unknown>;
|
|
8
|
+
isError?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface ToolDefinition {
|
|
11
|
+
name: string;
|
|
12
|
+
title: string;
|
|
13
|
+
description: string;
|
|
14
|
+
inputSchema: Record<string, unknown>;
|
|
15
|
+
annotations: Record<string, boolean>;
|
|
16
|
+
run: (args: Record<string, unknown>) => Promise<ToolResult>;
|
|
17
|
+
}
|
|
18
|
+
export interface PromptDefinition {
|
|
19
|
+
name: string;
|
|
20
|
+
title: string;
|
|
21
|
+
description: string;
|
|
22
|
+
text: () => string;
|
|
23
|
+
}
|
|
24
|
+
export interface McpServerConfig {
|
|
25
|
+
name: string;
|
|
26
|
+
title: string;
|
|
27
|
+
version: string;
|
|
28
|
+
instructions: string;
|
|
29
|
+
tools: ToolDefinition[];
|
|
30
|
+
prompts?: PromptDefinition[];
|
|
31
|
+
}
|
|
32
|
+
/** Thrown by a tool for bad arguments; reported to the assistant as a tool error, not a crash. */
|
|
33
|
+
export declare class InvalidParams extends Error {
|
|
34
|
+
}
|
|
35
|
+
export declare function text(value: string, structured?: Record<string, unknown>, isError?: boolean): ToolResult;
|
|
36
|
+
export declare function looksLikeRepo(dir: string): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Short fingerprint of what a preview showed. A confirm call must echo it, so what is saved is
|
|
39
|
+
* exactly what the developer approved (keys sorted, so argument order does not matter).
|
|
40
|
+
*/
|
|
41
|
+
export declare function previewToken(value: unknown): string;
|
|
42
|
+
export declare function runStdioServer(config: McpServerConfig): Promise<void>;
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// Minimal MCP server over stdio (newline-delimited JSON-RPC 2.0), shared by
|
|
3
|
+
// `duct mcp` (onboarding) and `duct mcp-setup` (dashboard setup). No dependencies.
|
|
4
|
+
// ============================================================
|
|
5
|
+
import { createHash } from "crypto";
|
|
6
|
+
import { existsSync, readdirSync } from "fs";
|
|
7
|
+
import * as path from "path";
|
|
8
|
+
import { createInterface } from "readline";
|
|
9
|
+
const SUPPORTED_PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
|
|
10
|
+
/** Thrown by a tool for bad arguments; reported to the assistant as a tool error, not a crash. */
|
|
11
|
+
export class InvalidParams extends Error {
|
|
12
|
+
}
|
|
13
|
+
export function text(value, structured, isError = false) {
|
|
14
|
+
return {
|
|
15
|
+
content: [{ type: "text", text: value }],
|
|
16
|
+
...(structured ? { structuredContent: structured } : {}),
|
|
17
|
+
...(isError ? { isError: true } : {}),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/** Files that mark a repository root, across stacks. */
|
|
21
|
+
const REPO_MARKERS = [
|
|
22
|
+
".git", "package.json", "pyproject.toml", "requirements.txt", "go.mod", "Gemfile", "pom.xml",
|
|
23
|
+
"build.gradle", "build.gradle.kts", "composer.json", "Cargo.toml", "mix.exs", "duct", "duct.config.ts",
|
|
24
|
+
];
|
|
25
|
+
export function looksLikeRepo(dir) {
|
|
26
|
+
if (REPO_MARKERS.some((marker) => existsSync(path.join(dir, marker))))
|
|
27
|
+
return true;
|
|
28
|
+
try {
|
|
29
|
+
return readdirSync(dir).some((name) => name.endsWith(".csproj") || name.endsWith(".sln"));
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Short fingerprint of what a preview showed. A confirm call must echo it, so what is saved is
|
|
37
|
+
* exactly what the developer approved (keys sorted, so argument order does not matter).
|
|
38
|
+
*/
|
|
39
|
+
export function previewToken(value) {
|
|
40
|
+
const sort = (v) => Array.isArray(v)
|
|
41
|
+
? v.map(sort)
|
|
42
|
+
: v && typeof v === "object"
|
|
43
|
+
? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sort(v[k])]))
|
|
44
|
+
: v;
|
|
45
|
+
return createHash("sha256").update(JSON.stringify(sort(value))).digest("hex").slice(0, 16);
|
|
46
|
+
}
|
|
47
|
+
function send(message) {
|
|
48
|
+
process.stdout.write(`${JSON.stringify(message)}\n`);
|
|
49
|
+
}
|
|
50
|
+
function reply(id, result) {
|
|
51
|
+
send({ jsonrpc: "2.0", id, result });
|
|
52
|
+
}
|
|
53
|
+
function replyError(id, code, message) {
|
|
54
|
+
send({ jsonrpc: "2.0", id, error: { code, message } });
|
|
55
|
+
}
|
|
56
|
+
async function handle(config, message) {
|
|
57
|
+
const { id, method } = message;
|
|
58
|
+
const isRequest = id !== undefined && id !== null;
|
|
59
|
+
const params = message.params ?? {};
|
|
60
|
+
const prompts = config.prompts ?? [];
|
|
61
|
+
switch (method) {
|
|
62
|
+
case "initialize": {
|
|
63
|
+
const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : "";
|
|
64
|
+
reply(id ?? null, {
|
|
65
|
+
protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : SUPPORTED_PROTOCOL_VERSIONS[0],
|
|
66
|
+
capabilities: {
|
|
67
|
+
tools: { listChanged: false },
|
|
68
|
+
...(prompts.length ? { prompts: { listChanged: false } } : {}),
|
|
69
|
+
},
|
|
70
|
+
serverInfo: { name: config.name, title: config.title, version: config.version },
|
|
71
|
+
instructions: config.instructions,
|
|
72
|
+
});
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
case "ping":
|
|
76
|
+
if (isRequest)
|
|
77
|
+
reply(id, {});
|
|
78
|
+
return;
|
|
79
|
+
case "tools/list":
|
|
80
|
+
reply(id ?? null, {
|
|
81
|
+
tools: config.tools.map(({ name, title, description, inputSchema, annotations }) => ({
|
|
82
|
+
name,
|
|
83
|
+
title,
|
|
84
|
+
description,
|
|
85
|
+
inputSchema,
|
|
86
|
+
annotations: { title, ...annotations },
|
|
87
|
+
})),
|
|
88
|
+
});
|
|
89
|
+
return;
|
|
90
|
+
case "tools/call": {
|
|
91
|
+
const tool = config.tools.find((t) => t.name === params.name);
|
|
92
|
+
if (!tool) {
|
|
93
|
+
replyError(id ?? null, -32602, `Unknown tool: ${String(params.name)}`);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const args = (params.arguments && typeof params.arguments === "object" ? params.arguments : {});
|
|
97
|
+
try {
|
|
98
|
+
reply(id ?? null, await tool.run(args));
|
|
99
|
+
}
|
|
100
|
+
catch (err) {
|
|
101
|
+
if (err instanceof InvalidParams)
|
|
102
|
+
reply(id ?? null, text(err.message, undefined, true));
|
|
103
|
+
else
|
|
104
|
+
reply(id ?? null, text(`${tool.name} failed: ${err instanceof Error ? err.message : String(err)}`, undefined, true));
|
|
105
|
+
}
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
case "prompts/list":
|
|
109
|
+
reply(id ?? null, { prompts: prompts.map(({ name, title, description }) => ({ name, title, description })) });
|
|
110
|
+
return;
|
|
111
|
+
case "prompts/get": {
|
|
112
|
+
const prompt = prompts.find((p) => p.name === params.name);
|
|
113
|
+
if (!prompt) {
|
|
114
|
+
replyError(id ?? null, -32602, `Unknown prompt: ${String(params.name)}`);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
reply(id ?? null, {
|
|
118
|
+
description: prompt.description,
|
|
119
|
+
messages: [{ role: "user", content: { type: "text", text: prompt.text() } }],
|
|
120
|
+
});
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
default:
|
|
124
|
+
// Notifications (initialized, cancelled, …) need no answer; unknown requests get one.
|
|
125
|
+
if (isRequest)
|
|
126
|
+
replyError(id, -32601, `Method not found: ${String(method)}`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
export async function runStdioServer(config) {
|
|
130
|
+
// stdout carries the protocol. Anything a library logs goes to stderr instead.
|
|
131
|
+
const toStderr = (...args) => console.error(...args);
|
|
132
|
+
console.log = toStderr;
|
|
133
|
+
console.info = toStderr;
|
|
134
|
+
console.warn = toStderr;
|
|
135
|
+
const pending = new Set();
|
|
136
|
+
const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
137
|
+
for await (const line of lines) {
|
|
138
|
+
if (!line.trim())
|
|
139
|
+
continue;
|
|
140
|
+
let message;
|
|
141
|
+
try {
|
|
142
|
+
message = JSON.parse(line);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
replyError(null, -32700, "Parse error");
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (!message || typeof message !== "object" || Array.isArray(message)) {
|
|
149
|
+
replyError(null, -32600, "Invalid request");
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
// Requests run concurrently (a slow check must not block ping); replies carry their id.
|
|
153
|
+
const task = handle(config, message).catch((err) => {
|
|
154
|
+
if (message.id !== undefined && message.id !== null)
|
|
155
|
+
replyError(message.id, -32603, err instanceof Error ? err.message : String(err));
|
|
156
|
+
});
|
|
157
|
+
pending.add(task);
|
|
158
|
+
task.finally(() => pending.delete(task));
|
|
159
|
+
}
|
|
160
|
+
await Promise.all(pending);
|
|
161
|
+
}
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct-sdk/sdk — dashboard setup MCP server
|
|
3
|
+
//
|
|
4
|
+
// npx @duct-sdk/sdk mcp-setup
|
|
5
|
+
//
|
|
6
|
+
// A second, separate server so a coding assistant can finish the dashboard side of a shell
|
|
7
|
+
// (webhooks, sign-in links, partner profiles) and check every connection, without loading the
|
|
8
|
+
// onboarding tools into its context. Four small tools, short answers.
|
|
9
|
+
//
|
|
10
|
+
// Secrets never pass through the conversation: a generated webhook signing secret is written to
|
|
11
|
+
// a git-ignored .env.duct.* file and only its file path is returned.
|
|
12
|
+
// ============================================================
|
|
13
|
+
import { randomBytes } from "crypto";
|
|
14
|
+
import { existsSync, readFileSync } from "fs";
|
|
15
|
+
import * as fs from "fs/promises";
|
|
16
|
+
import * as path from "path";
|
|
17
|
+
import { fileURLToPath } from "url";
|
|
18
|
+
import { CloudError, createPartnerProfile, getShellWebhooks, listAccountShells, listPartnerProfiles, patchShellWebhooks, readAuth, resolveApiKey, runConnectionChecks, } from "./cloud.js";
|
|
19
|
+
import { InvalidParams, looksLikeRepo, previewToken, runStdioServer, text } from "./mcp-core.js";
|
|
20
|
+
import { ensureGitIgnored } from "./shells.js";
|
|
21
|
+
export const SETUP_SERVER_NAME = "duct-setup";
|
|
22
|
+
const VERSION = JSON.parse(readFileSync(path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../package.json"), "utf-8")).version;
|
|
23
|
+
const SIGN_IN = "Not signed in to Duct. Ask the developer to run `npx @duct-sdk/sdk login` in their own terminal (it opens the browser). Then retry.";
|
|
24
|
+
const INSTRUCTIONS = `Finishes a Duct shell's dashboard setup and checks its connections.
|
|
25
|
+
Use setup_status first. Change settings with setup_configure or setup_partner: call without confirm to get a preview and preview_token, show it to the developer, then call again with the same arguments, confirm: true and that preview_token. setup_check calls every URL the way Duct does in production and says what to fix. Never ask for keys or secrets in chat.`;
|
|
26
|
+
const WEBHOOK_FIELDS = {
|
|
27
|
+
event_stream: "eventStream",
|
|
28
|
+
deeplink_callback: "deeplinkCallback",
|
|
29
|
+
identity_url: "identityUrl",
|
|
30
|
+
};
|
|
31
|
+
const FIELD_LABEL = {
|
|
32
|
+
event_stream: "Event stream (signed webhook)",
|
|
33
|
+
deeplink_callback: "Deep link webhook (signed)",
|
|
34
|
+
identity_url: "Sign-in page for agent access",
|
|
35
|
+
};
|
|
36
|
+
// ----------------------------------------------------------------
|
|
37
|
+
// Helpers
|
|
38
|
+
// ----------------------------------------------------------------
|
|
39
|
+
async function session() {
|
|
40
|
+
const auth = await readAuth();
|
|
41
|
+
const apiKey = resolveApiKey(auth);
|
|
42
|
+
return apiKey ? { auth, apiKey } : null;
|
|
43
|
+
}
|
|
44
|
+
function str(args, key) {
|
|
45
|
+
const v = args[key];
|
|
46
|
+
if (v === undefined || v === null)
|
|
47
|
+
return undefined;
|
|
48
|
+
if (typeof v !== "string")
|
|
49
|
+
throw new InvalidParams(`${key} must be a string`);
|
|
50
|
+
return v.trim();
|
|
51
|
+
}
|
|
52
|
+
/** Accept a shell ID or its name (prod, staging, checkout-prod, ...). */
|
|
53
|
+
function pickShell(shells, wanted) {
|
|
54
|
+
if (!wanted) {
|
|
55
|
+
if (shells.length === 1)
|
|
56
|
+
return shells[0];
|
|
57
|
+
throw new InvalidParams(shells.length === 0
|
|
58
|
+
? "This account has no shells yet. Create one with the duct-onboarding server or `npx @duct-sdk/sdk shells create`."
|
|
59
|
+
: `Pass shell: one of ${shells.map((s) => s.environment).join(", ")}.`);
|
|
60
|
+
}
|
|
61
|
+
const found = shells.find((s) => s.id === wanted || s.environment === wanted.toLowerCase());
|
|
62
|
+
if (!found)
|
|
63
|
+
throw new InvalidParams(`No shell "${wanted}". Shells: ${shells.map((s) => s.environment).join(", ") || "none"}.`);
|
|
64
|
+
return found;
|
|
65
|
+
}
|
|
66
|
+
function compactCheck(r) {
|
|
67
|
+
return r.ok
|
|
68
|
+
? { target: r.target, ok: true, status: r.status, ms: r.latency_ms }
|
|
69
|
+
: r.configured
|
|
70
|
+
? { target: r.target, ok: false, problem: r.problem, fix: r.fix }
|
|
71
|
+
: { target: r.target, set: false };
|
|
72
|
+
}
|
|
73
|
+
function checkLines(results) {
|
|
74
|
+
return results
|
|
75
|
+
.map((r) => !r.configured
|
|
76
|
+
? `- ${r.label}: not set`
|
|
77
|
+
: r.ok
|
|
78
|
+
? `- ${r.label}: connected (${r.status ?? "ok"}, ${r.latency_ms ?? "?"} ms)`
|
|
79
|
+
: `- ${r.label}: FAILED. ${[r.problem, r.fix].filter(Boolean).join(" ")}`)
|
|
80
|
+
.join("\n");
|
|
81
|
+
}
|
|
82
|
+
function isHttpUrl(v) {
|
|
83
|
+
try {
|
|
84
|
+
const u = new URL(v);
|
|
85
|
+
return u.protocol === "https:" || u.protocol === "http:";
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** Upsert DUCT_WEBHOOK_SECRET in .env.duct.<shell> (git-ignored, mode 600). Returns the path. */
|
|
92
|
+
async function saveWebhookSecret(dir, shell, secret) {
|
|
93
|
+
const file = path.join(dir, `.env.duct.${shell.environment}`);
|
|
94
|
+
await ensureGitIgnored(dir);
|
|
95
|
+
const current = existsSync(file) ? await fs.readFile(file, "utf-8") : `# Duct shell ${shell.id}. Keep this file out of version control.\n`;
|
|
96
|
+
const line = `DUCT_WEBHOOK_SECRET=${secret}`;
|
|
97
|
+
const next = /^DUCT_WEBHOOK_SECRET=.*$/m.test(current)
|
|
98
|
+
? current.replace(/^DUCT_WEBHOOK_SECRET=.*$/m, line)
|
|
99
|
+
: `${current}${current.endsWith("\n") ? "" : "\n"}${line}\n`;
|
|
100
|
+
await fs.writeFile(file, next, { encoding: "utf-8", mode: 0o600 });
|
|
101
|
+
return file;
|
|
102
|
+
}
|
|
103
|
+
async function withSession(fn) {
|
|
104
|
+
const s = await session();
|
|
105
|
+
if (!s)
|
|
106
|
+
return text(SIGN_IN, { signed_in: false }, true);
|
|
107
|
+
try {
|
|
108
|
+
return await fn(s);
|
|
109
|
+
}
|
|
110
|
+
catch (err) {
|
|
111
|
+
if (err instanceof InvalidParams)
|
|
112
|
+
throw err;
|
|
113
|
+
if (err instanceof CloudError)
|
|
114
|
+
return text(err.message, { error: err.code ?? "cloud_error" }, true);
|
|
115
|
+
throw err;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const SHELL_ARG = { type: "string", description: "Shell ID or name (prod, staging, ...). Optional with one shell." };
|
|
119
|
+
// ----------------------------------------------------------------
|
|
120
|
+
// Tools
|
|
121
|
+
// ----------------------------------------------------------------
|
|
122
|
+
const statusTool = {
|
|
123
|
+
name: "setup_status",
|
|
124
|
+
title: "Setup status",
|
|
125
|
+
description: "What is set up for a shell (webhooks, sign-in links, signing secret, partner profiles) and what to do next.",
|
|
126
|
+
inputSchema: { type: "object", properties: { shell: SHELL_ARG }, additionalProperties: false },
|
|
127
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
128
|
+
async run(args) {
|
|
129
|
+
return withSession(async ({ auth, apiKey }) => {
|
|
130
|
+
const shells = await listAccountShells(auth, apiKey);
|
|
131
|
+
const shell = pickShell(shells, str(args, "shell"));
|
|
132
|
+
const [webhooks, profiles] = await Promise.all([
|
|
133
|
+
getShellWebhooks(auth, apiKey, shell.id),
|
|
134
|
+
listPartnerProfiles(auth, apiKey, shell.id).catch(() => []),
|
|
135
|
+
]);
|
|
136
|
+
const set = {
|
|
137
|
+
event_stream: webhooks.eventStream || null,
|
|
138
|
+
deeplink_callback: webhooks.deeplinkCallback || null,
|
|
139
|
+
identity_url: webhooks.identityUrl || null,
|
|
140
|
+
signing_secret: webhooks.secretConfigured,
|
|
141
|
+
};
|
|
142
|
+
const next = [];
|
|
143
|
+
if ((set.event_stream || set.deeplink_callback) && !set.signing_secret)
|
|
144
|
+
next.push("Generate a signing secret (setup_configure generate_signing_secret: true).");
|
|
145
|
+
if (!set.identity_url)
|
|
146
|
+
next.push("Agents acting for signed-in people need identity_url (the product's sign-in page for Duct).");
|
|
147
|
+
if (profiles.length === 0)
|
|
148
|
+
next.push("Create a partner profile if outside agents will use this shell (setup_partner).");
|
|
149
|
+
next.push("Run setup_check to confirm every URL answers.");
|
|
150
|
+
const summary = `${shell.environment} (${shell.id})\n` +
|
|
151
|
+
Object.keys(WEBHOOK_FIELDS)
|
|
152
|
+
.map((k) => `- ${FIELD_LABEL[k]}: ${set[k] ?? "not set"}`)
|
|
153
|
+
.join("\n") +
|
|
154
|
+
`\n- Signing secret: ${set.signing_secret ? "set" : "not set"}\n- Partner profiles: ${profiles.length}\nNext:\n${next.map((n) => `- ${n}`).join("\n")}`;
|
|
155
|
+
return text(summary, { shell_id: shell.id, shell: shell.environment, ...set, partner_profiles: profiles.map((p) => p.name), next });
|
|
156
|
+
});
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
const configureTool = {
|
|
160
|
+
name: "setup_configure",
|
|
161
|
+
title: "Configure shell links",
|
|
162
|
+
description: "Set webhook and sign-in URLs, or generate a signing secret. Without confirm it previews and returns preview_token; confirm: true with that token saves and checks the changed URLs.",
|
|
163
|
+
inputSchema: {
|
|
164
|
+
type: "object",
|
|
165
|
+
properties: {
|
|
166
|
+
shell: SHELL_ARG,
|
|
167
|
+
event_stream: { type: "string", description: "HTTPS URL that receives signed events. Empty string clears it." },
|
|
168
|
+
deeplink_callback: { type: "string", description: "HTTPS URL that receives signed deep link events." },
|
|
169
|
+
identity_url: { type: "string", description: "Product page Duct sends people to so they sign in before approving an agent." },
|
|
170
|
+
generate_signing_secret: { type: "boolean", description: "Create a new signing secret; it is saved to a git-ignored .env.duct.<shell> file." },
|
|
171
|
+
confirm: { type: "boolean", description: "true only after the developer approved the preview." },
|
|
172
|
+
preview_token: { type: "string", description: "The preview_token from the preview the developer approved." },
|
|
173
|
+
project_dir: { type: "string", description: "Repository root for the secret file, when the server does not run inside it." },
|
|
174
|
+
},
|
|
175
|
+
additionalProperties: false,
|
|
176
|
+
},
|
|
177
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
178
|
+
async run(args) {
|
|
179
|
+
return withSession(async ({ auth, apiKey }) => {
|
|
180
|
+
const shells = await listAccountShells(auth, apiKey);
|
|
181
|
+
const shell = pickShell(shells, str(args, "shell"));
|
|
182
|
+
const patch = {};
|
|
183
|
+
for (const key of Object.keys(WEBHOOK_FIELDS)) {
|
|
184
|
+
const v = str(args, key);
|
|
185
|
+
if (v === undefined)
|
|
186
|
+
continue;
|
|
187
|
+
if (v !== "" && !isHttpUrl(v))
|
|
188
|
+
throw new InvalidParams(`${key} must be a full http(s) URL.`);
|
|
189
|
+
patch[WEBHOOK_FIELDS[key]] = v;
|
|
190
|
+
}
|
|
191
|
+
const rotate = args.generate_signing_secret === true;
|
|
192
|
+
if (Object.keys(patch).length === 0 && !rotate)
|
|
193
|
+
throw new InvalidParams("Nothing to change. Pass a URL field or generate_signing_secret: true.");
|
|
194
|
+
const current = await getShellWebhooks(auth, apiKey, shell.id);
|
|
195
|
+
const changes = Object.keys(WEBHOOK_FIELDS)
|
|
196
|
+
.filter((k) => patch[WEBHOOK_FIELDS[k]] !== undefined)
|
|
197
|
+
.map((k) => ({ field: k, from: current[WEBHOOK_FIELDS[k]] || null, to: patch[WEBHOOK_FIELDS[k]] || null }));
|
|
198
|
+
if (rotate)
|
|
199
|
+
changes.push({ field: "signing_secret", from: current.secretConfigured ? "set" : null, to: "new secret" });
|
|
200
|
+
const token = previewToken({ shell: shell.id, patch, rotate });
|
|
201
|
+
// Where a new secret will be written, decided before anything is saved.
|
|
202
|
+
let secretDir;
|
|
203
|
+
if (rotate) {
|
|
204
|
+
const explicit = str(args, "project_dir");
|
|
205
|
+
secretDir = path.resolve(explicit || process.cwd());
|
|
206
|
+
if (!explicit && !looksLikeRepo(secretDir)) {
|
|
207
|
+
throw new InvalidParams(`The server is running in ${secretDir}, which does not look like a repository. Call again with project_dir set to the repository root so the secret file lands there.`);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (args.confirm !== true) {
|
|
211
|
+
const lines = changes.map((c) => `- ${c.field}: ${c.from ?? "not set"} -> ${c.to ?? "cleared"}`).join("\n");
|
|
212
|
+
const warn = rotate && current.secretConfigured ? "\nThe current signing secret stops working immediately; the product must load the new one." : "";
|
|
213
|
+
return text(`Preview for ${shell.environment}:\n${lines}${warn}\nShow this to the developer. After they approve, call again with the same arguments, confirm: true and preview_token: "${token}".`, { shell_id: shell.id, preview: changes, preview_token: token, confirmed: false });
|
|
214
|
+
}
|
|
215
|
+
if (str(args, "preview_token") !== token) {
|
|
216
|
+
throw new InvalidParams("preview_token does not match these changes. Preview again, show the developer, then confirm with the new token.");
|
|
217
|
+
}
|
|
218
|
+
let secretFile;
|
|
219
|
+
if (rotate && secretDir) {
|
|
220
|
+
const secret = `whsec_${randomBytes(24).toString("hex")}`;
|
|
221
|
+
secretFile = await saveWebhookSecret(secretDir, shell, secret);
|
|
222
|
+
patch.secret = secret;
|
|
223
|
+
}
|
|
224
|
+
await patchShellWebhooks(auth, apiKey, shell.id, patch);
|
|
225
|
+
const touched = new Set();
|
|
226
|
+
if (patch.eventStream || (rotate && current.eventStream))
|
|
227
|
+
touched.add("events");
|
|
228
|
+
if (patch.deeplinkCallback || (rotate && current.deeplinkCallback))
|
|
229
|
+
touched.add("deeplinks");
|
|
230
|
+
if (patch.identityUrl)
|
|
231
|
+
touched.add("identity");
|
|
232
|
+
const checks = touched.size ? (await runConnectionChecks(auth, apiKey, shell.id, [...touched])).results : [];
|
|
233
|
+
const secretNote = secretFile
|
|
234
|
+
? `\nSigning secret saved to ${secretFile} as DUCT_WEBHOOK_SECRET (git-ignored). Load it where the product verifies X-Duct-Signature.`
|
|
235
|
+
: "";
|
|
236
|
+
return text(`Saved for ${shell.environment}.${secretNote}${checks.length ? `\nChecks:\n${checkLines(checks)}` : ""}`, {
|
|
237
|
+
shell_id: shell.id,
|
|
238
|
+
confirmed: true,
|
|
239
|
+
changed: changes.map((c) => c.field),
|
|
240
|
+
...(secretFile ? { secret_file: secretFile } : {}),
|
|
241
|
+
checks: checks.map(compactCheck),
|
|
242
|
+
});
|
|
243
|
+
});
|
|
244
|
+
},
|
|
245
|
+
};
|
|
246
|
+
const checkTool = {
|
|
247
|
+
name: "setup_check",
|
|
248
|
+
title: "Check connections",
|
|
249
|
+
description: "Call the shell's API, webhooks and sign-in pages the way Duct does in production; returns what failed and how to fix it.",
|
|
250
|
+
inputSchema: {
|
|
251
|
+
type: "object",
|
|
252
|
+
properties: {
|
|
253
|
+
shell: SHELL_ARG,
|
|
254
|
+
targets: {
|
|
255
|
+
type: "array",
|
|
256
|
+
items: { type: "string", enum: ["api", "events", "deeplinks", "identity"] },
|
|
257
|
+
description: "Only these. Default: all.",
|
|
258
|
+
},
|
|
259
|
+
},
|
|
260
|
+
additionalProperties: false,
|
|
261
|
+
},
|
|
262
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
263
|
+
async run(args) {
|
|
264
|
+
return withSession(async ({ auth, apiKey }) => {
|
|
265
|
+
const shells = await listAccountShells(auth, apiKey);
|
|
266
|
+
const shell = pickShell(shells, str(args, "shell"));
|
|
267
|
+
const targets = Array.isArray(args.targets) ? args.targets : undefined;
|
|
268
|
+
const { ok, results } = await runConnectionChecks(auth, apiKey, shell.id, targets);
|
|
269
|
+
return text(`${ok ? "All set URLs answer." : "Some checks need attention."}\n${checkLines(results)}`, {
|
|
270
|
+
shell_id: shell.id,
|
|
271
|
+
ok,
|
|
272
|
+
results: results.map(compactCheck),
|
|
273
|
+
});
|
|
274
|
+
});
|
|
275
|
+
},
|
|
276
|
+
};
|
|
277
|
+
const PROFILE_RE = /^[a-z][a-z0-9_-]{1,63}$/;
|
|
278
|
+
const partnerTool = {
|
|
279
|
+
name: "setup_partner",
|
|
280
|
+
title: "Partner profiles",
|
|
281
|
+
description: "List partner profiles, or create one that limits what an outside agent may do (reads only, all, or listed action IDs). Create needs confirm: true.",
|
|
282
|
+
inputSchema: {
|
|
283
|
+
type: "object",
|
|
284
|
+
properties: {
|
|
285
|
+
shell: SHELL_ARG,
|
|
286
|
+
create: {
|
|
287
|
+
type: "object",
|
|
288
|
+
properties: {
|
|
289
|
+
name: { type: "string", description: "Shown in the audit log, e.g. Acme support assistant." },
|
|
290
|
+
profile_id: { type: "string", description: "Optional. Lowercase ID the partner sends; derived from name." },
|
|
291
|
+
access: {
|
|
292
|
+
description: '"reads" (look things up only), "all", or an array of action IDs.',
|
|
293
|
+
oneOf: [{ type: "string", enum: ["reads", "all"] }, { type: "array", items: { type: "string" } }],
|
|
294
|
+
},
|
|
295
|
+
},
|
|
296
|
+
required: ["name", "access"],
|
|
297
|
+
additionalProperties: false,
|
|
298
|
+
},
|
|
299
|
+
confirm: { type: "boolean" },
|
|
300
|
+
preview_token: { type: "string", description: "The preview_token from the approved preview." },
|
|
301
|
+
},
|
|
302
|
+
additionalProperties: false,
|
|
303
|
+
},
|
|
304
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
|
|
305
|
+
async run(args) {
|
|
306
|
+
return withSession(async ({ auth, apiKey }) => {
|
|
307
|
+
const shells = await listAccountShells(auth, apiKey);
|
|
308
|
+
const shell = pickShell(shells, str(args, "shell"));
|
|
309
|
+
const create = args.create;
|
|
310
|
+
if (!create) {
|
|
311
|
+
const profiles = await listPartnerProfiles(auth, apiKey, shell.id);
|
|
312
|
+
const lines = profiles.map((p) => `- ${p.label} (${p.name}): ${p.scopes.join(", ")}`).join("\n") || "- none";
|
|
313
|
+
return text(`Partner profiles on ${shell.environment}:\n${lines}`, {
|
|
314
|
+
shell_id: shell.id,
|
|
315
|
+
profiles: profiles.map((p) => ({ profile_id: p.name, name: p.label, scopes: p.scopes })),
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
const label = typeof create.name === "string" ? create.name.trim() : "";
|
|
319
|
+
if (!label)
|
|
320
|
+
throw new InvalidParams("create.name is required.");
|
|
321
|
+
const id = typeof create.profile_id === "string" && create.profile_id.trim()
|
|
322
|
+
? create.profile_id.trim()
|
|
323
|
+
: label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+$/, "").slice(0, 64);
|
|
324
|
+
if (!PROFILE_RE.test(id))
|
|
325
|
+
throw new InvalidParams("profile_id: 2-64 lowercase letters, digits, - or _, starting with a letter.");
|
|
326
|
+
const access = create.access;
|
|
327
|
+
const scopes = access === "reads" ? ["read:*"] : access === "all" ? ["*"] : Array.isArray(access) && access.every((a) => typeof a === "string" && a) ? access : null;
|
|
328
|
+
if (!scopes || scopes.length === 0)
|
|
329
|
+
throw new InvalidParams('access must be "reads", "all", or a non-empty array of action IDs.');
|
|
330
|
+
const token = previewToken({ shell: shell.id, id, label, scopes });
|
|
331
|
+
if (args.confirm !== true) {
|
|
332
|
+
const what = access === "reads" ? "look things up only" : access === "all" ? "every action open to agents" : scopes.join(", ");
|
|
333
|
+
return text(`Preview: profile "${label}" (${id}) on ${shell.environment}, may do: ${what}.\nShow this to the developer, then call again with the same arguments, confirm: true and preview_token: "${token}".`, { shell_id: shell.id, preview: { profile_id: id, name: label, scopes }, preview_token: token, confirmed: false });
|
|
334
|
+
}
|
|
335
|
+
if (str(args, "preview_token") !== token) {
|
|
336
|
+
throw new InvalidParams("preview_token does not match this profile. Preview again and confirm with the new token.");
|
|
337
|
+
}
|
|
338
|
+
const created = await createPartnerProfile(auth, apiKey, shell.id, { name: id, label, scopes });
|
|
339
|
+
return text(`Created "${label}". Send the partner: shell_id ${shell.id}, profile ${created.name}. Their agent gets a token with POST /v1/agent-access-token { shellId, profile }. Neither value is a secret.`, { shell_id: shell.id, profile_id: created.name, confirmed: true });
|
|
340
|
+
});
|
|
341
|
+
},
|
|
342
|
+
};
|
|
343
|
+
export const SETUP_TOOLS = [statusTool, configureTool, checkTool, partnerTool];
|
|
344
|
+
export async function runSetupMcpServer() {
|
|
345
|
+
await runStdioServer({
|
|
346
|
+
name: SETUP_SERVER_NAME,
|
|
347
|
+
title: "Duct setup",
|
|
348
|
+
version: VERSION,
|
|
349
|
+
instructions: INSTRUCTIONS,
|
|
350
|
+
tools: SETUP_TOOLS,
|
|
351
|
+
});
|
|
352
|
+
}
|