@happyvertical/smrt-app-mcp 0.40.61 → 0.40.63
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 +8 -2
- package/dist/chunks/{protocol-DfGYbPjN.js → protocol-DoieND6v.js} +8 -3
- package/dist/chunks/protocol-DoieND6v.js.map +1 -0
- package/dist/index.d.ts +34 -2
- package/dist/index.js +82 -3
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +3 -2
- package/dist/smrt-knowledge.json +10 -5
- package/dist/sveltekit.d.ts +27 -0
- package/dist/sveltekit.js +134 -2
- package/dist/sveltekit.js.map +1 -1
- package/package.json +4 -2
- package/dist/chunks/protocol-DfGYbPjN.js.map +0 -1
package/README.md
CHANGED
|
@@ -53,8 +53,14 @@ export const POST = mountMcpRoute(mcpServer);
|
|
|
53
53
|
|
|
54
54
|
`mountMcpRoute` is a modern-only, fetch-style Streamable HTTP endpoint. It
|
|
55
55
|
serves `server/discover`, `tools/list`, and `tools/call` with the SDK's
|
|
56
|
-
2026-07-28 envelope
|
|
57
|
-
|
|
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
|
|
58
64
|
`Mcp-Method` header (and `Mcp-Name` for `tools/call`); the mount validates them
|
|
59
65
|
against the JSON-RPC body and returns the protocol `HeaderMismatch` error
|
|
60
66
|
(`-32020`, HTTP 400) for a missing or mismatched header.
|
|
@@ -47,6 +47,7 @@ function compareMcpToolNames(left, right) {
|
|
|
47
47
|
}
|
|
48
48
|
//#endregion
|
|
49
49
|
//#region src/protocol.ts
|
|
50
|
+
var MCP_TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
|
|
50
51
|
var DEFAULT_TOOL_LIST_CACHE_HINT = {
|
|
51
52
|
ttlMs: 864e5,
|
|
52
53
|
cacheScope: "private"
|
|
@@ -56,8 +57,12 @@ async function resolvePrincipal(option, context) {
|
|
|
56
57
|
return option ?? null;
|
|
57
58
|
}
|
|
58
59
|
function createMcpProtocolServer(appServer, options = {}) {
|
|
60
|
+
const tasksEnabled = appServer.tasksEnabled && typeof options.principal !== "function" && Boolean(options.principal?.id);
|
|
59
61
|
const server = new Server(appServer.serverInfo, {
|
|
60
|
-
capabilities: {
|
|
62
|
+
capabilities: {
|
|
63
|
+
tools: {},
|
|
64
|
+
...tasksEnabled ? { extensions: { [MCP_TASKS_EXTENSION]: {} } } : {}
|
|
65
|
+
},
|
|
61
66
|
cacheHints: { "tools/list": DEFAULT_TOOL_LIST_CACHE_HINT }
|
|
62
67
|
});
|
|
63
68
|
server.setRequestHandler("tools/list", async (_request, context) => {
|
|
@@ -89,6 +94,6 @@ function createMcpProtocolServer(appServer, options = {}) {
|
|
|
89
94
|
return server;
|
|
90
95
|
}
|
|
91
96
|
//#endregion
|
|
92
|
-
export {
|
|
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 };
|
|
93
98
|
|
|
94
|
-
//# sourceMappingURL=protocol-
|
|
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;CACxC,YACW,QACT,SACS,WAAmC,CAAC,GAC7C;EACA,MAAM,OAAO;EAJJ,KAAA,SAAA;EAEA,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+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';
|
|
@@ -50,8 +51,13 @@ export declare function classNamePrefixes(classNames: readonly string[]): Readon
|
|
|
50
51
|
|
|
51
52
|
/**
|
|
52
53
|
* Build the app-runtime MCP server core. The returned object is intentionally
|
|
53
|
-
* framework-agnostic: HTTP wrappers live in `@happyvertical/smrt-app-mcp/sveltekit
|
|
54
|
-
*
|
|
54
|
+
* framework-agnostic: HTTP wrappers live in `@happyvertical/smrt-app-mcp/sveltekit`,
|
|
55
|
+
* this package's only other export.
|
|
56
|
+
*
|
|
57
|
+
* This package ships no stdio bridge. To pipe a deployed app's HTTP MCP surface
|
|
58
|
+
* to a local stdio MCP client, use `@happyvertical/smrt-app-cli`, which provides
|
|
59
|
+
* a generic `smrt-mcp-bridge` bin plus `runMcpStdioBridge` and
|
|
60
|
+
* `createAppCli().startMcpBridge()` for branded entry points.
|
|
55
61
|
*/
|
|
56
62
|
export declare function createMcpAppServer(options: CreateMcpAppServerOptions): McpAppServer;
|
|
57
63
|
|
|
@@ -183,6 +189,10 @@ export declare interface McpAccessErrorMetadata {
|
|
|
183
189
|
*/
|
|
184
190
|
export declare interface McpAppPrincipal {
|
|
185
191
|
id?: string;
|
|
192
|
+
/** Tenant boundary for task ownership and generated tenant-scoped actions. */
|
|
193
|
+
tenantId?: string;
|
|
194
|
+
/** Trusted operator override for generated tenant-scoped actions. */
|
|
195
|
+
allowCrossTenant?: boolean;
|
|
186
196
|
kind?: string;
|
|
187
197
|
roles?: string[];
|
|
188
198
|
scopes?: string[];
|
|
@@ -192,6 +202,28 @@ export declare interface McpAppPrincipal {
|
|
|
192
202
|
export declare interface McpAppServer {
|
|
193
203
|
listTools(input: ListToolsInput): Promise<MCPTool[]>;
|
|
194
204
|
callTool(input: CallToolInput): Promise<MCPResponse>;
|
|
205
|
+
/** Whether this app has any explicitly enabled Tasks extension action. */
|
|
206
|
+
hasTaskSupport?(): Promise<boolean>;
|
|
207
|
+
/** Whether a particular visible tool is task-enabled. */
|
|
208
|
+
isTaskTool?(name: string): Promise<boolean>;
|
|
209
|
+
/** Static declaration used by the protocol discovery capability surface. */
|
|
210
|
+
readonly tasksEnabled?: boolean;
|
|
211
|
+
/** Create a durable task after applying the same tool policy as tools/call. */
|
|
212
|
+
callTask?(input: CallToolInput): Promise<MCPResponse>;
|
|
213
|
+
/** Principal-scoped task lifecycle operations. */
|
|
214
|
+
getTask?(input: {
|
|
215
|
+
taskId: string;
|
|
216
|
+
principal?: McpAppPrincipal | null;
|
|
217
|
+
}): Promise<McpTask>;
|
|
218
|
+
updateTask?(input: {
|
|
219
|
+
taskId: string;
|
|
220
|
+
inputResponses: Record<string, unknown>;
|
|
221
|
+
principal?: McpAppPrincipal | null;
|
|
222
|
+
}): Promise<void>;
|
|
223
|
+
cancelTask?(input: {
|
|
224
|
+
taskId: string;
|
|
225
|
+
principal?: McpAppPrincipal | null;
|
|
226
|
+
}): Promise<void>;
|
|
195
227
|
/** Cache policy for protocol tools/list responses. */
|
|
196
228
|
getToolsListCacheHint?(): Promise<McpToolListCacheHint>;
|
|
197
229
|
/** Read-only view of the configured server identity. */
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { a as
|
|
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
2
|
import { ObjectRegistry, isTenantScopedClassResolved } from "@happyvertical/smrt-core";
|
|
3
3
|
import { MCPGenerator, MCP_STABLE_CATALOG_TTL_MS } from "@happyvertical/smrt-core/generators/mcp";
|
|
4
|
+
import { McpTaskNotFoundError, McpTaskStore } from "@happyvertical/smrt-jobs";
|
|
4
5
|
//#region src/server.ts
|
|
5
6
|
function configuredToolListCacheHint(options) {
|
|
6
7
|
const ttlMs = options?.ttlMs ?? MCP_STABLE_CATALOG_TTL_MS;
|
|
@@ -21,12 +22,19 @@ function isTenantScopedTool(tool) {
|
|
|
21
22
|
}
|
|
22
23
|
return false;
|
|
23
24
|
}
|
|
25
|
+
function taskOwnerIdFor(principal) {
|
|
26
|
+
return JSON.stringify([principal.tenantId ?? null, principal.id]);
|
|
27
|
+
}
|
|
24
28
|
function createMcpAppServer(options) {
|
|
25
29
|
const allowedPrefixes = classNamePrefixes(options.allowedClassNames);
|
|
26
30
|
const getPublicPatterns = options.publicToolPatterns ?? (() => []);
|
|
27
31
|
const toolPolicy = options.toolPolicy;
|
|
28
32
|
const workflowAssertions = options.workflowAssertions ?? {};
|
|
29
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
|
+
});
|
|
30
38
|
function userForGenerator(principal) {
|
|
31
39
|
if (!principal?.id) return void 0;
|
|
32
40
|
return {
|
|
@@ -34,11 +42,20 @@ function createMcpAppServer(options) {
|
|
|
34
42
|
roles: principal.roles
|
|
35
43
|
};
|
|
36
44
|
}
|
|
37
|
-
function
|
|
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) {
|
|
38
52
|
const user = userForGenerator(principal);
|
|
39
53
|
return new MCPGenerator(options.serverInfo, {
|
|
40
54
|
...options.smrtOptions(),
|
|
41
|
-
user
|
|
55
|
+
user,
|
|
56
|
+
tenantId: principal?.tenantId,
|
|
57
|
+
allowCrossTenant: principal?.allowCrossTenant,
|
|
58
|
+
...taskStore ? { taskStore } : {}
|
|
42
59
|
});
|
|
43
60
|
}
|
|
44
61
|
function principalForList(input) {
|
|
@@ -106,9 +123,71 @@ function createMcpAppServer(options) {
|
|
|
106
123
|
}
|
|
107
124
|
});
|
|
108
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
|
+
}
|
|
109
181
|
return {
|
|
110
182
|
listTools,
|
|
111
183
|
callTool,
|
|
184
|
+
hasTaskSupport,
|
|
185
|
+
isTaskTool,
|
|
186
|
+
callTask,
|
|
187
|
+
getTask,
|
|
188
|
+
updateTask,
|
|
189
|
+
cancelTask,
|
|
190
|
+
tasksEnabled,
|
|
112
191
|
getToolsListCacheHint,
|
|
113
192
|
serverInfo: options.serverInfo
|
|
114
193
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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 { 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 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 /** 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 * 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\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\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 return {\n listTools,\n callTool,\n getToolsListCacheHint,\n serverInfo: options.serverInfo,\n };\n}\n"],"mappings":";;;;AA4LA,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,WACR,0DACF;CAEF,OAAO;EACL;EACA,YACE,SAAS,eAAe,YAAY,QAAQ,kBAAkB,OAC1D,WACA;CACR;AACF;AAEA,SAAS,mBAAmB,MAAwB;CAClD,MAAM,YAAY,KAAK,KAAK,QAAQ,GAAG;CACvC,IAAI,aAAa,GAAG,OAAO;CAC3B,MAAM,aAAa,KAAK,KAAK,MAAM,GAAG,SAAS,CAAA,CAAE,YAAY;CAC7D,KAAA,MAAW,CAAC,KAAK,cAAc,eAAe,cAAc,GAAG;EAC7D,MAAM,OAAO,UAAU,QAAQ;EAC/B,IAAI,KAAK,YAAY,MAAM,YACzB,OACE,eAAe,eAAe,IAAI,KAAK,4BAA4B,IAAI;CAG7E;CACA,OAAO;AACT;AAOO,SAAS,mBACd,SACc;CACd,MAAM,kBAAkB,kBAAkB,QAAQ,iBAAiB;CACnE,M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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 * this package's only other export.\n *\n * This package ships no stdio bridge. To pipe a deployed app's HTTP MCP surface\n * to a local stdio MCP client, use `@happyvertical/smrt-app-cli`, which provides\n * a generic `smrt-mcp-bridge` bin plus `runMcpStdioBridge` and\n * `createAppCli().startMcpBridge()` for branded entry points.\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;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ACd,IAAI,iBAAiB,sBACnB,MAAM,IAAI,eAAe,KAAK,mBAAmB;GAEnD,MAAM;EACR;CACF;CAEA,eAAe,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"}
|
package/dist/manifest.json
CHANGED
|
@@ -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.
|
|
5
|
+
"packageVersion": "0.40.63",
|
|
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
|
}
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -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.
|
|
5
|
+
"packageVersion": "0.40.63",
|
|
6
6
|
"sourceManifestPath": "dist/manifest.json",
|
|
7
7
|
"agentDocPath": "AGENTS.md",
|
|
8
8
|
"sourceHashes": {
|
|
9
|
-
"manifest": "
|
|
10
|
-
"packageJson": "
|
|
9
|
+
"manifest": "8800ea9ffd9406f76d03edc3230b4774aac5175dd9713ea27d2c56f4cc50e465",
|
|
10
|
+
"packageJson": "fd2823f3326786fc4e65ca2aed1e72548634364ef52a8546de3668f113208ee1",
|
|
11
11
|
"agents": "fd1dc36d1530f81aae49e6efa2e2f5011a8a62d30816f25649d4cb597fc5662a"
|
|
12
12
|
},
|
|
13
13
|
"exports": [
|
|
@@ -16,6 +16,8 @@
|
|
|
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",
|
|
20
22
|
"@modelcontextprotocol/client": "2.0.0",
|
|
21
23
|
"@modelcontextprotocol/conformance": "0.2.0-alpha.10",
|
|
@@ -26,9 +28,12 @@
|
|
|
26
28
|
"vitest": "4.1.10"
|
|
27
29
|
},
|
|
28
30
|
"smrtDependencies": [
|
|
29
|
-
"@happyvertical/smrt-core"
|
|
31
|
+
"@happyvertical/smrt-core",
|
|
32
|
+
"@happyvertical/smrt-jobs"
|
|
33
|
+
],
|
|
34
|
+
"sdkDependencies": [
|
|
35
|
+
"@happyvertical/sql"
|
|
30
36
|
],
|
|
31
|
-
"sdkDependencies": [],
|
|
32
37
|
"tags": [],
|
|
33
38
|
"risks": [],
|
|
34
39
|
"objects": [],
|
package/dist/sveltekit.d.ts
CHANGED
|
@@ -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. */
|
|
@@ -98,6 +99,10 @@ declare interface McpAccessErrorMetadata {
|
|
|
98
99
|
*/
|
|
99
100
|
export declare interface McpAppPrincipal {
|
|
100
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;
|
|
101
106
|
kind?: string;
|
|
102
107
|
roles?: string[];
|
|
103
108
|
scopes?: string[];
|
|
@@ -107,6 +112,28 @@ export declare interface McpAppPrincipal {
|
|
|
107
112
|
export declare interface McpAppServer {
|
|
108
113
|
listTools(input: ListToolsInput): Promise<MCPTool[]>;
|
|
109
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>;
|
|
110
137
|
/** Cache policy for protocol tools/list responses. */
|
|
111
138
|
getToolsListCacheHint?(): Promise<McpToolListCacheHint>;
|
|
112
139
|
/** Read-only view of the configured server identity. */
|
package/dist/sveltekit.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { createMcpHandler } from "@modelcontextprotocol/server";
|
|
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";
|
|
3
3
|
//#region src/sveltekit.ts
|
|
4
4
|
var defaultResolvePrincipal = (event) => event.locals?.user ?? null;
|
|
5
5
|
function resolveRequestPrincipal(event, options) {
|
|
@@ -28,12 +28,144 @@ function protocolServerForRequest(server, resolved) {
|
|
|
28
28
|
function mountMcpRoute(server, options = {}) {
|
|
29
29
|
return async (event) => {
|
|
30
30
|
const resolved = resolveRequestPrincipal(event, options);
|
|
31
|
+
const taskResponse = await maybeHandleTaskRequest(server, resolved.principal, event.request);
|
|
32
|
+
if (taskResponse) return taskResponse;
|
|
31
33
|
return createMcpHandler(() => createMcpProtocolServer(protocolServerForRequest(server, resolved), { principal: resolved.principal }), {
|
|
32
34
|
legacy: "reject",
|
|
33
35
|
maxSubscriptions: 0
|
|
34
36
|
}).fetch(event.request);
|
|
35
37
|
};
|
|
36
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
|
+
}
|
|
37
169
|
function mountMcpToolsRoute(server, options = {}) {
|
|
38
170
|
return async (event) => {
|
|
39
171
|
try {
|
package/dist/sveltekit.js.map
CHANGED
|
@@ -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/+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 { createMcpHandler } from '@modelcontextprotocol/server';\nimport { McpAccessError } from './errors.js';\nimport { createMcpProtocolServer } 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 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 * 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":";;;AA+CA,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;AAoBA,SAAS,yBACP,QACA,UACc;CAId,IAAI,CAAC,SAAS,uBAAuB,SAAS,WAAW,OAAO;CAChE,OAAO;EACL,YAAY,OAAO;EACnB,iBAAiB,OAAO,UAAU,EAAE,eAAe,KAAK,CAAC;EACzD,WAAW,UAAU,OAAO,SAAS,KAAK;CAC5C;AACF;AASO,SAAS,cACd,QACA,UAAgC,CAAC,GACZ;CACrB,OAAO,OAAO,UAAU;EACtB,MAAM,WAAW,w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,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,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;AAoBA,SAAS,yBACP,QAC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Z;CACrB,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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-app-mcp",
|
|
3
|
-
"version": "0.40.
|
|
3
|
+
"version": "0.40.63",
|
|
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,8 +43,10 @@
|
|
|
43
43
|
],
|
|
44
44
|
"author": "HappyVertical",
|
|
45
45
|
"dependencies": {
|
|
46
|
+
"@happyvertical/sql": "^0.86.1",
|
|
46
47
|
"@modelcontextprotocol/server": "2.0.0",
|
|
47
|
-
"@happyvertical/smrt-core": "0.40.
|
|
48
|
+
"@happyvertical/smrt-core": "0.40.63",
|
|
49
|
+
"@happyvertical/smrt-jobs": "0.40.63"
|
|
48
50
|
},
|
|
49
51
|
"devDependencies": {
|
|
50
52
|
"@modelcontextprotocol/client": "2.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"protocol-DfGYbPjN.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\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 const server = new Server(appServer.serverInfo, {\n capabilities: { tools: {} },\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 === 'bool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