@dudko.dev/baton-mcp 0.1.3 → 0.2.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 +321 -0
- package/dist/src/tools.d.ts +28 -1
- package/dist/src/tools.js +122 -8
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +16 -6
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. 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.";
|
|
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,321 @@
|
|
|
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. 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 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.
|
|
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("run_request", {
|
|
153
|
+
description: app
|
|
154
|
+
? "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."
|
|
155
|
+
: "Execute one request through the standard pipeline (requires --allow-run). Response headers are masked and bodies truncated.",
|
|
156
|
+
inputSchema: z.object({ path: z.string(), environment: z.string().default("") }),
|
|
157
|
+
annotations: { openWorldHint: true },
|
|
158
|
+
}, ({ path, environment }) => respond(() => app ? app.send(path, environment || undefined) : tools.runRequest(path, environment)));
|
|
159
|
+
server.registerTool("run_collection", {
|
|
160
|
+
description: app
|
|
161
|
+
? "Send every request under a collection path through the Baton app, one after another."
|
|
162
|
+
: "Execute every request under a collection path (requires --allow-run).",
|
|
163
|
+
inputSchema: z.object({ collection: z.string(), environment: z.string().default("") }),
|
|
164
|
+
annotations: { openWorldHint: true },
|
|
165
|
+
}, ({ collection, environment }) => respond(async () => {
|
|
166
|
+
if (!app)
|
|
167
|
+
return tools.runCollection(collection, environment);
|
|
168
|
+
const results = [];
|
|
169
|
+
for (const entry of tools.listRequests(collection)) {
|
|
170
|
+
results.push(await app.send(entry.path, environment || undefined));
|
|
171
|
+
}
|
|
172
|
+
return results;
|
|
173
|
+
}));
|
|
174
|
+
server.registerTool("list_examples", {
|
|
175
|
+
description: "A request's saved responses (<slug>.examples.yaml beside it): names, statuses, sizes. Examples are what a mock answers with.",
|
|
176
|
+
inputSchema: z.object({ path: z.string() }),
|
|
177
|
+
annotations: { readOnlyHint: true },
|
|
178
|
+
}, ({ path }) => respond(() => tools.listExamples(path)));
|
|
179
|
+
server.registerTool("save_example", {
|
|
180
|
+
description: app
|
|
181
|
+
? "Save the response the Baton app last got for a request as a named example, replacing one of the same name."
|
|
182
|
+
: "Save the response run_request last got for a request as a named example, replacing one of the same name.",
|
|
183
|
+
inputSchema: z.object({ path: z.string(), name: z.string() }),
|
|
184
|
+
annotations: { idempotentHint: true },
|
|
185
|
+
}, ({ path, name }) => respond(() => (app ? app.saveExample(path, name) : tools.saveExample(path, name))));
|
|
186
|
+
server.registerTool("list_mocks", {
|
|
187
|
+
description: "The mocks defined under mocks/*.yaml, with their ports and whether this server is running them.",
|
|
188
|
+
annotations: { readOnlyHint: true },
|
|
189
|
+
}, () => respond(() => tools.listMocks()));
|
|
190
|
+
server.registerTool("start_mock", {
|
|
191
|
+
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.",
|
|
192
|
+
inputSchema: z.object({ name: z.string() }),
|
|
193
|
+
}, ({ name }) => respond(() => tools.startMock(name)));
|
|
194
|
+
server.registerTool("stop_mock", {
|
|
195
|
+
description: "Take a running mock down.",
|
|
196
|
+
inputSchema: z.object({ name: z.string() }),
|
|
197
|
+
annotations: { idempotentHint: true },
|
|
198
|
+
}, ({ name }) => respond(() => tools.stopMock(name)));
|
|
199
|
+
// Mocks die with the connection: a port left open by an agent that is
|
|
200
|
+
// gone is a surprise nobody asked for.
|
|
201
|
+
const previousClose = server.server.onclose;
|
|
202
|
+
server.server.onclose = () => {
|
|
203
|
+
void tools.mocks.stopAll();
|
|
204
|
+
previousClose?.();
|
|
205
|
+
};
|
|
206
|
+
registerPrompts(server, app !== null);
|
|
207
|
+
if (app)
|
|
208
|
+
registerAppResources(server, app);
|
|
209
|
+
return server;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Two ways of working an agent host offers from its prompt menu. Each is a
|
|
213
|
+
* plan the agent follows with the tools above — written here so the plan
|
|
214
|
+
* says where the files are and what not to do, rather than being improvised.
|
|
215
|
+
*/
|
|
216
|
+
function registerPrompts(server, appMode) {
|
|
217
|
+
const landing = appMode
|
|
218
|
+
? "Edits land as drafts on the request's tab in the Baton app; say so, and let the person accept them."
|
|
219
|
+
: "Edits are written to the workspace files; the person reviews them in git.";
|
|
220
|
+
server.registerPrompt("debug-failing-request", {
|
|
221
|
+
title: "Debug a failing request",
|
|
222
|
+
description: "Find out why a request fails and propose the fix.",
|
|
223
|
+
argsSchema: z.object({
|
|
224
|
+
path: z.string().describe("Workspace-relative path, collections/<...>/<slug>.req.yaml"),
|
|
225
|
+
environment: z.string().optional().describe("Environment slug; the active one when omitted"),
|
|
226
|
+
}),
|
|
227
|
+
}, ({ path, environment }) => ({
|
|
228
|
+
messages: [
|
|
229
|
+
{
|
|
230
|
+
role: "user",
|
|
231
|
+
content: {
|
|
232
|
+
type: "text",
|
|
233
|
+
text: [
|
|
234
|
+
`Debug the Baton request at ${path}${environment ? ` in the ${environment} environment` : ""}.`,
|
|
235
|
+
"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.",
|
|
236
|
+
"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.",
|
|
237
|
+
"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.",
|
|
238
|
+
`4. Propose the smallest change with upsert_request (or upsert_script for a test). ${landing}`,
|
|
239
|
+
"5. Run it again and report what changed — status before and after, and which test outcomes moved.",
|
|
240
|
+
].join("\n"),
|
|
241
|
+
},
|
|
242
|
+
},
|
|
243
|
+
],
|
|
244
|
+
}));
|
|
245
|
+
server.registerPrompt("write-tests", {
|
|
246
|
+
title: "Write tests for a collection",
|
|
247
|
+
description: "Add a test script to every request under a collection that has none.",
|
|
248
|
+
argsSchema: z.object({
|
|
249
|
+
collection: z.string().describe("Workspace-relative collection path, collections/<name>"),
|
|
250
|
+
}),
|
|
251
|
+
}, ({ collection }) => ({
|
|
252
|
+
messages: [
|
|
253
|
+
{
|
|
254
|
+
role: "user",
|
|
255
|
+
content: {
|
|
256
|
+
type: "text",
|
|
257
|
+
text: [
|
|
258
|
+
`Write test scripts for the requests under ${collection} in this Baton workspace.`,
|
|
259
|
+
"1. list_requests on the collection, then get_request on each; skip any whose scripts.tests is already set.",
|
|
260
|
+
"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).",
|
|
261
|
+
"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.",
|
|
262
|
+
`4. Point the request at it with upsert_request, setting scripts.tests to "./<slug>.test.js" and changing nothing else. ${landing}`,
|
|
263
|
+
"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.",
|
|
264
|
+
].join("\n"),
|
|
265
|
+
},
|
|
266
|
+
},
|
|
267
|
+
],
|
|
268
|
+
}));
|
|
269
|
+
}
|
|
270
|
+
/** What the agent can subscribe to in app mode, and how it learns of change. */
|
|
271
|
+
export const APP_STATE_URI = "baton://app/state";
|
|
272
|
+
export const APP_SELECTION_URI = "baton://app/selection";
|
|
273
|
+
/**
|
|
274
|
+
* Two resources over the app's state, kept current by the app's event stream:
|
|
275
|
+
* a change in the app becomes `notifications/resources/updated` on the
|
|
276
|
+
* agent's subscription, and the next read answers with the new state. The
|
|
277
|
+
* stream is followed for as long as this connection lives.
|
|
278
|
+
*/
|
|
279
|
+
function registerAppResources(server, app) {
|
|
280
|
+
server.registerResource("app-state", APP_STATE_URI, {
|
|
281
|
+
title: "Baton app state",
|
|
282
|
+
description: "The open request, the active environment, open tabs, drafts waiting for review, and the last sends' outcomes.",
|
|
283
|
+
mimeType: "application/json",
|
|
284
|
+
}, async (uri) => ({
|
|
285
|
+
contents: [
|
|
286
|
+
{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(await app.state(), null, 2) },
|
|
287
|
+
],
|
|
288
|
+
}));
|
|
289
|
+
server.registerResource("app-selection", APP_SELECTION_URI, {
|
|
290
|
+
title: "Selected request",
|
|
291
|
+
description: "The workspace-relative path of the request open in the Baton app, or empty.",
|
|
292
|
+
mimeType: "text/plain",
|
|
293
|
+
}, async (uri) => ({
|
|
294
|
+
contents: [
|
|
295
|
+
{
|
|
296
|
+
uri: uri.href,
|
|
297
|
+
mimeType: "text/plain",
|
|
298
|
+
text: String((await app.state()).selection ?? ""),
|
|
299
|
+
},
|
|
300
|
+
],
|
|
301
|
+
}));
|
|
302
|
+
const abort = new AbortController();
|
|
303
|
+
const notify = (uri) => {
|
|
304
|
+
// Nothing listening is not an error, and neither is a transport that
|
|
305
|
+
// closed between the event and the send.
|
|
306
|
+
server.server.sendResourceUpdated({ uri }).catch(() => undefined);
|
|
307
|
+
};
|
|
308
|
+
void app.events((event) => {
|
|
309
|
+
if (event.type === "hello")
|
|
310
|
+
return;
|
|
311
|
+
notify(APP_STATE_URI);
|
|
312
|
+
if (event.type === "selection")
|
|
313
|
+
notify(APP_SELECTION_URI);
|
|
314
|
+
}, abort.signal);
|
|
315
|
+
const previous = server.server.onclose;
|
|
316
|
+
server.server.onclose = () => {
|
|
317
|
+
abort.abort();
|
|
318
|
+
previous?.();
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
//# sourceMappingURL=server.js.map
|
package/dist/src/tools.d.ts
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import { CollectionFile, EnvironmentFile, 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,26 @@ 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;
|
|
40
55
|
runRequest(path: string, environment: string): Promise<unknown>;
|
|
56
|
+
/** A request's saved responses, names and sizes — the bodies stay in the file. */
|
|
57
|
+
listExamples(path: string): unknown;
|
|
58
|
+
/**
|
|
59
|
+
* Saves the last response this process got for [path] (run_request) as an
|
|
60
|
+
* example named [name], replacing one of the same name. The body is saved
|
|
61
|
+
* as the API answered — the file is the workspace, not an agent result —
|
|
62
|
+
* and only the name and the size come back.
|
|
63
|
+
*/
|
|
64
|
+
saveExample(path: string, name: string): unknown;
|
|
65
|
+
listMocks(): unknown;
|
|
66
|
+
startMock(name: string): Promise<unknown>;
|
|
67
|
+
stopMock(name: string): Promise<unknown>;
|
|
41
68
|
runCollection(collectionPath: string, environment: string): Promise<unknown>;
|
|
42
69
|
/**
|
|
43
70
|
* Rewrites the `order` list of the collection or folder at [directory].
|
package/dist/src/tools.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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 { 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";
|
|
5
5
|
/** Tool-layer errors carry a message meant for the calling agent. */
|
|
6
6
|
export class ToolError extends Error {
|
|
7
7
|
}
|
|
@@ -10,12 +10,17 @@ const MASKED_HEADERS = new Set(["authorization", "set-cookie", "cookie", "x-api-
|
|
|
10
10
|
export class BatonTools {
|
|
11
11
|
root;
|
|
12
12
|
allowRun;
|
|
13
|
+
/** The last response per request path, for save_example in file mode. */
|
|
14
|
+
lastRuns = new Map();
|
|
15
|
+
/** Mocks this process stands up (docs/WORKER.md, "Mock servers"). */
|
|
16
|
+
mocks;
|
|
13
17
|
constructor(root, allowRun) {
|
|
14
18
|
this.root = root;
|
|
15
19
|
this.allowRun = allowRun;
|
|
16
20
|
if (!existsSync(join(root, "baton.yaml"))) {
|
|
17
21
|
throw new ToolError(`${root} is not a Baton workspace (no baton.yaml)`);
|
|
18
22
|
}
|
|
23
|
+
this.mocks = new MockRegistry(() => this.workspace());
|
|
19
24
|
}
|
|
20
25
|
workspace() {
|
|
21
26
|
return openWorkspace(this.root);
|
|
@@ -69,21 +74,29 @@ export class BatonTools {
|
|
|
69
74
|
raw: readFileSync(this.safePath(path), "utf8"),
|
|
70
75
|
};
|
|
71
76
|
}
|
|
72
|
-
/**
|
|
73
|
-
|
|
77
|
+
/**
|
|
78
|
+
* The checks every request an agent hands over goes through, whichever
|
|
79
|
+
* way it lands — written here, or drafted in the app: the path shape, no
|
|
80
|
+
* literal credential, and a round trip through the parser so invalid input
|
|
81
|
+
* fails before anything is written. Returns the canonical bytes.
|
|
82
|
+
*/
|
|
83
|
+
validateRequest(path, request) {
|
|
74
84
|
if (!path.endsWith(".req.yaml")) {
|
|
75
85
|
throw new ToolError("request path must end with .req.yaml");
|
|
76
86
|
}
|
|
77
87
|
rejectLiteralSecrets(request.auth);
|
|
78
|
-
let canonical;
|
|
79
88
|
try {
|
|
80
|
-
canonical = serializeRequestFile(request);
|
|
81
|
-
// Round-trip through the parser so invalid input fails before writing.
|
|
89
|
+
const canonical = serializeRequestFile(request);
|
|
82
90
|
parseRequestFile(canonical);
|
|
91
|
+
return canonical;
|
|
83
92
|
}
|
|
84
93
|
catch (error) {
|
|
85
94
|
throw new ToolError(`invalid request: ${String(error)}`);
|
|
86
95
|
}
|
|
96
|
+
}
|
|
97
|
+
/** Validates and writes a request; input is the normalized request JSON. */
|
|
98
|
+
upsertRequest(path, request) {
|
|
99
|
+
const canonical = this.validateRequest(path, request);
|
|
87
100
|
const target = this.safePath(path);
|
|
88
101
|
mkdirSync(dirname(target), { recursive: true });
|
|
89
102
|
writeFileSync(target, canonical);
|
|
@@ -173,9 +186,15 @@ export class BatonTools {
|
|
|
173
186
|
slug: entry.slug,
|
|
174
187
|
variables: entry.environment.variables,
|
|
175
188
|
secrets: entry.environment.secrets,
|
|
189
|
+
// Locations, not values: which declared secrets are read from Vault,
|
|
190
|
+
// and where (`<mount>/<path>#<key>`).
|
|
191
|
+
...(entry.environment.vault !== undefined ? { vault: entry.environment.vault } : {}),
|
|
176
192
|
}));
|
|
177
193
|
}
|
|
178
|
-
/**
|
|
194
|
+
/**
|
|
195
|
+
* Creates or replaces an environment. Secret **names** only (invariant 2);
|
|
196
|
+
* `vault` may map a name to a Vault location, which is still not a value.
|
|
197
|
+
*/
|
|
179
198
|
upsertEnvironment(path, environment) {
|
|
180
199
|
if (!path.endsWith(".env.yaml")) {
|
|
181
200
|
throw new ToolError("environment path must end with .env.yaml");
|
|
@@ -191,6 +210,14 @@ export class BatonTools {
|
|
|
191
210
|
`secret name; the value belongs in the OS secure store`);
|
|
192
211
|
}
|
|
193
212
|
}
|
|
213
|
+
// The writer emits a Vault path only under a declared secret; a path
|
|
214
|
+
// for any other name would vanish without a word.
|
|
215
|
+
for (const name of Object.keys(environment.vault ?? {})) {
|
|
216
|
+
if (!declared.has(name)) {
|
|
217
|
+
throw new ToolError(`vault names ${name}, which is not in secrets — declare it as a ` +
|
|
218
|
+
`secret, or drop the Vault path`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
194
221
|
let canonical;
|
|
195
222
|
try {
|
|
196
223
|
canonical = serializeEnvironmentFile(environment);
|
|
@@ -223,8 +250,85 @@ export class BatonTools {
|
|
|
223
250
|
async runRequest(path, environment) {
|
|
224
251
|
this.assertRunsEnabled();
|
|
225
252
|
const result = await runWorkspaceRequest(this.workspace(), path, environment);
|
|
253
|
+
// Kept masked by value: what save_example writes into the workspace is
|
|
254
|
+
// what the agent was shown, never a credential the API echoed back
|
|
255
|
+
// (invariant 2) — a mock would otherwise serve it to anyone.
|
|
256
|
+
const secrets = secretsFromEnv(process.env);
|
|
257
|
+
this.lastRuns.set(path, {
|
|
258
|
+
status: result.status,
|
|
259
|
+
headers: result.headers.map(([name, value]) => [maskSecrets(name, secrets), maskSecrets(value, secrets)]),
|
|
260
|
+
bodyText: maskSecrets(result.bodyText, secrets),
|
|
261
|
+
});
|
|
226
262
|
return redactResult(result);
|
|
227
263
|
}
|
|
264
|
+
/** A request's saved responses, names and sizes — the bodies stay in the file. */
|
|
265
|
+
listExamples(path) {
|
|
266
|
+
const found = findRequest(this.workspace(), path);
|
|
267
|
+
if (!found)
|
|
268
|
+
throw new ToolError(`request not found: ${path}`);
|
|
269
|
+
return {
|
|
270
|
+
path,
|
|
271
|
+
file: examplesPathFor(path),
|
|
272
|
+
examples: found.entry.examples.map((example) => ({
|
|
273
|
+
name: example.name,
|
|
274
|
+
status: example.status,
|
|
275
|
+
headers: example.headers.length,
|
|
276
|
+
bodyBytes: Buffer.byteLength(example.body),
|
|
277
|
+
})),
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Saves the last response this process got for [path] (run_request) as an
|
|
282
|
+
* example named [name], replacing one of the same name. The body is saved
|
|
283
|
+
* as the API answered — the file is the workspace, not an agent result —
|
|
284
|
+
* and only the name and the size come back.
|
|
285
|
+
*/
|
|
286
|
+
saveExample(path, name) {
|
|
287
|
+
const found = findRequest(this.workspace(), path);
|
|
288
|
+
if (!found)
|
|
289
|
+
throw new ToolError(`request not found: ${path}`);
|
|
290
|
+
if (name.trim() === "")
|
|
291
|
+
throw new ToolError("the example needs a name");
|
|
292
|
+
const last = this.lastRuns.get(path);
|
|
293
|
+
if (!last || last.status <= 0) {
|
|
294
|
+
throw new ToolError(`no response for ${path} in this session — run_request it first`);
|
|
295
|
+
}
|
|
296
|
+
const example = {
|
|
297
|
+
name: name.trim(),
|
|
298
|
+
status: last.status,
|
|
299
|
+
headers: last.headers
|
|
300
|
+
.filter(([header]) => !HOP_BY_HOP.has(header.toLowerCase()))
|
|
301
|
+
.map(([header, value]) => ({ name: header.toLowerCase(), value, enabled: true })),
|
|
302
|
+
body: last.bodyText,
|
|
303
|
+
};
|
|
304
|
+
const existing = found.entry.examples;
|
|
305
|
+
const index = existing.findIndex((e) => e.name === example.name);
|
|
306
|
+
const examples = index < 0 ? [...existing, example] : existing.map((e, i) => (i === index ? example : e));
|
|
307
|
+
const file = examplesPathFor(path);
|
|
308
|
+
writeFileSync(this.safePath(file), serializeExamplesFile({ format: 1, examples }));
|
|
309
|
+
return { path, file, example: example.name, status: example.status, bodyBytes: Buffer.byteLength(example.body) };
|
|
310
|
+
}
|
|
311
|
+
listMocks() {
|
|
312
|
+
return this.mocks.list();
|
|
313
|
+
}
|
|
314
|
+
async startMock(name) {
|
|
315
|
+
try {
|
|
316
|
+
const started = await this.mocks.start(name);
|
|
317
|
+
return {
|
|
318
|
+
name,
|
|
319
|
+
url: `http://127.0.0.1:${started.port}`,
|
|
320
|
+
routes: started.routes,
|
|
321
|
+
running: true,
|
|
322
|
+
note: "Point the client you are writing at this URL; a request without examples is not routed.",
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
catch (error) {
|
|
326
|
+
throw new ToolError(String(error instanceof Error ? error.message : error));
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
async stopMock(name) {
|
|
330
|
+
return { name, running: false, stopped: await this.mocks.stop(name) };
|
|
331
|
+
}
|
|
228
332
|
async runCollection(collectionPath, environment) {
|
|
229
333
|
this.assertRunsEnabled();
|
|
230
334
|
const ws = this.workspace();
|
|
@@ -289,6 +393,16 @@ export class BatonTools {
|
|
|
289
393
|
}
|
|
290
394
|
}
|
|
291
395
|
}
|
|
396
|
+
/** Response headers that describe the hop, not the answer; a replay must not carry them. */
|
|
397
|
+
const HOP_BY_HOP = new Set([
|
|
398
|
+
"connection",
|
|
399
|
+
"keep-alive",
|
|
400
|
+
"transfer-encoding",
|
|
401
|
+
"content-length",
|
|
402
|
+
"content-encoding",
|
|
403
|
+
"date",
|
|
404
|
+
"set-cookie",
|
|
405
|
+
]);
|
|
292
406
|
/** Literal credentials in auth config are rejected — reference a secret. */
|
|
293
407
|
function rejectLiteralSecrets(auth) {
|
|
294
408
|
const fields = [];
|
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.2.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,7 +30,10 @@
|
|
|
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\"",
|
|
@@ -32,11 +41,12 @@
|
|
|
32
41
|
},
|
|
33
42
|
"dependencies": {
|
|
34
43
|
"@dudko.dev/baton-format": "^0.1.2",
|
|
35
|
-
"@dudko.dev/baton-worker": "^0.2.
|
|
36
|
-
"@modelcontextprotocol/
|
|
37
|
-
"zod": "^
|
|
44
|
+
"@dudko.dev/baton-worker": "^0.2.3",
|
|
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
|
}
|