hmcp-gateway 0.0.2 → 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.
Files changed (114) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +135 -9
  3. package/bin/hmcp-gateway.js +20 -0
  4. package/catalog/atlassian.yaml +41 -0
  5. package/catalog/brave-search.yaml +57 -0
  6. package/catalog/context7.yaml +42 -0
  7. package/catalog/fetch.yaml +37 -0
  8. package/catalog/figma.yaml +48 -0
  9. package/catalog/filesystem.yaml +48 -0
  10. package/catalog/git.yaml +48 -0
  11. package/catalog/github.yaml +103 -0
  12. package/catalog/huggingface.yaml +59 -0
  13. package/catalog/linear.yaml +47 -0
  14. package/catalog/memory.yaml +47 -0
  15. package/catalog/notion.yaml +41 -0
  16. package/catalog/playwright.yaml +38 -0
  17. package/catalog/postgres.yaml +66 -0
  18. package/catalog/sentry.yaml +39 -0
  19. package/catalog/sequential-thinking.yaml +29 -0
  20. package/catalog/stripe.yaml +41 -0
  21. package/catalog/supabase.yaml +45 -0
  22. package/catalog/time.yaml +49 -0
  23. package/dist/adopt-cli.d.ts +355 -0
  24. package/dist/adopt-cli.js +1885 -0
  25. package/dist/adopt-emit.d.ts +64 -0
  26. package/dist/adopt-emit.js +248 -0
  27. package/dist/adopt-plan.d.ts +108 -0
  28. package/dist/adopt-plan.js +501 -0
  29. package/dist/catalog.d.ts +140 -0
  30. package/dist/catalog.js +250 -0
  31. package/dist/classify.d.ts +23 -0
  32. package/dist/classify.js +47 -0
  33. package/dist/cli.d.ts +2 -0
  34. package/dist/cli.js +656 -0
  35. package/dist/client-allow.d.ts +42 -0
  36. package/dist/client-allow.js +95 -0
  37. package/dist/client-config.d.ts +263 -0
  38. package/dist/client-config.js +995 -0
  39. package/dist/config-source.d.ts +106 -0
  40. package/dist/config-source.js +156 -0
  41. package/dist/config.d.ts +159 -0
  42. package/dist/config.js +330 -0
  43. package/dist/connect-client.d.ts +51 -0
  44. package/dist/connect-client.js +299 -0
  45. package/dist/contracts.d.ts +251 -0
  46. package/dist/contracts.js +9 -0
  47. package/dist/credential.d.ts +63 -0
  48. package/dist/credential.js +136 -0
  49. package/dist/desktop-extensions.d.ts +53 -0
  50. package/dist/desktop-extensions.js +126 -0
  51. package/dist/draft.d.ts +71 -0
  52. package/dist/draft.js +596 -0
  53. package/dist/exposure-cli.d.ts +28 -0
  54. package/dist/exposure-cli.js +119 -0
  55. package/dist/gateway.d.ts +766 -0
  56. package/dist/gateway.js +2122 -0
  57. package/dist/github-doors.d.ts +162 -0
  58. package/dist/github-doors.js +780 -0
  59. package/dist/guard-install.d.ts +109 -0
  60. package/dist/guard-install.js +396 -0
  61. package/dist/guard.d.ts +265 -0
  62. package/dist/guard.js +975 -0
  63. package/dist/import-client.d.ts +184 -0
  64. package/dist/import-client.js +578 -0
  65. package/dist/index.d.ts +31 -0
  66. package/dist/index.js +31 -0
  67. package/dist/notify.d.ts +44 -0
  68. package/dist/notify.js +93 -0
  69. package/dist/oauth.d.ts +139 -0
  70. package/dist/oauth.js +641 -0
  71. package/dist/observe.d.ts +10 -0
  72. package/dist/observe.js +26 -0
  73. package/dist/open.d.ts +24 -0
  74. package/dist/open.js +31 -0
  75. package/dist/packs.d.ts +119 -0
  76. package/dist/packs.js +131 -0
  77. package/dist/pin-cli.d.ts +28 -0
  78. package/dist/pin-cli.js +103 -0
  79. package/dist/probe-upstream.d.ts +31 -0
  80. package/dist/probe-upstream.js +377 -0
  81. package/dist/registry-map.d.ts +39 -0
  82. package/dist/registry-map.js +390 -0
  83. package/dist/rule-cli.d.ts +51 -0
  84. package/dist/rule-cli.js +412 -0
  85. package/dist/serve-http.d.ts +67 -0
  86. package/dist/serve-http.js +478 -0
  87. package/dist/snippet.d.ts +20 -0
  88. package/dist/snippet.js +826 -0
  89. package/dist/status-cli.d.ts +61 -0
  90. package/dist/status-cli.js +195 -0
  91. package/dist/suggest-cli.d.ts +43 -0
  92. package/dist/suggest-cli.js +279 -0
  93. package/dist/toml-edit.d.ts +43 -0
  94. package/dist/toml-edit.js +363 -0
  95. package/dist/toolname.d.ts +47 -0
  96. package/dist/toolname.js +149 -0
  97. package/dist/upstream-errors.d.ts +54 -0
  98. package/dist/upstream-errors.js +330 -0
  99. package/dist/upstream.d.ts +128 -0
  100. package/dist/upstream.js +413 -0
  101. package/dist/version.d.ts +10 -0
  102. package/dist/version.js +11 -0
  103. package/package.json +51 -6
  104. package/packs/brave-search.yaml +20 -0
  105. package/packs/context7.yaml +13 -0
  106. package/packs/fetch.yaml +14 -0
  107. package/packs/filesystem.yaml +79 -0
  108. package/packs/git.yaml +29 -0
  109. package/packs/github.yaml +47 -0
  110. package/packs/huggingface.yaml +16 -0
  111. package/packs/memory.yaml +23 -0
  112. package/packs/playwright.yaml +41 -0
  113. package/packs/sequential-thinking.yaml +13 -0
  114. package/packs/time.yaml +14 -0
