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

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/config.js ADDED
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Environment-derived configuration.
3
+ *
4
+ * PLAN §1 "Config (env only)" + 1B PLAN §2 (docs/plans/agentmesh_plan_mcp_http_1b_2026-07-28.md):
5
+ * - AGENTMESH_API_KEY (stdio: required; the `am_live_` key; RULE-10 secret — never
6
+ * logged/printed. http: OPTIONAL and never used for requests —
7
+ * every HTTP request presents its own key, see context.ts.)
8
+ * - AGENTMESH_API_BASE_URL (default "https://agentmesh.md"; override for non-prod QA)
9
+ * - AGENTMESH_MCP_TRANSPORT ("stdio" default | "http")
10
+ * - PORT (http only; default 3001; 0 = OS-assigned ephemeral port)
11
+ * - AGENTMESH_MCP_HTTP_HOST (http only; default "127.0.0.1". LOOPBACK ONLY in this tier:
12
+ * anything but 127.0.0.1 / localhost / ::1 is REFUSED at boot,
13
+ * fail-closed, before any socket opens — remote exposure requires
14
+ * a separately accepted security amendment (Verity terminal
15
+ * repair, 2026-07-29; see the 1B PLAN §5).)
16
+ * - AGENTMESH_MCP_ALLOWED_ORIGINS (http only; comma-separated exact Origin values; default
17
+ * EMPTY = any Origin-bearing request is rejected 403. Non-browser
18
+ * MCP clients send no Origin header and are unaffected.)
19
+ * - HTTP auth-cache bound (http only; the SESSION-REGISTRY knob family that
20
+ * used to sit here — MAX_SESSIONS / MAX_SESSIONS_PER_KEY / SESSION_IDLE_TTL /
21
+ * SESSION_MAX_LIFETIME / INIT_RATE_LIMIT / INIT_RATE_WINDOW /
22
+ * MAX_STREAMS_PER_SESSION — was DELETED with the registry in the v2
23
+ * stateless migration, td-7dd275; see mcp/test/retired_c15_ledger.md):
24
+ * AGENTMESH_MCP_AUTH_CACHE_TTL_MS (30000 = 30 s; 0 allowed = revalidate upstream on
25
+ * EVERY request) positive-verdict auth-cache TTL —
26
+ * this TTL IS the accepted upstream-revocation
27
+ * detection latency (documented in http.ts + PLAN)
28
+ *
29
+ * This module is evaluated once (ES modules are singletons per resolved
30
+ * path), at the moment something first imports it. A missing/invalid
31
+ * required value writes a clear message to STDERR and exits the process —
32
+ * fail closed, before any transport is wired up, so an operator sees a
33
+ * plain diagnostic instead of a downstream 401 with no context. The key's
34
+ * VALUE is never written anywhere by this module, including in the error
35
+ * paths below.
36
+ */
37
+ import { logStderr } from "./logger.js";
38
+ const DEFAULT_API_BASE_URL = "https://agentmesh.md";
39
+ const DEFAULT_HTTP_PORT = 3001;
40
+ const DEFAULT_HTTP_HOST = "127.0.0.1";
41
+ /** Writes `message` to stderr and terminates the process. Never returns. */
42
+ function fatal(message) {
43
+ logStderr(`agentmesh-mcp: ${message}`);
44
+ process.exit(1);
45
+ }
46
+ function readApiKey(transport) {
47
+ const value = process.env["AGENTMESH_API_KEY"];
48
+ if (value === undefined || value.length === 0) {
49
+ if (transport === "http") {
50
+ // 1B PLAN §2: HTTP mode has no process-wide downstream credential — every
51
+ // request presents its own key (context.ts) and an env key would never be
52
+ // consulted for a request. Absent is therefore VALID here, and the empty
53
+ // string can never reach an Authorization header (client.ts refuses it).
54
+ return "";
55
+ }
56
+ fatal("missing required environment variable AGENTMESH_API_KEY (the AgentMesh Bearer credential). " +
57
+ "Set it before starting this server; it is never read from argv or a config file.");
58
+ }
59
+ // RULE-10 / PLAN §7: the key is placed verbatim into the outbound `Authorization`
60
+ // header. A key carrying a control character (a stray newline from a paste, or a
61
+ // multi-line config value) is not a legal HTTP header value, so `fetch()` throws a
62
+ // TypeError whose message ECHOES the attempted `Bearer <value>` — which would leak
63
+ // the credential into a tool-result error string on stdout. Reject it here, fail
64
+ // closed, and never print its value. (A charCodeAt scan, not a regex literal, so no
65
+ // control byte or escape sequence can be mangled into the source.)
66
+ for (const ch of value) {
67
+ const code = ch.charCodeAt(0);
68
+ if (code <= 0x1f || code === 0x7f) {
69
+ fatal("AGENTMESH_API_KEY contains a control character (for example a newline) and is not a " +
70
+ "valid credential — check for a trailing newline or a multi-line paste. Its value is not shown.");
71
+ }
72
+ }
73
+ return value;
74
+ }
75
+ function readApiBaseUrl() {
76
+ const value = process.env["AGENTMESH_API_BASE_URL"];
77
+ if (value === undefined || value.length === 0) {
78
+ return DEFAULT_API_BASE_URL;
79
+ }
80
+ return value;
81
+ }
82
+ function readTransport() {
83
+ const value = process.env["AGENTMESH_MCP_TRANSPORT"];
84
+ if (value === undefined || value.length === 0) {
85
+ return "stdio";
86
+ }
87
+ if (value === "stdio" || value === "http") {
88
+ return value;
89
+ }
90
+ fatal(`invalid AGENTMESH_MCP_TRANSPORT "${value}" (expected "stdio" or "http").`);
91
+ }
92
+ function readHttpPort(transport) {
93
+ if (transport !== "http") {
94
+ // Never read (let alone fatal on) PORT in stdio mode: many host
95
+ // environments export an unrelated PORT, and stdio ignores it entirely.
96
+ return DEFAULT_HTTP_PORT;
97
+ }
98
+ const value = process.env["PORT"];
99
+ if (value === undefined || value.length === 0) {
100
+ return DEFAULT_HTTP_PORT;
101
+ }
102
+ const port = Number(value);
103
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
104
+ fatal(`invalid PORT "${value}" (expected an integer 0-65535; 0 selects an ephemeral port).`);
105
+ }
106
+ return port;
107
+ }
108
+ /**
109
+ * The complete set of bind hosts this tier will accept. Verity terminal
110
+ * repair (REVISE 2026-07-29T00:09Z): the server REFUSES to bind non-loopback
111
+ * — the prior "0.0.0.0 as a deploy opt-in" pathway is REMOVED. Remote
112
+ * exposure requires a separately accepted security amendment (TLS
113
+ * termination / ingress + Host-proxy contract, credential/audience decision
114
+ * or an explicit raw-key pass-through waiver, bounds, rollback, direct
115
+ * operator authority) — 1B PLAN §5.
116
+ */
117
+ const LOOPBACK_HTTP_HOSTS = ["127.0.0.1", "localhost", "::1"];
118
+ function readHttpHost(transport) {
119
+ if (transport !== "http") {
120
+ return DEFAULT_HTTP_HOST;
121
+ }
122
+ const value = process.env["AGENTMESH_MCP_HTTP_HOST"];
123
+ if (value === undefined || value.length === 0) {
124
+ return DEFAULT_HTTP_HOST;
125
+ }
126
+ if (!LOOPBACK_HTTP_HOSTS.includes(value)) {
127
+ fatal(`AGENTMESH_MCP_HTTP_HOST="${value}" refused: this build binds LOOPBACK ONLY ` +
128
+ `(${LOOPBACK_HTTP_HOSTS.join(", ")}). Exposing the MCP HTTP transport beyond loopback requires a ` +
129
+ "separately accepted security amendment (TLS termination / ingress + Host-proxy contract, " +
130
+ "credential/audience decision or an explicit raw-key pass-through waiver, bounds, rollback, and " +
131
+ "direct operator authority) — see docs/plans/agentmesh_plan_mcp_http_1b_2026-07-28.md §5. " +
132
+ "Exiting fail-closed before any socket opens.");
133
+ }
134
+ return value;
135
+ }
136
+ /**
137
+ * Reads an integer env var for the http transport's registry bounds.
138
+ * Non-http transports get the default without consulting the environment
139
+ * (mirrors readHttpPort's "never read http-only vars in stdio mode" rule).
140
+ * Out-of-range / non-integer values fail closed at boot. The ceiling keeps
141
+ * every ms value safely inside a 32-bit signed timer range.
142
+ */
143
+ function readBoundedInt(transport, name, defaultValue, minimum) {
144
+ if (transport !== "http") {
145
+ return defaultValue;
146
+ }
147
+ const value = process.env[name];
148
+ if (value === undefined || value.length === 0) {
149
+ return defaultValue;
150
+ }
151
+ const parsed = Number(value);
152
+ if (!Number.isInteger(parsed) || parsed < minimum || parsed > 2_147_483_647) {
153
+ fatal(`invalid ${name} "${value}" (expected an integer >= ${minimum} and <= 2147483647).`);
154
+ }
155
+ return parsed;
156
+ }
157
+ function readHttpAllowedOrigins(transport) {
158
+ if (transport !== "http") {
159
+ return [];
160
+ }
161
+ const value = process.env["AGENTMESH_MCP_ALLOWED_ORIGINS"];
162
+ if (value === undefined || value.length === 0) {
163
+ return [];
164
+ }
165
+ return value
166
+ .split(",")
167
+ .map((origin) => origin.trim())
168
+ .filter((origin) => origin.length > 0);
169
+ }
170
+ // Transport is resolved FIRST: it decides whether AGENTMESH_API_KEY is
171
+ // required (stdio) or optional (http), and whether the http-only vars are
172
+ // read at all.
173
+ const transport = readTransport();
174
+ /**
175
+ * The process-wide, validated configuration. Reading `process.env` happens
176
+ * exactly once, here, at first import.
177
+ */
178
+ export const config = {
179
+ apiKey: readApiKey(transport),
180
+ apiBaseUrl: readApiBaseUrl(),
181
+ transport,
182
+ httpPort: readHttpPort(transport),
183
+ httpHost: readHttpHost(transport),
184
+ httpAllowedOrigins: readHttpAllowedOrigins(transport),
185
+ // Registry knob family DELETED with the session registry (v2 stateless,
186
+ // td-7dd275 — see retired_c15_ledger.md §3b). The one surviving HTTP bound:
187
+ // the 30s auth-cache TTL is the accepted revocation detection latency.
188
+ httpAuthCacheTtlMs: readBoundedInt(transport, "AGENTMESH_MCP_AUTH_CACHE_TTL_MS", 30_000, 0),
189
+ };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Per-request auth context (1B "Per-request key threading", carried across
3
+ * the v2 per-request migration unchanged — td-7dd275 Seam B).
4
+ *
5
+ * In HTTP mode every inbound request presents its own AgentMesh credential
6
+ * (`Authorization: Bearer am_…`), and THAT key — never a process-wide one —
7
+ * must be the Bearer on every upstream `/api/v1` call the request causes.
8
+ * `http.ts` wraps each dispatch — `mcp.fetch(...)` plus the streamed
9
+ * response write — in `runWithRequestApiKey(...)`; `client.ts` (the single
10
+ * builder of the outbound Authorization header) and `redact.ts` (RULE-10
11
+ * scrubbing) read it back via `currentRequestApiKey()`. This module is one
12
+ * of the three seams of the documented Bearer->OAuth swap surface (http.ts
13
+ * edge gate -> THIS ALS carry -> client.ts header builder); it deliberately
14
+ * never learns what kind of credential it carries.
15
+ *
16
+ * AsyncLocalStorage propagates through the v2 handler's promise chains —
17
+ * `createMcpHandler` builds the per-request Server, runs the CallTool
18
+ * handler, and streams the response all within continuations created inside
19
+ * the `runWithRequestApiKey` scope — so the tool's `run()` and the upstream
20
+ * fetch observe the initiating request's context even while the response is
21
+ * still streaming. In stdio mode nothing ever enters this storage and
22
+ * `currentRequestApiKey()` is always `undefined`.
23
+ *
24
+ * This module deliberately imports nothing from config.ts / logger.ts /
25
+ * redact.ts so it can sit below all of them with no import cycle.
26
+ */
27
+ import { AsyncLocalStorage } from "node:async_hooks";
28
+ const storage = new AsyncLocalStorage();
29
+ /** Run `fn` with `apiKey` as the ambient request credential (HTTP mode only). */
30
+ export function runWithRequestApiKey(apiKey, fn) {
31
+ return storage.run({ apiKey }, fn);
32
+ }
33
+ /** The ambient request credential, or `undefined` outside any HTTP request (e.g. stdio mode). */
34
+ export function currentRequestApiKey() {
35
+ return storage.getStore()?.apiKey;
36
+ }
@@ -0,0 +1,10 @@
1
+ import { readFileSync } from "node:fs";
2
+ // Copied from the API's canonical asset at build/pack time. The same relative
3
+ // lookup also works in the existing plugin bundle (server/lib/).
4
+ export const OPERATING_CONTRACT = readFileSync(new URL("./agent-operating-contract.txt", import.meta.url), "utf8");
5
+ export const MCP_INSTRUCTIONS = OPERATING_CONTRACT + "\n\nMCP CONNECTION\n--------------\n" +
6
+ "Use the advertised MCP tools for the operations they expose. They supply authentication and " +
7
+ "idempotency headers internally; never pass credentials in tool arguments. " +
8
+ "{{BASE_URL}} denotes the configured AgentMesh API base URL. " +
9
+ "The REST route catalog above is broader than the MCP tool list. " +
10
+ "Available tools and scopes are capabilities, not assignments; follow your operator's task.\n";
package/dist/errors.js ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Types and helpers for the AgentMesh upstream error envelope and its
3
+ * mapping onto MCP tool-error text.
4
+ *
5
+ * PLAN §6 "Error mapping": upstream envelope is
6
+ * { error: { code, message, request_id, details? } }
7
+ * (`request_id` INSIDE `error`, not top-level). Closed code -> status set:
8
+ * 400 VALIDATION / WORKSPACE_CONFLICT / SPOOFED_AUTHOR
9
+ * 401 UNAUTHENTICATED
10
+ * 403 FORBIDDEN / EMAIL_UNVERIFIED
11
+ * 404 NOT_FOUND
12
+ * 409 ALREADY_CLAIMED / CARD_STATE_CONFLICT / ASK_STATE_CONFLICT /
13
+ * IDEMPOTENCY_MISMATCH / CHANNEL_ARCHIVED / CHANNEL_EXISTS /
14
+ * VERSION_CONFLICT / CURSOR_EXPIRED
15
+ * 413 PAYLOAD_TOO_LARGE
16
+ * 429 RATE_LIMITED
17
+ * 500 INTERNAL (uncontracted)
18
+ *
19
+ * "500 INTERNAL (uncontracted)" is the spec's own signal that the code
20
+ * space is not exhaustively enumerable at the wire level (an uncontracted
21
+ * 500, or a future code, can legitimately arrive). `code` is therefore
22
+ * parsed as an open `string`, never validated against ERROR_CODES — this
23
+ * module must not throw or drop information just because it sees an
24
+ * unlisted code. ERROR_CODES is exported for documentation / exhaustive
25
+ * `switch` use by callers who want it, not as a runtime allowlist.
26
+ */
27
+ /** The closed CODE set documented in PLAN §6, for reference / exhaustive-switch use. */
28
+ export const ERROR_CODES = [
29
+ // 400
30
+ "VALIDATION",
31
+ "WORKSPACE_CONFLICT",
32
+ "SPOOFED_AUTHOR",
33
+ // 401
34
+ "UNAUTHENTICATED",
35
+ // 403
36
+ "FORBIDDEN",
37
+ "EMAIL_UNVERIFIED",
38
+ // 404
39
+ "NOT_FOUND",
40
+ // 409
41
+ "ALREADY_CLAIMED",
42
+ "CARD_STATE_CONFLICT",
43
+ "ASK_STATE_CONFLICT",
44
+ "IDEMPOTENCY_MISMATCH",
45
+ "CHANNEL_ARCHIVED",
46
+ "CHANNEL_EXISTS",
47
+ "VERSION_CONFLICT",
48
+ "CURSOR_EXPIRED",
49
+ // 413
50
+ "PAYLOAD_TOO_LARGE",
51
+ // 429
52
+ "RATE_LIMITED",
53
+ // 500 (uncontracted)
54
+ "INTERNAL",
55
+ ];
56
+ /**
57
+ * Turn a non-2xx upstream response (status + already-parsed JSON body, or
58
+ * `undefined`/non-object if the body was empty or unparseable) into a
59
+ * normalized `{ code, message, status }`. Never throws.
60
+ *
61
+ * If the body does not conform to the documented envelope shape, falls back
62
+ * to a status-derived code rather than fabricating a plausible-looking but
63
+ * invented upstream code — the fallback codes below are clearly synthesized
64
+ * by THIS client (not asserted as real AgentMesh codes).
65
+ */
66
+ export function errorFromResponse(status, body) {
67
+ const envelope = extractEnvelope(body);
68
+ if (envelope !== null) {
69
+ return { code: envelope.code, message: envelope.message, status };
70
+ }
71
+ return {
72
+ code: fallbackCodeForStatus(status),
73
+ message: `AgentMesh returned HTTP ${status} with a non-conforming error body.`,
74
+ status,
75
+ };
76
+ }
77
+ function extractEnvelope(body) {
78
+ if (typeof body !== "object" || body === null || !("error" in body)) {
79
+ return null;
80
+ }
81
+ const errorField = body.error;
82
+ if (typeof errorField !== "object" || errorField === null) {
83
+ return null;
84
+ }
85
+ const record = errorField;
86
+ const code = record["code"];
87
+ const message = record["message"];
88
+ if (typeof code !== "string" || typeof message !== "string") {
89
+ return null;
90
+ }
91
+ return { code, message };
92
+ }
93
+ /** Status-derived fallback code, used only when the response body doesn't match the envelope. */
94
+ function fallbackCodeForStatus(status) {
95
+ switch (status) {
96
+ case 400:
97
+ return "VALIDATION";
98
+ case 401:
99
+ return "UNAUTHENTICATED";
100
+ case 403:
101
+ return "FORBIDDEN";
102
+ case 404:
103
+ return "NOT_FOUND";
104
+ case 409:
105
+ return "CONFLICT";
106
+ case 413:
107
+ return "PAYLOAD_TOO_LARGE";
108
+ case 429:
109
+ return "RATE_LIMITED";
110
+ default:
111
+ return status >= 500 ? "INTERNAL" : "UNKNOWN_ERROR";
112
+ }
113
+ }
114
+ /** Format a tool error's content text per PLAN §3 / §9 (C-series): `"<CODE>: <message>"`. */
115
+ export function formatToolErrorText(err) {
116
+ return `${err.code}: ${err.message}`;
117
+ }