hmcp-gateway 0.0.2 → 0.1.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 (102) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +41 -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 +351 -0
  24. package/dist/adopt-cli.js +1857 -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 +386 -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 +535 -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 +200 -0
  38. package/dist/client-config.js +784 -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 +49 -0
  44. package/dist/connect-client.js +249 -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/draft.d.ts +71 -0
  50. package/dist/draft.js +596 -0
  51. package/dist/exposure-cli.d.ts +28 -0
  52. package/dist/exposure-cli.js +119 -0
  53. package/dist/gateway.d.ts +756 -0
  54. package/dist/gateway.js +2106 -0
  55. package/dist/index.d.ts +26 -0
  56. package/dist/index.js +26 -0
  57. package/dist/notify.d.ts +44 -0
  58. package/dist/notify.js +93 -0
  59. package/dist/oauth.d.ts +139 -0
  60. package/dist/oauth.js +641 -0
  61. package/dist/observe.d.ts +10 -0
  62. package/dist/observe.js +26 -0
  63. package/dist/open.d.ts +24 -0
  64. package/dist/open.js +31 -0
  65. package/dist/packs.d.ts +119 -0
  66. package/dist/packs.js +131 -0
  67. package/dist/pin-cli.d.ts +28 -0
  68. package/dist/pin-cli.js +103 -0
  69. package/dist/probe-upstream.d.ts +31 -0
  70. package/dist/probe-upstream.js +377 -0
  71. package/dist/registry-map.d.ts +39 -0
  72. package/dist/registry-map.js +390 -0
  73. package/dist/rule-cli.d.ts +51 -0
  74. package/dist/rule-cli.js +412 -0
  75. package/dist/serve-http.d.ts +67 -0
  76. package/dist/serve-http.js +478 -0
  77. package/dist/snippet.d.ts +20 -0
  78. package/dist/snippet.js +826 -0
  79. package/dist/status-cli.d.ts +61 -0
  80. package/dist/status-cli.js +195 -0
  81. package/dist/suggest-cli.d.ts +43 -0
  82. package/dist/suggest-cli.js +279 -0
  83. package/dist/toolname.d.ts +47 -0
  84. package/dist/toolname.js +149 -0
  85. package/dist/upstream-errors.d.ts +54 -0
  86. package/dist/upstream-errors.js +330 -0
  87. package/dist/upstream.d.ts +128 -0
  88. package/dist/upstream.js +413 -0
  89. package/dist/version.d.ts +10 -0
  90. package/dist/version.js +11 -0
  91. package/package.json +50 -6
  92. package/packs/brave-search.yaml +20 -0
  93. package/packs/context7.yaml +13 -0
  94. package/packs/fetch.yaml +14 -0
  95. package/packs/filesystem.yaml +79 -0
  96. package/packs/git.yaml +29 -0
  97. package/packs/github.yaml +47 -0
  98. package/packs/huggingface.yaml +16 -0
  99. package/packs/memory.yaml +23 -0
  100. package/packs/playwright.yaml +41 -0
  101. package/packs/sequential-thinking.yaml +13 -0
  102. package/packs/time.yaml +14 -0