@@ -0,0 +1,363 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { parse } from "smol-toml";
3
+ /**
4
+ * Codex's `config.toml` (shared with the ChatGPT desktop app): reading it,
5
+ * and changing only the MCP server tables in it.
6
+ *
7
+ * The TOML library is used to read, never to write. Writing a whole TOML
8
+ * document back from its parsed value loses every comment and all of the
9
+ * person's layout, in a file they edit by hand. So every change here is a
10
+ * cut or an append on the file's own text: a server's table (and its
11
+ * `[mcp_servers.<name>.*]` sub-tables) removed, or a new table added at the
12
+ * end. After each change the result is read again and must equal the
13
+ * original with exactly that change, or nothing is written.
14
+ *
15
+ * A file whose servers are written in a form these cuts cannot handle safely
16
+ * -- an inline table, dotted keys, an array of tables, a server split across
17
+ * the file -- can be read and listed, but is refused for editing.
18
+ */
19
+ export class TomlEditError extends Error {
20
+ }
21
+ /** The file as a plain JSON value: no null prototypes, dates as their TOML text. */
22
+ export function parseToml(text) {
23
+ return JSON.parse(JSON.stringify(parse(text)));
24
+ }
25
+ const SERVERS = "mcp_servers";
26
+ const BOM = "";
27
+ function lineEnd(text, i) {
28
+ const nl = text.indexOf("\n", i);
29
+ return nl === -1 ? text.length : nl + 1;
30
+ }
31
+ function skipBlanks(text, i) {
32
+ while (i < text.length && (text[i] === " " || text[i] === "\t"))
33
+ i++;
34
+ return i;
35
+ }
36
+ /** Where a string starting at `i` ends, or -1 when no string starts there. */
37
+ function stringEnd(text, i) {
38
+ if (text.startsWith('"""', i) || text.startsWith("'''", i)) {
39
+ const quote = text[i];
40
+ const close = quote.repeat(3);
41
+ let j = i + 3;
42
+ while (j < text.length) {
43
+ if (quote === '"' && text[j] === "\\") {
44
+ j += 2;
45
+ continue;
46
+ }
47
+ if (text.startsWith(close, j)) {
48
+ j += 3;
49
+ // Up to two quotes may sit right before the closing three.
50
+ for (let k = 0; k < 2 && text[j] === quote; k++)
51
+ j++;
52
+ return j;
53
+ }
54
+ j++;
55
+ }
56
+ throw new TomlEditError("a multi-line string is not closed");
57
+ }
58
+ if (text[i] === '"') {
59
+ let j = i + 1;
60
+ while (j < text.length && text[j] !== '"')
61
+ j += text[j] === "\\" ? 2 : 1;
62
+ return j + 1;
63
+ }
64
+ if (text[i] === "'") {
65
+ const close = text.indexOf("'", i + 1);
66
+ if (close === -1)
67
+ throw new TomlEditError("a string is not closed");
68
+ return close + 1;
69
+ }
70
+ return -1;
71
+ }
72
+ function unescapeBasic(body) {
73
+ return body.replace(/\\(u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|.)/g, (_, e) => {
74
+ if (e[0] === "u" || e[0] === "U")
75
+ return String.fromCodePoint(parseInt(e.slice(1), 16));
76
+ const map = { b: "\b", t: "\t", n: "\n", f: "\f", r: "\r", e: "\u001b", '"': '"', "\\": "\\" };
77
+ return map[e] ?? e;
78
+ });
79
+ }
80
+ /** A dotted key starting at `i`: its segments, and where it ends. */
81
+ function readKey(text, i) {
82
+ const path = [];
83
+ for (;;) {
84
+ i = skipBlanks(text, i);
85
+ const c = text[i];
86
+ if (c === '"' || c === "'") {
87
+ const end = stringEnd(text, i);
88
+ const body = text.slice(i + 1, end - 1);
89
+ path.push(c === '"' ? unescapeBasic(body) : body);
90
+ i = end;
91
+ }
92
+ else {
93
+ const m = /^[A-Za-z0-9_-]+/.exec(text.slice(i, i + 256));
94
+ if (!m)
95
+ throw new TomlEditError("a key could not be read");
96
+ path.push(m[0]);
97
+ i += m[0].length;
98
+ }
99
+ i = skipBlanks(text, i);
100
+ if (text[i] !== ".")
101
+ return { path, next: i };
102
+ i++;
103
+ }
104
+ }
105
+ /** Where the value starting at `i` ends: strings, arrays and inline tables over any number of lines. */
106
+ function valueEnd(text, i) {
107
+ i = skipBlanks(text, i);
108
+ const asString = stringEnd(text, i);
109
+ if (asString !== -1)
110
+ return asString;
111
+ if (text[i] === "[" || text[i] === "{") {
112
+ let depth = 0;
113
+ while (i < text.length) {
114
+ const s = stringEnd(text, i);
115
+ if (s !== -1) {
116
+ i = s;
117
+ continue;
118
+ }
119
+ const c = text[i];
120
+ if (c === "#") {
121
+ i = lineEnd(text, i);
122
+ continue;
123
+ }
124
+ if (c === "[" || c === "{")
125
+ depth++;
126
+ else if (c === "]" || c === "}") {
127
+ depth--;
128
+ if (depth === 0)
129
+ return i + 1;
130
+ }
131
+ i++;
132
+ }
133
+ throw new TomlEditError("an array or inline table is not closed");
134
+ }
135
+ while (i < text.length && !/[\s#]/.test(text[i]))
136
+ i++;
137
+ return i;
138
+ }
139
+ /** Every table header and every key line, with where each one sits in the text. */
140
+ function scan(text) {
141
+ const headers = [];
142
+ const keys = [];
143
+ let table = null;
144
+ // A byte-order mark some editors put first is not part of the first line.
145
+ let i = text.startsWith(BOM) ? 1 : 0;
146
+ while (i < text.length) {
147
+ const start = i;
148
+ i = skipBlanks(text, i);
149
+ const c = text[i];
150
+ if (c === undefined)
151
+ break;
152
+ if (c === "\n" || c === "\r" || c === "#") {
153
+ i = lineEnd(text, i);
154
+ continue;
155
+ }
156
+ if (c === "[") {
157
+ const array = text[i + 1] === "[";
158
+ const key = readKey(text, i + (array ? 2 : 1));
159
+ i = skipBlanks(text, key.next);
160
+ if (!text.startsWith(array ? "]]" : "]", i))
161
+ throw new TomlEditError("a table header could not be read");
162
+ i = lineEnd(text, i);
163
+ headers.push({ start, end: i, path: key.path, array });
164
+ table = key.path;
165
+ continue;
166
+ }
167
+ const key = readKey(text, i);
168
+ i = skipBlanks(text, key.next);
169
+ if (text[i] !== "=")
170
+ throw new TomlEditError("a line could not be read");
171
+ i = lineEnd(text, valueEnd(text, i + 1));
172
+ keys.push({ start, end: i, path: key.path, table });
173
+ }
174
+ return { headers, keys };
175
+ }
176
+ const isServerHeader = (h, name) => h.path[0] === SERVERS && h.path.length >= 2 && (name === undefined || h.path[1] === name);
177
+ /**
178
+ * Why this file's servers cannot be changed by cutting and appending text, or
179
+ * null when they can. Names a form, never a value.
180
+ */
181
+ export function tomlEditProblem(text) {
182
+ let layout;
183
+ try {
184
+ parse(text);
185
+ layout = scan(text);
186
+ }
187
+ catch {
188
+ return "the file could not be read closely enough to change it safely";
189
+ }
190
+ if (layout.headers.some((h) => h.array && h.path[0] === SERVERS)) {
191
+ return "its MCP servers are written as a list of tables ([[mcp_servers]])";
192
+ }
193
+ if (layout.keys.some((k) => k.table === null && k.path[0] === SERVERS)) {
194
+ return "its MCP servers are written on one line (mcp_servers = { ... } or mcp_servers.<name>.<setting> = ...)";
195
+ }
196
+ if (layout.keys.some((k) => k.table !== null && k.table.length === 1 && k.table[0] === SERVERS)) {
197
+ return "its MCP servers are written as keys inside [mcp_servers] rather than as [mcp_servers.<name>] tables";
198
+ }
199
+ const names = new Set(layout.headers.filter((h) => isServerHeader(h)).map((h) => h.path[1]));
200
+ for (const name of names) {
201
+ const at = layout.headers.flatMap((h, i) => (isServerHeader(h, name) ? [i] : []));
202
+ if (at[at.length - 1] - at[0] + 1 !== at.length) {
203
+ return `the settings of the server "${name}" are split across the file`;
204
+ }
205
+ }
206
+ return null;
207
+ }
208
+ /** The text range of one server's tables, from its first header to the end of its last setting. */
209
+ function serverRange(text, layout, name) {
210
+ const at = layout.headers.flatMap((h, i) => (isServerHeader(h, name) ? [i] : []));
211
+ if (at.length === 0)
212
+ throw new TomlEditError(`the server "${name}" has no [mcp_servers.${name}] table to remove`);
213
+ const first = layout.headers[at[0]];
214
+ const next = layout.headers[at[at.length - 1] + 1];
215
+ const limit = next ? next.start : text.length;
216
+ // Comments and blank lines after its last setting are left: they may be about what follows.
217
+ let end = first.end;
218
+ for (const item of [...layout.headers, ...layout.keys]) {
219
+ if (item.start >= first.start && item.start < limit)
220
+ end = Math.max(end, item.end);
221
+ }
222
+ return [first.start, end];
223
+ }
224
+ /* ------------------------------------------------------------ the writer */
225
+ /** A TOML basic string: quotes, backslashes and control characters escaped. */
226
+ export function tomlString(value) {
227
+ let out = '"';
228
+ for (const ch of value) {
229
+ const code = ch.codePointAt(0);
230
+ if (ch === '"')
231
+ out += '\\"';
232
+ else if (ch === "\\")
233
+ out += "\\\\";
234
+ else if (ch === "\n")
235
+ out += "\\n";
236
+ else if (ch === "\r")
237
+ out += "\\r";
238
+ else if (ch === "\t")
239
+ out += "\\t";
240
+ else if (ch === "\b")
241
+ out += "\\b";
242
+ else if (ch === "\f")
243
+ out += "\\f";
244
+ else if (code < 0x20 || code === 0x7f)
245
+ out += `\\u${code.toString(16).padStart(4, "0")}`;
246
+ else
247
+ out += ch;
248
+ }
249
+ return `${out}"`;
250
+ }
251
+ /** A key, bare when TOML allows it and quoted otherwise. */
252
+ export function tomlKey(key) {
253
+ return /^[A-Za-z0-9_-]+$/.test(key) ? key : tomlString(key);
254
+ }
255
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
256
+ function inlineValue(value) {
257
+ if (typeof value === "string")
258
+ return tomlString(value);
259
+ if (typeof value === "boolean")
260
+ return String(value);
261
+ if (typeof value === "number" && Number.isFinite(value))
262
+ return String(value);
263
+ if (Array.isArray(value))
264
+ return `[${value.map(inlineValue).join(", ")}]`;
265
+ if (isRecord(value)) {
266
+ const body = Object.entries(value).map(([k, v]) => `${tomlKey(k)} = ${inlineValue(v)}`);
267
+ return body.length === 0 ? "{}" : `{ ${body.join(", ")} }`;
268
+ }
269
+ throw new TomlEditError("a setting has a value that cannot be written as TOML");
270
+ }
271
+ /** `[a.b]` with its plain settings, then each table-valued setting as a `[a.b.<key>]` of its own. */
272
+ export function tomlTable(path, value, eol = "\n") {
273
+ const lines = [`[${path.map(tomlKey).join(".")}]`];
274
+ const subs = [];
275
+ for (const [key, v] of Object.entries(value)) {
276
+ if (isRecord(v))
277
+ subs.push([key, v]);
278
+ else
279
+ lines.push(`${tomlKey(key)} = ${inlineValue(v)}`);
280
+ }
281
+ let out = lines.join(eol) + eol;
282
+ for (const [key, v] of subs)
283
+ out += eol + tomlTable([...path, key], v, eol);
284
+ return out;
285
+ }
286
+ /* -------------------------------------------------------------- the edit */
287
+ /** Whether two read TOML documents say the same, a missing `mcp_servers` and an empty one being the same. */
288
+ export function sameToml(a, b) {
289
+ if (!isRecord(a) || !isRecord(b))
290
+ return false;
291
+ return isDeepStrictEqual(withoutEmptyServers(a), withoutEmptyServers(b));
292
+ }
293
+ function withoutEmptyServers(doc) {
294
+ const servers = doc[SERVERS];
295
+ if (!isRecord(servers) || Object.keys(servers).length > 0)
296
+ return doc;
297
+ const rest = { ...doc };
298
+ delete rest[SERVERS];
299
+ return rest;
300
+ }
301
+ /**
302
+ * The file's text with its servers changed from `current` to `next`: each
303
+ * server that went or changed has its tables cut out, each one that is new
304
+ * or changed is appended at the end. Everything else is the file's own bytes.
305
+ *
306
+ * Refuses, with nothing written by the caller, when the servers are in a form
307
+ * this cannot cut safely or when the result does not read back as exactly
308
+ * the intended change.
309
+ */
310
+ export function editTomlServers(text, next) {
311
+ const problem = tomlEditProblem(text);
312
+ if (problem)
313
+ throw new TomlEditError(problem);
314
+ const original = parseToml(text);
315
+ const current = isRecord(original[SERVERS]) ? original[SERVERS] : {};
316
+ const changed = (name) => !isDeepStrictEqual(current[name], JSON.parse(JSON.stringify(next[name] ?? null)));
317
+ const remove = Object.keys(current).filter((name) => !(name in next) || changed(name));
318
+ const add = Object.keys(next).filter((name) => !(name in current) || changed(name));
319
+ const layout = scan(text);
320
+ const ranges = remove.map((name) => serverRange(text, layout, name)).sort((a, b) => b[0] - a[0]);
321
+ // A byte-order mark stays first in the file, whatever is cut or added.
322
+ const bom = text.startsWith(BOM) ? BOM : "";
323
+ let out = text;
324
+ for (const [start, end] of ranges) {
325
+ const before = out.slice(0, start);
326
+ let after = out.slice(end);
327
+ // One blank line is enough where two tables used to meet around this one.
328
+ if (before === bom)
329
+ after = after.replace(/^(\r?\n)+/, "");
330
+ else if (/\n\r?\n$/.test(before))
331
+ after = after.replace(/^\r?\n/, "");
332
+ // The blank line an append put before a table that was last in the file goes with it.
333
+ out = after === "" ? before.replace(/(\n)\r?\n$/, "$1") : before + after;
334
+ }
335
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
336
+ for (const name of add) {
337
+ const value = next[name];
338
+ if (!isRecord(value))
339
+ throw new TomlEditError(`the server "${name}" is not a table of settings`);
340
+ if (out.slice(bom.length).trim() !== "") {
341
+ if (!out.endsWith("\n"))
342
+ out += eol;
343
+ if (!out.endsWith(`${eol}${eol}`))
344
+ out += eol;
345
+ }
346
+ else {
347
+ out = bom;
348
+ }
349
+ out += tomlTable([SERVERS, name], value, eol);
350
+ }
351
+ let reread;
352
+ try {
353
+ reread = parseToml(out);
354
+ }
355
+ catch {
356
+ throw new TomlEditError("the changed file would not read back, so nothing was changed");
357
+ }
358
+ const expected = { ...original, [SERVERS]: JSON.parse(JSON.stringify(next)) };
359
+ if (!isDeepStrictEqual(withoutEmptyServers(reread), withoutEmptyServers(expected))) {
360
+ throw new TomlEditError("the changed file would not read back as exactly the intended change, so nothing was changed");
361
+ }
362
+ return out;
363
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Why this name cannot be used, or `undefined` if it can.
3
+ *
4
+ * Deliberately not an allowlist of characters. Tool names in the wild are
5
+ * snake_case, kebab-case, camelCase, dotted and occasionally non-Latin, and
6
+ * refusing a legitimate Japanese tool name would be a bug rather than a
7
+ * safeguard. What is refused is text that cannot be *read*: anything invisible,
8
+ * anything that reorders what follows it, and anything that is not already in
9
+ * its composed form.
10
+ */
11
+ export declare function toolNameProblem(name: string): string | undefined;
12
+ /**
13
+ * What two names have to differ in for a human to be able to tell them apart.
14
+ *
15
+ * Case is folded and separators are dropped, so `delete_note`, `delete-note`
16
+ * and `DeleteNote` share a key. That is deliberately more aggressive than
17
+ * `toolNameProblem`: those three are each perfectly readable on their own, and
18
+ * a reviewer scanning a list of forty tools should still never have to notice
19
+ * that two rows differ only by a hyphen before switching the right one off.
20
+ */
21
+ export declare function displayKey(name: string): string;
22
+ /**
23
+ * The longest tool name a model API accepts.
24
+ *
25
+ * Anthropic's and OpenAI's tool-calling APIs both cap a tool name at 64
26
+ * characters, and reject the whole request -- every tool, not the one long
27
+ * name -- when a name is over. In practice that ends the session.
28
+ */
29
+ export declare const CLIENT_TOOL_NAME_LIMIT = 64;
30
+ /**
31
+ * The name a client sends the model for one of a gateway's tools.
32
+ *
33
+ * Claude Code's scheme, `mcp__<server>__<tool>`, where the server is the name
34
+ * the gateway's entry has in the client's config. Other clients prefix
35
+ * differently or not at all; this is the longest of the common ones, so a name
36
+ * that fits here fits elsewhere.
37
+ */
38
+ export declare function clientToolName(entryName: string, localName: string): string;
39
+ /**
40
+ * How long one of the gateway's own tool names may be and still fit.
41
+ *
42
+ * Wrapping a server makes every name longer: `mcp__github__<tool>` becomes
43
+ * `mcp__hmcp__github__<tool>`. A tool that fitted when the server was used
44
+ * directly can stop fitting, so the room left is worked out from the entry's
45
+ * name and handed to the gateway as `max_tool_name_length`.
46
+ */
47
+ export declare function toolNameBudget(entryName: string): number;
@@ -0,0 +1,149 @@
1
+ import { INVISIBLE_ANYWHERE, hasLookalikeLetters, readsAs } from "hmcp-core";
2
+ /**
3
+ * Whether an upstream's name for a tool can be used safely.
4
+ *
5
+ * A tool name is not just text on a screen. It is the key the exposure switch,
6
+ * every approval row and `bindingHash` are stored under, and it is the thing an
7
+ * operator reads when deciding what to switch off. So two names that a human
8
+ * cannot tell apart, but the database can, break the one promise the kill
9
+ * switch makes: an upstream advertising both `delete_note` and
10
+ * `delete_note​` shows a reviewer two identical rows, and switching one
11
+ * off leaves the other live, callable, and reported as off.
12
+ *
13
+ * `normalizeTenantKey` already refuses this class of thing for tenants, with
14
+ * the reasoning that "a key that can be spelled two ways is a key that can be
15
+ * made to collide or to split". Tool names arrive from a server we do not
16
+ * control, so they need it more, not less.
17
+ *
18
+ * The name is *refused* rather than normalised. Normalising would fold two
19
+ * genuinely distinct upstream tools onto one key, which trades a visible
20
+ * problem for a silent one — and an upstream whose tool cannot be named
21
+ * unambiguously is in the same position as one whose tool cannot be
22
+ * classified, which this gateway already declines to expose.
23
+ */
24
+ /** Generous for a tool name, short of being a payload. */
25
+ const MAX_TOOL_NAME = 128;
26
+ /*
27
+ * Control codes: C0, DEL and C1. These are the ones that can drive a terminal
28
+ * -- clear a screen, move a cursor -- as well as being unreadable.
29
+ */
30
+ // eslint-disable-next-line no-control-regex
31
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
32
+ /*
33
+ * Space characters other than the ordinary one. A reader cannot tell a
34
+ * no-break or ideographic space from a plain space, or a thin one from none.
35
+ */
36
+ const ODD_SPACE = /[\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;
37
+ /** A run of letters: the unit a reader takes in at once. */
38
+ const WORD = /\p{L}+/gu;
39
+ /**
40
+ * Why this name cannot be used, or `undefined` if it can.
41
+ *
42
+ * Deliberately not an allowlist of characters. Tool names in the wild are
43
+ * snake_case, kebab-case, camelCase, dotted and occasionally non-Latin, and
44
+ * refusing a legitimate Japanese tool name would be a bug rather than a
45
+ * safeguard. What is refused is text that cannot be *read*: anything invisible,
46
+ * anything that reorders what follows it, and anything that is not already in
47
+ * its composed form.
48
+ */
49
+ export function toolNameProblem(name) {
50
+ if (name.length === 0)
51
+ return "it is empty";
52
+ if (name.length > MAX_TOOL_NAME) {
53
+ return `it is ${name.length} characters; the maximum is ${MAX_TOOL_NAME}`;
54
+ }
55
+ /*
56
+ * Anything that draws nothing. The list is shared with the scanner's
57
+ * description check (`unicode.ts` in core) and has no exceptions here: an
58
+ * emoji's presentation selector is ordinary in prose and has no business in
59
+ * an identifier, where all it can do is make two names differ invisibly.
60
+ */
61
+ const bad = CONTROL.exec(name) ?? INVISIBLE_ANYWHERE.exec(name) ?? ODD_SPACE.exec(name);
62
+ if (bad) {
63
+ const code = bad[0].codePointAt(0).toString(16).toUpperCase().padStart(4, "0");
64
+ return (`it contains U+${code} at offset ${bad.index}, which a reviewer cannot see. ` +
65
+ `A name that renders identically to another one is a kill switch that appears to work and does not`);
66
+ }
67
+ if (name !== name.normalize("NFC")) {
68
+ return ("it is not in Unicode composed (NFC) form, so the same name could be written a second way " +
69
+ "and stored under a different key");
70
+ }
71
+ if (name.trim() !== name)
72
+ return "it begins or ends with whitespace, which is invisible in a listing";
73
+ /*
74
+ * A compatibility form of an ASCII character: fullwidth `d`, mathematical
75
+ * bold `𝐝`, a circled digit. It is drawn as the plain character and is a
76
+ * different code point, so `delete_note` is `delete_note` to a reader and
77
+ * to nothing else -- not to a policy rule, and not to the verb list that
78
+ * decides whether a claim to be read-only is believed.
79
+ */
80
+ for (const ch of name) {
81
+ if (ch.codePointAt(0) < 0x80)
82
+ continue;
83
+ if (/^[\x21-\x7e]+$/.test(ch.normalize("NFKC"))) {
84
+ const code = ch.codePointAt(0).toString(16).toUpperCase().padStart(4, "0");
85
+ return (`it contains U+${code}, a compatibility form that is drawn as "${ch.normalize("NFKC")}" ` +
86
+ `and is not that character, so the name reads as one thing and is stored as another`);
87
+ }
88
+ }
89
+ /*
90
+ * A word that mixes Latin letters with letters from another script that are
91
+ * drawn the same way: `dеlete` with a Cyrillic `е`. A name wholly in another
92
+ * script is fine and so is `get_заметку`, where each word keeps to one
93
+ * script; what is refused is a single word a reader takes for Latin and the
94
+ * bytes say is not. (A word that is *entirely* look-alikes is caught the
95
+ * other way, by `displayKey`, when it collides with the name it imitates.)
96
+ */
97
+ for (const [word] of name.matchAll(WORD)) {
98
+ if (/[A-Za-z]/.test(word) && hasLookalikeLetters(word)) {
99
+ return (`"${word}" mixes Latin letters with look-alike letters from another script, ` +
100
+ `so it reads as a different name from the one it is stored under`);
101
+ }
102
+ }
103
+ return undefined;
104
+ }
105
+ /**
106
+ * What two names have to differ in for a human to be able to tell them apart.
107
+ *
108
+ * Case is folded and separators are dropped, so `delete_note`, `delete-note`
109
+ * and `DeleteNote` share a key. That is deliberately more aggressive than
110
+ * `toolNameProblem`: those three are each perfectly readable on their own, and
111
+ * a reviewer scanning a list of forty tools should still never have to notice
112
+ * that two rows differ only by a hyphen before switching the right one off.
113
+ */
114
+ export function displayKey(name) {
115
+ // `readsAs` folds compatibility forms and look-alike letters, so a name
116
+ // spelled wholly in Cyrillic or fullwidth collides with the Latin name it
117
+ // is drawn as.
118
+ return readsAs(name).toLowerCase().replace(/[-._\s]+/g, "");
119
+ }
120
+ /**
121
+ * The longest tool name a model API accepts.
122
+ *
123
+ * Anthropic's and OpenAI's tool-calling APIs both cap a tool name at 64
124
+ * characters, and reject the whole request -- every tool, not the one long
125
+ * name -- when a name is over. In practice that ends the session.
126
+ */
127
+ export const CLIENT_TOOL_NAME_LIMIT = 64;
128
+ /**
129
+ * The name a client sends the model for one of a gateway's tools.
130
+ *
131
+ * Claude Code's scheme, `mcp__<server>__<tool>`, where the server is the name
132
+ * the gateway's entry has in the client's config. Other clients prefix
133
+ * differently or not at all; this is the longest of the common ones, so a name
134
+ * that fits here fits elsewhere.
135
+ */
136
+ export function clientToolName(entryName, localName) {
137
+ return `mcp__${entryName}__${localName}`;
138
+ }
139
+ /**
140
+ * How long one of the gateway's own tool names may be and still fit.
141
+ *
142
+ * Wrapping a server makes every name longer: `mcp__github__<tool>` becomes
143
+ * `mcp__hmcp__github__<tool>`. A tool that fitted when the server was used
144
+ * directly can stop fitting, so the room left is worked out from the entry's
145
+ * name and handed to the gateway as `max_tool_name_length`.
146
+ */
147
+ export function toolNameBudget(entryName) {
148
+ return CLIENT_TOOL_NAME_LIMIT - clientToolName(entryName, "").length;
149
+ }
@@ -0,0 +1,54 @@
1
+ import { type UpstreamProblem } from "hmcp-core";
2
+ import type { Upstream } from "./config.js";
3
+ /** Connecting took longer than `connect_timeout_ms`. */
4
+ export declare class UpstreamTimeout extends Error {
5
+ readonly upstream: string;
6
+ readonly limitMs: number;
7
+ constructor(message: string, upstream: string, limitMs: number);
8
+ }
9
+ /**
10
+ * A stdio server's process ended -- before it answered, or later, while it
11
+ * was serving. Carries what the process left behind, because "it quit" with
12
+ * no exit code and no last words is the least useful thing a log can say.
13
+ */
14
+ export declare class UpstreamExited extends Error {
15
+ readonly upstream: string;
16
+ readonly exitCode: number | null;
17
+ readonly stderrTail: readonly string[];
18
+ readonly signal: string | null;
19
+ constructor(upstream: string, exitCode: number | null, stderrTail: readonly string[], signal?: string | null);
20
+ }
21
+ /**
22
+ * The URL answers only the old HTTP+SSE transport (an event stream on GET,
23
+ * nothing on POST). Streamable HTTP is what this gateway speaks, so this is a
24
+ * dead end to be told about rather than a 405 to puzzle over.
25
+ */
26
+ export declare class UpstreamSseOnly extends Error {
27
+ readonly url: string;
28
+ constructor(url: string);
29
+ }
30
+ /** The literal values in a spec's env and headers, which must never be repeated in a problem. */
31
+ export declare function specValues(spec: Upstream): string[];
32
+ /**
33
+ * Replaces every known value with `[redacted]`.
34
+ *
35
+ * Short values are left alone: an env of `DEBUG=1` would otherwise turn
36
+ * every "1" in a log line into noise, and a value that short is not a
37
+ * credential anyone could lose. Anything that came out of the locked-keys
38
+ * file is redacted whatever its length -- the caller passes those as `always`.
39
+ */
40
+ export declare function scrub(text: string, values: readonly string[], always?: readonly string[]): string;
41
+ /**
42
+ * A name and password before an address's host, or a key-named query value,
43
+ * taken out of a message: messages are what people screenshot and paste into
44
+ * support chats.
45
+ */
46
+ export declare function withoutAddressKeys(text: string): string;
47
+ export interface ClassifyOptions {
48
+ /**
49
+ * Values resolved from the locked-keys file for this spec. Redacted from
50
+ * the message and the stderr tail whatever their length.
51
+ */
52
+ readonly redact?: readonly string[];
53
+ }
54
+ export declare function classifyUpstreamError(err: unknown, spec: Upstream, stderrTail?: readonly string[], options?: ClassifyOptions): UpstreamProblem;