@nanobpm/urban 0.84.0 → 0.86.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.
@@ -0,0 +1,994 @@
1
+ // mcp — the runtime-served Model Context Protocol surface (ADR 0067). A Streamable-HTTP MCP
2
+ // endpoint the Urban runtime mounts UNCONDITIONALLY at `/app/mcp` (it answers `POST`, plus `DELETE`
3
+ // to end a session; the optional `GET` server→client stream is declined with 405 at the string-body
4
+ // host seam), exactly like the `/app/agent` brief and `/app/api-docs` docs surfaces — so an MCP
5
+ // client (`copilot mcp add
6
+ // --transport http <name> http://localhost:<port>/app/mcp`) discovers an app's operations as
7
+ // tools with ZERO app-side MCP code.
8
+ //
9
+ // Derive-don't-declare (ADR 0053): the app tool list is PROJECTED from the SAME OpenAPI
10
+ // enumeration `mountApi` routes from — `parseSpec` + `collectOperations` (openapi/spec.ts), read
11
+ // through `readApiBinding` — never a second spec walker. Each projected operation becomes one tool
12
+ // whose `operationId` is the tool name and whose request-body/params schema is the tool input
13
+ // schema; a tool call is reconstructed into the operation's HTTP request and dispatched through the
14
+ // SAME `mountApi` router, so it flows through the identical delegate registry + validation the HTTP
15
+ // route uses (a tool call is equivalent to the corresponding HTTP call).
16
+ //
17
+ // This module (ADR 0067) exposes app operations as MCP tools — each authorized exactly as its own
18
+ // HTTP route by the operation's OpenAPI `security` (a read or mutating op with no `security` is
19
+ // open; there is NO extra MCP-level shared-secret guard on app operations). An operation opts out
20
+ // of projection with the `x-mcp` extension. It also exposes framework-owned process-debugging tools
21
+ // over BOTH truth planes: engine truth via existing `EngineClient` methods (reads, plus mutating
22
+ // unstick tools — cancel/resolve/retry/set-variables, which ARE guarded by the app's shared secret
23
+ // or the `mcp.allowMutations` opt-in), and the ADR 0065 canonical projection stores
24
+ // (`urban_instance_state` / `urban_open_user_tasks`).
25
+ // The app's system brief (`/app/agent.json`) is served as an MCP resource, plus one orientation
26
+ // entry under MCP prompts.
27
+ //
28
+ // Transport: the SDK's Web-Standard Streamable-HTTP transport (`Request`→`Response`), bridged to
29
+ // the runtime's host `HttpRequest`/`HttpResponse` seam — core/ imports no `node:*`; the MCP SDK is
30
+ // an ordinary dependency. Access is loopback-only behind a manifest/env flag that defaults ON for
31
+ // loopback.
32
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
33
+ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
34
+ import { CallToolRequestSchema, ErrorCode, GetPromptRequestSchema, isInitializeRequest, ListPromptsRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
35
+ import { GENERATED_DIR } from "../../../toolkit/artifact.js";
36
+ import { SYSTEM_BRIEF_JSON } from "../../../toolkit/derivers/system-brief.js";
37
+ import { collectOperations, evaluateSecurity, isMutatingMethod, parseSpec, sharedSecretSchemeName, } from "../../../openapi/spec.js";
38
+ import { errorMessage } from "../guards.js";
39
+ import { presentFormIdentifier } from "../host.js";
40
+ import { resolveBindMode } from "../manifest.js";
41
+ import { json, makeRouter } from "../router.js";
42
+ import { API_BASE, readApiBinding } from "./api.js";
43
+ import { resolveAppPath } from "./datasource.js";
44
+ import { InstanceStateStore } from "./instance-state-store.js";
45
+ import { OpenUserTasksStore } from "./open-user-tasks-store.js";
46
+ /** The mount path of the MCP endpoint — a sibling of `/app/api` / `/app/agent`, mounted
47
+ * unconditionally so an MCP client always has a stable address to connect to. */
48
+ const MCP_PATH = "/app/mcp";
49
+ /** The header carrying the Streamable-HTTP session id (MCP spec). */
50
+ const SESSION_HEADER = "mcp-session-id";
51
+ /** Hard upper bound on concurrently-resident MCP sessions. Each session is a live `Server` +
52
+ * transport pair, so an unbounded session map is a memory/handle-exhaustion vector: any local
53
+ * process can repeatedly `initialize` without reusing its `mcp-session-id` and pin a fresh pair
54
+ * each time. Capping the map (LRU-evicted, refreshed on use — see `evictExcessSessions` /
55
+ * `touchSession`) categorically bounds growth regardless of client behaviour or timing. */
56
+ const MAX_SESSIONS = 256;
57
+ /** The MCP resource URI for the app's system brief (the `/app/agent.json` content). */
58
+ const SYSTEM_BRIEF_URI = "urban://system-brief.json";
59
+ /** The single orientation prompt registered under MCP `prompts`. */
60
+ const ORIENTATION_PROMPT = "urban-orientation";
61
+ /** The framework debug-tool name prefix — a reserved namespace. `loadReadOnlyOps` drops any app
62
+ * `operationId` in this namespace before it is projected as a tool, so a framework tool can never
63
+ * collide with (be shadowed by, or duplicate the name of) an app-projected tool. */
64
+ const DEBUG_PREFIX = "urban_debug_";
65
+ /** Mint a fresh MCP session id, host-agnostically. Prefers the Web Crypto `randomUUID` (a global,
66
+ * not `node:crypto`) where present, with a time+random fallback so a host without `crypto` never
67
+ * throws — mirroring how core treats Web Crypto as optional (see `mintRootRequestKey`). */
68
+ export function newSessionId() {
69
+ const uuid = globalThis.crypto?.randomUUID?.();
70
+ if (uuid)
71
+ return uuid;
72
+ return `sess-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
73
+ }
74
+ /** Mark a session as most-recently-used. A `Map` preserves insertion order, so deleting and
75
+ * re-inserting a live entry moves it to the tail — which makes the first key the least-recently-used
76
+ * entry that `evictExcessSessions` reaps first. Refreshing on every use is what keeps an active
77
+ * session from being evicted out from under a client that is still talking to it. */
78
+ function touchSession(sessions, id, session) {
79
+ sessions.delete(id);
80
+ sessions.set(id, session);
81
+ }
82
+ /** Bound the live-session map to `max` by evicting least-recently-used entries (the `Map`'s leading
83
+ * keys, given `touchSession` re-inserts on use), closing each victim best-effort so its transport /
84
+ * server releases. This is the categorical fix for the unbounded-growth vector: no client can pin
85
+ * more than `max` server/transport pairs, whatever its `initialize` cadence. Exported for a direct
86
+ * unit test of the LRU eviction contract. */
87
+ export async function evictExcessSessions(sessions, max, close) {
88
+ while (sessions.size > max) {
89
+ const oldest = sessions.keys().next().value;
90
+ if (oldest === undefined)
91
+ break;
92
+ const victim = sessions.get(oldest);
93
+ sessions.delete(oldest);
94
+ if (victim !== undefined) {
95
+ try {
96
+ await close(victim);
97
+ }
98
+ catch {
99
+ // Best-effort: a victim whose transport is already torn down must not abort eviction.
100
+ }
101
+ }
102
+ }
103
+ }
104
+ function isRecord(v) {
105
+ return typeof v === "object" && v !== null && !Array.isArray(v);
106
+ }
107
+ /**
108
+ * Resolve the MCP access policy from the manifest
109
+ * (`mcp: { enabled?, allowRemote?, allowMutations? }`, read reflectively until the app schema folds
110
+ * the field in — mirroring how `readApiBinding` reads `api`) and the environment
111
+ * (`URBAN_MCP_ENABLED`, `URBAN_MCP_ALLOW_REMOTE`, `URBAN_MCP_ALLOW_MUTATIONS`). The env flags win so
112
+ * an operator can force the surface off (or open it to a non-loopback bind, or enable mutating
113
+ * tools) without editing the manifest. Enabled defaults ON and access defaults to loopback-only
114
+ * ("defaults ON for loopback"); `allowMutations` defaults OFF (mutating tools stay closed).
115
+ */
116
+ export function readMcpConfig(manifest, env) {
117
+ const raw = manifest && typeof manifest === "object" ? Reflect.get(manifest, "mcp") : undefined;
118
+ // Honour manifest flags only when they are actual booleans (mirroring `readApiBinding`'s strict
119
+ // type checks), so a stray non-boolean value falls back to the default instead of coercing
120
+ // surprisingly (e.g. the string `"false"` is not a boolean `false`).
121
+ const rawEnabled = isRecord(raw) ? Reflect.get(raw, "enabled") : undefined;
122
+ const rawAllowRemote = isRecord(raw) ? Reflect.get(raw, "allowRemote") : undefined;
123
+ const rawAllowMutations = isRecord(raw) ? Reflect.get(raw, "allowMutations") : undefined;
124
+ const manifestEnabled = typeof rawEnabled === "boolean" ? rawEnabled : undefined;
125
+ const manifestAllowRemote = typeof rawAllowRemote === "boolean" ? rawAllowRemote : undefined;
126
+ const manifestAllowMutations = typeof rawAllowMutations === "boolean" ? rawAllowMutations : undefined;
127
+ const envEnabled = env("URBAN_MCP_ENABLED");
128
+ const envAllowRemote = env("URBAN_MCP_ALLOW_REMOTE");
129
+ const envAllowMutations = env("URBAN_MCP_ALLOW_MUTATIONS");
130
+ const enabled = envEnabled === "false" ? false : envEnabled === "true" ? true : manifestEnabled !== false;
131
+ const allowRemote = envAllowRemote === "true" ? true : envAllowRemote === "false" ? false : manifestAllowRemote === true;
132
+ const allowMutations = envAllowMutations === "true" ? true : envAllowMutations === "false" ? false : manifestAllowMutations === true;
133
+ return { enabled, allowRemote, allowMutations };
134
+ }
135
+ /** The host portion of an HTTP `Host` header, lower-cased and stripped of any `:port` (and of the
136
+ * `[...]` brackets around an IPv6 literal), or `undefined` when there is no Host header. */
137
+ function hostName(req) {
138
+ const host = req.headers.get("host");
139
+ if (!host)
140
+ return undefined;
141
+ const trimmed = host.trim().toLowerCase();
142
+ if (trimmed.startsWith("[")) {
143
+ const end = trimmed.indexOf("]");
144
+ return end > 0 ? trimmed.slice(1, end) : trimmed.slice(1);
145
+ }
146
+ const colon = trimmed.indexOf(":");
147
+ return colon >= 0 ? trimmed.slice(0, colon) : trimmed;
148
+ }
149
+ /** Whether the request targets a loopback host — the best-effort loopback signal available at the
150
+ * host seam (which carries no peer address). A missing Host header is treated as loopback (a direct
151
+ * local client that sent none). */
152
+ export function isLoopbackRequest(req) {
153
+ const name = hostName(req);
154
+ return name === undefined || name === "localhost" || name === "127.0.0.1" || name === "::1";
155
+ }
156
+ /** Read a header value from the SDK's per-request `requestInfo.headers` map (lower-cased keys,
157
+ * values `string | string[] | undefined`). A repeated header (`string[]`, as Node's raw adapter
158
+ * surfaces it) is comma-joined to MATCH `Headers.get()` semantics — the same read `mountApi` and
159
+ * the reconstructed `toHttpRequest` use for OpenAPI route enforcement — so the shared-secret guard
160
+ * cannot diverge from route enforcement on a repeated credential header. Returns `undefined` when
161
+ * absent. Used to read the shared-secret credential the client presents on the MCP connection for a
162
+ * mutating tool call. */
163
+ export function readHeader(headers, name) {
164
+ const value = headers[name.toLowerCase()];
165
+ if (Array.isArray(value))
166
+ return value.join(", ");
167
+ return value;
168
+ }
169
+ /** A minimal read of the `x-mcp` extension for a projected operation is done at parse time
170
+ * (`OperationInfo.mcpExcluded`); here we only need the mutation classification, shared with the CI
171
+ * parity guard via {@link isMutatingMethod}. Kept as a named predicate for readability at the call
172
+ * sites (tool annotations + guard). */
173
+ function isMutatingOperation(op) {
174
+ return isMutatingMethod(op.method);
175
+ }
176
+ /** A JSON Schema (OpenAPI object subset) describing a tool's input, derived from an operation's
177
+ * path/query parameters and its request-body schema. Keeping the property schemas verbatim from the
178
+ * spec means the tool input schema and the HTTP validation share one source of truth. */
179
+ function toolInputSchema(op) {
180
+ const properties = {};
181
+ const required = [];
182
+ for (const p of op.parameters) {
183
+ if (p.in === "path" || p.in === "query") {
184
+ properties[p.name] = p.schema ?? {};
185
+ if (p.required)
186
+ required.push(p.name);
187
+ }
188
+ }
189
+ if (op.requestBodySchema) {
190
+ properties.body = op.requestBodySchema;
191
+ if (op.requestBodyRequired)
192
+ required.push("body");
193
+ }
194
+ const schema = { type: "object", properties };
195
+ if (required.length > 0)
196
+ schema.required = required;
197
+ return schema;
198
+ }
199
+ /** Substitute an operation's `{param}` path-template segments with the supplied arguments, building
200
+ * the request path under the shared `/app/api` base so dispatch hits the exact `mountApi` route. */
201
+ function fillPath(op, args) {
202
+ const path = op.path.replace(/\{([^}]+)\}/g, (_m, name) => {
203
+ const value = args[name];
204
+ return encodeURIComponent(value === undefined || value === null ? "" : String(value));
205
+ });
206
+ return `${API_BASE}${path}`;
207
+ }
208
+ /** Build the query string for a tool call from the operation's declared query parameters and the
209
+ * supplied arguments — repeated (array) values become repeated keys, exactly as an HTTP client
210
+ * would send them, so the reused dispatcher validates identical input. */
211
+ function toolQuery(op, args) {
212
+ const query = new URLSearchParams();
213
+ for (const p of op.parameters) {
214
+ if (p.in !== "query")
215
+ continue;
216
+ const value = args[p.name];
217
+ if (value === undefined || value === null)
218
+ continue;
219
+ if (Array.isArray(value)) {
220
+ for (const item of value)
221
+ query.append(p.name, String(item));
222
+ }
223
+ else {
224
+ query.append(p.name, String(value));
225
+ }
226
+ }
227
+ return query;
228
+ }
229
+ /** Whether an argument is absent for presence purposes: unset (`undefined`/`null`), or a string that
230
+ * is empty or whitespace-only after trimming. This is the trimmed-presence rule
231
+ * {@link presentFormIdentifier} enforces for form identifiers, reused here so MCP required/path args
232
+ * and form resolution cannot drift on what "provided" means (a whitespace-only `" "` is absent in
233
+ * both). A non-string value (e.g. a numeric path id) is considered present. */
234
+ function isBlankArg(value) {
235
+ if (value === undefined || value === null)
236
+ return true;
237
+ if (typeof value === "string")
238
+ return presentFormIdentifier(value) === undefined;
239
+ return false;
240
+ }
241
+ /** The required path parameters an operation declares that the tool `args` did not supply. Unlike
242
+ * an HTTP request (whose path can't structurally omit a segment), a tool call can leave a
243
+ * `{param}` unset or blank; `fillPath` would then substitute an empty string and silently mis-route
244
+ * (a 404 route mismatch, or worse a different route shape), so a missing/blank path arg is rejected
245
+ * up front. Blankness uses the shared trimmed-presence rule so a whitespace-only value is rejected
246
+ * too. */
247
+ function missingPathParams(op, args) {
248
+ return op.parameters
249
+ .filter((p) => p.in === "path" && isBlankArg(args[p.name]))
250
+ .map((p) => p.name);
251
+ }
252
+ /** The `required` keys a tool's `inputSchema` declares but the call omitted. Presence is decided
253
+ * solely by {@link isBlankArg} — the single source of truth also used for path args — so a value is
254
+ * "provided" unless it is absent (`undefined`/`null`) or a blank/whitespace-only string. A required
255
+ * non-string input (e.g. a numeric/boolean/object arg) that is present is therefore accepted, not
256
+ * wrongly reported missing. Derived from the schema's own `required` array so declaring a field
257
+ * required is enough to have missing (or whitespace-only) calls rejected rather than silently
258
+ * substituted with an empty string. */
259
+ export function missingRequiredArgs(inputSchema, args) {
260
+ const required = inputSchema.required;
261
+ if (!Array.isArray(required))
262
+ return [];
263
+ const missing = [];
264
+ for (const key of required) {
265
+ if (typeof key !== "string")
266
+ continue;
267
+ if (isBlankArg(args[key]))
268
+ missing.push(key);
269
+ }
270
+ return missing;
271
+ }
272
+ /** Reconstruct the HTTP request an operation tool call is equivalent to, ready to hand to the
273
+ * reused `mountApi` router. The JSON body is the tool's `body` argument (when the op declares one).
274
+ * The MCP connection's request headers are FORWARDED (with `content-type` pinned to JSON) so the
275
+ * reused router's `evaluateSecurity` sees the client's credential: a mutating (or a secured
276
+ * read-only) app operation is then guarded exactly as its HTTP route is — the app operation tools
277
+ * inherit the OpenAPI `security` contract rather than a bespoke MCP gate (ADR 0067 §4). */
278
+ function toHttpRequest(op, args, forwardHeaders) {
279
+ const bodyText = op.requestBodySchema !== undefined && args.body !== undefined
280
+ ? JSON.stringify(args.body)
281
+ : "";
282
+ const headers = new Headers();
283
+ for (const [key, value] of Object.entries(forwardHeaders)) {
284
+ if (typeof value === "string")
285
+ headers.set(key, value);
286
+ else if (Array.isArray(value))
287
+ for (const v of value)
288
+ headers.append(key, v);
289
+ }
290
+ headers.set("content-type", "application/json");
291
+ return {
292
+ method: op.method.toUpperCase(),
293
+ path: fillPath(op, args),
294
+ query: toolQuery(op, args),
295
+ headers,
296
+ text: () => Promise.resolve(bodyText),
297
+ };
298
+ }
299
+ /** Wrap a value as an MCP tool text result. A JSON payload is stringified; `isError` flags a
300
+ * non-2xx dispatch so the client sees the failure (carrying the delegate's own error body). */
301
+ function textResult(value, isError = false) {
302
+ const text = typeof value === "string" ? value : JSON.stringify(value ?? null);
303
+ return isError ? { content: [{ type: "text", text }], isError: true } : { content: [{ type: "text", text }] };
304
+ }
305
+ function readString(args, key) {
306
+ const v = args[key];
307
+ return typeof v === "string" ? v : undefined;
308
+ }
309
+ /** Read an OPTIONAL string argument in its TRIMMED present form, or `undefined` when it is missing,
310
+ * non-string, or blank/whitespace-only. The canonical read for identifying keys and filter values
311
+ * (processInstanceKey/elementId/assignee/candidateGroup): it applies the SAME
312
+ * {@link presentFormIdentifier} trimmed-presence rule that `missingRequiredArgs`/{@link isBlankArg}
313
+ * use for presence, so a padded value like `" pi-1 "` normalizes to `"pi-1"` instead of reaching
314
+ * the engine untrimmed — where a filter would silently match nothing and a keyed lookup would target
315
+ * a whitespace-padded entity that does not exist. The single source of truth {@link requireString}
316
+ * also derives from, so required and optional reads cannot drift on how they normalize. */
317
+ function readPresentString(args, key) {
318
+ return presentFormIdentifier(readString(args, key));
319
+ }
320
+ /** Read a REQUIRED non-empty string argument, TRIMMED, or throw `InvalidParams`. The canonical guard
321
+ * the mutating debug tools use for their identifying keys (processInstanceKey/incidentKey/jobKey/
322
+ * scopeKey): a missing, non-string, or blank value fails fast before any engine state is touched,
323
+ * rather than silently degrading to `""` and performing a broken/misleading mutation. Derived from
324
+ * {@link readPresentString} — the same trimmed-presence rule {@link isBlankArg} (hence
325
+ * `missingRequiredArgs`) uses — so a padded key like `" pi-1 "` cannot pass the required-arg check
326
+ * yet reach the engine untrimmed and mis-target the entity. */
327
+ function requireString(args, key) {
328
+ const present = readPresentString(args, key);
329
+ if (present === undefined)
330
+ throw new McpError(ErrorCode.InvalidParams, `${key} must be a non-empty string`);
331
+ return present;
332
+ }
333
+ function readStringArray(args, key) {
334
+ const v = args[key];
335
+ if (!Array.isArray(v))
336
+ return undefined;
337
+ const out = [];
338
+ for (const item of v)
339
+ if (typeof item === "string")
340
+ out.push(item);
341
+ return out;
342
+ }
343
+ function readProcessInstanceState(args, key) {
344
+ const v = args[key];
345
+ return v === "ACTIVE" || v === "COMPLETED" || v === "TERMINATED" ? v : undefined;
346
+ }
347
+ function readUserTaskState(args, key) {
348
+ const v = args[key];
349
+ return v === "CREATED" || v === "COMPLETED" || v === "CANCELED" || v === "FAILED" ? v : undefined;
350
+ }
351
+ function readWaitStateType(args, key) {
352
+ const v = args[key];
353
+ return v === "JOB" || v === "MESSAGE" || v === "USER_TASK" || v === "TIMER" || v === "SIGNAL" || v === "CONDITION"
354
+ ? v
355
+ : undefined;
356
+ }
357
+ /** Narrow an argument to a real engine incident state — the `"UNKNOWN"` client-side sentinel is
358
+ * deliberately NOT a selector (see `IncidentState`/`IncidentFilter`), so it is rejected here. */
359
+ function readIncidentState(args, key) {
360
+ const v = args[key];
361
+ return v === "ACTIVE" || v === "MIGRATED" || v === "PENDING" || v === "RESOLVED" ? v : undefined;
362
+ }
363
+ /** Read a plain JSON object argument (an MCP `object` input), else `undefined`. Used for the
364
+ * `set_variables` payload — an arbitrary variable map handed to the engine verbatim. */
365
+ function readObject(args, key) {
366
+ const v = args[key];
367
+ return isRecord(v) ? v : undefined;
368
+ }
369
+ /** Read a finite integer argument (for a job's retry count), else `undefined`. */
370
+ function readInteger(args, key) {
371
+ const v = args[key];
372
+ return typeof v === "number" && Number.isInteger(v) ? v : undefined;
373
+ }
374
+ const OPTIONAL_STRING = { type: "string" };
375
+ /** Build the framework debug tools, closing over the app's engine (truth plane) and default data
376
+ * source (the ADR 0065 projection stores). READ tools consume the engine's read accessors and the
377
+ * projection stores; MUTATING tools (ADR 0067 Slice 3, gated by the shared-secret guard) drive the
378
+ * Slice 2 seam extension — cancel an instance, resolve/retry an incident, set variables. */
379
+ function buildDebugTools(app) {
380
+ const projectionDb = () => app.data.hasDefaultSource() ? app.data.source().db : undefined;
381
+ return [
382
+ {
383
+ name: `${DEBUG_PREFIX}search_process_instances`,
384
+ description: "Engine truth: search process instances by key and/or lifecycle state.",
385
+ inputSchema: {
386
+ type: "object",
387
+ properties: {
388
+ processInstanceKeys: { type: "array", items: OPTIONAL_STRING },
389
+ state: { type: "string", enum: ["ACTIVE", "COMPLETED", "TERMINATED"] },
390
+ },
391
+ },
392
+ run: (args) => {
393
+ const filter = {};
394
+ const keys = readStringArray(args, "processInstanceKeys");
395
+ if (keys)
396
+ filter.processInstanceKeys = keys;
397
+ const state = readProcessInstanceState(args, "state");
398
+ if (state)
399
+ filter.state = state;
400
+ return app.engine.searchProcessInstances(filter);
401
+ },
402
+ },
403
+ {
404
+ name: `${DEBUG_PREFIX}search_element_instance_wait_states`,
405
+ description: "Engine truth: search element-instance wait states (every park, not only user tasks).",
406
+ inputSchema: {
407
+ type: "object",
408
+ properties: {
409
+ processInstanceKey: OPTIONAL_STRING,
410
+ elementId: OPTIONAL_STRING,
411
+ waitStateType: {
412
+ type: "string",
413
+ enum: ["JOB", "MESSAGE", "USER_TASK", "TIMER", "SIGNAL", "CONDITION"],
414
+ },
415
+ },
416
+ },
417
+ run: (args) => {
418
+ const filter = {};
419
+ const pik = readPresentString(args, "processInstanceKey");
420
+ if (pik)
421
+ filter.processInstanceKey = pik;
422
+ const elementId = readPresentString(args, "elementId");
423
+ if (elementId)
424
+ filter.elementId = elementId;
425
+ const waitStateType = readWaitStateType(args, "waitStateType");
426
+ if (waitStateType)
427
+ filter.waitStateType = waitStateType;
428
+ return app.engine.searchElementInstanceWaitStates(filter);
429
+ },
430
+ },
431
+ {
432
+ name: `${DEBUG_PREFIX}get_element_instance`,
433
+ description: "Engine truth: fetch a single element instance by key (null when absent).",
434
+ inputSchema: {
435
+ type: "object",
436
+ properties: { elementInstanceKey: OPTIONAL_STRING },
437
+ required: ["elementInstanceKey"],
438
+ },
439
+ run: (args) => app.engine.getElementInstance(requireString(args, "elementInstanceKey")),
440
+ },
441
+ {
442
+ name: `${DEBUG_PREFIX}search_user_tasks`,
443
+ description: "Engine truth: search user tasks by process instance, assignee, candidate group, and/or state.",
444
+ inputSchema: {
445
+ type: "object",
446
+ properties: {
447
+ processInstanceKey: OPTIONAL_STRING,
448
+ assignee: OPTIONAL_STRING,
449
+ candidateGroup: OPTIONAL_STRING,
450
+ state: { type: "string", enum: ["CREATED", "COMPLETED", "CANCELED", "FAILED"] },
451
+ },
452
+ },
453
+ run: (args) => {
454
+ const filter = {};
455
+ const pik = readPresentString(args, "processInstanceKey");
456
+ if (pik)
457
+ filter.processInstanceKey = pik;
458
+ const assignee = readPresentString(args, "assignee");
459
+ if (assignee)
460
+ filter.assignee = assignee;
461
+ const candidateGroup = readPresentString(args, "candidateGroup");
462
+ if (candidateGroup)
463
+ filter.candidateGroup = candidateGroup;
464
+ const state = readUserTaskState(args, "state");
465
+ if (state)
466
+ filter.state = state;
467
+ return app.engine.searchUserTasks(filter);
468
+ },
469
+ },
470
+ {
471
+ name: `${DEBUG_PREFIX}search_incidents`,
472
+ description: "Engine truth: search incidents (stuck tokens — a job out of retries, an unhandled error, a failed gateway) by process instance and/or state. Read-only; each result carries the incidentKey/jobKey the mutating unstick tools take.",
473
+ inputSchema: {
474
+ type: "object",
475
+ properties: {
476
+ processInstanceKey: OPTIONAL_STRING,
477
+ state: { type: "string", enum: ["ACTIVE", "MIGRATED", "PENDING", "RESOLVED"] },
478
+ },
479
+ },
480
+ run: (args) => {
481
+ const filter = {};
482
+ const pik = readPresentString(args, "processInstanceKey");
483
+ if (pik)
484
+ filter.processInstanceKey = pik;
485
+ const state = readIncidentState(args, "state");
486
+ if (state)
487
+ filter.state = state;
488
+ return app.engine.searchIncidents(filter);
489
+ },
490
+ },
491
+ {
492
+ name: `${DEBUG_PREFIX}cancel_instance`,
493
+ description: "MUTATING: cancel a running process instance. Requires the shared-secret guard.",
494
+ mutating: true,
495
+ inputSchema: {
496
+ type: "object",
497
+ properties: { processInstanceKey: OPTIONAL_STRING },
498
+ required: ["processInstanceKey"],
499
+ },
500
+ run: async (args) => {
501
+ const processInstanceKey = requireString(args, "processInstanceKey");
502
+ await app.engine.cancelInstance({ processInstanceKey });
503
+ return { cancelled: processInstanceKey };
504
+ },
505
+ },
506
+ {
507
+ name: `${DEBUG_PREFIX}resolve_incident`,
508
+ description: "MUTATING: resolve an open incident by key, unblocking the parked token (bump the job's retries first for a jobNoRetries incident — see retry_job). Requires the shared-secret guard.",
509
+ mutating: true,
510
+ inputSchema: {
511
+ type: "object",
512
+ properties: { incidentKey: OPTIONAL_STRING },
513
+ required: ["incidentKey"],
514
+ },
515
+ run: async (args) => {
516
+ const incidentKey = requireString(args, "incidentKey");
517
+ await app.engine.resolveIncident({ incidentKey });
518
+ return { resolved: incidentKey };
519
+ },
520
+ },
521
+ {
522
+ name: `${DEBUG_PREFIX}retry_job`,
523
+ description: "MUTATING: set a failed job's remaining retries (making it activatable again — the 'retry' half of unsticking a jobNoRetries incident). Requires the shared-secret guard.",
524
+ mutating: true,
525
+ inputSchema: {
526
+ type: "object",
527
+ properties: { jobKey: OPTIONAL_STRING, retries: { type: "integer", minimum: 0 } },
528
+ required: ["jobKey", "retries"],
529
+ },
530
+ run: async (args) => {
531
+ const jobKey = requireString(args, "jobKey");
532
+ const retries = readInteger(args, "retries");
533
+ if (retries === undefined || retries < 0)
534
+ throw new McpError(ErrorCode.InvalidParams, "retries must be a non-negative integer");
535
+ await app.engine.updateJobRetries({ jobKey, retries });
536
+ return { jobKey, retries };
537
+ },
538
+ },
539
+ {
540
+ name: `${DEBUG_PREFIX}set_variables`,
541
+ description: "MUTATING: merge variables into a scope (a process-instance or element-instance key); set `local` true to keep them in that local scope. Repairs state before resolving an incident. Requires the shared-secret guard.",
542
+ mutating: true,
543
+ inputSchema: {
544
+ type: "object",
545
+ properties: {
546
+ scopeKey: OPTIONAL_STRING,
547
+ variables: { type: "object" },
548
+ local: { type: "boolean" },
549
+ },
550
+ required: ["scopeKey", "variables"],
551
+ },
552
+ run: async (args) => {
553
+ const scopeKey = requireString(args, "scopeKey");
554
+ const variables = readObject(args, "variables");
555
+ if (variables === undefined)
556
+ throw new McpError(ErrorCode.InvalidParams, "variables must be an object");
557
+ const input = {
558
+ scopeKey,
559
+ variables,
560
+ };
561
+ if (args.local === true)
562
+ input.local = true;
563
+ await app.engine.setVariables(input);
564
+ return { scopeKey, set: Object.keys(variables) };
565
+ },
566
+ },
567
+ {
568
+ name: `${DEBUG_PREFIX}instance_state`,
569
+ description: "Projection (urban_instance_state, ADR 0065): the canonical engine-lifecycle state for an instance.",
570
+ inputSchema: {
571
+ type: "object",
572
+ properties: { processInstanceKey: OPTIONAL_STRING },
573
+ required: ["processInstanceKey"],
574
+ },
575
+ run: (args) => {
576
+ const key = requireString(args, "processInstanceKey");
577
+ const db = projectionDb();
578
+ if (!db)
579
+ return Promise.resolve(null);
580
+ return Promise.resolve(new InstanceStateStore(db).getState(key) ?? null);
581
+ },
582
+ },
583
+ {
584
+ name: `${DEBUG_PREFIX}open_user_tasks`,
585
+ description: "Projection (urban_open_user_tasks, ADR 0065): the currently-open user tasks for an instance.",
586
+ inputSchema: {
587
+ type: "object",
588
+ properties: { processInstanceKey: OPTIONAL_STRING },
589
+ required: ["processInstanceKey"],
590
+ },
591
+ run: (args) => {
592
+ const key = requireString(args, "processInstanceKey");
593
+ const db = projectionDb();
594
+ if (!db)
595
+ return Promise.resolve([]);
596
+ return Promise.resolve(new OpenUserTasksStore(db).openTasks(key));
597
+ },
598
+ },
599
+ ];
600
+ }
601
+ /**
602
+ * Mount the runtime-served MCP surface at `/app/mcp` (ADR 0067). Returns a single `*`-method route
603
+ * (mounted unconditionally, like `/app/agent`); the handler bridges the host request/response seam
604
+ * to the SDK's Web-Standard Streamable-HTTP transport, maintaining one MCP session per
605
+ * `mcp-session-id`. The tool projection reuses the SAME OpenAPI enumeration and dispatch path as
606
+ * `mountApi`, so a tool call is equivalent to the corresponding HTTP call.
607
+ */
608
+ export function mountMcp(ctx, app, apiRoutes) {
609
+ const config = readMcpConfig(ctx.manifest, ctx.host.env);
610
+ // The effective HTTP bind interface. When the app is bound to all interfaces, the
611
+ // client-controlled `Host` header is not a trustworthy loopback signal (a remote caller can send
612
+ // `Host: localhost`), so a loopback-only surface must refuse EVERY caller rather than trust it.
613
+ const bindMode = resolveBindMode(ctx.manifest, ctx.host.env);
614
+ // Reuse the app's OpenAPI dispatch VERBATIM: `mountSurfaces` already built the `/app/api` router
615
+ // (validation + delegate registry) via `mountApi` and hands us its routes here, so tool and HTTP
616
+ // calls share ONE dispatcher instance (no forked dispatcher, no second doc/delegate cache). A tool
617
+ // call is reconstructed into the operation's HTTP request and routed through this same router.
618
+ const apiRouter = makeRouter(apiRoutes);
619
+ let docPromise;
620
+ const loadSpecDoc = () => {
621
+ if (!docPromise) {
622
+ docPromise = (async () => {
623
+ const binding = readApiBinding(ctx.manifest);
624
+ if (!binding)
625
+ return { doc: undefined, failed: false };
626
+ const text = await ctx.host.readTextFile(resolveAppPath(ctx.root, binding.spec));
627
+ return { doc: parseSpec(text) };
628
+ })().catch((e) => {
629
+ docPromise = undefined; // don't cache the failure — let a later request retry
630
+ ctx.host.log("warn", "mcp: failed to load the app OpenAPI spec", { error: errorMessage(e) });
631
+ return { doc: undefined, failed: true };
632
+ });
633
+ }
634
+ return docPromise;
635
+ };
636
+ // The projected app operation table (read AND mutating), derived from the same enumeration
637
+ // `mountApi` routes. `x-mcp`-excluded operations are dropped (the security-relevant opt-out) as
638
+ // are reserved-namespace ids; the read/mutate split is applied at annotation + guard time via
639
+ // `isMutatingOperation`, never a forked walker. Memoized PER parsed spec document (keyed on the
640
+ // cached doc promise `loadSpecDoc` returns): `tools/list` and `tools/call` both hit this on every
641
+ // request, so recomputing `collectOperations` + the reserved-namespace filter (and re-emitting its
642
+ // warn) each time is avoidable overhead and log spam. When the spec fails to load `loadSpecDoc`
643
+ // resets its promise, so the key changes and the projection is recomputed on the retry.
644
+ let projectedOps;
645
+ const loadProjectedOps = () => {
646
+ const docKey = loadSpecDoc();
647
+ if (projectedOps?.docKey !== docKey) {
648
+ const ops = docKey.then(({ doc }) => {
649
+ if (!doc)
650
+ return [];
651
+ const projected = collectOperations(doc).filter((op) => !op.mcpExcluded);
652
+ // The `urban_debug_` namespace is framework-reserved (see DEBUG_PREFIX). A `urban_debug_*`
653
+ // operationId is a legal safe path segment, so an app could declare one — but `CallTool`
654
+ // resolves `debugByName` before app ops, so such an op would be shadowed by the framework
655
+ // tool AND surface a duplicate name in `tools/list`. Drop reserved-namespace app ops here
656
+ // (the single projection source both `tools/list` and `CallTool` read), warning per drop,
657
+ // so the collision is impossible by construction rather than order-dependent.
658
+ return projected.filter((op) => {
659
+ if (op.operationId.startsWith(DEBUG_PREFIX)) {
660
+ ctx.host.log("warn", "mcp: dropped app operation using reserved framework tool namespace", {
661
+ operationId: op.operationId,
662
+ reservedPrefix: DEBUG_PREFIX,
663
+ });
664
+ return false;
665
+ }
666
+ return true;
667
+ });
668
+ });
669
+ projectedOps = { docKey, ops };
670
+ }
671
+ return projectedOps.ops;
672
+ };
673
+ const debugTools = buildDebugTools(app);
674
+ const debugByName = new Map(debugTools.map((t) => [t.name, t]));
675
+ // A minimal `OperationInfo` that requires ONLY the app's shared-secret scheme, so the framework
676
+ // mutating tools reuse `evaluateSecurity` VERBATIM (constant-time compare, misconfig→500, absent
677
+ // credential→401) rather than a bespoke comparison — the same enforcement path an app operation's
678
+ // own `security` takes. It is never routed; only its `security` field is read.
679
+ const sharedSecretOp = (schemeName) => ({
680
+ operationId: "__mcp_mutation_guard__",
681
+ method: "post",
682
+ path: "/__mcp_mutation_guard__",
683
+ parameters: [],
684
+ requestBodyRequired: false,
685
+ responseSchemas: [],
686
+ security: [{ [schemeName]: [] }],
687
+ eject: false,
688
+ mcpExcluded: false,
689
+ });
690
+ // Decide whether a mutating tool call is authorized. Either an explicit runtime opt-in
691
+ // (`mcp.allowMutations` / `URBAN_MCP_ALLOW_MUTATIONS`) opens mutations credential-free — but only
692
+ // LOOPBACK-ONLY (`!allowRemote`), so exposing the surface to non-loopback callers can never
693
+ // silently drop the guard — OR the client presented the app's shared secret (the apiKey header
694
+ // scheme, via `x-nano-secret-env`). With no shared-secret scheme configured and no (in-scope)
695
+ // opt-in, mutations are refused (fail closed).
696
+ const NO_SHARED_SECRET_SCHEME_ERROR = "mutating MCP tools require the app's shared secret (an apiKey header security scheme with x-nano-secret-env), or the explicit mcp.allowMutations opt-in (honoured loopback-only, i.e. when mcp.allowRemote is off)";
697
+ const authorizeMutation = async (headers) => {
698
+ // The credential-free opt-in is loopback-only: with `allowRemote` on, a non-loopback caller
699
+ // could otherwise reach mutating `urban_debug_*` tools with no shared-secret guard at all, which
700
+ // contradicts the "trusted, purely local box" intent. When remote exposure is enabled we ignore
701
+ // the bypass and fall through to require the shared secret.
702
+ if (config.allowMutations && !config.allowRemote)
703
+ return { ok: true };
704
+ const loaded = await loadSpecDoc();
705
+ if (!loaded.doc && loaded.failed) {
706
+ // A broken/unparseable spec is a server misconfiguration (500) — already logged by
707
+ // `loadSpecDoc` — not a missing credential (401): with no parsed spec we cannot even tell
708
+ // whether a shared-secret scheme exists to authorize against, so mirror `mountApi` and surface
709
+ // a 500 (the CallTool handler logs it) rather than a misleading 401.
710
+ return {
711
+ ok: false,
712
+ status: 500,
713
+ error: "mutating MCP tools cannot be authorized: the app OpenAPI spec failed to load (server misconfiguration — see the logged 'mcp: failed to load the app OpenAPI spec' error)",
714
+ };
715
+ }
716
+ // A misconfigured spec — more than one candidate shared-secret scheme, so which one guards
717
+ // mutations would depend on authoring order — is a 500 (see `sharedSecretSchemeName`), not a
718
+ // missing/bad credential. Surface it like the other misconfiguration branches above.
719
+ let schemeName;
720
+ try {
721
+ schemeName = loaded.doc ? sharedSecretSchemeName(loaded.doc) : undefined;
722
+ }
723
+ catch (e) {
724
+ return { ok: false, status: 500, error: errorMessage(e) };
725
+ }
726
+ if (!loaded.doc || !schemeName) {
727
+ return { ok: false, status: 401, error: NO_SHARED_SECRET_SCHEME_ERROR };
728
+ }
729
+ return evaluateSecurity(loaded.doc, sharedSecretOp(schemeName), (name) => readHeader(headers, name), () => undefined, (envVar) => ctx.host.env(envVar));
730
+ };
731
+ const dispatchOperationTool = async (op, args, headers) => {
732
+ const missing = missingPathParams(op, args);
733
+ if (missing.length > 0) {
734
+ // Surface as an error tool result (like a reused-validator failure), not a silent 404 from an
735
+ // empty-string substitution — the calling agent sees exactly which required params it omitted.
736
+ return textResult({ error: `validation failed: missing required path parameter(s): ${missing.join(", ")}` }, true);
737
+ }
738
+ // Forward the MCP connection's headers so the reused router enforces the operation's own
739
+ // OpenAPI `security` (a mutating — or secured read — app op is guarded exactly as its HTTP
740
+ // route). A `401`/`403`/`500` from that enforcement flows back as an error tool result.
741
+ const res = await apiRouter(toHttpRequest(op, args, headers));
742
+ const status = res.status ?? 200;
743
+ return textResult(res.body ?? "", status >= 400);
744
+ };
745
+ const readSystemBrief = async () => {
746
+ const path = resolveAppPath(ctx.root, `${GENERATED_DIR}/${SYSTEM_BRIEF_JSON}`);
747
+ if (!(await ctx.host.exists(path))) {
748
+ throw new McpError(ErrorCode.InvalidParams, "system brief not generated — run `urban gen`");
749
+ }
750
+ return ctx.host.readTextFile(path);
751
+ };
752
+ const orientationText = () => [
753
+ `# ${ctx.manifest.name ?? "Urban app"} — MCP orientation`,
754
+ "",
755
+ "This endpoint is the app's runtime-served MCP surface (ADR 0067).",
756
+ "",
757
+ `- Read the \`${SYSTEM_BRIEF_URI}\` resource first for the app's system model (processes, service-task call graph, decisions, ownership).`,
758
+ "- App tools mirror the app's HTTP operations one-to-one: a tool call is equivalent to the corresponding `/app/api` HTTP call, validated identically and authorized exactly as that HTTP route by the operation's own OpenAPI `security` (an operation with no `security` is open — there is no extra MCP-level guard). An operation is exposed unless it opts out with the `x-mcp` extension (a security-relevant authoring switch).",
759
+ `- \`${DEBUG_PREFIX}*\` READ tools are framework-owned process-debugging tools: engine truth (process instances, wait states, element instances, user tasks, incidents) and the ADR 0065 projection stores (instance state, open user tasks). They are unauthenticated on loopback.`,
760
+ `- \`${DEBUG_PREFIX}*\` MUTATING tools (cancel_instance, resolve_incident, retry_job, set_variables) are framework-GUARDED: present the app's shared secret as its apiKey header on the MCP connection, or the operator must set the mcp.allowMutations opt-in (honoured loopback-only — when mcp.allowRemote is enabled, mutations always require the shared secret). A mutating call without the credential is refused. (App operation tools are NOT covered by this guard — they are authorized by their own OpenAPI \`security\`, above.)`,
761
+ ].join("\n");
762
+ /** Build a fresh low-level MCP `Server` with this app's tools/resources/prompts wired. One is
763
+ * created per session and connected to that session's transport. */
764
+ const buildServer = () => {
765
+ const server = new Server({ name: "urban", version: "1.0.0" }, { capabilities: { tools: {}, resources: {}, prompts: {} } });
766
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
767
+ const ops = await loadProjectedOps();
768
+ const appTools = ops.map((op) => {
769
+ const mutating = isMutatingOperation(op);
770
+ return {
771
+ name: op.operationId,
772
+ description: op.summary ?? `${op.method.toUpperCase()} ${op.path}`,
773
+ inputSchema: toolInputSchema(op),
774
+ annotations: { readOnlyHint: !mutating, destructiveHint: mutating },
775
+ };
776
+ });
777
+ const frameworkTools = debugTools.map((t) => ({
778
+ name: t.name,
779
+ description: t.description,
780
+ inputSchema: t.inputSchema,
781
+ annotations: { readOnlyHint: !t.mutating, destructiveHint: t.mutating === true },
782
+ }));
783
+ return { tools: [...appTools, ...frameworkTools] };
784
+ });
785
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
786
+ const { name } = request.params;
787
+ const args = isRecord(request.params.arguments) ? request.params.arguments : {};
788
+ // The client presents its shared-secret credential as a header on the MCP connection; the SDK
789
+ // surfaces the request's headers here via `requestInfo`. Empty when a host cannot supply them
790
+ // (then a mutating call falls back to refuse unless the runtime opt-in is set).
791
+ const headers = extra.requestInfo?.headers ?? {};
792
+ const debug = debugByName.get(name);
793
+ if (debug) {
794
+ if (debug.mutating) {
795
+ const authz = await authorizeMutation(headers);
796
+ if (!authz.ok) {
797
+ const status = authz.status ?? 401;
798
+ // Mirror `mountApi`'s security handling: a `500` refusal means the shared-secret scheme
799
+ // is misconfigured (unknown/unsupported scheme, or an unset secret env var) rather than a
800
+ // bad/absent credential. Log it — as `mountApi` does for its OpenAPI security — so an
801
+ // operator can diagnose the misconfiguration, and carry the status in the error payload
802
+ // so a client can distinguish a `500` misconfig from a `401` unauthorized.
803
+ if (status === 500) {
804
+ ctx.host.log("error", "mcp mutating tool security is misconfigured (ADR 0059)", {
805
+ tool: name,
806
+ reason: authz.error,
807
+ });
808
+ }
809
+ return textResult({ error: authz.error ?? "unauthorized", status }, true);
810
+ }
811
+ }
812
+ const missing = missingRequiredArgs(debug.inputSchema, args);
813
+ if (missing.length > 0) {
814
+ // Fail fast like an operation-tool validation error, instead of substituting an empty
815
+ // string that makes an invalid call look like a legitimate "not found" result.
816
+ return textResult({ error: `validation failed: missing required parameter(s): ${missing.join(", ")}` }, true);
817
+ }
818
+ try {
819
+ return textResult(await debug.run(args));
820
+ }
821
+ catch (e) {
822
+ return textResult({ error: errorMessage(e) }, true);
823
+ }
824
+ }
825
+ const ops = await loadProjectedOps();
826
+ const op = ops.find((o) => o.operationId === name);
827
+ if (!op) {
828
+ throw new McpError(ErrorCode.MethodNotFound, `no such tool: ${name}`);
829
+ }
830
+ // App operation tools inherit their OpenAPI `security` — the forwarded headers let the reused
831
+ // router enforce it, so a mutating (or secured read) app op is guarded exactly as its HTTP route.
832
+ return dispatchOperationTool(op, args, headers);
833
+ });
834
+ server.setRequestHandler(ListResourcesRequestSchema, async () => ({
835
+ resources: [
836
+ {
837
+ uri: SYSTEM_BRIEF_URI,
838
+ name: "system-brief",
839
+ title: "App system brief",
840
+ description: "The app's derived institutional-memory brief (the /app/agent.json content).",
841
+ mimeType: "application/json",
842
+ },
843
+ ],
844
+ }));
845
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
846
+ const { uri } = request.params;
847
+ if (uri !== SYSTEM_BRIEF_URI) {
848
+ throw new McpError(ErrorCode.InvalidParams, `no such resource: ${uri}`);
849
+ }
850
+ const text = await readSystemBrief();
851
+ return { contents: [{ uri, mimeType: "application/json", text }] };
852
+ });
853
+ server.setRequestHandler(ListPromptsRequestSchema, async () => ({
854
+ prompts: [
855
+ {
856
+ name: ORIENTATION_PROMPT,
857
+ title: "Orient on this app",
858
+ description: "How to use this app's MCP surface: its read tools, debug tools, and system-brief resource.",
859
+ arguments: [],
860
+ },
861
+ ],
862
+ }));
863
+ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
864
+ if (request.params.name !== ORIENTATION_PROMPT) {
865
+ throw new McpError(ErrorCode.InvalidParams, `no such prompt: ${request.params.name}`);
866
+ }
867
+ return {
868
+ description: "Orientation for working against this app over MCP.",
869
+ messages: [{ role: "user", content: { type: "text", text: orientationText() } }],
870
+ };
871
+ });
872
+ return server;
873
+ };
874
+ const sessions = new Map();
875
+ const createSession = async () => {
876
+ const transport = new WebStandardStreamableHTTPServerTransport({
877
+ sessionIdGenerator: () => newSessionId(),
878
+ enableJsonResponse: true,
879
+ onsessionclosed: (id) => {
880
+ sessions.delete(id);
881
+ },
882
+ });
883
+ transport.onclose = () => {
884
+ if (transport.sessionId)
885
+ sessions.delete(transport.sessionId);
886
+ };
887
+ const server = buildServer();
888
+ await server.connect(transport);
889
+ return { server, transport };
890
+ };
891
+ /** Convert the host request into the Web-Standard `Request` the SDK transport consumes. The body
892
+ * is passed separately (as `parsedBody`) so the transport never re-reads it; the Request carries
893
+ * the method + headers (Accept, content-type, `mcp-session-id`, protocol version) it inspects. */
894
+ const toWebRequest = (req) => {
895
+ const search = req.query.toString();
896
+ const url = `http://localhost${req.path}${search ? `?${search}` : ""}`;
897
+ const headers = new Headers();
898
+ for (const [key, value] of req.headers)
899
+ headers.set(key, value);
900
+ return new Request(url, { method: req.method, headers });
901
+ };
902
+ const toHttpResponse = async (res) => {
903
+ const headers = {};
904
+ for (const [key, value] of res.headers)
905
+ headers[key] = value;
906
+ return { status: res.status, headers, body: await res.text() };
907
+ };
908
+ const methodNotAllowed = () => ({
909
+ status: 405,
910
+ headers: { allow: "POST, DELETE", "content-type": "application/json" },
911
+ body: JSON.stringify({
912
+ jsonrpc: "2.0",
913
+ error: { code: -32000, message: "Method Not Allowed: the MCP endpoint accepts POST (and DELETE to end a session)." },
914
+ id: null,
915
+ }),
916
+ });
917
+ const handle = async (req) => {
918
+ if (!config.enabled)
919
+ return json({ error: "MCP surface is disabled" }, 404);
920
+ if (!config.allowRemote) {
921
+ // Bound to all interfaces, `Host` can't be trusted as a loopback proof: refuse everyone
922
+ // unless remote access is explicitly opted in (mcp.allowRemote / URBAN_MCP_ALLOW_REMOTE).
923
+ if (bindMode === "all") {
924
+ return json({ error: "MCP surface is loopback-only, but the app is bound to all interfaces; set mcp.allowRemote to expose it" }, 403);
925
+ }
926
+ if (!isLoopbackRequest(req)) {
927
+ return json({ error: "MCP surface is loopback-only" }, 403);
928
+ }
929
+ }
930
+ const method = req.method.toUpperCase();
931
+ // The string-body host seam cannot hold open an SSE stream, so the optional GET server→client
932
+ // stream is declined with 405 (spec-compliant): clients fall back to POST request/response.
933
+ if (method !== "POST" && method !== "DELETE")
934
+ return methodNotAllowed();
935
+ const rawBody = method === "POST" ? await req.text() : "";
936
+ let parsedBody;
937
+ if (rawBody) {
938
+ try {
939
+ parsedBody = JSON.parse(rawBody);
940
+ }
941
+ catch {
942
+ return json({ jsonrpc: "2.0", error: { code: ErrorCode.ParseError, message: "request body is not valid JSON" }, id: null }, 400);
943
+ }
944
+ }
945
+ const sessionId = req.headers.get(SESSION_HEADER) ?? undefined;
946
+ let session = sessionId ? sessions.get(sessionId) : undefined;
947
+ // Refresh an existing session's recency so an actively-used session is never the LRU victim.
948
+ if (session && sessionId)
949
+ touchSession(sessions, sessionId, session);
950
+ if (!session) {
951
+ const messages = Array.isArray(parsedBody) ? parsedBody : [parsedBody];
952
+ if (!messages.some((m) => isInitializeRequest(m))) {
953
+ return json({
954
+ jsonrpc: "2.0",
955
+ error: { code: -32000, message: "Bad Request: no valid session id, and not an initialize request." },
956
+ id: null,
957
+ }, 400);
958
+ }
959
+ session = await createSession();
960
+ }
961
+ const webResponse = await session.transport.handleRequest(toWebRequest(req), { parsedBody });
962
+ // A newly-initialized session assigns its id during handleRequest — register it so the client's
963
+ // follow-up requests (carrying `mcp-session-id`) resolve back to this same server/transport.
964
+ const assignedId = session.transport.sessionId;
965
+ if (assignedId && !sessions.has(assignedId)) {
966
+ sessions.set(assignedId, session);
967
+ // Enforce the hard cap once the freshly-initialized session is registered, evicting the
968
+ // least-recently-used pairs (never this one — it is now the newest) so the map stays bounded.
969
+ await evictExcessSessions(sessions, MAX_SESSIONS, (s) => s.server.close());
970
+ }
971
+ return toHttpResponse(webResponse);
972
+ };
973
+ const routes = [
974
+ { method: "*", path: MCP_PATH, source: "surface:mcp", handler: handle },
975
+ ];
976
+ ctx.host.log("info", "mcp surface mounted", {
977
+ path: MCP_PATH,
978
+ enabled: config.enabled,
979
+ loopbackOnly: !config.allowRemote,
980
+ });
981
+ return {
982
+ name: "mcp",
983
+ routes,
984
+ enabled: config.enabled,
985
+ describe: () => ({
986
+ mcp: {
987
+ path: MCP_PATH,
988
+ enabled: config.enabled,
989
+ loopbackOnly: !config.allowRemote,
990
+ allowMutations: config.allowMutations,
991
+ },
992
+ }),
993
+ };
994
+ }