@dudko.dev/baton-mcp 0.2.0 → 0.4.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.
@@ -8,7 +8,7 @@ import { BatonTools } from "./tools.js";
8
8
  * The rules here are the ones an agent gets wrong without being told — where
9
9
  * secrets go, which paths are which, and that a run is live traffic.
10
10
  */
11
- export declare const INSTRUCTIONS = "Baton is a git-native API client: a workspace is a folder of YAML files (collections/**/*.req.yaml, collection.yaml, folder.yaml, environments/*.env.yaml) in the user's own git repository. These tools read and write those files directly; the app shows the result as soon as the file changes, and git review covers every edit.\n\nRules:\n- Secret VALUES never pass through this server. Reference a secret as {{name}} (or {{secret:name}} to insist on one) and declare the name in the environment; a literal token in an auth field is refused.\n- Paths are workspace-relative: collections/<collection>/<folder...>/<slug>.req.yaml. Call workspace_info first, then list_requests, before writing.\n- upsert_* tools write deterministic YAML, so a diff shows only what you changed. Keep the request's id when replacing one.\n- run_request and run_collection send live traffic to the request's real URL. They are off unless the server was started with --allow-run; when they are off, tell the user how to enable them rather than retrying.\n- Variables resolve as {{name}} from the active environment, then the collection and folder; a request's own variables come first.";
11
+ export declare const INSTRUCTIONS = "Baton is a git-native API client: a workspace is a folder of YAML files (collections/**/*.req.yaml, collection.yaml, folder.yaml, environments/*.env.yaml) in the user's own git repository. These tools read and write those files directly; the app shows the result as soon as the file changes, and git review covers every edit.\n\nRules:\n- Secret VALUES never pass through this server. Reference a secret as {{name}} (or {{secret:name}} to insist on one) and declare the name in the environment; a literal token in an auth field is refused.\n- Paths are workspace-relative: collections/<collection>/<folder...>/<slug>.req.yaml, and flows/<slug>.flow.yaml for a flow (a graph of steps: requests, and log, if, switch, loop, get and set nodes, each naming the steps it runs after). Call workspace_info first, then list_requests, before writing.\n- upsert_* tools write deterministic YAML, so a diff shows only what you changed. Keep the request's id when replacing one.\n- run_request, run_collection and run_flow send live traffic to the request's real URL. They are off unless the server was started with --allow-run; when they are off, tell the user how to enable them rather than retrying.\n- Variables resolve as {{name}} from the active environment, then the collection and folder; a request's own variables come first.";
12
12
  /** Appended when the desktop app is open on the workspace (app mode). */
13
13
  export declare const APP_MODE_INSTRUCTIONS = "\nThe Baton desktop app is open on this workspace, so you are working with the person in real time:\n- upsert_request on an existing request puts your edit on its tab as a DRAFT the person reviews and accepts (or discards). Say so, and do not retry if the file has not changed yet. A new request is created as a file.\n- run_request sends through the app with its secrets; the response panel shows the result. A send into an environment marked production, and delete_request, wait for the person to confirm in the app \u2014 a refusal is their decision, not an error to work around.\n- app_state (or the baton://app/state resource) tells you which request and environment are open and what the last sends answered; select_request opens a request for the person.";
14
14
  /**
@@ -13,9 +13,9 @@ export const INSTRUCTIONS = `Baton is a git-native API client: a workspace is a
13
13
 
14
14
  Rules:
15
15
  - Secret VALUES never pass through this server. Reference a secret as {{name}} (or {{secret:name}} to insist on one) and declare the name in the environment; a literal token in an auth field is refused.
16
- - Paths are workspace-relative: collections/<collection>/<folder...>/<slug>.req.yaml. Call workspace_info first, then list_requests, before writing.
16
+ - Paths are workspace-relative: collections/<collection>/<folder...>/<slug>.req.yaml, and flows/<slug>.flow.yaml for a flow (a graph of steps: requests, and log, if, switch, loop, get and set nodes, each naming the steps it runs after). Call workspace_info first, then list_requests, before writing.
17
17
  - upsert_* tools write deterministic YAML, so a diff shows only what you changed. Keep the request's id when replacing one.
18
- - run_request and run_collection send live traffic to the request's real URL. They are off unless the server was started with --allow-run; when they are off, tell the user how to enable them rather than retrying.
18
+ - run_request, run_collection and run_flow send live traffic to the request's real URL. They are off unless the server was started with --allow-run; when they are off, tell the user how to enable them rather than retrying.
19
19
  - Variables resolve as {{name}} from the active environment, then the collection and folder; a request's own variables come first.`;
20
20
  /** Appended when the desktop app is open on the workspace (app mode). */
