@happyvertical/smrt-app-mcp 0.40.60 → 0.40.62

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/README.md CHANGED
@@ -2,8 +2,11 @@
2
2
 
3
3
  App-runtime MCP server scaffolding for s-m-r-t apps. Provides:
4
4
 
5
- - **Core** — `createMcpAppServer({ smrtOptions, serverInfo, allowedClassNames, publicToolPatterns?, toolPolicy?, workflowAssertions? })` returning `{ listTools, callTool }` wired to `@happyvertical/smrt-core/generators/mcp`.
6
- - **SvelteKit adapters** (`./sveltekit`) — `mountMcpToolsRoute` / `mountMcpCallRoute` for `/api/mcp/{tools,call}/+server.ts`.
5
+ - **Core** — `createMcpAppServer({ smrtOptions, serverInfo, allowedClassNames, publicToolPatterns?, toolListCache?, toolPolicy?, workflowAssertions? })` returning `{ listTools, callTool }` wired to `@happyvertical/smrt-core/generators/mcp`.
6
+ - **SvelteKit adapters** (`./sveltekit`) — `mountMcpRoute` mounts a modern
7
+ 2026-07-28 stateless Streamable HTTP MCP endpoint. The REST-shaped
8
+ `mountMcpToolsRoute` / `mountMcpCallRoute` aliases remain available for one
9
+ release while applications migrate.
7
10
 
8
11
  For piping a deployed app's MCP surface to a local stdio MCP client, see `@happyvertical/smrt-app-cli` — the client-side runtime CLI exposes a `startMcpBridge()` default and a generic `smrt-mcp-bridge` bin.
9
12
 
@@ -41,6 +44,57 @@ export const mcpServer = createMcpAppServer({
41
44
  });
42
45
  ```
43
46
 
47
+ ```ts
48
+ // src/routes/api/mcp/+server.ts
49
+ import { mountMcpRoute } from '@happyvertical/smrt-app-mcp/sveltekit';
50
+ import { mcpServer } from '$lib/server/mcp';
51
+ export const POST = mountMcpRoute(mcpServer);
52
+ ```
53
+
54
+ `mountMcpRoute` is a modern-only, fetch-style Streamable HTTP endpoint. It
55
+ serves `server/discover`, `tools/list`, and `tools/call` with the SDK's
56
+ 2026-07-28 envelope. It advertises the optional
57
+ `io.modelcontextprotocol/tasks` extension only when an allowed object enables
58
+ MCP tasks (`mcp: { tasks: [...] }`); task-aware clients can then call
59
+ `tasks/get`, `tasks/update`, and `tasks/cancel`. Application deployments must
60
+ run a `TaskRunner` for the `mcp-tasks` queue. Task lifecycle operations require
61
+ a stable authenticated principal id; include its `tenantId` in the principal
62
+ when the application uses tenant-scoped objects. Tool discovery is deterministically
63
+ ordered by name. Stock MCP clients send the required
64
+ `Mcp-Method` header (and `Mcp-Name` for `tools/call`); the mount validates them
65
+ against the JSON-RPC body and returns the protocol `HeaderMismatch` error
66
+ (`-32020`, HTTP 400) for a missing or mismatched header.
67
+
68
+ `tools/list` emits the required cache metadata with a one-day, `private`
69
+ default. Shared (`public`) caching is intentionally exceptional: set
70
+ `toolListCache: { cacheScope: 'public', publicCatalog: true }` only for a
71
+ reviewed catalog where every allowed tool is unauthenticated, read-only, and
72
+ global. The server verifies that shape (including the absence of tenant-scoped
73
+ tools and principal-aware policy) and falls back to `private` otherwise.
74
+
75
+ The route constructs a fresh protocol server for every HTTP request. It does
76
+ not issue or rely on `Mcp-Session-Id`, sticky load-balancer routing, or a held
77
+ SSE connection, so it is safe behind ordinary round-robin deployment. This
78
+ mount exposes no subscription capability; subscription requests are refused as
79
+ a JSON-RPC error before any SSE stream opens. Persist stateful workflow
80
+ progress in application objects, then pass their explicit s-m-r-t object id
81
+ back to the next tool call:
82
+
83
+ ```ts
84
+ // `basket_create` returns an object with id "basket-123".
85
+ await client.callTool({
86
+ name: 'basket_additem',
87
+ arguments: { id: 'basket-123', productId: 'product-456' },
88
+ });
89
+ ```
90
+
91
+ ## Deprecated REST compatibility
92
+
93
+ For one release, applications that have not moved their route path can retain
94
+ the old handlers below. They are REST-shaped compatibility aliases, not an MCP
95
+ transport, and will be removed after the migration window. Direct calls to a
96
+ tool outside the app allow-list continue to receive the safe 404 behavior.
97
+
44
98
  ```ts
45
99
  // src/routes/api/mcp/tools/+server.ts
46
100
  import { mountMcpToolsRoute } from '@happyvertical/smrt-app-mcp/sveltekit';
@@ -0,0 +1,99 @@
1
+ import { ProtocolError, ProtocolErrorCode, Server } from "@modelcontextprotocol/server";
2
+ //#region src/errors.ts
3
+ var MCP_TOOL_ACCESS_DENIED_CODE = "mcp_tool_access_denied";
4
+ var McpAccessError = class extends Error {
5
+ constructor(status, message, metadata = {}) {
6
+ super(message);
7
+ this.status = status;
8
+ this.metadata = metadata;
9
+ this.name = "McpAccessError";
10
+ }
11
+ status;
12
+ metadata;
13
+ };
14
+ //#endregion
15
+ //#region src/tools.ts
16
+ function matchesToolPattern(toolName, pattern) {
17
+ if (!pattern) return false;
18
+ if (pattern === "*") return true;
19
+ const parts = pattern.split("*");
20
+ if (parts.length === 1) return toolName === pattern;
21
+ let cursor = 0;
22
+ if (parts[0] && !toolName.startsWith(parts[0])) return false;
23
+ for (const part of parts) {
24
+ if (!part) continue;
25
+ const index = toolName.indexOf(part, cursor);
26
+ if (index < 0) return false;
27
+ cursor = index + part.length;
28
+ }
29
+ const last = parts.at(-1);
30
+ return !last || toolName.endsWith(last);
31
+ }
32
+ function isReadOnlyToolName(toolName) {
33
+ return toolName.endsWith("_list") || toolName.endsWith("_get");
34
+ }
35
+ function isPublicToolName(toolName, patterns) {
36
+ return isReadOnlyToolName(toolName) && patterns.some((pattern) => matchesToolPattern(toolName, pattern));
37
+ }
38
+ function classNamePrefixes(classNames) {
39
+ return new Set(classNames.map((className) => `${className.toLowerCase()}_`));
40
+ }
41
+ function isAllowedCoreTool(toolName, prefixes) {
42
+ for (const prefix of prefixes) if (toolName.startsWith(prefix)) return true;
43
+ return false;
44
+ }
45
+ function compareMcpToolNames(left, right) {
46
+ return left < right ? -1 : left > right ? 1 : 0;
47
+ }
48
+ //#endregion
49
+ //#region src/protocol.ts
50
+ var MCP_TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
51
+ var DEFAULT_TOOL_LIST_CACHE_HINT = {
52
+ ttlMs: 864e5,
53
+ cacheScope: "private"
54
+ };
55
+ async function resolvePrincipal(option, context) {
56
+ if (typeof option === "function") return await option(context) ?? null;
57
+ return option ?? null;
58
+ }
59
+ function createMcpProtocolServer(appServer, options = {}) {
60
+ const tasksEnabled = appServer.tasksEnabled && typeof options.principal !== "function" && Boolean(options.principal?.id);
61
+ const server = new Server(appServer.serverInfo, {
62
+ capabilities: {
63
+ tools: {},
64
+ ...tasksEnabled ? { extensions: { [MCP_TASKS_EXTENSION]: {} } } : {}
65
+ },
66
+ cacheHints: { "tools/list": DEFAULT_TOOL_LIST_CACHE_HINT }
67
+ });
68
+ server.setRequestHandler("tools/list", async (_request, context) => {
69
+ const principal = await resolvePrincipal(options.principal, context);
70
+ const cacheHint = await appServer.getToolsListCacheHint?.() ?? DEFAULT_TOOL_LIST_CACHE_HINT;
71
+ return {
72
+ tools: [...await appServer.listTools({ principal })].sort((left, right) => compareMcpToolNames(left.name, right.name)),
73
+ ...cacheHint
74
+ };
75
+ });
76
+ server.setRequestHandler("tools/call", async (request, context) => {
77
+ try {
78
+ return await appServer.callTool({
79
+ name: request.params.name,
80
+ arguments: request.params.arguments,
81
+ principal: await resolvePrincipal(options.principal, context)
82
+ });
83
+ } catch (error) {
84
+ if (error instanceof McpAccessError) {
85
+ const { code, retryable } = error.metadata;
86
+ throw new ProtocolError(error.status === 404 ? ProtocolErrorCode.InvalidParams : ProtocolErrorCode.InvalidRequest, error.message, {
87
+ ...typeof code === "string" ? { code } : {},
88
+ ...typeof retryable === "boolean" ? { retryable } : {}
89
+ });
90
+ }
91
+ throw error;
92
+ }
93
+ });
94
+ return server;
95
+ }
96
+ //#endregion
97
+ export { isAllowedCoreTool as a, matchesToolPattern as c, compareMcpToolNames as i, MCP_TOOL_ACCESS_DENIED_CODE as l, createMcpProtocolServer as n, isPublicToolName as o, classNamePrefixes as r, isReadOnlyToolName as s, MCP_TASKS_EXTENSION as t, McpAccessError as u };
98
+
99
+ //# sourceMappingURL=protocol-DoieND6v.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol-DoieND6v.js","names":[],"sources":["../../src/errors.ts","../../src/tools.ts","../../src/protocol.ts"],"sourcesContent":["/** Machine-readable code for a principal policy denial. */\nexport const MCP_TOOL_ACCESS_DENIED_CODE = 'mcp_tool_access_denied';\n\n/**\n * Metadata that is safe to expose for an app-MCP access failure. Policy\n * implementations must not place principal, scope, tool, or internal-error\n * details here.\n */\nexport interface McpAccessErrorMetadata {\n code?: string;\n retryable?: boolean;\n}\n\n/**\n * Error returned by the MCP app server when a caller tries to use a tool\n * they are not allowed to access. The HTTP layer should map `status` onto\n * the response status code.\n */\nexport class McpAccessError extends Error {\n constructor(\n readonly status: number,\n message: string,\n readonly metadata: McpAccessErrorMetadata = {},\n ) {\n super(message);\n this.name = 'McpAccessError';\n }\n}\n","/**\n * Tool-name policy helpers — used by `McpAppServer` to filter the full set\n * of generated tools down to what the calling principal is allowed to see,\n * and to decide whether an unauthenticated tool call should be permitted.\n *\n * @packageDocumentation\n */\n\n/**\n * Match a tool name against a glob-ish pattern with `*` wildcards.\n *\n * - Empty pattern → never matches.\n * - `*` → matches everything.\n * - `prefix_*` → matches anything starting with `prefix_`.\n * - `*_suffix` → matches anything ending with `_suffix`.\n * - `a_*_b` → matches any name containing `a_`, then any text, then `_b`.\n *\n * No regex characters are special besides `*` — the input is treated as a\n * literal string with star wildcards.\n */\nexport function matchesToolPattern(toolName: string, pattern: string): boolean {\n if (!pattern) return false;\n if (pattern === '*') return true;\n\n const parts = pattern.split('*');\n if (parts.length === 1) return toolName === pattern;\n\n let cursor = 0;\n if (parts[0] && !toolName.startsWith(parts[0])) return false;\n for (const part of parts) {\n if (!part) continue;\n const index = toolName.indexOf(part, cursor);\n if (index < 0) return false;\n cursor = index + part.length;\n }\n\n const last = parts.at(-1);\n return !last || toolName.endsWith(last);\n}\n\n/**\n * Read-only tool detection. Generated SMRT MCP tools follow the naming\n * convention `<class>_<verb>`; we treat `_list` and `_get` as read-only.\n */\nexport function isReadOnlyToolName(toolName: string): boolean {\n return toolName.endsWith('_list') || toolName.endsWith('_get');\n}\n\n/**\n * Check whether a tool name is currently allowed for unauthenticated callers\n * given the configured public-tool patterns. Only read-only tools may ever\n * be public, regardless of pattern.\n */\nexport function isPublicToolName(\n toolName: string,\n patterns: readonly string[],\n): boolean {\n return (\n isReadOnlyToolName(toolName) &&\n patterns.some((pattern) => matchesToolPattern(toolName, pattern))\n );\n}\n\n/**\n * Lower-case `<class>_` prefixes the app considers \"allowed core tools\"\n * given a list of SMRT class names. Used to build the allow-list for\n * `McpAppServer.listTools`.\n */\nexport function classNamePrefixes(\n classNames: readonly string[],\n): ReadonlySet<string> {\n return new Set(classNames.map((className) => `${className.toLowerCase()}_`));\n}\n\n/**\n * Whether a given tool name starts with any of the configured class\n * prefixes.\n */\nexport function isAllowedCoreTool(\n toolName: string,\n prefixes: ReadonlySet<string>,\n): boolean {\n for (const prefix of prefixes) {\n if (toolName.startsWith(prefix)) return true;\n }\n return false;\n}\n\n/**\n * Compare tool names by Unicode code unit, rather than the host locale, so a\n * catalog has one byte-stable order across every runtime.\n */\nexport function compareMcpToolNames(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n","/** MCP SDK v2 protocol adapter for the framework-neutral app server core. */\nimport {\n type CallToolResult,\n ProtocolError,\n ProtocolErrorCode,\n Server,\n type ServerContext,\n type Tool,\n} from '@modelcontextprotocol/server';\nimport { McpAccessError } from './errors.js';\nimport type { McpAppPrincipal, McpAppServer } from './server.js';\nimport { compareMcpToolNames } from './tools.js';\n\nexport const MCP_TASKS_EXTENSION = 'io.modelcontextprotocol/tasks';\n\nconst DEFAULT_TOOL_LIST_CACHE_HINT = {\n ttlMs: 86_400_000,\n cacheScope: 'private' as const,\n};\n\nexport interface McpProtocolServerOptions {\n /** Resolve the authenticated application principal for each MCP request. */\n principal?:\n | McpAppPrincipal\n | null\n | ((\n context: ServerContext,\n ) => McpAppPrincipal | null | Promise<McpAppPrincipal | null>);\n}\n\nasync function resolvePrincipal(\n option: McpProtocolServerOptions['principal'],\n context: ServerContext,\n): Promise<McpAppPrincipal | null> {\n if (typeof option === 'function') return (await option(context)) ?? null;\n return option ?? null;\n}\n\n/**\n * Adapt an app MCP core to the SDK v2 low-level server protocol.\n *\n * Transport ownership remains with the caller. In particular, this does not\n * add a production HTTP endpoint; it is safe to compose with `serveStdio` or\n * `createMcpHandler` in a deployment that supplies its own authentication.\n */\nexport function createMcpProtocolServer(\n appServer: McpAppServer,\n options: McpProtocolServerOptions = {},\n): Server {\n // Task lifecycle records are owner-scoped. Unlike ordinary public read-only\n // tools, they cannot be safely exposed without a stable principal id.\n const tasksEnabled =\n appServer.tasksEnabled &&\n typeof options.principal !== 'function' &&\n Boolean(options.principal?.id);\n const server = new Server(appServer.serverInfo, {\n capabilities: {\n tools: {},\n ...(tasksEnabled ? { extensions: { [MCP_TASKS_EXTENSION]: {} } } : {}),\n } as never,\n cacheHints: { 'tools/list': DEFAULT_TOOL_LIST_CACHE_HINT },\n });\n\n server.setRequestHandler('tools/list', async (_request, context) => {\n const principal = await resolvePrincipal(options.principal, context);\n const cacheHint =\n (await appServer.getToolsListCacheHint?.()) ??\n DEFAULT_TOOL_LIST_CACHE_HINT;\n return {\n tools: [...(await appServer.listTools({ principal }))].sort(\n (left, right) => compareMcpToolNames(left.name, right.name),\n ) as Tool[],\n ...cacheHint,\n };\n });\n\n server.setRequestHandler('tools/call', async (request, context) => {\n try {\n return (await appServer.callTool({\n name: request.params.name,\n arguments: request.params.arguments,\n principal: await resolvePrincipal(options.principal, context),\n })) as CallToolResult;\n } catch (error) {\n if (error instanceof McpAccessError) {\n const { code, retryable } = error.metadata;\n throw new ProtocolError(\n error.status === 404\n ? ProtocolErrorCode.InvalidParams\n : ProtocolErrorCode.InvalidRequest,\n error.message,\n {\n ...(typeof code === 'string' ? { code } : {}),\n ...(typeof retryable === 'boolean' ? { retryable } : {}),\n },\n );\n }\n throw error;\n }\n });\n\n return server;\n}\n"],"mappings":";;AACO,IAAM,8BAA8B;AAiBpC,IAAM,iBAAN,cAA6B,MAAM;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F;GACA,MAAM;EACR;CACF,CAAC;CAED,OAAO;AACT"}
package/dist/index.d.ts CHANGED
@@ -24,6 +24,7 @@
24
24
 
