@happyvertical/smrt-dev-mcp 0.61.3 → 0.61.5
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 +2 -0
- package/README.md +18 -0
- package/dist/dev-plane.js +2 -2
- package/dist/{http-BqKiyqgN.js → http-Brjn_G5R.js} +2 -2
- package/dist/{http-BqKiyqgN.js.map → http-Brjn_G5R.js.map} +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +148 -6
- package/dist/index.js.map +1 -1
- package/dist/{knowledge-CCBDF01R.js → knowledge-tD6NTmy1.js} +2 -2
- package/dist/{knowledge-CCBDF01R.js.map → knowledge-tD6NTmy1.js.map} +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/smrt-knowledge.okf.md +2 -2
- package/dist/{tool-catalog-BhnSCF8g.js → tool-catalog-CEB611ri.js} +65 -1
- package/dist/tool-catalog-CEB611ri.js.map +1 -0
- package/dist/tool-catalog.d.ts.map +1 -1
- package/dist/tools/harden-smrt-class.d.ts +43 -0
- package/dist/tools/harden-smrt-class.d.ts.map +1 -0
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.d.ts.map +1 -1
- package/package.json +6 -6
- package/dist/tool-catalog-BhnSCF8g.js.map +0 -1
package/AGENTS.md
CHANGED
|
@@ -8,6 +8,7 @@ deterministic SMRT ecosystem knowledge, and portable agent workflows.
|
|
|
8
8
|
| Tool | Purpose |
|
|
9
9
|
|------|---------|
|
|
10
10
|
| `generate-smrt-class` | Generates `@smrt()` class with fields, decorator config, imports |
|
|
11
|
+
| `harden-smrt-class` | Suggests (and, with `write: true`, writes into app code) a same-named subclass overriding fields; never touches a database (#4936) |
|
|
11
12
|
| `introspect-project` | Scans project directory for SMRT objects; compact summary by default, `detail: 'full'` for field/schema/method detail |
|
|
12
13
|
| `review-smrt-project` | Advisory downstream ecosystem alignment review for dependencies, storage, app shell, auth/tenancy, manifest generation, and intent-driven hand-rolled-equivalent detection (#4690) |
|
|
13
14
|
| `reflect-knowledge` | Reports deterministic SMRT + HappyVertical SDK knowledge coverage and freshness |
|
|
@@ -203,6 +204,7 @@ when `dist` is missing or older, so rebuild `dist` after server edits. Guarded b
|
|
|
203
204
|
- `skills/smrt-contribute/SKILL.md` — contributor skill (copy at repo-root `.agents/skills/smrt-contribute/`)
|
|
204
205
|
- `skills/smrt-catalog/SKILL.md` — catalog router skill; `skills/smrt-catalog/evals.json` — its trigger eval set
|
|
205
206
|
- `src/tools/generate-smrt-class.ts` — class generation logic and package-ready templates
|
|
207
|
+
- `src/tools/harden-smrt-class.ts` — hardening suggestion; file write only, no database or SQL (#4936)
|
|
206
208
|
- `src/tools/introspect-project.ts` — manifest-first project scanning, falling back to `@happyvertical/smrt-scanner`
|
|
207
209
|
- `src/dev-plane.ts` — in-app runtime dev-plane (#2782): `createDevPlane({ token, projectRoot, db })` serves JSON + MCP on one mount with loopback/bearer guards and a positive catalog (`registry-live` + the nine runtime tools); mounted by the generated `_dev/[...tool]` SvelteKit route
|
|
208
210
|
- `src/runtime.ts` — `RUNTIME_TOOLS` map for in-process callers (`smrt dev:runtime` fallback)
|
package/README.md
CHANGED
|
@@ -310,6 +310,24 @@ Generate a complete s-m-r-t class with `@smrt()` decorator, fields, and imports.
|
|
|
310
310
|
|
|
311
311
|
Supported property types: `text`, `integer`, `decimal`, `boolean`, `datetime`, `json`.
|
|
312
312
|
|
|
313
|
+
### `harden-smrt-class`
|
|
314
|
+
|
|
315
|
+
Suggest a hardening for a s-m-r-t class the app uses, as a same-named subclass
|
|
316
|
+
that overrides fields. It returns the source. It writes the file only when you
|
|
317
|
+
pass `write: true`, and never overwrites one. It never touches a database: the
|
|
318
|
+
build and `smrt db:migrate` turn the override into a constraint, and migrate
|
|
319
|
+
stops with a report if existing rows break it. It refuses a loosening that smrt
|
|
320
|
+
needs for its own correctness (a required field with a stated reason).
|
|
321
|
+
|
|
322
|
+
| Parameter | Type | Required | Description |
|
|
323
|
+
|-----------|------|----------|-------------|
|
|
324
|
+
| `className` | `string` | Yes | The s-m-r-t class the app uses (PascalCase) |
|
|
325
|
+
| `importFrom` | `string` | Yes | Package that exports the class |
|
|
326
|
+
| `overrides` | `object[]` | Yes | Fields to override (`name`, `type?`, `required?`, `maxLength?`, `description?`); `required` defaults to `true` |
|
|
327
|
+
| `directory` | `string` | No | Project directory (default: cwd) |
|
|
328
|
+
| `outputPath` | `string` | No | File to write, relative to `directory` (default `src/models/<ClassName>.ts`) |
|
|
329
|
+
| `write` | `boolean` | No | Write the file (default `false`: suggestion only) |
|
|
330
|
+
|
|
313
331
|
### `introspect-project`
|
|
314
332
|
|
|
315
333
|
Scan a project directory for s-m-r-t objects and return a manifest-equivalent
|
package/dist/dev-plane.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as runtimeMigrationStatus, c as runtimeScheduleHealth, g as loadProjectCore, i as runtimeJobHealth, m as ProjectRuntimeResolutionError, o as runtimeRecentChanges, p as safeErrorMessage, r as runtimeDispatchHealth, s as runtimeRegistryDrift, t as RUNTIME_PROVENANCE } from "./tools-B0uaPTz0.js";
|
|
2
|
-
import { i as SERVER_VERSION, r as SERVER_NAME, t as bearerMatches } from "./http-
|
|
3
|
-
import { n as TOOLS } from "./tool-catalog-
|
|
2
|
+
import { i as SERVER_VERSION, r as SERVER_NAME, t as bearerMatches } from "./http-Brjn_G5R.js";
|
|
3
|
+
import { n as TOOLS } from "./tool-catalog-CEB611ri.js";
|
|
4
4
|
import { i as runtimeSchemaDiff, n as runtimeObject, r as runtimeRegistry } from "./observation-DbB4z-9t.js";
|
|
5
5
|
import { Server, createMcpHandler } from "@modelcontextprotocol/server";
|
|
6
6
|
//#region src/dev-plane.ts
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as runtimeMigrationStatus, c as runtimeScheduleHealth, i as runtimeJobHealth, o as runtimeRecentChanges, r as runtimeDispatchHealth, s as runtimeRegistryDrift } from "./tools-B0uaPTz0.js";
|
|
2
|
-
import { n as TOOLS } from "./tool-catalog-
|
|
2
|
+
import { n as TOOLS } from "./tool-catalog-CEB611ri.js";
|
|
3
3
|
import { a as bootRuntime, i as runtimeSchemaDiff, n as runtimeObject, r as runtimeRegistry } from "./observation-DbB4z-9t.js";
|
|
4
4
|
import { readFileSync } from "node:fs";
|
|
5
5
|
import { dirname, join } from "node:path";
|
|
@@ -166,4 +166,4 @@ async function startRuntimeHttpHost(options = {}) {
|
|
|
166
166
|
//#endregion
|
|
167
167
|
export { SERVER_VERSION as i, startRuntimeHttpHost as n, SERVER_NAME as r, bearerMatches as t };
|
|
168
168
|
|
|
169
|
-
//# sourceMappingURL=http-
|
|
169
|
+
//# sourceMappingURL=http-Brjn_G5R.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http-BqKiyqgN.js","names":[],"sources":["../src/server-info.ts","../src/http.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport const SERVER_NAME = 'smrt-dev-mcp';\n\nfunction readPackageVersion(): string {\n try {\n const packageRoot = dirname(fileURLToPath(import.meta.url));\n const packageJsonPath = join(packageRoot, '..', 'package.json');\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as {\n version?: unknown;\n };\n return typeof packageJson.version === 'string'\n ? packageJson.version\n : '0.0.0';\n } catch {\n return '0.0.0';\n }\n}\n\nexport const SERVER_VERSION = readPackageVersion();\n","/**\n * Standalone Level 2 runtime dev-plane host (#1831).\n *\n * Serves a *positive* read-only tool catalog over the stateless 2026-07-28\n * Streamable HTTP transport (#2147): `createMcpHandler` with `legacy: 'reject'`\n * and `maxSubscriptions: 0`, adapted to Node with `toNodeHandler`. No SSE,\n * no session header, no sticky routing.\n *\n * Security boundary (development only):\n * - binds loopback only; SDK localhost Host/Origin validation runs first;\n * - every request needs `Authorization: Bearer <token>` (constant-time\n * compare) — from `SMRT_DEV_MCP_TOKEN` or minted per process;\n * - no authenticated principal exists here, so scope stays fail-closed\n * global-only exactly as in Level 1;\n * - the catalog never includes generated CRUD, custom actions, `do()`, or\n * tool-backed `is()`.\n */\n\nimport { randomBytes, timingSafeEqual } from 'node:crypto';\nimport {\n createServer as createHttpServer,\n type Server as HttpServer,\n type IncomingMessage,\n type ServerResponse,\n} from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport {\n localhostHostValidation,\n localhostOriginValidation,\n toNodeHandler,\n} from '@modelcontextprotocol/node';\nimport type { CallToolResult } from '@modelcontextprotocol/server';\nimport { createMcpHandler, Server } from '@modelcontextprotocol/server';\nimport { SERVER_NAME, SERVER_VERSION } from './server-info.js';\nimport { TOOLS } from './tool-catalog.js';\nimport { bootRuntime, type RuntimeBoot } from './tools/runtime/boot.js';\nimport {\n runtimeObject,\n runtimeRegistry,\n runtimeSchemaDiff,\n} from './tools/runtime/observation.js';\nimport {\n runtimeDispatchHealth,\n runtimeJobHealth,\n runtimeMigrationStatus,\n runtimeRecentChanges,\n runtimeRegistryDrift,\n runtimeScheduleHealth,\n} from './tools/runtime/tools.js';\n\n/**\n * The complete Level 2 catalog. A tool is exposed over HTTP only if it is\n * named here; the static stdio catalog is deliberately not mounted.\n */\nexport const RUNTIME_HTTP_TOOL_NAMES = [\n 'runtime-registry',\n 'runtime-object',\n 'runtime-schema-diff',\n 'migration-status',\n 'job-health',\n 'schedule-health',\n 'dispatch-health',\n 'recent-changes',\n 'registry-drift',\n] as const;\n\nexport type RuntimeHttpToolName = (typeof RUNTIME_HTTP_TOOL_NAMES)[number];\n\nconst RUNTIME_HTTP_HANDLERS: Record<\n RuntimeHttpToolName,\n (args: Record<string, unknown>) => Promise<unknown>\n> = {\n 'runtime-registry': (args) => runtimeRegistry(args as never),\n 'runtime-object': (args) => runtimeObject(args as never),\n 'runtime-schema-diff': (args) => runtimeSchemaDiff(args as never),\n 'migration-status': (args) => runtimeMigrationStatus(args as never),\n 'job-health': (args) => runtimeJobHealth(args as never),\n 'schedule-health': (args) => runtimeScheduleHealth(args as never),\n 'dispatch-health': (args) => runtimeDispatchHealth(args as never),\n 'recent-changes': (args) => runtimeRecentChanges(args as never),\n 'registry-drift': (args) => runtimeRegistryDrift(args as never),\n};\n\n/** Catalog definitions for the HTTP plane, in catalog order. */\nexport function runtimeHttpTools() {\n const names = new Set<string>(RUNTIME_HTTP_TOOL_NAMES);\n return TOOLS.filter((tool) => names.has(tool.name));\n}\n\n/**\n * Build a fresh protocol server per request (stateless transport contract).\n * `projectRoot` is fixed at host start; per-request `projectPath` arguments\n * are ignored so a client cannot re-point the booted process.\n */\nexport function createRuntimeProtocolServer(projectRoot: string): Server {\n const server = new Server(\n { name: `${SERVER_NAME}-runtime`, version: SERVER_VERSION },\n { capabilities: { tools: {} } },\n );\n server.setRequestHandler('tools/list', async () => ({\n tools: runtimeHttpTools(),\n }));\n server.setRequestHandler('tools/call', async (request) => {\n const name = request.params.name as string;\n const handler = (RUNTIME_HTTP_HANDLERS as Record<string, unknown>)[name];\n if (typeof handler !== 'function') {\n throw new Error(`Unknown runtime tool: ${name}`);\n }\n const { projectPath: _ignored, ...args } = (request.params.arguments ??\n {}) as Record<string, unknown>;\n const result = await (\n handler as (a: Record<string, unknown>) => Promise<unknown>\n )({ ...args, projectPath: projectRoot });\n const text = JSON.stringify(result, null, 2);\n return {\n content: [{ type: 'text', text }],\n structuredContent: result as Record<string, unknown>,\n } satisfies CallToolResult;\n });\n return server;\n}\n\nexport interface RuntimeHttpHostOptions {\n projectRoot?: string;\n /** Loopback interface only; anything else is refused at startup. */\n host?: '127.0.0.1' | 'localhost' | '::1';\n /** `0` (default) picks a free port. */\n port?: number;\n /** Bearer token; defaults to `SMRT_DEV_MCP_TOKEN` or a per-process random token. */\n token?: string;\n /** Path the MCP endpoint is mounted on (default `/mcp`). */\n path?: string;\n}\n\nexport interface RuntimeHttpHost {\n url: string;\n token: string;\n boot: RuntimeBoot;\n close(): Promise<void>;\n}\n\nconst LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1']);\n\nexport function bearerMatches(\n header: string | undefined,\n token: string,\n): boolean {\n if (!header?.startsWith('Bearer ')) return false;\n const presented = Buffer.from(header.slice('Bearer '.length));\n const expected = Buffer.from(token);\n return (\n presented.length === expected.length && timingSafeEqual(presented, expected)\n );\n}\n\nfunction deny(res: ServerResponse, status: number, message: string): void {\n res.statusCode = status;\n res.setHeader('content-type', 'application/json');\n if (status === 401) {\n res.setHeader('www-authenticate', 'Bearer realm=\"smrt-dev-mcp runtime\"');\n }\n res.end(JSON.stringify({ error: message }));\n}\n\n/** Start the Level 2 host. Boots the confined runtime before listening. */\nexport async function startRuntimeHttpHost(\n options: RuntimeHttpHostOptions = {},\n): Promise<RuntimeHttpHost> {\n const host = options.host ?? '127.0.0.1';\n if (!LOOPBACK_HOSTS.has(host)) {\n throw new Error(\n 'The runtime dev-plane binds loopback only (127.0.0.1, localhost, ::1).',\n );\n }\n const path = options.path ?? '/mcp';\n const token =\n options.token ??\n process.env.SMRT_DEV_MCP_TOKEN?.trim() ??\n randomBytes(24).toString('base64url');\n if (!token) {\n throw new Error('SMRT_DEV_MCP_TOKEN must not be empty.');\n }\n const projectRoot = options.projectRoot ?? process.cwd();\n const boot = await bootRuntime({ projectRoot });\n\n const mcp = toNodeHandler(\n createMcpHandler(() => createRuntimeProtocolServer(projectRoot), {\n legacy: 'reject',\n maxSubscriptions: 0,\n }),\n );\n const hostGuard = localhostHostValidation();\n const originGuard = localhostOriginValidation();\n\n const httpServer: HttpServer = createHttpServer(\n (req: IncomingMessage, res: ServerResponse) => {\n // Guards answer and end the response themselves when they return false.\n if (!hostGuard(req, res)) return;\n if (!originGuard(req, res)) return;\n const url = new URL(req.url ?? '/', 'http://localhost');\n if (url.pathname !== path) {\n deny(res, 404, 'not found');\n return;\n }\n if (!bearerMatches(req.headers.authorization, token)) {\n deny(res, 401, 'missing or invalid bearer token');\n return;\n }\n void mcp(req, res);\n },\n );\n\n await new Promise<void>((resolve, reject) => {\n httpServer.once('error', reject);\n httpServer.listen(options.port ?? 0, host, () => {\n httpServer.off('error', reject);\n resolve();\n });\n });\n const address = httpServer.address() as AddressInfo;\n const urlHost =\n address.family === 'IPv6' ? `[${address.address}]` : address.address;\n return {\n url: `http://${urlHost}:${address.port}${path}`,\n token,\n boot,\n close: () =>\n new Promise<void>((resolve, reject) => {\n httpServer.closeAllConnections?.();\n httpServer.close((error) => (error ? reject(error) : resolve()));\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;AAIA,IAAa,cAAc;AAE3B,SAAS,qBAA6B;CACpC,IAAI;EAEF,MAAM,kBAAkB,KADJ,QAAQ,cAAc,OAAO,KAAK,GAAG,CAC5B,GAAa,MAAM,cAAc;EAC9D,MAAM,cAAc,KAAK,MAAM,aAAa,iBAAiB,OAAO,CAAC;EAGrE,OAAO,OAAO,YAAY,YAAY,WAClC,YAAY,UACZ;CACN,QAAQ;EACN,OAAO;CACT;AACF;AAEA,IAAa,iBAAiB,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;ACiCjD,IAAa,0BAA0B;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAIA,IAAM,wBAGF;CACF,qBAAqB,SAAS,gBAAgB,IAAa;CAC3D,mBAAmB,SAAS,cAAc,IAAa;CACvD,wBAAwB,SAAS,kBAAkB,IAAa;CAChE,qBAAqB,SAAS,uBAAuB,IAAa;CAClE,eAAe,SAAS,iBAAiB,IAAa;CACtD,oBAAoB,SAAS,sBAAsB,IAAa;CAChE,oBAAoB,SAAS,sBAAsB,IAAa;CAChE,mBAAmB,SAAS,qBAAqB,IAAa;CAC9D,mBAAmB,SAAS,qBAAqB,IAAa;AAChE;;AAGA,SAAgB,mBAAmB;CACjC,MAAM,QAAQ,IAAI,IAAY,uBAAuB;CACrD,OAAO,MAAM,QAAQ,SAAS,MAAM,IAAI,KAAK,IAAI,CAAC;AACpD;;;;;;AAOA,SAAgB,4BAA4B,aAA6B;CACvE,MAAM,SAAS,IAAI,OACjB;E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AQ,OAAO,KAAK,IAAI,QAAQ,CAAE;EACjE,CAAC;CACL;AACF"}
|
|
1
|
+
{"version":3,"file":"http-Brjn_G5R.js","names":[],"sources":["../src/server-info.ts","../src/http.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport const SERVER_NAME = 'smrt-dev-mcp';\n\nfunction readPackageVersion(): string {\n try {\n const packageRoot = dirname(fileURLToPath(import.meta.url));\n const packageJsonPath = join(packageRoot, '..', 'package.json');\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as {\n version?: unknown;\n };\n return typeof packageJson.version === 'string'\n ? packageJson.version\n : '0.0.0';\n } catch {\n return '0.0.0';\n }\n}\n\nexport const SERVER_VERSION = readPackageVersion();\n","/**\n * Standalone Level 2 runtime dev-plane host (#1831).\n *\n * Serves a *positive* read-only tool catalog over the stateless 2026-07-28\n * Streamable HTTP transport (#2147): `createMcpHandler` with `legacy: 'reject'`\n * and `maxSubscriptions: 0`, adapted to Node with `toNodeHandler`. No SSE,\n * no session header, no sticky routing.\n *\n * Security boundary (development only):\n * - binds loopback only; SDK localhost Host/Origin validation runs first;\n * - every request needs `Authorization: Bearer <token>` (constant-time\n * compare) — from `SMRT_DEV_MCP_TOKEN` or minted per process;\n * - no authenticated principal exists here, so scope stays fail-closed\n * global-only exactly as in Level 1;\n * - the catalog never includes generated CRUD, custom actions, `do()`, or\n * tool-backed `is()`.\n */\n\nimport { randomBytes, timingSafeEqual } from 'node:crypto';\nimport {\n createServer as createHttpServer,\n type Server as HttpServer,\n type IncomingMessage,\n type ServerResponse,\n} from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport {\n localhostHostValidation,\n localhostOriginValidation,\n toNodeHandler,\n} from '@modelcontextprotocol/node';\nimport type { CallToolResult } from '@modelcontextprotocol/server';\nimport { createMcpHandler, Server } from '@modelcontextprotocol/server';\nimport { SERVER_NAME, SERVER_VERSION } from './server-info.js';\nimport { TOOLS } from './tool-catalog.js';\nimport { bootRuntime, type RuntimeBoot } from './tools/runtime/boot.js';\nimport {\n runtimeObject,\n runtimeRegistry,\n runtimeSchemaDiff,\n} from './tools/runtime/observation.js';\nimport {\n runtimeDispatchHealth,\n runtimeJobHealth,\n runtimeMigrationStatus,\n runtimeRecentChanges,\n runtimeRegistryDrift,\n runtimeScheduleHealth,\n} from './tools/runtime/tools.js';\n\n/**\n * The complete Level 2 catalog. A tool is exposed over HTTP only if it is\n * named here; the static stdio catalog is deliberately not mounted.\n */\nexport const RUNTIME_HTTP_TOOL_NAMES = [\n 'runtime-registry',\n 'runtime-object',\n 'runtime-schema-diff',\n 'migration-status',\n 'job-health',\n 'schedule-health',\n 'dispatch-health',\n 'recent-changes',\n 'registry-drift',\n] as const;\n\nexport type RuntimeHttpToolName = (typeof RUNTIME_HTTP_TOOL_NAMES)[number];\n\nconst RUNTIME_HTTP_HANDLERS: Record<\n RuntimeHttpToolName,\n (args: Record<string, unknown>) => Promise<unknown>\n> = {\n 'runtime-registry': (args) => runtimeRegistry(args as never),\n 'runtime-object': (args) => runtimeObject(args as never),\n 'runtime-schema-diff': (args) => runtimeSchemaDiff(args as never),\n 'migration-status': (args) => runtimeMigrationStatus(args as never),\n 'job-health': (args) => runtimeJobHealth(args as never),\n 'schedule-health': (args) => runtimeScheduleHealth(args as never),\n 'dispatch-health': (args) => runtimeDispatchHealth(args as never),\n 'recent-changes': (args) => runtimeRecentChanges(args as never),\n 'registry-drift': (args) => runtimeRegistryDrift(args as never),\n};\n\n/** Catalog definitions for the HTTP plane, in catalog order. */\nexport function runtimeHttpTools() {\n const names = new Set<string>(RUNTIME_HTTP_TOOL_NAMES);\n return TOOLS.filter((tool) => names.has(tool.name));\n}\n\n/**\n * Build a fresh protocol server per request (stateless transport contract).\n * `projectRoot` is fixed at host start; per-request `projectPath` arguments\n * are ignored so a client cannot re-point the booted process.\n */\nexport function createRuntimeProtocolServer(projectRoot: string): Server {\n const server = new Server(\n { name: `${SERVER_NAME}-runtime`, version: SERVER_VERSION },\n { capabilities: { tools: {} } },\n );\n server.setRequestHandler('tools/list', async () => ({\n tools: runtimeHttpTools(),\n }));\n server.setRequestHandler('tools/call', async (request) => {\n const name = request.params.name as string;\n const handler = (RUNTIME_HTTP_HANDLERS as Record<string, unknown>)[name];\n if (typeof handler !== 'function') {\n throw new Error(`Unknown runtime tool: ${name}`);\n }\n const { projectPath: _ignored, ...args } = (request.params.arguments ??\n {}) as Record<string, unknown>;\n const result = await (\n handler as (a: Record<string, unknown>) => Promise<unknown>\n )({ ...args, projectPath: projectRoot });\n const text = JSON.stringify(result, null, 2);\n return {\n content: [{ type: 'text', text }],\n structuredContent: result as Record<string, unknown>,\n } satisfies CallToolResult;\n });\n return server;\n}\n\nexport interface RuntimeHttpHostOptions {\n projectRoot?: string;\n /** Loopback interface only; anything else is refused at startup. */\n host?: '127.0.0.1' | 'localhost' | '::1';\n /** `0` (default) picks a free port. */\n port?: number;\n /** Bearer token; defaults to `SMRT_DEV_MCP_TOKEN` or a per-process random token. */\n token?: string;\n /** Path the MCP endpoint is mounted on (default `/mcp`). */\n path?: string;\n}\n\nexport interface RuntimeHttpHost {\n url: string;\n token: string;\n boot: RuntimeBoot;\n close(): Promise<void>;\n}\n\nconst LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1']);\n\nexport function bearerMatches(\n header: string | undefined,\n token: string,\n): boolean {\n if (!header?.startsWith('Bearer ')) return false;\n const presented = Buffer.from(header.slice('Bearer '.length));\n const expected = Buffer.from(token);\n return (\n presented.length === expected.length && timingSafeEqual(presented, expected)\n );\n}\n\nfunction deny(res: ServerResponse, status: number, message: string): void {\n res.statusCode = status;\n res.setHeader('content-type', 'application/json');\n if (status === 401) {\n res.setHeader('www-authenticate', 'Bearer realm=\"smrt-dev-mcp runtime\"');\n }\n res.end(JSON.stringify({ error: message }));\n}\n\n/** Start the Level 2 host. Boots the confined runtime before listening. */\nexport async function startRuntimeHttpHost(\n options: RuntimeHttpHostOptions = {},\n): Promise<RuntimeHttpHost> {\n const host = options.host ?? '127.0.0.1';\n if (!LOOPBACK_HOSTS.has(host)) {\n throw new Error(\n 'The runtime dev-plane binds loopback only (127.0.0.1, localhost, ::1).',\n );\n }\n const path = options.path ?? '/mcp';\n const token =\n options.token ??\n process.env.SMRT_DEV_MCP_TOKEN?.trim() ??\n randomBytes(24).toString('base64url');\n if (!token) {\n throw new Error('SMRT_DEV_MCP_TOKEN must not be empty.');\n }\n const projectRoot = options.projectRoot ?? process.cwd();\n const boot = await bootRuntime({ projectRoot });\n\n const mcp = toNodeHandler(\n createMcpHandler(() => createRuntimeProtocolServer(projectRoot), {\n legacy: 'reject',\n maxSubscriptions: 0,\n }),\n );\n const hostGuard = localhostHostValidation();\n const originGuard = localhostOriginValidation();\n\n const httpServer: HttpServer = createHttpServer(\n (req: IncomingMessage, res: ServerResponse) => {\n // Guards answer and end the response themselves when they return false.\n if (!hostGuard(req, res)) return;\n if (!originGuard(req, res)) return;\n const url = new URL(req.url ?? '/', 'http://localhost');\n if (url.pathname !== path) {\n deny(res, 404, 'not found');\n return;\n }\n if (!bearerMatches(req.headers.authorization, token)) {\n deny(res, 401, 'missing or invalid bearer token');\n return;\n }\n void mcp(req, res);\n },\n );\n\n await new Promise<void>((resolve, reject) => {\n httpServer.once('error', reject);\n httpServer.listen(options.port ?? 0, host, () => {\n httpServer.off('error', reject);\n resolve();\n });\n });\n const address = httpServer.address() as AddressInfo;\n const urlHost =\n address.family === 'IPv6' ? `[${address.address}]` : address.address;\n return {\n url: `http://${urlHost}:${address.port}${path}`,\n token,\n boot,\n close: () =>\n new Promise<void>((resolve, reject) => {\n httpServer.closeAllConnections?.();\n httpServer.close((error) => (error ? reject(error) : resolve()));\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;AAIA,IAAa,cAAc;AAE3B,SAAS,qBAA6B;CACpC,IAAI;EAEF,MAAM,kBAAkB,KADJ,QAAQ,cAAc,OAAO,KAAK,GAAG,CAC5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AAwB;CAC1C,MAAM,cAAc,0BAA0B;CAE9C,MAAM,aAAyB,cAC5B,KAAsB,QAAwB;EAE7C,IAAI,CAAC,UAAU,KAAK,GAAG,GAAG;EAC1B,IAAI,CAAC,YAAY,KAAK,GAAG,GAAG;EAE5B,IAAI,IADY,IAAI,IAAI,OAAO,KAAK,kBAChC,CAAA,CAAI,aAAa,MAAM;GACzB,KAAK,KAAK,KAAK,WAAW;GAC1B;EACF;EACA,IAAI,CAAC,cAAc,IAAI,QAAQ,eAAe,KAAK,GAAG;GACpD,KAAK,KAAK,KAAK,iCAAiC;GAChD;EACF;EACA,IAAS,KAAK,GAAG;CACnB,CACF;CAEA,MAAM,IAAI,SAAe,SAAS,WAAW;EAC3C,WAAW,KAAK,SAAS,MAAM;EAC/B,WAAW,OAAO,QAAQ,QAAQ,GAAG,YAAY;GAC/C,WAAW,IAAI,SAAS,MAAM;GAC9B,QAAQ;EACV,CAAC;CACH,CAAC;CACD,MAAM,UAAU,WAAW,QAAQ;CAGnC,OAAO;EACL,KAAK,UAFL,QAAQ,WAAW,SAAS,IAAI,QAAQ,QAAQ,KAAK,QAAQ,QAEtC,GAAG,QAAQ,OAAO;EACzC;EACA;EACA,aACE,IAAI,SAAe,SAAS,WAAW;GACrC,WAAW,sBAAsB;GACjC,WAAW,OAAO,UAAW,QAAQ,OAAO,KAAK,IAAI,QAAQ,CAAE;EACjE,CAAC;CACL;AACF"}
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAUA,OAAO,EAGL,MAAM,EACP,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAUA,OAAO,EAGL,MAAM,EACP,MAAM,8BAA8B,CAAC;AAqBtC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AA8B1C,wBAAgB,YAAY,IAAI,MAAM,CAgoBrC;AAyND;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG;IACzD,IAAI,EAAE,OAAO,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAsBA"}
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { f as redactConnectionString, m as ProjectRuntimeResolutionError } from "./tools-B0uaPTz0.js";
|
|
3
3
|
import { getAgentSkill, listAgentSkills } from "./agent-skills.js";
|
|
4
|
-
import { i as SERVER_VERSION, n as startRuntimeHttpHost, r as SERVER_NAME } from "./http-
|
|
5
|
-
import { n as TOOLS, t as REVIEW_SKILL_NAME } from "./tool-catalog-
|
|
6
|
-
import { a as buildReviewContext, c as compactContextResult, i as buildPackageSpecialistContext, n as buildContext, o as checkKnowledgeFreshness, r as buildKnowledgeIndex, s as checkKnowledgeFreshnessFromIndex, t as buildArchitectureContext } from "./knowledge-
|
|
4
|
+
import { i as SERVER_VERSION, n as startRuntimeHttpHost, r as SERVER_NAME } from "./http-Brjn_G5R.js";
|
|
5
|
+
import { n as TOOLS, t as REVIEW_SKILL_NAME } from "./tool-catalog-CEB611ri.js";
|
|
6
|
+
import { a as buildReviewContext, c as compactContextResult, i as buildPackageSpecialistContext, n as buildContext, o as checkKnowledgeFreshness, r as buildKnowledgeIndex, s as checkKnowledgeFreshnessFromIndex, t as buildArchitectureContext } from "./knowledge-tD6NTmy1.js";
|
|
7
7
|
import { t as reviewSmrtProject } from "./review-smrt-project-ByEwPcor.js";
|
|
8
|
-
import { realpathSync } from "node:fs";
|
|
8
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
9
10
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
10
11
|
import { ProtocolError, ProtocolErrorCode, Server } from "@modelcontextprotocol/server";
|
|
11
12
|
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
12
13
|
//#region src/tools/generate-smrt-class.ts
|
|
13
|
-
var TYPE_MAPPING = {
|
|
14
|
+
var TYPE_MAPPING$1 = {
|
|
14
15
|
text: {
|
|
15
16
|
tsType: "string",
|
|
16
17
|
defaultValue: "''"
|
|
@@ -146,7 +147,7 @@ function renderTenantIdField(tenantScoped) {
|
|
|
146
147
|
return nullable ? ` @tenantId({ nullable: true })\n ${field}: string | null = null;` : ` @tenantId()\n ${field}: string = '';`;
|
|
147
148
|
}
|
|
148
149
|
function renderProperty(prop) {
|
|
149
|
-
const mapping = TYPE_MAPPING[prop.type];
|
|
150
|
+
const mapping = TYPE_MAPPING$1[prop.type];
|
|
150
151
|
const nullable = prop.nullable === true;
|
|
151
152
|
const tsType = nullable ? `${mapping.tsType} | null` : mapping.tsType;
|
|
152
153
|
const defaultValue = prop.defaultValue !== void 0 ? renderLiteral(prop.defaultValue) : nullable ? "null" : mapping.defaultValue;
|
|
@@ -197,6 +198,144 @@ function compactObject(value) {
|
|
|
197
198
|
return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0));
|
|
198
199
|
}
|
|
199
200
|
//#endregion
|
|
201
|
+
//#region src/tools/harden-smrt-class.ts
|
|
202
|
+
/**
|
|
203
|
+
* Harden SMRT Class Tool (#4936, rule 3 of #4920)
|
|
204
|
+
*
|
|
205
|
+
* Suggests a hardening for a smrt class an app uses and, only when asked,
|
|
206
|
+
* writes it into the app's code as a same-named subclass that overrides the
|
|
207
|
+
* fields. The app owns its data shape: the override is code, and the build and
|
|
208
|
+
* `smrt db:migrate` turn it into constraints.
|
|
209
|
+
*
|
|
210
|
+
* This tool never touches a database. It reads one installed package manifest
|
|
211
|
+
* (JSON, to check the class and field names) and writes one source file under
|
|
212
|
+
* the project directory. It imports no database client and has no function
|
|
213
|
+
* that builds SQL; `harden-smrt-class.test.ts` pins that.
|
|
214
|
+
*/
|
|
215
|
+
var TYPE_MAPPING = {
|
|
216
|
+
text: {
|
|
217
|
+
tsType: "string",
|
|
218
|
+
initializer: "''"
|
|
219
|
+
},
|
|
220
|
+
integer: {
|
|
221
|
+
tsType: "number",
|
|
222
|
+
initializer: "0"
|
|
223
|
+
},
|
|
224
|
+
decimal: {
|
|
225
|
+
tsType: "number",
|
|
226
|
+
initializer: "0.0"
|
|
227
|
+
},
|
|
228
|
+
boolean: {
|
|
229
|
+
tsType: "boolean",
|
|
230
|
+
initializer: "false"
|
|
231
|
+
},
|
|
232
|
+
datetime: {
|
|
233
|
+
tsType: "Date",
|
|
234
|
+
initializer: "new Date()"
|
|
235
|
+
},
|
|
236
|
+
json: {
|
|
237
|
+
tsType: "any",
|
|
238
|
+
initializer: "{}"
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
var MANIFEST_TYPE_TO_PROPERTY = {
|
|
242
|
+
text: "text",
|
|
243
|
+
integer: "integer",
|
|
244
|
+
decimal: "decimal",
|
|
245
|
+
boolean: "boolean",
|
|
246
|
+
datetime: "datetime",
|
|
247
|
+
json: "json"
|
|
248
|
+
};
|
|
249
|
+
var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
250
|
+
var PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
|
|
251
|
+
/** The installed package's manifest, when it can be read. */
|
|
252
|
+
function readParentFields(directory, importFrom, className) {
|
|
253
|
+
const path = join(directory, "node_modules", importFrom, "dist/manifest.json");
|
|
254
|
+
if (!existsSync(path)) return null;
|
|
255
|
+
let manifest;
|
|
256
|
+
try {
|
|
257
|
+
manifest = JSON.parse(readFileSync(path, "utf-8"));
|
|
258
|
+
} catch {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
return Object.values(manifest.objects ?? {}).find((candidate) => candidate.className === className)?.fields ?? null;
|
|
262
|
+
}
|
|
263
|
+
function fieldSource(override, type, required) {
|
|
264
|
+
const options = [];
|
|
265
|
+
options.push(`required: ${required}`);
|
|
266
|
+
if (override.maxLength !== void 0) options.push(`maxLength: ${override.maxLength}`);
|
|
267
|
+
if (override.description) options.push(`description: ${JSON.stringify(override.description)}`);
|
|
268
|
+
const { tsType, initializer } = TYPE_MAPPING[type];
|
|
269
|
+
return ` @field({ ${options.join(", ")} })\n override ${override.name}: ${tsType} = ${initializer};`;
|
|
270
|
+
}
|
|
271
|
+
/** Build the suggestion, and write it when `write` is true. */
|
|
272
|
+
async function hardenSmrtClass(args) {
|
|
273
|
+
const result = harden(args);
|
|
274
|
+
return JSON.stringify(result, null, 2);
|
|
275
|
+
}
|
|
276
|
+
function harden(args) {
|
|
277
|
+
const { className, importFrom, overrides } = args;
|
|
278
|
+
if (!IDENTIFIER.test(className)) throw new Error(`className must be a class name, got "${className}".`);
|
|
279
|
+
if (!PACKAGE_NAME.test(importFrom)) throw new Error(`importFrom must be a package name, got "${importFrom}".`);
|
|
280
|
+
if (!Array.isArray(overrides) || overrides.length === 0) throw new Error("overrides needs at least one field.");
|
|
281
|
+
const directory = resolve(args.directory ?? process.cwd());
|
|
282
|
+
const parentFields = readParentFields(directory, importFrom, className);
|
|
283
|
+
const notes = [];
|
|
284
|
+
if (!parentFields) notes.push(`Could not read ${importFrom}/dist/manifest.json, so field names, types and reasons were not checked. The build still checks them.`);
|
|
285
|
+
const seen = /* @__PURE__ */ new Set();
|
|
286
|
+
const lines = [];
|
|
287
|
+
for (const override of overrides) {
|
|
288
|
+
if (!IDENTIFIER.test(override.name)) throw new Error(`Field name "${override.name}" is not a valid name.`);
|
|
289
|
+
if (seen.has(override.name)) throw new Error(`Field "${override.name}" is listed twice.`);
|
|
290
|
+
seen.add(override.name);
|
|
291
|
+
if (override.maxLength !== void 0 && !(Number.isInteger(override.maxLength) && override.maxLength > 0)) throw new Error(`${override.name}: maxLength must be a positive whole number.`);
|
|
292
|
+
const parent = parentFields?.[override.name];
|
|
293
|
+
if (parentFields && !parent) throw new Error(`${className} has no field "${override.name}" in ${importFrom}. Add a new field with generate-smrt-class in a differently named subclass, or check the name.`);
|
|
294
|
+
const required = override.required ?? true;
|
|
295
|
+
if (parent?.required === true && required === false && typeof parent._meta?.requiredFor === "string") throw new Error(`${className}.${override.name} cannot be made optional. smrt needs it (${parent._meta.requiredFor}).`);
|
|
296
|
+
const type = override.type ?? (parent?.type ? MANIFEST_TYPE_TO_PROPERTY[parent.type] : void 0);
|
|
297
|
+
if (!type) throw new Error(`${override.name}: give a type (text, integer, decimal, boolean, datetime or json); it could not be read from ${importFrom}.`);
|
|
298
|
+
lines.push(fieldSource(override, type, required));
|
|
299
|
+
}
|
|
300
|
+
const alias = `Smrt${className}`;
|
|
301
|
+
const source = [
|
|
302
|
+
`import { field, smrt } from '@happyvertical/smrt-core';`,
|
|
303
|
+
`import { ${className} as ${alias} } from '${importFrom}';`,
|
|
304
|
+
"",
|
|
305
|
+
"/**",
|
|
306
|
+
` * The app's ${className}. Same name as the smrt class, so it replaces it`,
|
|
307
|
+
" * everywhere. Only the fields below change; everything else is inherited.",
|
|
308
|
+
" */",
|
|
309
|
+
"@smrt()",
|
|
310
|
+
`export class ${className} extends ${alias} {`,
|
|
311
|
+
lines.join("\n\n"),
|
|
312
|
+
"}",
|
|
313
|
+
""
|
|
314
|
+
].join("\n");
|
|
315
|
+
const path = args.outputPath ?? join("src", "models", `${className}.ts`);
|
|
316
|
+
const target = resolve(directory, path);
|
|
317
|
+
const inside = relative(directory, target);
|
|
318
|
+
if (isAbsolute(path) || inside.startsWith("..") || inside.split(sep)[0] === "..") throw new Error("outputPath must stay inside the project directory.");
|
|
319
|
+
let written = false;
|
|
320
|
+
if (args.write === true) {
|
|
321
|
+
if (existsSync(target)) throw new Error(`${inside} already exists. Not overwriting it; edit the class by hand or choose another outputPath.`);
|
|
322
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
323
|
+
writeFileSync(target, source, { flag: "wx" });
|
|
324
|
+
written = true;
|
|
325
|
+
}
|
|
326
|
+
return {
|
|
327
|
+
source,
|
|
328
|
+
path: inside,
|
|
329
|
+
written,
|
|
330
|
+
next: [
|
|
331
|
+
written ? `Check ${inside}, and export the class where the app registers its models.` : `Review the source. Run again with write: true to create ${inside}.`,
|
|
332
|
+
"Run the build. It refuses a change smrt cannot allow, and names the class and field.",
|
|
333
|
+
"Run `smrt db:migrate`. It applies the constraint. It stops, with a report, if existing rows break the rule."
|
|
334
|
+
],
|
|
335
|
+
notes
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
//#endregion
|
|
200
339
|
//#region src/index.ts
|
|
201
340
|
/**
|
|
202
341
|
* SMRT Development MCP Server
|
|
@@ -480,6 +619,9 @@ function createServer() {
|
|
|
480
619
|
case "generate-smrt-class":
|
|
481
620
|
result = await generateSmrtClass(args);
|
|
482
621
|
break;
|
|
622
|
+
case "harden-smrt-class":
|
|
623
|
+
result = await hardenSmrtClass(args);
|
|
624
|
+
break;
|
|
483
625
|
case "introspect-project":
|
|
484
626
|
result = await (await import("./introspect-project-QUHJk-gJ.js")).introspectProject(args);
|
|
485
627
|
break;
|