@nanobpm/urban 0.84.0 → 0.85.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/runtime/core/modules/api.d.ts +5 -0
- package/dist/runtime/core/modules/api.js +2 -2
- package/dist/runtime/core/modules/mcp.d.ts +57 -0
- package/dist/runtime/core/modules/mcp.js +709 -0
- package/dist/runtime/core/modules/surfaces.js +11 -0
- package/package.json +2 -1
- package/src/runtime/core/modules/api.ts +2 -2
- package/src/runtime/core/modules/mcp.test.ts +687 -0
- package/src/runtime/core/modules/mcp.ts +814 -0
- package/src/runtime/core/modules/surfaces.test.ts +16 -0
- package/src/runtime/core/modules/surfaces.ts +11 -0
|
@@ -0,0 +1,709 @@
|
|
|
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 read-only 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 slice (ADR 0067 Slice 1) exposes READ-ONLY app operations only (GET/HEAD) — mutating
|
|
18
|
+
// operations and their guards are Slice 3. It also exposes framework-owned read-only
|
|
19
|
+
// process-debugging tools over BOTH truth planes: engine truth via existing `EngineClient` methods,
|
|
20
|
+
// and the ADR 0065 canonical projection stores (`urban_instance_state` / `urban_open_user_tasks`).
|
|
21
|
+
// The app's system brief (`/app/agent.json`) is served as an MCP resource, plus one orientation
|
|
22
|
+
// entry under MCP prompts.
|
|
23
|
+
//
|
|
24
|
+
// Transport: the SDK's Web-Standard Streamable-HTTP transport (`Request`→`Response`), bridged to
|
|
25
|
+
// the runtime's host `HttpRequest`/`HttpResponse` seam — core/ imports no `node:*`; the MCP SDK is
|
|
26
|
+
// an ordinary dependency. Access is loopback-only behind a manifest/env flag that defaults ON for
|
|
27
|
+
// loopback.
|
|
28
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
29
|
+
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
30
|
+
import { CallToolRequestSchema, ErrorCode, GetPromptRequestSchema, isInitializeRequest, ListPromptsRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
|
31
|
+
import { GENERATED_DIR } from "../../../toolkit/artifact.js";
|
|
32
|
+
import { SYSTEM_BRIEF_JSON } from "../../../toolkit/derivers/system-brief.js";
|
|
33
|
+
import { collectOperations, parseSpec, } from "../../../openapi/spec.js";
|
|
34
|
+
import { errorMessage } from "../guards.js";
|
|
35
|
+
import { presentFormIdentifier } from "../host.js";
|
|
36
|
+
import { resolveBindMode } from "../manifest.js";
|
|
37
|
+
import { json, makeRouter } from "../router.js";
|
|
38
|
+
import { API_BASE, readApiBinding } from "./api.js";
|
|
39
|
+
import { resolveAppPath } from "./datasource.js";
|
|
40
|
+
import { InstanceStateStore } from "./instance-state-store.js";
|
|
41
|
+
import { OpenUserTasksStore } from "./open-user-tasks-store.js";
|
|
42
|
+
/** The mount path of the MCP endpoint — a sibling of `/app/api` / `/app/agent`, mounted
|
|
43
|
+
* unconditionally so an MCP client always has a stable address to connect to. */
|
|
44
|
+
const MCP_PATH = "/app/mcp";
|
|
45
|
+
/** The header carrying the Streamable-HTTP session id (MCP spec). */
|
|
46
|
+
const SESSION_HEADER = "mcp-session-id";
|
|
47
|
+
/** Hard upper bound on concurrently-resident MCP sessions. Each session is a live `Server` +
|
|
48
|
+
* transport pair, so an unbounded session map is a memory/handle-exhaustion vector: any local
|
|
49
|
+
* process can repeatedly `initialize` without reusing its `mcp-session-id` and pin a fresh pair
|
|
50
|
+
* each time. Capping the map (LRU-evicted, refreshed on use — see `evictExcessSessions` /
|
|
51
|
+
* `touchSession`) categorically bounds growth regardless of client behaviour or timing. */
|
|
52
|
+
const MAX_SESSIONS = 256;
|
|
53
|
+
/** The MCP resource URI for the app's system brief (the `/app/agent.json` content). */
|
|
54
|
+
const SYSTEM_BRIEF_URI = "urban://system-brief.json";
|
|
55
|
+
/** The single orientation prompt registered under MCP `prompts`. */
|
|
56
|
+
const ORIENTATION_PROMPT = "urban-orientation";
|
|
57
|
+
/** The framework debug-tool name prefix — a reserved namespace. `loadReadOnlyOps` drops any app
|
|
58
|
+
* `operationId` in this namespace before it is projected as a tool, so a framework tool can never
|
|
59
|
+
* collide with (be shadowed by, or duplicate the name of) an app-projected tool. */
|
|
60
|
+
const DEBUG_PREFIX = "urban_debug_";
|
|
61
|
+
/** Mint a fresh MCP session id, host-agnostically. Prefers the Web Crypto `randomUUID` (a global,
|
|
62
|
+
* not `node:crypto`) where present, with a time+random fallback so a host without `crypto` never
|
|
63
|
+
* throws — mirroring how core treats Web Crypto as optional (see `mintRootRequestKey`). */
|
|
64
|
+
export function newSessionId() {
|
|
65
|
+
const uuid = globalThis.crypto?.randomUUID?.();
|
|
66
|
+
if (uuid)
|
|
67
|
+
return uuid;
|
|
68
|
+
return `sess-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
69
|
+
}
|
|
70
|
+
/** Mark a session as most-recently-used. A `Map` preserves insertion order, so deleting and
|
|
71
|
+
* re-inserting a live entry moves it to the tail — which makes the first key the least-recently-used
|
|
72
|
+
* entry that `evictExcessSessions` reaps first. Refreshing on every use is what keeps an active
|
|
73
|
+
* session from being evicted out from under a client that is still talking to it. */
|
|
74
|
+
function touchSession(sessions, id, session) {
|
|
75
|
+
sessions.delete(id);
|
|
76
|
+
sessions.set(id, session);
|
|
77
|
+
}
|
|
78
|
+
/** Bound the live-session map to `max` by evicting least-recently-used entries (the `Map`'s leading
|
|
79
|
+
* keys, given `touchSession` re-inserts on use), closing each victim best-effort so its transport /
|
|
80
|
+
* server releases. This is the categorical fix for the unbounded-growth vector: no client can pin
|
|
81
|
+
* more than `max` server/transport pairs, whatever its `initialize` cadence. Exported for a direct
|
|
82
|
+
* unit test of the LRU eviction contract. */
|
|
83
|
+
export async function evictExcessSessions(sessions, max, close) {
|
|
84
|
+
while (sessions.size > max) {
|
|
85
|
+
const oldest = sessions.keys().next().value;
|
|
86
|
+
if (oldest === undefined)
|
|
87
|
+
break;
|
|
88
|
+
const victim = sessions.get(oldest);
|
|
89
|
+
sessions.delete(oldest);
|
|
90
|
+
if (victim !== undefined) {
|
|
91
|
+
try {
|
|
92
|
+
await close(victim);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
// Best-effort: a victim whose transport is already torn down must not abort eviction.
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function isRecord(v) {
|
|
101
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Resolve the MCP access policy from the manifest (`mcp: { enabled?, allowRemote? }`, read
|
|
105
|
+
* reflectively until the app schema folds the field in — mirroring how `readApiBinding` reads
|
|
106
|
+
* `api`) and the environment (`URBAN_MCP_ENABLED`, `URBAN_MCP_ALLOW_REMOTE`). The env flags win so
|
|
107
|
+
* an operator can force the surface off (or open it to a non-loopback bind) without editing the
|
|
108
|
+
* manifest. Enabled defaults ON and access defaults to loopback-only ("defaults ON for loopback").
|
|
109
|
+
*/
|
|
110
|
+
export function readMcpConfig(manifest, env) {
|
|
111
|
+
const raw = manifest && typeof manifest === "object" ? Reflect.get(manifest, "mcp") : undefined;
|
|
112
|
+
// Honour manifest flags only when they are actual booleans (mirroring `readApiBinding`'s strict
|
|
113
|
+
// type checks), so a stray non-boolean value falls back to the default instead of coercing
|
|
114
|
+
// surprisingly (e.g. the string `"false"` is not a boolean `false`).
|
|
115
|
+
const rawEnabled = isRecord(raw) ? Reflect.get(raw, "enabled") : undefined;
|
|
116
|
+
const rawAllowRemote = isRecord(raw) ? Reflect.get(raw, "allowRemote") : undefined;
|
|
117
|
+
const manifestEnabled = typeof rawEnabled === "boolean" ? rawEnabled : undefined;
|
|
118
|
+
const manifestAllowRemote = typeof rawAllowRemote === "boolean" ? rawAllowRemote : undefined;
|
|
119
|
+
const envEnabled = env("URBAN_MCP_ENABLED");
|
|
120
|
+
const envAllowRemote = env("URBAN_MCP_ALLOW_REMOTE");
|
|
121
|
+
const enabled = envEnabled === "false" ? false : envEnabled === "true" ? true : manifestEnabled !== false;
|
|
122
|
+
const allowRemote = envAllowRemote === "true" ? true : envAllowRemote === "false" ? false : manifestAllowRemote === true;
|
|
123
|
+
return { enabled, allowRemote };
|
|
124
|
+
}
|
|
125
|
+
/** The host portion of an HTTP `Host` header, lower-cased and stripped of any `:port` (and of the
|
|
126
|
+
* `[...]` brackets around an IPv6 literal), or `undefined` when there is no Host header. */
|
|
127
|
+
function hostName(req) {
|
|
128
|
+
const host = req.headers.get("host");
|
|
129
|
+
if (!host)
|
|
130
|
+
return undefined;
|
|
131
|
+
const trimmed = host.trim().toLowerCase();
|
|
132
|
+
if (trimmed.startsWith("[")) {
|
|
133
|
+
const end = trimmed.indexOf("]");
|
|
134
|
+
return end > 0 ? trimmed.slice(1, end) : trimmed.slice(1);
|
|
135
|
+
}
|
|
136
|
+
const colon = trimmed.indexOf(":");
|
|
137
|
+
return colon >= 0 ? trimmed.slice(0, colon) : trimmed;
|
|
138
|
+
}
|
|
139
|
+
/** Whether the request targets a loopback host — the best-effort loopback signal available at the
|
|
140
|
+
* host seam (which carries no peer address). A missing Host header is treated as loopback (a direct
|
|
141
|
+
* local client that sent none). */
|
|
142
|
+
export function isLoopbackRequest(req) {
|
|
143
|
+
const name = hostName(req);
|
|
144
|
+
return name === undefined || name === "localhost" || name === "127.0.0.1" || name === "::1";
|
|
145
|
+
}
|
|
146
|
+
/** True for a read-only operation — the only operations this slice projects as tools. Mutating
|
|
147
|
+
* operations (POST/PUT/PATCH/DELETE) are withheld until Slice 3 adds them behind a guard. */
|
|
148
|
+
function isReadOnlyOperation(op) {
|
|
149
|
+
return op.method === "get" || op.method === "head";
|
|
150
|
+
}
|
|
151
|
+
/** A JSON Schema (OpenAPI object subset) describing a tool's input, derived from an operation's
|
|
152
|
+
* path/query parameters and its request-body schema. Keeping the property schemas verbatim from the
|
|
153
|
+
* spec means the tool input schema and the HTTP validation share one source of truth. */
|
|
154
|
+
function toolInputSchema(op) {
|
|
155
|
+
const properties = {};
|
|
156
|
+
const required = [];
|
|
157
|
+
for (const p of op.parameters) {
|
|
158
|
+
if (p.in === "path" || p.in === "query") {
|
|
159
|
+
properties[p.name] = p.schema ?? {};
|
|
160
|
+
if (p.required)
|
|
161
|
+
required.push(p.name);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (op.requestBodySchema) {
|
|
165
|
+
properties.body = op.requestBodySchema;
|
|
166
|
+
if (op.requestBodyRequired)
|
|
167
|
+
required.push("body");
|
|
168
|
+
}
|
|
169
|
+
const schema = { type: "object", properties };
|
|
170
|
+
if (required.length > 0)
|
|
171
|
+
schema.required = required;
|
|
172
|
+
return schema;
|
|
173
|
+
}
|
|
174
|
+
/** Substitute an operation's `{param}` path-template segments with the supplied arguments, building
|
|
175
|
+
* the request path under the shared `/app/api` base so dispatch hits the exact `mountApi` route. */
|
|
176
|
+
function fillPath(op, args) {
|
|
177
|
+
const path = op.path.replace(/\{([^}]+)\}/g, (_m, name) => {
|
|
178
|
+
const value = args[name];
|
|
179
|
+
return encodeURIComponent(value === undefined || value === null ? "" : String(value));
|
|
180
|
+
});
|
|
181
|
+
return `${API_BASE}${path}`;
|
|
182
|
+
}
|
|
183
|
+
/** Build the query string for a tool call from the operation's declared query parameters and the
|
|
184
|
+
* supplied arguments — repeated (array) values become repeated keys, exactly as an HTTP client
|
|
185
|
+
* would send them, so the reused dispatcher validates identical input. */
|
|
186
|
+
function toolQuery(op, args) {
|
|
187
|
+
const query = new URLSearchParams();
|
|
188
|
+
for (const p of op.parameters) {
|
|
189
|
+
if (p.in !== "query")
|
|
190
|
+
continue;
|
|
191
|
+
const value = args[p.name];
|
|
192
|
+
if (value === undefined || value === null)
|
|
193
|
+
continue;
|
|
194
|
+
if (Array.isArray(value)) {
|
|
195
|
+
for (const item of value)
|
|
196
|
+
query.append(p.name, String(item));
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
query.append(p.name, String(value));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return query;
|
|
203
|
+
}
|
|
204
|
+
/** Whether an argument is absent for presence purposes: unset (`undefined`/`null`), or a string that
|
|
205
|
+
* is empty or whitespace-only after trimming. This is the trimmed-presence rule
|
|
206
|
+
* {@link presentFormIdentifier} enforces for form identifiers, reused here so MCP required/path args
|
|
207
|
+
* and form resolution cannot drift on what "provided" means (a whitespace-only `" "` is absent in
|
|
208
|
+
* both). A non-string value (e.g. a numeric path id) is considered present. */
|
|
209
|
+
function isBlankArg(value) {
|
|
210
|
+
if (value === undefined || value === null)
|
|
211
|
+
return true;
|
|
212
|
+
if (typeof value === "string")
|
|
213
|
+
return presentFormIdentifier(value) === undefined;
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
/** The required path parameters an operation declares that the tool `args` did not supply. Unlike
|
|
217
|
+
* an HTTP request (whose path can't structurally omit a segment), a tool call can leave a
|
|
218
|
+
* `{param}` unset or blank; `fillPath` would then substitute an empty string and silently mis-route
|
|
219
|
+
* (a 404 route mismatch, or worse a different route shape), so a missing/blank path arg is rejected
|
|
220
|
+
* up front. Blankness uses the shared trimmed-presence rule so a whitespace-only value is rejected
|
|
221
|
+
* too. */
|
|
222
|
+
function missingPathParams(op, args) {
|
|
223
|
+
return op.parameters
|
|
224
|
+
.filter((p) => p.in === "path" && isBlankArg(args[p.name]))
|
|
225
|
+
.map((p) => p.name);
|
|
226
|
+
}
|
|
227
|
+
/** The `required` keys a tool's `inputSchema` declares but the call omitted. Presence is decided
|
|
228
|
+
* solely by {@link isBlankArg} — the single source of truth also used for path args — so a value is
|
|
229
|
+
* "provided" unless it is absent (`undefined`/`null`) or a blank/whitespace-only string. A required
|
|
230
|
+
* non-string input (e.g. a numeric/boolean/object arg) that is present is therefore accepted, not
|
|
231
|
+
* wrongly reported missing. Derived from the schema's own `required` array so declaring a field
|
|
232
|
+
* required is enough to have missing (or whitespace-only) calls rejected rather than silently
|
|
233
|
+
* substituted with an empty string. */
|
|
234
|
+
export function missingRequiredArgs(inputSchema, args) {
|
|
235
|
+
const required = inputSchema.required;
|
|
236
|
+
if (!Array.isArray(required))
|
|
237
|
+
return [];
|
|
238
|
+
const missing = [];
|
|
239
|
+
for (const key of required) {
|
|
240
|
+
if (typeof key !== "string")
|
|
241
|
+
continue;
|
|
242
|
+
if (isBlankArg(args[key]))
|
|
243
|
+
missing.push(key);
|
|
244
|
+
}
|
|
245
|
+
return missing;
|
|
246
|
+
}
|
|
247
|
+
/** Reconstruct the HTTP request an operation tool call is equivalent to, ready to hand to the
|
|
248
|
+
* reused `mountApi` router. The JSON body is the tool's `body` argument (when the op declares one).
|
|
249
|
+
*/
|
|
250
|
+
function toHttpRequest(op, args) {
|
|
251
|
+
const bodyText = op.requestBodySchema !== undefined && args.body !== undefined
|
|
252
|
+
? JSON.stringify(args.body)
|
|
253
|
+
: "";
|
|
254
|
+
return {
|
|
255
|
+
method: op.method.toUpperCase(),
|
|
256
|
+
path: fillPath(op, args),
|
|
257
|
+
query: toolQuery(op, args),
|
|
258
|
+
headers: new Headers({ "content-type": "application/json" }),
|
|
259
|
+
text: () => Promise.resolve(bodyText),
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
/** Wrap a value as an MCP tool text result. A JSON payload is stringified; `isError` flags a
|
|
263
|
+
* non-2xx dispatch so the client sees the failure (carrying the delegate's own error body). */
|
|
264
|
+
function textResult(value, isError = false) {
|
|
265
|
+
const text = typeof value === "string" ? value : JSON.stringify(value ?? null);
|
|
266
|
+
return isError ? { content: [{ type: "text", text }], isError: true } : { content: [{ type: "text", text }] };
|
|
267
|
+
}
|
|
268
|
+
function readString(args, key) {
|
|
269
|
+
const v = args[key];
|
|
270
|
+
return typeof v === "string" ? v : undefined;
|
|
271
|
+
}
|
|
272
|
+
function readStringArray(args, key) {
|
|
273
|
+
const v = args[key];
|
|
274
|
+
if (!Array.isArray(v))
|
|
275
|
+
return undefined;
|
|
276
|
+
const out = [];
|
|
277
|
+
for (const item of v)
|
|
278
|
+
if (typeof item === "string")
|
|
279
|
+
out.push(item);
|
|
280
|
+
return out;
|
|
281
|
+
}
|
|
282
|
+
function readProcessInstanceState(args, key) {
|
|
283
|
+
const v = args[key];
|
|
284
|
+
return v === "ACTIVE" || v === "COMPLETED" || v === "TERMINATED" ? v : undefined;
|
|
285
|
+
}
|
|
286
|
+
function readUserTaskState(args, key) {
|
|
287
|
+
const v = args[key];
|
|
288
|
+
return v === "CREATED" || v === "COMPLETED" || v === "CANCELED" || v === "FAILED" ? v : undefined;
|
|
289
|
+
}
|
|
290
|
+
function readWaitStateType(args, key) {
|
|
291
|
+
const v = args[key];
|
|
292
|
+
return v === "JOB" || v === "MESSAGE" || v === "USER_TASK" || v === "TIMER" || v === "SIGNAL" || v === "CONDITION"
|
|
293
|
+
? v
|
|
294
|
+
: undefined;
|
|
295
|
+
}
|
|
296
|
+
const OPTIONAL_STRING = { type: "string" };
|
|
297
|
+
/** Build the framework debug tools, closing over the app's engine (truth plane) and default data
|
|
298
|
+
* source (the ADR 0065 projection stores). The engine tools consume only EXISTING `EngineClient`
|
|
299
|
+
* methods — no seam extension in this slice. */
|
|
300
|
+
function buildDebugTools(app) {
|
|
301
|
+
const projectionDb = () => app.data.hasDefaultSource() ? app.data.source().db : undefined;
|
|
302
|
+
return [
|
|
303
|
+
{
|
|
304
|
+
name: `${DEBUG_PREFIX}search_process_instances`,
|
|
305
|
+
description: "Engine truth: search process instances by key and/or lifecycle state.",
|
|
306
|
+
inputSchema: {
|
|
307
|
+
type: "object",
|
|
308
|
+
properties: {
|
|
309
|
+
processInstanceKeys: { type: "array", items: OPTIONAL_STRING },
|
|
310
|
+
state: { type: "string", enum: ["ACTIVE", "COMPLETED", "TERMINATED"] },
|
|
311
|
+
},
|
|
312
|
+
},
|
|
313
|
+
run: (args) => {
|
|
314
|
+
const filter = {};
|
|
315
|
+
const keys = readStringArray(args, "processInstanceKeys");
|
|
316
|
+
if (keys)
|
|
317
|
+
filter.processInstanceKeys = keys;
|
|
318
|
+
const state = readProcessInstanceState(args, "state");
|
|
319
|
+
if (state)
|
|
320
|
+
filter.state = state;
|
|
321
|
+
return app.engine.searchProcessInstances(filter);
|
|
322
|
+
},
|
|
323
|
+
},
|
|
324
|
+
{
|
|
325
|
+
name: `${DEBUG_PREFIX}search_element_instance_wait_states`,
|
|
326
|
+
description: "Engine truth: search element-instance wait states (every park, not only user tasks).",
|
|
327
|
+
inputSchema: {
|
|
328
|
+
type: "object",
|
|
329
|
+
properties: {
|
|
330
|
+
processInstanceKey: OPTIONAL_STRING,
|
|
331
|
+
elementId: OPTIONAL_STRING,
|
|
332
|
+
waitStateType: {
|
|
333
|
+
type: "string",
|
|
334
|
+
enum: ["JOB", "MESSAGE", "USER_TASK", "TIMER", "SIGNAL", "CONDITION"],
|
|
335
|
+
},
|
|
336
|
+
},
|
|
337
|
+
},
|
|
338
|
+
run: (args) => {
|
|
339
|
+
const filter = {};
|
|
340
|
+
const pik = readString(args, "processInstanceKey");
|
|
341
|
+
if (pik)
|
|
342
|
+
filter.processInstanceKey = pik;
|
|
343
|
+
const elementId = readString(args, "elementId");
|
|
344
|
+
if (elementId)
|
|
345
|
+
filter.elementId = elementId;
|
|
346
|
+
const waitStateType = readWaitStateType(args, "waitStateType");
|
|
347
|
+
if (waitStateType)
|
|
348
|
+
filter.waitStateType = waitStateType;
|
|
349
|
+
return app.engine.searchElementInstanceWaitStates(filter);
|
|
350
|
+
},
|
|
351
|
+
},
|
|
352
|
+
{
|
|
353
|
+
name: `${DEBUG_PREFIX}get_element_instance`,
|
|
354
|
+
description: "Engine truth: fetch a single element instance by key (null when absent).",
|
|
355
|
+
inputSchema: {
|
|
356
|
+
type: "object",
|
|
357
|
+
properties: { elementInstanceKey: OPTIONAL_STRING },
|
|
358
|
+
required: ["elementInstanceKey"],
|
|
359
|
+
},
|
|
360
|
+
run: (args) => app.engine.getElementInstance(readString(args, "elementInstanceKey") ?? ""),
|
|
361
|
+
},
|
|
362
|
+
{
|
|
363
|
+
name: `${DEBUG_PREFIX}search_user_tasks`,
|
|
364
|
+
description: "Engine truth: search user tasks by process instance, assignee, candidate group, and/or state.",
|
|
365
|
+
inputSchema: {
|
|
366
|
+
type: "object",
|
|
367
|
+
properties: {
|
|
368
|
+
processInstanceKey: OPTIONAL_STRING,
|
|
369
|
+
assignee: OPTIONAL_STRING,
|
|
370
|
+
candidateGroup: OPTIONAL_STRING,
|
|
371
|
+
state: { type: "string", enum: ["CREATED", "COMPLETED", "CANCELED", "FAILED"] },
|
|
372
|
+
},
|
|
373
|
+
},
|
|
374
|
+
run: (args) => {
|
|
375
|
+
const filter = {};
|
|
376
|
+
const pik = readString(args, "processInstanceKey");
|
|
377
|
+
if (pik)
|
|
378
|
+
filter.processInstanceKey = pik;
|
|
379
|
+
const assignee = readString(args, "assignee");
|
|
380
|
+
if (assignee)
|
|
381
|
+
filter.assignee = assignee;
|
|
382
|
+
const candidateGroup = readString(args, "candidateGroup");
|
|
383
|
+
if (candidateGroup)
|
|
384
|
+
filter.candidateGroup = candidateGroup;
|
|
385
|
+
const state = readUserTaskState(args, "state");
|
|
386
|
+
if (state)
|
|
387
|
+
filter.state = state;
|
|
388
|
+
return app.engine.searchUserTasks(filter);
|
|
389
|
+
},
|
|
390
|
+
},
|
|
391
|
+
{
|
|
392
|
+
name: `${DEBUG_PREFIX}instance_state`,
|
|
393
|
+
description: "Projection (urban_instance_state, ADR 0065): the canonical engine-lifecycle state for an instance.",
|
|
394
|
+
inputSchema: {
|
|
395
|
+
type: "object",
|
|
396
|
+
properties: { processInstanceKey: OPTIONAL_STRING },
|
|
397
|
+
required: ["processInstanceKey"],
|
|
398
|
+
},
|
|
399
|
+
run: (args) => {
|
|
400
|
+
const db = projectionDb();
|
|
401
|
+
if (!db)
|
|
402
|
+
return Promise.resolve(null);
|
|
403
|
+
const key = readString(args, "processInstanceKey") ?? "";
|
|
404
|
+
return Promise.resolve(new InstanceStateStore(db).getState(key) ?? null);
|
|
405
|
+
},
|
|
406
|
+
},
|
|
407
|
+
{
|
|
408
|
+
name: `${DEBUG_PREFIX}open_user_tasks`,
|
|
409
|
+
description: "Projection (urban_open_user_tasks, ADR 0065): the currently-open user tasks for an instance.",
|
|
410
|
+
inputSchema: {
|
|
411
|
+
type: "object",
|
|
412
|
+
properties: { processInstanceKey: OPTIONAL_STRING },
|
|
413
|
+
required: ["processInstanceKey"],
|
|
414
|
+
},
|
|
415
|
+
run: (args) => {
|
|
416
|
+
const db = projectionDb();
|
|
417
|
+
if (!db)
|
|
418
|
+
return Promise.resolve([]);
|
|
419
|
+
const key = readString(args, "processInstanceKey") ?? "";
|
|
420
|
+
return Promise.resolve(new OpenUserTasksStore(db).openTasks(key));
|
|
421
|
+
},
|
|
422
|
+
},
|
|
423
|
+
];
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Mount the runtime-served MCP surface at `/app/mcp` (ADR 0067). Returns a single `*`-method route
|
|
427
|
+
* (mounted unconditionally, like `/app/agent`); the handler bridges the host request/response seam
|
|
428
|
+
* to the SDK's Web-Standard Streamable-HTTP transport, maintaining one MCP session per
|
|
429
|
+
* `mcp-session-id`. The tool projection reuses the SAME OpenAPI enumeration and dispatch path as
|
|
430
|
+
* `mountApi`, so a tool call is equivalent to the corresponding HTTP call.
|
|
431
|
+
*/
|
|
432
|
+
export function mountMcp(ctx, app, apiRoutes) {
|
|
433
|
+
const config = readMcpConfig(ctx.manifest, ctx.host.env);
|
|
434
|
+
// The effective HTTP bind interface. When the app is bound to all interfaces, the
|
|
435
|
+
// client-controlled `Host` header is not a trustworthy loopback signal (a remote caller can send
|
|
436
|
+
// `Host: localhost`), so a loopback-only surface must refuse EVERY caller rather than trust it.
|
|
437
|
+
const bindMode = resolveBindMode(ctx.manifest, ctx.host.env);
|
|
438
|
+
// Reuse the app's OpenAPI dispatch VERBATIM: `mountSurfaces` already built the `/app/api` router
|
|
439
|
+
// (validation + delegate registry) via `mountApi` and hands us its routes here, so tool and HTTP
|
|
440
|
+
// calls share ONE dispatcher instance (no forked dispatcher, no second doc/delegate cache). A tool
|
|
441
|
+
// call is reconstructed into the operation's HTTP request and routed through this same router.
|
|
442
|
+
const apiRouter = makeRouter(apiRoutes);
|
|
443
|
+
// The read-only operation table, projected lazily from the same spec `mountApi` reads and cached
|
|
444
|
+
// (mirroring `mountApi`'s lazy `loadDoc`). A missing/broken spec degrades to "no app tools"
|
|
445
|
+
// rather than breaking the whole MCP endpoint (the debug tools + resource + prompt still serve).
|
|
446
|
+
let opsPromise;
|
|
447
|
+
const loadReadOnlyOps = () => {
|
|
448
|
+
if (!opsPromise) {
|
|
449
|
+
opsPromise = (async () => {
|
|
450
|
+
const binding = readApiBinding(ctx.manifest);
|
|
451
|
+
if (!binding)
|
|
452
|
+
return [];
|
|
453
|
+
const text = await ctx.host.readTextFile(resolveAppPath(ctx.root, binding.spec));
|
|
454
|
+
const readOnly = collectOperations(parseSpec(text)).filter(isReadOnlyOperation);
|
|
455
|
+
// The `urban_debug_` namespace is framework-reserved (see DEBUG_PREFIX). A `urban_debug_*`
|
|
456
|
+
// operationId is a legal safe path segment, so an app could declare one — but `CallTool`
|
|
457
|
+
// resolves `debugByName` before app ops, so such an op would be shadowed by the framework
|
|
458
|
+
// tool AND surface a duplicate name in `tools/list`. Drop reserved-namespace app ops here
|
|
459
|
+
// (the single projection source both `tools/list` and `CallTool` read), warning per drop,
|
|
460
|
+
// so the collision is impossible by construction rather than order-dependent.
|
|
461
|
+
return readOnly.filter((op) => {
|
|
462
|
+
if (op.operationId.startsWith(DEBUG_PREFIX)) {
|
|
463
|
+
ctx.host.log("warn", "mcp: dropped app operation using reserved framework tool namespace", {
|
|
464
|
+
operationId: op.operationId,
|
|
465
|
+
reservedPrefix: DEBUG_PREFIX,
|
|
466
|
+
});
|
|
467
|
+
return false;
|
|
468
|
+
}
|
|
469
|
+
return true;
|
|
470
|
+
});
|
|
471
|
+
})().catch((e) => {
|
|
472
|
+
opsPromise = undefined; // don't cache the failure — let a later request retry
|
|
473
|
+
ctx.host.log("warn", "mcp: failed to project app operations as tools", { error: errorMessage(e) });
|
|
474
|
+
return [];
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
return opsPromise;
|
|
478
|
+
};
|
|
479
|
+
const debugTools = buildDebugTools(app);
|
|
480
|
+
const debugByName = new Map(debugTools.map((t) => [t.name, t]));
|
|
481
|
+
const dispatchOperationTool = async (op, args) => {
|
|
482
|
+
const missing = missingPathParams(op, args);
|
|
483
|
+
if (missing.length > 0) {
|
|
484
|
+
// Surface as an error tool result (like a reused-validator failure), not a silent 404 from an
|
|
485
|
+
// empty-string substitution — the calling agent sees exactly which required params it omitted.
|
|
486
|
+
return textResult({ error: `validation failed: missing required path parameter(s): ${missing.join(", ")}` }, true);
|
|
487
|
+
}
|
|
488
|
+
const res = await apiRouter(toHttpRequest(op, args));
|
|
489
|
+
const status = res.status ?? 200;
|
|
490
|
+
return textResult(res.body ?? "", status >= 400);
|
|
491
|
+
};
|
|
492
|
+
const readSystemBrief = async () => {
|
|
493
|
+
const path = resolveAppPath(ctx.root, `${GENERATED_DIR}/${SYSTEM_BRIEF_JSON}`);
|
|
494
|
+
if (!(await ctx.host.exists(path))) {
|
|
495
|
+
throw new McpError(ErrorCode.InvalidParams, "system brief not generated — run `urban gen`");
|
|
496
|
+
}
|
|
497
|
+
return ctx.host.readTextFile(path);
|
|
498
|
+
};
|
|
499
|
+
const orientationText = () => [
|
|
500
|
+
`# ${ctx.manifest.name ?? "Urban app"} — MCP orientation`,
|
|
501
|
+
"",
|
|
502
|
+
"This endpoint is the app's runtime-served MCP surface (ADR 0067).",
|
|
503
|
+
"",
|
|
504
|
+
`- Read the \`${SYSTEM_BRIEF_URI}\` resource first for the app's system model (processes, service-task call graph, decisions, ownership).`,
|
|
505
|
+
"- App tools mirror the app's read-only HTTP operations one-to-one: a tool call is equivalent to the corresponding `/app/api` HTTP call, validated identically.",
|
|
506
|
+
`- \`${DEBUG_PREFIX}*\` tools are framework-owned read-only process-debugging tools: engine truth (process instances, wait states, element instances, user tasks) and the ADR 0065 projection stores (instance state, open user tasks).`,
|
|
507
|
+
"- This slice is read-only; mutating tools are added in a later slice behind an access guard.",
|
|
508
|
+
].join("\n");
|
|
509
|
+
/** Build a fresh low-level MCP `Server` with this app's tools/resources/prompts wired. One is
|
|
510
|
+
* created per session and connected to that session's transport. */
|
|
511
|
+
const buildServer = () => {
|
|
512
|
+
const server = new Server({ name: "urban", version: "1.0.0" }, { capabilities: { tools: {}, resources: {}, prompts: {} } });
|
|
513
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
514
|
+
const ops = await loadReadOnlyOps();
|
|
515
|
+
const appTools = ops.map((op) => ({
|
|
516
|
+
name: op.operationId,
|
|
517
|
+
description: op.summary ?? `${op.method.toUpperCase()} ${op.path}`,
|
|
518
|
+
inputSchema: toolInputSchema(op),
|
|
519
|
+
annotations: { readOnlyHint: true },
|
|
520
|
+
}));
|
|
521
|
+
const frameworkTools = debugTools.map((t) => ({
|
|
522
|
+
name: t.name,
|
|
523
|
+
description: t.description,
|
|
524
|
+
inputSchema: t.inputSchema,
|
|
525
|
+
annotations: { readOnlyHint: true },
|
|
526
|
+
}));
|
|
527
|
+
return { tools: [...appTools, ...frameworkTools] };
|
|
528
|
+
});
|
|
529
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
530
|
+
const { name } = request.params;
|
|
531
|
+
const args = isRecord(request.params.arguments) ? request.params.arguments : {};
|
|
532
|
+
const debug = debugByName.get(name);
|
|
533
|
+
if (debug) {
|
|
534
|
+
const missing = missingRequiredArgs(debug.inputSchema, args);
|
|
535
|
+
if (missing.length > 0) {
|
|
536
|
+
// Fail fast like an operation-tool validation error, instead of substituting an empty
|
|
537
|
+
// string that makes an invalid call look like a legitimate "not found" result.
|
|
538
|
+
return textResult({ error: `validation failed: missing required parameter(s): ${missing.join(", ")}` }, true);
|
|
539
|
+
}
|
|
540
|
+
try {
|
|
541
|
+
return textResult(await debug.run(args));
|
|
542
|
+
}
|
|
543
|
+
catch (e) {
|
|
544
|
+
return textResult({ error: errorMessage(e) }, true);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
const ops = await loadReadOnlyOps();
|
|
548
|
+
const op = ops.find((o) => o.operationId === name);
|
|
549
|
+
if (!op) {
|
|
550
|
+
throw new McpError(ErrorCode.MethodNotFound, `no such tool: ${name}`);
|
|
551
|
+
}
|
|
552
|
+
return dispatchOperationTool(op, args);
|
|
553
|
+
});
|
|
554
|
+
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
|
|
555
|
+
resources: [
|
|
556
|
+
{
|
|
557
|
+
uri: SYSTEM_BRIEF_URI,
|
|
558
|
+
name: "system-brief",
|
|
559
|
+
title: "App system brief",
|
|
560
|
+
description: "The app's derived institutional-memory brief (the /app/agent.json content).",
|
|
561
|
+
mimeType: "application/json",
|
|
562
|
+
},
|
|
563
|
+
],
|
|
564
|
+
}));
|
|
565
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
566
|
+
const { uri } = request.params;
|
|
567
|
+
if (uri !== SYSTEM_BRIEF_URI) {
|
|
568
|
+
throw new McpError(ErrorCode.InvalidParams, `no such resource: ${uri}`);
|
|
569
|
+
}
|
|
570
|
+
const text = await readSystemBrief();
|
|
571
|
+
return { contents: [{ uri, mimeType: "application/json", text }] };
|
|
572
|
+
});
|
|
573
|
+
server.setRequestHandler(ListPromptsRequestSchema, async () => ({
|
|
574
|
+
prompts: [
|
|
575
|
+
{
|
|
576
|
+
name: ORIENTATION_PROMPT,
|
|
577
|
+
title: "Orient on this app",
|
|
578
|
+
description: "How to use this app's MCP surface: its read tools, debug tools, and system-brief resource.",
|
|
579
|
+
arguments: [],
|
|
580
|
+
},
|
|
581
|
+
],
|
|
582
|
+
}));
|
|
583
|
+
server.setRequestHandler(GetPromptRequestSchema, async (request) => {
|
|
584
|
+
if (request.params.name !== ORIENTATION_PROMPT) {
|
|
585
|
+
throw new McpError(ErrorCode.InvalidParams, `no such prompt: ${request.params.name}`);
|
|
586
|
+
}
|
|
587
|
+
return {
|
|
588
|
+
description: "Orientation for working against this app over MCP.",
|
|
589
|
+
messages: [{ role: "user", content: { type: "text", text: orientationText() } }],
|
|
590
|
+
};
|
|
591
|
+
});
|
|
592
|
+
return server;
|
|
593
|
+
};
|
|
594
|
+
const sessions = new Map();
|
|
595
|
+
const createSession = async () => {
|
|
596
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
597
|
+
sessionIdGenerator: () => newSessionId(),
|
|
598
|
+
enableJsonResponse: true,
|
|
599
|
+
onsessionclosed: (id) => {
|
|
600
|
+
sessions.delete(id);
|
|
601
|
+
},
|
|
602
|
+
});
|
|
603
|
+
transport.onclose = () => {
|
|
604
|
+
if (transport.sessionId)
|
|
605
|
+
sessions.delete(transport.sessionId);
|
|
606
|
+
};
|
|
607
|
+
const server = buildServer();
|
|
608
|
+
await server.connect(transport);
|
|
609
|
+
return { server, transport };
|
|
610
|
+
};
|
|
611
|
+
/** Convert the host request into the Web-Standard `Request` the SDK transport consumes. The body
|
|
612
|
+
* is passed separately (as `parsedBody`) so the transport never re-reads it; the Request carries
|
|
613
|
+
* the method + headers (Accept, content-type, `mcp-session-id`, protocol version) it inspects. */
|
|
614
|
+
const toWebRequest = (req) => {
|
|
615
|
+
const search = req.query.toString();
|
|
616
|
+
const url = `http://localhost${req.path}${search ? `?${search}` : ""}`;
|
|
617
|
+
const headers = new Headers();
|
|
618
|
+
for (const [key, value] of req.headers)
|
|
619
|
+
headers.set(key, value);
|
|
620
|
+
return new Request(url, { method: req.method, headers });
|
|
621
|
+
};
|
|
622
|
+
const toHttpResponse = async (res) => {
|
|
623
|
+
const headers = {};
|
|
624
|
+
for (const [key, value] of res.headers)
|
|
625
|
+
headers[key] = value;
|
|
626
|
+
return { status: res.status, headers, body: await res.text() };
|
|
627
|
+
};
|
|
628
|
+
const methodNotAllowed = () => ({
|
|
629
|
+
status: 405,
|
|
630
|
+
headers: { allow: "POST, DELETE", "content-type": "application/json" },
|
|
631
|
+
body: JSON.stringify({
|
|
632
|
+
jsonrpc: "2.0",
|
|
633
|
+
error: { code: -32000, message: "Method Not Allowed: the MCP endpoint accepts POST (and DELETE to end a session)." },
|
|
634
|
+
id: null,
|
|
635
|
+
}),
|
|
636
|
+
});
|
|
637
|
+
const handle = async (req) => {
|
|
638
|
+
if (!config.enabled)
|
|
639
|
+
return json({ error: "MCP surface is disabled" }, 404);
|
|
640
|
+
if (!config.allowRemote) {
|
|
641
|
+
// Bound to all interfaces, `Host` can't be trusted as a loopback proof: refuse everyone
|
|
642
|
+
// unless remote access is explicitly opted in (mcp.allowRemote / URBAN_MCP_ALLOW_REMOTE).
|
|
643
|
+
if (bindMode === "all") {
|
|
644
|
+
return json({ error: "MCP surface is loopback-only, but the app is bound to all interfaces; set mcp.allowRemote to expose it" }, 403);
|
|
645
|
+
}
|
|
646
|
+
if (!isLoopbackRequest(req)) {
|
|
647
|
+
return json({ error: "MCP surface is loopback-only" }, 403);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
const method = req.method.toUpperCase();
|
|
651
|
+
// The string-body host seam cannot hold open an SSE stream, so the optional GET server→client
|
|
652
|
+
// stream is declined with 405 (spec-compliant): clients fall back to POST request/response.
|
|
653
|
+
if (method !== "POST" && method !== "DELETE")
|
|
654
|
+
return methodNotAllowed();
|
|
655
|
+
const rawBody = method === "POST" ? await req.text() : "";
|
|
656
|
+
let parsedBody;
|
|
657
|
+
if (rawBody) {
|
|
658
|
+
try {
|
|
659
|
+
parsedBody = JSON.parse(rawBody);
|
|
660
|
+
}
|
|
661
|
+
catch {
|
|
662
|
+
return json({ jsonrpc: "2.0", error: { code: ErrorCode.ParseError, message: "request body is not valid JSON" }, id: null }, 400);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
const sessionId = req.headers.get(SESSION_HEADER) ?? undefined;
|
|
666
|
+
let session = sessionId ? sessions.get(sessionId) : undefined;
|
|
667
|
+
// Refresh an existing session's recency so an actively-used session is never the LRU victim.
|
|
668
|
+
if (session && sessionId)
|
|
669
|
+
touchSession(sessions, sessionId, session);
|
|
670
|
+
if (!session) {
|
|
671
|
+
const messages = Array.isArray(parsedBody) ? parsedBody : [parsedBody];
|
|
672
|
+
if (!messages.some((m) => isInitializeRequest(m))) {
|
|
673
|
+
return json({
|
|
674
|
+
jsonrpc: "2.0",
|
|
675
|
+
error: { code: -32000, message: "Bad Request: no valid session id, and not an initialize request." },
|
|
676
|
+
id: null,
|
|
677
|
+
}, 400);
|
|
678
|
+
}
|
|
679
|
+
session = await createSession();
|
|
680
|
+
}
|
|
681
|
+
const webResponse = await session.transport.handleRequest(toWebRequest(req), { parsedBody });
|
|
682
|
+
// A newly-initialized session assigns its id during handleRequest — register it so the client's
|
|
683
|
+
// follow-up requests (carrying `mcp-session-id`) resolve back to this same server/transport.
|
|
684
|
+
const assignedId = session.transport.sessionId;
|
|
685
|
+
if (assignedId && !sessions.has(assignedId)) {
|
|
686
|
+
sessions.set(assignedId, session);
|
|
687
|
+
// Enforce the hard cap once the freshly-initialized session is registered, evicting the
|
|
688
|
+
// least-recently-used pairs (never this one — it is now the newest) so the map stays bounded.
|
|
689
|
+
await evictExcessSessions(sessions, MAX_SESSIONS, (s) => s.server.close());
|
|
690
|
+
}
|
|
691
|
+
return toHttpResponse(webResponse);
|
|
692
|
+
};
|
|
693
|
+
const routes = [
|
|
694
|
+
{ method: "*", path: MCP_PATH, source: "surface:mcp", handler: handle },
|
|
695
|
+
];
|
|
696
|
+
ctx.host.log("info", "mcp surface mounted", {
|
|
697
|
+
path: MCP_PATH,
|
|
698
|
+
enabled: config.enabled,
|
|
699
|
+
loopbackOnly: !config.allowRemote,
|
|
700
|
+
});
|
|
701
|
+
return {
|
|
702
|
+
name: "mcp",
|
|
703
|
+
routes,
|
|
704
|
+
enabled: config.enabled,
|
|
705
|
+
describe: () => ({
|
|
706
|
+
mcp: { path: MCP_PATH, enabled: config.enabled, loopbackOnly: !config.allowRemote },
|
|
707
|
+
}),
|
|
708
|
+
};
|
|
709
|
+
}
|