@agentmesh-md/mcp-server 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/http.js ADDED
@@ -0,0 +1,347 @@
1
+ /**
2
+ * HTTP transport — v2 per-request model (td-7dd275 Phase 1, Seam B).
3
+ * PLAN: ~/agentmesh@1b562f4 docs/plans/PLAN_mcp_2026-07-28_upgrade_and_workstate.md
4
+ * (Seam B) + docs/plans/BUILD_PLAN_mcp_phase1.md resolution (b). Preflight
5
+ * verdict (mcp/test/preflight_inventory.md): CLEAR — no sessionful HTTP MCP
6
+ * consumer exists, so this build takes the registry-DELETION branch.
7
+ *
8
+ * Shape: a single `/mcp` endpoint served by `createMcpHandler` from
9
+ * `@modelcontextprotocol/server@2.0.0` with `legacy: "stateless"` — one
10
+ * factory (`buildServer()`), one endpoint, both eras:
11
+ * - 2026-07-28 traffic: a FRESH MCP `Server` per request; identity rides
12
+ * each request's `_meta` envelope. No `Mcp-Session-Id` is ever issued.
13
+ * - 2025-era traffic: served statelessly through the SAME factory (the
14
+ * established `sessionIdGenerator: undefined` idiom). Legacy GET/DELETE
15
+ * session operations answer 405 — the sessionful surface is RETIRED,
16
+ * loudly, not silently claimed compatible.
17
+ *
18
+ * DELETED with the session registry (the accepted 1B/t5 sessionful machinery
19
+ * — see mcp/test/retired_c15_ledger.md for the control-by-control ledger):
20
+ * - the `sessions` Map (SessionEntry: transport/keyDigest/slot/timestamps)
21
+ * - session binding (sha256 key digest `timingSafeEqual` per session)
22
+ * - capacity reservation (global + per-key caps; CapacitySlot accounting)
23
+ * - the initialize rate limit (global fixed window, pre-auth flood gate)
24
+ * - idle-TTL + absolute-lifetime expiry sweeper (setInterval)
25
+ * - per-session concurrent stream quotas
26
+ * - the SIGUSR2 counts-only registry snapshot
27
+ * Nothing outlives its request on this path, so there is no cross-request
28
+ * state to cap, expire, sweep, bind, or snapshot. The seven registry config
29
+ * knobs (`AGENTMESH_MCP_{MAX_SESSIONS,MAX_SESSIONS_PER_KEY,SESSION_IDLE_TTL_MS,
30
+ * SESSION_MAX_LIFETIME_MS,INIT_RATE_LIMIT,INIT_RATE_WINDOW_MS,
31
+ * MAX_STREAMS_PER_SESSION}`) were DELETED from config.ts in the integration
32
+ * pass with the registry itself — setting them now does nothing and nothing
33
+ * reads them (retired_c15_ledger.md §3b).
34
+ *
35
+ * AUTH — preserved BEHAVIORALLY on the per-request model (accepted 1B model,
36
+ * re-expressed; each gate fails closed, before ANY dispatch):
37
+ * 1. Origin gate — a present-but-unallowlisted `Origin` header is 403
38
+ * rejected before auth/body/dispatch (browser-vector defense; native
39
+ * MCP clients send no Origin and never hit it).
40
+ * 2. Bearer SHAPE gate — every request MUST carry `Authorization: Bearer
41
+ * <key>` (non-empty, control-character-free). Missing/malformed/empty
42
+ * => 401 + `WWW-Authenticate: Bearer` with NOTHING dispatched: no body
43
+ * read, no handler call, no upstream request.
44
+ * 3. Upstream VALIDATION gate, on EVERY request — a syntactically fine key
45
+ * is NOT trusted: before the MCP handler sees the request, the
46
+ * presented key is validated through the SAME AgentMesh auth path every
47
+ * tool call uses — a bounded `GET /api/v1/me` via client.ts
48
+ * (15s/attempt, 30s deadline, <=2 attempts). Invalid/revoked => edge
49
+ * 401, nothing dispatched; upstream unreachable => 503, fail closed.
50
+ * Positive verdicts are cached per key DIGEST for
51
+ * config.httpAuthCacheTtlMs (default 30s; 0 disables the cache).
52
+ * Because EVERY request runs this gate, "per-request revalidation" is
53
+ * now the only model — there is no session for a revoked key to hide
54
+ * in, and the ACCEPTED revocation-detection latency is exactly the
55
+ * cache TTL (unchanged semantics from the accepted 1B build: after
56
+ * expiry, the next request under a revoked key 401s; negative verdicts
57
+ * are never cached, and a definitive rejection drops any stale positive
58
+ * cache entry). A per-request SSE response opened before revocation
59
+ * ends with its own request; no standalone session stream exists to
60
+ * revoke (the GET stream surface is retired — 405).
61
+ * 4. The presented key is threaded (context.ts AsyncLocalStorage) around
62
+ * the ENTIRE dispatch — `mcp.fetch()` and the streamed response body —
63
+ * so the CallTool handler and its upstream fetch observe THIS request's
64
+ * key as the outbound `Authorization: Bearer`: the SAME `/api/v1`
65
+ * auth/scope path stdio uses. An under-scoped key surfaces as the
66
+ * existing `FORBIDDEN: ...` tool error decided server-side.
67
+ *
68
+ * OAuth-swap surface (documented for Phase 2, unchanged by this migration):
69
+ * the Bearer path remains isolated to exactly three seams — (a) this file's
70
+ * edge gate (extract + validate), (b) context.ts (per-request ALS carry),
71
+ * (c) client.ts `effectiveApiKey()` (the single outbound header builder).
72
+ * Swapping Bearer for OAuth touches those three seams and nothing else; the
73
+ * SDK handler is never handed the credential — `authInfo` is deliberately not
74
+ * populated AND the `authorization` header is STRIPPED from the forwarded
75
+ * Request (NON_FORWARDED_HEADERS), so the boundary holds by construction, not
76
+ * by trusting the SDK to keep ignoring it. Identity threading stays in the ALS.
77
+ *
78
+ * Bind posture: loopback only. config.ts REFUSES a non-loopback
79
+ * AGENTMESH_MCP_HTTP_HOST at boot (fail-closed, before any socket opens) —
80
+ * unchanged from the accepted Verity terminal repair; remote exposure still
81
+ * requires the separately accepted security amendment (1B PLAN §5).
82
+ *
83
+ * RULE-10: tokens are never logged (logStderr redacts every string/Error);
84
+ * the auth cache stores key DIGESTS only; redact.ts scrubs the current
85
+ * request's key from every surfaced string. Edge error bodies keep the
86
+ * JSON-RPC error dialect (-32000/-32700) the accepted build used; the SDK
87
+ * handler answers everything past the edge in its own era-correct dialect.
88
+ */
89
+ import { createServer } from "node:http";
90
+ import { createHash } from "node:crypto";
91
+ import { createMcpHandler } from "@modelcontextprotocol/server";
92
+ import { callApi } from "./client.js";
93
+ import { config } from "./config.js";
94
+ import { runWithRequestApiKey } from "./context.js";
95
+ import { logStderr } from "./logger.js";
96
+ import { buildServer } from "./server.js";
97
+ import { readBody, toWebRequest, writeWebResponse } from "./node-bridge.js";
98
+ /**
99
+ * The ONLY body cap on this path — the v2 handler enforces no message-size
100
+ * bound of its own (unbounded request.text() + a clone() double-buffer), so
101
+ * this edge cap must never be relaxed "because the SDK caps anyway" (that was
102
+ * v1-era truth; verified false for @modelcontextprotocol/server@2.0.0).
103
+ * 4 MiB retained from the accepted 1B envelope.
104
+ */
105
+ const MAX_BODY_BYTES = 4 * 1024 * 1024;
106
+ const MCP_PATH = "/mcp";
107
+ /**
108
+ * Hard cap on positive auth-cache entries (distinct key digests). Bounds the
109
+ * cache; oldest-inserted entries are evicted first. Deliberately a constant:
110
+ * it is a memory bound, not a policy knob (each entry is one 64-char digest
111
+ * + one number).
112
+ */
113
+ const AUTH_CACHE_MAX_ENTRIES = 256;
114
+ function sha256Hex(value) {
115
+ return createHash("sha256").update(value, "utf8").digest("hex");
116
+ }
117
+ /** JSON-RPC-shaped edge error, matching the dialect the accepted build used. */
118
+ function respondJsonRpcError(res, status, code, message, extraHeaders) {
119
+ res.writeHead(status, { "Content-Type": "application/json", ...extraHeaders });
120
+ res.end(JSON.stringify({ jsonrpc: "2.0", error: { code, message }, id: null }));
121
+ }
122
+ /** 401 for a key the upstream rejected (invalid or revoked). Never echoes the key. */
123
+ function respondKeyRejected(res) {
124
+ respondJsonRpcError(res, 401, -32000, "Unauthorized: the presented AgentMesh API key was rejected by /api/v1 (invalid or revoked).", { "WWW-Authenticate": "Bearer" });
125
+ }
126
+ /** 503 when the upstream auth check cannot be completed — fail closed, dispatch nothing. */
127
+ function respondValidationUnavailable(res) {
128
+ respondJsonRpcError(res, 503, -32000, "Service Unavailable: upstream credential validation could not be completed; request refused fail-closed.", { "Retry-After": "5" });
129
+ }
130
+ /**
131
+ * Extract the Bearer token, or `null` for a missing/duplicated/malformed
132
+ * header. Mirrors config.ts's control-character hygiene so a garbage token
133
+ * can never be echoed into a fetch TypeError. The raw value is never logged.
134
+ * This is a SHAPE gate only — whether the key actually authenticates is
135
+ * decided by the upstream validation gate (see the module header).
136
+ */
137
+ function bearerToken(req) {
138
+ const header = req.headers["authorization"];
139
+ if (header === undefined || Array.isArray(header)) {
140
+ return null;
141
+ }
142
+ if (!header.startsWith("Bearer ")) {
143
+ return null;
144
+ }
145
+ const token = header.slice("Bearer ".length).trim();
146
+ if (token.length === 0) {
147
+ return null;
148
+ }
149
+ for (const ch of token) {
150
+ const code = ch.charCodeAt(0);
151
+ if (code <= 0x1f || code === 0x7f) {
152
+ return null;
153
+ }
154
+ }
155
+ return token;
156
+ }
157
+ /**
158
+ * Bring up the v2 per-request HTTP transport on config.httpHost:config.httpPort
159
+ * (config.ts guarantees the host is loopback — a non-loopback value never
160
+ * reaches this function). Resolves once listening (with the REAL bound port
161
+ * — PORT=0 selects an ephemeral one); logs the bind line to stderr.
162
+ */
163
+ export async function startHttpServer() {
164
+ // ---- upstream key validation (+ short positive-verdict cache) ----
165
+ // digest hex -> validUntilMs. Positive verdicts only; a negative verdict
166
+ // both returns "invalid" AND drops any stale positive entry, so a
167
+ // revocation observed once is never masked by the cache afterwards.
168
+ const authCache = new Map();
169
+ async function validatePresentedKey(token, keyDigestHex) {
170
+ const ttlMs = config.httpAuthCacheTtlMs;
171
+ if (ttlMs > 0) {
172
+ const validUntil = authCache.get(keyDigestHex);
173
+ if (validUntil !== undefined && Date.now() < validUntil) {
174
+ return "valid";
175
+ }
176
+ }
177
+ // The SAME auth path every tool call uses: /api/v1/me through client.ts,
178
+ // under THIS request's key (context.ts). Bounded by client.ts's 15s
179
+ // per-attempt / 30s total / <=2 attempts policy.
180
+ const result = await runWithRequestApiKey(token, () => callApi({ method: "GET", path: "/me" }));
181
+ if (result.ok) {
182
+ if (ttlMs > 0) {
183
+ if (!authCache.has(keyDigestHex) && authCache.size >= AUTH_CACHE_MAX_ENTRIES) {
184
+ const oldest = authCache.keys().next().value;
185
+ if (oldest !== undefined) {
186
+ authCache.delete(oldest);
187
+ }
188
+ }
189
+ authCache.set(keyDigestHex, Date.now() + ttlMs);
190
+ }
191
+ return "valid";
192
+ }
193
+ authCache.delete(keyDigestHex);
194
+ if (result.status === 401 || result.status === 403) {
195
+ // Upstream affirmatively rejected the credential.
196
+ return "invalid";
197
+ }
198
+ // Network failure / upstream 5xx / client deadline: the verdict is
199
+ // UNKNOWN — fail closed (503 at the edge), never "assume valid".
200
+ return "unavailable";
201
+ }
202
+ // ---- the ONE dual-era MCP handler: fresh Server per request/exchange ----
203
+ // `legacy: "stateless"` is the SDK default; it is written out because the
204
+ // value is load-bearing (control c16: flipping it to "reject" must break
205
+ // the 2025-era client — the dual-era claim is this option, not prose).
206
+ const mcp = createMcpHandler(() => buildServer(), {
207
+ legacy: "stateless",
208
+ onerror: (err) => {
209
+ // Reporting only (never alters the response). logStderr redacts.
210
+ logStderr("agentmesh-mcp: mcp handler error:", err);
211
+ },
212
+ });
213
+ let boundPort = config.httpPort;
214
+ const originHost = config.httpHost === "::1" ? "[::1]" : config.httpHost;
215
+ async function handle(req, res) {
216
+ const url = new URL(req.url ?? "/", "http://localhost");
217
+ if (url.pathname !== MCP_PATH) {
218
+ respondJsonRpcError(res, 404, -32000, "Not Found: this server exposes a single MCP endpoint at /mcp.");
219
+ return;
220
+ }
221
+ // ---- 1. Origin gate (browser-vector defense; before auth/body/dispatch) ----
222
+ const origin = req.headers["origin"];
223
+ if (origin !== undefined) {
224
+ const originValue = Array.isArray(origin) ? undefined : origin;
225
+ if (originValue === undefined || !config.httpAllowedOrigins.includes(originValue)) {
226
+ respondJsonRpcError(res, 403, -32000, "Forbidden: Origin is not allowed for this MCP endpoint.");
227
+ return;
228
+ }
229
+ }
230
+ // ---- 2. Bearer SHAPE gate: 401 BEFORE any body read / dispatch ----
231
+ const token = bearerToken(req);
232
+ if (token === null) {
233
+ respondJsonRpcError(res, 401, -32000, "Unauthorized: every request must carry an AgentMesh API key as 'Authorization: Bearer <key>'.", { "WWW-Authenticate": "Bearer" });
234
+ return;
235
+ }
236
+ // ---- 3. Method gate. POST is the only verb that ever succeeds on the
237
+ // per-request model; GET/DELETE are FORWARDED so the SDK answers the
238
+ // retired 2025 session operations with its own 405 (the loud, spec-shaped
239
+ // retirement the plan requires). Anything else is 405 at the edge.
240
+ const method = req.method ?? "";
241
+ if (method !== "POST" && method !== "GET" && method !== "DELETE") {
242
+ res.writeHead(405, { "Content-Type": "application/json", Allow: "POST" });
243
+ res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32000, message: "Method not allowed." }, id: null }));
244
+ return;
245
+ }
246
+ // ---- read the body (POST only; size cap at the edge). The bytes are
247
+ // passed through untouched — the SDK owns JSON parsing and answers parse
248
+ // errors in the era-correct dialect.
249
+ let body;
250
+ if (method === "POST") {
251
+ try {
252
+ body = await readBody(req, MAX_BODY_BYTES);
253
+ }
254
+ catch (err) {
255
+ if (err instanceof Error && err.message === "PAYLOAD_TOO_LARGE") {
256
+ // Connection: close is load-bearing: the request body was only
257
+ // partially consumed, so the socket must not be reused for
258
+ // keep-alive (framing would be corrupt). The response flushes
259
+ // first, then the server closes the connection.
260
+ respondJsonRpcError(res, 413, -32000, `Request body exceeds the ${MAX_BODY_BYTES}-byte limit.`, {
261
+ Connection: "close",
262
+ });
263
+ }
264
+ else {
265
+ respondJsonRpcError(res, 400, -32700, "Parse error: request body could not be read.");
266
+ }
267
+ return;
268
+ }
269
+ }
270
+ // ---- 4. Upstream validation gate, EVERY request (cache-aware) ----
271
+ const verdict = await validatePresentedKey(token, sha256Hex(token));
272
+ if (verdict === "invalid") {
273
+ respondKeyRejected(res);
274
+ return;
275
+ }
276
+ if (verdict === "unavailable") {
277
+ respondValidationUnavailable(res);
278
+ return;
279
+ }
280
+ // ---- 5. Dispatch inside the request's auth context ----
281
+ // Everything the SDK does for this request — the per-request Server the
282
+ // factory builds, the CallTool handler, its upstream fetch, and the
283
+ // streamed response body — observes THIS request's key via context.ts
284
+ // (AsyncLocalStorage flows through the continuations created inside this
285
+ // scope, including handler work that completes while the response is
286
+ // still streaming). Dispatch errors are logged INSIDE this scope so
287
+ // redact() can scrub the request's credential from them (RULE-10).
288
+ const aborter = new AbortController();
289
+ res.once("close", () => {
290
+ if (!res.writableEnded) {
291
+ aborter.abort();
292
+ }
293
+ });
294
+ const webRequest = toWebRequest(req, `http://${originHost}:${boundPort}${req.url ?? MCP_PATH}`, body, aborter.signal);
295
+ await runWithRequestApiKey(token, async () => {
296
+ try {
297
+ const response = await mcp.fetch(webRequest);
298
+ await writeWebResponse(res, response);
299
+ }
300
+ catch (err) {
301
+ logStderr("agentmesh-mcp: http dispatch failed:", err instanceof Error ? err : String(err));
302
+ if (!res.headersSent) {
303
+ respondJsonRpcError(res, 500, -32603, "Internal server error");
304
+ }
305
+ else {
306
+ res.end();
307
+ }
308
+ }
309
+ });
310
+ }
311
+ const server = createServer((req, res) => {
312
+ handle(req, res).catch((err) => {
313
+ logStderr("agentmesh-mcp: http request handling failed:", err instanceof Error ? err : String(err));
314
+ if (!res.headersSent) {
315
+ respondJsonRpcError(res, 500, -32603, "Internal server error");
316
+ }
317
+ else {
318
+ res.end();
319
+ }
320
+ });
321
+ });
322
+ await new Promise((resolve, reject) => {
323
+ server.once("error", reject);
324
+ server.listen(config.httpPort, config.httpHost, () => resolve());
325
+ });
326
+ const address = server.address();
327
+ boundPort = address !== null && typeof address === "object" ? address.port : config.httpPort;
328
+ logStderr(`agentmesh-mcp: http transport listening on http://${config.httpHost}:${boundPort}${MCP_PATH}`);
329
+ return {
330
+ server,
331
+ host: config.httpHost,
332
+ port: boundPort,
333
+ async close() {
334
+ // Tear down the modern leg (aborts in-flight modern exchanges and
335
+ // closes their per-request instances; the stateless legacy leg holds
336
+ // nothing between exchanges by construction).
337
+ await mcp.close();
338
+ const closed = new Promise((resolve) => {
339
+ server.close(() => resolve());
340
+ });
341
+ // Sever any connection still open (e.g. a held SSE response whose
342
+ // stream close hasn't flushed yet) so shutdown can never hang.
343
+ server.closeAllConnections();
344
+ await closed;
345
+ },
346
+ };
347
+ }
package/dist/index.js ADDED
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env node
2
+ // Dispatch before loading the legacy key-required configuration.
3
+ const action = process.argv[2];
4
+ if (action === "connect") {
5
+ const { connect } = await import("./connect.js");
6
+ const { terminalDiagnostic } = await import("./terminal-diagnostic.js");
7
+ await connect(process.argv.slice(3)).catch((error) => {
8
+ process.stderr.write(`AgentMesh ${terminalDiagnostic(error, 'index.js', 'connect')}.\n`);
9
+ process.stderr.write("AgentMesh Connect failed at connect.ts:connect. Re-run Connect to sign in or check the installed client version. No credentials were printed.\n");
10
+ process.exitCode = 1;
11
+ });
12
+ }
13
+ else if (action === "bridge") {
14
+ const { bridge } = await import("./connect-bridge.js");
15
+ const { terminalDiagnostic } = await import("./terminal-diagnostic.js");
16
+ await bridge(process.argv[3] ?? "").catch((error) => {
17
+ process.stderr.write(`AgentMesh ${terminalDiagnostic(error, 'index.js', 'bridge')}.\n`);
18
+ process.stderr.write("AgentMesh terminal bridge unavailable at connect-bridge.ts:bridge; re-run Connect.\n");
19
+ process.exitCode = 1;
20
+ });
21
+ }
22
+ else
23
+ await import("./legacy.js");
24
+ export {};
package/dist/legacy.js ADDED
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Entrypoint (package.json "bin": "dist/index.js").
4
+ *
5
+ * Stdout purity (PLAN §PRESERVE 2): this file, and every module it imports,
6
+ * writes diagnostics ONLY via logStderr (-> console.error -> stderr). The
7
+ * ONE sanctioned writer of stdout in this whole package is the stdio MCP
8
+ * transport itself — under v2, `serveStdio`'s internally-constructed
9
+ * `StdioServerTransport`, which binds the real `process.stdout` for MCP
10
+ * JSON-RPC frames (that IS the transport, not a logging path).
11
+ *
12
+ * v2 migration (td-7dd275, Seam B): stdio is served through
13
+ * `serveStdio(() => buildServer())` from `@modelcontextprotocol/server/stdio`
14
+ * — dual-era by default (`legacy: 'serve'`): a 2025-era opening (an
15
+ * `initialize` handshake, the deployed 1a behavior) pins a legacy-era
16
+ * instance from the SAME factory and is served exactly as the hand-wired 1a
17
+ * stdio server served it; a modern (2026-07-28) opening gets a modern
18
+ * instance. One factory backs both eras and both transports (http.ts uses
19
+ * the same `buildServer`), so the tool surface cannot drift.
20
+ */
21
+ import { config } from "./config.js";
22
+ import { logStderr } from "./logger.js";
23
+ import { buildServer } from "./server.js";
24
+ import { startHttpServer } from "./http.js";
25
+ import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
26
+ import { readWakeConfig, WakeLoop } from "./wake.js";
27
+ async function main() {
28
+ logStderr(`agentmesh-mcp: starting (transport=${config.transport}, apiBaseUrl=${config.apiBaseUrl})`);
29
+ if (config.transport === "http") {
30
+ // Phase 1 (td-7dd275): v2 per-request Streamable HTTP — single /mcp
31
+ // endpoint, per-request `Authorization: Bearer <am_* key>` required and
32
+ // forwarded upstream as that request's credential (http.ts). The 1A
33
+ // stdout rule is trivially preserved here: http mode writes nothing to
34
+ // stdout.
35
+ const running = await startHttpServer();
36
+ // Graceful shutdown: close the MCP handler + listener, then exit. The
37
+ // timer fallback guarantees a wedged connection can never turn SIGTERM
38
+ // into a hang.
39
+ const shutdown = (signal) => {
40
+ logStderr(`agentmesh-mcp: ${signal} received, closing http transport.`);
41
+ setTimeout(() => process.exit(1), 3000).unref();
42
+ running.close().then(() => process.exit(0), () => process.exit(1));
43
+ };
44
+ process.once("SIGTERM", () => shutdown("SIGTERM"));
45
+ process.once("SIGINT", () => shutdown("SIGINT"));
46
+ return;
47
+ }
48
+ // stdio (default): serveStdio owns the transport (constructed over this
49
+ // process's stdio) and the per-connection era decision; `legacy` is left
50
+ // at its 'serve' default deliberately — 2025-era clients (the deployed 1a
51
+ // consumers) remain first-class. The banner text is load-bearing: the c1
52
+ // controls (and the deployed 00028-qak behavior) key on it.
53
+ // td-ef46e2: optional session wake. Off unless AGENTMESH_WAKE_MODE is set,
54
+ // so the default stdio behavior above is unchanged.
55
+ const wake = readWakeConfig();
56
+ const channel = wake?.mode === "channel";
57
+ let pinned;
58
+ let initialized = false;
59
+ // Claude Code drops channel pushes on a 2026-era connection, so a channel
60
+ // server is wired by hand: it has no server/discover handler, and the
61
+ // client falls back to the 2025 initialize handshake by itself.
62
+ if (channel) {
63
+ const server = buildServer({ channel });
64
+ server.oninitialized = () => {
65
+ initialized = true;
66
+ };
67
+ pinned = server;
68
+ await server.connect(new StdioServerTransport());
69
+ }
70
+ else
71
+ serveStdio(() => {
72
+ const server = buildServer({ channel });
73
+ server.oninitialized = () => {
74
+ initialized = true;
75
+ };
76
+ pinned = server;
77
+ return server;
78
+ }, {
79
+ onerror: (err) => {
80
+ // Reporting only; logStderr redacts (RULE-10).
81
+ logStderr("agentmesh-mcp: stdio transport error:", err);
82
+ },
83
+ });
84
+ logStderr("agentmesh-mcp: connected over stdio, ready.");
85
+ if (wake !== null) {
86
+ const stop = new AbortController();
87
+ process.stdin.once("end", () => stop.abort());
88
+ // A signal listener replaces Node's default exit, so exit explicitly
89
+ // (this also runs the wake lock's exit cleanup).
90
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
91
+ process.once(signal, () => {
92
+ stop.abort();
93
+ process.exit(0);
94
+ });
95
+ }
96
+ const push = async (item, replay) => {
97
+ // Hold the event (it stays queued on disk) until a 2025-era handshake
98
+ // completes; a notification written before that would be dropped.
99
+ let waited = 0;
100
+ while (!initialized && !stop.signal.aborted) {
101
+ if (waited === 30_000) {
102
+ logStderr("agentmesh-mcp: wake is holding channel events: the client has not completed the initialize handshake.");
103
+ }
104
+ await new Promise((r) => setTimeout(r, 200));
105
+ waited += 200;
106
+ }
107
+ if (!initialized || pinned === undefined)
108
+ throw new Error("not delivered");
109
+ await pinned.notification({
110
+ method: "notifications/claude/channel",
111
+ params: { content: item.content, meta: replay ? { ...item.meta, replay: "possible" } : item.meta },
112
+ });
113
+ };
114
+ void new WakeLoop({ ...wake, push: channel ? push : undefined, signal: stop.signal })
115
+ .run()
116
+ .catch((err) => logStderr("agentmesh-mcp: wake failed:", err instanceof Error ? err : String(err)));
117
+ }
118
+ }
119
+ main().catch((err) => {
120
+ const message = err instanceof Error ? (err.stack ?? `${err.name}: ${err.message}`) : String(err);
121
+ logStderr(`agentmesh-mcp: fatal error: ${message}`);
122
+ process.exit(1);
123
+ });
package/dist/logger.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Stderr-only logging.
3
+ *
4
+ * PLAN §PRESERVE 2 (stdout purity): stdio carries only MCP JSON-RPC frames.
5
+ * Nothing in this package may write to stdout except the MCP transport
6
+ * itself (StdioServerTransport, wired in index.ts). Every other module that
7
+ * needs to emit a diagnostic MUST go through `logStderr` (or, before this
8
+ * module can be imported, write to `process.stderr` directly) — never
9
+ * `console.log` / `process.stdout`.
10
+ */
11
+ /**
12
+ * Write a line to stderr. Accepts the same varargs shape as `console.error`;
13
+ * non-string arguments are stringified so callers can pass an Error, an
14
+ * object, etc. without crashing the logger itself.
15
+ *
16
+ * `console.error` targets `process.stderr` in Node (unlike `console.log` /
17
+ * `console.info`, which target stdout), so this is safe by construction —
18
+ * there is no code path here that can reach stdout.
19
+ */
20
+ import { redact } from "./redact.js";
21
+ export function logStderr(...args) {
22
+ // eslint-disable-next-line no-console -- this IS the stderr sink; console.error writes to stderr, never stdout.
23
+ console.error(...args.map(formatArg));
24
+ }
25
+ // Every string (and every Error's stack) that reaches stderr is redacted
26
+ // (build-QA B1 / PLAN §7): the API key must never appear in a log line, even
27
+ // if an Error carrying an upstream/undici message happens to include it.
28
+ function formatArg(value) {
29
+ if (value instanceof Error) {
30
+ return redact(value.stack ?? `${value.name}: ${value.message}`);
31
+ }
32
+ if (typeof value === "string") {
33
+ return redact(value);
34
+ }
35
+ return value;
36
+ }
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+ /** Groups from `groups` tagged as @group; '-' also ends a name, so @team-ops is not @team. */
3
+ function mentionedGroups(body, groups) {
4
+ const out = [];
5
+ for (const g of groups) {
6
+ const escaped = g.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7
+ if (new RegExp(`(?<![\\w@.])@${escaped}(?![\\w-])`, "i").test(body)) out.push(g);
8
+ }
9
+ return out;
10
+ }
11
+
12
+ /** True when the body @mentions anyone at all. */
13
+ function mentionsAnyone(body) {
14
+ return /(?<![\w@.])@[A-Za-z0-9]/.test(body);
15
+ }
16
+
17
+ function mentionsAgent(body, name) {
18
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
19
+ return new RegExp(`(?<![\\w@.])@${escaped}(?![\\w])`, "i").test(body);
20
+ }
21
+
22
+ module.exports = { mentionedGroups, mentionsAnyone, mentionsAgent };
@@ -0,0 +1,110 @@
1
+ import { Readable } from "node:stream";
2
+ import { pipeline } from "node:stream/promises";
3
+ const NON_FORWARDED_HEADERS = new Set([
4
+ "connection",
5
+ "keep-alive",
6
+ "transfer-encoding",
7
+ "upgrade",
8
+ "te",
9
+ "trailer",
10
+ "proxy-authenticate",
11
+ "proxy-authorization",
12
+ "content-length",
13
+ // The raw credential NEVER rides into the SDK layer: the edge gate has
14
+ // already validated it and threaded identity through the ALS (context.ts).
15
+ // Stripping it here makes the documented three-seam OAuth-swap boundary true
16
+ // BY CONSTRUCTION — the v2 SDK neither reads nor derives authInfo from
17
+ // headers today, but it does echo other request-header values into response
18
+ // bodies/onerror, and a future SDK/middleware change must not be able to
19
+ // surface the key (code-review 18e6e24, transport dimension).
20
+ "authorization",
21
+ ]);
22
+ export function readBody(req, maxBytes = 4 * 1024 * 1024, signal) {
23
+ return new Promise((resolve, reject) => {
24
+ const abort = () => { req.pause(); reject(new Error("REQUEST_ABORTED")); };
25
+ if (signal?.aborted) {
26
+ abort();
27
+ return;
28
+ }
29
+ signal?.addEventListener("abort", abort, { once: true });
30
+ const cleanup = () => signal?.removeEventListener("abort", abort);
31
+ req.once("end", cleanup);
32
+ req.once("error", cleanup);
33
+ req.once("aborted", () => { cleanup(); abort(); });
34
+ const chunks = [];
35
+ let total = 0;
36
+ req.on("data", (chunk) => {
37
+ total += chunk.length;
38
+ if (total > maxBytes) {
39
+ reject(new Error("PAYLOAD_TOO_LARGE"));
40
+ req.pause();
41
+ return;
42
+ }
43
+ chunks.push(chunk);
44
+ });
45
+ req.on("end", () => resolve(Buffer.concat(chunks)));
46
+ req.on("error", (err) => reject(err));
47
+ });
48
+ }
49
+ /**
50
+ * Bridge a node:http request to the web-standard `Request` the v2 handler's
51
+ * `fetch` face consumes. (`@modelcontextprotocol/node`'s `toNodeHandler` is
52
+ * not a dependency of this package; the bridge is ~30 lines and keeps the
53
+ * edge auth gates in one file.) `body` is the already-buffered POST payload
54
+ * (cap enforced by readBody); GET/DELETE carry none. `signal` aborts the
55
+ * SDK's exchange when the client disconnects mid-response.
56
+ */
57
+ export function toWebRequest(req, url, body, signal) {
58
+ const headers = new Headers();
59
+ for (const [name, value] of Object.entries(req.headers)) {
60
+ if (value === undefined || NON_FORWARDED_HEADERS.has(name)) {
61
+ continue;
62
+ }
63
+ if (Array.isArray(value)) {
64
+ for (const item of value) {
65
+ headers.append(name, item);
66
+ }
67
+ }
68
+ else {
69
+ headers.set(name, value);
70
+ }
71
+ }
72
+ return new Request(url, {
73
+ method: req.method,
74
+ headers,
75
+ ...(body !== undefined ? { body: new Uint8Array(body) } : {}),
76
+ signal,
77
+ });
78
+ }
79
+ /**
80
+ * Write a web-standard `Response` back onto the node:http response. Streams
81
+ * the body (SSE responses stay open for as long as the SDK keeps them open);
82
+ * a client disconnect destroys the source stream via pipeline(), which
83
+ * cancels the SDK's underlying exchange.
84
+ */
85
+ export async function writeWebResponse(res, response) {
86
+ const headers = {};
87
+ response.headers.forEach((value, name) => {
88
+ headers[name] = value;
89
+ });
90
+ res.writeHead(response.status, headers);
91
+ if (response.body === null) {
92
+ res.end();
93
+ return;
94
+ }
95
+ res.flushHeaders();
96
+ try {
97
+ // Type note: undici's ReadableStream and node:stream/web's are the same
98
+ // runtime object; the lib typings disagree, hence the narrow cast.
99
+ await pipeline(Readable.fromWeb(response.body), res);
100
+ }
101
+ catch (err) {
102
+ // A client that goes away mid-stream (premature close / abort) is a
103
+ // normal end-of-life for an SSE response, not a server error. pipeline()
104
+ // has already destroyed the source, which cancels the SDK exchange.
105
+ const code = err?.code;
106
+ if (code !== "ERR_STREAM_PREMATURE_CLOSE" && code !== "ABORT_ERR") {
107
+ throw err;
108
+ }
109
+ }
110
+ }