dsh-hiss-plugins 1.4.0 → 1.5.1

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.
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The `/mcp` dialog's action surface: one dispatcher over the dialog's five requests,
3
+ * so the HTTP seam in `index.js` only reads a body and writes a JSON answer.
4
+ *
5
+ * Every dependency is injected: the dispatcher never imports a host package, which is
6
+ * what lets the whole request matrix run offline against fakes.
7
+ *
8
+ * @module dsh-hiss-plugins/project-mcp/actions
9
+ */
10
+
11
+ /** Read one thrown value as text. */
12
+ function messageOf(error) {
13
+ return error instanceof Error ? error.message : String(error);
14
+ }
15
+
16
+ /** Refuse one request with a code the dialog can branch on. */
17
+ function refusal(code, message) {
18
+ return { ok: false, error: { code, message } };
19
+ }
20
+
21
+ /**
22
+ * Run one dialog request.
23
+ * @param {object} body - the parsed request body.
24
+ * @param {object} deps - the host operations the dispatcher may call (status, setTool,
25
+ * setServer, add, promote). Every method receives the session id first.
26
+ * @returns {Promise<{ ok: true, value: unknown } | { ok: false, error: { code: string, message: string } }>}
27
+ * the answer the dialog reads.
28
+ */
29
+ export async function dispatch(body, deps) {
30
+ const action = body?.action;
31
+ const sessionId = body?.sessionId;
32
+ if (typeof sessionId !== "string" || sessionId === "") return refusal("invalid-request", "sessionId is required");
33
+ if (typeof action !== "string") return refusal("unknown-action", "unknown action \"undefined\"");
34
+ try {
35
+ if (action === "status") return { ok: true, value: await deps.status(sessionId) };
36
+ if (action === "set-tool" || action === "set-server" || action === "set-global-server") {
37
+ if (typeof body.enabled !== "boolean") return refusal("invalid-request", "enabled must be a boolean");
38
+ const field = action === "set-tool" ? "tool" : "server";
39
+ const name = body[field];
40
+ if (typeof name !== "string" || name === "") return refusal("invalid-request", `${field} is required`);
41
+ const value = action === "set-tool"
42
+ ? await deps.setTool(sessionId, name, body.enabled)
43
+ : action === "set-server"
44
+ ? await deps.setServer(sessionId, name, body.enabled)
45
+ : await deps.setGlobalServer(sessionId, name, body.enabled);
46
+ return { ok: true, value };
47
+ }
48
+ if (action === "add-server") {
49
+ if (body.server === null || typeof body.server !== "object") return refusal("invalid-request", "server is required");
50
+ return { ok: true, value: await deps.add(sessionId, body.server) };
51
+ }
52
+ if (action === "promote") {
53
+ if (typeof body.server !== "string" || body.server === "") return refusal("invalid-request", "server is required");
54
+ return { ok: true, value: await deps.promote(sessionId, body.server) };
55
+ }
56
+ return refusal("unknown-action", `unknown action "${action}"`);
57
+ } catch (error) {
58
+ return refusal("failed", messageOf(error));
59
+ }
60
+ }
@@ -1,4 +1,5 @@
1
- import { access, readFile } from "node:fs/promises";
1
+ import { randomUUID } from "node:crypto";
2
+ import { access, chmod, mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
2
3
  import { dirname, join, resolve } from "node:path";
3
4
 
4
5
  /**
@@ -156,3 +157,120 @@ export async function loadServers(configPath, cwd) {
156
157
  }
157
158
  return { servers, skipped };
158
159
  }
160
+ /** Names the MCP bridge accepts as a tool namespace. */
161
+ const SERVER_NAME = /^[A-Za-z0-9_-]{1,32}$/;
162
+
163
+ /**
164
+ * Validate one server entry a user typed into the dialog before it reaches any file.
165
+ * @param {string} serverName - the entry key, which becomes the tool namespace.
166
+ * @param {unknown} entry - the raw entry value.
167
+ * @param {string} projectDir - directory holding `.mcp.json`, the stdio default cwd.
168
+ * @returns {void}
169
+ * @throws when the name or the entry could not be used.
170
+ */
171
+ export function validateEntry(serverName, entry, projectDir) {
172
+ if (!SERVER_NAME.test(serverName)) {
173
+ throw new Error(`"${serverName}": name must match ${String(SERVER_NAME)}`);
174
+ }
175
+ toSpec(serverName, entry, projectDir);
176
+ }
177
+
178
+ /**
179
+ * Read one `.mcp.json` as a plain document, so a write can keep every unrelated key.
180
+ * @param {string} configPath - absolute path to the `.mcp.json`.
181
+ * @returns {Promise<Record<string, unknown>>} the parsed object, or `{}` when the file is absent.
182
+ * @throws when the file exists but is not a JSON object.
183
+ */
184
+ export async function readConfig(configPath) {
185
+ let raw;
186
+ try {
187
+ raw = await readFile(configPath, "utf8");
188
+ } catch (error) {
189
+ // Only an absent file reads as empty: a locked or unreadable one must fail
190
+ // the write path instead of being replaced by a document holding one server.
191
+ if (error?.code === "ENOENT") return {};
192
+ throw error;
193
+ }
194
+ let parsed;
195
+ try {
196
+ parsed = JSON.parse(raw);
197
+ } catch (error) {
198
+ throw new Error(`${configPath} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
199
+ }
200
+ if (!isRecord(parsed)) throw new Error(`${configPath} must contain a JSON object`);
201
+ return parsed;
202
+ }
203
+
204
+ /**
205
+ * Write one `.mcp.json` atomically: a rename never leaves a half-written config.
206
+ * @param {string} configPath - absolute path to the `.mcp.json`.
207
+ * @param {Record<string, unknown>} parsed - the document to write.
208
+ * @returns {Promise<void>}
209
+ */
210
+ export async function writeConfig(configPath, parsed) {
211
+ await mkdir(dirname(resolve(configPath)), { recursive: true });
212
+ // A token-bearing .mcp.json must not lose its mode to the rename, and a
213
+ // failed write must not leave a tmp file in the project directory.
214
+ const mode = await stat(configPath).then((info) => info.mode & 0o777, () => undefined);
215
+ const temporary = `${configPath}.${randomUUID()}.tmp`;
216
+ try {
217
+ await writeFile(temporary, `${JSON.stringify(parsed, null, 2)}\n`);
218
+ if (mode !== undefined) await chmod(temporary, mode);
219
+ await rename(temporary, configPath);
220
+ } finally {
221
+ await unlink(temporary).catch(() => {});
222
+ }
223
+ }
224
+ /** Split a dialog argument line into argv, without shell quoting. */
225
+ export function splitArgs(value) {
226
+ if (Array.isArray(value)) return value.filter((entry) => typeof entry === "string");
227
+ return typeof value === "string" ? value.split(/\s+/).filter((entry) => entry !== "") : [];
228
+ }
229
+
230
+ /**
231
+ * A `.mcp.json` entry built from the dialog add form.
232
+ * @param {object} input - the form values.
233
+ * @returns {Record<string, unknown>} the entry to store under `mcpServers`.
234
+ */
235
+ export function entryFromInput(input) {
236
+ if (input.type === "http") {
237
+ return {
238
+ type: "http",
239
+ url: String(input.url ?? ""),
240
+ ...(isRecord(input.headers) ? { headers: input.headers } : {}),
241
+ };
242
+ }
243
+ const args = splitArgs(input.args);
244
+ return {
245
+ type: "stdio",
246
+ command: String(input.command ?? ""),
247
+ ...(args.length === 0 ? {} : { args }),
248
+ ...(isRecord(input.env) ? { env: input.env } : {}),
249
+ };
250
+ }
251
+
252
+ /**
253
+ * The manager-shaped entry one declared server becomes when registered globally.
254
+ * @param {unknown} entry - the `.mcp.json` entry.
255
+ * @param {string} projectDir - directory holding that `.mcp.json`.
256
+ * @returns {Record<string, unknown>} the entry `mcp-manager` accepts.
257
+ */
258
+ export function managerEntry(entry, projectDir) {
259
+ const fields = isRecord(entry) ? entry : {};
260
+ if (fields.type === "http") {
261
+ return {
262
+ transport: "streamable-http",
263
+ url: String(fields.url ?? ""),
264
+ headers: isRecord(fields.headers) ? fields.headers : {},
265
+ enabled: true,
266
+ };
267
+ }
268
+ return {
269
+ transport: "stdio",
270
+ command: String(fields.command ?? ""),
271
+ args: Array.isArray(fields.args) ? fields.args.filter((arg) => typeof arg === "string") : [],
272
+ env: isRecord(fields.env) ? fields.env : {},
273
+ cwd: resolve(projectDir, typeof fields.cwd === "string" ? fields.cwd : "."),
274
+ enabled: true,
275
+ };
276
+ }