@@ -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;
@@ -0,0 +1,330 @@
1
+ /**
2
+ * Why a server failed, as a code the console puts into words. Used by the
3
+ * gateway and by the console's "Test it".
4
+ *
5
+ * The person reading the result usually did not write the command that
6
+ * failed -- it came from a catalog card or a pasted README -- so "spawn npx
7
+ * ENOENT" is not an answer. A code is: the console turns `runtime-missing`
8
+ * with `runtime: "npx"` into "Node.js is not installed" and a button that
9
+ * shows how to install it. The original text is kept in `message`, under
10
+ * "Details", for whoever wants it.
11
+ *
12
+ * Classification only reads what the failure already carries -- the error,
13
+ * its cause chain, the spec and the last lines the server wrote -- plus a
14
+ * stat of the folders the spec names. It never makes a request of its own;
15
+ * the one thing that needs one, telling an old SSE-only server apart from a
16
+ * wrong URL, is asked by the connection before it gives up (see
17
+ * `UpstreamSseOnly`).
18
+ */
19
+ import { existsSync } from "node:fs";
20
+ import { homedir } from "node:os";
21
+ import { basename, isAbsolute, join } from "node:path";
22
+ import { isSecretRef } from "hmcp-core";
23
+ /** Connecting took longer than `connect_timeout_ms`. */
24
+ export class UpstreamTimeout extends Error {
25
+ upstream;
26
+ limitMs;
27
+ constructor(message, upstream, limitMs) {
28
+ super(message);
29
+ this.upstream = upstream;
30
+ this.limitMs = limitMs;
31
+ this.name = "UpstreamTimeout";
32
+ }
33
+ }
34
+ /**
35
+ * A stdio server's process ended -- before it answered, or later, while it
36
+ * was serving. Carries what the process left behind, because "it quit" with
37
+ * no exit code and no last words is the least useful thing a log can say.
38
+ */
39
+ export class UpstreamExited extends Error {
40
+ upstream;
41
+ exitCode;
42
+ stderrTail;
43
+ signal;
44
+ constructor(upstream, exitCode, stderrTail, signal = null) {
45
+ super(`upstream "${upstream}" exited` +
46
+ (exitCode !== null ? ` with code ${exitCode}` : signal ? ` on signal ${signal}` : "") +
47
+ (stderrTail.length > 0 ? `; it last wrote: ${stderrTail[stderrTail.length - 1]}` : ""));
48
+ this.upstream = upstream;
49
+ this.exitCode = exitCode;
50
+ this.stderrTail = stderrTail;
51
+ this.signal = signal;
52
+ this.name = "UpstreamExited";
53
+ }
54
+ }
55
+ /**
56
+ * The URL answers only the old HTTP+SSE transport (an event stream on GET,
57
+ * nothing on POST). Streamable HTTP is what this gateway speaks, so this is a
58
+ * dead end to be told about rather than a 405 to puzzle over.
59
+ */
60
+ export class UpstreamSseOnly extends Error {
61
+ url;
62
+ constructor(url) {
63
+ super(`${url} only speaks the older SSE transport, not Streamable HTTP`);
64
+ this.url = url;
65
+ this.name = "UpstreamSseOnly";
66
+ }
67
+ }
68
+ /** The programs a catalog entry or a pasted snippet launches through, by what has to be installed. */
69
+ const RUNTIMES = {
70
+ npx: "npx",
71
+ node: "node",
72
+ npm: "npx",
73
+ uvx: "uvx",
74
+ uv: "uv",
75
+ docker: "docker",
76
+ python: "python",
77
+ python3: "python",
78
+ pip: "python",
79
+ git: "git"
80
+ };
81
+ const NETWORK_CODES = new Set([
82
+ "ENOTFOUND",
83
+ "EAI_AGAIN",
84
+ "ECONNREFUSED",
85
+ "ECONNRESET",
86
+ "EHOSTUNREACH",
87
+ "ENETUNREACH",
88
+ "EPIPE",
89
+ "UND_ERR_SOCKET",
90
+ "UND_ERR_CLOSED"
91
+ ]);
92
+ const TIMEOUT_CODES = new Set(["ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT"]);
93
+ const TLS_CODES = new Set([
94
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
95
+ "SELF_SIGNED_CERT_IN_CHAIN",
96
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
97
+ "UNABLE_TO_GET_ISSUER_CERT",
98
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
99
+ "CERT_HAS_EXPIRED",
100
+ "CERT_NOT_YET_VALID",
101
+ "CERT_REVOKED",
102
+ "CERT_UNTRUSTED",
103
+ "ERR_TLS_CERT_ALTNAME_INVALID",
104
+ "ERR_SSL_WRONG_VERSION_NUMBER",
105
+ "EPROTO"
106
+ ]);
107
+ /** Every error in the `cause` chain, outermost first, bounded against a cycle. */
108
+ function causeChain(err) {
109
+ const out = [];
110
+ let current = err;
111
+ while (current !== undefined && current !== null && out.length < 8 && !out.includes(current)) {
112
+ out.push(current);
113
+ current = current.cause;
114
+ }
115
+ return out;
116
+ }
117
+ function facts(err) {
118
+ const chain = causeChain(err);
119
+ const names = new Set();
120
+ const codes = new Set();
121
+ const texts = [];
122
+ for (const e of chain) {
123
+ if (typeof e !== "object" || e === null) {
124
+ texts.push(String(e));
125
+ continue;
126
+ }
127
+ const { name, code, message } = e;
128
+ if (typeof name === "string")
129
+ names.add(name);
130
+ if (typeof code === "string")
131
+ codes.add(code);
132
+ if (typeof message === "string")
133
+ texts.push(message);
134
+ }
135
+ return { chain, names, codes, text: texts.join(" | ") };
136
+ }
137
+ function find(chain, name) {
138
+ return chain.find((e) => typeof e === "object" && e !== null && e.name === name);
139
+ }
140
+ /** The HTTP status a failure carries, from the SDK's StreamableHTTPError (its `code`) or our own text. */
141
+ function httpStatus(f) {
142
+ for (const e of f.chain) {
143
+ const code = e?.code;
144
+ if (typeof code === "number" && code >= 100 && code < 600)
145
+ return code;
146
+ }
147
+ const m = /\(HTTP (\d{3})\)|\bstatus(?: code)? (\d{3})\b|\breturned (\d{3})\b/i.exec(f.text);
148
+ const raw = m?.[1] ?? m?.[2] ?? m?.[3];
149
+ return raw ? Number(raw) : undefined;
150
+ }
151
+ function expandHome(p) {
152
+ return p === "~" ? homedir() : p.startsWith("~/") ? join(homedir(), p.slice(2)) : p;
153
+ }
154
+ /** An argument that names a place on disk, rather than a flag or a package. */
155
+ function looksLikePath(arg) {
156
+ if (arg.startsWith("-") || arg.includes("://"))
157
+ return false;
158
+ return isAbsolute(arg) || arg.startsWith("~/") || arg === "~" || /^[A-Za-z]:[\\/]/.test(arg);
159
+ }
160
+ /**
161
+ * A folder the spec names that is not there.
162
+ *
163
+ * The cwd always counts: a missing cwd makes Node report the *command* as
164
+ * missing (`spawn npx ENOENT`), which would send someone off reinstalling
165
+ * Node over a folder they renamed. An argument counts when it reads like a
166
+ * folder (no extension): a missing *file* is more often the script being run
167
+ * or a database the server will create, and calling either a missing folder
168
+ * would send someone looking for the wrong thing. The server's own last
169
+ * words, in the tail, cover those.
170
+ */
171
+ function missingFolder(spec, includeArgs) {
172
+ if (spec.transport !== "stdio")
173
+ return undefined;
174
+ if (spec.cwd && !existsSync(expandHome(spec.cwd)))
175
+ return spec.cwd;
176
+ if (!includeArgs)
177
+ return undefined;
178
+ for (const arg of spec.args) {
179
+ const candidate = arg.includes("=") && !looksLikePath(arg) ? arg.slice(arg.indexOf("=") + 1) : arg;
180
+ if (!looksLikePath(candidate))
181
+ continue;
182
+ const full = expandHome(candidate);
183
+ if (existsSync(full))
184
+ continue;
185
+ if (!/\.[A-Za-z0-9]{1,6}$/.test(basename(full)))
186
+ return candidate;
187
+ }
188
+ return undefined;
189
+ }
190
+ /** The literal values in a spec's env and headers, which must never be repeated in a problem. */
191
+ export function specValues(spec) {
192
+ const record = spec.transport === "stdio" ? spec.env : spec.headers;
193
+ return Object.values(record).filter((v) => typeof v === "string" && !isSecretRef(v));
194
+ }
195
+ /**
196
+ * Replaces every known value with `[redacted]`.
197
+ *
198
+ * Short values are left alone: an env of `DEBUG=1` would otherwise turn
199
+ * every "1" in a log line into noise, and a value that short is not a
200
+ * credential anyone could lose. Anything that came out of the locked-keys
201
+ * file is redacted whatever its length -- the caller passes those as `always`.
202
+ */
203
+ export function scrub(text, values, always = []) {
204
+ let out = text;
205
+ const all = [...always.filter((v) => v.length > 0), ...values.filter((v) => v.length >= 6)];
206
+ // Longest first, so a value that contains another is replaced whole.
207
+ for (const v of [...new Set(all)].sort((a, b) => b.length - a.length))
208
+ out = out.split(v).join("[redacted]");
209
+ return out;
210
+ }
211
+ function hostOf(spec) {
212
+ if (spec.transport !== "http")
213
+ return undefined;
214
+ try {
215
+ return new URL(spec.url).host;
216
+ }
217
+ catch {
218
+ return undefined;
219
+ }
220
+ }
221
+ /**
222
+ * What the Docker CLI says when Docker Desktop (the daemon) isn't running,
223
+ * across versions and systems: the old "Cannot connect to the Docker daemon",
224
+ * 29.x's "failed to connect to the docker API at unix:///var/run/docker.sock",
225
+ * and Windows' named pipe.
226
+ */
227
+ const DOCKER_NOT_RUNNING = /Cannot connect to the Docker daemon|docker daemon is not running|error during connect|Is the docker daemon running|failed to connect to the docker API|check if the path is correct and if the daemon is running|dial unix [^\s]*docker\.sock|docker_engine.*(cannot find|not found|no such)|pipe\/docker_engine|Docker Desktop is (not running|starting|stopped|unable to start)|daemon is not running/i;
228
+ /**
229
+ * A name and password before an address's host, or a key-named query value,
230
+ * taken out of a message: messages are what people screenshot and paste into
231
+ * support chats.
232
+ */
233
+ export function withoutAddressKeys(text) {
234
+ return text
235
+ .replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^/\s@"']+@/gi, "$1")
236
+ .replace(/([?&](?:api[_-]?key|apikey|key|token|access[_-]?token|auth[_-]?token|auth|secret|client[_-]?secret|password|pass|pwd|sig|signature)=)[^&\s"']+/gi, "$1[removed]");
237
+ }
238
+ export function classifyUpstreamError(err, spec, stderrTail = [], options = {}) {
239
+ const f = facts(err);
240
+ const literals = specValues(spec);
241
+ const clean = (s) => withoutAddressKeys(scrub(s, literals, options.redact ?? []));
242
+ const exited = find(f.chain, "UpstreamExited");
243
+ const tailSource = stderrTail.length > 0 ? stderrTail : (exited?.stderrTail ?? []);
244
+ const tail = tailSource.slice(-20).map(clean);
245
+ const make = (code, detail = {}) => {
246
+ let message = clean(f.text || String(err));
247
+ // The gateway's own log advice ("run that by hand", "raise connect_timeout_ms") is for its log, not for a person's screen.
248
+ if (code === "timeout")
249
+ message = message.replace(/\s*(It was started as:|Run that by hand|Raise connect_timeout_ms)[\s\S]*$/, "").trim() || message;
250
+ const d = { ...detail, ...(tail.length > 0 ? { stderrTail: tail } : {}) };
251
+ return { code, message, ...(Object.keys(d).length > 0 ? { detail: d } : {}) };
252
+ };
253
+ const command = spec.transport === "stdio" ? spec.command : undefined;
254
+ const commandBase = command ? basename(command).replace(/\.(exe|cmd|bat)$/i, "").toLowerCase() : undefined;
255
+ const runtime = commandBase ? RUNTIMES[commandBase] : undefined;
256
+ // Locked keys and sign-in first: a missing key can make anything else fail too.
257
+ const missing = find(f.chain, "SecretMissing");
258
+ if (missing)
259
+ return make("secret-missing", { secret: missing.secretName });
260
+ const signIn = find(f.chain, "NeedsSignIn");
261
+ if (signIn)
262
+ return make("needs-sign-in", { secret: signIn.secretName });
263
+ if (find(f.chain, "UpstreamSseOnly"))
264
+ return make("sse-only", { ...(hostOf(spec) ? { host: hostOf(spec) } : {}) });
265
+ // Spawning. A missing cwd looks exactly like a missing command, so it is checked first.
266
+ if (f.codes.has("ENOENT") && /\bspawn\b/.test(f.text)) {
267
+ const folder = missingFolder(spec, false);
268
+ if (folder)
269
+ return make("folder-missing", { path: folder });
270
+ if (runtime)
271
+ return make("runtime-missing", { runtime, ...(command ? { command } : {}) });
272
+ return make("command-not-found", { ...(command ? { command } : {}) });
273
+ }
274
+ if (f.codes.has("EACCES") && /\bspawn\b/.test(f.text)) {
275
+ return make("command-not-found", { ...(command ? { command } : {}) });
276
+ }
277
+ // Docker installed but not running: the CLI exists, the daemon does not answer.
278
+ const said = `${tail.join("\n")}\n${f.text}`;
279
+ if (commandBase === "docker" &&
280
+ DOCKER_NOT_RUNNING.test(said)) {
281
+ return make("runtime-not-running", { runtime: "docker", command: command });
282
+ }
283
+ if (find(f.chain, "UpstreamTimeout") || f.names.has("TimeoutError") || f.codes.has("ETIMEDOUT")) {
284
+ return make("timeout");
285
+ }
286
+ const tlsCode = [...f.codes].find((c) => TLS_CODES.has(c) || c.startsWith("CERT_") || c.startsWith("ERR_TLS_"));
287
+ if (tlsCode || /certificate|self[- ]signed|unable to verify the first certificate/i.test(f.text)) {
288
+ return make("tls", { ...(hostOf(spec) ? { host: hostOf(spec) } : {}) });
289
+ }
290
+ if ([...f.codes].some((c) => NETWORK_CODES.has(c)) || /\b(ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN)\b/.test(f.text)) {
291
+ return make("network", { ...(hostOf(spec) ? { host: hostOf(spec) } : {}) });
292
+ }
293
+ if ([...f.codes].some((c) => TIMEOUT_CODES.has(c)))
294
+ return make("timeout");
295
+ const egress = find(f.chain, "EgressDenied");
296
+ if (egress) {
297
+ const host = hostOf(spec);
298
+ const withHost = host ? { host } : {};
299
+ if (egress.code === "dns" || egress.code === "network")
300
+ return make("network", withHost);
301
+ if (egress.code === "aborted")
302
+ return make("timeout", withHost);
303
+ return make("egress-refused", withHost);
304
+ }
305
+ if (f.names.has("UpstreamCredentialRejected") || f.names.has("UnauthorizedError")) {
306
+ return make("auth-rejected", { status: 401 });
307
+ }
308
+ const status = httpStatus(f);
309
+ if (spec.transport === "http") {
310
+ if (status === 401 || status === 403)
311
+ return make("auth-rejected", { status });
312
+ if (status === 404 || status === 405 || status === 406 || status === 415)
313
+ return make("not-mcp", { status });
314
+ if (/Unexpected content type|text\/html|is not valid JSON|Unexpected token/i.test(f.text) || f.names.has("SyntaxError")) {
315
+ return make("not-mcp", { ...(status !== undefined && status > 0 ? { status } : {}) });
316
+ }
317
+ if (f.names.has("ZodError") || /invalid_union|"code":\s*"invalid/i.test(f.text))
318
+ return make("not-mcp");
319
+ }
320
+ if (exited || /Connection closed/i.test(f.text)) {
321
+ const folder = missingFolder(spec, true);
322
+ if (folder)
323
+ return make("folder-missing", { path: folder });
324
+ return make("exited", { exitCode: exited?.exitCode ?? null });
325
+ }
326
+ // A stdio child whose stdout is not JSON-RPC: something answered, but not MCP.
327
+ if (spec.transport === "stdio" && (f.names.has("SyntaxError") || f.names.has("ZodError")))
328
+ return make("not-mcp");
329
+ return make("unknown");
330
+ }
@@ -0,0 +1,128 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import { type EgressGuard, type SecretStore } from "hmcp-core";
3
+ import type { Upstream } from "./config.js";
4
+ import type { UpstreamTokenSource } from "./contracts.js";
5
+ import { UpstreamExited } from "./upstream-errors.js";
6
+ /** How many of a server's last stderr lines are kept for a problem report. */
7
+ export declare const STDERR_TAIL_LINES = 20;
8
+ export interface UpstreamTool {
9
+ readonly name: string;
10
+ readonly description: string;
11
+ readonly inputSchema: unknown;
12
+ /**
13
+ * The upstream's own output schema, when it declared one. Carried verbatim
14
+ * and never synthesised: half a tool's contract is what comes back.
15
+ */
16
+ readonly outputSchema: unknown | undefined;
17
+ readonly annotations: {
18
+ readOnlyHint?: boolean;
19
+ destructiveHint?: boolean;
20
+ idempotentHint?: boolean;
21
+ title?: string;
22
+ } | undefined;
23
+ }
24
+ /**
25
+ * A resource as the upstream advertises it. `uri` is the identifier the model
26
+ * sends back verbatim, so it is carried exactly as given and never rewritten.
27
+ */
28
+ export interface UpstreamResource {
29
+ readonly uri: string;
30
+ readonly name: string;
31
+ readonly description: string;
32
+ readonly mimeType: string | undefined;
33
+ /** A template (`docs://{id}`) rather than a resource that exists now. */
34
+ readonly template: boolean;
35
+ }
36
+ export interface UpstreamPrompt {
37
+ readonly name: string;
38
+ readonly description: string;
39
+ readonly arguments: readonly {
40
+ name: string;
41
+ description?: string;
42
+ required?: boolean;
43
+ }[];
44
+ }
45
+ /**
46
+ * A connection to one upstream MCP server. HTTP upstreams are vetted by the
47
+ * egress guard before a connection is opened, so the allowlist and the SSRF
48
+ * checks apply to servers we did not build just as they do to a REST API.
49
+ */
50
+ export declare class UpstreamConnection {
51
+ readonly spec: Upstream;
52
+ private readonly tail;
53
+ private readonly transport;
54
+ readonly client: Client;
55
+ private tools;
56
+ private resources;
57
+ private prompts;
58
+ /** Set by `close()`, so an intended close is not reported as a crash. */
59
+ private closing;
60
+ private constructor();
61
+ /** The last lines a stdio server wrote to stderr, secrets removed. */
62
+ stderrTail(): string[];
63
+ /**
64
+ * Calls back once if the server goes away on its own -- a stdio child that
65
+ * exits or crashes while serving. Not called for `close()`.
66
+ */
67
+ onClosed(listener: (err: UpstreamExited) => void): void;
68
+ /**
69
+ * Reads a stdio upstream's stderr and hands over whole lines.
70
+ *
71
+ * Whole lines rather than chunks, because a chunk boundary falls mid-message
72
+ * and a half-line prefixed with the upstream's name is worse than no line
73
+ * at all. The stream is read to its end either way: this is the only place
74
+ * a stdio server can say why it will not start.
75
+ */
76
+ private static drainStderr;
77
+ static connect(spec: Upstream, egress: EgressGuard, options?: {
78
+ /**
79
+ * Where a stdio upstream's stderr lines go. The default is the
80
+ * gateway's own stderr, which is safe even over stdio: stdout is the
81
+ * protocol, stderr is not.
82
+ */
83
+ readonly onStderr?: (line: string) => void;
84
+ /** Where `{ secret: name }` values are resolved from. */
85
+ readonly secrets?: SecretStore;
86
+ /** For an http upstream with `oauth:`: where its Authorization header comes from. */
87
+ readonly tokenSource?: UpstreamTokenSource;
88
+ /** Aborting closes whatever was started, so a timed-out connect leaves no child behind. */
89
+ readonly signal?: AbortSignal;
90
+ /** Receives the values resolved from the locked-keys file, so a caller can redact them too. */
91
+ readonly onResolved?: (values: string[]) => void;
92
+ }): Promise<UpstreamConnection>;
93
+ /**
94
+ * Whether a URL that refused a POST answers a GET with an event stream --
95
+ * the shape of the old HTTP+SSE transport. Asked only after a failure, so a
96
+ * working server never sees the extra request, and bounded to a few
97
+ * seconds because the answer is only worth a better error message.
98
+ */
99
+ private static answersSse;
100
+ /** What this upstream offers beyond tools, as it declared at initialize. */
101
+ get offers(): {
102
+ resources: boolean;
103
+ prompts: boolean;
104
+ };
105
+ refreshTools(): Promise<UpstreamTool[]>;
106
+ listTools(): readonly UpstreamTool[];
107
+ /**
108
+ * Resources, including templates, which are listed by a separate call and
109
+ * are the same thing to everything downstream: an advertised description
110
+ * and a URI the model will send back.
111
+ */
112
+ refreshResources(): Promise<UpstreamResource[]>;
113
+ listResources(): readonly UpstreamResource[];
114
+ refreshPrompts(): Promise<UpstreamPrompt[]>;
115
+ listPrompts(): readonly UpstreamPrompt[];
116
+ /**
117
+ * Calls back when this upstream announces that its tool list changed.
118
+ *
119
+ * Registered only when the upstream said it would send them, because the
120
+ * SDK treats a handler for an undeclared notification as a programming
121
+ * error rather than ignoring it.
122
+ */
123
+ onToolsChanged(listener: () => void): void;
124
+ callTool(name: string, args: Record<string, unknown>): Promise<unknown>;
125
+ readResource(uri: string): Promise<unknown>;
126
+ getPrompt(name: string, args: Record<string, string>): Promise<unknown>;
127
+ close(): Promise<void>;
128
+ }