@happyvertical/smrt-core 0.56.0 → 0.56.2
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/AGENTS.md +6 -0
- package/agents/browser-entry.md +5 -0
- package/agents/generators.md +61 -0
- package/agents/object-runtime.md +17 -0
- package/dist/browser.d.ts +2 -0
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +3 -1
- package/dist/cookbook/engine/commands.d.ts.map +1 -1
- package/dist/cookbook/engine/commands.js +12 -0
- package/dist/cookbook/engine/commands.js.map +1 -1
- package/dist/cookbook/engine/defaults.d.ts.map +1 -1
- package/dist/cookbook/engine/defaults.js +8 -0
- package/dist/cookbook/engine/defaults.js.map +1 -1
- package/dist/cookbook/engine/document.d.ts +4 -0
- package/dist/cookbook/engine/document.d.ts.map +1 -1
- package/dist/cookbook/engine/document.js +11 -3
- package/dist/cookbook/engine/document.js.map +1 -1
- package/dist/cookbook/engine/engine.d.ts.map +1 -1
- package/dist/cookbook/engine/engine.js +3 -1
- package/dist/cookbook/engine/engine.js.map +1 -1
- package/dist/cookbook/engine/schemas.d.ts.map +1 -1
- package/dist/cookbook/engine/schemas.js +8 -0
- package/dist/cookbook/engine/schemas.js.map +1 -1
- package/dist/cookbook/engine/types.d.ts +5 -1
- package/dist/cookbook/engine/types.d.ts.map +1 -1
- package/dist/cookbook/engine/types.js.map +1 -1
- package/dist/generators/index.d.ts +1 -0
- package/dist/generators/index.d.ts.map +1 -1
- package/dist/generators/index.js +2 -1
- package/dist/generators/mcp-runtime-template.d.ts +3 -0
- package/dist/generators/mcp-runtime-template.d.ts.map +1 -1
- package/dist/generators/mcp-runtime-template.js +30 -4
- package/dist/generators/mcp-runtime-template.js.map +1 -1
- package/dist/generators/mcp.d.ts +5 -0
- package/dist/generators/mcp.d.ts.map +1 -1
- package/dist/generators/mcp.js +78 -7
- package/dist/generators/mcp.js.map +1 -1
- package/dist/generators.js +2 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/interceptors.d.ts +7 -0
- package/dist/interceptors.d.ts.map +1 -1
- package/dist/interceptors.js +15 -1
- package/dist/interceptors.js.map +1 -1
- package/dist/manifest/browser-capability.generated.d.ts.map +1 -1
- package/dist/manifest/browser-capability.generated.js +47 -5
- package/dist/manifest/browser-capability.generated.js.map +1 -1
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/manifest-loader.d.ts.map +1 -1
- package/dist/manifest/manifest-loader.js +1 -2
- package/dist/manifest/manifest-loader.js.map +1 -1
- package/dist/manifest/static-manifest.js +1 -1
- package/dist/manifest/static-manifest.js.map +1 -1
- package/dist/manifest/store.js +1 -1
- package/dist/manifest.json +1 -1
- package/dist/mcp-serializer.d.ts +38 -0
- package/dist/mcp-serializer.d.ts.map +1 -0
- package/dist/mcp-serializer.js +60 -0
- package/dist/mcp-serializer.js.map +1 -0
- package/dist/object.d.ts +1 -0
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +44 -13
- package/dist/object.js.map +1 -1
- package/dist/registry/collection-exposure.d.ts +99 -0
- package/dist/registry/collection-exposure.d.ts.map +1 -0
- package/dist/registry/collection-exposure.js +135 -0
- package/dist/registry/collection-exposure.js.map +1 -0
- package/dist/registry/types.d.ts +13 -0
- package/dist/registry/types.d.ts.map +1 -1
- package/dist/registry.d.ts +8 -1
- package/dist/registry.d.ts.map +1 -1
- package/dist/registry.js +76 -3
- package/dist/registry.js.map +1 -1
- package/dist/scanner/manifest-generator.d.ts +14 -0
- package/dist/scanner/manifest-generator.d.ts.map +1 -1
- package/dist/scanner/manifest-generator.js +66 -13
- package/dist/scanner/manifest-generator.js.map +1 -1
- package/dist/smrt-knowledge.json +13 -11
- package/dist/utils/import-project-vite.js +1 -1
- package/dist/utils/import-workspace-module.js +1 -1
- package/dist/utils/sha256.js +2 -2
- package/dist/vite-plugin/dev-plane-route.js +1 -1
- package/dist/vite-plugin/import-build-aware.js +1 -1
- package/dist/vite-plugin/index.js +2 -2
- package/dist/vite-plugin/resources-route.js +1 -1
- package/dist/vite-plugin/sveltekit-generator.d.ts.map +1 -1
- package/dist/vite-plugin/sveltekit-generator.js +5 -1
- package/dist/vite-plugin/sveltekit-generator.js.map +1 -1
- package/package.json +16 -10
- package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_md.js +0 -169
- package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_md.js.map +0 -1
- package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_u64.js +0 -13
- package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_u64.js.map +0 -1
- package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/sha2.js +0 -198
- package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/sha2.js.map +0 -1
- package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/utils.js +0 -243
- package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/utils.js.map +0 -1
- package/dist/node_modules/.pnpm/balanced-match@4.0.4/node_modules/balanced-match/dist/esm/index.js +0 -51
- package/dist/node_modules/.pnpm/balanced-match@4.0.4/node_modules/balanced-match/dist/esm/index.js.map +0 -1
- package/dist/node_modules/.pnpm/brace-expansion@5.0.11/node_modules/brace-expansion/dist/esm/index.js +0 -202
- package/dist/node_modules/.pnpm/brace-expansion@5.0.11/node_modules/brace-expansion/dist/esm/index.js.map +0 -1
- package/dist/node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/assert-valid-pattern.js +0 -10
- package/dist/node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/assert-valid-pattern.js.map +0 -1
- package/dist/node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/ast.js +0 -514
- package/dist/node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/ast.js.map +0 -1
- package/dist/node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/brace-expressions.js +0 -124
- package/dist/node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/brace-expressions.js.map +0 -1
- package/dist/node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/escape.js +0 -21
- package/dist/node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/escape.js.map +0 -1
- package/dist/node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/index.js +0 -629
- package/dist/node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/index.js.map +0 -1
- package/dist/node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/unescape.js +0 -28
- package/dist/node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/unescape.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/generators/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,EACL,2BAA2B,EAC3B,eAAe,EACf,uBAAuB,EACvB,uBAAuB,EACvB,2BAA2B,EAC3B,oBAAoB,EACpB,0BAA0B,EAC1B,KAAK,uBAAuB,EAC5B,uBAAuB,EACvB,8BAA8B,EAC9B,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,sBAAmB,CAAC;AAC3B,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,sBAAsB,EAC3B,4BAA4B,EAC5B,+BAA+B,EAC/B,eAAe,EACf,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACtB,yBAAyB,EACzB,4BAA4B,EAC5B,0BAA0B,EAC1B,wBAAwB,EACxB,gCAAgC,EAChC,8BAA8B,EAC9B,uBAAuB,EACvB,wBAAwB,EACxB,6BAA6B,EAC7B,KAAK,uBAAuB,EAC5B,KAAK,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;AAE/C,OAAO,EACL,mBAAmB,EACnB,cAAc,GACf,MAAM,cAAW,CAAC;AAEnB,OAAO,EACL,iBAAiB,EACjB,yBAAyB,EACzB,KAAK,sBAAsB,EAC3B,KAAK,iBAAiB,GACvB,MAAM,kBAAe,CAAC;AAEvB,OAAO,EACL,uBAAuB,EACvB,KAAK,gBAAgB,GACtB,MAAM,uBAAoB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/generators/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,EACL,2BAA2B,EAC3B,eAAe,EACf,uBAAuB,EACvB,uBAAuB,EACvB,2BAA2B,EAC3B,oBAAoB,EACpB,0BAA0B,EAC1B,KAAK,uBAAuB,EAC5B,uBAAuB,EACvB,8BAA8B,EAC9B,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,sBAAmB,CAAC;AAC3B,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,sBAAsB,EAC3B,4BAA4B,EAC5B,+BAA+B,EAC/B,eAAe,EACf,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACtB,yBAAyB,EACzB,4BAA4B,EAC5B,0BAA0B,EAC1B,wBAAwB,EACxB,gCAAgC,EAChC,8BAA8B,EAC9B,uBAAuB,EACvB,wBAAwB,EACxB,6BAA6B,EAC7B,KAAK,uBAAuB,EAC5B,KAAK,eAAe,EACpB,eAAe,EACf,gBAAgB,EAChB,KAAK,qBAAqB,EAC1B,4BAA4B,EAC5B,qBAAqB,EACrB,KAAK,+BAA+B,EACpC,KAAK,kCAAkC,EACvC,KAAK,4BAA4B,EACjC,yBAAyB,EACzB,wBAAwB,EACxB,2BAA2B,EAC3B,4BAA4B,EAC5B,8BAA8B,EAC9B,qCAAqC,EACrC,KAAK,UAAU,EACf,qBAAqB,EACrB,kBAAkB,EAClB,oBAAoB,EACpB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,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.js
CHANGED
|
@@ -2,9 +2,10 @@ import { PRIVATE_READ_CACHE_CONTROL, canonicalReadRepresentation, computeBodyEta
|
|
|
2
2
|
import { CRUD_OPERATIONS, SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, buildCustomActionInputSchema, buildCustomActionInvocationArgs, classifyMethodWireability, classifyParameterWireability, coerceCustomActionArgument, createClassNamePredicate, createManifestClassNamePredicate, customActionParameterInputName, declaredTypeAcceptsDate, declaresRuntimeRestRoute, declaresRuntimeRestRouteShape, isCrudOperation, isCrudToolAction, normalizeCustomActionFailure, queryStringDecoderFor, readMethodDecoratorConfig, resolveApiMethodExposure, resolveCustomActionMetadata, resolveDeclaredScopeMismatch, resolveEffectiveActionMetadata, toCustomActionBoolean, toCustomActionDate, toCustomActionNumber } from "./custom-action.js";
|
|
3
3
|
import { DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, buildChangeEventStream, changeEventSubscribersAtCapacity, eventStreamCapacityExceededResponse, normalizeEventsMaxSubscribers, signalVisibleToTenant, tryReserveChangeEventSubscriberSlot } from "./events-route.js";
|
|
4
4
|
import { runWithTenantGate, setTenantEntryPointRunner } from "./tenant-gate.js";
|
|
5
|
+
import { fieldTypeToJsonSchema } from "./tool-schema.js";
|
|
5
6
|
import { MCPGenerator, MCP_STABLE_CATALOG_TTL_MS, resolveMCPToolListCacheHint, sortMCPTools } from "./mcp.js";
|
|
6
7
|
import { PLAYBOOK_PREFLIGHT_CAPABILITY, PLAYBOOK_PREFLIGHT_ROUTE_SEGMENT, handlePlaybookPreflightRoute, isApiActionEnabledForObject, isRestActionRoutable, isRestRoutePublic, resolveRegisteredObjectName, restFieldReadPermissions, restMethodForApiAction } from "./preflight-route.js";
|
|
7
8
|
import { normalizeTypedHttpError } from "./typed-http-error.js";
|
|
8
9
|
import { APIGenerator, computeRuntimeWebManifestHash, createRestServer, startRestServer } from "./rest.js";
|
|
9
10
|
import { generateOpenAPISpec, setupSwaggerUI } from "./swagger.js";
|
|
10
|
-
export { APIGenerator, CRUD_OPERATIONS, DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, MCPGenerator, MCP_STABLE_CATALOG_TTL_MS, PLAYBOOK_PREFLIGHT_CAPABILITY, PLAYBOOK_PREFLIGHT_ROUTE_SEGMENT, PRIVATE_READ_CACHE_CONTROL, SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, buildChangeEventStream, buildCustomActionInputSchema, buildCustomActionInvocationArgs, canonicalReadRepresentation, changeEventSubscribersAtCapacity, classifyMethodWireability, classifyParameterWireability, coerceCustomActionArgument, computeBodyEtag, computeRuntimeWebManifestHash, computeTableVersionEtag, conditionalJsonResponse, createClassNamePredicate, createManifestClassNamePredicate, createRestServer, customActionParameterInputName, declaredTypeAcceptsDate, declaresRuntimeRestRoute, declaresRuntimeRestRouteShape, eventStreamCapacityExceededResponse, generateOpenAPISpec, handlePlaybookPreflightRoute, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, isApiActionEnabledForObject, isCrudOperation, isCrudToolAction, isRestActionRoutable, isRestRoutePublic, normalizeCustomActionFailure, normalizeEventsMaxSubscribers, normalizeTypedHttpError, queryStringDecoderFor, readMethodDecoratorConfig, resolveApiMethodExposure, resolveCustomActionMetadata, resolveDeclaredScopeMismatch, resolveEffectiveActionMetadata, resolveMCPToolListCacheHint, resolveReadCacheControl, resolveRegisteredObjectName, resolveTenantEtagDiscriminator, restFieldReadPermissions, restMethodForApiAction, runWithTenantGate, setTenantEntryPointRunner, setupSwaggerUI, signalVisibleToTenant, sortMCPTools, startRestServer, toCustomActionBoolean, toCustomActionDate, toCustomActionNumber, tryReserveChangeEventSubscriberSlot, versionConditionalResponse, warnIfSharedCacheNeutralized };
|
|
11
|
+
export { APIGenerator, CRUD_OPERATIONS, DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, MCPGenerator, MCP_STABLE_CATALOG_TTL_MS, PLAYBOOK_PREFLIGHT_CAPABILITY, PLAYBOOK_PREFLIGHT_ROUTE_SEGMENT, PRIVATE_READ_CACHE_CONTROL, SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, buildChangeEventStream, buildCustomActionInputSchema, buildCustomActionInvocationArgs, canonicalReadRepresentation, changeEventSubscribersAtCapacity, classifyMethodWireability, classifyParameterWireability, coerceCustomActionArgument, computeBodyEtag, computeRuntimeWebManifestHash, computeTableVersionEtag, conditionalJsonResponse, createClassNamePredicate, createManifestClassNamePredicate, createRestServer, customActionParameterInputName, declaredTypeAcceptsDate, declaresRuntimeRestRoute, declaresRuntimeRestRouteShape, eventStreamCapacityExceededResponse, fieldTypeToJsonSchema, generateOpenAPISpec, handlePlaybookPreflightRoute, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, isApiActionEnabledForObject, isCrudOperation, isCrudToolAction, isRestActionRoutable, isRestRoutePublic, normalizeCustomActionFailure, normalizeEventsMaxSubscribers, normalizeTypedHttpError, queryStringDecoderFor, readMethodDecoratorConfig, resolveApiMethodExposure, resolveCustomActionMetadata, resolveDeclaredScopeMismatch, resolveEffectiveActionMetadata, resolveMCPToolListCacheHint, resolveReadCacheControl, resolveRegisteredObjectName, resolveTenantEtagDiscriminator, restFieldReadPermissions, restMethodForApiAction, runWithTenantGate, setTenantEntryPointRunner, setupSwaggerUI, signalVisibleToTenant, sortMCPTools, startRestServer, toCustomActionBoolean, toCustomActionDate, toCustomActionNumber, tryReserveChangeEventSubscriberSlot, versionConditionalResponse, warnIfSharedCacheNeutralized };
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* - Error handling and logging
|
|
10
10
|
* - Graceful shutdown
|
|
11
11
|
*/
|
|
12
|
+
import type { ApiSerializerReference } from '../registry/types.js';
|
|
12
13
|
import type { CustomActionScope } from './custom-action.js';
|
|
13
14
|
import type { MCPConfig, MCPContext } from './mcp.js';
|
|
14
15
|
import type { McpToolTarget } from './mcp-tool-name.js';
|
|
@@ -48,6 +49,8 @@ export interface RuntimeOptions {
|
|
|
48
49
|
}>;
|
|
49
50
|
/** Explicit original execution targets for generated protocol aliases. */
|
|
50
51
|
toolTargets?: Record<string, McpToolTarget>;
|
|
52
|
+
/** Async serializers for standard get tools, keyed by emitted tool name. */
|
|
53
|
+
getSerializers?: Record<string, ApiSerializerReference>;
|
|
51
54
|
/** Cache hint emitted for deploy-static tools/list results. */
|
|
52
55
|
toolListCacheHint?: {
|
|
53
56
|
ttlMs: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-runtime-template.d.ts","sourceRoot":"","sources":["../../src/generators/mcp-runtime-template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAOH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AASxD,MAAM,WAAW,cAAc;IAC7B,6CAA6C;IAC7C,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd,mDAAmD;IACnD,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB,yBAAyB;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB,kCAAkC;IAClC,MAAM,CAAC,EAAE,SAAS,CAAC;IAEnB,8CAA8C;IAC9C,OAAO,CAAC,EAAE,UAAU,CAAC;IAErB,2BAA2B;IAC3B,KAAK,CAAC,EAAE,OAAO,CAAC;IAEhB,wDAAwD;IACxD,KAAK,CAAC,EAAE,KAAK,CAAC;QACZ,IAAI,EAAE,MAAM,CAAC;QACb,WAAW,EAAE,MAAM,CAAC;QACpB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAA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UAAU,EAAE,MAAM,CAAC;QACnB,UAAU,EAAE,MAAM,CAAC;QACnB,qDAAqD;QACrD,WAAW,CAAC,EAAE,MAAM,CAAC;KACtB,CACF,CAAC;IAEF;;;;;;OAMG;IACH,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC;IAE/B;;;;;OAKG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAEpD;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC;CACjD;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,GAAE,cAAmB,GAAG,MAAM,CAiyB7E;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAC/B,UAAU,GAAE,MAA6B,GACxC,MAAM,CAER;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,GACjB,MAAM,CASR;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CACtC,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,GACjB,MAAM,CA6GR"}
|
|
@@ -24,7 +24,7 @@ function capitalize(str) {
|
|
|
24
24
|
* @returns TypeScript code for server entry point
|
|
25
25
|
*/
|
|
26
26
|
function generateRuntimeBootstrap(options = {}) {
|
|
27
|
-
const { name = "smrt-mcp-server", version = "1.0.0", description = "Auto-generated MCP server from SMRT objects", debug = false, tools = [], toolTargets: explicitToolTargets, customActions = {}, taskActions = {}, tenantScopedObjects = [], stiTargets = {}, listOrderBy = {}, toolListCacheHint = {
|
|
27
|
+
const { name = "smrt-mcp-server", version = "1.0.0", description = "Auto-generated MCP server from SMRT objects", debug = false, tools = [], toolTargets: explicitToolTargets, getSerializers = {}, customActions = {}, taskActions = {}, tenantScopedObjects = [], stiTargets = {}, listOrderBy = {}, toolListCacheHint = {
|
|
28
28
|
ttlMs: 864e5,
|
|
29
29
|
cacheScope: "private"
|
|
30
30
|
} } = options;
|
|
@@ -85,7 +85,7 @@ ${indent} if (!item) {
|
|
|
85
85
|
${indent} throw new Error('Object not found');
|
|
86
86
|
${indent} }
|
|
87
87
|
|
|
88
|
-
${indent} return successResult(
|
|
88
|
+
${indent} return successResult(await serializeGetResult(${JSON.stringify(tool.name)}, item));
|
|
89
89
|
${indent}}`;
|
|
90
90
|
case "create": return `${indent}case '${tool.name}': {
|
|
91
91
|
${indent} const { collection, objectName: targetObjectName } = await resolveCreateTarget(${JSON.stringify(objectName)}, ${JSON.stringify(lookup)}, args, aiConfig);
|
|
@@ -248,6 +248,20 @@ const PUBLIC_JSON_OPTIONS = {
|
|
|
248
248
|
.map((permission) => permission.trim())
|
|
249
249
|
.filter(Boolean),
|
|
250
250
|
};
|
|
251
|
+
const GET_SERIALIZERS: Record<string, { importPath: string; exportName: string }> = ${JSON.stringify(getSerializers)};
|
|
252
|
+
|
|
253
|
+
async function serializeGetResult(toolName: string, item: any): Promise<any> {
|
|
254
|
+
const reference = GET_SERIALIZERS[toolName];
|
|
255
|
+
if (!reference) return item.toPublicJSON(PUBLIC_JSON_OPTIONS);
|
|
256
|
+
const serializerModule = await import(reference.importPath);
|
|
257
|
+
const serializer = serializerModule[reference.exportName];
|
|
258
|
+
if (typeof serializer !== 'function') {
|
|
259
|
+
throw new Error(
|
|
260
|
+
\`MCP get serializer '\${reference.exportName}' was not exported by '\${reference.importPath}'\`,
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
return toPublicResult(await serializer(item, PUBLIC_JSON_OPTIONS));
|
|
264
|
+
}
|
|
251
265
|
|
|
252
266
|
/**
|
|
253
267
|
* Page-bound guard (#2367). MCP tool arguments are untyped JSON, so \`limit\`
|
|
@@ -357,6 +371,17 @@ function errorResult(structuredContent: any, text: string, _meta?: Record<string
|
|
|
357
371
|
};
|
|
358
372
|
}
|
|
359
373
|
|
|
374
|
+
function normalizePublicToolError(error: any): { code: string; message: string } | undefined {
|
|
375
|
+
if (!error || typeof error !== 'object') return undefined;
|
|
376
|
+
if (
|
|
377
|
+
typeof error.code !== 'string' ||
|
|
378
|
+
!/^[A-Za-z][A-Za-z0-9_.:-]{0,127}$/.test(error.code) ||
|
|
379
|
+
typeof error.publicMessage !== 'string' ||
|
|
380
|
+
error.publicMessage.length === 0
|
|
381
|
+
) return undefined;
|
|
382
|
+
return { code: error.code, message: error.publicMessage };
|
|
383
|
+
}
|
|
384
|
+
|
|
360
385
|
${hasTaskActions ? `
|
|
361
386
|
// The bundled SDK validates tools/call responses against its older result
|
|
362
387
|
// codec, which does not yet know CreateTaskResult. Intercept the extension at
|
|
@@ -678,11 +703,12 @@ ${hasTenantScoped ? `
|
|
|
678
703
|
|
|
679
704
|
return result;
|
|
680
705
|
} catch (error) {
|
|
681
|
-
const
|
|
706
|
+
const publicError = normalizePublicToolError(error);
|
|
707
|
+
const errorMessage = publicError?.message ?? (error instanceof Error ? error.message : 'Unknown error');
|
|
682
708
|
console.error(\`[MCP] Tool execution failed: \${toolName}\`, error);
|
|
683
709
|
|
|
684
710
|
return errorResult(
|
|
685
|
-
{ error: { message: errorMessage } },
|
|
711
|
+
{ error: publicError ?? { message: errorMessage } },
|
|
686
712
|
\`Error executing tool \${toolName}: \${errorMessage}\`,
|
|
687
713
|
);
|
|
688
714
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-runtime-template.js","names":[],"sources":["../../src/generators/mcp-runtime-template.ts"],"sourcesContent":["/**\n * Runtime bootstrap template for generated MCP servers\n *\n * This template provides stdio transport integration for SMRT-generated MCP servers.\n * It handles:\n * - Server initialization with @modelcontextprotocol/server v2\n * - Tool registration from MCPGenerator\n * - Stdio transport connection\n * - Error handling and logging\n * - Graceful shutdown\n */\n\nimport {\n DEFAULT_LIST_LIMIT,\n DEFAULT_LIST_ORDER_BY,\n MAX_LIST_LIMIT,\n} from '../query-bounds.js';\nimport type { CustomActionScope } from './custom-action.js';\nimport type { MCPConfig, MCPContext } from './mcp.js';\nimport type { McpToolTarget } from './mcp-tool-name.js';\n\n/**\n * Helper function to capitalize first letter\n */\nfunction capitalize(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nexport interface RuntimeOptions {\n /** Server name (defaults to package name) */\n name?: string;\n\n /** Server version (defaults to package version) */\n version?: string;\n\n /** Server description */\n description?: string;\n\n /** MCP generator configuration */\n config?: MCPConfig;\n\n /** MCP context (database, AI client, etc.) */\n context?: MCPContext;\n\n /** Enable debug logging */\n debug?: boolean;\n\n /** Static tool definitions (generated at build time) */\n tools?: Array<{\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n outputSchema?: Record<string, unknown>;\n annotations?: {\n readOnlyHint: boolean;\n destructiveHint: boolean;\n idempotentHint: boolean;\n openWorldHint: boolean;\n };\n title?: string;\n icons?: Array<{\n src: string;\n mimeType?: string;\n sizes?: string[];\n theme?: 'light' | 'dark';\n }>;\n _meta?: Record<string, unknown>;\n }>;\n /** Explicit original execution targets for generated protocol aliases. */\n toolTargets?: Record<string, McpToolTarget>;\n /** Cache hint emitted for deploy-static tools/list results. */\n toolListCacheHint?: {\n ttlMs: number;\n cacheScope: 'private' | 'public';\n };\n /** Internal invocation metadata; never exposed by the MCP tools/list result. */\n customActions?: Record<\n string,\n {\n scope: CustomActionScope;\n isStatic: boolean;\n /** Declared method name; tool IDs are lowercased protocol aliases. */\n methodName?: string;\n parameterNames?: string[];\n optionsParameter?: boolean;\n legacyOptions: boolean;\n }\n >;\n /** Task-enabled item custom actions. Never emitted in tools/list. */\n taskActions?: Record<\n string,\n {\n objectName: string;\n objectType: string;\n /** Registry identity of the task's class (#3490). */\n registryKey?: string;\n }\n >;\n\n /**\n * Lowercased simple names of objects that are `@TenantScoped` (#1554). When\n * non-empty, the generated server imports the tenancy fail-closed gate and\n * wraps tenant-scoped tool calls so a stdio invocation cannot read across all\n * tenants. The tenant is sourced from `SMRT_MCP_TENANT_ID` /\n * `SMRT_MCP_ALLOW_CROSS_TENANT` env vars (this server has no auth principal).\n */\n tenantScopedObjects?: string[];\n\n /**\n * Build-time approved STI discriminators, keyed by the lowercased MCP object\n * prefix. The generated runtime uses this instead of searching an initially\n * empty registry, then loads the approved qualified type through the public\n * collection API.\n */\n stiTargets?: Record<string, Record<string, string>>;\n\n /**\n * Default list ordering per lowercased MCP object prefix (#2367).\n *\n * Baked in at generation time because the tiebreak follows the model's\n * declared primary key, which the emitted server cannot resolve on its own.\n * Prefixes absent from this map fall back to {@link DEFAULT_LIST_ORDER_BY}.\n */\n listOrderBy?: Record<string, readonly string[]>;\n}\n\n/**\n * Generate runtime bootstrap code for MCP server\n *\n * @param options - Runtime configuration options\n * @returns TypeScript code for server entry point\n */\nexport function generateRuntimeBootstrap(options: RuntimeOptions = {}): string {\n const {\n name = 'smrt-mcp-server',\n version = '1.0.0',\n description = 'Auto-generated MCP server from SMRT objects',\n debug = false,\n tools = [],\n toolTargets: explicitToolTargets,\n customActions = {},\n taskActions = {},\n tenantScopedObjects = [],\n stiTargets = {},\n listOrderBy = {},\n toolListCacheHint = { ttlMs: 86_400_000, cacheScope: 'private' },\n } = options;\n\n // Direct template callers retain their legacy object_action inputs. The\n // owning generator always supplies explicit targets, including valid aliases.\n const toolTargets: Record<string, McpToolTarget> =\n explicitToolTargets ??\n Object.fromEntries(\n tools.map((tool) => {\n const separator = tool.name.indexOf('_');\n return [\n tool.name,\n {\n objectName: capitalize(tool.name.slice(0, separator)),\n action: tool.name.slice(separator + 1),\n },\n ];\n }),\n );\n for (const tool of tools) {\n if (!Object.hasOwn(toolTargets, tool.name)) {\n throw new Error(`Missing MCP tool target: ${tool.name}`);\n }\n }\n\n // Generate static tool array as TypeScript code\n const toolsCode = tools.length > 0 ? JSON.stringify(tools, null, 2) : '[]';\n const hasTaskActions = Object.keys(taskActions).length > 0;\n\n // Fail-closed tenant context (#1554): only wire the tenancy gate when at\n // least one exposed object is tenant-scoped, so apps without tenancy never\n // get a dangling import.\n const tenantScopedSet = Array.from(\n new Set(tenantScopedObjects.map((n) => n.toLowerCase())),\n );\n const hasTenantScoped = tenantScopedSet.length > 0;\n\n // Generate static switch cases using shared helper\n const generateSwitchCases = (indent: string) => {\n return tools\n .map((tool) => {\n const objectName = toolTargets[tool.name].objectName.toLowerCase();\n const action = toolTargets[tool.name].action;\n // Registry identity for every emitted lookup (#3490).\n const lookup =\n toolTargets[tool.name].registryKey ??\n toolTargets[tool.name].objectName;\n\n switch (action) {\n case 'list':\n return `${indent}case '${tool.name}': {\n${indent} const limit = resolveListBound(args.limit, 'limit', ${DEFAULT_LIST_LIMIT}, ${MAX_LIST_LIMIT});\n${indent} const offset = resolveListBound(args.offset, 'offset', 0);\n${indent} // #2367: the tool schema advertises \\`orderBy\\`, so honour it; and page\n${indent} // deterministically when it is omitted — LIMIT/OFFSET with no ORDER BY\n${indent} // lets successive pages repeat and skip rows on PostgreSQL.\n${indent} const orderBy = args.orderBy ?? ${JSON.stringify(\n listOrderBy[objectName] ?? DEFAULT_LIST_ORDER_BY,\n )};\n${indent} const where = args.where ?? {};\n\n${indent} const collection = await ObjectRegistry.getCollection(${JSON.stringify(lookup)}, {\n${indent} persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n${indent} ai: aiConfig\n${indent} });\n\n${indent} const items = await collection.list({ where, limit, offset, orderBy });\n${indent} const itemsPublic = items.map((item) => item.toPublicJSON(PUBLIC_JSON_OPTIONS));\n${indent} const structuredContent = {\n${indent} data: itemsPublic,\n${indent} meta: { total: await collection.count({ where }), limit, offset, count: items.length },\n${indent} };\n${indent} return successResult(structuredContent, JSON.stringify(itemsPublic));\n${indent}}`;\n\n case 'get':\n return `${indent}case '${tool.name}': {\n${indent} if (!args.id && !args.slug) {\n${indent} throw new Error('Either id or slug is required');\n${indent} }\n\n${indent} const collection = await ObjectRegistry.getCollection(${JSON.stringify(lookup)}, {\n${indent} persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n${indent} ai: aiConfig\n${indent} });\n\n${indent} const filter = args.id || args.slug;\n${indent} const item = await collection.get(filter);\n\n${indent} if (!item) {\n${indent} throw new Error('Object not found');\n${indent} }\n\n${indent} return successResult(item.toPublicJSON(PUBLIC_JSON_OPTIONS));\n${indent}}`;\n\n case 'create':\n return `${indent}case '${tool.name}': {\n${indent} const { collection, objectName: targetObjectName } = await resolveCreateTarget(${JSON.stringify(objectName)}, ${JSON.stringify(lookup)}, args, aiConfig);\n\n${indent} const newItem = await collection.create(applyWritablePolicy(targetObjectName, args));\n\n${indent} return successResult(newItem.toPublicJSON(PUBLIC_JSON_OPTIONS));\n${indent}}`;\n\n case 'update':\n return `${indent}case '${tool.name}': {\n${indent} const { id, ...updateData } = args;\n${indent} if (!id) {\n${indent} throw new Error('ID is required for update');\n${indent} }\n\n${indent} const collection = await ObjectRegistry.getCollection(${JSON.stringify(lookup)}, {\n${indent} persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n${indent} ai: aiConfig\n${indent} });\n\n${indent} const existing = await collection.get(id);\n${indent} if (!existing) {\n${indent} throw new Error('Object not found');\n${indent} }\n\n${indent} await collection.withAuditMutation(existing, 'updated', async (bound) => {\n${indent} Object.assign(bound, applyWritablePolicy(${JSON.stringify(lookup)}, updateData));\n${indent} await bound.save();\n${indent} });\n\n${indent} return successResult(existing.toPublicJSON(PUBLIC_JSON_OPTIONS));\n${indent}}`;\n\n case 'delete':\n return `${indent}case '${tool.name}': {\n${indent} if (!args.id) {\n${indent} throw new Error('ID is required for delete');\n${indent} }\n\n${indent} const collection = await ObjectRegistry.getCollection(${JSON.stringify(lookup)}, {\n${indent} persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n${indent} ai: aiConfig\n${indent} });\n\n${indent} const toDelete = await collection.get(args.id);\n${indent} if (!toDelete) {\n${indent} throw new Error('Object not found');\n${indent} }\n\n${indent} await collection.delete(args.id);\n\n${indent} return successResult({ success: true, message: 'Object deleted successfully' });\n${indent}}`;\n\n default:\n // Custom action. Its descriptor is deliberately kept separate\n // from TOOLS so MCP clients receive only protocol-defined fields.\n return `${indent}case '${tool.name}': {\n${indent} const actionMeta = CUSTOM_ACTIONS['${tool.name}'] || { scope: 'item', isStatic: false, legacyOptions: true };\n${indent} const { id, options, ...directArgs } = args;\n\n${indent} if (actionMeta.scope === 'item' && !id) {\n${indent} throw new Error(${JSON.stringify(`ID is required for custom action ${action}`)});\n${indent} }\n${indent} if (actionMeta.scope === 'collection' && id) {\n${indent} throw new Error(${JSON.stringify(`Custom action ${action} is collection-scoped and does not accept an ID`)});\n${indent} }\n\n${indent} const collection = await ObjectRegistry.getCollection(${JSON.stringify(lookup)}, {\n${indent} persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n${indent} ai: aiConfig\n${indent} });\n\n${indent} const target = actionMeta.scope === 'item'\n${indent} ? await collection.get(id)\n${indent} : actionMeta.isStatic\n${indent} ? ObjectRegistry.getClass(${JSON.stringify(lookup)})?.constructor\n${indent} : collection;\n${indent} if (!target) {\n${indent} throw new Error(actionMeta.scope === 'item' ? 'Object not found' : 'Custom action target not found');\n${indent} }\n${indent} const actionMethod = target[actionMeta.methodName || ${JSON.stringify(action)}];\n${indent} if (typeof actionMethod !== 'function') {\n${indent} throw new Error(${JSON.stringify(`Method ${action} not found on custom action target`)});\n${indent} }\n\n${indent} const methodArgs = actionMeta.legacyOptions\n${indent} ? [Object.keys(options ?? {}).length > 0 ? options : directArgs]\n${indent} : actionMeta.optionsParameter\n${indent} ? [options]\n${indent} : (actionMeta.parameterNames || []).map((parameterName) => args[\n${indent} parameterName === 'id'\n${indent} ? 'actionId'\n${indent} : parameterName\n${indent} ]);\n${indent} const result = await actionMethod.call(target, ...methodArgs);\n${indent} const failure = normalizeCustomActionFailure(result);\n${indent} if (failure) {\n${indent} return errorResult(\n${indent} { error: failure },\n${indent} JSON.stringify({ error: failure }),\n${indent} { [SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY]: failure },\n${indent} );\n${indent} }\n\n${indent} const publicResult = toPublicResult(result);\n${indent} return successResult({ data: publicResult }, JSON.stringify(publicResult));\n${indent}}`;\n }\n })\n .join('\\n\\n');\n };\n\n const switchCases = generateSwitchCases(' ');\n\n return `#!/usr/bin/env node\n/**\n * Auto-generated MCP Server\n * Generated by @smrt/core MCPGenerator\n *\n * This server exposes SMRT objects as MCP tools for AI integration.\n *\n * SECURITY (#1540): tool responses exclude @field({ sensitive }) fields and\n * create/update bodies are mass-assignment guarded. This stdio server has NO\n * per-call authentication principal — its trust boundary is the host process /\n * MCP client that launches it. Run it only in a trusted context, or front it\n * with an authenticated gateway. Do not expose it directly to untrusted callers.\n */\n\nimport {\n type CallToolRequest,\n type ListToolsRequest,\n Server,\n ${hasTaskActions ? 'specTypeSchemas,' : ''}\n} from '@modelcontextprotocol/server';\nimport { ${hasTaskActions ? 'StdioServerTransport, ' : ''}serveStdio } from '@modelcontextprotocol/server/stdio';\nimport { existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\nimport { normalizeCustomActionFailure, SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY } from '@happyvertical/smrt-core';\nimport { loadConfig } from '@happyvertical/smrt-config';\n${hasTaskActions ? \"import { McpTaskStore, TaskRunner } from '@happyvertical/smrt-jobs';\\n\" : ''}\n${hasTenantScoped ? \"import { enableTenancy, runTenantScopedEntryPoint } from '@happyvertical/smrt-tenancy';\\n\" : ''}\n// Server configuration\nconst SERVER_NAME = ${JSON.stringify(name)};\nconst SERVER_VERSION = ${JSON.stringify(version)};\nconst SERVER_DESCRIPTION = ${JSON.stringify(description)};\nconst DEBUG = ${debug};\n\n// Static tool definitions (generated at build time)\nconst TOOLS = ${toolsCode};\nconst TOOL_LIST_CACHE_HINT = ${JSON.stringify(toolListCacheHint)};\nconst TOOL_TARGETS: Record<string, { objectName: string; action: string; registryKey?: string }> = ${JSON.stringify(toolTargets)};\nconst CUSTOM_ACTIONS = ${JSON.stringify(customActions)};\nconst TASK_ACTIONS = ${JSON.stringify(taskActions)};\nconst STI_TARGETS: Record<string, Record<string, string>> = ${JSON.stringify(stiTargets)};\n${\n hasTenantScoped\n ? `\n// Fail-closed tenant context (#1554): tenant-scoped objects must run inside a\n// tenant. This stdio server has no auth principal, so the tenant is taken from\n// the environment; without it (and with tenancy enabled) tenant-scoped tools\n// throw rather than reading across all tenants.\nconst TENANT_SCOPED = new Set(${JSON.stringify(tenantScopedSet)});\nconst MCP_TENANT_ID = process.env.SMRT_MCP_TENANT_ID || undefined;\nconst MCP_ALLOW_CROSS_TENANT = process.env.SMRT_MCP_ALLOW_CROSS_TENANT === 'true';\n`\n : ''\n}\nconst PUBLIC_JSON_OPTIONS = {\n permissions: (process.env.SMRT_MCP_PERMISSIONS || '')\n .split(',')\n .map((permission) => permission.trim())\n .filter(Boolean),\n};\n\n/**\n * Page-bound guard (#2367). MCP tool arguments are untyped JSON, so \\`limit\\`\n * arrives as whatever the client sent: \\`\"abc\"\\` used to become \\`LIMIT NaN\\`\n * (a driver error, not a tool error), and nothing capped the value, so one\n * \\`limit: 100000000\\` call was a full table scan. Rejects anything that is not\n * a non-negative integer and clamps the rest to \\`max\\`.\n */\nfunction resolveListBound(raw: any, name: string, fallback: number, max?: number): number {\n if (raw === undefined || raw === null || raw === '') {\n return max === undefined ? fallback : Math.min(fallback, max);\n }\n const value = typeof raw === 'string' && /^\\\\d+$/.test(raw.trim()) ? Number(raw.trim()) : raw;\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error(\"Invalid \" + name + \": expected a non-negative integer, got \" + JSON.stringify(raw));\n }\n return max === undefined ? value : Math.min(value, max);\n}\n\n/**\n * Mass-assignment guard (#1540): strip framework/server-managed and\n * \\`@field({ readonly: true })\\` fields from create/update bodies, intersecting\n * with the optional \\`@smrt({ api: { writable: [...] } })\\` allowlist.\n */\nfunction applyWritablePolicy(objectName: string, data: any): Record<string, any> {\n if (!data || typeof data !== 'object') return {};\n const serverManaged = new Set([\n 'id', 'tenantId', 'tenant_id',\n 'createdAt', 'created_at', 'updatedAt', 'updated_at',\n ]);\n const readonly = new Set<string>();\n let writable: string[] | null = null;\n const apiConfig = ObjectRegistry.getConfig(objectName)?.api as any;\n if (apiConfig && typeof apiConfig === 'object' && Array.isArray(apiConfig.writable)) {\n writable = apiConfig.writable;\n }\n for (const [name, def] of ObjectRegistry.getFields(objectName)) {\n if (def && ((def as any).readonly === true || (def as any)._meta?.readonly === true)) {\n readonly.add(name);\n }\n }\n const result: Record<string, any> = {};\n for (const [key, value] of Object.entries(data)) {\n if (key.startsWith('_')) continue;\n if (serverManaged.has(key)) continue;\n if (readonly.has(key)) continue;\n if (writable && !writable.includes(key)) continue;\n result[key] = value;\n }\n return result;\n}\n\n/** Resolve an advertised STI discriminator to its registered subtype collection. */\nasync function resolveCreateTarget(stiKey: string, baseObjectName: string, args: Record<string, any>, aiConfig: any) {\n let objectName = baseObjectName;\n const discriminator = args._meta_type;\n const targets = STI_TARGETS[stiKey];\n if (typeof discriminator === 'string' && targets) {\n const target = targets[discriminator];\n if (!target) throw new Error('Unknown STI discriminator: ' + discriminator);\n objectName = target;\n }\n const collection = await ObjectRegistry.getCollection(objectName, {\n persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n ai: aiConfig,\n });\n return { collection, objectName };\n}\n\n/**\n * Sensitive-field-safe serialization for custom-action results (#1540).\n * Recurses through arrays and plain objects so nested SmrtObjects are stripped\n * too; non-plain instances (Date, etc.) and primitives pass through. Cycle-safe.\n */\nfunction toPublicResult(value: any, seen: WeakSet<object> = new WeakSet()): any {\n if (value === null || typeof value !== 'object') return value;\n if (typeof value.toPublicJSON === 'function') return value.toPublicJSON(PUBLIC_JSON_OPTIONS);\n if (Array.isArray(value)) {\n if (seen.has(value)) return value;\n seen.add(value);\n return value.map((entry: any) => toPublicResult(entry, seen));\n }\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) return value;\n if (seen.has(value)) return value;\n seen.add(value);\n const out: Record<string, any> = {};\n for (const [key, entry] of Object.entries(value)) {\n out[key] = toPublicResult(entry, seen);\n }\n return out;\n}\n\nfunction successResult(structuredContent: any, text = JSON.stringify(structuredContent)) {\n return {\n content: [{ type: 'text', text }],\n structuredContent,\n };\n}\n\nfunction errorResult(structuredContent: any, text: string, _meta?: Record<string, any>) {\n return {\n content: [{ type: 'text', text }],\n isError: true,\n structuredContent,\n ...(_meta ? { _meta } : {}),\n };\n}\n\n${\n hasTaskActions\n ? `\n// The bundled SDK validates tools/call responses against its older result\n// codec, which does not yet know CreateTaskResult. Intercept the extension at\n// the transport boundary, then pass every non-task message untouched to the\n// SDK server. This keeps ordinary MCP behaviour and version negotiation owned\n// by the SDK while making the extension available today.\nconst MCP_TASKS_EXTENSION = 'io.modelcontextprotocol/tasks';\nlet taskRuntime: Promise<{ store: McpTaskStore; runner: TaskRunner }> | undefined;\n\nfunction clientSupportsTasks(message: any): boolean {\n return message?.params?._meta?.['io.modelcontextprotocol/clientCapabilities']\n ?.extensions?.[MCP_TASKS_EXTENSION] !== undefined;\n}\n\n/** Validate the 2026 request envelope before task dispatch mutates a job. */\nfunction taskEnvelopeError(message: any): { code: number; message: string; data?: any } | undefined {\n const meta = message?.params?._meta;\n if (!meta || typeof meta !== 'object' || Array.isArray(meta)) {\n return {\n code: -32602,\n message: 'Request is missing the required _meta envelope for protocol revision 2026-07-28',\n };\n }\n const protocolVersion = meta['io.modelcontextprotocol/protocolVersion'];\n if (protocolVersion !== '2026-07-28') {\n return typeof protocolVersion === 'string'\n ? {\n code: -32022,\n message: 'Unsupported protocol version: ' + protocolVersion,\n data: { supported: ['2026-07-28'], requested: protocolVersion },\n }\n : {\n code: -32602,\n message: 'Invalid _meta envelope for protocol revision 2026-07-28: io.modelcontextprotocol/protocolVersion must be a string',\n };\n }\n if (!specTypeSchemas.ClientCapabilities.safeParse(\n meta['io.modelcontextprotocol/clientCapabilities'],\n ).success) {\n return {\n code: -32602,\n message: 'Invalid _meta envelope for protocol revision 2026-07-28: io.modelcontextprotocol/clientCapabilities is invalid',\n };\n }\n if (\n meta['io.modelcontextprotocol/clientInfo'] !== undefined &&\n !specTypeSchemas.Implementation.safeParse(\n meta['io.modelcontextprotocol/clientInfo'],\n ).success\n ) {\n return {\n code: -32602,\n message: 'Invalid _meta envelope for protocol revision 2026-07-28: io.modelcontextprotocol/clientInfo is invalid',\n };\n }\n if (\n meta['io.modelcontextprotocol/logLevel'] !== undefined &&\n !specTypeSchemas.LoggingLevel.safeParse(\n meta['io.modelcontextprotocol/logLevel'],\n ).success\n ) {\n return {\n code: -32602,\n message: 'Invalid _meta envelope for protocol revision 2026-07-28: io.modelcontextprotocol/logLevel is invalid',\n };\n }\n if (\n meta.progressToken !== undefined &&\n !specTypeSchemas.ProgressToken.safeParse(meta.progressToken).success\n ) {\n return {\n code: -32602,\n message: 'Invalid _meta envelope for protocol revision 2026-07-28: progressToken is invalid',\n };\n }\n return undefined;\n}\n\nfunction jsonRpcError(id: any, code: number, message: string, data?: any) {\n return { jsonrpc: '2.0', id, error: { code, message, ...(data === undefined ? {} : { data }) } };\n}\n\nasync function getTaskRuntime() {\n if (!taskRuntime) {\n taskRuntime = (async () => {\n const firstAction = Object.values(TASK_ACTIONS)[0] as { objectName: string; registryKey?: string } | undefined;\n if (!firstAction) throw new Error('No task-enabled MCP action is configured');\n const collection = await ObjectRegistry.getCollection(firstAction.registryKey ?? firstAction.objectName, {\n persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n });\n const db = collection.db;\n const store = await McpTaskStore.create(db, { ownerId: process.env.SMRT_MCP_TENANT_ID || null, tenantId: ${hasTenantScoped ? 'MCP_TENANT_ID ?? null' : 'null'} });\n const runner = new TaskRunner({ queues: ['mcp-tasks'] });\n await runner.initialize(db);\n await runner.start();\n return { store, runner };\n })();\n }\n return taskRuntime;\n}\n\nfunction taskInvocationArgs(actionMeta: any, args: Record<string, any>): any[] {\n const { id: _id, options, ...directArgs } = args;\n if (actionMeta.legacyOptions) {\n return [Object.keys(options ?? {}).length > 0 ? options : directArgs];\n }\n if (actionMeta.optionsParameter) return [options];\n const parameterNames = actionMeta.parameterNames || [];\n const invocationParameterNames = parameterNames.at(-1) === 'context'\n ? parameterNames.slice(0, -1)\n : parameterNames;\n return invocationParameterNames.map((parameterName: string) =>\n args[parameterName === 'id' ? 'actionId' : parameterName],\n );\n}\n\nasync function handleTaskExtensionMessage(message: any): Promise<any | null> {\n if (!message || typeof message !== 'object' || message.id === undefined) return null;\n const method = message.method;\n const params = message.params ?? {};\n const action = method === 'tools/call' ? TASK_ACTIONS[params.name] : undefined;\n const isTaskMethod = action || ['tasks/get', 'tasks/update', 'tasks/cancel'].includes(method);\n if (!isTaskMethod) return null;\n // A task-enabled tool retains its normal synchronous behaviour until its\n // client explicitly opts into Tasks. Do not impose the task envelope on\n // legacy calls that will be passed untouched to the SDK.\n if (!clientSupportsTasks(message) && method === 'tools/call') return null;\n const envelopeError = taskEnvelopeError(message);\n if (envelopeError) {\n return jsonRpcError(message.id, envelopeError.code, envelopeError.message, envelopeError.data);\n }\n if (!clientSupportsTasks(message)) {\n // A task-only method cannot fall back to a legacy response shape. A task\n // tool can still run normally when the client did not opt in, so let the\n // SDK handle that direct tools/call path.\n if (method === 'tools/call') return null;\n return jsonRpcError(message.id, -32021, 'Missing required client capability', {\n requiredCapabilities: { extensions: { [MCP_TASKS_EXTENSION]: {} } },\n });\n }\n try {\n const { store } = await getTaskRuntime();\n if (action) {\n if (typeof params.arguments?.id !== 'string') {\n return jsonRpcError(message.id, -32602, 'Task-enabled custom actions require an id');\n }\n const actionMeta = CUSTOM_ACTIONS[params.name];\n const task = await store.createTask({\n objectType: action.objectType,\n objectId: params.arguments.id,\n method: actionMeta.methodName || TOOL_TARGETS[params.name]?.action,\n invocationArgs: taskInvocationArgs(actionMeta, params.arguments),\n tenantId: ${hasTenantScoped ? 'MCP_TENANT_ID ?? null' : 'null'},\n });\n return { jsonrpc: '2.0', id: message.id, result: { resultType: 'task', content: [], structuredContent: {}, ...task } };\n }\n if (typeof params.taskId !== 'string') {\n return jsonRpcError(message.id, -32602, 'taskId is required');\n }\n if (method === 'tasks/get') {\n const task = await store.getTask(params.taskId);\n return { jsonrpc: '2.0', id: message.id, result: { resultType: 'complete', ...task } };\n }\n if (method === 'tasks/update') {\n await store.updateTask(\n params.taskId,\n params.inputResponses && typeof params.inputResponses === 'object'\n ? params.inputResponses\n : {},\n );\n return { jsonrpc: '2.0', id: message.id, result: { resultType: 'complete' } };\n }\n await store.cancelTask(params.taskId);\n return { jsonrpc: '2.0', id: message.id, result: { resultType: 'complete' } };\n } catch (error) {\n const messageText = error instanceof Error ? error.message : 'Task operation failed';\n return jsonRpcError(message.id, -32602, messageText);\n }\n}\n\nclass McpTaskExtensionTransport {\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: any) => void;\n\n // An explicit field, not a parameter property: a \\`.ts\\` target has to stay\n // erasable-syntax-only so Node's type stripping can run it (#2279).\n wire: StdioServerTransport;\n\n constructor(wire: StdioServerTransport) {\n this.wire = wire;\n }\n\n async start() {\n this.wire.onclose = () => this.onclose?.();\n this.wire.onerror = (error) => this.onerror?.(error);\n this.wire.onmessage = (message) => {\n void (async () => {\n const response = await handleTaskExtensionMessage(message);\n if (response) await this.wire.send(response);\n else this.onmessage?.(message);\n })().catch((error) => this.onerror?.(error instanceof Error ? error : new Error(String(error))));\n };\n await this.wire.start();\n }\n\n close() { return this.wire.close(); }\n send(message: any) { return this.wire.send(message); }\n}\n`\n : ''\n}\n\n/**\n * Main server startup function\n */\nexport async function createServer(): Promise<Server> {\n if (DEBUG) {\n console.error(\\`[MCP] Starting server: \\${SERVER_NAME} v\\${SERVER_VERSION}\\`);\n }\n${\n hasTenantScoped\n ? `\n // Fail-closed tenant context (#1554): install the tenancy interceptor so\n // tenant-scoped tools are actually filtered, and so the entry-point gate\n // throws (rather than passing through) when no tenant is supplied. Without\n // this, a tenant set via SMRT_MCP_TENANT_ID would only set async context\n // with no interceptor to enforce it.\n enableTenancy();\n`\n : ''\n}\n // Register the application package manifest before resolving generated\n // object names. Generated servers are commonly run from the application\n // package itself, which is not a node_modules dependency of its process.\n const localManifestPaths = [\n resolve(process.cwd(), 'dist', 'manifest.json'),\n resolve(process.cwd(), '.smrt', 'manifest.json'),\n ].filter(existsSync);\n if (localManifestPaths.length > 0) {\n ObjectRegistry.loadAllManifests({ manifestPaths: localManifestPaths });\n }\n\n // A manifest supplies schemas and tool metadata, while an executable\n // custom action also needs the application's actual class constructor.\n // Consumer builds generate this registration module; load it after the\n // manifest so decorators enrich the already-known metadata.\n const localRegisterPath = process.env.SMRT_MCP_REGISTER_PATH\n || resolve(process.cwd(), '.smrt', 'register.js');\n if (existsSync(localRegisterPath)) {\n await import(pathToFileURL(localRegisterPath).href);\n }\n\n // Load configuration from environment and .smrt.config files\n const appConfig = await loadConfig();\n const aiConfig = appConfig?.ai || {};\n\n if (DEBUG) {\n console.error(\\`[MCP] Loaded \\${TOOLS.length} static tools\\`);\n console.error(\\`[MCP] Available tools:\\`, TOOLS.map(t => t.name).join(', '));\n }\n\n // Create MCP server\n const server = new Server(\n {\n name: SERVER_NAME,\n version: SERVER_VERSION,\n },\n {\n capabilities: {\n tools: {},\n ${hasTaskActions ? \"extensions: { 'io.modelcontextprotocol/tasks': {} },\" : ''}\n },\n cacheHints: {\n 'tools/list': TOOL_LIST_CACHE_HINT,\n },\n }\n );\n\n // Register ListTools handler\n server.setRequestHandler('tools/list', async (_request: ListToolsRequest) => {\n if (DEBUG) {\n console.error(\\`[MCP] ListTools request received\\`);\n }\n\n return {\n tools: [...TOOLS].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0),\n };\n });\n\n // Register CallTool handler\n server.setRequestHandler('tools/call', async (request: CallToolRequest) => {\n const { name: toolName, arguments: args = {} } = request.params;\n\n if (DEBUG) {\n console.error(\\`[MCP] CallTool request: \\${toolName}\\`);\n console.error(\\`[MCP] Arguments:\\`, JSON.stringify(args, null, 2));\n }\n\n try {\n // Static switch statement for tool execution\n const runToolBody = async () => {\n switch (toolName) {\n${switchCases}\n\n default:\n throw new Error(\\`Unknown tool: \\${toolName}\\`);\n }\n };\n${\n hasTenantScoped\n ? `\n // Fail-closed tenant context for tenant-scoped tools (#1554).\n const toolObject = TOOL_TARGETS[toolName]?.objectName;\n const result =\n toolObject && TENANT_SCOPED.has(toolObject.toLowerCase())\n ? await runTenantScopedEntryPoint(\n { tenantScoped: true, tenantId: MCP_TENANT_ID, allowCrossTenant: MCP_ALLOW_CROSS_TENANT, surface: 'MCP' },\n runToolBody,\n )\n : await runToolBody();`\n : `\n const result = await runToolBody();`\n}\n\n if (DEBUG) {\n console.error(\\`[MCP] Tool executed successfully: \\${toolName}\\`);\n }\n\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n console.error(\\`[MCP] Tool execution failed: \\${toolName}\\`, error);\n\n return errorResult(\n { error: { message: errorMessage } },\n \\`Error executing tool \\${toolName}: \\${errorMessage}\\`,\n );\n }\n });\n\n return server;\n}\n\nasync function main() {\n try {\n // Initialize the registry before accepting an intercepted task call. The\n // SDK would normally invoke this factory for the first regular message,\n // but task calls can be the first message on a stdio connection.\n const server = await createServer();\n const transport = ${hasTaskActions ? 'new McpTaskExtensionTransport(new StdioServerTransport())' : 'undefined'};\n const handle = serveStdio(() => server, {\n ...(transport ? { transport } : {}),\n onerror: (error) => console.error('[MCP] Protocol error:', error),\n });\n const shutdown = async () => {\n if (DEBUG) console.error('[MCP] Shutting down gracefully');\n ${hasTaskActions ? 'if (taskRuntime) {\\n const { runner } = await taskRuntime;\\n await runner.stop();\\n }' : ''}\n await handle.close();\n process.exit(0);\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n } catch (error) {\n console.error('[MCP] Fatal error during server startup:', error);\n process.exit(1);\n }\n}\n\n// Start only when executed, so adapters and tests may import the factory.\nif (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {\n main().catch((error) => {\n console.error('[MCP] Unhandled error:', error);\n process.exit(1);\n });\n}\n`;\n}\n\n/**\n * Generate package.json script for running MCP server\n *\n * @param serverPath - Path to generated server file (relative to package root)\n * @returns Script command for package.json\n */\nexport function generateMCPScript(\n serverPath: string = 'dist/mcp-server.js',\n): string {\n return `node ${serverPath}`;\n}\n\n/**\n * Generate Claude Desktop configuration example\n *\n * @param serverName - Name for the MCP server\n * @param serverPath - Absolute path to server file\n * @returns Configuration object for claude_desktop_config.json\n */\nexport function generateClaudeConfig(\n serverName: string,\n serverPath: string,\n): object {\n return {\n mcpServers: {\n [serverName]: {\n command: 'node',\n args: [serverPath],\n },\n },\n };\n}\n\n/**\n * Generate README documentation for MCP server setup\n *\n * @param serverName - Name of the MCP server\n * @param serverPath - Path to the server file\n * @returns Markdown documentation\n */\nexport function generateMCPDocumentation(\n serverName: string,\n serverPath: string,\n): string {\n return `# MCP Server Setup\n\nThis project includes an auto-generated MCP (Model Context Protocol) server that exposes SMRT objects as tools for AI integration.\n\n## Quick Start\n\n### 1. Build the MCP Server\n\n\\`\\`\\`bash\nnpm run build\n\\`\\`\\`\n\nThis generates the MCP server at: \\`${serverPath}\\`\n\n### 2. Configure Claude Desktop\n\nAdd the following to your Claude Desktop configuration file:\n\n**macOS**: \\`~/.config/Claude/claude_desktop_config.json\\`\n**Windows**: \\`%APPDATA%\\\\Claude\\\\claude_desktop_config.json\\`\n\n\\`\\`\\`json\n{\n \"mcpServers\": {\n \"${serverName}\": {\n \"command\": \"node\",\n \"args\": [\"/absolute/path/to/${serverPath}\"]\n }\n }\n}\n\\`\\`\\`\n\nReplace \\`/absolute/path/to/\\` with the actual absolute path to your project directory.\n\n### 3. Restart Claude Desktop\n\nClose and reopen Claude Desktop to load the new MCP server.\n\n### 4. Test the Integration\n\nIn Claude Code, you can now use the auto-generated tools. For example:\n\n- \\`list_products\\` - List all products\n- \\`get_product\\` - Get a specific product by ID\n- \\`create_product\\` - Create a new product\n- And more...\n\n## Environment Variables\n\nThe MCP server supports optional environment variables:\n\n- \\`DATABASE_URL\\` - Database connection string\n\n**AI Provider Configuration (in priority order):**\n1. **\\`ai\\` block in \\`smrt.config.ts\\`** (declare once; keep the secret in the environment):\n - \\`ai: { provider: 'openai', model: 'gpt-4o', apiKeyEnv: 'OPENAI_API_KEY' }\\`\n\n2. **Generic environment configuration** (supports any provider):\n - \\`SMRT_AI_PROVIDER\\` - Provider name (e.g., 'openai', 'anthropic', 'claude-cli', 'gemini')\n - \\`SMRT_AI_API_KEY\\` - API key for the provider\n - \\`SMRT_AI_MODEL\\` - Model to use (optional)\n - \\`SMRT_AI_BASE_URL\\` - Endpoint override (optional)\n\n3. **Provider-specific key fallbacks** (used when the \\`ai\\` block selects the provider, and only for that provider):\n - \\`OPENAI_API_KEY\\`, \\`ANTHROPIC_API_KEY\\`, \\`GEMINI_API_KEY\\`\n - \\`CLAUDE_API_KEY\\` + \\`CLAUDE_MODEL\\` - Claude CLI provider (defaults to 'sonnet'); read by \\`@happyvertical/ai\\`\n\n**Examples:**\n\\`\\`\\`bash\n# Using generic configuration (recommended)\nexport SMRT_AI_PROVIDER=claude-cli\nexport SMRT_AI_MODEL=sonnet\n\n# Using provider-specific configuration\nexport CLAUDE_API_KEY=your-key\nexport CLAUDE_MODEL=sonnet\n\n# Using OpenAI\nexport OPENAI_API_KEY=your-openai-key\n\\`\\`\\`\n\n## Troubleshooting\n\n### Server Not Appearing in Claude\n\n1. Check that the path in \\`claude_desktop_config.json\\` is absolute\n2. Verify the server file exists at the specified path\n3. Check Claude Desktop logs for errors\n\n### Tools Not Working\n\n1. Ensure your database is accessible (if using one)\n2. Check that SMRT objects are properly decorated with \\`@smrt()\\`\n3. Look for errors in the MCP server output\n\n### Debug Mode\n\nTo enable debug logging, set the \\`DEBUG\\` constant to \\`true\\` in the generated server file.\n\n## Generated Tools\n\nThe following tools are automatically generated from your SMRT objects:\n\n- **CRUD Operations**: \\`list_\\`, \\`get_\\`, \\`create_\\`, \\`update_\\`, \\`delete_\\` for each object type\n- **Custom Actions**: Any custom methods included in the \\`@smrt()\\` decorator configuration\n\nSee the SMRT object definitions for the complete list of available tools and their parameters.\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAwBA,SAAS,WAAW,KAAqB;CACvC,OAAO,IAAI,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,IAAI,MAAM,CAAC;AAClD;;;;;;;AA0GA,SAAgB,yBAAyB,UAA0B,CAAC,GAAW;CAC7E,MAAM,EACJ,OAAO,mBACP,UAAU,SACV,cAAc,+CACd,QAAQ,OACR,QAAQ,CAAC,GACT,aAAa,qBACb,gBAAgB,CAAC,GACjB,cAAc,CAAC,GACf,sBAAsB,CAAC,GACvB,aAAa,CAAC,GACd,cAAc,CAAC,GACf,oBAAoB;EAAE,OAAO;EAAY,YAAY;CAAU,MAC7D;CAIJ,MAAM,cACJ,uBACA,OAAO,YACL,MAAM,KAAK,SAAS;EAClB,MAAM,YAAY,KAAK,KAAK,QAAQ,GAAG;EACvC,OAAO,CACL,KAAK,MACL;GACE,YAAY,WAAW,KAAK,KAAK,MAAM,GAAG,SAAS,CAAC;GACpD,QAAQ,KAAK,KAAK,MAAM,YAAY,CAAC;EACvC,CACF;CACF,CAAC,CACH;CACF,KAAK,MAAM,QAAQ,OACjB,IAAI,CAAC,OAAO,OAAO,aAAa,KAAK,IAAI,GACvC,MAAM,IAAI,MAAM,4BAA4B,KAAK,MAAM;CAK3D,MAAM,YAAY,MAAM,SAAS,IAAI,KAAK,UAAU,OAAO,MAAM,CAAC,IAAI;CACtE,MAAM,iBAAiB,OAAO,KAAK,WAAW,CAAC,CAAC,SAAS;CAKzD,MAAM,k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;;YAwCW,iBAAiB,yDAAyD,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgCvF,YAAY;;;;;;EAOZ,kBACI;;;;;;;;;sCAUA;6CAEL;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA2BuB,iBAAiB,8DAA8D,YAAY;;;;;;;QAO3G,iBAAiB,6GAA6G,GAAG;;;;;;;;;;;;;;;;;;;;AAoBzI;;;;;;;AAQA,SAAgB,kBACd,aAAqB,sBACb;CACR,OAAO,QAAQ;AACjB;;;;;;;;AASA,SAAgB,qBACd,YACA,YACQ;CACR,OAAO,EACL,YAAY,GACT,aAAa;EACZ,SAAS;EACT,MAAM,CAAC,UAAU;CACnB,EACF,EACF;AACF;;;;;;;;AASA,SAAgB,yBACd,YACA,YACQ;CACR,OAAO;;;;;;;;;;;;sCAY6B,WAAW;;;;;;;;;;;;OAY1C,WAAW;;oCAEkB,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkF/C"}
|
|
1
|
+
{"version":3,"file":"mcp-runtime-template.js","names":[],"sources":["../../src/generators/mcp-runtime-template.ts"],"sourcesContent":["/**\n * Runtime bootstrap template for generated MCP servers\n *\n * This template provides stdio transport integration for SMRT-generated MCP servers.\n * It handles:\n * - Server initialization with @modelcontextprotocol/server v2\n * - Tool registration from MCPGenerator\n * - Stdio transport connection\n * - Error handling and logging\n * - Graceful shutdown\n */\n\nimport {\n DEFAULT_LIST_LIMIT,\n DEFAULT_LIST_ORDER_BY,\n MAX_LIST_LIMIT,\n} from '../query-bounds.js';\nimport type { ApiSerializerReference } from '../registry/types.js';\nimport type { CustomActionScope } from './custom-action.js';\nimport type { MCPConfig, MCPContext } from './mcp.js';\nimport type { McpToolTarget } from './mcp-tool-name.js';\n\n/**\n * Helper function to capitalize first letter\n */\nfunction capitalize(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nexport interface RuntimeOptions {\n /** Server name (defaults to package name) */\n name?: string;\n\n /** Server version (defaults to package version) */\n version?: string;\n\n /** Server description */\n description?: string;\n\n /** MCP generator configuration */\n config?: MCPConfig;\n\n /** MCP context (database, AI client, etc.) */\n context?: MCPContext;\n\n /** Enable debug logging */\n debug?: boolean;\n\n /** Static tool definitions (generated at build time) */\n tools?: Array<{\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n outputSchema?: Record<string, unknown>;\n annotations?: {\n readOnlyHint: boolean;\n destructiveHint: boolean;\n idempotentHint: boolean;\n openWorldHint: boolean;\n };\n title?: string;\n icons?: Array<{\n src: string;\n mimeType?: string;\n sizes?: string[];\n theme?: 'light' | 'dark';\n }>;\n _meta?: Record<string, unknown>;\n }>;\n /** Explicit original execution targets for generated protocol aliases. */\n toolTargets?: Record<string, McpToolTarget>;\n /** Async serializers for standard get tools, keyed by emitted tool name. */\n getSerializers?: Record<string, ApiSerializerReference>;\n /** Cache hint emitted for deploy-static tools/list results. */\n toolListCacheHint?: {\n ttlMs: number;\n cacheScope: 'private' | 'public';\n };\n /** Internal invocation metadata; never exposed by the MCP tools/list result. */\n customActions?: Record<\n string,\n {\n scope: CustomActionScope;\n isStatic: boolean;\n /** Declared method name; tool IDs are lowercased protocol aliases. */\n methodName?: string;\n parameterNames?: string[];\n optionsParameter?: boolean;\n legacyOptions: boolean;\n }\n >;\n /** Task-enabled item custom actions. Never emitted in tools/list. */\n taskActions?: Record<\n string,\n {\n objectName: string;\n objectType: string;\n /** Registry identity of the task's class (#3490). */\n registryKey?: string;\n }\n >;\n\n /**\n * Lowercased simple names of objects that are `@TenantScoped` (#1554). When\n * non-empty, the generated server imports the tenancy fail-closed gate and\n * wraps tenant-scoped tool calls so a stdio invocation cannot read across all\n * tenants. The tenant is sourced from `SMRT_MCP_TENANT_ID` /\n * `SMRT_MCP_ALLOW_CROSS_TENANT` env vars (this server has no auth principal).\n */\n tenantScopedObjects?: string[];\n\n /**\n * Build-time approved STI discriminators, keyed by the lowercased MCP object\n * prefix. The generated runtime uses this instead of searching an initially\n * empty registry, then loads the approved qualified type through the public\n * collection API.\n */\n stiTargets?: Record<string, Record<string, string>>;\n\n /**\n * Default list ordering per lowercased MCP object prefix (#2367).\n *\n * Baked in at generation time because the tiebreak follows the model's\n * declared primary key, which the emitted server cannot resolve on its own.\n * Prefixes absent from this map fall back to {@link DEFAULT_LIST_ORDER_BY}.\n */\n listOrderBy?: Record<string, readonly string[]>;\n}\n\n/**\n * Generate runtime bootstrap code for MCP server\n *\n * @param options - Runtime configuration options\n * @returns TypeScript code for server entry point\n */\nexport function generateRuntimeBootstrap(options: RuntimeOptions = {}): string {\n const {\n name = 'smrt-mcp-server',\n version = '1.0.0',\n description = 'Auto-generated MCP server from SMRT objects',\n debug = false,\n tools = [],\n toolTargets: explicitToolTargets,\n getSerializers = {},\n customActions = {},\n taskActions = {},\n tenantScopedObjects = [],\n stiTargets = {},\n listOrderBy = {},\n toolListCacheHint = { ttlMs: 86_400_000, cacheScope: 'private' },\n } = options;\n\n // Direct template callers retain their legacy object_action inputs. The\n // owning generator always supplies explicit targets, including valid aliases.\n const toolTargets: Record<string, McpToolTarget> =\n explicitToolTargets ??\n Object.fromEntries(\n tools.map((tool) => {\n const separator = tool.name.indexOf('_');\n return [\n tool.name,\n {\n objectName: capitalize(tool.name.slice(0, separator)),\n action: tool.name.slice(separator + 1),\n },\n ];\n }),\n );\n for (const tool of tools) {\n if (!Object.hasOwn(toolTargets, tool.name)) {\n throw new Error(`Missing MCP tool target: ${tool.name}`);\n }\n }\n\n // Generate static tool array as TypeScript code\n const toolsCode = tools.length > 0 ? JSON.stringify(tools, null, 2) : '[]';\n const hasTaskActions = Object.keys(taskActions).length > 0;\n\n // Fail-closed tenant context (#1554): only wire the tenancy gate when at\n // least one exposed object is tenant-scoped, so apps without tenancy never\n // get a dangling import.\n const tenantScopedSet = Array.from(\n new Set(tenantScopedObjects.map((n) => n.toLowerCase())),\n );\n const hasTenantScoped = tenantScopedSet.length > 0;\n\n // Generate static switch cases using shared helper\n const generateSwitchCases = (indent: string) => {\n return tools\n .map((tool) => {\n const objectName = toolTargets[tool.name].objectName.toLowerCase();\n const action = toolTargets[tool.name].action;\n // Registry identity for every emitted lookup (#3490).\n const lookup =\n toolTargets[tool.name].registryKey ??\n toolTargets[tool.name].objectName;\n\n switch (action) {\n case 'list':\n return `${indent}case '${tool.name}': {\n${indent} const limit = resolveListBound(args.limit, 'limit', ${DEFAULT_LIST_LIMIT}, ${MAX_LIST_LIMIT});\n${indent} const offset = resolveListBound(args.offset, 'offset', 0);\n${indent} // #2367: the tool schema advertises \\`orderBy\\`, so honour it; and page\n${indent} // deterministically when it is omitted — LIMIT/OFFSET with no ORDER BY\n${indent} // lets successive pages repeat and skip rows on PostgreSQL.\n${indent} const orderBy = args.orderBy ?? ${JSON.stringify(\n listOrderBy[objectName] ?? DEFAULT_LIST_ORDER_BY,\n )};\n${indent} const where = args.where ?? {};\n\n${indent} const collection = await ObjectRegistry.getCollection(${JSON.stringify(lookup)}, {\n${indent} persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n${indent} ai: aiConfig\n${indent} });\n\n${indent} const items = await collection.list({ where, limit, offset, orderBy });\n${indent} const itemsPublic = items.map((item) => item.toPublicJSON(PUBLIC_JSON_OPTIONS));\n${indent} const structuredContent = {\n${indent} data: itemsPublic,\n${indent} meta: { total: await collection.count({ where }), limit, offset, count: items.length },\n${indent} };\n${indent} return successResult(structuredContent, JSON.stringify(itemsPublic));\n${indent}}`;\n\n case 'get':\n return `${indent}case '${tool.name}': {\n${indent} if (!args.id && !args.slug) {\n${indent} throw new Error('Either id or slug is required');\n${indent} }\n\n${indent} const collection = await ObjectRegistry.getCollection(${JSON.stringify(lookup)}, {\n${indent} persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n${indent} ai: aiConfig\n${indent} });\n\n${indent} const filter = args.id || args.slug;\n${indent} const item = await collection.get(filter);\n\n${indent} if (!item) {\n${indent} throw new Error('Object not found');\n${indent} }\n\n${indent} return successResult(await serializeGetResult(${JSON.stringify(tool.name)}, item));\n${indent}}`;\n\n case 'create':\n return `${indent}case '${tool.name}': {\n${indent} const { collection, objectName: targetObjectName } = await resolveCreateTarget(${JSON.stringify(objectName)}, ${JSON.stringify(lookup)}, args, aiConfig);\n\n${indent} const newItem = await collection.create(applyWritablePolicy(targetObjectName, args));\n\n${indent} return successResult(newItem.toPublicJSON(PUBLIC_JSON_OPTIONS));\n${indent}}`;\n\n case 'update':\n return `${indent}case '${tool.name}': {\n${indent} const { id, ...updateData } = args;\n${indent} if (!id) {\n${indent} throw new Error('ID is required for update');\n${indent} }\n\n${indent} const collection = await ObjectRegistry.getCollection(${JSON.stringify(lookup)}, {\n${indent} persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n${indent} ai: aiConfig\n${indent} });\n\n${indent} const existing = await collection.get(id);\n${indent} if (!existing) {\n${indent} throw new Error('Object not found');\n${indent} }\n\n${indent} await collection.withAuditMutation(existing, 'updated', async (bound) => {\n${indent} Object.assign(bound, applyWritablePolicy(${JSON.stringify(lookup)}, updateData));\n${indent} await bound.save();\n${indent} });\n\n${indent} return successResult(existing.toPublicJSON(PUBLIC_JSON_OPTIONS));\n${indent}}`;\n\n case 'delete':\n return `${indent}case '${tool.name}': {\n${indent} if (!args.id) {\n${indent} throw new Error('ID is required for delete');\n${indent} }\n\n${indent} const collection = await ObjectRegistry.getCollection(${JSON.stringify(lookup)}, {\n${indent} persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n${indent} ai: aiConfig\n${indent} });\n\n${indent} const toDelete = await collection.get(args.id);\n${indent} if (!toDelete) {\n${indent} throw new Error('Object not found');\n${indent} }\n\n${indent} await collection.delete(args.id);\n\n${indent} return successResult({ success: true, message: 'Object deleted successfully' });\n${indent}}`;\n\n default:\n // Custom action. Its descriptor is deliberately kept separate\n // from TOOLS so MCP clients receive only protocol-defined fields.\n return `${indent}case '${tool.name}': {\n${indent} const actionMeta = CUSTOM_ACTIONS['${tool.name}'] || { scope: 'item', isStatic: false, legacyOptions: true };\n${indent} const { id, options, ...directArgs } = args;\n\n${indent} if (actionMeta.scope === 'item' && !id) {\n${indent} throw new Error(${JSON.stringify(`ID is required for custom action ${action}`)});\n${indent} }\n${indent} if (actionMeta.scope === 'collection' && id) {\n${indent} throw new Error(${JSON.stringify(`Custom action ${action} is collection-scoped and does not accept an ID`)});\n${indent} }\n\n${indent} const collection = await ObjectRegistry.getCollection(${JSON.stringify(lookup)}, {\n${indent} persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n${indent} ai: aiConfig\n${indent} });\n\n${indent} const target = actionMeta.scope === 'item'\n${indent} ? await collection.get(id)\n${indent} : actionMeta.isStatic\n${indent} ? ObjectRegistry.getClass(${JSON.stringify(lookup)})?.constructor\n${indent} : collection;\n${indent} if (!target) {\n${indent} throw new Error(actionMeta.scope === 'item' ? 'Object not found' : 'Custom action target not found');\n${indent} }\n${indent} const actionMethod = target[actionMeta.methodName || ${JSON.stringify(action)}];\n${indent} if (typeof actionMethod !== 'function') {\n${indent} throw new Error(${JSON.stringify(`Method ${action} not found on custom action target`)});\n${indent} }\n\n${indent} const methodArgs = actionMeta.legacyOptions\n${indent} ? [Object.keys(options ?? {}).length > 0 ? options : directArgs]\n${indent} : actionMeta.optionsParameter\n${indent} ? [options]\n${indent} : (actionMeta.parameterNames || []).map((parameterName) => args[\n${indent} parameterName === 'id'\n${indent} ? 'actionId'\n${indent} : parameterName\n${indent} ]);\n${indent} const result = await actionMethod.call(target, ...methodArgs);\n${indent} const failure = normalizeCustomActionFailure(result);\n${indent} if (failure) {\n${indent} return errorResult(\n${indent} { error: failure },\n${indent} JSON.stringify({ error: failure }),\n${indent} { [SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY]: failure },\n${indent} );\n${indent} }\n\n${indent} const publicResult = toPublicResult(result);\n${indent} return successResult({ data: publicResult }, JSON.stringify(publicResult));\n${indent}}`;\n }\n })\n .join('\\n\\n');\n };\n\n const switchCases = generateSwitchCases(' ');\n\n return `#!/usr/bin/env node\n/**\n * Auto-generated MCP Server\n * Generated by @smrt/core MCPGenerator\n *\n * This server exposes SMRT objects as MCP tools for AI integration.\n *\n * SECURITY (#1540): tool responses exclude @field({ sensitive }) fields and\n * create/update bodies are mass-assignment guarded. This stdio server has NO\n * per-call authentication principal — its trust boundary is the host process /\n * MCP client that launches it. Run it only in a trusted context, or front it\n * with an authenticated gateway. Do not expose it directly to untrusted callers.\n */\n\nimport {\n type CallToolRequest,\n type ListToolsRequest,\n Server,\n ${hasTaskActions ? 'specTypeSchemas,' : ''}\n} from '@modelcontextprotocol/server';\nimport { ${hasTaskActions ? 'StdioServerTransport, ' : ''}serveStdio } from '@modelcontextprotocol/server/stdio';\nimport { existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\nimport { normalizeCustomActionFailure, SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY } from '@happyvertical/smrt-core';\nimport { loadConfig } from '@happyvertical/smrt-config';\n${hasTaskActions ? \"import { McpTaskStore, TaskRunner } from '@happyvertical/smrt-jobs';\\n\" : ''}\n${hasTenantScoped ? \"import { enableTenancy, runTenantScopedEntryPoint } from '@happyvertical/smrt-tenancy';\\n\" : ''}\n// Server configuration\nconst SERVER_NAME = ${JSON.stringify(name)};\nconst SERVER_VERSION = ${JSON.stringify(version)};\nconst SERVER_DESCRIPTION = ${JSON.stringify(description)};\nconst DEBUG = ${debug};\n\n// Static tool definitions (generated at build time)\nconst TOOLS = ${toolsCode};\nconst TOOL_LIST_CACHE_HINT = ${JSON.stringify(toolListCacheHint)};\nconst TOOL_TARGETS: Record<string, { objectName: string; action: string; registryKey?: string }> = ${JSON.stringify(toolTargets)};\nconst CUSTOM_ACTIONS = ${JSON.stringify(customActions)};\nconst TASK_ACTIONS = ${JSON.stringify(taskActions)};\nconst STI_TARGETS: Record<string, Record<string, string>> = ${JSON.stringify(stiTargets)};\n${\n hasTenantScoped\n ? `\n// Fail-closed tenant context (#1554): tenant-scoped objects must run inside a\n// tenant. This stdio server has no auth principal, so the tenant is taken from\n// the environment; without it (and with tenancy enabled) tenant-scoped tools\n// throw rather than reading across all tenants.\nconst TENANT_SCOPED = new Set(${JSON.stringify(tenantScopedSet)});\nconst MCP_TENANT_ID = process.env.SMRT_MCP_TENANT_ID || undefined;\nconst MCP_ALLOW_CROSS_TENANT = process.env.SMRT_MCP_ALLOW_CROSS_TENANT === 'true';\n`\n : ''\n}\nconst PUBLIC_JSON_OPTIONS = {\n permissions: (process.env.SMRT_MCP_PERMISSIONS || '')\n .split(',')\n .map((permission) => permission.trim())\n .filter(Boolean),\n};\nconst GET_SERIALIZERS: Record<string, { importPath: string; exportName: string }> = ${JSON.stringify(getSerializers)};\n\nasync function serializeGetResult(toolName: string, item: any): Promise<any> {\n const reference = GET_SERIALIZERS[toolName];\n if (!reference) return item.toPublicJSON(PUBLIC_JSON_OPTIONS);\n const serializerModule = await import(reference.importPath);\n const serializer = serializerModule[reference.exportName];\n if (typeof serializer !== 'function') {\n throw new Error(\n \\`MCP get serializer '\\${reference.exportName}' was not exported by '\\${reference.importPath}'\\`,\n );\n }\n return toPublicResult(await serializer(item, PUBLIC_JSON_OPTIONS));\n}\n\n/**\n * Page-bound guard (#2367). MCP tool arguments are untyped JSON, so \\`limit\\`\n * arrives as whatever the client sent: \\`\"abc\"\\` used to become \\`LIMIT NaN\\`\n * (a driver error, not a tool error), and nothing capped the value, so one\n * \\`limit: 100000000\\` call was a full table scan. Rejects anything that is not\n * a non-negative integer and clamps the rest to \\`max\\`.\n */\nfunction resolveListBound(raw: any, name: string, fallback: number, max?: number): number {\n if (raw === undefined || raw === null || raw === '') {\n return max === undefined ? fallback : Math.min(fallback, max);\n }\n const value = typeof raw === 'string' && /^\\\\d+$/.test(raw.trim()) ? Number(raw.trim()) : raw;\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error(\"Invalid \" + name + \": expected a non-negative integer, got \" + JSON.stringify(raw));\n }\n return max === undefined ? value : Math.min(value, max);\n}\n\n/**\n * Mass-assignment guard (#1540): strip framework/server-managed and\n * \\`@field({ readonly: true })\\` fields from create/update bodies, intersecting\n * with the optional \\`@smrt({ api: { writable: [...] } })\\` allowlist.\n */\nfunction applyWritablePolicy(objectName: string, data: any): Record<string, any> {\n if (!data || typeof data !== 'object') return {};\n const serverManaged = new Set([\n 'id', 'tenantId', 'tenant_id',\n 'createdAt', 'created_at', 'updatedAt', 'updated_at',\n ]);\n const readonly = new Set<string>();\n let writable: string[] | null = null;\n const apiConfig = ObjectRegistry.getConfig(objectName)?.api as any;\n if (apiConfig && typeof apiConfig === 'object' && Array.isArray(apiConfig.writable)) {\n writable = apiConfig.writable;\n }\n for (const [name, def] of ObjectRegistry.getFields(objectName)) {\n if (def && ((def as any).readonly === true || (def as any)._meta?.readonly === true)) {\n readonly.add(name);\n }\n }\n const result: Record<string, any> = {};\n for (const [key, value] of Object.entries(data)) {\n if (key.startsWith('_')) continue;\n if (serverManaged.has(key)) continue;\n if (readonly.has(key)) continue;\n if (writable && !writable.includes(key)) continue;\n result[key] = value;\n }\n return result;\n}\n\n/** Resolve an advertised STI discriminator to its registered subtype collection. */\nasync function resolveCreateTarget(stiKey: string, baseObjectName: string, args: Record<string, any>, aiConfig: any) {\n let objectName = baseObjectName;\n const discriminator = args._meta_type;\n const targets = STI_TARGETS[stiKey];\n if (typeof discriminator === 'string' && targets) {\n const target = targets[discriminator];\n if (!target) throw new Error('Unknown STI discriminator: ' + discriminator);\n objectName = target;\n }\n const collection = await ObjectRegistry.getCollection(objectName, {\n persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n ai: aiConfig,\n });\n return { collection, objectName };\n}\n\n/**\n * Sensitive-field-safe serialization for custom-action results (#1540).\n * Recurses through arrays and plain objects so nested SmrtObjects are stripped\n * too; non-plain instances (Date, etc.) and primitives pass through. Cycle-safe.\n */\nfunction toPublicResult(value: any, seen: WeakSet<object> = new WeakSet()): any {\n if (value === null || typeof value !== 'object') return value;\n if (typeof value.toPublicJSON === 'function') return value.toPublicJSON(PUBLIC_JSON_OPTIONS);\n if (Array.isArray(value)) {\n if (seen.has(value)) return value;\n seen.add(value);\n return value.map((entry: any) => toPublicResult(entry, seen));\n }\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) return value;\n if (seen.has(value)) return value;\n seen.add(value);\n const out: Record<string, any> = {};\n for (const [key, entry] of Object.entries(value)) {\n out[key] = toPublicResult(entry, seen);\n }\n return out;\n}\n\nfunction successResult(structuredContent: any, text = JSON.stringify(structuredContent)) {\n return {\n content: [{ type: 'text', text }],\n structuredContent,\n };\n}\n\nfunction errorResult(structuredContent: any, text: string, _meta?: Record<string, any>) {\n return {\n content: [{ type: 'text', text }],\n isError: true,\n structuredContent,\n ...(_meta ? { _meta } : {}),\n };\n}\n\nfunction normalizePublicToolError(error: any): { code: string; message: string } | undefined {\n if (!error || typeof error !== 'object') return undefined;\n if (\n typeof error.code !== 'string' ||\n !/^[A-Za-z][A-Za-z0-9_.:-]{0,127}$/.test(error.code) ||\n typeof error.publicMessage !== 'string' ||\n error.publicMessage.length === 0\n ) return undefined;\n return { code: error.code, message: error.publicMessage };\n}\n\n${\n hasTaskActions\n ? `\n// The bundled SDK validates tools/call responses against its older result\n// codec, which does not yet know CreateTaskResult. Intercept the extension at\n// the transport boundary, then pass every non-task message untouched to the\n// SDK server. This keeps ordinary MCP behaviour and version negotiation owned\n// by the SDK while making the extension available today.\nconst MCP_TASKS_EXTENSION = 'io.modelcontextprotocol/tasks';\nlet taskRuntime: Promise<{ store: McpTaskStore; runner: TaskRunner }> | undefined;\n\nfunction clientSupportsTasks(message: any): boolean {\n return message?.params?._meta?.['io.modelcontextprotocol/clientCapabilities']\n ?.extensions?.[MCP_TASKS_EXTENSION] !== undefined;\n}\n\n/** Validate the 2026 request envelope before task dispatch mutates a job. */\nfunction taskEnvelopeError(message: any): { code: number; message: string; data?: any } | undefined {\n const meta = message?.params?._meta;\n if (!meta || typeof meta !== 'object' || Array.isArray(meta)) {\n return {\n code: -32602,\n message: 'Request is missing the required _meta envelope for protocol revision 2026-07-28',\n };\n }\n const protocolVersion = meta['io.modelcontextprotocol/protocolVersion'];\n if (protocolVersion !== '2026-07-28') {\n return typeof protocolVersion === 'string'\n ? {\n code: -32022,\n message: 'Unsupported protocol version: ' + protocolVersion,\n data: { supported: ['2026-07-28'], requested: protocolVersion },\n }\n : {\n code: -32602,\n message: 'Invalid _meta envelope for protocol revision 2026-07-28: io.modelcontextprotocol/protocolVersion must be a string',\n };\n }\n if (!specTypeSchemas.ClientCapabilities.safeParse(\n meta['io.modelcontextprotocol/clientCapabilities'],\n ).success) {\n return {\n code: -32602,\n message: 'Invalid _meta envelope for protocol revision 2026-07-28: io.modelcontextprotocol/clientCapabilities is invalid',\n };\n }\n if (\n meta['io.modelcontextprotocol/clientInfo'] !== undefined &&\n !specTypeSchemas.Implementation.safeParse(\n meta['io.modelcontextprotocol/clientInfo'],\n ).success\n ) {\n return {\n code: -32602,\n message: 'Invalid _meta envelope for protocol revision 2026-07-28: io.modelcontextprotocol/clientInfo is invalid',\n };\n }\n if (\n meta['io.modelcontextprotocol/logLevel'] !== undefined &&\n !specTypeSchemas.LoggingLevel.safeParse(\n meta['io.modelcontextprotocol/logLevel'],\n ).success\n ) {\n return {\n code: -32602,\n message: 'Invalid _meta envelope for protocol revision 2026-07-28: io.modelcontextprotocol/logLevel is invalid',\n };\n }\n if (\n meta.progressToken !== undefined &&\n !specTypeSchemas.ProgressToken.safeParse(meta.progressToken).success\n ) {\n return {\n code: -32602,\n message: 'Invalid _meta envelope for protocol revision 2026-07-28: progressToken is invalid',\n };\n }\n return undefined;\n}\n\nfunction jsonRpcError(id: any, code: number, message: string, data?: any) {\n return { jsonrpc: '2.0', id, error: { code, message, ...(data === undefined ? {} : { data }) } };\n}\n\nasync function getTaskRuntime() {\n if (!taskRuntime) {\n taskRuntime = (async () => {\n const firstAction = Object.values(TASK_ACTIONS)[0] as { objectName: string; registryKey?: string } | undefined;\n if (!firstAction) throw new Error('No task-enabled MCP action is configured');\n const collection = await ObjectRegistry.getCollection(firstAction.registryKey ?? firstAction.objectName, {\n persistence: { type: process.env.DATABASE_TYPE || 'sqlite', url: process.env.DATABASE_URL || ':memory:' },\n });\n const db = collection.db;\n const store = await McpTaskStore.create(db, { ownerId: process.env.SMRT_MCP_TENANT_ID || null, tenantId: ${hasTenantScoped ? 'MCP_TENANT_ID ?? null' : 'null'} });\n const runner = new TaskRunner({ queues: ['mcp-tasks'] });\n await runner.initialize(db);\n await runner.start();\n return { store, runner };\n })();\n }\n return taskRuntime;\n}\n\nfunction taskInvocationArgs(actionMeta: any, args: Record<string, any>): any[] {\n const { id: _id, options, ...directArgs } = args;\n if (actionMeta.legacyOptions) {\n return [Object.keys(options ?? {}).length > 0 ? options : directArgs];\n }\n if (actionMeta.optionsParameter) return [options];\n const parameterNames = actionMeta.parameterNames || [];\n const invocationParameterNames = parameterNames.at(-1) === 'context'\n ? parameterNames.slice(0, -1)\n : parameterNames;\n return invocationParameterNames.map((parameterName: string) =>\n args[parameterName === 'id' ? 'actionId' : parameterName],\n );\n}\n\nasync function handleTaskExtensionMessage(message: any): Promise<any | null> {\n if (!message || typeof message !== 'object' || message.id === undefined) return null;\n const method = message.method;\n const params = message.params ?? {};\n const action = method === 'tools/call' ? TASK_ACTIONS[params.name] : undefined;\n const isTaskMethod = action || ['tasks/get', 'tasks/update', 'tasks/cancel'].includes(method);\n if (!isTaskMethod) return null;\n // A task-enabled tool retains its normal synchronous behaviour until its\n // client explicitly opts into Tasks. Do not impose the task envelope on\n // legacy calls that will be passed untouched to the SDK.\n if (!clientSupportsTasks(message) && method === 'tools/call') return null;\n const envelopeError = taskEnvelopeError(message);\n if (envelopeError) {\n return jsonRpcError(message.id, envelopeError.code, envelopeError.message, envelopeError.data);\n }\n if (!clientSupportsTasks(message)) {\n // A task-only method cannot fall back to a legacy response shape. A task\n // tool can still run normally when the client did not opt in, so let the\n // SDK handle that direct tools/call path.\n if (method === 'tools/call') return null;\n return jsonRpcError(message.id, -32021, 'Missing required client capability', {\n requiredCapabilities: { extensions: { [MCP_TASKS_EXTENSION]: {} } },\n });\n }\n try {\n const { store } = await getTaskRuntime();\n if (action) {\n if (typeof params.arguments?.id !== 'string') {\n return jsonRpcError(message.id, -32602, 'Task-enabled custom actions require an id');\n }\n const actionMeta = CUSTOM_ACTIONS[params.name];\n const task = await store.createTask({\n objectType: action.objectType,\n objectId: params.arguments.id,\n method: actionMeta.methodName || TOOL_TARGETS[params.name]?.action,\n invocationArgs: taskInvocationArgs(actionMeta, params.arguments),\n tenantId: ${hasTenantScoped ? 'MCP_TENANT_ID ?? null' : 'null'},\n });\n return { jsonrpc: '2.0', id: message.id, result: { resultType: 'task', content: [], structuredContent: {}, ...task } };\n }\n if (typeof params.taskId !== 'string') {\n return jsonRpcError(message.id, -32602, 'taskId is required');\n }\n if (method === 'tasks/get') {\n const task = await store.getTask(params.taskId);\n return { jsonrpc: '2.0', id: message.id, result: { resultType: 'complete', ...task } };\n }\n if (method === 'tasks/update') {\n await store.updateTask(\n params.taskId,\n params.inputResponses && typeof params.inputResponses === 'object'\n ? params.inputResponses\n : {},\n );\n return { jsonrpc: '2.0', id: message.id, result: { resultType: 'complete' } };\n }\n await store.cancelTask(params.taskId);\n return { jsonrpc: '2.0', id: message.id, result: { resultType: 'complete' } };\n } catch (error) {\n const messageText = error instanceof Error ? error.message : 'Task operation failed';\n return jsonRpcError(message.id, -32602, messageText);\n }\n}\n\nclass McpTaskExtensionTransport {\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: any) => void;\n\n // An explicit field, not a parameter property: a \\`.ts\\` target has to stay\n // erasable-syntax-only so Node's type stripping can run it (#2279).\n wire: StdioServerTransport;\n\n constructor(wire: StdioServerTransport) {\n this.wire = wire;\n }\n\n async start() {\n this.wire.onclose = () => this.onclose?.();\n this.wire.onerror = (error) => this.onerror?.(error);\n this.wire.onmessage = (message) => {\n void (async () => {\n const response = await handleTaskExtensionMessage(message);\n if (response) await this.wire.send(response);\n else this.onmessage?.(message);\n })().catch((error) => this.onerror?.(error instanceof Error ? error : new Error(String(error))));\n };\n await this.wire.start();\n }\n\n close() { return this.wire.close(); }\n send(message: any) { return this.wire.send(message); }\n}\n`\n : ''\n}\n\n/**\n * Main server startup function\n */\nexport async function createServer(): Promise<Server> {\n if (DEBUG) {\n console.error(\\`[MCP] Starting server: \\${SERVER_NAME} v\\${SERVER_VERSION}\\`);\n }\n${\n hasTenantScoped\n ? `\n // Fail-closed tenant context (#1554): install the tenancy interceptor so\n // tenant-scoped tools are actually filtered, and so the entry-point gate\n // throws (rather than passing through) when no tenant is supplied. Without\n // this, a tenant set via SMRT_MCP_TENANT_ID would only set async context\n // with no interceptor to enforce it.\n enableTenancy();\n`\n : ''\n}\n // Register the application package manifest before resolving generated\n // object names. Generated servers are commonly run from the application\n // package itself, which is not a node_modules dependency of its process.\n const localManifestPaths = [\n resolve(process.cwd(), 'dist', 'manifest.json'),\n resolve(process.cwd(), '.smrt', 'manifest.json'),\n ].filter(existsSync);\n if (localManifestPaths.length > 0) {\n ObjectRegistry.loadAllManifests({ manifestPaths: localManifestPaths });\n }\n\n // A manifest supplies schemas and tool metadata, while an executable\n // custom action also needs the application's actual class constructor.\n // Consumer builds generate this registration module; load it after the\n // manifest so decorators enrich the already-known metadata.\n const localRegisterPath = process.env.SMRT_MCP_REGISTER_PATH\n || resolve(process.cwd(), '.smrt', 'register.js');\n if (existsSync(localRegisterPath)) {\n await import(pathToFileURL(localRegisterPath).href);\n }\n\n // Load configuration from environment and .smrt.config files\n const appConfig = await loadConfig();\n const aiConfig = appConfig?.ai || {};\n\n if (DEBUG) {\n console.error(\\`[MCP] Loaded \\${TOOLS.length} static tools\\`);\n console.error(\\`[MCP] Available tools:\\`, TOOLS.map(t => t.name).join(', '));\n }\n\n // Create MCP server\n const server = new Server(\n {\n name: SERVER_NAME,\n version: SERVER_VERSION,\n },\n {\n capabilities: {\n tools: {},\n ${hasTaskActions ? \"extensions: { 'io.modelcontextprotocol/tasks': {} },\" : ''}\n },\n cacheHints: {\n 'tools/list': TOOL_LIST_CACHE_HINT,\n },\n }\n );\n\n // Register ListTools handler\n server.setRequestHandler('tools/list', async (_request: ListToolsRequest) => {\n if (DEBUG) {\n console.error(\\`[MCP] ListTools request received\\`);\n }\n\n return {\n tools: [...TOOLS].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0),\n };\n });\n\n // Register CallTool handler\n server.setRequestHandler('tools/call', async (request: CallToolRequest) => {\n const { name: toolName, arguments: args = {} } = request.params;\n\n if (DEBUG) {\n console.error(\\`[MCP] CallTool request: \\${toolName}\\`);\n console.error(\\`[MCP] Arguments:\\`, JSON.stringify(args, null, 2));\n }\n\n try {\n // Static switch statement for tool execution\n const runToolBody = async () => {\n switch (toolName) {\n${switchCases}\n\n default:\n throw new Error(\\`Unknown tool: \\${toolName}\\`);\n }\n };\n${\n hasTenantScoped\n ? `\n // Fail-closed tenant context for tenant-scoped tools (#1554).\n const toolObject = TOOL_TARGETS[toolName]?.objectName;\n const result =\n toolObject && TENANT_SCOPED.has(toolObject.toLowerCase())\n ? await runTenantScopedEntryPoint(\n { tenantScoped: true, tenantId: MCP_TENANT_ID, allowCrossTenant: MCP_ALLOW_CROSS_TENANT, surface: 'MCP' },\n runToolBody,\n )\n : await runToolBody();`\n : `\n const result = await runToolBody();`\n}\n\n if (DEBUG) {\n console.error(\\`[MCP] Tool executed successfully: \\${toolName}\\`);\n }\n\n return result;\n } catch (error) {\n const publicError = normalizePublicToolError(error);\n const errorMessage = publicError?.message ?? (error instanceof Error ? error.message : 'Unknown error');\n console.error(\\`[MCP] Tool execution failed: \\${toolName}\\`, error);\n\n return errorResult(\n { error: publicError ?? { message: errorMessage } },\n \\`Error executing tool \\${toolName}: \\${errorMessage}\\`,\n );\n }\n });\n\n return server;\n}\n\nasync function main() {\n try {\n // Initialize the registry before accepting an intercepted task call. The\n // SDK would normally invoke this factory for the first regular message,\n // but task calls can be the first message on a stdio connection.\n const server = await createServer();\n const transport = ${hasTaskActions ? 'new McpTaskExtensionTransport(new StdioServerTransport())' : 'undefined'};\n const handle = serveStdio(() => server, {\n ...(transport ? { transport } : {}),\n onerror: (error) => console.error('[MCP] Protocol error:', error),\n });\n const shutdown = async () => {\n if (DEBUG) console.error('[MCP] Shutting down gracefully');\n ${hasTaskActions ? 'if (taskRuntime) {\\n const { runner } = await taskRuntime;\\n await runner.stop();\\n }' : ''}\n await handle.close();\n process.exit(0);\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n } catch (error) {\n console.error('[MCP] Fatal error during server startup:', error);\n process.exit(1);\n }\n}\n\n// Start only when executed, so adapters and tests may import the factory.\nif (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {\n main().catch((error) => {\n console.error('[MCP] Unhandled error:', error);\n process.exit(1);\n });\n}\n`;\n}\n\n/**\n * Generate package.json script for running MCP server\n *\n * @param serverPath - Path to generated server file (relative to package root)\n * @returns Script command for package.json\n */\nexport function generateMCPScript(\n serverPath: string = 'dist/mcp-server.js',\n): string {\n return `node ${serverPath}`;\n}\n\n/**\n * Generate Claude Desktop configuration example\n *\n * @param serverName - Name for the MCP server\n * @param serverPath - Absolute path to server file\n * @returns Configuration object for claude_desktop_config.json\n */\nexport function generateClaudeConfig(\n serverName: string,\n serverPath: string,\n): object {\n return {\n mcpServers: {\n [serverName]: {\n command: 'node',\n args: [serverPath],\n },\n },\n };\n}\n\n/**\n * Generate README documentation for MCP server setup\n *\n * @param serverName - Name of the MCP server\n * @param serverPath - Path to the server file\n * @returns Markdown documentation\n */\nexport function generateMCPDocumentation(\n serverName: string,\n serverPath: string,\n): string {\n return `# MCP Server Setup\n\nThis project includes an auto-generated MCP (Model Context Protocol) server that exposes SMRT objects as tools for AI integration.\n\n## Quick Start\n\n### 1. Build the MCP Server\n\n\\`\\`\\`bash\nnpm run build\n\\`\\`\\`\n\nThis generates the MCP server at: \\`${serverPath}\\`\n\n### 2. Configure Claude Desktop\n\nAdd the following to your Claude Desktop configuration file:\n\n**macOS**: \\`~/.config/Claude/claude_desktop_config.json\\`\n**Windows**: \\`%APPDATA%\\\\Claude\\\\claude_desktop_config.json\\`\n\n\\`\\`\\`json\n{\n \"mcpServers\": {\n \"${serverName}\": {\n \"command\": \"node\",\n \"args\": [\"/absolute/path/to/${serverPath}\"]\n }\n }\n}\n\\`\\`\\`\n\nReplace \\`/absolute/path/to/\\` with the actual absolute path to your project directory.\n\n### 3. Restart Claude Desktop\n\nClose and reopen Claude Desktop to load the new MCP server.\n\n### 4. Test the Integration\n\nIn Claude Code, you can now use the auto-generated tools. For example:\n\n- \\`list_products\\` - List all products\n- \\`get_product\\` - Get a specific product by ID\n- \\`create_product\\` - Create a new product\n- And more...\n\n## Environment Variables\n\nThe MCP server supports optional environment variables:\n\n- \\`DATABASE_URL\\` - Database connection string\n\n**AI Provider Configuration (in priority order):**\n1. **\\`ai\\` block in \\`smrt.config.ts\\`** (declare once; keep the secret in the environment):\n - \\`ai: { provider: 'openai', model: 'gpt-4o', apiKeyEnv: 'OPENAI_API_KEY' }\\`\n\n2. **Generic environment configuration** (supports any provider):\n - \\`SMRT_AI_PROVIDER\\` - Provider name (e.g., 'openai', 'anthropic', 'claude-cli', 'gemini')\n - \\`SMRT_AI_API_KEY\\` - API key for the provider\n - \\`SMRT_AI_MODEL\\` - Model to use (optional)\n - \\`SMRT_AI_BASE_URL\\` - Endpoint override (optional)\n\n3. **Provider-specific key fallbacks** (used when the \\`ai\\` block selects the provider, and only for that provider):\n - \\`OPENAI_API_KEY\\`, \\`ANTHROPIC_API_KEY\\`, \\`GEMINI_API_KEY\\`\n - \\`CLAUDE_API_KEY\\` + \\`CLAUDE_MODEL\\` - Claude CLI provider (defaults to 'sonnet'); read by \\`@happyvertical/ai\\`\n\n**Examples:**\n\\`\\`\\`bash\n# Using generic configuration (recommended)\nexport SMRT_AI_PROVIDER=claude-cli\nexport SMRT_AI_MODEL=sonnet\n\n# Using provider-specific configuration\nexport CLAUDE_API_KEY=your-key\nexport CLAUDE_MODEL=sonnet\n\n# Using OpenAI\nexport OPENAI_API_KEY=your-openai-key\n\\`\\`\\`\n\n## Troubleshooting\n\n### Server Not Appearing in Claude\n\n1. Check that the path in \\`claude_desktop_config.json\\` is absolute\n2. Verify the server file exists at the specified path\n3. Check Claude Desktop logs for errors\n\n### Tools Not Working\n\n1. Ensure your database is accessible (if using one)\n2. Check that SMRT objects are properly decorated with \\`@smrt()\\`\n3. Look for errors in the MCP server output\n\n### Debug Mode\n\nTo enable debug logging, set the \\`DEBUG\\` constant to \\`true\\` in the generated server file.\n\n## Generated Tools\n\nThe following tools are automatically generated from your SMRT objects:\n\n- **CRUD Operations**: \\`list_\\`, \\`get_\\`, \\`create_\\`, \\`update_\\`, \\`delete_\\` for each object type\n- **Custom Actions**: Any custom methods included in the \\`@smrt()\\` decorator configuration\n\nSee the SMRT object definitions for the complete list of available tools and their parameters.\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyBA,SAAS,WAAW,KAAqB;CACvC,OAAO,IAAI,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,IAAI,MAAM,CAAC;AAClD;;;;;;;AA4GA,SAAgB,yBAAyB,UAA0B,CAAC,GAAW;CAC7E,MAAM,EACJ,OAAO,mBACP,UAAU,SACV,cAAc,+CACd,QAAQ,OACR,QAAQ,CAAC,GACT,aAAa,qBACb,iBAAiB,CAAC,GAClB,gBAAgB,CAAC,GACjB,cAAc,CAAC,GACf,sBAAsB,CAAC,GACvB,aAAa,CAAC,GACd,cAAc,CAAC,GACf,oBAAoB;EAAE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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkF/C"}
|
package/dist/generators/mcp.d.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { type CustomActionMetadata, type ToolEffect } from './custom-action.js';
|
|
7
7
|
import { type ToolJsonSchema } from './tool-schema.js';
|
|
8
|
+
export { type McpGetSerializer, type McpGetSerializerReference, resolveMcpGetSerializer, } from '../mcp-serializer.js';
|
|
8
9
|
export type { ToolEffect } from './custom-action.js';
|
|
9
10
|
export { assertMcpJsonSchemaSafety, type ToolJsonSchema, } from './tool-schema.js';
|
|
10
11
|
/**
|
|
@@ -206,6 +207,7 @@ export declare class MCPGenerator {
|
|
|
206
207
|
private config;
|
|
207
208
|
private context;
|
|
208
209
|
private collections;
|
|
210
|
+
private getSerializers;
|
|
209
211
|
constructor(config?: MCPConfig, context?: MCPContext);
|
|
210
212
|
/**
|
|
211
213
|
* Get server name
|
|
@@ -341,6 +343,9 @@ export declare class MCPGenerator {
|
|
|
341
343
|
* invoked inside the tenant gate established by {@link executeAction}.
|
|
342
344
|
*/
|
|
343
345
|
private runAction;
|
|
346
|
+
private getSerializerReference;
|
|
347
|
+
private serializeGetResult;
|
|
348
|
+
private runtimeGetSerializers;
|
|
344
349
|
/**
|
|
345
350
|
* Execute a custom action on a collection/object
|
|
346
351
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../src/generators/mcp.ts"],"names":[],"mappings":"AAAA;;;;GAIG;
|
|
1
|
+
{"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../src/generators/mcp.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAyBH,OAAO,EAGL,KAAK,oBAAoB,EAQzB,KAAK,UAAU,EAChB,MAAM,oBAAoB,CAAC;AAiB5B,OAAO,EAQL,KAAK,cAAc,EACpB,MAAM,kBAAkB,C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;;;;;;;;;;;;;;OA0BG;IACG,cAAc,CAClB,OAAO,GAAE;QACP;;;;;;WAMG;QACH,UAAU,CAAC,EAAE,MAAM,CAAC;QAEpB,oCAAoC;QACpC,UAAU,CAAC,EAAE,MAAM,CAAC;QAEpB,qBAAqB;QACrB,aAAa,CAAC,EAAE,MAAM,CAAC;QAEvB,2BAA2B;QAC3B,KAAK,CAAC,EAAE,OAAO,CAAC;QAEhB,oDAAoD;QACpD,wBAAwB,CAAC,EAAE,OAAO,CAAC;QAEnC,oCAAoC;QACpC,cAAc,CAAC,EAAE,OAAO,CAAC;QAEzB,uEAAuE;QACvE,OAAO,CAAC,EAAE,OAAO,CAAC;KACd,GACL,OAAO,CAAC,IAAI,CAAC;YA6FF,oBAAoB;IA0ClC,4EAA4E;YAC9D,kBAAkB;IAmBhC;;;;;OAKG;IACH;;;;;;;;OAQG;IACH,OAAO,CAAC,yBAAyB;IAejC;;;;OAIG;IACH,OAAO,CAAC,kBAAkB;IAkB1B,OAAO,CAAC,iBAAiB;IAyBzB;;;;;;;;;;;;;;;OAeG;YACW,qBAAqB;IA0DnC;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAiB1B;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAwBzB;;OAEG;YACW,uBAAuB;IA6MrC;;OAEG;YACW,oBAAoB;IAuNlC;;;;;OAKG;IACH,OAAO,CAAC,oBAAoB;CAsH7B"}
|
package/dist/generators/mcp.js
CHANGED
|
@@ -5,6 +5,7 @@ import { SmrtCollection } from "../collection.js";
|
|
|
5
5
|
import { readFieldEnum } from "../registry/manifest-field-merge.js";
|
|
6
6
|
import { ObjectRegistry } from "../registry.js";
|
|
7
7
|
import { SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, buildCustomActionInvocationArgs, customActionParameterInputName, isCrudOperation, isCrudToolAction, isFrameworkLifecycleMethod, normalizeCustomActionFailure, resolveCustomActionMetadata } from "./custom-action.js";
|
|
8
|
+
import { resolveMcpGetSerializer } from "../mcp-serializer.js";
|
|
8
9
|
import { resolveDisplayLabelField } from "../ui-metadata.js";
|
|
9
10
|
import { generatedSiblingExtension, renderGeneratedSource, resolveGeneratedSourceLanguage } from "./mcp-emit.js";
|
|
10
11
|
import { generateClaudeConfig, generateMCPDocumentation, generateMCPScript, generateRuntimeBootstrap } from "./mcp-runtime-template.js";
|
|
@@ -32,6 +33,15 @@ import { dirname, resolve } from "node:path";
|
|
|
32
33
|
async function writeGeneratedFile(targetPath, source, language) {
|
|
33
34
|
await writeFile(targetPath, await renderGeneratedSource(source, language, targetPath), "utf-8");
|
|
34
35
|
}
|
|
36
|
+
function normalizePublicToolError(error) {
|
|
37
|
+
if (!error || typeof error !== "object") return void 0;
|
|
38
|
+
const candidate = error;
|
|
39
|
+
if (typeof candidate.code !== "string" || !/^[A-Za-z][A-Za-z0-9_.:-]{0,127}$/.test(candidate.code) || typeof candidate.publicMessage !== "string" || candidate.publicMessage.length === 0) return void 0;
|
|
40
|
+
return {
|
|
41
|
+
code: candidate.code,
|
|
42
|
+
message: candidate.publicMessage
|
|
43
|
+
};
|
|
44
|
+
}
|
|
35
45
|
var MCP_STABLE_CATALOG_TTL_MS = 864e5;
|
|
36
46
|
/**
|
|
37
47
|
* Resolve the generated tools/list cache policy at generation time.
|
|
@@ -145,6 +155,7 @@ var MCPGenerator = class {
|
|
|
145
155
|
config;
|
|
146
156
|
context;
|
|
147
157
|
collections = /* @__PURE__ */ new Map();
|
|
158
|
+
getSerializers = /* @__PURE__ */ new Map();
|
|
148
159
|
constructor(config = {}, context = {}) {
|
|
149
160
|
this.config = {
|
|
150
161
|
name: "smrt-mcp-server",
|
|
@@ -595,14 +606,15 @@ var MCPGenerator = class {
|
|
|
595
606
|
_meta: { [SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY]: error.failure }
|
|
596
607
|
};
|
|
597
608
|
}
|
|
598
|
-
const
|
|
609
|
+
const publicError = normalizePublicToolError(error);
|
|
610
|
+
const message = publicError?.message ?? (error instanceof Error ? error.message : "Unknown error");
|
|
599
611
|
return {
|
|
600
612
|
content: [{
|
|
601
613
|
type: "text",
|
|
602
614
|
text: `Error: ${message}`
|
|
603
615
|
}],
|
|
604
616
|
isError: true,
|
|
605
|
-
structuredContent: { error: { message } }
|
|
617
|
+
structuredContent: { error: publicError ?? { message } }
|
|
606
618
|
};
|
|
607
619
|
}
|
|
608
620
|
}
|
|
@@ -878,7 +890,7 @@ var MCPGenerator = class {
|
|
|
878
890
|
const filter = args.id ? args.id : args.slug;
|
|
879
891
|
const item = await collection.get(filter);
|
|
880
892
|
if (!item) throw new Error("Object not found");
|
|
881
|
-
return this.
|
|
893
|
+
return this.serializeGetResult(objectName, item);
|
|
882
894
|
}
|
|
883
895
|
case "create": {
|
|
884
896
|
const createData = this.applyWritablePolicy(objectName, args);
|
|
@@ -916,6 +928,37 @@ var MCPGenerator = class {
|
|
|
916
928
|
}
|
|
917
929
|
}
|
|
918
930
|
}
|
|
931
|
+
getSerializerReference(objectName) {
|
|
932
|
+
if (!objectName) return void 0;
|
|
933
|
+
const mcp = ObjectRegistry.getConfig(objectName)?.mcp;
|
|
934
|
+
return mcp && typeof mcp === "object" ? mcp.serializers?.get : void 0;
|
|
935
|
+
}
|
|
936
|
+
async serializeGetResult(objectName, item) {
|
|
937
|
+
const reference = this.getSerializerReference(objectName);
|
|
938
|
+
if (!reference) return this.toPublicData(item);
|
|
939
|
+
const cacheKey = `${objectName ?? ""}\u0000${reference.importPath}\u0000${reference.exportName}`;
|
|
940
|
+
let serializerPromise = this.getSerializers.get(cacheKey);
|
|
941
|
+
if (!serializerPromise) {
|
|
942
|
+
serializerPromise = resolveMcpGetSerializer(reference, {
|
|
943
|
+
parentUrl: import.meta.url,
|
|
944
|
+
ownerRegistryKey: objectName
|
|
945
|
+
});
|
|
946
|
+
this.getSerializers.set(cacheKey, serializerPromise);
|
|
947
|
+
}
|
|
948
|
+
const serializer = await serializerPromise;
|
|
949
|
+
const options = this.getPublicJsonOptions();
|
|
950
|
+
return this.toPublicData(await serializer(item, options), /* @__PURE__ */ new WeakSet(), options);
|
|
951
|
+
}
|
|
952
|
+
runtimeGetSerializers(tools) {
|
|
953
|
+
const serializers = {};
|
|
954
|
+
for (const tool of tools) {
|
|
955
|
+
if (this.toolTarget(tool).action !== "get") continue;
|
|
956
|
+
const owner = this.toolClass(tool);
|
|
957
|
+
const reference = this.getSerializerReference(owner?.key);
|
|
958
|
+
if (reference) serializers[tool.name] = reference;
|
|
959
|
+
}
|
|
960
|
+
return serializers;
|
|
961
|
+
}
|
|
919
962
|
/**
|
|
920
963
|
* Execute a custom action on a collection/object
|
|
921
964
|
*/
|
|
@@ -1016,6 +1059,7 @@ var MCPGenerator = class {
|
|
|
1016
1059
|
debug,
|
|
1017
1060
|
tools,
|
|
1018
1061
|
toolTargets: this.runtimeToolTargets(tools),
|
|
1062
|
+
getSerializers: this.runtimeGetSerializers(tools),
|
|
1019
1063
|
customActions: await this.runtimeCustomActions(tools),
|
|
1020
1064
|
taskActions: await this.runtimeTaskActions(tools),
|
|
1021
1065
|
tenantScopedObjects,
|
|
@@ -1261,7 +1305,7 @@ ${indent} if (!item) {
|
|
|
1261
1305
|
${indent} throw new Error('Object not found');
|
|
1262
1306
|
${indent} }
|
|
1263
1307
|
|
|
1264
|
-
${indent} return successResult(
|
|
1308
|
+
${indent} return successResult(await serializeGetResult(${JSON.stringify(tool.name)}, item));
|
|
1265
1309
|
${indent}}`;
|
|
1266
1310
|
case "create": return `${indent}case '${tool.name}': {
|
|
1267
1311
|
${indent} const { collection, objectName: targetObjectName } = await resolveCreateTarget(${JSON.stringify(objectName)}, ${JSON.stringify(lookup)}, args, aiConfig);
|
|
@@ -1374,6 +1418,7 @@ ${indent}}`;
|
|
|
1374
1418
|
const switchCases = await this.generateToolSwitchCases(" ", tools);
|
|
1375
1419
|
const stiTargets = this.runtimeStiTargets(tools);
|
|
1376
1420
|
const toolTargets = this.runtimeToolTargets(tools);
|
|
1421
|
+
const getSerializers = this.runtimeGetSerializers(tools);
|
|
1377
1422
|
const tenantScopedSet = Array.from(new Set(tenantScopedObjects.map((n) => n.toLowerCase())));
|
|
1378
1423
|
const hasTenantScoped = tenantScopedSet.length > 0;
|
|
1379
1424
|
return `/**
|
|
@@ -1408,8 +1453,22 @@ const PUBLIC_JSON_OPTIONS = {
|
|
|
1408
1453
|
.map((permission) => permission.trim())
|
|
1409
1454
|
.filter(Boolean),
|
|
1410
1455
|
};
|
|
1456
|
+
const GET_SERIALIZERS: Record<string, { importPath: string; exportName: string }> = ${JSON.stringify(getSerializers)};
|
|
1411
1457
|
const STI_TARGETS: Record<string, Record<string, string>> = ${JSON.stringify(stiTargets)};
|
|
1412
1458
|
|
|
1459
|
+
async function serializeGetResult(toolName: string, item: any): Promise<any> {
|
|
1460
|
+
const reference = GET_SERIALIZERS[toolName];
|
|
1461
|
+
if (!reference) return item.toPublicJSON(PUBLIC_JSON_OPTIONS);
|
|
1462
|
+
const serializerModule = await import(reference.importPath);
|
|
1463
|
+
const serializer = serializerModule[reference.exportName];
|
|
1464
|
+
if (typeof serializer !== 'function') {
|
|
1465
|
+
throw new Error(
|
|
1466
|
+
\`MCP get serializer '\${reference.exportName}' was not exported by '\${reference.importPath}'\`,
|
|
1467
|
+
);
|
|
1468
|
+
}
|
|
1469
|
+
return toPublicResult(await serializer(item, PUBLIC_JSON_OPTIONS));
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1413
1472
|
/**
|
|
1414
1473
|
* Mass-assignment guard (#1540): strip framework/server-managed and
|
|
1415
1474
|
* \`@field({ readonly: true })\` fields from create/update bodies, intersecting
|
|
@@ -1500,6 +1559,17 @@ function errorResult(structuredContent: any, text: string, _meta?: Record<string
|
|
|
1500
1559
|
};
|
|
1501
1560
|
}
|
|
1502
1561
|
|
|
1562
|
+
function normalizePublicToolError(error: any): { code: string; message: string } | undefined {
|
|
1563
|
+
if (!error || typeof error !== 'object') return undefined;
|
|
1564
|
+
if (
|
|
1565
|
+
typeof error.code !== 'string' ||
|
|
1566
|
+
!/^[A-Za-z][A-Za-z0-9_.:-]{0,127}$/.test(error.code) ||
|
|
1567
|
+
typeof error.publicMessage !== 'string' ||
|
|
1568
|
+
error.publicMessage.length === 0
|
|
1569
|
+
) return undefined;
|
|
1570
|
+
return { code: error.code, message: error.publicMessage };
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1503
1573
|
/**
|
|
1504
1574
|
* Handle tool call request
|
|
1505
1575
|
*/
|
|
@@ -1533,10 +1603,11 @@ ${hasTenantScoped ? `
|
|
|
1533
1603
|
|
|
1534
1604
|
return result;
|
|
1535
1605
|
} catch (error) {
|
|
1536
|
-
const
|
|
1606
|
+
const publicError = normalizePublicToolError(error);
|
|
1607
|
+
const errorMessage = publicError?.message ?? (error instanceof Error ? error.message : 'Unknown error');
|
|
1537
1608
|
|
|
1538
1609
|
return errorResult(
|
|
1539
|
-
{ error: { message: errorMessage } },
|
|
1610
|
+
{ error: publicError ?? { message: errorMessage } },
|
|
1540
1611
|
\`Error executing tool \${name}: \${errorMessage}\`,
|
|
1541
1612
|
);
|
|
1542
1613
|
}
|
|
@@ -1666,6 +1737,6 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
|
|
|
1666
1737
|
}
|
|
1667
1738
|
};
|
|
1668
1739
|
//#endregion
|
|
1669
|
-
export { MCPGenerator, MCP_STABLE_CATALOG_TTL_MS, assertMcpJsonSchemaSafety, mcpToolAnnotations, mcpToolAnnotationsFor, resolveMCPToolListCacheHint, sortMCPTools };
|
|
1740
|
+
export { MCPGenerator, MCP_STABLE_CATALOG_TTL_MS, assertMcpJsonSchemaSafety, mcpToolAnnotations, mcpToolAnnotationsFor, resolveMCPToolListCacheHint, resolveMcpGetSerializer, sortMCPTools };
|
|
1670
1741
|
|
|
1671
1742
|
//# sourceMappingURL=mcp.js.map
|