@12-apps/mcp 3.2.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,331 @@
1
+ import {
2
+ AI_CAPABILITIES,
3
+ AI_PERMISSION_MODEL,
4
+ aiConnectPrompt,
5
+ aiHostGuides,
6
+ providerForHostId
7
+ } from "./chunk-FYEVBTDU.js";
8
+ import {
9
+ PROTECTED_RESOURCE_METADATA_PATH,
10
+ bearerChallenge,
11
+ buildAuthorizationServerMetadata,
12
+ buildProtectedResourceMetadata
13
+ } from "./chunk-WJJNKKNS.js";
14
+ import {
15
+ buildManifest,
16
+ generateTools,
17
+ serializeManifest,
18
+ serializeSurfaceLock,
19
+ surfaceDigest,
20
+ surfaceLockProblem
21
+ } from "./chunk-HAZOPC6U.js";
22
+ import {
23
+ __name
24
+ } from "./chunk-7QVYU63E.js";
25
+
26
+ // src/openapi/refs.ts
27
+ var UnsupportedSchemaError = class extends Error {
28
+ static {
29
+ __name(this, "UnsupportedSchemaError");
30
+ }
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = "UnsupportedSchemaError";
34
+ }
35
+ };
36
+ var REF_PREFIXES = ["#/$defs/", "#/definitions/", "#/components/schemas/"];
37
+ var DEF_CONTAINERS = ["$defs", "definitions"];
38
+ function refName(ref) {
39
+ const prefix = REF_PREFIXES.find((candidate) => ref.startsWith(candidate));
40
+ return prefix ? decodeURIComponent(ref.slice(prefix.length)) : null;
41
+ }
42
+ __name(refName, "refName");
43
+ function collectDefs(root) {
44
+ const defs = {};
45
+ DEF_CONTAINERS.forEach((key) => {
46
+ const container = root[key];
47
+ if (container && typeof container === "object") {
48
+ Object.assign(defs, container);
49
+ }
50
+ });
51
+ return defs;
52
+ }
53
+ __name(collectDefs, "collectDefs");
54
+ function inlineRef(ref, defs, active) {
55
+ const name = refName(ref);
56
+ if (name === null) throw new UnsupportedSchemaError(`Unsupported $ref pointer: ${ref}`);
57
+ const target = defs[name];
58
+ if (!target) throw new UnsupportedSchemaError(`Unresolved $ref: ${ref}`);
59
+ if (active.has(name)) throw new UnsupportedSchemaError(`Recursive schema not supported: ${name}`);
60
+ active.add(name);
61
+ const resolved = walk(target, defs, active);
62
+ active.delete(name);
63
+ return resolved;
64
+ }
65
+ __name(inlineRef, "inlineRef");
66
+ function walk(node, defs, active) {
67
+ if (Array.isArray(node)) return node.map((item) => walk(item, defs, active));
68
+ if (!node || typeof node !== "object") return node;
69
+ const obj = node;
70
+ if (typeof obj.$ref === "string") return inlineRef(obj.$ref, defs, active);
71
+ const out = {};
72
+ Object.entries(obj).forEach(([key, value]) => {
73
+ if (!DEF_CONTAINERS.includes(key)) {
74
+ out[key] = walk(value, defs, active);
75
+ }
76
+ });
77
+ return out;
78
+ }
79
+ __name(walk, "walk");
80
+ function inlineSchemaRefs(schema) {
81
+ const defs = collectDefs(schema);
82
+ return walk(schema, defs, /* @__PURE__ */ new Set());
83
+ }
84
+ __name(inlineSchemaRefs, "inlineSchemaRefs");
85
+
86
+ // src/dispatch/proxy.ts
87
+ var DispatchInputError = class extends Error {
88
+ static {
89
+ __name(this, "DispatchInputError");
90
+ }
91
+ constructor(message) {
92
+ super(message);
93
+ this.name = "DispatchInputError";
94
+ }
95
+ };
96
+ function expandPath(tool, args) {
97
+ return tool.path.replace(/\{([^}]+)\}/g, (_match, key) => {
98
+ const value = args[key];
99
+ if (value === void 0 || value === null) {
100
+ throw new DispatchInputError(`Missing required path parameter: ${key}`);
101
+ }
102
+ return encodeURIComponent(String(value));
103
+ });
104
+ }
105
+ __name(expandPath, "expandPath");
106
+ function routeParams(tool, args) {
107
+ const query = new URLSearchParams();
108
+ const headers = {};
109
+ tool.parameters.filter((param) => param.in !== "path").forEach((param) => {
110
+ const value = args[param.name];
111
+ if (value === void 0 || value === null) {
112
+ if (param.required) {
113
+ throw new DispatchInputError(`Missing required ${param.in} parameter: ${param.name}`);
114
+ }
115
+ return;
116
+ }
117
+ if (param.in === "query") query.set(param.name, String(value));
118
+ else headers[param.name] = String(value);
119
+ });
120
+ return { query, headers };
121
+ }
122
+ __name(routeParams, "routeParams");
123
+ function routeBody(tool, args) {
124
+ if (tool.bodyIsWhole) return args.body;
125
+ if (!tool.bodyProps.length) return void 0;
126
+ const payload = {};
127
+ tool.bodyProps.forEach((key) => {
128
+ if (args[key] !== void 0) payload[key] = args[key];
129
+ });
130
+ return Object.keys(payload).length ? payload : void 0;
131
+ }
132
+ __name(routeBody, "routeBody");
133
+ async function dispatchTool(tool, args, config) {
134
+ const doFetch = config.fetchImpl ?? fetch;
135
+ const pathname = expandPath(tool, args);
136
+ const { query, headers } = routeParams(tool, args);
137
+ const body = routeBody(tool, args);
138
+ const url = new URL(pathname, config.baseUrl);
139
+ for (const [key, value] of query) url.searchParams.set(key, value);
140
+ const base = new URL(config.baseUrl);
141
+ const init = {
142
+ method: tool.method,
143
+ headers: {
144
+ accept: "application/json",
145
+ authorization: `Bearer ${config.bearer}`,
146
+ "x-forwarded-proto": base.protocol.replace(/:$/, ""),
147
+ "x-forwarded-host": base.host,
148
+ ...headers
149
+ }
150
+ };
151
+ if (body !== void 0) {
152
+ init.headers["content-type"] = "application/json";
153
+ init.body = JSON.stringify(body);
154
+ }
155
+ const response = await doFetch(url.toString(), init);
156
+ const text = await response.text();
157
+ let parsed = text;
158
+ const contentType = response.headers.get("content-type") ?? "";
159
+ if (contentType.includes("application/json") && text) {
160
+ try {
161
+ parsed = JSON.parse(text);
162
+ } catch {
163
+ parsed = text;
164
+ }
165
+ }
166
+ return { status: response.status, ok: response.ok, body: parsed };
167
+ }
168
+ __name(dispatchTool, "dispatchTool");
169
+
170
+ // src/server/redact.ts
171
+ function stripPath(value, segments) {
172
+ if (value === null || typeof value !== "object") return;
173
+ if (Array.isArray(value)) {
174
+ value.forEach((entry) => stripPath(entry, segments));
175
+ return;
176
+ }
177
+ const [head, ...rest] = segments;
178
+ if (!head) return;
179
+ const record = value;
180
+ if (rest.length === 0) {
181
+ delete record[head];
182
+ return;
183
+ }
184
+ if (head in record) stripPath(record[head], rest);
185
+ }
186
+ __name(stripPath, "stripPath");
187
+ function redactResponseBody(body, paths) {
188
+ if (!paths?.length || body === null || typeof body !== "object") return body;
189
+ const clone = structuredClone(body);
190
+ paths.forEach((path) => stripPath(clone, path.split(".")));
191
+ return clone;
192
+ }
193
+ __name(redactResponseBody, "redactResponseBody");
194
+
195
+ // src/server/registry.ts
196
+ var HTTP_STATUS_META_KEY = "dispatch/httpStatus";
197
+ function textResult(value, isError, httpStatus) {
198
+ const text = typeof value === "string" ? value : JSON.stringify(value, null, 2);
199
+ const result = { content: [{ type: "text", text }], isError };
200
+ if (httpStatus !== void 0) {
201
+ result._meta = { [HTTP_STATUS_META_KEY]: httpStatus };
202
+ }
203
+ return result;
204
+ }
205
+ __name(textResult, "textResult");
206
+ function successfulResult(tool, value) {
207
+ const safe = redactResponseBody(value, tool.redactResponse);
208
+ const result = textResult(safe, false);
209
+ if (tool.outputSchema && safe !== null && typeof safe === "object" && !Array.isArray(safe)) {
210
+ result.structuredContent = safe;
211
+ }
212
+ return result;
213
+ }
214
+ __name(successfulResult, "successfulResult");
215
+ function createToolRegistry(options) {
216
+ const byName = new Map(options.tools.map((tool) => [tool.name, tool]));
217
+ return {
218
+ listTools(auth) {
219
+ return options.tools.filter(
220
+ (tool) => options.isVisible ? options.isVisible(tool, auth) : true
221
+ ).map((tool) => ({
222
+ name: tool.name,
223
+ description: tool.description,
224
+ inputSchema: tool.inputSchema,
225
+ ...tool.outputSchema ? { outputSchema: tool.outputSchema } : {},
226
+ annotations: tool.annotations
227
+ }));
228
+ },
229
+ async callTool(name, args, auth) {
230
+ const tool = byName.get(name);
231
+ if (!tool) return textResult(`Unknown tool: ${name}`, true);
232
+ try {
233
+ const result = await dispatchTool(tool, args, {
234
+ baseUrl: options.baseUrl,
235
+ bearer: auth.bearer,
236
+ fetchImpl: options.fetchImpl
237
+ });
238
+ return result.ok ? successfulResult(tool, result.body) : textResult(result.body, true, result.status);
239
+ } catch (error) {
240
+ const message = error instanceof Error ? error.message : String(error);
241
+ return textResult(`Tool dispatch failed: ${message}`, true);
242
+ }
243
+ }
244
+ };
245
+ }
246
+ __name(createToolRegistry, "createToolRegistry");
247
+
248
+ // src/server/jsonrpc.ts
249
+ var MCP_PROTOCOL_VERSION = "2025-06-18";
250
+ var UNAUTHORIZED_CODE = -32001;
251
+ var INVALID_REQUEST_CODE = -32600;
252
+ var METHOD_NOT_FOUND_CODE = -32601;
253
+ var INVALID_PARAMS_CODE = -32602;
254
+ function ok(id, result) {
255
+ return { jsonrpc: "2.0", id: id ?? null, result };
256
+ }
257
+ __name(ok, "ok");
258
+ function fail(id, code, message) {
259
+ return { jsonrpc: "2.0", id: id ?? null, error: { code, message } };
260
+ }
261
+ __name(fail, "fail");
262
+ function isWellFormed(request) {
263
+ return request != null && typeof request === "object" && typeof request.method === "string";
264
+ }
265
+ __name(isWellFormed, "isWellFormed");
266
+ async function handleToolsCall(request, registry, auth) {
267
+ if (!auth) return fail(request.id, UNAUTHORIZED_CODE, "Authentication required");
268
+ const params = request.params ?? {};
269
+ if (!params.name) return fail(request.id, INVALID_PARAMS_CODE, "Missing tool name");
270
+ const result = await registry.callTool(params.name, params.arguments ?? {}, auth);
271
+ return ok(request.id, result);
272
+ }
273
+ __name(handleToolsCall, "handleToolsCall");
274
+ function handleInitialize(request, options) {
275
+ return ok(request.id, {
276
+ protocolVersion: options.protocolVersion ?? MCP_PROTOCOL_VERSION,
277
+ // Deliberately does NOT claim `listChanged`: this transport has no
278
+ // server→client stream, so the notification could never be sent, and
279
+ // advertising it would stop a host from ever re-reading `tools/list`.
280
+ capabilities: { tools: {} },
281
+ serverInfo: options.serverInfo,
282
+ ...options.instructions ? { instructions: options.instructions } : {}
283
+ });
284
+ }
285
+ __name(handleInitialize, "handleInitialize");
286
+ async function handleMcpJsonRpc(request, registry, auth, options) {
287
+ if (!isWellFormed(request)) {
288
+ return fail(request?.id ?? null, INVALID_REQUEST_CODE, "Invalid Request");
289
+ }
290
+ switch (request.method) {
291
+ case "initialize":
292
+ return handleInitialize(request, options);
293
+ case "ping":
294
+ return ok(request.id, {});
295
+ case "tools/list":
296
+ return ok(request.id, { tools: registry.listTools(auth ?? void 0) });
297
+ case "tools/call":
298
+ return handleToolsCall(request, registry, auth);
299
+ default:
300
+ if (request.method.startsWith("notifications/")) return null;
301
+ return fail(request.id, METHOD_NOT_FOUND_CODE, `Method not found: ${request.method}`);
302
+ }
303
+ }
304
+ __name(handleMcpJsonRpc, "handleMcpJsonRpc");
305
+ export {
306
+ AI_CAPABILITIES,
307
+ AI_PERMISSION_MODEL,
308
+ DispatchInputError,
309
+ HTTP_STATUS_META_KEY,
310
+ MCP_PROTOCOL_VERSION,
311
+ PROTECTED_RESOURCE_METADATA_PATH,
312
+ UNAUTHORIZED_CODE,
313
+ UnsupportedSchemaError,
314
+ aiConnectPrompt,
315
+ aiHostGuides,
316
+ bearerChallenge,
317
+ buildAuthorizationServerMetadata,
318
+ buildManifest,
319
+ buildProtectedResourceMetadata,
320
+ createToolRegistry,
321
+ dispatchTool,
322
+ generateTools,
323
+ handleMcpJsonRpc,
324
+ inlineSchemaRefs,
325
+ providerForHostId,
326
+ serializeManifest,
327
+ serializeSurfaceLock,
328
+ surfaceDigest,
329
+ surfaceLockProblem
330
+ };
331
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/openapi/refs.ts","../src/dispatch/proxy.ts","../src/server/redact.ts","../src/server/registry.ts","../src/server/jsonrpc.ts"],"sourcesContent":["import type { JsonSchema } from \"../types\";\n\n/**\n * Raised when a JSON Schema cannot be turned into a flat, self-contained tool\n * input — an unresolvable `$ref`, an unsupported pointer, or a recursive schema.\n * The MCP tool surface is deliberately finite and flat (it is handed to an LLM\n * and committed to the drift manifest), so recursion is rejected rather than\n * silently truncated.\n */\nexport class UnsupportedSchemaError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"UnsupportedSchemaError\";\n }\n}\n\n/** Local-definition containers a `$ref` may point into, in resolution order. */\nconst REF_PREFIXES = [\"#/$defs/\", \"#/definitions/\", \"#/components/schemas/\"] as const;\nconst DEF_CONTAINERS = [\"$defs\", \"definitions\"] as const;\n\n/** The definition name a supported local pointer targets, or `null` if unsupported. */\nfunction refName(ref: string): string | null {\n const prefix = REF_PREFIXES.find((candidate) => ref.startsWith(candidate));\n return prefix ? decodeURIComponent(ref.slice(prefix.length)) : null;\n}\n\n/** Collect the `$defs`/`definitions` maps hoisted onto a schema root into one lookup. */\nfunction collectDefs(root: JsonSchema): Record<string, JsonSchema> {\n const defs: Record<string, JsonSchema> = {};\n DEF_CONTAINERS.forEach((key) => {\n const container = root[key];\n if (container && typeof container === \"object\") {\n Object.assign(defs, container as Record<string, JsonSchema>);\n }\n });\n return defs;\n}\n\nfunction inlineRef(\n ref: string,\n defs: Record<string, JsonSchema>,\n active: Set<string>,\n): unknown {\n const name = refName(ref);\n if (name === null) throw new UnsupportedSchemaError(`Unsupported $ref pointer: ${ref}`);\n const target = defs[name];\n if (!target) throw new UnsupportedSchemaError(`Unresolved $ref: ${ref}`);\n if (active.has(name)) throw new UnsupportedSchemaError(`Recursive schema not supported: ${name}`);\n active.add(name);\n const resolved = walk(target, defs, active);\n active.delete(name);\n return resolved;\n}\n\n/** Deep-copy `node`, inlining every `$ref` and stripping definition containers. */\nfunction walk(node: unknown, defs: Record<string, JsonSchema>, active: Set<string>): unknown {\n if (Array.isArray(node)) return node.map((item) => walk(item, defs, active));\n if (!node || typeof node !== \"object\") return node;\n\n const obj = node as Record<string, unknown>;\n if (typeof obj.$ref === \"string\") return inlineRef(obj.$ref, defs, active);\n\n const out: Record<string, unknown> = {};\n Object.entries(obj).forEach(([key, value]) => {\n if (!DEF_CONTAINERS.includes(key as (typeof DEF_CONTAINERS)[number])) {\n out[key] = walk(value, defs, active);\n }\n });\n return out;\n}\n\n/**\n * Inline every local `$ref` in a JSON Schema and drop the now-empty `$defs`/\n * `definitions` containers, yielding a flat, self-contained schema. Diamond reuse\n * (the same definition referenced by sibling branches) is fine; only a true cycle\n * — a definition that references itself up the resolution stack — is rejected.\n *\n * A schema with no `$ref`/definitions is returned structurally unchanged, so\n * inlining an already-flat spec is a no-op (the drift gate stays a stable diff).\n */\nexport function inlineSchemaRefs(schema: JsonSchema): JsonSchema {\n const defs = collectDefs(schema);\n return walk(schema, defs, new Set<string>()) as JsonSchema;\n}\n","import type { DispatchConfig, DispatchResult, GeneratedTool } from \"../types\";\n\n/** Raised when tool arguments cannot be routed onto the HTTP request. */\nexport class DispatchInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DispatchInputError\";\n }\n}\n\n/** Expand a path template (`/products/{id}`) using the path args, URL-encoding each. */\nfunction expandPath(\n tool: GeneratedTool,\n args: Record<string, unknown>,\n): string {\n return tool.path.replace(/\\{([^}]+)\\}/g, (_match, key: string) => {\n const value = args[key];\n if (value === undefined || value === null) {\n throw new DispatchInputError(`Missing required path parameter: ${key}`);\n }\n return encodeURIComponent(String(value));\n });\n}\n\n/**\n * Route the non-path parameters (query + header) from the flat args. A missing\n * required parameter is a hard error; a missing optional one is simply omitted.\n */\nfunction routeParams(\n tool: GeneratedTool,\n args: Record<string, unknown>,\n): { query: URLSearchParams; headers: Record<string, string> } {\n const query = new URLSearchParams();\n const headers: Record<string, string> = {};\n\n tool.parameters\n .filter((param) => param.in !== \"path\")\n .forEach((param) => {\n const value = args[param.name];\n if (value === undefined || value === null) {\n if (param.required) {\n throw new DispatchInputError(`Missing required ${param.in} parameter: ${param.name}`);\n }\n return;\n }\n if (param.in === \"query\") query.set(param.name, String(value));\n else headers[param.name] = String(value);\n });\n\n return { query, headers };\n}\n\n/**\n * Reconstruct the request body from the flat args using the routing metadata.\n * Anything not claimed by a known body property is dropped — the input schema is\n * `additionalProperties: false`, so a validated call never carries extras and an\n * unvalidated one cannot smuggle fields upstream.\n */\nfunction routeBody(tool: GeneratedTool, args: Record<string, unknown>): unknown {\n if (tool.bodyIsWhole) return args.body;\n if (!tool.bodyProps.length) return undefined;\n const payload: Record<string, unknown> = {};\n tool.bodyProps.forEach((key) => {\n if (args[key] !== undefined) payload[key] = args[key];\n });\n return Object.keys(payload).length ? payload : undefined;\n}\n\n/**\n * Execute one generated tool by proxying to its HTTP endpoint, forwarding the\n * caller's bearer verbatim. This function performs NO authorization — the\n * endpoint does, exactly as it would for a first-party request. That is the whole\n * point of the passthrough: the agent can do precisely what the user can.\n */\nexport async function dispatchTool(\n tool: GeneratedTool,\n args: Record<string, unknown>,\n config: DispatchConfig,\n): Promise<DispatchResult> {\n const doFetch = config.fetchImpl ?? fetch;\n const pathname = expandPath(tool, args);\n const { query, headers } = routeParams(tool, args);\n const body = routeBody(tool, args);\n\n const url = new URL(pathname, config.baseUrl);\n for (const [key, value] of query) url.searchParams.set(key, value);\n\n // Carry the proxy origin as the standard reverse-proxy forwarded headers. The\n // wrapped endpoint's auth guard re-derives the request origin (to check the\n // access token's `aud`) WITHOUT a request object, so it can only see the origin\n // through these headers. `baseUrl` is exactly the origin the token was minted\n // and transport-verified against, so forwarding its scheme+host makes the\n // wrapped guard reconstruct the SAME origin — the `aud` survives the replay in\n // both dev (http) and prod (any proxied https origin). Omitting them let the\n // guard default the scheme to https and 401 a valid http-minted bearer.\n const base = new URL(config.baseUrl);\n\n const init: RequestInit = {\n method: tool.method,\n headers: {\n accept: \"application/json\",\n authorization: `Bearer ${config.bearer}`,\n \"x-forwarded-proto\": base.protocol.replace(/:$/, \"\"),\n \"x-forwarded-host\": base.host,\n ...headers,\n },\n };\n if (body !== undefined) {\n (init.headers as Record<string, string>)[\"content-type\"] = \"application/json\";\n init.body = JSON.stringify(body);\n }\n\n const response = await doFetch(url.toString(), init);\n const text = await response.text();\n let parsed: unknown = text;\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\") && text) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = text;\n }\n }\n\n return { status: response.status, ok: response.ok, body: parsed };\n}\n","/**\n * Strip audited-sensitive fields out of a tool result before it reaches the\n * agent.\n *\n * The dispatcher forwards the wrapped endpoint's response body verbatim, so a\n * narrowed `outputSchema` alone would only change what the manifest CLAIMS is\n * returned. This module is what actually removes the value, keeping the served\n * payload and the advertised schema in agreement.\n */\n\n/** Walk one dotted path, mapping over arrays, and delete the leaf. */\nfunction stripPath(value: unknown, segments: readonly string[]): void {\n if (value === null || typeof value !== \"object\") return;\n\n if (Array.isArray(value)) {\n value.forEach((entry) => stripPath(entry, segments));\n return;\n }\n\n const [head, ...rest] = segments;\n if (!head) return;\n\n const record = value as Record<string, unknown>;\n if (rest.length === 0) {\n delete record[head];\n return;\n }\n if (head in record) stripPath(record[head], rest);\n}\n\n/**\n * Return `body` without the listed dotted paths.\n *\n * The input is deep-cloned first: dispatch results are handed straight to the\n * JSON-RPC encoder AND reused as `structuredContent`, so mutating in place\n * could leak a half-redacted object into one of the two surfaces.\n */\nexport function redactResponseBody(\n body: unknown,\n paths: readonly string[] | undefined,\n): unknown {\n if (!paths?.length || body === null || typeof body !== \"object\") return body;\n\n const clone = structuredClone(body);\n paths.forEach((path) => stripPath(clone, path.split(\".\")));\n return clone;\n}\n","import { dispatchTool } from \"../dispatch/proxy\";\nimport type {\n GeneratedTool,\n JsonSchema,\n RequestAuth,\n ToolAnnotations,\n} from \"../types\";\nimport { redactResponseBody } from \"./redact\";\n\n/**\n * The registry is the transport-agnostic seam between the generated tools and the\n * MCP SDK. The consuming app owns the HTTP/JSON-RPC transport (mounting it at\n * `/api/mcp`) and, per request, resolves {@link RequestAuth} and calls\n * {@link ToolRegistry.listTools} / {@link ToolRegistry.callTool}. Keeping the\n * SDK out of this package means the core stays testable and portable.\n */\n\n/** An MCP tool descriptor as advertised to clients (subset of the MCP schema). */\nexport interface McpToolDescriptor {\n name: string;\n description: string;\n inputSchema: JsonSchema;\n outputSchema?: JsonSchema;\n annotations: ToolAnnotations;\n}\n\n/**\n * `_meta` key carrying the upstream HTTP status of a dispatched call.\n *\n * `isError` is one bit, and it collapses answers that mean opposite things: a\n * 404 for a record that does not exist, a 403 a guard correctly refused, a\n * domain refusal (\"this store does not use comandas\"), and a 500 where the route\n * threw all arrive identical. Callers that need to tell \"correctly refused\" from\n * \"actually broken\" — `mcp:smoke` above all — cannot, because the status is\n * known at dispatch and then dropped. Publishing it under a namespaced `_meta`\n * key (permitted by the MCP result schema) keeps `isError` as the agent-facing\n * signal while making the distinction recoverable.\n */\nexport const HTTP_STATUS_META_KEY = \"dispatch/httpStatus\";\n\n/** An MCP tool-call result (subset of the MCP schema). */\nexport interface McpToolResult {\n content: Array<{ type: \"text\"; text: string }>;\n isError: boolean;\n /** Machine-readable output matching the advertised outputSchema. */\n structuredContent?: Record<string, unknown>;\n /** Out-of-band metadata; carries {@link HTTP_STATUS_META_KEY} when dispatched. */\n _meta?: Record<string, unknown>;\n}\n\nexport interface ToolRegistry {\n listTools(auth?: RequestAuth): McpToolDescriptor[];\n callTool(\n name: string,\n args: Record<string, unknown>,\n auth: RequestAuth,\n ): Promise<McpToolResult>;\n}\n\nexport interface RegistryOptions {\n tools: GeneratedTool[];\n /** Origin the tools proxy to (usually the app's own public URL). */\n baseUrl: string;\n fetchImpl?: typeof fetch;\n /**\n * Optional visibility filter — e.g. hide mutating tools, or tools whose\n * required scope the caller lacks. Authorization is still enforced upstream;\n * this only shapes what the agent is shown.\n */\n isVisible?: (tool: GeneratedTool, auth?: RequestAuth) => boolean;\n}\n\nfunction textResult(\n value: unknown,\n isError: boolean,\n httpStatus?: number,\n): McpToolResult {\n const text =\n typeof value === \"string\" ? value : JSON.stringify(value, null, 2);\n const result: McpToolResult = { content: [{ type: \"text\", text }], isError };\n if (httpStatus !== undefined) {\n result._meta = { [HTTP_STATUS_META_KEY]: httpStatus };\n }\n return result;\n}\n\nfunction successfulResult(tool: GeneratedTool, value: unknown): McpToolResult {\n // Redact BEFORE rendering the text block: the agent reads `content` even when\n // it ignores `structuredContent`, so stripping only the latter would still\n // hand over the field.\n const safe = redactResponseBody(value, tool.redactResponse);\n const result = textResult(safe, false);\n if (\n tool.outputSchema &&\n safe !== null &&\n typeof safe === \"object\" &&\n !Array.isArray(safe)\n ) {\n result.structuredContent = safe as Record<string, unknown>;\n }\n return result;\n}\n\nexport function createToolRegistry(options: RegistryOptions): ToolRegistry {\n const byName = new Map(options.tools.map((tool) => [tool.name, tool]));\n\n return {\n listTools(auth) {\n return options.tools\n .filter((tool) =>\n options.isVisible ? options.isVisible(tool, auth) : true,\n )\n .map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),\n annotations: tool.annotations,\n }));\n },\n\n async callTool(name, args, auth) {\n const tool = byName.get(name);\n if (!tool) return textResult(`Unknown tool: ${name}`, true);\n\n try {\n const result = await dispatchTool(tool, args, {\n baseUrl: options.baseUrl,\n bearer: auth.bearer,\n fetchImpl: options.fetchImpl,\n });\n // A non-2xx from the endpoint (e.g. 403 tenant-forbidden) is surfaced to\n // the agent as an error result, NOT thrown — the permission decision was\n // made upstream and its message is the useful signal. The status rides\n // along in `_meta` so a caller can tell a correct refusal from a break.\n return result.ok\n ? successfulResult(tool, result.body)\n : textResult(result.body, true, result.status);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return textResult(`Tool dispatch failed: ${message}`, true);\n }\n },\n };\n}\n","import type { RequestAuth } from \"../types\";\n\nimport type { ToolRegistry } from \"./registry\";\n\n/**\n * The MCP JSON-RPC 2.0 request half of the Streamable HTTP transport.\n *\n * Implemented directly rather than via the MCP SDK because the SDK's transport is\n * Node-`http` oriented, and a host serving Web `Request`/`Response` (a Next route\n * handler, a Hono route) has no `http.IncomingMessage` to hand it. It covers the\n * methods a client needs to discover and call tools: `initialize`, `tools/list`,\n * `tools/call`, plus `ping`.\n *\n * WHAT IS MECHANISM AND LIVES HERE: the envelope, the method table, the error\n * codes, the well-formedness rule, and the notification convention. None of it\n * varies per host — it is JSON-RPC 2.0 and the MCP specification.\n *\n * WHAT IS VOCABULARY AND STAYS WITH THE HOST: the server's NAME, its version, and\n * the `instructions` string an agent reads on connect. Those describe one\n * particular product's tool surface, so they arrive as {@link McpJsonRpcOptions}\n * rather than being written here.\n */\n\n/** The MCP protocol revision this transport implements. */\nexport const MCP_PROTOCOL_VERSION = \"2025-06-18\";\n\n/**\n * JSON-RPC error code for \"authentication required\", returned by `tools/call`\n * when the request carried no valid bearer. Outside the reserved -32768..-32000\n * band's *defined* codes on purpose: it is an implementation-defined server\n * error, and a host maps it to HTTP 401.\n */\nexport const UNAUTHORIZED_CODE = -32001;\n\n/** JSON-RPC \"Invalid Request\" — a payload that isn't a well-formed request object. */\nconst INVALID_REQUEST_CODE = -32600;\n\n/** JSON-RPC \"Method not found\". */\nconst METHOD_NOT_FOUND_CODE = -32601;\n\n/** JSON-RPC \"Invalid params\". */\nconst INVALID_PARAMS_CODE = -32602;\n\nexport interface JsonRpcRequest {\n jsonrpc: \"2.0\";\n id?: string | number | null;\n method: string;\n params?: unknown;\n}\n\nexport interface JsonRpcResponse {\n jsonrpc: \"2.0\";\n id: string | number | null;\n result?: unknown;\n error?: { code: number; message: string };\n}\n\n/** What a client is told it connected to, in `initialize`'s `serverInfo`. */\nexport interface McpServerInfo {\n /** The server's name, as a connected host displays it. */\n name: string;\n /**\n * The advertised surface version.\n *\n * This is the ONLY signal a client gets that the tool surface changed: the\n * transport is request/response only, so `notifications/tools/list_changed`\n * can never be sent, and a host that cached `tools/list` at the handshake has\n * no other reason to ask again. See `server/surface-lock.ts` for the guard\n * that makes forgetting to move it a build error instead of a comment.\n */\n version: string;\n}\n\nexport interface McpJsonRpcOptions {\n /** The host's identity, returned verbatim in `initialize`. */\n serverInfo: McpServerInfo;\n /**\n * Server-level guidance surfaced to the model on `initialize` (the MCP spec's\n * optional `instructions` field). Omitted from the result when absent, rather\n * than sent empty — a blank string is a claim that there is guidance.\n */\n instructions?: string;\n /**\n * Override the advertised protocol revision. Defaults to\n * {@link MCP_PROTOCOL_VERSION}; a host should not normally set it.\n */\n protocolVersion?: string;\n}\n\nfunction ok(id: JsonRpcRequest[\"id\"], result: unknown): JsonRpcResponse {\n return { jsonrpc: \"2.0\", id: id ?? null, result };\n}\n\nfunction fail(id: JsonRpcRequest[\"id\"], code: number, message: string): JsonRpcResponse {\n return { jsonrpc: \"2.0\", id: id ?? null, error: { code, message } };\n}\n\n/** A parsed body is a usable request only if it's an object carrying a string `method`. */\nfunction isWellFormed(request: JsonRpcRequest): boolean {\n return request != null && typeof request === \"object\" && typeof request.method === \"string\";\n}\n\nasync function handleToolsCall(\n request: JsonRpcRequest,\n registry: ToolRegistry,\n auth: RequestAuth | null,\n): Promise<JsonRpcResponse> {\n if (!auth) return fail(request.id, UNAUTHORIZED_CODE, \"Authentication required\");\n const params = (request.params ?? {}) as { name?: string; arguments?: Record<string, unknown> };\n if (!params.name) return fail(request.id, INVALID_PARAMS_CODE, \"Missing tool name\");\n const result = await registry.callTool(params.name, params.arguments ?? {}, auth);\n return ok(request.id, result);\n}\n\nfunction handleInitialize(\n request: JsonRpcRequest,\n options: McpJsonRpcOptions,\n): JsonRpcResponse {\n return ok(request.id, {\n protocolVersion: options.protocolVersion ?? MCP_PROTOCOL_VERSION,\n // Deliberately does NOT claim `listChanged`: this transport has no\n // server→client stream, so the notification could never be sent, and\n // advertising it would stop a host from ever re-reading `tools/list`.\n capabilities: { tools: {} },\n serverInfo: options.serverInfo,\n ...(options.instructions ? { instructions: options.instructions } : {}),\n });\n}\n\n/**\n * Handle one MCP JSON-RPC request.\n *\n * Returns `null` for notifications (no id, no reply expected). `auth` is the\n * verified caller identity, or `null` when the request carried no valid bearer —\n * `tools/call` then returns {@link UNAUTHORIZED_CODE}, which the host surfaces as\n * HTTP 401. Discovery (`initialize`, `ping`, `tools/list`) stays open, so a client\n * can read the surface before it has a token.\n */\nexport async function handleMcpJsonRpc(\n request: JsonRpcRequest,\n registry: ToolRegistry,\n auth: RequestAuth | null,\n options: McpJsonRpcOptions,\n): Promise<JsonRpcResponse | null> {\n // A host casts the parsed body to JsonRpcRequest without validating it, so a\n // malformed payload can arrive here: a `null` body/batch element, a non-object,\n // or an object with no `method`. Reject any of these as Invalid Request rather\n // than dereferencing `request`/`request.method` and throwing a 500 below.\n if (!isWellFormed(request)) {\n return fail(request?.id ?? null, INVALID_REQUEST_CODE, \"Invalid Request\");\n }\n switch (request.method) {\n case \"initialize\":\n return handleInitialize(request, options);\n case \"ping\":\n return ok(request.id, {});\n case \"tools/list\":\n return ok(request.id, { tools: registry.listTools(auth ?? undefined) });\n case \"tools/call\":\n return handleToolsCall(request, registry, auth);\n default:\n // JSON-RPC notifications (`notifications/*`) expect no reply — silently\n // ignore any we don't explicitly handle, rather than returning an error.\n if (request.method.startsWith(\"notifications/\")) return null;\n return fail(request.id, METHOD_NOT_FOUND_CODE, `Method not found: ${request.method}`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AASO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EATlD,OASkD;AAAA;AAAA;AAAA,EAChD,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAGA,IAAM,eAAe,CAAC,YAAY,kBAAkB,uBAAuB;AAC3E,IAAM,iBAAiB,CAAC,SAAS,aAAa;AAG9C,SAAS,QAAQ,KAA4B;AAC3C,QAAM,SAAS,aAAa,KAAK,CAAC,cAAc,IAAI,WAAW,SAAS,CAAC;AACzE,SAAO,SAAS,mBAAmB,IAAI,MAAM,OAAO,MAAM,CAAC,IAAI;AACjE;AAHS;AAMT,SAAS,YAAY,MAA8C;AACjE,QAAM,OAAmC,CAAC;AAC1C,iBAAe,QAAQ,CAAC,QAAQ;AAC9B,UAAM,YAAY,KAAK,GAAG;AAC1B,QAAI,aAAa,OAAO,cAAc,UAAU;AAC9C,aAAO,OAAO,MAAM,SAAuC;AAAA,IAC7D;AAAA,EACF,CAAC;AACD,SAAO;AACT;AATS;AA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