toolscript-mcp 1.0.0 → 1.0.2

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.
Files changed (3) hide show
  1. package/README.md +76 -61
  2. package/dist/host/main.js +215 -20
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -5,8 +5,8 @@ servers in a sandbox. The program filters and joins the data there. Only the res
5
5
 
6
6
  The goal is a server that works with any MCP client, for example Claude Code, Claude Desktop, Cursor and Codex.
7
7
 
8
- > **Status: 1.0.0 is the first npm release.** Until it is published, use the [beta clone](#from-github-beta) or the
9
- > [Claude Code plugin](#with-the-claude-code-plugin). Read [Limits](#limits) before you use it.
8
+ > **Install from npm.** Set it up [from npm](#from-npm) with `npx -y toolscript-mcp init`. Read
9
+ > [Limits](#limits) before you use it.
10
10
 
11
11
  - [Features](#features)
12
12
  - [Measured](#measured)
@@ -66,7 +66,7 @@ It uses Sonnet 5.5 on Windows 11, with 6 tasks and 3 runs per task and arm. All
66
66
  | Mean seconds per task | 12.7 | 9.9 | 10.6 |
67
67
 
68
68
  The table excludes two cold runs. One slow server start remains in the toolscript-mcp mean.
69
- These results use commit `49d871f`, fixed fake data and one model. They do not measure the current beta or Codex.
69
+ These results use commit `49d871f`, fixed fake data and one model. They cover that commit in Claude Code.
70
70
  Read [bench/RESULTS-codemode.md](bench/RESULTS-codemode.md) for the method, cold runs and limits.
71
71
 
72
72
  ## How it works
@@ -100,60 +100,34 @@ The model sees a short list of keys and titles, not every full issue.
100
100
 
101
101
  ## Install
102
102
 
103
- You need Node 22.13 or later and npm. The GitHub clone also needs git.
103
+ You need Node 22.13 or later and npm.
104
104
 
105
105
  ### From npm
106
106
 
107
- This works once 1.0.0 is published. Until then, use the GitHub clone or the Claude Code plugin below.
108
-
109
107
  ```sh
110
108
  npx -y toolscript-mcp init
111
109
  ```
112
110
 
113
- `init` prints the entry of each client it finds, with `npx -y toolscript-mcp` as the command. For Codex, which init
114
- does not read, use the Codex entry in [Client setup](#client-setup) with `command = "npx"` and
115
- `args = ["-y", "toolscript-mcp", "--config", "/absolute/path/to/config.json"]`. Then follow
111
+ init imports user-scope servers from Claude Code, Claude Desktop and Cursor. It writes a toolscript-mcp config
112
+ and prints the client changes. Use [Client setup](#client-setup) for Codex or a manual setup. Then follow
116
113
  [Configure downstream servers](#configure-downstream-servers).
117
114
 
118
- ### From GitHub (beta)
119
-
120
- The `beta` branch points at a commit of `main` that passed every test. Clone it once, and `npm ci` builds `dist/`:
121
-
122
- ```sh
123
- git clone --branch beta https://github.com/yeeyon/toolscript-mcp.git ~/toolscript-mcp
124
- cd ~/toolscript-mcp
125
- npm ci
126
- node dist/host/main.js init
127
- ```
128
-
129
- init imports the user-scope servers of Claude Code, Claude Desktop and Cursor. It writes a toolscript-mcp config
130
- and prints the client changes. It does not edit your client files. It does not import Codex configs.
131
- See [init](#init) for the options.
115
+ To update, run `npx -y toolscript-mcp@latest --help` and restart your client. If your client entry pins a version,
116
+ change the version in that entry before you restart.
132
117
 
133
- Next, follow [Client setup](#client-setup) and [Configure downstream servers](#configure-downstream-servers).
134
- Use an absolute path to `dist/host/main.js` in your client.
118
+ #### Move an existing clone setup to npm
135
119
 
136
- To update the clone:
120
+ 1. Find the config path in the existing client entry. If it uses the default path, keep that default.
121
+ 2. Replace the client entry's command and arguments. Keep the same config path and any environment variables. Use
122
+ [Client setup](#client-setup).
123
+ 3. Restart the client and run a task through toolscript-mcp. Check it with [runs](#check-a-server-and-a-run).
137
124
 
138
- ```sh
139
- cd ~/toolscript-mcp
140
- git pull --ff-only
141
- npm ci
142
- ```
143
-
144
- Then start a new session of your client. Do not start the server with `npx github:…` in a client.
145
- In a measured start, the GitHub check of npx added about 12 seconds.
146
-
147
- The commands that toolscript-mcp prints, such as the login command and the steps of `init`, use the start of the
148
- running process. From a clone, they start with `node /absolute/path/to/toolscript-mcp/dist/host/main.js`. From npm,
149
- they start with `npx -y toolscript-mcp`. On Windows, each path in them has forward slashes. So the login command
150
- works in cmd.exe, PowerShell and Git Bash. Run the Claude Code step of an npm install in PowerShell or cmd.exe. Run
151
- `node dist/host/main.js --help` to see the usage.
125
+ The config keeps your servers and policy. The same user account also keeps its saved OAuth tokens.
126
+ If an entry uses a file inside the clone, keep that file or update its path first.
152
127
 
153
128
  #### With the Claude Code plugin
154
129
 
155
- This repo is also a Claude Code plugin marketplace. Its plugin `toolscript` installs the beta with you. In
156
- Claude Code, run:
130
+ This repo is also a Claude Code plugin marketplace. Its plugin `toolscript` guides the npm setup. In Claude Code, run:
157
131
 
158
132
  ```text
159
133
  /plugin marketplace add yeeyon/toolscript-mcp
@@ -163,7 +137,7 @@ Claude Code, run:
163
137
  Then run `/toolscript:setup`, or ask Claude to set up toolscript-mcp. The skill asks you before each step that changes
164
138
  something:
165
139
 
166
- 1. It checks Node and git, then clones the `beta` branch, or updates a clone that exists.
140
+ 1. It checks Node and npm, then checks that the published package starts.
167
141
  2. It runs `init` when you agree, and shows the servers that init imported.
168
142
  3. It adds toolscript-mcp to Claude Code with `claude mcp add`.
169
143
  4. It sends you to `/toolscript:start` for the first run. See the list below.
@@ -181,25 +155,25 @@ something:
181
155
  6. After a run works, the skill offers to remove the direct copy of the server from Claude Code. It shows the scope of the copy first.
182
156
 
183
157
  `/toolscript:doctor` checks the whole setup and changes no setting. It runs [doctor](#doctor), then checks the Claude
184
- Code registration, the direct copies of your servers and the clone. For each problem, it names the step that fixes it.
158
+ Code registration and the direct copies of your servers. For each problem, it names the step that fixes it.
185
159
 
186
160
  The skills do not edit the config files of your clients. They show the lines to change. To update or uninstall
187
161
  toolscript-mcp, ask Claude again.
188
162
 
189
163
  ### Client setup
190
164
 
191
- Replace each path below with the absolute path of your clone or config. Use the server name `toolscript`.
165
+ Replace the example config path with your absolute config path. Use the server name `toolscript`.
192
166
 
193
167
  Claude Code on Linux and macOS:
194
168
 
195
169
  ```sh
196
- claude mcp add --scope user toolscript '--' node "/absolute/path/to/toolscript-mcp/dist/host/main.js" --config "/absolute/path/to/config.json"
170
+ claude mcp add --scope user toolscript '--' npx -y toolscript-mcp --config "/absolute/path/to/config.json"
197
171
  ```
198
172
 
199
173
  Claude Code on Windows, in PowerShell:
200
174
 
201
175
  ```powershell
202
- claude mcp add --scope user toolscript '--' node "C:/tools/toolscript-mcp/dist/host/main.js" --config "C:/tools/toolscript-config.json"
176
+ claude mcp add --scope user toolscript '--' cmd /c npx -y toolscript-mcp --config "C:/tools/toolscript-config.json"
203
177
  ```
204
178
 
205
179
  Keep the quotes around `'--'`. The PowerShell `claude.ps1` shim drops a bare `--`, so it can misread `--config`.
@@ -210,8 +184,8 @@ Claude Desktop (`claude_desktop_config.json`) and Cursor (`~/.cursor/mcp.json`):
210
184
  {
211
185
  "mcpServers": {
212
186
  "toolscript": {
213
- "command": "node",
214
- "args": ["/absolute/path/to/toolscript-mcp/dist/host/main.js", "--config", "/absolute/path/to/config.json"]
187
+ "command": "npx",
188
+ "args": ["-y", "toolscript-mcp", "--config", "/absolute/path/to/config.json"]
215
189
  }
216
190
  }
217
191
  }
@@ -221,8 +195,8 @@ Codex (`~/.codex/config.toml`):
221
195
 
222
196
  ```toml
223
197
  [mcp_servers.toolscript]
224
- command = "node"
225
- args = ["/absolute/path/to/toolscript-mcp/dist/host/main.js", "--config", "/absolute/path/to/config.json"]
198
+ command = "npx"
199
+ args = ["-y", "toolscript-mcp", "--config", "/absolute/path/to/config.json"]
226
200
  default_tools_approval_mode = "approve"
227
201
  ```
228
202
 
@@ -231,7 +205,8 @@ toolscript-mcp still checks its own policy on each call of a program.
231
205
  In a test on Windows, Codex started toolscript-mcp in the folder where `codex exec` ran. A downstream server with
232
206
  no `cwd` in its entry starts in that folder too.
233
207
 
234
- On Windows, use paths such as `C:/tools/toolscript-mcp/dist/host/main.js` in JSON and TOML.
208
+ On Windows, set the command to `cmd` and put `"/c", "npx"` at the start of the arguments in JSON and TOML.
209
+ Use a config path such as `C:/tools/toolscript-config.json`.
235
210
  If you put the config file in the default place, you can omit `--config` and its path.
236
211
  See [The config file](#the-config-file).
237
212
 
@@ -284,12 +259,13 @@ npm ci
284
259
  npm run build
285
260
  ```
286
261
 
287
- Then use [Client setup](#client-setup) with the path of this clone.
262
+ For a development session, use `node` as the client command. Replace the npm arguments with
263
+ `["/absolute/path/to/toolscript-mcp/dist/host/main.js", "--config", "/absolute/path/to/config.json"]`.
288
264
 
289
265
  ### init
290
266
 
291
- - `node /absolute/path/to/toolscript-mcp/dist/host/main.js init` imports the user-scope servers of Claude Code. It does not import the servers of a
292
- project. To add them, use `--list` and `--add` below.
267
+ - `npx -y toolscript-mcp init` imports the user-scope servers of Claude Code, Claude Desktop and Cursor.
268
+ To add servers from a project, use `--list` and `--add` below.
293
269
  - If two clients have a server with the same name, init keeps the first one. The order is Claude Code, Claude
294
270
  Desktop, Cursor.
295
271
  - init does not import an SSE server, a disabled server, or toolscript-mcp itself.
@@ -515,13 +491,19 @@ worked. Without `--server`, the run must call a tool of any server. These cases
515
491
 
516
492
  #### Demo server
517
493
 
518
- `demo/server.mjs` is a read-only MCP server with 40 sample pull requests of a made-up repository. It needs no account
519
- and no network. The npm package and a clone both hold it. Add it to the config with the absolute path of the file:
494
+ `demo/server.mjs` is a read-only MCP server with 40 sample pull requests. It needs no account.
495
+ Install the npm package in a folder of your choice to give the demo file a stable path.
496
+
497
+ ```sh
498
+ npm install --prefix "/absolute/path/to/demo-package" toolscript-mcp@latest
499
+ ```
500
+
501
+ Add the demo file to your config. Replace the example path with your path.
520
502
 
521
503
  ```json
522
504
  {
523
505
  "mcpServers": {
524
- "demo": { "command": "node", "args": ["/absolute/path/to/toolscript-mcp/demo/server.mjs"] }
506
+ "demo": { "command": "node", "args": ["/absolute/path/to/demo-package/node_modules/toolscript-mcp/demo/server.mjs"] }
525
507
  },
526
508
  "policy": [{ "match": "mcp__demo__list_pull_requests", "action": "allow" }]
527
509
  }
@@ -876,7 +858,7 @@ The `claude mcp serve` bridge costs about 315 MB of private memory in each sessi
876
858
  toolscript-mcp logs in to a remote HTTP server with OAuth. You do not need a proxy such as `mcp-remote`.
877
859
 
878
860
  1. Add the server to the config with `"type": "http"` and `url`, without `headers`.
879
- 2. Run `node /absolute/path/to/toolscript-mcp/dist/host/main.js login <server>`. If your config uses another path, add `--config <path>`.
861
+ 2. Run `npx -y toolscript-mcp login <server>`. If your config uses another path, add `--config <path>`.
880
862
  3. Log in and approve the access in the browser. If the browser does not open, open the URL that login prints.
881
863
 
882
864
  login waits 5 minutes for the browser and 30 s for the token exchange. Then it connects to the server and prints the
@@ -934,6 +916,39 @@ shows the cause. The next search or call tries the refresh again.
934
916
  Sessions that share one token store refresh one at a time, so a server that revokes a reused refresh token keeps your login.
935
917
  A `.lock` file can show beside the store for a moment. If a session waits up to 20 s for another session, `search_tools` shows the cause. The next call tries again.
936
918
 
919
+ ### AWS SigV4
920
+
921
+ toolscript-mcp signs the requests to an AWS HTTP server, such as the AWS MCP Server, with AWS SigV4. It uses the
922
+ credentials of a profile of the AWS CLI. You do not need a proxy such as `mcp-proxy-for-aws`, and you do not need a
923
+ login.
924
+
925
+ ```json
926
+ {
927
+ "mcpServers": {
928
+ "aws": {
929
+ "type": "http",
930
+ "url": "https://aws-mcp.us-east-1.api.aws/mcp",
931
+ "sigv4": { "profile": "dev" }
932
+ }
933
+ }
934
+ }
935
+ ```
936
+
937
+ 1. Install the AWS CLI version 2 and put `aws` on your `PATH`.
938
+ 2. For an SSO profile, run `aws sso login --profile <profile>`.
939
+ 3. Add one entry for each profile. Each entry uses one account.
940
+
941
+ - toolscript-mcp gets the credentials with `aws configure export-credentials --profile <profile>`. It keeps them in
942
+ memory and gets new ones 5 minutes before they expire.
943
+ - When the credentials cannot be read, the call fails with the cause and the `aws sso login` command. After you log in
944
+ again, the next call works, with no restart.
945
+ - The region and the service come from the host of `url`, such as `us-east-1` and `aws-mcp`. For another host, set
946
+ `"region"` and `"service"` in `sigv4`.
947
+ - An entry with `sigv4` does not log in with OAuth. An entry with `sigv4` and `oauth`, or with an `Authorization`
948
+ header, is an error.
949
+ - toolscript-mcp signs only the requests to the origin of `url`. It never writes the credentials or the signature to a
950
+ log.
951
+
937
952
  ### Run log
938
953
 
939
954
  toolscript-mcp writes one line to `~/.toolscript-mcp/runs.jsonl` for each `run_code` call.
@@ -1255,11 +1270,11 @@ Code 2.1.325.
1255
1270
  - [x] Write the docs and add the release workflow.
1256
1271
  - [x] Compare toolscript-mcp with Claude Code Code Mode in the bench.
1257
1272
  - [x] Log in to remote servers with OAuth.
1258
- - [x] Offer guided beta setup through the Claude Code plugin.
1273
+ - [x] Offer guided setup through the Claude Code plugin.
1259
1274
  - [x] Run Claude Code tools through the optional stdio bridge, with a project `cwd`.
1260
1275
  - [x] Require per-run approval for tools marked for user interaction.
1261
1276
  - [x] Keep images and other non-text results as files, and show the images that a program returns.
1262
- - [ ] Publish 1.0.0 to npm.
1277
+ - [x] Publish 1.0.0 to npm.
1263
1278
  - [ ] Run the Codex comparison and publish its results.
1264
1279
  - [ ] Keep state between `run_code` calls, as an option.
1265
1280
  - [ ] Serve hint files and saved functions as tools.
package/dist/host/main.js CHANGED
@@ -17294,6 +17294,7 @@ var rankTools = (tools, query, limit) => {
17294
17294
  } else if (short.includes(word)) hit = 3;
17295
17295
  else if (word.length >= 4 && joinedIn(segs, word)) hit = 2.5;
17296
17296
  else if (ofServer.has(word)) hit = 2;
17297
+ else if (tool.actions?.has(word) && !FILLER.has(word)) hit = 1.5 - 0.01 * Math.min(segs.length, 20);
17297
17298
  else if (description.includes(word)) hit = 1;
17298
17299
  else if (stem2 !== word && (short.includes(stem2) || description.includes(stem2))) hit = 0.5;
17299
17300
  else if (stem2 !== word && stem2.length >= 4 && joinedIn(segs, stem2)) hit = 0.5;
@@ -17676,6 +17677,49 @@ var nonEmpty = (v, path15, errors) => {
17676
17677
  return "";
17677
17678
  };
17678
17679
  var OAUTH_KEYS = ["clientId", "clientSecret", "scopes", "callbackPort"];
17680
+ var SIGV4_KEYS = ["profile", "region", "service"];
17681
+ var AWS_PROFILE = /^[A-Za-z0-9][A-Za-z0-9_.+=@-]{0,127}$/;
17682
+ var AWS_REGION = /^[a-z]{2}(?:-[a-z]+)+-\d{1,2}$/;
17683
+ var AWS_SERVICE = /^[a-z0-9][a-z0-9-]{0,62}$/;
17684
+ var awsEndpoint = (url2) => {
17685
+ if (!URL.canParse(url2)) return void 0;
17686
+ const host = /^https:\/\/([^/?#@:]+)(?::\d+)?(?:[/?#]|$)/i.exec(url2)?.[1]?.toLowerCase() ?? "";
17687
+ const m = /^([a-z0-9-]+)\.([a-z]{2}(?:-[a-z]+)+-\d{1,2})\.(?:api\.aws|amazonaws\.com)$/.exec(host);
17688
+ return m ? { service: m[1], region: m[2] } : void 0;
17689
+ };
17690
+ var parseSigV4 = (raw, url2, headers, oauth, path15, env, errors) => {
17691
+ if (raw === void 0) return void 0;
17692
+ if (!isObject2(raw)) {
17693
+ errors.push(`${path15}: must be an object with "profile"`);
17694
+ return void 0;
17695
+ }
17696
+ unknownKeys(raw, SIGV4_KEYS, path15, errors);
17697
+ if (oauth !== void 0 && oauth !== false)
17698
+ errors.push(`${path15}: an entry with "sigv4" does not log in: remove "oauth"`);
17699
+ if (Object.keys(headers).some((name) => name.toLowerCase() === "authorization"))
17700
+ errors.push(`${path15}: an entry with an Authorization header cannot sign with SigV4: remove one of them`);
17701
+ const field = (key, rule, fallback) => {
17702
+ const value = raw[key];
17703
+ if (value === void 0) {
17704
+ if (fallback === void 0) errors.push(`${path15}.${key}: is needed, because the URL is not an AWS endpoint`);
17705
+ return fallback;
17706
+ }
17707
+ const text2 = expand(nonEmpty(value, `${path15}.${key}`, errors), env, `${path15}.${key}`, errors);
17708
+ if (text2 !== "" && !rule.test(text2)) {
17709
+ errors.push(`${path15}.${key}: is not a valid ${key}`);
17710
+ return void 0;
17711
+ }
17712
+ return text2;
17713
+ };
17714
+ const endpoint = awsEndpoint(url2);
17715
+ const found = errors.length;
17716
+ if (raw.profile === void 0) errors.push(`${path15}.profile: is needed`);
17717
+ const profile = raw.profile === void 0 ? void 0 : field("profile", AWS_PROFILE, void 0);
17718
+ const region = field("region", AWS_REGION, endpoint?.region);
17719
+ const service = field("service", AWS_SERVICE, endpoint?.service);
17720
+ if (errors.length !== found || !profile || !region || !service) return void 0;
17721
+ return { profile, region, service };
17722
+ };
17679
17723
  var parseOAuth = (raw, headers, path15, env, errors) => {
17680
17724
  if (raw === false) return void 0;
17681
17725
  if (raw === void 0) return Object.keys(headers).length === 0 ? { scopes: [] } : void 0;
@@ -17775,7 +17819,7 @@ var parseServer = (raw, path15, env, platform, errors) => {
17775
17819
  };
17776
17820
  }
17777
17821
  if (type === "http") {
17778
- unknownKeys(raw, ["type", "url", "headers", "oauth", "untrusted"], path15, errors);
17822
+ unknownKeys(raw, ["type", "url", "headers", "oauth", "sigv4", "untrusted"], path15, errors);
17779
17823
  const found = errors.length;
17780
17824
  const url2 = expand(nonEmpty(raw.url, `${path15}.url`, errors), env, `${path15}.url`, errors);
17781
17825
  if (errors.length === found) {
@@ -17783,12 +17827,14 @@ var parseServer = (raw, path15, env, platform, errors) => {
17783
17827
  else if (!URL.canParse(url2)) errors.push(`${path15}.url: must be a valid URL`);
17784
17828
  }
17785
17829
  const headers = stringMap(raw.headers, `${path15}.headers`, env, errors);
17786
- const oauth = parseOAuth(raw.oauth, headers, `${path15}.oauth`, env, errors);
17830
+ const sigv4 = parseSigV4(raw.sigv4, url2, headers, raw.oauth, `${path15}.sigv4`, env, errors);
17831
+ const oauth = raw.sigv4 === void 0 ? parseOAuth(raw.oauth, headers, `${path15}.oauth`, env, errors) : void 0;
17787
17832
  return {
17788
17833
  kind: "http",
17789
17834
  url: url2,
17790
17835
  headers,
17791
17836
  ...oauth && { oauth },
17837
+ ...sigv4 && { sigv4 },
17792
17838
  ...parseTrust(raw.untrusted, `${path15}.untrusted`, errors)
17793
17839
  };
17794
17840
  }
@@ -18736,9 +18782,33 @@ var namesByServer = (all, cap = NAMES_CAP) => {
18736
18782
  return `mcp__${s.key}__: ${s.names.slice(0, s.shown).join(", ")}${more > 0 ? ` (+${more} more)` : ""}`;
18737
18783
  });
18738
18784
  };
18785
+ var ACTION_PROPERTIES = ["action", "method", "operation"];
18786
+ var MAX_ACTION_VALUE = 40;
18787
+ var MAX_ACTION_WORDS = 50;
18788
+ var actionWords = (inputSchema) => {
18789
+ const words2 = /* @__PURE__ */ new Set();
18790
+ if (!isObject3(inputSchema) || !Object.hasOwn(inputSchema, "properties")) return words2;
18791
+ const properties = inputSchema.properties;
18792
+ if (!isObject3(properties)) return words2;
18793
+ for (const key of ACTION_PROPERTIES) {
18794
+ const property = Object.hasOwn(properties, key) ? properties[key] : void 0;
18795
+ if (!isObject3(property) || !Array.isArray(property.enum)) continue;
18796
+ for (let i = 0; i < property.enum.length && i < MAX_ENUM; i++) {
18797
+ const value = property.enum[i];
18798
+ if (typeof value !== "string" || value.length > MAX_ACTION_VALUE) continue;
18799
+ for (const word of value.toLowerCase().split(/[^a-z0-9]+/))
18800
+ if (word !== "" && words2.size < MAX_ACTION_WORDS) words2.add(word);
18801
+ }
18802
+ }
18803
+ return words2;
18804
+ };
18739
18805
  var searchResult = (states, query, limit, shapes = /* @__PURE__ */ new Map(), canAsk = true) => {
18740
18806
  const all = catalogOf(states);
18741
- const found = rankTools(all, query, limit);
18807
+ const found = rankTools(
18808
+ all.map((t) => ({ ...t, actions: actionWords(t.inputSchema) })),
18809
+ query,
18810
+ limit
18811
+ );
18742
18812
  const tail = notConnectedText(states);
18743
18813
  if (found.length === 0) {
18744
18814
  const shown = query.length > ECHO_MAX ? `${query.slice(0, ECHO_MAX)}... (${query.length} characters)` : query;
@@ -29355,6 +29425,127 @@ var oauthProvider = (file2, oauth, mode, lockFs) => {
29355
29425
  };
29356
29426
  };
29357
29427
 
29428
+ // src/host/sigv4.ts
29429
+ var import_cross_spawn4 = __toESM(require_cross_spawn(), 1);
29430
+ import { createHash as createHash2, createHmac } from "node:crypto";
29431
+ var sha256 = (data) => createHash2("sha256").update(data).digest("hex");
29432
+ var hmac = (key, data) => createHmac("sha256", key).update(data).digest();
29433
+ var encode3 = (text2) => encodeURIComponent(text2).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
29434
+ var canonicalPath = (pathname) => pathname.split("/").map(encode3).join("/") || "/";
29435
+ var canonicalQuery = (params) => [...params].map(([k, v]) => [encode3(k), encode3(v)]).sort(([a, av], [b, bv]) => a < b ? -1 : a > b ? 1 : av < bv ? -1 : av > bv ? 1 : 0).map(([k, v]) => `${k}=${v}`).join("&");
29436
+ var signRequest = (request, credentials, scope, now) => {
29437
+ const url2 = new URL(request.url);
29438
+ const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, "");
29439
+ const day = amzDate.slice(0, 8);
29440
+ const added = { "x-amz-date": amzDate };
29441
+ if (credentials.sessionToken !== void 0) added["x-amz-security-token"] = credentials.sessionToken;
29442
+ const signed = { host: url2.host, ...added };
29443
+ const contentType2 = request.headers.get("content-type");
29444
+ if (contentType2 !== null) signed["content-type"] = contentType2;
29445
+ const names = Object.keys(signed).sort();
29446
+ const canonical2 = [
29447
+ request.method.toUpperCase(),
29448
+ canonicalPath(url2.pathname),
29449
+ canonicalQuery(url2.searchParams),
29450
+ names.map((n) => `${n}:${signed[n].trim().replace(/\s+/g, " ")}
29451
+ `).join(""),
29452
+ names.join(";"),
29453
+ sha256(request.body)
29454
+ ].join("\n");
29455
+ const credentialScope = `${day}/${scope.region}/${scope.service}/aws4_request`;
29456
+ const toSign = ["AWS4-HMAC-SHA256", amzDate, credentialScope, sha256(canonical2)].join("\n");
29457
+ let key = hmac(`AWS4${credentials.secretAccessKey}`, day);
29458
+ for (const part of [scope.region, scope.service, "aws4_request"]) key = hmac(key, part);
29459
+ const signature = createHmac("sha256", key).update(toSign).digest("hex");
29460
+ added.authorization = `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${credentialScope}, SignedHeaders=${names.join(";")}, Signature=${signature}`;
29461
+ return added;
29462
+ };
29463
+ var EARLY_MS = 5 * 6e4;
29464
+ var CLI_TIMEOUT_MS = 3e4;
29465
+ var MAX_OUTPUT = 64 * 1024;
29466
+ var AwsCredentialsError = class extends Error {
29467
+ };
29468
+ var parseExported = (text2) => {
29469
+ let raw;
29470
+ try {
29471
+ raw = JSON.parse(text2);
29472
+ } catch {
29473
+ return void 0;
29474
+ }
29475
+ if (typeof raw !== "object" || raw === null) return void 0;
29476
+ const { AccessKeyId, SecretAccessKey, SessionToken, Expiration } = raw;
29477
+ if (typeof AccessKeyId !== "string" || AccessKeyId === "" || typeof SecretAccessKey !== "string") return void 0;
29478
+ if (SecretAccessKey === "") return void 0;
29479
+ const expiresAt = typeof Expiration === "string" ? Date.parse(Expiration) : NaN;
29480
+ return {
29481
+ accessKeyId: AccessKeyId,
29482
+ secretAccessKey: SecretAccessKey,
29483
+ ...typeof SessionToken === "string" && SessionToken !== "" && { sessionToken: SessionToken },
29484
+ ...Number.isFinite(expiresAt) && { expiresAt }
29485
+ };
29486
+ };
29487
+ var failure2 = (profile, why) => new AwsCredentialsError(
29488
+ `could not get AWS credentials for the profile "${profile}" (${why}). If it is an SSO profile, run: aws sso login --profile ${profile}`
29489
+ );
29490
+ var exportCredentials = (profile, command3 = "aws") => new Promise((resolve2, reject) => {
29491
+ let child;
29492
+ try {
29493
+ child = (0, import_cross_spawn4.default)(command3, ["configure", "export-credentials", "--profile", profile, "--format", "process"], {
29494
+ stdio: ["ignore", "pipe", "pipe"],
29495
+ windowsHide: true
29496
+ });
29497
+ } catch {
29498
+ reject(failure2(profile, "the AWS CLI did not start"));
29499
+ return;
29500
+ }
29501
+ let out = "";
29502
+ let err = "";
29503
+ child.stdout?.on("data", (b) => void (out.length < MAX_OUTPUT && (out += b.toString("utf8"))));
29504
+ child.stderr?.on("data", (b) => void (err.length < MAX_OUTPUT && (err += b.toString("utf8"))));
29505
+ const timer = setTimeout(() => child.kill(), CLI_TIMEOUT_MS);
29506
+ child.on("error", (e) => {
29507
+ clearTimeout(timer);
29508
+ reject(failure2(profile, e.code === "ENOENT" ? 'the AWS CLI "aws" is not on PATH' : "the AWS CLI did not start"));
29509
+ });
29510
+ child.on("close", (code) => {
29511
+ clearTimeout(timer);
29512
+ const credentials = code === 0 ? parseExported(out) : void 0;
29513
+ if (credentials) return resolve2(credentials);
29514
+ const line = err.split(/\r?\n/).find((l) => l.trim() !== "")?.trim().slice(0, 300);
29515
+ reject(failure2(profile, line ?? (code === 0 ? "the AWS CLI printed no credentials" : `exit ${code}`)));
29516
+ });
29517
+ });
29518
+ var sigv4Fetch = (server2, base, load = exportCredentials, clock = Date.now) => {
29519
+ const origin = new URL(server2.url).origin;
29520
+ let current;
29521
+ let pending;
29522
+ const credentials = async () => {
29523
+ if (current && (current.expiresAt === void 0 || current.expiresAt - EARLY_MS > clock())) return current;
29524
+ pending ??= load(server2.sigv4.profile).finally(() => pending = void 0);
29525
+ current = await pending;
29526
+ return current;
29527
+ };
29528
+ const signed = async (url2, init) => {
29529
+ const target = new URL(url2);
29530
+ if (target.origin !== origin) return base(url2, init);
29531
+ const headers = new Headers(init?.headers);
29532
+ for (const [name, value] of Object.entries(server2.headers ?? {})) headers.set(name, value);
29533
+ const body = init?.body;
29534
+ if (body !== void 0 && body !== null && typeof body !== "string" && !(body instanceof Uint8Array))
29535
+ throw new Error("a SigV4 request body must be a string or bytes");
29536
+ const added = signRequest(
29537
+ { method: init?.method ?? "GET", url: target.href, headers, body: body ?? "" },
29538
+ await credentials(),
29539
+ server2.sigv4,
29540
+ new Date(clock())
29541
+ );
29542
+ for (const [name, value] of Object.entries(added)) headers.set(name, value);
29543
+ return base(url2, { ...init, headers, redirect: "manual" });
29544
+ };
29545
+ const secrets = () => current ? [current.accessKeyId, current.secretAccessKey, ...current.sessionToken ? [current.sessionToken] : []] : [];
29546
+ return Object.assign(signed, { secrets });
29547
+ };
29548
+
29358
29549
  // src/host/downstream.ts
29359
29550
  var CONNECT_TIMEOUT_MS = 3e4;
29360
29551
  var MAX_PAGES = 100;
@@ -29458,13 +29649,16 @@ var isOAuthStop = (err) => err instanceof LoginNeeded || err instanceof RefreshF
29458
29649
  var HttpTransport = class extends StreamableHTTPClientTransport {
29459
29650
  #onSessionEnd;
29460
29651
  #loginReason;
29461
- constructor(server2, onSessionEnd, auth2) {
29652
+ /** The AWS credentials of a SigV4 entry, to hide from the texts that reach the model and the log. */
29653
+ secrets;
29654
+ constructor(server2, onSessionEnd, auth2, signed = server2.sigv4 && !auth2 ? sigv4Fetch({ url: server2.url, sigv4: server2.sigv4, headers: server2.headers }, serverFetch(server2)) : void 0) {
29462
29655
  super(new URL(server2.url), {
29463
- fetch: auth2 ? auth2.provider.fetch(serverFetch(server2)) : serverFetch(server2),
29656
+ fetch: auth2 ? auth2.provider.fetch(serverFetch(server2)) : signed ?? serverFetch(server2),
29464
29657
  ...auth2 && { authProvider: auth2.provider }
29465
29658
  });
29466
29659
  this.#onSessionEnd = onSessionEnd;
29467
29660
  this.#loginReason = auth2?.reason;
29661
+ this.secrets = signed?.secrets ?? (() => []);
29468
29662
  }
29469
29663
  async send(...args) {
29470
29664
  const hadSession = this.sessionId !== void 0;
@@ -29644,6 +29838,7 @@ var connectAll = (servers, version3, log2, {
29644
29838
  if (closing2) throw new OwnError("toolscript-mcp is shutting down");
29645
29839
  const made = transportOf(key, server2, sessionEnded, auth2, childStderr, share, lazily);
29646
29840
  lastError = made.lastError;
29841
+ if (made.transport instanceof HttpTransport && !auth2) secrets = made.transport.secrets;
29647
29842
  if (made.child !== void 0) {
29648
29843
  children.add(made.child);
29649
29844
  if (closing2) made.child.hurry();
@@ -29691,7 +29886,7 @@ var connectAll = (servers, version3, log2, {
29691
29886
  await client.close().catch(() => {
29692
29887
  });
29693
29888
  opened.delete(client);
29694
- if (isOAuthStop(err) || err instanceof OwnError || err instanceof BrokerError)
29889
+ if (isOAuthStop(err) || err instanceof OwnError || err instanceof BrokerError || err instanceof AwsCredentialsError)
29695
29890
  fail3(stderr === "" ? errorText(err) : `${errorText(err)}. ${STDERR_UNSHOWN}`);
29696
29891
  else fail3(stderr === "" ? errorText(err) : `${errorText(err)}. ${STDERR_UNSHOWN}`, "the connect failed");
29697
29892
  }
@@ -30229,17 +30424,17 @@ var launch = (o) => {
30229
30424
  };
30230
30425
 
30231
30426
  // src/host/toolscache.ts
30232
- import { createHash as createHash3 } from "node:crypto";
30427
+ import { createHash as createHash4 } from "node:crypto";
30233
30428
 
30234
30429
  // src/host/shapes.ts
30235
- import { createHash as createHash2 } from "node:crypto";
30430
+ import { createHash as createHash3 } from "node:crypto";
30236
30431
  import fs10 from "node:fs";
30237
30432
  var hashes = /* @__PURE__ */ new WeakMap();
30238
30433
  var schemaHash = (inputSchema) => {
30239
30434
  const key = inputSchema !== null && typeof inputSchema === "object" ? inputSchema : void 0;
30240
30435
  const known = key === void 0 ? void 0 : hashes.get(key);
30241
30436
  if (known !== void 0) return known;
30242
- const hash = createHash2("sha256").update(canonicalJson(inputSchema)).digest("hex").slice(0, 32);
30437
+ const hash = createHash3("sha256").update(canonicalJson(inputSchema)).digest("hex").slice(0, 32);
30243
30438
  if (key !== void 0) hashes.set(key, hash);
30244
30439
  return hash;
30245
30440
  };
@@ -30337,7 +30532,7 @@ var write = async (home, learned, log2) => {
30337
30532
  // src/host/toolscache.ts
30338
30533
  import fs11 from "node:fs";
30339
30534
  import path8 from "node:path";
30340
- var toolsKey = (server2) => createHash3("sha256").update(toolsKeyText(server2, childEnv(server2))).digest("hex");
30535
+ var toolsKey = (server2) => createHash4("sha256").update(toolsKeyText(server2, childEnv(server2))).digest("hex");
30341
30536
  var read = async (home, log2) => {
30342
30537
  try {
30343
30538
  const text2 = await readText(toolsFile(home), MAX_CACHE_BYTES);
@@ -31412,7 +31607,7 @@ import http from "node:http";
31412
31607
  import path11 from "node:path";
31413
31608
  import { parseArgs as parseArgs5 } from "node:util";
31414
31609
  var LOGIN_USAGE = "usage: toolscript-mcp login <server> [--config <path>] [--help]";
31415
- var failure2 = (err) => errorText(err) || (err instanceof OAuthError && err.errorCode ? `the authorization server answered ${err.errorCode}` : "no reason given");
31610
+ var failure3 = (err) => errorText(err) || (err instanceof OAuthError && err.errorCode ? `the authorization server answered ${err.errorCode}` : "no reason given");
31416
31611
  var NO_REGISTRATION = "Incompatible auth server: does not support dynamic client registration";
31417
31612
  var OTHER_RESOURCE = /^Protected resource (\S+) does not match expected/;
31418
31613
  var STILL_ASKS = "the server still asks for a login after the token exchange";
@@ -31420,7 +31615,7 @@ var Reason = class extends Error {
31420
31615
  };
31421
31616
  var notStarted = (err, url2) => {
31422
31617
  if (err instanceof Reason) return err.message;
31423
- const text2 = failure2(err);
31618
+ const text2 = failure3(err);
31424
31619
  if (text2 === NO_REGISTRATION)
31425
31620
  return 'its authorization server has no dynamic client registration. Calls that need a token need "clientId" in "oauth": see "OAuth login" in the README';
31426
31621
  const other = OTHER_RESOURCE.exec(text2)?.[1];
@@ -31510,7 +31705,7 @@ var metadataLike = (text2) => {
31510
31705
  };
31511
31706
  var invalidText = (err) => {
31512
31707
  const issues = err?.issues;
31513
- return Array.isArray(issues) ? issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") : failure2(err);
31708
+ return Array.isArray(issues) ? issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") : failure3(err);
31514
31709
  };
31515
31710
  var takesOAuth = async (url2, fetchFn) => {
31516
31711
  let unsure = false;
@@ -31679,7 +31874,7 @@ ${url2.href}`);
31679
31874
  io2.print(`Logged in to ${key}. It has ${plural2(tools.length)}. The tokens are in ${store}${mode}.`);
31680
31875
  return 0;
31681
31876
  } catch (err) {
31682
- io2.print(`login to ${key} failed: ${hide2(failure2(err))}`);
31877
+ io2.print(`login to ${key} failed: ${hide2(failure3(err))}`);
31683
31878
  return 1;
31684
31879
  } finally {
31685
31880
  clearTimeout(timer);
@@ -33208,7 +33403,7 @@ import os4 from "node:os";
33208
33403
  import path14 from "node:path";
33209
33404
 
33210
33405
  // src/host/run.ts
33211
- import { createHash as createHash4, randomBytes as randomBytes2, randomUUID as randomUUID5 } from "node:crypto";
33406
+ import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID5 } from "node:crypto";
33212
33407
  import fs15 from "node:fs";
33213
33408
  import path13 from "node:path";
33214
33409
 
@@ -33546,7 +33741,7 @@ var saveFile = async (dir, name, data) => {
33546
33741
  await fs15.promises.writeFile(file2, text2, { mode: 384 });
33547
33742
  return { ok: true, value: file2 };
33548
33743
  };
33549
- var sha256 = (bytes) => createHash4("sha256").update(bytes).digest("hex");
33744
+ var sha2562 = (bytes) => createHash5("sha256").update(bytes).digest("hex");
33550
33745
  var writeAttachments = async (dir, files, written2) => {
33551
33746
  if (files.length === 0) return;
33552
33747
  await fs15.promises.mkdir(dir, { recursive: true, mode: 448 });
@@ -33559,7 +33754,7 @@ var writeAttachments = async (dir, files, written2) => {
33559
33754
  });
33560
33755
  throw err;
33561
33756
  });
33562
- done.push({ file: file2, record: { mimeType, bytes: bytes.length, sha256: sha256(bytes) } });
33757
+ done.push({ file: file2, record: { mimeType, bytes: bytes.length, sha256: sha2562(bytes) } });
33563
33758
  }
33564
33759
  } catch (err) {
33565
33760
  await Promise.all(done.map(({ file: file2 }) => fs15.promises.rm(file2, { force: true }).catch(() => {
@@ -33584,7 +33779,7 @@ var showImages = async (written2, returned) => {
33584
33779
  if (stat.size !== record2.bytes) return "changed";
33585
33780
  const bytes = await fs15.promises.readFile(file2).catch(() => void 0);
33586
33781
  if (bytes === void 0) return "unreadable";
33587
- if (bytes.length !== record2.bytes || sha256(bytes) !== record2.sha256) return "changed";
33782
+ if (bytes.length !== record2.bytes || sha2562(bytes) !== record2.sha256) return "changed";
33588
33783
  if (!holdsImage(record2.mimeType, bytes)) return "not-image";
33589
33784
  total += bytes.length;
33590
33785
  return { data: bytes.toString("base64"), mimeType: record2.mimeType };
@@ -33777,7 +33972,7 @@ could not answer message ${id} of the program: ${errorText(err)}`;
33777
33972
  const answerCall = async (id, tool, args, sentKey) => {
33778
33973
  if (ended) return;
33779
33974
  const began = performance.now();
33780
- const { code: failure3, cls, untrusted: fromTool, ...r } = await callTool(id, tool, args);
33975
+ const { code: failure4, cls, untrusted: fromTool, ...r } = await callTool(id, tool, args);
33781
33976
  if (closed) return;
33782
33977
  if (fromTool === true) untrusted = true;
33783
33978
  const tainted = untrusted;
@@ -33786,7 +33981,7 @@ could not answer message ${id} of the program: ${errorText(err)}`;
33786
33981
  decision: decided.get(id),
33787
33982
  ms: performance.now() - began,
33788
33983
  ok: r.ok,
33789
- ...r.ok ? {} : { error: failure3 ?? "failed" },
33984
+ ...r.ok ? {} : { error: failure4 ?? "failed" },
33790
33985
  ...r.ok || cls === void 0 ? {} : { class: cls }
33791
33986
  });
33792
33987
  const key = sentKey ?? callKey(tool, args);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toolscript-mcp",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "Standalone MCP server for code mode: the model writes one JavaScript program that calls your MCP tools in a sandbox.",
5
5
  "keywords": [
6
6
  "mcp",