@dudko.dev/baton-mcp 0.1.3 → 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.
- package/README.md +39 -22
- package/dist/src/app.d.ts +48 -0
- package/dist/src/app.js +173 -0
- package/dist/src/index.js +19 -34
- package/dist/src/server.d.ts +25 -0
- package/dist/src/server.js +350 -0
- package/dist/src/tools.d.ts +56 -2
- package/dist/src/tools.js +244 -9
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +17 -7
package/README.md
CHANGED
|
@@ -1,22 +1,28 @@
|
|
|
1
1
|
# baton-mcp
|
|
2
2
|
|
|
3
|
-
A local
|
|
3
|
+
A local MCP server that gives AI agents structured access to a
|
|
4
4
|
[Baton](https://baton.dudko.dev) workspace: list, read, edit, and run requests.
|
|
5
5
|
|
|
6
6
|
Baton is a git-native API client — collections, environments, and schedules are
|
|
7
|
-
plain YAML files in a git repository you own.
|
|
8
|
-
|
|
9
|
-
|
|
7
|
+
plain YAML files in a git repository you own. One configuration, two modes:
|
|
8
|
+
|
|
9
|
+
- **File mode** — the Baton app is not open: an edit is a write to the YAML
|
|
10
|
+
file, the same bytes the app would write, reviewed through git.
|
|
11
|
+
- **App mode** — the desktop app is open on the workspace: an edit lands as a
|
|
12
|
+
**draft** on the request's tab for you to accept or discard, a send runs
|
|
13
|
+
through the app with the app's secrets, a send into a production environment
|
|
14
|
+
or a delete waits for your confirmation, and the agent sees which request
|
|
15
|
+
and environment you have open.
|
|
10
16
|
|
|
11
17
|
## Use it
|
|
12
18
|
|
|
13
19
|
```jsonc
|
|
14
|
-
// Claude Code: .mcp.json
|
|
20
|
+
// Claude Code: .mcp.json in the workspace (Settings → Agents in the app writes it)
|
|
15
21
|
{
|
|
16
22
|
"mcpServers": {
|
|
17
23
|
"baton": {
|
|
18
24
|
"command": "npx",
|
|
19
|
-
"args": ["-y", "@dudko.dev/baton-mcp", "--workspace", "
|
|
25
|
+
"args": ["-y", "@dudko.dev/baton-mcp", "--workspace", "."]
|
|
20
26
|
}
|
|
21
27
|
}
|
|
22
28
|
}
|
|
@@ -25,38 +31,49 @@ review like any other change.
|
|
|
25
31
|
| Flag | Meaning |
|
|
26
32
|
|---|---|
|
|
27
33
|
| `--workspace <dir>` | The workspace root — the folder holding `baton.yaml`. Defaults to the working directory. |
|
|
28
|
-
| `--allow-run` | Lets the agent execute requests. Off by default. |
|
|
34
|
+
| `--allow-run` | Lets the agent execute requests in file mode. Off by default; app-mode sends go through the app. |
|
|
35
|
+
| `--agent <name>` | What the app calls this agent on its banners and confirmations. |
|
|
29
36
|
|
|
30
|
-
Requires Node.js 24 or newer.
|
|
37
|
+
Requires Node.js 24 or newer. Speaks MCP revision 2026-07-28 (SDK v2) and
|
|
38
|
+
still serves 2025-era clients.
|
|
31
39
|
|
|
32
40
|
## Tools
|
|
33
41
|
|
|
34
42
|
| Tool | What it does |
|
|
35
43
|
|---|---|
|
|
36
|
-
| `workspace_info` | Collections, environments, schedules, load issues. |
|
|
44
|
+
| `workspace_info` | Collections, environments, schedules, load issues, and whether the app is connected. |
|
|
37
45
|
| `list_requests` | Requests with method, url, tags — optionally under one collection. |
|
|
38
46
|
| `get_request` | Full parsed request, raw YAML, and where its auth comes from. |
|
|
39
|
-
| `upsert_request` | Create or replace a request
|
|
47
|
+
| `upsert_request` | Create or replace a request (file mode) or propose it as a draft in the app. |
|
|
40
48
|
| `move_request` | Move or rename a request, keeping its id. |
|
|
41
|
-
| `delete_request` | Delete a request. |
|
|
49
|
+
| `delete_request` | Delete a request; in app mode, after you confirm. |
|
|
42
50
|
| `upsert_collection` | Create or replace a collection, its variables, and its auth. |
|
|
43
|
-
| `list_environments` | Variables and secret **names
|
|
51
|
+
| `list_environments` | Variables and secret **names**, with each secret's source. |
|
|
44
52
|
| `upsert_environment` | Create or replace an environment. |
|
|
45
53
|
| `get_script` / `upsert_script` | Read and write pre-request, test, and shared library scripts. |
|
|
46
|
-
| `run_request` | Execute one request (needs `--allow-run
|
|
47
|
-
| `run_collection` | Execute every request under a collection
|
|
54
|
+
| `run_request` | Execute one request (file mode needs `--allow-run`; app mode sends through the app). |
|
|
55
|
+
| `run_collection` | Execute every request under a collection. |
|
|
56
|
+
| `list_examples` / `save_example` | A request's saved responses, and save the last response as one. |
|
|
57
|
+
| `list_mocks` / `start_mock` / `stop_mock` | Stand a mock up from `mocks/<name>.yaml`, answering from the examples. |
|
|
58
|
+
| `app_state` / `select_request` | App mode only: what is open in the app, and open a request there. |
|
|
59
|
+
|
|
60
|
+
Resources `baton://app/state` and `baton://app/selection` are subscribable in
|
|
61
|
+
app mode, so an agent learns of a click, an accepted draft or a finished send
|
|
62
|
+
as it happens.
|
|
48
63
|
|
|
49
64
|
## Secrets
|
|
50
65
|
|
|
51
66
|
Secret **values** never cross the MCP boundary. Environment files hold secret
|
|
52
|
-
names; the values live in the OS secure store. A tool call carrying
|
|
53
|
-
credential is rejected with a message telling the agent to use a
|
|
54
|
-
`{{secret:name}}` reference instead. Responses returned to agents
|
|
55
|
-
bodies and
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
67
|
+
names; the values live in the OS secure store or in Vault. A tool call carrying
|
|
68
|
+
a literal credential is rejected with a message telling the agent to use a
|
|
69
|
+
`{{secret:name}}` reference instead. Responses returned to agents are masked by
|
|
70
|
+
value, truncate bodies, and replace `Authorization`, `Cookie`, `Set-Cookie`,
|
|
71
|
+
and `X-API-Key` by name.
|
|
72
|
+
|
|
73
|
+
Runs in file mode are capability-gated because an agent editing files should
|
|
74
|
+
not silently fire live traffic; with runs disabled the tools still exist and
|
|
75
|
+
return a clear error, so the agent can tell you how to turn them on. In app
|
|
76
|
+
mode every send is on your screen as it happens.
|
|
60
77
|
|
|
61
78
|
The server never touches git — commits stay a deliberate action.
|
|
62
79
|
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** One change pushed by the app's event stream. */
|
|
2
|
+
export interface AppEvent {
|
|
3
|
+
type: string;
|
|
4
|
+
[key: string]: unknown;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* The running desktop app, reached over its loopback bridge (docs/MCP.md,
|
|
8
|
+
* "App mode"). Found through the discovery file the app writes while the
|
|
9
|
+
* workspace is open; everything after is plain HTTP with the per-launch token.
|
|
10
|
+
*
|
|
11
|
+
* The protocol an agent speaks stays in this package — the app only answers
|
|
12
|
+
* state, takes drafts, sends with its own secrets, and asks the person when a
|
|
13
|
+
* send goes into production or a request is to be deleted.
|
|
14
|
+
*/
|
|
15
|
+
export declare class AppClient {
|
|
16
|
+
private readonly base;
|
|
17
|
+
private readonly token;
|
|
18
|
+
readonly pid: number;
|
|
19
|
+
private readonly agent;
|
|
20
|
+
private constructor();
|
|
21
|
+
/**
|
|
22
|
+
* Looks for the app serving [workspace]. Null when the file is missing or
|
|
23
|
+
* nothing answers at its port — the app was closed, or the file is stale
|
|
24
|
+
* from a crash — in which case the package works on the files alone.
|
|
25
|
+
*/
|
|
26
|
+
static discover(workspace: string, agent?: string): Promise<AppClient | null>;
|
|
27
|
+
/** The app as the agent sees it: selection, environment, drafts, last runs. */
|
|
28
|
+
state(timeoutMs?: number): Promise<Record<string, unknown>>;
|
|
29
|
+
/** Puts a request on its tab as a draft (or creates a new file). */
|
|
30
|
+
draft(path: string, request: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
31
|
+
/** Sends through the app; the person confirms when the environment is production. */
|
|
32
|
+
send(path: string, environment?: string): Promise<Record<string, unknown>>;
|
|
33
|
+
/** Deletes after the person confirms in the app. */
|
|
34
|
+
delete(path: string): Promise<Record<string, unknown>>;
|
|
35
|
+
/** Saves the app's last response for a request as a named example. */
|
|
36
|
+
saveExample(path: string, name: string): Promise<Record<string, unknown>>;
|
|
37
|
+
/** Opens a request in the app. */
|
|
38
|
+
select(path: string): Promise<Record<string, unknown>>;
|
|
39
|
+
/** Has the app re-read the workspace after this package wrote a file. */
|
|
40
|
+
reload(): Promise<Record<string, unknown>>;
|
|
41
|
+
/**
|
|
42
|
+
* Follows the app's event stream until [signal] aborts. Each `data:` line
|
|
43
|
+
* is one event; the stream ending means the app closed.
|
|
44
|
+
*/
|
|
45
|
+
events(onEvent: (event: AppEvent) => void, signal: AbortSignal, onClose?: () => void): Promise<void>;
|
|
46
|
+
private headers;
|
|
47
|
+
private call;
|
|
48
|
+
}
|
package/dist/src/app.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { ToolError } from "./tools.js";
|
|
4
|
+
/**
|
|
5
|
+
* The running desktop app, reached over its loopback bridge (docs/MCP.md,
|
|
6
|
+
* "App mode"). Found through the discovery file the app writes while the
|
|
7
|
+
* workspace is open; everything after is plain HTTP with the per-launch token.
|
|
8
|
+
*
|
|
9
|
+
* The protocol an agent speaks stays in this package — the app only answers
|
|
10
|
+
* state, takes drafts, sends with its own secrets, and asks the person when a
|
|
11
|
+
* send goes into production or a request is to be deleted.
|
|
12
|
+
*/
|
|
13
|
+
export class AppClient {
|
|
14
|
+
base;
|
|
15
|
+
token;
|
|
16
|
+
pid;
|
|
17
|
+
agent;
|
|
18
|
+
constructor(base, token, pid, agent) {
|
|
19
|
+
this.base = base;
|
|
20
|
+
this.token = token;
|
|
21
|
+
this.pid = pid;
|
|
22
|
+
this.agent = agent;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Looks for the app serving [workspace]. Null when the file is missing or
|
|
26
|
+
* nothing answers at its port — the app was closed, or the file is stale
|
|
27
|
+
* from a crash — in which case the package works on the files alone.
|
|
28
|
+
*/
|
|
29
|
+
static async discover(workspace, agent = "an MCP agent") {
|
|
30
|
+
const file = join(workspace, ".baton", "mcp.json");
|
|
31
|
+
if (!existsSync(file))
|
|
32
|
+
return null;
|
|
33
|
+
let discovery;
|
|
34
|
+
try {
|
|
35
|
+
discovery = JSON.parse(readFileSync(file, "utf8"));
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
if (typeof discovery.port !== "number" || typeof discovery.token !== "string") {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
const client = new AppClient(`http://127.0.0.1:${discovery.port}`, discovery.token, discovery.pid, agent);
|
|
44
|
+
try {
|
|
45
|
+
await client.state(1000);
|
|
46
|
+
return client;
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** The app as the agent sees it: selection, environment, drafts, last runs. */
|
|
53
|
+
state(timeoutMs) {
|
|
54
|
+
return this.call("GET", "/v1/state", undefined, timeoutMs);
|
|
55
|
+
}
|
|
56
|
+
/** Puts a request on its tab as a draft (or creates a new file). */
|
|
57
|
+
draft(path, request) {
|
|
58
|
+
return this.call("POST", "/v1/drafts", { path, request });
|
|
59
|
+
}
|
|
60
|
+
/** Sends through the app; the person confirms when the environment is production. */
|
|
61
|
+
send(path, environment) {
|
|
62
|
+
return this.call("POST", "/v1/send", {
|
|
63
|
+
path,
|
|
64
|
+
...(environment ? { environment } : {}),
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/** Deletes after the person confirms in the app. */
|
|
68
|
+
delete(path) {
|
|
69
|
+
return this.call("POST", "/v1/delete", { path });
|
|
70
|
+
}
|
|
71
|
+
/** Saves the app's last response for a request as a named example. */
|
|
72
|
+
saveExample(path, name) {
|
|
73
|
+
return this.call("POST", "/v1/examples", { path, name });
|
|
74
|
+
}
|
|
75
|
+
/** Opens a request in the app. */
|
|
76
|
+
select(path) {
|
|
77
|
+
return this.call("POST", "/v1/select", { path });
|
|
78
|
+
}
|
|
79
|
+
/** Has the app re-read the workspace after this package wrote a file. */
|
|
80
|
+
reload() {
|
|
81
|
+
return this.call("POST", "/v1/reload");
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Follows the app's event stream until [signal] aborts. Each `data:` line
|
|
85
|
+
* is one event; the stream ending means the app closed.
|
|
86
|
+
*/
|
|
87
|
+
async events(onEvent, signal, onClose) {
|
|
88
|
+
let response;
|
|
89
|
+
try {
|
|
90
|
+
response = await fetch(`${this.base}/v1/events`, {
|
|
91
|
+
headers: this.headers(),
|
|
92
|
+
signal,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
onClose?.();
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (!response.ok || !response.body) {
|
|
100
|
+
onClose?.();
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const reader = response.body.getReader();
|
|
104
|
+
const decoder = new TextDecoder();
|
|
105
|
+
let buffer = "";
|
|
106
|
+
try {
|
|
107
|
+
for (;;) {
|
|
108
|
+
const { value, done } = await reader.read();
|
|
109
|
+
if (done)
|
|
110
|
+
break;
|
|
111
|
+
buffer += decoder.decode(value, { stream: true });
|
|
112
|
+
let end;
|
|
113
|
+
while ((end = buffer.indexOf("\n\n")) >= 0) {
|
|
114
|
+
const chunk = buffer.slice(0, end);
|
|
115
|
+
buffer = buffer.slice(end + 2);
|
|
116
|
+
for (const line of chunk.split("\n")) {
|
|
117
|
+
if (!line.startsWith("data: "))
|
|
118
|
+
continue;
|
|
119
|
+
try {
|
|
120
|
+
onEvent(JSON.parse(line.slice(6)));
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
// A line that is not JSON is not an event.
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
// Aborted, or the app went away.
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
onClose?.();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
headers() {
|
|
137
|
+
return {
|
|
138
|
+
authorization: `Bearer ${this.token}`,
|
|
139
|
+
"x-baton-agent": this.agent,
|
|
140
|
+
accept: "application/json",
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
async call(method, path, body, timeoutMs = 10 * 60 * 1000) {
|
|
144
|
+
let response;
|
|
145
|
+
try {
|
|
146
|
+
response = await fetch(`${this.base}${path}`, {
|
|
147
|
+
method,
|
|
148
|
+
headers: {
|
|
149
|
+
...this.headers(),
|
|
150
|
+
...(body === undefined ? {} : { "content-type": "application/json" }),
|
|
151
|
+
},
|
|
152
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
153
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
throw new ToolError(`the Baton app is not answering (${String(error)}); it may have closed — restart the agent connection to work on the files instead`);
|
|
158
|
+
}
|
|
159
|
+
const text = await response.text();
|
|
160
|
+
let json = {};
|
|
161
|
+
try {
|
|
162
|
+
json = text ? JSON.parse(text) : {};
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
throw new ToolError(`the Baton app answered ${response.status} with something that is not JSON`);
|
|
166
|
+
}
|
|
167
|
+
if (!response.ok) {
|
|
168
|
+
throw new ToolError(typeof json.error === "string" ? json.error : `the Baton app answered ${response.status}`);
|
|
169
|
+
}
|
|
170
|
+
return json;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
//# sourceMappingURL=app.js.map
|
package/dist/src/index.js
CHANGED
|
@@ -1,47 +1,32 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { BatonTools
|
|
6
|
-
import { MCP_VERSION } from "./version.js";
|
|
2
|
+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
3
|
+
import { AppClient } from "./app.js";
|
|
4
|
+
import { buildServer } from "./server.js";
|
|
5
|
+
import { BatonTools } from "./tools.js";
|
|
7
6
|
function parseArgs(argv) {
|
|
8
7
|
let workspace = process.cwd();
|
|
9
8
|
let allowRun = false;
|
|
9
|
+
let agent = "an MCP agent";
|
|
10
10
|
for (let i = 0; i < argv.length; i++) {
|
|
11
11
|
if (argv[i] === "--workspace")
|
|
12
12
|
workspace = argv[++i] ?? workspace;
|
|
13
13
|
else if (argv[i] === "--allow-run")
|
|
14
14
|
allowRun = true;
|
|
15
|
+
else if (argv[i] === "--agent")
|
|
16
|
+
agent = argv[++i] ?? agent;
|
|
15
17
|
}
|
|
16
|
-
return { workspace, allowRun };
|
|
18
|
+
return { workspace, allowRun, agent };
|
|
17
19
|
}
|
|
18
|
-
const { workspace, allowRun } = parseArgs(process.argv.slice(2));
|
|
20
|
+
const { workspace, allowRun, agent } = parseArgs(process.argv.slice(2));
|
|
19
21
|
const tools = new BatonTools(workspace, allowRun);
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
throw error;
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
server.tool("workspace_info", "Workspace overview: collections, environments, schedules, load issues.", {}, () => respond(() => tools.workspaceInfo()));
|
|
34
|
-
server.tool("list_requests", "List requests (method, url, tags), optionally under one collection path.", { collection: z.string().optional() }, ({ collection }) => respond(() => tools.listRequests(collection)));
|
|
35
|
-
server.tool("get_request", "Full parsed request plus raw YAML and the collection that supplies its auth.", { path: z.string() }, ({ path }) => respond(() => tools.getRequest(path)));
|
|
36
|
-
server.tool("upsert_request", "Create or replace a request file from normalized request JSON. Auth must use {{secret:name}} references — literal credentials are rejected.", { path: z.string(), request: z.record(z.unknown()) }, ({ path, request }) => respond(() => tools.upsertRequest(path, request)));
|
|
37
|
-
server.tool("move_request", "Move or rename a request. Keeps its id, carries its own scripts along, and fixes the order lists of both folders.", { from: z.string(), to: z.string() }, ({ from, to }) => respond(() => tools.moveRequest(from, to)));
|
|
38
|
-
server.tool("delete_request", "Delete a request file.", { path: z.string() }, ({ path }) => respond(() => tools.deleteRequest(path)));
|
|
39
|
-
server.tool("upsert_collection", "Create or replace a collection or folder: name, variables, auth, order. Auth must use {{secret:name}} references.", { path: z.string(), collection: z.record(z.unknown()) }, ({ path, collection }) => respond(() => tools.upsertCollection(path, collection)));
|
|
40
|
-
server.tool("list_environments", "Environments with variables and secret NAMES (values never cross MCP).", {}, () => respond(() => tools.listEnvironments()));
|
|
41
|
-
server.tool("upsert_environment", "Create or replace an environment. `secrets` holds NAMES only — a variable named after a declared secret is rejected.", { path: z.string(), environment: z.record(z.unknown()) }, ({ path, environment }) => respond(() => tools.upsertEnvironment(path, environment)));
|
|
42
|
-
server.tool("get_script", "Read a pre-request/test script or shared library file.", { path: z.string() }, ({ path }) => respond(() => tools.getScript(path)));
|
|
43
|
-
server.tool("upsert_script", "Create or replace a .js script inside the workspace.", { path: z.string(), source: z.string() }, ({ path, source }) => respond(() => tools.upsertScript(path, source)));
|
|
44
|
-
server.tool("run_request", "Execute one request through the standard pipeline (requires --allow-run). Response headers are masked and bodies truncated.", { path: z.string(), environment: z.string().default("") }, ({ path, environment }) => respond(() => tools.runRequest(path, environment)));
|
|
45
|
-
server.tool("run_collection", "Execute every request under a collection path (requires --allow-run).", { collection: z.string(), environment: z.string().default("") }, ({ collection, environment }) => respond(() => tools.runCollection(collection, environment)));
|
|
46
|
-
await server.connect(new StdioServerTransport());
|
|
22
|
+
// Decided once, at startup: the app is either open for this workspace or it
|
|
23
|
+
// is not. The agent's configuration is the same either way (docs/MCP.md).
|
|
24
|
+
const app = await AppClient.discover(workspace, agent);
|
|
25
|
+
// stdout is the wire; anything to say goes to stderr.
|
|
26
|
+
console.error(app === null
|
|
27
|
+
? `baton-mcp: file mode on ${workspace} (the Baton app is not open on it)`
|
|
28
|
+
: `baton-mcp: app mode — edits land as drafts in the Baton app (pid ${app.pid})`);
|
|
29
|
+
serveStdio(() => buildServer(tools, app), {
|
|
30
|
+
onerror: (error) => console.error(`baton-mcp: ${error.message}`),
|
|
31
|
+
});
|
|
47
32
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/server";
|
|
2
|
+
import { AppClient } from "./app.js";
|
|
3
|
+
import { BatonTools } from "./tools.js";
|
|
4
|
+
/**
|
|
5
|
+
* What an agent is told about this server before it calls anything.
|
|
6
|
+
*
|
|
7
|
+
* Short on purpose: it goes into the agent's system prompt on every session.
|
|
8
|
+
* The rules here are the ones an agent gets wrong without being told — where
|
|
9
|
+
* secrets go, which paths are which, and that a run is live traffic.
|
|
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, 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
|
+
/** Appended when the desktop app is open on the workspace (app mode). */
|
|
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
|
+
/**
|
|
15
|
+
* Builds the server for one connection over [tools].
|
|
16
|
+
*
|
|
17
|
+
* Registration order is the order of this function, top to bottom, and that is
|
|
18
|
+
* the order tools/list returns them in — an agent reads the list once and
|
|
19
|
+
* builds a plan from it, so the orientation calls come first and the ones that
|
|
20
|
+
* send traffic come last.
|
|
21
|
+
*/
|
|
22
|
+
export declare function buildServer(tools: BatonTools, app?: AppClient | null): McpServer;
|
|
23
|
+
/** What the agent can subscribe to in app mode, and how it learns of change. */
|
|
24
|
+
export declare const APP_STATE_URI = "baton://app/state";
|
|
25
|
+
export declare const APP_SELECTION_URI = "baton://app/selection";
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/server";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { ToolError } from "./tools.js";
|
|
4
|
+
import { MCP_VERSION } from "./version.js";
|
|
5
|
+
/**
|
|
6
|
+
* What an agent is told about this server before it calls anything.
|
|
7
|
+
*
|
|
8
|
+
* Short on purpose: it goes into the agent's system prompt on every session.
|
|
9
|
+
* The rules here are the ones an agent gets wrong without being told — where
|
|
10
|
+
* secrets go, which paths are which, and that a run is live traffic.
|
|
11
|
+
*/
|
|
12
|
+
export 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.
|
|
13
|
+
|
|
14
|
+
Rules:
|
|
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, 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
|
+
- upsert_* tools write deterministic YAML, so a diff shows only what you changed. Keep the request's id when replacing one.
|
|
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
|
+
- Variables resolve as {{name}} from the active environment, then the collection and folder; a request's own variables come first.`;
|
|
20
|
+
/** Appended when the desktop app is open on the workspace (app mode). */
|
|
21
|
+
export const APP_MODE_INSTRUCTIONS = `
|
|
22
|
+
The Baton desktop app is open on this workspace, so you are working with the person in real time:
|
|
23
|
+
- 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.
|
|
24
|
+
- 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 — a refusal is their decision, not an error to work around.
|
|
25
|
+
- 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.`;
|
|
26
|
+
async function respond(fn) {
|
|
27
|
+
try {
|
|
28
|
+
const result = await fn();
|
|
29
|
+
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (error instanceof ToolError) {
|
|
33
|
+
return { content: [{ type: "text", text: error.message }], isError: true };
|
|
34
|
+
}
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** How long an agent may hold a tools/list answer: the set is static. */
|
|
39
|
+
const LIST_CACHE = { ttlMs: 60 * 60 * 1000, cacheScope: "private" };
|
|
40
|
+
/**
|
|
41
|
+
* Builds the server for one connection over [tools].
|
|
42
|
+
*
|
|
43
|
+
* Registration order is the order of this function, top to bottom, and that is
|
|
44
|
+
* the order tools/list returns them in — an agent reads the list once and
|
|
45
|
+
* builds a plan from it, so the orientation calls come first and the ones that
|
|
46
|
+
* send traffic come last.
|
|
47
|
+
*/
|
|
48
|
+
export function buildServer(tools, app = null) {
|
|
49
|
+
const server = new McpServer({ name: "baton", version: MCP_VERSION }, {
|
|
50
|
+
capabilities: {
|
|
51
|
+
tools: {},
|
|
52
|
+
prompts: {},
|
|
53
|
+
...(app ? { resources: { subscribe: true, listChanged: false } } : {}),
|
|
54
|
+
},
|
|
55
|
+
instructions: app ? INSTRUCTIONS + APP_MODE_INSTRUCTIONS : INSTRUCTIONS,
|
|
56
|
+
cacheHints: { "tools/list": LIST_CACHE, "prompts/list": LIST_CACHE },
|
|
57
|
+
});
|
|
58
|
+
// After a file write in app mode the app re-reads the workspace, so the
|
|
59
|
+
// sidebar shows the change at once. Best effort: the write already landed.
|
|
60
|
+
const reloadApp = async (result) => {
|
|
61
|
+
if (app)
|
|
62
|
+
await app.reload().catch(() => undefined);
|
|
63
|
+
return result;
|
|
64
|
+
};
|
|
65
|
+
server.registerTool("workspace_info", {
|
|
66
|
+
description: "Workspace overview: collections, environments, schedules, load issues.",
|
|
67
|
+
annotations: { readOnlyHint: true },
|
|
68
|
+
}, () => respond(async () => {
|
|
69
|
+
const info = tools.workspaceInfo();
|
|
70
|
+
if (!app)
|
|
71
|
+
return { ...info, app: { connected: false } };
|
|
72
|
+
const state = await app.state();
|
|
73
|
+
return {
|
|
74
|
+
...info,
|
|
75
|
+
app: {
|
|
76
|
+
connected: true,
|
|
77
|
+
selection: state.selection ?? null,
|
|
78
|
+
environment: state.environment ?? null,
|
|
79
|
+
drafts: state.drafts ?? [],
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}));
|
|
83
|
+
if (app) {
|
|
84
|
+
server.registerTool("app_state", {
|
|
85
|
+
description: "What the person sees in the Baton app right now: the open request, the active environment, open tabs, drafts waiting for review, and what the last sends answered (status, timing, test tally — never a body or a secret).",
|
|
86
|
+
annotations: { readOnlyHint: true },
|
|
87
|
+
}, () => respond(() => app.state()));
|
|
88
|
+
server.registerTool("select_request", {
|
|
89
|
+
description: "Open a request in the Baton app, so the person is looking at the same one you are.",
|
|
90
|
+
inputSchema: z.object({ path: z.string() }),
|
|
91
|
+
}, ({ path }) => respond(() => app.select(path)));
|
|
92
|
+
}
|
|
93
|
+
server.registerTool("list_requests", {
|
|
94
|
+
description: "List requests (method, url, tags), optionally under one collection path.",
|
|
95
|
+
inputSchema: z.object({ collection: z.string().optional() }),
|
|
96
|
+
annotations: { readOnlyHint: true },
|
|
97
|
+
}, ({ collection }) => respond(() => tools.listRequests(collection)));
|
|
98
|
+
server.registerTool("get_request", {
|
|
99
|
+
description: "Full parsed request plus raw YAML and the collection that supplies its auth.",
|
|
100
|
+
inputSchema: z.object({ path: z.string() }),
|
|
101
|
+
annotations: { readOnlyHint: true },
|
|
102
|
+
}, ({ path }) => respond(() => tools.getRequest(path)));
|
|
103
|
+
server.registerTool("upsert_request", {
|
|
104
|
+
description: app
|
|
105
|
+
? "Propose a request as a DRAFT on its tab in the Baton app, for the person to accept; a request that does not exist yet is created as a file. Auth must use {{secret:name}} references — literal credentials are rejected."
|
|
106
|
+
: "Create or replace a request file from normalized request JSON. Auth must use {{secret:name}} references — literal credentials are rejected.",
|
|
107
|
+
inputSchema: z.object({ path: z.string(), request: z.record(z.string(), z.unknown()) }),
|
|
108
|
+
annotations: { idempotentHint: true },
|
|
109
|
+
}, ({ path, request }) => respond(() => {
|
|
110
|
+
if (!app)
|
|
111
|
+
return tools.upsertRequest(path, request);
|
|
112
|
+
// The same checks a file write gets, then the app takes it as a
|
|
113
|
+
// draft on the request's tab (or creates the file for a new one).
|
|
114
|
+
tools.validateRequest(path, request);
|
|
115
|
+
return app.draft(path, request);
|
|
116
|
+
}));
|
|
117
|
+
server.registerTool("move_request", {
|
|
118
|
+
description: "Move or rename a request. Keeps its id, carries its own scripts along, and fixes the order lists of both folders.",
|
|
119
|
+
inputSchema: z.object({ from: z.string(), to: z.string() }),
|
|
120
|
+
}, ({ from, to }) => respond(() => reloadApp(tools.moveRequest(from, to))));
|
|
121
|
+
server.registerTool("delete_request", {
|
|
122
|
+
description: app
|
|
123
|
+
? "Delete a request. The person confirms in the Baton app first; a refusal comes back as an error."
|
|
124
|
+
: "Delete a request file.",
|
|
125
|
+
inputSchema: z.object({ path: z.string() }),
|
|
126
|
+
annotations: { destructiveHint: true },
|
|
127
|
+
}, ({ path }) => respond(() => (app ? app.delete(path) : tools.deleteRequest(path))));
|
|
128
|
+
server.registerTool("upsert_collection", {
|
|
129
|
+
description: "Create or replace a collection or folder: name, variables, auth, order. Auth must use {{secret:name}} references.",
|
|
130
|
+
inputSchema: z.object({ path: z.string(), collection: z.record(z.string(), z.unknown()) }),
|
|
131
|
+
annotations: { idempotentHint: true },
|
|
132
|
+
}, ({ path, collection }) => respond(() => reloadApp(tools.upsertCollection(path, collection))));
|
|
133
|
+
server.registerTool("list_environments", {
|
|
134
|
+
description: "Environments with variables and secret NAMES (values never cross MCP).",
|
|
135
|
+
annotations: { readOnlyHint: true },
|
|
136
|
+
}, () => respond(() => tools.listEnvironments()));
|
|
137
|
+
server.registerTool("upsert_environment", {
|
|
138
|
+
description: "Create or replace an environment. `secrets` holds NAMES only — a variable named after a declared secret is rejected. `vault` may map a secret name to a Vault location `<mount>/<path>#<key>`, read at send time; the token is never part of the workspace.",
|
|
139
|
+
inputSchema: z.object({ path: z.string(), environment: z.record(z.string(), z.unknown()) }),
|
|
140
|
+
annotations: { idempotentHint: true },
|
|
141
|
+
}, ({ path, environment }) => respond(() => reloadApp(tools.upsertEnvironment(path, environment))));
|
|
142
|
+
server.registerTool("get_script", {
|
|
143
|
+
description: "Read a pre-request/test script or shared library file.",
|
|
144
|
+
inputSchema: z.object({ path: z.string() }),
|
|
145
|
+
annotations: { readOnlyHint: true },
|
|
146
|
+
}, ({ path }) => respond(() => tools.getScript(path)));
|
|
147
|
+
server.registerTool("upsert_script", {
|
|
148
|
+
description: "Create or replace a .js script inside the workspace.",
|
|
149
|
+
inputSchema: z.object({ path: z.string(), source: z.string() }),
|
|
150
|
+
annotations: { idempotentHint: true },
|
|
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))));
|
|
166
|
+
server.registerTool("run_request", {
|
|
167
|
+
description: app
|
|
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."
|
|
169
|
+
: "Execute one request through the standard pipeline (requires --allow-run). Response headers are masked and bodies truncated.",
|
|
170
|
+
inputSchema: z.object({ path: z.string(), environment: z.string().default("") }),
|
|
171
|
+
annotations: { openWorldHint: true },
|
|
172
|
+
}, ({ path, environment }) => respond(() => app ? app.send(path, environment || undefined) : tools.runRequest(path, environment)));
|
|
173
|
+
server.registerTool("run_collection", {
|
|
174
|
+
description: app
|
|
175
|
+
? "Send every request under a collection path through the Baton app, one after another."
|
|
176
|
+
: "Execute every request under a collection path (requires --allow-run).",
|
|
177
|
+
inputSchema: z.object({ collection: z.string(), environment: z.string().default("") }),
|
|
178
|
+
annotations: { openWorldHint: true },
|
|
179
|
+
}, ({ collection, environment }) => respond(async () => {
|
|
180
|
+
if (!app)
|
|
181
|
+
return tools.runCollection(collection, environment);
|
|
182
|
+
const results = [];
|
|
183
|
+
for (const entry of tools.listRequests(collection)) {
|
|
184
|
+
results.push(await app.send(entry.path, environment || undefined));
|
|
185
|
+
}
|
|
186
|
+
return results;
|
|
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
|
+
}));
|
|
203
|
+
server.registerTool("list_examples", {
|
|
204
|
+
description: "A request's saved responses (<slug>.examples.yaml beside it): names, statuses, sizes. Examples are what a mock answers with.",
|
|
205
|
+
inputSchema: z.object({ path: z.string() }),
|
|
206
|
+
annotations: { readOnlyHint: true },
|
|
207
|
+
}, ({ path }) => respond(() => tools.listExamples(path)));
|
|
208
|
+
server.registerTool("save_example", {
|
|
209
|
+
description: app
|
|
210
|
+
? "Save the response the Baton app last got for a request as a named example, replacing one of the same name."
|
|
211
|
+
: "Save the response run_request last got for a request as a named example, replacing one of the same name.",
|
|
212
|
+
inputSchema: z.object({ path: z.string(), name: z.string() }),
|
|
213
|
+
annotations: { idempotentHint: true },
|
|
214
|
+
}, ({ path, name }) => respond(() => (app ? app.saveExample(path, name) : tools.saveExample(path, name))));
|
|
215
|
+
server.registerTool("list_mocks", {
|
|
216
|
+
description: "The mocks defined under mocks/*.yaml, with their ports and whether this server is running them.",
|
|
217
|
+
annotations: { readOnlyHint: true },
|
|
218
|
+
}, () => respond(() => tools.listMocks()));
|
|
219
|
+
server.registerTool("start_mock", {
|
|
220
|
+
description: "Stand a mock up from mocks/<name>.yaml on 127.0.0.1 at its port: every request under its collections that has an example answers with it. Runs in this process until stop_mock or the connection ends.",
|
|
221
|
+
inputSchema: z.object({ name: z.string() }),
|
|
222
|
+
}, ({ name }) => respond(() => tools.startMock(name)));
|
|
223
|
+
server.registerTool("stop_mock", {
|
|
224
|
+
description: "Take a running mock down.",
|
|
225
|
+
inputSchema: z.object({ name: z.string() }),
|
|
226
|
+
annotations: { idempotentHint: true },
|
|
227
|
+
}, ({ name }) => respond(() => tools.stopMock(name)));
|
|
228
|
+
// Mocks die with the connection: a port left open by an agent that is
|
|
229
|
+
// gone is a surprise nobody asked for.
|
|
230
|
+
const previousClose = server.server.onclose;
|
|
231
|
+
server.server.onclose = () => {
|
|
232
|
+
void tools.mocks.stopAll();
|
|
233
|
+
previousClose?.();
|
|
234
|
+
};
|
|
235
|
+
registerPrompts(server, app !== null);
|
|
236
|
+
if (app)
|
|
237
|
+
registerAppResources(server, app);
|
|
238
|
+
return server;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Two ways of working an agent host offers from its prompt menu. Each is a
|
|
242
|
+
* plan the agent follows with the tools above — written here so the plan
|
|
243
|
+
* says where the files are and what not to do, rather than being improvised.
|
|
244
|
+
*/
|
|
245
|
+
function registerPrompts(server, appMode) {
|
|
246
|
+
const landing = appMode
|
|
247
|
+
? "Edits land as drafts on the request's tab in the Baton app; say so, and let the person accept them."
|
|
248
|
+
: "Edits are written to the workspace files; the person reviews them in git.";
|
|
249
|
+
server.registerPrompt("debug-failing-request", {
|
|
250
|
+
title: "Debug a failing request",
|
|
251
|
+
description: "Find out why a request fails and propose the fix.",
|
|
252
|
+
argsSchema: z.object({
|
|
253
|
+
path: z.string().describe("Workspace-relative path, collections/<...>/<slug>.req.yaml"),
|
|
254
|
+
environment: z.string().optional().describe("Environment slug; the active one when omitted"),
|
|
255
|
+
}),
|
|
256
|
+
}, ({ path, environment }) => ({
|
|
257
|
+
messages: [
|
|
258
|
+
{
|
|
259
|
+
role: "user",
|
|
260
|
+
content: {
|
|
261
|
+
type: "text",
|
|
262
|
+
text: [
|
|
263
|
+
`Debug the Baton request at ${path}${environment ? ` in the ${environment} environment` : ""}.`,
|
|
264
|
+
"1. get_request to read it and the collection its auth comes from; list_environments for the variables it resolves against. Secrets are references — do not ask for values.",
|
|
265
|
+
"2. run_request and read the status, the headers, the body, the test results and the console. Note the final URL and what the request actually sent.",
|
|
266
|
+
"3. Diagnose: an unresolved {{variable}}, a wrong base URL, a missing header, an auth that is inherited from the wrong collection, a body the API rejects, or a test that asserts the wrong thing.",
|
|
267
|
+
`4. Propose the smallest change with upsert_request (or upsert_script for a test). ${landing}`,
|
|
268
|
+
"5. Run it again and report what changed — status before and after, and which test outcomes moved.",
|
|
269
|
+
].join("\n"),
|
|
270
|
+
},
|
|
271
|
+
},
|
|
272
|
+
],
|
|
273
|
+
}));
|
|
274
|
+
server.registerPrompt("write-tests", {
|
|
275
|
+
title: "Write tests for a collection",
|
|
276
|
+
description: "Add a test script to every request under a collection that has none.",
|
|
277
|
+
argsSchema: z.object({
|
|
278
|
+
collection: z.string().describe("Workspace-relative collection path, collections/<name>"),
|
|
279
|
+
}),
|
|
280
|
+
}, ({ collection }) => ({
|
|
281
|
+
messages: [
|
|
282
|
+
{
|
|
283
|
+
role: "user",
|
|
284
|
+
content: {
|
|
285
|
+
type: "text",
|
|
286
|
+
text: [
|
|
287
|
+
`Write test scripts for the requests under ${collection} in this Baton workspace.`,
|
|
288
|
+
"1. list_requests on the collection, then get_request on each; skip any whose scripts.tests is already set.",
|
|
289
|
+
"2. For each request, run_request once to see the real shape of a good response (status, content type, the fields that are always there).",
|
|
290
|
+
"3. Write a .test.js beside the request with upsert_script: baton.test('name', () => { ... }) blocks using baton.response.status, baton.response.json() and baton.expect(...). Assert what the API promises, not incidental values. Docs: the baton.* API is in SCRIPTING.md.",
|
|
291
|
+
`4. Point the request at it with upsert_request, setting scripts.tests to "./<slug>.test.js" and changing nothing else. ${landing}`,
|
|
292
|
+
"5. run_request again and report the tally per request; fix a test that fails for a reason in the test rather than in the API.",
|
|
293
|
+
].join("\n"),
|
|
294
|
+
},
|
|
295
|
+
},
|
|
296
|
+
],
|
|
297
|
+
}));
|
|
298
|
+
}
|
|
299
|
+
/** What the agent can subscribe to in app mode, and how it learns of change. */
|
|
300
|
+
export const APP_STATE_URI = "baton://app/state";
|
|
301
|
+
export const APP_SELECTION_URI = "baton://app/selection";
|
|
302
|
+
/**
|
|
303
|
+
* Two resources over the app's state, kept current by the app's event stream:
|
|
304
|
+
* a change in the app becomes `notifications/resources/updated` on the
|
|
305
|
+
* agent's subscription, and the next read answers with the new state. The
|
|
306
|
+
* stream is followed for as long as this connection lives.
|
|
307
|
+
*/
|
|
308
|
+
function registerAppResources(server, app) {
|
|
309
|
+
server.registerResource("app-state", APP_STATE_URI, {
|
|
310
|
+
title: "Baton app state",
|
|
311
|
+
description: "The open request, the active environment, open tabs, drafts waiting for review, and the last sends' outcomes.",
|
|
312
|
+
mimeType: "application/json",
|
|
313
|
+
}, async (uri) => ({
|
|
314
|
+
contents: [
|
|
315
|
+
{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(await app.state(), null, 2) },
|
|
316
|
+
],
|
|
317
|
+
}));
|
|
318
|
+
server.registerResource("app-selection", APP_SELECTION_URI, {
|
|
319
|
+
title: "Selected request",
|
|
320
|
+
description: "The workspace-relative path of the request open in the Baton app, or empty.",
|
|
321
|
+
mimeType: "text/plain",
|
|
322
|
+
}, async (uri) => ({
|
|
323
|
+
contents: [
|
|
324
|
+
{
|
|
325
|
+
uri: uri.href,
|
|
326
|
+
mimeType: "text/plain",
|
|
327
|
+
text: String((await app.state()).selection ?? ""),
|
|
328
|
+
},
|
|
329
|
+
],
|
|
330
|
+
}));
|
|
331
|
+
const abort = new AbortController();
|
|
332
|
+
const notify = (uri) => {
|
|
333
|
+
// Nothing listening is not an error, and neither is a transport that
|
|
334
|
+
// closed between the event and the send.
|
|
335
|
+
server.server.sendResourceUpdated({ uri }).catch(() => undefined);
|
|
336
|
+
};
|
|
337
|
+
void app.events((event) => {
|
|
338
|
+
if (event.type === "hello")
|
|
339
|
+
return;
|
|
340
|
+
notify(APP_STATE_URI);
|
|
341
|
+
if (event.type === "selection")
|
|
342
|
+
notify(APP_SELECTION_URI);
|
|
343
|
+
}, abort.signal);
|
|
344
|
+
const previous = server.server.onclose;
|
|
345
|
+
server.server.onclose = () => {
|
|
346
|
+
abort.abort();
|
|
347
|
+
previous?.();
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
//# sourceMappingURL=server.js.map
|
package/dist/src/tools.d.ts
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
|
-
import { CollectionFile, EnvironmentFile, RequestFile } from "@dudko.dev/baton-format";
|
|
1
|
+
import { CollectionFile, EnvironmentFile, FlowFile, RequestFile } from "@dudko.dev/baton-format";
|
|
2
|
+
import { MockRegistry } from "@dudko.dev/baton-worker";
|
|
2
3
|
/** Tool-layer errors carry a message meant for the calling agent. */
|
|
3
4
|
export declare class ToolError extends Error {
|
|
4
5
|
}
|
|
5
6
|
export declare class BatonTools {
|
|
6
7
|
private readonly root;
|
|
7
8
|
private readonly allowRun;
|
|
9
|
+
/** The last response per request path, for save_example in file mode. */
|
|
10
|
+
private readonly lastRuns;
|
|
11
|
+
/** Mocks this process stands up (docs/WORKER.md, "Mock servers"). */
|
|
12
|
+
readonly mocks: MockRegistry;
|
|
8
13
|
constructor(root: string, allowRun: boolean);
|
|
9
14
|
private workspace;
|
|
10
15
|
/** Rejects absolute paths and traversal; returns the workspace-rooted path. */
|
|
@@ -12,6 +17,13 @@ export declare class BatonTools {
|
|
|
12
17
|
workspaceInfo(): unknown;
|
|
13
18
|
listRequests(collectionPath?: string): unknown;
|
|
14
19
|
getRequest(path: string): unknown;
|
|
20
|
+
/**
|
|
21
|
+
* The checks every request an agent hands over goes through, whichever
|
|
22
|
+
* way it lands — written here, or drafted in the app: the path shape, no
|
|
23
|
+
* literal credential, and a round trip through the parser so invalid input
|
|
24
|
+
* fails before anything is written. Returns the canonical bytes.
|
|
25
|
+
*/
|
|
26
|
+
validateRequest(path: string, request: RequestFile): string;
|
|
15
27
|
/** Validates and writes a request; input is the normalized request JSON. */
|
|
16
28
|
upsertRequest(path: string, request: RequestFile): unknown;
|
|
17
29
|
/**
|
|
@@ -33,11 +45,53 @@ export declare class BatonTools {
|
|
|
33
45
|
upsertCollection(path: string, collection: CollectionFile): unknown;
|
|
34
46
|
deleteRequest(path: string): unknown;
|
|
35
47
|
listEnvironments(): unknown;
|
|
36
|
-
/**
|
|
48
|
+
/**
|
|
49
|
+
* Creates or replaces an environment. Secret **names** only (invariant 2);
|
|
50
|
+
* `vault` may map a name to a Vault location, which is still not a value.
|
|
51
|
+
*/
|
|
37
52
|
upsertEnvironment(path: string, environment: EnvironmentFile): unknown;
|
|
38
53
|
getScript(path: string): unknown;
|
|
39
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>;
|
|
40
82
|
runRequest(path: string, environment: string): Promise<unknown>;
|
|
83
|
+
/** A request's saved responses, names and sizes — the bodies stay in the file. */
|
|
84
|
+
listExamples(path: string): unknown;
|
|
85
|
+
/**
|
|
86
|
+
* Saves the last response this process got for [path] (run_request) as an
|
|
87
|
+
* example named [name], replacing one of the same name. The body is saved
|
|
88
|
+
* as the API answered — the file is the workspace, not an agent result —
|
|
89
|
+
* and only the name and the size come back.
|
|
90
|
+
*/
|
|
91
|
+
saveExample(path: string, name: string): unknown;
|
|
92
|
+
listMocks(): unknown;
|
|
93
|
+
startMock(name: string): Promise<unknown>;
|
|
94
|
+
stopMock(name: string): Promise<unknown>;
|
|
41
95
|
runCollection(collectionPath: string, environment: string): Promise<unknown>;
|
|
42
96
|
/**
|
|
43
97
|
* Rewrites the `order` list of the collection or folder at [directory].
|
package/dist/src/tools.js
CHANGED
|
@@ -1,21 +1,28 @@
|
|
|
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, serializeRequestFile, } from "@dudko.dev/baton-format";
|
|
4
|
-
import { findRequest, maskSecrets, 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;
|
|
12
14
|
allowRun;
|
|
15
|
+
/** The last response per request path, for save_example in file mode. */
|
|
16
|
+
lastRuns = new Map();
|
|
17
|
+
/** Mocks this process stands up (docs/WORKER.md, "Mock servers"). */
|
|
18
|
+
mocks;
|
|
13
19
|
constructor(root, allowRun) {
|
|
14
20
|
this.root = root;
|
|
15
21
|
this.allowRun = allowRun;
|
|
16
22
|
if (!existsSync(join(root, "baton.yaml"))) {
|
|
17
23
|
throw new ToolError(`${root} is not a Baton workspace (no baton.yaml)`);
|
|
18
24
|
}
|
|
25
|
+
this.mocks = new MockRegistry(() => this.workspace());
|
|
19
26
|
}
|
|
20
27
|
workspace() {
|
|
21
28
|
return openWorkspace(this.root);
|
|
@@ -40,6 +47,7 @@ export class BatonTools {
|
|
|
40
47
|
name: ws.manifest.name,
|
|
41
48
|
collections: summarize(ws.collections),
|
|
42
49
|
environments: ws.environments.map((e) => e.slug),
|
|
50
|
+
flows: ws.flows.map((f) => f.path),
|
|
43
51
|
schedules: ws.schedules?.schedules.map((s) => s.id) ?? [],
|
|
44
52
|
issues: ws.issues,
|
|
45
53
|
runsEnabled: this.allowRun,
|
|
@@ -69,21 +77,29 @@ export class BatonTools {
|
|
|
69
77
|
raw: readFileSync(this.safePath(path), "utf8"),
|
|
70
78
|
};
|
|
71
79
|
}
|
|
72
|
-
/**
|
|
73
|
-
|
|
80
|
+
/**
|
|
81
|
+
* The checks every request an agent hands over goes through, whichever
|
|
82
|
+
* way it lands — written here, or drafted in the app: the path shape, no
|
|
83
|
+
* literal credential, and a round trip through the parser so invalid input
|
|
84
|
+
* fails before anything is written. Returns the canonical bytes.
|
|
85
|
+
*/
|
|
86
|
+
validateRequest(path, request) {
|
|
74
87
|
if (!path.endsWith(".req.yaml")) {
|
|
75
88
|
throw new ToolError("request path must end with .req.yaml");
|
|
76
89
|
}
|
|
77
90
|
rejectLiteralSecrets(request.auth);
|
|
78
|
-
let canonical;
|
|
79
91
|
try {
|
|
80
|
-
canonical = serializeRequestFile(request);
|
|
81
|
-
// Round-trip through the parser so invalid input fails before writing.
|
|
92
|
+
const canonical = serializeRequestFile(request);
|
|
82
93
|
parseRequestFile(canonical);
|
|
94
|
+
return canonical;
|
|
83
95
|
}
|
|
84
96
|
catch (error) {
|
|
85
97
|
throw new ToolError(`invalid request: ${String(error)}`);
|
|
86
98
|
}
|
|
99
|
+
}
|
|
100
|
+
/** Validates and writes a request; input is the normalized request JSON. */
|
|
101
|
+
upsertRequest(path, request) {
|
|
102
|
+
const canonical = this.validateRequest(path, request);
|
|
87
103
|
const target = this.safePath(path);
|
|
88
104
|
mkdirSync(dirname(target), { recursive: true });
|
|
89
105
|
writeFileSync(target, canonical);
|
|
@@ -173,9 +189,15 @@ export class BatonTools {
|
|
|
173
189
|
slug: entry.slug,
|
|
174
190
|
variables: entry.environment.variables,
|
|
175
191
|
secrets: entry.environment.secrets,
|
|
192
|
+
// Locations, not values: which declared secrets are read from Vault,
|
|
193
|
+
// and where (`<mount>/<path>#<key>`).
|
|
194
|
+
...(entry.environment.vault !== undefined ? { vault: entry.environment.vault } : {}),
|
|
176
195
|
}));
|
|
177
196
|
}
|
|
178
|
-
/**
|
|
197
|
+
/**
|
|
198
|
+
* Creates or replaces an environment. Secret **names** only (invariant 2);
|
|
199
|
+
* `vault` may map a name to a Vault location, which is still not a value.
|
|
200
|
+
*/
|
|
179
201
|
upsertEnvironment(path, environment) {
|
|
180
202
|
if (!path.endsWith(".env.yaml")) {
|
|
181
203
|
throw new ToolError("environment path must end with .env.yaml");
|
|
@@ -191,6 +213,14 @@ export class BatonTools {
|
|
|
191
213
|
`secret name; the value belongs in the OS secure store`);
|
|
192
214
|
}
|
|
193
215
|
}
|
|
216
|
+
// The writer emits a Vault path only under a declared secret; a path
|
|
217
|
+
// for any other name would vanish without a word.
|
|
218
|
+
for (const name of Object.keys(environment.vault ?? {})) {
|
|
219
|
+
if (!declared.has(name)) {
|
|
220
|
+
throw new ToolError(`vault names ${name}, which is not in secrets — declare it as a ` +
|
|
221
|
+
`secret, or drop the Vault path`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
194
224
|
let canonical;
|
|
195
225
|
try {
|
|
196
226
|
canonical = serializeEnvironmentFile(environment);
|
|
@@ -220,11 +250,201 @@ export class BatonTools {
|
|
|
220
250
|
writeFileSync(target, source);
|
|
221
251
|
return { path, bytes: source.length };
|
|
222
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
|
+
}
|
|
223
366
|
async runRequest(path, environment) {
|
|
224
367
|
this.assertRunsEnabled();
|
|
225
368
|
const result = await runWorkspaceRequest(this.workspace(), path, environment);
|
|
369
|
+
// Kept masked by value: what save_example writes into the workspace is
|
|
370
|
+
// what the agent was shown, never a credential the API echoed back
|
|
371
|
+
// (invariant 2) — a mock would otherwise serve it to anyone.
|
|
372
|
+
const secrets = secretsFromEnv(process.env);
|
|
373
|
+
this.lastRuns.set(path, {
|
|
374
|
+
status: result.status,
|
|
375
|
+
headers: result.headers.map(([name, value]) => [maskSecrets(name, secrets), maskSecrets(value, secrets)]),
|
|
376
|
+
bodyText: maskSecrets(result.bodyText, secrets),
|
|
377
|
+
});
|
|
226
378
|
return redactResult(result);
|
|
227
379
|
}
|
|
380
|
+
/** A request's saved responses, names and sizes — the bodies stay in the file. */
|
|
381
|
+
listExamples(path) {
|
|
382
|
+
const found = findRequest(this.workspace(), path);
|
|
383
|
+
if (!found)
|
|
384
|
+
throw new ToolError(`request not found: ${path}`);
|
|
385
|
+
return {
|
|
386
|
+
path,
|
|
387
|
+
file: examplesPathFor(path),
|
|
388
|
+
examples: found.entry.examples.map((example) => ({
|
|
389
|
+
name: example.name,
|
|
390
|
+
status: example.status,
|
|
391
|
+
headers: example.headers.length,
|
|
392
|
+
bodyBytes: Buffer.byteLength(example.body),
|
|
393
|
+
})),
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Saves the last response this process got for [path] (run_request) as an
|
|
398
|
+
* example named [name], replacing one of the same name. The body is saved
|
|
399
|
+
* as the API answered — the file is the workspace, not an agent result —
|
|
400
|
+
* and only the name and the size come back.
|
|
401
|
+
*/
|
|
402
|
+
saveExample(path, name) {
|
|
403
|
+
const found = findRequest(this.workspace(), path);
|
|
404
|
+
if (!found)
|
|
405
|
+
throw new ToolError(`request not found: ${path}`);
|
|
406
|
+
if (name.trim() === "")
|
|
407
|
+
throw new ToolError("the example needs a name");
|
|
408
|
+
const last = this.lastRuns.get(path);
|
|
409
|
+
if (!last || last.status <= 0) {
|
|
410
|
+
throw new ToolError(`no response for ${path} in this session — run_request it first`);
|
|
411
|
+
}
|
|
412
|
+
const example = {
|
|
413
|
+
name: name.trim(),
|
|
414
|
+
status: last.status,
|
|
415
|
+
headers: last.headers
|
|
416
|
+
.filter(([header]) => !HOP_BY_HOP.has(header.toLowerCase()))
|
|
417
|
+
.map(([header, value]) => ({ name: header.toLowerCase(), value, enabled: true })),
|
|
418
|
+
body: last.bodyText,
|
|
419
|
+
};
|
|
420
|
+
const existing = found.entry.examples;
|
|
421
|
+
const index = existing.findIndex((e) => e.name === example.name);
|
|
422
|
+
const examples = index < 0 ? [...existing, example] : existing.map((e, i) => (i === index ? example : e));
|
|
423
|
+
const file = examplesPathFor(path);
|
|
424
|
+
writeFileSync(this.safePath(file), serializeExamplesFile({ format: 1, examples }));
|
|
425
|
+
return { path, file, example: example.name, status: example.status, bodyBytes: Buffer.byteLength(example.body) };
|
|
426
|
+
}
|
|
427
|
+
listMocks() {
|
|
428
|
+
return this.mocks.list();
|
|
429
|
+
}
|
|
430
|
+
async startMock(name) {
|
|
431
|
+
try {
|
|
432
|
+
const started = await this.mocks.start(name);
|
|
433
|
+
return {
|
|
434
|
+
name,
|
|
435
|
+
url: `http://127.0.0.1:${started.port}`,
|
|
436
|
+
routes: started.routes,
|
|
437
|
+
running: true,
|
|
438
|
+
note: "Point the client you are writing at this URL; a request without examples is not routed.",
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
catch (error) {
|
|
442
|
+
throw new ToolError(String(error instanceof Error ? error.message : error));
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
async stopMock(name) {
|
|
446
|
+
return { name, running: false, stopped: await this.mocks.stop(name) };
|
|
447
|
+
}
|
|
228
448
|
async runCollection(collectionPath, environment) {
|
|
229
449
|
this.assertRunsEnabled();
|
|
230
450
|
const ws = this.workspace();
|
|
@@ -289,6 +509,16 @@ export class BatonTools {
|
|
|
289
509
|
}
|
|
290
510
|
}
|
|
291
511
|
}
|
|
512
|
+
/** Response headers that describe the hop, not the answer; a replay must not carry them. */
|
|
513
|
+
const HOP_BY_HOP = new Set([
|
|
514
|
+
"connection",
|
|
515
|
+
"keep-alive",
|
|
516
|
+
"transfer-encoding",
|
|
517
|
+
"content-length",
|
|
518
|
+
"content-encoding",
|
|
519
|
+
"date",
|
|
520
|
+
"set-cookie",
|
|
521
|
+
]);
|
|
292
522
|
/** Literal credentials in auth config are rejected — reference a secret. */
|
|
293
523
|
function rejectLiteralSecrets(auth) {
|
|
294
524
|
const fields = [];
|
|
@@ -311,7 +541,12 @@ function rejectLiteralSecrets(auth) {
|
|
|
311
541
|
}
|
|
312
542
|
}
|
|
313
543
|
}
|
|
314
|
-
function redactResult(
|
|
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;
|
|
315
550
|
// Masking by *name* is not enough, which is what this used to do.
|
|
316
551
|
//
|
|
317
552
|
// rejectLiteralSecrets guards `auth.*`, so an agent cannot store a literal
|
package/dist/src/version.d.ts
CHANGED
package/dist/src/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dudko.dev/baton-mcp",
|
|
3
|
-
"version": "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
|
-
"keywords": [
|
|
6
|
+
"keywords": [
|
|
7
|
+
"baton",
|
|
8
|
+
"mcp",
|
|
9
|
+
"model-context-protocol",
|
|
10
|
+
"api-client",
|
|
11
|
+
"ai-agent"
|
|
12
|
+
],
|
|
7
13
|
"homepage": "https://baton.dudko.dev",
|
|
8
14
|
"repository": {
|
|
9
15
|
"type": "git",
|
|
@@ -24,19 +30,23 @@
|
|
|
24
30
|
"access": "public",
|
|
25
31
|
"registry": "https://registry.npmjs.org/"
|
|
26
32
|
},
|
|
27
|
-
"files": [
|
|
33
|
+
"files": [
|
|
34
|
+
"dist/src/**/*.js",
|
|
35
|
+
"dist/src/**/*.d.ts"
|
|
36
|
+
],
|
|
28
37
|
"scripts": {
|
|
29
38
|
"build": "tsc",
|
|
30
39
|
"test": "tsc && node --test \"dist/test/*.test.js\"",
|
|
31
40
|
"prepublishOnly": "tsc"
|
|
32
41
|
},
|
|
33
42
|
"dependencies": {
|
|
34
|
-
"@dudko.dev/baton-format": "^0.
|
|
35
|
-
"@dudko.dev/baton-worker": "^0.
|
|
36
|
-
"@modelcontextprotocol/
|
|
37
|
-
"zod": "^
|
|
43
|
+
"@dudko.dev/baton-format": "^0.3.0",
|
|
44
|
+
"@dudko.dev/baton-worker": "^0.4.0",
|
|
45
|
+
"@modelcontextprotocol/server": "^2.3.1",
|
|
46
|
+
"zod": "^4.6.5"
|
|
38
47
|
},
|
|
39
48
|
"devDependencies": {
|
|
49
|
+
"@modelcontextprotocol/client": "^2.3.1",
|
|
40
50
|
"@types/node": "^24.0.0",
|
|
41
51
|
"typescript": "^5.5.0"
|
|
42
52
|
}
|