21
21
  export const APP_MODE_INSTRUCTIONS = `
@@ -149,6 +149,20 @@ export function buildServer(tools, app = null) {
149
149
  inputSchema: z.object({ path: z.string(), source: z.string() }),
150
150
  annotations: { idempotentHint: true },
151
151
  }, ({ path, source }) => respond(() => reloadApp(tools.upsertScript(path, source))));
152
+ server.registerTool("list_flows", {
153
+ description: "List the flows under flows/: path, id, name, and how many steps each has.",
154
+ annotations: { readOnlyHint: true },
155
+ }, () => respond(() => tools.listFlows()));
156
+ server.registerTool("get_flow", {
157
+ description: "A flow parsed, plus its raw YAML. A file that does not parse comes back as raw YAML and the parse error.",
158
+ inputSchema: z.object({ path: z.string() }),
159
+ annotations: { readOnlyHint: true },
160
+ }, ({ path }) => respond(() => tools.getFlow(path)));
161
+ server.registerTool("upsert_flow", {
162
+ description: "Create or replace flows/<slug>.flow.yaml from flow JSON: format, id (a ULID; keep it when replacing), name, optional environment, and steps. Every step has an id, after (step ids; out of an if, switch or loop, id.port — if: true/false, switch: a case name or default, loop: each/done) and exactly one of: request (a .req.yaml path; with optional expect.status and continueOnFailure), log (a message template), if (a condition such as \"{{status}} == 200\"), switch ({value, cases: {port: text}}), loop ({items: a template rendering a JSON list; the steps after its each port run once per item with {{item}}, {{item.<path>}} and {{index}}}), get ({from: a request step it follows, values: {variable: dotted path into that response's JSON body}}) or set ({variable: template}). Validated and written as canonical YAML; a cycle, an unknown step or port, or a get that reads a step it does not follow is refused. An older capture on a request is turned into a get step.",
163
+ inputSchema: z.object({ path: z.string(), flow: z.record(z.string(), z.unknown()) }),
164
+ annotations: { idempotentHint: true },
165
+ }, ({ path, flow }) => respond(() => reloadApp(tools.upsertFlow(path, flow))));
152
166
  server.registerTool("run_request", {
153
167
  description: app
154
168
  ? "Send one request through the Baton app, with the app's secrets; the response lands in its panel too. An environment marked production asks the person first. Response headers are masked and bodies truncated."
@@ -171,6 +185,21 @@ export function buildServer(tools, app = null) {
171
185
  }
172
186
  return results;
173
187
  }));
188
+ server.registerTool("run_flow", {
189
+ description: app
190
+ ? "Not available while the Baton app is open on this workspace: ask the person to run the flow in the app."
191
+ : "Run a flow (requires --allow-run) in the environment given, else the one the flow names: up to four requests at a time, each with what the steps before it read, set and received as cookies. Returns every step's outcome — passed, failed, or skipped and why — each sent request's masked, truncated result, log messages, the port an if or switch took, a loop's count, and one entry per item for the steps inside a loop.",
192
+ inputSchema: z.object({ path: z.string(), environment: z.string().default("") }),
193
+ annotations: { openWorldHint: true },
194
+ }, ({ path, environment }) => respond(() => {
195
+ // The app sends with its own secrets and asks before production; a
196
+ // flow run here would do neither, and the app takes no flow runs
197
+ // from an agent yet.
198
+ if (app) {
199
+ throw new ToolError("run_flow is not available while the Baton app is open on this workspace — ask the person to run the flow in the app, or work with the app closed and --allow-run");
200
+ }
201
+ return tools.runFlow(path, environment);
202
+ }));
174
203
  server.registerTool("list_examples", {
175
204
  description: "A request's saved responses (<slug>.examples.yaml beside it): names, statuses, sizes. Examples are what a mock answers with.",
176
205
  inputSchema: z.object({ path: z.string() }),
@@ -1,4 +1,4 @@
1
- import { CollectionFile, EnvironmentFile, RequestFile } from "@dudko.dev/baton-format";
1
+ import { CollectionFile, EnvironmentFile, FlowFile, RequestFile } from "@dudko.dev/baton-format";
2
2
  import { MockRegistry } from "@dudko.dev/baton-worker";
3
3
  /** Tool-layer errors carry a message meant for the calling agent. */
4
4
  export declare class ToolError extends Error {
@@ -52,6 +52,33 @@ export declare class BatonTools {
52
52
  upsertEnvironment(path: string, environment: EnvironmentFile): unknown;
53
53
  getScript(path: string): unknown;
54
54
  upsertScript(path: string, source: string): unknown;
55
+ /** The flows under `flows/`; a file that does not parse is in workspace_info's issues. */
56
+ listFlows(): unknown;
57
+ /**
58
+ * A flow, parsed, with its raw YAML. A file that does not parse comes back
59
+ * as its raw text and the parse error, so it can be fixed with upsert_flow.
60
+ */
61
+ getFlow(path: string): unknown;
62
+ /**
63
+ * The checks a flow from an agent goes through before it is written: the
64
+ * path shape, and the parser reading exactly what the agent sent — JSON is
65
+ * YAML — which rejects an unknown or misspelled field, a value of the wrong
66
+ * type, unknown or repeated edges, cycles, duplicate step ids and a capture
67
+ * name written by two steps. Fields at their defaults may be left out.
68
+ * Returns the canonical bytes.
69
+ *
70
+ * Writing first and parsing the writer's output let the writer coerce the
71
+ * input: `continueOnFailure: "false"` came out as `true`, and a misspelled
72
+ * `when` was dropped, so the step ran with no condition.
73
+ */
74
+ validateFlow(path: string, flow: FlowFile): string;
75
+ /** Validates and writes a flow as canonical bytes. */
76
+ upsertFlow(path: string, flow: FlowFile): unknown;
77
+ /**
78
+ * Runs a flow through the worker's driver: every step's outcome, and for a
79
+ * step that ran its result, masked and truncated like run_request's.
80
+ */
81
+ runFlow(path: string, environment: string): Promise<unknown>;
55
82
  runRequest(path: string, environment: string): Promise<unknown>;
56
83
  /** A request's saved responses, names and sizes — the bodies stay in the file. */
57
84
  listExamples(path: string): unknown;
package/dist/src/tools.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { basename, dirname, join, normalize } from "node:path";
3
- import { parseCollectionFile, parseEnvironmentFile, parseRequestFile, serializeCollectionFile, serializeEnvironmentFile, serializeExamplesFile, serializeRequestFile, } from "@dudko.dev/baton-format";
4
- import { examplesPathFor, findRequest, maskSecrets, MockRegistry, openWorkspace, requestsUnder, runWorkspaceRequest, secretsFromEnv, } from "@dudko.dev/baton-worker";
3
+ import { FormatError, parseCollectionFile, parseEnvironmentFile, parseFlowFile, parseRequestFile, serializeCollectionFile, serializeEnvironmentFile, serializeExamplesFile, serializeFlowFile, serializeRequestFile, } from "@dudko.dev/baton-format";
4
+ import { examplesPathFor, findRequest, FlowLoadError, maskSecrets, MockRegistry, openWorkspace, requestsUnder, runWorkspaceFlow, runWorkspaceRequest, secretsFromEnv, } from "@dudko.dev/baton-worker";
5
5
  /** Tool-layer errors carry a message meant for the calling agent. */
6
6
  export class ToolError extends Error {
7
7
  }
8
8
  const BODY_LIMIT = 16 * 1024;
9
+ /** Where a flow lives: `flows/<slug>.flow.yaml`, one level, nothing deeper. */
10
+ const FLOW_PATH = /^flows\/[^/]+\.flow\.yaml$/;
9
11
  const MASKED_HEADERS = new Set(["authorization", "set-cookie", "cookie", "x-api-key"]);
10
12
  export class BatonTools {
11
13
  root;
@@ -45,6 +47,7 @@ export class BatonTools {
45
47
  name: ws.manifest.name,
46
48
  collections: summarize(ws.collections),
47
49
  environments: ws.environments.map((e) => e.slug),
50
+ flows: ws.flows.map((f) => f.path),
48
51
  schedules: ws.schedules?.schedules.map((s) => s.id) ?? [],
49
52
  issues: ws.issues,
50
53
  runsEnabled: this.allowRun,
@@ -247,6 +250,119 @@ export class BatonTools {
247
250
  writeFileSync(target, source);
248
251
  return { path, bytes: source.length };
249
252
  }
253
+ /** The flows under `flows/`; a file that does not parse is in workspace_info's issues. */
254
+ listFlows() {
255
+ return this.workspace().flows.map((entry) => ({
256
+ path: entry.path,
257
+ id: entry.flow.id,
258
+ name: entry.flow.name,
259
+ ...(entry.flow.description !== undefined ? { description: entry.flow.description } : {}),
260
+ steps: entry.flow.steps.length,
261
+ }));
262
+ }
263
+ /**
264
+ * A flow, parsed, with its raw YAML. A file that does not parse comes back
265
+ * as its raw text and the parse error, so it can be fixed with upsert_flow.
266
+ */
267
+ getFlow(path) {
268
+ if (!FLOW_PATH.test(path))
269
+ throw new ToolError("flow paths look like flows/<slug>.flow.yaml");
270
+ const target = this.safePath(path);
271
+ if (!existsSync(target))
272
+ throw new ToolError(`flow not found: ${path}`);
273
+ const raw = readFileSync(target, "utf8");
274
+ try {
275
+ return { path, flow: parseFlowFile(raw), raw };
276
+ }
277
+ catch (error) {
278
+ if (!(error instanceof FormatError))
279
+ throw error;
280
+ return { path, raw, error: error.message };
281
+ }
282
+ }
283
+ /**
284
+ * The checks a flow from an agent goes through before it is written: the
285
+ * path shape, and the parser reading exactly what the agent sent — JSON is
286
+ * YAML — which rejects an unknown or misspelled field, a value of the wrong
287
+ * type, unknown or repeated edges, cycles, duplicate step ids and a capture
288
+ * name written by two steps. Fields at their defaults may be left out.
289
+ * Returns the canonical bytes.
290
+ *
291
+ * Writing first and parsing the writer's output let the writer coerce the
292
+ * input: `continueOnFailure: "false"` came out as `true`, and a misspelled
293
+ * `when` was dropped, so the step ran with no condition.
294
+ */
295
+ validateFlow(path, flow) {
296
+ if (!FLOW_PATH.test(path))
297
+ throw new ToolError("flow paths look like flows/<slug>.flow.yaml");
298
+ if (flow === null || typeof flow !== "object" || Array.isArray(flow)) {
299
+ throw new ToolError("invalid flow: must be an object");
300
+ }
301
+ try {
302
+ const sent = flow;
303
+ return serializeFlowFile(parseFlowFile(JSON.stringify({ ...sent, format: sent.format ?? 1 })));
304
+ }
305
+ catch (error) {
306
+ throw new ToolError(`invalid flow: ${error instanceof Error ? error.message : String(error)}`);
307
+ }
308
+ }
309
+ /** Validates and writes a flow as canonical bytes. */
310
+ upsertFlow(path, flow) {
311
+ const canonical = this.validateFlow(path, flow);
312
+ const target = this.safePath(path);
313
+ mkdirSync(dirname(target), { recursive: true });
314
+ writeFileSync(target, canonical);
315
+ // A step may name a request that is not written yet; it fails when the
316
+ // flow runs, so say which ones now.
317
+ const ws = this.workspace();
318
+ const missing = parseFlowFile(canonical)
319
+ .steps.flatMap((step) => (step.kind === "request" ? [step.request] : []))
320
+ .filter((request, i, all) => all.indexOf(request) === i && !findRequest(ws, request));
321
+ return { path, bytes: canonical.length, ...(missing.length > 0 ? { missingRequests: missing } : {}) };
322
+ }
323
+ /**
324
+ * Runs a flow through the worker's driver: every step's outcome, and for a
325
+ * step that ran its result, masked and truncated like run_request's.
326
+ */
327
+ async runFlow(path, environment) {
328
+ this.assertRunsEnabled();
329
+ try {
330
+ const report = await runWorkspaceFlow(this.workspace(), path, environment);
331
+ const secrets = secretsFromEnv(process.env);
332
+ // Values a Get read out of a response are shown masked, like a body.
333
+ const pass = (step) => ({
334
+ outcome: step.outcome,
335
+ ...(step.reason !== undefined ? { reason: step.reason } : {}),
336
+ ...(step.result !== undefined ? { result: redactResult(step.result) } : {}),
337
+ ...(step.values !== undefined
338
+ ? {
339
+ values: Object.fromEntries(Object.entries(step.values).map(([name, value]) => [name, maskSecrets(value, secrets)])),
340
+ }
341
+ : {}),
342
+ ...(step.message !== undefined ? { message: maskSecrets(step.message, secrets) } : {}),
343
+ ...(step.branch !== undefined ? { branch: step.branch } : {}),
344
+ });
345
+ return {
346
+ path,
347
+ environment: report.environment,
348
+ ok: report.ok,
349
+ steps: report.steps.map((step) => ({
350
+ id: step.id,
351
+ kind: step.kind,
352
+ ...(step.request !== undefined ? { request: step.request } : {}),
353
+ ...pass(step),
354
+ ...(step.count !== undefined ? { count: step.count } : {}),
355
+ ...(step.error !== undefined ? { error: step.error } : {}),
356
+ ...(step.iterations !== undefined ? { iterations: step.iterations.map(pass) } : {}),
357
+ })),
358
+ };
359
+ }
360
+ catch (error) {
361
+ if (error instanceof FlowLoadError)
362
+ throw new ToolError(error.message);
363
+ throw error;
364
+ }
365
+ }
250
366
  async runRequest(path, environment) {
251
367
  this.assertRunsEnabled();
252
368
  const result = await runWorkspaceRequest(this.workspace(), path, environment);
@@ -425,7 +541,12 @@ function rejectLiteralSecrets(auth) {
425
541
  }
426
542
  }
427
543
  }
428
- function redactResult(result) {
544
+ function redactResult(full) {
545
+ // A parsed cookie is the Set-Cookie value under another name (invariant
546
+ // 2), and script overlays are there for the flow steps after this one.
547
+ // Neither is the agent's to read; the masked headers below still say that
548
+ // a cookie was set.
549
+ const { setCookies: _cookies, varOverlays: _vars, envOverlays: _env, ...result } = full;
429
550
  // Masking by *name* is not enough, which is what this used to do.
430
551
  //
431
552
  // rejectLiteralSecrets guards `auth.*`, so an agent cannot store a literal
@@ -5,4 +5,4 @@
5
5
  * worker keeps one: the file sits at a different depth in the npm tarball
6
6
  * than in the test build. `test/version.test.ts` fails when it drifts.
7
7
  */
8
- export declare const MCP_VERSION = "0.2.0";
8
+ export declare const MCP_VERSION = "0.4.0";
@@ -5,5 +5,5 @@
5
5
  * worker keeps one: the file sits at a different depth in the npm tarball
6
6
  * than in the test build. `test/version.test.ts` fails when it drifts.
7
7
  */
8
- export const MCP_VERSION = "0.2.0";
8
+ export const MCP_VERSION = "0.4.0";
9
9
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dudko.dev/baton-mcp",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Baton MCP server (stdio): structured tools for AI agents to edit and run workspace requests.",
5
5
  "mcpName": "dev.dudko/baton",
6
6
  "keywords": [
@@ -40,8 +40,8 @@
40
40
  "prepublishOnly": "tsc"
41
41
  },
42
42
  "dependencies": {
43
- "@dudko.dev/baton-format": "^0.1.2",
44
- "@dudko.dev/baton-worker": "^0.2.3",
43
+ "@dudko.dev/baton-format": "^0.3.0",
44
+ "@dudko.dev/baton-worker": "^0.4.0",
45
45
  "@modelcontextprotocol/server": "^2.3.1",
46
46
  "zod": "^4.6.5"
47
47
  },