25
25
  import { MCPConfig } from '@happyvertical/smrt-core/generators/mcp';
26
26
  import { MCPResponse } from '@happyvertical/smrt-core/generators/mcp';
27
+ import { McpTask } from '@happyvertical/smrt-jobs';
27
28
  import { MCPTool } from '@happyvertical/smrt-core/generators/mcp';
28
29
  import { Server } from '@modelcontextprotocol/server';
29
30
  import { ServerContext } from '@modelcontextprotocol/server';
@@ -75,6 +76,12 @@ export declare interface CreateMcpAppServerOptions {
75
76
  * (everything requires auth).
76
77
  */
77
78
  publicToolPatterns?: McpPublicToolPatternsThunk;
79
+ /**
80
+ * Cache policy for the MCP tools/list result. Public caching is honored only
81
+ * when this explicitly opts in and every allowed tool is a non-tenant,
82
+ * unauthenticated read-only tool with no principal-aware policy.
83
+ */
84
+ toolListCache?: McpToolListCacheOptions;
78
85
  /**
79
86
  * Optional generic principal-aware tool policy. It is evaluated for every
80
87
  * tool that passes the app allow-list and base public/authenticated policy,
@@ -177,6 +184,10 @@ export declare interface McpAccessErrorMetadata {
177
184
  */
178
185
  export declare interface McpAppPrincipal {
179
186
  id?: string;
187
+ /** Tenant boundary for task ownership and generated tenant-scoped actions. */
188
+ tenantId?: string;
189
+ /** Trusted operator override for generated tenant-scoped actions. */
190
+ allowCrossTenant?: boolean;
180
191
  kind?: string;
181
192
  roles?: string[];
182
193
  scopes?: string[];
@@ -186,6 +197,30 @@ export declare interface McpAppPrincipal {
186
197
  export declare interface McpAppServer {
187
198
  listTools(input: ListToolsInput): Promise<MCPTool[]>;
188
199
  callTool(input: CallToolInput): Promise<MCPResponse>;
200
+ /** Whether this app has any explicitly enabled Tasks extension action. */
201
+ hasTaskSupport?(): Promise<boolean>;
202
+ /** Whether a particular visible tool is task-enabled. */
203
+ isTaskTool?(name: string): Promise<boolean>;
204
+ /** Static declaration used by the protocol discovery capability surface. */
205
+ readonly tasksEnabled?: boolean;
206
+ /** Create a durable task after applying the same tool policy as tools/call. */
207
+ callTask?(input: CallToolInput): Promise<MCPResponse>;
208
+ /** Principal-scoped task lifecycle operations. */
209
+ getTask?(input: {
210
+ taskId: string;
211
+ principal?: McpAppPrincipal | null;
212
+ }): Promise<McpTask>;
213
+ updateTask?(input: {
214
+ taskId: string;
215
+ inputResponses: Record<string, unknown>;
216
+ principal?: McpAppPrincipal | null;
217
+ }): Promise<void>;
218
+ cancelTask?(input: {
219
+ taskId: string;
220
+ principal?: McpAppPrincipal | null;
221
+ }): Promise<void>;
222
+ /** Cache policy for protocol tools/list responses. */
223
+ getToolsListCacheHint?(): Promise<McpToolListCacheHint>;
189
224
  /** Read-only view of the configured server identity. */
190
225
  readonly serverInfo: CreateMcpAppServerOptions['serverInfo'];
191
226
  }
@@ -210,6 +245,23 @@ export declare type McpPublicToolPatternsThunk = () => readonly string[];
210
245
  */
211
246
  export declare type McpSmrtOptionsThunk = () => Record<string, unknown>;
212
247
 
248
+ export declare interface McpToolListCacheHint {
249
+ ttlMs: number;
250
+ cacheScope: 'private' | 'public';
251
+ }
252
+
253
+ export declare interface McpToolListCacheOptions {
254
+ /** Cache lifetime in milliseconds. Defaults to one day for a deploy-static catalog. */
255
+ ttlMs?: number;
256
+ /** Requested cache visibility. Defaults to private. */
257
+ cacheScope?: 'private' | 'public';
258
+ /**
259
+ * Explicit attestation that every allowed tool is global, unauthenticated,
260
+ * and safe to share through an intermediary cache.
261
+ */
262
+ publicCatalog?: true;
263
+ }
264
+
213
265
  /**
214
266
  * Per-tool access policy. Return `true` to expose/allow the tool and `false`
215
267
  * to hide it from discovery and deny a direct call. A thrown error is treated
package/dist/index.js CHANGED
@@ -1,72 +1,40 @@
1
- import { n as McpAccessError, t as MCP_TOOL_ACCESS_DENIED_CODE } from "./chunks/errors-CHYu0Vr2.js";
2
- import { ProtocolError, ProtocolErrorCode, Server } from "@modelcontextprotocol/server";
3
- import { MCPGenerator } from "@happyvertical/smrt-core/generators/mcp";
4
- //#region src/protocol.ts
5
- async function resolvePrincipal(option, context) {
6
- if (typeof option === "function") return await option(context) ?? null;
7
- return option ?? null;
8
- }
9
- function createMcpProtocolServer(appServer, options = {}) {
10
- const server = new Server(appServer.serverInfo, { capabilities: { tools: {} } });
11
- server.setRequestHandler("tools/list", async (_request, context) => ({ tools: await appServer.listTools({ principal: await resolvePrincipal(options.principal, context) }) }));
12
- server.setRequestHandler("tools/call", async (request, context) => {
13
- try {
14
- return await appServer.callTool({
15
- name: request.params.name,
16
- arguments: request.params.arguments,
17
- principal: await resolvePrincipal(options.principal, context)
18
- });
19
- } catch (error) {
20
- if (error instanceof McpAccessError) {
21
- const { code, retryable } = error.metadata;
22
- throw new ProtocolError(error.status === 404 ? ProtocolErrorCode.InvalidParams : ProtocolErrorCode.InvalidRequest, error.message, {
23
- ...typeof code === "string" ? { code } : {},
24
- ...typeof retryable === "boolean" ? { retryable } : {}
25
- });
26
- }
27
- throw error;
28
- }
29
- });
30
- return server;
31
- }
32
- //#endregion
33
- //#region src/tools.ts
34
- function matchesToolPattern(toolName, pattern) {
35
- if (!pattern) return false;
36
- if (pattern === "*") return true;
37
- const parts = pattern.split("*");
38
- if (parts.length === 1) return toolName === pattern;
39
- let cursor = 0;
40
- if (parts[0] && !toolName.startsWith(parts[0])) return false;
41
- for (const part of parts) {
42
- if (!part) continue;
43
- const index = toolName.indexOf(part, cursor);
44
- if (index < 0) return false;
45
- cursor = index + part.length;
46
- }
47
- const last = parts.at(-1);
48
- return !last || toolName.endsWith(last);
49
- }
50
- function isReadOnlyToolName(toolName) {
51
- return toolName.endsWith("_list") || toolName.endsWith("_get");
52
- }
53
- function isPublicToolName(toolName, patterns) {
54
- return isReadOnlyToolName(toolName) && patterns.some((pattern) => matchesToolPattern(toolName, pattern));
55
- }
56
- function classNamePrefixes(classNames) {
57
- return new Set(classNames.map((className) => `${className.toLowerCase()}_`));
1
+ import { a as isAllowedCoreTool, c as matchesToolPattern, i as compareMcpToolNames, l as MCP_TOOL_ACCESS_DENIED_CODE, n as createMcpProtocolServer, o as isPublicToolName, r as classNamePrefixes, s as isReadOnlyToolName, u as McpAccessError } from "./chunks/protocol-DoieND6v.js";
2
+ import { ObjectRegistry, isTenantScopedClassResolved } from "@happyvertical/smrt-core";
3
+ import { MCPGenerator, MCP_STABLE_CATALOG_TTL_MS } from "@happyvertical/smrt-core/generators/mcp";
4
+ import { McpTaskNotFoundError, McpTaskStore } from "@happyvertical/smrt-jobs";
5
+ //#region src/server.ts
6
+ function configuredToolListCacheHint(options) {
7
+ const ttlMs = options?.ttlMs ?? MCP_STABLE_CATALOG_TTL_MS;
8
+ if (!Number.isSafeInteger(ttlMs) || ttlMs < 0) throw new RangeError("MCP tools/list cache ttlMs must be a non-negative safe integer.");
9
+ if (options?.cacheScope !== void 0 && options.cacheScope !== "private" && options.cacheScope !== "public") throw new RangeError("MCP tools/list cacheScope must be 'private' or 'public'.");
10
+ return {
11
+ ttlMs,
12
+ cacheScope: options?.cacheScope === "public" && options.publicCatalog === true ? "public" : "private"
13
+ };
58
14
  }
59
- function isAllowedCoreTool(toolName, prefixes) {
60
- for (const prefix of prefixes) if (toolName.startsWith(prefix)) return true;
15
+ function isTenantScopedTool(tool) {
16
+ const separator = tool.name.indexOf("_");
17
+ if (separator <= 0) return false;
18
+ const objectName = tool.name.slice(0, separator).toLowerCase();
19
+ for (const [key, classInfo] of ObjectRegistry.getAllClasses()) {
20
+ const name = classInfo.name || key;
21
+ if (name.toLowerCase() === objectName) return ObjectRegistry.isTenantScoped(name) || isTenantScopedClassResolved(name);
22
+ }
61
23
  return false;
62
24
  }
63
- //#endregion
64
- //#region src/server.ts
25
+ function taskOwnerIdFor(principal) {
26
+ return JSON.stringify([principal.tenantId ?? null, principal.id]);
27
+ }
65
28
  function createMcpAppServer(options) {
66
29
  const allowedPrefixes = classNamePrefixes(options.allowedClassNames);
67
30
  const getPublicPatterns = options.publicToolPatterns ?? (() => []);
68
31
  const toolPolicy = options.toolPolicy;
69
32
  const workflowAssertions = options.workflowAssertions ?? {};
33
+ const requestedToolListCacheHint = configuredToolListCacheHint(options.toolListCache);
34
+ const tasksEnabled = options.allowedClassNames.some((className) => {
35
+ const mcp = ObjectRegistry.getConfig(className).mcp;
36
+ return typeof mcp === "object" && (mcp.tasks === true || Array.isArray(mcp.tasks) && mcp.tasks.length > 0);
37
+ });
70
38
  function userForGenerator(principal) {
71
39
  if (!principal?.id) return void 0;
72
40
  return {
@@ -74,11 +42,20 @@ function createMcpAppServer(options) {
74
42
  roles: principal.roles
75
43
  };
76
44
  }
77
- function makeGenerator(principal) {
45
+ async function taskStoreFor(principal) {
46
+ if (!principal?.id) throw new McpAccessError(401, "Authentication is required for MCP tasks.");
47
+ const db = options.smrtOptions().db;
48
+ if (!db) throw new Error("MCP Tasks requires smrtOptions() to provide a database");
49
+ return McpTaskStore.create(db, { ownerId: taskOwnerIdFor(principal) });
50
+ }
51
+ function makeGenerator(principal, taskStore) {
78
52
  const user = userForGenerator(principal);
79
53
  return new MCPGenerator(options.serverInfo, {
80
54
  ...options.smrtOptions(),
81
- user
55
+ user,
56
+ tenantId: principal?.tenantId,
57
+ allowCrossTenant: principal?.allowCrossTenant,
58
+ ...taskStore ? { taskStore } : {}
82
59
  });
83
60
  }
84
61
  function principalForList(input) {
@@ -90,7 +67,7 @@ function createMcpAppServer(options) {
90
67
  return input.user ?? null;
91
68
  }
92
69
  async function allowedTools() {
93
- return (await makeGenerator().generateTools()).filter((tool) => isAllowedCoreTool(tool.name, allowedPrefixes));
70
+ return (await makeGenerator().generateTools()).filter((tool) => isAllowedCoreTool(tool.name.toLowerCase(), allowedPrefixes)).sort((left, right) => compareMcpToolNames(left.name, right.name));
94
71
  }
95
72
  function passesBasePolicy(tool, principal, publicPatterns) {
96
73
  if (principal) return true;
@@ -117,11 +94,20 @@ function createMcpAppServer(options) {
117
94
  }));
118
95
  return tools.filter((_, index) => visible[index]);
119
96
  }
97
+ async function getToolsListCacheHint() {
98
+ if (requestedToolListCacheHint.cacheScope !== "public") return requestedToolListCacheHint;
99
+ const tools = await allowedTools();
100
+ const publicPatterns = getPublicPatterns();
101
+ return !toolPolicy && tools.every((tool) => isPublicToolName(tool.name, publicPatterns) && !isTenantScopedTool(tool)) ? requestedToolListCacheHint : {
102
+ ...requestedToolListCacheHint,
103
+ cacheScope: "private"
104
+ };
105
+ }
120
106
  async function callTool(input) {
121
107
  const args = input.arguments ?? {};
122
108
  const principal = principalForCall(input);
123
109
  const tool = (await allowedTools()).find((candidate) => candidate.name === input.name);
124
- if (!tool) throw new McpAccessError(404, `Unknown MCP tool: ${input.name}`);
110
+ if (!tool) throw new McpAccessError(404, "Unknown MCP tool.");
125
111
  if (!passesBasePolicy(tool, principal, principal ? void 0 : getPublicPatterns())) throw new McpAccessError(401, `Authentication is required for MCP tool: ${input.name}`);
126
112
  if (!await passesToolPolicy(tool, principal)) throw new McpAccessError(403, "MCP tool access is not permitted.", {
127
113
  code: MCP_TOOL_ACCESS_DENIED_CODE,
@@ -137,9 +123,72 @@ function createMcpAppServer(options) {
137
123
  }
138
124
  });
139
125
  }
126
+ async function authorizeCall(input) {
127
+ const args = input.arguments ?? {};
128
+ const principal = principalForCall(input);
129
+ const tool = (await allowedTools()).find((candidate) => candidate.name === input.name);
130
+ if (!tool) throw new McpAccessError(404, "Unknown MCP tool.");
131
+ if (!passesBasePolicy(tool, principal, principal ? void 0 : getPublicPatterns())) throw new McpAccessError(401, `Authentication is required for MCP tool: ${input.name}`);
132
+ if (!await passesToolPolicy(tool, principal)) throw new McpAccessError(403, "MCP tool access is not permitted.", {
133
+ code: MCP_TOOL_ACCESS_DENIED_CODE,
134
+ retryable: false
135
+ });
136
+ const assertion = workflowAssertions[input.name];
137
+ if (assertion) assertion(args, userForGenerator(principal) ?? null);
138
+ return {
139
+ args,
140
+ principal,
141
+ tool
142
+ };
143
+ }
144
+ async function hasTaskSupport() {
145
+ const tools = await allowedTools();
146
+ const generator = makeGenerator();
147
+ for (const tool of tools) if (await generator.supportsTaskTool(tool.name)) return true;
148
+ return false;
149
+ }
150
+ async function isTaskTool(name) {
151
+ if (!(await allowedTools()).some((tool) => tool.name === name)) return false;
152
+ return makeGenerator().supportsTaskTool(name);
153
+ }
154
+ async function callTask(input) {
155
+ const { args, principal } = await authorizeCall(input);
156
+ return makeGenerator(principal, await taskStoreFor(principal)).createTask({
157
+ method: "tools/call",
158
+ params: {
159
+ arguments: args,
160
+ name: input.name
161
+ }
162
+ });
163
+ }
164
+ async function withTaskStore(principal, operation) {
165
+ try {
166
+ return await operation(await taskStoreFor(principal));
167
+ } catch (error) {
168
+ if (error instanceof McpTaskNotFoundError) throw new McpAccessError(404, "Unknown MCP task.");
169
+ throw error;
170
+ }
171
+ }
172
+ async function getTask(input) {
173
+ return withTaskStore(input.principal, (store) => store.getTask(input.taskId));
174
+ }
175
+ async function updateTask(input) {
176
+ await withTaskStore(input.principal, (store) => store.updateTask(input.taskId, input.inputResponses));
177
+ }
178
+ async function cancelTask(input) {
179
+ await withTaskStore(input.principal, (store) => store.cancelTask(input.taskId));
180
+ }
140
181
  return {
141
182
  listTools,
142
183
  callTool,
184
+ hasTaskSupport,
185
+ isTaskTool,
186
+ callTask,
187
+ getTask,
188
+ updateTask,
189
+ cancelTask,
190
+ tasksEnabled,
191
+ getToolsListCacheHint,
143
192
  serverInfo: options.serverInfo
144
193
  };
145
194
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/protocol.ts","../src/tools.ts","../src/server.ts"],"sourcesContent":["/** MCP SDK v2 protocol adapter for the framework-neutral app server core. */\nimport {\n type CallToolResult,\n ProtocolError,\n ProtocolErrorCode,\n Server,\n type ServerContext,\n type Tool,\n} from '@modelcontextprotocol/server';\nimport { McpAccessError } from './errors.js';\nimport type { McpAppPrincipal, McpAppServer } from './server.js';\n\nexport interface McpProtocolServerOptions {\n /** Resolve the authenticated application principal for each MCP request. */\n principal?:\n | McpAppPrincipal\n | null\n | ((\n context: ServerContext,\n ) => McpAppPrincipal | null | Promise<McpAppPrincipal | null>);\n}\n\nasync function resolvePrincipal(\n option: McpProtocolServerOptions['principal'],\n context: ServerContext,\n): Promise<McpAppPrincipal | null> {\n if (typeof option === 'function') return (await option(context)) ?? null;\n return option ?? null;\n}\n\n/**\n * Adapt an app MCP core to the SDK v2 low-level server protocol.\n *\n * Transport ownership remains with the caller. In particular, this does not\n * add a production HTTP endpoint; it is safe to compose with `serveStdio` or\n * `createMcpHandler` in a deployment that supplies its own authentication.\n */\nexport function createMcpProtocolServer(\n appServer: McpAppServer,\n options: McpProtocolServerOptions = {},\n): Server {\n const server = new Server(appServer.serverInfo, {\n capabilities: { tools: {} },\n });\n\n server.setRequestHandler('tools/list', async (_request, context) => ({\n tools: (await appServer.listTools({\n principal: await resolvePrincipal(options.principal, context),\n })) as Tool[],\n }));\n\n server.setRequestHandler('tools/call', async (request, context) => {\n try {\n return (await appServer.callTool({\n name: request.params.name,\n arguments: request.params.arguments,\n principal: await resolvePrincipal(options.principal, context),\n })) as CallToolResult;\n } catch (error) {\n if (error instanceof McpAccessError) {\n const { code, retryable } = error.metadata;\n throw new ProtocolError(\n error.status === 404\n ? ProtocolErrorCode.InvalidParams\n : ProtocolErrorCode.InvalidRequest,\n error.message,\n {\n ...(typeof code === 'string' ? { code } : {}),\n ...(typeof retryable === 'boolean' ? { retryable } : {}),\n },\n );\n }\n throw error;\n }\n });\n\n return server;\n}\n","/**\n * Tool-name policy helpers — used by `McpAppServer` to filter the full set\n * of generated tools down to what the calling principal is allowed to see,\n * and to decide whether an unauthenticated tool call should be permitted.\n *\n * @packageDocumentation\n */\n\n/**\n * Match a tool name against a glob-ish pattern with `*` wildcards.\n *\n * - Empty pattern → never matches.\n * - `*` → matches everything.\n * - `prefix_*` → matches anything starting with `prefix_`.\n * - `*_suffix` → matches anything ending with `_suffix`.\n * - `a_*_b` → matches any name containing `a_`, then any text, then `_b`.\n *\n * No regex characters are special besides `*` — the input is treated as a\n * literal string with star wildcards.\n */\nexport function matchesToolPattern(toolName: string, pattern: string): boolean {\n if (!pattern) return false;\n if (pattern === '*') return true;\n\n const parts = pattern.split('*');\n if (parts.length === 1) return toolName === pattern;\n\n let cursor = 0;\n if (parts[0] && !toolName.startsWith(parts[0])) return false;\n for (const part of parts) {\n if (!part) continue;\n const index = toolName.indexOf(part, cursor);\n if (index < 0) return false;\n cursor = index + part.length;\n }\n\n const last = parts.at(-1);\n return !last || toolName.endsWith(last);\n}\n\n/**\n * Read-only tool detection. Generated SMRT MCP tools follow the naming\n * convention `<class>_<verb>`; we treat `_list` and `_get` as read-only.\n */\nexport function isReadOnlyToolName(toolName: string): boolean {\n return toolName.endsWith('_list') || toolName.endsWith('_get');\n}\n\n/**\n * Check whether a tool name is currently allowed for unauthenticated callers\n * given the configured public-tool patterns. Only read-only tools may ever\n * be public, regardless of pattern.\n */\nexport function isPublicToolName(\n toolName: string,\n patterns: readonly string[],\n): boolean {\n return (\n isReadOnlyToolName(toolName) &&\n patterns.some((pattern) => matchesToolPattern(toolName, pattern))\n );\n}\n\n/**\n * Lower-case `<class>_` prefixes the app considers \"allowed core tools\"\n * given a list of SMRT class names. Used to build the allow-list for\n * `McpAppServer.listTools`.\n */\nexport function classNamePrefixes(\n classNames: readonly string[],\n): ReadonlySet<string> {\n return new Set(classNames.map((className) => `${className.toLowerCase()}_`));\n}\n\n/**\n * Whether a given tool name starts with any of the configured class\n * prefixes.\n */\nexport function isAllowedCoreTool(\n toolName: string,\n prefixes: ReadonlySet<string>,\n): boolean {\n for (const prefix of prefixes) {\n if (toolName.startsWith(prefix)) return true;\n }\n return false;\n}\n","/**\n * `createMcpAppServer` returns the framework-agnostic core that backs an\n * app's HTTP MCP endpoints and stdio bridge. It wraps `MCPGenerator` from\n * `@happyvertical/smrt-core` with:\n *\n * - an allow-list of SMRT class names (so apps publish a subset of their\n * objects, not everything decorated with `@smrt()`),\n * - a public-tool policy for unauthenticated callers (read-only patterns\n * via `publicToolPatterns`),\n * - an optional principal-aware `toolPolicy`, used for both discovery and\n * direct calls,\n * - a pluggable `workflowAssertions` hook so apps can guard their own\n * domain-specific tool calls (e.g. \"approval requires an authenticated\n * user\") without that policy living in this package.\n *\n * @packageDocumentation\n */\n\nimport type {\n MCPConfig,\n MCPResponse,\n MCPTool,\n} from '@happyvertical/smrt-core/generators/mcp';\nimport { MCPGenerator } from '@happyvertical/smrt-core/generators/mcp';\nimport { MCP_TOOL_ACCESS_DENIED_CODE, McpAccessError } from './errors.js';\nimport {\n classNamePrefixes,\n isAllowedCoreTool,\n isPublicToolName,\n} from './tools.js';\n\n/**\n * Generic authenticated caller information available to app-MCP policy.\n *\n * `kind`, `roles`, and `scopes` are deliberately unconstrained so an app can\n * represent a human or a scoped service without this package encoding an\n * application's identity or capability model. A missing principal means the\n * request is unauthenticated.\n */\nexport interface McpAppPrincipal {\n id?: string;\n kind?: string;\n roles?: string[];\n scopes?: string[];\n}\n\n/** Minimal legacy user shape used for generated tool-call attribution. */\nexport interface McpAppUser extends McpAppPrincipal {\n id: string;\n}\n\n/** Context supplied to the optional per-tool principal policy. */\nexport interface McpToolPolicyContext {\n principal: McpAppPrincipal | null;\n tool: MCPTool;\n}\n\n/**\n * Per-tool access policy. Return `true` to expose/allow the tool and `false`\n * to hide it from discovery and deny a direct call. A thrown error is treated\n * as a denial so policy implementation details cannot escape the app-MCP\n * boundary.\n */\nexport type McpToolPolicy = (\n context: McpToolPolicyContext,\n) => boolean | Promise<boolean>;\n\n/**\n * Workflow assertion hook signature. Throw `McpAccessError` to reject the\n * call. Implementations may mutate `args` in place to inject server-trusted\n * fields (e.g. clamping `approvedByUserId` to the authenticated user's id).\n */\nexport type McpWorkflowAssertion = (\n args: Record<string, unknown>,\n user: McpAppUser | null,\n) => void;\n\n/**\n * SMRT options thunk — returns the `{ db }` (and similar) bag to pass into\n * MCPGenerator's per-request context. A function is used so apps can lazily\n * resolve env vars at call time.\n */\nexport type McpSmrtOptionsThunk = () => Record<string, unknown>;\n\n/** Public-tool patterns thunk — same lazy-evaluation rationale. */\nexport type McpPublicToolPatternsThunk = () => readonly string[];\n\n/**\n * Options for `createMcpAppServer`.\n */\nexport interface CreateMcpAppServerOptions {\n /** SMRT context bag (db, etc.) passed to MCPGenerator per call. */\n smrtOptions: McpSmrtOptionsThunk;\n /** Server identity surfaced in the MCP protocol. */\n serverInfo: Required<Pick<MCPConfig, 'name' | 'version'>> &\n Pick<MCPConfig, 'description'>;\n /**\n * SMRT class names the app wants to publish. Tools whose name does not\n * start with any of these classes (lowercased + underscore) are filtered\n * out, even if SMRT generated them.\n */\n allowedClassNames: readonly string[];\n /**\n * Optional thunk returning glob-ish patterns for read-only tools that\n * unauthenticated callers are allowed to use. Defaults to an empty list\n * (everything requires auth).\n */\n publicToolPatterns?: McpPublicToolPatternsThunk;\n /**\n * Optional generic principal-aware tool policy. It is evaluated for every\n * tool that passes the app allow-list and base public/authenticated policy,\n * for both discovery and a direct call.\n */\n toolPolicy?: McpToolPolicy;\n /**\n * Optional per-tool guards. Keyed by tool name. The assertion runs after\n * tool resolution and before `MCPGenerator.handleToolCall`; throwing\n * `McpAccessError` aborts the call with the error's status. Implementations\n * may mutate `args` to inject trusted fields.\n */\n workflowAssertions?: Record<string, McpWorkflowAssertion>;\n}\n\n/** Tool listing inputs. */\nexport interface ListToolsInput {\n /** Caller used for public/authenticated and optional tool-policy checks. */\n principal?: McpAppPrincipal | null;\n /**\n * Backwards-compatible authenticated marker. New mounts should pass\n * `principal` so discovery and direct calls use the same identity.\n */\n authenticated?: boolean;\n}\n\n/** Tool call inputs. */\nexport interface CallToolInput {\n name: string;\n arguments?: Record<string, unknown>;\n /** Caller used for public/authenticated and optional tool-policy checks. */\n principal?: McpAppPrincipal | null;\n /**\n * Backwards-compatible user input. New callers should pass `principal`.\n * Null/undefined means unauthenticated.\n */\n user?: McpAppUser | null;\n}\n\n/** Shape returned by `createMcpAppServer`. */\nexport interface McpAppServer {\n listTools(input: ListToolsInput): Promise<MCPTool[]>;\n callTool(input: CallToolInput): Promise<MCPResponse>;\n /** Read-only view of the configured server identity. */\n readonly serverInfo: CreateMcpAppServerOptions['serverInfo'];\n}\n\n/**\n * Build the app-runtime MCP server core. The returned object is intentionally\n * framework-agnostic: HTTP wrappers live in `@happyvertical/smrt-app-mcp/sveltekit`\n * and a stdio bridge lives in `@happyvertical/smrt-app-mcp/bin/smrt-mcp-bridge`.\n */\nexport function createMcpAppServer(\n options: CreateMcpAppServerOptions,\n): McpAppServer {\n const allowedPrefixes = classNamePrefixes(options.allowedClassNames);\n const getPublicPatterns =\n options.publicToolPatterns ?? ((): readonly string[] => []);\n const toolPolicy = options.toolPolicy;\n const workflowAssertions = options.workflowAssertions ?? {};\n\n function userForGenerator(\n principal?: McpAppPrincipal | null,\n ): McpAppUser | undefined {\n if (!principal?.id) return undefined;\n return { id: principal.id, roles: principal.roles };\n }\n\n function makeGenerator(principal?: McpAppPrincipal | null): MCPGenerator {\n const user = userForGenerator(principal);\n return new MCPGenerator(options.serverInfo as MCPConfig, {\n ...options.smrtOptions(),\n user,\n });\n }\n\n function principalForList(input: ListToolsInput): McpAppPrincipal | null {\n if (input.principal !== undefined) return input.principal;\n // Preserve callers of the original boolean API without inventing an id.\n return input.authenticated ? {} : null;\n }\n\n function principalForCall(input: CallToolInput): McpAppPrincipal | null {\n if (input.principal !== undefined) return input.principal;\n return input.user ?? null;\n }\n\n async function allowedTools(): Promise<MCPTool[]> {\n const tools = await makeGenerator().generateTools();\n return tools.filter((tool) =>\n isAllowedCoreTool(tool.name, allowedPrefixes),\n );\n }\n\n function passesBasePolicy(\n tool: MCPTool,\n principal: McpAppPrincipal | null,\n publicPatterns?: readonly string[],\n ): boolean {\n if (principal) return true;\n return isPublicToolName(tool.name, publicPatterns ?? []);\n }\n\n async function passesToolPolicy(\n tool: MCPTool,\n principal: McpAppPrincipal | null,\n ): Promise<boolean> {\n if (!toolPolicy) return true;\n try {\n return Boolean(await toolPolicy({ principal, tool }));\n } catch {\n // A policy failure must fail closed and never leak implementation detail.\n return false;\n }\n }\n\n async function listTools(input: ListToolsInput): Promise<MCPTool[]> {\n const principal = principalForList(input);\n const tools = await allowedTools();\n // Keep the lazy thunk per request, not per tool. Besides avoiding repeated\n // work, this gives one consistent public surface when a thunk reads a\n // dynamic source such as an environment-backed configuration.\n const publicPatterns = principal ? undefined : getPublicPatterns();\n const visible = await Promise.all(\n tools.map(async (tool) => {\n if (!passesBasePolicy(tool, principal, publicPatterns)) return false;\n return passesToolPolicy(tool, principal);\n }),\n );\n return tools.filter((_, index) => visible[index]);\n }\n\n async function callTool(input: CallToolInput): Promise<MCPResponse> {\n const args = input.arguments ?? {};\n const principal = principalForCall(input);\n const tools = await allowedTools();\n const tool = tools.find((candidate) => candidate.name === input.name);\n if (!tool) {\n throw new McpAccessError(404, `Unknown MCP tool: ${input.name}`);\n }\n\n const publicPatterns = principal ? undefined : getPublicPatterns();\n if (!passesBasePolicy(tool, principal, publicPatterns)) {\n throw new McpAccessError(\n 401,\n `Authentication is required for MCP tool: ${input.name}`,\n );\n }\n\n if (!(await passesToolPolicy(tool, principal))) {\n throw new McpAccessError(403, 'MCP tool access is not permitted.', {\n code: MCP_TOOL_ACCESS_DENIED_CODE,\n retryable: false,\n });\n }\n\n const assertion = workflowAssertions[input.name];\n if (assertion) {\n assertion(args, userForGenerator(principal) ?? null);\n }\n\n return makeGenerator(principal).handleToolCall({\n method: 'tools/call',\n params: { arguments: args, name: input.name },\n });\n }\n\n return {\n listTools,\n callTool,\n serverInfo: options.serverInfo,\n };\n}\n"],"mappings":";;;;AAsBA,eAAe,iBACb,QACA,SACiC;CACjC,IAAI,OAAO,WAAW,YAAY,OAAQ,MAAM,OAAO,OAAO,KAAM;CACpE,OAAO,UAAU;AACnB;AASO,SAAS,wBACd,WACA,UAAoC,CAAC,GAC7B;CACR,MAAM,SAAS,IAAI,OAAO,UAAU,YAAY,EAC9C,cAAc,EAAE,OAAO,CAAC,EAAE,EAC5B,CAAC;CAED,OAAO,kBAAkB,cAAc,OAAO,UAA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9C,CAAC;CACH;CAEA,OAAO;EACL;EACA;EACA,YAAY,QAAQ;CACtB;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/server.ts"],"sourcesContent":["/**\n * `createMcpAppServer` returns the framework-agnostic core that backs an\n * app's HTTP MCP endpoints and stdio bridge. It wraps `MCPGenerator` from\n * `@happyvertical/smrt-core` with:\n *\n * - an allow-list of SMRT class names (so apps publish a subset of their\n * objects, not everything decorated with `@smrt()`),\n * - a public-tool policy for unauthenticated callers (read-only patterns\n * via `publicToolPatterns`),\n * - an optional principal-aware `toolPolicy`, used for both discovery and\n * direct calls,\n * - a pluggable `workflowAssertions` hook so apps can guard their own\n * domain-specific tool calls (e.g. \"approval requires an authenticated\n * user\") without that policy living in this package.\n *\n * @packageDocumentation\n */\n\nimport {\n isTenantScopedClassResolved,\n ObjectRegistry,\n} from '@happyvertical/smrt-core';\nimport type {\n MCPConfig,\n MCPResponse,\n MCPTool,\n} from '@happyvertical/smrt-core/generators/mcp';\nimport {\n MCP_STABLE_CATALOG_TTL_MS,\n MCPGenerator,\n} from '@happyvertical/smrt-core/generators/mcp';\nimport {\n type McpTask,\n McpTaskNotFoundError,\n McpTaskStore,\n} from '@happyvertical/smrt-jobs';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { MCP_TOOL_ACCESS_DENIED_CODE, McpAccessError } from './errors.js';\nimport {\n classNamePrefixes,\n compareMcpToolNames,\n isAllowedCoreTool,\n isPublicToolName,\n} from './tools.js';\n\n/**\n * Generic authenticated caller information available to app-MCP policy.\n *\n * `kind`, `roles`, and `scopes` are deliberately unconstrained so an app can\n * represent a human or a scoped service without this package encoding an\n * application's identity or capability model. A missing principal means the\n * request is unauthenticated.\n */\nexport interface McpAppPrincipal {\n id?: string;\n /** Tenant boundary for task ownership and generated tenant-scoped actions. */\n tenantId?: string;\n /** Trusted operator override for generated tenant-scoped actions. */\n allowCrossTenant?: boolean;\n kind?: string;\n roles?: string[];\n scopes?: string[];\n}\n\n/** Minimal legacy user shape used for generated tool-call attribution. */\nexport interface McpAppUser extends McpAppPrincipal {\n id: string;\n}\n\n/** Context supplied to the optional per-tool principal policy. */\nexport interface McpToolPolicyContext {\n principal: McpAppPrincipal | null;\n tool: MCPTool;\n}\n\n/**\n * Per-tool access policy. Return `true` to expose/allow the tool and `false`\n * to hide it from discovery and deny a direct call. A thrown error is treated\n * as a denial so policy implementation details cannot escape the app-MCP\n * boundary.\n */\nexport type McpToolPolicy = (\n context: McpToolPolicyContext,\n) => boolean | Promise<boolean>;\n\n/**\n * Workflow assertion hook signature. Throw `McpAccessError` to reject the\n * call. Implementations may mutate `args` in place to inject server-trusted\n * fields (e.g. clamping `approvedByUserId` to the authenticated user's id).\n */\nexport type McpWorkflowAssertion = (\n args: Record<string, unknown>,\n user: McpAppUser | null,\n) => void;\n\n/**\n * SMRT options thunk — returns the `{ db }` (and similar) bag to pass into\n * MCPGenerator's per-request context. A function is used so apps can lazily\n * resolve env vars at call time.\n */\nexport type McpSmrtOptionsThunk = () => Record<string, unknown>;\n\n/** Public-tool patterns thunk — same lazy-evaluation rationale. */\nexport type McpPublicToolPatternsThunk = () => readonly string[];\n\nexport interface McpToolListCacheHint {\n ttlMs: number;\n cacheScope: 'private' | 'public';\n}\n\nexport interface McpToolListCacheOptions {\n /** Cache lifetime in milliseconds. Defaults to one day for a deploy-static catalog. */\n ttlMs?: number;\n /** Requested cache visibility. Defaults to private. */\n cacheScope?: 'private' | 'public';\n /**\n * Explicit attestation that every allowed tool is global, unauthenticated,\n * and safe to share through an intermediary cache.\n */\n publicCatalog?: true;\n}\n\n/**\n * Options for `createMcpAppServer`.\n */\nexport interface CreateMcpAppServerOptions {\n /** SMRT context bag (db, etc.) passed to MCPGenerator per call. */\n smrtOptions: McpSmrtOptionsThunk;\n /** Server identity surfaced in the MCP protocol. */\n serverInfo: Required<Pick<MCPConfig, 'name' | 'version'>> &\n Pick<MCPConfig, 'description'>;\n /**\n * SMRT class names the app wants to publish. Tools whose name does not\n * start with any of these classes (lowercased + underscore) are filtered\n * out, even if SMRT generated them.\n */\n allowedClassNames: readonly string[];\n /**\n * Optional thunk returning glob-ish patterns for read-only tools that\n * unauthenticated callers are allowed to use. Defaults to an empty list\n * (everything requires auth).\n */\n publicToolPatterns?: McpPublicToolPatternsThunk;\n /**\n * Cache policy for the MCP tools/list result. Public caching is honored only\n * when this explicitly opts in and every allowed tool is a non-tenant,\n * unauthenticated read-only tool with no principal-aware policy.\n */\n toolListCache?: McpToolListCacheOptions;\n /**\n * Optional generic principal-aware tool policy. It is evaluated for every\n * tool that passes the app allow-list and base public/authenticated policy,\n * for both discovery and a direct call.\n */\n toolPolicy?: McpToolPolicy;\n /**\n * Optional per-tool guards. Keyed by tool name. The assertion runs after\n * tool resolution and before `MCPGenerator.handleToolCall`; throwing\n * `McpAccessError` aborts the call with the error's status. Implementations\n * may mutate `args` to inject trusted fields.\n */\n workflowAssertions?: Record<string, McpWorkflowAssertion>;\n}\n\n/** Tool listing inputs. */\nexport interface ListToolsInput {\n /** Caller used for public/authenticated and optional tool-policy checks. */\n principal?: McpAppPrincipal | null;\n /**\n * Backwards-compatible authenticated marker. New mounts should pass\n * `principal` so discovery and direct calls use the same identity.\n */\n authenticated?: boolean;\n}\n\n/** Tool call inputs. */\nexport interface CallToolInput {\n name: string;\n arguments?: Record<string, unknown>;\n /** Caller used for public/authenticated and optional tool-policy checks. */\n principal?: McpAppPrincipal | null;\n /**\n * Backwards-compatible user input. New callers should pass `principal`.\n * Null/undefined means unauthenticated.\n */\n user?: McpAppUser | null;\n}\n\n/** Shape returned by `createMcpAppServer`. */\nexport interface McpAppServer {\n listTools(input: ListToolsInput): Promise<MCPTool[]>;\n callTool(input: CallToolInput): Promise<MCPResponse>;\n /** Whether this app has any explicitly enabled Tasks extension action. */\n hasTaskSupport?(): Promise<boolean>;\n /** Whether a particular visible tool is task-enabled. */\n isTaskTool?(name: string): Promise<boolean>;\n /** Static declaration used by the protocol discovery capability surface. */\n readonly tasksEnabled?: boolean;\n /** Create a durable task after applying the same tool policy as tools/call. */\n callTask?(input: CallToolInput): Promise<MCPResponse>;\n /** Principal-scoped task lifecycle operations. */\n getTask?(input: {\n taskId: string;\n principal?: McpAppPrincipal | null;\n }): Promise<McpTask>;\n updateTask?(input: {\n taskId: string;\n inputResponses: Record<string, unknown>;\n principal?: McpAppPrincipal | null;\n }): Promise<void>;\n cancelTask?(input: {\n taskId: string;\n principal?: McpAppPrincipal | null;\n }): Promise<void>;\n /** Cache policy for protocol tools/list responses. */\n getToolsListCacheHint?(): Promise<McpToolListCacheHint>;\n /** Read-only view of the configured server identity. */\n readonly serverInfo: CreateMcpAppServerOptions['serverInfo'];\n}\n\nfunction configuredToolListCacheHint(\n options: McpToolListCacheOptions | undefined,\n): McpToolListCacheHint {\n const ttlMs = options?.ttlMs ?? MCP_STABLE_CATALOG_TTL_MS;\n if (!Number.isSafeInteger(ttlMs) || ttlMs < 0) {\n throw new RangeError(\n 'MCP tools/list cache ttlMs must be a non-negative safe integer.',\n );\n }\n if (\n options?.cacheScope !== undefined &&\n options.cacheScope !== 'private' &&\n options.cacheScope !== 'public'\n ) {\n throw new RangeError(\n \"MCP tools/list cacheScope must be 'private' or 'public'.\",\n );\n }\n return {\n ttlMs,\n cacheScope:\n options?.cacheScope === 'public' && options.publicCatalog === true\n ? 'public'\n : 'private',\n };\n}\n\nfunction isTenantScopedTool(tool: MCPTool): boolean {\n const separator = tool.name.indexOf('_');\n if (separator <= 0) return false;\n const objectName = tool.name.slice(0, separator).toLowerCase();\n for (const [key, classInfo] of ObjectRegistry.getAllClasses()) {\n const name = classInfo.name || key;\n if (name.toLowerCase() === objectName) {\n return (\n ObjectRegistry.isTenantScoped(name) || isTenantScopedClassResolved(name)\n );\n }\n }\n return false;\n}\n\n/**\n * Scope task lookup to both the authenticated principal and its tenant. The\n * opaque value is stored in the existing job row, so no separate task table\n * can accidentally bypass a tenant boundary.\n */\nfunction taskOwnerIdFor(principal: McpAppPrincipal): string {\n return JSON.stringify([principal.tenantId ?? null, principal.id]);\n}\n\n/**\n * Build the app-runtime MCP server core. The returned object is intentionally\n * framework-agnostic: HTTP wrappers live in `@happyvertical/smrt-app-mcp/sveltekit`\n * and a stdio bridge lives in `@happyvertical/smrt-app-mcp/bin/smrt-mcp-bridge`.\n */\nexport function createMcpAppServer(\n options: CreateMcpAppServerOptions,\n): McpAppServer {\n const allowedPrefixes = classNamePrefixes(options.allowedClassNames);\n const getPublicPatterns =\n options.publicToolPatterns ?? ((): readonly string[] => []);\n const toolPolicy = options.toolPolicy;\n const workflowAssertions = options.workflowAssertions ?? {};\n const requestedToolListCacheHint = configuredToolListCacheHint(\n options.toolListCache,\n );\n const tasksEnabled = options.allowedClassNames.some((className) => {\n const mcp = ObjectRegistry.getConfig(className).mcp;\n return (\n typeof mcp === 'object' &&\n (mcp.tasks === true || (Array.isArray(mcp.tasks) && mcp.tasks.length > 0))\n );\n });\n\n function userForGenerator(\n principal?: McpAppPrincipal | null,\n ): McpAppUser | undefined {\n if (!principal?.id) return undefined;\n return { id: principal.id, roles: principal.roles };\n }\n\n async function taskStoreFor(\n principal?: McpAppPrincipal | null,\n ): Promise<McpTaskStore> {\n if (!principal?.id) {\n throw new McpAccessError(\n 401,\n 'Authentication is required for MCP tasks.',\n );\n }\n const db = options.smrtOptions().db as DatabaseInterface | undefined;\n if (!db) {\n throw new Error('MCP Tasks requires smrtOptions() to provide a database');\n }\n return McpTaskStore.create(db, { ownerId: taskOwnerIdFor(principal) });\n }\n\n function makeGenerator(\n principal?: McpAppPrincipal | null,\n taskStore?: McpTaskStore,\n ): MCPGenerator {\n const user = userForGenerator(principal);\n return new MCPGenerator(options.serverInfo as MCPConfig, {\n ...options.smrtOptions(),\n user,\n tenantId: principal?.tenantId,\n allowCrossTenant: principal?.allowCrossTenant,\n ...(taskStore ? { taskStore } : {}),\n });\n }\n\n function principalForList(input: ListToolsInput): McpAppPrincipal | null {\n if (input.principal !== undefined) return input.principal;\n // Preserve callers of the original boolean API without inventing an id.\n return input.authenticated ? {} : null;\n }\n\n function principalForCall(input: CallToolInput): McpAppPrincipal | null {\n if (input.principal !== undefined) return input.principal;\n return input.user ?? null;\n }\n\n async function allowedTools(): Promise<MCPTool[]> {\n const tools = await makeGenerator().generateTools();\n return tools\n .filter((tool) =>\n isAllowedCoreTool(tool.name.toLowerCase(), allowedPrefixes),\n )\n .sort((left, right) => compareMcpToolNames(left.name, right.name));\n }\n\n function passesBasePolicy(\n tool: MCPTool,\n principal: McpAppPrincipal | null,\n publicPatterns?: readonly string[],\n ): boolean {\n if (principal) return true;\n return isPublicToolName(tool.name, publicPatterns ?? []);\n }\n\n async function passesToolPolicy(\n tool: MCPTool,\n principal: McpAppPrincipal | null,\n ): Promise<boolean> {\n if (!toolPolicy) return true;\n try {\n return Boolean(await toolPolicy({ principal, tool }));\n } catch {\n // A policy failure must fail closed and never leak implementation detail.\n return false;\n }\n }\n\n async function listTools(input: ListToolsInput): Promise<MCPTool[]> {\n const principal = principalForList(input);\n const tools = await allowedTools();\n // Keep the lazy thunk per request, not per tool. Besides avoiding repeated\n // work, this gives one consistent public surface when a thunk reads a\n // dynamic source such as an environment-backed configuration.\n const publicPatterns = principal ? undefined : getPublicPatterns();\n const visible = await Promise.all(\n tools.map(async (tool) => {\n if (!passesBasePolicy(tool, principal, publicPatterns)) return false;\n return passesToolPolicy(tool, principal);\n }),\n );\n return tools.filter((_, index) => visible[index]);\n }\n\n async function getToolsListCacheHint(): Promise<McpToolListCacheHint> {\n if (requestedToolListCacheHint.cacheScope !== 'public') {\n return requestedToolListCacheHint;\n }\n\n // A principal-aware policy can make one caller's catalog differ from\n // another's. Likewise, tenant-scoped reads must never be shared across\n // tenants. The requested public scope is therefore honored only for a\n // complete, unauthenticated, non-tenant read-only catalog.\n const tools = await allowedTools();\n const publicPatterns = getPublicPatterns();\n const isSafePublicCatalog =\n !toolPolicy &&\n tools.every(\n (tool) =>\n isPublicToolName(tool.name, publicPatterns) &&\n !isTenantScopedTool(tool),\n );\n\n return isSafePublicCatalog\n ? requestedToolListCacheHint\n : { ...requestedToolListCacheHint, cacheScope: 'private' };\n }\n\n async function callTool(input: CallToolInput): Promise<MCPResponse> {\n const args = input.arguments ?? {};\n const principal = principalForCall(input);\n const tools = await allowedTools();\n const tool = tools.find((candidate) => candidate.name === input.name);\n if (!tool) {\n throw new McpAccessError(404, 'Unknown MCP tool.');\n }\n\n const publicPatterns = principal ? undefined : getPublicPatterns();\n if (!passesBasePolicy(tool, principal, publicPatterns)) {\n throw new McpAccessError(\n 401,\n `Authentication is required for MCP tool: ${input.name}`,\n );\n }\n\n if (!(await passesToolPolicy(tool, principal))) {\n throw new McpAccessError(403, 'MCP tool access is not permitted.', {\n code: MCP_TOOL_ACCESS_DENIED_CODE,\n retryable: false,\n });\n }\n\n const assertion = workflowAssertions[input.name];\n if (assertion) {\n assertion(args, userForGenerator(principal) ?? null);\n }\n\n return makeGenerator(principal).handleToolCall({\n method: 'tools/call',\n params: { arguments: args, name: input.name },\n });\n }\n\n async function authorizeCall(input: CallToolInput): Promise<{\n args: Record<string, unknown>;\n principal: McpAppPrincipal | null;\n tool: MCPTool;\n }> {\n const args = input.arguments ?? {};\n const principal = principalForCall(input);\n const tools = await allowedTools();\n const tool = tools.find((candidate) => candidate.name === input.name);\n if (!tool) throw new McpAccessError(404, 'Unknown MCP tool.');\n const publicPatterns = principal ? undefined : getPublicPatterns();\n if (!passesBasePolicy(tool, principal, publicPatterns)) {\n throw new McpAccessError(\n 401,\n `Authentication is required for MCP tool: ${input.name}`,\n );\n }\n if (!(await passesToolPolicy(tool, principal))) {\n throw new McpAccessError(403, 'MCP tool access is not permitted.', {\n code: MCP_TOOL_ACCESS_DENIED_CODE,\n retryable: false,\n });\n }\n const assertion = workflowAssertions[input.name];\n if (assertion) assertion(args, userForGenerator(principal) ?? null);\n return { args, principal, tool };\n }\n\n async function hasTaskSupport(): Promise<boolean> {\n const tools = await allowedTools();\n const generator = makeGenerator();\n for (const tool of tools) {\n if (await generator.supportsTaskTool(tool.name)) return true;\n }\n return false;\n }\n\n async function isTaskTool(name: string): Promise<boolean> {\n const tools = await allowedTools();\n if (!tools.some((tool) => tool.name === name)) return false;\n return makeGenerator().supportsTaskTool(name);\n }\n\n async function callTask(input: CallToolInput): Promise<MCPResponse> {\n const { args, principal } = await authorizeCall(input);\n const taskStore = await taskStoreFor(principal);\n return makeGenerator(principal, taskStore).createTask({\n method: 'tools/call',\n params: { arguments: args, name: input.name },\n });\n }\n\n async function withTaskStore<T>(\n principal: McpAppPrincipal | null | undefined,\n operation: (store: McpTaskStore) => Promise<T>,\n ): Promise<T> {\n try {\n return await operation(await taskStoreFor(principal));\n } catch (error) {\n if (error instanceof McpTaskNotFoundError) {\n throw new McpAccessError(404, 'Unknown MCP task.');\n }\n throw error;\n }\n }\n\n async function getTask(input: {\n taskId: string;\n principal?: McpAppPrincipal | null;\n }): Promise<McpTask> {\n return withTaskStore(input.principal, (store) =>\n store.getTask(input.taskId),\n );\n }\n\n async function updateTask(input: {\n taskId: string;\n inputResponses: Record<string, unknown>;\n principal?: McpAppPrincipal | null;\n }): Promise<void> {\n await withTaskStore(input.principal, (store) =>\n store.updateTask(input.taskId, input.inputResponses),\n );\n }\n\n async function cancelTask(input: {\n taskId: string;\n principal?: McpAppPrincipal | null;\n }): Promise<void> {\n await withTaskStore(input.principal, (store) =>\n store.cancelTask(input.taskId),\n );\n }\n\n return {\n listTools,\n callTool,\n hasTaskSupport,\n isTaskTool,\n callTask,\n getTask,\n updateTask,\n cancelTask,\n tasksEnabled,\n getToolsListCacheHint,\n serverInfo: options.serverInfo,\n };\n}\n"],"mappings":";;;;;AA4NA,SAAS,4BACP,SACsB;CACtB,MAAM,QAAQ,SAAS,SAAS;CAChC,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,GAC1C,MAAM,IAAI,WACR,iEACF;CAEF,IACE,SAAS,eAAe,KAAA,KACxB,QAAQ,eAAe,aACvB,QAAQ,eAAe,UAEvB,MAAM,IAAI,WAC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Ae,QAAQ,OAGF;EACnB,OAAO,cAAc,MAAM,YAAY,UACrC,MAAM,QAAQ,MAAM,MAAM,CAC5B;CACF;CAEA,eAAe,WAAW,OAIR;EAChB,MAAM,cAAc,MAAM,YAAY,UACpC,MAAM,WAAW,MAAM,QAAQ,MAAM,cAAc,CACrD;CACF;CAEA,eAAe,WAAW,OAGR;EAChB,MAAM,cAAc,MAAM,YAAY,UACpC,MAAM,WAAW,MAAM,MAAM,CAC/B;CACF;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,YAAY,QAAQ;CACtB;AACF"}
@@ -2,10 +2,11 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-app-mcp",
5
- "packageVersion": "0.40.60",
5
+ "packageVersion": "0.40.62",
6
6
  "objects": {},
7
7
  "moduleType": "smrt",
8
8
  "smrtDependencies": [
9
- "@happyvertical/smrt-core"
9
+ "@happyvertical/smrt-core",
10
+ "@happyvertical/smrt-jobs"
10
11
  ]
11
12
  }
@@ -2,12 +2,12 @@
2
2
  "schemaVersion": 1,
3
3
  "generatedAt": "1970-01-01T00:00:00.000Z",
4
4
  "packageName": "@happyvertical/smrt-app-mcp",
5
- "packageVersion": "0.40.60",
5
+ "packageVersion": "0.40.62",
6
6
  "sourceManifestPath": "dist/manifest.json",
7
7
  "agentDocPath": "AGENTS.md",
8
8
  "sourceHashes": {
9
- "manifest": "98fe6f9633d2cb128908beedc694351ef37d538d1935147c21b48848ee4b640c",
10
- "packageJson": "4f1731b2730f637cf051dcabca311ba3671e58bd11793b91b7f04279698c2f5a",
9
+ "manifest": "7b0a9d90c52e22dbb71c6448680fac49c00b58eb96c468d822e08403402c5464",
10
+ "packageJson": "adf8bad9c61b71023c06d1c244b4b15943132e7e0e80fd8a585c6b3a340b6704",
11
11
  "agents": "fd1dc36d1530f81aae49e6efa2e2f5011a8a62d30816f25649d4cb597fc5662a"
12
12
  },
13
13
  "exports": [
@@ -16,7 +16,10 @@
16
16
  ],
17
17
  "dependencies": {
18
18
  "@happyvertical/smrt-core": "workspace:*",
19
+ "@happyvertical/smrt-jobs": "workspace:*",
20
+ "@happyvertical/sql": "catalog:",
19
21
  "@modelcontextprotocol/server": "2.0.0",
22
+ "@modelcontextprotocol/client": "2.0.0",
20
23
  "@modelcontextprotocol/conformance": "0.2.0-alpha.10",
21
24
  "@modelcontextprotocol/node": "2.0.0",
22
25
  "@types/node": "24.13.2",
@@ -25,9 +28,12 @@
25
28
  "vitest": "4.1.10"
26
29
  },
27
30
  "smrtDependencies": [
28
- "@happyvertical/smrt-core"
31
+ "@happyvertical/smrt-core",
32
+ "@happyvertical/smrt-jobs"
33
+ ],
34
+ "sdkDependencies": [
35
+ "@happyvertical/sql"
29
36
  ],
30
- "sdkDependencies": [],
31
37
  "tags": [],
32
38
  "risks": [],
33
39
  "objects": [],
@@ -1,5 +1,6 @@
1
1
  import { MCPConfig } from '@happyvertical/smrt-core/generators/mcp';
2
2
  import { MCPResponse } from '@happyvertical/smrt-core/generators/mcp';
3
+ import { McpTask } from '@happyvertical/smrt-jobs';
3
4
  import { MCPTool } from '@happyvertical/smrt-core/generators/mcp';
4
5
 
5
6
  /** Tool call inputs. */
@@ -35,6 +36,12 @@ declare interface CreateMcpAppServerOptions {
35
36
  * (everything requires auth).
36
37
  */
37
38
  publicToolPatterns?: McpPublicToolPatternsThunk;
39
+ /**
40
+ * Cache policy for the MCP tools/list result. Public caching is honored only
41
+ * when this explicitly opts in and every allowed tool is a non-tenant,
42
+ * unauthenticated read-only tool with no principal-aware policy.
43
+ */
44
+ toolListCache?: McpToolListCacheOptions;
38
45
  /**
39
46
  * Optional generic principal-aware tool policy. It is evaluated for every
40
47
  * tool that passes the app allow-list and base public/authenticated policy,
@@ -92,6 +99,10 @@ declare interface McpAccessErrorMetadata {
92
99
  */
93
100
  export declare interface McpAppPrincipal {
94
101
  id?: string;
102
+ /** Tenant boundary for task ownership and generated tenant-scoped actions. */
103
+ tenantId?: string;
104
+ /** Trusted operator override for generated tenant-scoped actions. */
105
+ allowCrossTenant?: boolean;
95
106
  kind?: string;
96
107
  roles?: string[];
97
108
  scopes?: string[];
@@ -101,6 +112,30 @@ export declare interface McpAppPrincipal {
101
112
  export declare interface McpAppServer {
102
113
  listTools(input: ListToolsInput): Promise<MCPTool[]>;
103
114
  callTool(input: CallToolInput): Promise<MCPResponse>;
115
+ /** Whether this app has any explicitly enabled Tasks extension action. */
116
+ hasTaskSupport?(): Promise<boolean>;
117
+ /** Whether a particular visible tool is task-enabled. */
118
+ isTaskTool?(name: string): Promise<boolean>;
119
+ /** Static declaration used by the protocol discovery capability surface. */
120
+ readonly tasksEnabled?: boolean;
121
+ /** Create a durable task after applying the same tool policy as tools/call. */
122
+ callTask?(input: CallToolInput): Promise<MCPResponse>;
123
+ /** Principal-scoped task lifecycle operations. */
124
+ getTask?(input: {
125
+ taskId: string;
126
+ principal?: McpAppPrincipal | null;
127
+ }): Promise<McpTask>;
128
+ updateTask?(input: {
129
+ taskId: string;
130
+ inputResponses: Record<string, unknown>;
131
+ principal?: McpAppPrincipal | null;
132
+ }): Promise<void>;
133
+ cancelTask?(input: {
134
+ taskId: string;
135
+ principal?: McpAppPrincipal | null;
136
+ }): Promise<void>;
137
+ /** Cache policy for protocol tools/list responses. */
138
+ getToolsListCacheHint?(): Promise<McpToolListCacheHint>;
104
139
  /** Read-only view of the configured server identity. */
105
140
  readonly serverInfo: CreateMcpAppServerOptions['serverInfo'];
106
141
  }
@@ -123,6 +158,26 @@ declare type McpPublicToolPatternsThunk = () => readonly string[];
123
158
  */
124
159
  declare type McpSmrtOptionsThunk = () => Record<string, unknown>;
125
160
 
161
+ /** A SvelteKit `+server.ts` request handler with no SvelteKit dependency. */
162
+ export declare type McpSvelteKitHandler = (event: SvelteKitRequestEvent) => Promise<Response>;
163
+
164
+ declare interface McpToolListCacheHint {
165
+ ttlMs: number;
166
+ cacheScope: 'private' | 'public';
167
+ }
168
+
169
+ declare interface McpToolListCacheOptions {
170
+ /** Cache lifetime in milliseconds. Defaults to one day for a deploy-static catalog. */
171
+ ttlMs?: number;
172
+ /** Requested cache visibility. Defaults to private. */
173
+ cacheScope?: 'private' | 'public';
174
+ /**
175
+ * Explicit attestation that every allowed tool is global, unauthenticated,
176
+ * and safe to share through an intermediary cache.
177
+ */
178
+ publicCatalog?: true;
179
+ }
180
+
126
181
  /**
127
182
  * Per-tool access policy. Return `true` to expose/allow the tool and `false`
128
183
  * to hide it from discovery and deny a direct call. A thrown error is treated
@@ -150,8 +205,20 @@ declare type McpWorkflowAssertion = (args: Record<string, unknown>, user: McpApp
150
205
  /**
151
206
  * Mount `server.callTool` as a `POST` handler that expects
152
207
  * `{ name, arguments }` in the JSON body.
208
+ *
209
+ * @deprecated Use {@link mountMcpRoute}; retained for one release so existing
210
+ * REST-shaped mounts can migrate without a coordinated cutover.
153
211
  */
154
- export declare function mountMcpCallRoute(server: McpAppServer, options?: MountMcpRouteOptions): SvelteKitHandler;
212
+ export declare function mountMcpCallRoute(server: McpAppServer, options?: MountMcpRouteOptions): McpSvelteKitHandler;
213
+
214
+ /**
215
+ * Mount a modern, stateless Streamable HTTP MCP endpoint as a SvelteKit
216
+ * `POST` handler. The scoped SDK validates the 2026-07-28 envelope plus the
217
+ * required `Mcp-Method` and `Mcp-Name` headers, returning `-32020` on a
218
+ * mismatch. A fresh protocol server is created for each HTTP request, so this
219
+ * route holds neither MCP sessions nor request principal state between nodes.
220
+ */
221
+ export declare function mountMcpRoute(server: McpAppServer, options?: MountMcpRouteOptions): McpSvelteKitHandler;
155
222
 
156
223
  /** Options shared by both route mounts. */
157
224
  export declare interface MountMcpRouteOptions {
@@ -174,10 +241,11 @@ export declare interface MountMcpRouteOptions {
174
241
  /**
175
242
  * Mount `server.listTools` as a `GET` handler. Returns the tool list shape
176
243
  * `{ tools }` for compatibility with the stock MCP bridge.
244
+ *
245
+ * @deprecated Use {@link mountMcpRoute}; retained for one release so existing
246
+ * REST-shaped mounts can migrate without a coordinated cutover.
177
247
  */
178
- export declare function mountMcpToolsRoute(server: McpAppServer, options?: MountMcpRouteOptions): SvelteKitHandler;
179
-
180
- declare type SvelteKitHandler = (event: SvelteKitRequestEvent) => Promise<Response>;
248
+ export declare function mountMcpToolsRoute(server: McpAppServer, options?: MountMcpRouteOptions): McpSvelteKitHandler;
181
249
 
182
250
  /** Minimal subset of a SvelteKit RequestEvent we actually touch. */
183
251
  declare type SvelteKitRequestEvent = {
package/dist/sveltekit.js CHANGED
@@ -1,4 +1,5 @@
1
- import { n as McpAccessError } from "./chunks/errors-CHYu0Vr2.js";
1
+ import { n as createMcpProtocolServer, t as MCP_TASKS_EXTENSION, u as McpAccessError } from "./chunks/protocol-DoieND6v.js";
2
+ import { classifyInboundRequest, createMcpHandler, isJsonContentType } from "@modelcontextprotocol/server";
2
3
  //#region src/sveltekit.ts
3
4
  var defaultResolvePrincipal = (event) => event.locals?.user ?? null;
4
5
  function resolveRequestPrincipal(event, options) {
@@ -16,6 +17,155 @@ function listToolsInput(resolved) {
16
17
  if (!resolved.principal && resolved.legacyAuthenticated) return { authenticated: true };
17
18
  return { principal: resolved.principal };
18
19
  }
20
+ function protocolServerForRequest(server, resolved) {
21
+ if (!resolved.legacyAuthenticated || resolved.principal) return server;
22
+ return {
23
+ serverInfo: server.serverInfo,
24
+ listTools: () => server.listTools({ authenticated: true }),
25
+ callTool: (input) => server.callTool(input)
26
+ };
27
+ }
28
+ function mountMcpRoute(server, options = {}) {
29
+ return async (event) => {
30
+ const resolved = resolveRequestPrincipal(event, options);
31
+ const taskResponse = await maybeHandleTaskRequest(server, resolved.principal, event.request);
32
+ if (taskResponse) return taskResponse;
33
+ return createMcpHandler(() => createMcpProtocolServer(protocolServerForRequest(server, resolved), { principal: resolved.principal }), {
34
+ legacy: "reject",
35
+ maxSubscriptions: 0
36
+ }).fetch(event.request);
37
+ };
38
+ }
39
+ async function maybeHandleTaskRequest(server, principal, request) {
40
+ if (!server.tasksEnabled || !server.callTask || !server.getTask || !server.updateTask || !server.cancelTask || request.method !== "POST") return null;
41
+ const body = await request.clone().json().catch(() => null);
42
+ if (body?.jsonrpc !== "2.0" || body.id === void 0) return null;
43
+ const params = body.params ?? {};
44
+ const taskTool = body.method === "tools/call" && typeof params.name === "string" && await server.isTaskTool?.(params.name) === true;
45
+ const taskMethod = [
46
+ "tasks/get",
47
+ "tasks/update",
48
+ "tasks/cancel"
49
+ ].includes(body.method ?? "");
50
+ if (!taskTool && !taskMethod) return null;
51
+ if (!isJsonContentType(request.headers.get("content-type"))) return null;
52
+ const classification = classifyInboundRequest({
53
+ httpMethod: request.method,
54
+ protocolVersionHeader: request.headers.get("mcp-protocol-version") ?? void 0,
55
+ mcpMethodHeader: request.headers.get("mcp-method") ?? void 0,
56
+ mcpNameHeader: request.headers.get("mcp-name") ?? void 0,
57
+ body
58
+ });
59
+ if (classification.kind === "reject") return jsonRpcResponse(body.id, void 0, {
60
+ code: classification.code,
61
+ message: classification.message,
62
+ ...classification.data === void 0 ? {} : { data: classification.data }
63
+ }, classification.httpStatus);
64
+ if (classification.kind !== "modern" || classification.classification.revision !== "2026-07-28") return null;
65
+ const headerMismatch = taskHeaderMismatch(request, body.method, params);
66
+ if (headerMismatch) return jsonRpcResponse(body.id, void 0, headerMismatch, 400);
67
+ const clientCapabilities = asRecord(params._meta)["io.modelcontextprotocol/clientCapabilities"];
68
+ const clientSupportsTasks = Object.hasOwn(asRecord(asRecord(clientCapabilities).extensions), MCP_TASKS_EXTENSION);
69
+ if (!clientSupportsTasks && body.method === "tools/call") return null;
70
+ if (!clientSupportsTasks) return jsonRpcResponse(body.id, void 0, {
71
+ code: -32021,
72
+ message: "Missing required client capability",
73
+ data: { requiredCapabilities: { extensions: { [MCP_TASKS_EXTENSION]: {} } } }
74
+ }, 400);
75
+ try {
76
+ if (body.method === "tools/call") {
77
+ const result = await server.callTask({
78
+ name: params.name,
79
+ arguments: params.arguments ?? {},
80
+ principal
81
+ });
82
+ return jsonRpcResponse(body.id, result);
83
+ }
84
+ if (typeof params.taskId !== "string") return jsonRpcResponse(body.id, void 0, {
85
+ code: -32602,
86
+ message: "taskId is required"
87
+ });
88
+ if (body.method === "tasks/get") {
89
+ const task = await server.getTask({
90
+ taskId: params.taskId,
91
+ principal
92
+ });
93
+ return jsonRpcResponse(body.id, {
94
+ resultType: "complete",
95
+ ...task
96
+ });
97
+ }
98
+ if (body.method === "tasks/update") {
99
+ await server.updateTask({
100
+ taskId: params.taskId,
101
+ inputResponses: params.inputResponses && typeof params.inputResponses === "object" ? params.inputResponses : {},
102
+ principal
103
+ });
104
+ return jsonRpcResponse(body.id, { resultType: "complete" });
105
+ }
106
+ await server.cancelTask({
107
+ taskId: params.taskId,
108
+ principal
109
+ });
110
+ return jsonRpcResponse(body.id, { resultType: "complete" });
111
+ } catch (error) {
112
+ if (error instanceof McpAccessError) {
113
+ const { code, retryable } = error.metadata;
114
+ return jsonRpcResponse(body.id, void 0, {
115
+ code: error.status === 404 ? -32602 : -32600,
116
+ message: error.message,
117
+ data: {
118
+ ...typeof code === "string" ? { code } : {},
119
+ ...typeof retryable === "boolean" ? { retryable } : {}
120
+ }
121
+ });
122
+ }
123
+ const message = error instanceof Error ? error.message : "Task operation failed";
124
+ return jsonRpcResponse(body.id, void 0, {
125
+ code: -32602,
126
+ message
127
+ });
128
+ }
129
+ }
130
+ function taskHeaderMismatch(request, method, params) {
131
+ if (!method || normalizeHeaderValue(request.headers.get("mcp-method") ?? "") !== method) return {
132
+ code: -32020,
133
+ message: "Mcp-Method header must match the JSON-RPC method."
134
+ };
135
+ const toolName = method === "tools/call" && typeof params.name === "string" ? params.name : void 0;
136
+ const headerName = request.headers.get("mcp-name");
137
+ if (toolName !== void 0 && (headerName === null || decodeMcpHeaderValue(headerName) !== toolName)) return {
138
+ code: -32020,
139
+ message: "Mcp-Name header must match the tools/call name."
140
+ };
141
+ }
142
+ function normalizeHeaderValue(value) {
143
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
144
+ }
145
+ function decodeMcpHeaderValue(value) {
146
+ const normalized = normalizeHeaderValue(value);
147
+ if (!normalized.startsWith("=?base64?") || !normalized.endsWith("?=")) return normalized;
148
+ const encoded = normalized.slice(9, -2);
149
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) return;
150
+ try {
151
+ return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0)));
152
+ } catch {
153
+ return;
154
+ }
155
+ }
156
+ function jsonRpcResponse(id, result, error, status = 200) {
157
+ return new Response(JSON.stringify({
158
+ jsonrpc: "2.0",
159
+ id,
160
+ ...error ? { error } : { result }
161
+ }), {
162
+ status,
163
+ headers: { "content-type": "application/json" }
164
+ });
165
+ }
166
+ function asRecord(value) {
167
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
168
+ }
19
169
  function mountMcpToolsRoute(server, options = {}) {
20
170
  return async (event) => {
21
171
  try {
@@ -61,6 +211,6 @@ function jsonResponse(body, status = 200) {
61
211
  });
62
212
  }
63
213
  //#endregion
64
- export { McpAccessError, mountMcpCallRoute, mountMcpToolsRoute };
214
+ export { McpAccessError, mountMcpCallRoute, mountMcpRoute, mountMcpToolsRoute };
65
215
 
66
216
  //# sourceMappingURL=sveltekit.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sveltekit.js","names":[],"sources":["../src/sveltekit.ts"],"sourcesContent":["/**\n * SvelteKit route adapters for an `McpAppServer`. Mirrors the\n * `@happyvertical/smrt-users/sveltekit` pattern: minimal `HandleInput` type\n * so we never need `@sveltejs/kit` as a real dependency.\n *\n * @packageDocumentation\n *\n * @example\n * ```ts\n * // src/routes/api/mcp/tools/+server.ts\n * import { mountMcpToolsRoute } from '@happyvertical/smrt-app-mcp/sveltekit';\n * import { mcpServer } from '$lib/server/mcp';\n * export const GET = mountMcpToolsRoute(mcpServer);\n * ```\n */\n\nimport { McpAccessError } from './errors.js';\nimport type { CallToolInput, McpAppPrincipal, McpAppServer } from './server.js';\n\n/** Minimal subset of a SvelteKit RequestEvent we actually touch. */\ntype SvelteKitRequestEvent = {\n locals?: Record<string, unknown>;\n request: Request;\n url: URL;\n};\n\ntype SvelteKitHandler = (event: SvelteKitRequestEvent) => Promise<Response>;\n\ntype ResolvedRequestPrincipal = {\n principal: McpAppPrincipal | null;\n /** Defined only for the legacy discovery-only authentication adapter. */\n legacyAuthenticated?: boolean;\n};\n\n/** Locals reader used to pull the request principal out of `event.locals`. */\nexport type McpPrincipalResolver = (\n event: SvelteKitRequestEvent,\n) => McpAppPrincipal | null | undefined;\n\n/** Backwards-compatible alias for callers that name the principal a user. */\nexport type McpUserResolver = McpPrincipalResolver;\n\nconst defaultResolvePrincipal: McpPrincipalResolver = (event) =>\n (event.locals?.user ?? null) as McpAppPrincipal | null;\n\nfunction resolveRequestPrincipal(\n event: SvelteKitRequestEvent,\n options: MountMcpRouteOptions,\n): ResolvedRequestPrincipal {\n const resolvePrincipal =\n options.resolvePrincipal ?? options.resolveUser ?? defaultResolvePrincipal;\n const principal = resolvePrincipal(event) ?? null;\n // Keep the legacy boolean gate for existing apps, but apply it to the same\n // principal that both routes receive. A new principal resolver supersedes it.\n if (\n !options.resolvePrincipal &&\n options.resolveAuthenticated &&\n !options.resolveAuthenticated(event)\n ) {\n return { principal: null, legacyAuthenticated: false };\n }\n return {\n principal,\n ...(options.resolvePrincipal || !options.resolveAuthenticated\n ? {}\n : { legacyAuthenticated: true }),\n };\n}\n\nfunction listToolsInput(resolved: ResolvedRequestPrincipal) {\n // Before principal-aware routes, `resolveAuthenticated` affected discovery\n // independently of `resolveUser`. Preserve a true legacy result only when\n // there is no principal to pass; new routes should use `resolvePrincipal`\n // for a single identity on both discovery and calls.\n if (!resolved.principal && resolved.legacyAuthenticated) {\n return { authenticated: true };\n }\n return { principal: resolved.principal };\n}\n\n/** Options shared by both route mounts. */\nexport interface MountMcpRouteOptions {\n /**\n * Resolve the request principal once for both discovery and direct calls.\n * Defaults to `event.locals.user`.\n */\n resolvePrincipal?: McpPrincipalResolver;\n /**\n * Backwards-compatible alias for `resolvePrincipal`.\n */\n resolveUser?: McpUserResolver;\n /**\n * Deprecated legacy authentication gate. When `resolvePrincipal` is not\n * supplied, a false result makes the principal null for both routes.\n */\n resolveAuthenticated?: (event: SvelteKitRequestEvent) => boolean;\n}\n\n/**\n * Mount `server.listTools` as a `GET` handler. Returns the tool list shape\n * `{ tools }` for compatibility with the stock MCP bridge.\n */\nexport function mountMcpToolsRoute(\n server: McpAppServer,\n options: MountMcpRouteOptions = {},\n): SvelteKitHandler {\n return async (event) => {\n try {\n const tools = await server.listTools(\n listToolsInput(resolveRequestPrincipal(event, options)),\n );\n return jsonResponse({ tools });\n } catch (error) {\n if (error instanceof McpAccessError) {\n return jsonResponse(mcpAccessErrorBody(error), error.status);\n }\n throw error;\n }\n };\n}\n\n/**\n * Mount `server.callTool` as a `POST` handler that expects\n * `{ name, arguments }` in the JSON body.\n */\nexport function mountMcpCallRoute(\n server: McpAppServer,\n options: MountMcpRouteOptions = {},\n): SvelteKitHandler {\n return async (event) => {\n const body = (await event.request.json().catch(() => null)) as {\n arguments?: Record<string, unknown>;\n name?: string;\n } | null;\n\n if (!body?.name) {\n return jsonResponse({ error: 'name is required.' }, 400);\n }\n\n const input: CallToolInput = {\n arguments: body.arguments ?? {},\n name: body.name,\n principal: resolveRequestPrincipal(event, options).principal,\n };\n\n try {\n return jsonResponse(await server.callTool(input));\n } catch (error) {\n if (error instanceof McpAccessError) {\n return jsonResponse(mcpAccessErrorBody(error), error.status);\n }\n throw error;\n }\n };\n}\n\nfunction mcpAccessErrorBody(error: McpAccessError): unknown {\n const { code, retryable } = error.metadata;\n // Preserve the legacy shape unless an error deliberately opts into the\n // shared structured failure contract.\n if (!code) return { error: error.message };\n return {\n error: {\n ok: false,\n code,\n message: error.message,\n status: error.status,\n ...(retryable === undefined ? {} : { retryable }),\n },\n };\n}\n\nfunction jsonResponse(body: unknown, status = 200): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n}\n\nexport { McpAccessError } from './errors.js';\nexport type { McpAppPrincipal, McpAppServer } from './server.js';\n"],"mappings":";;AA0CA,IAAM,2BAAiD,UACpD,MAAM,QAAQ,QAAQ;AAEzB,SAAS,wBACP,OACA,SAC0B;CAG1B,MAAM,aADJ,QAAQ,oBAAoB,QAAQ,eAAe,wBAAA,CAClB,KAAK,KAAK;CAG7C,IACE,CAAC,QAAQ,oBACT,QAAQ,wBACR,CAAC,QAAQ,qBAAqB,KAAK,GAEnC,OAAO;EAAE,WAAW;EAAM,qBAAqB;CAAM;CAEvD,OAAO;EACL;EACA,GAAI,QAAQ,oBAAoB,CAAC,QAAQ,uBACrC,CAAC,IACD,EAAE,qBAAqB,KAAK;CAClC;AACF;AAEA,SAAS,eAAe,UAAoC;CAK1D,IAAI,CAAC,SAAS,aAAa,SAAS,qBAClC,OAAO,EAAE,eAAe,KAAK;CAE/B,OAAO,EAAE,WAAW,SAAS,UAAU;AACzC;AAwBO,SAAS,mBACd,QACA,UAAgC,CAAC,GACf;CAClB,OAAO,OAAO,UAAU;EACtB,IAAI;GAIF,OAAO,aAAa,EAAE,OAAA,MAHF,OAAO,UACzB,eAAe,wBAAwB,OAAO,OAAO,CAAC,CACxD,EAC4B,CAAC;EAC/B,SAAS,OAAO;GACd,IAAI,iBAAiB,gBACnB,OAAO,aAAa,mBAAmB,KAAK,GAAG,MAAM,MAAM;GAE7D,MAAM;EACR;CACF;AACF;AAMO,SAAS,kBACd,QACA,UAAgC,CAAC,GACf;CAClB,OAAO,OAAO,UAAU;EACtB,MAAM,OAAQ,MAAM,MAAM,QAAQ,KAAK,CAAA,CAAE,YAAY,IAAI;EAKzD,IAAI,CAAC,MAAM,MACT,OAAO,aAAa,EAAE,OAAO,oBAAoB,GAAG,GAAG;EAGzD,MAAM,QAAuB;GAC3B,WAAW,KAAK,aAAa,CAAC;GAC9B,MAAM,KAAK;GACX,WAAW,wBAAwB,OAAO,OAAO,CAAA,CAAE;EACrD;EAEA,IAAI;GACF,OAAO,aAAa,MAAM,OAAO,SAAS,KAAK,CAAC;EAClD,SAAS,OAAO;GACd,IAAI,iBAAiB,gBACnB,OAAO,aAAa,mBAAmB,KAAK,GAAG,MAAM,MAAM;GAE7D,MAAM;EACR;CACF;AACF;AAEA,SAAS,mBAAmB,OAAgC;CAC1D,MAAM,EAAE,MAAM,cAAc,MAAM;CAGlC,IAAI,CAAC,MAAM,OAAO,EAAE,OAAO,MAAM,QAAQ;CACzC,OAAO,EACL,OAAO;EACL,IAAI;EACJ;EACA,SAAS,MAAM;EACf,QAAQ,MAAM;EACd,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;CACjD,EACF;AACF;AAEA,SAAS,aAAa,MAAe,SAAS,KAAe;CAC3D,OAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;EACxC;EACA,SAAS,EAAE,gBAAgB,mBAAmB;CAChD,CAAC;AACH"}
1
+ {"version":3,"file":"sveltekit.js","names":[],"sources":["../src/sveltekit.ts"],"sourcesContent":["/**\n * SvelteKit route adapters for an `McpAppServer`. Mirrors the\n * `@happyvertical/smrt-users/sveltekit` pattern: minimal `HandleInput` type\n * so we never need `@sveltejs/kit` as a real dependency.\n *\n * @packageDocumentation\n *\n * @example\n * ```ts\n * // src/routes/api/mcp/+server.ts\n * import { mountMcpRoute } from '@happyvertical/smrt-app-mcp/sveltekit';\n * import { mcpServer } from '$lib/server/mcp';\n * export const POST = mountMcpRoute(mcpServer);\n * ```\n */\n\nimport {\n classifyInboundRequest,\n createMcpHandler,\n isJsonContentType,\n} from '@modelcontextprotocol/server';\nimport { McpAccessError } from './errors.js';\nimport { createMcpProtocolServer, MCP_TASKS_EXTENSION } from './protocol.js';\nimport type { CallToolInput, McpAppPrincipal, McpAppServer } from './server.js';\n\n/** Minimal subset of a SvelteKit RequestEvent we actually touch. */\ntype SvelteKitRequestEvent = {\n locals?: Record<string, unknown>;\n request: Request;\n url: URL;\n};\n\n/** A SvelteKit `+server.ts` request handler with no SvelteKit dependency. */\nexport type McpSvelteKitHandler = (\n event: SvelteKitRequestEvent,\n) => Promise<Response>;\n\ntype ResolvedRequestPrincipal = {\n principal: McpAppPrincipal | null;\n /** Defined only for the legacy discovery-only authentication adapter. */\n legacyAuthenticated?: boolean;\n};\n\n/** Locals reader used to pull the request principal out of `event.locals`. */\nexport type McpPrincipalResolver = (\n event: SvelteKitRequestEvent,\n) => McpAppPrincipal | null | undefined;\n\n/** Backwards-compatible alias for callers that name the principal a user. */\nexport type McpUserResolver = McpPrincipalResolver;\n\nconst defaultResolvePrincipal: McpPrincipalResolver = (event) =>\n (event.locals?.user ?? null) as McpAppPrincipal | null;\n\nfunction resolveRequestPrincipal(\n event: SvelteKitRequestEvent,\n options: MountMcpRouteOptions,\n): ResolvedRequestPrincipal {\n const resolvePrincipal =\n options.resolvePrincipal ?? options.resolveUser ?? defaultResolvePrincipal;\n const principal = resolvePrincipal(event) ?? null;\n // Keep the legacy boolean gate for existing apps, but apply it to the same\n // principal that both routes receive. A new principal resolver supersedes it.\n if (\n !options.resolvePrincipal &&\n options.resolveAuthenticated &&\n !options.resolveAuthenticated(event)\n ) {\n return { principal: null, legacyAuthenticated: false };\n }\n return {\n principal,\n ...(options.resolvePrincipal || !options.resolveAuthenticated\n ? {}\n : { legacyAuthenticated: true }),\n };\n}\n\nfunction listToolsInput(resolved: ResolvedRequestPrincipal) {\n // Before principal-aware routes, `resolveAuthenticated` affected discovery\n // independently of `resolveUser`. Preserve a true legacy result only when\n // there is no principal to pass; new routes should use `resolvePrincipal`\n // for a single identity on both discovery and calls.\n if (!resolved.principal && resolved.legacyAuthenticated) {\n return { authenticated: true };\n }\n return { principal: resolved.principal };\n}\n\n/** Options shared by both route mounts. */\nexport interface MountMcpRouteOptions {\n /**\n * Resolve the request principal once for both discovery and direct calls.\n * Defaults to `event.locals.user`.\n */\n resolvePrincipal?: McpPrincipalResolver;\n /**\n * Backwards-compatible alias for `resolvePrincipal`.\n */\n resolveUser?: McpUserResolver;\n /**\n * Deprecated legacy authentication gate. When `resolvePrincipal` is not\n * supplied, a false result makes the principal null for both routes.\n */\n resolveAuthenticated?: (event: SvelteKitRequestEvent) => boolean;\n}\n\nfunction protocolServerForRequest(\n server: McpAppServer,\n resolved: ResolvedRequestPrincipal,\n): McpAppServer {\n // Older applications sometimes used a boolean discovery-only adapter. Keep\n // its positive result intact for the deprecated resolver while new mounts\n // consistently use the principal on both MCP methods.\n if (!resolved.legacyAuthenticated || resolved.principal) return server;\n return {\n serverInfo: server.serverInfo,\n listTools: () => server.listTools({ authenticated: true }),\n callTool: (input) => server.callTool(input),\n };\n}\n\n/**\n * Mount a modern, stateless Streamable HTTP MCP endpoint as a SvelteKit\n * `POST` handler. The scoped SDK validates the 2026-07-28 envelope plus the\n * required `Mcp-Method` and `Mcp-Name` headers, returning `-32020` on a\n * mismatch. A fresh protocol server is created for each HTTP request, so this\n * route holds neither MCP sessions nor request principal state between nodes.\n */\nexport function mountMcpRoute(\n server: McpAppServer,\n options: MountMcpRouteOptions = {},\n): McpSvelteKitHandler {\n return async (event) => {\n const resolved = resolveRequestPrincipal(event, options);\n const taskResponse = await maybeHandleTaskRequest(\n server,\n resolved.principal,\n event.request,\n );\n if (taskResponse) return taskResponse;\n const handler = createMcpHandler(\n () =>\n createMcpProtocolServer(protocolServerForRequest(server, resolved), {\n principal: resolved.principal,\n }),\n {\n // The legacy REST-shaped mounts below remain the migration path for\n // one release. This endpoint is deliberately 2026-07-28-only.\n legacy: 'reject',\n // The SDK validates every request before consulting its listen router.\n // Zero capacity keeps this tools-only mount stateless by refusing a\n // listen request before it can open an SSE response.\n maxSubscriptions: 0,\n },\n );\n return handler.fetch(event.request);\n };\n}\n\n/**\n * The installed MCP SDK validates tools/call against a pre-Tasks result codec.\n * Intercept the extension before the SDK handler so the regular stateless HTTP\n * protocol stays untouched for every other method.\n */\nasync function maybeHandleTaskRequest(\n server: McpAppServer,\n principal: McpAppPrincipal | null,\n request: Request,\n): Promise<Response | null> {\n if (\n !server.tasksEnabled ||\n !server.callTask ||\n !server.getTask ||\n !server.updateTask ||\n !server.cancelTask ||\n request.method !== 'POST'\n ) {\n return null;\n }\n const body = (await request\n .clone()\n .json()\n .catch(() => null)) as {\n id?: string | number | null;\n jsonrpc?: string;\n method?: string;\n params?: Record<string, unknown>;\n } | null;\n if (body?.jsonrpc !== '2.0' || body.id === undefined) return null;\n const params = body.params ?? {};\n const taskTool =\n body.method === 'tools/call' &&\n typeof params.name === 'string' &&\n (await server.isTaskTool?.(params.name)) === true;\n const taskMethod = ['tasks/get', 'tasks/update', 'tasks/cancel'].includes(\n body.method ?? '',\n );\n if (!taskTool && !taskMethod) return null;\n\n // Keep task requests on the SDK's protocol-validation path until their\n // 2026 request envelope is known-good. In particular, never enqueue durable\n // work for malformed envelopes, unsupported revisions, or non-JSON bodies.\n // The fallback handler owns its wire-exact error response for those cases.\n if (!isJsonContentType(request.headers.get('content-type'))) return null;\n const classification = classifyInboundRequest({\n httpMethod: request.method,\n protocolVersionHeader:\n request.headers.get('mcp-protocol-version') ?? undefined,\n mcpMethodHeader: request.headers.get('mcp-method') ?? undefined,\n mcpNameHeader: request.headers.get('mcp-name') ?? undefined,\n body: body as never,\n });\n if (classification.kind === 'reject') {\n return jsonRpcResponse(\n body.id,\n undefined,\n {\n code: classification.code,\n message: classification.message,\n ...(classification.data === undefined\n ? {}\n : { data: classification.data }),\n },\n classification.httpStatus,\n );\n }\n if (\n classification.kind !== 'modern' ||\n classification.classification.revision !== '2026-07-28'\n ) {\n return null;\n }\n\n // The SDK normally performs this modern HTTP routing validation before\n // dispatch. Task responses are intercepted ahead of that SDK handler, so\n // retain the same fail-closed header/body contract here.\n const headerMismatch = taskHeaderMismatch(request, body.method, params);\n if (headerMismatch) {\n return jsonRpcResponse(body.id, undefined, headerMismatch, 400);\n }\n\n const clientCapabilities = asRecord(params._meta)[\n 'io.modelcontextprotocol/clientCapabilities'\n ];\n const clientSupportsTasks = Object.hasOwn(\n asRecord(asRecord(clientCapabilities).extensions),\n MCP_TASKS_EXTENSION,\n );\n\n // A synchronous fallback exists for tools/call; lifecycle methods do not.\n if (!clientSupportsTasks && body.method === 'tools/call') return null;\n if (!clientSupportsTasks) {\n return jsonRpcResponse(\n body.id,\n undefined,\n {\n code: -32021,\n message: 'Missing required client capability',\n data: {\n requiredCapabilities: { extensions: { [MCP_TASKS_EXTENSION]: {} } },\n },\n },\n 400,\n );\n }\n\n try {\n if (body.method === 'tools/call') {\n const result = await server.callTask({\n name: params.name as string,\n arguments: (params.arguments as Record<string, unknown>) ?? {},\n principal,\n });\n return jsonRpcResponse(body.id, result);\n }\n if (typeof params.taskId !== 'string') {\n return jsonRpcResponse(body.id, undefined, {\n code: -32602,\n message: 'taskId is required',\n });\n }\n if (body.method === 'tasks/get') {\n const task = await server.getTask({ taskId: params.taskId, principal });\n return jsonRpcResponse(body.id, { resultType: 'complete', ...task });\n }\n if (body.method === 'tasks/update') {\n await server.updateTask({\n taskId: params.taskId,\n inputResponses:\n params.inputResponses && typeof params.inputResponses === 'object'\n ? (params.inputResponses as Record<string, unknown>)\n : {},\n principal,\n });\n return jsonRpcResponse(body.id, { resultType: 'complete' });\n }\n await server.cancelTask({ taskId: params.taskId, principal });\n return jsonRpcResponse(body.id, { resultType: 'complete' });\n } catch (error) {\n if (error instanceof McpAccessError) {\n const { code, retryable } = error.metadata;\n return jsonRpcResponse(body.id, undefined, {\n code: error.status === 404 ? -32602 : -32600,\n message: error.message,\n data: {\n ...(typeof code === 'string' ? { code } : {}),\n ...(typeof retryable === 'boolean' ? { retryable } : {}),\n },\n });\n }\n const message =\n error instanceof Error ? error.message : 'Task operation failed';\n return jsonRpcResponse(body.id, undefined, { code: -32602, message });\n }\n}\n\nfunction taskHeaderMismatch(\n request: Request,\n method: string | undefined,\n params: Record<string, unknown>,\n): { code: number; message: string } | undefined {\n if (\n !method ||\n normalizeHeaderValue(request.headers.get('mcp-method') ?? '') !== method\n ) {\n return {\n code: -32020,\n message: 'Mcp-Method header must match the JSON-RPC method.',\n };\n }\n const toolName =\n method === 'tools/call' && typeof params.name === 'string'\n ? params.name\n : undefined;\n const headerName = request.headers.get('mcp-name');\n if (\n toolName !== undefined &&\n (headerName === null || decodeMcpHeaderValue(headerName) !== toolName)\n ) {\n return {\n code: -32020,\n message: 'Mcp-Name header must match the tools/call name.',\n };\n }\n return undefined;\n}\n\n/** Match the SDK's RFC 9110 optional-whitespace handling for MCP headers. */\nfunction normalizeHeaderValue(value: string): string {\n return value.replace(/^[\\t ]+|[\\t ]+$/g, '');\n}\n\n/** Decode the SDK's canonical Base64 sentinel for an MCP header value. */\nfunction decodeMcpHeaderValue(value: string): string | undefined {\n const normalized = normalizeHeaderValue(value);\n const prefix = '=?base64?';\n if (!normalized.startsWith(prefix) || !normalized.endsWith('?=')) {\n return normalized;\n }\n const encoded = normalized.slice(prefix.length, -2);\n if (\n !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(\n encoded,\n )\n ) {\n return undefined;\n }\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(\n Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0)),\n );\n } catch {\n return undefined;\n }\n}\n\nfunction jsonRpcResponse(\n id: string | number | null,\n result?: unknown,\n error?: { code: number; message: string; data?: unknown },\n status = 200,\n): Response {\n return new Response(\n JSON.stringify({ jsonrpc: '2.0', id, ...(error ? { error } : { result }) }),\n { status, headers: { 'content-type': 'application/json' } },\n );\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\n/**\n * Mount `server.listTools` as a `GET` handler. Returns the tool list shape\n * `{ tools }` for compatibility with the stock MCP bridge.\n *\n * @deprecated Use {@link mountMcpRoute}; retained for one release so existing\n * REST-shaped mounts can migrate without a coordinated cutover.\n */\nexport function mountMcpToolsRoute(\n server: McpAppServer,\n options: MountMcpRouteOptions = {},\n): McpSvelteKitHandler {\n return async (event) => {\n try {\n const tools = await server.listTools(\n listToolsInput(resolveRequestPrincipal(event, options)),\n );\n return jsonResponse({ tools });\n } catch (error) {\n if (error instanceof McpAccessError) {\n return jsonResponse(mcpAccessErrorBody(error), error.status);\n }\n throw error;\n }\n };\n}\n\n/**\n * Mount `server.callTool` as a `POST` handler that expects\n * `{ name, arguments }` in the JSON body.\n *\n * @deprecated Use {@link mountMcpRoute}; retained for one release so existing\n * REST-shaped mounts can migrate without a coordinated cutover.\n */\nexport function mountMcpCallRoute(\n server: McpAppServer,\n options: MountMcpRouteOptions = {},\n): McpSvelteKitHandler {\n return async (event) => {\n const body = (await event.request.json().catch(() => null)) as {\n arguments?: Record<string, unknown>;\n name?: string;\n } | null;\n\n if (!body?.name) {\n return jsonResponse({ error: 'name is required.' }, 400);\n }\n\n const input: CallToolInput = {\n arguments: body.arguments ?? {},\n name: body.name,\n principal: resolveRequestPrincipal(event, options).principal,\n };\n\n try {\n return jsonResponse(await server.callTool(input));\n } catch (error) {\n if (error instanceof McpAccessError) {\n return jsonResponse(mcpAccessErrorBody(error), error.status);\n }\n throw error;\n }\n };\n}\n\nfunction mcpAccessErrorBody(error: McpAccessError): unknown {\n const { code, retryable } = error.metadata;\n // Preserve the legacy shape unless an error deliberately opts into the\n // shared structured failure contract.\n if (!code) return { error: error.message };\n return {\n error: {\n ok: false,\n code,\n message: error.message,\n status: error.status,\n ...(retryable === undefined ? {} : { retryable }),\n },\n };\n}\n\nfunction jsonResponse(body: unknown, status = 200): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n}\n\nexport { McpAccessError } from './errors.js';\nexport type { McpAppPrincipal, McpAppServer } from './server.js';\n"],"mappings":";;;AAmDA,IAAM,2BAAiD,UACpD,MAAM,QAAQ,QAAQ;AAEzB,SAAS,wBACP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KAAe;CAC3D,OAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;EACxC;EACA,SAAS,EAAE,gBAAgB,mBAAmB;CAChD,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-app-mcp",
3
- "version": "0.40.60",
3
+ "version": "0.40.62",
4
4
  "description": "App-runtime MCP server scaffolding for SMRT apps — `createMcpAppServer` plus transport adapters (SvelteKit today) for exposing a SMRT app's MCP surface over HTTP.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -43,10 +43,13 @@
43
43
  ],
44
44
  "author": "HappyVertical",
45
45
  "dependencies": {
46
+ "@happyvertical/sql": "^0.85.5",
46
47
  "@modelcontextprotocol/server": "2.0.0",
47
- "@happyvertical/smrt-core": "0.40.60"
48
+ "@happyvertical/smrt-core": "0.40.62",
49
+ "@happyvertical/smrt-jobs": "0.40.62"
48
50
  },
49
51
  "devDependencies": {
52
+ "@modelcontextprotocol/client": "2.0.0",
50
53
  "@modelcontextprotocol/conformance": "0.2.0-alpha.10",
51
54
  "@modelcontextprotocol/node": "2.0.0",
52
55
  "@types/node": "24.13.2",
@@ -1,16 +0,0 @@
1
- //#region src/errors.ts
2
- var MCP_TOOL_ACCESS_DENIED_CODE = "mcp_tool_access_denied";
3
- var McpAccessError = class extends Error {
4
- constructor(status, message, metadata = {}) {
5
- super(message);
6
- this.status = status;
7
- this.metadata = metadata;
8
- this.name = "McpAccessError";
9
- }
10
- status;
11
- metadata;
12
- };
13
- //#endregion
14
- export { McpAccessError as n, MCP_TOOL_ACCESS_DENIED_CODE as t };
15
-
16
- //# sourceMappingURL=errors-CHYu0Vr2.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"errors-CHYu0Vr2.js","names":[],"sources":["../../src/errors.ts"],"sourcesContent":["/** Machine-readable code for a principal policy denial. */\nexport const MCP_TOOL_ACCESS_DENIED_CODE = 'mcp_tool_access_denied';\n\n/**\n * Metadata that is safe to expose for an app-MCP access failure. Policy\n * implementations must not place principal, scope, tool, or internal-error\n * details here.\n */\nexport interface McpAccessErrorMetadata {\n code?: string;\n retryable?: boolean;\n}\n\n/**\n * Error returned by the MCP app server when a caller tries to use a tool\n * they are not allowed to access. The HTTP layer should map `status` onto\n * the response status code.\n */\nexport class McpAccessError extends Error {\n constructor(\n readonly status: number,\n message: string,\n readonly metadata: McpAccessErrorMetadata = {},\n ) {\n super(message);\n this.name = 'McpAccessError';\n }\n}\n"],"mappings":";AACO,IAAM,8BAA8B;AAiBpC,IAAM,iBAAN,cAA6B,MAAM;CACxC,YACW,QACT,SACS,WAAmC,CAAC,GAC7C;EACA,MAAM,OAAO;EAJJ,KAAA,SAAA;EAEA,KAAA,WAAA;EAGT,KAAK,OAAO;CACd;CANW;CAEA;AAKb"}